summaryrefslogtreecommitdiff
path: root/src/id3v1.rs
blob: ccade4a8c9734c66a8733fb134ac5efd7b2fdcab (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
use std::fs::File;
use std::io::{self, Read, Seek};

#[derive(Copy, Clone, Debug)]
pub enum TagType {
    /// An ID3v1.0 tag
    TAGv10,
    /// An ID3v1.1 enhanced tag (TAG+) in addition to the v1.0 tag
    TAGv11,
    /// An ID3v1.2 extended tag (EXT) in addition to the v1.0 tag
    TAGv12,
}

pub fn recognise(file: &mut File) -> io::Result<Option<TagType>> {
    let length = file.seek(io::SeekFrom::End(0))?;
    if length < 128 { return Ok(None); }

    let mut buf4 = [0u8; 4];

    // Check whether we have a v1.0 tag
    file.seek(io::SeekFrom::End(-128))?;
    file.read_exact(&mut buf4[0..3])?;
    if &buf4[0..3] == b"TAG" {
        // Check whether we also have a v1.1 tag
        if length >= 128 + 227 {
            file.seek(io::SeekFrom::End(-128 - 227))?;
            file.read_exact(&mut buf4)?;
            if &buf4 == b"TAG+" {
                return Ok(Some(TagType::TAGv11));
            }
        }

        // Otherwise, check whether we also have a v1.2 tag
        if length >= 128 + 128 {
            file.seek(io::SeekFrom::End(-128 - 128))?;
            file.read_exact(&mut buf4[0..3])?;
            if &buf4[0..3] == b"EXT" {
                return Ok(Some(TagType::TAGv12));
            }
        }

        // Nope, just v1.0
        Ok(Some(TagType::TAGv10))
    } else {
        Ok(None)
    }
}

pub fn remove_tag(file: &mut File, typ: TagType) -> io::Result<()> {
    let tag_len = match typ {
        TagType::TAGv10 => 128,
        TagType::TAGv11 => 128 + 227,
        TagType::TAGv12 => 128 + 128,
    };

    let length = file.seek(io::SeekFrom::End(0))?;
    eprintln!("remove_tag: Resizing file from {} to {} bytes", length, length - tag_len);
    file.set_len(length - tag_len)?;

    Ok(())
}