forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

edit_trim.rs183 lines, 6.9 KiBHistoryRawDownload
1//! The audio edit's duration: an `elst` that plays a track's media for a stated
2//! length rather than to its end, written by [`Mp4Muxer::set_edit`].
3//!
4//! Also the default-output pin: a file muxed without `set_edit` is byte-identical to
5//! what the writer produced before the call existed, held by an MD5.
6
7use std::io::Cursor;
8use std::path::Path;
9use std::process::Command;
10
11use ec_core::{Buf, CodecId, Muxer, Packet, StreamInfo, TimeBase};
12use ec_mp4::{Mp4Demuxer, Mp4Muxer};
13
14/// A 48 kHz stereo AAC-LC track's stream description.
15fn aac_stream() -> StreamInfo {
16 let rate = TimeBase::from_rate(48_000);
17 let mut info = StreamInfo::new(0, rate, ec_core::CodecParameters::new(CodecId::Aac));
18 if let ec_core::MediaParameters::Audio(a) = &mut info.params.media {
19 a.sample_rate = 48_000;
20 a.layout = ec_core::ChannelLayout::Stereo;
21 }
22 info.params.extradata = Some(Buf::copy_from_slice(&[0x11, 0x90])); // AAC-LC 48k stereo ASC
23 info
24}
25
26/// `frames` AAC frames of 1024 samples each, laid end to end, the way
27/// `aac_priming_round_trips_through_an_elst` writes them.
28fn aac_packets(frames: i64) -> Vec<Packet> {
29 let rate = TimeBase::from_rate(48_000);
30 (0..frames)
31 .map(|_| {
32 let mut packet = Packet::new(0, rate, vec![0u8; 8]);
33 packet.duration = Some(1024);
34 packet.flags.keyframe = true;
35 packet
36 })
37 .collect()
38}
39
40/// The default path: AAC with a priming delay and no edit duration, as the file
41/// stood before `set_edit` existed.
42fn default_output() -> Vec<u8> {
43 let mut muxer = Mp4Muxer::new(Cursor::new(Vec::new())).expect("muxer");
44 let stream = muxer.add_stream(aac_stream()).expect("stream");
45 muxer.set_audio_delay(stream, 1024).expect("declare delay");
46 for packet in aac_packets(47) {
47 muxer.write_packet(&packet).expect("packet");
48 }
49 muxer.finish().expect("finish");
50 muxer.into_inner().into_inner()
51}
52
53/// The MD5 of `bytes`, from the `md5sum` tool. A missing tool skips the check.
54fn md5_of(bytes: &[u8]) -> Option<String> {
55 let dir = std::env::temp_dir().join("ec-mp4-edit-trim");
56 std::fs::create_dir_all(&dir).ok()?;
57 let path = dir.join(format!("md5-{}.mp4", std::process::id()));
58 std::fs::write(&path, bytes).ok()?;
59 let out = Command::new("md5sum").arg(&path).output().ok()?;
60 let _ = std::fs::remove_file(&path);
61 String::from_utf8_lossy(&out.stdout)
62 .split_whitespace()
63 .next()
64 .map(str::to_string)
65}
66
67/// Pinned before `set_edit` was added: the default output of the AAC priming
68/// case must not change by a byte.
69const DEFAULT_AAC_PRIMING_MD5: &str = "2ba0fd44a7dfa3b69cb60d7aceb71753";
70
71#[test]
72fn default_aac_priming_output_is_byte_identical() {
73 let bytes = default_output();
74 match md5_of(&bytes) {
75 Some(sum) => assert_eq!(sum, DEFAULT_AAC_PRIMING_MD5, "default output changed"),
76 None => eprintln!("skip: md5sum is not installed"),
77 }
78}
79
80/// The big-endian `u32` at `offset` into the payload of the first `kind` box in
81/// `bytes`, where a full box's `version/flags` word is the first four bytes.
82fn payload_u32(bytes: &[u8], kind: &[u8; 4], offset: usize) -> Option<u32> {
83 let at = bytes.windows(4).position(|w| w == kind)? + 4;
84 let raw = bytes.get(at + offset..at + offset + 4)?;
85 Some(u32::from_be_bytes([raw[0], raw[1], raw[2], raw[3]]))
86}
87
88/// `key=value` lines from `ffprobe`, keyed by name. `None` where ffprobe is not
89/// installed, which skips the check.
90fn ffprobe_fields(path: &Path, select: &str, entries: &str) -> Option<Vec<(String, String)>> {
91 let out = Command::new("ffprobe")
92 .args([
93 "-v",
94 "error",
95 "-select_streams",
96 select,
97 "-show_entries",
98 entries,
99 ])
100 .args(["-of", "default=nw=1"])
101 .arg(path)
102 .output()
103 .ok()?;
104 let text = String::from_utf8_lossy(&out.stdout);
105 Some(
106 text.lines()
107 .filter_map(|line| line.split_once('='))
108 .map(|(k, v)| (k.to_string(), v.to_string()))
109 .collect(),
110 )
111}
112
113fn field(fields: &[(String, String)], key: &str) -> f64 {
114 fields
115 .iter()
116 .find(|(k, _)| k == key)
117 .and_then(|(_, v)| v.parse().ok())
118 .unwrap_or(f64::NAN)
119}
120
121#[test]
122fn set_edit_trims_the_audio_edit_to_its_stated_length() {
123 // 47 AAC frames of 1024 samples is 48128 samples of media; the edit plays
124 // 40000 of them after the 1024-sample priming, a picture that ends early.
125 const PRIMING: u32 = 1024;
126 const PICTURE: u32 = 40_000;
127 let mut muxer = Mp4Muxer::new(Cursor::new(Vec::new())).expect("muxer");
128 let stream = muxer.add_stream(aac_stream()).expect("stream");
129 muxer.set_edit(stream, PRIMING, PICTURE).expect("edit set");
130 for packet in aac_packets(47) {
131 muxer.write_packet(&packet).expect("packet");
132 }
133 muxer.finish().expect("finish");
134 let bytes = muxer.into_inner().into_inner();
135
136 // The movie clock is 1000 Hz, so the picture's length is 833.33 ms, rounded up
137 // to 834. The track's `tkhd` and the movie's `mvhd` state the same length.
138 let expected_movie = 834;
139 assert_eq!(
140 payload_u32(&bytes, b"tkhd", 20),
141 Some(expected_movie),
142 "tkhd"
143 );
144 assert_eq!(
145 payload_u32(&bytes, b"mvhd", 16),
146 Some(expected_movie),
147 "mvhd"
148 );
149 assert_eq!(payload_u32(&bytes, b"mvhd", 12), Some(1000), "movie clock");
150
151 // This crate reads the edit back as it was written.
152 let demuxer = Mp4Demuxer::new(Cursor::new(bytes.clone())).expect("reopens");
153 let tracks = demuxer.tracks();
154 let edits = &tracks[0].edits;
155 assert_eq!(edits.len(), 1, "one edit entry");
156 assert_eq!(edits[0].segment_duration, u64::from(expected_movie));
157 assert_eq!(edits[0].media_time, i64::from(PRIMING));
158 assert_eq!(tracks[0].media_time, Some(i64::from(PRIMING)));
159
160 // ffprobe reads the stream as the picture's length, starting at zero, to
161 // within one AAC frame.
162 let path = std::env::temp_dir()
163 .join("ec-mp4-edit-trim")
164 .join(format!("trim-{}.mp4", std::process::id()));
165 std::fs::create_dir_all(path.parent().expect("dir")).expect("work dir");
166 std::fs::write(&path, &bytes).expect("write");
167 let stream_fields = ffprobe_fields(&path, "a:0", "stream=start_time,duration");
168 if let Some(fields) = stream_fields {
169 let frame = 1024.0 / 48_000.0;
170 let want = f64::from(PICTURE) / 48_000.0;
171 let duration = field(&fields, "duration");
172 let start = field(&fields, "start_time");
173 eprintln!("ffprobe a:0 start_time {start} duration {duration} (picture {want})");
174 assert!(
175 (duration - want).abs() <= frame,
176 "stream duration {duration} against the picture's {want}"
177 );
178 assert!(start.abs() < 1e-6, "start_time {start} is not zero");
179 } else {
180 eprintln!("skip ffprobe: not installed");
181 }
182 let _ = std::fs::remove_file(&path);
183}