forge
Explore
Log in

Don't you dare go Hollow

A QuickTime .mov keeps its AAC — read v1/v2 sound descriptions

Browse files at this commit

7fbbd0f26ebffb0409226ae9ee5773b10771568aAhmet Kaan GümüşParent: dee569d
  • fix
    • a QuickTime .mov keeps its AAC — read v1/v2 sound descriptions
Show full message
🐛 fix(engine): a QuickTime .mov keeps its AAC — read v1/v2 sound descriptions

A Resolve export (qt brand) opened with no sound: mp4 0.14
reads the mp4a sample entry as ISO only, skipping the 8 bytes QuickTime
uses for version/revision/vendor, so a version-1 SoundDescription's
16-byte tail was taken for the first child box and the wave-wrapped esds
behind it never seen -- "trak[2].stbl.esds not found", and with it every
Resolve / Final Cut / `ffmpeg -f mov` file. Vendored mp4 0.14 under
vendor/mp4 (patch table entry, workspace exclude): Mp4aBox::read_box now
reads the version, skips the v1 tail or takes rate/channels from the v2
block, and finds the esds directly or inside `wave`; the crate's ten
lint warnings cleaned with it. New fixture assets/test_qt.mov (ffmpeg -f
mov, same 440/880 tone) and a test in audio_decode that fails on stock
0.14 and passes here.

Verified in the harness on a Resolve export: opens with picture and waveform,
plays (sink RMS -26.9 dBFS), seeks to 00:10 and plays the right audio
(captured peak -11.109 dBFS = source's own). Workspace suite 981/987;
the six failures are five load flakes that pass serially and one
pre-existing failure on clean main (audio_multi layout refusal), logged.
Cargo.lockmodified+0 -2
@@ -3504,8 +3504,6 @@ dependencies = [
3504 [[package]]3504 [[package]]
3505 name = "mp4"3505 name = "mp4"
3506 version = "0.14.0"3506 version = "0.14.0"
3507-source = "registry+https://github.com/rust-lang/crates.io-index"
3508-checksum = "c9ef834d5ed55e494a2ae350220314dc4aacd1c43a9498b00e320e0ea352a5c3"
3509 dependencies = [3507 dependencies = [
3510 "byteorder",3508 "byteorder",
3511 "bytes",3509 "bytes",
Cargo.tomlmodified+15 -1
@@ -8,6 +8,7 @@ exclude = [
8 "vendor/rusty_aac",8 "vendor/rusty_aac",
9 "vendor/oxideav-h265",9 "vendor/oxideav-h265",
10 "vendor/rusty_h264-common",10 "vendor/rusty_h264-common",
11+ "vendor/mp4",
11 ]12 ]
12 13
13 [workspace.package]14 [workspace.package]
@@ -76,7 +77,15 @@ edition = "2024"
76 # default and the six-line declaration in `src/lib.rs`; every77 # default and the six-line declaration in `src/lib.rs`; every
77 # line of codec code is byte-identical to 0.9.1, so decode stays78 # line of codec code is byte-identical to 0.9.1, so decode stays
78 # bit-exact and the process gets glibc's malloc back.79 # bit-exact and the process gets glibc's malloc back.
79-# Drop `vendor/` entirely once released versions handle all five.80+# mp4 - reads the `mp4a` sample entry as ISO only: the 8 bytes
81+# QuickTime uses for version/revision/vendor are skipped as
82+# reserved, so a version-1 SoundDescription's 16-byte tail
83+# (version 2's 36-byte one) is taken for the first child box
84+# and the `wave`-wrapped `esds` behind it is never seen -- an
85+# AAC track "with no esds", every Resolve / Final Cut / `ffmpeg
86+# -f mov` file silent. The patch is `Mp4aBox::read_box` and a
87+# `WaveBox` fourcc; writing is untouched.
88+# Drop `vendor/` entirely once released versions handle all six.
80 [patch.crates-io]89 [patch.crates-io]
81 cros-libva = { path = "vendor/cros-libva" }90 cros-libva = { path = "vendor/cros-libva" }
82 cros-codecs = { path = "vendor/cros-codecs" }91 cros-codecs = { path = "vendor/cros-codecs" }
@@ -85,3 +94,8 @@ rusty_h264-common = { path = "vendor/rusty_h264-common" }
85 # Drops the `pub use proc_macro;` re-export (E0365 future-incompat, rustc94 # Drops the `pub use proc_macro;` re-export (E0365 future-incompat, rustc
86 # warns on every workspace build); nothing in the crate or its users names it.95 # warns on every workspace build); nothing in the crate or its users names it.
87 proc-macro-error2 = { path = "vendor/proc-macro-error2" }96 proc-macro-error2 = { path = "vendor/proc-macro-error2" }
97+# Reads QuickTime version-1/2 sound sample descriptions (Resolve, Final Cut,
98+# `ffmpeg -f mov`): the 16/36-byte block after samplerate and the `esds`
99+# inside the `wave` wrapper. Stock 0.14 walks past both and calls the AAC
100+# track esds-less, so a `.mov` opens without sound.
101+mp4 = { path = "vendor/mp4" }
crates/engine/tests/audio_decode.rsmodified+38 -0
@@ -103,6 +103,44 @@ fn decodes_av_mp4_audio() {
103 );103 );
104 }104 }
105 105
106+/// A QuickTime-brand `.mov` -- Resolve's, Final Cut's, `ffmpeg -f mov`'s --
107+/// keeps its AAC `esds` behind a version-1 SoundDescription and inside a
108+/// `wave` wrapper. Stock mp4 0.14 read neither and refused the track as
109+/// "esds not found", so a `.mov` opened as a silent film (a Resolve export,
110+/// 2026-09-06); the vendored crate reads both. The tone is the fixture's
111+/// 440 Hz left / 880 Hz right, so this also proves the config it found is the
112+/// right one and not a guess: a wrong rate or layout moves the crossings.
113+#[test]
114+fn a_quicktime_mov_keeps_its_aac_behind_a_wave_wrapper() {
115+ let (meta, rx) = AudioSession::open(asset("test_qt.mov"))
116+ .expect("open")
117+ .expect("test_qt.mov has an audio track");
118+ assert_eq!((meta.sample_rate, meta.channels), (RATE, 2));
119+
120+ let mut left = Vec::new();
121+ let mut right = Vec::new();
122+ for chunk in rx {
123+ left.extend(chunk.samples.iter().step_by(2));
124+ right.extend(chunk.samples[1..].iter().step_by(2));
125+ }
126+ let frames = left.len();
127+ let want = (RATE * 2) as i64;
128+ let slack = frames as i64 - want;
129+ assert!(
130+ (0..=FRAME).contains(&slack),
131+ "{frames} frames per channel, want {want} (+0..={FRAME})"
132+ );
133+ let secs = frames as f64 / RATE as f64;
134+ for (name, samples, hz) in [("left", &left, 440.0), ("right", &right, 880.0)] {
135+ let want = 2.0 * hz * secs;
136+ let got = zero_crossings(samples) as f64;
137+ assert!(
138+ (got - want).abs() <= 0.05 * want,
139+ "{name}: {got} zero crossings, want {want} +/-5%"
140+ );
141+ }
142+}
143+
106 #[test]144 #[test]
107 fn video_only_file_has_no_audio() {145 fn video_only_file_has_no_audio() {
108 assert!(146 assert!(
scripts/gen_fixtures.shmodified+14 -0
@@ -539,4 +539,18 @@ ffmpeg -y -f lavfi -i "testsrc2=size=320x240:rate=30:duration=2" \
539 ffmpeg -y -f lavfi -i "sine=frequency=440:duration=3" \539 ffmpeg -y -f lavfi -i "sine=frequency=440:duration=3" \
540 -c:a aac -b:a 128k assets/test_audio_only.mp4540 -c:a aac -b:a 128k assets/test_audio_only.mp4
541 541
542+# A QuickTime-brand `.mov` (what Resolve, Final Cut and `ffmpeg -f mov` write):
543+# its AAC sample entry is a version-1 SoundDescription -- 16 bytes of
544+# compression fields after the sample rate, then the `esds` inside a `wave`
545+# wrapper -- rather than the bare ISO `mp4a`+`esds` an `.mp4` carries. Stock
546+# mp4 0.14 walked past both and called the track esds-less, so a `.mov` opened
547+# with no sound at all (`tests/audio_decode.rs`). 440 Hz left / 880 Hz right
548+# at 44.1k, 2 s, so the same channel-identity check applies.
549+ffmpeg -y -f lavfi -i testsrc2=size=320x240:rate=24:duration=2 \
550+ -f lavfi -i "sine=frequency=440:duration=2" \
551+ -f lavfi -i "sine=frequency=880:duration=2" \
552+ -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo[a]" \
553+ -map 0:v -map "[a]" -c:v libx264 -profile:v baseline -pix_fmt yuv420p \
554+ -c:a aac -b:a 96k -f mov assets/test_qt.mov
555+
542 echo "fixtures written to assets/"556 echo "fixtures written to assets/"
vendor/mp4/.cargo-okadded+1 -0
@@ -0,0 +1 @@
1+{"v":1}
\ No newline at end of file\ No newline at end of file
vendor/mp4/Cargo.tomladded+63 -0
@@ -0,0 +1,63 @@
1+# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
2+#
3+# When uploading crates to the registry Cargo will automatically
4+# "normalize" Cargo.toml files for maximal compatibility
5+# with all versions of Cargo and also rewrite `path` dependencies
6+# to registry (e.g., crates.io) dependencies.
7+#
8+# If you are reading this file be aware that the original Cargo.toml
9+# will likely look very different (and much more reasonable).
10+# See Cargo.toml.orig for the original contents.
11+
12+[package]
13+edition = "2018"
14+name = "mp4"
15+version = "0.14.0"
16+authors = ["Alf <alf.g.jr@gmail.com>"]
17+include = [
18+ "src",
19+ "benches",
20+ "Cargo.toml",
21+ "README",
22+ "LICENSE",
23+]
24+description = "MP4 reader and writer library in Rust."
25+homepage = "https://github.com/alfg/mp4-rust"
26+documentation = "https://docs.rs/mp4"
27+readme = "README.md"
28+keywords = [
29+ "mp4",
30+ "iso-mp4",
31+ "isobmff",
32+ "video",
33+ "multimedia",
34+]
35+license = "MIT"
36+repository = "https://github.com/alfg/mp4-rust"
37+
38+[[bench]]
39+name = "bench_main"
40+harness = false
41+
42+[dependencies.byteorder]
43+version = "1"
44+
45+[dependencies.bytes]
46+version = "1.1.0"
47+
48+[dependencies.num-rational]
49+version = "0.4.0"
50+features = ["serde"]
51+
52+[dependencies.serde]
53+version = "1.0"
54+features = ["derive"]
55+
56+[dependencies.serde_json]
57+version = "1.0"
58+
59+[dependencies.thiserror]
60+version = "^1.0"
61+
62+[dev-dependencies.criterion]
63+version = "0.3"
vendor/mp4/Cargo.toml.origadded+28 -0
@@ -0,0 +1,28 @@
1+[package]
2+name = "mp4"
3+version = "0.14.0"
4+authors = ["Alf <alf.g.jr@gmail.com>"]
5+edition = "2018"
6+description = "MP4 reader and writer library in Rust."
7+documentation = "https://docs.rs/mp4"
8+readme = "README.md"
9+homepage = "https://github.com/alfg/mp4-rust"
10+repository = "https://github.com/alfg/mp4-rust"
11+keywords = ["mp4", "iso-mp4", "isobmff", "video", "multimedia"]
12+license = "MIT"
13+include = ["src", "benches", "Cargo.toml", "README", "LICENSE"]
14+
15+[dependencies]
16+thiserror = "^1.0"
17+byteorder = "1"
18+bytes = "1.1.0"
19+num-rational = { version = "0.4.0", features = ["serde"] }
20+serde = { version = "1.0", features = ["derive"] }
21+serde_json = "1.0"
22+
23+[dev-dependencies]
24+criterion = "0.3"
25+
26+[[bench]]
27+name = "bench_main"
28+harness = false
vendor/mp4/LICENSEadded+21 -0
@@ -0,0 +1,21 @@
1+MIT License
2+
3+Copyright (c) 2020 Alfred Gutierrez
4+
5+Permission is hereby granted, free of charge, to any person obtaining a copy
6+of this software and associated documentation files (the "Software"), to deal
7+in the Software without restriction, including without limitation the rights
8+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+copies of the Software, and to permit persons to whom the Software is
10+furnished to do so, subject to the following conditions:
11+
12+The above copyright notice and this permission notice shall be included in all
13+copies or substantial portions of the Software.
14+
15+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+SOFTWARE.
\ No newline at end of file\ No newline at end of file
vendor/mp4/README.mdadded+151 -0
@@ -0,0 +1,151 @@
1+# mp4
2+> MP4 Reader and Writer in Rust 🦀
3+
4+`mp4` is a Rust library to read and write ISO-MP4 files. This package contains MPEG-4 specifications defined in parts:
5+* [ISO/IEC 14496-12](https://en.wikipedia.org/wiki/ISO/IEC_base_media_file_format) - ISO Base Media File Format (QuickTime, MPEG-4, etc)
6+* [ISO/IEC 14496-14](https://en.wikipedia.org/wiki/MPEG-4_Part_14) - MP4 file format
7+* ISO/IEC 14496-17 - Streaming text format
8+
9+https://crates.io/crates/mp4
10+
11+[![Crates.io](https://img.shields.io/crates/v/mp4)](https://crates.io/crates/mp4)
12+[![Crates.io](https://img.shields.io/crates/d/mp4)](https://crates.io/crates/mp4)
13+[![Docs](https://img.shields.io/badge/docs-online-5023dd.svg?style=flat-square)](https://docs.rs/mp4)
14+[![Rust](https://github.com/alfg/mp4-rust/workflows/Rust/badge.svg)](https://github.com/alfg/mp4-rust/actions)
15+
16+#### Example
17+```rust
18+use std::fs::File;
19+use std::io::{BufReader};
20+use mp4::{Result};
21+
22+fn main() -> Result<()> {
23+ let f = File::open("tests/samples/minimal.mp4").unwrap();
24+ let size = f.metadata()?.len();
25+ let reader = BufReader::new(f);
26+
27+ let mp4 = mp4::Mp4Reader::read_header(reader, size)?;
28+
29+ // Print boxes.
30+ println!("major brand: {}", mp4.ftyp.major_brand);
31+ println!("timescale: {}", mp4.moov.mvhd.timescale);
32+
33+ // Use available methods.
34+ println!("size: {}", mp4.size());
35+
36+ let mut compatible_brands = String::new();
37+ for brand in mp4.compatible_brands().iter() {
38+ compatible_brands.push_str(&brand.to_string());
39+ compatible_brands.push_str(",");
40+ }
41+ println!("compatible brands: {}", compatible_brands);
42+ println!("duration: {:?}", mp4.duration());
43+
44+ // Track info.
45+ for track in mp4.tracks().values() {
46+ println!(
47+ "track: #{}({}) {} : {}",
48+ track.track_id(),
49+ track.language(),
50+ track.track_type()?,
51+ track.box_type()?,
52+ );
53+ }
54+ Ok(())
55+}
56+```
57+
58+See [examples/](examples/) for more examples.
59+
60+#### Install
61+```
62+cargo add mp4
63+```
64+or add to your `Cargo.toml`:
65+```toml
66+mp4 = "0.14.0"
67+```
68+
69+#### Documentation
70+* https://docs.rs/mp4/
71+
72+## Development
73+
74+#### Requirements
75+* [Rust](https://www.rust-lang.org/)
76+
77+#### Build
78+```
79+cargo build
80+```
81+
82+#### Lint and Format
83+```
84+cargo clippy --fix
85+cargo fmt --all
86+```
87+
88+#### Run Examples
89+* `mp4info`
90+```
91+cargo run --example mp4info <movie.mp4>
92+```
93+
94+* `mp4dump`
95+```
96+cargo run --example mp4dump <movie.mp4>
97+```
98+
99+#### Run Tests
100+```
101+cargo test
102+```
103+
104+With print statement output.
105+```
106+cargo test -- --nocapture
107+```
108+
109+#### Run Cargo fmt
110+Run fmt to catch formatting errors.
111+
112+```
113+rustup component add rustfmt
114+cargo fmt --all -- --check
115+```
116+
117+#### Run Clippy
118+Run Clippy tests to catch common lints and mistakes.
119+
120+```
121+rustup component add clippy
122+cargo clippy --no-deps -- -D warnings
123+```
124+
125+#### Run Benchmark Tests
126+```
127+cargo bench
128+```
129+
130+View HTML report at `target/criterion/report/index.html`
131+
132+#### Generate Docs
133+```
134+cargo docs
135+```
136+
137+View at `target/doc/mp4/index.html`
138+
139+## Web Assembly
140+See the [mp4-inspector](https://github.com/alfg/mp4-inspector) project as a reference for using this library in Javascript via Web Assembly.
141+
142+## Related Projects
143+* https://github.com/mozilla/mp4parse-rust
144+* https://github.com/pcwalton/rust-media
145+* https://github.com/alfg/mp4
146+
147+## License
148+MIT
149+
150+[docs]: https://docs.rs/mp4
151+[docs-badge]: https://img.shields.io/badge/docs-online-5023dd.svg?style=flat-square
vendor/mp4/benches/bench_main.rsadded+26 -0
@@ -0,0 +1,26 @@
1+use criterion::BenchmarkId;
2+use criterion::{criterion_group, criterion_main, Criterion};
3+
4+use std::fs::File;
5+
6+fn read_mp4(filename: &str) -> u64 {
7+ let f = File::open(filename).unwrap();
8+ let m = mp4::read_mp4(f).unwrap();
9+
10+ m.size()
11+}
12+
13+fn criterion_benchmark(c: &mut Criterion) {
14+ let filename = "tests/samples/minimal.mp4";
15+
16+ c.bench_with_input(
17+ BenchmarkId::new("input_example", filename),
18+ &filename,
19+ |b, &s| {
20+ b.iter(|| read_mp4(s));
21+ },
22+ );
23+}
24+
25+criterion_group!(benches, criterion_benchmark);
26+criterion_main!(benches);
vendor/mp4/src/error.rsadded+29 -0
@@ -0,0 +1,29 @@
1+use thiserror::Error;
2+
3+use crate::mp4box::BoxType;
4+
5+#[derive(Error, Debug)]
6+pub enum Error {
7+ #[error("{0}")]
8+ IoError(#[from] std::io::Error),
9+ #[error("{0}")]
10+ InvalidData(&'static str),
11+ #[error("{0} not found")]
12+ BoxNotFound(BoxType),
13+ #[error("{0} and {1} not found")]
14+ Box2NotFound(BoxType, BoxType),
15+ #[error("trak[{0}] not found")]
16+ TrakNotFound(u32),
17+ #[error("trak[{0}].{1} not found")]
18+ BoxInTrakNotFound(u32, BoxType),
19+ #[error("traf[{0}].{1} not found")]
20+ BoxInTrafNotFound(u32, BoxType),
21+ #[error("trak[{0}].stbl.{1} not found")]
22+ BoxInStblNotFound(u32, BoxType),
23+ #[error("trak[{0}].stbl.{1}.entry[{2}] not found")]
24+ EntryInStblNotFound(u32, BoxType, u32),
25+ #[error("traf[{0}].trun.{1}.entry[{2}] not found")]
26+ EntryInTrunNotFound(u32, BoxType, u32),
27+ #[error("{0} version {1} is not supported")]
28+ UnsupportedBoxVersion(BoxType, u8),
29+}
vendor/mp4/src/lib.rsadded+96 -0
@@ -0,0 +1,96 @@
1+//! `mp4` is a Rust library to read and write ISO-MP4 files.
2+//!
3+//! This package contains MPEG-4 specifications defined in parts:
4+//! * ISO/IEC 14496-12 - ISO Base Media File Format (QuickTime, MPEG-4, etc)
5+//! * ISO/IEC 14496-14 - MP4 file format
6+//! * ISO/IEC 14496-17 - Streaming text format
7+//!
8+//! See: [mp4box] for supported MP4 atoms.
9+//!
10+//! ### Example
11+//!
12+//! ```
13+//! use std::fs::File;
14+//! use std::io::{BufReader};
15+//! use mp4::{Result};
16+//!
17+//! fn main() -> Result<()> {
18+//! let f = File::open("tests/samples/minimal.mp4").unwrap();
19+//! let size = f.metadata()?.len();
20+//! let reader = BufReader::new(f);
21+//!
22+//! let mp4 = mp4::Mp4Reader::read_header(reader, size)?;
23+//!
24+//! // Print boxes.
25+//! println!("major brand: {}", mp4.ftyp.major_brand);
26+//! println!("timescale: {}", mp4.moov.mvhd.timescale);
27+//!
28+//! // Use available methods.
29+//! println!("size: {}", mp4.size());
30+//!
31+//! let mut compatible_brands = String::new();
32+//! for brand in mp4.compatible_brands().iter() {
33+//! compatible_brands.push_str(&brand.to_string());
34+//! compatible_brands.push_str(",");
35+//! }
36+//! println!("compatible brands: {}", compatible_brands);
37+//! println!("duration: {:?}", mp4.duration());
38+//!
39+//! // Track info.
40+//! for track in mp4.tracks().values() {
41+//! println!(
42+//! "track: #{}({}) {} : {}",
43+//! track.track_id(),
44+//! track.language(),
45+//! track.track_type()?,
46+//! track.box_type()?,
47+//! );
48+//! }
49+//! Ok(())
50+//! }
51+//! ```
52+//!
53+//! See [examples] for more examples.
54+//!
55+//! # Installation
56+//!
57+//! Add the following to your `Cargo.toml` file:
58+//!
59+//! ```toml
60+//! [dependencies]
61+//! mp4 = "0.7.0"
62+//! ```
63+//!
64+//! [mp4box]: https://github.com/alfg/mp4-rust/blob/master/src/mp4box/mod.rs
65+//! [examples]: https://github.com/alfg/mp4-rust/tree/master/examples
66+#![doc(html_root_url = "https://docs.rs/mp4/*")]
67+
68+use std::fs::File;
69+use std::io::BufReader;
70+
71+mod error;
72+pub use error::Error;
73+
74+pub type Result<T> = std::result::Result<T, Error>;
75+
76+mod types;
77+pub use types::*;
78+
79+mod mp4box;
80+pub use mp4box::*;
81+
82+mod track;
83+pub use track::{Mp4Track, TrackConfig};
84+
85+mod reader;
86+pub use reader::Mp4Reader;
87+
88+mod writer;
89+pub use writer::{Mp4Config, Mp4Writer};
90+
91+pub fn read_mp4(f: File) -> Result<Mp4Reader<BufReader<File>>> {
92+ let size = f.metadata()?.len();
93+ let reader = BufReader::new(f);
94+ let mp4 = reader::Mp4Reader::read_header(reader, size)?;
95+ Ok(mp4)
96+}
vendor/mp4/src/mp4box/avc1.rsadded+347 -0
@@ -0,0 +1,347 @@
1+use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
2+use serde::Serialize;
3+use std::io::{Read, Seek, Write};
4+
5+use crate::mp4box::*;
6+
7+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
8+pub struct Avc1Box {
9+ pub data_reference_index: u16,
10+ pub width: u16,
11+ pub height: u16,
12+
13+ #[serde(with = "value_u32")]
14+ pub horizresolution: FixedPointU16,
15+
16+ #[serde(with = "value_u32")]
17+ pub vertresolution: FixedPointU16,
18+ pub frame_count: u16,
19+ pub depth: u16,
20+ pub avcc: AvcCBox,
21+}
22+
23+impl Default for Avc1Box {
24+ fn default() -> Self {
25+ Avc1Box {
26+ data_reference_index: 0,
27+ width: 0,
28+ height: 0,
29+ horizresolution: FixedPointU16::new(0x48),
30+ vertresolution: FixedPointU16::new(0x48),
31+ frame_count: 1,
32+ depth: 0x0018,
33+ avcc: AvcCBox::default(),
34+ }
35+ }
36+}
37+
38+impl Avc1Box {
39+ pub fn new(config: &AvcConfig) -> Self {
40+ Avc1Box {
41+ data_reference_index: 1,
42+ width: config.width,
43+ height: config.height,
44+ horizresolution: FixedPointU16::new(0x48),
45+ vertresolution: FixedPointU16::new(0x48),
46+ frame_count: 1,
47+ depth: 0x0018,
48+ avcc: AvcCBox::new(&config.seq_param_set, &config.pic_param_set),
49+ }
50+ }
51+
52+ pub fn get_type(&self) -> BoxType {
53+ BoxType::Avc1Box
54+ }
55+
56+ pub fn get_size(&self) -> u64 {
57+ HEADER_SIZE + 8 + 70 + self.avcc.box_size()
58+ }
59+}
60+
61+impl Mp4Box for Avc1Box {
62+ fn box_type(&self) -> BoxType {
63+ self.get_type()
64+ }
65+
66+ fn box_size(&self) -> u64 {
67+ self.get_size()
68+ }
69+
70+ fn to_json(&self) -> Result<String> {
71+ Ok(serde_json::to_string(&self).unwrap())
72+ }
73+
74+ fn summary(&self) -> Result<String> {
75+ let s = format!(
76+ "data_reference_index={} width={} height={} frame_count={}",
77+ self.data_reference_index, self.width, self.height, self.frame_count
78+ );
79+ Ok(s)
80+ }
81+}
82+
83+impl<R: Read + Seek> ReadBox<&mut R> for Avc1Box {
84+ fn read_box(reader: &mut R, size: u64) -> Result<Self> {
85+ let start = box_start(reader)?;
86+
87+ reader.read_u32::<BigEndian>()?; // reserved
88+ reader.read_u16::<BigEndian>()?; // reserved
89+ let data_reference_index = reader.read_u16::<BigEndian>()?;
90+
91+ reader.read_u32::<BigEndian>()?; // pre-defined, reserved
92+ reader.read_u64::<BigEndian>()?; // pre-defined
93+ reader.read_u32::<BigEndian>()?; // pre-defined
94+ let width = reader.read_u16::<BigEndian>()?;
95+ let height = reader.read_u16::<BigEndian>()?;
96+ let horizresolution = FixedPointU16::new_raw(reader.read_u32::<BigEndian>()?);
97+ let vertresolution = FixedPointU16::new_raw(reader.read_u32::<BigEndian>()?);
98+ reader.read_u32::<BigEndian>()?; // reserved
99+ let frame_count = reader.read_u16::<BigEndian>()?;
100+ skip_bytes(reader, 32)?; // compressorname
101+ let depth = reader.read_u16::<BigEndian>()?;
102+ reader.read_i16::<BigEndian>()?; // pre-defined
103+
104+ let header = BoxHeader::read(reader)?;
105+ let BoxHeader { name, size: s } = header;
106+ if s > size {
107+ return Err(Error::InvalidData(
108+ "avc1 box contains a box with a larger size than it",
109+ ));
110+ }
111+ if name == BoxType::AvcCBox {
112+ let avcc = AvcCBox::read_box(reader, s)?;
113+
114+ skip_bytes_to(reader, start + size)?;
115+
116+ Ok(Avc1Box {
117+ data_reference_index,
118+ width,
119+ height,
120+ horizresolution,
121+ vertresolution,
122+ frame_count,
123+ depth,
124+ avcc,
125+ })
126+ } else {
127+ Err(Error::InvalidData("avcc not found"))
128+ }
129+ }
130+}
131+
132+impl<W: Write> WriteBox<&mut W> for Avc1Box {
133+ fn write_box(&self, writer: &mut W) -> Result<u64> {
134+ let size = self.box_size();
135+ BoxHeader::new(self.box_type(), size).write(writer)?;
136+
137+ writer.write_u32::<BigEndian>(0)?; // reserved
138+ writer.write_u16::<BigEndian>(0)?; // reserved
139+ writer.write_u16::<BigEndian>(self.data_reference_index)?;
140+
141+ writer.write_u32::<BigEndian>(0)?; // pre-defined, reserved
142+ writer.write_u64::<BigEndian>(0)?; // pre-defined
143+ writer.write_u32::<BigEndian>(0)?; // pre-defined
144+ writer.write_u16::<BigEndian>(self.width)?;
145+ writer.write_u16::<BigEndian>(self.height)?;
146+ writer.write_u32::<BigEndian>(self.horizresolution.raw_value())?;
147+ writer.write_u32::<BigEndian>(self.vertresolution.raw_value())?;
148+ writer.write_u32::<BigEndian>(0)?; // reserved
149+ writer.write_u16::<BigEndian>(self.frame_count)?;
150+ // skip compressorname
151+ write_zeros(writer, 32)?;
152+ writer.write_u16::<BigEndian>(self.depth)?;
153+ writer.write_i16::<BigEndian>(-1)?; // pre-defined
154+
155+ self.avcc.write_box(writer)?;
156+
157+ Ok(size)
158+ }
159+}
160+
161+#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize)]
162+pub struct AvcCBox {
163+ pub configuration_version: u8,
164+ pub avc_profile_indication: u8,
165+ pub profile_compatibility: u8,
166+ pub avc_level_indication: u8,
167+ pub length_size_minus_one: u8,
168+ pub sequence_parameter_sets: Vec<NalUnit>,
169+ pub picture_parameter_sets: Vec<NalUnit>,
170+}
171+
172+impl AvcCBox {
173+ pub fn new(sps: &[u8], pps: &[u8]) -> Self {
174+ Self {
175+ configuration_version: 1,
176+ avc_profile_indication: sps[1],
177+ profile_compatibility: sps[2],
178+ avc_level_indication: sps[3],
179+ length_size_minus_one: 0xff, // length_size = 4
180+ sequence_parameter_sets: vec![NalUnit::from(sps)],
181+ picture_parameter_sets: vec![NalUnit::from(pps)],
182+ }
183+ }
184+}
185+
186+impl Mp4Box for AvcCBox {
187+ fn box_type(&self) -> BoxType {
188+ BoxType::AvcCBox
189+ }
190+
191+ fn box_size(&self) -> u64 {
192+ let mut size = HEADER_SIZE + 7;
193+ for sps in self.sequence_parameter_sets.iter() {
194+ size += sps.size() as u64;
195+ }
196+ for pps in self.picture_parameter_sets.iter() {
197+ size += pps.size() as u64;
198+ }
199+ size
200+ }
201+
202+ fn to_json(&self) -> Result<String> {
203+ Ok(serde_json::to_string(&self).unwrap())
204+ }
205+
206+ fn summary(&self) -> Result<String> {
207+ let s = format!("avc_profile_indication={}", self.avc_profile_indication);
208+ Ok(s)
209+ }
210+}
211+
212+impl<R: Read + Seek> ReadBox<&mut R> for AvcCBox {
213+ fn read_box(reader: &mut R, size: u64) -> Result<Self> {
214+ let start = box_start(reader)?;
215+
216+ let configuration_version = reader.read_u8()?;
217+ let avc_profile_indication = reader.read_u8()?;
218+ let profile_compatibility = reader.read_u8()?;
219+ let avc_level_indication = reader.read_u8()?;
220+ let length_size_minus_one = reader.read_u8()? & 0x3;
221+ let num_of_spss = reader.read_u8()? & 0x1F;
222+ let mut sequence_parameter_sets = Vec::with_capacity(num_of_spss as usize);
223+ for _ in 0..num_of_spss {
224+ let nal_unit = NalUnit::read(reader)?;
225+ sequence_parameter_sets.push(nal_unit);
226+ }
227+ let num_of_ppss = reader.read_u8()?;
228+ let mut picture_parameter_sets = Vec::with_capacity(num_of_ppss as usize);
229+ for _ in 0..num_of_ppss {
230+ let nal_unit = NalUnit::read(reader)?;
231+ picture_parameter_sets.push(nal_unit);
232+ }
233+
234+ skip_bytes_to(reader, start + size)?;
235+
236+ Ok(AvcCBox {
237+ configuration_version,
238+ avc_profile_indication,
239+ profile_compatibility,
240+ avc_level_indication,
241+ length_size_minus_one,
242+ sequence_parameter_sets,
243+ picture_parameter_sets,
244+ })
245+ }
246+}
247+
248+impl<W: Write> WriteBox<&mut W> for AvcCBox {
249+ fn write_box(&self, writer: &mut W) -> Result<u64> {
250+ let size = self.box_size();
251+ BoxHeader::new(self.box_type(), size).write(writer)?;
252+
253+ writer.write_u8(self.configuration_version)?;
254+ writer.write_u8(self.avc_profile_indication)?;
255+ writer.write_u8(self.profile_compatibility)?;
256+ writer.write_u8(self.avc_level_indication)?;
257+ writer.write_u8(self.length_size_minus_one | 0xFC)?;
258+ writer.write_u8(self.sequence_parameter_sets.len() as u8 | 0xE0)?;
259+ for sps in self.sequence_parameter_sets.iter() {
260+ sps.write(writer)?;
261+ }
262+ writer.write_u8(self.picture_parameter_sets.len() as u8)?;
263+ for pps in self.picture_parameter_sets.iter() {
264+ pps.write(writer)?;
265+ }
266+ Ok(size)
267+ }
268+}
269+
270+#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize)]
271+pub struct NalUnit {
272+ pub bytes: Vec<u8>,
273+}
274+
275+impl From<&[u8]> for NalUnit {
276+ fn from(bytes: &[u8]) -> Self {
277+ Self {
278+ bytes: bytes.to_vec(),
279+ }
280+ }
281+}
282+
283+impl NalUnit {
284+ fn size(&self) -> usize {
285+ 2 + self.bytes.len()
286+ }
287+
288+ fn read<R: Read + Seek>(reader: &mut R) -> Result<Self> {
289+ let length = reader.read_u16::<BigEndian>()? as usize;
290+ let mut bytes = vec![0u8; length];
291+ reader.read_exact(&mut bytes)?;
292+ Ok(NalUnit { bytes })
293+ }
294+
295+ fn write<W: Write>(&self, writer: &mut W) -> Result<u64> {
296+ writer.write_u16::<BigEndian>(self.bytes.len() as u16)?;
297+ writer.write_all(&self.bytes)?;
298+ Ok(self.size() as u64)
299+ }
300+}
301+
302+#[cfg(test)]
303+mod tests {
304+ use super::*;
305+ use crate::mp4box::BoxHeader;
306+ use std::io::Cursor;
307+
308+ #[test]
309+ fn test_avc1() {
310+ let src_box = Avc1Box {
311+ data_reference_index: 1,
312+ width: 320,
313+ height: 240,
314+ horizresolution: FixedPointU16::new(0x48),
315+ vertresolution: FixedPointU16::new(0x48),
316+ frame_count: 1,
317+ depth: 24,
318+ avcc: AvcCBox {
319+ configuration_version: 1,
320+ avc_profile_indication: 100,
321+ profile_compatibility: 0,
322+ avc_level_indication: 13,
323+ length_size_minus_one: 3,
324+ sequence_parameter_sets: vec![NalUnit {
325+ bytes: vec![
326+ 0x67, 0x64, 0x00, 0x0D, 0xAC, 0xD9, 0x41, 0x41, 0xFA, 0x10, 0x00, 0x00,
327+ 0x03, 0x00, 0x10, 0x00, 0x00, 0x03, 0x03, 0x20, 0xF1, 0x42, 0x99, 0x60,
328+ ],
329+ }],
330+ picture_parameter_sets: vec![NalUnit {
331+ bytes: vec![0x68, 0xEB, 0xE3, 0xCB, 0x22, 0xC0],
332+ }],
333+ },
334+ };
335+ let mut buf = Vec::new();
336+ src_box.write_box(&mut buf).unwrap();
337+ assert_eq!(buf.len(), src_box.box_size() as usize);
338+
339+ let mut reader = Cursor::new(&buf);
340+ let header = BoxHeader::read(&mut reader).unwrap();
341+ assert_eq!(header.name, BoxType::Avc1Box);
342+ assert_eq!(src_box.box_size(), header.size);
343+
344+ let dst_box = Avc1Box::read_box(&mut reader, header.size).unwrap();
345+ assert_eq!(src_box, dst_box);
346+ }
347+}
vendor/mp4/src/mp4box/co64.rsadded+123 -0
@@ -0,0 +1,123 @@
1+use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
2+use serde::Serialize;
3+use std::io::{Read, Seek, Write};
4+use std::mem::size_of;
5+
6+use crate::mp4box::*;
7+
8+#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize)]
9+pub struct Co64Box {
10+ pub version: u8,
11+ pub flags: u32,
12+
13+ #[serde(skip_serializing)]
14+ pub entries: Vec<u64>,
15+}
16+
17+impl Co64Box {
18+ pub fn get_type(&self) -> BoxType {
19+ BoxType::Co64Box
20+ }
21+
22+ pub fn get_size(&self) -> u64 {
23+ HEADER_SIZE + HEADER_EXT_SIZE + 4 + (8 * self.entries.len() as u64)
24+ }
25+}
26+
27+impl Mp4Box for Co64Box {
28+ fn box_type(&self) -> BoxType {
29+ self.get_type()
30+ }
31+
32+ fn box_size(&self) -> u64 {
33+ self.get_size()
34+ }
35+
36+ fn to_json(&self) -> Result<String> {
37+ Ok(serde_json::to_string(&self).unwrap())
38+ }
39+
40+ fn summary(&self) -> Result<String> {
41+ let s = format!("entries_count={}", self.entries.len());
42+ Ok(s)
43+ }
44+}
45+
46+impl<R: Read + Seek> ReadBox<&mut R> for Co64Box {
47+ fn read_box(reader: &mut R, size: u64) -> Result<Self> {
48+ let start = box_start(reader)?;
49+
50+ let (version, flags) = read_box_header_ext(reader)?;
51+
52+ let header_size = HEADER_SIZE + HEADER_EXT_SIZE;
53+ let other_size = size_of::<u32>(); // entry_count
54+ let entry_size = size_of::<u64>(); // chunk_offset
55+ let entry_count = reader.read_u32::<BigEndian>()?;
56+ if u64::from(entry_count)
57+ > size
58+ .saturating_sub(header_size)
59+ .saturating_sub(other_size as u64)
60+ / entry_size as u64
61+ {
62+ return Err(Error::InvalidData(
63+ "co64 entry_count indicates more entries than could fit in the box",
64+ ));
65+ }
66+ let mut entries = Vec::with_capacity(entry_count as usize);
67+ for _i in 0..entry_count {
68+ let chunk_offset = reader.read_u64::<BigEndian>()?;
69+ entries.push(chunk_offset);
70+ }
71+
72+ skip_bytes_to(reader, start + size)?;
73+
74+ Ok(Co64Box {
75+ version,
76+ flags,
77+ entries,
78+ })
79+ }
80+}
81+
82+impl<W: Write> WriteBox<&mut W> for Co64Box {
83+ fn write_box(&self, writer: &mut W) -> Result<u64> {
84+ let size = self.box_size();
85+ BoxHeader::new(self.box_type(), size).write(writer)?;
86+
87+ write_box_header_ext(writer, self.version, self.flags)?;
88+
89+ writer.write_u32::<BigEndian>(self.entries.len() as u32)?;
90+ for chunk_offset in self.entries.iter() {
91+ writer.write_u64::<BigEndian>(*chunk_offset)?;
92+ }
93+
94+ Ok(size)
95+ }
96+}
97+
98+#[cfg(test)]
99+mod tests {
100+ use super::*;
101+ use crate::mp4box::BoxHeader;
102+ use std::io::Cursor;
103+
104+ #[test]
105+ fn test_co64() {
106+ let src_box = Co64Box {
107+ version: 0,
108+ flags: 0,
109+ entries: vec![267, 1970, 2535, 2803, 11843, 22223, 33584],
110+ };
111+ let mut buf = Vec::new();
112+ src_box.write_box(&mut buf).unwrap();
113+ assert_eq!(buf.len(), src_box.box_size() as usize);
114+
115+ let mut reader = Cursor::new(&buf);
116+ let header = BoxHeader::read(&mut reader).unwrap();
117+ assert_eq!(header.name, BoxType::Co64Box);
118+ assert_eq!(src_box.box_size(), header.size);
119+
120+ let dst_box = Co64Box::read_box(&mut reader, header.size).unwrap();
121+ assert_eq!(src_box, dst_box);
122+ }
123+}
vendor/mp4/src/mp4box/ctts.rsadded+143 -0
@@ -0,0 +1,143 @@
1+use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
2+use serde::Serialize;
3+use std::io::{Read, Seek, Write};
4+use std::mem::size_of;
5+
6+use crate::mp4box::*;
7+
8+#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize)]
9+pub struct CttsBox {
10+ pub version: u8,
11+ pub flags: u32,
12+
13+ #[serde(skip_serializing)]
14+ pub entries: Vec<CttsEntry>,
15+}
16+
17+impl CttsBox {
18+ pub fn get_type(&self) -> BoxType {
19+ BoxType::CttsBox
20+ }
21+
22+ pub fn get_size(&self) -> u64 {
23+ HEADER_SIZE + HEADER_EXT_SIZE + 4 + (8 * self.entries.len() as u64)
24+ }
25+}
26+
27+#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize)]
28+pub struct CttsEntry {
29+ pub sample_count: u32,
30+ pub sample_offset: i32,
31+}
32+
33+impl Mp4Box for CttsBox {
34+ fn box_type(&self) -> BoxType {
35+ self.get_type()
36+ }
37+
38+ fn box_size(&self) -> u64 {
39+ self.get_size()
40+ }
41+
42+ fn to_json(&self) -> Result<String> {
43+ Ok(serde_json::to_string(&self).unwrap())
44+ }
45+
46+ fn summary(&self) -> Result<String> {
47+ let s = format!("entries_count={}", self.entries.len());
48+ Ok(s)
49+ }
50+}
51+
52+impl<R: Read + Seek> ReadBox<&mut R> for CttsBox {
53+ fn read_box(reader: &mut R, size: u64) -> Result<Self> {
54+ let start = box_start(reader)?;
55+
56+ let (version, flags) = read_box_header_ext(reader)?;
57+
58+ let header_size = HEADER_SIZE + HEADER_EXT_SIZE;
59+ let entry_count = reader.read_u32::<BigEndian>()?;
60+ let entry_size = size_of::<u32>() + size_of::<i32>(); // sample_count + sample_offset
61+ // (sample_offset might be a u32, but the size is the same.)
62+ let other_size = size_of::<i32>(); // entry_count
63+ if u64::from(entry_count)
64+ > size
65+ .saturating_sub(header_size)
66+ .saturating_sub(other_size as u64)
67+ / entry_size as u64
68+ {
69+ return Err(Error::InvalidData(
70+ "ctts entry_count indicates more entries than could fit in the box",
71+ ));
72+ }
73+ let mut entries = Vec::with_capacity(entry_count as usize);
74+ for _ in 0..entry_count {
75+ let entry = CttsEntry {
76+ sample_count: reader.read_u32::<BigEndian>()?,
77+ sample_offset: reader.read_i32::<BigEndian>()?,
78+ };
79+ entries.push(entry);
80+ }
81+
82+ skip_bytes_to(reader, start + size)?;
83+
84+ Ok(CttsBox {
85+ version,
86+ flags,
87+ entries,
88+ })
89+ }
90+}
91+
92+impl<W: Write> WriteBox<&mut W> for CttsBox {
93+ fn write_box(&self, writer: &mut W) -> Result<u64> {
94+ let size = self.box_size();
95+ BoxHeader::new(self.box_type(), size).write(writer)?;
96+
97+ write_box_header_ext(writer, self.version, self.flags)?;
98+
99+ writer.write_u32::<BigEndian>(self.entries.len() as u32)?;
100+ for entry in self.entries.iter() {
101+ writer.write_u32::<BigEndian>(entry.sample_count)?;
102+ writer.write_i32::<BigEndian>(entry.sample_offset)?;
103+ }
104+
105+ Ok(size)
106+ }
107+}
108+
109+#[cfg(test)]
110+mod tests {
111+ use super::*;
112+ use crate::mp4box::BoxHeader;
113+ use std::io::Cursor;
114+
115+ #[test]
116+ fn test_ctts() {
117+ let src_box = CttsBox {
118+ version: 0,
119+ flags: 0,
120+ entries: vec![
121+ CttsEntry {
122+ sample_count: 1,
123+ sample_offset: 200,
124+ },
125+ CttsEntry {
126+ sample_count: 2,
127+ sample_offset: -100,
128+ },
129+ ],
130+ };
131+ let mut buf = Vec::new();
132+ src_box.write_box(&mut buf).unwrap();
133+ assert_eq!(buf.len(), src_box.box_size() as usize);
134+
135+ let mut reader = Cursor::new(&buf);
136+ let header = BoxHeader::read(&mut reader).unwrap();
137+ assert_eq!(header.name, BoxType::CttsBox);
138+ assert_eq!(src_box.box_size(), header.size);
139+
140+ let dst_box = CttsBox::read_box(&mut reader, header.size).unwrap();
141+ assert_eq!(src_box, dst_box);
142+ }
143+}
vendor/mp4/src/mp4box/data.rsadded+118 -0
@@ -0,0 +1,118 @@
1+use std::{
2+ convert::TryFrom,
3+ io::{Read, Seek},
4+};
5+
6+use serde::Serialize;
7+
8+use crate::mp4box::*;
9+
10+#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize)]
11+pub struct DataBox {
12+ pub data: Vec<u8>,
13+ pub data_type: DataType,
14+}
15+
16+impl DataBox {
17+ pub fn get_type(&self) -> BoxType {
18+ BoxType::DataBox
19+ }
20+
21+ pub fn get_size(&self) -> u64 {
22+ let mut size = HEADER_SIZE;
23+ size += 4; // data_type
24+ size += 4; // reserved
25+ size += self.data.len() as u64;
26+ size
27+ }
28+}
29+
30+impl Mp4Box for DataBox {
31+ fn box_type(&self) -> BoxType {
32+ self.get_type()
33+ }
34+
35+ fn box_size(&self) -> u64 {
36+ self.get_size()
37+ }
38+
39+ fn to_json(&self) -> Result<String> {
40+ Ok(serde_json::to_string(&self).unwrap())
41+ }
42+
43+ fn summary(&self) -> Result<String> {
44+ let s = format!("type={:?} len={}", self.data_type, self.data.len());
45+ Ok(s)
46+ }
47+}
48+
49+impl<R: Read + Seek> ReadBox<&mut R> for DataBox {
50+ fn read_box(reader: &mut R, size: u64) -> Result<Self> {
51+ let start = box_start(reader)?;
52+
53+ let data_type = DataType::try_from(reader.read_u32::<BigEndian>()?)?;
54+
55+ reader.read_u32::<BigEndian>()?; // reserved = 0
56+
57+ let current = reader.stream_position()?;
58+ let mut data = vec![0u8; (start + size - current) as usize];
59+ reader.read_exact(&mut data)?;
60+
61+ Ok(DataBox { data, data_type })
62+ }
63+}
64+
65+impl<W: Write> WriteBox<&mut W> for DataBox {
66+ fn write_box(&self, writer: &mut W) -> Result<u64> {
67+ let size = self.box_size();
68+ BoxHeader::new(self.box_type(), size).write(writer)?;
69+
70+ writer.write_u32::<BigEndian>(self.data_type.clone() as u32)?;
71+ writer.write_u32::<BigEndian>(0)?; // reserved = 0
72+ writer.write_all(&self.data)?;
73+
74+ Ok(size)
75+ }
76+}
77+
78+#[cfg(test)]
79+mod tests {
80+ use super::*;
81+ use crate::mp4box::BoxHeader;
82+ use std::io::Cursor;
83+
84+ #[test]
85+ fn test_data() {
86+ let src_box = DataBox {
87+ data_type: DataType::Text,
88+ data: b"test_data".to_vec(),
89+ };
90+ let mut buf = Vec::new();
91+ src_box.write_box(&mut buf).unwrap();
92+ assert_eq!(buf.len(), src_box.box_size() as usize);
93+
94+ let mut reader = Cursor::new(&buf);
95+ let header = BoxHeader::read(&mut reader).unwrap();
96+ assert_eq!(header.name, BoxType::DataBox);
97+ assert_eq!(src_box.box_size(), header.size);
98+
99+ let dst_box = DataBox::read_box(&mut reader, header.size).unwrap();
100+ assert_eq!(src_box, dst_box);
101+ }
102+
103+ #[test]
104+ fn test_data_empty() {
105+ let src_box = DataBox::default();
106+ let mut buf = Vec::new();
107+ src_box.write_box(&mut buf).unwrap();
108+ assert_eq!(buf.len(), src_box.box_size() as usize);
109+
110+ let mut reader = Cursor::new(&buf);
111+ let header = BoxHeader::read(&mut reader).unwrap();
112+ assert_eq!(header.name, BoxType::DataBox);
113+ assert_eq!(src_box.box_size(), header.size);
114+
115+ let dst_box = DataBox::read_box(&mut reader, header.size).unwrap();
116+ assert_eq!(src_box, dst_box);
117+ }
118+}
vendor/mp4/src/mp4box/dinf.rsadded+308 -0
@@ -0,0 +1,308 @@
1+use serde::Serialize;
2+use std::io::{Read, Seek, Write};
3+
4+use crate::mp4box::*;
5+
6+#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize)]
7+pub struct DinfBox {
8+ dref: DrefBox,
9+}
10+
11+impl DinfBox {
12+ pub fn get_type(&self) -> BoxType {
13+ BoxType::DinfBox
14+ }
15+
16+ pub fn get_size(&self) -> u64 {
17+ HEADER_SIZE + self.dref.box_size()
18+ }
19+}
20+
21+impl Mp4Box for DinfBox {
22+ fn box_type(&self) -> BoxType {
23+ self.get_type()
24+ }
25+
26+ fn box_size(&self) -> u64 {
27+ self.get_size()
28+ }
29+
30+ fn to_json(&self) -> Result<String> {
31+ Ok(serde_json::to_string(&self).unwrap())
32+ }
33+
34+ fn summary(&self) -> Result<String> {
35+ let s = String::new();
36+ Ok(s)
37+ }
38+}
39+
40+impl<R: Read + Seek> ReadBox<&mut R> for DinfBox {
41+ fn read_box(reader: &mut R, size: u64) -> Result<Self> {
42+ let start = box_start(reader)?;
43+
44+ let mut dref = None;
45+
46+ let mut current = reader.stream_position()?;
47+ let end = start + size;
48+ while current < end {
49+ // Get box header.
50+ let header = BoxHeader::read(reader)?;
51+ let BoxHeader { name, size: s } = header;
52+ if s > size {
53+ return Err(Error::InvalidData(
54+ "dinf box contains a box with a larger size than it",
55+ ));
56+ }
57+
58+ match name {
59+ BoxType::DrefBox => {
60+ dref = Some(DrefBox::read_box(reader, s)?);
61+ }
62+ _ => {
63+ // XXX warn!()
64+ skip_box(reader, s)?;
65+ }
66+ }
67+
68+ current = reader.stream_position()?;
69+ }
70+
71+ if dref.is_none() {
72+ return Err(Error::BoxNotFound(BoxType::DrefBox));
73+ }
74+
75+ skip_bytes_to(reader, start + size)?;
76+
77+ Ok(DinfBox {
78+ dref: dref.unwrap(),
79+ })
80+ }
81+}
82+
83+impl<W: Write> WriteBox<&mut W> for DinfBox {
84+ fn write_box(&self, writer: &mut W) -> Result<u64> {
85+ let size = self.box_size();
86+ BoxHeader::new(self.box_type(), size).write(writer)?;
87+ self.dref.write_box(writer)?;
88+ Ok(size)
89+ }
90+}
91+
92+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
93+pub struct DrefBox {
94+ pub version: u8,
95+ pub flags: u32,
96+
97+ #[serde(skip_serializing_if = "Option::is_none")]
98+ pub url: Option<UrlBox>,
99+}
100+
101+impl Default for DrefBox {
102+ fn default() -> Self {
103+ DrefBox {
104+ version: 0,
105+ flags: 0,
106+ url: Some(UrlBox::default()),
107+ }
108+ }
109+}
110+
111+impl DrefBox {
112+ pub fn get_type(&self) -> BoxType {
113+ BoxType::DrefBox
114+ }
115+
116+ pub fn get_size(&self) -> u64 {
117+ let mut size = HEADER_SIZE + HEADER_EXT_SIZE + 4;
118+ if let Some(ref url) = self.url {
119+ size += url.box_size();
120+ }
121+ size
122+ }
123+}
124+
125+impl Mp4Box for DrefBox {
126+ fn box_type(&self) -> BoxType {
127+ self.get_type()
128+ }
129+
130+ fn box_size(&self) -> u64 {
131+ self.get_size()
132+ }
133+
134+ fn to_json(&self) -> Result<String> {
135+ Ok(serde_json::to_string(&self).unwrap())
136+ }
137+
138+ fn summary(&self) -> Result<String> {
139+ let s = String::new();
140+ Ok(s)
141+ }
142+}
143+
144+impl<R: Read + Seek> ReadBox<&mut R> for DrefBox {
145+ fn read_box(reader: &mut R, size: u64) -> Result<Self> {
146+ let start = box_start(reader)?;
147+
148+ let mut current = reader.stream_position()?;
149+
150+ let (version, flags) = read_box_header_ext(reader)?;
151+ let end = start + size;
152+
153+ let mut url = None;
154+
155+ let entry_count = reader.read_u32::<BigEndian>()?;
156+ for _i in 0..entry_count {
157+ if current >= end {
158+ break;
159+ }
160+
161+ // Get box header.
162+ let header = BoxHeader::read(reader)?;
163+ let BoxHeader { name, size: s } = header;
164+ if s > size {
165+ return Err(Error::InvalidData(
166+ "dinf box contains a box with a larger size than it",
167+ ));
168+ }
169+
170+ match name {
171+ BoxType::UrlBox => {
172+ url = Some(UrlBox::read_box(reader, s)?);
173+ }
174+ _ => {
175+ skip_box(reader, s)?;
176+ }
177+ }
178+
179+ current = reader.stream_position()?;
180+ }
181+
182+ skip_bytes_to(reader, start + size)?;
183+
184+ Ok(DrefBox {
185+ version,
186+ flags,
187+ url,
188+ })
189+ }
190+}
191+
192+impl<W: Write> WriteBox<&mut W> for DrefBox {
193+ fn write_box(&self, writer: &mut W) -> Result<u64> {
194+ let size = self.box_size();
195+ BoxHeader::new(self.box_type(), size).write(writer)?;
196+
197+ write_box_header_ext(writer, self.version, self.flags)?;
198+
199+ writer.write_u32::<BigEndian>(1)?;
200+
201+ if let Some(ref url) = self.url {
202+ url.write_box(writer)?;
203+ }
204+
205+ Ok(size)
206+ }
207+}
208+
209+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
210+pub struct UrlBox {
211+ pub version: u8,
212+ pub flags: u32,
213+ pub location: String,
214+}
215+
216+impl Default for UrlBox {
217+ fn default() -> Self {
218+ UrlBox {
219+ version: 0,
220+ flags: 1,
221+ location: String::default(),
222+ }
223+ }
224+}
225+
226+impl UrlBox {
227+ pub fn get_type(&self) -> BoxType {
228+ BoxType::UrlBox
229+ }
230+
231+ pub fn get_size(&self) -> u64 {
232+ let mut size = HEADER_SIZE + HEADER_EXT_SIZE;
233+
234+ if !self.location.is_empty() {
235+ size += self.location.bytes().len() as u64 + 1;
236+ }
237+
238+ size
239+ }
240+}
241+
242+impl Mp4Box for UrlBox {
243+ fn box_type(&self) -> BoxType {
244+ self.get_type()
245+ }
246+
247+ fn box_size(&self) -> u64 {
248+ self.get_size()
249+ }
250+
251+ fn to_json(&self) -> Result<String> {
252+ Ok(serde_json::to_string(&self).unwrap())
253+ }
254+
255+ fn summary(&self) -> Result<String> {
256+ let s = format!("location={}", self.location);
257+ Ok(s)
258+ }
259+}
260+
261+impl<R: Read + Seek> ReadBox<&mut R> for UrlBox {
262+ fn read_box(reader: &mut R, size: u64) -> Result<Self> {
263+ let start = box_start(reader)?;
264+
265+ let (version, flags) = read_box_header_ext(reader)?;
266+
267+ let location = if size.saturating_sub(HEADER_SIZE + HEADER_EXT_SIZE) > 0 {
268+ let buf_size = size - HEADER_SIZE - HEADER_EXT_SIZE - 1;
269+ let mut buf = vec![0u8; buf_size as usize];
270+ reader.read_exact(&mut buf)?;
271+ match String::from_utf8(buf) {
272+ Ok(t) => {
273+ if t.len() != buf_size as usize {
274+ return Err(Error::InvalidData("string too small"));
275+ }
276+ t
277+ }
278+ _ => String::default(),
279+ }
280+ } else {
281+ String::default()
282+ };
283+
284+ skip_bytes_to(reader, start + size)?;
285+
286+ Ok(UrlBox {
287+ version,
288+ flags,
289+ location,
290+ })
291+ }
292+}
293+
294+impl<W: Write> WriteBox<&mut W> for UrlBox {
295+ fn write_box(&self, writer: &mut W) -> Result<u64> {
296+ let size = self.box_size();
297+ BoxHeader::new(self.box_type(), size).write(writer)?;
298+
299+ write_box_header_ext(writer, self.version, self.flags)?;
300+
301+ if !self.location.is_empty() {
302+ writer.write_all(self.location.as_bytes())?;
303+ writer.write_u8(0)?;
304+ }
305+
306+ Ok(size)
307+ }
308+}
vendor/mp4/src/mp4box/edts.rsadded+85 -0
@@ -0,0 +1,85 @@
1+use serde::Serialize;
2+use std::io::{Read, Seek, Write};
3+
4+use crate::mp4box::elst::ElstBox;
5+use crate::mp4box::*;
6+
7+#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize)]
8+pub struct EdtsBox {
9+ pub elst: Option<ElstBox>,
10+}
11+
12+impl EdtsBox {
13+ pub(crate) fn new() -> EdtsBox {
14+ Default::default()
15+ }
16+
17+ pub fn get_type(&self) -> BoxType {
18+ BoxType::EdtsBox
19+ }
20+
21+ pub fn get_size(&self) -> u64 {
22+ let mut size = HEADER_SIZE;
23+ if let Some(ref elst) = self.elst {
24+ size += elst.box_size();
25+ }
26+ size
27+ }
28+}
29+
30+impl Mp4Box for EdtsBox {
31+ fn box_type(&self) -> BoxType {
32+ self.get_type()
33+ }
34+
35+ fn box_size(&self) -> u64 {
36+ self.get_size()
37+ }
38+
39+ fn to_json(&self) -> Result<String> {
40+ Ok(serde_json::to_string(&self).unwrap())
41+ }
42+
43+ fn summary(&self) -> Result<String> {
44+ let s = String::new();
45+ Ok(s)
46+ }
47+}
48+
49+impl<R: Read + Seek> ReadBox<&mut R> for EdtsBox {
50+ fn read_box(reader: &mut R, size: u64) -> Result<Self> {
51+ let start = box_start(reader)?;
52+
53+ let mut edts = EdtsBox::new();
54+
55+ let header = BoxHeader::read(reader)?;
56+ let BoxHeader { name, size: s } = header;
57+ if s > size {
58+ return Err(Error::InvalidData(
59+ "edts box contains a box with a larger size than it",
60+ ));
61+ }
62+
63+ if let BoxType::ElstBox = name {
64+ let elst = ElstBox::read_box(reader, s)?;
65+ edts.elst = Some(elst);
66+ }
67+
68+ skip_bytes_to(reader, start + size)?;
69+
70+ Ok(edts)
71+ }
72+}
73+
74+impl<W: Write> WriteBox<&mut W> for EdtsBox {
75+ fn write_box(&self, writer: &mut W) -> Result<u64> {
76+ let size = self.box_size();
77+ BoxHeader::new(self.box_type(), size).write(writer)?;
78+
79+ if let Some(ref elst) = self.elst {
80+ elst.write_box(writer)?;
81+ }
82+
83+ Ok(size)
84+ }
85+}
vendor/mp4/src/mp4box/elst.rsadded+201 -0
@@ -0,0 +1,201 @@
1+use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
2+use serde::Serialize;
3+use std::io::{Read, Seek, Write};
4+use std::mem::size_of;
5+
6+use crate::mp4box::*;
7+
8+#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize)]
9+pub struct ElstBox {
10+ pub version: u8,
11+ pub flags: u32,
12+
13+ #[serde(skip_serializing)]
14+ pub entries: Vec<ElstEntry>,
15+}
16+
17+#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize)]
18+pub struct ElstEntry {
19+ pub segment_duration: u64,
20+ pub media_time: u64,
21+ pub media_rate: u16,
22+ pub media_rate_fraction: u16,
23+}
24+
25+impl ElstBox {
26+ pub fn get_type(&self) -> BoxType {
27+ BoxType::ElstBox
28+ }
29+
30+ pub fn get_size(&self) -> u64 {
31+ let mut size = HEADER_SIZE + HEADER_EXT_SIZE + 4;
32+ if self.version == 1 {
33+ size += self.entries.len() as u64 * 20;
34+ } else if self.version == 0 {
35+ size += self.entries.len() as u64 * 12;
36+ }
37+ size
38+ }
39+}
40+
41+impl Mp4Box for ElstBox {
42+ fn box_type(&self) -> BoxType {
43+ self.get_type()
44+ }
45+
46+ fn box_size(&self) -> u64 {
47+ self.get_size()
48+ }
49+
50+ fn to_json(&self) -> Result<String> {
51+ Ok(serde_json::to_string(&self).unwrap())
52+ }
53+
54+ fn summary(&self) -> Result<String> {
55+ let s = format!("elst_entries={}", self.entries.len());
56+ Ok(s)
57+ }
58+}
59+
60+impl<R: Read + Seek> ReadBox<&mut R> for ElstBox {
61+ fn read_box(reader: &mut R, size: u64) -> Result<Self> {
62+ let start = box_start(reader)?;
63+
64+ let (version, flags) = read_box_header_ext(reader)?;
65+
66+ let header_size = HEADER_SIZE + HEADER_EXT_SIZE;
67+ let entry_count = reader.read_u32::<BigEndian>()?;
68+ let other_size = size_of::<i32>(); // entry_count
69+ let entry_size = {
70+ let mut entry_size = 0;
71+ entry_size += if version == 1 {
72+ size_of::<u64>() + size_of::<i64>() // segment_duration + media_time
73+ } else {
74+ size_of::<u32>() + size_of::<i32>() // segment_duration + media_time
75+ };
76+ entry_size += size_of::<i16>() + size_of::<i16>(); // media_rate_integer + media_rate_fraction
77+ entry_size
78+ };
79+ if u64::from(entry_count)
80+ > size
81+ .saturating_sub(header_size)
82+ .saturating_sub(other_size as u64)
83+ / entry_size as u64
84+ {
85+ return Err(Error::InvalidData(
86+ "elst entry_count indicates more entries than could fit in the box",
87+ ));
88+ }
89+ let mut entries = Vec::with_capacity(entry_count as usize);
90+ for _ in 0..entry_count {
91+ let (segment_duration, media_time) = if version == 1 {
92+ (
93+ reader.read_u64::<BigEndian>()?,
94+ reader.read_u64::<BigEndian>()?,
95+ )
96+ } else {
97+ (
98+ reader.read_u32::<BigEndian>()? as u64,
99+ reader.read_u32::<BigEndian>()? as u64,
100+ )
101+ };
102+
103+ let entry = ElstEntry {
104+ segment_duration,
105+ media_time,
106+ media_rate: reader.read_u16::<BigEndian>()?,
107+ media_rate_fraction: reader.read_u16::<BigEndian>()?,
108+ };
109+ entries.push(entry);
110+ }
111+
112+ skip_bytes_to(reader, start + size)?;
113+
114+ Ok(ElstBox {
115+ version,
116+ flags,
117+ entries,
118+ })
119+ }
120+}
121+
122+impl<W: Write> WriteBox<&mut W> for ElstBox {
123+ fn write_box(&self, writer: &mut W) -> Result<u64> {
124+ let size = self.box_size();
125+ BoxHeader::new(self.box_type(), size).write(writer)?;
126+
127+ write_box_header_ext(writer, self.version, self.flags)?;
128+
129+ writer.write_u32::<BigEndian>(self.entries.len() as u32)?;
130+ for entry in self.entries.iter() {
131+ if self.version == 1 {
132+ writer.write_u64::<BigEndian>(entry.segment_duration)?;
133+ writer.write_u64::<BigEndian>(entry.media_time)?;
134+ } else {
135+ writer.write_u32::<BigEndian>(entry.segment_duration as u32)?;
136+ writer.write_u32::<BigEndian>(entry.media_time as u32)?;
137+ }
138+ writer.write_u16::<BigEndian>(entry.media_rate)?;
139+ writer.write_u16::<BigEndian>(entry.media_rate_fraction)?;
140+ }
141+
142+ Ok(size)
143+ }
144+}
145+
146+#[cfg(test)]
147+mod tests {
148+ use super::*;
149+ use crate::mp4box::BoxHeader;
150+ use std::io::Cursor;
151+
152+ #[test]
153+ fn test_elst32() {
154+ let src_box = ElstBox {
155+ version: 0,
156+ flags: 0,
157+ entries: vec![ElstEntry {
158+ segment_duration: 634634,
159+ media_time: 0,
160+ media_rate: 1,
161+ media_rate_fraction: 0,
162+ }],
163+ };
164+ let mut buf = Vec::new();
165+ src_box.write_box(&mut buf).unwrap();
166+ assert_eq!(buf.len(), src_box.box_size() as usize);
167+
168+ let mut reader = Cursor::new(&buf);
169+ let header = BoxHeader::read(&mut reader).unwrap();
170+ assert_eq!(header.name, BoxType::ElstBox);
171+ assert_eq!(src_box.box_size(), header.size);
172+
173+ let dst_box = ElstBox::read_box(&mut reader, header.size).unwrap();
174+ assert_eq!(src_box, dst_box);
175+ }
176+
177+ #[test]
178+ fn test_elst64() {
179+ let src_box = ElstBox {
180+ version: 1,
181+ flags: 0,
182+ entries: vec![ElstEntry {
183+ segment_duration: 634634,
184+ media_time: 0,
185+ media_rate: 1,
186+ media_rate_fraction: 0,
187+ }],
188+ };
189+ let mut buf = Vec::new();
190+ src_box.write_box(&mut buf).unwrap();
191+ assert_eq!(buf.len(), src_box.box_size() as usize);
192+
193+ let mut reader = Cursor::new(&buf);
194+ let header = BoxHeader::read(&mut reader).unwrap();
195+ assert_eq!(header.name, BoxType::ElstBox);
196+ assert_eq!(src_box.box_size(), header.size);
197+
198+ let dst_box = ElstBox::read_box(&mut reader, header.size).unwrap();
199+ assert_eq!(src_box, dst_box);
200+ }
201+}
vendor/mp4/src/mp4box/emsg.rsadded+242 -0
@@ -0,0 +1,242 @@
1+use std::ffi::CStr;
2+use std::io::{Read, Seek, Write};
3+
4+use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
5+use serde::Serialize;
6+
7+use crate::mp4box::*;
8+
9+#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize)]
10+pub struct EmsgBox {
11+ pub version: u8,
12+ pub flags: u32,
13+ pub timescale: u32,
14+ pub presentation_time: Option<u64>,
15+ pub presentation_time_delta: Option<u32>,
16+ pub event_duration: u32,
17+ pub id: u32,
18+ pub scheme_id_uri: String,
19+ pub value: String,
20+ pub message_data: Vec<u8>,
21+}
22+
23+impl EmsgBox {
24+ fn size_without_message(version: u8, scheme_id_uri: &str, value: &str) -> u64 {
25+ HEADER_SIZE + HEADER_EXT_SIZE +
26+ 4 + // id
27+ Self::time_size(version) +
28+ (scheme_id_uri.len() + 1) as u64 +
29+ (value.len() as u64 + 1)
30+ }
31+
32+ fn time_size(version: u8) -> u64 {
33+ match version {
34+ 0 => 12,
35+ 1 => 16,
36+ _ => panic!("version must be 0 or 1"),
37+ }
38+ }
39+}
40+
41+impl Mp4Box for EmsgBox {
42+ fn box_type(&self) -> BoxType {
43+ BoxType::EmsgBox
44+ }
45+
46+ fn box_size(&self) -> u64 {
47+ Self::size_without_message(self.version, &self.scheme_id_uri, &self.value)
48+ + self.message_data.len() as u64
49+ }
50+
51+ fn to_json(&self) -> Result<String> {
52+ Ok(serde_json::to_string(&self).unwrap())
53+ }
54+
55+ fn summary(&self) -> Result<String> {
56+ let s = format!("id={} value={}", self.id, self.value);
57+ Ok(s)
58+ }
59+}
60+
61+impl<R: Read + Seek> ReadBox<&mut R> for EmsgBox {
62+ fn read_box(reader: &mut R, size: u64) -> Result<Self> {
63+ let start = box_start(reader)?;
64+ let (version, flags) = read_box_header_ext(reader)?;
65+
66+ let (
67+ timescale,
68+ presentation_time,
69+ presentation_time_delta,
70+ event_duration,
71+ id,
72+ scheme_id_uri,
73+ value,
74+ ) = match version {
75+ 0 => {
76+ let scheme_id_uri = read_null_terminated_utf8_string(reader)?;
77+ let value = read_null_terminated_utf8_string(reader)?;
78+ (
79+ reader.read_u32::<BigEndian>()?,
80+ None,
81+ Some(reader.read_u32::<BigEndian>()?),
82+ reader.read_u32::<BigEndian>()?,
83+ reader.read_u32::<BigEndian>()?,
84+ scheme_id_uri,
85+ value,
86+ )
87+ }
88+ 1 => (
89+ reader.read_u32::<BigEndian>()?,
90+ Some(reader.read_u64::<BigEndian>()?),
91+ None,
92+ reader.read_u32::<BigEndian>()?,
93+ reader.read_u32::<BigEndian>()?,
94+ read_null_terminated_utf8_string(reader)?,
95+ read_null_terminated_utf8_string(reader)?,
96+ ),
97+ _ => return Err(Error::InvalidData("version must be 0 or 1")),
98+ };
99+
100+ let message_size = size - Self::size_without_message(version, &scheme_id_uri, &value);
101+ let mut message_data = Vec::with_capacity(message_size as usize);
102+ for _ in 0..message_size {
103+ message_data.push(reader.read_u8()?);
104+ }
105+
106+ skip_bytes_to(reader, start + size)?;
107+
108+ Ok(EmsgBox {
109+ version,
110+ flags,
111+ timescale,
112+ presentation_time,
113+ presentation_time_delta,
114+ event_duration,
115+ id,
116+ scheme_id_uri,
117+ value,
118+ message_data,
119+ })
120+ }
121+}
122+
123+impl<W: Write> WriteBox<&mut W> for EmsgBox {
124+ fn write_box(&self, writer: &mut W) -> Result<u64> {
125+ let size = self.box_size();
126+ BoxHeader::new(self.box_type(), size).write(writer)?;
127+
128+ write_box_header_ext(writer, self.version, self.flags)?;
129+ match self.version {
130+ 0 => {
131+ write_null_terminated_str(writer, &self.scheme_id_uri)?;
132+ write_null_terminated_str(writer, &self.value)?;
133+ writer.write_u32::<BigEndian>(self.timescale)?;
134+ writer.write_u32::<BigEndian>(self.presentation_time_delta.unwrap())?;
135+ writer.write_u32::<BigEndian>(self.event_duration)?;
136+ writer.write_u32::<BigEndian>(self.id)?;
137+ }
138+ 1 => {
139+ writer.write_u32::<BigEndian>(self.timescale)?;
140+ writer.write_u64::<BigEndian>(self.presentation_time.unwrap())?;
141+ writer.write_u32::<BigEndian>(self.event_duration)?;
142+ writer.write_u32::<BigEndian>(self.id)?;
143+ write_null_terminated_str(writer, &self.scheme_id_uri)?;
144+ write_null_terminated_str(writer, &self.value)?;
145+ }
146+ _ => return Err(Error::InvalidData("version must be 0 or 1")),
147+ }
148+
149+ for &byte in &self.message_data {
150+ writer.write_u8(byte)?;
151+ }
152+
153+ Ok(size)
154+ }
155+}
156+
157+fn read_null_terminated_utf8_string<R: Read + Seek>(reader: &mut R) -> Result<String> {
158+ let mut bytes = Vec::new();
159+ loop {
160+ let byte = reader.read_u8()?;
161+ bytes.push(byte);
162+ if byte == 0 {
163+ break;
164+ }
165+ }
166+ if let Ok(str) = unsafe { CStr::from_bytes_with_nul_unchecked(&bytes) }.to_str() {
167+ Ok(str.to_string())
168+ } else {
169+ Err(Error::InvalidData("invalid utf8"))
170+ }
171+}
172+
173+fn write_null_terminated_str<W: Write>(writer: &mut W, string: &str) -> Result<()> {
174+ for byte in string.bytes() {
175+ writer.write_u8(byte)?;
176+ }
177+ writer.write_u8(0)?;
178+ Ok(())
179+}
180+
181+#[cfg(test)]
182+mod tests {
183+ use std::io::Cursor;
184+
185+ use crate::mp4box::BoxHeader;
186+
187+ use super::*;
188+
189+ #[test]
190+ fn test_emsg_version0() {
191+ let src_box = EmsgBox {
192+ version: 0,
193+ flags: 0,
194+ timescale: 48000,
195+ presentation_time: None,
196+ presentation_time_delta: Some(100),
197+ event_duration: 200,
198+ id: 8,
199+ scheme_id_uri: String::from("foo"),
200+ value: String::from("foo"),
201+ message_data: vec![1, 2, 3],
202+ };
203+ let mut buf = Vec::new();
204+ src_box.write_box(&mut buf).unwrap();
205+ assert_eq!(buf.len(), src_box.box_size() as usize);
206+
207+ let mut reader = Cursor::new(&buf);
208+ let header = BoxHeader::read(&mut reader).unwrap();
209+ assert_eq!(header.name, BoxType::EmsgBox);
210+ assert_eq!(src_box.box_size(), header.size);
211+
212+ let dst_box = EmsgBox::read_box(&mut reader, header.size).unwrap();
213+ assert_eq!(src_box, dst_box);
214+ }
215+
216+ #[test]
217+ fn test_emsg_version1() {
218+ let src_box = EmsgBox {
219+ version: 1,
220+ flags: 0,
221+ timescale: 48000,
222+ presentation_time: Some(50000),
223+ presentation_time_delta: None,
224+ event_duration: 200,
225+ id: 8,
226+ scheme_id_uri: String::from("foo"),
227+ value: String::from("foo"),
228+ message_data: vec![3, 2, 1],
229+ };
230+ let mut buf = Vec::new();
231+ src_box.write_box(&mut buf).unwrap();
232+ assert_eq!(buf.len(), src_box.box_size() as usize);
233+
234+ let mut reader = Cursor::new(&buf);
235+ let header = BoxHeader::read(&mut reader).unwrap();
236+ assert_eq!(header.name, BoxType::EmsgBox);
237+ assert_eq!(src_box.box_size(), header.size);
238+
239+ let dst_box = EmsgBox::read_box(&mut reader, header.size).unwrap();
240+ assert_eq!(src_box, dst_box);
241+ }
242+}
vendor/mp4/src/mp4box/ftyp.rsadded+123 -0
@@ -0,0 +1,123 @@
1+use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
2+use serde::Serialize;
3+use std::io::{Read, Seek, Write};
4+
5+use crate::mp4box::*;
6+
7+#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize)]
8+pub struct FtypBox {
9+ pub major_brand: FourCC,
10+ pub minor_version: u32,
11+ pub compatible_brands: Vec<FourCC>,
12+}
13+
14+impl FtypBox {
15+ pub fn get_type(&self) -> BoxType {
16+ BoxType::FtypBox
17+ }
18+
19+ pub fn get_size(&self) -> u64 {
20+ HEADER_SIZE + 8 + (4 * self.compatible_brands.len() as u64)
21+ }
22+}
23+
24+impl Mp4Box for FtypBox {
25+ fn box_type(&self) -> BoxType {
26+ self.get_type()
27+ }
28+
29+ fn box_size(&self) -> u64 {
30+ self.get_size()
31+ }
32+
33+ fn to_json(&self) -> Result<String> {
34+ Ok(serde_json::to_string(&self).unwrap())
35+ }
36+
37+ fn summary(&self) -> Result<String> {
38+ let mut compatible_brands = Vec::new();
39+ for brand in self.compatible_brands.iter() {
40+ compatible_brands.push(brand.to_string());
41+ }
42+ let s = format!(
43+ "major_brand={} minor_version={} compatible_brands={}",
44+ self.major_brand,
45+ self.minor_version,
46+ compatible_brands.join("-")
47+ );
48+ Ok(s)
49+ }
50+}
51+
52+impl<R: Read + Seek> ReadBox<&mut R> for FtypBox {
53+ fn read_box(reader: &mut R, size: u64) -> Result<Self> {
54+ let start = box_start(reader)?;
55+
56+ if size < 16 || size % 4 != 0 {
57+ return Err(Error::InvalidData("ftyp size too small or not aligned"));
58+ }
59+ let brand_count = (size - 16) / 4; // header + major + minor
60+ let major = reader.read_u32::<BigEndian>()?;
61+ let minor = reader.read_u32::<BigEndian>()?;
62+
63+ let mut brands = Vec::new();
64+ for _ in 0..brand_count {
65+ let b = reader.read_u32::<BigEndian>()?;
66+ brands.push(From::from(b));
67+ }
68+
69+ skip_bytes_to(reader, start + size)?;
70+
71+ Ok(FtypBox {
72+ major_brand: From::from(major),
73+ minor_version: minor,
74+ compatible_brands: brands,
75+ })
76+ }
77+}
78+
79+impl<W: Write> WriteBox<&mut W> for FtypBox {
80+ fn write_box(&self, writer: &mut W) -> Result<u64> {
81+ let size = self.box_size();
82+ BoxHeader::new(self.box_type(), size).write(writer)?;
83+
84+ writer.write_u32::<BigEndian>((&self.major_brand).into())?;
85+ writer.write_u32::<BigEndian>(self.minor_version)?;
86+ for b in self.compatible_brands.iter() {
87+ writer.write_u32::<BigEndian>(b.into())?;
88+ }
89+ Ok(size)
90+ }
91+}
92+
93+#[cfg(test)]
94+mod tests {
95+ use super::*;
96+ use crate::mp4box::BoxHeader;
97+ use std::io::Cursor;
98+
99+ #[test]
100+ fn test_ftyp() {
101+ let src_box = FtypBox {
102+ major_brand: str::parse("isom").unwrap(),
103+ minor_version: 0,
104+ compatible_brands: vec![
105+ str::parse("isom").unwrap(),
106+ str::parse("iso2").unwrap(),
107+ str::parse("avc1").unwrap(),
108+ str::parse("mp41").unwrap(),
109+ ],
110+ };
111+ let mut buf = Vec::new();
112+ src_box.write_box(&mut buf).unwrap();
113+ assert_eq!(buf.len(), src_box.box_size() as usize);
114+
115+ let mut reader = Cursor::new(&buf);
116+ let header = BoxHeader::read(&mut reader).unwrap();
117+ assert_eq!(header.name, BoxType::FtypBox);
118+ assert_eq!(src_box.box_size(), header.size);
119+
120+ let dst_box = FtypBox::read_box(&mut reader, header.size).unwrap();
121+ assert_eq!(src_box, dst_box);
122+ }
123+}
vendor/mp4/src/mp4box/hdlr.rsadded+130 -0
@@ -0,0 +1,130 @@
1+use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
2+use serde::Serialize;
3+use std::io::{Read, Seek, Write};
4+
5+use crate::mp4box::*;
6+
7+#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize)]
8+pub struct HdlrBox {
9+ pub version: u8,
10+ pub flags: u32,
11+ pub handler_type: FourCC,
12+ pub name: String,
13+}
14+
15+impl HdlrBox {
16+ pub fn get_type(&self) -> BoxType {
17+ BoxType::HdlrBox
18+ }
19+
20+ pub fn get_size(&self) -> u64 {
21+ HEADER_SIZE + HEADER_EXT_SIZE + 20 + self.name.len() as u64 + 1
22+ }
23+}
24+
25+impl Mp4Box for HdlrBox {
26+ fn box_type(&self) -> BoxType {
27+ self.get_type()
28+ }
29+
30+ fn box_size(&self) -> u64 {
31+ self.get_size()
32+ }
33+
34+ fn to_json(&self) -> Result<String> {
35+ Ok(serde_json::to_string(&self).unwrap())
36+ }
37+
38+ fn summary(&self) -> Result<String> {
39+ let s = format!("handler_type={} name={}", self.handler_type, self.name);
40+ Ok(s)
41+ }
42+}
43+
44+impl<R: Read + Seek> ReadBox<&mut R> for HdlrBox {
45+ fn read_box(reader: &mut R, size: u64) -> Result<Self> {
46+ let start = box_start(reader)?;
47+
48+ let (version, flags) = read_box_header_ext(reader)?;
49+
50+ reader.read_u32::<BigEndian>()?; // pre-defined
51+ let handler = reader.read_u32::<BigEndian>()?;
52+
53+ skip_bytes(reader, 12)?; // reserved
54+
55+ let buf_size = size
56+ .checked_sub(HEADER_SIZE + HEADER_EXT_SIZE + 20 + 1)
57+ .ok_or(Error::InvalidData("hdlr size too small"))?;
58+ let mut buf = vec![0u8; buf_size as usize];
59+ reader.read_exact(&mut buf)?;
60+
61+ let handler_string = match String::from_utf8(buf) {
62+ Ok(t) => {
63+ if t.len() != buf_size as usize {
64+ return Err(Error::InvalidData("string too small"));
65+ }
66+ t
67+ }
68+ _ => String::from("null"),
69+ };
70+
71+ skip_bytes_to(reader, start + size)?;
72+
73+ Ok(HdlrBox {
74+ version,
75+ flags,
76+ handler_type: From::from(handler),
77+ name: handler_string,
78+ })
79+ }
80+}
81+
82+impl<W: Write> WriteBox<&mut W> for HdlrBox {
83+ fn write_box(&self, writer: &mut W) -> Result<u64> {
84+ let size = self.box_size();
85+ BoxHeader::new(self.box_type(), size).write(writer)?;
86+
87+ write_box_header_ext(writer, self.version, self.flags)?;
88+
89+ writer.write_u32::<BigEndian>(0)?; // pre-defined
90+ writer.write_u32::<BigEndian>((&self.handler_type).into())?;
91+
92+ // 12 bytes reserved
93+ for _ in 0..3 {
94+ writer.write_u32::<BigEndian>(0)?;
95+ }
96+
97+ writer.write_all(self.name.as_bytes())?;
98+ writer.write_u8(0)?;
99+
100+ Ok(size)
101+ }
102+}
103+
104+#[cfg(test)]
105+mod tests {
106+ use super::*;
107+ use crate::mp4box::BoxHeader;
108+ use std::io::Cursor;
109+
110+ #[test]
111+ fn test_hdlr() {
112+ let src_box = HdlrBox {
113+ version: 0,
114+ flags: 0,
115+ handler_type: str::parse::<FourCC>("vide").unwrap(),
116+ name: String::from("VideoHandler"),
117+ };
118+ let mut buf = Vec::new();
119+ src_box.write_box(&mut buf).unwrap();
120+ assert_eq!(buf.len(), src_box.box_size() as usize);
121+
122+ let mut reader = Cursor::new(&buf);
123+ let header = BoxHeader::read(&mut reader).unwrap();
124+ assert_eq!(header.name, BoxType::HdlrBox);
125+ assert_eq!(src_box.box_size(), header.size);
126+
127+ let dst_box = HdlrBox::read_box(&mut reader, header.size).unwrap();
128+ assert_eq!(src_box, dst_box);
129+ }
130+}
vendor/mp4/src/mp4box/hev1.rsadded+249 -0
@@ -0,0 +1,249 @@
1+use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
2+use serde::Serialize;
3+use std::io::{Read, Seek, Write};
4+
5+use crate::mp4box::*;
6+
7+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
8+pub struct Hev1Box {
9+ pub data_reference_index: u16,
10+ pub width: u16,
11+ pub height: u16,
12+
13+ #[serde(with = "value_u32")]
14+ pub horizresolution: FixedPointU16,
15+
16+ #[serde(with = "value_u32")]
17+ pub vertresolution: FixedPointU16,
18+ pub frame_count: u16,
19+ pub depth: u16,
20+ pub hvcc: HvcCBox,
21+}
22+
23+impl Default for Hev1Box {
24+ fn default() -> Self {
25+ Hev1Box {
26+ data_reference_index: 0,
27+ width: 0,
28+ height: 0,
29+ horizresolution: FixedPointU16::new(0x48),
30+ vertresolution: FixedPointU16::new(0x48),
31+ frame_count: 1,
32+ depth: 0x0018,
33+ hvcc: HvcCBox::default(),
34+ }
35+ }
36+}
37+
38+impl Hev1Box {
39+ pub fn new(config: &HevcConfig) -> Self {
40+ Hev1Box {
41+ data_reference_index: 1,
42+ width: config.width,
43+ height: config.height,
44+ horizresolution: FixedPointU16::new(0x48),
45+ vertresolution: FixedPointU16::new(0x48),
46+ frame_count: 1,
47+ depth: 0x0018,
48+ hvcc: HvcCBox::new(),
49+ }
50+ }
51+
52+ pub fn get_type(&self) -> BoxType {
53+ BoxType::Hev1Box
54+ }
55+
56+ pub fn get_size(&self) -> u64 {
57+ HEADER_SIZE + 8 + 70 + self.hvcc.box_size()
58+ }
59+}
60+
61+impl Mp4Box for Hev1Box {
62+ fn box_type(&self) -> BoxType {
63+ self.get_type()
64+ }
65+
66+ fn box_size(&self) -> u64 {
67+ self.get_size()
68+ }
69+
70+ fn to_json(&self) -> Result<String> {
71+ Ok(serde_json::to_string(&self).unwrap())
72+ }
73+
74+ fn summary(&self) -> Result<String> {
75+ let s = format!(
76+ "data_reference_index={} width={} height={} frame_count={}",
77+ self.data_reference_index, self.width, self.height, self.frame_count
78+ );
79+ Ok(s)
80+ }
81+}
82+
83+impl<R: Read + Seek> ReadBox<&mut R> for Hev1Box {
84+ fn read_box(reader: &mut R, size: u64) -> Result<Self> {
85+ let start = box_start(reader)?;
86+
87+ reader.read_u32::<BigEndian>()?; // reserved
88+ reader.read_u16::<BigEndian>()?; // reserved
89+ let data_reference_index = reader.read_u16::<BigEndian>()?;
90+
91+ reader.read_u32::<BigEndian>()?; // pre-defined, reserved
92+ reader.read_u64::<BigEndian>()?; // pre-defined
93+ reader.read_u32::<BigEndian>()?; // pre-defined
94+ let width = reader.read_u16::<BigEndian>()?;
95+ let height = reader.read_u16::<BigEndian>()?;
96+ let horizresolution = FixedPointU16::new_raw(reader.read_u32::<BigEndian>()?);
97+ let vertresolution = FixedPointU16::new_raw(reader.read_u32::<BigEndian>()?);
98+ reader.read_u32::<BigEndian>()?; // reserved
99+ let frame_count = reader.read_u16::<BigEndian>()?;
100+ skip_bytes(reader, 32)?; // compressorname
101+ let depth = reader.read_u16::<BigEndian>()?;
102+ reader.read_i16::<BigEndian>()?; // pre-defined
103+
104+ let header = BoxHeader::read(reader)?;
105+ let BoxHeader { name, size: s } = header;
106+ if s > size {
107+ return Err(Error::InvalidData(
108+ "hev1 box contains a box with a larger size than it",
109+ ));
110+ }
111+ if name == BoxType::HvcCBox {
112+ let hvcc = HvcCBox::read_box(reader, s)?;
113+
114+ skip_bytes_to(reader, start + size)?;
115+
116+ Ok(Hev1Box {
117+ data_reference_index,
118+ width,
119+ height,
120+ horizresolution,
121+ vertresolution,
122+ frame_count,
123+ depth,
124+ hvcc,
125+ })
126+ } else {
127+ Err(Error::InvalidData("hvcc not found"))
128+ }
129+ }
130+}
131+
132+impl<W: Write> WriteBox<&mut W> for Hev1Box {
133+ fn write_box(&self, writer: &mut W) -> Result<u64> {
134+ let size = self.box_size();
135+ BoxHeader::new(self.box_type(), size).write(writer)?;
136+
137+ writer.write_u32::<BigEndian>(0)?; // reserved
138+ writer.write_u16::<BigEndian>(0)?; // reserved
139+ writer.write_u16::<BigEndian>(self.data_reference_index)?;
140+
141+ writer.write_u32::<BigEndian>(0)?; // pre-defined, reserved
142+ writer.write_u64::<BigEndian>(0)?; // pre-defined
143+ writer.write_u32::<BigEndian>(0)?; // pre-defined
144+ writer.write_u16::<BigEndian>(self.width)?;
145+ writer.write_u16::<BigEndian>(self.height)?;
146+ writer.write_u32::<BigEndian>(self.horizresolution.raw_value())?;
147+ writer.write_u32::<BigEndian>(self.vertresolution.raw_value())?;
148+ writer.write_u32::<BigEndian>(0)?; // reserved
149+ writer.write_u16::<BigEndian>(self.frame_count)?;
150+ // skip compressorname
151+ write_zeros(writer, 32)?;
152+ writer.write_u16::<BigEndian>(self.depth)?;
153+ writer.write_i16::<BigEndian>(-1)?; // pre-defined
154+
155+ self.hvcc.write_box(writer)?;
156+
157+ Ok(size)
158+ }
159+}
160+
161+#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize)]
162+pub struct HvcCBox {
163+ pub configuration_version: u8,
164+}
165+
166+impl HvcCBox {
167+ pub fn new() -> Self {
168+ Self {
169+ configuration_version: 1,
170+ }
171+ }
172+}
173+
174+impl Mp4Box for HvcCBox {
175+ fn box_type(&self) -> BoxType {
176+ BoxType::HvcCBox
177+ }
178+
179+ fn box_size(&self) -> u64 {
180+ HEADER_SIZE + 1
181+ }
182+
183+ fn to_json(&self) -> Result<String> {
184+ Ok(serde_json::to_string(&self).unwrap())
185+ }
186+
187+ fn summary(&self) -> Result<String> {
188+ let s = format!("configuration_version={}", self.configuration_version);
189+ Ok(s)
190+ }
191+}
192+
193+impl<R: Read + Seek> ReadBox<&mut R> for HvcCBox {
194+ fn read_box(reader: &mut R, size: u64) -> Result<Self> {
195+ let start = box_start(reader)?;
196+
197+ let configuration_version = reader.read_u8()?;
198+
199+ skip_bytes_to(reader, start + size)?;
200+
201+ Ok(HvcCBox {
202+ configuration_version,
203+ })
204+ }
205+}
206+
207+impl<W: Write> WriteBox<&mut W> for HvcCBox {
208+ fn write_box(&self, writer: &mut W) -> Result<u64> {
209+ let size = self.box_size();
210+ BoxHeader::new(self.box_type(), size).write(writer)?;
211+
212+ writer.write_u8(self.configuration_version)?;
213+ Ok(size)
214+ }
215+}
216+
217+#[cfg(test)]
218+mod tests {
219+ use super::*;
220+ use crate::mp4box::BoxHeader;
221+ use std::io::Cursor;
222+
223+ #[test]
224+ fn test_hev1() {
225+ let src_box = Hev1Box {
226+ data_reference_index: 1,
227+ width: 320,
228+ height: 240,
229+ horizresolution: FixedPointU16::new(0x48),
230+ vertresolution: FixedPointU16::new(0x48),
231+ frame_count: 1,
232+ depth: 24,
233+ hvcc: HvcCBox {
234+ configuration_version: 1,
235+ },
236+ };
237+ let mut buf = Vec::new();
238+ src_box.write_box(&mut buf).unwrap();
239+ assert_eq!(buf.len(), src_box.box_size() as usize);
240+
241+ let mut reader = Cursor::new(&buf);
242+ let header = BoxHeader::read(&mut reader).unwrap();
243+ assert_eq!(header.name, BoxType::Hev1Box);
244+ assert_eq!(src_box.box_size(), header.size);
245+
246+ let dst_box = Hev1Box::read_box(&mut reader, header.size).unwrap();
247+ assert_eq!(src_box, dst_box);
248+ }
249+}
vendor/mp4/src/mp4box/ilst.rsadded+253 -0
@@ -0,0 +1,253 @@
1+use std::borrow::Cow;
2+use std::collections::HashMap;
3+use std::io::{Read, Seek};
4+
5+use byteorder::ByteOrder;
6+use serde::Serialize;
7+
8+use crate::mp4box::data::DataBox;
9+use crate::mp4box::*;
10+
11+#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize)]
12+pub struct IlstBox {
13+ pub items: HashMap<MetadataKey, IlstItemBox>,
14+}
15+
16+impl IlstBox {
17+ pub fn get_type(&self) -> BoxType {
18+ BoxType::IlstBox
19+ }
20+
21+ pub fn get_size(&self) -> u64 {
22+ let mut size = HEADER_SIZE;
23+ for item in self.items.values() {
24+ size += item.get_size();
25+ }
26+ size
27+ }
28+}
29+
30+impl Mp4Box for IlstBox {
31+ fn box_type(&self) -> BoxType {
32+ self.get_type()
33+ }
34+
35+ fn box_size(&self) -> u64 {
36+ self.get_size()
37+ }
38+
39+ fn to_json(&self) -> Result<String> {
40+ Ok(serde_json::to_string(&self).unwrap())
41+ }
42+
43+ fn summary(&self) -> Result<String> {
44+ let s = format!("item_count={}", self.items.len());
45+ Ok(s)
46+ }
47+}
48+
49+impl<R: Read + Seek> ReadBox<&mut R> for IlstBox {
50+ fn read_box(reader: &mut R, size: u64) -> Result<Self> {
51+ let start = box_start(reader)?;
52+
53+ let mut items = HashMap::new();
54+
55+ let mut current = reader.stream_position()?;
56+ let end = start + size;
57+ while current < end {
58+ // Get box header.
59+ let header = BoxHeader::read(reader)?;
60+ let BoxHeader { name, size: s } = header;
61+ if s > size {
62+ return Err(Error::InvalidData(
63+ "ilst box contains a box with a larger size than it",
64+ ));
65+ }
66+
67+ match name {
68+ BoxType::NameBox => {
69+ items.insert(MetadataKey::Title, IlstItemBox::read_box(reader, s)?);
70+ }
71+ BoxType::DayBox => {
72+ items.insert(MetadataKey::Year, IlstItemBox::read_box(reader, s)?);
73+ }
74+ BoxType::CovrBox => {
75+ items.insert(MetadataKey::Poster, IlstItemBox::read_box(reader, s)?);
76+ }
77+ BoxType::DescBox => {
78+ items.insert(MetadataKey::Summary, IlstItemBox::read_box(reader, s)?);
79+ }
80+ _ => {
81+ // XXX warn!()
82+ skip_box(reader, s)?;
83+ }
84+ }
85+
86+ current = reader.stream_position()?;
87+ }
88+
89+ skip_bytes_to(reader, start + size)?;
90+
91+ Ok(IlstBox { items })
92+ }
93+}
94+
95+impl<W: Write> WriteBox<&mut W> for IlstBox {
96+ fn write_box(&self, writer: &mut W) -> Result<u64> {
97+ let size = self.box_size();
98+ BoxHeader::new(self.box_type(), size).write(writer)?;
99+
100+ for (key, value) in &self.items {
101+ let name = match key {
102+ MetadataKey::Title => BoxType::NameBox,
103+ MetadataKey::Year => BoxType::DayBox,
104+ MetadataKey::Poster => BoxType::CovrBox,
105+ MetadataKey::Summary => BoxType::DescBox,
106+ };
107+ BoxHeader::new(name, value.get_size()).write(writer)?;
108+ value.data.write_box(writer)?;
109+ }
110+ Ok(size)
111+ }
112+}
113+
114+#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize)]
115+pub struct IlstItemBox {
116+ pub data: DataBox,
117+}
118+
119+impl IlstItemBox {
120+ fn get_size(&self) -> u64 {
121+ HEADER_SIZE + self.data.box_size()
122+ }
123+}
124+
125+impl<R: Read + Seek> ReadBox<&mut R> for IlstItemBox {
126+ fn read_box(reader: &mut R, size: u64) -> Result<Self> {
127+ let start = box_start(reader)?;
128+
129+ let mut data = None;
130+
131+ let mut current = reader.stream_position()?;
132+ let end = start + size;
133+ while current < end {
134+ // Get box header.
135+ let header = BoxHeader::read(reader)?;
136+ let BoxHeader { name, size: s } = header;
137+ if s > size {
138+ return Err(Error::InvalidData(
139+ "ilst item box contains a box with a larger size than it",
140+ ));
141+ }
142+
143+ match name {
144+ BoxType::DataBox => {
145+ data = Some(DataBox::read_box(reader, s)?);
146+ }
147+ _ => {
148+ // XXX warn!()
149+ skip_box(reader, s)?;
150+ }
151+ }
152+
153+ current = reader.stream_position()?;
154+ }
155+
156+ if data.is_none() {
157+ return Err(Error::BoxNotFound(BoxType::DataBox));
158+ }
159+
160+ skip_bytes_to(reader, start + size)?;
161+
162+ Ok(IlstItemBox {
163+ data: data.unwrap(),
164+ })
165+ }
166+}
167+
168+impl<'a> Metadata<'a> for IlstBox {
169+ fn title(&self) -> Option<Cow<'_, str>> {
170+ self.items.get(&MetadataKey::Title).map(item_to_str)
171+ }
172+
173+ fn year(&self) -> Option<u32> {
174+ self.items.get(&MetadataKey::Year).and_then(item_to_u32)
175+ }
176+
177+ fn poster(&self) -> Option<&[u8]> {
178+ self.items.get(&MetadataKey::Poster).map(item_to_bytes)
179+ }
180+
181+ fn summary(&self) -> Option<Cow<'_, str>> {
182+ self.items.get(&MetadataKey::Summary).map(item_to_str)
183+ }
184+}
185+
186+fn item_to_bytes(item: &IlstItemBox) -> &[u8] {
187+ &item.data.data
188+}
189+
190+fn item_to_str(item: &IlstItemBox) -> Cow<'_, str> {
191+ String::from_utf8_lossy(&item.data.data)
192+}
193+
194+fn item_to_u32(item: &IlstItemBox) -> Option<u32> {
195+ match item.data.data_type {
196+ DataType::Binary if item.data.data.len() == 4 => Some(BigEndian::read_u32(&item.data.data)),
197+ DataType::Text => String::from_utf8_lossy(&item.data.data).parse::<u32>().ok(),
198+ _ => None,
199+ }
200+}
201+
202+#[cfg(test)]
203+mod tests {
204+ use super::*;
205+ use crate::mp4box::BoxHeader;
206+ use std::io::Cursor;
207+
208+ #[test]
209+ fn test_ilst() {
210+ let src_year = IlstItemBox {
211+ data: DataBox {
212+ data_type: DataType::Text,
213+ data: b"test_year".to_vec(),
214+ },
215+ };
216+ let src_box = IlstBox {
217+ items: [
218+ (MetadataKey::Title, IlstItemBox::default()),
219+ (MetadataKey::Year, src_year),
220+ (MetadataKey::Poster, IlstItemBox::default()),
221+ (MetadataKey::Summary, IlstItemBox::default()),
222+ ]
223+ .into(),
224+ };
225+ let mut buf = Vec::new();
226+ src_box.write_box(&mut buf).unwrap();
227+ assert_eq!(buf.len(), src_box.box_size() as usize);
228+
229+ let mut reader = Cursor::new(&buf);
230+ let header = BoxHeader::read(&mut reader).unwrap();
231+ assert_eq!(header.name, BoxType::IlstBox);
232+ assert_eq!(src_box.box_size(), header.size);
233+
234+ let dst_box = IlstBox::read_box(&mut reader, header.size).unwrap();
235+ assert_eq!(src_box, dst_box);
236+ }
237+
238+ #[test]
239+ fn test_ilst_empty() {
240+ let src_box = IlstBox::default();
241+ let mut buf = Vec::new();
242+ src_box.write_box(&mut buf).unwrap();
243+ assert_eq!(buf.len(), src_box.box_size() as usize);
244+
245+ let mut reader = Cursor::new(&buf);
246+ let header = BoxHeader::read(&mut reader).unwrap();
247+ assert_eq!(header.name, BoxType::IlstBox);
248+ assert_eq!(src_box.box_size(), header.size);
249+
250+ let dst_box = IlstBox::read_box(&mut reader, header.size).unwrap();
251+ assert_eq!(src_box, dst_box);
252+ }
253+}
vendor/mp4/src/mp4box/mdhd.rsadded+231 -0
@@ -0,0 +1,231 @@
1+use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
2+use serde::Serialize;
3+use std::char::{decode_utf16, REPLACEMENT_CHARACTER};
4+use std::io::{Read, Seek, Write};
5+
6+use crate::mp4box::*;
7+
8+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
9+pub struct MdhdBox {
10+ pub version: u8,
11+ pub flags: u32,
12+ pub creation_time: u64,
13+ pub modification_time: u64,
14+ pub timescale: u32,
15+ pub duration: u64,
16+ pub language: String,
17+}
18+
19+impl MdhdBox {
20+ pub fn get_type(&self) -> BoxType {
21+ BoxType::MdhdBox
22+ }
23+
24+ pub fn get_size(&self) -> u64 {
25+ let mut size = HEADER_SIZE + HEADER_EXT_SIZE;
26+
27+ if self.version == 1 {
28+ size += 28;
29+ } else if self.version == 0 {
30+ size += 16;
31+ }
32+ size += 4;
33+ size
34+ }
35+}
36+
37+impl Default for MdhdBox {
38+ fn default() -> Self {
39+ MdhdBox {
40+ version: 0,
41+ flags: 0,
42+ creation_time: 0,
43+ modification_time: 0,
44+ timescale: 1000,
45+ duration: 0,
46+ language: String::from("und"),
47+ }
48+ }
49+}
50+
51+impl Mp4Box for MdhdBox {
52+ fn box_type(&self) -> BoxType {
53+ self.get_type()
54+ }
55+
56+ fn box_size(&self) -> u64 {
57+ self.get_size()
58+ }
59+
60+ fn to_json(&self) -> Result<String> {
61+ Ok(serde_json::to_string(&self).unwrap())
62+ }
63+
64+ fn summary(&self) -> Result<String> {
65+ let s = format!(
66+ "creation_time={} timescale={} duration={} language={}",
67+ self.creation_time, self.timescale, self.duration, self.language
68+ );
69+ Ok(s)
70+ }
71+}
72+
73+impl<R: Read + Seek> ReadBox<&mut R> for MdhdBox {
74+ fn read_box(reader: &mut R, size: u64) -> Result<Self> {
75+ let start = box_start(reader)?;
76+
77+ let (version, flags) = read_box_header_ext(reader)?;
78+
79+ let (creation_time, modification_time, timescale, duration) = if version == 1 {
80+ (
81+ reader.read_u64::<BigEndian>()?,
82+ reader.read_u64::<BigEndian>()?,
83+ reader.read_u32::<BigEndian>()?,
84+ reader.read_u64::<BigEndian>()?,
85+ )
86+ } else if version == 0 {
87+ (
88+ reader.read_u32::<BigEndian>()? as u64,
89+ reader.read_u32::<BigEndian>()? as u64,
90+ reader.read_u32::<BigEndian>()?,
91+ reader.read_u32::<BigEndian>()? as u64,
92+ )
93+ } else {
94+ return Err(Error::InvalidData("version must be 0 or 1"));
95+ };
96+ let language_code = reader.read_u16::<BigEndian>()?;
97+ let language = language_string(language_code);
98+
99+ skip_bytes_to(reader, start + size)?;
100+
101+ Ok(MdhdBox {
102+ version,
103+ flags,
104+ creation_time,
105+ modification_time,
106+ timescale,
107+ duration,
108+ language,
109+ })
110+ }
111+}
112+
113+impl<W: Write> WriteBox<&mut W> for MdhdBox {
114+ fn write_box(&self, writer: &mut W) -> Result<u64> {
115+ let size = self.box_size();
116+ BoxHeader::new(self.box_type(), size).write(writer)?;
117+
118+ write_box_header_ext(writer, self.version, self.flags)?;
119+
120+ if self.version == 1 {
121+ writer.write_u64::<BigEndian>(self.creation_time)?;
122+ writer.write_u64::<BigEndian>(self.modification_time)?;
123+ writer.write_u32::<BigEndian>(self.timescale)?;
124+ writer.write_u64::<BigEndian>(self.duration)?;
125+ } else if self.version == 0 {
126+ writer.write_u32::<BigEndian>(self.creation_time as u32)?;
127+ writer.write_u32::<BigEndian>(self.modification_time as u32)?;
128+ writer.write_u32::<BigEndian>(self.timescale)?;
129+ writer.write_u32::<BigEndian>(self.duration as u32)?;
130+ } else {
131+ return Err(Error::InvalidData("version must be 0 or 1"));
132+ }
133+
134+ let language_code = language_code(&self.language);
135+ writer.write_u16::<BigEndian>(language_code)?;
136+ writer.write_u16::<BigEndian>(0)?; // pre-defined
137+
138+ Ok(size)
139+ }
140+}
141+
142+fn language_string(language: u16) -> String {
143+ let mut lang: [u16; 3] = [0; 3];
144+
145+ lang[0] = ((language >> 10) & 0x1F) + 0x60;
146+ lang[1] = ((language >> 5) & 0x1F) + 0x60;
147+ lang[2] = ((language) & 0x1F) + 0x60;
148+
149+ // Decode utf-16 encoded bytes into a string.
150+ let lang_str = decode_utf16(lang.iter().cloned())
151+ .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))
152+ .collect::<String>();
153+
154+ lang_str
155+}
156+
157+fn language_code(language: &str) -> u16 {
158+ let mut lang = language.encode_utf16();
159+ let mut code = (lang.next().unwrap_or(0) & 0x1F) << 10;
160+ code += (lang.next().unwrap_or(0) & 0x1F) << 5;
161+ code += lang.next().unwrap_or(0) & 0x1F;
162+ code
163+}
164+
165+#[cfg(test)]
166+mod tests {
167+ use super::*;
168+ use crate::mp4box::BoxHeader;
169+ use std::io::Cursor;
170+
171+ fn test_language_code(lang: &str) {
172+ let code = language_code(lang);
173+ let lang2 = language_string(code);
174+ assert_eq!(lang, lang2);
175+ }
176+
177+ #[test]
178+ fn test_language_codes() {
179+ test_language_code("und");
180+ test_language_code("eng");
181+ test_language_code("kor");
182+ }
183+
184+ #[test]
185+ fn test_mdhd32() {
186+ let src_box = MdhdBox {
187+ version: 0,
188+ flags: 0,
189+ creation_time: 100,
190+ modification_time: 200,
191+ timescale: 48000,
192+ duration: 30439936,
193+ language: String::from("und"),
194+ };
195+ let mut buf = Vec::new();
196+ src_box.write_box(&mut buf).unwrap();
197+ assert_eq!(buf.len(), src_box.box_size() as usize);
198+
199+ let mut reader = Cursor::new(&buf);
200+ let header = BoxHeader::read(&mut reader).unwrap();
201+ assert_eq!(header.name, BoxType::MdhdBox);
202+ assert_eq!(src_box.box_size(), header.size);
203+
204+ let dst_box = MdhdBox::read_box(&mut reader, header.size).unwrap();
205+ assert_eq!(src_box, dst_box);
206+ }
207+
208+ #[test]
209+ fn test_mdhd64() {
210+ let src_box = MdhdBox {
211+ version: 0,
212+ flags: 0,
213+ creation_time: 100,
214+ modification_time: 200,
215+ timescale: 48000,
216+ duration: 30439936,
217+ language: String::from("eng"),
218+ };
219+ let mut buf = Vec::new();
220+ src_box.write_box(&mut buf).unwrap();
221+ assert_eq!(buf.len(), src_box.box_size() as usize);
222+
223+ let mut reader = Cursor::new(&buf);
224+ let header = BoxHeader::read(&mut reader).unwrap();
225+ assert_eq!(header.name, BoxType::MdhdBox);
226+ assert_eq!(src_box.box_size(), header.size);
227+
228+ let dst_box = MdhdBox::read_box(&mut reader, header.size).unwrap();
229+ assert_eq!(src_box, dst_box);
230+ }
231+}
vendor/mp4/src/mp4box/mdia.rsadded+113 -0
@@ -0,0 +1,113 @@
1+use serde::Serialize;
2+use std::io::{Read, Seek, Write};
3+
4+use crate::mp4box::*;
5+use crate::mp4box::{hdlr::HdlrBox, mdhd::MdhdBox, minf::MinfBox};
6+
7+#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize)]
8+pub struct MdiaBox {
9+ pub mdhd: MdhdBox,
10+ pub hdlr: HdlrBox,
11+ pub minf: MinfBox,
12+}
13+
14+impl MdiaBox {
15+ pub fn get_type(&self) -> BoxType {
16+ BoxType::MdiaBox
17+ }
18+
19+ pub fn get_size(&self) -> u64 {
20+ HEADER_SIZE + self.mdhd.box_size() + self.hdlr.box_size() + self.minf.box_size()
21+ }
22+}
23+
24+impl Mp4Box for MdiaBox {
25+ fn box_type(&self) -> BoxType {
26+ self.get_type()
27+ }
28+
29+ fn box_size(&self) -> u64 {
30+ self.get_size()
31+ }
32+
33+ fn to_json(&self) -> Result<String> {
34+ Ok(serde_json::to_string(&self).unwrap())
35+ }
36+
37+ fn summary(&self) -> Result<String> {
38+ let s = String::new();
39+ Ok(s)
40+ }
41+}
42+
43+impl<R: Read + Seek> ReadBox<&mut R> for MdiaBox {
44+ fn read_box(reader: &mut R, size: u64) -> Result<Self> {
45+ let start = box_start(reader)?;
46+
47+ let mut mdhd = None;
48+ let mut hdlr = None;
49+ let mut minf = None;
50+
51+ let mut current = reader.stream_position()?;
52+ let end = start + size;
53+ while current < end {
54+ // Get box header.
55+ let header = BoxHeader::read(reader)?;
56+ let BoxHeader { name, size: s } = header;
57+ if s > size {
58+ return Err(Error::InvalidData(
59+ "mdia box contains a box with a larger size than it",
60+ ));
61+ }
62+
63+ match name {
64+ BoxType::MdhdBox => {
65+ mdhd = Some(MdhdBox::read_box(reader, s)?);
66+ }
67+ BoxType::HdlrBox => {
68+ hdlr = Some(HdlrBox::read_box(reader, s)?);
69+ }
70+ BoxType::MinfBox => {
71+ minf = Some(MinfBox::read_box(reader, s)?);
72+ }
73+ _ => {
74+ // XXX warn!()
75+ skip_box(reader, s)?;
76+ }
77+ }
78+
79+ current = reader.stream_position()?;
80+ }
81+
82+ if mdhd.is_none() {
83+ return Err(Error::BoxNotFound(BoxType::MdhdBox));
84+ }
85+ if hdlr.is_none() {
86+ return Err(Error::BoxNotFound(BoxType::HdlrBox));
87+ }
88+ if minf.is_none() {
89+ return Err(Error::BoxNotFound(BoxType::MinfBox));
90+ }
91+
92+ skip_bytes_to(reader, start + size)?;
93+
94+ Ok(MdiaBox {
95+ mdhd: mdhd.unwrap(),
96+ hdlr: hdlr.unwrap(),
97+ minf: minf.unwrap(),
98+ })
99+ }
100+}
101+
102+impl<W: Write> WriteBox<&mut W> for MdiaBox {
103+ fn write_box(&self, writer: &mut W) -> Result<u64> {
104+ let size = self.box_size();
105+ BoxHeader::new(self.box_type(), size).write(writer)?;
106+
107+ self.mdhd.write_box(writer)?;
108+ self.hdlr.write_box(writer)?;
109+ self.minf.write_box(writer)?;
110+
111+ Ok(size)
112+ }
113+}
vendor/mp4/src/mp4box/mehd.rsadded+137 -0
@@ -0,0 +1,137 @@
1+use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
2+use serde::Serialize;
3+use std::io::{Read, Seek, Write};
4+
5+use crate::mp4box::*;
6+
7+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Default)]
8+pub struct MehdBox {
9+ pub version: u8,
10+ pub flags: u32,
11+ pub fragment_duration: u64,
12+}
13+
14+impl MehdBox {
15+ pub fn get_type(&self) -> BoxType {
16+ BoxType::MehdBox
17+ }
18+
19+ pub fn get_size(&self) -> u64 {
20+ let mut size = HEADER_SIZE + HEADER_EXT_SIZE;
21+
22+ if self.version == 1 {
23+ size += 8;
24+ } else if self.version == 0 {
25+ size += 4;
26+ }
27+ size
28+ }
29+}
30+
31+impl Mp4Box for MehdBox {
32+ fn box_type(&self) -> BoxType {
33+ self.get_type()
34+ }
35+
36+ fn box_size(&self) -> u64 {
37+ self.get_size()
38+ }
39+
40+ fn to_json(&self) -> Result<String> {
41+ Ok(serde_json::to_string(&self).unwrap())
42+ }
43+
44+ fn summary(&self) -> Result<String> {
45+ let s = format!("fragment_duration={}", self.fragment_duration);
46+ Ok(s)
47+ }
48+}
49+
50+impl<R: Read + Seek> ReadBox<&mut R> for MehdBox {
51+ fn read_box(reader: &mut R, size: u64) -> Result<Self> {
52+ let start = box_start(reader)?;
53+
54+ let (version, flags) = read_box_header_ext(reader)?;
55+
56+ let fragment_duration = if version == 1 {
57+ reader.read_u64::<BigEndian>()?
58+ } else if version == 0 {
59+ reader.read_u32::<BigEndian>()? as u64
60+ } else {
61+ return Err(Error::InvalidData("version must be 0 or 1"));
62+ };
63+ skip_bytes_to(reader, start + size)?;
64+
65+ Ok(MehdBox {
66+ version,
67+ flags,
68+ fragment_duration,
69+ })
70+ }
71+}
72+
73+impl<W: Write> WriteBox<&mut W> for MehdBox {
74+ fn write_box(&self, writer: &mut W) -> Result<u64> {
75+ let size = self.box_size();
76+ BoxHeader::new(self.box_type(), size).write(writer)?;
77+
78+ write_box_header_ext(writer, self.version, self.flags)?;
79+
80+ if self.version == 1 {
81+ writer.write_u64::<BigEndian>(self.fragment_duration)?;
82+ } else if self.version == 0 {
83+ writer.write_u32::<BigEndian>(self.fragment_duration as u32)?;
84+ } else {
85+ return Err(Error::InvalidData("version must be 0 or 1"));
86+ }
87+
88+ Ok(size)
89+ }
90+}
91+
92+#[cfg(test)]
93+mod tests {
94+ use super::*;
95+ use crate::mp4box::BoxHeader;
96+ use std::io::Cursor;
97+
98+ #[test]
99+ fn test_mehd32() {
100+ let src_box = MehdBox {
101+ version: 0,
102+ flags: 0,
103+ fragment_duration: 32,
104+ };
105+ let mut buf = Vec::new();
106+ src_box.write_box(&mut buf).unwrap();
107+ assert_eq!(buf.len(), src_box.box_size() as usize);
108+
109+ let mut reader = Cursor::new(&buf);
110+ let header = BoxHeader::read(&mut reader).unwrap();
111+ assert_eq!(header.name, BoxType::MehdBox);
112+ assert_eq!(src_box.box_size(), header.size);
113+
114+ let dst_box = MehdBox::read_box(&mut reader, header.size).unwrap();
115+ assert_eq!(src_box, dst_box);
116+ }
117+
118+ #[test]
119+ fn test_mehd64() {
120+ let src_box = MehdBox {
121+ version: 0,
122+ flags: 0,
123+ fragment_duration: 30439936,
124+ };
125+ let mut buf = Vec::new();
126+ src_box.write_box(&mut buf).unwrap();
127+ assert_eq!(buf.len(), src_box.box_size() as usize);
128+
129+ let mut reader = Cursor::new(&buf);
130+ let header = BoxHeader::read(&mut reader).unwrap();
131+ assert_eq!(header.name, BoxType::MehdBox);
132+ assert_eq!(src_box.box_size(), header.size);
133+
134+ let dst_box = MehdBox::read_box(&mut reader, header.size).unwrap();
135+ assert_eq!(src_box, dst_box);
136+ }
137+}
vendor/mp4/src/mp4box/meta.rsadded+312 -0
@@ -0,0 +1,312 @@
1+use std::io::{Read, Seek};
2+
3+use serde::Serialize;
4+
5+use crate::mp4box::hdlr::HdlrBox;
6+use crate::mp4box::ilst::IlstBox;
7+use crate::mp4box::*;
8+
9+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
10+#[serde(tag = "hdlr")]
11+#[serde(rename_all = "lowercase")]
12+pub enum MetaBox {
13+ Mdir {
14+ #[serde(skip_serializing_if = "Option::is_none")]
15+ ilst: Option<IlstBox>,
16+ },
17+
18+ #[serde(skip)]
19+ Unknown {
20+ #[serde(skip)]
21+ hdlr: HdlrBox,
22+
23+ #[serde(skip)]
24+ data: Vec<(BoxType, Vec<u8>)>,
25+ },
26+}
27+
28+const MDIR: FourCC = FourCC { value: *b"mdir" };
29+
30+impl MetaBox {
31+ pub fn get_type(&self) -> BoxType {
32+ BoxType::MetaBox
33+ }
34+
35+ pub fn get_size(&self) -> u64 {
36+ let mut size = HEADER_SIZE + HEADER_EXT_SIZE;
37+ match self {
38+ Self::Mdir { ilst } => {
39+ size += HdlrBox::default().box_size();
40+ if let Some(ilst) = ilst {
41+ size += ilst.box_size();
42+ }
43+ }
44+ Self::Unknown { hdlr, data } => {
45+ size += hdlr.box_size()
46+ + data
47+ .iter()
48+ .map(|(_, data)| data.len() as u64 + HEADER_SIZE)
49+ .sum::<u64>()
50+ }
51+ }
52+ size
53+ }
54+}
55+
56+impl Mp4Box for MetaBox {
57+ fn box_type(&self) -> BoxType {
58+ self.get_type()
59+ }
60+
61+ fn box_size(&self) -> u64 {
62+ self.get_size()
63+ }
64+
65+ fn to_json(&self) -> Result<String> {
66+ Ok(serde_json::to_string(&self).unwrap())
67+ }
68+
69+ fn summary(&self) -> Result<String> {
70+ let s = match self {
71+ Self::Mdir { .. } => "hdlr=ilst".to_string(),
72+ Self::Unknown { hdlr, data } => {
73+ format!("hdlr={} data_len={}", hdlr.handler_type, data.len())
74+ }
75+ };
76+ Ok(s)
77+ }
78+}
79+
80+impl Default for MetaBox {
81+ fn default() -> Self {
82+ Self::Unknown {
83+ hdlr: Default::default(),
84+ data: Default::default(),
85+ }
86+ }
87+}
88+
89+impl<R: Read + Seek> ReadBox<&mut R> for MetaBox {
90+ fn read_box(reader: &mut R, size: u64) -> Result<Self> {
91+ let start = box_start(reader)?;
92+
93+ let extended_header = reader.read_u32::<BigEndian>()?;
94+ if extended_header != 0 {
95+ // ISO mp4 requires this header (version & flags) to be 0. Some
96+ // files skip the extended header and directly start the hdlr box.
97+ let possible_hdlr = BoxType::from(reader.read_u32::<BigEndian>()?);
98+ if possible_hdlr == BoxType::HdlrBox {
99+ // This file skipped the extended header! Go back to start.
100+ reader.seek(SeekFrom::Current(-8))?;
101+ } else {
102+ // Looks like we actually have a bad version number or flags.
103+ let v = (extended_header >> 24) as u8;
104+ return Err(Error::UnsupportedBoxVersion(BoxType::MetaBox, v));
105+ }
106+ }
107+
108+ let mut current = reader.stream_position()?;
109+ let end = start + size;
110+
111+ let content_start = current;
112+
113+ // find the hdlr box
114+ let mut hdlr = None;
115+ while current < end {
116+ // Get box header.
117+ let header = BoxHeader::read(reader)?;
118+ let BoxHeader { name, size: s } = header;
119+
120+ match name {
121+ BoxType::HdlrBox => {
122+ hdlr = Some(HdlrBox::read_box(reader, s)?);
123+ }
124+ _ => {
125+ // XXX warn!()
126+ skip_box(reader, s)?;
127+ }
128+ }
129+
130+ current = reader.stream_position()?;
131+ }
132+
133+ let Some(hdlr) = hdlr else {
134+ return Err(Error::BoxNotFound(BoxType::HdlrBox));
135+ };
136+
137+ // rewind and handle the other boxes
138+ reader.seek(SeekFrom::Start(content_start))?;
139+ current = reader.stream_position()?;
140+
141+ let mut ilst = None;
142+
143+ match hdlr.handler_type {
144+ MDIR => {
145+ while current < end {
146+ // Get box header.
147+ let header = BoxHeader::read(reader)?;
148+ let BoxHeader { name, size: s } = header;
149+
150+ match name {
151+ BoxType::IlstBox => {
152+ ilst = Some(IlstBox::read_box(reader, s)?);
153+ }
154+ _ => {
155+ // XXX warn!()
156+ skip_box(reader, s)?;
157+ }
158+ }
159+
160+ current = reader.stream_position()?;
161+ }
162+
163+ Ok(MetaBox::Mdir { ilst })
164+ }
165+ _ => {
166+ let mut data = Vec::new();
167+
168+ while current < end {
169+ // Get box header.
170+ let header = BoxHeader::read(reader)?;
171+ let BoxHeader { name, size: s } = header;
172+
173+ match name {
174+ BoxType::HdlrBox => {
175+ skip_box(reader, s)?;
176+ }
177+ _ => {
178+ let mut box_data = vec![0; (s - HEADER_SIZE) as usize];
179+ reader.read_exact(&mut box_data)?;
180+
181+ data.push((name, box_data));
182+ }
183+ }
184+
185+ current = reader.stream_position()?;
186+ }
187+
188+ Ok(MetaBox::Unknown { hdlr, data })
189+ }
190+ }
191+ }
192+}
193+
194+impl<W: Write> WriteBox<&mut W> for MetaBox {
195+ fn write_box(&self, writer: &mut W) -> Result<u64> {
196+ let size = self.box_size();
197+ BoxHeader::new(self.box_type(), size).write(writer)?;
198+
199+ write_box_header_ext(writer, 0, 0)?;
200+
201+ let hdlr = match self {
202+ Self::Mdir { .. } => HdlrBox {
203+ handler_type: MDIR,
204+ ..Default::default()
205+ },
206+ Self::Unknown { hdlr, .. } => hdlr.clone(),
207+ };
208+ hdlr.write_box(writer)?;
209+
210+ match self {
211+ Self::Mdir { ilst } => {
212+ if let Some(ilst) = ilst {
213+ ilst.write_box(writer)?;
214+ }
215+ }
216+ Self::Unknown { data, .. } => {
217+ for (box_type, data) in data {
218+ BoxHeader::new(*box_type, data.len() as u64 + HEADER_SIZE).write(writer)?;
219+ writer.write_all(data)?;
220+ }
221+ }
222+ }
223+ Ok(size)
224+ }
225+}
226+
227+#[cfg(test)]
228+mod tests {
229+ use super::*;
230+ use crate::mp4box::BoxHeader;
231+ use std::io::Cursor;
232+
233+ #[test]
234+ fn test_meta_mdir_empty() {
235+ let src_box = MetaBox::Mdir { ilst: None };
236+
237+ let mut buf = Vec::new();
238+ src_box.write_box(&mut buf).unwrap();
239+ assert_eq!(buf.len(), src_box.box_size() as usize);
240+
241+ let mut reader = Cursor::new(&buf);
242+ let header = BoxHeader::read(&mut reader).unwrap();
243+ assert_eq!(header.name, BoxType::MetaBox);
244+ assert_eq!(header.size, src_box.box_size());
245+
246+ let dst_box = MetaBox::read_box(&mut reader, header.size).unwrap();
247+ assert_eq!(dst_box, src_box);
248+ }
249+
250+ #[test]
251+ fn test_meta_mdir() {
252+ let src_box = MetaBox::Mdir {
253+ ilst: Some(IlstBox::default()),
254+ };
255+
256+ let mut buf = Vec::new();
257+ src_box.write_box(&mut buf).unwrap();
258+ assert_eq!(buf.len(), src_box.box_size() as usize);
259+
260+ let mut reader = Cursor::new(&buf);
261+ let header = BoxHeader::read(&mut reader).unwrap();
262+ assert_eq!(header.name, BoxType::MetaBox);
263+ assert_eq!(header.size, src_box.box_size());
264+
265+ let dst_box = MetaBox::read_box(&mut reader, header.size).unwrap();
266+ assert_eq!(dst_box, src_box);
267+ }
268+
269+ #[test]
270+ fn test_meta_hdrl_non_first() {
271+ let data = b"\x00\x00\x00\x7fmeta\x00\x00\x00\x00\x00\x00\x00Qilst\x00\x00\x00I\xa9too\x00\x00\x00Adata\x00\x00\x00\x01\x00\x00\x00\x00TMPGEnc Video Mastering Works 7 Version 7.0.15.17\x00\x00\x00\"hdlr\x00\x00\x00\x00\x00\x00\x00\x00mdirappl\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00";
272+ let mut reader = Cursor::new(data);
273+ let header = BoxHeader::read(&mut reader).unwrap();
274+ assert_eq!(header.name, BoxType::MetaBox);
275+
276+ let meta_box = MetaBox::read_box(&mut reader, header.size).unwrap();
277+
278+ // this contains \xa9too box in the ilst
279+ // it designates the tool that created the file, but is not yet supported by this crate
280+ assert_eq!(
281+ meta_box,
282+ MetaBox::Mdir {
283+ ilst: Some(IlstBox::default())
284+ }
285+ );
286+ }
287+
288+ #[test]
289+ fn test_meta_unknown() {
290+ let src_hdlr = HdlrBox {
291+ handler_type: FourCC::from(*b"test"),
292+ ..Default::default()
293+ };
294+ let src_data = (BoxType::UnknownBox(0x42494241), b"123".to_vec());
295+ let src_box = MetaBox::Unknown {
296+ hdlr: src_hdlr,
297+ data: vec![src_data],
298+ };
299+
300+ let mut buf = Vec::new();
301+ src_box.write_box(&mut buf).unwrap();
302+ assert_eq!(buf.len(), src_box.box_size() as usize);
303+
304+ let mut reader = Cursor::new(&buf);
305+ let header = BoxHeader::read(&mut reader).unwrap();
306+ assert_eq!(header.name, BoxType::MetaBox);
307+ assert_eq!(header.size, src_box.box_size());
308+
309+ let dst_box = MetaBox::read_box(&mut reader, header.size).unwrap();
310+ assert_eq!(dst_box, src_box);
311+ }
312+}
vendor/mp4/src/mp4box/mfhd.rsadded+107 -0
@@ -0,0 +1,107 @@
1+use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
2+use serde::Serialize;
3+use std::io::{Read, Seek, Write};
4+
5+use crate::mp4box::*;
6+
7+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
8+pub struct MfhdBox {
9+ pub version: u8,
10+ pub flags: u32,
11+ pub sequence_number: u32,
12+}
13+
14+impl Default for MfhdBox {
15+ fn default() -> Self {
16+ MfhdBox {
17+ version: 0,
18+ flags: 0,
19+ sequence_number: 1,
20+ }
21+ }
22+}
23+
24+impl MfhdBox {
25+ pub fn get_type(&self) -> BoxType {
26+ BoxType::MfhdBox
27+ }
28+
29+ pub fn get_size(&self) -> u64 {
30+ HEADER_SIZE + HEADER_EXT_SIZE + 4
31+ }
32+}
33+
34+impl Mp4Box for MfhdBox {
35+ fn box_type(&self) -> BoxType {
36+ self.get_type()
37+ }
38+
39+ fn box_size(&self) -> u64 {
40+ self.get_size()
41+ }
42+
43+ fn to_json(&self) -> Result<String> {
44+ Ok(serde_json::to_string(&self).unwrap())
45+ }
46+
47+ fn summary(&self) -> Result<String> {
48+ let s = format!("sequence_number={}", self.sequence_number);
49+ Ok(s)
50+ }
51+}
52+
53+impl<R: Read + Seek> ReadBox<&mut R> for MfhdBox {
54+ fn read_box(reader: &mut R, size: u64) -> Result<Self> {
55+ let start = box_start(reader)?;
56+
57+ let (version, flags) = read_box_header_ext(reader)?;
58+ let sequence_number = reader.read_u32::<BigEndian>()?;
59+
60+ skip_bytes_to(reader, start + size)?;
61+
62+ Ok(MfhdBox {
63+ version,
64+ flags,
65+ sequence_number,
66+ })
67+ }
68+}
69+
70+impl<W: Write> WriteBox<&mut W> for MfhdBox {
71+ fn write_box(&self, writer: &mut W) -> Result<u64> {
72+ let size = self.box_size();
73+ BoxHeader::new(self.box_type(), size).write(writer)?;
74+
75+ write_box_header_ext(writer, self.version, self.flags)?;
76+ writer.write_u32::<BigEndian>(self.sequence_number)?;
77+
78+ Ok(size)
79+ }
80+}
81+
82+#[cfg(test)]
83+mod tests {
84+ use super::*;
85+ use crate::mp4box::BoxHeader;
86+ use std::io::Cursor;
87+
88+ #[test]
89+ fn test_mfhd() {
90+ let src_box = MfhdBox {
91+ version: 0,
92+ flags: 0,
93+ sequence_number: 1,
94+ };
95+ let mut buf = Vec::new();
96+ src_box.write_box(&mut buf).unwrap();
97+ assert_eq!(buf.len(), src_box.box_size() as usize);
98+
99+ let mut reader = Cursor::new(&buf);
100+ let header = BoxHeader::read(&mut reader).unwrap();
101+ assert_eq!(header.name, BoxType::MfhdBox);
102+ assert_eq!(src_box.box_size(), header.size);
103+
104+ let dst_box = MfhdBox::read_box(&mut reader, header.size).unwrap();
105+ assert_eq!(src_box, dst_box);
106+ }
107+}
vendor/mp4/src/mp4box/minf.rsadded+134 -0
@@ -0,0 +1,134 @@
1+use serde::Serialize;
2+use std::io::{Read, Seek, Write};
3+
4+use crate::mp4box::*;
5+use crate::mp4box::{dinf::DinfBox, smhd::SmhdBox, stbl::StblBox, vmhd::VmhdBox};
6+
7+#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize)]
8+pub struct MinfBox {
9+ #[serde(skip_serializing_if = "Option::is_none")]
10+ pub vmhd: Option<VmhdBox>,
11+
12+ #[serde(skip_serializing_if = "Option::is_none")]
13+ pub smhd: Option<SmhdBox>,
14+
15+ pub dinf: DinfBox,
16+ pub stbl: StblBox,
17+}
18+
19+impl MinfBox {
20+ pub fn get_type(&self) -> BoxType {
21+ BoxType::MinfBox
22+ }
23+
24+ pub fn get_size(&self) -> u64 {
25+ let mut size = HEADER_SIZE;
26+ if let Some(ref vmhd) = self.vmhd {
27+ size += vmhd.box_size();
28+ }
29+ if let Some(ref smhd) = self.smhd {
30+ size += smhd.box_size();
31+ }
32+ size += self.dinf.box_size();
33+ size += self.stbl.box_size();
34+ size
35+ }
36+}
37+
38+impl Mp4Box for MinfBox {
39+ fn box_type(&self) -> BoxType {
40+ self.get_type()
41+ }
42+
43+ fn box_size(&self) -> u64 {
44+ self.get_size()
45+ }
46+
47+ fn to_json(&self) -> Result<String> {
48+ Ok(serde_json::to_string(&self).unwrap())
49+ }
50+
51+ fn summary(&self) -> Result<String> {
52+ let s = String::new();
53+ Ok(s)
54+ }
55+}
56+
57+impl<R: Read + Seek> ReadBox<&mut R> for MinfBox {
58+ fn read_box(reader: &mut R, size: u64) -> Result<Self> {
59+ let start = box_start(reader)?;
60+
61+ let mut vmhd = None;
62+ let mut smhd = None;
63+ let mut dinf = None;
64+ let mut stbl = None;
65+
66+ let mut current = reader.stream_position()?;
67+ let end = start + size;
68+ while current < end {
69+ // Get box header.
70+ let header = BoxHeader::read(reader)?;
71+ let BoxHeader { name, size: s } = header;
72+ if s > size {
73+ return Err(Error::InvalidData(
74+ "minf box contains a box with a larger size than it",
75+ ));
76+ }
77+
78+ match name {
79+ BoxType::VmhdBox => {
80+ vmhd = Some(VmhdBox::read_box(reader, s)?);
81+ }
82+ BoxType::SmhdBox => {
83+ smhd = Some(SmhdBox::read_box(reader, s)?);
84+ }
85+ BoxType::DinfBox => {
86+ dinf = Some(DinfBox::read_box(reader, s)?);
87+ }
88+ BoxType::StblBox => {
89+ stbl = Some(StblBox::read_box(reader, s)?);
90+ }
91+ _ => {
92+ // XXX warn!()
93+ skip_box(reader, s)?;
94+ }
95+ }
96+
97+ current = reader.stream_position()?;
98+ }
99+
100+ if dinf.is_none() {
101+ return Err(Error::BoxNotFound(BoxType::DinfBox));
102+ }
103+ if stbl.is_none() {
104+ return Err(Error::BoxNotFound(BoxType::StblBox));
105+ }
106+
107+ skip_bytes_to(reader, start + size)?;
108+
109+ Ok(MinfBox {
110+ vmhd,
111+ smhd,
112+ dinf: dinf.unwrap(),
113+ stbl: stbl.unwrap(),
114+ })
115+ }
116+}
117+
118+impl<W: Write> WriteBox<&mut W> for MinfBox {
119+ fn write_box(&self, writer: &mut W) -> Result<u64> {
120+ let size = self.box_size();
121+ BoxHeader::new(self.box_type(), size).write(writer)?;
122+
123+ if let Some(ref vmhd) = self.vmhd {
124+ vmhd.write_box(writer)?;
125+ }
126+ if let Some(ref smhd) = self.smhd {
127+ smhd.write_box(writer)?;
128+ }
129+ self.dinf.write_box(writer)?;
130+ self.stbl.write_box(writer)?;
131+
132+ Ok(size)
133+ }
134+}
vendor/mp4/src/mp4box/mod.rsadded+395 -0
@@ -0,0 +1,395 @@
1+//! All ISO-MP4 boxes (atoms) and operations.
2+//!
3+//! * [ISO/IEC 14496-12](https://en.wikipedia.org/wiki/MPEG-4_Part_14) - ISO Base Media File Format (QuickTime, MPEG-4, etc)
4+//! * [ISO/IEC 14496-14](https://en.wikipedia.org/wiki/MPEG-4_Part_14) - MP4 file format
5+//! * ISO/IEC 14496-17 - Streaming text format
6+//! * [ISO 23009-1](https://www.iso.org/standard/79329.html) -Dynamic adaptive streaming over HTTP (DASH)
7+//!
8+//! http://developer.apple.com/documentation/QuickTime/QTFF/index.html
9+//! http://www.adobe.com/devnet/video/articles/mp4_movie_atom.html
10+//! http://mp4ra.org/#/atoms
11+//!
12+//! Supported Atoms:
13+//! ftyp
14+//! moov
15+//! mvhd
16+//! udta
17+//! meta
18+//! ilst
19+//! data
20+//! trak
21+//! tkhd
22+//! mdia
23+//! mdhd
24+//! hdlr
25+//! minf
26+//! stbl
27+//! stsd
28+//! avc1
29+//! hev1
30+//! mp4a
31+//! tx3g
32+//! stts
33+//! stsc
34+//! stsz
35+//! stss
36+//! stco
37+//! co64
38+//! ctts
39+//! dinf
40+//! dref
41+//! smhd
42+//! vmhd
43+//! edts
44+//! elst
45+//! mvex
46+//! mehd
47+//! trex
48+//! emsg
49+//! moof
50+//! mfhd
51+//! traf
52+//! tfhd
53+//! tfdt
54+//! trun
55+//! mdat
56+//! free
57+//!
58+
59+use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
60+use std::convert::TryInto;
61+use std::io::{Read, Seek, SeekFrom, Write};
62+
63+use crate::*;
64+
65+pub(crate) mod avc1;
66+pub(crate) mod co64;
67+pub(crate) mod ctts;
68+pub(crate) mod data;
69+pub(crate) mod dinf;
70+pub(crate) mod edts;
71+pub(crate) mod elst;
72+pub(crate) mod emsg;
73+pub(crate) mod ftyp;
74+pub(crate) mod hdlr;
75+pub(crate) mod hev1;
76+pub(crate) mod ilst;
77+pub(crate) mod mdhd;
78+pub(crate) mod mdia;
79+pub(crate) mod mehd;
80+pub(crate) mod meta;
81+pub(crate) mod mfhd;
82+pub(crate) mod minf;
83+pub(crate) mod moof;
84+pub(crate) mod moov;
85+pub(crate) mod mp4a;
86+pub(crate) mod mvex;
87+pub(crate) mod mvhd;
88+pub(crate) mod smhd;
89+pub(crate) mod stbl;
90+pub(crate) mod stco;
91+pub(crate) mod stsc;
92+pub(crate) mod stsd;
93+pub(crate) mod stss;
94+pub(crate) mod stsz;
95+pub(crate) mod stts;
96+pub(crate) mod tfdt;
97+pub(crate) mod tfhd;
98+pub(crate) mod tkhd;
99+pub(crate) mod traf;
100+pub(crate) mod trak;
101+pub(crate) mod trex;
102+pub(crate) mod trun;
103+pub(crate) mod tx3g;
104+pub(crate) mod udta;
105+pub(crate) mod vmhd;
106+pub(crate) mod vp09;
107+pub(crate) mod vpcc;
108+
109+pub use emsg::EmsgBox;
110+pub use ftyp::FtypBox;
111+pub use moof::MoofBox;
112+pub use moov::MoovBox;
113+
114+pub const HEADER_SIZE: u64 = 8;
115+// const HEADER_LARGE_SIZE: u64 = 16;
116+pub const HEADER_EXT_SIZE: u64 = 4;
117+
118+macro_rules! boxtype {
119+ ($( $name:ident => $value:expr ),*) => {
120+ #[derive(Clone, Copy, PartialEq, Eq)]
121+ pub enum BoxType {
122+ $( $name, )*
123+ UnknownBox(u32),
124+ }
125+
126+ impl From<u32> for BoxType {
127+ fn from(t: u32) -> BoxType {
128+ match t {
129+ $( $value => BoxType::$name, )*
130+ _ => BoxType::UnknownBox(t),
131+ }
132+ }
133+ }
134+
135+ impl From<BoxType> for u32 {
136+ fn from(b: BoxType) -> u32 {
137+ match b {
138+ $( BoxType::$name => $value, )*
139+ BoxType::UnknownBox(t) => t,
140+ }
141+ }
142+ }
143+ }
144+}
145+
146+boxtype! {
147+ FtypBox => 0x66747970,
148+ MvhdBox => 0x6d766864,
149+ MfhdBox => 0x6d666864,
150+ FreeBox => 0x66726565,
151+ MdatBox => 0x6d646174,
152+ MoovBox => 0x6d6f6f76,
153+ MvexBox => 0x6d766578,
154+ MehdBox => 0x6d656864,
155+ TrexBox => 0x74726578,
156+ EmsgBox => 0x656d7367,
157+ MoofBox => 0x6d6f6f66,
158+ TkhdBox => 0x746b6864,
159+ TfhdBox => 0x74666864,
160+ TfdtBox => 0x74666474,
161+ EdtsBox => 0x65647473,
162+ MdiaBox => 0x6d646961,
163+ ElstBox => 0x656c7374,
164+ MdhdBox => 0x6d646864,
165+ HdlrBox => 0x68646c72,
166+ MinfBox => 0x6d696e66,
167+ VmhdBox => 0x766d6864,
168+ StblBox => 0x7374626c,
169+ StsdBox => 0x73747364,
170+ SttsBox => 0x73747473,
171+ CttsBox => 0x63747473,
172+ StssBox => 0x73747373,
173+ StscBox => 0x73747363,
174+ StszBox => 0x7374737A,
175+ StcoBox => 0x7374636F,
176+ Co64Box => 0x636F3634,
177+ TrakBox => 0x7472616b,
178+ TrafBox => 0x74726166,
179+ TrunBox => 0x7472756E,
180+ UdtaBox => 0x75647461,
181+ MetaBox => 0x6d657461,
182+ DinfBox => 0x64696e66,
183+ DrefBox => 0x64726566,
184+ UrlBox => 0x75726C20,
185+ SmhdBox => 0x736d6864,
186+ Avc1Box => 0x61766331,
187+ AvcCBox => 0x61766343,
188+ Hev1Box => 0x68657631,
189+ HvcCBox => 0x68766343,
190+ Mp4aBox => 0x6d703461,
191+ EsdsBox => 0x65736473,
192+ WaveBox => 0x77617665,
193+ Tx3gBox => 0x74783367,
194+ VpccBox => 0x76706343,
195+ Vp09Box => 0x76703039,
196+ DataBox => 0x64617461,
197+ IlstBox => 0x696c7374,
198+ NameBox => 0xa96e616d,
199+ DayBox => 0xa9646179,
200+ CovrBox => 0x636f7672,
201+ DescBox => 0x64657363,
202+ WideBox => 0x77696465
203+}
204+
205+pub trait Mp4Box: Sized {
206+ fn box_type(&self) -> BoxType;
207+ fn box_size(&self) -> u64;
208+ fn to_json(&self) -> Result<String>;
209+ fn summary(&self) -> Result<String>;
210+}
211+
212+pub trait ReadBox<T>: Sized {
213+ fn read_box(_: T, size: u64) -> Result<Self>;
214+}
215+
216+pub trait WriteBox<T>: Sized {
217+ fn write_box(&self, _: T) -> Result<u64>;
218+}
219+
220+#[derive(Debug, Clone, Copy)]
221+pub struct BoxHeader {
222+ pub name: BoxType,
223+ pub size: u64,
224+}
225+
226+impl BoxHeader {
227+ pub fn new(name: BoxType, size: u64) -> Self {
228+ Self { name, size }
229+ }
230+
231+ // TODO: if size is 0, then this box is the last one in the file
232+ pub fn read<R: Read>(reader: &mut R) -> Result<Self> {
233+ // Create and read to buf.
234+ let mut buf = [0u8; 8]; // 8 bytes for box header.
235+ reader.read_exact(&mut buf)?;
236+
237+ // Get size.
238+ let s = buf[0..4].try_into().unwrap();
239+ let size = u32::from_be_bytes(s);
240+
241+ // Get box type string.
242+ let t = buf[4..8].try_into().unwrap();
243+ let typ = u32::from_be_bytes(t);
244+
245+ // Get largesize if size is 1
246+ if size == 1 {
247+ reader.read_exact(&mut buf)?;
248+ let largesize = u64::from_be_bytes(buf);
249+
250+ Ok(BoxHeader {
251+ name: BoxType::from(typ),
252+
253+ // Subtract the length of the serialized largesize, as callers assume `size - HEADER_SIZE` is the length
254+ // of the box data. Disallow `largesize < 16`, or else a largesize of 8 will result in a BoxHeader::size
255+ // of 0, incorrectly indicating that the box data extends to the end of the stream.
256+ size: match largesize {
257+ 0 => 0,
258+ 1..=15 => return Err(Error::InvalidData("64-bit box size too small")),
259+ 16..=u64::MAX => largesize - 8,
260+ },
261+ })
262+ } else {
263+ Ok(BoxHeader {
264+ name: BoxType::from(typ),
265+ size: size as u64,
266+ })
267+ }
268+ }
269+
270+ pub fn write<W: Write>(&self, writer: &mut W) -> Result<u64> {
271+ if self.size > u32::MAX as u64 {
272+ writer.write_u32::<BigEndian>(1)?;
273+ writer.write_u32::<BigEndian>(self.name.into())?;
274+ writer.write_u64::<BigEndian>(self.size)?;
275+ Ok(16)
276+ } else {
277+ writer.write_u32::<BigEndian>(self.size as u32)?;
278+ writer.write_u32::<BigEndian>(self.name.into())?;
279+ Ok(8)
280+ }
281+ }
282+}
283+
284+pub fn read_box_header_ext<R: Read>(reader: &mut R) -> Result<(u8, u32)> {
285+ let version = reader.read_u8()?;
286+ let flags = reader.read_u24::<BigEndian>()?;
287+ Ok((version, flags))
288+}
289+
290+pub fn write_box_header_ext<W: Write>(w: &mut W, v: u8, f: u32) -> Result<u64> {
291+ w.write_u8(v)?;
292+ w.write_u24::<BigEndian>(f)?;
293+ Ok(4)
294+}
295+
296+pub fn box_start<R: Seek>(seeker: &mut R) -> Result<u64> {
297+ Ok(seeker.stream_position()? - HEADER_SIZE)
298+}
299+
300+pub fn skip_bytes<S: Seek>(seeker: &mut S, size: u64) -> Result<()> {
301+ seeker.seek(SeekFrom::Current(size as i64))?;
302+ Ok(())
303+}
304+
305+pub fn skip_bytes_to<S: Seek>(seeker: &mut S, pos: u64) -> Result<()> {
306+ seeker.seek(SeekFrom::Start(pos))?;
307+ Ok(())
308+}
309+
310+pub fn skip_box<S: Seek>(seeker: &mut S, size: u64) -> Result<()> {
311+ let start = box_start(seeker)?;
312+ skip_bytes_to(seeker, start + size)?;
313+ Ok(())
314+}
315+
316+pub fn write_zeros<W: Write>(writer: &mut W, size: u64) -> Result<()> {
317+ for _ in 0..size {
318+ writer.write_u8(0)?;
319+ }
320+ Ok(())
321+}
322+
323+mod value_u32 {
324+ use crate::types::FixedPointU16;
325+ use serde::{self, Serializer};
326+
327+ pub fn serialize<S>(fixed: &FixedPointU16, serializer: S) -> Result<S::Ok, S::Error>
328+ where
329+ S: Serializer,
330+ {
331+ serializer.serialize_u16(fixed.value())
332+ }
333+}
334+
335+mod value_i16 {
336+ use crate::types::FixedPointI8;
337+ use serde::{self, Serializer};
338+
339+ pub fn serialize<S>(fixed: &FixedPointI8, serializer: S) -> Result<S::Ok, S::Error>
340+ where
341+ S: Serializer,
342+ {
343+ serializer.serialize_i8(fixed.value())
344+ }
345+}
346+
347+mod value_u8 {
348+ use crate::types::FixedPointU8;
349+ use serde::{self, Serializer};
350+
351+ pub fn serialize<S>(fixed: &FixedPointU8, serializer: S) -> Result<S::Ok, S::Error>
352+ where
353+ S: Serializer,
354+ {
355+ serializer.serialize_u8(fixed.value())
356+ }
357+}
358+
359+#[cfg(test)]
360+mod tests {
361+ use super::*;
362+
363+ #[test]
364+ fn test_fourcc() {
365+ let ftyp_fcc = 0x66747970;
366+ let ftyp_value = FourCC::from(ftyp_fcc);
367+ assert_eq!(&ftyp_value.value[..], b"ftyp");
368+ let ftyp_fcc2: u32 = ftyp_value.into();
369+ assert_eq!(ftyp_fcc, ftyp_fcc2);
370+ }
371+
372+ #[test]
373+ fn test_largesize_too_small() {
374+ let error = BoxHeader::read(&mut &[0, 0, 0, 1, 1, 2, 3, 4, 0, 0, 0, 0, 0, 0, 0, 7][..]);
375+ assert!(matches!(error, Err(Error::InvalidData(_))));
376+ }
377+
378+ #[test]
379+ fn test_zero_largesize() {
380+ let error = BoxHeader::read(&mut &[0, 0, 0, 1, 1, 2, 3, 4, 0, 0, 0, 0, 0, 0, 0, 8][..]);
381+ assert!(matches!(error, Err(Error::InvalidData(_))));
382+ }
383+
384+ #[test]
385+ fn test_nonzero_largesize_too_small() {
386+ let error = BoxHeader::read(&mut &[0, 0, 0, 1, 1, 2, 3, 4, 0, 0, 0, 0, 0, 0, 0, 15][..]);
387+ assert!(matches!(error, Err(Error::InvalidData(_))));
388+ }
389+
390+ #[test]
391+ fn test_valid_largesize() {
392+ let header = BoxHeader::read(&mut &[0, 0, 0, 1, 1, 2, 3, 4, 0, 0, 0, 0, 0, 0, 0, 16][..]);
393+ assert!(matches!(header, Ok(BoxHeader { size: 8, .. })));
394+ }
395+}
vendor/mp4/src/mp4box/moof.rsadded+107 -0
@@ -0,0 +1,107 @@
1+use serde::Serialize;
2+use std::io::{Read, Seek, Write};
3+
4+use crate::mp4box::*;
5+use crate::mp4box::{mfhd::MfhdBox, traf::TrafBox};
6+
7+#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize)]
8+pub struct MoofBox {
9+ pub mfhd: MfhdBox,
10+
11+ #[serde(rename = "traf")]
12+ pub trafs: Vec<TrafBox>,
13+}
14+
15+impl MoofBox {
16+ pub fn get_type(&self) -> BoxType {
17+ BoxType::MoofBox
18+ }
19+
20+ pub fn get_size(&self) -> u64 {
21+ let mut size = HEADER_SIZE + self.mfhd.box_size();
22+ for traf in self.trafs.iter() {
23+ size += traf.box_size();
24+ }
25+ size
26+ }
27+}
28+
29+impl Mp4Box for MoofBox {
30+ fn box_type(&self) -> BoxType {
31+ self.get_type()
32+ }
33+
34+ fn box_size(&self) -> u64 {
35+ self.get_size()
36+ }
37+
38+ fn to_json(&self) -> Result<String> {
39+ Ok(serde_json::to_string(&self).unwrap())
40+ }
41+
42+ fn summary(&self) -> Result<String> {
43+ let s = format!("trafs={}", self.trafs.len());
44+ Ok(s)
45+ }
46+}
47+
48+impl<R: Read + Seek> ReadBox<&mut R> for MoofBox {
49+ fn read_box(reader: &mut R, size: u64) -> Result<Self> {
50+ let start = box_start(reader)?;
51+
52+ let mut mfhd = None;
53+ let mut trafs = Vec::new();
54+
55+ let mut current = reader.stream_position()?;
56+ let end = start + size;
57+ while current < end {
58+ // Get box header.
59+ let header = BoxHeader::read(reader)?;
60+ let BoxHeader { name, size: s } = header;
61+ if s > size {
62+ return Err(Error::InvalidData(
63+ "moof box contains a box with a larger size than it",
64+ ));
65+ }
66+
67+ match name {
68+ BoxType::MfhdBox => {
69+ mfhd = Some(MfhdBox::read_box(reader, s)?);
70+ }
71+ BoxType::TrafBox => {
72+ let traf = TrafBox::read_box(reader, s)?;
73+ trafs.push(traf);
74+ }
75+ _ => {
76+ // XXX warn!()
77+ skip_box(reader, s)?;
78+ }
79+ }
80+ current = reader.stream_position()?;
81+ }
82+
83+ if mfhd.is_none() {
84+ return Err(Error::BoxNotFound(BoxType::MfhdBox));
85+ }
86+
87+ skip_bytes_to(reader, start + size)?;
88+
89+ Ok(MoofBox {
90+ mfhd: mfhd.unwrap(),
91+ trafs,
92+ })
93+ }
94+}
95+
96+impl<W: Write> WriteBox<&mut W> for MoofBox {
97+ fn write_box(&self, writer: &mut W) -> Result<u64> {
98+ let size = self.box_size();
99+ BoxHeader::new(self.box_type(), size).write(writer)?;
100+
101+ self.mfhd.write_box(writer)?;
102+ for traf in self.trafs.iter() {
103+ traf.write_box(writer)?;
104+ }
105+ Ok(0)
106+ }
107+}
vendor/mp4/src/mp4box/moov.rsadded+192 -0
@@ -0,0 +1,192 @@
1+use serde::Serialize;
2+use std::io::{Read, Seek, Write};
3+
4+use crate::meta::MetaBox;
5+use crate::mp4box::*;
6+use crate::mp4box::{mvex::MvexBox, mvhd::MvhdBox, trak::TrakBox, udta::UdtaBox};
7+
8+#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize)]
9+pub struct MoovBox {
10+ pub mvhd: MvhdBox,
11+
12+ #[serde(skip_serializing_if = "Option::is_none")]
13+ pub meta: Option<MetaBox>,
14+
15+ #[serde(skip_serializing_if = "Option::is_none")]
16+ pub mvex: Option<MvexBox>,
17+
18+ #[serde(rename = "trak")]
19+ pub traks: Vec<TrakBox>,
20+
21+ #[serde(skip_serializing_if = "Option::is_none")]
22+ pub udta: Option<UdtaBox>,
23+}
24+
25+impl MoovBox {
26+ pub fn get_type(&self) -> BoxType {
27+ BoxType::MoovBox
28+ }
29+
30+ pub fn get_size(&self) -> u64 {
31+ let mut size = HEADER_SIZE + self.mvhd.box_size();
32+ for trak in self.traks.iter() {
33+ size += trak.box_size();
34+ }
35+ if let Some(meta) = &self.meta {
36+ size += meta.box_size();
37+ }
38+ if let Some(udta) = &self.udta {
39+ size += udta.box_size();
40+ }
41+ size
42+ }
43+}
44+
45+impl Mp4Box for MoovBox {
46+ fn box_type(&self) -> BoxType {
47+ self.get_type()
48+ }
49+
50+ fn box_size(&self) -> u64 {
51+ self.get_size()
52+ }
53+
54+ fn to_json(&self) -> Result<String> {
55+ Ok(serde_json::to_string(&self).unwrap())
56+ }
57+
58+ fn summary(&self) -> Result<String> {
59+ let s = format!("traks={}", self.traks.len());
60+ Ok(s)
61+ }
62+}
63+
64+impl<R: Read + Seek> ReadBox<&mut R> for MoovBox {
65+ fn read_box(reader: &mut R, size: u64) -> Result<Self> {
66+ let start = box_start(reader)?;
67+
68+ let mut mvhd = None;
69+ let mut meta = None;
70+ let mut udta = None;
71+ let mut mvex = None;
72+ let mut traks = Vec::new();
73+
74+ let mut current = reader.stream_position()?;
75+ let end = start + size;
76+ while current < end {
77+ // Get box header.
78+ let header = BoxHeader::read(reader)?;
79+ let BoxHeader { name, size: s } = header;
80+ if s > size {
81+ return Err(Error::InvalidData(
82+ "moov box contains a box with a larger size than it",
83+ ));
84+ }
85+
86+ match name {
87+ BoxType::MvhdBox => {
88+ mvhd = Some(MvhdBox::read_box(reader, s)?);
89+ }
90+ BoxType::MetaBox => {
91+ meta = Some(MetaBox::read_box(reader, s)?);
92+ }
93+ BoxType::MvexBox => {
94+ mvex = Some(MvexBox::read_box(reader, s)?);
95+ }
96+ BoxType::TrakBox => {
97+ let trak = TrakBox::read_box(reader, s)?;
98+ traks.push(trak);
99+ }
100+ BoxType::UdtaBox => {
101+ udta = Some(UdtaBox::read_box(reader, s)?);
102+ }
103+ _ => {
104+ // XXX warn!()
105+ skip_box(reader, s)?;
106+ }
107+ }
108+
109+ current = reader.stream_position()?;
110+ }
111+
112+ if mvhd.is_none() {
113+ return Err(Error::BoxNotFound(BoxType::MvhdBox));
114+ }
115+
116+ skip_bytes_to(reader, start + size)?;
117+
118+ Ok(MoovBox {
119+ mvhd: mvhd.unwrap(),
120+ meta,
121+ udta,
122+ mvex,
123+ traks,
124+ })
125+ }
126+}
127+
128+impl<W: Write> WriteBox<&mut W> for MoovBox {
129+ fn write_box(&self, writer: &mut W) -> Result<u64> {
130+ let size = self.box_size();
131+ BoxHeader::new(self.box_type(), size).write(writer)?;
132+
133+ self.mvhd.write_box(writer)?;
134+ for trak in self.traks.iter() {
135+ trak.write_box(writer)?;
136+ }
137+ if let Some(meta) = &self.meta {
138+ meta.write_box(writer)?;
139+ }
140+ if let Some(udta) = &self.udta {
141+ udta.write_box(writer)?;
142+ }
143+ Ok(0)
144+ }
145+}
146+
147+#[cfg(test)]
148+mod tests {
149+ use super::*;
150+ use crate::mp4box::BoxHeader;
151+ use std::io::Cursor;
152+
153+ #[test]
154+ fn test_moov() {
155+ let src_box = MoovBox {
156+ mvhd: MvhdBox::default(),
157+ mvex: None, // XXX mvex is not written currently
158+ traks: vec![],
159+ meta: Some(MetaBox::default()),
160+ udta: Some(UdtaBox::default()),
161+ };
162+
163+ let mut buf = Vec::new();
164+ src_box.write_box(&mut buf).unwrap();
165+ assert_eq!(buf.len(), src_box.box_size() as usize);
166+
167+ let mut reader = Cursor::new(&buf);
168+ let header = BoxHeader::read(&mut reader).unwrap();
169+ assert_eq!(header.name, BoxType::MoovBox);
170+ assert_eq!(header.size, src_box.box_size());
171+
172+ let dst_box = MoovBox::read_box(&mut reader, header.size).unwrap();
173+ assert_eq!(dst_box, src_box);
174+ }
175+
176+ #[test]
177+ fn test_moov_empty() {
178+ let src_box = MoovBox::default();
179+
180+ let mut buf = Vec::new();
181+ src_box.write_box(&mut buf).unwrap();
182+ assert_eq!(buf.len(), src_box.box_size() as usize);
183+
184+ let mut reader = Cursor::new(&buf);
185+ let header = BoxHeader::read(&mut reader).unwrap();
186+ assert_eq!(header.name, BoxType::MoovBox);
187+ assert_eq!(header.size, src_box.box_size());
188+
189+ let dst_box = MoovBox::read_box(&mut reader, header.size).unwrap();
190+ assert_eq!(dst_box, src_box);
191+ }
192+}
vendor/mp4/src/mp4box/mp4a.rsadded+701 -0
@@ -0,0 +1,701 @@
1+use std::convert::TryFrom;
2+use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
3+use serde::Serialize;
4+use std::io::{Read, Seek, Write};
5+
6+use crate::mp4box::*;
7+
8+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
9+pub struct Mp4aBox {
10+ pub data_reference_index: u16,
11+ pub channelcount: u16,
12+ pub samplesize: u16,
13+
14+ #[serde(with = "value_u32")]
15+ pub samplerate: FixedPointU16,
16+ pub esds: Option<EsdsBox>,
17+}
18+
19+impl Default for Mp4aBox {
20+ fn default() -> Self {
21+ Self {
22+ data_reference_index: 0,
23+ channelcount: 2,
24+ samplesize: 16,
25+ samplerate: FixedPointU16::new(48000),
26+ esds: Some(EsdsBox::default()),
27+ }
28+ }
29+}
30+
31+impl Mp4aBox {
32+ pub fn new(config: &AacConfig) -> Self {
33+ Self {
34+ data_reference_index: 1,
35+ channelcount: config.chan_conf as u16,
36+ samplesize: 16,
37+ samplerate: FixedPointU16::new(config.freq_index.freq() as u16),
38+ esds: Some(EsdsBox::new(config)),
39+ }
40+ }
41+
42+ pub fn get_type(&self) -> BoxType {
43+ BoxType::Mp4aBox
44+ }
45+
46+ pub fn get_size(&self) -> u64 {
47+ let mut size = HEADER_SIZE + 8 + 20;
48+ if let Some(ref esds) = self.esds {
49+ size += esds.box_size();
50+ }
51+ size
52+ }
53+}
54+
55+impl Mp4Box for Mp4aBox {
56+ fn box_type(&self) -> BoxType {
57+ self.get_type()
58+ }
59+
60+ fn box_size(&self) -> u64 {
61+ self.get_size()
62+ }
63+
64+ fn to_json(&self) -> Result<String> {
65+ Ok(serde_json::to_string(&self).unwrap())
66+ }
67+
68+ fn summary(&self) -> Result<String> {
69+ let s = format!(
70+ "channel_count={} sample_size={} sample_rate={}",
71+ self.channelcount,
72+ self.samplesize,
73+ self.samplerate.value()
74+ );
75+ Ok(s)
76+ }
77+}
78+
79+impl<R: Read + Seek> ReadBox<&mut R> for Mp4aBox {
80+ fn read_box(reader: &mut R, size: u64) -> Result<Self> {
81+ let start = box_start(reader)?;
82+
83+ reader.read_u32::<BigEndian>()?; // reserved
84+ reader.read_u16::<BigEndian>()?; // reserved
85+ let data_reference_index = reader.read_u16::<BigEndian>()?;
86+
87+ // ISO 14496-12 calls the next 8 bytes reserved; QuickTime (which is
88+ // what a `qt ` brand from Resolve, Final Cut, ffmpeg `-f mov` writes)
89+ // reads them as version(2) revision(2) vendor(4). Version 1 appends a
90+ // 16-byte compression block after samplerate; version 2 replaces
91+ // channelcount/samplesize/samplerate with a 36-byte block of its own.
92+ // Both then wrap the `esds` in a `wave` atom, which the stock parser
93+ // walked straight past, reporting an AAC track with no `esds`.
94+ let version = reader.read_u16::<BigEndian>()?;
95+ reader.read_u16::<BigEndian>()?; // revision
96+ reader.read_u32::<BigEndian>()?; // vendor
97+ let mut channelcount = reader.read_u16::<BigEndian>()?;
98+ let samplesize = reader.read_u16::<BigEndian>()?;
99+ reader.read_u32::<BigEndian>()?; // compression_id + packet_size
100+ let mut samplerate = FixedPointU16::new_raw(reader.read_u32::<BigEndian>()?);
101+ match version {
102+ 1 => skip_bytes(reader, 16)?,
103+ 2 => {
104+ reader.read_u32::<BigEndian>()?; // sizeOfStructOnly
105+ let rate = f64::from_bits(reader.read_u64::<BigEndian>()?);
106+ let channels = reader.read_u32::<BigEndian>()?;
107+ skip_bytes(reader, 20)?; // always7F000000 .. constLPCMFramesPerAudioPacket
108+ if (1.0..=f64::from(u16::MAX)).contains(&rate) {
109+ samplerate = FixedPointU16::new(rate as u16);
110+ }
111+ if let Ok(c) = u16::try_from(channels) {
112+ channelcount = c;
113+ }
114+ }
115+ _ => {}
116+ }
117+
118+ let esds = read_esds(reader, start + size)?;
119+
120+ Ok(Mp4aBox {
121+ data_reference_index,
122+ channelcount,
123+ samplesize,
124+ samplerate,
125+ esds,
126+ })
127+ }
128+}
129+
130+/// The first `esds` among the child boxes up to `end`, looking inside a
131+/// QuickTime `wave` wrapper when one is met. Leaves the reader at `end`.
132+fn read_esds<R: Read + Seek>(reader: &mut R, end: u64) -> Result<Option<EsdsBox>> {
133+ let mut esds = None;
134+ while reader.stream_position()? + HEADER_SIZE <= end {
135+ let header = BoxHeader::read(reader)?;
136+ let BoxHeader { name, size: s } = header;
137+ let here = box_start(reader)?;
138+ if s == 0 || here + s > end {
139+ // A `wave` atom ends with an 8-byte terminator whose size is 0;
140+ // anything else claiming to run past its parent is malformed.
141+ break;
142+ }
143+ if esds.is_none() {
144+ if name == BoxType::EsdsBox {
145+ esds = Some(EsdsBox::read_box(reader, s)?);
146+ } else if name == BoxType::WaveBox {
147+ esds = read_esds(reader, here + s)?;
148+ }
149+ }
150+ skip_bytes_to(reader, here + s)?;
151+ }
152+ skip_bytes_to(reader, end)?;
153+ Ok(esds)
154+}
155+
156+impl<W: Write> WriteBox<&mut W> for Mp4aBox {
157+ fn write_box(&self, writer: &mut W) -> Result<u64> {
158+ let size = self.box_size();
159+ BoxHeader::new(self.box_type(), size).write(writer)?;
160+
161+ writer.write_u32::<BigEndian>(0)?; // reserved
162+ writer.write_u16::<BigEndian>(0)?; // reserved
163+ writer.write_u16::<BigEndian>(self.data_reference_index)?;
164+
165+ writer.write_u64::<BigEndian>(0)?; // reserved
166+ writer.write_u16::<BigEndian>(self.channelcount)?;
167+ writer.write_u16::<BigEndian>(self.samplesize)?;
168+ writer.write_u32::<BigEndian>(0)?; // reserved
169+ writer.write_u32::<BigEndian>(self.samplerate.raw_value())?;
170+
171+ if let Some(ref esds) = self.esds {
172+ esds.write_box(writer)?;
173+ }
174+
175+ Ok(size)
176+ }
177+}
178+
179+#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize)]
180+pub struct EsdsBox {
181+ pub version: u8,
182+ pub flags: u32,
183+ pub es_desc: ESDescriptor,
184+}
185+
186+impl EsdsBox {
187+ pub fn new(config: &AacConfig) -> Self {
188+ Self {
189+ version: 0,
190+ flags: 0,
191+ es_desc: ESDescriptor::new(config),
192+ }
193+ }
194+}
195+
196+impl Mp4Box for EsdsBox {
197+ fn box_type(&self) -> BoxType {
198+ BoxType::EsdsBox
199+ }
200+
201+ fn box_size(&self) -> u64 {
202+ HEADER_SIZE
203+ + HEADER_EXT_SIZE
204+ + 1
205+ + size_of_length(ESDescriptor::desc_size()) as u64
206+ + ESDescriptor::desc_size() as u64
207+ }
208+
209+ fn to_json(&self) -> Result<String> {
210+ Ok(serde_json::to_string(&self).unwrap())
211+ }
212+
213+ fn summary(&self) -> Result<String> {
214+ Ok(String::new())
215+ }
216+}
217+
218+impl<R: Read + Seek> ReadBox<&mut R> for EsdsBox {
219+ fn read_box(reader: &mut R, size: u64) -> Result<Self> {
220+ let start = box_start(reader)?;
221+
222+ let (version, flags) = read_box_header_ext(reader)?;
223+
224+ let mut es_desc = None;
225+
226+ let mut current = reader.stream_position()?;
227+ let end = start + size;
228+ while current < end {
229+ let (desc_tag, desc_size) = read_desc(reader)?;
230+ match desc_tag {
231+ 0x03 => {
232+ es_desc = Some(ESDescriptor::read_desc(reader, desc_size)?);
233+ }
234+ _ => break,
235+ }
236+ current = reader.stream_position()?;
237+ }
238+
239+ if es_desc.is_none() {
240+ return Err(Error::InvalidData("ESDescriptor not found"));
241+ }
242+
243+ skip_bytes_to(reader, start + size)?;
244+
245+ Ok(EsdsBox {
246+ version,
247+ flags,
248+ es_desc: es_desc.unwrap(),
249+ })
250+ }
251+}
252+
253+impl<W: Write> WriteBox<&mut W> for EsdsBox {
254+ fn write_box(&self, writer: &mut W) -> Result<u64> {
255+ let size = self.box_size();
256+ BoxHeader::new(self.box_type(), size).write(writer)?;
257+
258+ write_box_header_ext(writer, self.version, self.flags)?;
259+
260+ self.es_desc.write_desc(writer)?;
261+
262+ Ok(size)
263+ }
264+}
265+
266+trait Descriptor: Sized {
267+ fn desc_tag() -> u8;
268+ fn desc_size() -> u32;
269+}
270+
271+trait ReadDesc<T>: Sized {
272+ fn read_desc(_: T, size: u32) -> Result<Self>;
273+}
274+
275+trait WriteDesc<T>: Sized {
276+ fn write_desc(&self, _: T) -> Result<u32>;
277+}
278+
279+fn read_desc<R: Read>(reader: &mut R) -> Result<(u8, u32)> {
280+ let tag = reader.read_u8()?;
281+
282+ let mut size: u32 = 0;
283+ for _ in 0..4 {
284+ let b = reader.read_u8()?;
285+ size = (size << 7) | (b & 0x7F) as u32;
286+ if b & 0x80 == 0 {
287+ break;
288+ }
289+ }
290+
291+ Ok((tag, size))
292+}
293+
294+fn size_of_length(size: u32) -> u32 {
295+ match size {
296+ 0x0..=0x7F => 1,
297+ 0x80..=0x3FFF => 2,
298+ 0x4000..=0x1FFFFF => 3,
299+ _ => 4,
300+ }
301+}
302+
303+fn write_desc<W: Write>(writer: &mut W, tag: u8, size: u32) -> Result<u64> {
304+ writer.write_u8(tag)?;
305+
306+ if size as u64 > std::u32::MAX as u64 {
307+ return Err(Error::InvalidData("invalid descriptor length range"));
308+ }
309+
310+ let nbytes = size_of_length(size);
311+
312+ for i in 0..nbytes {
313+ let mut b = (size >> ((nbytes - i - 1) * 7)) as u8 & 0x7F;
314+ if i < nbytes - 1 {
315+ b |= 0x80;
316+ }
317+ writer.write_u8(b)?;
318+ }
319+
320+ Ok(1 + nbytes as u64)
321+}
322+
323+#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize)]
324+pub struct ESDescriptor {
325+ pub es_id: u16,
326+
327+ pub dec_config: DecoderConfigDescriptor,
328+ pub sl_config: SLConfigDescriptor,
329+}
330+
331+impl ESDescriptor {
332+ pub fn new(config: &AacConfig) -> Self {
333+ Self {
334+ es_id: 1,
335+ dec_config: DecoderConfigDescriptor::new(config),
336+ sl_config: SLConfigDescriptor::new(),
337+ }
338+ }
339+}
340+
341+impl Descriptor for ESDescriptor {
342+ fn desc_tag() -> u8 {
343+ 0x03
344+ }
345+
346+ fn desc_size() -> u32 {
347+ 3 + 1
348+ + size_of_length(DecoderConfigDescriptor::desc_size())
349+ + DecoderConfigDescriptor::desc_size()
350+ + 1
351+ + size_of_length(SLConfigDescriptor::desc_size())
352+ + SLConfigDescriptor::desc_size()
353+ }
354+}
355+
356+impl<R: Read + Seek> ReadDesc<&mut R> for ESDescriptor {
357+ fn read_desc(reader: &mut R, size: u32) -> Result<Self> {
358+ let start = reader.stream_position()?;
359+
360+ let es_id = reader.read_u16::<BigEndian>()?;
361+ reader.read_u8()?; // XXX flags must be 0
362+
363+ let mut dec_config = None;
364+ let mut sl_config = None;
365+
366+ let mut current = reader.stream_position()?;
367+ let end = start + size as u64;
368+ while current < end {
369+ let (desc_tag, desc_size) = read_desc(reader)?;
370+ match desc_tag {
371+ 0x04 => {
372+ dec_config = Some(DecoderConfigDescriptor::read_desc(reader, desc_size)?);
373+ }
374+ 0x06 => {
375+ sl_config = Some(SLConfigDescriptor::read_desc(reader, desc_size)?);
376+ }
377+ _ => {
378+ skip_bytes(reader, desc_size as u64)?;
379+ }
380+ }
381+ current = reader.stream_position()?;
382+ }
383+
384+ Ok(ESDescriptor {
385+ es_id,
386+ dec_config: dec_config.unwrap_or_default(),
387+ sl_config: sl_config.unwrap_or_default(),
388+ })
389+ }
390+}
391+
392+impl<W: Write> WriteDesc<&mut W> for ESDescriptor {
393+ fn write_desc(&self, writer: &mut W) -> Result<u32> {
394+ let size = Self::desc_size();
395+ write_desc(writer, Self::desc_tag(), size)?;
396+
397+ writer.write_u16::<BigEndian>(self.es_id)?;
398+ writer.write_u8(0)?;
399+
400+ self.dec_config.write_desc(writer)?;
401+ self.sl_config.write_desc(writer)?;
402+
403+ Ok(size)
404+ }
405+}
406+
407+#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize)]
408+pub struct DecoderConfigDescriptor {
409+ pub object_type_indication: u8,
410+ pub stream_type: u8,
411+ pub up_stream: u8,
412+ pub buffer_size_db: u32,
413+ pub max_bitrate: u32,
414+ pub avg_bitrate: u32,
415+
416+ pub dec_specific: DecoderSpecificDescriptor,
417+}
418+
419+impl DecoderConfigDescriptor {
420+ pub fn new(config: &AacConfig) -> Self {
421+ Self {
422+ object_type_indication: 0x40, // XXX AAC
423+ stream_type: 0x05, // XXX Audio
424+ up_stream: 0,
425+ buffer_size_db: 0,
426+ max_bitrate: config.bitrate, // XXX
427+ avg_bitrate: config.bitrate,
428+ dec_specific: DecoderSpecificDescriptor::new(config),
429+ }
430+ }
431+}
432+
433+impl Descriptor for DecoderConfigDescriptor {
434+ fn desc_tag() -> u8 {
435+ 0x04
436+ }
437+
438+ fn desc_size() -> u32 {
439+ 13 + 1
440+ + size_of_length(DecoderSpecificDescriptor::desc_size())
441+ + DecoderSpecificDescriptor::desc_size()
442+ }
443+}
444+
445+impl<R: Read + Seek> ReadDesc<&mut R> for DecoderConfigDescriptor {
446+ fn read_desc(reader: &mut R, size: u32) -> Result<Self> {
447+ let start = reader.stream_position()?;
448+
449+ let object_type_indication = reader.read_u8()?;
450+ let byte_a = reader.read_u8()?;
451+ let stream_type = (byte_a & 0xFC) >> 2;
452+ let up_stream = byte_a & 0x02;
453+ let buffer_size_db = reader.read_u24::<BigEndian>()?;
454+ let max_bitrate = reader.read_u32::<BigEndian>()?;
455+ let avg_bitrate = reader.read_u32::<BigEndian>()?;
456+
457+ let mut dec_specific = None;
458+
459+ let mut current = reader.stream_position()?;
460+ let end = start + size as u64;
461+ while current < end {
462+ let (desc_tag, desc_size) = read_desc(reader)?;
463+ match desc_tag {
464+ 0x05 => {
465+ dec_specific = Some(DecoderSpecificDescriptor::read_desc(reader, desc_size)?);
466+ }
467+ _ => {
468+ skip_bytes(reader, desc_size as u64)?;
469+ }
470+ }
471+ current = reader.stream_position()?;
472+ }
473+
474+ Ok(DecoderConfigDescriptor {
475+ object_type_indication,
476+ stream_type,
477+ up_stream,
478+ buffer_size_db,
479+ max_bitrate,
480+ avg_bitrate,
481+ dec_specific: dec_specific.unwrap_or_default(),
482+ })
483+ }
484+}
485+
486+impl<W: Write> WriteDesc<&mut W> for DecoderConfigDescriptor {
487+ fn write_desc(&self, writer: &mut W) -> Result<u32> {
488+ let size = Self::desc_size();
489+ write_desc(writer, Self::desc_tag(), size)?;
490+
491+ writer.write_u8(self.object_type_indication)?;
492+ writer.write_u8((self.stream_type << 2) + (self.up_stream & 0x02) + 1)?; // 1 reserved
493+ writer.write_u24::<BigEndian>(self.buffer_size_db)?;
494+ writer.write_u32::<BigEndian>(self.max_bitrate)?;
495+ writer.write_u32::<BigEndian>(self.avg_bitrate)?;
496+
497+ self.dec_specific.write_desc(writer)?;
498+
499+ Ok(size)
500+ }
501+}
502+
503+#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize)]
504+pub struct DecoderSpecificDescriptor {
505+ pub profile: u8,
506+ pub freq_index: u8,
507+ pub chan_conf: u8,
508+}
509+
510+impl DecoderSpecificDescriptor {
511+ pub fn new(config: &AacConfig) -> Self {
512+ Self {
513+ profile: config.profile as u8,
514+ freq_index: config.freq_index as u8,
515+ chan_conf: config.chan_conf as u8,
516+ }
517+ }
518+}
519+
520+impl Descriptor for DecoderSpecificDescriptor {
521+ fn desc_tag() -> u8 {
522+ 0x05
523+ }
524+
525+ fn desc_size() -> u32 {
526+ 2
527+ }
528+}
529+
530+fn get_audio_object_type(byte_a: u8, byte_b: u8) -> u8 {
531+ let mut profile = byte_a >> 3;
532+ if profile == 31 {
533+ profile = 32 + ((byte_a & 7) | (byte_b >> 5));
534+ }
535+
536+ profile
537+}
538+
539+fn get_chan_conf<R: Read + Seek>(
540+ reader: &mut R,
541+ byte_b: u8,
542+ freq_index: u8,
543+ extended_profile: bool,
544+) -> Result<u8> {
545+ let chan_conf;
546+ if freq_index == 15 {
547+ // Skip the 24 bit sample rate
548+ let sample_rate = reader.read_u24::<BigEndian>()?;
549+ chan_conf = ((sample_rate >> 4) & 0x0F) as u8;
550+ } else if extended_profile {
551+ let byte_c = reader.read_u8()?;
552+ chan_conf = (byte_b & 1) | (byte_c & 0xE0);
553+ } else {
554+ chan_conf = (byte_b >> 3) & 0x0F;
555+ }
556+
557+ Ok(chan_conf)
558+}
559+
560+impl<R: Read + Seek> ReadDesc<&mut R> for DecoderSpecificDescriptor {
561+ fn read_desc(reader: &mut R, _size: u32) -> Result<Self> {
562+ let byte_a = reader.read_u8()?;
563+ let byte_b = reader.read_u8()?;
564+ let profile = get_audio_object_type(byte_a, byte_b);
565+ let freq_index;
566+ let chan_conf;
567+ if profile > 31 {
568+ freq_index = (byte_b >> 1) & 0x0F;
569+ chan_conf = get_chan_conf(reader, byte_b, freq_index, true)?;
570+ } else {
571+ freq_index = ((byte_a & 0x07) << 1) + (byte_b >> 7);
572+ chan_conf = get_chan_conf(reader, byte_b, freq_index, false)?;
573+ }
574+
575+ Ok(DecoderSpecificDescriptor {
576+ profile,
577+ freq_index,
578+ chan_conf,
579+ })
580+ }
581+}
582+
583+impl<W: Write> WriteDesc<&mut W> for DecoderSpecificDescriptor {
584+ fn write_desc(&self, writer: &mut W) -> Result<u32> {
585+ let size = Self::desc_size();
586+ write_desc(writer, Self::desc_tag(), size)?;
587+
588+ writer.write_u8((self.profile << 3) + (self.freq_index >> 1))?;
589+ writer.write_u8((self.freq_index << 7) + (self.chan_conf << 3))?;
590+
591+ Ok(size)
592+ }
593+}
594+
595+#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize)]
596+pub struct SLConfigDescriptor {}
597+
598+impl SLConfigDescriptor {
599+ pub fn new() -> Self {
600+ SLConfigDescriptor {}
601+ }
602+}
603+
604+impl Descriptor for SLConfigDescriptor {
605+ fn desc_tag() -> u8 {
606+ 0x06
607+ }
608+
609+ fn desc_size() -> u32 {
610+ 1
611+ }
612+}
613+
614+impl<R: Read + Seek> ReadDesc<&mut R> for SLConfigDescriptor {
615+ fn read_desc(reader: &mut R, _size: u32) -> Result<Self> {
616+ reader.read_u8()?; // pre-defined
617+
618+ Ok(SLConfigDescriptor {})
619+ }
620+}
621+
622+impl<W: Write> WriteDesc<&mut W> for SLConfigDescriptor {
623+ fn write_desc(&self, writer: &mut W) -> Result<u32> {
624+ let size = Self::desc_size();
625+ write_desc(writer, Self::desc_tag(), size - 1)?;
626+
627+ writer.write_u8(0)?; // pre-defined
628+ Ok(size)
629+ }
630+}
631+
632+#[cfg(test)]
633+mod tests {
634+ use super::*;
635+ use crate::mp4box::BoxHeader;
636+ use std::io::Cursor;
637+
638+ #[test]
639+ fn test_mp4a() {
640+ let src_box = Mp4aBox {
641+ data_reference_index: 1,
642+ channelcount: 2,
643+ samplesize: 16,
644+ samplerate: FixedPointU16::new(48000),
645+ esds: Some(EsdsBox {
646+ version: 0,
647+ flags: 0,
648+ es_desc: ESDescriptor {
649+ es_id: 2,
650+ dec_config: DecoderConfigDescriptor {
651+ object_type_indication: 0x40,
652+ stream_type: 0x05,
653+ up_stream: 0,
654+ buffer_size_db: 0,
655+ max_bitrate: 67695,
656+ avg_bitrate: 67695,
657+ dec_specific: DecoderSpecificDescriptor {
658+ profile: 2,
659+ freq_index: 3,
660+ chan_conf: 1,
661+ },
662+ },
663+ sl_config: SLConfigDescriptor::default(),
664+ },
665+ }),
666+ };
667+ let mut buf = Vec::new();
668+ src_box.write_box(&mut buf).unwrap();
669+ assert_eq!(buf.len(), src_box.box_size() as usize);
670+
671+ let mut reader = Cursor::new(&buf);
672+ let header = BoxHeader::read(&mut reader).unwrap();
673+ assert_eq!(header.name, BoxType::Mp4aBox);
674+ assert_eq!(src_box.box_size(), header.size);
675+
676+ let dst_box = Mp4aBox::read_box(&mut reader, header.size).unwrap();
677+ assert_eq!(src_box, dst_box);
678+ }
679+
680+ #[test]
681+ fn test_mp4a_no_esds() {
682+ let src_box = Mp4aBox {
683+ data_reference_index: 1,
684+ channelcount: 2,
685+ samplesize: 16,
686+ samplerate: FixedPointU16::new(48000),
687+ esds: None,
688+ };
689+ let mut buf = Vec::new();
690+ src_box.write_box(&mut buf).unwrap();
691+ assert_eq!(buf.len(), src_box.box_size() as usize);
692+
693+ let mut reader = Cursor::new(&buf);
694+ let header = BoxHeader::read(&mut reader).unwrap();
695+ assert_eq!(header.name, BoxType::Mp4aBox);
696+ assert_eq!(src_box.box_size(), header.size);
697+
698+ let dst_box = Mp4aBox::read_box(&mut reader, header.size).unwrap();
699+ assert_eq!(src_box, dst_box);
700+ }
701+}
vendor/mp4/src/mp4box/mvex.rsadded+102 -0
@@ -0,0 +1,102 @@
1+use serde::Serialize;
2+use std::io::{Read, Seek, Write};
3+
4+use crate::mp4box::*;
5+use crate::mp4box::{mehd::MehdBox, trex::TrexBox};
6+
7+#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize)]
8+pub struct MvexBox {
9+ pub mehd: Option<MehdBox>,
10+ pub trex: TrexBox,
11+}
12+
13+impl MvexBox {
14+ pub fn get_type(&self) -> BoxType {
15+ BoxType::MdiaBox
16+ }
17+
18+ pub fn get_size(&self) -> u64 {
19+ HEADER_SIZE + self.mehd.as_ref().map(|x| x.box_size()).unwrap_or(0) + self.trex.box_size()
20+ }
21+}
22+
23+impl Mp4Box for MvexBox {
24+ fn box_type(&self) -> BoxType {
25+ self.get_type()
26+ }
27+
28+ fn box_size(&self) -> u64 {
29+ self.get_size()
30+ }
31+
32+ fn to_json(&self) -> Result<String> {
33+ Ok(serde_json::to_string(&self).unwrap())
34+ }
35+
36+ fn summary(&self) -> Result<String> {
37+ let s = String::new();
38+ Ok(s)
39+ }
40+}
41+
42+impl<R: Read + Seek> ReadBox<&mut R> for MvexBox {
43+ fn read_box(reader: &mut R, size: u64) -> Result<Self> {
44+ let start = box_start(reader)?;
45+
46+ let mut mehd = None;
47+ let mut trex = None;
48+
49+ let mut current = reader.stream_position()?;
50+ let end = start + size;
51+ while current < end {
52+ // Get box header.
53+ let header = BoxHeader::read(reader)?;
54+ let BoxHeader { name, size: s } = header;
55+ if s > size {
56+ return Err(Error::InvalidData(
57+ "mvex box contains a box with a larger size than it",
58+ ));
59+ }
60+
61+ match name {
62+ BoxType::MehdBox => {
63+ mehd = Some(MehdBox::read_box(reader, s)?);
64+ }
65+ BoxType::TrexBox => {
66+ trex = Some(TrexBox::read_box(reader, s)?);
67+ }
68+ _ => {
69+ // XXX warn!()
70+ skip_box(reader, s)?;
71+ }
72+ }
73+
74+ current = reader.stream_position()?;
75+ }
76+
77+ if trex.is_none() {
78+ return Err(Error::BoxNotFound(BoxType::TrexBox));
79+ }
80+
81+ skip_bytes_to(reader, start + size)?;
82+
83+ Ok(MvexBox {
84+ mehd,
85+ trex: trex.unwrap(),
86+ })
87+ }
88+}
89+
90+impl<W: Write> WriteBox<&mut W> for MvexBox {
91+ fn write_box(&self, writer: &mut W) -> Result<u64> {
92+ let size = self.box_size();
93+ BoxHeader::new(self.box_type(), size).write(writer)?;
94+
95+ if let Some(mehd) = &self.mehd {
96+ mehd.write_box(writer)?;
97+ }
98+ self.trex.write_box(writer)?;
99+
100+ Ok(size)
101+ }
102+}
vendor/mp4/src/mp4box/mvhd.rsadded+257 -0
@@ -0,0 +1,257 @@
1+use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
2+use serde::Serialize;
3+use std::io::{Read, Seek, Write};
4+
5+use crate::mp4box::*;
6+
7+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
8+pub struct MvhdBox {
9+ pub version: u8,
10+ pub flags: u32,
11+ pub creation_time: u64,
12+ pub modification_time: u64,
13+ pub timescale: u32,
14+ pub duration: u64,
15+
16+ #[serde(with = "value_u32")]
17+ pub rate: FixedPointU16,
18+ #[serde(with = "value_u8")]
19+ pub volume: FixedPointU8,
20+
21+ pub matrix: tkhd::Matrix,
22+
23+ pub next_track_id: u32,
24+}
25+
26+impl MvhdBox {
27+ pub fn get_type(&self) -> BoxType {
28+ BoxType::MvhdBox
29+ }
30+
31+ pub fn get_size(&self) -> u64 {
32+ let mut size = HEADER_SIZE + HEADER_EXT_SIZE;
33+ if self.version == 1 {
34+ size += 28;
35+ } else if self.version == 0 {
36+ size += 16;
37+ }
38+ size += 80;
39+ size
40+ }
41+}
42+
43+impl Default for MvhdBox {
44+ fn default() -> Self {
45+ MvhdBox {
46+ version: 0,
47+ flags: 0,
48+ creation_time: 0,
49+ modification_time: 0,
50+ timescale: 1000,
51+ duration: 0,
52+ rate: FixedPointU16::new(1),
53+ matrix: tkhd::Matrix::default(),
54+ volume: FixedPointU8::new(1),
55+ next_track_id: 1,
56+ }
57+ }
58+}
59+
60+impl Mp4Box for MvhdBox {
61+ fn box_type(&self) -> BoxType {
62+ self.get_type()
63+ }
64+
65+ fn box_size(&self) -> u64 {
66+ self.get_size()
67+ }
68+
69+ fn to_json(&self) -> Result<String> {
70+ Ok(serde_json::to_string(&self).unwrap())
71+ }
72+
73+ fn summary(&self) -> Result<String> {
74+ let s = format!(
75+ "creation_time={} timescale={} duration={} rate={} volume={}, matrix={}, next_track_id={}",
76+ self.creation_time,
77+ self.timescale,
78+ self.duration,
79+ self.rate.value(),
80+ self.volume.value(),
81+ self.matrix,
82+ self.next_track_id
83+ );
84+ Ok(s)
85+ }
86+}
87+
88+impl<R: Read + Seek> ReadBox<&mut R> for MvhdBox {
89+ fn read_box(reader: &mut R, size: u64) -> Result<Self> {
90+ let start = box_start(reader)?;
91+
92+ let (version, flags) = read_box_header_ext(reader)?;
93+
94+ let (creation_time, modification_time, timescale, duration) = if version == 1 {
95+ (
96+ reader.read_u64::<BigEndian>()?,
97+ reader.read_u64::<BigEndian>()?,
98+ reader.read_u32::<BigEndian>()?,
99+ reader.read_u64::<BigEndian>()?,
100+ )
101+ } else if version == 0 {
102+ (
103+ reader.read_u32::<BigEndian>()? as u64,
104+ reader.read_u32::<BigEndian>()? as u64,
105+ reader.read_u32::<BigEndian>()?,
106+ reader.read_u32::<BigEndian>()? as u64,
107+ )
108+ } else {
109+ return Err(Error::InvalidData("version must be 0 or 1"));
110+ };
111+ let rate = FixedPointU16::new_raw(reader.read_u32::<BigEndian>()?);
112+
113+ let volume = FixedPointU8::new_raw(reader.read_u16::<BigEndian>()?);
114+
115+ reader.read_u16::<BigEndian>()?; // reserved = 0
116+
117+ reader.read_u64::<BigEndian>()?; // reserved = 0
118+
119+ let matrix = tkhd::Matrix {
120+ a: reader.read_i32::<BigEndian>()?,
121+ b: reader.read_i32::<BigEndian>()?,
122+ u: reader.read_i32::<BigEndian>()?,
123+ c: reader.read_i32::<BigEndian>()?,
124+ d: reader.read_i32::<BigEndian>()?,
125+ v: reader.read_i32::<BigEndian>()?,
126+ x: reader.read_i32::<BigEndian>()?,
127+ y: reader.read_i32::<BigEndian>()?,
128+ w: reader.read_i32::<BigEndian>()?,
129+ };
130+
131+ skip_bytes(reader, 24)?; // pre_defined = 0
132+
133+ let next_track_id = reader.read_u32::<BigEndian>()?;
134+
135+ skip_bytes_to(reader, start + size)?;
136+
137+ Ok(MvhdBox {
138+ version,
139+ flags,
140+ creation_time,
141+ modification_time,
142+ timescale,
143+ duration,
144+ rate,
145+ volume,
146+ matrix,
147+ next_track_id,
148+ })
149+ }
150+}
151+
152+impl<W: Write> WriteBox<&mut W> for MvhdBox {
153+ fn write_box(&self, writer: &mut W) -> Result<u64> {
154+ let size = self.box_size();
155+ BoxHeader::new(self.box_type(), size).write(writer)?;
156+
157+ write_box_header_ext(writer, self.version, self.flags)?;
158+
159+ if self.version == 1 {
160+ writer.write_u64::<BigEndian>(self.creation_time)?;
161+ writer.write_u64::<BigEndian>(self.modification_time)?;
162+ writer.write_u32::<BigEndian>(self.timescale)?;
163+ writer.write_u64::<BigEndian>(self.duration)?;
164+ } else if self.version == 0 {
165+ writer.write_u32::<BigEndian>(self.creation_time as u32)?;
166+ writer.write_u32::<BigEndian>(self.modification_time as u32)?;
167+ writer.write_u32::<BigEndian>(self.timescale)?;
168+ writer.write_u32::<BigEndian>(self.duration as u32)?;
169+ } else {
170+ return Err(Error::InvalidData("version must be 0 or 1"));
171+ }
172+ writer.write_u32::<BigEndian>(self.rate.raw_value())?;
173+
174+ writer.write_u16::<BigEndian>(self.volume.raw_value())?;
175+
176+ writer.write_u16::<BigEndian>(0)?; // reserved = 0
177+
178+ writer.write_u64::<BigEndian>(0)?; // reserved = 0
179+
180+ writer.write_i32::<BigEndian>(self.matrix.a)?;
181+ writer.write_i32::<BigEndian>(self.matrix.b)?;
182+ writer.write_i32::<BigEndian>(self.matrix.u)?;
183+ writer.write_i32::<BigEndian>(self.matrix.c)?;
184+ writer.write_i32::<BigEndian>(self.matrix.d)?;
185+ writer.write_i32::<BigEndian>(self.matrix.v)?;
186+ writer.write_i32::<BigEndian>(self.matrix.x)?;
187+ writer.write_i32::<BigEndian>(self.matrix.y)?;
188+ writer.write_i32::<BigEndian>(self.matrix.w)?;
189+
190+ write_zeros(writer, 24)?; // pre_defined = 0
191+
192+ writer.write_u32::<BigEndian>(self.next_track_id)?;
193+
194+ Ok(size)
195+ }
196+}
197+
198+#[cfg(test)]
199+mod tests {
200+ use super::*;
201+ use crate::mp4box::BoxHeader;
202+ use std::io::Cursor;
203+
204+ #[test]
205+ fn test_mvhd32() {
206+ let src_box = MvhdBox {
207+ version: 0,
208+ flags: 0,
209+ creation_time: 100,
210+ modification_time: 200,
211+ timescale: 1000,
212+ duration: 634634,
213+ rate: FixedPointU16::new(1),
214+ volume: FixedPointU8::new(1),
215+ matrix: tkhd::Matrix::default(),
216+ next_track_id: 1,
217+ };
218+ let mut buf = Vec::new();
219+ src_box.write_box(&mut buf).unwrap();
220+ assert_eq!(buf.len(), src_box.box_size() as usize);
221+
222+ let mut reader = Cursor::new(&buf);
223+ let header = BoxHeader::read(&mut reader).unwrap();
224+ assert_eq!(header.name, BoxType::MvhdBox);
225+ assert_eq!(src_box.box_size(), header.size);
226+
227+ let dst_box = MvhdBox::read_box(&mut reader, header.size).unwrap();
228+ assert_eq!(src_box, dst_box);
229+ }
230+
231+ #[test]
232+ fn test_mvhd64() {
233+ let src_box = MvhdBox {
234+ version: 1,
235+ flags: 0,
236+ creation_time: 100,
237+ modification_time: 200,
238+ timescale: 1000,
239+ duration: 634634,
240+ rate: FixedPointU16::new(1),
241+ volume: FixedPointU8::new(1),
242+ matrix: tkhd::Matrix::default(),
243+ next_track_id: 1,
244+ };
245+ let mut buf = Vec::new();
246+ src_box.write_box(&mut buf).unwrap();
247+ assert_eq!(buf.len(), src_box.box_size() as usize);
248+
249+ let mut reader = Cursor::new(&buf);
250+ let header = BoxHeader::read(&mut reader).unwrap();
251+ assert_eq!(header.name, BoxType::MvhdBox);
252+ assert_eq!(src_box.box_size(), header.size);
253+
254+ let dst_box = MvhdBox::read_box(&mut reader, header.size).unwrap();
255+ assert_eq!(src_box, dst_box);
256+ }
257+}
vendor/mp4/src/mp4box/smhd.rsadded+112 -0
@@ -0,0 +1,112 @@
1+use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
2+use serde::Serialize;
3+use std::io::{Read, Seek, Write};
4+
5+use crate::mp4box::*;
6+
7+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
8+pub struct SmhdBox {
9+ pub version: u8,
10+ pub flags: u32,
11+
12+ #[serde(with = "value_i16")]
13+ pub balance: FixedPointI8,
14+}
15+
16+impl SmhdBox {
17+ pub fn get_type(&self) -> BoxType {
18+ BoxType::SmhdBox
19+ }
20+
21+ pub fn get_size(&self) -> u64 {
22+ HEADER_SIZE + HEADER_EXT_SIZE + 4
23+ }
24+}
25+
26+impl Default for SmhdBox {
27+ fn default() -> Self {
28+ SmhdBox {
29+ version: 0,
30+ flags: 0,
31+ balance: FixedPointI8::new_raw(0),
32+ }
33+ }
34+}
35+
36+impl Mp4Box for SmhdBox {
37+ fn box_type(&self) -> BoxType {
38+ self.get_type()
39+ }
40+
41+ fn box_size(&self) -> u64 {
42+ self.get_size()
43+ }
44+
45+ fn to_json(&self) -> Result<String> {
46+ Ok(serde_json::to_string(&self).unwrap())
47+ }
48+
49+ fn summary(&self) -> Result<String> {
50+ let s = format!("balance={}", self.balance.value());
51+ Ok(s)
52+ }
53+}
54+
55+impl<R: Read + Seek> ReadBox<&mut R> for SmhdBox {
56+ fn read_box(reader: &mut R, size: u64) -> Result<Self> {
57+ let start = box_start(reader)?;
58+
59+ let (version, flags) = read_box_header_ext(reader)?;
60+
61+ let balance = FixedPointI8::new_raw(reader.read_i16::<BigEndian>()?);
62+
63+ skip_bytes_to(reader, start + size)?;
64+
65+ Ok(SmhdBox {
66+ version,
67+ flags,
68+ balance,
69+ })
70+ }
71+}
72+
73+impl<W: Write> WriteBox<&mut W> for SmhdBox {
74+ fn write_box(&self, writer: &mut W) -> Result<u64> {
75+ let size = self.box_size();
76+ BoxHeader::new(self.box_type(), size).write(writer)?;
77+
78+ write_box_header_ext(writer, self.version, self.flags)?;
79+
80+ writer.write_i16::<BigEndian>(self.balance.raw_value())?;
81+ writer.write_u16::<BigEndian>(0)?; // reserved
82+
83+ Ok(size)
84+ }
85+}
86+
87+#[cfg(test)]
88+mod tests {
89+ use super::*;
90+ use crate::mp4box::BoxHeader;
91+ use std::io::Cursor;
92+
93+ #[test]
94+ fn test_smhd() {
95+ let src_box = SmhdBox {
96+ version: 0,
97+ flags: 0,
98+ balance: FixedPointI8::new_raw(-1),
99+ };
100+ let mut buf = Vec::new();
101+ src_box.write_box(&mut buf).unwrap();
102+ assert_eq!(buf.len(), src_box.box_size() as usize);
103+
104+ let mut reader = Cursor::new(&buf);
105+ let header = BoxHeader::read(&mut reader).unwrap();
106+ assert_eq!(header.name, BoxType::SmhdBox);
107+ assert_eq!(src_box.box_size(), header.size);
108+
109+ let dst_box = SmhdBox::read_box(&mut reader, header.size).unwrap();
110+ assert_eq!(src_box, dst_box);
111+ }
112+}
vendor/mp4/src/mp4box/stbl.rsadded+189 -0
@@ -0,0 +1,189 @@
1+use serde::Serialize;
2+use std::io::{Read, Seek, Write};
3+
4+use crate::mp4box::*;
5+use crate::mp4box::{
6+ co64::Co64Box, ctts::CttsBox, stco::StcoBox, stsc::StscBox, stsd::StsdBox, stss::StssBox,
7+ stsz::StszBox, stts::SttsBox,
8+};
9+
10+#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize)]
11+pub struct StblBox {
12+ pub stsd: StsdBox,
13+ pub stts: SttsBox,
14+
15+ #[serde(skip_serializing_if = "Option::is_none")]
16+ pub ctts: Option<CttsBox>,
17+
18+ #[serde(skip_serializing_if = "Option::is_none")]
19+ pub stss: Option<StssBox>,
20+ pub stsc: StscBox,
21+ pub stsz: StszBox,
22+
23+ #[serde(skip_serializing_if = "Option::is_none")]
24+ pub stco: Option<StcoBox>,
25+
26+ #[serde(skip_serializing_if = "Option::is_none")]
27+ pub co64: Option<Co64Box>,
28+}
29+
30+impl StblBox {
31+ pub fn get_type(&self) -> BoxType {
32+ BoxType::StblBox
33+ }
34+
35+ pub fn get_size(&self) -> u64 {
36+ let mut size = HEADER_SIZE;
37+ size += self.stsd.box_size();
38+ size += self.stts.box_size();
39+ if let Some(ref ctts) = self.ctts {
40+ size += ctts.box_size();
41+ }
42+ if let Some(ref stss) = self.stss {
43+ size += stss.box_size();
44+ }
45+ size += self.stsc.box_size();
46+ size += self.stsz.box_size();
47+ if let Some(ref stco) = self.stco {
48+ size += stco.box_size();
49+ }
50+ if let Some(ref co64) = self.co64 {
51+ size += co64.box_size();
52+ }
53+ size
54+ }
55+}
56+
57+impl Mp4Box for StblBox {
58+ fn box_type(&self) -> BoxType {
59+ self.get_type()
60+ }
61+
62+ fn box_size(&self) -> u64 {
63+ self.get_size()
64+ }
65+
66+ fn to_json(&self) -> Result<String> {
67+ Ok(serde_json::to_string(&self).unwrap())
68+ }
69+
70+ fn summary(&self) -> Result<String> {
71+ let s = String::new();
72+ Ok(s)
73+ }
74+}
75+
76+impl<R: Read + Seek> ReadBox<&mut R> for StblBox {
77+ fn read_box(reader: &mut R, size: u64) -> Result<Self> {
78+ let start = box_start(reader)?;
79+
80+ let mut stsd = None;
81+ let mut stts = None;
82+ let mut ctts = None;
83+ let mut stss = None;
84+ let mut stsc = None;
85+ let mut stsz = None;
86+ let mut stco = None;
87+ let mut co64 = None;
88+
89+ let mut current = reader.stream_position()?;
90+ let end = start + size;
91+ while current < end {
92+ // Get box header.
93+ let header = BoxHeader::read(reader)?;
94+ let BoxHeader { name, size: s } = header;
95+ if s > size {
96+ return Err(Error::InvalidData(
97+ "stbl box contains a box with a larger size than it",
98+ ));
99+ }
100+
101+ match name {
102+ BoxType::StsdBox => {
103+ stsd = Some(StsdBox::read_box(reader, s)?);
104+ }
105+ BoxType::SttsBox => {
106+ stts = Some(SttsBox::read_box(reader, s)?);
107+ }
108+ BoxType::CttsBox => {
109+ ctts = Some(CttsBox::read_box(reader, s)?);
110+ }
111+ BoxType::StssBox => {
112+ stss = Some(StssBox::read_box(reader, s)?);
113+ }
114+ BoxType::StscBox => {
115+ stsc = Some(StscBox::read_box(reader, s)?);
116+ }
117+ BoxType::StszBox => {
118+ stsz = Some(StszBox::read_box(reader, s)?);
119+ }
120+ BoxType::StcoBox => {
121+ stco = Some(StcoBox::read_box(reader, s)?);
122+ }
123+ BoxType::Co64Box => {
124+ co64 = Some(Co64Box::read_box(reader, s)?);
125+ }
126+ _ => {
127+ // XXX warn!()
128+ skip_box(reader, s)?;
129+ }
130+ }
131+ current = reader.stream_position()?;
132+ }
133+
134+ if stsd.is_none() {
135+ return Err(Error::BoxNotFound(BoxType::StsdBox));
136+ }
137+ if stts.is_none() {
138+ return Err(Error::BoxNotFound(BoxType::SttsBox));
139+ }
140+ if stsc.is_none() {
141+ return Err(Error::BoxNotFound(BoxType::StscBox));
142+ }
143+ if stsz.is_none() {
144+ return Err(Error::BoxNotFound(BoxType::StszBox));
145+ }
146+ if stco.is_none() && co64.is_none() {
147+ return Err(Error::Box2NotFound(BoxType::StcoBox, BoxType::Co64Box));
148+ }
149+
150+ skip_bytes_to(reader, start + size)?;
151+
152+ Ok(StblBox {
153+ stsd: stsd.unwrap(),
154+ stts: stts.unwrap(),
155+ ctts,
156+ stss,
157+ stsc: stsc.unwrap(),
158+ stsz: stsz.unwrap(),
159+ stco,
160+ co64,
161+ })
162+ }
163+}
164+
165+impl<W: Write> WriteBox<&mut W> for StblBox {
166+ fn write_box(&self, writer: &mut W) -> Result<u64> {
167+ let size = self.box_size();
168+ BoxHeader::new(self.box_type(), size).write(writer)?;
169+
170+ self.stsd.write_box(writer)?;
171+ self.stts.write_box(writer)?;
172+ if let Some(ref ctts) = self.ctts {
173+ ctts.write_box(writer)?;
174+ }
175+ if let Some(ref stss) = self.stss {
176+ stss.write_box(writer)?;
177+ }
178+ self.stsc.write_box(writer)?;
179+ self.stsz.write_box(writer)?;
180+ if let Some(ref stco) = self.stco {
181+ stco.write_box(writer)?;
182+ }
183+ if let Some(ref co64) = self.co64 {
184+ co64.write_box(writer)?;
185+ }
186+
187+ Ok(size)
188+ }
189+}
vendor/mp4/src/mp4box/stco.rsadded+141 -0
@@ -0,0 +1,141 @@
1+use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
2+use serde::Serialize;
3+use std::io::{Read, Seek, Write};
4+use std::mem::size_of;
5+
6+use crate::mp4box::*;
7+
8+#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize)]
9+pub struct StcoBox {
10+ pub version: u8,
11+ pub flags: u32,
12+
13+ #[serde(skip_serializing)]
14+ pub entries: Vec<u32>,
15+}
16+
17+impl StcoBox {
18+ pub fn get_type(&self) -> BoxType {
19+ BoxType::StcoBox
20+ }
21+
22+ pub fn get_size(&self) -> u64 {
23+ HEADER_SIZE + HEADER_EXT_SIZE + 4 + (4 * self.entries.len() as u64)
24+ }
25+}
26+
27+impl Mp4Box for StcoBox {
28+ fn box_type(&self) -> BoxType {
29+ self.get_type()
30+ }
31+
32+ fn box_size(&self) -> u64 {
33+ self.get_size()
34+ }
35+
36+ fn to_json(&self) -> Result<String> {
37+ Ok(serde_json::to_string(&self).unwrap())
38+ }
39+
40+ fn summary(&self) -> Result<String> {
41+ let s = format!("entries={}", self.entries.len());
42+ Ok(s)
43+ }
44+}
45+
46+impl<R: Read + Seek> ReadBox<&mut R> for StcoBox {
47+ fn read_box(reader: &mut R, size: u64) -> Result<Self> {
48+ let start = box_start(reader)?;
49+
50+ let (version, flags) = read_box_header_ext(reader)?;
51+
52+ let header_size = HEADER_SIZE + HEADER_EXT_SIZE;
53+ let other_size = size_of::<u32>(); // entry_count
54+ let entry_size = size_of::<u32>(); // chunk_offset
55+ let entry_count = reader.read_u32::<BigEndian>()?;
56+ if u64::from(entry_count)
57+ > size
58+ .saturating_sub(header_size)
59+ .saturating_sub(other_size as u64)
60+ / entry_size as u64
61+ {
62+ return Err(Error::InvalidData(
63+ "stco entry_count indicates more entries than could fit in the box",
64+ ));
65+ }
66+ let mut entries = Vec::with_capacity(entry_count as usize);
67+ for _i in 0..entry_count {
68+ let chunk_offset = reader.read_u32::<BigEndian>()?;
69+ entries.push(chunk_offset);
70+ }
71+
72+ skip_bytes_to(reader, start + size)?;
73+
74+ Ok(StcoBox {
75+ version,
76+ flags,
77+ entries,
78+ })
79+ }
80+}
81+
82+impl<W: Write> WriteBox<&mut W> for StcoBox {
83+ fn write_box(&self, writer: &mut W) -> Result<u64> {
84+ let size = self.box_size();
85+ BoxHeader::new(self.box_type(), size).write(writer)?;
86+
87+ write_box_header_ext(writer, self.version, self.flags)?;
88+
89+ writer.write_u32::<BigEndian>(self.entries.len() as u32)?;
90+ for chunk_offset in self.entries.iter() {
91+ writer.write_u32::<BigEndian>(*chunk_offset)?;
92+ }
93+
94+ Ok(size)
95+ }
96+}
97+
98+impl std::convert::TryFrom<&co64::Co64Box> for StcoBox {
99+ type Error = std::num::TryFromIntError;
100+
101+ fn try_from(co64: &co64::Co64Box) -> std::result::Result<Self, Self::Error> {
102+ let entries = co64
103+ .entries
104+ .iter()
105+ .copied()
106+ .map(u32::try_from)
107+ .collect::<std::result::Result<Vec<_>, _>>()?;
108+ Ok(Self {
109+ version: 0,
110+ flags: 0,
111+ entries,
112+ })
113+ }
114+}
115+
116+#[cfg(test)]
117+mod tests {
118+ use super::*;
119+ use crate::mp4box::BoxHeader;
120+ use std::io::Cursor;
121+
122+ #[test]
123+ fn test_stco() {
124+ let src_box = StcoBox {
125+ version: 0,
126+ flags: 0,
127+ entries: vec![267, 1970, 2535, 2803, 11843, 22223, 33584],
128+ };
129+ let mut buf = Vec::new();
130+ src_box.write_box(&mut buf).unwrap();
131+ assert_eq!(buf.len(), src_box.box_size() as usize);
132+
133+ let mut reader = Cursor::new(&buf);
134+ let header = BoxHeader::read(&mut reader).unwrap();
135+ assert_eq!(header.name, BoxType::StcoBox);
136+ assert_eq!(src_box.box_size(), header.size);
137+
138+ let dst_box = StcoBox::read_box(&mut reader, header.size).unwrap();
139+ assert_eq!(src_box, dst_box);
140+ }
141+}
vendor/mp4/src/mp4box/stsc.rsadded+171 -0
@@ -0,0 +1,171 @@
1+use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
2+use serde::Serialize;
3+use std::io::{Read, Seek, Write};
4+use std::mem::size_of;
5+
6+use crate::mp4box::*;
7+
8+#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize)]
9+pub struct StscBox {
10+ pub version: u8,
11+ pub flags: u32,
12+
13+ #[serde(skip_serializing)]
14+ pub entries: Vec<StscEntry>,
15+}
16+
17+impl StscBox {
18+ pub fn get_type(&self) -> BoxType {
19+ BoxType::StscBox
20+ }
21+
22+ pub fn get_size(&self) -> u64 {
23+ HEADER_SIZE + HEADER_EXT_SIZE + 4 + (12 * self.entries.len() as u64)
24+ }
25+}
26+
27+#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize)]
28+pub struct StscEntry {
29+ pub first_chunk: u32,
30+ pub samples_per_chunk: u32,
31+ pub sample_description_index: u32,
32+ pub first_sample: u32,
33+}
34+
35+impl Mp4Box for StscBox {
36+ fn box_type(&self) -> BoxType {
37+ self.get_type()
38+ }
39+
40+ fn box_size(&self) -> u64 {
41+ self.get_size()
42+ }
43+
44+ fn to_json(&self) -> Result<String> {
45+ Ok(serde_json::to_string(&self).unwrap())
46+ }
47+
48+ fn summary(&self) -> Result<String> {
49+ let s = format!("entries={}", self.entries.len());
50+ Ok(s)
51+ }
52+}
53+
54+impl<R: Read + Seek> ReadBox<&mut R> for StscBox {
55+ fn read_box(reader: &mut R, size: u64) -> Result<Self> {
56+ let start = box_start(reader)?;
57+
58+ let (version, flags) = read_box_header_ext(reader)?;
59+
60+ let header_size = HEADER_SIZE + HEADER_EXT_SIZE;
61+ let other_size = size_of::<u32>(); // entry_count
62+ let entry_size = size_of::<u32>() + size_of::<u32>() + size_of::<u32>(); // first_chunk + samples_per_chunk + sample_description_index
63+ let entry_count = reader.read_u32::<BigEndian>()?;
64+ if u64::from(entry_count)
65+ > size
66+ .saturating_sub(header_size)
67+ .saturating_sub(other_size as u64)
68+ / entry_size as u64
69+ {
70+ return Err(Error::InvalidData(
71+ "stsc entry_count indicates more entries than could fit in the box",
72+ ));
73+ }
74+ let mut entries = Vec::with_capacity(entry_count as usize);
75+ for _ in 0..entry_count {
76+ let entry = StscEntry {
77+ first_chunk: reader.read_u32::<BigEndian>()?,
78+ samples_per_chunk: reader.read_u32::<BigEndian>()?,
79+ sample_description_index: reader.read_u32::<BigEndian>()?,
80+ first_sample: 0,
81+ };
82+ entries.push(entry);
83+ }
84+
85+ let mut sample_id = 1;
86+ for i in 0..entry_count {
87+ let (first_chunk, samples_per_chunk) = {
88+ let entry = entries.get_mut(i as usize).unwrap();
89+ entry.first_sample = sample_id;
90+ (entry.first_chunk, entry.samples_per_chunk)
91+ };
92+ if i < entry_count - 1 {
93+ let next_entry = entries.get(i as usize + 1).unwrap();
94+ sample_id = next_entry
95+ .first_chunk
96+ .checked_sub(first_chunk)
97+ .and_then(|n| n.checked_mul(samples_per_chunk))
98+ .and_then(|n| n.checked_add(sample_id))
99+ .ok_or(Error::InvalidData(
100+ "attempt to calculate stsc sample_id with overflow",
101+ ))?;
102+ }
103+ }
104+
105+ skip_bytes_to(reader, start + size)?;
106+
107+ Ok(StscBox {
108+ version,
109+ flags,
110+ entries,
111+ })
112+ }
113+}
114+
115+impl<W: Write> WriteBox<&mut W> for StscBox {
116+ fn write_box(&self, writer: &mut W) -> Result<u64> {
117+ let size = self.box_size();
118+ BoxHeader::new(self.box_type(), size).write(writer)?;
119+
120+ write_box_header_ext(writer, self.version, self.flags)?;
121+
122+ writer.write_u32::<BigEndian>(self.entries.len() as u32)?;
123+ for entry in self.entries.iter() {
124+ writer.write_u32::<BigEndian>(entry.first_chunk)?;
125+ writer.write_u32::<BigEndian>(entry.samples_per_chunk)?;
126+ writer.write_u32::<BigEndian>(entry.sample_description_index)?;
127+ }
128+
129+ Ok(size)
130+ }
131+}
132+
133+#[cfg(test)]
134+mod tests {
135+ use super::*;
136+ use crate::mp4box::BoxHeader;
137+ use std::io::Cursor;
138+
139+ #[test]
140+ fn test_stsc() {
141+ let src_box = StscBox {
142+ version: 0,
143+ flags: 0,
144+ entries: vec![
145+ StscEntry {
146+ first_chunk: 1,
147+ samples_per_chunk: 1,
148+ sample_description_index: 1,
149+ first_sample: 1,
150+ },
151+ StscEntry {
152+ first_chunk: 19026,
153+ samples_per_chunk: 14,
154+ sample_description_index: 1,
155+ first_sample: 19026,
156+ },
157+ ],
158+ };
159+ let mut buf = Vec::new();
160+ src_box.write_box(&mut buf).unwrap();
161+ assert_eq!(buf.len(), src_box.box_size() as usize);
162+
163+ let mut reader = Cursor::new(&buf);
164+ let header = BoxHeader::read(&mut reader).unwrap();
165+ assert_eq!(header.name, BoxType::StscBox);
166+ assert_eq!(src_box.box_size(), header.size);
167+
168+ let dst_box = StscBox::read_box(&mut reader, header.size).unwrap();
169+ assert_eq!(src_box, dst_box);
170+ }
171+}
vendor/mp4/src/mp4box/stsd.rsadded+150 -0
@@ -0,0 +1,150 @@
1+use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
2+use serde::Serialize;
3+use std::io::{Read, Seek, Write};
4+
5+use crate::mp4box::vp09::Vp09Box;
6+use crate::mp4box::*;
7+use crate::mp4box::{avc1::Avc1Box, hev1::Hev1Box, mp4a::Mp4aBox, tx3g::Tx3gBox};
8+
9+#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize)]
10+pub struct StsdBox {
11+ pub version: u8,
12+ pub flags: u32,
13+
14+ #[serde(skip_serializing_if = "Option::is_none")]
15+ pub avc1: Option<Avc1Box>,
16+
17+ #[serde(skip_serializing_if = "Option::is_none")]
18+ pub hev1: Option<Hev1Box>,
19+
20+ #[serde(skip_serializing_if = "Option::is_none")]
21+ pub vp09: Option<Vp09Box>,
22+
23+ #[serde(skip_serializing_if = "Option::is_none")]
24+ pub mp4a: Option<Mp4aBox>,
25+
26+ #[serde(skip_serializing_if = "Option::is_none")]
27+ pub tx3g: Option<Tx3gBox>,
28+}
29+
30+impl StsdBox {
31+ pub fn get_type(&self) -> BoxType {
32+ BoxType::StsdBox
33+ }
34+
35+ pub fn get_size(&self) -> u64 {
36+ let mut size = HEADER_SIZE + HEADER_EXT_SIZE + 4;
37+ if let Some(ref avc1) = self.avc1 {
38+ size += avc1.box_size();
39+ } else if let Some(ref hev1) = self.hev1 {
40+ size += hev1.box_size();
41+ } else if let Some(ref vp09) = self.vp09 {
42+ size += vp09.box_size();
43+ } else if let Some(ref mp4a) = self.mp4a {
44+ size += mp4a.box_size();
45+ } else if let Some(ref tx3g) = self.tx3g {
46+ size += tx3g.box_size();
47+ }
48+ size
49+ }
50+}
51+
52+impl Mp4Box for StsdBox {
53+ fn box_type(&self) -> BoxType {
54+ self.get_type()
55+ }
56+
57+ fn box_size(&self) -> u64 {
58+ self.get_size()
59+ }
60+
61+ fn to_json(&self) -> Result<String> {
62+ Ok(serde_json::to_string(&self).unwrap())
63+ }
64+
65+ fn summary(&self) -> Result<String> {
66+ let s = String::new();
67+ Ok(s)
68+ }
69+}
70+
71+impl<R: Read + Seek> ReadBox<&mut R> for StsdBox {
72+ fn read_box(reader: &mut R, size: u64) -> Result<Self> {
73+ let start = box_start(reader)?;
74+
75+ let (version, flags) = read_box_header_ext(reader)?;
76+
77+ reader.read_u32::<BigEndian>()?; // XXX entry_count
78+
79+ let mut avc1 = None;
80+ let mut hev1 = None;
81+ let mut vp09 = None;
82+ let mut mp4a = None;
83+ let mut tx3g = None;
84+
85+ // Get box header.
86+ let header = BoxHeader::read(reader)?;
87+ let BoxHeader { name, size: s } = header;
88+ if s > size {
89+ return Err(Error::InvalidData(
90+ "stsd box contains a box with a larger size than it",
91+ ));
92+ }
93+
94+ match name {
95+ BoxType::Avc1Box => {
96+ avc1 = Some(Avc1Box::read_box(reader, s)?);
97+ }
98+ BoxType::Hev1Box => {
99+ hev1 = Some(Hev1Box::read_box(reader, s)?);
100+ }
101+ BoxType::Vp09Box => {
102+ vp09 = Some(Vp09Box::read_box(reader, s)?);
103+ }
104+ BoxType::Mp4aBox => {
105+ mp4a = Some(Mp4aBox::read_box(reader, s)?);
106+ }
107+ BoxType::Tx3gBox => {
108+ tx3g = Some(Tx3gBox::read_box(reader, s)?);
109+ }
110+ _ => {}
111+ }
112+
113+ skip_bytes_to(reader, start + size)?;
114+
115+ Ok(StsdBox {
116+ version,
117+ flags,
118+ avc1,
119+ hev1,
120+ vp09,
121+ mp4a,
122+ tx3g,
123+ })
124+ }
125+}
126+
127+impl<W: Write> WriteBox<&mut W> for StsdBox {
128+ fn write_box(&self, writer: &mut W) -> Result<u64> {
129+ let size = self.box_size();
130+ BoxHeader::new(self.box_type(), size).write(writer)?;
131+
132+ write_box_header_ext(writer, self.version, self.flags)?;
133+
134+ writer.write_u32::<BigEndian>(1)?; // entry_count
135+
136+ if let Some(ref avc1) = self.avc1 {
137+ avc1.write_box(writer)?;
138+ } else if let Some(ref hev1) = self.hev1 {
139+ hev1.write_box(writer)?;
140+ } else if let Some(ref vp09) = self.vp09 {
141+ vp09.write_box(writer)?;
142+ } else if let Some(ref mp4a) = self.mp4a {
143+ mp4a.write_box(writer)?;
144+ } else if let Some(ref tx3g) = self.tx3g {
145+ tx3g.write_box(writer)?;
146+ }
147+
148+ Ok(size)
149+ }
150+}
vendor/mp4/src/mp4box/stss.rsadded+123 -0
@@ -0,0 +1,123 @@
1+use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
2+use serde::Serialize;
3+use std::io::{Read, Seek, Write};
4+use std::mem::size_of;
5+
6+use crate::mp4box::*;
7+
8+#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize)]
9+pub struct StssBox {
10+ pub version: u8,
11+ pub flags: u32,
12+
13+ #[serde(skip_serializing)]
14+ pub entries: Vec<u32>,
15+}
16+
17+impl StssBox {
18+ pub fn get_type(&self) -> BoxType {
19+ BoxType::StssBox
20+ }
21+
22+ pub fn get_size(&self) -> u64 {
23+ HEADER_SIZE + HEADER_EXT_SIZE + 4 + (4 * self.entries.len() as u64)
24+ }
25+}
26+
27+impl Mp4Box for StssBox {
28+ fn box_type(&self) -> BoxType {
29+ self.get_type()
30+ }
31+
32+ fn box_size(&self) -> u64 {
33+ self.get_size()
34+ }
35+
36+ fn to_json(&self) -> Result<String> {
37+ Ok(serde_json::to_string(&self).unwrap())
38+ }
39+
40+ fn summary(&self) -> Result<String> {
41+ let s = format!("entries={}", self.entries.len());
42+ Ok(s)
43+ }
44+}
45+
46+impl<R: Read + Seek> ReadBox<&mut R> for StssBox {
47+ fn read_box(reader: &mut R, size: u64) -> Result<Self> {
48+ let start = box_start(reader)?;
49+
50+ let (version, flags) = read_box_header_ext(reader)?;
51+
52+ let header_size = HEADER_SIZE + HEADER_EXT_SIZE;
53+ let other_size = size_of::<u32>(); // entry_count
54+ let entry_size = size_of::<u32>(); // sample_number
55+ let entry_count = reader.read_u32::<BigEndian>()?;
56+ if u64::from(entry_count)
57+ > size
58+ .saturating_sub(header_size)
59+ .saturating_sub(other_size as u64)
60+ / entry_size as u64
61+ {
62+ return Err(Error::InvalidData(
63+ "stss entry_count indicates more entries than could fit in the box",
64+ ));
65+ }
66+ let mut entries = Vec::with_capacity(entry_count as usize);
67+ for _i in 0..entry_count {
68+ let sample_number = reader.read_u32::<BigEndian>()?;
69+ entries.push(sample_number);
70+ }
71+
72+ skip_bytes_to(reader, start + size)?;
73+
74+ Ok(StssBox {
75+ version,
76+ flags,
77+ entries,
78+ })
79+ }
80+}
81+
82+impl<W: Write> WriteBox<&mut W> for StssBox {
83+ fn write_box(&self, writer: &mut W) -> Result<u64> {
84+ let size = self.box_size();
85+ BoxHeader::new(self.box_type(), size).write(writer)?;
86+
87+ write_box_header_ext(writer, self.version, self.flags)?;
88+
89+ writer.write_u32::<BigEndian>(self.entries.len() as u32)?;
90+ for sample_number in self.entries.iter() {
91+ writer.write_u32::<BigEndian>(*sample_number)?;
92+ }
93+
94+ Ok(size)
95+ }
96+}
97+
98+#[cfg(test)]
99+mod tests {
100+ use super::*;
101+ use crate::mp4box::BoxHeader;
102+ use std::io::Cursor;
103+
104+ #[test]
105+ fn test_stss() {
106+ let src_box = StssBox {
107+ version: 0,
108+ flags: 0,
109+ entries: vec![1, 61, 121, 181, 241, 301, 361, 421, 481],
110+ };
111+ let mut buf = Vec::new();
112+ src_box.write_box(&mut buf).unwrap();
113+ assert_eq!(buf.len(), src_box.box_size() as usize);
114+
115+ let mut reader = Cursor::new(&buf);
116+ let header = BoxHeader::read(&mut reader).unwrap();
117+ assert_eq!(header.name, BoxType::StssBox);
118+ assert_eq!(src_box.box_size(), header.size);
119+
120+ let dst_box = StssBox::read_box(&mut reader, header.size).unwrap();
121+ assert_eq!(src_box, dst_box);
122+ }
123+}
vendor/mp4/src/mp4box/stsz.rsadded+170 -0
@@ -0,0 +1,170 @@
1+use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
2+use serde::Serialize;
3+use std::io::{Read, Seek, Write};
4+use std::mem::size_of;
5+
6+use crate::mp4box::*;
7+
8+#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize)]
9+pub struct StszBox {
10+ pub version: u8,
11+ pub flags: u32,
12+ pub sample_size: u32,
13+ pub sample_count: u32,
14+
15+ #[serde(skip_serializing)]
16+ pub sample_sizes: Vec<u32>,
17+}
18+
19+impl StszBox {
20+ pub fn get_type(&self) -> BoxType {
21+ BoxType::StszBox
22+ }
23+
24+ pub fn get_size(&self) -> u64 {
25+ HEADER_SIZE + HEADER_EXT_SIZE + 8 + (4 * self.sample_sizes.len() as u64)
26+ }
27+}
28+
29+impl Mp4Box for StszBox {
30+ fn box_type(&self) -> BoxType {
31+ self.get_type()
32+ }
33+
34+ fn box_size(&self) -> u64 {
35+ self.get_size()
36+ }
37+
38+ fn to_json(&self) -> Result<String> {
39+ Ok(serde_json::to_string(&self).unwrap())
40+ }
41+
42+ fn summary(&self) -> Result<String> {
43+ let s = format!(
44+ "sample_size={} sample_count={} sample_sizes={}",
45+ self.sample_size,
46+ self.sample_count,
47+ self.sample_sizes.len()
48+ );
49+ Ok(s)
50+ }
51+}
52+
53+impl<R: Read + Seek> ReadBox<&mut R> for StszBox {
54+ fn read_box(reader: &mut R, size: u64) -> Result<Self> {
55+ let start = box_start(reader)?;
56+
57+ let (version, flags) = read_box_header_ext(reader)?;
58+
59+ let header_size = HEADER_SIZE + HEADER_EXT_SIZE;
60+ let other_size = size_of::<u32>() + size_of::<u32>(); // sample_size + sample_count
61+ let sample_size = reader.read_u32::<BigEndian>()?;
62+ let stsz_item_size = if sample_size == 0 {
63+ size_of::<u32>() // entry_size
64+ } else {
65+ 0
66+ };
67+ let sample_count = reader.read_u32::<BigEndian>()?;
68+ let mut sample_sizes = Vec::new();
69+ if sample_size == 0 {
70+ if u64::from(sample_count)
71+ > size
72+ .saturating_sub(header_size)
73+ .saturating_sub(other_size as u64)
74+ / stsz_item_size as u64
75+ {
76+ return Err(Error::InvalidData(
77+ "stsz sample_count indicates more values than could fit in the box",
78+ ));
79+ }
80+ sample_sizes.reserve(sample_count as usize);
81+ for _ in 0..sample_count {
82+ let sample_number = reader.read_u32::<BigEndian>()?;
83+ sample_sizes.push(sample_number);
84+ }
85+ }
86+
87+ skip_bytes_to(reader, start + size)?;
88+
89+ Ok(StszBox {
90+ version,
91+ flags,
92+ sample_size,
93+ sample_count,
94+ sample_sizes,
95+ })
96+ }
97+}
98+
99+impl<W: Write> WriteBox<&mut W> for StszBox {
100+ fn write_box(&self, writer: &mut W) -> Result<u64> {
101+ let size = self.box_size();
102+ BoxHeader::new(self.box_type(), size).write(writer)?;
103+
104+ write_box_header_ext(writer, self.version, self.flags)?;
105+
106+ writer.write_u32::<BigEndian>(self.sample_size)?;
107+ writer.write_u32::<BigEndian>(self.sample_count)?;
108+ if self.sample_size == 0 {
109+ if self.sample_count != self.sample_sizes.len() as u32 {
110+ return Err(Error::InvalidData("sample count out of sync"));
111+ }
112+ for sample_number in self.sample_sizes.iter() {
113+ writer.write_u32::<BigEndian>(*sample_number)?;
114+ }
115+ }
116+
117+ Ok(size)
118+ }
119+}
120+
121+#[cfg(test)]
122+mod tests {
123+ use super::*;
124+ use crate::mp4box::BoxHeader;
125+ use std::io::Cursor;
126+
127+ #[test]
128+ fn test_stsz_same_size() {
129+ let src_box = StszBox {
130+ version: 0,
131+ flags: 0,
132+ sample_size: 1165,
133+ sample_count: 12,
134+ sample_sizes: vec![],
135+ };
136+ let mut buf = Vec::new();
137+ src_box.write_box(&mut buf).unwrap();
138+ assert_eq!(buf.len(), src_box.box_size() as usize);
139+
140+ let mut reader = Cursor::new(&buf);
141+ let header = BoxHeader::read(&mut reader).unwrap();
142+ assert_eq!(header.name, BoxType::StszBox);
143+ assert_eq!(src_box.box_size(), header.size);
144+
145+ let dst_box = StszBox::read_box(&mut reader, header.size).unwrap();
146+ assert_eq!(src_box, dst_box);
147+ }
148+
149+ #[test]
150+ fn test_stsz_many_sizes() {
151+ let src_box = StszBox {
152+ version: 0,
153+ flags: 0,
154+ sample_size: 0,
155+ sample_count: 9,
156+ sample_sizes: vec![1165, 11, 11, 8545, 10126, 10866, 9643, 9351, 7730],
157+ };
158+ let mut buf = Vec::new();
159+ src_box.write_box(&mut buf).unwrap();
160+ assert_eq!(buf.len(), src_box.box_size() as usize);
161+
162+ let mut reader = Cursor::new(&buf);
163+ let header = BoxHeader::read(&mut reader).unwrap();
164+ assert_eq!(header.name, BoxType::StszBox);
165+ assert_eq!(src_box.box_size(), header.size);
166+
167+ let dst_box = StszBox::read_box(&mut reader, header.size).unwrap();
168+ assert_eq!(src_box, dst_box);
169+ }
170+}
vendor/mp4/src/mp4box/stts.rsadded+142 -0
@@ -0,0 +1,142 @@
1+use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
2+use serde::Serialize;
3+use std::io::{Read, Seek, Write};
4+use std::mem::size_of;
5+
6+use crate::mp4box::*;
7+
8+#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize)]
9+pub struct SttsBox {
10+ pub version: u8,
11+ pub flags: u32,
12+
13+ #[serde(skip_serializing)]
14+ pub entries: Vec<SttsEntry>,
15+}
16+
17+impl SttsBox {
18+ pub fn get_type(&self) -> BoxType {
19+ BoxType::SttsBox
20+ }
21+
22+ pub fn get_size(&self) -> u64 {
23+ HEADER_SIZE + HEADER_EXT_SIZE + 4 + (8 * self.entries.len() as u64)
24+ }
25+}
26+
27+#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize)]
28+pub struct SttsEntry {
29+ pub sample_count: u32,
30+ pub sample_delta: u32,
31+}
32+
33+impl Mp4Box for SttsBox {
34+ fn box_type(&self) -> BoxType {
35+ self.get_type()
36+ }
37+
38+ fn box_size(&self) -> u64 {
39+ self.get_size()
40+ }
41+
42+ fn to_json(&self) -> Result<String> {
43+ Ok(serde_json::to_string(&self).unwrap())
44+ }
45+
46+ fn summary(&self) -> Result<String> {
47+ let s = format!("entries={}", self.entries.len());
48+ Ok(s)
49+ }
50+}
51+
52+impl<R: Read + Seek> ReadBox<&mut R> for SttsBox {
53+ fn read_box(reader: &mut R, size: u64) -> Result<Self> {
54+ let start = box_start(reader)?;
55+
56+ let (version, flags) = read_box_header_ext(reader)?;
57+
58+ let header_size = HEADER_SIZE + HEADER_EXT_SIZE;
59+ let other_size = size_of::<u32>(); // entry_count
60+ let entry_size = size_of::<u32>() + size_of::<u32>(); // sample_count + sample_delta
61+ let entry_count = reader.read_u32::<BigEndian>()?;
62+ if u64::from(entry_count)
63+ > size
64+ .saturating_sub(header_size)
65+ .saturating_sub(other_size as u64)
66+ / entry_size as u64
67+ {
68+ return Err(Error::InvalidData(
69+ "stts entry_count indicates more entries than could fit in the box",
70+ ));
71+ }
72+ let mut entries = Vec::with_capacity(entry_count as usize);
73+ for _i in 0..entry_count {
74+ let entry = SttsEntry {
75+ sample_count: reader.read_u32::<BigEndian>()?,
76+ sample_delta: reader.read_u32::<BigEndian>()?,
77+ };
78+ entries.push(entry);
79+ }
80+
81+ skip_bytes_to(reader, start + size)?;
82+
83+ Ok(SttsBox {
84+ version,
85+ flags,
86+ entries,
87+ })
88+ }
89+}
90+
91+impl<W: Write> WriteBox<&mut W> for SttsBox {
92+ fn write_box(&self, writer: &mut W) -> Result<u64> {
93+ let size = self.box_size();
94+ BoxHeader::new(self.box_type(), size).write(writer)?;
95+
96+ write_box_header_ext(writer, self.version, self.flags)?;
97+
98+ writer.write_u32::<BigEndian>(self.entries.len() as u32)?;
99+ for entry in self.entries.iter() {
100+ writer.write_u32::<BigEndian>(entry.sample_count)?;
101+ writer.write_u32::<BigEndian>(entry.sample_delta)?;
102+ }
103+
104+ Ok(size)
105+ }
106+}
107+
108+#[cfg(test)]
109+mod tests {
110+ use super::*;
111+ use crate::mp4box::BoxHeader;
112+ use std::io::Cursor;
113+
114+ #[test]
115+ fn test_stts() {
116+ let src_box = SttsBox {
117+ version: 0,
118+ flags: 0,
119+ entries: vec![
120+ SttsEntry {
121+ sample_count: 29726,
122+ sample_delta: 1024,
123+ },
124+ SttsEntry {
125+ sample_count: 1,
126+ sample_delta: 512,
127+ },
128+ ],
129+ };
130+ let mut buf = Vec::new();
131+ src_box.write_box(&mut buf).unwrap();
132+ assert_eq!(buf.len(), src_box.box_size() as usize);
133+
134+ let mut reader = Cursor::new(&buf);
135+ let header = BoxHeader::read(&mut reader).unwrap();
136+ assert_eq!(header.name, BoxType::SttsBox);
137+ assert_eq!(src_box.box_size(), header.size);
138+
139+ let dst_box = SttsBox::read_box(&mut reader, header.size).unwrap();
140+ assert_eq!(src_box, dst_box);
141+ }
142+}
vendor/mp4/src/mp4box/tfdt.rsadded+137 -0
@@ -0,0 +1,137 @@
1+use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
2+use serde::Serialize;
3+use std::io::{Read, Seek, Write};
4+
5+use crate::mp4box::*;
6+
7+#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize)]
8+pub struct TfdtBox {
9+ pub version: u8,
10+ pub flags: u32,
11+ pub base_media_decode_time: u64,
12+}
13+
14+impl TfdtBox {
15+ pub fn get_type(&self) -> BoxType {
16+ BoxType::TfdtBox
17+ }
18+
19+ pub fn get_size(&self) -> u64 {
20+ let mut sum = HEADER_SIZE + HEADER_EXT_SIZE;
21+ if self.version == 1 {
22+ sum += 8;
23+ } else {
24+ sum += 4;
25+ }
26+ sum
27+ }
28+}
29+
30+impl Mp4Box for TfdtBox {
31+ fn box_type(&self) -> BoxType {
32+ self.get_type()
33+ }
34+
35+ fn box_size(&self) -> u64 {
36+ self.get_size()
37+ }
38+
39+ fn to_json(&self) -> Result<String> {
40+ Ok(serde_json::to_string(&self).unwrap())
41+ }
42+
43+ fn summary(&self) -> Result<String> {
44+ let s = format!("base_media_decode_time={}", self.base_media_decode_time);
45+ Ok(s)
46+ }
47+}
48+
49+impl<R: Read + Seek> ReadBox<&mut R> for TfdtBox {
50+ fn read_box(reader: &mut R, size: u64) -> Result<Self> {
51+ let start = box_start(reader)?;
52+
53+ let (version, flags) = read_box_header_ext(reader)?;
54+
55+ let base_media_decode_time = if version == 1 {
56+ reader.read_u64::<BigEndian>()?
57+ } else if version == 0 {
58+ reader.read_u32::<BigEndian>()? as u64
59+ } else {
60+ return Err(Error::InvalidData("version must be 0 or 1"));
61+ };
62+
63+ skip_bytes_to(reader, start + size)?;
64+
65+ Ok(TfdtBox {
66+ version,
67+ flags,
68+ base_media_decode_time,
69+ })
70+ }
71+}
72+
73+impl<W: Write> WriteBox<&mut W> for TfdtBox {
74+ fn write_box(&self, writer: &mut W) -> Result<u64> {
75+ let size = self.box_size();
76+ BoxHeader::new(self.box_type(), size).write(writer)?;
77+
78+ write_box_header_ext(writer, self.version, self.flags)?;
79+
80+ if self.version == 1 {
81+ writer.write_u64::<BigEndian>(self.base_media_decode_time)?;
82+ } else if self.version == 0 {
83+ writer.write_u32::<BigEndian>(self.base_media_decode_time as u32)?;
84+ } else {
85+ return Err(Error::InvalidData("version must be 0 or 1"));
86+ }
87+
88+ Ok(size)
89+ }
90+}
91+
92+#[cfg(test)]
93+mod tests {
94+ use super::*;
95+ use crate::mp4box::BoxHeader;
96+ use std::io::Cursor;
97+
98+ #[test]
99+ fn test_tfdt32() {
100+ let src_box = TfdtBox {
101+ version: 0,
102+ flags: 0,
103+ base_media_decode_time: 0,
104+ };
105+ let mut buf = Vec::new();
106+ src_box.write_box(&mut buf).unwrap();
107+ assert_eq!(buf.len(), src_box.box_size() as usize);
108+
109+ let mut reader = Cursor::new(&buf);
110+ let header = BoxHeader::read(&mut reader).unwrap();
111+ assert_eq!(header.name, BoxType::TfdtBox);
112+ assert_eq!(src_box.box_size(), header.size);
113+
114+ let dst_box = TfdtBox::read_box(&mut reader, header.size).unwrap();
115+ assert_eq!(src_box, dst_box);
116+ }
117+
118+ #[test]
119+ fn test_tfdt64() {
120+ let src_box = TfdtBox {
121+ version: 1,
122+ flags: 0,
123+ base_media_decode_time: 0,
124+ };
125+ let mut buf = Vec::new();
126+ src_box.write_box(&mut buf).unwrap();
127+ assert_eq!(buf.len(), src_box.box_size() as usize);
128+
129+ let mut reader = Cursor::new(&buf);
130+ let header = BoxHeader::read(&mut reader).unwrap();
131+ assert_eq!(header.name, BoxType::TfdtBox);
132+ assert_eq!(src_box.box_size(), header.size);
133+
134+ let dst_box = TfdtBox::read_box(&mut reader, header.size).unwrap();
135+ assert_eq!(src_box, dst_box);
136+ }
137+}
vendor/mp4/src/mp4box/tfhd.rsadded+201 -0
@@ -0,0 +1,201 @@
1+use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
2+use serde::Serialize;
3+use std::io::{Read, Seek, Write};
4+
5+use crate::mp4box::*;
6+
7+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Default)]
8+pub struct TfhdBox {
9+ pub version: u8,
10+ pub flags: u32,
11+ pub track_id: u32,
12+ pub base_data_offset: Option<u64>,
13+ pub sample_description_index: Option<u32>,
14+ pub default_sample_duration: Option<u32>,
15+ pub default_sample_size: Option<u32>,
16+ pub default_sample_flags: Option<u32>,
17+}
18+
19+impl TfhdBox {
20+ pub const FLAG_BASE_DATA_OFFSET: u32 = 0x01;
21+ pub const FLAG_SAMPLE_DESCRIPTION_INDEX: u32 = 0x02;
22+ pub const FLAG_DEFAULT_SAMPLE_DURATION: u32 = 0x08;
23+ pub const FLAG_DEFAULT_SAMPLE_SIZE: u32 = 0x10;
24+ pub const FLAG_DEFAULT_SAMPLE_FLAGS: u32 = 0x20;
25+
26+ pub fn get_type(&self) -> BoxType {
27+ BoxType::TfhdBox
28+ }
29+
30+ pub fn get_size(&self) -> u64 {
31+ let mut sum = HEADER_SIZE + HEADER_EXT_SIZE + 4;
32+ if TfhdBox::FLAG_BASE_DATA_OFFSET & self.flags > 0 {
33+ sum += 8;
34+ }
35+ if TfhdBox::FLAG_SAMPLE_DESCRIPTION_INDEX & self.flags > 0 {
36+ sum += 4;
37+ }
38+ if TfhdBox::FLAG_DEFAULT_SAMPLE_DURATION & self.flags > 0 {
39+ sum += 4;
40+ }
41+ if TfhdBox::FLAG_DEFAULT_SAMPLE_SIZE & self.flags > 0 {
42+ sum += 4;
43+ }
44+ if TfhdBox::FLAG_DEFAULT_SAMPLE_FLAGS & self.flags > 0 {
45+ sum += 4;
46+ }
47+ sum
48+ }
49+}
50+
51+impl Mp4Box for TfhdBox {
52+ fn box_type(&self) -> BoxType {
53+ self.get_type()
54+ }
55+
56+ fn box_size(&self) -> u64 {
57+ self.get_size()
58+ }
59+
60+ fn to_json(&self) -> Result<String> {
61+ Ok(serde_json::to_string(&self).unwrap())
62+ }
63+
64+ fn summary(&self) -> Result<String> {
65+ let s = format!("track_id={}", self.track_id);
66+ Ok(s)
67+ }
68+}
69+
70+impl<R: Read + Seek> ReadBox<&mut R> for TfhdBox {
71+ fn read_box(reader: &mut R, size: u64) -> Result<Self> {
72+ let start = box_start(reader)?;
73+
74+ let (version, flags) = read_box_header_ext(reader)?;
75+ let track_id = reader.read_u32::<BigEndian>()?;
76+ let base_data_offset = if TfhdBox::FLAG_BASE_DATA_OFFSET & flags > 0 {
77+ Some(reader.read_u64::<BigEndian>()?)
78+ } else {
79+ None
80+ };
81+ let sample_description_index = if TfhdBox::FLAG_SAMPLE_DESCRIPTION_INDEX & flags > 0 {
82+ Some(reader.read_u32::<BigEndian>()?)
83+ } else {
84+ None
85+ };
86+ let default_sample_duration = if TfhdBox::FLAG_DEFAULT_SAMPLE_DURATION & flags > 0 {
87+ Some(reader.read_u32::<BigEndian>()?)
88+ } else {
89+ None
90+ };
91+ let default_sample_size = if TfhdBox::FLAG_DEFAULT_SAMPLE_SIZE & flags > 0 {
92+ Some(reader.read_u32::<BigEndian>()?)
93+ } else {
94+ None
95+ };
96+ let default_sample_flags = if TfhdBox::FLAG_DEFAULT_SAMPLE_FLAGS & flags > 0 {
97+ Some(reader.read_u32::<BigEndian>()?)
98+ } else {
99+ None
100+ };
101+
102+ skip_bytes_to(reader, start + size)?;
103+
104+ Ok(TfhdBox {
105+ version,
106+ flags,
107+ track_id,
108+ base_data_offset,
109+ sample_description_index,
110+ default_sample_duration,
111+ default_sample_size,
112+ default_sample_flags,
113+ })
114+ }
115+}
116+
117+impl<W: Write> WriteBox<&mut W> for TfhdBox {
118+ fn write_box(&self, writer: &mut W) -> Result<u64> {
119+ let size = self.box_size();
120+ BoxHeader::new(self.box_type(), size).write(writer)?;
121+
122+ write_box_header_ext(writer, self.version, self.flags)?;
123+ writer.write_u32::<BigEndian>(self.track_id)?;
124+ if let Some(base_data_offset) = self.base_data_offset {
125+ writer.write_u64::<BigEndian>(base_data_offset)?;
126+ }
127+ if let Some(sample_description_index) = self.sample_description_index {
128+ writer.write_u32::<BigEndian>(sample_description_index)?;
129+ }
130+ if let Some(default_sample_duration) = self.default_sample_duration {
131+ writer.write_u32::<BigEndian>(default_sample_duration)?;
132+ }
133+ if let Some(default_sample_size) = self.default_sample_size {
134+ writer.write_u32::<BigEndian>(default_sample_size)?;
135+ }
136+ if let Some(default_sample_flags) = self.default_sample_flags {
137+ writer.write_u32::<BigEndian>(default_sample_flags)?;
138+ }
139+
140+ Ok(size)
141+ }
142+}
143+
144+#[cfg(test)]
145+mod tests {
146+ use super::*;
147+ use crate::mp4box::BoxHeader;
148+ use std::io::Cursor;
149+
150+ #[test]
151+ fn test_tfhd() {
152+ let src_box = TfhdBox {
153+ version: 0,
154+ flags: 0,
155+ track_id: 1,
156+ base_data_offset: None,
157+ sample_description_index: None,
158+ default_sample_duration: None,
159+ default_sample_size: None,
160+ default_sample_flags: None,
161+ };
162+ let mut buf = Vec::new();
163+ src_box.write_box(&mut buf).unwrap();
164+ assert_eq!(buf.len(), src_box.box_size() as usize);
165+
166+ let mut reader = Cursor::new(&buf);
167+ let header = BoxHeader::read(&mut reader).unwrap();
168+ assert_eq!(header.name, BoxType::TfhdBox);
169+ assert_eq!(src_box.box_size(), header.size);
170+
171+ let dst_box = TfhdBox::read_box(&mut reader, header.size).unwrap();
172+ assert_eq!(src_box, dst_box);
173+ }
174+
175+ #[test]
176+ fn test_tfhd_with_flags() {
177+ let src_box = TfhdBox {
178+ version: 0,
179+ flags: TfhdBox::FLAG_SAMPLE_DESCRIPTION_INDEX
180+ | TfhdBox::FLAG_DEFAULT_SAMPLE_DURATION
181+ | TfhdBox::FLAG_DEFAULT_SAMPLE_FLAGS,
182+ track_id: 1,
183+ base_data_offset: None,
184+ sample_description_index: Some(1),
185+ default_sample_duration: Some(512),
186+ default_sample_size: None,
187+ default_sample_flags: Some(0x1010000),
188+ };
189+ let mut buf = Vec::new();
190+ src_box.write_box(&mut buf).unwrap();
191+ assert_eq!(buf.len(), src_box.box_size() as usize);
192+
193+ let mut reader = Cursor::new(&buf);
194+ let header = BoxHeader::read(&mut reader).unwrap();
195+ assert_eq!(header.name, BoxType::TfhdBox);
196+ assert_eq!(src_box.box_size(), header.size);
197+
198+ let dst_box = TfhdBox::read_box(&mut reader, header.size).unwrap();
199+ assert_eq!(src_box, dst_box);
200+ }
201+}
vendor/mp4/src/mp4box/tkhd.rsadded+323 -0
@@ -0,0 +1,323 @@
1+use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
2+use serde::Serialize;
3+use std::io::{Read, Seek, Write};
4+
5+use crate::mp4box::*;
6+
7+pub enum TrackFlag {
8+ TrackEnabled = 0x000001,
9+ // TrackInMovie = 0x000002,
10+ // TrackInPreview = 0x000004,
11+}
12+
13+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
14+pub struct TkhdBox {
15+ pub version: u8,
16+ pub flags: u32,
17+ pub creation_time: u64,
18+ pub modification_time: u64,
19+ pub track_id: u32,
20+ pub duration: u64,
21+ pub layer: u16,
22+ pub alternate_group: u16,
23+
24+ #[serde(with = "value_u8")]
25+ pub volume: FixedPointU8,
26+ pub matrix: Matrix,
27+
28+ #[serde(with = "value_u32")]
29+ pub width: FixedPointU16,
30+
31+ #[serde(with = "value_u32")]
32+ pub height: FixedPointU16,
33+}
34+
35+impl Default for TkhdBox {
36+ fn default() -> Self {
37+ TkhdBox {
38+ version: 0,
39+ flags: TrackFlag::TrackEnabled as u32,
40+ creation_time: 0,
41+ modification_time: 0,
42+ track_id: 0,
43+ duration: 0,
44+ layer: 0,
45+ alternate_group: 0,
46+ volume: FixedPointU8::new(1),
47+ matrix: Matrix::default(),
48+ width: FixedPointU16::new(0),
49+ height: FixedPointU16::new(0),
50+ }
51+ }
52+}
53+
54+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
55+pub struct Matrix {
56+ pub a: i32,
57+ pub b: i32,
58+ pub u: i32,
59+ pub c: i32,
60+ pub d: i32,
61+ pub v: i32,
62+ pub x: i32,
63+ pub y: i32,
64+ pub w: i32,
65+}
66+
67+impl std::fmt::Display for Matrix {
68+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
69+ write!(
70+ f,
71+ "{:#x} {:#x} {:#x} {:#x} {:#x} {:#x} {:#x} {:#x} {:#x}",
72+ self.a, self.b, self.u, self.c, self.d, self.v, self.x, self.y, self.w
73+ )
74+ }
75+}
76+
77+impl Default for Matrix {
78+ fn default() -> Self {
79+ Self {
80+ // unity matrix according to ISO/IEC 14496-12:2005(E)
81+ a: 0x00010000,
82+ b: 0,
83+ u: 0,
84+ c: 0,
85+ d: 0x00010000,
86+ v: 0,
87+ x: 0,
88+ y: 0,
89+ w: 0x40000000,
90+ }
91+ }
92+}
93+
94+impl TkhdBox {
95+ pub fn get_type(&self) -> BoxType {
96+ BoxType::TkhdBox
97+ }
98+
99+ pub fn get_size(&self) -> u64 {
100+ let mut size = HEADER_SIZE + HEADER_EXT_SIZE;
101+ if self.version == 1 {
102+ size += 32;
103+ } else if self.version == 0 {
104+ size += 20;
105+ }
106+ size += 60;
107+ size
108+ }
109+
110+ pub fn set_width(&mut self, width: u16) {
111+ self.width = FixedPointU16::new(width);
112+ }
113+
114+ pub fn set_height(&mut self, height: u16) {
115+ self.height = FixedPointU16::new(height);
116+ }
117+}
118+
119+impl Mp4Box for TkhdBox {
120+ fn box_type(&self) -> BoxType {
121+ self.get_type()
122+ }
123+
124+ fn box_size(&self) -> u64 {
125+ self.get_size()
126+ }
127+
128+ fn to_json(&self) -> Result<String> {
129+ Ok(serde_json::to_string(&self).unwrap())
130+ }
131+
132+ fn summary(&self) -> Result<String> {
133+ let s = format!(
134+ "creation_time={} track_id={} duration={} layer={} volume={} matrix={} width={} height={}",
135+ self.creation_time,
136+ self.track_id,
137+ self.duration,
138+ self.layer,
139+ self.volume.value(),
140+ self.matrix,
141+ self.width.value(),
142+ self.height.value()
143+ );
144+ Ok(s)
145+ }
146+}
147+
148+impl<R: Read + Seek> ReadBox<&mut R> for TkhdBox {
149+ fn read_box(reader: &mut R, size: u64) -> Result<Self> {
150+ let start = box_start(reader)?;
151+
152+ let (version, flags) = read_box_header_ext(reader)?;
153+
154+ let (creation_time, modification_time, track_id, _, duration) = if version == 1 {
155+ (
156+ reader.read_u64::<BigEndian>()?,
157+ reader.read_u64::<BigEndian>()?,
158+ reader.read_u32::<BigEndian>()?,
159+ reader.read_u32::<BigEndian>()?,
160+ reader.read_u64::<BigEndian>()?,
161+ )
162+ } else if version == 0 {
163+ (
164+ reader.read_u32::<BigEndian>()? as u64,
165+ reader.read_u32::<BigEndian>()? as u64,
166+ reader.read_u32::<BigEndian>()?,
167+ reader.read_u32::<BigEndian>()?,
168+ reader.read_u32::<BigEndian>()? as u64,
169+ )
170+ } else {
171+ return Err(Error::InvalidData("version must be 0 or 1"));
172+ };
173+ reader.read_u64::<BigEndian>()?; // reserved
174+ let layer = reader.read_u16::<BigEndian>()?;
175+ let alternate_group = reader.read_u16::<BigEndian>()?;
176+ let volume = FixedPointU8::new_raw(reader.read_u16::<BigEndian>()?);
177+
178+ reader.read_u16::<BigEndian>()?; // reserved
179+ let matrix = Matrix {
180+ a: reader.read_i32::<BigEndian>()?,
181+ b: reader.read_i32::<BigEndian>()?,
182+ u: reader.read_i32::<BigEndian>()?,
183+ c: reader.read_i32::<BigEndian>()?,
184+ d: reader.read_i32::<BigEndian>()?,
185+ v: reader.read_i32::<BigEndian>()?,
186+ x: reader.read_i32::<BigEndian>()?,
187+ y: reader.read_i32::<BigEndian>()?,
188+ w: reader.read_i32::<BigEndian>()?,
189+ };
190+
191+ let width = FixedPointU16::new_raw(reader.read_u32::<BigEndian>()?);
192+ let height = FixedPointU16::new_raw(reader.read_u32::<BigEndian>()?);
193+
194+ skip_bytes_to(reader, start + size)?;
195+
196+ Ok(TkhdBox {
197+ version,
198+ flags,
199+ creation_time,
200+ modification_time,
201+ track_id,
202+ duration,
203+ layer,
204+ alternate_group,
205+ volume,
206+ matrix,
207+ width,
208+ height,
209+ })
210+ }
211+}
212+
213+impl<W: Write> WriteBox<&mut W> for TkhdBox {
214+ fn write_box(&self, writer: &mut W) -> Result<u64> {
215+ let size = self.box_size();
216+ BoxHeader::new(self.box_type(), size).write(writer)?;
217+
218+ write_box_header_ext(writer, self.version, self.flags)?;
219+
220+ if self.version == 1 {
221+ writer.write_u64::<BigEndian>(self.creation_time)?;
222+ writer.write_u64::<BigEndian>(self.modification_time)?;
223+ writer.write_u32::<BigEndian>(self.track_id)?;
224+ writer.write_u32::<BigEndian>(0)?; // reserved
225+ writer.write_u64::<BigEndian>(self.duration)?;
226+ } else if self.version == 0 {
227+ writer.write_u32::<BigEndian>(self.creation_time as u32)?;
228+ writer.write_u32::<BigEndian>(self.modification_time as u32)?;
229+ writer.write_u32::<BigEndian>(self.track_id)?;
230+ writer.write_u32::<BigEndian>(0)?; // reserved
231+ writer.write_u32::<BigEndian>(self.duration as u32)?;
232+ } else {
233+ return Err(Error::InvalidData("version must be 0 or 1"));
234+ }
235+
236+ writer.write_u64::<BigEndian>(0)?; // reserved
237+ writer.write_u16::<BigEndian>(self.layer)?;
238+ writer.write_u16::<BigEndian>(self.alternate_group)?;
239+ writer.write_u16::<BigEndian>(self.volume.raw_value())?;
240+
241+ writer.write_u16::<BigEndian>(0)?; // reserved
242+
243+ writer.write_i32::<BigEndian>(self.matrix.a)?;
244+ writer.write_i32::<BigEndian>(self.matrix.b)?;
245+ writer.write_i32::<BigEndian>(self.matrix.u)?;
246+ writer.write_i32::<BigEndian>(self.matrix.c)?;
247+ writer.write_i32::<BigEndian>(self.matrix.d)?;
248+ writer.write_i32::<BigEndian>(self.matrix.v)?;
249+ writer.write_i32::<BigEndian>(self.matrix.x)?;
250+ writer.write_i32::<BigEndian>(self.matrix.y)?;
251+ writer.write_i32::<BigEndian>(self.matrix.w)?;
252+
253+ writer.write_u32::<BigEndian>(self.width.raw_value())?;
254+ writer.write_u32::<BigEndian>(self.height.raw_value())?;
255+
256+ Ok(size)
257+ }
258+}
259+
260+#[cfg(test)]
261+mod tests {
262+ use super::*;
263+ use crate::mp4box::BoxHeader;
264+ use std::io::Cursor;
265+
266+ #[test]
267+ fn test_tkhd32() {
268+ let src_box = TkhdBox {
269+ version: 0,
270+ flags: TrackFlag::TrackEnabled as u32,
271+ creation_time: 100,
272+ modification_time: 200,
273+ track_id: 1,
274+ duration: 634634,
275+ layer: 0,
276+ alternate_group: 0,
277+ volume: FixedPointU8::new(1),
278+ matrix: Matrix::default(),
279+ width: FixedPointU16::new(512),
280+ height: FixedPointU16::new(288),
281+ };
282+ let mut buf = Vec::new();
283+ src_box.write_box(&mut buf).unwrap();
284+ assert_eq!(buf.len(), src_box.box_size() as usize);
285+
286+ let mut reader = Cursor::new(&buf);
287+ let header = BoxHeader::read(&mut reader).unwrap();
288+ assert_eq!(header.name, BoxType::TkhdBox);
289+ assert_eq!(src_box.box_size(), header.size);
290+
291+ let dst_box = TkhdBox::read_box(&mut reader, header.size).unwrap();
292+ assert_eq!(src_box, dst_box);
293+ }
294+
295+ #[test]
296+ fn test_tkhd64() {
297+ let src_box = TkhdBox {
298+ version: 1,
299+ flags: TrackFlag::TrackEnabled as u32,
300+ creation_time: 100,
301+ modification_time: 200,
302+ track_id: 1,
303+ duration: 634634,
304+ layer: 0,
305+ alternate_group: 0,
306+ volume: FixedPointU8::new(1),
307+ matrix: Matrix::default(),
308+ width: FixedPointU16::new(512),
309+ height: FixedPointU16::new(288),
310+ };
311+ let mut buf = Vec::new();
312+ src_box.write_box(&mut buf).unwrap();
313+ assert_eq!(buf.len(), src_box.box_size() as usize);
314+
315+ let mut reader = Cursor::new(&buf);
316+ let header = BoxHeader::read(&mut reader).unwrap();
317+ assert_eq!(header.name, BoxType::TkhdBox);
318+ assert_eq!(src_box.box_size(), header.size);
319+
320+ let dst_box = TkhdBox::read_box(&mut reader, header.size).unwrap();
321+ assert_eq!(src_box, dst_box);
322+ }
323+}
vendor/mp4/src/mp4box/traf.rsadded+110 -0
@@ -0,0 +1,110 @@
1+use serde::Serialize;
2+use std::io::{Read, Seek, Write};
3+
4+use crate::mp4box::*;
5+use crate::mp4box::{tfdt::TfdtBox, tfhd::TfhdBox, trun::TrunBox};
6+
7+#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize)]
8+pub struct TrafBox {
9+ pub tfhd: TfhdBox,
10+ pub tfdt: Option<TfdtBox>,
11+ pub trun: Option<TrunBox>,
12+}
13+
14+impl TrafBox {
15+ pub fn get_type(&self) -> BoxType {
16+ BoxType::TrafBox
17+ }
18+
19+ pub fn get_size(&self) -> u64 {
20+ let mut size = HEADER_SIZE;
21+ size += self.tfhd.box_size();
22+ if let Some(ref trun) = self.trun {
23+ size += trun.box_size();
24+ }
25+ size
26+ }
27+}
28+
29+impl Mp4Box for TrafBox {
30+ fn box_type(&self) -> BoxType {
31+ self.get_type()
32+ }
33+
34+ fn box_size(&self) -> u64 {
35+ self.get_size()
36+ }
37+
38+ fn to_json(&self) -> Result<String> {
39+ Ok(serde_json::to_string(&self).unwrap())
40+ }
41+
42+ fn summary(&self) -> Result<String> {
43+ let s = String::new();
44+ Ok(s)
45+ }
46+}
47+
48+impl<R: Read + Seek> ReadBox<&mut R> for TrafBox {
49+ fn read_box(reader: &mut R, size: u64) -> Result<Self> {
50+ let start = box_start(reader)?;
51+
52+ let mut tfhd = None;
53+ let mut tfdt = None;
54+ let mut trun = None;
55+
56+ let mut current = reader.stream_position()?;
57+ let end = start + size;
58+ while current < end {
59+ // Get box header.
60+ let header = BoxHeader::read(reader)?;
61+ let BoxHeader { name, size: s } = header;
62+ if s > size {
63+ return Err(Error::InvalidData(
64+ "traf box contains a box with a larger size than it",
65+ ));
66+ }
67+
68+ match name {
69+ BoxType::TfhdBox => {
70+ tfhd = Some(TfhdBox::read_box(reader, s)?);
71+ }
72+ BoxType::TfdtBox => {
73+ tfdt = Some(TfdtBox::read_box(reader, s)?);
74+ }
75+ BoxType::TrunBox => {
76+ trun = Some(TrunBox::read_box(reader, s)?);
77+ }
78+ _ => {
79+ // XXX warn!()
80+ skip_box(reader, s)?;
81+ }
82+ }
83+
84+ current = reader.stream_position()?;
85+ }
86+
87+ if tfhd.is_none() {
88+ return Err(Error::BoxNotFound(BoxType::TfhdBox));
89+ }
90+
91+ skip_bytes_to(reader, start + size)?;
92+
93+ Ok(TrafBox {
94+ tfhd: tfhd.unwrap(),
95+ tfdt,
96+ trun,
97+ })
98+ }
99+}
100+
101+impl<W: Write> WriteBox<&mut W> for TrafBox {
102+ fn write_box(&self, writer: &mut W) -> Result<u64> {
103+ let size = self.box_size();
104+ BoxHeader::new(self.box_type(), size).write(writer)?;
105+
106+ self.tfhd.write_box(writer)?;
107+
108+ Ok(size)
109+ }
110+}
vendor/mp4/src/mp4box/trak.rsadded+130 -0
@@ -0,0 +1,130 @@
1+use serde::Serialize;
2+use std::io::{Read, Seek, Write};
3+
4+use crate::meta::MetaBox;
5+use crate::mp4box::*;
6+use crate::mp4box::{edts::EdtsBox, mdia::MdiaBox, tkhd::TkhdBox};
7+
8+#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize)]
9+pub struct TrakBox {
10+ pub tkhd: TkhdBox,
11+
12+ #[serde(skip_serializing_if = "Option::is_none")]
13+ pub edts: Option<EdtsBox>,
14+
15+ #[serde(skip_serializing_if = "Option::is_none")]
16+ pub meta: Option<MetaBox>,
17+
18+ pub mdia: MdiaBox,
19+}
20+
21+impl TrakBox {
22+ pub fn get_type(&self) -> BoxType {
23+ BoxType::TrakBox
24+ }
25+
26+ pub fn get_size(&self) -> u64 {
27+ let mut size = HEADER_SIZE;
28+ size += self.tkhd.box_size();
29+ if let Some(ref edts) = self.edts {
30+ size += edts.box_size();
31+ }
32+ size += self.mdia.box_size();
33+ size
34+ }
35+}
36+
37+impl Mp4Box for TrakBox {
38+ fn box_type(&self) -> BoxType {
39+ self.get_type()
40+ }
41+
42+ fn box_size(&self) -> u64 {
43+ self.get_size()
44+ }
45+
46+ fn to_json(&self) -> Result<String> {
47+ Ok(serde_json::to_string(&self).unwrap())
48+ }
49+
50+ fn summary(&self) -> Result<String> {
51+ let s = String::new();
52+ Ok(s)
53+ }
54+}
55+
56+impl<R: Read + Seek> ReadBox<&mut R> for TrakBox {
57+ fn read_box(reader: &mut R, size: u64) -> Result<Self> {
58+ let start = box_start(reader)?;
59+
60+ let mut tkhd = None;
61+ let mut edts = None;
62+ let mut meta = None;
63+ let mut mdia = None;
64+
65+ let mut current = reader.stream_position()?;
66+ let end = start + size;
67+ while current < end {
68+ // Get box header.
69+ let header = BoxHeader::read(reader)?;
70+ let BoxHeader { name, size: s } = header;
71+ if s > size {
72+ return Err(Error::InvalidData(
73+ "trak box contains a box with a larger size than it",
74+ ));
75+ }
76+
77+ match name {
78+ BoxType::TkhdBox => {
79+ tkhd = Some(TkhdBox::read_box(reader, s)?);
80+ }
81+ BoxType::EdtsBox => {
82+ edts = Some(EdtsBox::read_box(reader, s)?);
83+ }
84+ BoxType::MetaBox => {
85+ meta = Some(MetaBox::read_box(reader, s)?);
86+ }
87+ BoxType::MdiaBox => {
88+ mdia = Some(MdiaBox::read_box(reader, s)?);
89+ }
90+ _ => {
91+ // XXX warn!()
92+ skip_box(reader, s)?;
93+ }
94+ }
95+
96+ current = reader.stream_position()?;
97+ }
98+
99+ if tkhd.is_none() {
100+ return Err(Error::BoxNotFound(BoxType::TkhdBox));
101+ }
102+ if mdia.is_none() {
103+ return Err(Error::BoxNotFound(BoxType::MdiaBox));
104+ }
105+
106+ skip_bytes_to(reader, start + size)?;
107+
108+ Ok(TrakBox {
109+ tkhd: tkhd.unwrap(),
110+ edts,
111+ meta,
112+ mdia: mdia.unwrap(),
113+ })
114+ }
115+}
116+
117+impl<W: Write> WriteBox<&mut W> for TrakBox {
118+ fn write_box(&self, writer: &mut W) -> Result<u64> {
119+ let size = self.box_size();
120+ BoxHeader::new(self.box_type(), size).write(writer)?;
121+
122+ self.tkhd.write_box(writer)?;
123+ if let Some(ref edts) = self.edts {
124+ edts.write_box(writer)?;
125+ }
126+ self.mdia.write_box(writer)?;
127+
128+ Ok(size)
129+ }
130+}
vendor/mp4/src/mp4box/trex.rsadded+122 -0
@@ -0,0 +1,122 @@
1+use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
2+use serde::Serialize;
3+use std::io::{Read, Seek, Write};
4+
5+use crate::mp4box::*;
6+
7+#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize)]
8+pub struct TrexBox {
9+ pub version: u8,
10+ pub flags: u32,
11+ pub track_id: u32,
12+ pub default_sample_description_index: u32,
13+ pub default_sample_duration: u32,
14+ pub default_sample_size: u32,
15+ pub default_sample_flags: u32,
16+}
17+
18+impl TrexBox {
19+ pub fn get_type(&self) -> BoxType {
20+ BoxType::TrexBox
21+ }
22+
23+ pub fn get_size(&self) -> u64 {
24+ HEADER_SIZE + HEADER_EXT_SIZE + 20
25+ }
26+}
27+
28+impl Mp4Box for TrexBox {
29+ fn box_type(&self) -> BoxType {
30+ self.get_type()
31+ }
32+
33+ fn box_size(&self) -> u64 {
34+ self.get_size()
35+ }
36+
37+ fn to_json(&self) -> Result<String> {
38+ Ok(serde_json::to_string(&self).unwrap())
39+ }
40+
41+ fn summary(&self) -> Result<String> {
42+ let s = format!(
43+ "track_id={} default_sample_duration={}",
44+ self.track_id, self.default_sample_duration
45+ );
46+ Ok(s)
47+ }
48+}
49+
50+impl<R: Read + Seek> ReadBox<&mut R> for TrexBox {
51+ fn read_box(reader: &mut R, size: u64) -> Result<Self> {
52+ let start = box_start(reader)?;
53+
54+ let (version, flags) = read_box_header_ext(reader)?;
55+
56+ let track_id = reader.read_u32::<BigEndian>()?;
57+ let default_sample_description_index = reader.read_u32::<BigEndian>()?;
58+ let default_sample_duration = reader.read_u32::<BigEndian>()?;
59+ let default_sample_size = reader.read_u32::<BigEndian>()?;
60+ let default_sample_flags = reader.read_u32::<BigEndian>()?;
61+
62+ skip_bytes_to(reader, start + size)?;
63+
64+ Ok(TrexBox {
65+ version,
66+ flags,
67+ track_id,
68+ default_sample_description_index,
69+ default_sample_duration,
70+ default_sample_size,
71+ default_sample_flags,
72+ })
73+ }
74+}
75+
76+impl<W: Write> WriteBox<&mut W> for TrexBox {
77+ fn write_box(&self, writer: &mut W) -> Result<u64> {
78+ let size = self.box_size();
79+ BoxHeader::new(self.box_type(), size).write(writer)?;
80+
81+ write_box_header_ext(writer, self.version, self.flags)?;
82+
83+ writer.write_u32::<BigEndian>(self.track_id)?;
84+ writer.write_u32::<BigEndian>(self.default_sample_description_index)?;
85+ writer.write_u32::<BigEndian>(self.default_sample_duration)?;
86+ writer.write_u32::<BigEndian>(self.default_sample_size)?;
87+ writer.write_u32::<BigEndian>(self.default_sample_flags)?;
88+
89+ Ok(size)
90+ }
91+}
92+
93+#[cfg(test)]
94+mod tests {
95+ use super::*;
96+ use crate::mp4box::BoxHeader;
97+ use std::io::Cursor;
98+
99+ #[test]
100+ fn test_trex() {
101+ let src_box = TrexBox {
102+ version: 0,
103+ flags: 0,
104+ track_id: 1,
105+ default_sample_description_index: 1,
106+ default_sample_duration: 1000,
107+ default_sample_size: 0,
108+ default_sample_flags: 65536,
109+ };
110+ let mut buf = Vec::new();
111+ src_box.write_box(&mut buf).unwrap();
112+ assert_eq!(buf.len(), src_box.box_size() as usize);
113+
114+ let mut reader = Cursor::new(&buf);
115+ let header = BoxHeader::read(&mut reader).unwrap();
116+ assert_eq!(header.name, BoxType::TrexBox);
117+ assert_eq!(src_box.box_size(), header.size);
118+
119+ let dst_box = TrexBox::read_box(&mut reader, header.size).unwrap();
120+ assert_eq!(src_box, dst_box);
121+ }
122+}
vendor/mp4/src/mp4box/trun.rsadded+270 -0
@@ -0,0 +1,270 @@
1+use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
2+use serde::Serialize;
3+use std::io::{Read, Seek, Write};
4+use std::mem::size_of;
5+
6+use crate::mp4box::*;
7+
8+#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize)]
9+pub struct TrunBox {
10+ pub version: u8,
11+ pub flags: u32,
12+ pub sample_count: u32,
13+ pub data_offset: Option<i32>,
14+ pub first_sample_flags: Option<u32>,
15+
16+ #[serde(skip_serializing)]
17+ pub sample_durations: Vec<u32>,
18+ #[serde(skip_serializing)]
19+ pub sample_sizes: Vec<u32>,
20+ #[serde(skip_serializing)]
21+ pub sample_flags: Vec<u32>,
22+ #[serde(skip_serializing)]
23+ pub sample_cts: Vec<u32>,
24+}
25+
26+impl TrunBox {
27+ pub const FLAG_DATA_OFFSET: u32 = 0x01;
28+ pub const FLAG_FIRST_SAMPLE_FLAGS: u32 = 0x04;
29+ pub const FLAG_SAMPLE_DURATION: u32 = 0x100;
30+ pub const FLAG_SAMPLE_SIZE: u32 = 0x200;
31+ pub const FLAG_SAMPLE_FLAGS: u32 = 0x400;
32+ pub const FLAG_SAMPLE_CTS: u32 = 0x800;
33+
34+ pub fn get_type(&self) -> BoxType {
35+ BoxType::TrunBox
36+ }
37+
38+ pub fn get_size(&self) -> u64 {
39+ let mut sum = HEADER_SIZE + HEADER_EXT_SIZE + 4;
40+ if TrunBox::FLAG_DATA_OFFSET & self.flags > 0 {
41+ sum += 4;
42+ }
43+ if TrunBox::FLAG_FIRST_SAMPLE_FLAGS & self.flags > 0 {
44+ sum += 4;
45+ }
46+ if TrunBox::FLAG_SAMPLE_DURATION & self.flags > 0 {
47+ sum += 4 * self.sample_count as u64;
48+ }
49+ if TrunBox::FLAG_SAMPLE_SIZE & self.flags > 0 {
50+ sum += 4 * self.sample_count as u64;
51+ }
52+ if TrunBox::FLAG_SAMPLE_FLAGS & self.flags > 0 {
53+ sum += 4 * self.sample_count as u64;
54+ }
55+ if TrunBox::FLAG_SAMPLE_CTS & self.flags > 0 {
56+ sum += 4 * self.sample_count as u64;
57+ }
58+ sum
59+ }
60+}
61+
62+impl Mp4Box for TrunBox {
63+ fn box_type(&self) -> BoxType {
64+ self.get_type()
65+ }
66+
67+ fn box_size(&self) -> u64 {
68+ self.get_size()
69+ }
70+
71+ fn to_json(&self) -> Result<String> {
72+ Ok(serde_json::to_string(&self).unwrap())
73+ }
74+
75+ fn summary(&self) -> Result<String> {
76+ let s = format!("sample_size={}", self.sample_count);
77+ Ok(s)
78+ }
79+}
80+
81+impl<R: Read + Seek> ReadBox<&mut R> for TrunBox {
82+ fn read_box(reader: &mut R, size: u64) -> Result<Self> {
83+ let start = box_start(reader)?;
84+
85+ let (version, flags) = read_box_header_ext(reader)?;
86+
87+ let header_size = HEADER_SIZE + HEADER_EXT_SIZE;
88+ let other_size = size_of::<u32>() // sample_count
89+ + if TrunBox::FLAG_DATA_OFFSET & flags > 0 { size_of::<i32>() } else { 0 } // data_offset
90+ + if TrunBox::FLAG_FIRST_SAMPLE_FLAGS & flags > 0 { size_of::<u32>() } else { 0 }; // first_sample_flags
91+ let sample_size = if TrunBox::FLAG_SAMPLE_DURATION & flags > 0 { size_of::<u32>() } else { 0 } // sample_duration
92+ + if TrunBox::FLAG_SAMPLE_SIZE & flags > 0 { size_of::<u32>() } else { 0 } // sample_size
93+ + if TrunBox::FLAG_SAMPLE_FLAGS & flags > 0 { size_of::<u32>() } else { 0 } // sample_flags
94+ + if TrunBox::FLAG_SAMPLE_CTS & flags > 0 { size_of::<u32>() } else { 0 }; // sample_composition_time_offset
95+
96+ let sample_count = reader.read_u32::<BigEndian>()?;
97+
98+ let data_offset = if TrunBox::FLAG_DATA_OFFSET & flags > 0 {
99+ Some(reader.read_i32::<BigEndian>()?)
100+ } else {
101+ None
102+ };
103+
104+ let first_sample_flags = if TrunBox::FLAG_FIRST_SAMPLE_FLAGS & flags > 0 {
105+ Some(reader.read_u32::<BigEndian>()?)
106+ } else {
107+ None
108+ };
109+
110+ let mut sample_durations = Vec::new();
111+ let mut sample_sizes = Vec::new();
112+ let mut sample_flags = Vec::new();
113+ let mut sample_cts = Vec::new();
114+ if u64::from(sample_count) * sample_size as u64
115+ > size
116+ .saturating_sub(header_size)
117+ .saturating_sub(other_size as u64)
118+ {
119+ return Err(Error::InvalidData(
120+ "trun sample_count indicates more values than could fit in the box",
121+ ));
122+ }
123+ if TrunBox::FLAG_SAMPLE_DURATION & flags > 0 {
124+ sample_durations.reserve(sample_count as usize);
125+ }
126+ if TrunBox::FLAG_SAMPLE_SIZE & flags > 0 {
127+ sample_sizes.reserve(sample_count as usize);
128+ }
129+ if TrunBox::FLAG_SAMPLE_FLAGS & flags > 0 {
130+ sample_flags.reserve(sample_count as usize);
131+ }
132+ if TrunBox::FLAG_SAMPLE_CTS & flags > 0 {
133+ sample_cts.reserve(sample_count as usize);
134+ }
135+
136+ for _ in 0..sample_count {
137+ if TrunBox::FLAG_SAMPLE_DURATION & flags > 0 {
138+ let duration = reader.read_u32::<BigEndian>()?;
139+ sample_durations.push(duration);
140+ }
141+
142+ if TrunBox::FLAG_SAMPLE_SIZE & flags > 0 {
143+ let sample_size = reader.read_u32::<BigEndian>()?;
144+ sample_sizes.push(sample_size);
145+ }
146+
147+ if TrunBox::FLAG_SAMPLE_FLAGS & flags > 0 {
148+ let sample_flag = reader.read_u32::<BigEndian>()?;
149+ sample_flags.push(sample_flag);
150+ }
151+
152+ if TrunBox::FLAG_SAMPLE_CTS & flags > 0 {
153+ let cts = reader.read_u32::<BigEndian>()?;
154+ sample_cts.push(cts);
155+ }
156+ }
157+
158+ skip_bytes_to(reader, start + size)?;
159+
160+ Ok(TrunBox {
161+ version,
162+ flags,
163+ sample_count,
164+ data_offset,
165+ first_sample_flags,
166+ sample_durations,
167+ sample_sizes,
168+ sample_flags,
169+ sample_cts,
170+ })
171+ }
172+}
173+
174+impl<W: Write> WriteBox<&mut W> for TrunBox {
175+ fn write_box(&self, writer: &mut W) -> Result<u64> {
176+ let size = self.box_size();
177+ BoxHeader::new(self.box_type(), size).write(writer)?;
178+
179+ write_box_header_ext(writer, self.version, self.flags)?;
180+
181+ writer.write_u32::<BigEndian>(self.sample_count)?;
182+ if let Some(v) = self.data_offset {
183+ writer.write_i32::<BigEndian>(v)?;
184+ }
185+ if let Some(v) = self.first_sample_flags {
186+ writer.write_u32::<BigEndian>(v)?;
187+ }
188+ if self.sample_count != self.sample_sizes.len() as u32 {
189+ return Err(Error::InvalidData("sample count out of sync"));
190+ }
191+ for i in 0..self.sample_count as usize {
192+ if TrunBox::FLAG_SAMPLE_DURATION & self.flags > 0 {
193+ writer.write_u32::<BigEndian>(self.sample_durations[i])?;
194+ }
195+ if TrunBox::FLAG_SAMPLE_SIZE & self.flags > 0 {
196+ writer.write_u32::<BigEndian>(self.sample_sizes[i])?;
197+ }
198+ if TrunBox::FLAG_SAMPLE_FLAGS & self.flags > 0 {
199+ writer.write_u32::<BigEndian>(self.sample_flags[i])?;
200+ }
201+ if TrunBox::FLAG_SAMPLE_CTS & self.flags > 0 {
202+ writer.write_u32::<BigEndian>(self.sample_cts[i])?;
203+ }
204+ }
205+
206+ Ok(size)
207+ }
208+}
209+
210+#[cfg(test)]
211+mod tests {
212+ use super::*;
213+ use crate::mp4box::BoxHeader;
214+ use std::io::Cursor;
215+
216+ #[test]
217+ fn test_trun_same_size() {
218+ let src_box = TrunBox {
219+ version: 0,
220+ flags: 0,
221+ data_offset: None,
222+ sample_count: 0,
223+ sample_sizes: vec![],
224+ sample_flags: vec![],
225+ first_sample_flags: None,
226+ sample_durations: vec![],
227+ sample_cts: vec![],
228+ };
229+ let mut buf = Vec::new();
230+ src_box.write_box(&mut buf).unwrap();
231+ assert_eq!(buf.len(), src_box.box_size() as usize);
232+
233+ let mut reader = Cursor::new(&buf);
234+ let header = BoxHeader::read(&mut reader).unwrap();
235+ assert_eq!(header.name, BoxType::TrunBox);
236+ assert_eq!(src_box.box_size(), header.size);
237+
238+ let dst_box = TrunBox::read_box(&mut reader, header.size).unwrap();
239+ assert_eq!(src_box, dst_box);
240+ }
241+
242+ #[test]
243+ fn test_trun_many_sizes() {
244+ let src_box = TrunBox {
245+ version: 0,
246+ flags: TrunBox::FLAG_SAMPLE_DURATION
247+ | TrunBox::FLAG_SAMPLE_SIZE
248+ | TrunBox::FLAG_SAMPLE_FLAGS
249+ | TrunBox::FLAG_SAMPLE_CTS,
250+ data_offset: None,
251+ sample_count: 9,
252+ sample_sizes: vec![1165, 11, 11, 8545, 10126, 10866, 9643, 9351, 7730],
253+ sample_flags: vec![1165, 11, 11, 8545, 10126, 10866, 9643, 9351, 7730],
254+ first_sample_flags: None,
255+ sample_durations: vec![1165, 11, 11, 8545, 10126, 10866, 9643, 9351, 7730],
256+ sample_cts: vec![1165, 11, 11, 8545, 10126, 10866, 9643, 9351, 7730],
257+ };
258+ let mut buf = Vec::new();
259+ src_box.write_box(&mut buf).unwrap();
260+ assert_eq!(buf.len(), src_box.box_size() as usize);
261+
262+ let mut reader = Cursor::new(&buf);
263+ let header = BoxHeader::read(&mut reader).unwrap();
264+ assert_eq!(header.name, BoxType::TrunBox);
265+ assert_eq!(src_box.box_size(), header.size);
266+
267+ let dst_box = TrunBox::read_box(&mut reader, header.size).unwrap();
268+ assert_eq!(src_box, dst_box);
269+ }
270+}
vendor/mp4/src/mp4box/tx3g.rsadded+189 -0
@@ -0,0 +1,189 @@
1+use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
2+use serde::Serialize;
3+use std::io::{Read, Seek, Write};
4+
5+use crate::mp4box::*;
6+
7+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
8+pub struct Tx3gBox {
9+ pub data_reference_index: u16,
10+ pub display_flags: u32,
11+ pub horizontal_justification: i8,
12+ pub vertical_justification: i8,
13+ pub bg_color_rgba: RgbaColor,
14+ pub box_record: [i16; 4],
15+ pub style_record: [u8; 12],
16+}
17+
18+#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize)]
19+pub struct RgbaColor {
20+ pub red: u8,
21+ pub green: u8,
22+ pub blue: u8,
23+ pub alpha: u8,
24+}
25+
26+impl Default for Tx3gBox {
27+ fn default() -> Self {
28+ Tx3gBox {
29+ data_reference_index: 0,
30+ display_flags: 0,
31+ horizontal_justification: 1,
32+ vertical_justification: -1,
33+ bg_color_rgba: RgbaColor {
34+ red: 0,
35+ green: 0,
36+ blue: 0,
37+ alpha: 255,
38+ },
39+ box_record: [0, 0, 0, 0],
40+ style_record: [0, 0, 0, 0, 0, 1, 0, 16, 255, 255, 255, 255],
41+ }
42+ }
43+}
44+
45+impl Tx3gBox {
46+ pub fn get_type(&self) -> BoxType {
47+ BoxType::Tx3gBox
48+ }
49+
50+ pub fn get_size(&self) -> u64 {
51+ HEADER_SIZE + 6 + 32
52+ }
53+}
54+
55+impl Mp4Box for Tx3gBox {
56+ fn box_type(&self) -> BoxType {
57+ self.get_type()
58+ }
59+
60+ fn box_size(&self) -> u64 {
61+ self.get_size()
62+ }
63+
64+ fn to_json(&self) -> Result<String> {
65+ Ok(serde_json::to_string(&self).unwrap())
66+ }
67+
68+ fn summary(&self) -> Result<String> {
69+ let s = format!("data_reference_index={} horizontal_justification={} vertical_justification={} rgba={}{}{}{}",
70+ self.data_reference_index, self.horizontal_justification,
71+ self.vertical_justification, self.bg_color_rgba.red,
72+ self.bg_color_rgba.green, self.bg_color_rgba.blue, self.bg_color_rgba.alpha);
73+ Ok(s)
74+ }
75+}
76+
77+impl<R: Read + Seek> ReadBox<&mut R> for Tx3gBox {
78+ fn read_box(reader: &mut R, size: u64) -> Result<Self> {
79+ let start = box_start(reader)?;
80+
81+ reader.read_u32::<BigEndian>()?; // reserved
82+ reader.read_u16::<BigEndian>()?; // reserved
83+ let data_reference_index = reader.read_u16::<BigEndian>()?;
84+
85+ let display_flags = reader.read_u32::<BigEndian>()?;
86+ let horizontal_justification = reader.read_i8()?;
87+ let vertical_justification = reader.read_i8()?;
88+ let bg_color_rgba = RgbaColor {
89+ red: reader.read_u8()?,
90+ green: reader.read_u8()?,
91+ blue: reader.read_u8()?,
92+ alpha: reader.read_u8()?,
93+ };
94+ let box_record: [i16; 4] = [
95+ reader.read_i16::<BigEndian>()?,
96+ reader.read_i16::<BigEndian>()?,
97+ reader.read_i16::<BigEndian>()?,
98+ reader.read_i16::<BigEndian>()?,
99+ ];
100+ let style_record: [u8; 12] = [
101+ reader.read_u8()?,
102+ reader.read_u8()?,
103+ reader.read_u8()?,
104+ reader.read_u8()?,
105+ reader.read_u8()?,
106+ reader.read_u8()?,
107+ reader.read_u8()?,
108+ reader.read_u8()?,
109+ reader.read_u8()?,
110+ reader.read_u8()?,
111+ reader.read_u8()?,
112+ reader.read_u8()?,
113+ ];
114+
115+ skip_bytes_to(reader, start + size)?;
116+
117+ Ok(Tx3gBox {
118+ data_reference_index,
119+ display_flags,
120+ horizontal_justification,
121+ vertical_justification,
122+ bg_color_rgba,
123+ box_record,
124+ style_record,
125+ })
126+ }
127+}
128+
129+impl<W: Write> WriteBox<&mut W> for Tx3gBox {
130+ fn write_box(&self, writer: &mut W) -> Result<u64> {
131+ let size = self.box_size();
132+ BoxHeader::new(self.box_type(), size).write(writer)?;
133+
134+ writer.write_u32::<BigEndian>(0)?; // reserved
135+ writer.write_u16::<BigEndian>(0)?; // reserved
136+ writer.write_u16::<BigEndian>(self.data_reference_index)?;
137+ writer.write_u32::<BigEndian>(self.display_flags)?;
138+ writer.write_i8(self.horizontal_justification)?;
139+ writer.write_i8(self.vertical_justification)?;
140+ writer.write_u8(self.bg_color_rgba.red)?;
141+ writer.write_u8(self.bg_color_rgba.green)?;
142+ writer.write_u8(self.bg_color_rgba.blue)?;
143+ writer.write_u8(self.bg_color_rgba.alpha)?;
144+ for n in 0..4 {
145+ writer.write_i16::<BigEndian>(self.box_record[n])?;
146+ }
147+ for n in 0..12 {
148+ writer.write_u8(self.style_record[n])?;
149+ }
150+
151+ Ok(size)
152+ }
153+}
154+
155+#[cfg(test)]
156+mod tests {
157+ use super::*;
158+ use crate::mp4box::BoxHeader;
159+ use std::io::Cursor;
160+
161+ #[test]
162+ fn test_tx3g() {
163+ let src_box = Tx3gBox {
164+ data_reference_index: 1,
165+ display_flags: 0,
166+ horizontal_justification: 1,
167+ vertical_justification: -1,
168+ bg_color_rgba: RgbaColor {
169+ red: 0,
170+ green: 0,
171+ blue: 0,
172+ alpha: 255,
173+ },
174+ box_record: [0, 0, 0, 0],
175+ style_record: [0, 0, 0, 0, 0, 1, 0, 16, 255, 255, 255, 255],
176+ };
177+ let mut buf = Vec::new();
178+ src_box.write_box(&mut buf).unwrap();
179+ assert_eq!(buf.len(), src_box.box_size() as usize);
180+
181+ let mut reader = Cursor::new(&buf);
182+ let header = BoxHeader::read(&mut reader).unwrap();
183+ assert_eq!(header.name, BoxType::Tx3gBox);
184+ assert_eq!(src_box.box_size(), header.size);
185+
186+ let dst_box = Tx3gBox::read_box(&mut reader, header.size).unwrap();
187+ assert_eq!(src_box, dst_box);
188+ }
189+}
vendor/mp4/src/mp4box/udta.rsadded+136 -0
@@ -0,0 +1,136 @@
1+use std::io::{Read, Seek};
2+
3+use serde::Serialize;
4+
5+use crate::mp4box::meta::MetaBox;
6+use crate::mp4box::*;
7+
8+#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize)]
9+pub struct UdtaBox {
10+ #[serde(skip_serializing_if = "Option::is_none")]
11+ pub meta: Option<MetaBox>,
12+}
13+
14+impl UdtaBox {
15+ pub fn get_type(&self) -> BoxType {
16+ BoxType::UdtaBox
17+ }
18+
19+ pub fn get_size(&self) -> u64 {
20+ let mut size = HEADER_SIZE;
21+ if let Some(meta) = &self.meta {
22+ size += meta.box_size();
23+ }
24+ size
25+ }
26+}
27+
28+impl Mp4Box for UdtaBox {
29+ fn box_type(&self) -> BoxType {
30+ self.get_type()
31+ }
32+
33+ fn box_size(&self) -> u64 {
34+ self.get_size()
35+ }
36+
37+ fn to_json(&self) -> Result<String> {
38+ Ok(serde_json::to_string(&self).unwrap())
39+ }
40+
41+ fn summary(&self) -> Result<String> {
42+ Ok(String::new())
43+ }
44+}
45+
46+impl<R: Read + Seek> ReadBox<&mut R> for UdtaBox {
47+ fn read_box(reader: &mut R, size: u64) -> Result<Self> {
48+ let start = box_start(reader)?;
49+
50+ let mut meta = None;
51+
52+ let mut current = reader.stream_position()?;
53+ let end = start + size;
54+ while current < end {
55+ // Get box header.
56+ let header = BoxHeader::read(reader)?;
57+ let BoxHeader { name, size: s } = header;
58+ if s > size {
59+ return Err(Error::InvalidData(
60+ "udta box contains a box with a larger size than it",
61+ ));
62+ }
63+
64+ match name {
65+ BoxType::MetaBox => {
66+ meta = Some(MetaBox::read_box(reader, s)?);
67+ }
68+ _ => {
69+ // XXX warn!()
70+ skip_box(reader, s)?;
71+ }
72+ }
73+
74+ current = reader.stream_position()?;
75+ }
76+
77+ skip_bytes_to(reader, start + size)?;
78+
79+ Ok(UdtaBox { meta })
80+ }
81+}
82+
83+impl<W: Write> WriteBox<&mut W> for UdtaBox {
84+ fn write_box(&self, writer: &mut W) -> Result<u64> {
85+ let size = self.box_size();
86+ BoxHeader::new(self.box_type(), size).write(writer)?;
87+
88+ if let Some(meta) = &self.meta {
89+ meta.write_box(writer)?;
90+ }
91+ Ok(size)
92+ }
93+}
94+
95+#[cfg(test)]
96+mod tests {
97+ use super::*;
98+ use crate::mp4box::BoxHeader;
99+ use std::io::Cursor;
100+
101+ #[test]
102+ fn test_udta_empty() {
103+ let src_box = UdtaBox { meta: None };
104+
105+ let mut buf = Vec::new();
106+ src_box.write_box(&mut buf).unwrap();
107+ assert_eq!(buf.len(), src_box.box_size() as usize);
108+
109+ let mut reader = Cursor::new(&buf);
110+ let header = BoxHeader::read(&mut reader).unwrap();
111+ assert_eq!(header.name, BoxType::UdtaBox);
112+ assert_eq!(header.size, src_box.box_size());
113+
114+ let dst_box = UdtaBox::read_box(&mut reader, header.size).unwrap();
115+ assert_eq!(dst_box, src_box);
116+ }
117+
118+ #[test]
119+ fn test_udta() {
120+ let src_box = UdtaBox {
121+ meta: Some(MetaBox::default()),
122+ };
123+
124+ let mut buf = Vec::new();
125+ src_box.write_box(&mut buf).unwrap();
126+ assert_eq!(buf.len(), src_box.box_size() as usize);
127+
128+ let mut reader = Cursor::new(&buf);
129+ let header = BoxHeader::read(&mut reader).unwrap();
130+ assert_eq!(header.name, BoxType::UdtaBox);
131+ assert_eq!(header.size, src_box.box_size());
132+
133+ let dst_box = UdtaBox::read_box(&mut reader, header.size).unwrap();
134+ assert_eq!(dst_box, src_box);
135+ }
136+}
vendor/mp4/src/mp4box/vmhd.rsadded+124 -0
@@ -0,0 +1,124 @@
1+use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
2+use serde::Serialize;
3+use std::io::{Read, Seek, Write};
4+
5+use crate::mp4box::*;
6+
7+#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize)]
8+pub struct VmhdBox {
9+ pub version: u8,
10+ pub flags: u32,
11+ pub graphics_mode: u16,
12+ pub op_color: RgbColor,
13+}
14+
15+#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize)]
16+pub struct RgbColor {
17+ pub red: u16,
18+ pub green: u16,
19+ pub blue: u16,
20+}
21+
22+impl VmhdBox {
23+ pub fn get_type(&self) -> BoxType {
24+ BoxType::VmhdBox
25+ }
26+
27+ pub fn get_size(&self) -> u64 {
28+ HEADER_SIZE + HEADER_EXT_SIZE + 8
29+ }
30+}
31+
32+impl Mp4Box for VmhdBox {
33+ fn box_type(&self) -> BoxType {
34+ self.get_type()
35+ }
36+
37+ fn box_size(&self) -> u64 {
38+ self.get_size()
39+ }
40+
41+ fn to_json(&self) -> Result<String> {
42+ Ok(serde_json::to_string(&self).unwrap())
43+ }
44+
45+ fn summary(&self) -> Result<String> {
46+ let s = format!(
47+ "graphics_mode={} op_color={}{}{}",
48+ self.graphics_mode, self.op_color.red, self.op_color.green, self.op_color.blue
49+ );
50+ Ok(s)
51+ }
52+}
53+
54+impl<R: Read + Seek> ReadBox<&mut R> for VmhdBox {
55+ fn read_box(reader: &mut R, size: u64) -> Result<Self> {
56+ let start = box_start(reader)?;
57+
58+ let (version, flags) = read_box_header_ext(reader)?;
59+
60+ let graphics_mode = reader.read_u16::<BigEndian>()?;
61+ let op_color = RgbColor {
62+ red: reader.read_u16::<BigEndian>()?,
63+ green: reader.read_u16::<BigEndian>()?,
64+ blue: reader.read_u16::<BigEndian>()?,
65+ };
66+
67+ skip_bytes_to(reader, start + size)?;
68+
69+ Ok(VmhdBox {
70+ version,
71+ flags,
72+ graphics_mode,
73+ op_color,
74+ })
75+ }
76+}
77+
78+impl<W: Write> WriteBox<&mut W> for VmhdBox {
79+ fn write_box(&self, writer: &mut W) -> Result<u64> {
80+ let size = self.box_size();
81+ BoxHeader::new(self.box_type(), size).write(writer)?;
82+
83+ write_box_header_ext(writer, self.version, self.flags)?;
84+
85+ writer.write_u16::<BigEndian>(self.graphics_mode)?;
86+ writer.write_u16::<BigEndian>(self.op_color.red)?;
87+ writer.write_u16::<BigEndian>(self.op_color.green)?;
88+ writer.write_u16::<BigEndian>(self.op_color.blue)?;
89+
90+ Ok(size)
91+ }
92+}
93+
94+#[cfg(test)]
95+mod tests {
96+ use super::*;
97+ use crate::mp4box::BoxHeader;
98+ use std::io::Cursor;
99+
100+ #[test]
101+ fn test_vmhd() {
102+ let src_box = VmhdBox {
103+ version: 0,
104+ flags: 1,
105+ graphics_mode: 0,
106+ op_color: RgbColor {
107+ red: 0,
108+ green: 0,
109+ blue: 0,
110+ },
111+ };
112+ let mut buf = Vec::new();
113+ src_box.write_box(&mut buf).unwrap();
114+ assert_eq!(buf.len(), src_box.box_size() as usize);
115+
116+ let mut reader = Cursor::new(&buf);
117+ let header = BoxHeader::read(&mut reader).unwrap();
118+ assert_eq!(header.name, BoxType::VmhdBox);
119+ assert_eq!(src_box.box_size(), header.size);
120+
121+ let dst_box = VmhdBox::read_box(&mut reader, header.size).unwrap();
122+ assert_eq!(src_box, dst_box);
123+ }
124+}
vendor/mp4/src/mp4box/vp09.rsadded+205 -0
@@ -0,0 +1,205 @@
1+use crate::mp4box::vpcc::VpccBox;
2+use crate::mp4box::*;
3+use crate::Mp4Box;
4+use serde::Serialize;
5+
6+#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize)]
7+pub struct Vp09Box {
8+ pub version: u8,
9+ pub flags: u32,
10+ pub start_code: u16,
11+ pub data_reference_index: u16,
12+ pub reserved0: [u8; 16],
13+ pub width: u16,
14+ pub height: u16,
15+ pub horizresolution: (u16, u16),
16+ pub vertresolution: (u16, u16),
17+ pub reserved1: [u8; 4],
18+ pub frame_count: u16,
19+ pub compressorname: [u8; 32],
20+ pub depth: u16,
21+ pub end_code: u16,
22+ pub vpcc: VpccBox,
23+}
24+
25+impl Vp09Box {
26+ pub const DEFAULT_START_CODE: u16 = 0;
27+ pub const DEFAULT_END_CODE: u16 = 0xFFFF;
28+ pub const DEFAULT_DATA_REFERENCE_INDEX: u16 = 1;
29+ pub const DEFAULT_HORIZRESOLUTION: (u16, u16) = (0x48, 0x00);
30+ pub const DEFAULT_VERTRESOLUTION: (u16, u16) = (0x48, 0x00);
31+ pub const DEFAULT_FRAME_COUNT: u16 = 1;
32+ pub const DEFAULT_COMPRESSORNAME: [u8; 32] = [0; 32];
33+ pub const DEFAULT_DEPTH: u16 = 24;
34+
35+ pub fn new(config: &Vp9Config) -> Self {
36+ Vp09Box {
37+ version: 0,
38+ flags: 0,
39+ start_code: Vp09Box::DEFAULT_START_CODE,
40+ data_reference_index: Vp09Box::DEFAULT_DATA_REFERENCE_INDEX,
41+ reserved0: Default::default(),
42+ width: config.width,
43+ height: config.height,
44+ horizresolution: Vp09Box::DEFAULT_HORIZRESOLUTION,
45+ vertresolution: Vp09Box::DEFAULT_VERTRESOLUTION,
46+ reserved1: Default::default(),
47+ frame_count: Vp09Box::DEFAULT_FRAME_COUNT,
48+ compressorname: Vp09Box::DEFAULT_COMPRESSORNAME,
49+ depth: Vp09Box::DEFAULT_DEPTH,
50+ end_code: Vp09Box::DEFAULT_END_CODE,
51+ vpcc: VpccBox {
52+ version: VpccBox::DEFAULT_VERSION,
53+ flags: 0,
54+ profile: 0,
55+ level: 0x1F,
56+ bit_depth: VpccBox::DEFAULT_BIT_DEPTH,
57+ chroma_subsampling: 0,
58+ video_full_range_flag: false,
59+ color_primaries: 0,
60+ transfer_characteristics: 0,
61+ matrix_coefficients: 0,
62+ codec_initialization_data_size: 0,
63+ },
64+ }
65+ }
66+}
67+
68+impl Mp4Box for Vp09Box {
69+ fn box_type(&self) -> BoxType {
70+ BoxType::Vp09Box
71+ }
72+
73+ fn box_size(&self) -> u64 {
74+ 0x6A
75+ }
76+
77+ fn to_json(&self) -> Result<String> {
78+ Ok(serde_json::to_string(&self).unwrap())
79+ }
80+
81+ fn summary(&self) -> Result<String> {
82+ Ok(format!("{self:?}"))
83+ }
84+}
85+
86+impl<R: Read + Seek> ReadBox<&mut R> for Vp09Box {
87+ fn read_box(reader: &mut R, size: u64) -> Result<Self> {
88+ let start = box_start(reader)?;
89+ let (version, flags) = read_box_header_ext(reader)?;
90+
91+ let start_code: u16 = reader.read_u16::<BigEndian>()?;
92+ let data_reference_index: u16 = reader.read_u16::<BigEndian>()?;
93+ let reserved0: [u8; 16] = {
94+ let mut buf = [0u8; 16];
95+ reader.read_exact(&mut buf)?;
96+ buf
97+ };
98+ let width: u16 = reader.read_u16::<BigEndian>()?;
99+ let height: u16 = reader.read_u16::<BigEndian>()?;
100+ let horizresolution: (u16, u16) = (
101+ reader.read_u16::<BigEndian>()?,
102+ reader.read_u16::<BigEndian>()?,
103+ );
104+ let vertresolution: (u16, u16) = (
105+ reader.read_u16::<BigEndian>()?,
106+ reader.read_u16::<BigEndian>()?,
107+ );
108+ let reserved1: [u8; 4] = {
109+ let mut buf = [0u8; 4];
110+ reader.read_exact(&mut buf)?;
111+ buf
112+ };
113+ let frame_count: u16 = reader.read_u16::<BigEndian>()?;
114+ let compressorname: [u8; 32] = {
115+ let mut buf = [0u8; 32];
116+ reader.read_exact(&mut buf)?;
117+ buf
118+ };
119+ let depth: u16 = reader.read_u16::<BigEndian>()?;
120+ let end_code: u16 = reader.read_u16::<BigEndian>()?;
121+
122+ let vpcc = {
123+ let header = BoxHeader::read(reader)?;
124+ if header.size > size {
125+ return Err(Error::InvalidData(
126+ "vp09 box contains a box with a larger size than it",
127+ ));
128+ }
129+ VpccBox::read_box(reader, header.size)?
130+ };
131+
132+ skip_bytes_to(reader, start + size)?;
133+
134+ Ok(Self {
135+ version,
136+ flags,
137+ start_code,
138+ data_reference_index,
139+ reserved0,
140+ width,
141+ height,
142+ horizresolution,
143+ vertresolution,
144+ reserved1,
145+ frame_count,
146+ compressorname,
147+ depth,
148+ end_code,
149+ vpcc,
150+ })
151+ }
152+}
153+
154+impl<W: Write> WriteBox<&mut W> for Vp09Box {
155+ fn write_box(&self, writer: &mut W) -> Result<u64> {
156+ let size = self.box_size();
157+ BoxHeader::new(self.box_type(), size).write(writer)?;
158+
159+ write_box_header_ext(writer, self.version, self.flags)?;
160+
161+ writer.write_u16::<BigEndian>(self.start_code)?;
162+ writer.write_u16::<BigEndian>(self.data_reference_index)?;
163+ writer.write_all(&self.reserved0)?;
164+ writer.write_u16::<BigEndian>(self.width)?;
165+ writer.write_u16::<BigEndian>(self.height)?;
166+ writer.write_u16::<BigEndian>(self.horizresolution.0)?;
167+ writer.write_u16::<BigEndian>(self.horizresolution.1)?;
168+ writer.write_u16::<BigEndian>(self.vertresolution.0)?;
169+ writer.write_u16::<BigEndian>(self.vertresolution.1)?;
170+ writer.write_all(&self.reserved1)?;
171+ writer.write_u16::<BigEndian>(self.frame_count)?;
172+ writer.write_all(&self.compressorname)?;
173+ writer.write_u16::<BigEndian>(self.depth)?;
174+ writer.write_u16::<BigEndian>(self.end_code)?;
175+ VpccBox::write_box(&self.vpcc, writer)?;
176+
177+ Ok(size)
178+ }
179+}
180+
181+#[cfg(test)]
182+mod tests {
183+ use super::*;
184+ use crate::mp4box::BoxHeader;
185+ use std::io::Cursor;
186+
187+ #[test]
188+ fn test_vpcc() {
189+ let src_box = Vp09Box::new(&Vp9Config {
190+ width: 1920,
191+ height: 1080,
192+ });
193+ let mut buf = Vec::new();
194+ src_box.write_box(&mut buf).unwrap();
195+ assert_eq!(buf.len(), src_box.box_size() as usize);
196+
197+ let mut reader = Cursor::new(&buf);
198+ let header = BoxHeader::read(&mut reader).unwrap();
199+ assert_eq!(header.name, BoxType::Vp09Box);
200+ assert_eq!(src_box.box_size(), header.size);
201+
202+ let dst_box = Vp09Box::read_box(&mut reader, header.size).unwrap();
203+ assert_eq!(src_box, dst_box);
204+ }
205+}
vendor/mp4/src/mp4box/vpcc.rsadded+132 -0
@@ -0,0 +1,132 @@
1+use crate::mp4box::*;
2+use crate::Mp4Box;
3+use serde::Serialize;
4+
5+#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize)]
6+pub struct VpccBox {
7+ pub version: u8,
8+ pub flags: u32,
9+ pub profile: u8,
10+ pub level: u8,
11+ pub bit_depth: u8,
12+ pub chroma_subsampling: u8,
13+ pub video_full_range_flag: bool,
14+ pub color_primaries: u8,
15+ pub transfer_characteristics: u8,
16+ pub matrix_coefficients: u8,
17+ pub codec_initialization_data_size: u16,
18+}
19+
20+impl VpccBox {
21+ pub const DEFAULT_VERSION: u8 = 1;
22+ pub const DEFAULT_BIT_DEPTH: u8 = 8;
23+}
24+
25+impl Mp4Box for VpccBox {
26+ fn box_type(&self) -> BoxType {
27+ BoxType::VpccBox
28+ }
29+
30+ fn box_size(&self) -> u64 {
31+ HEADER_SIZE + HEADER_EXT_SIZE + 8
32+ }
33+
34+ fn to_json(&self) -> Result<String> {
35+ Ok(serde_json::to_string(&self).unwrap())
36+ }
37+
38+ fn summary(&self) -> Result<String> {
39+ Ok(format!("{self:?}"))
40+ }
41+}
42+
43+impl<R: Read + Seek> ReadBox<&mut R> for VpccBox {
44+ fn read_box(reader: &mut R, size: u64) -> Result<Self> {
45+ let start = box_start(reader)?;
46+ let (version, flags) = read_box_header_ext(reader)?;
47+
48+ let profile: u8 = reader.read_u8()?;
49+ let level: u8 = reader.read_u8()?;
50+ let (bit_depth, chroma_subsampling, video_full_range_flag) = {
51+ let b = reader.read_u8()?;
52+ (b >> 4, b << 4 >> 5, b & 0x01 == 1)
53+ };
54+ let transfer_characteristics: u8 = reader.read_u8()?;
55+ let matrix_coefficients: u8 = reader.read_u8()?;
56+ let codec_initialization_data_size: u16 = reader.read_u16::<BigEndian>()?;
57+
58+ skip_bytes_to(reader, start + size)?;
59+
60+ Ok(Self {
61+ version,
62+ flags,
63+ profile,
64+ level,
65+ bit_depth,
66+ chroma_subsampling,
67+ video_full_range_flag,
68+ color_primaries: 0,
69+ transfer_characteristics,
70+ matrix_coefficients,
71+ codec_initialization_data_size,
72+ })
73+ }
74+}
75+
76+impl<W: Write> WriteBox<&mut W> for VpccBox {
77+ fn write_box(&self, writer: &mut W) -> Result<u64> {
78+ let size = self.box_size();
79+ BoxHeader::new(self.box_type(), size).write(writer)?;
80+
81+ write_box_header_ext(writer, self.version, self.flags)?;
82+
83+ writer.write_u8(self.profile)?;
84+ writer.write_u8(self.level)?;
85+ writer.write_u8(
86+ (self.bit_depth << 4)
87+ | (self.chroma_subsampling << 1)
88+ | (self.video_full_range_flag as u8),
89+ )?;
90+ writer.write_u8(self.color_primaries)?;
91+ writer.write_u8(self.transfer_characteristics)?;
92+ writer.write_u8(self.matrix_coefficients)?;
93+ writer.write_u16::<BigEndian>(self.codec_initialization_data_size)?;
94+
95+ Ok(size)
96+ }
97+}
98+
99+#[cfg(test)]
100+mod tests {
101+ use super::*;
102+ use crate::mp4box::BoxHeader;
103+ use std::io::Cursor;
104+
105+ #[test]
106+ fn test_vpcc() {
107+ let src_box = VpccBox {
108+ version: VpccBox::DEFAULT_VERSION,
109+ flags: 0,
110+ profile: 0,
111+ level: 0x1F,
112+ bit_depth: VpccBox::DEFAULT_BIT_DEPTH,
113+ chroma_subsampling: 0,
114+ video_full_range_flag: false,
115+ color_primaries: 0,
116+ transfer_characteristics: 0,
117+ matrix_coefficients: 0,
118+ codec_initialization_data_size: 0,
119+ };
120+ let mut buf = Vec::new();
121+ src_box.write_box(&mut buf).unwrap();
122+ assert_eq!(buf.len(), src_box.box_size() as usize);
123+
124+ let mut reader = Cursor::new(&buf);
125+ let header = BoxHeader::read(&mut reader).unwrap();
126+ assert_eq!(header.name, BoxType::VpccBox);
127+ assert_eq!(src_box.box_size(), header.size);
128+
129+ let dst_box = VpccBox::read_box(&mut reader, header.size).unwrap();
130+ assert_eq!(src_box, dst_box);
131+ }
132+}
vendor/mp4/src/reader.rsadded+186 -0
@@ -0,0 +1,186 @@
1+use std::collections::HashMap;
2+use std::io::{Read, Seek};
3+use std::time::Duration;
4+
5+use crate::meta::MetaBox;
6+use crate::*;
7+
8+#[derive(Debug)]
9+pub struct Mp4Reader<R> {
10+ reader: R,
11+ pub ftyp: FtypBox,
12+ pub moov: MoovBox,
13+ pub moofs: Vec<MoofBox>,
14+ pub emsgs: Vec<EmsgBox>,
15+
16+ tracks: HashMap<u32, Mp4Track>,
17+ size: u64,
18+}
19+
20+impl<R: Read + Seek> Mp4Reader<R> {
21+ pub fn read_header(mut reader: R, size: u64) -> Result<Self> {
22+ let start = reader.stream_position()?;
23+
24+ let mut ftyp = None;
25+ let mut moov = None;
26+ let mut moofs = Vec::new();
27+ let mut emsgs = Vec::new();
28+
29+ let mut current = start;
30+ while current < size {
31+ // Get box header.
32+ let header = BoxHeader::read(&mut reader)?;
33+ let BoxHeader { name, size: s } = header;
34+ if s > size {
35+ return Err(Error::InvalidData(
36+ "file contains a box with a larger size than it",
37+ ));
38+ }
39+
40+ // Break if size zero BoxHeader, which can result in dead-loop.
41+ if s == 0 {
42+ break;
43+ }
44+
45+ // Match and parse the atom boxes.
46+ match name {
47+ BoxType::FtypBox => {
48+ ftyp = Some(FtypBox::read_box(&mut reader, s)?);
49+ }
50+ BoxType::FreeBox => {
51+ skip_box(&mut reader, s)?;
52+ }
53+ BoxType::MdatBox => {
54+ skip_box(&mut reader, s)?;
55+ }
56+ BoxType::MoovBox => {
57+ moov = Some(MoovBox::read_box(&mut reader, s)?);
58+ }
59+ BoxType::MoofBox => {
60+ let moof = MoofBox::read_box(&mut reader, s)?;
61+ moofs.push(moof);
62+ }
63+ BoxType::EmsgBox => {
64+ let emsg = EmsgBox::read_box(&mut reader, s)?;
65+ emsgs.push(emsg);
66+ }
67+ _ => {
68+ // XXX warn!()
69+ skip_box(&mut reader, s)?;
70+ }
71+ }
72+ current = reader.stream_position()?;
73+ }
74+
75+ if ftyp.is_none() {
76+ return Err(Error::BoxNotFound(BoxType::FtypBox));
77+ }
78+ if moov.is_none() {
79+ return Err(Error::BoxNotFound(BoxType::MoovBox));
80+ }
81+
82+ let size = current - start;
83+ let mut tracks = if let Some(ref moov) = moov {
84+ if moov.traks.iter().any(|trak| trak.tkhd.track_id == 0) {
85+ return Err(Error::InvalidData("illegal track id 0"));
86+ }
87+ moov.traks
88+ .iter()
89+ .map(|trak| (trak.tkhd.track_id, Mp4Track::from(trak)))
90+ .collect()
91+ } else {
92+ HashMap::new()
93+ };
94+
95+ // Update tracks if any fragmented (moof) boxes are found.
96+ if !moofs.is_empty() {
97+ let mut default_sample_duration = 0;
98+ if let Some(ref moov) = moov {
99+ if let Some(ref mvex) = &moov.mvex {
100+ default_sample_duration = mvex.trex.default_sample_duration
101+ }
102+ }
103+
104+ for moof in moofs.iter() {
105+ for traf in moof.trafs.iter() {
106+ let track_id = traf.tfhd.track_id;
107+ if let Some(track) = tracks.get_mut(&track_id) {
108+ track.default_sample_duration = default_sample_duration;
109+ track.trafs.push(traf.clone())
110+ } else {
111+ return Err(Error::TrakNotFound(track_id));
112+ }
113+ }
114+ }
115+ }
116+
117+ Ok(Mp4Reader {
118+ reader,
119+ ftyp: ftyp.unwrap(),
120+ moov: moov.unwrap(),
121+ moofs,
122+ emsgs,
123+ size,
124+ tracks,
125+ })
126+ }
127+
128+ pub fn size(&self) -> u64 {
129+ self.size
130+ }
131+
132+ pub fn major_brand(&self) -> &FourCC {
133+ &self.ftyp.major_brand
134+ }
135+
136+ pub fn minor_version(&self) -> u32 {
137+ self.ftyp.minor_version
138+ }
139+
140+ pub fn compatible_brands(&self) -> &[FourCC] {
141+ &self.ftyp.compatible_brands
142+ }
143+
144+ pub fn duration(&self) -> Duration {
145+ Duration::from_millis(self.moov.mvhd.duration * 1000 / self.moov.mvhd.timescale as u64)
146+ }
147+
148+ pub fn timescale(&self) -> u32 {
149+ self.moov.mvhd.timescale
150+ }
151+
152+ pub fn is_fragmented(&self) -> bool {
153+ !self.moofs.is_empty()
154+ }
155+
156+ pub fn tracks(&self) -> &HashMap<u32, Mp4Track> {
157+ &self.tracks
158+ }
159+
160+ pub fn sample_count(&self, track_id: u32) -> Result<u32> {
161+ if let Some(track) = self.tracks.get(&track_id) {
162+ Ok(track.sample_count())
163+ } else {
164+ Err(Error::TrakNotFound(track_id))
165+ }
166+ }
167+
168+ pub fn read_sample(&mut self, track_id: u32, sample_id: u32) -> Result<Option<Mp4Sample>> {
169+ if let Some(track) = self.tracks.get(&track_id) {
170+ track.read_sample(&mut self.reader, sample_id)
171+ } else {
172+ Err(Error::TrakNotFound(track_id))
173+ }
174+ }
175+}
176+
177+impl<R> Mp4Reader<R> {
178+ pub fn metadata(&self) -> impl Metadata<'_> {
179+ self.moov.udta.as_ref().and_then(|udta| {
180+ udta.meta.as_ref().and_then(|meta| match meta {
181+ MetaBox::Mdir { ilst } => ilst.as_ref(),
182+ _ => None,
183+ })
184+ })
185+ }
186+}
vendor/mp4/src/track.rsadded+858 -0
@@ -0,0 +1,858 @@
1+use bytes::BytesMut;
2+use std::cmp;
3+use std::convert::TryFrom;
4+use std::io::{Read, Seek, SeekFrom, Write};
5+use std::time::Duration;
6+
7+use crate::mp4box::traf::TrafBox;
8+use crate::mp4box::trak::TrakBox;
9+use crate::mp4box::{
10+ avc1::Avc1Box, co64::Co64Box, ctts::CttsBox, ctts::CttsEntry, hev1::Hev1Box, mp4a::Mp4aBox,
11+ smhd::SmhdBox, stco::StcoBox, stsc::StscEntry, stss::StssBox, stts::SttsEntry, tx3g::Tx3gBox,
12+ vmhd::VmhdBox, vp09::Vp09Box,
13+};
14+use crate::*;
15+
16+#[derive(Debug, Clone, PartialEq, Eq)]
17+pub struct TrackConfig {
18+ pub track_type: TrackType,
19+ pub timescale: u32,
20+ pub language: String,
21+ pub media_conf: MediaConfig,
22+}
23+
24+impl From<MediaConfig> for TrackConfig {
25+ fn from(media_conf: MediaConfig) -> Self {
26+ match media_conf {
27+ MediaConfig::AvcConfig(avc_conf) => Self::from(avc_conf),
28+ MediaConfig::HevcConfig(hevc_conf) => Self::from(hevc_conf),
29+ MediaConfig::AacConfig(aac_conf) => Self::from(aac_conf),
30+ MediaConfig::TtxtConfig(ttxt_conf) => Self::from(ttxt_conf),
31+ MediaConfig::Vp9Config(vp9_config) => Self::from(vp9_config),
32+ }
33+ }
34+}
35+
36+impl From<AvcConfig> for TrackConfig {
37+ fn from(avc_conf: AvcConfig) -> Self {
38+ Self {
39+ track_type: TrackType::Video,
40+ timescale: 1000, // XXX
41+ language: String::from("und"), // XXX
42+ media_conf: MediaConfig::AvcConfig(avc_conf),
43+ }
44+ }
45+}
46+
47+impl From<HevcConfig> for TrackConfig {
48+ fn from(hevc_conf: HevcConfig) -> Self {
49+ Self {
50+ track_type: TrackType::Video,
51+ timescale: 1000, // XXX
52+ language: String::from("und"), // XXX
53+ media_conf: MediaConfig::HevcConfig(hevc_conf),
54+ }
55+ }
56+}
57+
58+impl From<AacConfig> for TrackConfig {
59+ fn from(aac_conf: AacConfig) -> Self {
60+ Self {
61+ track_type: TrackType::Audio,
62+ timescale: 1000, // XXX
63+ language: String::from("und"), // XXX
64+ media_conf: MediaConfig::AacConfig(aac_conf),
65+ }
66+ }
67+}
68+
69+impl From<TtxtConfig> for TrackConfig {
70+ fn from(txtt_conf: TtxtConfig) -> Self {
71+ Self {
72+ track_type: TrackType::Subtitle,
73+ timescale: 1000, // XXX
74+ language: String::from("und"), // XXX
75+ media_conf: MediaConfig::TtxtConfig(txtt_conf),
76+ }
77+ }
78+}
79+
80+impl From<Vp9Config> for TrackConfig {
81+ fn from(vp9_conf: Vp9Config) -> Self {
82+ Self {
83+ track_type: TrackType::Video,
84+ timescale: 1000, // XXX
85+ language: String::from("und"), // XXX
86+ media_conf: MediaConfig::Vp9Config(vp9_conf),
87+ }
88+ }
89+}
90+
91+#[derive(Debug)]
92+pub struct Mp4Track {
93+ pub trak: TrakBox,
94+ pub trafs: Vec<TrafBox>,
95+
96+ // Fragmented Tracks Defaults.
97+ pub default_sample_duration: u32,
98+}
99+
100+impl Mp4Track {
101+ pub(crate) fn from(trak: &TrakBox) -> Self {
102+ let trak = trak.clone();
103+ Self {
104+ trak,
105+ trafs: Vec::new(),
106+ default_sample_duration: 0,
107+ }
108+ }
109+
110+ pub fn track_id(&self) -> u32 {
111+ self.trak.tkhd.track_id
112+ }
113+
114+ pub fn track_type(&self) -> Result<TrackType> {
115+ TrackType::try_from(&self.trak.mdia.hdlr.handler_type)
116+ }
117+
118+ pub fn media_type(&self) -> Result<MediaType> {
119+ if self.trak.mdia.minf.stbl.stsd.avc1.is_some() {
120+ Ok(MediaType::H264)
121+ } else if self.trak.mdia.minf.stbl.stsd.hev1.is_some() {
122+ Ok(MediaType::H265)
123+ } else if self.trak.mdia.minf.stbl.stsd.vp09.is_some() {
124+ Ok(MediaType::VP9)
125+ } else if self.trak.mdia.minf.stbl.stsd.mp4a.is_some() {
126+ Ok(MediaType::AAC)
127+ } else if self.trak.mdia.minf.stbl.stsd.tx3g.is_some() {
128+ Ok(MediaType::TTXT)
129+ } else {
130+ Err(Error::InvalidData("unsupported media type"))
131+ }
132+ }
133+
134+ pub fn box_type(&self) -> Result<FourCC> {
135+ if self.trak.mdia.minf.stbl.stsd.avc1.is_some() {
136+ Ok(FourCC::from(BoxType::Avc1Box))
137+ } else if self.trak.mdia.minf.stbl.stsd.hev1.is_some() {
138+ Ok(FourCC::from(BoxType::Hev1Box))
139+ } else if self.trak.mdia.minf.stbl.stsd.vp09.is_some() {
140+ Ok(FourCC::from(BoxType::Vp09Box))
141+ } else if self.trak.mdia.minf.stbl.stsd.mp4a.is_some() {
142+ Ok(FourCC::from(BoxType::Mp4aBox))
143+ } else if self.trak.mdia.minf.stbl.stsd.tx3g.is_some() {
144+ Ok(FourCC::from(BoxType::Tx3gBox))
145+ } else {
146+ Err(Error::InvalidData("unsupported sample entry box"))
147+ }
148+ }
149+
150+ pub fn width(&self) -> u16 {
151+ if let Some(ref avc1) = self.trak.mdia.minf.stbl.stsd.avc1 {
152+ avc1.width
153+ } else {
154+ self.trak.tkhd.width.value()
155+ }
156+ }
157+
158+ pub fn height(&self) -> u16 {
159+ if let Some(ref avc1) = self.trak.mdia.minf.stbl.stsd.avc1 {
160+ avc1.height
161+ } else {
162+ self.trak.tkhd.height.value()
163+ }
164+ }
165+
166+ pub fn frame_rate(&self) -> f64 {
167+ let dur_msec = self.duration().as_millis() as u64;
168+ if dur_msec > 0 {
169+ ((self.sample_count() as u64 * 1000) / dur_msec) as f64
170+ } else {
171+ 0.0
172+ }
173+ }
174+
175+ pub fn sample_freq_index(&self) -> Result<SampleFreqIndex> {
176+ if let Some(ref mp4a) = self.trak.mdia.minf.stbl.stsd.mp4a {
177+ if let Some(ref esds) = mp4a.esds {
178+ SampleFreqIndex::try_from(esds.es_desc.dec_config.dec_specific.freq_index)
179+ } else {
180+ Err(Error::BoxInStblNotFound(self.track_id(), BoxType::EsdsBox))
181+ }
182+ } else {
183+ Err(Error::BoxInStblNotFound(self.track_id(), BoxType::Mp4aBox))
184+ }
185+ }
186+
187+ pub fn channel_config(&self) -> Result<ChannelConfig> {
188+ if let Some(ref mp4a) = self.trak.mdia.minf.stbl.stsd.mp4a {
189+ if let Some(ref esds) = mp4a.esds {
190+ ChannelConfig::try_from(esds.es_desc.dec_config.dec_specific.chan_conf)
191+ } else {
192+ Err(Error::BoxInStblNotFound(self.track_id(), BoxType::EsdsBox))
193+ }
194+ } else {
195+ Err(Error::BoxInStblNotFound(self.track_id(), BoxType::Mp4aBox))
196+ }
197+ }
198+
199+ pub fn language(&self) -> &str {
200+ &self.trak.mdia.mdhd.language
201+ }
202+
203+ pub fn timescale(&self) -> u32 {
204+ self.trak.mdia.mdhd.timescale
205+ }
206+
207+ pub fn duration(&self) -> Duration {
208+ Duration::from_micros(
209+ self.trak.mdia.mdhd.duration * 1_000_000 / self.trak.mdia.mdhd.timescale as u64,
210+ )
211+ }
212+
213+ pub fn bitrate(&self) -> u32 {
214+ if let Some(ref mp4a) = self.trak.mdia.minf.stbl.stsd.mp4a {
215+ if let Some(ref esds) = mp4a.esds {
216+ esds.es_desc.dec_config.avg_bitrate
217+ } else {
218+ 0
219+ }
220+ // mp4a.esds.es_desc.dec_config.avg_bitrate
221+ } else {
222+ let dur_sec = self.duration().as_secs();
223+ if dur_sec > 0 {
224+ let bitrate = self.total_sample_size() * 8 / dur_sec;
225+ bitrate as u32
226+ } else {
227+ 0
228+ }
229+ }
230+ }
231+
232+ pub fn sample_count(&self) -> u32 {
233+ if !self.trafs.is_empty() {
234+ let mut sample_count = 0u32;
235+ for traf in self.trafs.iter() {
236+ if let Some(ref trun) = traf.trun {
237+ sample_count = sample_count
238+ .checked_add(trun.sample_count)
239+ .expect("attempt to sum trun sample_count with overflow");
240+ }
241+ }
242+ sample_count
243+ } else {
244+ self.trak.mdia.minf.stbl.stsz.sample_count
245+ }
246+ }
247+
248+ pub fn video_profile(&self) -> Result<AvcProfile> {
249+ if let Some(ref avc1) = self.trak.mdia.minf.stbl.stsd.avc1 {
250+ AvcProfile::try_from((
251+ avc1.avcc.avc_profile_indication,
252+ avc1.avcc.profile_compatibility,
253+ ))
254+ } else {
255+ Err(Error::BoxInStblNotFound(self.track_id(), BoxType::Avc1Box))
256+ }
257+ }
258+
259+ pub fn sequence_parameter_set(&self) -> Result<&[u8]> {
260+ if let Some(ref avc1) = self.trak.mdia.minf.stbl.stsd.avc1 {
261+ match avc1.avcc.sequence_parameter_sets.get(0) {
262+ Some(nal) => Ok(nal.bytes.as_ref()),
263+ None => Err(Error::EntryInStblNotFound(
264+ self.track_id(),
265+ BoxType::AvcCBox,
266+ 0,
267+ )),
268+ }
269+ } else {
270+ Err(Error::BoxInStblNotFound(self.track_id(), BoxType::Avc1Box))
271+ }
272+ }
273+
274+ pub fn picture_parameter_set(&self) -> Result<&[u8]> {
275+ if let Some(ref avc1) = self.trak.mdia.minf.stbl.stsd.avc1 {
276+ match avc1.avcc.picture_parameter_sets.get(0) {
277+ Some(nal) => Ok(nal.bytes.as_ref()),
278+ None => Err(Error::EntryInStblNotFound(
279+ self.track_id(),
280+ BoxType::AvcCBox,
281+ 0,
282+ )),
283+ }
284+ } else {
285+ Err(Error::BoxInStblNotFound(self.track_id(), BoxType::Avc1Box))
286+ }
287+ }
288+
289+ pub fn audio_profile(&self) -> Result<AudioObjectType> {
290+ if let Some(ref mp4a) = self.trak.mdia.minf.stbl.stsd.mp4a {
291+ if let Some(ref esds) = mp4a.esds {
292+ AudioObjectType::try_from(esds.es_desc.dec_config.dec_specific.profile)
293+ } else {
294+ Err(Error::BoxInStblNotFound(self.track_id(), BoxType::EsdsBox))
295+ }
296+ } else {
297+ Err(Error::BoxInStblNotFound(self.track_id(), BoxType::Mp4aBox))
298+ }
299+ }
300+
301+ fn stsc_index(&self, sample_id: u32) -> Result<usize> {
302+ if self.trak.mdia.minf.stbl.stsc.entries.is_empty() {
303+ return Err(Error::InvalidData("no stsc entries"));
304+ }
305+ for (i, entry) in self.trak.mdia.minf.stbl.stsc.entries.iter().enumerate() {
306+ if sample_id < entry.first_sample {
307+ return if i == 0 {
308+ Err(Error::InvalidData("sample not found"))
309+ } else {
310+ Ok(i - 1)
311+ };
312+ }
313+ }
314+ Ok(self.trak.mdia.minf.stbl.stsc.entries.len() - 1)
315+ }
316+
317+ fn chunk_offset(&self, chunk_id: u32) -> Result<u64> {
318+ if self.trak.mdia.minf.stbl.stco.is_none() && self.trak.mdia.minf.stbl.co64.is_none() {
319+ return Err(Error::InvalidData("must have either stco or co64 boxes"));
320+ }
321+ if let Some(ref stco) = self.trak.mdia.minf.stbl.stco {
322+ if let Some(offset) = stco.entries.get(chunk_id as usize - 1) {
323+ return Ok(*offset as u64);
324+ } else {
325+ return Err(Error::EntryInStblNotFound(
326+ self.track_id(),
327+ BoxType::StcoBox,
328+ chunk_id,
329+ ));
330+ }
331+ } else if let Some(ref co64) = self.trak.mdia.minf.stbl.co64 {
332+ if let Some(offset) = co64.entries.get(chunk_id as usize - 1) {
333+ return Ok(*offset);
334+ } else {
335+ return Err(Error::EntryInStblNotFound(
336+ self.track_id(),
337+ BoxType::Co64Box,
338+ chunk_id,
339+ ));
340+ }
341+ }
342+ Err(Error::Box2NotFound(BoxType::StcoBox, BoxType::Co64Box))
343+ }
344+
345+ fn ctts_index(&self, sample_id: u32) -> Result<(usize, u32)> {
346+ let ctts = self.trak.mdia.minf.stbl.ctts.as_ref().unwrap();
347+ let mut sample_count: u32 = 1;
348+ for (i, entry) in ctts.entries.iter().enumerate() {
349+ let next_sample_count =
350+ sample_count
351+ .checked_add(entry.sample_count)
352+ .ok_or(Error::InvalidData(
353+ "attempt to sum ctts entries sample_count with overflow",
354+ ))?;
355+ if sample_id < next_sample_count {
356+ return Ok((i, sample_count));
357+ }
358+ sample_count = next_sample_count;
359+ }
360+
361+ Err(Error::EntryInStblNotFound(
362+ self.track_id(),
363+ BoxType::CttsBox,
364+ sample_id,
365+ ))
366+ }
367+
368+ /// return `(traf_idx, sample_idx_in_trun)`
369+ fn find_traf_idx_and_sample_idx(&self, sample_id: u32) -> Option<(usize, usize)> {
370+ let global_idx = sample_id - 1;
371+ let mut offset = 0;
372+ for traf_idx in 0..self.trafs.len() {
373+ if let Some(trun) = &self.trafs[traf_idx].trun {
374+ let sample_count = trun.sample_count;
375+ if sample_count > (global_idx - offset) {
376+ return Some((traf_idx, (global_idx - offset) as _));
377+ }
378+ offset = offset
379+ .checked_add(sample_count)
380+ .expect("attempt to sum trun sample_count with overflow");
381+ }
382+ }
383+ None
384+ }
385+
386+ fn sample_size(&self, sample_id: u32) -> Result<u32> {
387+ if !self.trafs.is_empty() {
388+ if let Some((traf_idx, sample_idx)) = self.find_traf_idx_and_sample_idx(sample_id) {
389+ if let Some(size) = self.trafs[traf_idx]
390+ .trun
391+ .as_ref()
392+ .unwrap()
393+ .sample_sizes
394+ .get(sample_idx)
395+ {
396+ Ok(*size)
397+ } else {
398+ Err(Error::EntryInTrunNotFound(
399+ self.track_id(),
400+ BoxType::TrunBox,
401+ sample_id,
402+ ))
403+ }
404+ } else {
405+ Err(Error::BoxInTrafNotFound(self.track_id(), BoxType::TrafBox))
406+ }
407+ } else {
408+ let stsz = &self.trak.mdia.minf.stbl.stsz;
409+ if stsz.sample_size > 0 {
410+ return Ok(stsz.sample_size);
411+ }
412+ if let Some(size) = stsz.sample_sizes.get(sample_id as usize - 1) {
413+ Ok(*size)
414+ } else {
415+ Err(Error::EntryInStblNotFound(
416+ self.track_id(),
417+ BoxType::StszBox,
418+ sample_id,
419+ ))
420+ }
421+ }
422+ }
423+
424+ fn total_sample_size(&self) -> u64 {
425+ let stsz = &self.trak.mdia.minf.stbl.stsz;
426+ if stsz.sample_size > 0 {
427+ stsz.sample_size as u64 * self.sample_count() as u64
428+ } else {
429+ let mut total_size = 0;
430+ for size in stsz.sample_sizes.iter() {
431+ total_size += *size as u64;
432+ }
433+ total_size
434+ }
435+ }
436+
437+ fn sample_offset(&self, sample_id: u32) -> Result<u64> {
438+ if !self.trafs.is_empty() {
439+ if let Some((traf_idx, _sample_idx)) = self.find_traf_idx_and_sample_idx(sample_id) {
440+ Ok(self.trafs[traf_idx].tfhd.base_data_offset.unwrap_or(0))
441+ } else {
442+ Err(Error::BoxInTrafNotFound(self.track_id(), BoxType::TrafBox))
443+ }
444+ } else {
445+ let stsc_index = self.stsc_index(sample_id)?;
446+
447+ let stsc = &self.trak.mdia.minf.stbl.stsc;
448+ let stsc_entry = stsc.entries.get(stsc_index).unwrap();
449+
450+ let first_chunk = stsc_entry.first_chunk;
451+ let first_sample = stsc_entry.first_sample;
452+ let samples_per_chunk = stsc_entry.samples_per_chunk;
453+
454+ let chunk_id = sample_id
455+ .checked_sub(first_sample)
456+ .map(|n| n / samples_per_chunk)
457+ .and_then(|n| n.checked_add(first_chunk))
458+ .ok_or(Error::InvalidData(
459+ "attempt to calculate stsc chunk_id with overflow",
460+ ))?;
461+
462+ let chunk_offset = self.chunk_offset(chunk_id)?;
463+
464+ let first_sample_in_chunk = sample_id - (sample_id - first_sample) % samples_per_chunk;
465+
466+ let mut sample_offset = 0;
467+ for i in first_sample_in_chunk..sample_id {
468+ sample_offset += self.sample_size(i)?;
469+ }
470+
471+ Ok(chunk_offset + sample_offset as u64)
472+ }
473+ }
474+
475+ fn sample_time(&self, sample_id: u32) -> Result<(u64, u32)> {
476+ let stts = &self.trak.mdia.minf.stbl.stts;
477+
478+ let mut sample_count: u32 = 1;
479+ let mut elapsed = 0;
480+
481+ if !self.trafs.is_empty() {
482+ let start_time = ((sample_id - 1) * self.default_sample_duration) as u64;
483+ Ok((start_time, self.default_sample_duration))
484+ } else {
485+ for entry in stts.entries.iter() {
486+ let new_sample_count =
487+ sample_count
488+ .checked_add(entry.sample_count)
489+ .ok_or(Error::InvalidData(
490+ "attempt to sum stts entries sample_count with overflow",
491+ ))?;
492+ if sample_id < new_sample_count {
493+ let start_time =
494+ (sample_id - sample_count) as u64 * entry.sample_delta as u64 + elapsed;
495+ return Ok((start_time, entry.sample_delta));
496+ }
497+
498+ sample_count = new_sample_count;
499+ elapsed += entry.sample_count as u64 * entry.sample_delta as u64;
500+ }
501+
502+ Err(Error::EntryInStblNotFound(
503+ self.track_id(),
504+ BoxType::SttsBox,
505+ sample_id,
506+ ))
507+ }
508+ }
509+
510+ fn sample_rendering_offset(&self, sample_id: u32) -> i32 {
511+ if let Some(ref ctts) = self.trak.mdia.minf.stbl.ctts {
512+ if let Ok((ctts_index, _)) = self.ctts_index(sample_id) {
513+ let ctts_entry = ctts.entries.get(ctts_index).unwrap();
514+ return ctts_entry.sample_offset;
515+ }
516+ }
517+ 0
518+ }
519+
520+ fn is_sync_sample(&self, sample_id: u32) -> bool {
521+ if !self.trafs.is_empty() {
522+ let sample_sizes_count = self.sample_count() / self.trafs.len() as u32;
523+ return sample_id == 1 || sample_id % sample_sizes_count == 0;
524+ }
525+
526+ if let Some(ref stss) = self.trak.mdia.minf.stbl.stss {
527+ stss.entries.binary_search(&sample_id).is_ok()
528+ } else {
529+ true
530+ }
531+ }
532+
533+ pub(crate) fn read_sample<R: Read + Seek>(
534+ &self,
535+ reader: &mut R,
536+ sample_id: u32,
537+ ) -> Result<Option<Mp4Sample>> {
538+ let sample_offset = match self.sample_offset(sample_id) {
539+ Ok(offset) => offset,
540+ Err(Error::EntryInStblNotFound(_, _, _)) => return Ok(None),
541+ Err(err) => return Err(err),
542+ };
543+ let sample_size = match self.sample_size(sample_id) {
544+ Ok(size) => size,
545+ Err(Error::EntryInStblNotFound(_, _, _)) => return Ok(None),
546+ Err(err) => return Err(err),
547+ };
548+
549+ let mut buffer = vec![0x0u8; sample_size as usize];
550+ reader.seek(SeekFrom::Start(sample_offset))?;
551+ reader.read_exact(&mut buffer)?;
552+
553+ let (start_time, duration) = self.sample_time(sample_id).unwrap(); // XXX
554+ let rendering_offset = self.sample_rendering_offset(sample_id);
555+ let is_sync = self.is_sync_sample(sample_id);
556+
557+ Ok(Some(Mp4Sample {
558+ start_time,
559+ duration,
560+ rendering_offset,
561+ is_sync,
562+ bytes: Bytes::from(buffer),
563+ }))
564+ }
565+}
566+
567+// TODO creation_time, modification_time
568+#[derive(Debug, Default)]
569+pub(crate) struct Mp4TrackWriter {
570+ trak: TrakBox,
571+
572+ sample_id: u32,
573+ fixed_sample_size: u32,
574+ is_fixed_sample_size: bool,
575+ chunk_samples: u32,
576+ chunk_duration: u32,
577+ chunk_buffer: BytesMut,
578+
579+ samples_per_chunk: u32,
580+ duration_per_chunk: u32,
581+}
582+
583+impl Mp4TrackWriter {
584+ pub(crate) fn new(track_id: u32, config: &TrackConfig) -> Result<Self> {
585+ let mut trak = TrakBox::default();
586+ trak.tkhd.track_id = track_id;
587+ trak.mdia.mdhd.timescale = config.timescale;
588+ trak.mdia.mdhd.language = config.language.to_owned();
589+ trak.mdia.hdlr.handler_type = config.track_type.into();
590+ trak.mdia.minf.stbl.co64 = Some(Co64Box::default());
591+ match config.media_conf {
592+ MediaConfig::AvcConfig(ref avc_config) => {
593+ trak.tkhd.set_width(avc_config.width);
594+ trak.tkhd.set_height(avc_config.height);
595+
596+ let vmhd = VmhdBox::default();
597+ trak.mdia.minf.vmhd = Some(vmhd);
598+
599+ let avc1 = Avc1Box::new(avc_config);
600+ trak.mdia.minf.stbl.stsd.avc1 = Some(avc1);
601+ }
602+ MediaConfig::HevcConfig(ref hevc_config) => {
603+ trak.tkhd.set_width(hevc_config.width);
604+ trak.tkhd.set_height(hevc_config.height);
605+
606+ let vmhd = VmhdBox::default();
607+ trak.mdia.minf.vmhd = Some(vmhd);
608+
609+ let hev1 = Hev1Box::new(hevc_config);
610+ trak.mdia.minf.stbl.stsd.hev1 = Some(hev1);
611+ }
612+ MediaConfig::Vp9Config(ref config) => {
613+ trak.tkhd.set_width(config.width);
614+ trak.tkhd.set_height(config.height);
615+
616+ trak.mdia.minf.stbl.stsd.vp09 = Some(Vp09Box::new(config));
617+ }
618+ MediaConfig::AacConfig(ref aac_config) => {
619+ let smhd = SmhdBox::default();
620+ trak.mdia.minf.smhd = Some(smhd);
621+
622+ let mp4a = Mp4aBox::new(aac_config);
623+ trak.mdia.minf.stbl.stsd.mp4a = Some(mp4a);
624+ }
625+ MediaConfig::TtxtConfig(ref _ttxt_config) => {
626+ let tx3g = Tx3gBox::default();
627+ trak.mdia.minf.stbl.stsd.tx3g = Some(tx3g);
628+ }
629+ }
630+ Ok(Mp4TrackWriter {
631+ trak,
632+ chunk_buffer: BytesMut::new(),
633+ sample_id: 1,
634+ duration_per_chunk: config.timescale, // 1 second
635+ ..Self::default()
636+ })
637+ }
638+
639+ fn update_sample_sizes(&mut self, size: u32) {
640+ if self.trak.mdia.minf.stbl.stsz.sample_count == 0 {
641+ if size == 0 {
642+ self.trak.mdia.minf.stbl.stsz.sample_size = 0;
643+ self.is_fixed_sample_size = false;
644+ self.trak.mdia.minf.stbl.stsz.sample_sizes.push(0);
645+ } else {
646+ self.trak.mdia.minf.stbl.stsz.sample_size = size;
647+ self.fixed_sample_size = size;
648+ self.is_fixed_sample_size = true;
649+ }
650+ } else if self.is_fixed_sample_size {
651+ if self.fixed_sample_size != size {
652+ self.is_fixed_sample_size = false;
653+ if self.trak.mdia.minf.stbl.stsz.sample_size > 0 {
654+ self.trak.mdia.minf.stbl.stsz.sample_size = 0;
655+ for _ in 0..self.trak.mdia.minf.stbl.stsz.sample_count {
656+ self.trak
657+ .mdia
658+ .minf
659+ .stbl
660+ .stsz
661+ .sample_sizes
662+ .push(self.fixed_sample_size);
663+ }
664+ }
665+ self.trak.mdia.minf.stbl.stsz.sample_sizes.push(size);
666+ }
667+ } else {
668+ self.trak.mdia.minf.stbl.stsz.sample_sizes.push(size);
669+ }
670+ self.trak.mdia.minf.stbl.stsz.sample_count += 1;
671+ }
672+
673+ fn update_sample_times(&mut self, dur: u32) {
674+ if let Some(ref mut entry) = self.trak.mdia.minf.stbl.stts.entries.last_mut() {
675+ if entry.sample_delta == dur {
676+ entry.sample_count += 1;
677+ return;
678+ }
679+ }
680+
681+ let entry = SttsEntry {
682+ sample_count: 1,
683+ sample_delta: dur,
684+ };
685+ self.trak.mdia.minf.stbl.stts.entries.push(entry);
686+ }
687+
688+ fn update_rendering_offsets(&mut self, offset: i32) {
689+ let ctts = if let Some(ref mut ctts) = self.trak.mdia.minf.stbl.ctts {
690+ ctts
691+ } else {
692+ if offset == 0 {
693+ return;
694+ }
695+ let mut ctts = CttsBox::default();
696+ if self.sample_id > 1 {
697+ let entry = CttsEntry {
698+ sample_count: self.sample_id - 1,
699+ sample_offset: 0,
700+ };
701+ ctts.entries.push(entry);
702+ }
703+ self.trak.mdia.minf.stbl.ctts = Some(ctts);
704+ self.trak.mdia.minf.stbl.ctts.as_mut().unwrap()
705+ };
706+
707+ if let Some(ref mut entry) = ctts.entries.last_mut() {
708+ if entry.sample_offset == offset {
709+ entry.sample_count += 1;
710+ return;
711+ }
712+ }
713+
714+ let entry = CttsEntry {
715+ sample_count: 1,
716+ sample_offset: offset,
717+ };
718+ ctts.entries.push(entry);
719+ }
720+
721+ fn update_sync_samples(&mut self, is_sync: bool) {
722+ if let Some(ref mut stss) = self.trak.mdia.minf.stbl.stss {
723+ if !is_sync {
724+ return;
725+ }
726+
727+ stss.entries.push(self.sample_id);
728+ } else {
729+ if !is_sync {
730+ return;
731+ }
732+
733+ // Create the stts box if not found and push the entry.
734+ let mut stss = StssBox::default();
735+ stss.entries.push(self.sample_id);
736+ self.trak.mdia.minf.stbl.stss = Some(stss);
737+ };
738+ }
739+
740+ fn is_chunk_full(&self) -> bool {
741+ if self.samples_per_chunk > 0 {
742+ self.chunk_samples >= self.samples_per_chunk
743+ } else {
744+ self.chunk_duration >= self.duration_per_chunk
745+ }
746+ }
747+
748+ fn update_durations(&mut self, dur: u32, movie_timescale: u32) {
749+ self.trak.mdia.mdhd.duration += dur as u64;
750+ if self.trak.mdia.mdhd.duration > (u32::MAX as u64) {
751+ self.trak.mdia.mdhd.version = 1
752+ }
753+ self.trak.tkhd.duration +=
754+ dur as u64 * movie_timescale as u64 / self.trak.mdia.mdhd.timescale as u64;
755+ if self.trak.tkhd.duration > (u32::MAX as u64) {
756+ self.trak.tkhd.version = 1
757+ }
758+ }
759+
760+ pub(crate) fn write_sample<W: Write + Seek>(
761+ &mut self,
762+ writer: &mut W,
763+ sample: &Mp4Sample,
764+ movie_timescale: u32,
765+ ) -> Result<u64> {
766+ self.chunk_buffer.extend_from_slice(&sample.bytes);
767+ self.chunk_samples += 1;
768+ self.chunk_duration += sample.duration;
769+ self.update_sample_sizes(sample.bytes.len() as u32);
770+ self.update_sample_times(sample.duration);
771+ self.update_rendering_offsets(sample.rendering_offset);
772+ self.update_sync_samples(sample.is_sync);
773+ if self.is_chunk_full() {
774+ self.write_chunk(writer)?;
775+ }
776+ self.update_durations(sample.duration, movie_timescale);
777+
778+ self.sample_id += 1;
779+
780+ Ok(self.trak.tkhd.duration)
781+ }
782+
783+ fn chunk_count(&self) -> u32 {
784+ let co64 = self.trak.mdia.minf.stbl.co64.as_ref().unwrap();
785+ co64.entries.len() as u32
786+ }
787+
788+ fn update_sample_to_chunk(&mut self, chunk_id: u32) {
789+ if let Some(entry) = self.trak.mdia.minf.stbl.stsc.entries.last() {
790+ if entry.samples_per_chunk == self.chunk_samples {
791+ return;
792+ }
793+ }
794+
795+ let entry = StscEntry {
796+ first_chunk: chunk_id,
797+ samples_per_chunk: self.chunk_samples,
798+ sample_description_index: 1,
799+ first_sample: self.sample_id - self.chunk_samples + 1,
800+ };
801+ self.trak.mdia.minf.stbl.stsc.entries.push(entry);
802+ }
803+
804+ fn update_chunk_offsets(&mut self, offset: u64) {
805+ let co64 = self.trak.mdia.minf.stbl.co64.as_mut().unwrap();
806+ co64.entries.push(offset);
807+ }
808+
809+ fn write_chunk<W: Write + Seek>(&mut self, writer: &mut W) -> Result<()> {
810+ if self.chunk_buffer.is_empty() {
811+ return Ok(());
812+ }
813+ let chunk_offset = writer.stream_position()?;
814+
815+ writer.write_all(&self.chunk_buffer)?;
816+
817+ self.update_sample_to_chunk(self.chunk_count() + 1);
818+ self.update_chunk_offsets(chunk_offset);
819+
820+ self.chunk_buffer.clear();
821+ self.chunk_samples = 0;
822+ self.chunk_duration = 0;
823+
824+ Ok(())
825+ }
826+
827+ fn max_sample_size(&self) -> u32 {
828+ if self.trak.mdia.minf.stbl.stsz.sample_size > 0 {
829+ self.trak.mdia.minf.stbl.stsz.sample_size
830+ } else {
831+ let mut max_size = 0;
832+ for sample_size in self.trak.mdia.minf.stbl.stsz.sample_sizes.iter() {
833+ max_size = cmp::max(max_size, *sample_size);
834+ }
835+ max_size
836+ }
837+ }
838+
839+ pub(crate) fn write_end<W: Write + Seek>(&mut self, writer: &mut W) -> Result<TrakBox> {
840+ self.write_chunk(writer)?;
841+
842+ let max_sample_size = self.max_sample_size();
843+ if let Some(ref mut mp4a) = self.trak.mdia.minf.stbl.stsd.mp4a {
844+ if let Some(ref mut esds) = mp4a.esds {
845+ esds.es_desc.dec_config.buffer_size_db = max_sample_size;
846+ }
847+ // TODO
848+ // mp4a.esds.es_desc.dec_config.max_bitrate
849+ // mp4a.esds.es_desc.dec_config.avg_bitrate
850+ }
851+ if let Ok(stco) = StcoBox::try_from(self.trak.mdia.minf.stbl.co64.as_ref().unwrap()) {
852+ self.trak.mdia.minf.stbl.stco = Some(stco);
853+ self.trak.mdia.minf.stbl.co64 = None;
854+ }
855+
856+ Ok(self.trak.clone())
857+ }
858+}
vendor/mp4/src/types.rsadded+735 -0
@@ -0,0 +1,735 @@
1+use serde::Serialize;
2+use std::borrow::Cow;
3+use std::convert::TryFrom;
4+use std::fmt;
5+
6+use crate::mp4box::*;
7+use crate::*;
8+
9+pub use bytes::Bytes;
10+pub use num_rational::Ratio;
11+
12+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
13+pub struct FixedPointU8(Ratio<u16>);
14+
15+impl FixedPointU8 {
16+ pub fn new(val: u8) -> Self {
17+ Self(Ratio::new_raw(val as u16 * 0x100, 0x100))
18+ }
19+
20+ pub fn new_raw(val: u16) -> Self {
21+ Self(Ratio::new_raw(val, 0x100))
22+ }
23+
24+ pub fn value(&self) -> u8 {
25+ self.0.to_integer() as u8
26+ }
27+
28+ pub fn raw_value(&self) -> u16 {
29+ *self.0.numer()
30+ }
31+}
32+
33+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
34+pub struct FixedPointI8(Ratio<i16>);
35+
36+impl FixedPointI8 {
37+ pub fn new(val: i8) -> Self {
38+ Self(Ratio::new_raw(val as i16 * 0x100, 0x100))
39+ }
40+
41+ pub fn new_raw(val: i16) -> Self {
42+ Self(Ratio::new_raw(val, 0x100))
43+ }
44+
45+ pub fn value(&self) -> i8 {
46+ self.0.to_integer() as i8
47+ }
48+
49+ pub fn raw_value(&self) -> i16 {
50+ *self.0.numer()
51+ }
52+}
53+
54+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
55+pub struct FixedPointU16(Ratio<u32>);
56+
57+impl FixedPointU16 {
58+ pub fn new(val: u16) -> Self {
59+ Self(Ratio::new_raw(val as u32 * 0x10000, 0x10000))
60+ }
61+
62+ pub fn new_raw(val: u32) -> Self {
63+ Self(Ratio::new_raw(val, 0x10000))
64+ }
65+
66+ pub fn value(&self) -> u16 {
67+ self.0.to_integer() as u16
68+ }
69+
70+ pub fn raw_value(&self) -> u32 {
71+ *self.0.numer()
72+ }
73+}
74+
75+impl fmt::Debug for BoxType {
76+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
77+ let fourcc: FourCC = From::from(*self);
78+ write!(f, "{fourcc}")
79+ }
80+}
81+
82+impl fmt::Display for BoxType {
83+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
84+ let fourcc: FourCC = From::from(*self);
85+ write!(f, "{fourcc}")
86+ }
87+}
88+
89+#[derive(Default, PartialEq, Eq, Clone, Copy, Serialize)]
90+pub struct FourCC {
91+ pub value: [u8; 4],
92+}
93+
94+impl std::str::FromStr for FourCC {
95+ type Err = Error;
96+
97+ fn from_str(s: &str) -> Result<Self> {
98+ if let [a, b, c, d] = s.as_bytes() {
99+ Ok(Self {
100+ value: [*a, *b, *c, *d],
101+ })
102+ } else {
103+ Err(Error::InvalidData("expected exactly four bytes in string"))
104+ }
105+ }
106+}
107+
108+impl From<u32> for FourCC {
109+ fn from(number: u32) -> Self {
110+ FourCC {
111+ value: number.to_be_bytes(),
112+ }
113+ }
114+}
115+
116+impl From<FourCC> for u32 {
117+ fn from(fourcc: FourCC) -> u32 {
118+ (&fourcc).into()
119+ }
120+}
121+
122+impl From<&FourCC> for u32 {
123+ fn from(fourcc: &FourCC) -> u32 {
124+ u32::from_be_bytes(fourcc.value)
125+ }
126+}
127+
128+impl From<[u8; 4]> for FourCC {
129+ fn from(value: [u8; 4]) -> FourCC {
130+ FourCC { value }
131+ }
132+}
133+
134+impl From<BoxType> for FourCC {
135+ fn from(t: BoxType) -> FourCC {
136+ let box_num: u32 = Into::into(t);
137+ From::from(box_num)
138+ }
139+}
140+
141+impl fmt::Debug for FourCC {
142+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
143+ let code: u32 = self.into();
144+ let string = String::from_utf8_lossy(&self.value[..]);
145+ write!(f, "{string} / {code:#010X}")
146+ }
147+}
148+
149+impl fmt::Display for FourCC {
150+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
151+ write!(f, "{}", String::from_utf8_lossy(&self.value[..]))
152+ }
153+}
154+
155+const DISPLAY_TYPE_VIDEO: &str = "Video";
156+const DISPLAY_TYPE_AUDIO: &str = "Audio";
157+const DISPLAY_TYPE_SUBTITLE: &str = "Subtitle";
158+
159+const HANDLER_TYPE_VIDEO: &str = "vide";
160+const HANDLER_TYPE_VIDEO_FOURCC: [u8; 4] = [b'v', b'i', b'd', b'e'];
161+
162+const HANDLER_TYPE_AUDIO: &str = "soun";
163+const HANDLER_TYPE_AUDIO_FOURCC: [u8; 4] = [b's', b'o', b'u', b'n'];
164+
165+const HANDLER_TYPE_SUBTITLE: &str = "sbtl";
166+const HANDLER_TYPE_SUBTITLE_FOURCC: [u8; 4] = [b's', b'b', b't', b'l'];
167+
168+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
169+pub enum TrackType {
170+ Video,
171+ Audio,
172+ Subtitle,
173+}
174+
175+impl fmt::Display for TrackType {
176+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
177+ let s = match self {
178+ TrackType::Video => DISPLAY_TYPE_VIDEO,
179+ TrackType::Audio => DISPLAY_TYPE_AUDIO,
180+ TrackType::Subtitle => DISPLAY_TYPE_SUBTITLE,
181+ };
182+ write!(f, "{s}")
183+ }
184+}
185+
186+impl TryFrom<&str> for TrackType {
187+ type Error = Error;
188+ fn try_from(handler: &str) -> Result<TrackType> {
189+ match handler {
190+ HANDLER_TYPE_VIDEO => Ok(TrackType::Video),
191+ HANDLER_TYPE_AUDIO => Ok(TrackType::Audio),
192+ HANDLER_TYPE_SUBTITLE => Ok(TrackType::Subtitle),
193+ _ => Err(Error::InvalidData("unsupported handler type")),
194+ }
195+ }
196+}
197+
198+impl TryFrom<&FourCC> for TrackType {
199+ type Error = Error;
200+ fn try_from(fourcc: &FourCC) -> Result<TrackType> {
201+ match fourcc.value {
202+ HANDLER_TYPE_VIDEO_FOURCC => Ok(TrackType::Video),
203+ HANDLER_TYPE_AUDIO_FOURCC => Ok(TrackType::Audio),
204+ HANDLER_TYPE_SUBTITLE_FOURCC => Ok(TrackType::Subtitle),
205+ _ => Err(Error::InvalidData("unsupported handler type")),
206+ }
207+ }
208+}
209+
210+impl From<TrackType> for FourCC {
211+ fn from(t: TrackType) -> FourCC {
212+ match t {
213+ TrackType::Video => HANDLER_TYPE_VIDEO_FOURCC.into(),
214+ TrackType::Audio => HANDLER_TYPE_AUDIO_FOURCC.into(),
215+ TrackType::Subtitle => HANDLER_TYPE_SUBTITLE_FOURCC.into(),
216+ }
217+ }
218+}
219+
220+const MEDIA_TYPE_H264: &str = "h264";
221+const MEDIA_TYPE_H265: &str = "h265";
222+const MEDIA_TYPE_VP9: &str = "vp9";
223+const MEDIA_TYPE_AAC: &str = "aac";
224+const MEDIA_TYPE_TTXT: &str = "ttxt";
225+
226+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
227+pub enum MediaType {
228+ H264,
229+ H265,
230+ VP9,
231+ AAC,
232+ TTXT,
233+}
234+
235+impl fmt::Display for MediaType {
236+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
237+ let s: &str = self.into();
238+ write!(f, "{s}")
239+ }
240+}
241+
242+impl TryFrom<&str> for MediaType {
243+ type Error = Error;
244+ fn try_from(media: &str) -> Result<MediaType> {
245+ match media {
246+ MEDIA_TYPE_H264 => Ok(MediaType::H264),
247+ MEDIA_TYPE_H265 => Ok(MediaType::H265),
248+ MEDIA_TYPE_VP9 => Ok(MediaType::VP9),
249+ MEDIA_TYPE_AAC => Ok(MediaType::AAC),
250+ MEDIA_TYPE_TTXT => Ok(MediaType::TTXT),
251+ _ => Err(Error::InvalidData("unsupported media type")),
252+ }
253+ }
254+}
255+
256+impl From<MediaType> for &str {
257+ fn from(t: MediaType) -> &'static str {
258+ match t {
259+ MediaType::H264 => MEDIA_TYPE_H264,
260+ MediaType::H265 => MEDIA_TYPE_H265,
261+ MediaType::VP9 => MEDIA_TYPE_VP9,
262+ MediaType::AAC => MEDIA_TYPE_AAC,
263+ MediaType::TTXT => MEDIA_TYPE_TTXT,
264+ }
265+ }
266+}
267+
268+impl From<&MediaType> for &str {
269+ fn from(t: &MediaType) -> &'static str {
270+ match t {
271+ MediaType::H264 => MEDIA_TYPE_H264,
272+ MediaType::H265 => MEDIA_TYPE_H265,
273+ MediaType::VP9 => MEDIA_TYPE_VP9,
274+ MediaType::AAC => MEDIA_TYPE_AAC,
275+ MediaType::TTXT => MEDIA_TYPE_TTXT,
276+ }
277+ }
278+}
279+
280+#[derive(Debug, PartialEq, Eq, Clone, Copy)]
281+pub enum AvcProfile {
282+ AvcConstrainedBaseline, // 66 with constraint set 1
283+ AvcBaseline, // 66,
284+ AvcMain, // 77,
285+ AvcExtended, // 88,
286+ AvcHigh, // 100
287+ // TODO Progressive High Profile, Constrained High Profile, ...
288+}
289+
290+impl TryFrom<(u8, u8)> for AvcProfile {
291+ type Error = Error;
292+ fn try_from(value: (u8, u8)) -> Result<AvcProfile> {
293+ let profile = value.0;
294+ let constraint_set1_flag = (value.1 & 0x40) >> 7;
295+ match (profile, constraint_set1_flag) {
296+ (66, 1) => Ok(AvcProfile::AvcConstrainedBaseline),
297+ (66, 0) => Ok(AvcProfile::AvcBaseline),
298+ (77, _) => Ok(AvcProfile::AvcMain),
299+ (88, _) => Ok(AvcProfile::AvcExtended),
300+ (100, _) => Ok(AvcProfile::AvcHigh),
301+ _ => Err(Error::InvalidData("unsupported avc profile")),
302+ }
303+ }
304+}
305+
306+impl fmt::Display for AvcProfile {
307+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
308+ let profile = match self {
309+ AvcProfile::AvcConstrainedBaseline => "Constrained Baseline",
310+ AvcProfile::AvcBaseline => "Baseline",
311+ AvcProfile::AvcMain => "Main",
312+ AvcProfile::AvcExtended => "Extended",
313+ AvcProfile::AvcHigh => "High",
314+ };
315+ write!(f, "{profile}")
316+ }
317+}
318+
319+#[derive(Debug, PartialEq, Eq, Clone, Copy)]
320+pub enum AudioObjectType {
321+ AacMain = 1, // AAC Main Profile
322+ AacLowComplexity = 2, // AAC Low Complexity
323+ AacScalableSampleRate = 3, // AAC Scalable Sample Rate
324+ AacLongTermPrediction = 4, // AAC Long Term Predictor
325+ SpectralBandReplication = 5, // Spectral band Replication
326+ AACScalable = 6, // AAC Scalable
327+ TwinVQ = 7, // Twin VQ
328+ CodeExcitedLinearPrediction = 8, // CELP
329+ HarmonicVectorExcitationCoding = 9, // HVXC
330+ TextToSpeechtInterface = 12, // TTSI
331+ MainSynthetic = 13, // Main Synthetic
332+ WavetableSynthesis = 14, // Wavetable Synthesis
333+ GeneralMIDI = 15, // General MIDI
334+ AlgorithmicSynthesis = 16, // Algorithmic Synthesis
335+ ErrorResilientAacLowComplexity = 17, // ER AAC LC
336+ ErrorResilientAacLongTermPrediction = 19, // ER AAC LTP
337+ ErrorResilientAacScalable = 20, // ER AAC Scalable
338+ ErrorResilientAacTwinVQ = 21, // ER AAC TwinVQ
339+ ErrorResilientAacBitSlicedArithmeticCoding = 22, // ER Bit Sliced Arithmetic Coding
340+ ErrorResilientAacLowDelay = 23, // ER AAC Low Delay
341+ ErrorResilientCodeExcitedLinearPrediction = 24, // ER CELP
342+ ErrorResilientHarmonicVectorExcitationCoding = 25, // ER HVXC
343+ ErrorResilientHarmonicIndividualLinesNoise = 26, // ER HILN
344+ ErrorResilientParametric = 27, // ER Parametric
345+ SinuSoidalCoding = 28, // SSC
346+ ParametricStereo = 29, // PS
347+ MpegSurround = 30, // MPEG Surround
348+ MpegLayer1 = 32, // MPEG Layer 1
349+ MpegLayer2 = 33, // MPEG Layer 2
350+ MpegLayer3 = 34, // MPEG Layer 3
351+ DirectStreamTransfer = 35, // DST Direct Stream Transfer
352+ AudioLosslessCoding = 36, // ALS Audio Lossless Coding
353+ ScalableLosslessCoding = 37, // SLC Scalable Lossless Coding
354+ ScalableLosslessCodingNoneCore = 38, // SLC non-core
355+ ErrorResilientAacEnhancedLowDelay = 39, // ER AAC ELD
356+ SymbolicMusicRepresentationSimple = 40, // SMR Simple
357+ SymbolicMusicRepresentationMain = 41, // SMR Main
358+ UnifiedSpeechAudioCoding = 42, // USAC
359+ SpatialAudioObjectCoding = 43, // SAOC
360+ LowDelayMpegSurround = 44, // LD MPEG Surround
361+ SpatialAudioObjectCodingDialogueEnhancement = 45, // SAOC-DE
362+ AudioSync = 46, // Audio Sync
363+}
364+
365+impl TryFrom<u8> for AudioObjectType {
366+ type Error = Error;
367+ fn try_from(value: u8) -> Result<AudioObjectType> {
368+ match value {
369+ 1 => Ok(AudioObjectType::AacMain),
370+ 2 => Ok(AudioObjectType::AacLowComplexity),
371+ 3 => Ok(AudioObjectType::AacScalableSampleRate),
372+ 4 => Ok(AudioObjectType::AacLongTermPrediction),
373+ 5 => Ok(AudioObjectType::SpectralBandReplication),
374+ 6 => Ok(AudioObjectType::AACScalable),
375+ 7 => Ok(AudioObjectType::TwinVQ),
376+ 8 => Ok(AudioObjectType::CodeExcitedLinearPrediction),
377+ 9 => Ok(AudioObjectType::HarmonicVectorExcitationCoding),
378+ 12 => Ok(AudioObjectType::TextToSpeechtInterface),
379+ 13 => Ok(AudioObjectType::MainSynthetic),
380+ 14 => Ok(AudioObjectType::WavetableSynthesis),
381+ 15 => Ok(AudioObjectType::GeneralMIDI),
382+ 16 => Ok(AudioObjectType::AlgorithmicSynthesis),
383+ 17 => Ok(AudioObjectType::ErrorResilientAacLowComplexity),
384+ 19 => Ok(AudioObjectType::ErrorResilientAacLongTermPrediction),
385+ 20 => Ok(AudioObjectType::ErrorResilientAacScalable),
386+ 21 => Ok(AudioObjectType::ErrorResilientAacTwinVQ),
387+ 22 => Ok(AudioObjectType::ErrorResilientAacBitSlicedArithmeticCoding),
388+ 23 => Ok(AudioObjectType::ErrorResilientAacLowDelay),
389+ 24 => Ok(AudioObjectType::ErrorResilientCodeExcitedLinearPrediction),
390+ 25 => Ok(AudioObjectType::ErrorResilientHarmonicVectorExcitationCoding),
391+ 26 => Ok(AudioObjectType::ErrorResilientHarmonicIndividualLinesNoise),
392+ 27 => Ok(AudioObjectType::ErrorResilientParametric),
393+ 28 => Ok(AudioObjectType::SinuSoidalCoding),
394+ 29 => Ok(AudioObjectType::ParametricStereo),
395+ 30 => Ok(AudioObjectType::MpegSurround),
396+ 32 => Ok(AudioObjectType::MpegLayer1),
397+ 33 => Ok(AudioObjectType::MpegLayer2),
398+ 34 => Ok(AudioObjectType::MpegLayer3),
399+ 35 => Ok(AudioObjectType::DirectStreamTransfer),
400+ 36 => Ok(AudioObjectType::AudioLosslessCoding),
401+ 37 => Ok(AudioObjectType::ScalableLosslessCoding),
402+ 38 => Ok(AudioObjectType::ScalableLosslessCodingNoneCore),
403+ 39 => Ok(AudioObjectType::ErrorResilientAacEnhancedLowDelay),
404+ 40 => Ok(AudioObjectType::SymbolicMusicRepresentationSimple),
405+ 41 => Ok(AudioObjectType::SymbolicMusicRepresentationMain),
406+ 42 => Ok(AudioObjectType::UnifiedSpeechAudioCoding),
407+ 43 => Ok(AudioObjectType::SpatialAudioObjectCoding),
408+ 44 => Ok(AudioObjectType::LowDelayMpegSurround),
409+ 45 => Ok(AudioObjectType::SpatialAudioObjectCodingDialogueEnhancement),
410+ 46 => Ok(AudioObjectType::AudioSync),
411+ _ => Err(Error::InvalidData("invalid audio object type")),
412+ }
413+ }
414+}
415+
416+impl fmt::Display for AudioObjectType {
417+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
418+ let type_str = match self {
419+ AudioObjectType::AacMain => "AAC Main",
420+ AudioObjectType::AacLowComplexity => "LC",
421+ AudioObjectType::AacScalableSampleRate => "SSR",
422+ AudioObjectType::AacLongTermPrediction => "LTP",
423+ AudioObjectType::SpectralBandReplication => "SBR",
424+ AudioObjectType::AACScalable => "Scalable",
425+ AudioObjectType::TwinVQ => "TwinVQ",
426+ AudioObjectType::CodeExcitedLinearPrediction => "CELP",
427+ AudioObjectType::HarmonicVectorExcitationCoding => "HVXC",
428+ AudioObjectType::TextToSpeechtInterface => "TTSI",
429+ AudioObjectType::MainSynthetic => "Main Synthetic",
430+ AudioObjectType::WavetableSynthesis => "Wavetable Synthesis",
431+ AudioObjectType::GeneralMIDI => "General MIDI",
432+ AudioObjectType::AlgorithmicSynthesis => "Algorithmic Synthesis",
433+ AudioObjectType::ErrorResilientAacLowComplexity => "ER AAC LC",
434+ AudioObjectType::ErrorResilientAacLongTermPrediction => "ER AAC LTP",
435+ AudioObjectType::ErrorResilientAacScalable => "ER AAC scalable",
436+ AudioObjectType::ErrorResilientAacTwinVQ => "ER AAC TwinVQ",
437+ AudioObjectType::ErrorResilientAacBitSlicedArithmeticCoding => "ER AAC BSAC",
438+ AudioObjectType::ErrorResilientAacLowDelay => "ER AAC LD",
439+ AudioObjectType::ErrorResilientCodeExcitedLinearPrediction => "ER CELP",
440+ AudioObjectType::ErrorResilientHarmonicVectorExcitationCoding => "ER HVXC",
441+ AudioObjectType::ErrorResilientHarmonicIndividualLinesNoise => "ER HILN",
442+ AudioObjectType::ErrorResilientParametric => "ER Parametric",
443+ AudioObjectType::SinuSoidalCoding => "SSC",
444+ AudioObjectType::ParametricStereo => "Parametric Stereo",
445+ AudioObjectType::MpegSurround => "MPEG surround",
446+ AudioObjectType::MpegLayer1 => "MPEG Layer 1",
447+ AudioObjectType::MpegLayer2 => "MPEG Layer 2",
448+ AudioObjectType::MpegLayer3 => "MPEG Layer 3",
449+ AudioObjectType::DirectStreamTransfer => "DST",
450+ AudioObjectType::AudioLosslessCoding => "ALS",
451+ AudioObjectType::ScalableLosslessCoding => "SLS",
452+ AudioObjectType::ScalableLosslessCodingNoneCore => "SLS Non-core",
453+ AudioObjectType::ErrorResilientAacEnhancedLowDelay => "ER AAC ELD",
454+ AudioObjectType::SymbolicMusicRepresentationSimple => "SMR Simple",
455+ AudioObjectType::SymbolicMusicRepresentationMain => "SMR Main",
456+ AudioObjectType::UnifiedSpeechAudioCoding => "USAC",
457+ AudioObjectType::SpatialAudioObjectCoding => "SAOC",
458+ AudioObjectType::LowDelayMpegSurround => "LD MPEG Surround",
459+ AudioObjectType::SpatialAudioObjectCodingDialogueEnhancement => "SAOC-DE",
460+ AudioObjectType::AudioSync => "Audio Sync",
461+ };
462+ write!(f, "{type_str}")
463+ }
464+}
465+
466+#[derive(Debug, PartialEq, Eq, Clone, Copy)]
467+pub enum SampleFreqIndex {
468+ Freq96000 = 0x0,
469+ Freq88200 = 0x1,
470+ Freq64000 = 0x2,
471+ Freq48000 = 0x3,
472+ Freq44100 = 0x4,
473+ Freq32000 = 0x5,
474+ Freq24000 = 0x6,
475+ Freq22050 = 0x7,
476+ Freq16000 = 0x8,
477+ Freq12000 = 0x9,
478+ Freq11025 = 0xa,
479+ Freq8000 = 0xb,
480+ Freq7350 = 0xc,
481+}
482+
483+impl TryFrom<u8> for SampleFreqIndex {
484+ type Error = Error;
485+ fn try_from(value: u8) -> Result<SampleFreqIndex> {
486+ match value {
487+ 0x0 => Ok(SampleFreqIndex::Freq96000),
488+ 0x1 => Ok(SampleFreqIndex::Freq88200),
489+ 0x2 => Ok(SampleFreqIndex::Freq64000),
490+ 0x3 => Ok(SampleFreqIndex::Freq48000),
491+ 0x4 => Ok(SampleFreqIndex::Freq44100),
492+ 0x5 => Ok(SampleFreqIndex::Freq32000),
493+ 0x6 => Ok(SampleFreqIndex::Freq24000),
494+ 0x7 => Ok(SampleFreqIndex::Freq22050),
495+ 0x8 => Ok(SampleFreqIndex::Freq16000),
496+ 0x9 => Ok(SampleFreqIndex::Freq12000),
497+ 0xa => Ok(SampleFreqIndex::Freq11025),
498+ 0xb => Ok(SampleFreqIndex::Freq8000),
499+ 0xc => Ok(SampleFreqIndex::Freq7350),
500+ _ => Err(Error::InvalidData("invalid sampling frequency index")),
501+ }
502+ }
503+}
504+
505+impl SampleFreqIndex {
506+ pub fn freq(&self) -> u32 {
507+ match *self {
508+ SampleFreqIndex::Freq96000 => 96000,
509+ SampleFreqIndex::Freq88200 => 88200,
510+ SampleFreqIndex::Freq64000 => 64000,
511+ SampleFreqIndex::Freq48000 => 48000,
512+ SampleFreqIndex::Freq44100 => 44100,
513+ SampleFreqIndex::Freq32000 => 32000,
514+ SampleFreqIndex::Freq24000 => 24000,
515+ SampleFreqIndex::Freq22050 => 22050,
516+ SampleFreqIndex::Freq16000 => 16000,
517+ SampleFreqIndex::Freq12000 => 12000,
518+ SampleFreqIndex::Freq11025 => 11025,
519+ SampleFreqIndex::Freq8000 => 8000,
520+ SampleFreqIndex::Freq7350 => 7350,
521+ }
522+ }
523+}
524+
525+#[derive(Debug, PartialEq, Eq, Clone, Copy)]
526+pub enum ChannelConfig {
527+ Mono = 0x1,
528+ Stereo = 0x2,
529+ Three = 0x3,
530+ Four = 0x4,
531+ Five = 0x5,
532+ FiveOne = 0x6,
533+ SevenOne = 0x7,
534+}
535+
536+impl TryFrom<u8> for ChannelConfig {
537+ type Error = Error;
538+ fn try_from(value: u8) -> Result<ChannelConfig> {
539+ match value {
540+ 0x1 => Ok(ChannelConfig::Mono),
541+ 0x2 => Ok(ChannelConfig::Stereo),
542+ 0x3 => Ok(ChannelConfig::Three),
543+ 0x4 => Ok(ChannelConfig::Four),
544+ 0x5 => Ok(ChannelConfig::Five),
545+ 0x6 => Ok(ChannelConfig::FiveOne),
546+ 0x7 => Ok(ChannelConfig::SevenOne),
547+ _ => Err(Error::InvalidData("invalid channel configuration")),
548+ }
549+ }
550+}
551+
552+impl fmt::Display for ChannelConfig {
553+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
554+ let s = match self {
555+ ChannelConfig::Mono => "mono",
556+ ChannelConfig::Stereo => "stereo",
557+ ChannelConfig::Three => "three",
558+ ChannelConfig::Four => "four",
559+ ChannelConfig::Five => "five",
560+ ChannelConfig::FiveOne => "five.one",
561+ ChannelConfig::SevenOne => "seven.one",
562+ };
563+ write!(f, "{s}")
564+ }
565+}
566+
567+#[derive(Debug, PartialEq, Eq, Clone, Default)]
568+pub struct AvcConfig {
569+ pub width: u16,
570+ pub height: u16,
571+ pub seq_param_set: Vec<u8>,
572+ pub pic_param_set: Vec<u8>,
573+}
574+
575+#[derive(Debug, PartialEq, Eq, Clone, Default)]
576+pub struct HevcConfig {
577+ pub width: u16,
578+ pub height: u16,
579+}
580+
581+#[derive(Debug, PartialEq, Eq, Clone, Default)]
582+pub struct Vp9Config {
583+ pub width: u16,
584+ pub height: u16,
585+}
586+
587+#[derive(Debug, PartialEq, Eq, Clone)]
588+pub struct AacConfig {
589+ pub bitrate: u32,
590+ pub profile: AudioObjectType,
591+ pub freq_index: SampleFreqIndex,
592+ pub chan_conf: ChannelConfig,
593+}
594+
595+impl Default for AacConfig {
596+ fn default() -> Self {
597+ Self {
598+ bitrate: 0,
599+ profile: AudioObjectType::AacLowComplexity,
600+ freq_index: SampleFreqIndex::Freq48000,
601+ chan_conf: ChannelConfig::Stereo,
602+ }
603+ }
604+}
605+
606+#[derive(Debug, PartialEq, Eq, Clone, Default)]
607+pub struct TtxtConfig {}
608+
609+#[derive(Debug, PartialEq, Eq, Clone)]
610+pub enum MediaConfig {
611+ AvcConfig(AvcConfig),
612+ HevcConfig(HevcConfig),
613+ Vp9Config(Vp9Config),
614+ AacConfig(AacConfig),
615+ TtxtConfig(TtxtConfig),
616+}
617+
618+#[derive(Debug)]
619+pub struct Mp4Sample {
620+ pub start_time: u64,
621+ pub duration: u32,
622+ pub rendering_offset: i32,
623+ pub is_sync: bool,
624+ pub bytes: Bytes,
625+}
626+
627+impl PartialEq for Mp4Sample {
628+ fn eq(&self, other: &Self) -> bool {
629+ self.start_time == other.start_time
630+ && self.duration == other.duration
631+ && self.rendering_offset == other.rendering_offset
632+ && self.is_sync == other.is_sync
633+ && self.bytes.len() == other.bytes.len() // XXX for easy check
634+ }
635+}
636+
637+impl fmt::Display for Mp4Sample {
638+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
639+ write!(
640+ f,
641+ "start_time {}, duration {}, rendering_offset {}, is_sync {}, length {}",
642+ self.start_time,
643+ self.duration,
644+ self.rendering_offset,
645+ self.is_sync,
646+ self.bytes.len()
647+ )
648+ }
649+}
650+
651+pub fn creation_time(creation_time: u64) -> u64 {
652+ // convert from MP4 epoch (1904-01-01) to Unix epoch (1970-01-01)
653+ if creation_time >= 2082844800 {
654+ creation_time - 2082844800
655+ } else {
656+ creation_time
657+ }
658+}
659+
660+#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize)]
661+pub enum DataType {
662+ #[default]
663+ Binary = 0x000000,
664+ Text = 0x000001,
665+ Image = 0x00000D,
666+ TempoCpil = 0x000015,
667+}
668+
669+impl TryFrom<u32> for DataType {
670+ type Error = Error;
671+ fn try_from(value: u32) -> Result<DataType> {
672+ match value {
673+ 0x000000 => Ok(DataType::Binary),
674+ 0x000001 => Ok(DataType::Text),
675+ 0x00000D => Ok(DataType::Image),
676+ 0x000015 => Ok(DataType::TempoCpil),
677+ _ => Err(Error::InvalidData("invalid data type")),
678+ }
679+ }
680+}
681+
682+#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
683+pub enum MetadataKey {
684+ Title,
685+ Year,
686+ Poster,
687+ Summary,
688+}
689+
690+pub trait Metadata<'a> {
691+ /// The video's title
692+ fn title(&self) -> Option<Cow<'_, str>>;
693+ /// The video's release year
694+ fn year(&self) -> Option<u32>;
695+ /// The video's poster (cover art)
696+ fn poster(&self) -> Option<&[u8]>;
697+ /// The video's summary
698+ fn summary(&self) -> Option<Cow<'_, str>>;
699+}
700+
701+impl<'a, T: Metadata<'a>> Metadata<'a> for &'a T {
702+ fn title(&self) -> Option<Cow<'_, str>> {
703+ (**self).title()
704+ }
705+
706+ fn year(&self) -> Option<u32> {
707+ (**self).year()
708+ }
709+
710+ fn poster(&self) -> Option<&[u8]> {
711+ (**self).poster()
712+ }
713+
714+ fn summary(&self) -> Option<Cow<'_, str>> {
715+ (**self).summary()
716+ }
717+}
718+
719+impl<'a, T: Metadata<'a>> Metadata<'a> for Option<T> {
720+ fn title(&self) -> Option<Cow<'_, str>> {
721+ self.as_ref().and_then(|t| t.title())
722+ }
723+
724+ fn year(&self) -> Option<u32> {
725+ self.as_ref().and_then(|t| t.year())
726+ }
727+
728+ fn poster(&self) -> Option<&[u8]> {
729+ self.as_ref().and_then(|t| t.poster())
730+ }
731+
732+ fn summary(&self) -> Option<Cow<'_, str>> {
733+ self.as_ref().and_then(|t| t.summary())
734+ }
735+}
vendor/mp4/src/writer.rsadded+148 -0
@@ -0,0 +1,148 @@
1+use byteorder::{BigEndian, WriteBytesExt};
2+use std::io::{Seek, SeekFrom, Write};
3+
4+use crate::track::Mp4TrackWriter;
5+use crate::*;
6+
7+#[derive(Debug, Clone, PartialEq, Eq)]
8+pub struct Mp4Config {
9+ pub major_brand: FourCC,
10+ pub minor_version: u32,
11+ pub compatible_brands: Vec<FourCC>,
12+ pub timescale: u32,
13+}
14+
15+#[derive(Debug)]
16+pub struct Mp4Writer<W> {
17+ writer: W,
18+ tracks: Vec<Mp4TrackWriter>,
19+ mdat_pos: u64,
20+ timescale: u32,
21+ duration: u64,
22+}
23+
24+impl<W> Mp4Writer<W> {
25+ /// Consume self, returning the inner writer.
26+ ///
27+ /// This can be useful to recover the inner writer after completion in case
28+ /// it's owned by the [Mp4Writer] instance.
29+ ///
30+ /// # Examples
31+ ///
32+ /// ```rust
33+ /// use mp4::{Mp4Writer, Mp4Config};
34+ /// use std::io::Cursor;
35+ ///
36+ /// # fn main() -> mp4::Result<()> {
37+ /// let config = Mp4Config {
38+ /// major_brand: str::parse("isom").unwrap(),
39+ /// minor_version: 512,
40+ /// compatible_brands: vec![
41+ /// str::parse("isom").unwrap(),
42+ /// str::parse("iso2").unwrap(),
43+ /// str::parse("avc1").unwrap(),
44+ /// str::parse("mp41").unwrap(),
45+ /// ],
46+ /// timescale: 1000,
47+ /// };
48+ ///
49+ /// let data = Cursor::new(Vec::<u8>::new());
50+ /// let mut writer = mp4::Mp4Writer::write_start(data, &config)?;
51+ /// writer.write_end()?;
52+ ///
53+ /// let data: Vec<u8> = writer.into_writer().into_inner();
54+ /// # Ok(()) }
55+ /// ```
56+ pub fn into_writer(self) -> W {
57+ self.writer
58+ }
59+}
60+
61+impl<W: Write + Seek> Mp4Writer<W> {
62+ pub fn write_start(mut writer: W, config: &Mp4Config) -> Result<Self> {
63+ let ftyp = FtypBox {
64+ major_brand: config.major_brand,
65+ minor_version: config.minor_version,
66+ compatible_brands: config.compatible_brands.clone(),
67+ };
68+ ftyp.write_box(&mut writer)?;
69+
70+ // TODO largesize
71+ let mdat_pos = writer.stream_position()?;
72+ BoxHeader::new(BoxType::MdatBox, HEADER_SIZE).write(&mut writer)?;
73+ BoxHeader::new(BoxType::WideBox, HEADER_SIZE).write(&mut writer)?;
74+
75+ let tracks = Vec::new();
76+ let timescale = config.timescale;
77+ let duration = 0;
78+ Ok(Self {
79+ writer,
80+ tracks,
81+ mdat_pos,
82+ timescale,
83+ duration,
84+ })
85+ }
86+
87+ pub fn add_track(&mut self, config: &TrackConfig) -> Result<()> {
88+ let track_id = self.tracks.len() as u32 + 1;
89+ let track = Mp4TrackWriter::new(track_id, config)?;
90+ self.tracks.push(track);
91+ Ok(())
92+ }
93+
94+ fn update_durations(&mut self, track_dur: u64) {
95+ if track_dur > self.duration {
96+ self.duration = track_dur;
97+ }
98+ }
99+
100+ pub fn write_sample(&mut self, track_id: u32, sample: &Mp4Sample) -> Result<()> {
101+ if track_id == 0 {
102+ return Err(Error::TrakNotFound(track_id));
103+ }
104+
105+ let track_dur = if let Some(ref mut track) = self.tracks.get_mut(track_id as usize - 1) {
106+ track.write_sample(&mut self.writer, sample, self.timescale)?
107+ } else {
108+ return Err(Error::TrakNotFound(track_id));
109+ };
110+
111+ self.update_durations(track_dur);
112+
113+ Ok(())
114+ }
115+
116+ fn update_mdat_size(&mut self) -> Result<()> {
117+ let mdat_end = self.writer.stream_position()?;
118+ let mdat_size = mdat_end - self.mdat_pos;
119+ if mdat_size > std::u32::MAX as u64 {
120+ self.writer.seek(SeekFrom::Start(self.mdat_pos))?;
121+ self.writer.write_u32::<BigEndian>(1)?;
122+ self.writer.seek(SeekFrom::Start(self.mdat_pos + 8))?;
123+ self.writer.write_u64::<BigEndian>(mdat_size)?;
124+ } else {
125+ self.writer.seek(SeekFrom::Start(self.mdat_pos))?;
126+ self.writer.write_u32::<BigEndian>(mdat_size as u32)?;
127+ }
128+ self.writer.seek(SeekFrom::Start(mdat_end))?;
129+ Ok(())
130+ }
131+
132+ pub fn write_end(&mut self) -> Result<()> {
133+ let mut moov = MoovBox::default();
134+
135+ for track in self.tracks.iter_mut() {
136+ moov.traks.push(track.write_end(&mut self.writer)?);
137+ }
138+ self.update_mdat_size()?;
139+
140+ moov.mvhd.timescale = self.timescale;
141+ moov.mvhd.duration = self.duration;
142+ if moov.mvhd.duration > (u32::MAX as u64) {
143+ moov.mvhd.version = 1
144+ }
145+ moov.write_box(&mut self.writer)?;
146+ Ok(())
147+ }
148+}