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
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
use std::fmt::Debug;
use std::fs::{File, OpenOptions};
use std::io::{BufReader, BufWriter, Read, Seek, SeekFrom, Write};
use std::path::Path;

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

use crate::{Atom, atom, Content, Data};

/// A list of standard genres found in the `gnre` `Atom`.
pub const GENRES: [(u16, &str); 80] = [
    (1, "Blues"),
    (2, "Classic rock"),
    (3, "Country"),
    (4, "Dance"),
    (5, "Disco"),
    (6, "Funk"),
    (7, "Grunge"),
    (8, "Hip,-Hop"),
    (9, "Jazz"),
    (10, "Metal"),
    (11, "New Age"),
    (12, "Oldies"),
    (13, "Other"),
    (14, "Pop"),
    (15, "Rhythm and Blues"),
    (16, "Rap"),
    (17, "Reggae"),
    (18, "Rock"),
    (19, "Techno"),
    (20, "Industrial"),
    (21, "Alternative"),
    (22, "Ska"),
    (23, "Death metal"),
    (24, "Pranks"),
    (25, "Soundtrack"),
    (26, "Euro-Techno"),
    (27, "Ambient"),
    (28, "Trip-Hop"),
    (29, "Vocal"),
    (30, "Jazz & Funk"),
    (31, "Fusion"),
    (32, "Trance"),
    (33, "Classical"),
    (34, "Instrumental"),
    (35, "Acid"),
    (36, "House"),
    (37, "Game"),
    (38, "Sound clip"),
    (39, "Gospel"),
    (40, "Noise"),
    (41, "Alternative Rock"),
    (42, "Bass"),
    (43, "Soul"),
    (44, "Punk"),
    (45, "Space"),
    (46, "Meditative"),
    (47, "Instrumental Pop"),
    (48, "Instrumental Rock"),
    (49, "Ethnic"),
    (50, "Gothic"),
    (51, "Darkwave"),
    (52, "Techno-Industrial"),
    (53, "Electronic"),
    (54, "Pop-Folk"),
    (55, "Eurodance"),
    (56, "Dream"),
    (57, "Southern Rock"),
    (58, "Comedy"),
    (59, "Cult"),
    (60, "Gangsta"),
    (61, "Top 41"),
    (62, "Christian Rap"),
    (63, "Pop/Funk"),
    (64, "Jungle"),
    (65, "Native US"),
    (66, "Cabaret"),
    (67, "New Wave"),
    (68, "Psychedelic"),
    (69, "Rave"),
    (70, "Show tunes"),
    (71, "Trailer"),
    (72, "Lo,-Fi"),
    (73, "Tribal"),
    (74, "Acid Punk"),
    (75, "Acid Jazz"),
    (76, "Polka"),
    (77, "Retro"),
    (78, "Musical"),
    (79, "Rock ’n’ Roll"),
    (80, "Hard Rock"),
];

/// A MPEG-4 audio tag containing metadata atoms
#[derive(Debug)]
pub struct Tag {
    /// A vector containing metadata atoms
    pub atoms: Vec<Atom>,
}

impl Tag {
    /// Creates a new empty MPEG-4 audio tag.
    pub fn new() -> Tag {
        Tag { atoms: Vec::new() }
    }

    /// Creates a new MPEG-4 audio tag containing the atom.
    pub fn with(atoms: Vec<Atom>) -> Tag {
        let mut tag = Tag { atoms };

        let mut i = 0;
        while i < tag.atoms.len() {
            if let Some(a) = tag.atoms[i].first_child() {
                if let Content::TypedData(Data::Unparsed(_)) = a.content {
                    tag.atoms.remove(i);
                    continue;
                }
            }
            i += 1;
        }

        tag
    }

    /// Attempts to read a MPEG-4 audio tag from the reader.
    pub fn read_from(reader: &mut (impl Read + Seek)) -> crate::Result<Tag> {
        Ok(Tag::with(Atom::read_from(reader)?))
    }

    /// Attempts to read a MPEG-4 audio tag from the file at the indicated path.
    pub fn read_from_path(path: impl AsRef<Path>) -> crate::Result<Tag> {
        let mut file = BufReader::new(File::open(path)?);
        Tag::read_from(&mut file)
    }

    /// Attempts to write the MPEG-4 audio tag to the writer.
    pub fn write_to(&self, writer: &mut (impl Write + Seek)) -> crate::Result<()> {
        for a in &self.atoms {
            a.write_to(writer)?;
        }

        Ok(())
    }

    /// Attempts to write the MPEG-4 audio tag to the path.
    pub fn write_to_path(&self, path: impl AsRef<Path>) -> crate::Result<()> {
        let file = OpenOptions::new().read(true).write(true).open(path)?;
        let mut reader = BufReader::new(&file);
        let mut writer = BufWriter::new(&file);

        let atom_pos_and_len = Atom::locate_metadata_item_list(&mut reader)?;

        let old_file_length = reader.seek(SeekFrom::End(0))?;
        let metadata_position = atom_pos_and_len[atom_pos_and_len.len() - 1].0 + 8;
        let old_metadata_length = atom_pos_and_len[atom_pos_and_len.len() - 1].1 - 8;
        let new_metadata_length = self.atoms.iter().map(|a| a.len()).sum::<usize>();
        let metadata_length_difference = new_metadata_length as i32 - old_metadata_length as i32;

        // reading additional data after metadata
        let mut additional_data = Vec::new();
        reader.seek(SeekFrom::Start((metadata_position + old_metadata_length) as u64))?;
        reader.read_to_end(&mut additional_data)?;

        // adjusting the file length
        file.set_len((old_file_length as i64 + metadata_length_difference as i64) as u64)?;

        // adjusting the atom lengths
        for (pos, len) in atom_pos_and_len {
            writer.seek(SeekFrom::Start(pos as u64))?;
            writer.write_u32::<BigEndian>((len as i32 + metadata_length_difference) as u32)?;
        }

        // writing metadata
        writer.seek(SeekFrom::Current(4))?;
        self.write_to(&mut BufWriter::new(&file))?;

        // writing additional data after metadata
        writer.write(&additional_data)?;
        writer.flush()?;

        Ok(())
    }

    // String fields

    /// Returns the album (©alb).
    pub fn album(&self) -> Option<&str> {
        self.string(atom::ALBUM)
    }

    /// Sets the album (©alb).
    pub fn set_album(&mut self, album: impl Into<String>) {
        self.set_data(atom::ALBUM, Data::Utf8(album.into()));
    }

    /// Removes the album (©alb).
    pub fn remove_album(&mut self) {
        self.remove_data(atom::ALBUM);
    }

    /// Returns the album artist (aART).
    pub fn album_artist(&self) -> Option<&str> {
        self.string(atom::ALBUM_ARTIST)
    }

    /// Sets the album artist (aART).
    pub fn set_album_artist(&mut self, album_artist: impl Into<String>) {
        self.set_data(atom::ALBUM_ARTIST, Data::Utf8(album_artist.into()));
    }

    /// Removes the album artist (aART).
    pub fn remove_album_artist(&mut self) {
        self.remove_data(atom::ALBUM_ARTIST);
    }

    /// Returns the artist (©ART).
    pub fn artist(&self) -> Option<&str> {
        self.string(atom::ARTIST)
    }

    /// Sets the artist (©ART).
    pub fn set_artist(&mut self, artist: impl Into<String>) {
        self.set_data(atom::ARTIST, Data::Utf8(artist.into()));
    }

    /// Removes the artist (©ART).
    pub fn remove_artist(&mut self) {
        self.remove_data(atom::ARTIST);
    }

    /// Returns the category (catg).
    pub fn category(&self) -> Option<&str> {
        self.string(atom::CATEGORY)
    }


    /// Sets the category (catg).
    pub fn set_category(&mut self, category: impl Into<String>) {
        self.set_data(atom::CATEGORY, Data::Utf8(category.into()));
    }

    /// Removes the category (catg).
    pub fn remove_category(&mut self) {
        self.remove_data(atom::CATEGORY);
    }

    /// Returns the comment (©cmt).
    pub fn comment(&self) -> Option<&str> {
        self.string(atom::COMMENT)
    }

    /// Sets the comment (©cmt).
    pub fn set_comment(&mut self, comment: impl Into<String>) {
        self.set_data(atom::COMMENT, Data::Utf8(comment.into()));
    }

    /// Removes the comment (©cmt).
    pub fn remove_comment(&mut self) {
        self.remove_data(atom::COMMENT);
    }

    /// Returns the composer (©wrt).
    pub fn composer(&self) -> Option<&str> {
        self.string(atom::COMPOSER)
    }

    /// Sets the composer (©wrt).
    pub fn set_composer(&mut self, composer: impl Into<String>) {
        self.set_data(atom::COMPOSER, Data::Utf8(composer.into()));
    }

    /// Removes the composer (©wrt).
    pub fn remove_composer(&mut self) {
        self.remove_data(atom::COMMENT);
    }

    /// Returns the copyright (cprt).
    pub fn copyright(&self) -> Option<&str> {
        self.string(atom::COPYRIGHT)
    }

    /// Sets the copyright (cprt).
    pub fn set_copyright(&mut self, copyright: impl Into<String>) {
        self.set_data(atom::COPYRIGHT, Data::Utf8(copyright.into()));
    }

    /// Removes the copyright (cprt).
    pub fn remove_copyright(&mut self) {
        self.remove_data(atom::COPYRIGHT);
    }

    /// Returns the description (desc).
    pub fn description(&self) -> Option<&str> {
        self.string(atom::DESCRIPTION)
    }

    /// Sets the description (desc).
    pub fn set_description(&mut self, description: impl Into<String>) {
        self.set_data(atom::DESCRIPTION, Data::Utf8(description.into()));
    }

    /// Removes the description (desc).
    pub fn remove_description(&mut self) {
        self.remove_data(atom::DESCRIPTION);
    }

    /// Returns the encoder (©too).
    pub fn encoder(&self) -> Option<&str> {
        self.string(atom::ENCODER)
    }

    /// Sets the encoder (©too).
    pub fn set_encoder(&mut self, encoder: impl Into<String>) {
        self.set_data(atom::ENCODER, Data::Utf8(encoder.into()));
    }

    /// Removes the encoder (©too).
    pub fn remove_encoder(&mut self) {
        self.remove_data(atom::ENCODER);
    }

    /// Returns the grouping (©grp).
    pub fn grouping(&self) -> Option<&str> {
        self.string(atom::GROUPING)
    }

    /// Sets the grouping (©grp).
    pub fn set_grouping(&mut self, grouping: impl Into<String>) {
        self.set_data(atom::GROUPING, Data::Utf8(grouping.into()));
    }

    /// Removes the grouping (©grp).
    pub fn remove_grouping(&mut self) {
        self.remove_data(atom::GROUPING);
    }

    /// Returns the keyword (keyw).
    pub fn keyword(&self) -> Option<&str> {
        self.string(atom::KEYWORD)
    }

    /// Sets the keyword (keyw).
    pub fn set_keyword(&mut self, keyword: impl Into<String>) {
        self.set_data(atom::KEYWORD, Data::Utf8(keyword.into()));
    }

    /// Removes the keyword (keyw).
    pub fn remove_keyword(&mut self) {
        self.remove_data(atom::KEYWORD);
    }

    /// Returns the lyrics (©lyr).
    pub fn lyrics(&self) -> Option<&str> {
        self.string(atom::LYRICS)
    }

    /// Sets the lyrics (©lyr).
    pub fn set_lyrics(&mut self, lyrics: impl Into<String>) {
        self.set_data(atom::LYRICS, Data::Utf8(lyrics.into()));
    }

    /// Removes the lyrics (©lyr).
    pub fn remove_lyrics(&mut self) {
        self.remove_data(atom::LYRICS);
    }

    /// Returns the title (©nam).
    pub fn title(&self) -> Option<&str> {
        self.string(atom::TITLE)
    }

    /// Sets the title (©nam).
    pub fn set_title(&mut self, title: impl Into<String>) {
        self.set_data(atom::TITLE, Data::Utf8(title.into()));
    }

    /// Removes the title (©nam).
    pub fn remove_title(&mut self) {
        self.remove_data(atom::TITLE);
    }

    /// Returns the tv episode number (tven).
    pub fn tv_episode_number(&self) -> Option<&str> {
        self.string(atom::TV_EPISODE_NUMBER)
    }

    /// Sets the tv episode number (tven).
    pub fn set_tv_episode_number(&mut self, tv_episode_number: impl Into<String>) {
        self.set_data(atom::TV_EPISODE_NUMBER, Data::Utf8(tv_episode_number.into()));
    }

    /// Removes the tv episode number (tven).
    pub fn remove_tv_episode_number(&mut self) {
        self.remove_data(atom::TV_EPISODE_NUMBER);
    }

    /// Returns the tv network name (tvnn).
    pub fn tv_network_name(&self) -> Option<&str> {
        self.string(atom::TV_NETWORK_NAME)
    }

    /// Sets the tv network name (tvnn).
    pub fn set_tv_network_name(&mut self, tv_network_name: impl Into<String>) {
        self.set_data(atom::TV_NETWORK_NAME, Data::Utf8(tv_network_name.into()));
    }

    /// Removes the tv network name (tvnn).
    pub fn remove_tv_network_name(&mut self) {
        self.remove_data(atom::TV_NETWORK_NAME);
    }

    /// Returns the tv show name (tvsh).
    pub fn tv_show_name(&self) -> Option<&str> {
        self.string(atom::TV_SHOW_NAME)
    }

    /// Sets the tv show name (tvsh).
    pub fn set_tv_show_name(&mut self, tv_show_name: impl Into<String>) {
        self.set_data(atom::TV_SHOW_NAME, Data::Utf8(tv_show_name.into()));
    }

    /// Removes the tv show name (tvsh).
    pub fn remove_tv_show_name(&mut self) {
        self.remove_data(atom::TV_SHOW_NAME);
    }

    /// Returns the year (©day).
    pub fn year(&self) -> Option<&str> {
        self.string(atom::YEAR)
    }

    /// Sets the year (©day).
    pub fn set_year(&mut self, year: impl Into<String>) {
        self.set_data(atom::YEAR, Data::Utf8(year.into()));
    }

    /// Removes the year (©day).
    pub fn remove_year(&mut self) {
        self.remove_data(atom::YEAR);
    }

    // Custom fields

    /// Returns the genre (gnre) or (©gen).
    pub fn genre(&self) -> Option<&str> {
        if let Some(s) = self.custom_genre() {
            return Some(s);
        }

        if let Some(genre_code) = self.standard_genre() {
            for g in GENRES.iter() {
                if g.0 == genre_code {
                    return Some(g.1);
                }
            }
        }

        None
    }

    /// Sets the standard genre (gnre) if it matches one otherwise a custom genre (©gen).
    pub fn set_genre(&mut self, genre: impl Into<String>) {
        let gen = genre.into();

        for g in GENRES.iter() {
            if g.1 == gen {
                self.remove_custom_genre();
                self.set_standard_genre(g.0);
                return;
            }
        }

        self.remove_standard_genre();
        self.set_custom_genre(gen)
    }

    /// Removes the genre (gnre) or (©gen).
    pub fn remove_genre(&mut self) {
        self.remove_standard_genre();
        self.remove_custom_genre();
    }

    /// Returns the standard genre (gnre).
    pub fn standard_genre(&self) -> Option<u16> {
        if let Some(v) = self.reserved(atom::STANDARD_GENRE) {
            let mut chunks = v.chunks(2);

            if let Ok(genre_code) = chunks.next()?.read_u16::<BigEndian>() {
                return Some(genre_code);
            }
        }

        None
    }

    /// Sets the standard genre (gnre).
    pub fn set_standard_genre(&mut self, genre_code: u16) {
        if genre_code > 0 && genre_code <= 80 {
            let mut vec: Vec<u8> = Vec::new();
            let _ = vec.write_u16::<BigEndian>(genre_code).is_ok();
            self.set_data(atom::STANDARD_GENRE, Data::Reserved(vec));
        }
    }

    /// Removes the standard genre (gnre).
    pub fn remove_standard_genre(&mut self) {
        self.remove_data(atom::STANDARD_GENRE);
    }

    /// Returns the custom genre (©gen).
    pub fn custom_genre(&self) -> Option<&str> {
        self.string(atom::CUSTOM_GENRE)
    }

    /// Sets the custom genre (©gen).
    pub fn set_custom_genre(&mut self, custom_genre: impl Into<String>) {
        self.set_data(atom::CUSTOM_GENRE, Data::Utf8(custom_genre.into()));
    }

    /// Removes the custom genre (©gen).
    pub fn remove_custom_genre(&mut self) {
        self.remove_data(atom::CUSTOM_GENRE);
    }

    /// Returns the track number and the total number of tracks (trkn).
    pub fn track_number(&self) -> (Option<u16>, Option<u16>) {
        let vec = match self.reserved(atom::TRACK_NUMBER) {
            Some(v) => v,
            None => return (None, None),
        };

        let mut buffs = Vec::new();

        for chunk in vec.chunks(2) {
            buffs.push(chunk);
        }

        let track_number = match buffs[1].read_u16::<BigEndian>() {
            Ok(tnr) => Some(tnr),
            Err(_) => None,
        };

        let total_tracks = match buffs[2].read_u16::<BigEndian>() {
            Ok(atr) => Some(atr),
            Err(_) => None,
        };

        (track_number, total_tracks)
    }

    /// Sets the track number and the total number of tracks (trkn).
    pub fn set_track_number(&mut self, track_number: u16, total_tracks: u16) {
        let vec32 = vec![0u16, track_number, total_tracks, 0u16];
        let mut vec = Vec::new();

        for i in vec32 {
            let _ = vec.write_u16::<BigEndian>(i).is_ok();
        }

        self.set_data(atom::TRACK_NUMBER, Data::Reserved(vec));
    }

    /// Removes the track number and the total number of tracks (trkn).
    pub fn remove_track_number(&mut self) {
        self.remove_data(atom::TRACK_NUMBER);
    }

    /// Returns the disk number and total number of disks (disk).
    pub fn disk_number(&self) -> (Option<u16>, Option<u16>) {
        let vec = match self.reserved(atom::DISK_NUMBER) {
            Some(v) => v,
            None => return (None, None),
        };

        let mut buffs = Vec::new();

        for chunk in vec.chunks(2) {
            buffs.push(chunk);
        }

        let disk_number = match buffs[1].read_u16::<BigEndian>() {
            Ok(tnr) => Some(tnr),
            Err(_) => None,
        };

        let total_disks = match buffs[2].read_u16::<BigEndian>() {
            Ok(atr) => Some(atr),
            Err(_) => None,
        };

        (disk_number, total_disks)
    }

    /// Sets the disk number and the total number of disks (disk).
    pub fn set_disk_number(&mut self, disk_number: u16, total_disks: u16) {
        let vec32 = vec![0u16, disk_number, total_disks];
        let mut vec = Vec::new();

        for i in vec32 {
            let _ = vec.write_u16::<BigEndian>(i).is_ok();
        }

        self.set_data(atom::DISK_NUMBER, Data::Reserved(vec));
    }

    /// Removes the disk number and the total number of disks (disk).
    pub fn remove_disk_number(&mut self) {
        self.remove_data(atom::DISK_NUMBER);
    }

    /// Returns the artwork image data of type `Data::JPEG` or `Data::PNG` (covr).
    pub fn artwork(&self) -> Option<Data> {
        self.image(atom::ARTWORK)
    }

    /// Sets the artwork image data of type `Data::JPEG` or `Data::PNG` (covr).
    pub fn set_artwork(&mut self, image: Data) {
        match &image {
            Data::Jpeg(_) => (),
            Data::Png(_) => (),
            _ => return,
        }

        self.set_data(atom::ARTWORK, image);
    }

    /// Removes the artwork image data (covr).
    pub fn remove_artwork(&mut self) {
        self.remove_data(atom::ARTWORK);
    }

    /// Attempts to return byte data corresponding to the head.
    ///
    /// # Example
    /// ```
    /// use mp4ameta::{Tag, Data};
    ///
    /// let mut tag = Tag::new();
    /// tag.set_data(*b"test", Data::Reserved(vec![1,2,3,4,5,6]));
    /// assert_eq!(tag.reserved(*b"test").unwrap().to_vec(), vec![1,2,3,4,5,6]);
    /// ```

    pub fn reserved(&self, head: [u8; 4]) -> Option<&Vec<u8>> {
        match self.data(head) {
            Some(Data::Reserved(v)) => Some(v),
            _ => None,
        }
    }

    /// Attempts to return a string reference corresponding to the head.
    ///
    /// # Example
    /// ```
    /// use mp4ameta::{Tag, Data};
    ///
    /// let mut tag = Tag::new();
    /// tag.set_data(*b"test", Data::Utf8("data".into()));
    /// assert_eq!(tag.string(*b"test").unwrap(), "data");
    /// ```
    pub fn string(&self, head: [u8; 4]) -> Option<&str> {
        let d = self.data(head)?;

        match d {
            Data::Utf8(s) => Some(s),
            Data::Utf16(s) => Some(s),
            _ => None,
        }
    }

    /// Attempts to return a mutable string reference corresponding to the head.
    /// # Example
    /// ```
    /// use mp4ameta::{Tag, Data};
    ///
    /// let mut tag = Tag::new();
    /// tag.set_data(*b"test", Data::Utf8("data".into()));
    /// tag.mut_string(*b"test").unwrap().push('1');
    /// assert_eq!(tag.string(*b"test").unwrap(), "data1");
    /// ```
    pub fn mut_string(&mut self, head: [u8; 4]) -> Option<&mut String> {
        let d = self.mut_data(head)?;

        match d {
            Data::Utf8(s) => Some(s),
            Data::Utf16(s) => Some(s),
            _ => None,
        }
    }

    /// Attempts to return image data of type `Data::JPEG` or `Data::PNG` corresponding to the head.
    ///
    /// # Example
    /// ```
    /// use mp4ameta::{Tag, Data};
    ///
    /// let mut tag = Tag::new();
    /// tag.set_data(*b"test", Data::Jpeg("<the image data>".as_bytes().to_vec()));
    /// if let Data::Jpeg(v) = tag.image(*b"test").unwrap(){
    ///     assert_eq!(v, "<the image data>".as_bytes())
    /// }
    /// ```
    pub fn image(&self, head: [u8; 4]) -> Option<Data> {
        let d = self.data(head)?;

        match d {
            Data::Jpeg(d) => Some(Data::Jpeg(d.to_vec())),
            Data::Png(d) => Some(Data::Png(d.to_vec())),
            _ => None,
        }
    }

    /// Attempts to return a data reference corresponding to the head.
    /// # Example
    /// ```
    /// use mp4ameta::{Tag, Data};
    ///
    /// let mut tag = Tag::new();
    /// tag.set_data(*b"test", Data::Utf8("data".into()));
    /// if let Data::Utf8(s) = tag.data(*b"test").unwrap(){
    ///     assert_eq!(s, "data");
    /// }else{
    ///     panic!("data does not match");
    /// }
    /// ```
    pub fn data(&self, head: [u8; 4]) -> Option<&Data> {
        for a in &self.atoms {
            if a.head == head {
                if let Content::TypedData(data) = &a.first_child()?.content {
                    return Some(data);
                }
            }
        }

        None
    }

    /// Attempts to return a mutable data reference corresponding to the head.
    ///
    /// # Example
    /// ```
    /// use mp4ameta::{Tag, Data};
    ///
    /// let mut tag = Tag::new();
    /// tag.set_data(*b"test", Data::Utf8("data".into()));
    /// if let Data::Utf8(s) = tag.mut_data(*b"test").unwrap(){
    ///     s.push('1');
    /// }
    /// assert_eq!(tag.string(*b"test").unwrap(), "data1");
    /// ```
    pub fn mut_data(&mut self, head: [u8; 4]) -> Option<&mut Data> {
        for a in &mut self.atoms {
            if a.head == head {
                if let Content::TypedData(data) = &mut a.mut_first_child()?.content {
                    return Some(data);
                }
            }
        }

        None
    }

    /// Updates or appends a new atom with the data corresponding to the head.
    ///
    /// # Example
    /// ```
    /// use mp4ameta::{Tag, Data};
    ///
    /// let mut tag = Tag::new();
    /// tag.set_data(*b"test", Data::Utf8("data".into()));
    /// assert_eq!(tag.string(*b"test").unwrap(), "data");
    /// ```
    pub fn set_data(&mut self, head: [u8; 4], data: Data) {
        for a in &mut self.atoms {
            if a.head == head {
                if let Some(p) = a.mut_first_child() {
                    if let Content::TypedData(d) = &mut p.content {
                        *d = data;
                        return;
                    }
                }
            }
        }

        self.atoms.push(Atom::with(head, 0, Content::data_atom_with(data)));
    }

    /// Removes the data corresponding to the head.
    ///
    /// # Example
    /// ```
    /// use mp4ameta::{Tag, Data};
    ///
    /// let mut tag = Tag::new();
    /// tag.set_data(*b"test", Data::Utf8("data".into()));
    /// assert!(tag.data(*b"test").is_some());
    /// tag.remove_data(*b"test");
    /// assert!(tag.data(*b"test").is_none());
    /// ```
    pub fn remove_data(&mut self, head: [u8; 4]) {
        for i in 0..self.atoms.len() {
            if self.atoms[i].head == head {
                self.atoms.remove(i);
                return;
            }
        }
    }
}