forked from dominikh/go-id3
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathid3.go
793 lines (633 loc) · 15.6 KB
/
id3.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
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
package id3
import (
"bytes"
"fmt"
"strconv"
"strings"
"time"
)
// TODO reevaluate TagHeader. Right now it's a snapshot of the past
// that doesn't reflect the present
var Magic = []byte("ID3")
var versionByte = []byte{4, 0}
const frameLength = 10
const TimeFormat = "2006-01-02T15:04:05"
var timeFormats = []string{
"2006-01-02T15:04:05",
"2006-01-02T15:04",
"2006-01-02T15",
"2006-01-02",
"2006-01",
"2006",
}
// TODO: ID3v2 extended header
// TODO: unsynchronisation
type HeaderFlags byte
type FrameFlags uint16
type Version int16
type FrameType string
type FramesMap map[FrameType][]Frame
type PictureType byte
type UnimplementedFeatureError struct {
Feature string
}
func (err UnimplementedFeatureError) Error() string {
return "unsupported feature: " + err.Feature
}
type InvalidFrameHeaderError struct {
Bytes struct {
ID [4]byte
Size [4]byte
Flags [2]byte
}
}
func (err InvalidFrameHeaderError) Error() string {
return fmt.Sprintf("not a frame header (ID = %q)", err.Bytes.ID)
}
type InvalidTagHeaderError struct {
Magic []byte
}
func (err InvalidTagHeaderError) Error() string {
return fmt.Sprintf("not an ID3v2 header: %q", err.Magic)
}
type UnsupportedVersionError struct {
Version Version
}
func (err UnsupportedVersionError) Error() string {
return fmt.Sprintf("unsupported version: %s", err.Version)
}
type Header struct {
Version Version
Flags HeaderFlags
Size int // The size of the tag (exluding the size of the header)
}
type Tag struct {
Flags HeaderFlags
Frames FramesMap
}
type Comment struct {
Language string
Description string
Text string
}
type Peeker interface {
Peek(n int) ([]byte, error)
}
// Check reports whether r looks like it starts with an ID3 tag.
func Check(r Peeker) (bool, error) {
b, err := r.Peek(3)
if err != nil {
return false, err
}
return bytes.Equal(b, Magic), nil
}
// NewTag returns an empty tag.
func NewTag() *Tag {
return &Tag{Frames: make(FramesMap)}
}
func (f FrameType) String() string {
v, ok := FrameNames[f]
if ok {
return v
}
return string(f)
}
func (p PictureType) String() string {
if int(p) >= len(PictureTypes) {
return ""
}
return PictureTypes[p]
}
// TODO: HeaderFlags.String()
// TODO: FrameFlags.String()
func (f HeaderFlags) Unsynchronisation() bool {
return (f & 128) > 0
}
func (f HeaderFlags) ExtendedHeader() bool {
return (f & 64) > 0
}
func (f HeaderFlags) Experimental() bool {
return (f & 32) > 0
}
func (f HeaderFlags) UndefinedSet() bool {
return (f & 31) > 0
}
func (f FrameFlags) PreserveTagAlteration() bool {
return (f & 0x4000) == 0
}
func (f FrameFlags) PreserveFileAlteration() bool {
return (f & 0x2000) == 0
}
func (f FrameFlags) ReadOnly() bool {
return (f & 0x1000) > 0
}
func (f FrameFlags) Compressed() bool {
return (f & 128) > 0
}
func (f FrameFlags) Encrypted() bool {
return (f & 64) > 0
}
func (f FrameFlags) Grouped() bool {
return (f & 32) > 0
}
func (v Version) String() string {
return fmt.Sprintf("ID3v2.%.1d.%.1d", v>>8, v&0xFF)
}
// upgrade upgrades tags from an older version to IDv2.4. It should
// only be called for files that use an older version.
func (t *Tag) upgrade() {
// Upgrade TYER/TDAT/TIME to TDRC if at least
// one of TYER, TDAT or TIME are set.
if t.HasFrame("TYER") || t.HasFrame("TDAT") || t.HasFrame("TIME") {
year := t.GetTextFrameNumber("TYER")
date := t.GetTextFrame("TDAT")
tim := t.GetTextFrame("TIME")
if len(date) != 4 {
date = "0101"
}
if len(tim) != 4 {
tim = "0000"
}
day, _ := strconv.Atoi(date[0:2])
month, _ := strconv.Atoi(date[2:])
hour, _ := strconv.Atoi(date[0:2])
minute, _ := strconv.Atoi(date[2:])
t.SetRecordingTime(time.Date(year, time.Month(month), day, hour, minute, 0, 0, time.UTC))
t.RemoveFrames("TYER")
t.RemoveFrames("TDAT")
t.RemoveFrames("TIME")
}
// Upgrade Original Release Year to Original Release Time
if !t.HasFrame("TDOR") {
if t.HasFrame("XDOR") {
panic("not implemented") // FIXME replace XDOR with TDOR
} else if t.HasFrame("TORY") {
year := t.GetTextFrameNumber("TORY")
t.SetOriginalReleaseTime(time.Date(year, 0, 0, 0, 0, 0, 0, time.UTC))
}
}
for name := range t.Frames {
switch name {
case "TLAN", "TCON", "TPE1", "TOPE", "TCOM", "TEXT", "TOLY":
t.SetTextFrameSlice(name, strings.Split(t.GetTextFrame(name), "/"))
}
}
// TODO EQUA → EQU2
// TODO IPL → TMCL, TIPL
// TODO RVAD → RVA2
// TODO TRDA → TDRL
}
// Clear removes all tags from the file.
func (t *Tag) Clear() {
t.Frames = make(FramesMap)
}
func (t *Tag) RemoveFrames(name FrameType) {
delete(t.Frames, name)
}
// Validate checks whether the tags are conforming to the
// specification.
//
// This entails two checks: Whether only frames that are covered by
// the specification are present and whether all values are within
// valid ranges.
//
// It is well possible that reading existing files will result in
// invalid tags.
//
// Calling Save() will not automatically validate the tags and will
// happily write invalid tags.
//
// Assuming that the original file was valid and that only the
// getter/setter methods were used the generated tags should always be
// valid.
func (t *Tag) Validate() error {
// TODO consider returning a list of errors, one per invalid frame,
// specifying the reason
panic("not implemented") // FIXME
if t.HasFrame("TSRC") && len(t.GetTextFrame("TSRC")) != 12 {
// TODO invalid TSRC frame
}
return nil
}
// Sanitize will remove all frames that aren't valid. Check the
// documentation of (*Tag).Validate() to see what "valid" means.
func (t *Tag) Sanitize() {
panic("not implemented") // FIXME
}
func (t *Tag) Album() string {
return t.GetTextFrame("TALB")
}
func (t *Tag) SetAlbum(album string) {
t.SetTextFrame("TALB", album)
}
func (t *Tag) Artists() []string {
return t.GetTextFrameSlice("TPE1")
}
func (t *Tag) SetArtists(artists []string) {
t.SetTextFrameSlice("TPE1", artists)
}
func (t *Tag) Artist() string {
artists := t.Artists()
if len(artists) > 0 {
return artists[0]
}
return ""
}
func (t *Tag) SetArtist(artist string) {
t.SetTextFrame("TPE1", artist)
}
func (t *Tag) Band() string {
return t.GetTextFrame("TPE2")
}
func (t *Tag) SetBand(band string) {
t.SetTextFrame("TPE2", band)
}
func (t *Tag) Conductor() string {
return t.GetTextFrame("TPE3")
}
func (t *Tag) SetConductor(name string) {
t.SetTextFrame("TPE3", name)
}
func (t *Tag) OriginalArtists() []string {
return t.GetTextFrameSlice("TOPE")
}
func (t *Tag) SetOriginalArtists(names []string) {
t.SetTextFrameSlice("TOPE", names)
}
func (t *Tag) OriginalArtist() string {
artists := t.OriginalArtists()
if len(artists) > 0 {
return artists[0]
}
return ""
}
func (t *Tag) SetOriginalArtist(name string) {
t.SetTextFrame("TOPE", name)
}
func (t *Tag) BPM() int {
return t.GetTextFrameNumber("TBPM")
}
func (t *Tag) SetBPM(bpm int) {
t.SetTextFrameNumber("TBPM", bpm)
}
func (t *Tag) Composers() []string {
return t.GetTextFrameSlice("TCOM")
}
func (t *Tag) SetComposers(composers []string) {
t.SetTextFrameSlice("TCOM", composers)
}
func (t *Tag) Composer() string {
composers := t.Composers()
if len(composers) > 0 {
return composers[0]
}
return ""
}
func (t *Tag) SetComposer(composer string) {
t.SetTextFrame("TCOM", composer)
}
func (t *Tag) Title() string {
return t.GetTextFrame("TIT2")
}
func (t *Tag) SetTitle(title string) {
t.SetTextFrame("TIT2", title)
}
func (t *Tag) Length() time.Duration {
// TODO if TLEN frame doesn't exist determine the length by
// parsing the underlying audio file
return time.Duration(t.GetTextFrameNumber("TLEN")) * time.Millisecond
}
func (t *Tag) SetLength(d time.Duration) {
t.SetTextFrameNumber("TLEN", int(d.Nanoseconds()/1e6))
}
func (t *Tag) Languages() []string {
return t.GetTextFrameSlice("TLAN")
}
func (t *Tag) Language() string {
langs := t.Languages()
if len(langs) == 0 {
return ""
}
return langs[0]
}
func (t *Tag) SetLanguages(langs []string) {
t.SetTextFrameSlice("TLAN", langs)
}
func (t *Tag) SetLanguage(lang string) {
t.SetTextFrame("TLAN", lang)
}
func (t *Tag) Publisher() string {
return t.GetTextFrame("TPUB")
}
func (t *Tag) SetPublisher(publisher string) {
t.SetTextFrame("TPUB", publisher)
}
func (t *Tag) StationName() string {
return t.GetTextFrame("TRSN")
}
func (t *Tag) SetStationName(name string) {
t.SetTextFrame("TRSN", name)
}
func (t *Tag) StationOwner() string {
return t.GetTextFrame("TRSO")
}
func (t *Tag) SetStationOwner(owner string) {
t.SetTextFrame("TRSO", owner)
}
func (t *Tag) Owner() string {
return t.GetTextFrame("TOWN")
}
func (t *Tag) SetOwner(owner string) {
t.SetTextFrame("TOWN", owner)
}
func (t *Tag) RecordingTime() time.Time {
return t.GetTextFrameTime("TDRC")
}
func (t *Tag) SetRecordingTime(rt time.Time) {
t.SetTextFrameTime("TDRC", rt)
}
func (t *Tag) OriginalReleaseTime() time.Time {
return t.GetTextFrameTime("TDOR")
}
func (t *Tag) SetOriginalReleaseTime(rt time.Time) {
t.SetTextFrameTime("TDOR", rt)
}
func (t *Tag) OriginalFilename() string {
return t.GetTextFrame("TOFN")
}
func (t *Tag) SetOriginalFilename(name string) {
t.SetTextFrame("TOFN", name)
}
func (t *Tag) PlaylistDelay() time.Duration {
return time.Duration(t.GetTextFrameNumber("TDLY")) * time.Millisecond
}
func (t *Tag) SetPlaylistDelay(d time.Duration) {
t.SetTextFrameNumber("TDLY", int(d.Nanoseconds()/1e6))
}
func (t *Tag) EncodingTime() time.Time {
return t.GetTextFrameTime("TDEN")
}
func (t *Tag) SetEncodingTime(et time.Time) {
t.SetTextFrameTime("TDEN", et)
}
func (t *Tag) AlbumSortOrder() string {
return t.GetTextFrame("TSOA")
}
func (t *Tag) SetAlbumSortOrder(s string) {
t.SetTextFrame("TSOA", s)
}
func (t *Tag) PerformerSortOrder() string {
return t.GetTextFrame("TSOP")
}
func (t *Tag) SetPerformerSortOrder(s string) {
t.SetTextFrame("TSOP", s)
}
func (t *Tag) TitleSortOrder() string {
return t.GetTextFrame("TSOT")
}
func (t *Tag) SetTitleSortOrder(s string) {
t.SetTextFrame("TSOT", s)
}
func (t *Tag) ISRC() string {
return t.GetTextFrame("TSRC")
}
func (t *Tag) SetISRC(isrc string) {
t.SetTextFrame("TSRC", isrc)
}
func (t *Tag) Mood() string {
return t.GetTextFrame("TMOO")
}
func (t *Tag) SetMood(mood string) {
t.SetTextFrame("TMOO", mood)
}
func (t *Tag) Comments() []Comment {
frames := t.Frames["COMM"]
comments := make([]Comment, len(frames))
for i, frame := range frames {
comment := frame.(CommentFrame)
comments[i] = Comment{
Language: comment.Language,
Description: comment.Description,
Text: comment.Text,
}
}
return comments
}
func (t *Tag) SetComments(comments []Comment) {
frames := make([]Frame, len(comments))
for i, comment := range comments {
frames[i] = CommentFrame{
FrameHeader: FrameHeader{
id: "COMM",
},
Language: comment.Language,
Description: comment.Description,
Text: comment.Text,
}
}
t.Frames["COMM"] = frames
}
func (t *Tag) HasFrame(name FrameType) bool {
_, ok := t.Frames[name]
return ok
}
// GetTextFrame returns the text frame specified by name.
//
// To access user text frames, specify the name like "TXXX:The
// description".
func (t *Tag) GetTextFrame(name FrameType) string {
userFrameName, ok := frameNameToUserFrame(name)
if ok {
return t.getUserTextFrame(userFrameName)
}
// Get normal text frame
frames := t.Frames[name]
if len(frames) == 0 {
return ""
}
return frames[0].Value()
}
func (t *Tag) getUserTextFrame(name string) string {
frames, ok := t.Frames["TXXX"]
if !ok {
return ""
}
for _, frame := range frames {
userFrame := frame.(UserTextInformationFrame)
if userFrame.Description == name {
return userFrame.Text
}
}
return ""
}
func (t *Tag) GetTextFrameNumber(name FrameType) int {
s := t.GetTextFrame(name)
if s == "" {
return 0
}
i, _ := strconv.Atoi(s)
return i
}
func (t *Tag) GetTextFrameSlice(name FrameType) []string {
s := t.GetTextFrame(name)
if s == "" {
return nil
}
return strings.Split(s, "\x00")
}
func (t *Tag) GetTextFrameTime(name FrameType) time.Time {
s := t.GetTextFrame(name)
if s == "" {
return time.Time{}
}
ft, err := parseTime(s)
if err != nil {
// FIXME figure out a way to signal format errors
panic(err)
}
return ft
}
func (t *Tag) SetTextFrame(name FrameType, value string) {
userFrameName, ok := frameNameToUserFrame(name)
if ok {
t.setUserTextFrame(userFrameName, value)
return
}
frames, ok := t.Frames[name]
if !ok {
frames = make([]Frame, 1)
t.Frames[name] = frames
}
frames[0] = TextInformationFrame{
FrameHeader: FrameHeader{
id: name,
},
Text: value,
}
// TODO what about flags and preserving them?
}
func (t *Tag) setUserTextFrame(name string, value string) {
// Set/create a user text frame
frame := UserTextInformationFrame{
FrameHeader: FrameHeader{id: "TXXX"},
Description: name,
Text: value,
}
frames, ok := t.Frames["TXXX"]
if !ok {
frames = make([]Frame, 0)
t.Frames["TXXX"] = frames
}
var i int
for i = range frames {
if frames[i].(UserTextInformationFrame).Description == name {
ok = true
break
}
}
if ok {
frames[i] = frame
} else {
t.Frames["TXXX"] = append(t.Frames["TXXX"], frame)
}
}
func (t *Tag) SetTextFrameNumber(name FrameType, value int) {
t.SetTextFrame(name, strconv.Itoa(value))
}
func (t *Tag) SetTextFrameSlice(name FrameType, value []string) {
t.SetTextFrame(name, strings.Join(value, "\x00"))
}
func (t *Tag) SetTextFrameTime(name FrameType, value time.Time) {
t.SetTextFrame(name, value.Format(TimeFormat))
}
// TODO all the other methods
// TODO UFID
// TODO USLT
// UserTextFrames returns all TXXX frames.
func (t *Tag) UserTextFrames() []UserTextInformationFrame {
res := make([]UserTextInformationFrame, len(t.Frames["TXXX"]))
for i, frame := range t.Frames["TXXX"] {
res[i] = frame.(UserTextInformationFrame)
}
return res
}
func (fm FramesMap) Size() int {
size := 0
for _, frames := range fm {
for _, frame := range frames {
size += frame.Size()
}
}
return size
}
func desynchsafeInt(b [4]byte) int {
return int(b[0])<<21 | int(b[1])<<14 | int(b[2])<<7 | int(b[3])
}
func synchsafeInt(i int) int {
return (i & 0x7f) |
((i & 0x3f80) << 1) |
((i & 0x1fc000) << 2) |
((i & 0xfe0000) << 3)
}
func intToBytes(i int) []byte {
return []byte{
byte(i & 0xff000000 >> 24),
byte(i & 0xff0000 >> 16),
byte(i & 0xff00 >> 8),
byte(i & 0xff),
}
}
func splitNullN(data []byte, encoding Encoding, n int) [][]byte {
if encoding == utf8 || encoding == iso88591 {
return bytes.SplitN(data, nul, n)
}
var (
matches [][]byte
prev int
)
for i := 0; i < len(data); i += 2 {
// TODO if there's no data[i+1] then this is malformed data
// and we should return an error
if data[i] == 0 && data[i+1] == 0 {
matches = append(matches, data[prev:i])
if len(matches) == n-1 {
break
}
}
}
if prev < len(data)-1 {
matches = append(matches, data[prev:])
}
return matches
}
func parseTime(input string) (res time.Time, err error) {
for _, format := range timeFormats {
res, err = time.Parse(format, input)
if err == nil {
break
}
}
return
}
func frameNameToUserFrame(name FrameType) (frameName string, ok bool) {
if len(name) < 6 {
return "", false
}
if name[0:4] != "TXXX" {
return "", false
}
return string(name[5:]), true
}
func concat(bs ...[]byte) []byte {
n := 0
for _, b := range bs {
n += len(b)
}
out := make([]byte, 0, n)
for _, b := range bs {
out = append(out, b...)
}
return out
}
// TRCK
// The 'Track number/Position in set' frame is a numeric string containing the order number of the audio-file on its original recording. This may be extended with a "/" character and a numeric string containing the total numer of tracks/elements on the original recording. E.g. "4/9".