summaryrefslogtreecommitdiff
path: root/src/id3v2.rs
blob: 7ad8edd6d8ecdb8b6cc89b0df5c6d1c8eeea5cf2 (plain)
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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
// http://id3.org/id3v2.3.0

use std::convert::TryFrom;
use std::io::{self, Read, Write};
use std::iter;
use std::num::TryFromIntError;
use crate::encoding::{from_latin_1, from_ucs_2_bom, from_utf16_bom, from_utf16_nobom, read_big_endian, write_big_endian};
use crate::error::IntoIOError;

fn parse_id3v2_header(bytes: &[u8]) -> Option<(u16, u8, usize)> {
    if bytes.len() == 10 &&
            bytes[0] == b'I' &&
            bytes[1] == b'D' &&
            bytes[2] == b'3' &&
            bytes[3] != 0xff &&
            bytes[4] != 0xff &&
            bytes[6..10].iter().all(|b| (b & 0x80) == 0) {
        Some((
            read_big_endian(&bytes[3..5], 8) as u16,
            bytes[5],
            read_big_endian(&bytes[6..10], 7)
        ))
    } else {
        None
    }
}

/// Returns the number of bytes consumed of the body.
fn parse_extended_header(body: &[u8], version_sub: u8) -> io::Result<usize> {
    let extended_size = match version_sub {
        3 => 4 + read_big_endian(&body[0..4], 8),
        4 => read_big_endian(&body[0..4], 7),
        _ => panic!("")
    };

    if body.len() < extended_size {
        return Err("Header too small for extended header size field".ioerr());
    }

    match version_sub {
        3 => if extended_size != 10 && extended_size != 14 {
            // Error message uses the v2.3 size format, which does not include the size
            // number itself.
            return Err(
                format!("Extended header has unrecognised length {} (not 6 or 10)",
                        extended_size)
                    .ioerr()
            );
        }

        4 => if extended_size < 6 {
            return Err(format!("Extended header size too small ({})", extended_size).ioerr());
        }

        _ => panic!("")
    }

    match version_sub {
        3 => {
            let flags = read_big_endian(&body[4..6], 8);
            // First bit is "CRC present", which we do not care about (it's contained in
            // the extended header, which we otherwise ignore anyhow).
            if (flags & 0x7fff) != 0 {
                return Err(
                    format!("Unknown extended header flags set (flags bytes 0x{:04x})",
                            flags)
                        .ioerr()
                );
            }
        }

        4 => {
            let num_flag_bytes = usize::from(body[4]);
            if num_flag_bytes != 1 {
                return Err(
                    format!("Unknown number of extended flag bytes {}", num_flag_bytes)
                        .ioerr()
                );
            }

            let flags = body[5];
            // 0x40: "update tag"; ignored
            // 0x20: "CRC present"; ignored
            // 0x10: tag restructions; ignored
            if (flags & 0x8f) != 0 {
                return Err(
                    format!("Unknown extended flags (flags byte 0x{:02x})", flags)
                        .ioerr()
                );
            }
        }

        _ => panic!("")
    }

    // Ignore the rest of the extended header
    Ok(extended_size)
}

/// Encodes native string to ID3v2 string encoding (either Latin-1 or UCS-2 according to the
/// characters used).
fn encode_string(s: &str) -> io::Result<Vec<u8>> {
    let as_latin1 = || iter::once(Ok(0))
                            .chain(s.chars().map(|c| u8::try_from(u32::from(c))))
                            .collect::<Result<Vec<u8>, _>>();

    let as_ucs2 = || {
        let nibbles = s.chars()
                            .map(|c| u16::try_from(u32::from(c)))
                            .collect::<Result<Vec<u16>, _>>()?;
        Ok(iter::once(1)
                .chain(ArrayIter2::new([0xfe, 0xff]))  // BOM
                .chain(nibbles.iter().flat_map(|&n| ArrayIter2::new([(n >> 8) as u8, n as u8])))
                .collect::<Vec<u8>>())
    };

    as_latin1()
        .or_else(|_| as_ucs2())
        .map_err(|e: TryFromIntError| e.ioerr())
}

#[derive(Debug)]
pub struct ID3v2 {
    header_size: usize,
    pub version_sub: u8,  // ID3v2.{}
    pub frames: Vec<RawFrame>,
}

#[derive(Debug)]
pub struct RawFrame {
    id: String,
    flags: u16,
    tag_version_sub: u8,  // ID3v2.{}
    body: Vec<u8>,
}

#[derive(Debug)]
pub enum Frame {
    TIT2(String),
    TYER(String),
    TPE1(String),
    TALB(String),
    TRCK(String),
}

struct ArrayIter2<T> {
    arr: [T; 2],
    cursor: u8,
}

impl<T> ArrayIter2<T> {
    fn new(arr: [T; 2]) -> Self {
        Self { arr, cursor: 0 }
    }
}

impl<T: Clone> Iterator for ArrayIter2<T> {
    type Item = T;
    fn next(&mut self) -> Option<T> {
        if (self.cursor as usize) < self.arr.len() {
            let i = self.cursor;
            self.cursor += 1;
            Some(self.arr[i as usize].clone())
        } else {
            None
        }
    }
}

impl RawFrame {
    fn parse(data: &[u8], tag_version_sub: u8) -> Result<Option<(Self, usize)>, String> {
        if data.len() < 10 {
            return Err(String::from("Frame buffer too short"));
        }

        if data[0..4].iter().all(|&b| b == 0) {
            return Ok(None)
        }

        if !data[0..4].iter().all(|&b| (b'A' <= b && b <= b'Z') || (b'0' <= b && b <= b'9')) {
            return Err(format!("Invalid frame type {:?}", &data[0..4]));
        }

        let id = String::from_utf8(data[0..4].to_vec()).unwrap();
        let size = match tag_version_sub {
            3 => read_big_endian(&data[4..8], 8),
            4 => read_big_endian(&data[4..8], 7),
            _ => panic!("")
        };
        let flags = read_big_endian(&data[8..10], 8) as u16;

        if flags != 0 {
            return Err(format!("Frame flags not supported (flags bytes {:04x})", flags));
        }

        let body = data[10..10+size].to_vec();

        Ok(Some((RawFrame { id, flags, tag_version_sub, body }, 10 + size)))
    }

    fn encode<W: Write>(&self, mut stream: W) -> io::Result<()> {
        stream.write_all(self.id.as_bytes())?;
        write_big_endian(&mut stream, self.body.len(), 4, 8)?;
        write_big_endian(&mut stream, self.flags as usize, 2, 8)?;
        stream.write_all(&self.body)?;
        Ok(())
    }

    fn interpret_encoded_string(&self) -> io::Result<String> {
        enum Encoding {
            Latin1,
            UCS2,
            UTF16BOM,
            UTF16BE,
            UTF8,
        }
        let encoding = match (self.body.get(0).ok_or("String field too small".ioerr())?, self.tag_version_sub) {
            (0, _) => Encoding::Latin1,
            (1, 3) => Encoding::UCS2,
            (1, 4) => Encoding::UTF16BOM,
            (2, 3) => return Err("UTF-16BE-encoded strings unsupported in ID3v2.3".ioerr()),
            (2, 4) => Encoding::UTF16BE,
            (3, 3) => return Err("UTF8-encoded strings unsupported in ID3v2.3".ioerr()),
            (3, 4) => Encoding::UTF8,
            (enc, _) => return Err(format!("Unknown string encoding {}", enc).ioerr()),
        };

        let contents = &self.body[1..];  // after the encoding byte

        macro_rules! trunc_zeros_1 {
            ($v:expr) => {{
                let v = $v;
                let mut i = 0;
                while i < v.len() && v[i] != 0 { i += 1; }
                &v[..i]
            }}
        }

        macro_rules! trunc_zeros_2 {
            ($v:expr) => {{
                let v = $v;
                let mut i = 0;
                while i <= v.len() - 2 && (v[i] != 0 || v[i+1] != 0) { i += 2; }
                &v[..i]
            }}
        }

        match encoding {
            Encoding::Latin1 =>   from_latin_1(trunc_zeros_1!(contents)).ok_or("Invalid Latin-1 string field".ioerr()),
            Encoding::UCS2 =>     from_ucs_2_bom(trunc_zeros_2!(contents)).ok_or("Invalid UCS-2 string field".ioerr()),
            Encoding::UTF16BOM => from_utf16_bom(trunc_zeros_2!(contents)).ok_or("Invalid UTF-16 string field".ioerr()),
            Encoding::UTF16BE =>  from_utf16_nobom(trunc_zeros_2!(contents)).ok_or("Invalid UTF-16BE string field".ioerr()),
            Encoding::UTF8 =>     String::from_utf8(trunc_zeros_1!(contents).to_vec()).map_err(|e| e.ioerr()),
        }
    }

    pub fn interpret(&self) -> io::Result<Option<Frame>> {
        let type_t = |typ: fn(String) -> Frame| self.interpret_encoded_string().map(typ).map(Some);

        if      self.id == "TIT2" { type_t(Frame::TIT2) }
        else if self.id == "TYER" { type_t(Frame::TYER) }
        else if self.id == "TPE1" { type_t(Frame::TPE1) }
        else if self.id == "TALB" { type_t(Frame::TALB) }
        else if self.id == "TRCK" { type_t(Frame::TRCK) }
        else {
            Ok(None)
        }
    }

    pub fn map_string<F: FnOnce(String) -> String>(&self, f: F) -> io::Result<Option<Self>> {
        let type_t = |id: &str, body: String| -> io::Result<Self> {
            Ok(Self {
                id: id.to_string(),
                flags: 0,
                tag_version_sub: self.tag_version_sub,
                body: encode_string(&body)?,
            })
        };

        match self.interpret()? {
            Some(Frame::TIT2(s)) => Ok(Some(type_t("TIT2", f(s))?)),
            Some(Frame::TYER(s)) => Ok(Some(type_t("TYER", f(s))?)),
            Some(Frame::TPE1(s)) => Ok(Some(type_t("TPE1", f(s))?)),
            Some(Frame::TALB(s)) => Ok(Some(type_t("TALB", f(s))?)),
            Some(Frame::TRCK(s)) => Ok(Some(type_t("TRCK", f(s))?)),
            None => Ok(None),
        }
    }

    pub fn get_id(&self) -> &str {
        &self.id
    }
}

impl Frame {
    fn to_raw(self, tag_version_sub: u8) -> io::Result<RawFrame> {
        let type_t = |typ: &str, body: String| Ok(RawFrame {
            id: typ.to_string(),
            flags: 0,
            tag_version_sub,
            body: encode_string(&body)?
        });

        match self {
            Self::TIT2(s) => type_t("TIT2", s),
            Self::TYER(s) => type_t("TYER", s),
            Self::TPE1(s) => type_t("TPE1", s),
            Self::TALB(s) => type_t("TALB", s),
            Self::TRCK(s) => type_t("TRCK", s),
        }
    }

    pub fn id(&self) -> &str {
        match self {
            Frame::TIT2(_) => "TIT2",
            Frame::TYER(_) => "TYER",
            Frame::TPE1(_) => "TPE1",
            Frame::TALB(_) => "TALB",
            Frame::TRCK(_) => "TRCK",
        }
    }
}

impl ID3v2 {
    pub fn from_stream<R: Read>(stream: &mut R) -> io::Result<Self> {
        let mut header = [0u8; 10];
        stream.read_exact(&mut header)?;

        let (id3version, flags, header_size) = parse_id3v2_header(&header).ok_or("Invalid ID3v2 header or no ID3v2 tag found".ioerr())?;

        let version_sub = match id3version {
            0x0300 => 3,
            0x0400 => {
                eprintln!("WARNING: ID3v2.4 tags only partially supported!");
                4
            }
            _ => {
                return Err(format!("ID3 header version {}.{} not supported", id3version / 256, id3version % 256).ioerr())
            }
        };

        if (flags & 0x80) != 0 {
            return Err(format!("ID3 unsynchronisation not supported").ioerr());
        }

        let extended_header = (flags & 0x40) != 0;

        if (flags & 0x20) != 0 {
            return Err(
                format!("Refusing to read ID3 tag in \"experimental\" stage, whatever that may mean")
                    .ioerr()
            );
        }

        // ID3v2.4 only
        if (flags & 0x10) != 0 {
            return Err(format!("3DI footer unsupported (ID3v2.4 section 3.4)").ioerr());
        }

        if (flags & 0x0f) != 0 {
            return Err(
                format!("Unknown ID3 header flags found (flags byte: 0x{:02x})", flags)
                    .ioerr()
            );
        }

        let body = {
            let mut body = Vec::new();
            body.resize(header_size, 0u8);
            stream.read_exact(&mut body)?;
            body
        };

        let mut frames = Vec::new();
        let mut cursor = 0;

        if extended_header {
            cursor += parse_extended_header(&body, version_sub)?;
        }

        while cursor < body.len() {
            let tag = &body[cursor..cursor+4];
            if tag.len() < 4 { break; }  // not even enough bytes anymore

            if tag.iter().all(|&b| b == 0) { break; }  // zero tag indicates end of ID3 header

            match RawFrame::parse(&body[cursor..], version_sub).map_err(|e| e.ioerr())? {
                Some((frame, consumed)) => {
                    frames.push(frame);
                    cursor += consumed;
                }

                None => {
                    return Err(format!("Failed parsing frame in header starting at offset {}", cursor).ioerr())
                }
            }
        }

        Ok(ID3v2 { frames, version_sub, header_size })
    }

    pub fn encode(&self) -> io::Result<Vec<u8>> {
        let mut result = Vec::new();

        result.push(b'I'); result.push(b'D'); result.push(b'3');  // magic tag
        result.push(self.version_sub); result.push(0x00);  // version
        result.push(0);  // flags
        write_big_endian(&mut result, self.header_size, 4, 7).unwrap();  // header size

        for frame in &self.frames {
            frame.encode(&mut result).unwrap();
        }

        // Zero out the rest of the header to ensure it does not get read as more frames
        if result.len() < self.header_size {
            result.resize(self.header_size, 0u8);
        }

        if result.len() > self.header_size {
            return Err(
                format!("New tag grew larger ({} bytes) than space allocated for original tag ({} bytes), dare not encode",
                        result.len(), self.header_size)
                    .ioerr()
            );
        }

        Ok(result)
    }

    pub fn to_raw(&self, frame: Frame) -> io::Result<RawFrame> {
        frame.to_raw(self.version_sub)
    }
}