forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB2e2ed69Tahinli3 months ago69 commits

demux.rs298 lines, 11.8 KiBHistoryRawDownload
1//! MP4 demux: pulls the H.264 track out as Annex-B access units.
2
3use std::fs::File;
4use std::io::BufReader;
5use std::path::Path;
6
7use mp4::{MediaType, Mp4Reader, Mp4Track};
8
9use crate::audio::{edit_media_time, packet_at, stts_pairs};
10
11const START_CODE: [u8; 4] = [0, 0, 0, 1];
12
13#[derive(Debug, Clone, Copy, PartialEq)]
14pub struct VideoMeta {
15 pub width: u32,
16 pub height: u32,
17 pub frame_rate: f64,
18 pub frame_count: u32,
19}
20
21pub struct Demuxer {
22 reader: Mp4Reader<BufReader<File>>,
23 track_id: u32,
24 sample_count: u32,
25 /// 1-based sample id of *frame 0*: the edit list can start the presentation
26 /// a couple of frames into the media, exactly as it does for audio priming
27 /// (`audio::priming_samples`), and frame indices count from there.
28 first_sample: u32,
29 /// Annex-B SPS+PPS, re-injected ahead of every sync sample.
30 parameter_sets: Vec<u8>,
31 /// `stss` entries, ascending 1-based sample ids. Empty means no `stss` box
32 /// at all, i.e. every sample is a sync sample.
33 sync_samples: Vec<u32>,
34 next_sample: u32,
35}
36
37impl Demuxer {
38 pub fn open(path: &Path) -> crate::Result<(VideoMeta, Self)> {
39 let file = File::open(path)?;
40 let size = file.metadata()?.len();
41 let reader = Mp4Reader::read_header(BufReader::new(file), size)?;
42
43 let track = reader
44 .tracks()
45 .values()
46 .find(|t| matches!(t.media_type(), Ok(MediaType::H264)))
47 .ok_or("no H.264 video track in file")?;
48
49 let track_id = track.track_id();
50 let meta = VideoMeta {
51 width: track.width() as u32,
52 height: track.height() as u32,
53 frame_rate: frame_rate(track),
54 frame_count: 0,
55 };
56 let first_sample = first_frame_sample(stts_pairs(track), trim_ticks(track));
57 let mut parameter_sets = Vec::new();
58 parameter_sets.extend_from_slice(&START_CODE);
59 parameter_sets.extend_from_slice(track.sequence_parameter_set()?);
60 parameter_sets.extend_from_slice(&START_CODE);
61 parameter_sets.extend_from_slice(track.picture_parameter_set()?);
62 let sync_samples = track
63 .trak
64 .mdia
65 .minf
66 .stbl
67 .stss
68 .as_ref()
69 .map(|stss| stss.entries.clone())
70 .unwrap_or_default();
71
72 let sample_count = reader.sample_count(track_id)?;
73 // Where a seek to frame 0 would put the cursor: the samples the edit list
74 // trims are still read, they are references for the ones that show.
75 let next_sample = sync_at_or_before(&sync_samples, first_sample);
76 Ok((
77 VideoMeta {
78 // The samples the edit list trims off the front are not frames of
79 // the presentation, so they are not counted as ones.
80 frame_count: sample_count.saturating_sub(first_sample - 1),
81 ..meta
82 },
83 Self {
84 reader,
85 track_id,
86 sample_count,
87 first_sample,
88 parameter_sets,
89 sync_samples,
90 next_sample,
91 },
92 ))
93 }
94
95 /// Next access unit in decode order, Annex-B framed. `None` at end of track.
96 pub fn next_access_unit(&mut self) -> crate::Result<Option<Vec<u8>>> {
97 if self.next_sample > self.sample_count {
98 return Ok(None);
99 }
100 let sample = self.reader.read_sample(self.track_id, self.next_sample)?;
101 self.next_sample += 1;
102 let Some(sample) = sample else {
103 return Ok(None);
104 };
105
106 let mut au = Vec::with_capacity(self.parameter_sets.len() + sample.bytes.len() + 16);
107 if sample.is_sync {
108 au.extend_from_slice(&self.parameter_sets);
109 }
110 append_annex_b(&sample.bytes, &mut au)?;
111 Ok(Some(au))
112 }
113
114 /// Rewinds/forwards the read cursor to the latest sync sample at or before
115 /// display frame `frame` (0-based), which is the earliest point a decoder can
116 /// start from and still reach it. Returns the display index of the first
117 /// picture the caller will now be handed -- *negative* when the landing sync
118 /// sample sits inside what the edit list trims, i.e. those pictures decode as
119 /// references but are not frame 0 or later.
120 pub fn seek_to_sync_at_or_before(&mut self, frame: u32) -> i64 {
121 let target = frame
122 .saturating_add(self.first_sample)
123 .clamp(1, self.sample_count.max(1));
124 let chosen = sync_at_or_before(&self.sync_samples, target);
125 self.next_sample = chosen;
126 i64::from(chosen) - i64::from(self.first_sample)
127 }
128}
129
130/// Frames per second off the sample table. `mp4 0.14`'s own
131/// [`Mp4Track::frame_rate`] divides the sample count by whole *milliseconds*
132/// before the float cast (`track.rs:166`), so 24000/1001 reads back as a flat
133/// 23.0 -- with the audio clock as master that is 4 % of drift, five minutes of
134/// it by the end of a two-hour film.
135fn frame_rate(track: &Mp4Track) -> f64 {
136 fps_from_stts(stts_pairs(track), track.timescale())
137}
138
139/// Whole track over whole track: constant-delta tables (the common case) come
140/// out as exactly `timescale / delta`, and a table that spreads 3753/3754 ticks
141/// to average 3753.75 averages instead of truncating. All of it in `f64`, which
142/// is the bug the caller above exists to avoid.
143fn fps_from_stts(entries: impl IntoIterator<Item = (u32, u32)>, timescale: u32) -> f64 {
144 let (samples, ticks) =
145 entries
146 .into_iter()
147 .fold((0u64, 0u64), |(samples, ticks), (count, delta)| {
148 (
149 samples + u64::from(count),
150 ticks + u64::from(count) * u64::from(delta),
151 )
152 });
153 match ticks {
154 // No timing in the header at all; `mp4`'s own answer for that is 0.0 too.
155 0 => 0.0,
156 ticks => samples as f64 * f64::from(timescale) / ticks as f64,
157 }
158}
159
160/// What the edit list really trims off the front, in media ticks: its
161/// `media_time` less the first sample's own composition offset. A stream with
162/// B-frames carries a `ctts` delay, and every muxer writes `media_time` equal to
163/// exactly that delay -- which is not a trim at all, it is the container saying
164/// "sample 1 is still the first picture". Reading it as one drops real frames
165/// (`test_high.mp4` loses two, and so did the film this bug came from). What is
166/// left over after the delay is the genuine trim.
167///
168/// ponytail: empty edits are ignored and `media_time` is otherwise taken at face
169/// value, which is exactly what [`crate::audio::edit_media_time`] gives the audio
170/// track -- symmetry between the two is the point, not a full edit-list engine.
171/// Their *empty* edits can differ (83 ms of video against 62 ms of audio in that
172/// film, so the picture stays 21 ms -- half a frame -- early); honouring those is
173/// the upgrade path, and it belongs to both tracks at once.
174fn trim_ticks(track: &Mp4Track) -> Option<u64> {
175 let delay = track
176 .trak
177 .mdia
178 .minf
179 .stbl
180 .ctts
181 .as_ref()
182 .and_then(|ctts| ctts.entries.first())
183 .map_or(0, |e| e.sample_offset.max(0) as u64);
184 edit_media_time(track).map(|t| t.saturating_sub(delay))
185}
186
187/// 1-based id of the sample the presentation starts on, for a track trimmed by
188/// `trim` media ticks ([`trim_ticks`]). `None` (no edit list) and zero are both
189/// "no trim", i.e. the first sample.
190fn first_frame_sample(entries: impl IntoIterator<Item = (u32, u32)>, trim: Option<u64>) -> u32 {
191 trim.map_or(1, |t| packet_at(entries, t, 0).0)
192}
193
194/// Largest entry of the ascending sync table that is `<= sample_id`. An empty
195/// table means every sample is a sync sample. When `sample_id` sits before the
196/// first sync sample there is nothing decodable earlier, so that one wins.
197fn sync_at_or_before(syncs: &[u32], sample_id: u32) -> u32 {
198 if syncs.is_empty() {
199 return sample_id;
200 }
201 match syncs.partition_point(|&s| s <= sample_id) {
202 0 => syncs[0],
203 i => syncs[i - 1],
204 }
205}
206
207/// avcC length-prefixed NALs -> Annex-B. Assumes a 4-byte length prefix, which
208/// mp4 0.14 does not expose; a wrong guess misparses immediately, hence the check.
209///
210/// ponytail: hardcoded 4-byte NAL length prefix (lengthSizeMinusOne == 3). 1/2-byte
211/// prefixes exist in the wild; upgrade path is parsing the avcC box from
212/// `track.trak` instead of assuming.
213fn append_annex_b(mut src: &[u8], out: &mut Vec<u8>) -> crate::Result<()> {
214 while !src.is_empty() {
215 if src.len() < 4 {
216 return Err(format!("truncated NAL length prefix: {} bytes left", src.len()).into());
217 }
218 let len = u32::from_be_bytes([src[0], src[1], src[2], src[3]]) as usize;
219 if len == 0 || len > src.len() - 4 {
220 return Err(format!(
221 "bad NAL length {len} with {} bytes remaining (not a 4-byte-prefixed avcC sample?)",
222 src.len() - 4
223 )
224 .into());
225 }
226 out.extend_from_slice(&START_CODE);
227 out.extend_from_slice(&src[4..4 + len]);
228 src = &src[4 + len..];
229 }
230 Ok(())
231}
232
233#[cfg(test)]
234mod tests {
235 use super::*;
236
237 #[test]
238 fn splits_two_nals() {
239 let mut out = Vec::new();
240 append_annex_b(&[0, 0, 0, 2, 0x65, 0xAA, 0, 0, 0, 1, 0x41], &mut out).unwrap();
241 assert_eq!(out, [0, 0, 0, 1, 0x65, 0xAA, 0, 0, 0, 1, 0x41]);
242 }
243
244 #[test]
245 fn sync_lookup() {
246 assert_eq!(sync_at_or_before(&[], 7), 7, "no stss: every sample syncs");
247 assert_eq!(sync_at_or_before(&[1, 31, 61], 31), 31, "exact hit");
248 assert_eq!(sync_at_or_before(&[1, 31, 61], 45), 31, "between syncs");
249 assert_eq!(sync_at_or_before(&[5, 31], 2), 5, "before the first sync");
250 assert_eq!(sync_at_or_before(&[1, 31, 61], 900), 61, "past the last");
251 }
252
253 /// The desync bug: NTSC rates must survive the sample table as themselves.
254 #[test]
255 fn ntsc_frame_rates_come_out_fractional() {
256 // 24000/1001 on a 90 kHz clock is 3753.75 ticks a frame, so a muxer
257 // spreads 3753/3754 and only the total is exact -- 4 frames, 15015 ticks.
258 let ntsc = fps_from_stts([(1u32, 3753u32), (3, 3754)], 90_000);
259 assert!(
260 (ntsc - 24_000.0 / 1001.0).abs() < 1e-9,
261 "23.976 fps read back as {ntsc} (mp4 0.14 says 23.0)"
262 );
263 // Constant delta stays an exact division, not an average.
264 assert_eq!(fps_from_stts([(300u32, 3000u32)], 90_000), 30.0);
265 assert_eq!(
266 fps_from_stts([(120u32, 1001u32)], 30_000),
267 30_000.0 / 1001.0
268 );
269 assert_eq!(fps_from_stts([(0u32, 0u32)], 90_000), 0.0, "no timing");
270 }
271
272 /// A video edit list trims the head of the media exactly as the audio one
273 /// does; frame 0 is the first frame that is *shown*. The B-frame delay is
274 /// the case that must **not** move it -- that one is a lie of a `media_time`
275 /// and taking it literally throws two real frames away.
276 #[test]
277 fn a_video_edit_list_moves_frame_zero_but_a_ctts_delay_does_not() {
278 let entries = [(1u32, 3753u32), (3, 3754)];
279 // The film's own numbers: media_time 7507 at 90 kHz, and a first ctts
280 // offset of 7507 to go with it -- nothing trimmed.
281 assert_eq!(first_frame_sample(entries, Some(7507 - 7507)), 1);
282 // Two frames genuinely cut off the front.
283 assert_eq!(first_frame_sample(entries, Some(7507)), 3);
284 assert_eq!(
285 first_frame_sample(entries, None),
286 1,
287 "no edit list, no trim"
288 );
289 assert_eq!(first_frame_sample(entries, Some(0)), 1, "zero is no trim");
290 }
291
292 #[test]
293 fn rejects_misparse() {
294 assert!(append_annex_b(&[0, 0, 0, 9, 0x65], &mut Vec::new()).is_err());
295 assert!(append_annex_b(&[0, 0, 0], &mut Vec::new()).is_err());
296 assert!(append_annex_b(&[0, 0, 0, 0], &mut Vec::new()).is_err());
297 }
298}