Repository navigation
Expand file tree
/
Copy pathAPEv2
More file actions
executable file
·1648 lines (1470 loc) · 50.2 KB
/
Copy pathAPEv2
File metadata and controls
executable file
·1648 lines (1470 loc) · 50.2 KB
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
#!/bin/bash
# Copyright © 2013 - 2014 Guillaume Cocatre-Zilgien <gcocatre@gmail.com>
# http://caudec.net/
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
#
# This program is provided without warranty of any kind, either expressed,
# implied, or statutory. The entire risk as to the quality and performance
# of this program is with You. Under no circumstances and under no legal
# theory shall any Contributor, or anyone who distributes this program,
# be liable to You for any damages of any character.
#
# Full APEv2 specification:
# http://wiki.hydrogenaudio.org/index.php?title=APEv2_specification
printUsage ()
{
echo "${me} ${VERSION}: APEv2 tagger
Copyright © 2013 - 2014 Guillaume Cocatre-Zilgien
http://caudec.net/
Usage: $me [ PARAMETERS ] FILE(S)
List, set or remove tags in APEv2 files (.ape, .wv, .mpc, .tak…).
Default action: list tags, with colored field names.
Tagging Parameters:
--------------------------------------------------------------------------------
-i read and set tags from STDIN
-f FILE copy APEv2 tags from FILE (must contain a valid APEv2 tag)
-t F=V set tag item with field name F and value V
-r F remove tag item with field name F
-R remove all APEv2 data
-a F=P set artwork tag item with field name F, with the contents of file P;
F must start with 'Cover Art', and P must be a valid path to the
file (normally, either .jpg, .png or .gif).
-b F=P set binary tag item with field name F, with the contents of file P;
P must be a valid path to the file
-d F=P dump value of tag item with field name F into file P; P may be a
filename, or '-' to dump to STDOUT. This parameter may be used with
any type of field (artwork, binary or text), and can only be used
on its own. When dumping artwork, ${me} will automatically append
the correct file extension, if the provided filename (P) ends with
a dot ('.').
Output Formatting Parameters:
--------------------------------------------------------------------------------
-C disable coloring
-D print debugging information to STDERR
-z machine-parsable output: replace new line chars with '\\n',
NULL chars with '\\x00', prefix read-only tag items with 'ro:', and
print artwork and binary data as Base64 (preceded by 'artwork:' and
'data:', respectively). Implies -C.
-Z raw mode: output new line chars, NULL chars and binary data as is.
Implies -C. Warning: this might mess up your terminal, unless you
redirect the output to a program that can handle it, or to a file.
Notes about output modes:
--------------------------------------------------------------------------------
By default, $me prints tags in a colored, human readable format, with new line
characters printed as is, NULL characters replaced with ' / ', artwork
designated as 'artwork: <SIZE>' (byte size of the artwork) and binary data
designated as 'data: <SIZE>' (byte size of the data).
To disable coloring, use -C. To change the color of field names,
export APEV2FCC='xyy', where 'x' is either '1' (bold) or '0', and 'yy' is
a number between 30 and 37 (see: man 4 console_codes). To change the color of
values, export APEV2VCC='xyy' (default: '000', i.e. no coloring of values).
If both environment variables are set to '000', coloring is disabled (like
using -C). Note that coloring is always disabled when using -z or -Z.
Notes about setting and removing tag items:
--------------------------------------------------------------------------------
To specify new lines with -t or -i, write them as '\\n' (though actual new lines
are accepted as well); to specify NULL chars (for NULL separated lists of
values), write them as '\\x00'. The -z parameter uses those notations.
When feeding tags via STDIN (-i), you must specify one FIELD=VALUE pair on each
line. Write new lines and NULL chars as '\\n' and '\\x00', respectively.
To read FIELD=VALUE pairs from a text file, simply run:
\$ ${me} -i file.ape < metadata.txt
In order to mark a tag item read-only with -t, -i, -a or -b, precede the field
name with 'ro:', e.g.: -t \"ro:Artist=Daft Punk\". Read-only items cannot be
updated, but they may be explicitely removed with the -r parameter.
Note that in the APEv2 specification, all field names are unique; using -i, -t,
-a or -b will either create new tag items, or replace existing ones. You may
also use the -r and -R parameters with -i, -t, -a and -b.
Miscellaneous:
--------------------------------------------------------------------------------
The full APEv2 specification can be found on the Hydrogenaudio Wiki:
http://wiki.hydrogenaudio.org/index.php?title=APEv2_specification"
}
cleanExit ()
{
if [ -n "$nProcesses" ]; then
if [ $nProcesses -gt 1 ]; then
kill $( jobs -p ) >/dev/null 2>&1
fi
fi
if [ -n "$tempDir" -a -e "$tempDir" ]; then
rm -rf "$tempDir" >/dev/null 2>&1
fi
exit $1
}
cleanAbort ()
{
if [ -n "$nProcesses" ]; then
if [ $nProcesses -gt 1 ]; then
kill $( jobs -p ) >/dev/null 2>&1
fi
unset nProcesses
fi
echo
cleanExit $EX_INTERRUPT
}
debugMsg ()
{
if [ $debug = true ]; then
echo -e "${WG}DEBUG:${NM} $1" 1>&2
fi
}
printWarning ()
{
if [ "$outputMode" = 'colors' ]; then
echo -e "${WG}Warning:${NM} $1" 1>&2
else
echo -E "Warning: $1" 1>&2
fi
}
printError ()
{
if [ "$outputMode" = 'colors' ]; then
echo -e "${KO}Error:${NM} $1" 1>&2
else
echo -E "Error: $1" 1>&2
fi
}
setColors ()
{
local boldCode='' colorCode=''
if [ "$outputMode" = 'colors' ]; then # default mode
if [ "$APEV2FCC" = '000' -a "$APEV2VCC" = '000' ]; then
outputMode='human' # disable all coloring
else
NM="\\033[0m" # reset
OK="\\033[1;32m" # success: bright green
KO="\\033[1;31m" # failure: bright red
WG="\\033[1;33m" # warning: bright orange
FC="\\033[1;34m" # field names: bright blue
VC="$NM" # item values: no coloring
# custom field name color
if [ "$APEV2FCC" = '000' ]; then
FC="$NM" # disable coloring of field names
elif [ "${#APEV2FCC}" -eq 3 ]; then
if [ "${APEV2FCC:0:1}" = '0' ]; then
boldCode='0'
else
boldCode='1'
fi
case "${APEV2FCC:1:2}" in
3[0-7]) colorCode="${APEV2FCC:1:2}" ;;
*) colorCode='34'
esac
FC="\\033[${boldCode};${colorCode}m"
fi
# custom item value color
if [ "$APEV2VCC" = '000' ]; then
VC="$NM" # disable coloring of item values
elif [ "${#APEV2VCC}" -eq 3 ]; then
if [ "${APEV2VCC:0:1}" = '0' ]; then
boldCode='0'
else
boldCode='1'
fi
colorCode="${APEV2VCC:1:2}"
case "$colorCode" in
3[0-7]) VC="\\033[${boldCode};${colorCode}m" ;;
esac
fi
fi
else # outputMode != 'colors'
# disable all colors
NM='' OK='' KO='' WG='' FC='' VC=''
fi
}
createTempDir ()
{
if [ -n "$tempDir" -a -d "$tempDir" -a -w "$tempDir" ]; then
return $EX_OK
fi
tempDir=''
if [ -n "$TMPDIR" -a -d "$TMPDIR" -a -w "$TMPDIR" ]; then
tempDir="$( TMPDIR="$TMPDIR" mktemp -d "${TMPDIR}/${me}.XXXXXXXX" )"
elif [ -d '/tmp' -a -w '/tmp' ]; then
tempDir="$( TMPDIR='/tmp' mktemp -d "/tmp/${me}.XXXXXXXX" )"
elif [ -d '/dev/shm' -a -w '/dev/shm' ]; then
tempDir="$( TMPDIR='/dev/shm' mktemp -d "/dev/shm/${me}.XXXXXXXX" )"
elif [ -d "$PWD" -a -w "$PWD" ]; then
tempDir="$( TMPDIR="$PWD" mktemp -d "${PWD}/${me}.XXXXXXXX" )"
fi
if [ -z "$tempDir" -o ! -d "$tempDir" -o ! -w "$tempDir" ]; then
printError "can't create temporary directory."
if [ -n "$tempDir" -a -d "$tempDir" ]; then
rm -rf "$tempDir" >/dev/null 2>&1
fi
cleanExit $EX_IOERR
else
mkdir -p "${tempDir}/common" >/dev/null 2>&1
return $EX_OK
fi
}
createTempProcessDir ()
{
tempProcessDir="${tempDir}/process.${pn}"
if [ -e "$tempProcessDir" ]; then
rm -rf "$tempProcessDir" >/dev/null 2>&1
fi
mkdir -p "$tempProcessDir"
}
checkBinary ()
{
local p rc=$EX_OK
for b in "$@"; do
p="x${b}Y"
if [ "$searchedBinaries" = "${searchedBinaries//$p/@}" ]; then # search for binary hasn't been done before
searchedBinaries="${searchedBinaries}${p}"
if which "$b" >/dev/null 2>&1 ; then
foundBinaries="${foundBinaries}${p}"
continue
else
rc=$EX_KO binaryMissing=true
printWarning "binary \"${b}\" not found. Make sure it is in your \$PATH."
fi
elif [ -z "$foundBinaries" -o "$foundBinaries" = "${foundBinaries//$p/@}" ]; then # binary was previously searched, but not found
rc=$EX_KO
fi
done
return $rc
}
checkBinaries ()
{
searchedBinaries=''
binaryMissing=false
if ! which 'which' >/dev/null 2>&1 ; then
printWarning "binary \"which\" not found. Make sure it is in your \$PATH."
cleanExit $EX_OSFILE
fi
checkBinary "$sedcmd" 'od' 'tr' 'cut' 'dd' 'mktemp' 'dirname' 'wc' 'sort' 'head' 'tail' 'base64' 'stat' 'kill'
if [ $binaryMissing = true ]; then
cleanExit $EX_OSFILE
else
return $EX_OK
fi
}
startTimer ()
{
if [ $gnudate = true ]; then
timer1="$( $datecmd '+%s.%N' )"
else
timer1="$( date '+%s' ).0"
fi
}
stopTimer ()
{
local seconds timer2
if [ $gnudate = true ]; then
timer2="$( $datecmd '+%s.%N' )"
else
timer2="$( date '+%s' ).0"
fi
seconds="$( printf 'scale=6; %.6f - %.6f\n' "$timer2" "$timer1" | bc 2>/dev/null )"
printf "${WG}%s:${NM} %.3f seconds\n" "$1" $seconds 1>&2
}
readBinaryDecimalInteger ()
{
local start="$1" length="$2" i=0
i="$( od -A n -j $start -N $length -i "$file" 2>/dev/null | tr -cd '0-9' )"
case "$i" in
[0-9]*) echo "$i" ;;
*) echo '-1' ;;
esac
}
getHumanByteSize ()
{
local bytes="$1"
if [ $bytes -lt 1024 ]; then
echo -n "$bytes B"
elif [ $bytes -lt 1048576 ]; then
printf "%.1f %s" "$( echo "scale=3; $bytes / 1024" | bc )" 'KiB'
elif [ $bytes -lt 1073741824 ]; then
printf "%.1f %s" "$( echo "scale=3; $bytes / 1048576" | bc )" 'MiB'
else # Houston, we have a problem.
printf "%.1f %s" "$( echo "scale=3; $bytes / 1073741824" | bc )" 'GiB'
fi
}
integerToBinaryData ()
{
local h=''
h="$( printf "%08X" "$1" )"
echo -en "\x${h:6:2}\x${h:4:2}\x${h:2:2}\x${h:0:2}"
}
getFileSize ()
{
local file="$1" bytes
if [ ! -e "$file" ]; then
printError "file \"${file}\" doesn't exist."
echo 0
else
if [ "$OS" = 'Linux' ]; then
bytes="$( stat -L -c %s "$file" 2>/dev/null | tr -cd '0-9' )"
else
bytes="$( stat -L -f %z "$file" 2>/dev/null | tr -cd '0-9' )"
fi
case "$bytes" in
[0-9]*) echo $bytes ;;
*) echo 0 ;;
esac
fi
}
getFilePortion ()
{
local offset=$1 size=$2 tailSize=0
if [ "$apetagLocation" = 'bottom' ]; then
tailSize=$(( fileSize - offset ))
tail -c $tailSize "$file" 2>/dev/null | head -c $size 2>/dev/null
else
head -c $(( offset + size )) "$file" 2>/dev/null | tail -c $size 2>/dev/null
fi
}
hasApetag ()
{
local preamble=''
if [ "$apetagPresent" = 'true' ]; then
return $EX_OK
elif [ "$apetagPresent" = 'false' ]; then
return $EX_KO
else
if [ $fileSize -le 64 ]; then
debugMsg 'no apetag present'
return $EX_KO
fi
# check the end of the file first
preamble="$( dd if="$file" bs=1 skip=$(( fileSize - 32 )) count=8 2>/dev/null | LC_ALL=C tr -cd 'A-Z' )"
if [ "$preamble" = 'APETAGEX' ]; then
apetagVersion="$( readBinaryDecimalInteger $(( fileSize - 32 + 8 )) 4 )"
apetagPresent='true' apetagLocation='bottom' hasFooter=true footerOffset=$(( fileSize - 32 ))
debugMsg "apetag present: location=${apetagLocation}, version=${apetagVersion}, footerOffset=${footerOffset}"
else
# check the beginning of the file
preamble="$( dd if="$file" bs=8 count=1 2>/dev/null | LC_ALL=C tr -cd 'A-Z' )"
if [ "$preamble" = 'APETAGEX' ]; then
apetagVersion="$( readBinaryDecimalInteger 8 4 )"
apetagPresent='true' apetagLocation='top' hasHeader=true headerOffset=0
debugMsg "apetag present: location=${apetagLocation}, version=${apetagVersion}, headerOffset=${headerOffset}"
fi
fi
if [ "$preamble" = 'APETAGEX' ]; then
if [ "$apetagVersion" = '2000' ]; then
apetagPresent='true'
return $EX_OK
elif [ "$apetagVersion" = '-1' ]; then
printError "file \"$file\" is corrupted: invalid APE version number."
return $EX_DATAERR
else
printWarning "unsupported APE version (${apetagVersion})"
apetagPresent='false'
return $EX_KO
fi
else
apetagPresent='false'
debugMsg 'no apetag present'
return $EX_KO
fi
fi
}
getApetagSize ()
{
# tag size does NOT include the header, if present
if [ "$apetagLocation" = 'bottom' ]; then
tagSize="$( readBinaryDecimalInteger $(( footerOffset + 8 + 4 )) 4 )"
if [ "$tagSize" = '-1' ]; then
printError "file \"$file\" is corrupted: invalid tag size."
return $EX_DATAERR
elif [ $tagSize -lt 32 ]; then # smaller than the footer alone
printError "file \"$file\" is corrupted: tag size smaller than 32 bytes."
return $EX_DATAERR
fi
else
tagSize="$( readBinaryDecimalInteger $(( headerOffset + 8 + 4 )) 4 )"
if [ $tagSize -lt 0 ]; then # invalid value (minimum: 0, no tag items, no footer)
printError "file \"$file\" is corrupted: invalid tag size."
return $EX_DATAERR
fi
fi
debugMsg "tagSize=${tagSize}"
}
getApetagOffset ()
{
local preamble=''
if [ "$apetagLocation" = 'bottom' ]; then
apetagOffset=$(( fileSize - tagSize ))
preamble="$( dd if="$file" bs=1 skip=$(( apetagOffset - 32 )) count=8 2>/dev/null | LC_ALL=C tr -cd 'A-Z' )"
if [ "$preamble" = 'APETAGEX' ]; then
hasHeader=true
apetagOffset=$(( apetagOffset - 32 ))
headerOffset=$apetagOffset
debugMsg "hasHeader=${hasHeader}, hasFooter=${hasFooter}, apetagOffset=${apetagOffset}, headerOffset=${headerOffset}"
else
debugMsg "hasHeader=${hasHeader}, hasFooter=${hasFooter}, apetagOffset=${apetagOffset}"
fi
else
apetagOffset=0
preamble="$( dd if="$file" bs=1 skip=$(( apetagOffset + 32 + tagSize - 32 )) count=8 2>/dev/null | LC_ALL=C tr -cd 'A-Z' )"
if [ "$preamble" = 'APETAGEX' ]; then
hasFooter=true
footerOffset=$(( apetagOffset + 32 + tagSize - 32 ))
debugMsg "hasHeader=${hasHeader}, hasFooter=${hasFooter}, apetagOffset=${apetagOffset}, footerOffset=${footerOffset}"
else
debugMsg "hasHeader=${hasHeader}, hasFooter=${hasFooter}, apetagOffset=${apetagOffset}"
fi
fi
}
resetApetagProperties ()
{
apetagPresent='false'
fileSize=$apetagOffset
tagSize=0
apetagOffset=0
headerOffset=0
footerOffset=0
itemsOffset=0
apetagLocation='none'
hasHeader=false
hasFooter=false
}
initFileVars ()
{
debugMsg '--------------------------------------------------------------------------------'
debugMsg "file: \"${file}\""
fileSize="$( getFileSize "$file" )"
debugMsg "fileSize=${fileSize}"
apetagPresent=''
tagSize=0
apetagOffset=0
headerOffset=0
footerOffset=0
itemsOffset=0
itemsCount=0
allKeys=''
readOnlyKeys=''
apetagLocation='none'
hasHeader=false
hasFooter=false
sortedItemSizes=''
unset itemKeys itemLowercaseKeys itemValues
declare -a itemKeys=()
declare -a itemLowercaseKeys=()
declare -a itemValues=()
}
removeApetag ()
{
local ec=$EX_OK tempFile=''
if [ "$apetagLocation" = 'bottom' ]; then
if which 'truncate' >/dev/null 2>&1 ; then
truncate -s $apetagOffset "$file" 2>/dev/null ; ec=$?
elif which 'gtruncate' >/dev/null 2>&1 ; then
gtruncate -s $apetagOffset "$file" 2>/dev/null ; ec=$?
else
tempFile="${tempProcessDir}/tempfile"
head -c $apetagOffset "$file" 2>/dev/null | dd of="$tempFile" bs=$(( 8192 * 1024 )) >/dev/null 2>&1 ; ec=$?
if [ $ec -eq $EX_OK ]; then
rm -f "$file" >/dev/null 2>&1 &&
mv -f "$tempFile" "$file" >/dev/null 2>&1 ; ec=$?
fi
if [ -e "$tempFile" ]; then rm -f "$tempFile"; fi
fi
resetApetagProperties
return $ec
else # apetagLocation = 'top'
tempFile="${tempProcessDir}/tempfile"
tail -c $(( fileSize - (32 + tagSize) )) "$file" 2>/dev/null | dd of="$tempFile" bs=$(( 8192 * 1024 )) >/dev/null 2>&1 ; ec=$?
resetApetagProperties
if [ $ec -eq $EX_OK ]; then
rm -f "$file" >/dev/null 2>&1 &&
mv -f "$tempFile" "$file" >/dev/null 2>&1 ; ec=$?
fi
if [ -e "$tempFile" ]; then rm -f "$tempFile"; fi
return $ec
fi
}
writeNewApetag ()
{
local itemKey itemValue itemValueSize itemSize itemValueTypes=() fileDir='' tempDirLength p artworkFilenameSize=0 artworkFilepath artworkFilename binaryFilepath
sortedItemSizes=''
fileDir="$( dirname "$file" )"
if [ "$fileDir" != '/' ]; then fileDir="${fileDir}/"; fi
tagSize=32
for ((i=0; i<itemsCount; i++)); do
itemKey="${itemKeys[$i]}"
itemValue="${itemValues[$i]}"
if [ "${itemValue:0:15}" = 'binaryfilepath:' ]; then
itemValueTypes[$i]='binary'
binaryFilepath="${itemValue##*:}"
itemSize="$( getFileSize "$binaryFilepath" )"
itemSize=$(( 4 + 4 + ${#itemKey} + 1 + itemSize ))
sortedItemSizes="${sortedItemSizes}$( echo -en "\n${itemSize} ${i}" )"
elif [ "${itemValue:0:16}" = 'artworkfilepath:' ]; then
itemValueTypes[$i]='artwork'
artworkFilepath="${itemValue##*:}"
artworkFilename="${itemValue:16}"; artworkFilename="${artworkFilename%:*}"
itemSize="$( getFileSize "$artworkFilepath" )"
artworkFilenameSize="$( echo -En "$artworkFilename" | wc -c | tr -cd '0-9' )"
itemSize=$(( 4 + 4 + ${#itemKey} + 1 + artworkFilenameSize + 1 + itemSize ))
sortedItemSizes="${sortedItemSizes}$( echo -en "\n${itemSize} ${i}" )"
else
itemValue="${itemValues[$i]}"
# adding 'x...x' when testing $itemValue because a value of '(' would make the tests crap out with a BASH error: line 581: [: `)' expected, found (
if [ "x${itemValue:0:7}x" = 'xhttp://x' -o "x${itemValue:0:6}x" = 'xftp://x' -o "x${itemValue:1:2}x" = 'x:/x' ]; then
itemValueTypes[$i]='locator'
elif [ "x${itemValue%.*}x" != "x${itemValue}x" -a -n "${itemValue##*.}" -a "x${itemValue:0:1}x" != 'x/x' -a -f "${fileDir}${itemValue}" ]; then
itemValueTypes[$i]='locator'
elif [ "x${itemValue%.*}x" != "x${itemValue}x" -a -n "${itemValue##*.}" -a "x${itemValue:0:1}x" = 'x/x' -a -f "${itemValue}" ]; then
itemValueTypes[$i]='locator'
else
itemValueTypes[$i]='text'
fi
itemSize="$( echo -En "$itemValue" | wc -c | tr -cd '0-9' )"
itemSize=$(( 4 + 4 + ${#itemKey} + 1 + $itemSize ))
sortedItemSizes="${sortedItemSizes}$( echo -en "\n${itemSize} ${i}" )"
fi
tagSize=$(( tagSize + itemSize ))
done
sortedItemSizes="$( echo "${sortedItemSizes:1}" | sort -n )"
{
# Header
echo -n 'APETAGEX' # preamble
echo -en "\xD0\x07\x00\x00" # version 2.0
integerToBinaryData $tagSize
integerToBinaryData $itemsCount
echo -en "\x00\x00\x00\xA0" # this is the header
echo -en "\x00\x00\x00\x00\x00\x00\x00\x00" # reserved
# Items
while read itemSize i; do
itemKey="${itemKeys[$i]}"
itemValue="${itemValues[$i]}"
if [ "${itemValueTypes[$i]}" = 'binary' ]; then
binaryFilepath="${itemValue##*:}"
integerToBinaryData "$( getFileSize "$binaryFilepath" )" # item value size
elif [ "${itemValueTypes[$i]}" = 'artwork' ]; then
artworkFilepath="${itemValue##*:}"
artworkFilename="${itemValue:16}"; artworkFilename="${artworkFilename%:*}"
artworkFilenameSize="$( echo -En "$artworkFilename" | wc -c | tr -cd '0-9' )"
itemValueSize="$( getFileSize "$artworkFilepath" )" # item value size
itemValueSize=$(( artworkFilenameSize + 1 + itemValueSize ))
integerToBinaryData "$itemValueSize" # item value size
else
itemSize="$( echo -En "$itemValue" | wc -c | tr -cd '0-9' )"
integerToBinaryData $itemSize # item value size
fi
p="x$( echo -En "$itemKey" | tr '[:upper:]' '[:lower:]' )Y"
if [ "$readOnlyKeys" = "${readOnlyKeys//$p/@}" -a "$newReadOnlyKeys" = "${newReadOnlyKeys//$p/@}" ]; then
case "${itemValueTypes[$i]}" in
text) echo -en "\x00\x00\x00\x00" ;;
binary|artwork) echo -en "\x02\x00\x00\x00" ;;
locator) echo -en "\x04\x00\x00\x00" ;;
esac
else
case "${itemValueTypes[$i]}" in
text) echo -en "\x01\x00\x00\x00" ;;
binary|artwork) echo -en "\x03\x00\x00\x00" ;;
locator) echo -en "\x05\x00\x00\x00" ;;
esac
fi
echo -En "$itemKey"
echo -en "\x00"
if [ "${itemValueTypes[$i]}" = 'binary' ]; then
cat "$binaryFilepath" 2>/dev/null
elif [ "${itemValueTypes[$i]}" = 'artwork' ]; then
echo -En "$artworkFilename"
echo -en "\x00"
cat "$artworkFilepath" 2>/dev/null
else
echo -En "$itemValue" | LC_ALL=C tr '\1' '\0' 2>/dev/null
fi
done < <( echo "$sortedItemSizes" )
# Footer
echo -n 'APETAGEX' # preamble
echo -en "\xD0\x07\x00\x00" # version 2.0
integerToBinaryData $tagSize
integerToBinaryData $itemsCount
echo -en "\x00\x00\x00\x80" # this is the footer
echo -en "\x00\x00\x00\x00\x00\x00\x00\x00" # reserved
} >> "$file"
return $EX_OK
}
getItemsOffset ()
{
if [ "$apetagLocation" = 'bottom' ]; then
if [ $hasHeader = true ]; then
itemsOffset=$(( apetagOffset + 32 ))
else
itemsOffset=$apetagOffset
fi
else
itemsOffset=$(( apetagOffset + 32 ))
fi
debugMsg "itemsOffset=${itemsOffset}"
}
getNumberOfItems ()
{
if [ "$apetagLocation" = 'bottom' ]; then
itemsCount="$( readBinaryDecimalInteger $(( footerOffset + 8 + 4 + 4 )) 4 )"
else
itemsCount="$( readBinaryDecimalInteger $(( headerOffset + 8 + 4 + 4 )) 4 )"
fi
if [ $itemsCount -lt 0 ]; then
printError "file \"$file\" is corrupted: invalid number of items."
return $EX_DATAERR
fi
debugMsg "itemsCount=${itemsCount}"
}
getItem ()
{
local itemValueSize=0 itemKeyOffset=0 char='' o=0 itemValueType='' itemSize itemIsBinary=false itemIsReadOnly=false p='' itemFilename='' itemDataSize=0
itemKey='' itemLowercaseKey='' itemValue=''
itemValueSize="$( readBinaryDecimalInteger $itemOffset 4 )"
if [ $itemValueSize -lt 1 ]; then
printError "file \"$file\" is corrupted: invalid length of item value."
return $EX_DATAERR
fi
itemValueType="$( readBinaryDecimalInteger $(( itemOffset + 4 )) 4)"
if [ $itemValueType -lt 0 -o $itemValueType -gt 5 ]; then
printError "file \"$file\" is corrupted: invalid item flags ($itemValueType)."
return $EX_DATAERR
fi
itemKeyOffset=$(( itemOffset + 4 + 4 ))
o=$itemKeyOffset
# here tr and cut fail on OS X if LC_ALL is not set to C
itemKey="$( dd if="$file" bs=1 skip=$o count=255 2>/dev/null | LC_ALL=C tr '\0\n' '\1\2' 2>/dev/null | LC_ALL=C cut -d "$( echo -en "\x01" )" -f 1 2>/dev/null )"
if [ ${#itemKey} -lt 2 ]; then
printError "file \"$file\" is invalid: length of field name (${#itemKey}) should range from 2 to 255 characters."
return $EX_DATAERR
elif [ ${#itemKey} -eq 255 ]; then
char="$( readBinaryDecimalInteger $(( o + 255 )) 1 )"
if [ $char -ne 0 ]; then # the mandatory null char that separates the key from the value isn't there
printError "file \"$file\" is corrupted: NULL char missing between field name and item value."
return $EX_DATAERR
fi
fi
itemLowercaseKey="$( echo -En "$itemKey" | tr '[:upper:]' '[:lower:]' )"
p="x${itemLowercaseKey}Y"
if [ "$allKeys" != "${allKeys//$p/@}" ]; then
printError "file \"$file\" is invalid: it contains two or more items with the same field name (they must be unique)."
return $EX_DATAERR
fi
o=$(( o + ${#itemKey} + 1 ))
case "$itemValueType" in
0|4) itemIsReadOnly=false itemIsBinary=false ;;
1|5) itemIsReadOnly=true itemIsBinary=false ;;
2) itemIsReadOnly=false itemIsBinary=true ;;
3) itemIsReadOnly=true itemIsBinary=true ;;
esac
if [ $itemIsReadOnly = true ]; then
readOnlyKeys="${readOnlyKeys}x${itemLowercaseKey}Y"
fi
if [ $itemIsBinary = true ]; then # binary data
if [ "${itemLowercaseKey:0:9}" = 'cover art' ]; then
itemFilename="$( dd if="$file" bs=1 skip=$o count=255 2>/dev/null | LC_ALL=C tr '\0\n' '\1\2' 2>/dev/null | LC_ALL=C cut -d "$( echo -en "\x01" )" -f 1 2>/dev/null )"
if [ ${#itemFilename} -lt 5 ]; then
printError "file \"$file\" is invalid: length of cover art filename (${#itemFilename}) should range from 5 to 255 characters."
return $EX_DATAERR
elif [ ${#itemFilename} -eq 255 ]; then
char="$( readBinaryDecimalInteger $(( o + 255 )) 1 )"
if [ $char -ne 0 ]; then # the mandatory null char that separates the filename from the data isn't there
printError "file \"$file\" is corrupted: NULL char missing between filename and artwork data."
return $EX_DATAERR
fi
fi
itemDataSize=$(( itemValueSize - ${#itemFilename} - 1 ))
if [ $itemDataSize -lt 4 -o $itemDataSize -gt 1073741824 ]; then
printError "file \"$file\" is corrupted: invalid size (${itemDataSize} B) of cover art."
return $EX_DATAERR
fi
getFilePortion $(( o + ${#itemFilename} + 1 )) $itemDataSize > "${tempProcessDir}/artwork.${i}"
itemValue="artworkfilepath:${itemFilename}:${tempProcessDir}/artwork.${i}"
else # binary data
if [ $itemValueSize -lt 1 -o $itemValueSize -gt 1073741824 ]; then
printError "file \"$file\" is corrupted: invalid size (${itemValueSize} B) of binary data."
return $EX_DATAERR
fi
getFilePortion $o $itemValueSize > "${tempProcessDir}/binary.${i}"
itemValue="binaryfilepath:${tempProcessDir}/binary.${i}"
fi
else
if [ $itemValueSize -lt 1 -o $itemValueSize -gt 1073741824 ]; then
printError "file \"$file\" is corrupted: invalid length (${itemValueSize}) of item value."
return $EX_DATAERR
fi
itemValue="$( dd if="$file" bs=1 skip=$o count=$itemValueSize 2>/dev/null | LC_ALL=C tr '\0' '\1' 2>/dev/null | LC_ALL=C tr -d '\r' 2>/dev/null )"
fi
itemSize=$(( o + itemValueSize - itemOffset ))
debugMsg "itemNumber=$i, itemOffset=${itemOffset}, itemSize=${itemSize}, readOnly=${itemIsReadOnly}, isBinary=${itemIsBinary}, itemKey=\"${itemKey}\", itemKeySize=${#itemKey}, itemValueSize=${itemValueSize}"
itemOffset=$(( o + itemValueSize ))
}
getItems ()
{
local ec=$EX_OK
itemOffset="$itemsOffset"
for ((i=0; i<itemsCount; i++)); do
getItem; ec=$?
if [ $ec -eq $EX_OK ]; then
itemKeys[$i]="$itemKey"
itemLowercaseKeys[$i]="$itemLowercaseKey"
itemValues[$i]="$itemValue"
allKeys="${allKeys}x${itemLowercaseKey}Y"
else
return $ec
fi
done
return $ec
}
removeItems ()
{
local tempItemCount=0 deleteKeys='' p='' itemValue=''
declare -a tempItemKeys=()
declare -a tempItemLowercaseKeys=()
declare -a tempItemValues=()
for ((i=0; i<deletedKeysCount; i++)); do
p="x${deletedLowercaseKeys[$i]}Y"
readOnlyKeys="${readOnlyKeys//$p/}"
deleteKeys="${deleteKeys}${p}"
done
for ((i=0; i<newTagsCount; i++)); do
p="x${newLowercaseKeys[$i]}Y"
if [ "$readOnlyKeys" = "${readOnlyKeys//$p/@}" ]; then
deleteKeys="${deleteKeys}${p}"
else
printWarning "item \"${newKeys[$i]}\" is marked read-only."
fi
done
for ((i=0; i<itemsCount; i++)); do
p="x${itemLowercaseKeys[$i]}Y"
if [ "$deleteKeys" = "${deleteKeys//$p/@}" ]; then
tempItemKeys[$tempItemCount]="${itemKeys[$i]}"
tempItemLowercaseKeys[$tempItemCount]="${itemLowercaseKeys[$i]}"
tempItemValues[$tempItemCount]="${itemValues[$i]}"
if [ -f "${tempProcessDir}/artwork.${i}" ]; then
mv "${tempProcessDir}/artwork.${i}" "${tempProcessDir}/tempArtwork.${tempItemCount}" >/dev/null 2>&1
elif [ -f "${tempProcessDir}/binary.${i}" ]; then
mv "${tempProcessDir}/binary.${i}" "${tempProcessDir}/tempBinary.${tempItemCount}" >/dev/null 2>&1
fi
((tempItemCount++))
elif [ -f "${tempProcessDir}/artwork.${i}" ]; then
rm -f "${tempProcessDir}/artwork.${i}" >/dev/null 2>&1
elif [ -f "${tempProcessDir}/binary.${i}" ]; then
rm -f "${tempProcessDir}/binary.${i}" >/dev/null 2>&1
fi
done
unset itemKeys itemLowercaseKeys itemValues
itemsCount=$tempItemCount
for ((i=0; i<tempItemCount; i++)); do
itemKeys[$i]="${tempItemKeys[$i]}"
itemLowercaseKeys[$i]="${tempItemLowercaseKeys[$i]}"
itemValues[$i]="${tempItemValues[$i]}"
if [ -f "${tempProcessDir}/tempArtwork.${i}" ]; then
mv "${tempProcessDir}/tempArtwork.${i}" "${tempProcessDir}/artwork.${i}" >/dev/null 2>&1
itemValue="${tempItemValues[$i]}"
itemValues[$i]="${itemValue%:*}:${tempProcessDir}/artwork.${i}"
elif [ -f "${tempProcessDir}/tempBinary.${i}" ]; then
mv "${tempProcessDir}/tempBinary.${i}" "${tempProcessDir}/binary.${i}" >/dev/null 2>&1
itemValue="${tempItemValues[$i]}"
itemValues[$i]="${itemValue%:*}:${tempProcessDir}/binary.${i}"
fi
done
unset tempItemKeys tempItemLowercaseKeys tempItemValues
}
addNewItems ()
{
local p=''
# itemsCount is either set by removeItems(), or equal to zero
for ((i=0; i<newTagsCount; i++)); do
p="x${newLowercaseKeys[$i]}Y"
if [ "$readOnlyKeys" = "${readOnlyKeys//$p/@}" ]; then
itemKeys[$itemsCount]="${newKeys[$i]}"
itemLowercaseKeys[$itemsCount]="${newLowercaseKeys[$i]}"
itemValues[$itemsCount]="${newValues[$i]}"
((itemsCount++))
fi
done
}
listItems ()
{
local itemKey='' itemLowercaseKey='' itemValue='' itemValueSize=0 roPrefix='' artworkFilename='' p='' ppn=0
if [ -z "$sortedItemSizes" ]; then
for ((i=0; i<itemsCount; i++)); do
sortedItemSizes="${sortedItemSizes}$( echo -en "\n0 ${i}" )"
done
sortedItemSizes="${sortedItemSizes:1}"
fi
case "$outputMode" in
colors)
{
while read foo i; do
itemKey="${itemKeys[$i]}"
itemValue="${itemValues[$i]}"
echo -en "${FC}"
echo -En "$itemKey"
echo -en "${NM}=${VC}"
if [ "${itemValue:0:15}" = 'binaryfilepath:' ]; then
itemValueSize="$( getFileSize "${itemValue:15}" )"
echo -En "data: $( getHumanByteSize "${itemValueSize}" )"
elif [ "${itemValue:0:16}" = 'artworkfilepath:' ]; then
itemValueSize="$( getFileSize "${itemValue##*:}" )"
echo -En "artwork: $( getHumanByteSize "${itemValueSize}" )"
else
echo -En "${itemValue}"
fi
echo -e "${NM}"
done < <( echo "$sortedItemSizes" )
} | $sedcmd -e 's@\x01@ / @g' > "${tempDir}/common/outputQueue.${pn}"
;;
human)
{
while read foo i; do
itemKey="${itemKeys[$i]}"
itemValue="${itemValues[$i]}"
if [ "${itemValue:0:15}" = 'binaryfilepath:' ]; then
itemValueSize="$( getFileSize "${itemValue:15}" )"
echo -E "${itemKey}=data: $( getHumanByteSize "${itemValueSize}" )"
elif [ "${itemValue:0:16}" = 'artworkfilepath:' ]; then
itemValueSize="$( getFileSize "${itemValue##*:}" )"
echo -E "${itemKey}=artwork: $( getHumanByteSize "${itemValueSize}" )"
else
echo -E "${itemKey}=${itemValue}"
fi
done < <( echo "$sortedItemSizes" )
} | $sedcmd -e 's@\x01@ / @g' > "${tempDir}/common/outputQueue.${pn}"
;;
machine)
{
while read foo i; do
itemKey="${itemKeys[$i]}"
itemLowercaseKey="${itemLowercaseKeys[$i]}"
itemValue="${itemValues[$i]}"
p="x${itemLowercaseKey}Y"
if [ "$readOnlyKeys" != "${readOnlyKeys//$p/@}" -o "$newReadOnlyKeys" != "${newReadOnlyKeys//$p/@}" ]; then
roPrefix='ro:'
else
roPrefix=''
fi
if [ "${itemValue:0:15}" = 'binaryfilepath:' ]; then
echo -En "${roPrefix}${itemKey}=data:"
if [ "$OS" = 'Linux' ]; then
base64 -w 0 "${itemValue:15}"
echo
else
# base64 on OS X outputs a trailing new line already
base64 -b 0 "${itemValue:15}"
fi
elif [ "${itemValue:0:16}" = 'artworkfilepath:' ]; then
artworkFilename="${itemValue:16}"; artworkFilename="${artworkFilename%:*}"
echo -En "${roPrefix}${itemKey}=artwork:${artworkFilename}\x00"
if [ "$OS" = 'Linux' ]; then
base64 -w 0 "${itemValue##*:}"
echo
else
# base64 on OS X outputs a trailing new line already
base64 -b 0 "${itemValue##*:}"
fi
else
echo -En "${roPrefix}${itemKey}="
echo -En "${itemValues[$i]}" | LC_ALL=C tr '\n' '\2' 2>/dev/null
echo
fi
done < <( echo "$sortedItemSizes" )
} | $sedcmd -e 's@\x01@\\x00@g' -e 's@\x02@\\n@g' > "${tempDir}/common/outputQueue.${pn}"
;;
raw)
{
while read foo i; do
itemKey="${itemKeys[$i]}"
itemValue="${itemValues[$i]}"
if [ "${itemValue:0:15}" = 'binaryfilepath:' ]; then
echo -En "${itemKeys[$i]}="
cat "${itemValue:15}"
elif [ "${itemValue:0:16}" = 'artworkfilepath:' ]; then
artworkFilename="${itemValue:16}"; artworkFilename="${artworkFilename%:*}"
echo -En "${itemKeys[$i]}=${artworkFilename}"
echo -en "\x00"
cat "${itemValue##*:}"
else
echo -E "${itemKeys[$i]}=${itemValue}"
fi
done < <( echo "$sortedItemSizes" )
} | LC_ALL=C tr '\1' '\0' 2>/dev/null > "${tempDir}/common/outputQueue.${pn}"
;;
esac
}
flushOutputQueue ()
{
local oq=0
for ((oq=0; oq<nProcesses; oq++)); do