-
Notifications
You must be signed in to change notification settings - Fork 0
/
mp3header.pm
2010 lines (1869 loc) · 62.7 KB
/
mp3header.pm
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
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# vim:sw=4:ts=4:sts=4:et:cc=72:tw=70
#
# Copyright (c) Quentin Sculo <[email protected]>
# Copyright (c) Alexandr Savca <[email protected]>
#
# This file is part of jukebox.
#
# jukebox is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3, as
# published by the Free Software Foundation
# Library to read/write mp3 tags (id3v1 id3v2 APE lyrics3), read mp3
# header, find mp3 length by reading VBR header or counting mp3
# frames:
#
# http://www.id3.org/develop.html
# http://www.dv.co.yu/mpgscript/mpeghdr.htm
# http://www.multiweb.cz/twoinches/MP3inside.htm
# http://www.thecodeproject.com/audio/MPEGAudioInfo.asp
#
# http://www.kevesoft.com/crossref.htm
# http://www.matroska.org/technical/specs/tagging/othertagsystems/comparetable.html
# http://hobba.hobba.nl/audio/tag_frame_reference.html
package Tag::MP3;
use strict;
use warnings;
my (@bitrates, @freq, @versions, @encodings, $regex_t);
our @Genres;
my $MODIFIEDFILE;
INIT {
@bitrates = (
# Version 1
[
# Layer 1
[
0, 32, 64, 96, 128, 160, 192, 224, 256, 288, 320,
352, 384, 416, 448
],
# Layer 2
[
0, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224,
256, 320, 384
],
# Layer 3
[
0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192,
224, 256, 320
],
],
# Version 2
[
# Layer 1
[
0, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176,
192, 224, 256
],
# Layer 2
[
0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128,
144, 160
],
# Layer 3
# [
# 0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112,
# 128, 144, 160
# ],
],
);
# v2 layer 2 & 3 have the same bitrates
$bitrates[1][2] = $bitrates[1][1];
@freq = (
[ 11025, 12000, 8000 ], # MPEG version 2.5 (from mp3info)
undef, # invalid version
[ 22050, 24000, 16000 ], # MPEG version 2
[ 44100, 48000, 32000 ], # MPEG version 1
);
@versions = (2.5, undef, 2, 1);
my $re8 = qr/^(.*?)(?:\x00|$)/s;
my $re16 = qr/^((?:..)*?)(?:\x00\x00|$)/s;
$regex_t = $re8;
@encodings = (
['iso-8859-1', "\x00", $re8],
['utf16', "\x00\x00", $re16], # with BOM
['utf16be', "\x00\x00", $re16],
['utf8', "\x00", $re8],
);
#@index_apic=(
# 'other',
# '32x32 PNG file icon',
# 'other file icon',
# 'front cover',
# 'back cover',
# 'leaflet page',
# 'media',
# 'lead artist',
# 'artist',
# 'conductor',
# 'band',
# 'composer',
# 'lyricist',
# 'recording location',
# 'during recording',
# 'during performance',
# 'movie/video screen capture',
# 'a bright coloured fish',
# 'illustration',
# 'band/artist logotype',
# 'Publisher/Studio logotype'
# );
@Genres = (
'Blues', 'Classic Rock',
'Country', 'Dance',
'Disco', 'Funk',
'Grunge', 'Hip-Hop',
'Jazz', 'Metal',
'New Age', 'Oldies',
'Other', 'Pop',
'R&B', 'Rap',
'Reggae', 'Rock',
'Techno', 'Industrial',
'Alternative', 'Ska',
'Death Metal', 'Pranks',
'Soundtrack', 'Euro-Techno',
'Ambient', 'Trip-Hop',
'Vocal', 'Jazz+Funk',
'Fusion', 'Trance',
'Classical', 'Instrumental',
'Acid', 'House',
'Game', 'Sound Clip',
'Gospel', 'Noise',
'Alt. Rock', 'Bass',
'Soul', 'Punk',
'Space', 'Meditative',
'Instrumental Pop', 'Instrumental Rock',
'Ethnic', 'Gothic',
'Darkwave', 'Techno-Industrial',
'Electronic', 'Pop-Folk',
'Eurodance', 'Dream',
'Southern Rock', 'Comedy',
'Cult', 'Gangsta Rap',
'Top 40', 'Christian Rap',
'Pop/Funk', 'Jungle',
'Native American', 'Cabaret',
'New Wave', 'Psychedelic',
'Rave', 'Showtunes',
'Trailer', 'Lo-Fi',
'Tribal', 'Acid Punk',
'Acid Jazz', 'Polka',
'Retro', 'Musical',
'Rock & Roll', 'Hard Rock',
'Folk', 'Folk/Rock',
'National Folk', 'Swing',
'Fast-Fusion', 'Bebob',
'Latin', 'Revival',
'Celtic', 'Bluegrass',
'Avantgarde', 'Gothic Rock',
'Progressive Rock', 'Psychedelic Rock',
'Symphonic Rock', 'Slow Rock',
'Big Band', 'Chorus',
'Easy Listening', 'Acoustic',
'Humour', 'Speech',
'Chanson', 'Opera',
'Chamber Music', 'Sonata',
'Symphony', 'Booty Bass',
'Primus', 'Porn Groove',
'Satire', 'Slow Jam',
'Club', 'Tango',
'Samba', 'Folklore',
'Ballad', 'Power Ballad',
'Rhythmic Soul', 'Freestyle',
'Duet', 'Punk Rock',
'Drum Solo', 'A Cappella',
'Euro-House', 'Dance Hall',
'Goa', 'Drum & Bass',
'Club-House', 'Hardcore',
'Terror', 'Indie',
'BritPop', 'Negerpunk',
'Polsk Punk', 'Beat',
'Christian Gangsta Rap', 'Heavy Metal',
'Black Metal', 'Crossover',
'Contemporary Christian', 'Christian Rock',
'Merengue', 'Salsa',
'Thrash Metal', 'Anime',
'JPop', 'Synthpop',
);
}
sub new {
my ($class, $file, $findlength) = @_;
my $self = bless {}, $class;
local $_;
# check that the file exists
unless (-e $file) {
warn "File '$file' does not exist.\n";
return undef;
}
$self->{filename} = $file;
$self->_open or return undef;
$self->_FindTags;
$self->_removeblank;
my $start_at;
for my $tries (0 .. 20) {
$self->{info} = $self->_FindFirstFrame($start_at);
last unless $self->{info};
my $tries;
my $count_to = 4;
if ( $findlength
&& !$self->{info}{frames}
&& ($findlength > 1 || !$self->{info}{seconds}))
{
warn
"mp3header: No VBR header found, must count all the frames to determine length.\n"
if $::debug && !$tries;
$count_to = 0;
}
last if _CountFrames($self, $count_to);
warn "mp3header: searching another first frame\n" if $::debug;
$self->{info} = undef;
$start_at = $self->{firstframe} + 1;
}
unless ($self->{info}) {
warn
"mp3header: Can't find enough valid frames, probably not a valid mp3 file.\n";
}
$self->_close;
return $self;
}
sub _FindTags {
my $self = shift;
$self->{tags_before} = [];
$self->{tags_after} = [];
$self->{startaudio} = 0;
my $fh = $self->{fileHandle};
# Find ID3 tag(s) at the start of the file.
{
my $tag;
seek $fh, $self->{startaudio}, 0;
read $fh, my ($header), 8;
if ($header =~ m/^ID3/) {
$tag = Tag::ID3v2->new_from_file($self);
}
elsif ($header =~ m/^APETAGEX/) {
$tag = Tag::APE->new_from_file($self);
}
last unless $tag;
$tag->{offset} = $self->{startaudio};
$self->{startaudio} += $tag->{size};
push @{$self->{tags_before}}, $tag;
redo if 1; # look for another tag ?
}
# Check end of file for tags.
seek $fh, 0, 2;
$self->{endaudio} = tell $fh;
seek $fh, -128, 2;
read $fh, my ($id3v1), 128;
my $apefooter = substr($id3v1, -32, 8) eq 'APETAGEX'
&& substr($id3v1, -8) eq ("\x00" x 8);
if (!$apefooter && substr($id3v1, 0, 3) eq 'TAG') #ID3v1 tag
{
$self->{ID3v1} = Tag::ID3v1->new_from_string($id3v1);
$self->{endaudio} -= 128;
}
# Search for tag signatures at the end, repeat until none is
# found.
{
seek $fh, $self->{endaudio} - 32, 0;
my $read = read $fh, my ($footer), 32;
last unless $read == 32; # for bogus files <32 bytes
my $tag;
if ($footer =~ m/^APETAGEX/) {
$tag = Tag::APE->new_from_file($self, 1);
}
elsif ('3DI' eq substr $footer, 32 - 10, 3) {
$tag = Tag::ID3v2->new_from_file($self, 1);
}
elsif ('LYRICS200' eq substr $footer, 32 - 9, 9) {
$tag = Tag::Lyrics3v2->new_from_file($self);
}
elsif ('LYRICSEND' eq substr $footer, 32 - 9, 9) {
$tag = Tag::Lyrics3v1->new_from_file($self);
}
if ($tag) {
$self->{endaudio} -= $tag->{size};
$tag->{offset} = $self->{endaudio};
push @{$self->{tags_after}}, $tag;
redo;
}
}
return;
}
sub SyncID3v1 # auto sync with id3v2
{
my $self = shift;
my $id3v1 = $self->{ID3v1} || $self->new_ID3v1;
my $genre = $id3v1->[6];
my @genres;
$id3v1->[6] = \@genres;
if (defined $genre) {
if (ref $genre) { push @genres, @$genre }
else { push @genres, $genre }
}
if ($self->{ID3v2}) {
my $ref = $self->{ID3v2}{frames};
my $r;
if ($ref->{TIT2} and ($r) = (grep defined, @{$ref->{TIT2}})) {
$id3v1->[0] = $r->[0];
}
if ($ref->{TPE1} and ($r) = (grep defined, @{$ref->{TPE1}})) {
$id3v1->[1] = $r->[0];
}
if ($ref->{TALB} and ($r) = (grep defined, @{$ref->{TALB}})) {
$id3v1->[2] = $r->[0];
}
if ($ref->{COMM} and ($r) = (grep defined, @{$ref->{COMM}})) {
$id3v1->[4] = $r->[2];
}
if ($ref->{TYER}) {
for (grep defined, @{$ref->{TYER}}) {
if ($_->[0] =~ m/(\d{4})/) { $id3v1->[3] = $1; last }
}
}
if ($ref->{TRCK}) {
for (grep defined, @{$ref->{TRCK}}) {
if ($_->[0] =~ m/^(\d\d?)/) { $id3v1->[5] = $1; last }
}
}
if ($ref->{TCON}) {
unshift @genres, @$_ for grep defined, @{$ref->{TCON}};
}
#unshift @genres, @{ $ref->{TCON}[0] } if $ref->{TCON};
}
}
sub new_ID3v1 { Tag::ID3v1->new($_[0]); }
sub new_Lyrics3v2 { Tag::Lyrics3v2->new($_[0]); }
sub new_APE { Tag::APE->new($_[0]); }
sub new_ID3v2 { Tag::ID3v2->new($_[0]); }
sub add {
my $self = shift;
my $id3v2 = $self->{ID3v2} || $self->new_ID3v2;
$id3v2->add(@_);
}
sub insert {
my $self = shift;
my $id3v2 = $self->{ID3v2} || $self->new_ID3v2;
$id3v2->insert(@_);
}
sub edit {
my $self = shift;
my $id3v2 = $self->{ID3v2} || return 0;
$id3v2->edit(@_);
}
sub remove {
my $self = shift;
my $id3v2 = $self->{ID3v2} || return 0;
$id3v2->remove(@_);
}
sub remove_all {
my $self = shift;
my $id3v2 = $self->{ID3v2} || return 0;
$id3v2->remove_all(@_);
}
sub write_file {
my $self = shift;
my @towritebefore = ();
my @towriteafter = ();
my $id3v2tag;
my $copybegin = $self->{startaudio};
my $copyend = $self->{endaudio};
{
my $blank = $self->{blank}; #blank before audio
my $fh;
my $hole = 0;
for my $tag (reverse @{$self->{tags_before}})
{ #warn "$tag : ".(join ' ',keys %$tag)."\n";
if ($tag->{deleted}) {
$hole = 1;
}
elsif ($tag->{edited}) {
$hole = 1;
unshift @towritebefore, $tag->make;
$id3v2tag = $towritebefore[0]
if ref $tag eq 'Tag::ID3v2';
}
elsif ($hole) {
# read tag, put it in @towritebefore
$fh ||= $self->_open or return undef;
seek $fh, $tag->{offset}, 0;
my $buffer;
read $fh, $buffer, $tag->{size};
unshift @towritebefore, \$buffer;
}
else {
if ($blank) {
$copybegin -= $blank;
$blank = 0;
}
$copybegin -= $tag->{size};
}
}
$hole = 0;
for my $tag (reverse @{$self->{tags_after}}) {
if ($tag->{deleted}) {
$hole = 1;
}
elsif ($tag->{edited}) {
$hole = 1;
push @towriteafter, $tag->make;
}
elsif ($hole) {
# read tag, put it in @towriteafter
$fh ||= $self->_open or return undef;
seek $fh, $tag->{offset}, 0;
my $buffer;
read $fh, $buffer, $tag->{size};
push @towriteafter, \$buffer;
}
else {
$copyend += $tag->{size};
}
}
$self->_close if $fh;
}
push @towriteafter, $self->{ID3v1}->make
if $self->{ID3v1};
warn "startaudio="
. $self->{startaudio}
. " copybegin=$copybegin length(towritebefore)="
. join(' ', map(length $$_, @towritebefore)) . "\n"
if $::debug;
warn "endaudio="
. $self->{endaudio}
. " copyend=$copyend length(towriteafter)="
. join(' ', map(length $$_, @towriteafter)) . "\n"
if $::debug;
my $in_place;
if ($id3v2tag) {
my $padding = $copybegin;
$padding -= length($$_) for @towritebefore;
if ($padding < 0 || $padding > 2048) { $padding = 256 }
else { $in_place = 1 }
Tag::ID3v2::_SetPadding($id3v2tag, $padding);
}
if ($in_place) { # in place editing
warn "in place editing.\n"; # DEBUG
my $fh = $self->_openw or return undef;
return undef unless defined $fh;
print $fh $$_ or warn $! for @towritebefore;
seek $fh, $copyend, 0;
print $fh $$_ or warn $! for @towriteafter;
truncate $fh, tell($fh);
$self->_close;
return 1;
}
my $INfh = $self->_open or return undef;
# create new file
my $OUTfh = $self->_openw(1) or return undef; #open .TEMP file
my $werr;
print $OUTfh $$_ or warn $! and $werr++ for @towritebefore;
# copy audio data + unmodified tags next to audio data
seek $INfh, $copybegin, 0;
#read $INfh,my($buffer),$copyend-$copybegin;
#print $OUTfh $buffer or warn $! and $werr++;
my $tocopy = $copyend - $copybegin;
while ($tocopy > 0) {
my $size = ($tocopy > 1048576) ? 1048576 : $tocopy;
read $INfh, my ($buffer), $size;
print $OUTfh $buffer or warn $! and $werr++;
$tocopy -= $size;
}
$self->_close;
print $OUTfh $$_ or warn $! and $werr++ for @towriteafter;
close $OUTfh;
if ($werr) {
warn "write errors... aborting.\n";
unlink $self->{filename} . '.TEMP';
return 0;
}
warn "replacing old file with new file.\n";
unlink $self->{filename} && rename $self->{filename} . '.TEMP',
$self->{filename};
$MODIFIEDFILE = 1;
%$self = ()
; #destroy the object to make sure it is not reused as many of its data are now invalid
return 1;
}
sub _open {
my $self = $_[0];
my $file = $self->{filename};
open my $fh, '<', $file or warn "can't open $file : $!\n" and return undef;
binmode $fh;
$self->{fileHandle} = $fh;
return $fh;
}
sub _openw {
my ($self, $tmp) = @_;
my $file = $self->{filename};
my $m = '+<';
if ($tmp) { $file .= '.TEMP'; $m = '>'; }
my $fh;
until (open $fh, $m, $file) {
my $err = "Error opening '$file' for writing :\n$!";
warn $err . "\n";
return undef
unless $self->{errorsub}
&& $self->{errorsub}($!, 'openwrite', $file) eq 'retry';
}
binmode $fh;
$self->{fileHandle} = $fh unless $tmp;
return $fh;
}
sub _close {
my $self = shift;
close delete($self->{fileHandle});
}
sub _removeblank #remove blank before audio
{
my $self = $_[0];
my $fh = $self->{fileHandle};
seek $fh, $self->{startaudio}, 0;
my ($buf, $read);
my $blank = 0;
while (($read = read $fh, $buf, 100) && $buf =~ m/^\00+/) {
$blank += $+[0];
last unless $read == $+[0];
}
$self->{blank} = $blank;
return unless $blank;
warn "blank before audio : $blank bytes\n" if $::debug;
$self->{startaudio} += $blank;
}
sub _FindFirstFrame {
my ($self, $offset) = @_;
my $fh = $self->{fileHandle};
$offset ||= $self->{startaudio};
seek $fh, $offset, 0;
my $pos = 0;
my %info;
read $fh, my $buf, 100;
SEARCH1ST:
while ($pos < 60000) #only look in the first 60000 bytes (after tag)
{
while ($buf =~ m/\xff(...)/sg)
#while ($buf=~m/\xff([\xe0-\xff][\x00-\xef].)/sg)
{
my ($byte2, $byte3, $byte4) = unpack 'CCC', $1;
#print "AAABBCCD EEEEFFGH IIJJKLMM\n"; #DEBUG
#@_=unpack 'B8B8B8B8',$1; print "@_\n"; #DEBUG
#next if $byte2<0xf0; #not a synchro signal (0b11110000)
# next if $byte2<0xe0; #not a synchro signal (0b11100000)
# next unless $byte3<0xf0; #invalid bitrate # ($byte3 & 0b11110000)==0b11110000
my $mpgversion = ($byte2 >> 3) & 0b11;
next if $mpgversion == 1; #invalid MPEG version
my $layer = ($byte2 >> 1) & 0b11;
next if $layer == 0; #invalid layer
my $freq = ($byte3 >> 2) & 0b11;
next
if $freq == 3; #invalid frequence #warn "unknown sampling rate\n"
my $bitrateindex = $byte3 >> 4;
next if $bitrateindex == 15; #invalid bitrate index
$pos += $-[0];
$self->{firstframe} = $pos + $offset;
warn "skipped $pos, first frame at $self->{firstframe}\n"
if $pos && $::debug;
$self->{byte2} = $byte2;
$info{version2} = ($mpgversion & 0b1) ? 0 : 1;
$info{versionid} = $versions[$mpgversion];
$info{rate} = $freq[$mpgversion][$freq];
$info{layer} = 4 - $layer;
$info{crc} = ($byte2 & 0b1) ? 0 : 1;
$info{bitrate} = 1000
* $bitrates[$info{version2}][$info{layer} - 1][$bitrateindex];
#if ($info{bitrate}==0) { warn "free bitrate not supported\n"; }
$info{channels} = ($byte4 >> 6 == 3) ? 1 : 2;
$info{sampleperframe} =
$info{layer} == 1 ? 384
: $info{version2} ? 576
: 1152;
#compute size of first frame
my $pad = ($info{layer} == 1) ? 4 : 1;
my $firstframe_size =
int($info{bitrate} * $info{sampleperframe} / 8 / $info{rate});
$firstframe_size += $pad if $byte3 & 0b10;
#warn "firstframe_size : $firstframe_size\n";
$self->{audiodatasize} = $self->{endaudio} - $self->{firstframe};
#check for VBRI header #http://www.thecodeproject.com/audio/MPEGAudioInfo.asp
{
seek $fh, $self->{firstframe} + 36, 0;
read $fh, $_, 18;
my ($id, $vers, $delay, $quality, undef, $frames) =
unpack 'a4nnnNN', $_;
#should I $frames-- to remove this info frame ?
last unless $id eq 'VBRI';
warn
"VBRI header found : version=$vers delay=$delay quality=$quality nbframes=$frames\n"
if $::debug;
$info{vbr} = 1;
$self->{audiodatasize} -= $firstframe_size;
_calclength(\%info, $frames, $self->{audiodatasize});
last SEARCH1ST
}
#check if frame is the Xing/LAME header
{ #offset depends on mpegversion and channels :
# 13 for mono v2/2.5 , 36 for stereo v1 , 21 for other
$_ = (13, 21, 36)[(!$info{version2}) + ($info{channels} != 3)];
seek $fh, $self->{firstframe} + $_, 0;
read $fh, $_, 12;
my ($id, $flags, $frames) = unpack 'a4NN', $_;
last unless ($id eq 'Xing' || $id eq 'Info');
warn "Xing header found : $id flags=$flags nbframes=$frames\n"
if $::debug;
last unless $flags & 1; # unless number of frames is stored
$info{vbr} = ($id eq 'Xing');
$self->{audiodatasize} -= $firstframe_size;
_calclength(\%info, $frames, $self->{audiodatasize});
last SEARCH1ST;
}
#estimating number of frames assuming: found correct first frame and fixed bitrate
if ($info{bitrate}) {
$info{estimated} = 1;
$info{seconds} = $self->{audiodatasize} * 8 / $info{bitrate};
warn "length estimation : $info{seconds} s\n" if $::debug;
}
last SEARCH1ST;
}
#read next chunk but keep last 3 bytes
$pos += length($buf) - 3;
$buf = substr $buf, -3;
last unless read $fh, $buf, 100, 3;
}
return \%info if defined $self->{firstframe};
warn "no MP3 frame found\n";
return undef;
}
sub _CountFrames #find and count each frames
{
my ($self, $count_to) = @_;
my $time = $::debug && times; #DEBUG
$MODIFIEDFILE = undef;
my $info = $self->{info};
return 0 if $info->{bitrate} == 0; #if unknown bitrate
return 0 unless $info->{rate};
my $fh = $self->{fileHandle};
seek $fh, $self->{firstframe}, 0;
my $frames = 0;
my $skipcount;
my $byte1_2 = "\xff" . chr $self->{byte2};
# size of padding when present
my $pad = ($info->{layer} == 1) ? 4 : 1;
# construct @size array, which will contain the size of the frame in function of the EEEE bits
my $m = 1000 * $info->{sampleperframe} / 8 / $info->{rate};
my @size = map int($_ * $m) - 4,
@{$bitrates[$info->{version2}][$info->{layer} - 1]};
# -4 to substract 4 bytes header
$size[0] = $size[15] = 0
; #for free (0) or reserved (15) bitrate -> skip frame header and look for next
my $count = 1000;
#search for each frame
while (read $fh, $_, 4) {
if (substr($_, 0, 2) eq $byte1_2)
{ #print "AAAAAAAA AAABBCCD EEEEFFGH IIJJKLMM\n"; #DEBUG
#@_=unpack "B8B8B8B8",$_; print "@_\n"; #DEBUG
#my $pos=tell $fh; #DEBUG
#print "$pos frame=$frames size=$s bytes\n"; #DEBUG
#my $s=$cache{substr($_,2,1)}||=((vec $_,17,1)? $size[ (vec $_,2,8)>>4 ]+$pad:$size[ (vec $_,2,8)>>4 ])}; # a bit faster, needs a my %cache
$_ = vec $_, 2, 8;
#seek to the end of the frame :
seek $fh,
( ($_ & 0b10)
? $size[$_ >> 4] + $pad
: $size[$_ >> 4]
),
1;
$frames++;
if ($count_to && $frames > 3) {
return 1;
} #only wanted to check if first frame ok
unless ($count--) {
$count = 1000;
Gtk2->main_iteration while Gtk2->events_pending;
}
}
else #skip
{ #@_=unpack "B8B8",$byte1_2; warn "@_ ".tell($fh)."\n"; #DEBUG
#warn "AAAAAAAA AAABBCCD EEEEFFGH IIJJKLMM\n"; #DEBUG
#@_=unpack "B8B8B8B8",$_; warn "@_ doesn't match bytes1_2 frame=$frames\n"; #DEBUG
# assume first frame invalid if can't find 3 first frames without skipping
return 0 if $frames < 4;
my $skipped = 0;
my $read;
my $pos;
while ($read = read $fh, $_, 252, 4) {
if (m/\Q$byte1_2\E/) { $pos = $-[0]; last; }
$skipped += $read;
$_ = substr $_, -4;
}
if ($skipcount++ > 50) {
warn "mp3header: too much skipping\n" if $::debug;
return 0;
}
last unless $read && tell($fh) < $self->{endaudio};
$skipped += $pos;
warn "mp3header: skipped $skipped bytes (offset="
. tell($fh) . ")\n"
if $::debug;
seek $fh, $pos - 256, 1;
}
}
_calclength($info, $frames, $self->{audiodatasize});
$info->{estimated} = 1
if $MODIFIEDFILE
; #if a file has been rewrote while reading, mark the info as suspicious
if ($::debug) {
$time = times - $time;
warn "mp3header: full scan : $time s\n";
} #DEBUG
return 1;
}
sub _calclength {
my ($info, $frames, $bytes) = @_;
$info->{estimated} = undef;
$info->{frames} = $frames;
my $s = $info->{seconds} =
$frames * $info->{sampleperframe} / $info->{rate};
$info->{mmss} = sprintf '%d:%02d', $s / 60, $s % 60;
$info->{bitrate} = ($s == 0) ? 0 : $bytes * 8 / $s;
warn
"total_frames=$info->{frames}, audio_size=$bytes, length=$info->{mmss}, bitrate=$info->{bitrate}\n"
if $::debug;
}
package Tag::ID3v1;
use Encode qw(decode encode);
sub new {
my $file = $_[1];
return $file->{ID3v1} = bless [];
}
sub new_from_string {
my $string = $_[1];
my ($title, $artist, $album, $year, $comment, $vers1_1, $track, $genre) =
unpack 'x3 Z30 Z30 Z30 Z4 Z28 C C C', $string;
if ($vers1_1 != 0) #-> id3v1.0
{
$comment = unpack 'x97 Z30', $string;
$track = '';
}
s/ *$// for $title, $artist, $album, $comment;
$_ = decode($::Options{TAG_id3v1_encoding} || 'iso-8859-1', $_)
for $title, $artist, $album, $comment;
$genre = ($genre < @Tag::MP3::Genres) ? $Tag::MP3::Genres[$genre] : '';
return bless [$title, $artist, $album, $year, $comment, $track, $genre];
}
sub make {
my $self = shift;
my ($title, $artist, $album, $year, $comment, $track, $genre) = @$self;
if (defined $genre) {
if (ref $genre) {
($genre) = grep defined, map _findgenre($_), @$genre;
}
elsif ($genre =~ m/^\D+$/) { $genre = _findgenre($genre); }
}
$genre = 255 unless defined $genre && $genre ne '';
my $buffer = 'TAG';
my @length = (30, 30, 30, 4, 30);
$length[4] = 28 if $track;
for my $v ($title, $artist, $album, $year, $comment) {
$v = '' unless defined $v;
my $l = shift @length;
$v = encode($::Options{TAG_id3v1_encoding} || 'iso-8859-1', $v);
if (bytes::length($v) < $l) { $buffer .= pack "Z$l", $v }
else {
$buffer .= pack "A$l", $v;
} #FIXME remove partial multi-byte chars
}
$buffer .= "\x00" . bytes::chr($track) if $track;
$buffer .= bytes::chr $genre;
return \$buffer;
}
sub _findgenre {
my $str = shift;
my $list = \@Tag::MP3::Genres;
$str = lc $str;
my $i;
for (0 .. $#$list) {
if ($str eq lc $list->[$_]) { $i = $_; last }
}
return $i;
}
sub get_values {
return $_[0][$_[1]];
}
package Tag::Lyrics3v1;
use Encode qw(decode encode);
sub new_from_file #http://www.id3.org/lyrics3.html #untested
{
my ($class, $file) = @_;
my $fh = $file->{fileHandle};
seek $fh, -5109, 1;
read $fh, my ($buffer), 5100;
return undef unless $buffer =~ m/LYRICSBEGIN(.+)/;
warn "found lyrics3 v1 tag (" . length($1) . " bytes of lyrics)\n"
if $::debug;
my %tag;
$tag{size} = length $1;
$tag{lyrics} = decode('iso-8859-1', $1);
$tag{makesub} = \&_MakeLyrics3Tag;
return $file->{lyrics3} = bless(\%tag, $class);
}
sub removetag { $_[0]{deleted} = 1; }
sub make {
my $tag = shift;
my $tagstring =
'LYRICSBEGIN'
. substr(encode('iso-8859-1', $tag->{lyrics}), 0, 4096)
. 'LYRICSEND';
return \$tagstring;
}
package Tag::Lyrics3v2;
use Encode qw(decode encode);
sub new {
my ($class, $file) = @_;
my $self = {fields => {}, fields_order => [], edited => 1};
unshift @{$file->{tags_after}}, $self;
$file->{lyrics3v2} = $self;
return bless($self, $class);
}
sub new_from_file #http://www.id3.org/lyrics3200.html
{
my ($class, $file) = @_;
my $fh = $file->{fileHandle};
seek $fh, $file->{endaudio} - 15, 0;
read $fh, my ($header), 15;
my $size = substr $header, 0, 6;
return undef unless $size =~ m/^[0-9]+$/;
seek $fh, -$size - 15, 1;
read $fh, my ($rawtag), $size;
return undef unless $rawtag =~ s/^LYRICSBEGIN//;
my %tag;
$tag{size} = $size + 15;
warn "found lyrics3 v2.00 tag (" . $tag{size} . " bytes)\n" if $::debug;
while ($rawtag =~ s/^([A-Z]{3})([0-9]{5})//) {
if ($1 eq 'IND') { $tag{IND} = substr($rawtag, 0, $2, ''); next; }
$tag{fields}{$1} = decode('iso-8859-1', substr($rawtag, 0, $2, ''));
push @{$tag{fields_order}}, $1;
warn "Lyrics3 $1 : $tag{fields}{$1}\n" if $::debug;
}
return $file->{lyrics3v2} = bless(\%tag, $class);
}
sub removetag { $_[0]{deleted} = 1; }
sub add {
my ($self, $field, $val) = @_;
return 0 if $self->{fields}{$field};
push @{$self->{fields_order}}, $field;
$self->{fields}{$field} = $val;
$self->{edited} = 1;
return 1;
}
sub edit {
my ($self, $field, $nb, $val) = @_;
return 0 unless $self->{fields}{$field};
$self->{fields}{$field} = $val;
$self->{edited} = 1;
return 1;
}
sub remove {
my ($self, $field) = @_;
delete $self->{fields}{$field};
$self->{edited} = 1;
return 1;
}
sub get_keys {
keys %{$_[0]{fields}};
}
sub get_values {
return $_[0]{fields}{$_[1]};
}
sub make {
my $tag = shift;
my $tagstring = 'LYRICSBEGIN';
$tagstring .= 'IND' . sprintf('%05d', length($tag->{IND})) . $tag->{IND}
if $tag->{IND};
for my $field (@{$tag->{fields_order}}) {
next unless defined $tag->{fields}{$field};
my $v = substr encode('iso-8859-1', delete $tag->{fields}{$field}), 0,
99999;
$tagstring .= $field . sprintf('%05d', length $v) . $v;
}
if ($tagstring ne 'LYRICSBEGIN') #not empty
{
$tagstring =
$tagstring . sprintf('%06d', length $tagstring) . 'LYRICS200';
}
return \$tagstring;
}
package Tag::APE;
# http://wiki.hydrogenaudio.org/index.php?title=APEv2_specification
use Encode qw(decode encode);
sub new {
my ($class, $file) = @_;
my $self = {realkey => {}, item => {}, edited => 1};
unshift @{$file->{tags_after}}, $self;
$file->{APE} = $self;
return bless($self, $class);
}
sub new_from_file {
my ($class, $file, $isfooter) = @_;
my $fh = $file->{fileHandle};
if ($isfooter) { seek $fh, $file->{endaudio} - 32, 0; }
else { seek $fh, $file->{startaudio}, 0; }
read $fh, my ($headorfoot), 32;
my ($v, $size, $Icount, $flags) = unpack 'x8VVVV', $headorfoot;
my $rawtag;
$size += 32 if $flags & 0x80000000; #if contains a header
return undef unless $size; #for some bogus header with a size=0
if ($flags & 0x20000000) #if $headorfoot is a header
{
read $fh, $rawtag, $size - 32;
return undef
unless ($flags & 0x40000000)
|| $rawtag =~ m/APETAGEX.{24}$/s; #check footer
}