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
use crate::{Error, ErrorKind, StorageFile};
use std::cmp;
use std::fs;
use std::io;
use std::ops;
use std::path::Path;

/// Location of the ID3v1 tag chunk relative to the end of the file.
static TAG_CHUNK: ops::Range<i64> = -128..0;
/// Location of the ID3v1 extended tag chunk relative to the end of the file.
static XTAG_CHUNK: ops::Range<i64> = -355..-128;

pub(crate) static GENRE_LIST: &[&str] = &[
    "Blues",
    "Classic Rock",
    "Country",
    "Dance",
    "Disco",
    "Funk",
    "Grunge",
    "Hip-Hop",
    "Jazz",
    "Metal",
    "New Age",
    "Oldies",
    "Other",
    "Pop",
    "R&B",
    "Rap",
    "Reggae",
    "Rock",
    "Techno",
    "Industrial",
    "Alternative",
    "Ska",
    "Death Metal",
    "Pranks",
    "Soundtrack",
    "Euro-Techno",
    "Ambient",
    "Trip-Hop",
    "Vocal",
    "Jazz+Funk",
    "Fusion",
    "Trance",
    "Classical",
    "Instrumental",
    "Acid",
    "House",
    "Game",
    "Sound Clip",
    "Gospel",
    "Noise",
    "Alternative Rock",
    "Bass",
    "Soul",
    "Punk",
    "Space",
    "Meditative",
    "Instrumental Pop",
    "Instrumental Rock",
    "Ethnic",
    "Gothic",
    "Darkwave",
    "Techno-Industrial",
    "Electronic",
    "Pop-Folk",
    "Eurodance",
    "Dream",
    "Southern Rock",
    "Comedy",
    "Cult",
    "Gangsta",
    "Top 40",
    "Christian Rap",
    "Pop/Funk",
    "Jungle",
    "Native US",
    "Cabaret",
    "New Wave",
    "Psychadelic",
    "Rave",
    "Showtunes",
    "Trailer",
    "Lo-Fi",
    "Tribal",
    "Acid Punk",
    "Acid Jazz",
    "Polka",
    "Retro",
    "Musical",
    "Rock & Roll",
    "Hard Rock",
    "Folk",
    "Folk-Rock",
    "National Folk",
    "Swing",
    "Fast Fusion",
    "Bebob",
    "Latin",
    "Revival",
    "Celtic",
    "Bluegrass",
    "Avantgarde",
    "Gothic Rock",
    "Progressive Rock",
    "Psychedelic Rock",
    "Symphonic Rock",
    "Slow Rock",
    "Big Band",
    "Chorus",
    "Easy Listening",
    "Acoustic",
    "Humour",
    "Speech",
    "Chanson",
    "Opera",
    "Chamber Music",
    "Sonata",
    "Symphony",
    "Booty Bass",
    "Primus",
    "Porn Groove",
    "Satire",
    "Slow Jam",
    "Club",
    "Tango",
    "Samba",
    "Folklore",
    "Ballad",
    "Power Ballad",
    "Rhytmic Soul",
    "Freestyle",
    "Duet",
    "Punk Rock",
    "Drum Solo",
    "Acapella",
    "Euro-House",
    "Dance Hall",
    "Goa",
    "Drum & Bass",
    "Club-House",
    "Hardcore",
    "Terror",
    "Indie",
    "BritPop",
    "Negerpunk",
    "Polsk Punk",
    "Beat",
    "Christian Gangsta",
    "Heavy Metal",
    "Black Metal",
    "Crossover",
    "Contemporary C",
    "Christian Rock",
    "Merengue",
    "Salsa",
    "Thrash Metal",
    "Anime",
    "JPop",
    "SynthPop",
];

/// A structure containing ID3v1 metadata.
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
pub struct Tag {
    /// The full title (ID3v1 + extension if present).
    pub title: String,
    /// The full artist (ID3v1 + extension if present).
    pub artist: String,
    /// The full album (ID3v1 + extension if present).
    pub album: String,
    /// The release year as four digits.
    ///
    /// The ID3v1 format can only represent values between 0 and 9999 inclusive.
    pub year: String,
    /// A free-form comment.
    pub comment: String,
    /// Number of the track. ID3v1.1 data.
    pub track: Option<u8>,
    /// The genre mapping is standardized up to 79, altough this implementation uses the Winamp
    /// extended genre list:
    /// <https://de.wikipedia.org/wiki/Liste_der_ID3v1-Genres>
    pub genre_id: u8,

    /// 1 (slow), 2, 3, 4 (fast) or None when not set. ID3v1 extended data.
    pub speed: Option<u8>,
    /// Free-form genre string. ID3v1 extended data.
    pub genre_str: Option<String>,
    /// The real start of the track, mmm:ss. ID3v1 extended data.
    pub start_time: Option<String>,
    /// The real end of the track, mmm:ss. ID3v1 extended data.
    pub end_time: Option<String>,
}

impl Tag {
    /// Creates a new empty ID3v1 tag.
    pub fn new() -> Tag {
        Tag::default()
    }

    /// Checks whether the reader contains an ID3v1 tag.
    ///
    /// The reader position will be reset back to the previous position before returning.
    pub fn is_candidate(mut reader: impl io::Read + io::Seek) -> crate::Result<bool> {
        let initial_position = reader.stream_position()?;
        reader.seek(io::SeekFrom::End(TAG_CHUNK.start))?;
        let mut buf = [0; 3];
        let nread = reader.read(&mut buf)?;
        reader.seek(io::SeekFrom::Start(initial_position))?;
        Ok(&buf[..nread] == b"TAG")
    }

    /// Seeks to and reads a ID3v1 tag from the reader.
    pub fn read_from(mut reader: impl io::Read + io::Seek) -> crate::Result<Tag> {
        let mut tag_buf = [0; 355];
        let file_len = reader.seek(io::SeekFrom::End(0))?;
        if file_len >= XTAG_CHUNK.start.unsigned_abs() {
            reader.seek(io::SeekFrom::End(XTAG_CHUNK.start))?;
            reader.read_exact(&mut tag_buf)?;
        } else if file_len >= TAG_CHUNK.start.unsigned_abs() {
            let l = tag_buf.len() as i64;
            reader.seek(io::SeekFrom::End(TAG_CHUNK.start))?;
            reader.read_exact(&mut tag_buf[(l + TAG_CHUNK.start) as usize..])?;
        } else {
            return Err(Error::new(
                ErrorKind::NoTag,
                "the file is too small to contain an ID3v1 tag",
            ));
        }

        let (tag, xtag) = {
            let (xtag, tag) = (&tag_buf[..227], &tag_buf[227..]);
            if &tag[0..3] != b"TAG" {
                return Err(Error::new(ErrorKind::NoTag, "no ID3v1 tag was found"));
            }
            (
                tag,
                if &xtag[0..4] == b"TAG+" {
                    Some(xtag)
                } else {
                    None
                },
            )
        };

        // Decodes a string consisting out of a base and possible extension to a String.
        // The input are one or two null-terminated ISO-8859-1 byte slices.
        fn decode_str(base: &[u8], ext: Option<&[u8]>) -> String {
            base.iter()
                .take_while(|c| **c != 0)
                .chain({
                    ext.into_iter()
                        .flat_map(|s| s.iter())
                        .take_while(|c| **c != 0)
                })
                // This works because the ISO 8859-1 code points match the unicode code
                // points. So,`c as char` will map correctly from ISO to unicode.
                .map(|c| *c as char)
                .collect()
        }
        let title = decode_str(&tag[3..33], xtag.as_ref().map(|t| &t[4..64]));
        let artist = decode_str(&tag[33..63], xtag.as_ref().map(|t| &t[64..124]));
        let album = decode_str(&tag[63..93], xtag.as_ref().map(|t| &t[124..184]));
        let year = decode_str(&tag[93..97], None);
        let (track, comment_raw) = if tag[125] == 0 && tag[126] != 0 {
            (Some(tag[126]), &tag[97..125])
        } else {
            (None, &tag[97..127])
        };
        let comment = decode_str(comment_raw, None);
        let genre_id = tag[127];
        let (speed, genre_str, start_time, end_time) = if let Some(xt) = xtag {
            let speed = if xt[184] == 0 { None } else { Some(xt[184]) };
            let genre_str = decode_str(&xt[185..215], None);
            let start_time = decode_str(&xt[185..215], None);
            let end_time = decode_str(&xt[185..215], None);
            (speed, Some(genre_str), Some(start_time), Some(end_time))
        } else {
            (None, None, None, None)
        };

        Ok(Tag {
            title,
            artist,
            album,
            year,
            comment,
            track,
            genre_id,
            speed,
            genre_str,
            start_time,
            end_time,
        })
    }

    /// Attempts to read an ID3v1 tag from the file at the indicated path.
    pub fn read_from_path(path: impl AsRef<Path>) -> crate::Result<Tag> {
        let file = fs::File::open(path)?;
        Tag::read_from(file)
    }

    /// Removes an ID3v1 tag plus possible extended data if any.
    ///
    /// The file cursor position will be reset back to the previous position before returning.
    ///
    /// Returns true if the file initially contained a tag.
    #[deprecated(note = "Use remove_from_file")]
    pub fn remove(file: &mut fs::File) -> crate::Result<bool> {
        Self::remove_from_file(file)
    }

    /// Removes an ID3v1 tag plus possible extended data if any.
    ///
    /// The file cursor position will be reset back to the previous position before returning.
    ///
    /// Returns true if the file initially contained a tag.
    pub fn remove_from_file(mut file: impl StorageFile) -> crate::Result<bool> {
        let cur_pos = file.stream_position()?;
        let file_len = file.seek(io::SeekFrom::End(0))?;
        let has_ext_tag = if file_len >= XTAG_CHUNK.start.unsigned_abs() {
            file.seek(io::SeekFrom::End(XTAG_CHUNK.start))?;
            let mut b = [0; 4];
            file.read_exact(&mut b)?;
            &b == b"TAG+"
        } else {
            false
        };
        let has_tag = if file_len >= TAG_CHUNK.start.unsigned_abs() {
            file.seek(io::SeekFrom::End(TAG_CHUNK.start))?;
            let mut b = [0; 3];
            file.read_exact(&mut b)?;
            &b == b"TAG"
        } else {
            false
        };

        let truncate_to = if has_ext_tag && has_tag {
            Some(file_len - XTAG_CHUNK.start.unsigned_abs())
        } else if has_tag {
            Some(file_len - TAG_CHUNK.start.unsigned_abs())
        } else {
            None
        };
        file.seek(io::SeekFrom::Start(cmp::min(
            truncate_to.unwrap_or(cur_pos),
            cur_pos,
        )))?;
        if let Some(l) = truncate_to {
            file.set_len(l)?;
        }
        Ok(truncate_to.is_some())
    }

    /// Removes an ID3v1 tag plus possible extended data if any.
    ///
    /// Returns true if the file initially contained a tag.
    pub fn remove_from_path(path: impl AsRef<Path>) -> crate::Result<bool> {
        let mut file = fs::OpenOptions::new().read(true).write(true).open(path)?;
        Tag::remove_from_file(&mut file)
    }

    /// Returns `genre_str`, falling back to translating `genre_id` to a string.
    pub fn genre(&self) -> Option<&str> {
        if let Some(ref g) = self.genre_str {
            if !g.is_empty() {
                return Some(g.as_str());
            }
        }
        GENRE_LIST.get(self.genre_id as usize).cloned()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use std::io::Seek;
    use tempfile::tempdir;

    #[test]
    fn read_id3v1() {
        let file = fs::File::open("testdata/id3v1.id3").unwrap();
        let tag = Tag::read_from(file).unwrap();
        assert_eq!("Title", tag.title);
        assert_eq!("Artist", tag.artist);
        assert_eq!("Album", tag.album);
        assert_eq!("2017", tag.year);
        assert_eq!("Comment", tag.comment);
        assert_eq!(Some(1), tag.track);
        assert_eq!(31, tag.genre_id);
        assert_eq!("Trance", tag.genre().unwrap());
        assert!(tag.speed.is_none());
        assert!(tag.genre_str.is_none());
        assert!(tag.start_time.is_none());
        assert!(tag.end_time.is_none());
    }

    #[test]
    fn remove_id3v1() {
        let tmp = tempdir().unwrap();
        let tmp_name = tmp.path().join("remove_id3v1_tag");
        {
            let mut tag_file = fs::File::create(&tmp_name).unwrap();
            let mut original = fs::File::open("testdata/id3v1.id3").unwrap();
            io::copy(&mut original, &mut tag_file).unwrap();
        }
        let mut tag_file = fs::OpenOptions::new()
            .read(true)
            .write(true)
            .open(&tmp_name)
            .unwrap();
        tag_file.seek(io::SeekFrom::Start(0)).unwrap();
        assert!(Tag::remove_from_file(&mut tag_file).unwrap());
        tag_file.seek(io::SeekFrom::Start(0)).unwrap();
        assert!(!Tag::remove_from_file(&mut tag_file).unwrap());
    }
}