flowly_mp4/mp4box/
stsc.rs

1use byteorder::{BigEndian, WriteBytesExt};
2use serde::Serialize;
3use std::io::Write;
4use std::mem::size_of;
5
6use crate::mp4box::*;
7
8#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize)]
9pub struct StscBox {
10    pub version: u8,
11    pub flags: u32,
12
13    #[serde(skip_serializing)]
14    pub entries: Vec<StscEntry>,
15}
16
17impl 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, Copy, PartialEq, Eq, Default, Serialize)]
28pub 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
35impl Mp4Box for StscBox {
36    const TYPE: BoxType = BoxType::StscBox;
37
38    fn box_size(&self) -> u64 {
39        self.get_size()
40    }
41
42    fn to_json(&self) -> Result<String, Error> {
43        Ok(serde_json::to_string(&self).unwrap())
44    }
45
46    fn summary(&self) -> Result<String, Error> {
47        let s = format!("entries={}", self.entries.len());
48        Ok(s)
49    }
50}
51
52impl BlockReader for StscBox {
53    fn read_block<'a>(reader: &mut impl Reader<'a>) -> Result<Self, Error> {
54        let (version, flags) = read_box_header_ext(reader);
55
56        let entry_size = size_of::<u32>() + size_of::<u32>() + size_of::<u32>(); // first_chunk + samples_per_chunk + sample_description_index
57        let entry_count = reader.get_u32();
58        if entry_count as usize > reader.remaining() / entry_size {
59            return Err(Error::InvalidData(
60                "stsc entry_count indicates more entries than could fit in the box",
61            ));
62        }
63        let mut entries = Vec::with_capacity(entry_count as usize);
64        for _ in 0..entry_count {
65            let entry = StscEntry {
66                first_chunk: reader.get_u32(),
67                samples_per_chunk: reader.get_u32(),
68                sample_description_index: reader.get_u32(),
69                first_sample: 0,
70            };
71            entries.push(entry);
72        }
73
74        let mut sample_id = 1;
75        for i in 0..entry_count {
76            let (first_chunk, samples_per_chunk) = {
77                let entry = entries.get_mut(i as usize).unwrap();
78                entry.first_sample = sample_id;
79                (entry.first_chunk, entry.samples_per_chunk)
80            };
81            if i < entry_count - 1 {
82                let next_entry = entries.get(i as usize + 1).unwrap();
83                sample_id = next_entry
84                    .first_chunk
85                    .checked_sub(first_chunk)
86                    .and_then(|n| n.checked_mul(samples_per_chunk))
87                    .and_then(|n| n.checked_add(sample_id))
88                    .ok_or(Error::InvalidData(
89                        "attempt to calculate stsc sample_id with overflow",
90                    ))?;
91            }
92        }
93
94        Ok(StscBox {
95            version,
96            flags,
97            entries,
98        })
99    }
100
101    fn size_hint() -> usize {
102        8
103    }
104}
105
106impl<W: Write> WriteBox<&mut W> for StscBox {
107    fn write_box(&self, writer: &mut W) -> Result<u64, Error> {
108        let size = self.box_size();
109        BoxHeader::new(Self::TYPE, size).write(writer)?;
110
111        write_box_header_ext(writer, self.version, self.flags)?;
112
113        writer.write_u32::<BigEndian>(self.entries.len() as u32)?;
114        for entry in self.entries.iter() {
115            writer.write_u32::<BigEndian>(entry.first_chunk)?;
116            writer.write_u32::<BigEndian>(entry.samples_per_chunk)?;
117            writer.write_u32::<BigEndian>(entry.sample_description_index)?;
118        }
119
120        Ok(size)
121    }
122}
123
124#[cfg(test)]
125mod tests {
126    use super::*;
127    use crate::mp4box::BoxHeader;
128
129    #[tokio::test]
130    async fn test_stsc() {
131        let src_box = StscBox {
132            version: 0,
133            flags: 0,
134            entries: vec![
135                StscEntry {
136                    first_chunk: 1,
137                    samples_per_chunk: 1,
138                    sample_description_index: 1,
139                    first_sample: 1,
140                },
141                StscEntry {
142                    first_chunk: 19026,
143                    samples_per_chunk: 14,
144                    sample_description_index: 1,
145                    first_sample: 19026,
146                },
147            ],
148        };
149        let mut buf = Vec::new();
150        src_box.write_box(&mut buf).unwrap();
151        assert_eq!(buf.len(), src_box.box_size() as usize);
152
153        let mut reader = buf.as_slice();
154        let header = BoxHeader::read(&mut reader, &mut 0).await.unwrap().unwrap();
155        assert_eq!(header.kind, BoxType::StscBox);
156        assert_eq!(src_box.box_size(), header.size);
157
158        let dst_box = StscBox::read_block(&mut reader).unwrap();
159        assert_eq!(src_box, dst_box);
160    }
161}