-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paths-cdda-to-db.pl
executable file
·3310 lines (2902 loc) · 95.5 KB
/
s-cdda-to-db.pl
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
#!/usr/bin/env perl
require 5.008_008; # ${^UTF8LOCALE}
my $SELF = 's-cdda-to-db';
my $ABSTRACT = 'integrate audio CDs into directory pool.';
#@ Web: https://www.sdaoden.eu/code.html
#@ Requirements:
#@ - s-cdda for CD-ROM access (https://ftp.sdaoden.eu/s-cdda-latest.tar.gz).
#@ P.S.: not on MacOS X/Darwin, but not tested there for many years
#@ - For MusicBrainz: XML::Parser and HTTP::Tiny (plus IO::Socket::SSL).
#@ - Unless --no-volume-normalize is used: sox(1) (sox.sourceforge.net).
#@ NOTE: sox(1) changed - see $NEW_SOX below.
#@ - For MP3: lame(1) (www.mp3dev.org).
#@ - For MP4/AAC: faac(1) (www.audiocoding.com).
#@ - For Ogg/Vorbis: oggenc(1) (www.xiph.org).
#@ - For FLAC: flac(1) (www.xiph.org).
#@ - For OPUS: opusenc (see Vorbis TODO untested!).
#
# Copyright (c) 1998 - 2003, 2010 - 2014, 2016 - 2018,
# 2020 - 2022 Steffen Nurpmeso <[email protected]>.
# SPDX-License-Identifier: ISC
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
my $VERSION = '0.8.1';
my $CONTACT = 'Steffen Nurpmeso <[email protected]>';
# MusicBrainz Web-Service; we use TLS if possible
my $MBRAINZ_URL = '://musicbrainz.org/ws/2';
my $MBRAINZ_AGENT = $SELF.'/'.$VERSION.' (https://www.sdaoden.eu/code.html)';
# New sox(1) (i guess this means post v14) with '-e signed-integer' instead of
# -s, '-b 16' instead of -w and -n (null device) instead of -e (to stop input
# file processing)
my $NEW_SOX = 1;
# Dito: change the undef to '/Desired/Path'
my $MUSIC_DB = defined $ENV{S_MUSIC_DB} ? $ENV{S_MUSIC_DB} : undef;
my $CDROM = defined $ENV{CDROM} ? $ENV{CDROM} : undef;
my $TMPDIR = (defined $ENV{TMPDIR} && -d $ENV{TMPDIR}) ? $ENV{TMPDIR} : '/tmp';
my $ED = defined $ENV{VISUAL} ? $ENV{VISUAL} : (defined $ENV{EDITOR} ? $ENV{EDITOR} : '/usr/bin/vi');
# Only MacOS X (xxx better undef??)
my $CDROMDEV = (defined $ENV{CDROMDEV} ? $ENV{CDROMDEV} : (defined $CDROM ? $CDROM : undef));
## -- >8 -- 8< -- ##
#use diagnostics -verbose;
use warnings;
use strict;
use Digest;
use Encode;
use Getopt::Long;
use POSIX qw(setlocale LC_ALL);
# Genre list, alpha sorted {{{
my @Genres = (
[ 123, 'A Cappella' ], [ 34, 'Acid' ], [ 74, 'Acid Jazz' ], [ 73, 'Acid Punk' ], [ 99, 'Acoustic' ],
[ 20, 'Alternative' ], [ 40, 'Alt. Rock' ], [ 26, 'Ambient' ], [ 145, 'Anime' ], [ 90, 'Avantgarde' ],
[ 116, 'Ballad' ], [ 41, 'Bass' ], [ 135, 'Beat' ], [ 85, 'Bebob' ], [ 96, 'Big Band' ], [ 138, 'Black Metal' ],
[ 89, 'Bluegrass' ], [ 0, 'Blues' ], [ 107, 'Booty Bass' ], [ 132, 'BritPop' ],
[ 65, 'Cabaret' ], [ 88, 'Celtic' ], [ 104, 'Chamber Music' ], [ 102, 'Chanson' ], [ 97, 'Chorus' ],
[ 136, 'Christian Gangsta Rap' ], [ 61, 'Christian Rap' ], [ 141, 'Christian Rock' ],
[ 32, 'Classical' ], [ 1, 'Classic Rock' ], [ 112, 'Club' ], [ 128, 'Club-House' ], [ 57, 'Comedy' ],
[ 140, 'Contemporary Christian' ], [ 2, 'Country' ], [ 139, 'Crossover' ], [ 58, 'Cult' ],
[ 3, 'Dance' ], [ 125, 'Dance Hall' ], [ 50, 'Darkwave' ], [ 22, 'Death Metal' ], [ 4, 'Disco' ],
[ 55, 'Dream' ], [ 127, 'Drum & Bass' ], [ 122, 'Drum Solo' ], [ 120, 'Duet' ],
[ 98, 'Easy Listening' ], [ 52, 'Electronic' ], [ 48, 'Ethnic' ], [ 54, 'Eurodance' ], [ 124, 'Euro-House' ],
[ 25, 'Euro-Techno' ],
[ 84, 'Fast-Fusion' ], [ 80, 'Folk' ], [ 115, 'Folklore' ], [ 81, 'Folk/Rock' ], [ 119, 'Freestyle' ],
[ 5, 'Funk' ], [ 30, 'Fusion' ],
[ 36, 'Game' ], [ 59, 'Gangsta Rap' ], [ 126, 'Goa' ], [ 38, 'Gospel' ], [ 49, 'Gothic' ],
[ 91, 'Gothic Rock' ], [ 6, 'Grunge' ],
[ 129, 'Hardcore' ], [ 79, 'Hard Rock' ], [ 137, 'Heavy Metal' ], [ 7, 'Hip-Hop' ], [ 35, 'House' ],
[ 100, 'Humour' ],
[ 131, 'Indie' ], [ 19, 'Industrial' ], [ 33, 'Instrumental' ], [ 46, 'Instrumental Pop' ],
[ 47, 'Instrumental Rock' ],
[ 8, 'Jazz' ], [ 29, 'Jazz+Funk' ], [ 146, 'JPop' ], [ 63, 'Jungle' ],
[ 86, 'Latin' ], [ 71, 'Lo-Fi' ],
[ 45, 'Meditative' ], [ 142, 'Merengue' ], [ 9, 'Metal' ], [ 77, 'Musical' ],
[ 82, 'National Folk' ], [ 64, 'Native American' ], [ 133, 'Negerpunk' ], [ 10, 'New Age' ],
[ 66, 'New Wave' ], [ 39, 'Noise' ],
[ 11, 'Oldies' ], [ 103, 'Opera' ], [ 12, 'Other' ],
[ 75, 'Polka' ], [ 134, 'Polsk Punk' ], [ 13, 'Pop' ], [ 53, 'Pop-Folk' ], [ 62, 'Pop/Funk' ],
[ 109, 'Porn Groove' ], [ 117, 'Power Ballad' ], [ 23, 'Pranks' ], [ 108, 'Primus' ],
[ 92, 'Progressive Rock' ], [ 67, 'Psychedelic' ], [ 93, 'Psychedelic Rock' ], [ 43, 'Punk' ],
[ 121, 'Punk Rock' ],
[ 15, 'Rap' ], [ 68, 'Rave' ], [ 14, 'R&B' ], [ 16, 'Reggae' ], [ 76, 'Retro' ], [ 87, 'Revival' ],
[ 118, 'Rhythmic Soul' ], [ 17, 'Rock' ], [ 78, 'Rock & Roll' ],
[ 143, 'Salsa' ], [ 114, 'Samba' ], [ 110, 'Satire' ], [ 69, 'Showtunes' ], [ 21, 'Ska' ],
[ 111, 'Slow Jam' ], [ 95, 'Slow Rock' ], [ 105, 'Sonata' ], [ 42, 'Soul' ], [ 37, 'Sound Clip' ],
[ 24, 'Soundtrack' ], [ 56, 'Southern Rock' ], [ 44, 'Space' ], [ 101, 'Speech' ], [ 83, 'Swing' ],
[ 94, 'Symphonic Rock' ], [ 106, 'Symphony' ], [ 147, 'Synthpop' ],
[ 113, 'Tango' ], [ 18, 'Techno' ], [ 51, 'Techno-Industrial' ], [ 130, 'Terror' ], [ 144, 'Thrash Metal' ],
[ 60, 'Top 40' ], [ 70, 'Trailer' ], [ 31, 'Trance' ], [ 72, 'Tribal' ], [ 27, 'Trip-Hop' ],
[ 28, 'Vocal' ]
); # }}}
my $DEBUG = undef;
my $ENC_ONLY = 0;
my $MBRAINZ_QUERY = 2;
my $NO_FRAMES = undef;
my $NO_VOL_NORM = 0;
my $READ_ONLY = 0;
my $VERBOSE = 0;
my $MBRAINZ_TLS = 0;
my ($CLEANUP_OK, $WORK_DIR, $TARGET_DIR) = (0);
sub main_fun{ # {{{
setlocale(LC_ALL, "");
if(!${^UTF8LOCALE}){
print STDERR <<__EOT;
WARNING WARNING WARNING
This is not an UTF-8 (Unicode) locale.
Track metadata is also stored in encoded files, and will be in UTF-8
encoding: it might be mangled by the encoder (only oggenc and flac
support specifying that data already is in UTF-8 encoding).
It could be that this does not produce the results you desire!
You could instead (temporarily) use an UTF-8 locale:
# or XY.utf8 etc.: system-dependent
EITHER: \$ LC_ALL=en_US.UTF-8; export LC_ALL
OR : \$ LC_ALL=en_US.UTF-8 s-cdda-to-db xy
WARNING WARNING WARNING
__EOT
print STDERR 'Continue nonetheless';
exit 1 unless user_confirm()
}
# Also verifies we have valid (DB,TMP..) paths
command_line();
$SIG{INT} = sub {print STDERR "\nInterrupted ... bye\n"; exit 1};
print "$SELF ($VERSION)\nPress ^C (CNTRL-C) at any time to interrupt\n";
my ($info_ok, $needs_cddb) = (0, 1);
# Unless we have seen --encode-only=ID
unless(defined $CDInfo::CDId){
CDInfo::discover();
$info_ok = 1
}
$WORK_DIR = "$TMPDIR/$SELF.$CDInfo::CDId";
$TARGET_DIR = "$MUSIC_DB/disc.${CDInfo::CDId}-";
if(-d "${TARGET_DIR}1"){
$TARGET_DIR = quick_and_dirty_dir_selector()
}else{
$TARGET_DIR .= '1'
}
print <<__EOT;
S_MUSIC_DB target: $TARGET_DIR
WORKing directory: $WORK_DIR
(In worst-case error situations it might be necessary to remove them manually.)
__EOT
die 'Non-existent session cannot be resumed via --encode-only' if $ENC_ONLY && ! -d $WORK_DIR;
unless(-d $WORK_DIR){
die "Cannot create $WORK_DIR: $!" unless mkdir $WORK_DIR
}
unless($READ_ONLY || -d $TARGET_DIR){
die "Cannot create $TARGET_DIR: $!" unless mkdir $TARGET_DIR
}
CDInfo::init_paths();
MBDB::init_paths();
# Get the info right, and maybe the database
if(!$info_ok){
CDInfo::read_data();
$info_ok = -1
}
Title::create_that_many($CDInfo::TrackCount);
if(-f $MBDB::FinalFile){
die 'Database corrupted - remove TARGET and re-create entire disc' unless MBDB::db_read();
$needs_cddb = 0
}elsif($info_ok > 0){
CDInfo::write_data()
}
if(!$READ_ONLY && $needs_cddb){
CDInfo::InfoSource::query_all();
MBDB::db_create()
}
# Handling files
if($READ_ONLY || !$ENC_ONLY){
user_tracks();
Title::read_all_selected();
print "\nUse --encode-only=$CDInfo::CDId to resume ...\n" if $READ_ONLY
}elsif($ENC_ONLY){
my @rawfl = glob("$WORK_DIR/*." . $CDInfo::ReadFileExt);
die '--encode-only session on empty file list' if @rawfl == 0;
foreach(sort @rawfl){
die '--encode-only session: illegal filenames exist' unless /(\d+).${CDInfo::ReadFileExt}$/;
my $i = int $1;
die "\
--encode-only session: track $_ is unknown!
It does not seem to belong to this disc, you need to re-create it."
unless $i > 0 && $i <= $CDInfo::TrackCount;
my $t = $Title::List[$i - 1];
$t->{IS_SELECTED} = 1
}
#print "\nThe following raw tracks will now be encoded:\n ";
#print "$_->{NUMBER} " foreach (@Title::List);
#print "\nIs this really ok? You may interrupt now";
#exit(5) unless user_confirm()
}
unless($READ_ONLY){
Enc::calculate_volume_normalize($NO_VOL_NORM);
Enc::encode_selected();
$CLEANUP_OK = 1
}
exit 0
} # }}}
END {finalize() if $CLEANUP_OK}
# command_line + support {{{
sub command_line{
Getopt::Long::Configure('bundling');
my %opts = (
'h|help|?' => sub {goto jdocu},
'g|genre-list' => sub{
printf("%3d %s\n", $_->[0], $_->[1]) foreach(@Genres);
exit 0
},
'debug=s' => \$DEBUG,
'd|device=s' => \$CDROM,
'e|encode-only=s' => \$ENC_ONLY,
'f|formats=s' => sub {parse_formats($_[1])},
'frames=i' => \$NO_FRAMES,
'm|music-db=s' => \$MUSIC_DB,
'no-volume-normalize' => \$NO_VOL_NORM,
'music-brainz!' => \$MBRAINZ_QUERY,
'r|read-only' => \$READ_ONLY,
'v|verbose' => \$VERBOSE,
'music-brainz-tls' => \$MBRAINZ_TLS
);
if($^O eq 'darwin'){
$opts{'cdromdev=s'} = \$CDROMDEV
}
my ($emsg) = (undef);
unless(GetOptions(%opts)){
$emsg = 'Invocation failure';
goto jdocu
}
if(defined $DEBUG){
print STDERR "! DEBUG mode..\n! -> S_MUSIC_DB=/tmp/\n! -> DATFILE=", $DEBUG, "\n";
$MUSIC_DB = '/tmp/'
}
if($ENC_ONLY){
if($READ_ONLY){
$emsg = '--read-only and --encode-only are mutual exclusive';
goto jdocu
}
if($ENC_ONLY !~ /[[:alnum:]]+/){
$emsg = "$ENC_ONLY is not a valid CD(DB)ID";
goto jdocu
}
$CDInfo::CDId = lc $ENC_ONLY;
$ENC_ONLY = 1
}
# We now always need this, even in $READ_ONLY mode.
$MUSIC_DB = glob $MUSIC_DB if defined $MUSIC_DB;
unless(defined $MUSIC_DB && -d $MUSIC_DB && -w _){
$emsg = '-m / $S_MUSIC_DB directory not accessible';
goto jdocu
}
unless($READ_ONLY){
if(!Enc::format_has_any() && defined(my $v = $ENV{S_MUSIC_FORMATS})){
parse_formats($v)
}
unless(Enc::format_has_any()){
$emsg = 'No audio formats given via -f or $S_MUSIC_FORMATS';
goto jdocu
}
}
$TMPDIR = glob $TMPDIR if defined $TMPDIR;
unless(defined $TMPDIR && -d $TMPDIR && -w _){
$emsg = "The given TMPDIR is somehow not accessible";
goto jdocu
}
return;
jdocu:
my $FH = defined $emsg ? *STDERR : *STDOUT;
my $flr = Enc::format_list();
$flr = join ',', @$flr;
print $FH <<__EOT;
$SELF ($VERSION): $ABSTRACT
$SELF -h|--help / $SELF -g|--genre-list
$SELF [-v] [-d DEV] [-f|--formats ..] [--frames=NUMBER]
[-m|--music-db PATH] [--no-volume-normalize]
Do all the entire processing in one run
$SELF [-v] [-d DEV] -r|--read-only
Only read audio tracks from CD-ROM to temporary work directory
$SELF [-v] [-f|--formats ..] [--frames=NUMBER] [-m|--music-db PATH]
[--no-volume-normalize] -e|--encode-only CDID
Only resume a --read-only session
-d|--device DEV Use CD-ROM DEVice; else s-cdda(1) fallback
-e|--encode-only CDID Resume --read-only session; it echoed the CDID to use
-f|--formats LIST Comma-separated audio format list; else \$S_MUSIC_FORMATS
Note: OPUS untested ($flr)
--frames=NUMBER frames to read per iteration
-m|--music-db PATH S-Music DB directory; else \$S_MUSIC_DB
-r|--read-only Only read data, then exit; resume with --encode-only
-v|--verbose Be more verbose; does not delete temporary files!
. Environment variables: \$TMPDIR, \$VISUAL (\$EDITOR), \$LC_ALL
. Bugs/Contact via $CONTACT
__EOT
if($^O eq 'darwin'){
print $FH <<__EOT;
MacOS only:
WARNING - Mac OS untested after (s-cdda(1) based) rewrite!
--cdromdev SPEC
Maybe needed in addition to \$CDROM; here SPEC is a simple drive number,
for example 1. Whereas --cdrom= is used for -drive option of drutil(1),
--cdromdev= is for raw </dev/disk?> access. Beware that these may not
match, and also depend on usage order of USB devices. The default settings
come from the \$CDROMDEV environment variable
__EOT
}
print $FH "\n! $emsg\n" if defined $emsg;
exit defined $emsg ? 1 : 0
}
sub parse_formats{
my ($v) = @_;
while($v =~ /^,?\s*(\w+)\s*(,.*)?$/){
$v = defined $2 ? $2 : '';
die "Unknown audio encoding format: $1" unless Enc::format_add($1)
}
}
# }}}
# v, genre, genre_id, finalize, user_confirm {{{
sub v{
return unless $VERBOSE > 0;
print STDOUT '-V ', shift, "\n";
while(@_ != 0) {print STDOUT '-V ++ ', shift, "\n"};
1
}
sub genre{
my $g = shift;
if($g =~ /^(\d+)$/){
$g = $1;
foreach my $tr (@Genres){
return $tr->[1] if $tr->[0] == $g
}
}else{
$g = lc $g;
foreach my $tr (@Genres){
return $tr->[1] if lc($tr->[1]) eq $g
}
}
undef
}
sub genre_id{
my $g = shift;
foreach my $tr (@Genres){
return $tr->[0] if $tr->[1] eq $g
}
# (Used only for valid genre-names)
}
# (Called by END{} only if $CLEANUP_OK)
sub finalize{
if($VERBOSE){
v("--verbose mode: NOT removing $WORK_DIR");
return
}
print "\nRemoving temporary $WORK_DIR\n";
unlink $CDInfo::DatFile, $MBDB::EditFile; # XXX
foreach(@Title::List){
next unless -f $_->{RAW_FILE};
die "Cannot unlink $_->{RAW_FILE}: $!" unless unlink $_->{RAW_FILE}
}
die "rmdir $WORK_DIR failed: $!" unless rmdir $WORK_DIR
}
sub user_confirm{
my $save = $|;
$| = 1;
print ' [^[Nn]* (or else)] ';
my $u = <STDIN>;
$| = $save;
chomp $u;
($u =~ /^n/i) ? 0 : 1
}
# }}}
sub quick_and_dirty_dir_selector{ # {{{
my @dlist = glob "${TARGET_DIR}*/music.db";
return "${TARGET_DIR}1" if @dlist == 0;
print <<__EOT;
CD(DB)ID clash detected!
Either (1) the disc is not unique
or (2) you are trying to extend/replace some files of a yet existent disc.
(Note that the temporary WORKing directory will clash no matter what you do!)
Here is a list of yet existent albums which match that CDID:
__EOT
my ($i, $usr);
for($i = 1; $i <= @dlist; ++$i){
my $d = "${TARGET_DIR}$i";
my $f = "$d/music.db";
unless(open F, '<:encoding(UTF-8)', $f){
print " [] Skipping due to failed open: $f\n";
next
}
my ($ast, $at, $tr) = (undef, undef, undef);
while(<F>){
if(/^\s*\[ALBUMSET\]\s*$/) {$tr = \$ast}
elsif(/^\s*\[ALBUM\]\s*$/) {$tr = \$at}
elsif(/^\s*\[CDDB\]\s*$/) {next}
elsif(/^\s*\[\w+\]\s*$/) {last}
elsif(defined $tr && /^\s*TITLE\s*=\s*(.+?)\s*$/) {$$tr = $1}
}
die "Cannot close $f: $!" unless close F;
unless(defined $at){
print " [] No TITLE entry in $f!\n Disc data seems corrupted and must be re-created!\n";
next
}
$at = "$ast - $at" if defined $ast;
print " [$i] $at\n"
}
print " [0] None of these - the disc should create a new entry!\n";
jREDO:
print " Choose the number to use: ";
$usr = <STDIN>;
chomp $usr;
unless($usr =~ /^\d+$/ && ($usr = int $usr) >= 0 && $usr <= @dlist){
print "! I am expecting one of the [numbers] ... !\n";
goto jREDO
}
if($usr == 0){
print " .. forced to create a new disc entry\n";
return "${TARGET_DIR}$i"
}else{
print " .. forced to resume an existent album\n";
return "${TARGET_DIR}$usr"
}
} # }}}
sub user_tracks{ # {{{
print "Disc $CDInfo::CDId contains $CDInfo::TrackCount songs - shall all be read";
if(user_confirm()){
print " Whee - all songs will be read!\n";
$_->{IS_SELECTED} = 1 foreach (@Title::List);
return
}
my ($line, @dt);
jREDO:
print ' Please enter a space separated list of the desired track numbers', "\n ";
$line = <STDIN>;
chomp $line;
@dt = split /\s+/, $line;
print " Is this list correct <", join(' ', @dt), '>';
goto jREDO unless user_confirm();
unless(@dt){
print "? So why are you using an audio CD reader, then?\n";
exit 42
}
foreach(@dt){
if($_ == 0 || $_ > $CDInfo::TrackCount){
print "! Invalid track number: $_!\n\n";
goto jREDO
}
}
$Title::List[$_ - 1]->{IS_SELECTED} = 1 foreach(@dt)
} # }}}
{package CDInfo; # {{{
our ($RawIsWAVE, $ReadFileExt) = (0, 'raw');
# Id field may also be set from command_line(). Mostly set by _calc_id() or parse() only
our ($CDId, $MBrainzDiscId, $MCN, $TrackCount, $TrackFirst, $TrackLast, $FileReader, $DatFile);
our @TracksLBA = ();
our @TracksISRC = ();
our @CDText = ();
my $DevId;
my $Leadout = 0xAA;
sub init_paths{
$DatFile = "$WORK_DIR/cdinfo.dat"
}
sub discover{
no strict 'refs';
die "! System $^O not supported" unless defined *{"CDInfo::_os_$^O"};
print "\nCDInfo: assuming an Audio-CD is in the drive ...\n";
my $i;
unless(defined $DEBUG){
$i = &{"CDInfo::_os_$^O"}()
}else{
my $j = $DatFile;
$DatFile = $DEBUG;
read_data();
$DatFile = $j;
return
}
if(defined $i){
print $i, "! Unable to collect CD Table-Of-Contents\n",
"! This may mean the Audio-CD was not yet fully loaded\n",
"! It can also happen for copy-protection .. or whatever\n";
exit 1
}
print " CD(DB) ID: $CDId | MusicBrainz Disc ID: ",
$MBrainzDiscId, "\n ",
'Track L(ogical)B(lock)A(ddressing)s: ' . join(' ', @TracksLBA),
"\n Track: count $TrackCount, first $TrackFirst, last $TrackLast\n"
}
sub _os_darwin{ # {{{
my $drive = defined $CDROM ? $CDROM : 1;
$DevId = defined $CDROMDEV ? $CDROMDEV : $drive;
print " Darwin/Mac OS X: drive $drive and /dev/disk$DevId\n",
"!! WARNING: Darwin/MAC OS X not tested for a long time, and after majore rewrite!\n";
$FileReader = sub{
my $title = shift;
my ($inf, $outf, $byteno, $blckno, $buf, $err) = (undef, undef, undef, 0, 0, undef, undef);
$inf = '/dev/disk' . $DevId . 's' . $title->{NUMBER};
$outf = $title->{RAW_FILE};
return "! Cannot open for reading: $inf: $!\n" unless open INFH, '<', $inf;
# (Yet-exists case handled by caller)
unless(open OUTFH, '>', $outf){
$err = $!;
close INFH;
return "! Cannot open for writing: $outf: $err\n"
}
unless(binmode(INFH) && binmode(OUTFH)){
close OUTFH;
close INFH;
return "! Failed to set binary mode for $inf and/or $outf\n"
}
while(1){
my $r = sysread INFH, $buf, 2352 * 20;
unless(defined $r){
$err = "! I/O read failed: $!\n";
last
}
last if $r == 0;
$byteno += $r;
$blckno += $r / 2352;
for(my $o = 0; $r > 0; ){
my $w = syswrite OUTFH, $buf, $r, $o;
unless(defined $w){
$err = "! I/O write failed: $!\n";
goto jdarwin_read_stop
}
$o += $w;
$r -= $w
}
}
jdarwin_read_stop:
close OUTFH; # XXX errors?
close INFH; # XXX errors?
return $err if defined $err;
print " .. stored $blckno blocks ($byteno bytes)\n";
return undef
};
# Problem: this non-UNIX thing succeeds even without media...
::v("Invoking drutil(1) -drive $drive toc");
sleep 1;
my $l = `drutil -drive $drive toc`;
return "! Drive $drive: failed reading TOC: $!\n" if $?;
my @res = split "\n", $l;
my (@cdtoc, $leadout, $leadout_lba);
($TrackFirst, $TrackLast) = (0xFF, 0x00);
for(;;){
$l = shift @res;
return "! Drive $drive: no lead-out information found\n" unless defined $l;
if($l =~ /^\s*Lead-out:\s+(\d+):(\d+)\.(\d+)/){
$leadout_lba = ((($1 * 60 + $2) * 75) + $3) - 150;
$leadout = "$Leadout $1 $2 $3";
last
}
}
for(my $li = 0;; ++$li){
$l = shift @res;
last unless defined $l;
last unless $l =~ /^\s*Session\s+\d+,\s+Track\s+(\d+):\s+(\d+):(\d+)\.(\d+).*/;
return "! Drive $drive: corrupted TOC: $1 follows $li\n" unless $1 == $li + 1;
$TrackFirst = $1 if $1 < $TrackFirst;
$TrackLast= $1 if $1 > $TrackLast;
push @cdtoc, "$1 $2 $3 $4";
push @TracksLBA, ((($2 * 60 + $3) * 75) + $4) - 150
}
return "! Drive $drive: no track information found\n" unless @cdtoc > 0;
push @cdtoc, $leadout;
push @TracksLBA, $leadout_lba;
my $emsg = _check_cddb_state('');
return $emsg if length $emsg;
_calc_cdid(\@cdtoc);
_calc_mb_discid();
return undef
} # }}}
# OSs for s-cdda {{{
sub _os_dragonfly {return _os_via_scdda('DragonFly BSD')}
sub _os_freebsd {return _os_via_scdda('FreeBSD')}
sub _os_linux {return _os_via_scdda('Linux')}
sub _os_netbsd {return _os_via_scdda('NetBSD')}
sub _os_openbsd {return _os_via_scdda('OpenBSD')}
sub _os_via_scdda{
($RawIsWAVE, $ReadFileExt) = (1, 'wav');
my ($frames, $dev, $l, @res, @cdtoc);
$frames = defined $NO_FRAMES ? ' -f ' . $NO_FRAMES : '';
print ' ', shift, ': ';
if(defined $CDROM){
$dev = "-d $CDROM";
print "device $CDROM"
}else{
$dev = '';
print 'using S-cdda(1) default device'
}
print "\n";
$FileReader = sub{
my $title = shift;
return undef if 0 == system("s-cdda $dev $frames " . ($VERBOSE ? '-v ' : '') .
'-r ' . $title->{NUMBER} . ' > ' . $title->{RAW_FILE});
return "! Device $dev: cannot read track $title->{NUMBER}: $?\n"
};
$l = 's-cdda ' . $dev . $frames .($VERBOSE ? ' -v' : '');
::v("Invoking $l");
$l = `$l`;
return "! ${dev}" . (length $dev ? ': f' : 'F') . "ailed reading TOC: $?/$!\n" if $?;
@res = split "\n", $l;
my ($emsg, $had_leadout) = ('', 0);
for(;;){
$l = shift @res;
last unless defined $l;
if($l =~ /^t=(\d+)\s+t\d+_msf=(\d+):(\d+).(\d+)\s+t\d+_lba=(\d+)\s+.*$/){
my ($tno, $mm, $ms, $mf, $lba) = ($1, $2, $3, $4, $5);
$emsg .= "! Corrupted: lead-out not last entry\n" if $had_leadout;
if($tno < 1){
$emsg .= "! Corrupted: invalid track number: $tno\n";
next
}
$cdtoc[$tno - 1] = "$tno $mm $ms $mf";
$TracksLBA[$tno - 1] = $lba
}elsif($l =~ /^t=0\s+t0_msf=(\d+):(\d+).(\d+)\s+t0_lba=(\d+)$/){
my ($mm, $ms, $mf, $lba) = ($1, $2, $3, $4);
$had_leadout = 1;
push @cdtoc, "$Leadout $mm $ms $mf";
push @TracksLBA, $lba
}elsif($l =~ /^t0_count=(\d+)\s+t0_track_first=(\d+)\s+t0_track_last=(\d+)/){
($TrackCount, $TrackFirst, $TrackLast) = ($1, $2, $3)
}elsif($l =~ /^t0_mcn=(\w+)\s*$/){ # (just take the content!)
$MCN = $1
}elsif($l =~ /^t(\d+)_isrc=(\w+)\s*$/){ # (just take the content!)
$TracksISRC[$1 - 1] = $2
}
# We ignore the ^x ones, we only look for audio "t"rack data
elsif($l =~ /^x=(\d+)\s+.*$/){
}elsif($l =~ /^x0_count=(\d+)\s+x0_track_first=(\d+)\s+x0_track_last=(\d+).*$/){
}elsif($l =~ /^#/){
push @CDText, $l
}else{
#$emsg .= "! Invalid line: $l\n"
}
}
$emsg .= "! No Lead-out information encountered\n" unless $had_leadout;
$emsg = _check_cddb_state($emsg);
return $emsg if length $emsg;
_calc_cdid(\@cdtoc);
_calc_mb_discid();
return undef
} # }}}
# Calculated CD(DB)-Id and *set*CDInfo*fields*, ditto MusicBrainz Disc ID
sub _calc_cdid{ # {{{
# This is a stripped down version of CDDB.pm::calculate_id()
my $cdtocr = shift;
my ($sec_first, $sum, $totalsecs);
foreach(@$cdtocr){
# MSF - minute, second, 1/75 second=frame (RedBook standard)
# CDDB/FreeDB calculation actually uses "wrong" numbers in that it
# adds the 2 seconds offset (see SCSI MMC-3 standard, Table 333 - LBA
# to MSF translation)
my ($no, $min, $sec, $frame) = split /\s+/, $_, 4;
my $frame_off = (($min * 60 + $sec) * 75) + $frame;
my $sec_begin = int($frame_off / 75);
$sec_first = $sec_begin unless defined $sec_first;
if($no == $Leadout){
$totalsecs = $sec_begin;
last
}
map {$sum += $_} split //, $sec_begin;
}
$CDId = sprintf("%02x%04x%02x", $sum % 255, $totalsecs - $sec_first, $TrackCount)
}
sub _calc_mb_discid{
my $d = Digest->new("SHA-1");
$d->add(sprintf '%02X', $TrackFirst);
$d->add(sprintf '%02X', $TrackLast);
my $i = @TracksLBA;
$d->add(sprintf '%08X', $TracksLBA[--$i] + 150);
for(my $j = 0; $j < $i; ++$j){
$d->add(sprintf '%08X', $TracksLBA[$j] + 150)
}
for(++$i; $i < 100; ++$i){
$d->add('00000000')
}
$d = $d->b64digest();
$d =~ tr[/+=][_.-];
$MBrainzDiscId = $d . '-'
} # }}}
# write_data, read_data ($DatFile handling) {{{
sub write_data{
my $f = $DatFile;
::v("CDInfo::write_data($f)");
die "Cannot open $f: $!" unless open DAT, '>:encoding(UTF-8)', $f;
die "Error writing $f: $!"
unless print DAT "# $SELF CDDB info for project $CDId\n",
"# Do not modify! Or project needs to be re-created!!\n",
"CDID = $CDId\n",
"MBRAINZ_DISC_ID = $MBrainzDiscId\n",
'TRACKS_LBA = ', join(' ', @TracksLBA), "\n",
"TRACK_FIRST = $TrackFirst\n",
"TRACK_LAST = $TrackLast\n",
"RAW_IS_WAVE = 1\n";
if(@CDText > 0){
die "Error writing $f: $!" unless print DAT "# CDTEXT-START\n", join("\n", @CDText)
}
die "Cannot close $f: $!" unless close DAT
}
sub read_data{
my $f = $DatFile;
::v("CDInfo::read_data($f)");
die "Cannot open $f: $!.\nI cannot continue - remove $WORK_DIR and re-create!"
unless open DAT, '<:encoding(UTF-8)', $f;
my @lines = <DAT>;
die "Cannot close $f: $!" unless close DAT;
# May be called even though discover() already queried the disc in the drive - nevertheless: resume!
my ($old_id, $laref) = ($CDId, shift);
$RawIsWAVE = $ReadFileExt = $CDId = $MBrainzDiscId = $TrackCount = $TrackFirst = $TrackLast = undef;
@TracksLBA = @TracksISRC = @CDText = ();
my ($emsg, $cdtext) = ('', 0);
foreach(@lines){
chomp;
if(/^\s*#/){
if(!$cdtext){
$cdtext = 1 if /CDTEXT-START/
}else{
push @CDText, $_
}
next
}
next if /^\s*$/;
unless(/^\s*(.+?)\s*=\s*(.+?)\s*$/){
$emsg .= "! Invalid line $_\n";
next
}
my ($k, $v) = ($1, $2);
if($k eq 'CDID'){
if(defined $old_id && $v ne $old_id){
$emsg .= "! Parsed CDID ($v) does not match\n";
next
}
$emsg .= "! Invalid CDID: $v\n" unless $v =~ /^([[:xdigit:]]+)$/;
$CDId = $v
}elsif($k eq 'MBRAINZ_DISC_ID'){
$emsg .= "! Invalid MBRAINZ_DISC_ID: $v\n" unless $v =~ /^([[:alnum:]_.-]+)$/;
$MBrainzDiscId = $v
}elsif($k eq 'TRACKS_LBA'){
my @x = split(/\s+/, $v);
@TracksLBA = map {return () unless /^(\d+)$/; $_} @x;
$emsg .= "! Invalid TRACKS_LBA entries: $v\n" if @x != @TracksLBA;
$TrackCount = @TracksLBA - 1
}elsif($k eq 'TRACK_FIRST'){
$emsg .= "! Invalid TRACK_FIRST: $v\n" unless $v =~ /^(\d+)$/;
$TrackFirst = $1
}elsif($k eq 'TRACK_LAST'){
$emsg .= "! Invalid TRACK_LAST: $v\n" unless $v =~ /^(\d+)$/;
$TrackLast = $1
}elsif($k eq 'RAW_IS_WAVE'){
$emsg .= "! Invalid RAW_IS_WAVE: $v\n" unless $v =~ /^(\d)$/;
$ReadFileExt = ($RawIsWAVE = $1) ? 'wav' : 'raw'
}else{
$emsg .= "! Invalid line: $_\n"
}
}
$emsg .= "! Corrupted: no CDID seen\n" unless defined $CDId;
$emsg .= "! Corrupted: no MBRAINZ_DISC_ID seen\n" unless defined $MBrainzDiscId;
$emsg = _check_cddb_state($emsg);
die "CDInfo: $emsg" if length $emsg;
print " CD(DB) ID: $CDId | MusicBrainz Disc ID: ", $MBrainzDiscId, "\n",
' Track L(ogical)B(lock)A(ddressing)s: ' . join(' ', @TracksLBA),
"\n Track: count $TrackCount, first $TrackFirst, last $TrackLast\n"
}
sub _check_cddb_state{
my ($emsg) = @_;
$emsg .= "! Corrupted: no TRACK_COUNT seen\n" unless defined $TrackCount;
$emsg .= "! Corrupted: no TRACK_FIRST seen\n" unless defined $TrackFirst;
$emsg .= "! Corrupted: no TRACK_LAST seen\n" unless defined $TrackLast;
$emsg .= "! Corrupted: no TRACKS_LBA seen\n" unless $TrackCount > 0;
$emsg .= "! Corrupted: no RAW_IS_WAVE seen\n" unless defined $RawIsWAVE;
if(@Title::List > 0){
$emsg .= "! Corrupted: TRACKS_LBA invalid\n" if $TrackCount != @Title::List
}
return $emsg
}
# }}}
{package CDInfo::InfoSource; # {{{
sub query_all{
CDInfo::InfoSource::Dummy::new()->create_db();
if(@CDInfo::CDText > 0){
CDInfo::InfoSource::CDText::new()->create_db()
}
if(defined $CDInfo::MBrainzDiscId){
CDInfo::InfoSource::MusicBrainz::new()->create_db()
}
}
# Super funs # {{{
sub new{
my ($name) = @_;
my $self = scalar caller;
$self = {name => $name};
bless $self
}
# }}}
{package CDInfo::InfoSource::Dummy; # {{{
our @ISA = 'CDInfo::InfoSource';
sub new{
my $self = CDInfo::InfoSource::new('Dummy');
$self = bless $self;
#$self
}
sub create_db{
my $self = $_[0];
my @data = split "\n", <<__EOT;
[CDDB]
CDID = $CDInfo::CDId
MBRAINZ_DISC_ID = $CDInfo::MBrainzDiscId
TRACKS_LBA = @CDInfo::TracksLBA
TRACK_FIRST = $CDInfo::TrackFirst
TRACK_LAST = $CDInfo::TrackLast
[ALBUM]
TITLE = UNTITLED
TRACK_COUNT = $CDInfo::TrackCount
GENRE = Humour
[CAST]
ARTIST = UNKNOWN
__EOT
foreach my $t (@Title::List){
push @data, $_ foreach(split "\n", <<__EOT);
[TRACK]
NUMBER = $t->{NUMBER}
TITLE = UNTITLED
__EOT
}
MBDB::db_slurp('Dummy', \@data)
}
} # }}} CDInfo::InfoSource::Dummy
{package CDInfo::InfoSource::CDText; # {{{
our @ISA = 'CDInfo::InfoSource';
sub new{
my $self = CDInfo::InfoSource::new('CDText');
$self = bless $self;
#$self
}
sub create_db{
my $self = $_[0];
my @data;
foreach(@CDInfo::CDText){
push @data, substr($_, 1)
}
MBDB::db_slurp('CDText', \@data)
}
} # }}} CDInfo::InfoSource::CDText
{package CDInfo::InfoSource::MusicBrainz; # {{{
our @ISA = 'CDInfo::InfoSource';
sub new{
my $self = CDInfo::InfoSource::new('MusicBrainz');
$self = bless $self;
#$self
}
sub create_db{ # {{{
my $self = $_[0];
return if $MBRAINZ_QUERY == 0;
if($MBRAINZ_QUERY == 2){
print "\nShall i contact the MusicBrainz Web-Service in order to\n",
' collect more data of the audio CD';
return unless ::user_confirm()
}
eval {require HTTP::Tiny; require XML::Parser};
if($@){
print "! Failed loading HTTP::Tiny and/or XML::Parser perl module(s).\n",
"! We could use the MusicBrainz CD information Web-Service.\n",
"! Are they installed? (Maybe install them via CPAN?)\n",
'! Confirm to again try to use them, otherwise we skip this';
return unless ::user_confirm();
$MBRAINZ_QUERY = 1;
return $self->create_db()
}
if($MBRAINZ_TLS && HTTP::Tiny::can_ssl()){
$self->{_use_ssl} = 1;
$self->{_protocol} = 'https'
}else{
$self->{_use_ssl} = 0;
$self->{_protocol} = 'http'
}
$self->{_headers} = {
'Accept' => 'application/xml',
'Content-Type' => 'application/xml'
};