forked from n10v/id3v2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
header.go
91 lines (73 loc) · 1.67 KB
/
header.go
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
// Copyright 2016 Albert Nigmatzianov. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package id3v2
import (
"bufio"
"bytes"
"errors"
"io"
)
const tagHeaderSize = 10
var (
id3Identifier = []byte("ID3")
errNoTag = errors.New("there is no tag in file")
ErrSmallHeaderSize = errors.New("size of tag header is less than expected")
)
type tagHeader struct {
FramesSize int64
Version byte
}
// parseHeader parses tag header in rd.
// If there is no tag in rd, it returns errNoTag.
// If rd is smaller than expected, it returns ErrSmallHeaderSize.
func parseHeader(rd io.Reader) (tagHeader, error) {
var header tagHeader
data := make([]byte, tagHeaderSize)
n, err := rd.Read(data)
if err != nil {
return header, err
}
if n < tagHeaderSize {
return header, ErrSmallHeaderSize
}
if !isID3Tag(data[0:3]) {
return header, errNoTag
}
size, err := parseSize(data[6:])
if err != nil {
return header, err
}
header.Version = data[3]
header.FramesSize = size
return header, nil
}
func isID3Tag(data []byte) bool {
if len(data) != len(id3Identifier) {
return false
}
return bytes.Equal(data, id3Identifier)
}
func writeTagHeader(bw *bufio.Writer, framesSize uint, version byte) error {
// Identifier
if _, err := bw.Write(id3Identifier); err != nil {
return err
}
// Version
if err := bw.WriteByte(version); err != nil {
return err
}
// Revision
if err := bw.WriteByte(0); err != nil {
return err
}
// Flags
if err := bw.WriteByte(0); err != nil {
return err
}
// Size of frames
if err := writeBytesSize(bw, framesSize); err != nil {
return err
}
return nil
}