Skip to main content

mp4/mp4box/
ilst.rs

1use std::borrow::Cow;
2use std::collections::HashMap;
3use std::io::{Read, Seek};
4
5use byteorder::ByteOrder;
6use serde::Serialize;
7
8use crate::mp4box::data::DataBox;
9use crate::mp4box::*;
10
11#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize)]
12pub struct IlstBox {
13    pub items: HashMap<MetadataKey, IlstItemBox>,
14}
15
16impl IlstBox {
17    pub fn get_type(&self) -> BoxType {
18        BoxType::IlstBox
19    }
20
21    pub fn get_size(&self) -> u64 {
22        let mut size = HEADER_SIZE;
23        for item in self.items.values() {
24            size += item.get_size();
25        }
26        size
27    }
28}
29
30impl Mp4Box for IlstBox {
31    fn box_type(&self) -> BoxType {
32        self.get_type()
33    }
34
35    fn box_size(&self) -> u64 {
36        self.get_size()
37    }
38
39    fn to_json(&self) -> Result<String> {
40        Ok(serde_json::to_string(&self).unwrap())
41    }
42
43    fn summary(&self) -> Result<String> {
44        let s = format!("item_count={}", self.items.len());
45        Ok(s)
46    }
47}
48
49impl<R: Read + Seek> ReadBox<&mut R> for IlstBox {
50    fn read_box(reader: &mut R, size: u64) -> Result<Self> {
51        let start = box_start(reader)?;
52
53        let mut items = HashMap::new();
54
55        let mut current = reader.stream_position()?;
56        let end = start + size;
57        while current < end {
58            // Get box header.
59            let header = BoxHeader::read(reader)?;
60            let BoxHeader { name, size: s } = header;
61            if s > size {
62                return Err(Error::InvalidData(
63                    "ilst box contains a box with a larger size than it",
64                ));
65            }
66
67            match name {
68                BoxType::NameBox => {
69                    items.insert(MetadataKey::Title, IlstItemBox::read_box(reader, s)?);
70                }
71                BoxType::DayBox => {
72                    items.insert(MetadataKey::Year, IlstItemBox::read_box(reader, s)?);
73                }
74                BoxType::CovrBox => {
75                    items.insert(MetadataKey::Poster, IlstItemBox::read_box(reader, s)?);
76                }
77                BoxType::DescBox => {
78                    items.insert(MetadataKey::Summary, IlstItemBox::read_box(reader, s)?);
79                }
80                _ => {
81                    // XXX warn!()
82                    skip_box(reader, s)?;
83                }
84            }
85
86            current = reader.stream_position()?;
87        }
88
89        skip_bytes_to(reader, start + size)?;
90
91        Ok(IlstBox { items })
92    }
93}
94
95impl<W: Write> WriteBox<&mut W> for IlstBox {
96    fn write_box(&self, writer: &mut W) -> Result<u64> {
97        let size = self.box_size();
98        BoxHeader::new(self.box_type(), size).write(writer)?;
99
100        for (key, value) in &self.items {
101            let name = match key {
102                MetadataKey::Title => BoxType::NameBox,
103                MetadataKey::Year => BoxType::DayBox,
104                MetadataKey::Poster => BoxType::CovrBox,
105                MetadataKey::Summary => BoxType::DescBox,
106            };
107            BoxHeader::new(name, value.get_size()).write(writer)?;
108            value.data.write_box(writer)?;
109        }
110        Ok(size)
111    }
112}
113
114#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize)]
115pub struct IlstItemBox {
116    pub data: DataBox,
117}
118
119impl IlstItemBox {
120    fn get_size(&self) -> u64 {
121        HEADER_SIZE + self.data.box_size()
122    }
123}
124
125impl<R: Read + Seek> ReadBox<&mut R> for IlstItemBox {
126    fn read_box(reader: &mut R, size: u64) -> Result<Self> {
127        let start = box_start(reader)?;
128
129        let mut data = None;
130
131        let mut current = reader.stream_position()?;
132        let end = start + size;
133        while current < end {
134            // Get box header.
135            let header = BoxHeader::read(reader)?;
136            let BoxHeader { name, size: s } = header;
137            if s > size {
138                return Err(Error::InvalidData(
139                    "ilst item box contains a box with a larger size than it",
140                ));
141            }
142
143            match name {
144                BoxType::DataBox => {
145                    data = Some(DataBox::read_box(reader, s)?);
146                }
147                _ => {
148                    // XXX warn!()
149                    skip_box(reader, s)?;
150                }
151            }
152
153            current = reader.stream_position()?;
154        }
155
156        if data.is_none() {
157            return Err(Error::BoxNotFound(BoxType::DataBox));
158        }
159
160        skip_bytes_to(reader, start + size)?;
161
162        Ok(IlstItemBox {
163            data: data.unwrap(),
164        })
165    }
166}
167
168impl<'a> Metadata<'a> for IlstBox {
169    fn title(&self) -> Option<Cow<str>> {
170        self.items.get(&MetadataKey::Title).map(item_to_str)
171    }
172
173    fn year(&self) -> Option<u32> {
174        self.items.get(&MetadataKey::Year).and_then(item_to_u32)
175    }
176
177    fn poster(&self) -> Option<&[u8]> {
178        self.items.get(&MetadataKey::Poster).map(item_to_bytes)
179    }
180
181    fn summary(&self) -> Option<Cow<str>> {
182        self.items.get(&MetadataKey::Summary).map(item_to_str)
183    }
184}
185
186fn item_to_bytes(item: &IlstItemBox) -> &[u8] {
187    &item.data.data
188}
189
190fn item_to_str(item: &IlstItemBox) -> Cow<str> {
191    String::from_utf8_lossy(&item.data.data)
192}
193
194fn item_to_u32(item: &IlstItemBox) -> Option<u32> {
195    match item.data.data_type {
196        DataType::Binary if item.data.data.len() == 4 => Some(BigEndian::read_u32(&item.data.data)),
197        DataType::Text => String::from_utf8_lossy(&item.data.data).parse::<u32>().ok(),
198        _ => None,
199    }
200}
201
202#[cfg(test)]
203mod tests {
204    use super::*;
205    use crate::mp4box::BoxHeader;
206    use std::io::Cursor;
207
208    #[test]
209    fn test_ilst() {
210        let src_year = IlstItemBox {
211            data: DataBox {
212                data_type: DataType::Text,
213                data: b"test_year".to_vec(),
214            },
215        };
216        let src_box = IlstBox {
217            items: [
218                (MetadataKey::Title, IlstItemBox::default()),
219                (MetadataKey::Year, src_year),
220                (MetadataKey::Poster, IlstItemBox::default()),
221                (MetadataKey::Summary, IlstItemBox::default()),
222            ]
223            .into(),
224        };
225        let mut buf = Vec::new();
226        src_box.write_box(&mut buf).unwrap();
227        assert_eq!(buf.len(), src_box.box_size() as usize);
228
229        let mut reader = Cursor::new(&buf);
230        let header = BoxHeader::read(&mut reader).unwrap();
231        assert_eq!(header.name, BoxType::IlstBox);
232        assert_eq!(src_box.box_size(), header.size);
233
234        let dst_box = IlstBox::read_box(&mut reader, header.size).unwrap();
235        assert_eq!(src_box, dst_box);
236    }
237
238    #[test]
239    fn test_ilst_empty() {
240        let src_box = IlstBox::default();
241        let mut buf = Vec::new();
242        src_box.write_box(&mut buf).unwrap();
243        assert_eq!(buf.len(), src_box.box_size() as usize);
244
245        let mut reader = Cursor::new(&buf);
246        let header = BoxHeader::read(&mut reader).unwrap();
247        assert_eq!(header.name, BoxType::IlstBox);
248        assert_eq!(src_box.box_size(), header.size);
249
250        let dst_box = IlstBox::read_box(&mut reader, header.size).unwrap();
251        assert_eq!(src_box, dst_box);
252    }
253}