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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
extern crate byteorder;

use self::byteorder::{BigEndian, ReadBytesExt};

use block::{Block, BlockType, Picture, PictureType, VorbisComment};
use error::{Error, ErrorKind, Result};
use std::fs::{File, OpenOptions};
use std::io::{BufReader, Read, Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};

/// A structure representing a flac metadata tag.
#[derive(Clone)]
pub struct Tag {
    /// The path from which the blocks were loaded.
    path: Option<PathBuf>,
    /// The metadata blocks contained in this tag.
    blocks: Vec<Block>,
    /// The size of the metadata when the file was read.
    length: u32,
}

impl<'a> Tag {
    /// Creates a new FLAC tag with no blocks.
    pub fn new() -> Tag {
        Tag {
            path: None,
            blocks: Vec::new(),
            length: 0,
        }
    }

    /// Adds a block to the tag.
    pub fn push_block(&mut self, block: Block) {
        self.blocks.push(block);
    }

    /// Returns a reference to the blocks in the tag.
    pub fn blocks(&'a self) -> impl Iterator<Item = &'a Block> + 'a {
        self.blocks.iter()
    }

    /// Returns references to the blocks with the specified type.
    pub fn get_blocks(&'a self, block_type: BlockType) -> impl Iterator<Item = &'a Block> + 'a {
        self.blocks().filter(move |block| block.block_type() == block_type)
    }

    /// Removes blocks with the specified type.
    ///
    /// # Example
    /// ```
    /// use metaflac::{Tag, Block, BlockType};
    ///
    /// let mut tag = Tag::new();
    /// tag.push_block(Block::Padding(10));
    /// tag.push_block(Block::Unknown((20, Vec::new())));
    /// tag.push_block(Block::Padding(15));
    ///
    /// tag.remove_blocks(BlockType::Padding);
    /// assert_eq!(tag.blocks().count(), 1);
    /// ```
    pub fn remove_blocks(&mut self, block_type: BlockType) {
        self.blocks.retain(|b| b.block_type() != block_type);
    }

    /// Returns a reference to the first vorbis comment block.
    /// Returns `None` if no vorbis comment blocks are found.
    ///
    /// # Example
    /// ```
    /// use metaflac::Tag;
    ///
    /// let mut tag = Tag::new();
    /// assert!(tag.vorbis_comments().is_none());
    ///
    /// tag.set_vorbis("key", vec!("value"));
    ///
    /// assert!(tag.vorbis_comments().is_some());
    /// ```
    pub fn vorbis_comments(&self) -> Option<&VorbisComment> {
        for block in self.blocks() {
            match *block {
                Block::VorbisComment(ref comm) => return Some(comm),
                _ => {}
            }
        }

        None
    }

    /// Returns a mutable reference to the first vorbis comment block.
    /// If no block is found, a new vorbis comment block is added to the tag and a reference to the
    /// newly added block is returned.
    ///
    /// # Example
    /// ```
    /// use metaflac::Tag;
    ///
    /// let mut tag = Tag::new();
    /// assert!(tag.vorbis_comments().is_none());
    ///
    /// let key = "key".to_owned();
    /// let value1 = "value1".to_owned();
    /// let value2 = "value2".to_owned();
    ///
    /// tag.vorbis_comments_mut().comments.insert(key.clone(), vec!(value1.clone(),
    ///     value2.clone()));
    ///
    /// assert!(tag.vorbis_comments().is_some());
    /// assert!(tag.vorbis_comments().unwrap().comments.get(&key).is_some());
    /// ```
    pub fn vorbis_comments_mut(&mut self) -> &mut VorbisComment {
        for i in 0..self.blocks.len() {
            unsafe {
                match *self.blocks.as_mut_ptr().offset(i as isize) {
                    Block::VorbisComment(ref mut comm) => return comm,
                    _ => {}
                }
            }
        }

        self.push_block(Block::VorbisComment(VorbisComment::new()));
        self.vorbis_comments_mut()
    }

    /// Returns a vector of strings values for the specified vorbis comment key.
    /// Returns `None` if the tag does not contain a vorbis comment or if the vorbis comment does
    /// not contain a comment with the specified key.
    ///
    /// # Example
    /// ```
    /// use metaflac::Tag;
    ///
    /// let mut tag = Tag::new();
    ///
    /// let key = "key".to_owned();
    /// let value1 = "value1".to_owned();
    /// let value2 = "value2".to_owned();
    ///
    /// tag.set_vorbis(&key[..], vec!(&value1[..], &value2[..]));
    ///
    /// assert_eq!(tag.get_vorbis(&key).unwrap().collect::<Vec<_>>(), &[&value1[..], &value2[..]]);
    /// ```
    pub fn get_vorbis(&'a self, key: &str) -> Option<impl Iterator<Item = &'a str> + 'a> {
        self.vorbis_comments()
            .and_then(|c| c.get(&key.to_ascii_uppercase()))
            .map(|l| l.iter().map(|s| s.as_ref()))
    }

    /// Sets the values for the specified vorbis comment key.
    ///
    /// # Example
    /// ```
    /// use metaflac::Tag;
    ///
    /// let mut tag = Tag::new();
    ///
    /// let key = "key".to_owned();
    /// let value1 = "value1".to_owned();
    /// let value2 = "value2".to_owned();
    ///
    /// tag.set_vorbis(&key[..], vec!(&value1[..], &value2[..]));
    ///
    /// assert_eq!(tag.get_vorbis(&key).unwrap().collect::<Vec<_>>(), &[&value1[..], &value2[..]]);
    /// ```
    pub fn set_vorbis<K: Into<String>, V: Into<String>>(&mut self, key: K, values: Vec<V>) {
        self.vorbis_comments_mut()
            .set(key.into().to_ascii_uppercase(), values);
    }

    /// Removes the values for the specified vorbis comment key.
    ///
    /// # Example
    /// ```
    /// use metaflac::Tag;
    ///
    /// let mut tag = Tag::new();
    ///
    /// let key = "key".to_owned();
    /// let value1 = "value1".to_owned();
    /// let value2 = "value2".to_owned();
    ///
    /// tag.set_vorbis(&key[..], vec!(&value1[..], &value2[..]));
    /// assert_eq!(tag.get_vorbis(&key).unwrap().collect::<Vec<_>>(), &[&value1[..], &value2[..]]);
    ///
    /// tag.remove_vorbis(&key);
    /// assert!(tag.get_vorbis(&key).is_none());
    /// ```
    pub fn remove_vorbis(&mut self, key: &str) {
        self.vorbis_comments_mut()
            .comments
            .remove(&key.to_ascii_uppercase());
    }

    /// Removes the vorbis comments with the specified key and value.
    ///
    /// # Example
    /// ```
    /// use metaflac::Tag;
    ///
    /// let mut tag = Tag::new();
    ///
    /// let key = "key".to_owned();
    /// let value1 = "value1".to_owned();
    /// let value2 = "value2".to_owned();
    ///
    /// tag.set_vorbis(key.clone(), vec!(&value1[..], &value2[..]));
    /// assert_eq!(tag.get_vorbis(&key).unwrap().collect::<Vec<_>>(), &[&value1[..], &value2[..]]);
    ///
    /// tag.remove_vorbis_pair(&key, &value1);
    /// assert_eq!(tag.get_vorbis(&key).unwrap().collect::<Vec<_>>(), &[&value2[..]]);
    /// ```
    pub fn remove_vorbis_pair(&mut self, key: &str, value: &str) {
        self.vorbis_comments_mut()
            .remove_pair(&key.to_ascii_uppercase(), value);
    }

    /// Returns a vector of references to the pictures in the tag.
    ///
    /// # Example
    /// ```
    /// use metaflac::Tag;
    /// use metaflac::block::PictureType::CoverFront;
    ///
    /// let mut tag = Tag::new();
    /// assert_eq!(tag.pictures().count(), 0);
    ///
    /// tag.add_picture("image/jpeg", CoverFront, vec!(0xFF));
    ///
    /// assert_eq!(tag.pictures().count(), 1);
    /// ```
    pub fn pictures(&'a self) -> impl Iterator<Item = &'a Picture> + 'a {
        return self.blocks.iter().filter_map(|block|
            match *block {
                Block::Picture(ref picture) => Some(picture),
                _ => None
            }
        )
    }

    /// Adds a picture block.
    ///
    /// # Example
    /// ```
    /// use metaflac::Tag;
    /// use metaflac::block::PictureType::CoverFront;
    ///
    /// let mut tag = Tag::new();
    /// assert_eq!(tag.pictures().count(), 0);
    ///
    /// tag.add_picture("image/jpeg", CoverFront, vec!(0xFF));
    ///
    /// let picture = tag.pictures().next().unwrap();
    /// assert_eq!(&picture.mime_type[..], "image/jpeg");
    /// assert_eq!(picture.picture_type, CoverFront);
    /// assert_eq!(&picture.data[..], &vec!(0xFF)[..]);
    /// ```
    pub fn add_picture<T: Into<String>>(
        &mut self,
        mime_type: T,
        picture_type: PictureType,
        data: Vec<u8>,
    ) {
        self.remove_picture_type(picture_type);

        let mut picture = Picture::new();
        picture.mime_type = mime_type.into();
        picture.picture_type = picture_type;
        picture.data = data;

        self.push_block(Block::Picture(picture));
    }

    /// Removes the picture with the specified picture type.
    ///
    /// # Example
    /// ```
    /// use metaflac::Tag;
    /// use metaflac::block::PictureType::{CoverFront, Other};
    ///
    /// let mut tag = Tag::new();
    /// assert_eq!(tag.pictures().count(), 0);
    ///
    /// tag.add_picture("image/jpeg", CoverFront, vec!(0xFF));
    /// tag.add_picture("image/png", Other, vec!(0xAB));
    /// assert_eq!(tag.pictures().count(), 2);
    ///
    /// tag.remove_picture_type(CoverFront);
    /// assert_eq!(tag.pictures().count(), 1);
    ///
    /// let picture = tag.pictures().next().unwrap();
    /// assert_eq!(&picture.mime_type[..], "image/png");
    /// assert_eq!(picture.picture_type, Other);
    /// assert_eq!(&picture.data[..], &vec!(0xAB)[..]);
    /// ```
    pub fn remove_picture_type(&mut self, picture_type: PictureType) {
        self.blocks.retain(|block: &Block| match *block {
            Block::Picture(ref picture) => picture.picture_type != picture_type,
            _ => true,
        });
    }

    /// Attempts to save the tag back to the file which it was read from. An `Error::InvalidInput`
    /// will be returned if this is called on a tag which was not read from a file.
    pub fn save(&mut self) -> ::Result<()> {
        if self.path.is_none() {
            return Err(::Error::new(
                ::ErrorKind::InvalidInput,
                "attempted to save file which was not read from a path",
            ));
        }

        let path = self.path.clone().unwrap();
        self.write_to_path(&path)
    }

    /// Returns the contents of the reader without any FLAC metadata.
    pub fn skip_metadata<R: Read + Seek>(reader: &mut R) -> Vec<u8> {
        macro_rules! try_io {
            ($reader:ident, $action:expr) => {
                match $action {
                    Ok(bytes) => bytes,
                    Err(_) => match $reader.seek(SeekFrom::Start(0)) {
                        Ok(_) => {
                            let mut data = Vec::new();
                            match $reader.read_to_end(&mut data) {
                                Ok(_) => return data,
                                Err(_) => return Vec::new(),
                            }
                        }
                        Err(_) => return Vec::new(),
                    },
                }
            };
        }

        let mut ident = [0; 4];
        try_io!(reader, reader.read(&mut ident));
        if &ident[..] == b"fLaC" {
            let mut more = true;
            while more {
                let header = try_io!(reader, reader.read_u32::<BigEndian>());

                more = ((header >> 24) & 0x80) == 0;
                let length = header & 0xFF_FF_FF;

                debug!("Skipping {} bytes", length);
                try_io!(reader, reader.seek(SeekFrom::Current(length as i64)));
            }
        } else {
            try_io!(reader, reader.seek(SeekFrom::Start(0)));
        }

        let mut data = Vec::new();
        try_io!(reader, reader.read_to_end(&mut data));
        data
    }

    /// Will return true if the reader is a candidate for FLAC metadata. The reader position will be
    /// reset back to the previous position before returning.
    pub fn is_candidate<R: Read + Seek>(reader: &mut R) -> bool {
        macro_rules! try_or_false {
            ($action:expr) => {
                match $action {
                    Ok(result) => result,
                    Err(_) => return false,
                }
            };
        }

        let mut ident = [0; 4];
        try_or_false!(reader.read(&mut ident));
        let _ = reader.seek(SeekFrom::Current(-4));
        &ident[..] == b"fLaC"
    }

    /// Attempts to read a FLAC tag from the reader.
    pub fn read_from(reader: &mut dyn Read) -> Result<Tag> {
        let mut tag = Tag::new();

        let mut ident = [0; 4];
        try!(reader.read(&mut ident));
        if &ident[..] != b"fLaC" {
            return Err(Error::new(
                ErrorKind::InvalidInput,
                "reader does not contain flac metadata",
            ));
        }

        loop {
            let (is_last, length, block) = try!(Block::read_from(reader));
            tag.length += length;
            tag.blocks.push(block);
            if is_last {
                break;
            }
        }

        Ok(tag)
    }

    /// Attempts to write the FLAC tag to the writer.
    pub fn write_to(&mut self, writer: &mut dyn Write) -> Result<()> {
        try!(writer.write(b"fLaC"));

        let nblocks = self.blocks.len();
        self.length = 0;
        for i in 0..nblocks {
            let block = &self.blocks[i];
            self.length += try!(block.write_to(i == nblocks - 1, writer));
        }

        Ok(())
    }

    /// Attempts to write the FLAC tag to a file at the indicated path. If the specified path is
    /// the same path which the tag was read from, then the tag will be written to the padding if
    /// possible.
    pub fn write_to_path<P: AsRef<Path>>(&mut self, path: P) -> Result<()> {
        self.remove_blocks(BlockType::Padding);

        let mut block_bytes = Vec::new();
        let nblocks = self.blocks.len();
        let mut new_length = 0;
        for i in 0..nblocks {
            let block = &self.blocks[i];
            let mut writer = Vec::<u8>::new();
            new_length += try!(block.write_to(false, &mut writer));
            block_bytes.push(writer);
        }

        // write using padding
        if self.path.is_some()
            && path.as_ref() == self.path.as_ref().unwrap().as_path()
            && new_length + 4 <= self.length
        {
            debug!("Writing using padding");
            let mut file = try!(OpenOptions::new()
                .write(true)
                .open(self.path.as_ref().unwrap()));
            try!(file.seek(SeekFrom::Start(4)));

            for bytes in block_bytes.iter() {
                try!(file.write(&bytes[..]));
            }

            let padding = Block::Padding(self.length - new_length - 4);
            try!(padding.write_to(true, &mut file));
            self.push_block(padding);
        } else {
            // write by copying file data
            debug!("Writing to new file");

            let data_opt = {
                match File::open(&path) {
                    Ok(mut file) => Some(Tag::skip_metadata(&mut file)),
                    Err(_) => None,
                }
            };

            let mut file = try!(OpenOptions::new()
                .write(true)
                .truncate(true)
                .create(true)
                .open(&path));

            try!(file.write(b"fLaC"));

            for bytes in block_bytes.iter() {
                try!(file.write(&bytes[..]));
            }

            let padding_size = 1024;
            debug!("Adding {} bytes of padding", padding_size);
            let padding = Block::Padding(padding_size);
            new_length += try!(padding.write_to(true, &mut file));
            self.push_block(padding);

            match data_opt {
                Some(data) => try!(file.write_all(&data[..])),
                None => {}
            }
        }

        self.length = new_length;
        self.path = Some(path.as_ref().to_path_buf());
        Ok(())
    }

    /// Attempts to read a FLAC tag from the file at the specified path.
    pub fn read_from_path<P: AsRef<Path>>(path: P) -> Result<Tag> {
        let file = try!(File::open(&path));
        let mut reader = BufReader::new(file);
        let mut tag = try!(Tag::read_from(&mut reader));
        tag.path = Some(path.as_ref().to_path_buf());
        Ok(tag)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn vorbis_case_sensitivity() {
        let mut tag = Tag::new();

        tag.set_vorbis("KEY", vec!["value"]);

        assert_eq!(tag.get_vorbis("KEY").unwrap().collect::<Vec<_>>(), &["value"]);
        assert_eq!(tag.get_vorbis("key").unwrap().collect::<Vec<_>>(), &["value"]);

        tag.remove_vorbis("key");
        assert!(tag.get_vorbis("KEY").is_none());
    }
}