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
use std::borrow::Cow;
use std::collections::HashMap;
use std::io::{Read, Seek};

use byteorder::ByteOrder;
use serde::Serialize;

use crate::mp4box::data::DataBox;
use crate::mp4box::*;

#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize)]
pub struct IlstBox {
    pub items: HashMap<MetadataKey, IlstItemBox>,
}

impl IlstBox {
    pub fn get_type(&self) -> BoxType {
        BoxType::IlstBox
    }

    pub fn get_size(&self) -> u64 {
        let mut size = HEADER_SIZE;
        for item in self.items.values() {
            size += item.get_size();
        }
        size
    }
}

impl Mp4Box for IlstBox {
    fn box_type(&self) -> BoxType {
        self.get_type()
    }

    fn box_size(&self) -> u64 {
        self.get_size()
    }

    fn to_json(&self) -> Result<String> {
        Ok(serde_json::to_string(&self).unwrap())
    }

    fn summary(&self) -> Result<String> {
        let s = format!("item_count={}", self.items.len());
        Ok(s)
    }
}

impl<R: Read + Seek> ReadBox<&mut R> for IlstBox {
    fn read_box(reader: &mut R, size: u64) -> Result<Self> {
        let start = box_start(reader)?;

        let mut items = HashMap::new();

        let mut current = reader.stream_position()?;
        let end = start + size;
        while current < end {
            // Get box header.
            let header = BoxHeader::read(reader)?;
            let BoxHeader { name, size: s } = header;
            if s > size {
                return Err(Error::InvalidData(
                    "ilst box contains a box with a larger size than it",
                ));
            }

            match name {
                BoxType::NameBox => {
                    items.insert(MetadataKey::Title, IlstItemBox::read_box(reader, s)?);
                }
                BoxType::DayBox => {
                    items.insert(MetadataKey::Year, IlstItemBox::read_box(reader, s)?);
                }
                BoxType::CovrBox => {
                    items.insert(MetadataKey::Poster, IlstItemBox::read_box(reader, s)?);
                }
                BoxType::DescBox => {
                    items.insert(MetadataKey::Summary, IlstItemBox::read_box(reader, s)?);
                }
                _ => {
                    // XXX warn!()
                    skip_box(reader, s)?;
                }
            }

            current = reader.stream_position()?;
        }

        skip_bytes_to(reader, start + size)?;

        Ok(IlstBox { items })
    }
}

impl<W: Write> WriteBox<&mut W> for IlstBox {
    fn write_box(&self, writer: &mut W) -> Result<u64> {
        let size = self.box_size();
        BoxHeader::new(self.box_type(), size).write(writer)?;

        for (key, value) in &self.items {
            let name = match key {
                MetadataKey::Title => BoxType::NameBox,
                MetadataKey::Year => BoxType::DayBox,
                MetadataKey::Poster => BoxType::CovrBox,
                MetadataKey::Summary => BoxType::DescBox,
            };
            BoxHeader::new(name, value.get_size()).write(writer)?;
            value.data.write_box(writer)?;
        }
        Ok(size)
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize)]
pub struct IlstItemBox {
    pub data: DataBox,
}

impl IlstItemBox {
    fn get_size(&self) -> u64 {
        HEADER_SIZE + self.data.box_size()
    }
}

impl<R: Read + Seek> ReadBox<&mut R> for IlstItemBox {
    fn read_box(reader: &mut R, size: u64) -> Result<Self> {
        let start = box_start(reader)?;

        let mut data = None;

        let mut current = reader.stream_position()?;
        let end = start + size;
        while current < end {
            // Get box header.
            let header = BoxHeader::read(reader)?;
            let BoxHeader { name, size: s } = header;
            if s > size {
                return Err(Error::InvalidData(
                    "ilst item box contains a box with a larger size than it",
                ));
            }

            match name {
                BoxType::DataBox => {
                    data = Some(DataBox::read_box(reader, s)?);
                }
                _ => {
                    // XXX warn!()
                    skip_box(reader, s)?;
                }
            }

            current = reader.stream_position()?;
        }

        if data.is_none() {
            return Err(Error::BoxNotFound(BoxType::DataBox));
        }

        skip_bytes_to(reader, start + size)?;

        Ok(IlstItemBox {
            data: data.unwrap(),
        })
    }
}

impl<'a> Metadata<'a> for IlstBox {
    fn title(&self) -> Option<Cow<str>> {
        self.items.get(&MetadataKey::Title).map(item_to_str)
    }

    fn year(&self) -> Option<u32> {
        self.items.get(&MetadataKey::Year).and_then(item_to_u32)
    }

    fn poster(&self) -> Option<&[u8]> {
        self.items.get(&MetadataKey::Poster).map(item_to_bytes)
    }

    fn summary(&self) -> Option<Cow<str>> {
        self.items.get(&MetadataKey::Summary).map(item_to_str)
    }
}

fn item_to_bytes(item: &IlstItemBox) -> &[u8] {
    &item.data.data
}

fn item_to_str(item: &IlstItemBox) -> Cow<str> {
    String::from_utf8_lossy(&item.data.data)
}

fn item_to_u32(item: &IlstItemBox) -> Option<u32> {
    match item.data.data_type {
        DataType::Binary if item.data.data.len() == 4 => Some(BigEndian::read_u32(&item.data.data)),
        DataType::Text => String::from_utf8_lossy(&item.data.data).parse::<u32>().ok(),
        _ => None,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::mp4box::BoxHeader;
    use std::io::Cursor;

    #[test]
    fn test_ilst() {
        let src_year = IlstItemBox {
            data: DataBox {
                data_type: DataType::Text,
                data: b"test_year".to_vec(),
            },
        };
        let src_box = IlstBox {
            items: [
                (MetadataKey::Title, IlstItemBox::default()),
                (MetadataKey::Year, src_year),
                (MetadataKey::Poster, IlstItemBox::default()),
                (MetadataKey::Summary, IlstItemBox::default()),
            ]
            .into(),
        };
        let mut buf = Vec::new();
        src_box.write_box(&mut buf).unwrap();
        assert_eq!(buf.len(), src_box.box_size() as usize);

        let mut reader = Cursor::new(&buf);
        let header = BoxHeader::read(&mut reader).unwrap();
        assert_eq!(header.name, BoxType::IlstBox);
        assert_eq!(src_box.box_size(), header.size);

        let dst_box = IlstBox::read_box(&mut reader, header.size).unwrap();
        assert_eq!(src_box, dst_box);
    }

    #[test]
    fn test_ilst_empty() {
        let src_box = IlstBox::default();
        let mut buf = Vec::new();
        src_box.write_box(&mut buf).unwrap();
        assert_eq!(buf.len(), src_box.box_size() as usize);

        let mut reader = Cursor::new(&buf);
        let header = BoxHeader::read(&mut reader).unwrap();
        assert_eq!(header.name, BoxType::IlstBox);
        assert_eq!(src_box.box_size(), header.size);

        let dst_box = IlstBox::read_box(&mut reader, header.size).unwrap();
        assert_eq!(src_box, dst_box);
    }
}