flowly-mp4 0.1.0

MP4 reader and writer library in Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
use bytes::{BufMut, Bytes, BytesMut};
use flowly::Fourcc;
use std::collections::BTreeSet;

use crate::ctts::CttsEntry;
use crate::error::Error;
use crate::stsc::StscEntry;
use crate::stts::SttsEntry;
use crate::{BoxType, TrackType};

#[derive(Clone)]
pub struct Mp4SampleOffset {
    pub offset: u64,
    pub size: u32,
    pub duration: u32,
    pub start_time: u64,
    pub rendering_offset: i32,
    pub is_sync: bool,
    pub chunk_id: u32,
}

#[derive(Clone)]
pub struct Mp4Track {
    pub track_id: u32,
    pub duration: u64,
    pub samples: Vec<Mp4SampleOffset>,
    pub tkhd: crate::TkhdBox,
    pub mdia: crate::MdiaBox,
}

impl Mp4Track {
    pub fn new(trak: crate::TrakBox, offsets: &mut BTreeSet<u64>) -> Result<Mp4Track, Error> {
        let default_sample_duration = 1024;
        let mut total_duration = 0;
        let mut samples = Vec::with_capacity(trak.mdia.minf.stbl.stsz.sample_count as _);
        let stco = &trak.mdia.minf.stbl.stco;
        let co64 = &trak.mdia.minf.stbl.co64;

        let mb_iter1 = stco.clone().map(IntoIterator::into_iter);
        let mb_iter2 = co64.clone().map(IntoIterator::into_iter);

        if let Some(stco) = co64.as_ref().map(IntoIterator::into_iter) {
            offsets.extend(stco);
        }

        if let Some(stco) = stco.as_ref().map(IntoIterator::into_iter) {
            offsets.extend(stco);
        }

        let chunk_iter = chunk_iter(
            trak.mdia.minf.stbl.stsc.entries.clone().into_iter(),
            mb_iter1
                .into_iter()
                .flatten()
                .chain(mb_iter2.into_iter().flatten()),
        );

        let mut sample_chunk_iter = run_len_iter(chunk_iter);

        let sync_iter_peek = trak
            .mdia
            .minf
            .stbl
            .stss
            .as_ref()
            .map(|x| x.entries.iter().copied().peekable());

        let mut sync_iter =
            (1..=trak.mdia.minf.stbl.stsz.sample_count).scan(sync_iter_peek, |iter, idx| {
                let iter = iter.as_mut()?;

                Some(if idx == iter.peek().copied().unwrap_or(u32::MAX) {
                    iter.next();
                    true
                } else {
                    false
                })
            });

        let mut ts_deltas =
            run_len_iter(trak.mdia.minf.stbl.stts.entries.clone().into_iter().chain(
                std::iter::once(SttsEntry {
                    sample_count: u32::MAX,
                    sample_delta: default_sample_duration,
                }),
            ))
            .scan(0u64, |s, delta| {
                let out = *s;
                *s += delta as u64;
                Some((out, delta))
            });

        let mut rend_offset_iter = run_len_iter(
            trak.mdia
                .minf
                .stbl
                .ctts
                .clone()
                .into_iter()
                .flat_map(|x| x.entries.into_iter()),
        );

        let mut sample_offset = 0;
        let mut curr_chunk_index = 0;
        let mut prev_size = 0;

        for sample_idx in 0..trak.mdia.minf.stbl.stsz.sample_count as usize {
            let (start_time, duration) = ts_deltas.next().unwrap();
            let chunk = sample_chunk_iter.next().unwrap();
            let size = *trak
                .mdia
                .minf
                .stbl
                .stsz
                .sample_sizes
                .get(sample_idx)
                .unwrap_or(&trak.mdia.minf.stbl.stsz.sample_size);

            if curr_chunk_index != chunk.index {
                curr_chunk_index = chunk.index;
                sample_offset = 0;
            } else {
                sample_offset += prev_size;
            }

            prev_size = size;
            total_duration = start_time + duration as u64;
            samples.push(Mp4SampleOffset {
                chunk_id: chunk.index,
                offset: chunk.offset + sample_offset as u64,
                size,
                duration,
                start_time,
                rendering_offset: rend_offset_iter.next().unwrap_or(0),
                is_sync: sync_iter.next().unwrap_or(true),
            })
        }

        Ok(Self {
            track_id: trak.tkhd.track_id,
            tkhd: trak.tkhd,
            mdia: trak.mdia,
            samples,
            duration: total_duration,
        })
    }

    #[inline]
    pub fn track_type(&self) -> TrackType {
        TrackType::from(&self.mdia.hdlr.handler_type)
    }

    #[inline]
    pub fn codec(&self) -> Fourcc {
        if self.mdia.minf.stbl.stsd.avc1.is_some() {
            Fourcc::VIDEO_AVC
        } else if self.mdia.minf.stbl.stsd.hev1.is_some() {
            Fourcc::VIDEO_HEVC
        } else if self.mdia.minf.stbl.stsd.vp09.is_some() {
            Fourcc::VIDEO_VP9
        } else if self.mdia.minf.stbl.stsd.mp4a.is_some() {
            Fourcc::AUDIO_AAC
        } else if self.mdia.minf.stbl.stsd.tx3g.is_some() {
            Fourcc::from_static("TTXT")
        } else {
            Default::default()
        }
    }

    pub(crate) fn add_traf(
        &mut self,
        base_moof_offset: u64,
        chunk_index: u32,
        traf: crate::TrafBox,
        offsets: &mut BTreeSet<u64>,
    ) {
        let base_data_offset = traf.tfhd.base_data_offset.unwrap_or(base_moof_offset);
        offsets.insert(base_data_offset);

        let default_sample_size = traf.tfhd.default_sample_size.unwrap_or(0);
        let default_sample_duration = traf.tfhd.default_sample_duration.unwrap_or(0);
        let base_start_time = traf
            .tfdt
            .map(|x| x.base_media_decode_time)
            .or_else(|| {
                self.samples
                    .last()
                    .map(|x| x.start_time + x.duration as u64)
            })
            .unwrap_or(0);

        let Some(trun) = traf.trun else {
            return;
        };

        let mut sample_offset = 0u64;
        let mut start_time_offset = 0u64;
        for sample_idx in 0..trun.sample_count as usize {
            let size = trun
                .sample_sizes
                .get(sample_idx)
                .copied()
                .unwrap_or(default_sample_size);

            let duration = trun
                .sample_durations
                .get(sample_idx)
                .copied()
                .unwrap_or(default_sample_duration);

            let rendering_offset = trun.sample_cts.get(sample_idx).copied().unwrap_or(0) as i32;

            self.samples.push(Mp4SampleOffset {
                chunk_id: chunk_index,
                offset: (base_data_offset as i64
                    + trun.data_offset.map(|x| x as i64).unwrap_or(0)
                    + sample_offset as i64) as u64,
                size,
                duration,
                start_time: base_start_time + start_time_offset,
                rendering_offset,
                is_sync: sample_idx == 0,
            });

            sample_offset += size as u64;
            start_time_offset += duration as u64;
        }
    }

    pub fn sequence_parameter_set(&self) -> Result<&[u8], Error> {
        if let Some(ref avc1) = self.mdia.minf.stbl.stsd.avc1 {
            match avc1.avcc.sequence_parameter_sets.first() {
                Some(nal) => Ok(nal.bytes.as_ref()),
                None => Err(Error::EntryInStblNotFound(
                    self.track_id,
                    BoxType::AvcCBox,
                    0,
                )),
            }
        } else {
            Err(Error::BoxInStblNotFound(self.track_id, BoxType::Avc1Box))
        }
    }

    pub fn picture_parameter_set(&self) -> Result<&[u8], Error> {
        if let Some(ref avc1) = self.mdia.minf.stbl.stsd.avc1 {
            match avc1.avcc.picture_parameter_sets.first() {
                Some(nal) => Ok(nal.bytes.as_ref()),
                None => Err(Error::EntryInStblNotFound(
                    self.track_id,
                    BoxType::AvcCBox,
                    0,
                )),
            }
        } else {
            Err(Error::BoxInStblNotFound(self.track_id, BoxType::Avc1Box))
        }
    }

    pub fn decode_params(&self) -> Option<Bytes> {
        match self.codec() {
            Fourcc::VIDEO_AVC => {
                let mut buf = BytesMut::new();

                let sps = self.sequence_parameter_set().unwrap();
                buf.put_u32(sps.len() as u32 + 4);
                buf.put_slice(&[0, 0, 0, 1]);
                buf.put_slice(sps);

                let pps = self.picture_parameter_set().unwrap();
                buf.put_u32(pps.len() as u32 + 4);
                buf.put_slice(&[0, 0, 0, 1]);
                buf.put_slice(pps);

                Some(buf.freeze())
            }

            Fourcc::VIDEO_HEVC => {
                let mut buf = BytesMut::new();
                let x = self.mdia.minf.stbl.stsd.hev1.as_ref().unwrap();
                for arr in &x.hvcc.arrays {
                    for nalu in &arr.nalus {
                        buf.put_u32(nalu.data.len() as u32 + 4);
                        buf.put_slice(&[0, 0, 0, 1]);
                        buf.put_slice(&nalu.data);
                    }
                }
                Some(buf.freeze())
            }

            _ => None,
        }
    }

    #[inline]
    pub fn timescale(&self) -> u32 {
        self.mdia.mdhd.timescale
    }
}

trait RunLenghtItem {
    type Value: Clone;

    fn count(&self) -> usize;
    fn value(&self) -> Self::Value;
}

impl<T: Clone> RunLenghtItem for (usize, T) {
    type Value = T;

    fn count(&self) -> usize {
        self.0
    }
    fn value(&self) -> Self::Value {
        self.1.clone()
    }
}

impl RunLenghtItem for CttsEntry {
    type Value = i32;

    fn count(&self) -> usize {
        self.sample_count as _
    }

    fn value(&self) -> Self::Value {
        self.sample_offset
    }
}

impl RunLenghtItem for SttsEntry {
    type Value = u32;

    fn count(&self) -> usize {
        self.sample_count as _
    }

    fn value(&self) -> Self::Value {
        self.sample_delta
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Chunk {
    pub index: u32,
    pub offset: u64,
    pub samples_per_chunk: u32,
    pub sample_description_index: u32,
}

impl RunLenghtItem for Chunk {
    type Value = Chunk;

    fn count(&self) -> usize {
        self.samples_per_chunk as _
    }

    fn value(&self) -> Self::Value {
        *self
    }
}

fn chunk_iter(
    mut stsc: impl Iterator<Item = StscEntry>,
    stco: impl Iterator<Item = u64>,
) -> impl Iterator<Item = Chunk> {
    let mut prev = stsc.next().unwrap_or(StscEntry {
        first_chunk: 1,
        samples_per_chunk: u32::MAX,
        sample_description_index: 1,
        first_sample: 1,
    });
    let mut curr = stsc.next();

    stco.enumerate().map(move |(idx, offset)| {
        if let Some(c) = &curr {
            if idx + 1 >= c.first_chunk as usize {
                prev = *c;
                curr = stsc.next();
            }
        }

        Chunk {
            index: idx as _,
            offset,
            samples_per_chunk: prev.samples_per_chunk,
            sample_description_index: prev.sample_description_index,
        }
    })
}

fn run_len_iter<E: RunLenghtItem, I: IntoIterator<Item = E>>(
    iter: I,
) -> impl Iterator<Item = E::Value> {
    let mut iter = iter.into_iter();
    let mut value = None::<E::Value>;
    let mut repeat = 0;
    std::iter::from_fn(move || loop {
        if let Some(val) = &value {
            if repeat > 0 {
                repeat -= 1;
                return Some(val.clone());
            } else {
                value = None;
            }
        }

        let x = iter.next()?;
        value = Some(x.value());
        repeat = x.count();
    })
}