mp4/mp4box/
stsz.rs

1use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
2use serde::Serialize;
3use std::io::{Read, Seek, Write};
4use std::mem::size_of;
5
6use crate::mp4box::*;
7
8#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize)]
9pub 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
19impl 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
29impl 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
53impl<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
99impl<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)]
122mod 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}