78dfdf5759f0fb013090039faec7e0e151bfa84b
[abcde.git] / abcde
1 #!/bin/bash
2 # Copyright (c) 1998-2001 Robert Woodcock <rcw@debian.org>
3 # Copyright (c) 2003-2006 Jesus Climent <jesus.climent@hispalinux.es>
4 # Copyright (c) 2009-2012 Colin Tuckley <colint@debian.org>
5 # Copyright (c) 2012-2018 Steve McIntyre <93sam@@debian.org>
6 # Copyright (c) 2015-2017 Andrew Strong <andrew.david.strong@gmail.com>
7 # This code is hereby licensed for public consumption under either the
8 # GNU GPL v2 or greater, or Larry Wall's Artistic license - your choice.
9 #
10 # You should have received a copy of the GNU General Public License along
11 # with this program; if not, write to the Free Software Foundation, Inc.,
12 # 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
13
14 VERSION='2.8.2-UNRELEASED'
15
16 usage ()
17 {
18 echo "This is abcde v$VERSION."
19 echo "Usage: abcde [options] [tracks]"
20 echo "Options:"
21 echo "-1     Encode the whole CD in a single file"
22 echo "-a <action1[,action2]...>"
23 echo "       Actions to perform:"
24 echo "       cddb,read,getalbumart,embedalbumart,normalize,encode,tag,move,replaygain,playlist,clean"
25 #echo "-A     Experimental actions (retag, transcode)"
26 echo "-b     Enable batch normalization"
27 echo "-B     Embed albumart (this also activates getalbumart)"
28 echo "-c <file>"
29 echo "       Specify a configuration file (overrides system and user config files)"
30 echo "-C <discid#>"
31 echo "       Specify discid to resume from (only needed if you no longer have the cd)"
32 echo "-d <device>"
33 echo "       Specify CDROM device to grab (flac uses a single-track flac file)"
34 echo "-D     Debugging mode (equivalent to sh -x abcde)"
35 echo "-e     Erase encoded track information from status file"
36 echo "-f     Force operations that otherwise are considered harmful. Read \"man abcde\""
37 echo "-g     Use \"lame --nogap\" for MP3 encoding. Disables low disk and pipes flags"
38 echo "-G     Get album art by using the 'getalbumart' action"
39 echo "-h     This help information"
40 #echo "-i    Tag files while encoding, when possible (local only) -NWY-"
41 echo "-j <#> Number of encoder processes to run at once (localhost)"
42 echo "-k     Keep the wav tracks for later use"
43 echo "-l     Use low disk space algorithm"
44 echo "-L     Use local CDDB storage directory"
45 echo "-m     Modify playlist to include CRLF endings, to comply with some players"
46 #echo "       WARNING: Deprecated. Use \"cue\" action"
47 #echo "-M     Create a CUE file"
48 echo "-n     No lookup. Don't query CDDB, just create and use template"
49 echo "-N     Noninteractive. Never prompt for anything"
50 echo "-o <type1[,type2]...>"
51 echo "       Output file type(s) (vorbis,mp3,flac,spx,mpc,wav,m4a,opus,mka,wv,ape,mp2,tta,aiff). Defaults to vorbis"
52 echo "-p     Pad track numbers with 0's (if less than 10 tracks)"
53 echo "-P     Use UNIX pipes to read+encode without wav files"
54 echo "-Q     Select CDDBMETHOD method(s) from the command line. Choose from any/all of musicbrainz,cddb,cdtext. Defaults to musicbrainz".
55 echo "-r <host1[,host2]...>"
56 echo "       Also encode on these remote hosts"
57 echo "-s <field>"
58 echo "       Show fields from the CDDB info (year,genre)"
59 echo "-S <#> Set the CD speed"
60 echo "-t <#> Start the track numbering at a given number"
61 echo "-T <#> Same as -t but modifies tag numbering"
62 echo "-U     Do NOT use UNICODE (UTF8) tags and comments"
63 echo "-v     Show version number and exit"
64 echo "-V     Be a bit more verbose about what is happening behind the scenes"
65 echo "-x     Eject CD after all tracks are read"
66 echo "-w <comment>"
67 echo "       Add a comment to the CD tracks"
68 echo "-W <#> Concatenate CDs: -T #01 -w \"CD #\""
69 echo "-z     Use debug CDROMREADERSYNTAX option (needs cdparanoia)"
70 echo ""
71 echo "Tracks is a space-delimited list of tracks to grab."
72 echo "Ranges specified with hyphens are allowed (i.e., 1-5)."
73 echo ""
74 #echo "Double hyphens are used to concatenate tracks"
75 }
76
77 addstatus ()
78 {
79         echo "$@" >> "${ABCDETEMPDIR}/status"
80 }
81
82 # log [level] [message]
83 #
84 # log outputs the right message in a common format
85 log ()
86 {
87         BLURB="$1"
88         shift
89         case $BLURB in
90                 error)   >&2 echo "[ERROR] abcde: $@" >&2 ;;
91                 warning) >&2 echo "[WARNING] $@" >&2 ;;
92                 info)    >&4 echo "[INFO] $@" ;;
93         esac
94 }
95
96 # Functions to replace the need of seq, which is too distribution dependent.
97 f_seq_row ()
98 {
99         i="$1"
100         while [ "$i" -le "$2" ]
101         do
102                 echo "$i"
103                 i=$(("$i" + 1))
104         done
105 }
106
107 f_seq_line ()
108 {
109         i="$1"
110         if echo "$i" | grep "[[:digit:]]" > /dev/null 2>&1 ; then
111                 while [ "$i" -le "$2" ]
112                 do
113                         printf "%d " "$i"
114                         i=$(("$i" + 1))
115                 done
116                 echo
117         else
118                 log error "syntax error while processing track numbers ($i)"
119                 exit 1
120         fi
121 }
122
123 # Functions to replace the need of awk {print $1} and {print $NF}
124 get_first()
125 {
126         if [ X"$1" = "X" ]; then
127                 for first in $(cat); do
128                         break
129                 done
130         else
131                 first=$1
132         fi
133         echo "$first"
134 }
135
136 get_last()
137 {
138         if [ X"$1" = "X" ]; then
139                 for stdin in $(cat); do
140                         last=$stdin
141                 done
142         else
143                 for last in "$@" ; do :; done
144         fi
145         echo "$last"
146 }
147
148 # checkstatus [blurb]
149 # Returns "0" if the blurb was found, returns 1 if it wasn't
150 # Puts the blurb content, if available, on stdout.
151 # Otherwise, returns "".
152 checkstatus ()
153 {
154         # Take the last line in the status file if there's multiple matches
155         PATTERN="^$1(=.*)?$"
156         BLURB=$(grep -E "$PATTERN" "${ABCDETEMPDIR}/status" | tail -n 1)
157
158         if [ -z "$BLURB" ]; then
159                 # No matches found
160                 return 1
161         else
162                 # Matches found
163                 # See if there's a = in it
164                 if ( echo "$BLURB" | grep -q '=' ); then
165                         echo "$BLURB" | cut -f2- -d=
166                 fi
167                 return 0
168         fi
169 }
170
171 # checkwarnings [blurb]
172 # Returns "0" if the blurb was found (meaning there was an warning),
173 # returns 1 if it wasn't (yes this is a little backwards).
174 # Does not print the blurb on stdout.
175 # Otherwise, returns "".
176 checkwarnings ()
177 {
178         if [ -e "${ABCDETEMPDIR}/warnings" ]; then :; else
179                 return 1
180         fi
181         # Take the last line in the status file if there's multiple matches
182         PATTERN="^$1(:.*)?$"
183         BLURB=$(grep -E "$PATTERN" "${ABCDETEMPDIR}/warnings" | tail -n 1)
184
185         if [ -z "$BLURB" ]; then
186                 # negative, we did not have a negative...
187                 return 1
188         else
189                 # affirmative, we had a negative...
190                 return 0
191         fi
192 }
193
194 # checkerrors [blurb]
195 # Returns "0" if the blurb was found (meaning there was an error),
196 # returns 1 if it wasn't (yes this is a little backwards).
197 # Does not print the blurb on stdout.
198 # Otherwise, returns "".
199 checkerrors ()
200 {
201         if [ -e "${ABCDETEMPDIR}/errors" ]; then :; else
202                 return 1
203         fi
204         # Take the last line in the status file if there's multiple matches
205         PATTERN="^$1(:.*)?$"
206         BLURB=$(grep -E "$PATTERN" "${ABCDETEMPDIR}/errors" | tail -n 1)
207
208         if [ -z "$BLURB" ]; then
209                 # negative, we did not have a negative...
210                 return 1
211         else
212                 # affirmative, we had a negative...
213                 return 0
214         fi
215 }
216
217 # page [file]
218 # Display a file. If it's too long to fit the current terminal size,
219 # find the right pager in the system and use it
220 page ()
221 {
222         PAGEFILE="$1"
223         local NUM_LINES=$(wc -l < "$PAGEFILE")
224
225         # Is the text long enough to need a pager?
226         if [ "$NUM_LINES" -ge $LINES ]; then
227                 # Yes!
228                 # Use the debian sensible-pager wrapper to pick the pager user
229                 # has requested via their $PAGER environment variable
230                 if [ -x "/usr/bin/sensible-pager" ]; then
231                         /usr/bin/sensible-pager "$PAGEFILE"
232                 elif [ -x "$PAGER" ]; then
233                         # That failed, try to load the preferred pager, starting
234                         # with their PAGER variable
235                         $PAGER "$PAGEFILE"
236                         # If that fails, check for less
237                 elif [ -x /usr/bin/less ]; then
238                         /usr/bin/less -f "$PAGEFILE"
239                         # more should be on all UNIX systems
240                 elif [ -x /bin/more ]; then
241                         /bin/more "$PAGEFILE"
242                 else
243                         # No bananas, just cat the thing
244                         cat "$PAGEFILE" >&2
245                 fi
246         else
247                 # No, just cat the thing
248                 cat "$PAGEFILE" >&2
249         fi
250 }
251
252 # run_command [blurb] [command...]
253 # Runs a command, silently if necessary, and updates the status file
254 run_command ()
255 {
256         vvecho "$@"
257         BLURB="$1"
258         shift
259         # See if this is supposed to be silent
260         if [ "$(checkstatus encode-output)" = "loud" ]; then
261                 "$@" >&2
262                 RETURN=$?
263         else
264                 # Special case for SMP, since
265                 # encoder output is never displayed, don't mute echos
266                 if [ -z "$BLURB" ] && [ "$MAXPROCS" != "1" ]; then
267                         "$@" >&2
268                         RETURN=$?
269                 else
270                         "$@" >/dev/null 2>&1
271                         RETURN=$?
272                 fi
273         fi
274         case "$1" in
275         normalize|normalize-audio)
276                 if [ "$RETURN" = "2" ]; then
277                         # File was already normalized.
278                         RETURN=0
279                 fi
280                 ;;
281         esac
282         if [ "$RETURN" != "0" ]; then
283                 # Put an error in the errors file. For various reasons we
284                 # can't capture a copy of the program's output but we can
285                 # log what we attempted to execute and the error code
286                 # returned by the program.
287                 if [ "$BLURB" ]; then
288                         TWEAK="$BLURB: "
289                 fi
290                 echo "${TWEAK}returned code $RETURN: $@" >> "${ABCDETEMPDIR}/errors"
291                 return $RETURN # Do not pass go, do not update the status file
292         fi
293         if [ "$BLURB" ]; then
294                 echo "$BLURB" >> "${ABCDETEMPDIR}/status"
295         fi
296 }
297
298 # relpath() and slash() are Copyright (c) 1999 Stuart Ballard and
299 # distributed under the terms of the GNU GPL v2 or later, at your option
300
301 # Function to determine if a word contains a slash.
302 slash ()
303 {
304         case "$1" in
305         */*) return 0;;
306         *) return 1;;
307         esac
308 }
309
310 # Function to give the relative path from one file to another.
311 # Usage: relpath fromfile tofile
312 # eg relpath music/Artist/Album.m3u music/Artist/Album/Song.mp3
313 # (the result would be Album/Song.mp3)
314 # Output is relative path to $2 from $1 on stdout
315
316 # This code has the following restrictions:
317 # Multiple ////s are not collapsed into single /s, with strange effects.
318 # Absolute paths and ../s are handled wrong in FR (but they work in TO)
319 # If FR is a directory it must have a trailing /
320
321 relpath ()
322 {
323         FR="$1"
324         TO="$2"
325
326         case "$TO" in
327         /*) ;; # No processing is needed for absolute paths
328         *)
329                 # Loop through common prefixes, ignoring them.
330                 while slash "$FR" && [ "$(echo "$FR" | cut -d/ -f1)" = "$(echo "$TO" | cut -d/ -f1)" ]
331                 do
332                         FR="$(echo "$FR" | cut -d/ -f2-)"
333                         TO="$(echo "$TO" | cut -d/ -f2-)"
334                 done
335                 # Loop through directory portions left in FR, adding appropriate ../s.
336                 while slash "$FR"
337                 do
338                         FR="$(echo "$FR" | cut -d/ -f2-)"
339                         TO="../$TO"
340                 done
341                 ;;
342         esac
343
344         echo "$TO"
345 }
346
347 new_checkexec ()
348 {
349         if [ ! "$@" = "" ]; then
350                 # Cut off any command-line option we added in
351                 X=$(echo "$@" | cut -d' ' -f2)
352                 WHICH=$(which "$X" 2>/dev/null)
353                 if [ -z "$WHICH" ]; then
354                         return 1
355                 elif [ ! -x "$WHICH" ]; then
356                         return 2
357                 fi
358         fi
359         return 0
360 }
361
362 checkexec ()
363 {
364         if [ ! "$@" = "" ]; then
365                 # Cut off any command-line option we added in
366                 X=$(echo "$@" | cut -d' ' -f2)
367                 # Test for built-in abcde.function
368                 [ "$X" != "${X#abcde.}" ] && type "$X" >/dev/null 2>&1 && return
369                 WHICH=$(which "$X" 2>/dev/null)
370                 if [ -z "$WHICH" ]; then
371                         log error "$X is not in your path." >&2
372                         log info  "Define the full path to the executable if it exists on your system." >&2
373                         if [ -e /etc/debian_version ] ; then
374                                 case $X in
375                                         oggenc)
376                                                 MISSING_PACKAGE=vorbis-tools
377                                                 ;;
378                                         lame|flac|cd-discid|eject|mkcue|icedax|glyrc)
379                                                 MISSING_PACKAGE=$X
380                                                 ;;
381                                 esac
382                                 log info "Hint: sudo apt-get install $MISSING_PACKAGE" >&2
383                         fi
384                         exit 1
385                 elif [ ! -x "$WHICH" ]; then
386                         log error "$X is not executable." >&2
387                         exit 1
388                 fi
389         fi
390 }
391
392 # diffentries <filename> <max_value> <entry1>,<entry2>
393 # max_value: the range of entries goes from 1 to <max_value>
394 diffentries ()
395 {
396         FILENAME=$1
397         shift
398         local CDDBDIFFCHOICES=$1
399         shift
400         local CDDBDIFFCHOICE="$@"
401         if [ ! X"$DIFF" = "X" ]; then
402                 PARSECHOICE1=$(echo "$CDDBDIFFCHOICE" | cut -d"," -f1 | xargs printf %d 2>/dev/null)
403                 PARSECHOICE2=$(echo "$CDDBDIFFCHOICE" | cut -d"," -f2 | xargs printf %d 2>/dev/null)
404                 if [ "$PARSECHOICE1" -lt 1 ] || [ "$PARSECHOICE1" -gt "$CDDBDIFFCHOICES" ] || \
405                    [ "$PARSECHOICE2" -lt 1 ] || [ "$PARSECHOICE2" -gt "$CDDBDIFFCHOICES" ] || \
406                    [ "$PARSECHOICE1" -eq "$PARSECHOICE2" ]; then
407                         echo "Invalid diff range. Please select two comma-separated numbers between 1 and $CDDBDIFFCHOICES" >&2
408                 else
409                         # We parse the 2 choices to diff, store them in temporary files and diff them.
410                         for PARSECHOICE in $(echo "$CDDBDIFFCHOICE" | tr , \ ); do
411                                 do_cddbparse "${ABCDETEMPDIR}/$FILENAME.$PARSECHOICE" > "${ABCDETEMPDIR}/$FILENAME.parsechoice.$PARSECHOICE"
412                         done
413                         echo "Showing diff between choices $PARSECHOICE1 and $PARSECHOICE2..." > "${ABCDETEMPDIR}/$FILENAME.diff"
414                         $DIFF $DIFFOPTS "${ABCDETEMPDIR}/$FILENAME.parsechoice.$PARSECHOICE1" \
415                                   "${ABCDETEMPDIR}/$FILENAME.parsechoice.$PARSECHOICE2" >> "${ABCDETEMPDIR}/$FILENAME.diff"
416                         page "${ABCDETEMPDIR}/$FILENAME.diff"
417                 fi
418         else
419                 echo "The diff program was not found in your path. Please choose a number between 0 and $CDDBDIFFCHOICES." >&2
420         fi
421 }
422
423 # getcddbinfo
424 # Finds an specific field from cddbinfo
425 getcddbinfo()
426 {
427         case $1 in
428         TRACKNAME1)
429                 TRACKNAME="$(grep -a "^TTITLE$CDDBTRACKNUM=" "$CDDBDATA" | head -n 1 | cut -f2- -d= | tr -d \[:cntrl:\] | sed 's/\ \+$//')"
430                 ;;
431         TRACKNAME)
432                 TRACKNAME="$(grep -a "^TTITLE$CDDBTRACKNUM=" "$CDDBDATA" | cut -f2- -d= | tr -d \[:cntrl:\] | sed 's/\ \+$//')"
433                 ;;
434         TRACK-INFO)
435                 grep -a "^EXTT$CDDBTRACKNUM=" "$CDDBDATA" | cut -f2- -d= | tr -d \[:cntrl:\] | sed 's/\\n/\n/g'
436                 ;;
437         esac
438 }
439
440 # gettracknum
441 # Get the track number we are going to use for different actions
442 gettracknum()
443 {
444         if [ -n "$STARTTRACKNUMBER" ] ; then
445                 # Get the trackpadding from the current track, also trim whitespace for MacOSX
446                 CURRENTTRACKPADDING=$(echo -n "$UTRACKNUM" | wc -c | tr -d ' ')
447                 TRACKNUM=$( printf %0."${CURRENTTRACKPADDING}"d $(("${UTRACKNUM}" + "${STARTTRACKNUMBER}" - "${FIRSTTRACK}")))
448         else
449                 TRACKNUM="${UTRACKNUM}"
450         fi
451 }
452
453 # makeids
454 #
455 # Calculate cddb disc ids without requiring specialized helper programs.
456 # largely copied from cd-discid and musicbrainz examples.  some of the steps
457 # don't make sense, but they're necessary to match the ids generated by other
458 # programs.
459 #
460 ## FIXME ## Right now, we get 2 frames more than with cue2discid ??
461 # data@petit:~$ sh /tmp/cue2discid /home/data/tmp/flac/01.Roisin_Murphy--Ruby_Blue.flac
462 # processing offsetimes 00:00:00 04:47:10 08:20:37 11:46:46 17:45:36 21:41:57 27:32:21 32:03:73 35:39:28 38:27:33 43:50:38 44:42:34
463 # 980b4b0c 12 150 21685 37687 53146 80061 97782 124071 144448 160603 173208 197438 201334 2895
464 # data@petit:~$ metaflac --export-cuesheet-to=- /home/data/tmp/flac/01.Roisin_Murphy--Ruby_Blue.flac| python /home/data/sources/abcde/trunk/examples/cue2discid
465 # 980b4b0c 12 150 21685 37687 53146 80061 97782 124071 144448 160603 173208 197438 201334 2893
466 #
467 # Variables: OFFSETS, TRACKS, LEADOUT, [LEADIN]
468 makeids ()
469 {
470         if [ X"$LEADOUT" = "X" ]; then
471                 log warning "Error trying to calculate disc ids without lead-out information."
472                 exit 1
473         fi
474
475         # default to a two second lead-in
476         IDMAGICNUM=150
477         LEADIN=${LEADIN:=150}
478
479         # number of cdframes per second
480         CDFRAMES=75
481
482         # reset cddb checksum for cddb disc-id calululation
483         CDDBCKSUM=0
484
485         COOKEDOFFSETS=""
486         for OFFSET in $OFFSETS
487         do
488                 COOKEDOFFSETS="${COOKEDOFFSETS} $(($OFFSET + $LEADIN))"
489
490                 OFFSETTIME=$(( ($OFFSET + $LEADIN) / $CDFRAMES  ))
491                 while [ $OFFSETTIME -gt 0 ]; do
492                         CDDBCKSUM=$(($CDDBCKSUM + $OFFSETTIME % 10))
493                         OFFSETTIME=$(($OFFSETTIME / 10))
494                 done
495
496         done
497
498         COOKEDOFFSETS="${COOKEDOFFSETS:1}"  # eat the leading space
499
500         PREGAP=$(echo $OFFSETS | cut -f1 -d' ')
501         TOTALTIME=$(( (($LEADOUT + $LEADIN + $PREGAP) / $CDFRAMES) - (($LEADIN + $PREGAP) / $CDFRAMES)))
502
503         vvecho "makeids: PREGAP $PREGAP, LEADIN $LEADIN, LEADOUT $LEADOUT"
504
505         # Calculate both the cddb discid *and* the musicbrainz discid
506         # now. We'll use the cddb discid for reference in most cases
507         # for consistency, but we also have the musicbrainz discid for
508         # when we need it
509         printf -v CDDBDISCID "%08lx" $(( ($CDDBCKSUM % 0xff) * 16777216 | $TOTALTIME * 256 | $TRACKS))
510         CDDBTRACKINFO="${CDDBDISCID} $((TRACKS)) ${COOKEDOFFSETS} $((($LEADOUT + $LEADIN + $IDMAGICNUM) / $CDFRAMES))"
511
512         case $CDDBMETHOD in
513                 *musicbrainz*)
514                         # FIXME: don't assume the first track is 1
515                         MBDISCID=$($MUSICBRAINZ --command calcid --discinfo 1 $TRACKS $LEADIN $(($PREGAP + $LEADOUT)) $OFFSETS)
516                         error=$?
517                         if [ $error != 0 ]; then
518                                 log error "$MUSICBRAINZ failed to run; ABORT"
519                                 exit $error
520                         fi
521                         MBTRACKINFO="${MBDISCID} $((TRACKS)) ${COOKEDOFFSETS} $((($LEADOUT + $LEADIN + $IDMAGICNUM) / $CDFRAMES))"
522                         ;;
523         esac
524 }
525
526 do_replaygain()
527 {
528         if checkstatus replaygain; then :; else
529                 run_command "" echo "Adding replaygain information..."
530                 for TMPOUTPUT in $( echo "$OUTPUTTYPE" | tr , \ )
531                 do
532                         case $TMPOUTPUT in
533                                 vorbis|ogg)
534                                         OUTPUT=$OGGOUTPUTCONTAINER
535                                         ;;
536                                 opus)
537                                         OUTPUT=$OPUSOUTPUTCONTAINER
538                                         ;;
539                                 flac)
540                                         OUTPUT=$FLACOUTPUTCONTAINER
541                                         ;;
542                                 *)
543                                         OUTPUT=$TMPOUTPUT
544                                         ;;
545                         esac
546                         OUTPUTFILES=""
547                         REPLAYINDEX=0
548                         for UTRACKNUM in $TRACKQUEUE
549                         do
550                                 CDDBTRACKNUM=$(("$UTRACKNUM" - 1))
551                                 getcddbinfo TRACKNAME
552                                 splitvarious
553                                 TRACKFILE="$(mungetrackname "$TRACKNAME")"
554                                 ARTISTFILE="$(mungeartistname "$TRACKARTIST")"
555                                 ALBUMFILE="$(mungealbumname "$DALBUM")"
556                                 GENRE="$(mungegenre "$GENRE")"
557                                 YEAR=${CDYEAR:-$CDYEAR}
558                                 gettracknum
559                                 if [ "$ONETRACK" = "y" ]; then
560                                         if [ "$VARIOUSARTISTS" = "y" ]; then
561                                                 OUTPUTFILE="$(eval echo \""$VAONETRACKOUTPUTFORMAT"\")"
562                                         else
563                                                 OUTPUTFILE="$(eval echo \""$ONETRACKOUTPUTFORMAT"\")"
564                                         fi
565                                 else
566                                         if [ "$VARIOUSARTISTS" = "y" ]; then
567                                                 OUTPUTFILE="$(eval echo \""$VAOUTPUTFORMAT"\")"
568                                         else
569                                                 OUTPUTFILE="$(eval echo \""$OUTPUTFORMAT"\")"
570                                         fi
571                                 fi
572                                 OUTPUTFILES[$REPLAYINDEX]="$OUTPUTDIR/$OUTPUTFILE.$OUTPUT"
573                                 (( REPLAYINDEX = $REPLAYINDEX + 1 ))
574                         done
575                         case "$OUTPUT" in
576                                 flac)
577                                         run_command "replaygain-flac" nice $ENCNICE $METAFLAC $FLACGAINOPTS "${OUTPUTFILES[@]}"
578                                         ;;
579                                 vorbis|ogg)
580                                         run_command "replaygain-vorbis" nice $ENCNICE $VORBISGAIN $VORBISGAINOPTS "${OUTPUTFILES[@]}"
581                                         ;;
582                                 mp3)
583                                         run_command "replaygain-mp3" nice $ENCNICE $MP3GAIN $MP3GAINOPTS "${OUTPUTFILES[@]}"
584                                         ;;
585                                 mpc)
586                                         run_command "replaygain-mpc" nice $ENCNICE $MPCGAIN "${OUTPUTFILES[@]}"
587                                         ;;
588                                 wv)
589                                         run_command "replaygain-wv" nice $ENCNICE $WVGAIN $WVGAINOPTS "${OUTPUTFILES[@]}"
590                                         ;;
591                                 *);;
592                         esac
593                 done
594                 if checkerrors "replaygain-.{3,6}"; then :; else
595                         run_command "replaygain" true
596                 fi
597         fi
598 }
599
600 # This code splits the a Various Artist track name from one of the following
601 # forms:
602 #
603 #  forward:        Artist / Track
604 #  forward-dash:   Artist - Track
605 #  reverse:        Track / Artist
606 #  reverse-dash:   Track - Artist
607 #  colon:          Artist: Track
608 #  trailing-paren: Artist (Track)
609 #
610 # variables used:
611 # VARIOUSARTISTS, VARIOUSARTISTSTYLE, TRACKNAME, TRACKARTIST
612 splitvarious ()
613 {
614         if [ "$VARIOUSARTISTS" = "y" ] && [ ! "$ONETRACK" = "y" ]; then
615                 case "$VARIOUSARTISTSTYLE" in
616                 forward)
617                         DTITLEARTIST="$(echo "$TRACKNAME" | sed 's- / -~-g')"
618                         TRACKARTIST="$(echo "$DTITLEARTIST" | cut -f1 -d~)"
619                         TRACKNAME="$(echo "$DTITLEARTIST" | cut -f2 -d~)"
620                         ;;
621                 forward-dash)
622                         DTITLEARTIST="$(echo "$TRACKNAME" | sed 's, - ,~,g')"
623                         TRACKARTIST="$(echo "$DTITLEARTIST" | cut -f1 -d~)"
624                         TRACKNAME="$(echo "$DTITLEARTIST" | cut -f2 -d~)"
625                         ;;
626                 reverse)
627                         DTITLEARTIST="$(echo "$TRACKNAME" | sed 's- / -~-g')"
628                         TRACKARTIST="$(echo "$DTITLEARTIST" | cut -f2 -d~)"
629                         TRACKNAME="$(echo "$DTITLEARTIST" | cut -f1 -d~)"
630                         ;;
631                 reverse-dash)
632                         DTITLEARTIST="$(echo "$TRACKNAME" | sed 's, - ,~,g')"
633                         TRACKARTIST="$(echo "$DTITLEARTIST" | cut -f2 -d~)"
634                         TRACKNAME="$(echo "$DTITLEARTIST" | cut -f1 -d~)"
635                         ;;
636                 colon)
637                         DTITLEARTIST="$(echo "$TRACKNAME" | sed 's-: -~-g')"
638                         TRACKARTIST="$(echo "$DTITLEARTIST" | cut -f1 -d~)"
639                         TRACKNAME="$(echo "$DTITLEARTIST" | cut -f2 -d~)"
640                         ;;
641                 trailing-paren)
642                         DTITLEARTIST="$(echo "$TRACKNAME" | sed 's,^\(.*\) (\(.*\)),\1~\2,')"
643                         TRACKARTIST="$(echo "$DTITLEARTIST" | cut -f2 -d~)"
644                         TRACKNAME="$(echo "$DTITLEARTIST" | cut -f1 -d~)"
645                         ;;
646                 esac
647         elif [ "$VARIOUSARTISTS" = "y" ] && [ "$ONETRACK" = "y" ]; then
648                 TRACKARTIST="Various"
649         else
650                 TRACKARTIST="$DARTIST"
651         fi
652 }
653
654 do_getgenreid () {
655         local genre=$(echo "${@}" | tr 'A-Z' 'a-z')
656         local id=""
657         case ${genre} in
658                 "blues")                 id=0 ;;
659                 "classic rock")          id=1 ;;
660                 "country")               id=2 ;;
661                 "dance")                 id=3 ;;
662                 "disco")                 id=4 ;;
663                 "funk")                  id=5 ;;
664                 "grunge")                id=6 ;;
665                 "hip-hop")               id=7 ;;
666                 "jazz")                  id=8 ;;
667                 "metal")                 id=9 ;;
668                 "new age")               id=10 ;;
669                 "oldies")                id=11 ;;
670                 "other")                 id=12 ;;
671                 "pop")                   id=13 ;;
672                 "r&b")                   id=14 ;;
673                 "rap")                   id=15 ;;
674                 "reggae")                id=16 ;;
675                 "rock")                  id=17 ;;
676                 "techno")                id=18 ;;
677                 "industrial")            id=19 ;;
678                 "alternative")           id=20 ;;
679                 "ska")                   id=21 ;;
680                 "death metal")           id=22 ;;
681                 "pranks")                id=23 ;;
682                 "soundtrack")            id=24 ;;
683                 "euro-techno")           id=25 ;;
684                 "ambient")               id=26 ;;
685                 "trip-hop")              id=27 ;;
686                 "vocal")                 id=28 ;;
687                 "jazz+funk")             id=29 ;;
688                 "fusion")                id=30 ;;
689                 "trance")                id=31 ;;
690                 "classical")             id=32 ;;
691                 "instrumental")          id=33 ;;
692                 "acid")                  id=34 ;;
693                 "house")                 id=35 ;;
694                 "game")                  id=36 ;;
695                 "sound clip")            id=37 ;;
696                 "gospel")                id=38 ;;
697                 "noise")                 id=39 ;;
698                 "alt. rock")             id=40 ;;
699                 "bass")                  id=41 ;;
700                 "soul")                  id=42 ;;
701                 "punk")                  id=43 ;;
702                 "space")                 id=44 ;;
703                 "meditative")            id=45 ;;
704                 "instrum. pop")          id=46 ;;
705                 "instrum. rock")         id=47 ;;
706                 "ethnic")                id=48 ;;
707                 "gothic")                id=49 ;;
708                 "darkwave")              id=50 ;;
709                 "techno-indust.")        id=51 ;;
710                 "electronic")            id=52 ;;
711                 "pop-folk")              id=53 ;;
712                 "eurodance")             id=54 ;;
713                 "dream")                 id=55 ;;
714                 "southern rock")         id=56 ;;
715                 "comedy")                id=57 ;;
716                 "cult")                  id=58 ;;
717                 "gangsta")               id=59 ;;
718                 "top 40")                id=60 ;;
719                 "christian rap")         id=61 ;;
720                 "pop/funk"|"pop / funk") id=62 ;;
721                 "jungle")                id=63 ;;
722                 "native american")       id=64 ;;
723                 "cabaret")               id=65 ;;
724                 "new wave")              id=66 ;;
725                 "psychadelic")           id=67 ;;
726                 "rave")                  id=68 ;;
727                 "showtunes")             id=69 ;;
728                 "trailer")               id=70 ;;
729                 "lo-fi")                 id=71 ;;
730                 "tribal")                id=72 ;;
731                 "acid punk")             id=73 ;;
732                 "acid jazz")             id=74 ;;
733                 "polka")                 id=75 ;;
734                 "retro")                 id=76 ;;
735                 "musical")               id=77 ;;
736                 "rock & roll")           id=78 ;;
737                 "hard rock")             id=79 ;;
738                 "folk")                  id=80 ;;
739                 "folk/rock")             id=81 ;;
740                 "national folk")         id=82 ;;
741                 "swing")                 id=83 ;;
742                 "fusion")                id=84 ;;
743                 "bebob")                 id=85 ;;
744                 "latin")                 id=86 ;;
745                 "revival")               id=87 ;;
746                 "celtic")                id=88 ;;
747                 "bluegrass")             id=89 ;;
748                 "avantgarde")            id=90 ;;
749                 "gothic rock")           id=91 ;;
750                 "progress. rock")        id=92 ;;
751                 "psychadel. rock")       id=93 ;;
752                 "symphonic rock")        id=94 ;;
753                 "slow rock")             id=95 ;;
754                 "big band")              id=96 ;;
755                 "chorus")                id=97 ;;
756                 "easy listening")        id=98 ;;
757                 "acoustic")              id=99 ;;
758                 "humour")                id=100 ;;
759                 "speech")                id=101 ;;
760                 "chanson")               id=102 ;;
761                 "opera")                 id=103 ;;
762                 "chamber music")         id=104 ;;
763                 "sonata")                id=105 ;;
764                 "symphony")              id=106 ;;
765                 "booty bass")            id=107 ;;
766                 "primus")                id=108 ;;
767                 "porn groove")           id=109 ;;
768                 "satire")                id=110 ;;
769                 "slow jam")              id=111 ;;
770                 "club")                  id=112 ;;
771                 "tango")                 id=113 ;;
772                 "samba")                 id=114 ;;
773                 "folklore")              id=115 ;;
774                 "ballad")                id=116 ;;
775                 "power ballad")          id=117 ;;
776                 "rhythmic soul")         id=118 ;;
777                 "freestyle")             id=119 ;;
778                 "duet")                  id=120 ;;
779                 "punk rock")             id=121 ;;
780                 "drum solo")             id=122 ;;
781                 "a capella")             id=123 ;;
782                 "euro-house")            id=124 ;;
783                 "dance hall")            id=125 ;;
784                 "goa")                   id=126 ;;
785                 "drum & bass")           id=127 ;;
786                 "club-house")            id=128 ;;
787                 "hardcore")              id=129 ;;
788                 "terror")                id=130 ;;
789                 "indie")                 id=131 ;;
790                 "britpop")               id=132 ;;
791                 "negerpunk")             id=133 ;;
792                 "polsk punk")            id=134 ;;
793                 "beat")                  id=135 ;;
794                 "christian gangsta rap") id=136 ;;
795                 "heavy metal")           id=137 ;;
796                 "black metal")           id=138 ;;
797                 "crossover")             id=139 ;;
798                 "contemporary christian")id=140 ;;
799                 "christian rock")        id=141 ;;
800                 "merengue")              id=142 ;;
801                 "salsa")                 id=143 ;;
802                 "thrash metal")          id=144 ;;
803                 "anime")                 id=145 ;;
804                 "jpop")                  id=146 ;;
805                 "synthpop")              id=147 ;;
806                 "rock/pop"|"rock / pop") id=148 ;;
807                 *)                       id=255 ;;
808         esac
809 echo ${id}
810 return 0
811 }
812
813 # do_tag [tracknumber]
814 # id3 tags a filename
815 # variables used:
816 # TRACKS, TRACKNAME, TRACKARTIST, TAGGER, TAGGEROPTS, VORBISCOMMENT, METAFLAC,
817 # COMMENT, DALBUM, DARTIST, CDYEAR, CDGENRE
818 do_tag ()
819 {
820         COMMENTOUTPUT="$(eval echo "${COMMENT}")"
821         if [ -z "$COMMENTOUTPUT" ]; then
822                 COMMENTOUTPUT="$(getcddbinfo TRACK-INFO)"
823         fi
824         CDDBDISCID=$(echo "$CDDBTRACKINFO" | cut -d' ' -f1)
825         run_command "" echo "Tagging track $1 of $TRACKS: $TRACKNAME..."
826         # If we want to start the tracks with a given number, we need to modify the
827         # TRACKNUM value before evaluation
828         if [ -n "$STARTTRACKNUMBERTAG" ] ; then
829                 gettracknum
830         fi
831         for OUTPUT in $(echo "$OUTPUTTYPE" | tr , \ )
832         do
833                 case "$OUTPUT" in
834                 mp3)
835                         # id3v2 v0.1.9 claims to have solved the -c bug, so we merge both id3 and id3v2
836                         GENREID=$(do_getgenreid "${CDGENRE}")
837                         # Set TPE2 in case we have a Various Artists rip.
838                         TPE2=""
839                         if [ "$VARIOUSARTISTS" = "y" ]; then
840                                 TPE2="Various"
841                         fi
842
843                         case "$ID3SYNTAX" in
844                                 id3)
845                                         run_command "tagtrack-$OUTPUT-$1" nice $ENCNICE \
846                                                 $TAGGER $TAGGEROPTS -c "$COMMENTOUTPUT" \
847                                                 -A "$DALBUM" -a "$TRACKARTIST" -t "$TRACKNAME" \
848                                                 -y "$CDYEAR" -g "$GENREID" \
849                                                 -T "${TRACKNUM:-$1}" \
850                                                 "${ABCDETEMPDIR}/track$1.$OUTPUT"
851                                         ;;
852                                 id3v2)
853                                         # FIXME # track numbers in mp3 come with 1/10, so we cannot
854                                         # happily substitute them with $TRACKNUM
855                                         run_command "tagtrack-$OUTPUT-$1" nice $ENCNICE \
856                                                 $TAGGER $TAGGEROPTS -c "$COMMENTOUTPUT" \
857                                                 -A "$DALBUM" -a "$TRACKARTIST" -t "$TRACKNAME" \
858                                                 -y "$CDYEAR" -g "$GENREID" \
859                                                 -T "${TRACKNUM:-$1}/$TRACKS" \
860                                                 ${TPE2:+--TPE2 "$TPE2"} \
861                                                 "${ABCDETEMPDIR}/track$1.$OUTPUT"
862                                         ;;
863                                 id3tag)
864                                         # FIXME # track numbers in mp3 come with 1/10, so we cannot
865                                         # happily substitute them with $TRACKNUM
866                                         run_command "tagtrack-$OUTPUT-$1" nice $ENCNICE \
867                                                 $TAGGER $TAGGEROPTS -c "$COMMENTOUTPUT" \
868                                                 -A "$DALBUM" -a "$TRACKARTIST" -s "$TRACKNAME" \
869                                                 -y "$CDYEAR" -g "$GENREID" \
870                                                 -t "${TRACKNUM:-$1}" ${TRACKNUM:+-T "$TRACKS"} \
871                                                 "${ABCDETEMPDIR}/track$1.$OUTPUT"
872                                         ;;
873                                 eyed3*)
874                                         # FIXME # track numbers in mp3 come with 1/10, so we cannot
875                                         # happily substitute them with $TRACKNUM
876                                         case "$ID3SYNTAX" in
877                                                 eyed3_06) addopts=( \
878                                                         ${ENCODING:+--set-encoding="$ENCODING"} \
879                                                         ${TPE2:+--set-text-frame=TPE2:"$TPE2"} \
880                                         # We set 'recording-date' so the date tag will show 
881                                         # in Audacious, vlc and friends...          Andrew.
882                                                         ${CDYEAR:+--set-text-frame="TDRC:$CDYEAR"} \
883                                                         ${COMMENTOUTPUT:+--comment=::"$COMMENTOUTPUT"} \
884                                                         );;
885                                                 *) addopts=( \
886                                                         ${ENCODING:+--encoding="$ENCODING"} \
887                                                         ${TPE2:+--text-frame=TPE2:"$TPE2"} \
888                                         # We set 'recording-date' so the date tag will show 
889                                         # in Audacious, vlc and friends...           Andrew.
890                                                         ${CDYEAR:+--text-frame="TDRC:$CDYEAR"} \
891                                                         ${COMMENTOUTPUT:+--comment "$COMMENTOUTPUT"} \
892                                                         );;
893                                         esac
894                                         run_command "tagtrack-$OUTPUT-$1" nice $ENCNICE $TAGGER $TAGGEROPTS \
895                                                 -A "$DALBUM" \
896                                                 -a "$TRACKARTIST" -t "$TRACKNAME" \
897                                                 -G "$GENREID" -n "${TRACKNUM:-$1}" \
898                                                 ${TRACKNUM:+-N "$TRACKS"} \
899                                                 "${addopts[@]}" \
900                                                 "${ABCDETEMPDIR}/track$1.$OUTPUT"
901                                         ;;
902                                 *)
903                                         log error "Internal error: ID3SYNTAX has an illegal value"
904                                         exit 1
905                                         ;;
906                         esac
907                         ;;
908                 vorbis|ogg)
909                         case "$OGGENCODERSYNTAX" in
910                                 vorbize|oggenc)
911                                         # vorbiscomment can't do in-place modification, mv the file first
912                                         if [ -f "${ABCDETEMPDIR}/track$1.$OGGOUTPUTCONTAINER" ] && \
913                                                    [ ! -f "${ABCDETEMPDIR}/track$1.uncommented.$OGGOUTPUTCONTAINER" ]; then
914                                                 mv "${ABCDETEMPDIR}/track$1.$OGGOUTPUTCONTAINER" \
915                                                    "${ABCDETEMPDIR}/track$1.uncommented.$OGGOUTPUTCONTAINER"
916                                         fi
917                                         (
918                                         # These are from
919                                         # https://www.xiph.org/vorbis/doc/v-comment.html
920
921                                         echo ARTIST="$TRACKARTIST"
922                                         echo ALBUM="$DALBUM"
923                                         echo TITLE="$TRACKNAME"
924                                         if [ -n "$CDYEAR" ]; then
925                                                 echo DATE="$CDYEAR"
926                                         fi
927                                         if [ -n "$CDGENRE" ]; then
928                                                 echo GENRE="$CDGENRE"
929                                         fi
930                                         echo TRACKNUMBER="${TRACKNUM:-$1}"
931                                         # TRACKTOTAL is not in the proposed, minimal list of standard field names from
932                                         # xiph.org: https://www.xiph.org/vorbis/doc/v-comment.html but is in common usage
933                                         # and read by mediainfo, ffprobe, vlc, Aqualung, ogg123, Foobar. And now abcde :)
934                                         # The tag is quietly ignored by  Audacious, MPlayer, mpv, XMMS....
935                                         echo TRACKTOTAL="${TRACKS}"
936                                         if [ -n "$DISCNUMBER" ]; then
937                                                 echo DISCNUMBER="$DISCNUMBER"
938                                         fi
939                                         echo CDDB="${CDDBDISCID}"
940                                         if [ "$(eval echo ${COMMENT})" != "" ]; then
941                                                 case "$COMMENTOUTPUT" in
942                                                         *=*) echo "$COMMENTOUTPUT";;
943                                                         *)   echo COMMENT="$COMMENTOUTPUT";;
944                                                 esac
945                                         fi
946                                         ) | run_command "tagtrack-$OUTPUT-$1" nice $ENCNICE \
947                                                 $VORBISCOMMENT $VORBISCOMMENTOPTS -w \
948                                                 "${ABCDETEMPDIR}/track$1.uncommented.$OGGOUTPUTCONTAINER" \
949                                                 "${ABCDETEMPDIR}/track$1.$OGGOUTPUTCONTAINER"
950                                         # Doublecheck that the commented file was created
951                                         # successfully before wiping the original
952                                         if [ -f "${ABCDETEMPDIR}/track$1.$OGGOUTPUTCONTAINER" ]; then
953                                                 rm -f "${ABCDETEMPDIR}/track$1.uncommented.$OGGOUTPUTCONTAINER"
954                                         else
955                                                 mv "${ABCDETEMPDIR}/track$1.uncommented.$OGGOUTPUTCONTAINER" \
956                                                    "${ABCDETEMPDIR}/track$1.$OGGOUTPUTCONTAINER"
957                                         fi
958                                         ;;
959                         esac
960                         ;;
961                 opus)
962                         run_command "tagtrack-$OUTPUT-$1" true
963                         ;;
964                 mka)
965                         run_command "tagtrack-$OUTPUT-$1" true
966                         ;;
967                 aiff)
968                         run_command "tagtrack-$OUTPUT-$1" true
969                         ;;
970                 flac)
971                         (
972                         echo ARTIST="$TRACKARTIST"
973                         echo ALBUM="$DALBUM"
974                         echo TITLE="$TRACKNAME"
975                         if [ -n "$CDYEAR" ]; then
976                                 echo DATE="$CDYEAR"
977                         fi
978                         if [ -n "$CDGENRE" ]; then
979                                 echo GENRE="$CDGENRE"
980                         fi
981                         echo TRACKNUMBER="${TRACKNUM:-$1}"
982                         # TRACKTOTAL is not in the proposed, minimal list of standard field names from
983                         # xiph.org: https://www.xiph.org/vorbis/doc/v-comment.html but is in common usage
984                         # and read by mediainfo, ffprobe, vlc, Aqualung, ogg123, Foobar. And now abcde :)
985                         # The tag is quietly ignored by  Audacious, MPlayer, mpv, XMMS....
986                         echo TRACKTOTAL="${TRACKS}"
987                         if [ -n "$DISCNUMBER" ]; then
988                                 echo DISCNUMBER="$DISCNUMBER"
989                         fi
990                         echo CDDB="${CDDBDISCID}"
991                         if [ -n "$(eval echo "${COMMENT}")" ]; then
992                                 case "$COMMENTOUTPUT" in
993                                         *=*) echo "$COMMENTOUTPUT";;
994                                         *)   echo COMMENT="$COMMENTOUTPUT";;
995                                 esac
996                         fi
997                         ) | run_command "tagtrack-$OUTPUT-$1" nice $ENCNICE $METAFLAC $METAFLACOPTS \
998                                                         ${IMPORTCUESHEET:+--import-cuesheet-from="${ABCDETEMPDIR}/$CUEFILE"} \
999                                                         --import-tags-from=- "${ABCDETEMPDIR}/track$1.$FLACOUTPUTCONTAINER"
1000                         ;;
1001                 spx)
1002                         run_command "tagtrack-$OUTPUT-$1" true
1003                         ;;
1004                 mpc)
1005                         run_command "tagtrack-$OUTPUT-$1" true
1006                         ;;
1007                 wv)
1008                         run_command "tagtrack-$OUTPUT-$1" true
1009                         ;;
1010                 ape)
1011                         # This tagging syntax is suitable for Robert Muth's application 'apetag', the Monkey's Audio 
1012                         # Console port (mac) used for encoding does not have the ability to tag.
1013                         run_command "tagtrack-$OUTPUT-$1" nice $ENCNICE "$APETAG" -i "${ABCDETEMPDIR}/track$1.ape" -m overwrite \
1014                                                 -p artist="$TRACKARTIST" -p album="$DALBUM" -p title="$TRACKNAME" -p track="${TRACKNUM:-$1}" \
1015                                                 -p year="$CDYEAR" -p genre="$CDGENRE" ${COMMENTOUTPUT:+-p comment="$COMMENTOUTPUT"} 
1016                         ;;
1017                 mp2)
1018                         # Using Mutagen's mid3v2 for tagging with id3v2.4.0. Interesting enough vlc, MPlayer and XMMS ignore
1019                         # these tags but they are read by Audacious, Xine, Aqualung, mediainfo, ffplay, ffprobe. FFmpeg does
1020                         # not currently tag mp2 audio so twolame and FFmpeg will both use mid3v2...
1021                         run_command "tagtrack-$OUTPUT-$1" nice $ENCNICE "$MID3V2" --verbose -A "$DALBUM" \
1022                                                 -a "$TRACKARTIST" -t "$TRACKNAME" -y "$CDYEAR" -g "$CDGENRE" \
1023                                                 -T "${TRACKNUM:-$1}/$TRACKS" ${TPE2:+--TPE2 "$TPE2"} \
1024                                                 ${COMMENTOUTPUT:+--comment="$COMMENTOUTPUT"} \
1025                                                 "${ABCDETEMPDIR}/track$1.mp2"
1026                         ;;
1027                 aac)
1028                         run_command "tagtrack-$OUTPUT-$1" true
1029                         ;;
1030                 m4a)
1031                         case "$AACENCODERSYNTAX" in
1032                                 fdkaac)
1033                                         # We will use inline tagging...
1034                                         run_command "tagtrack-$OUTPUT-$1" true
1035                                         ;;
1036                                 neroAacEnc)
1037                                         # Tag post encode with neroAacTag...
1038                                         run_command "tagtrack-$OUTPUT-$1" nice $ENCNICE "$NEROAACTAG" \
1039                                                                 "${ABCDETEMPDIR}/track$1.m4a" \
1040                                                                 -meta:artist="$TRACKARTIST" -meta:album="$DALBUM" \
1041                                                                 -meta:title="$TRACKNAME" -meta:track="${TRACKNUM:-$1}" \
1042                                                                 -meta:year="$CDYEAR" -meta:genre="$CDGENRE" -meta:comment="$COMMENT"
1043                                         ;;
1044                                 faac)
1045                                         run_command "tagtrack-$OUTPUT-$1" true
1046                                         ;;
1047                                 qaac)
1048                                         run_command "tagtrack-$OUTPUT-$1" true
1049                                         ;;
1050                                 fhgaacenc)
1051                                         # Tag post encode with AtomicParsley. Note that previous problems with seg fault when using
1052                                         # 'overWrite' cannot be reproduced with newer versions: https://bitbucket.org/wez/atomicparsley
1053                                         run_command "tagtrack-$OUTPUT-$1" nice $ENCNICE "$ATOMICPARSLEY" \
1054                                                                 "${ABCDETEMPDIR}/track$1.m4a" --artist="$TRACKARTIST" --album="$DALBUM" \
1055                                                                 --title="$TRACKNAME" --tracknum="${TRACKNUM:-$1}" \
1056                                                                 --year="$CDYEAR" --genre="$CDGENRE" --comment="$COMMENT" \
1057                                                                 $ATOMICPARSLEYOPTS --overWrite
1058                                         ;;
1059                                 ffmpeg)
1060                                         run_command "tagtrack-$OUTPUT-$1" true
1061                                 ;;
1062                         esac
1063                         ;;
1064                 tta)
1065                         # We use mid3v2 tagging for True Audio:
1066                         run_command "tagtrack-$OUTPUT-$1" nice $ENCNICE "$MID3V2" --verbose -A "$DALBUM" \
1067                                                 -a "$TRACKARTIST" -t "$TRACKNAME" -y "$CDYEAR" -g "$CDGENRE" \
1068                                                 -T "${TRACKNUM:-$1}/$TRACKS" ${TPE2:+--TPE2 "$TPE2"} \
1069                                                 ${COMMENTOUTPUT:+--comment="$COMMENTOUTPUT"} "${ABCDETEMPDIR}/track$1.tta"
1070                         ;;
1071                 wav)
1072                         run_command "tagtrack-$OUTPUT-$1" true
1073                         ;;
1074                 esac
1075         done
1076         if checkerrors "tagtrack-(.{3,6})-$1"; then :; else
1077                 run_command "tagtrack-$1" true
1078         fi
1079 }
1080
1081 # do_nogap_encode
1082 # variables used:
1083 # OUTPUTTYPE, {FOO}ENCODERSYNTAX, ENCNICE, ENCODER, ENCODEROPTS
1084 do_nogap_encode ()
1085 {
1086         # The commands here don't go through run_command because they're never
1087         # supposed to be silenced
1088         echo "Encoding gapless MP3 tracks: $TRACKQUEUE"
1089         for OUTPUT in $(echo "$OUTPUTTYPE" | tr , \ )
1090         do
1091                 case "$OUTPUT" in
1092                 mp3)
1093                         case "$MP3ENCODERSYNTAX" in
1094                         lame)
1095                                 (
1096                                         cd "${ABCDETEMPDIR}"
1097                                         TRACKFILES=
1098                                         for THISTRACKNUM in $TRACKQUEUE
1099                                         do
1100                                                 TRACKFILES="$TRACKFILES track$THISTRACKNUM.wav"
1101                                         done
1102                                         nice $ENCNICE $MP3ENCODER $MP3ENCODEROPTS --nogap $TRACKFILES
1103                                         RETURN=$?
1104                                         if [ "$RETURN" != "0" ]; then
1105                                                 echo "nogap-encode: $MP3ENCODER returned code $RETURN" >> "${ABCDETEMPDIR}/errors"
1106                                         else
1107                                                 for THISTRACKNUM in $TRACKQUEUE
1108                                                 do
1109                                                         run_command "encodetrack-$OUTPUT-$THISTRACKNUM" true
1110                                                 done
1111                                         fi
1112                                 )
1113                                 ;;
1114                         esac
1115                         ;;
1116                 esac
1117         done
1118         if checkerrors "nogap-encode"; then :; else
1119                 if [ ! "$KEEPWAVS" = "y" ] ; then
1120                         if [ ! "$KEEPWAVS" = "move" ] ; then
1121                                 rm -f "$IN"
1122                         fi
1123                 fi
1124         fi
1125         # Other encoders fall through to normal encoding as the tracks have not
1126         # been entered in the status file.
1127 }
1128
1129 # do_encode [tracknumber] [hostname]
1130 # If no hostname is specified, encode locally
1131 # variables used:
1132 # TRACKS, TRACKNAME, TRACKARTIST, DISTMP3, DISTMP3OPTS, {FOO}ENCODERSYNTAX, OUTPUTTYPE, ENCODEROPTS, 
1133 # DALBUM, DARTIST, ENCNICE, CDYEAR, CDGENRE, COMMENT
1134 do_encode ()
1135 {
1136         if [ "$USEPIPES" = "y" ]; then
1137                 case "$OUTPUT" in
1138                         mp3)
1139                                 TEMPARG="PIPE_$MP3ENCODERSYNTAX"
1140                                 ;;
1141                         vorbis|ogg)
1142                                 TEMPARG="PIPE_$OGGENCODERSYNTAX"
1143                                 ;;
1144                         opus)
1145                                 TEMPARG="PIPE_$OPUSENCODERSYNTAX"
1146                                 ;;
1147                         mka)
1148                                 TEMPARG="PIPE_$MKAENCODERSYNTAX"
1149                                 ;;
1150                         aiff)
1151                                 TEMPARG="PIPE_$AIFFENCODERSYNTAX"
1152                                 ;;
1153                         flac)
1154                                 TEMPARG="PIPE_$FLACENCODERSYNTAX"
1155                                 ;;
1156                         spx)
1157                                 TEMPARG="PIPE_$SPEEXENCODER"
1158                                 ;;
1159                         mpc)
1160                                 TEMPARG="PIPE_$MPCENCODER"
1161                                 ;;
1162                         wv)
1163                                 TEMPARG="PIPE_$WVENCODERSYNTAX"
1164                                 ;;
1165                         tta)
1166                                 TEMPARG="PIPE_$TTAENCODERSYNTAX"
1167                                 ;;
1168                         aac)
1169                                 TEMPARG="PIPE_$AACENCODERSYNTAX"
1170                                 ;;
1171                         m4a)
1172                                 TEMPARG="PIPE_$AACENCODERSYNTAX"
1173                                 ;;
1174                 esac
1175                 IN="$( eval echo "\$$TEMPARG" )"
1176         else
1177                 IN="${ABCDETEMPDIR}/track$1.wav"
1178         fi
1179         # We need IN to proceed, if we are not using pipes.
1180         if [ -s "$IN" ] || [ X"$USEPIPES" = "Xy" ] ; then
1181                 for TMPOUTPUT in $(echo "$OUTPUTTYPE" | tr , \ )
1182                 do
1183                         case "$TMPOUTPUT" in
1184                                 vorbis|ogg)
1185                                         OUTPUT=$OGGOUTPUTCONTAINER
1186                                         ;;
1187                                 opus)
1188                                         OUTPUT=$OPUSOUTPUTCONTAINER
1189                                         ;;
1190                                 mka)
1191                                         OUTPUT=$MKAOUTPUTCONTAINER
1192                                         ;;
1193                                 aiff)
1194                                         OUTPUT=$AIFFOUTPUTCONTAINER
1195                                         ;;
1196                                 flac)
1197                                         OUTPUT=$FLACOUTPUTCONTAINER
1198                                         ;;
1199                                 *)
1200                                         OUTPUT=$TMPOUTPUT
1201                                         ;;
1202                         esac
1203                         OUT="${ABCDETEMPDIR}/track$1.$OUTPUT"
1204                         if [ "$NOGAP" = "y" ] && checkstatus "encodetrack-$OUTPUT-$1" ; then
1205                                 continue
1206                         fi
1207                         if [ X"$USEPIPES" = "Xy" ]; then
1208                                 RUN_COMMAND=""
1209                                 # We need a way to store the creation of the files when using PIPES
1210                                 RUN_COMMAND_PIPES="run_command encodetrack-$OUTPUT-$1 true"
1211                                 # When piping it does not make sense to have a higher nice for
1212                                 # reading than for encoding, since it will be hold by the
1213                                 # encoding process. Setting an effective nice, to calm down a
1214                                 # bit the reading process.
1215                                 EFFECTIVE_NICE=$READNICE
1216                         else
1217                                 run_command "" echo "Encoding track $1 of $TRACKS: $TRACKNAME..."
1218                                 RUN_COMMAND="run_command encodetrack-$OUTPUT-$1"
1219                                 EFFECTIVE_NICE=$ENCNICE
1220                         fi
1221                         case "$OUTPUT" in
1222                         mp3)
1223                                 case "$2" in
1224                                 %local*%)
1225                                         case "$MP3ENCODERSYNTAX" in
1226                                         lame|gogo) $RUN_COMMAND nice $EFFECTIVE_NICE $MP3ENCODER $MP3ENCODEROPTS "$IN" "$OUT" ;;
1227                                         bladeenc) $RUN_COMMAND nice $EFFECTIVE_NICE $MP3ENCODER $MP3ENCODEROPTS -quit "$IN" "$OUT" ;;
1228                                         l3enc|xingmp3enc) $RUN_COMMAND nice $EFFECTIVE_NICE $MP3ENCODER "$IN" "$OUT" $MP3ENCODEROPTS ;;
1229                                         mp3enc) $RUN_COMMAND nice $EFFECTIVE_NICE $MP3ENCODER -if "$IN" -of "$OUT" $MP3ENCODEROPTS ;;
1230                                         esac
1231                                         ;;
1232                                 *)
1233                                         $RUN_COMMAND nice $DISTMP3NICE $DISTMP3 $DISTMP3OPTS "$2" "$IN" "$OUT" >/dev/null 2>&1
1234                                         ;;
1235                                 esac
1236                                 ;;
1237                         vorbis|ogg)
1238                                 case "$2" in
1239                                 %local*%)
1240                                         case "$OGGENCODERSYNTAX" in
1241                                         vorbize) $RUN_COMMAND nice $EFFECTIVE_NICE $OGGENCODER $OGGENCODEROPTS -w "$OUT" "$IN" ;;
1242                                         oggenc) $RUN_COMMAND nice $EFFECTIVE_NICE $OGGENCODER $OGGENCODEROPTS -o "$OUT" "$IN" ;;
1243                                         esac
1244                                         ;;
1245                                 *)
1246                                         $RUN_COMMAND nice $DISTMP3NICE $DISTMP3 $DISTMP3OPTS "$2" "$IN" "$OUT" >/dev/null 2>&1
1247                                         ;;
1248                                 esac
1249                                 ;;
1250                         opus)
1251                                 case "$2" in
1252                                 %local*%)
1253                                         case "$OPUSENCODERSYNTAX" in
1254                                         opusenc)
1255                                         # Tag the file at encode time, as it can't be done after encoding.
1256                                                 if [ "$DOTAG" = "y" ]; then
1257                                                         $RUN_COMMAND nice $EFFECTIVE_NICE $OPUSENCODER $OPUSENCODEROPTS \
1258                                                                                  --artist "$TRACKARTIST" --album "$DALBUM" --title "$TRACKNAME" \
1259                                                                                  --genre "$CDGENRE" --date "$CDYEAR" --comment TRACKNUMBER="$1" \
1260                                                                                  ${COMMENT:+--comment COMMENT="$COMMENT"} "$IN" "$OUT"
1261                                                 else
1262                                                         $RUN_COMMAND nice $EFFECTIVE_NICE $OPUSENCODER $OPUSENCODEROPTS "$IN" "$OUT"
1263                                                 fi
1264                                         ;;
1265                                         esac
1266                                         ;;
1267                                 *)
1268                                         $RUN_COMMAND nice $DISTMP3NICE $DISTMP3 $DISTMP3OPTS "$2" "$IN" "$OUT" >/dev/null 2>&1
1269                                         ;;
1270                                 esac
1271                                 ;;
1272                         mka)
1273                                 case "$MKAENCODERSYNTAX" in
1274                                 ffmpeg)
1275                                         if [ "$DOTAG" = "y" ]; then
1276                                                 $RUN_COMMAND nice $EFFECTIVE_NICE $MKAENCODER -i "$IN" $MKAENCODEROPTS \
1277                                                                          -metadata artist="$TRACKARTIST" -metadata album="$DALBUM" \
1278                                                                          -metadata title="$TRACKNAME" -metadata track="${TRACKNUM:-$1}" \
1279                                                                          -metadata date="$CDYEAR" -metadata genre="$CDGENRE" \
1280                                                                          -metadata comment="$COMMENT" "$OUT"
1281                                         else
1282                                                 $RUN_COMMAND nice $EFFECTIVE_NICE $MKAENCODER -i "$IN" $MKAENCODEROPTS "$OUT"
1283                                         fi
1284                                 ;;
1285                                 esac
1286                                 ;;
1287                         aiff)
1288                                 case "$AIFFENCODERSYNTAX" in
1289                                 ffmpeg)
1290                                         if [ "$DOTAG" = "y" ]; then
1291                                                 $RUN_COMMAND nice $EFFECTIVE_NICE $AIFFENCODER -i "$IN" $AIFFENCODEROPTS \
1292                                                                          -metadata artist="$TRACKARTIST" -metadata album="$DALBUM" \
1293                                                                          -metadata title="$TRACKNAME" -metadata track="${TRACKNUM:-$1}" \
1294                                                                          -metadata date="$CDYEAR" -metadata genre="$CDGENRE" \
1295                                                                          -metadata comment="$COMMENT" "$OUT"
1296                                         else
1297                                                 $RUN_COMMAND nice $EFFECTIVE_NICE $AIFFENCODER -i "$IN" $AIFFENCODEROPTS "$OUT"
1298                                         fi
1299                                 ;;
1300                                 esac
1301                                 ;;
1302                         flac)
1303                                 case "$2" in
1304                                 %local*%)
1305                                         case "$FLACENCODERSYNTAX" in
1306                                         flac) $RUN_COMMAND nice $EFFECTIVE_NICE $FLACENCODER -f $FLACENCODEROPTS -o "$OUT" "$IN" ;;
1307                                                 esac
1308                                                 ;;
1309                                         *)
1310                                                 vecho -n "DISTMP3:"
1311                                                 vecho "$DISTMP3 $DISTMP3OPTS $2 $IN $OUT >/dev/null 2>&1"
1312                                                 $RUN_COMMAND nice $DISTMP3NICE $DISTMP3 $DISTMP3OPTS "$2" "$IN" "$OUT" > /dev/null 2>&1
1313                                         ;;
1314                                 esac
1315                                 ;;
1316                         spx)
1317                                 if [ -n "$(eval echo "${COMMENT}")" ]; then
1318                                         case "$COMMENT" in
1319                                                 *=*) ;;
1320                                                 *)   COMMENT="COMMENT=$COMMENT" ;;
1321                                         esac
1322                                 fi
1323                                 # Tag the file at encode time, as it can't be done after encoding.
1324                                 if [ "$DOTAG" = "y" ]; then
1325                                         $RUN_COMMAND nice $EFFECTIVE_NICE $SPEEXENCODER $SPEEXENCODEROPTS \
1326                                                                  --author "$TRACKARTIST" --title "$TRACKNAME" \
1327                                                                  ${COMMENT:+--comment "$COMMENT"} "$IN" "$OUT"
1328                                 else
1329                                         $RUN_COMMAND nice $EFFECTIVE_NICE $SPEEXENCODER $SPEEXENCODEROPTS "$IN" "$OUT"
1330                                 fi
1331                                 ;;
1332                         mpc)
1333                                 # Tag the file inline at encode time.
1334                                 if [ "$DOTAG" = "y" ]; then
1335                                         $RUN_COMMAND nice $EFFECTIVE_NICE $MPCENCODER $MPCENCODEROPTS \
1336                                                                  --artist "$TRACKARTIST" --album "$DALBUM" \
1337                                                                  --title "$TRACKNAME" --track "$1" --genre "$CDGENRE" \
1338                                                                  --year "$CDYEAR" ${COMMENT:+--comment "$COMMENT"} "$IN" "$OUT"
1339                                 else
1340                                         $RUN_COMMAND nice $EFFECTIVE_NICE $MPCENCODER $MPCENCODEROPTS "$IN" "$OUT"
1341                                 fi
1342                                 ;;
1343                         tta)
1344                                 case "$TTAENCODERSYNTAX" in
1345                                 # tta is the newer version with a small syntax change...
1346                                         tta)
1347                                         $RUN_COMMAND nice $EFFECTIVE_NICE $TTAENCODER -e $TTAENCODEROPTS "$IN" "$OUT"
1348                                         ;;
1349                                         ttaenc)
1350                                         $RUN_COMMAND nice $EFFECTIVE_NICE $TTAENCODER -e $TTAENCODEROPTS "$IN" -o "$OUT"
1351                                         ;;
1352                                 esac
1353                                 ;;
1354                         wv)
1355                         case "$WVENCODERSYNTAX" in
1356                                 wavpack)
1357                                         if [ "$DOTAG" = "y" ]; then
1358                                                 $RUN_COMMAND nice $EFFECTIVE_NICE $WVENCODER $WVENCODEROPTS \
1359                                                                          -w Artist="$TRACKARTIST" -w Album="$DALBUM" \
1360                                                                          -w Title="$TRACKNAME" -w Track="$1" -w Genre="$CDGENRE" \
1361                                                                          -w Year="$CDYEAR" ${COMMENT:+-w Comment="$COMMENT"} "$IN" -o "$OUT"
1362                                         else
1363                                                 $RUN_COMMAND nice $EFFECTIVE_NICE $WVENCODER $WVENCODEROPTS "$IN" -o "$OUT"
1364                                         fi
1365                                 ;;
1366                                 ffmpeg)
1367                                         if [ "$DOTAG" = "y" ]; then
1368                                                 $RUN_COMMAND nice $EFFECTIVE_NICE $WVENCODER -i "$IN" $WVENCODEROPTS \
1369                                                                          -metadata artist="$TRACKARTIST" \
1370                                                                          -metadata album="$DALBUM" -metadata title="$TRACKNAME" \
1371                                                                          -metadata track="${TRACKNUM:-$1}" -metadata date="$CDYEAR" \
1372                                                                          -metadata genre="$CDGENRE" -metadata comment="$COMMENT" "$OUT" 
1373                                         else 
1374                                                 $RUN_COMMAND nice $EFFECTIVE_NICE $WVENCODER -i "$IN" $WVENCODEROPTS "$OUT"
1375                                         fi
1376                                 ;;
1377                         esac
1378                                 ;;
1379                         ape)
1380                                 $RUN_COMMAND nice $EFFECTIVE_NICE $APENCODER "$IN" "$OUT" $APENCODEROPTS
1381                                 ;;
1382                         mp2)
1383                                 case "$MP2ENCODERSYNTAX" in
1384                                         twolame)
1385                                                 $RUN_COMMAND nice $EFFECTIVE_NICE $MP2ENCODER $MP2ENCODEROPTS "$IN" "$OUT"
1386                                                 ;;
1387                                         ffmpeg)
1388                                                 $RUN_COMMAND nice $EFFECTIVE_NICE $MP2ENCODER -i "$IN" $MP2ENCODEROPTS "$OUT" 
1389                                                 ;;
1390                                 esac
1391                                 ;;
1392                         aac)
1393                                 # aac container is only used to catch faac encoded files where faac 
1394                                 # is compiled without mp4 support (with libmp4v2).
1395                                 $RUN_COMMAND nice $EFFECTIVE_NICE $AACENCODER $AACENCODEROPTS -o "$OUT" "$IN"
1396                                 ;;
1397                         m4a)
1398                                 case "$AACENCODERSYNTAX" in
1399                                         faac)
1400                                                 if [ "$DOTAG" = "y" ]; then
1401                                                         $RUN_COMMAND nice $EFFECTIVE_NICE $AACENCODER $AACENCODEROPTS  \
1402                                                                                  --artist "$TRACKARTIST" --album "$DALBUM" \
1403                                                                                  --title "$TRACKNAME" --track "${TRACKNUM:-$1}" \
1404                                                                                  --year "$CDYEAR" --genre "$CDGENRE" --comment "$COMMENT" -o "$OUT" "$IN"
1405                                                 else 
1406                                                         $RUN_COMMAND nice $EFFECTIVE_NICE $AACENCODER $AACENCODEROPTS -o "$OUT" "$IN"   
1407                                                 fi
1408                                                 ;;
1409                                         neroAacEnc)
1410                                                 $RUN_COMMAND nice $EFFECTIVE_NICE $AACENCODER $AACENCODEROPTS -if "$IN" -of "$OUT"
1411                                                 ;;
1412                                         fdkaac)      
1413                                                 if [ "$DOTAG" = "y" ]; then
1414                                                         $RUN_COMMAND nice $EFFECTIVE_NICE $AACENCODER $AACENCODEROPTS \
1415                                                                                  --artist "$TRACKARTIST" --album "$DALBUM" \
1416                                                                                  --title "$TRACKNAME" --track "$1" --genre "$CDGENRE" \
1417                                                                                  --date "$CDYEAR" --comment "$COMMENT" "$IN" -o "$OUT"
1418                                                 else
1419                                                         $RUN_COMMAND nice $EFFECTIVE_NICE $AACENCODER $AACENCODEROPTS "$IN" -o "$OUT"
1420                                                 fi
1421                                                 ;;
1422                                         qaac)
1423                                                 if [ "$DOTAG" = "y" ]; then
1424                                                         $RUN_COMMAND nice $EFFECTIVE_NICE $WINE $AACENCODER $AACENCODEROPTS \
1425                                                                                  --artist "$TRACKARTIST" --album "$DALBUM" \
1426                                                                                  --title "$TRACKNAME" --track "${TRACKNUM:-$1}" \
1427                                                                                  --date "$CDYEAR" --genre "$CDGENRE" --comment "$COMMENT" -o "$OUT" "$IN"
1428                                                 else 
1429                                                         $RUN_COMMAND nice $EFFECTIVE_NICE $WINE $AACENCODER $AACENCODEROPTS -o "$OUT" "$IN"
1430                                                 fi
1431                                                 ;;
1432                                         fhgaacenc)
1433                                                 $RUN_COMMAND nice $EFFECTIVE_NICE $WINE $AACENCODER $AACENCODEROPTS "$IN" "$OUT"
1434                                                 ;;
1435                                         ffmpeg)
1436                                                 if [ "$DOTAG" = "y" ]; then
1437                                                         $RUN_COMMAND nice $EFFECTIVE_NICE $AACENCODER -i "$IN" \
1438                                                                                  $AACENCODEROPTS -metadata artist="$TRACKARTIST" \
1439                                                                                  -metadata album="$DALBUM" -metadata title="$TRACKNAME" \
1440                                                                                  -metadata track="${TRACKNUM:-$1}" -metadata date="$CDYEAR" \
1441                                                                                  -metadata genre="$CDGENRE" -metadata comment="$COMMENT" "$OUT" 
1442                                                 else 
1443                                                         $RUN_COMMAND nice $EFFECTIVE_NICE $AACENCODER -i "$IN"  $AACENCODEROPTS "$OUT"
1444                                                 fi
1445                                                 ;;
1446                                         esac
1447                                 ;;
1448                         wav)
1449                                 # In case of wav output we need nothing. Just keep the wavs.
1450                                 # But we need the following to allow full logging and subsequent 
1451                                 # successful cleaning of ${ABCDETEMPDIR}.
1452                                 echo "encodetrack-$OUTPUT-$UTRACKNUM" >> "${ABCDETEMPDIR}/status"
1453                                 ;;
1454                         esac
1455                         $RUN_COMMAND_PIPES
1456                 done
1457                 # Only remove .wav if the encoding succeeded
1458                 if checkerrors "encodetrack-(.{3,6})-$1"; then :; else
1459                         run_command "encodetrack-$1" true
1460                         if [ ! "$KEEPWAVS" = "y" ] ; then
1461                                 if [ ! "$KEEPWAVS" = "move" ] ; then
1462                                         rm -f "$IN"
1463                                 fi
1464                         fi
1465                 fi
1466         else
1467                 run_command "" echo "HEH! The file we were about to encode disappeared:"
1468                 run_command "" echo ">> $IN"
1469                 run_command "encodetrack-$1" false
1470         fi
1471 }
1472
1473 # do_preprocess [tracknumber]
1474 # variables used:
1475 # TRACKS, TRACKNAME, TRACKARTIST, DISTMP3, DISTMP3OPTS, {FOO}ENCODERSYNTAX,
1476 # OUTPUTTYPE, ENCODEROPTS, DALBUM, DARTIST, ENCNICE, CDYEAR, CDGENRE, COMMENT
1477 #do_preprocess ()
1478 #{
1479 #       IN="${ABCDETEMPDIR}/track$1.wav"
1480 #       # We need IN to proceed.
1481 #       if [ -s "$IN" ] ; then
1482 #               for OUTPUT in $(echo $OUTPUTTYPE | tr , \ )
1483 #               do
1484 #                       #OUT="${ABCDETEMPDIR}/track$1.$OUTPUT"
1485 #                       run_command "" echo "Pre-processing track $1 of $TRACKS..."
1486 #                       case "$POSTPROCESSFORMAT" in
1487 #                       all|wav*)
1488 #                               run_command "preprocess-$OUTPUT-$1" nice $PRENICE $WAV_PRE $IF $OF ;;
1489 #                       mp3)
1490 #                               run_command "preprocess-$OUTPUT-$1" nice $PRENICE $MP3_PRE $IF $OF ;;
1491 #                       ogg)
1492 #                               run_command "preprocess-$OUTPUT-$1" nice $PRENICE $OGG_PRE $IF $OF ;;
1493 #                       flac)
1494 #                               run_command "preprocess-$OUTPUT-$1" nice $PRENICE $FLAC_PRE $IF $OF ;;
1495 #                       spx)
1496 #                               run_command "preprocess-$OUTPUT-$1" nice $PRENICE $SPX_PRE $IF $OF ;;
1497 #                       esac
1498 #               done
1499 #               # Only remove .wav if the encoding succeeded
1500 #               if checkerrors "preprocess-(.{3,4})-$1"; then
1501 #                       run_command "preprocess-$1" false
1502 #               else
1503 #                       run_command "preprocess-$1" true
1504 #               fi
1505 #       else
1506 #               if [ "$(checkstatus encode-output)" = "loud" ]; then
1507 #                       echo "HEH! The file we were about to pre-process disappeared:"
1508 #                       echo ">> $IN"
1509 #               fi
1510 #               run_command "preprocess-$1" false
1511 #       fi
1512 #}
1513
1514
1515 # do_postprocess [tracknumber]
1516 # variables used:
1517 # TRACKS, TRACKNAME, TRACKARTIST, DISTMP3, DISTMP3OPTS, {FOO}ENCODERSYNTAX, OUTPUTTYPE, ENCODEROPTS, 
1518 # DALBUM, DARTIST, ENCNICE, CDYEAR, CDGENRE, COMMENT
1519 #do_postprocess ()
1520 #{
1521 #       for POSTPROCESSFORMAT in $(echo $POSTPROCESSFORMATS | tr , \ )
1522 #       do
1523 #               IN="${ABCDETEMPDIR}/track$1.$POSTPROCESSFORMAT"
1524 #               # We need IN to proceed.
1525 #               if [ -s "$IN" ] ; then
1526 #                       #OUT="${ABCDETEMPDIR}/track$1.$OUTPUT"
1527 #                       run_command "" echo "Post-processing track $1 of $TRACKS..."
1528 #                       case "$POSTPROCESSFORMAT" in
1529 #                               mp3)
1530 #                                       run_command "postprocess-$OUTPUT-$1" nice $POSTNICE $MP3_POST $IF $OF ;;
1531 #                               ogg)
1532 #                                       run_command "postprocess-$OUTPUT-$1" nice $POSTNICE $OGG_POST $IF $OF ;;
1533 #                               flac)
1534 #                                       run_command "postprocess-$OUTPUT-$1" nice $POSTNICE $FLAC_POST $IF $OF ;;
1535 #                               spx)
1536 #                                       run_command "postprocess-$OUTPUT-$1" nice $POSTNICE $SPX_POST $IF $OF ;;
1537 #                       esac
1538 #                       # Only remove .wav if the encoding succeeded
1539 #                       if checkerrors "postprocess-(.{3,4})-$1"; then
1540 #                               run_command "postprocess-$1" false
1541 #                       else
1542 #                               run_command "postprocess-$1" true
1543 #                       fi
1544 #               else
1545 #                       if [ "$(checkstatus encode-output)" = "loud" ]; then
1546 #                               echo "HEH! The file we were about to post-process disappeared:"
1547 #                               echo ">> $IN"
1548 #                       fi
1549 #                       run_command "postprocess-$1" false
1550 #               fi
1551 #       done
1552 #}
1553
1554 # do_single_gain
1555 # variables used:
1556 # FIXME #
1557 do_single_gain ()
1558 {
1559 :
1560 }
1561
1562 # do_batch_gain
1563 # variables used:
1564 # MP3GAIN, MP3GAINOPTS, VORBISGAIN, VORBISGAINOPTS, MPCGAIN
1565 # FIXME #
1566 do_batch_gain ()
1567 {
1568         # The commands here don't go through run_command because they're never supposed to be silenced
1569         echo "Batch analizing gain in tracks: $TRACKQUEUE"
1570         (
1571         cd "${ABCDETEMPDIR}"
1572         BLURB=
1573         TRACKFILES=
1574         for UTRACKNUM in $TRACKQUEUE
1575         do
1576                 TRACKFILES="$TRACKFILES track$UTRACKNUM.mp3"
1577         done
1578         # FIXME # Hard-coded batch option!
1579         $NORMALIZER -b $NORMALIZEROPTS $TRACKFILES
1580         RETURN=$?
1581         if [ "$RETURN" != "0" ]; then
1582                 echo "batch-normalize: $NORMALIZER returned code $RETURN" >> "${ABCDETEMPDIR}/errors"
1583         else
1584                 for UTRACKNUM in $TRACKQUEUE
1585                 do
1586                         echo "normalizetrack-$UTRACKNUM" >> "${ABCDETEMPDIR}/status"
1587                 done
1588         fi
1589         )
1590 }
1591
1592 # do_batch_normalize
1593 # variables used:
1594 # NORMALIZER, NORMALIZEROPTS
1595 do_batch_normalize ()
1596 {
1597         # The commands here don't go through run_command because they're never supposed to be silenced
1598         echo "Batch normalizing tracks: $TRACKQUEUE"
1599         (
1600         cd "${ABCDETEMPDIR}"
1601         BLURB=
1602         TRACKFILES=
1603         for UTRACKNUM in $TRACKQUEUE
1604         do
1605                 TRACKFILES="$TRACKFILES track$UTRACKNUM.wav"
1606         done
1607         # XXX: Hard-coded batch option!
1608         $NORMALIZER -b $NORMALIZEROPTS $TRACKFILES
1609         RETURN=$?
1610         if [ "$RETURN" != "0" ]; then
1611                 echo "batch-normalize: $NORMALIZER returned code $RETURN" >> "${ABCDETEMPDIR}/errors"
1612         else
1613                 for UTRACKNUM in $TRACKQUEUE
1614                 do
1615                         echo "normalizetrack-$UTRACKNUM" >> "${ABCDETEMPDIR}/status"
1616                 done
1617         fi
1618         )
1619 }
1620
1621 # do_normalize [tracknumber]
1622 # variables used:
1623 # TRACKS, TRACKNAME, NORMALIZER, NORMALIZEROPTS
1624 do_normalize ()
1625 {
1626         IN="${ABCDETEMPDIR}/track$1.wav"
1627         if [ -e "$IN" ] ; then
1628                 run_command "" echo "Normalizing track $1 of $TRACKS: $TRACKNAME..."
1629                 run_command "normalizetrack-$1" $NORMALIZER $NORMALIZEROPTS "$IN"
1630         else
1631                 if [ "$(checkstatus encode-output)" = "loud" ]; then
1632                         echo "HEH! The file we were about to normalize disappeared:"
1633                         echo ">> $IN"
1634                 fi
1635                 run_command "normalizetrack-$1" false "File $IN was not found"
1636         fi
1637 }
1638
1639 # do_move [tracknumber]
1640 # Deduces the outfile from environment variables
1641 # Creates directory if necessary
1642 # variables used:
1643 # TRACKNUM, TRACKNAME, TRACKARTIST, DALBUM, OUTPUTFORMAT, CDGENRE, CDYEAR
1644 do_move ()
1645 {
1646         for TMPOUTPUT in $(echo "$OUTPUTTYPE" | tr , \ )
1647         do
1648                 # For now, set OUTPUT as TMPOUTPUT, and then change it once we have
1649                 # defined the OUTPUTFILE:
1650                 OUTPUT="$TMPOUTPUT"
1651
1652                 # Create ALBUMFILE, ARTISTFILE, TRACKFILE
1653                 ALBUMFILE="$(mungealbumname "$DALBUM")"
1654                 ARTISTFILE="$(mungeartistname "$TRACKARTIST")"
1655                 TRACKFILE="$(mungetrackname "$TRACKNAME")"
1656                 GENRE="$(mungegenre "$GENRE")"
1657                 YEAR=${CDYEAR:-$CDYEAR}
1658                 # If we want to start the tracks with a given number, we need to modify
1659                 # the TRACKNUM value before evaluation
1660                 gettracknum
1661                 # Supported variables for OUTPUTFORMAT are GENRE, YEAR, ALBUMFILE,
1662                 # ARTISTFILE, TRACKFILE, and TRACKNUM.
1663                 if [ "$ONETRACK" = "y" ]; then
1664                         if [ "$VARIOUSARTISTS" = "y" ]; then
1665                                 OUTPUTFILE="$(eval echo \""$VAONETRACKOUTPUTFORMAT"\")"
1666                         else
1667                                 OUTPUTFILE="$(eval echo \""$ONETRACKOUTPUTFORMAT"\")"
1668                         fi
1669                 else
1670                         if [ "$VARIOUSARTISTS" = "y" ]; then
1671                                 OUTPUTFILE="$(eval echo \""$VAOUTPUTFORMAT"\")"
1672                         else
1673                                 OUTPUTFILE="$(eval echo \""$OUTPUTFORMAT"\")"
1674                         fi
1675                 fi
1676                 if checkerrors "tagtrack-$OUTPUT-$1"; then :; else
1677                         # Once we know the specific output was successful, we can change
1678                         # the OUTPUT to the value containing the container
1679                         case $TMPOUTPUT in
1680                                 vorbis|ogg)
1681                                         OUTPUT=$OGGOUTPUTCONTAINER
1682                                         ;;
1683                                 opus)
1684                                         OUTPUT=$OPUSOUTPUTCONTAINER
1685                                         ;;
1686                                 mka)
1687                                         OUTPUT=$MKAOUTPUTCONTAINER
1688                                         ;;
1689                                 aiff)
1690                                         OUTPUT=$AIFFOUTPUTCONTAINER
1691                                         ;;
1692                                 flac)
1693                                         OUTPUT=$FLACOUTPUTCONTAINER
1694                                         ;;
1695                                 *)
1696                                         OUTPUT=$TMPOUTPUT
1697                                         ;;
1698                         esac
1699                         # Check that the directory for OUTPUTFILE exists, if it doesn't, create it
1700                         OUTPUTFILEDIR="$(dirname "$OUTPUTDIR/$OUTPUTFILE")"
1701                         case $OUTPUT in
1702                                 wav)
1703                                         if [ "$DOCLEAN" != "y" ] && [ "$FORCE" != "y" ]; then
1704                                                 # FIXME # introduce warnings?
1705                                                 :
1706                                         else
1707                                                 # mkdir -p shouldn't return an error if the directory already exists
1708                                                 mkdir -p "$OUTPUTFILEDIR"
1709                                                 run_command "movetrack-$1" mv "${ABCDETEMPDIR}/track$1.$OUTPUT" "$OUTPUTDIR/$OUTPUTFILE.$OUTPUT"
1710                                                 if checkstatus "movetrack-output-$OUTPUT"; then :; else
1711                                                         run_command "movetrack-output-$OUTPUT" true
1712                                                 fi
1713                                         fi
1714                                         ;;
1715                                 *)
1716                                         # mkdir -p shouldn't return an error if the directory already exists
1717                                         mkdir -p "$OUTPUTFILEDIR"
1718                                         run_command "movetrack-$1" mv "${ABCDETEMPDIR}/track$1.$OUTPUT" "$OUTPUTDIR/$OUTPUTFILE.$OUTPUT"
1719                                         if checkstatus "movetrack-output-$OUTPUT"; then :; else
1720                                                 run_command "movetrack-output-$OUTPUT" true
1721                                         fi
1722                                         ;;
1723                         esac
1724                         # Lets move the cue file
1725                         if CUEFILE=$(checkstatus cuefile) >/dev/null ; then
1726                                 if [ -r "${ABCDETEMPDIR}/$CUEFILE" ]; then
1727                                         if checkstatus "movecue-$OUTPUT"; then :; else
1728                                                 # Silence the Copying output since it overlaps with encoding processes...
1729                                                 #run_command "" vecho "Copying cue file to its destination directory..."
1730                                                 if checkstatus onetrack >/dev/null ; then
1731                                                         case $OUTPUT in
1732                                                                 wav)
1733                                                                         if [ "$DOCLEAN" != "y" ] && [ "$FORCE" != "y" ]; then
1734                                                                                 # We dont have the dir, since it was not created before.
1735                                                                                 :
1736                                                                         else
1737                                                                                 run_command "movecue-$OUTPUT" cp "${ABCDETEMPDIR}/$CUEFILE" "$OUTPUTDIR/$OUTPUTFILE.cue"
1738                                                                         fi
1739                                                                         ;;
1740                                                                 # NOTE: Creating a cue file with the 3-char-extension files is to comply with
1741                                                                 # http://brianvictor.tripod.com/mp3cue.htm#details
1742                                                                 [a-z0-9][a-z0-9][a-z0-9])
1743                                                                         run_command "movecue-$OUTPUT" cp "${ABCDETEMPDIR}/$CUEFILE" "$OUTPUTDIR/$OUTPUTFILE.cue"
1744                                                                         ;;
1745                                                                 *)
1746                                                                         run_command "movecue-$OUTPUT" cp "${ABCDETEMPDIR}/$CUEFILE" "$OUTPUTDIR/$OUTPUTFILE.$OUTPUT.cue"
1747                                                                         ;;
1748                                                         esac
1749                                                 else
1750                                                         run_command "movecue-$OUTPUT" cp "${ABCDETEMPDIR}/$CUEFILE" "$OUTPUTFILEDIR/$CUEFILE"
1751                                                 fi
1752                                                 echo "movecue-$OUTPUT" >> "${ABCDETEMPDIR}/status"
1753                                         fi
1754                                 fi
1755                         fi
1756                 fi
1757         done
1758 }
1759
1760 # do_playlist
1761 # Create the playlist if wanted
1762 # Variables used:
1763 # PLAYLISTFORMAT, PLAYLISTDATAPREFIX, VAPLAYLISTFORMAT, VAPLAYLISTDATAPREFIX,
1764 # VARIOUSARTISTS, OUTPUTDIR
1765 do_playlist ()
1766 {
1767         for TMPOUTPUT in $(echo "$OUTPUTTYPE" | tr , \ )
1768         do
1769                 case $TMPOUTPUT in
1770                         vorbis|ogg)
1771                                 OUTPUT=$OGGOUTPUTCONTAINER
1772                                 ;;
1773                         opus)
1774                                 OUTPUT=$OPUSOUTPUTCONTAINER
1775                                 ;;
1776                         mka)
1777                                 OUTPUT=$MKAOUTPUTCONTAINER
1778                                 ;;
1779                         aiff)
1780                                 OUTPUT=$AIFFOUTPUTCONTAINER
1781                                 ;;
1782                         flac)
1783                                 OUTPUT=$FLACOUTPUTCONTAINER
1784                                 ;;
1785                         *)
1786                                 OUTPUT=$TMPOUTPUT
1787                                 ;;
1788                 esac
1789                 # Create a playlist file for the playlist data to go into.
1790                 # We used to wipe it out if it existed. Now we request permission if interactive.
1791                 for LASTTRACK in $TRACKQUEUE; do :; done
1792                 ALBUMFILE="$(mungealbumname "$DALBUM")"
1793                 ARTISTFILE="$(mungeartistname "$DARTIST")"
1794                 GENRE="$(mungegenre "$GENRE")"
1795                 YEAR=${CDYEAR:-$CDYEAR}
1796                 if [ "$VARIOUSARTISTS" = "y" ] ; then
1797                         PLAYLISTFILE="$(eval echo "$VAPLAYLISTFORMAT")"
1798                 else
1799                         PLAYLISTFILE="$(eval echo "$PLAYLISTFORMAT")"
1800                 fi
1801                 FINALPLAYLISTDIR="$(dirname "$OUTPUTDIR/$PLAYLISTFILE")"
1802                 mkdir -p "$FINALPLAYLISTDIR"
1803                 if [ -s "$OUTPUTDIR/$PLAYLISTFILE" ]; then
1804                         echo -n "Erase, Append to, or Keep the existing playlist file? [e/a/k] (e): " >&2
1805                         if [ "$INTERACTIVE" = "y" ]; then
1806                                 while [ "$DONE" != "y" ]; do
1807                                         read ERASEPLAYLIST
1808                                         case $ERASEPLAYLIST in
1809                                                 e|E|a|A|k|K) DONE=y ;;
1810                                                 "") ERASEPLAYLIST=e ; DONE=y ;;
1811                                                 *) ;;
1812                                         esac
1813                                 done
1814                         else
1815                                 echo e >&2
1816                                 ERASEPLAYLIST=e
1817                         fi
1818                         # Once we erase the playlist, we use append to create the new one.
1819                         [ "$ERASEPLAYLIST" = "e" ] || [ "$ERASEPLAYLIST" = "E" ] && rm -f "$OUTPUTDIR/$PLAYLISTFILE" && ERASEPLAYLIST=a
1820                 else
1821                         # The playlist does not exist, so we can safelly use append to create the new list
1822                         ERASEPLAYLIST=a
1823                 fi
1824                 if [ "$ERASEPLAYLIST" = "a" ] || [ "$ERASEPLAYLIST" = "A" ]; then
1825                         touch "$OUTPUTDIR/$PLAYLISTFILE"
1826                         for UTRACKNUM in $TRACKQUEUE
1827                         do
1828                                 # Shares some code with do_move since the filenames have to match
1829                                 CDDBTRACKNUM=$(($UTRACKNUM - 1))
1830                                 getcddbinfo TRACKNAME
1831                                 splitvarious
1832                                 TRACKFILE="$(mungetrackname "$TRACKNAME")"
1833                                 ARTISTFILE="$(mungeartistname "$TRACKARTIST")"
1834                                 ALBUMFILE="$(mungealbumname "$DALBUM")"
1835                                 # If we want to start the tracks with a given number, we need to modify the
1836                                 # TRACKNUM value before evaluation
1837                                 gettracknum
1838                                 if [ "$VARIOUSARTISTS" = "y" ]; then
1839                                         OUTPUTFILE="$(eval echo \""$VAOUTPUTFORMAT\"")"
1840                                 else
1841                                         OUTPUTFILE="$(eval echo \""$OUTPUTFORMAT\"")"
1842                                 fi
1843                                 if [ "$VARIOUSARTISTS" = "y" ]; then
1844                                         if [ "$VAPLAYLISTDATAPREFIX" ] ; then
1845                                                 echo "${VAPLAYLISTDATAPREFIX}$OUTPUTFILE.$OUTPUT" >> "$OUTPUTDIR/$PLAYLISTFILE"
1846                                         else
1847                                                 relpath "$PLAYLISTFILE", "$OUTPUTFILE.$OUTPUT" >> "$OUTPUTDIR/$PLAYLISTFILE"
1848                                         fi
1849                                 else
1850                                         if [ "$PLAYLISTDATAPREFIX" ]; then
1851                                                 echo "${PLAYLISTDATAPREFIX}$OUTPUTFILE.$OUTPUT" >> "$OUTPUTDIR/$PLAYLISTFILE"
1852                                         else
1853                                                 relpath "$PLAYLISTFILE", "$OUTPUTFILE.$OUTPUT" >> "$OUTPUTDIR/$PLAYLISTFILE"
1854                                         fi
1855                                 fi
1856                         done
1857                 fi
1858                 ## this will convert the playlist to have CRLF line-endings, if specified
1859                 ## (some hardware players insist on CRLF endings)
1860                 if [ "$DOSPLAYLIST" = "y" ]; then
1861                         awk '{sub("\r$",""); printf "%s\r\n", $0}' "$OUTPUTDIR/$PLAYLISTFILE" > "${ABCDETEMPDIR}/PLAYLISTFILE.tmp"
1862 #                       mv -f "${ABCDETEMPDIR}/PLAYLISTFILE.tmp" "$OUTPUTDIR/$PLAYLISTFILE"
1863                         cat "${ABCDETEMPDIR}/PLAYLISTFILE.tmp" | sed 's/\//\\/' > "$OUTPUTDIR/$PLAYLISTFILE"
1864                 fi
1865                 echo "playlistcomplete" >> "${ABCDETEMPDIR}/status"
1866         done
1867 }
1868
1869 # abcde.cue2discid
1870 # This function reads a cuefile on stdin and writes an extended
1871 # cddb query on stdout.  Any PREGAP for track 1 is properly
1872 # handled, although cue files embedded in FLAC files do not
1873 # appear to properly store the PREGAP setting. :(
1874 abcde.cue2discid () {
1875
1876         cddb_sum () {
1877                 val=$1
1878                 ret=0
1879                 while [ "$val" -gt 0 ] ; do
1880                         ret=$(( "$ret" + ( "$val" % 10) ))
1881                         val=$(( "$val" / 10 ))
1882                 done
1883                 echo "$ret"
1884         }
1885
1886         msf2lba () {
1887                 OIFS="$IFS"
1888                 IFS=":"
1889                 set -- "$1"
1890                 IFS="$OIFS"
1891                 local first second third
1892                 first=$(( $1 + 0 ))
1893                 second=$(( $2 + 0 ))
1894                 third=$(( $3 + 0 ))
1895
1896                 echo $(( ((("$first" * 60) + "$second") * 75) + "$third" ))
1897         }
1898
1899         OFFSET=150
1900         PREGAP=0
1901         LEADOUT=0
1902         LEADIN=88200
1903         i=0
1904         N=0
1905
1906         while read line ; do
1907                 set -- "$line"
1908                 case "$1" in
1909                 TRACK)  i=$(( i + 1 ))
1910                         ;;
1911                 INDEX)  if [ "$2" -eq 1 ] ; then
1912                                 LBA=$(msf2lba "$3")
1913                                 START=$(( "$LBA" + "$PREGAP" + "$OFFSET" ))
1914                                 eval TRACK$i=$START
1915                                 X=$(cddb_sum $(( "$START" / 75 )) )
1916                                 N=$(( "$N" + "$X" ))
1917                         fi
1918                         ;;
1919                 PREGAP) PREGAP=$(msf2lba "$2")
1920                         ;;
1921                 REM)    case "$2" in
1922                         FLAC__lead-out)
1923                                 LEADOUT=$(( "$4" / 588 ))
1924                                 ;;
1925                         FLAC__lead-in)
1926                                 LEADIN=$(( "$3" / 588 ))
1927                                 ;;
1928                         esac
1929                         ;;
1930                 esac
1931
1932         done
1933
1934         TRACKS="$i"
1935         LEADOUT=$(( "$LEADOUT" + "$LEADIN" ))
1936
1937         LENGTH=$(( "$LEADOUT"/75 - "$TRACK1"/75 ))
1938         CDDBDISCID=$(( ( "$N" % 255 ) * 2**24 | "$LENGTH" * 2**8 | "$TRACKS" ))
1939         printf "%08x %i" "${CDDBDISCID}" "$TRACKS"
1940
1941         j=1
1942         while [ $j -le "$TRACKS" ] ; do
1943                 eval echo -n "\" \$TRACK$j\""
1944                 j=$(( $j + 1))
1945         done
1946         echo " $(( $LEADOUT / 75 ))"
1947 }
1948
1949 # abcde.mkcue
1950 # abcde.mkcue [--wholedisk]
1951 # This creates a cuefile directly from the extended discid information
1952 # The --wholedisk option controls whether we're ripping data from the
1953 # start of track one or from the start of the disk (usually, but not
1954 # always the same thing!)
1955 #
1956 # Track one leadin/pregap (if any) handeling:
1957 # --wholedisk specified:
1958 #   TRACK 01 AUDIO
1959 #     INDEX 00 00:00:00
1960 #     INDEX 01 <pregap value>
1961 #   Remaining track index values unchanged from disc TOC
1962 #
1963 # --wholedisk not specified
1964 #   TRACK 01 AUDIO
1965 #     PREGAP <pregap value>
1966 #     INDEX 01 00:00:00
1967 #   Remaining track index values offset by <pregap value>
1968 #
1969 # Variables used:
1970 # CDDBTRACKINFO
1971 abcde.mkcue () {
1972
1973         echomsf () {
1974                 printf "$1%02i:%02i:%02i\n" $(($2/4500)) $((($2/75)%60)) $(($2%75))
1975         }
1976
1977         local MODE DISCID TRACKS
1978         local i OFFSET LBA
1979         local CUEWAVFILE
1980
1981         if [ "$1" = --wholedisk ] ; then
1982                 MODE=INDEX
1983         else
1984                 MODE=PREGAP
1985         fi
1986
1987         vecho "One track is $ONETRACK"
1988         TRACKFILE="$(mungetrackname "$TRACKNAME")"
1989         ARTISTFILE="$(mungeartistname "$TRACKARTIST")"
1990         ALBUMFILE="$(mungealbumname "$DALBUM")"
1991         if [ "$ONETRACK" = "y" ]; then
1992                 if [ "$VARIOUSARTISTS" = "y" ]; then
1993                         CUEWAVFILE="$(eval echo \""$VAONETRACKOUTPUTFORMAT"\" | sed -e 's@^.*/@@').$OUTPUT"
1994                 else
1995                         CUEWAVFILE="$(eval echo \""$ONETRACKOUTPUTFORMAT"\" | sed -e 's@^.*/@@').$OUTPUT"
1996                 fi
1997                 vecho "Cue wav file is $CUEWAVFILE"
1998         else
1999                 CUEWAVFILE="dummy.wav"
2000         fi
2001
2002         set -- "$CDDBTRACKINFO"
2003
2004         DISCID="$1"
2005         TRACKS="$2"
2006         shift 2
2007
2008         echo "REM DISCID $DISCID"
2009         echo FILE \""$CUEWAVFILE"\" WAVE
2010
2011         if [ "$1" -ne 150 ] && [ "$MODE" = "PREGAP" ] ; then
2012                 OFFSET="$1"
2013         else
2014                 OFFSET="150"
2015         fi
2016
2017         i=1
2018         while [ $i -le "$TRACKS" ] ; do
2019                 LBA=$(( $1 - $OFFSET ))
2020                 printf "  TRACK %02i AUDIO\n" $i
2021                 if [ "$i" -eq 1 ] && [ "$1" -ne 150 ] ; then
2022                         if [ "$MODE" = PREGAP ] ; then
2023                                 echomsf "    PREGAP " $(($"OFFSET" - 150))
2024                         else
2025                                 echo    "    INDEX 00 00:00:00"
2026                         fi
2027                 fi
2028                 echomsf "    INDEX 01 " "$LBA"
2029                 i=$(( $i + 1))
2030                 shift
2031         done
2032 }
2033
2034 # do_discid
2035 # This is essentially the start of things
2036 do_discid ()
2037 {
2038         if [ -z "${CDDBDISCID}" ]; then
2039                 vecho -n "Getting CD track info... "
2040                 # In OSX, unmount the disc before a query
2041                 if [ "$OSFLAVOUR" = "OSX" ]; then
2042                         diskutil unmount "${CDROM#/dev/}"
2043                 fi
2044                 case "$CDROMREADERSYNTAX" in
2045                         flac)
2046                                 if $METAFLAC $METAFLACOPTS --export-cuesheet-to=- "$CDROM" > /dev/null 2>&1 ; then
2047                                         case "$CUE2DISCID" in
2048                                                 # FIXME # right now we have 2 cue2discid internal
2049                                                 # implementations: builtin and abcde.cue2discid. Test
2050                                                 # both of them and decide which one we want to use.
2051                                                 builtin)
2052                                                         #vecho "Using builtin cue2discid implementation..."
2053                                                         CUESHEET="$(metaflac $METAFLACOPTS --export-cuesheet-to=- "$CDROM")"
2054
2055                                                         #TRACKS=$(echo $CUESHEET | grep -E "TRACK \+[[:digit:]]\+ \+AUDIO" |wc -l)
2056                                                         #TRACKS=0
2057                                                         OFFSETTIMES=( $(echo "$CUESHEET" | sed -n -e's/\ *INDEX 01\ \+//p' ) )
2058                                                         TRACKS=${#OFFSETTIMES[@]}
2059                                                         unset OFFSETS
2060                                                         #echo "processing offsetimes ${OFFSETTIMES[@]}"
2061                                                         for OFFSETTIME in "${OFFSETTIMES[@]}"; do
2062                                                                 OFFSETS="$OFFSETS $(( 10#${OFFSETTIME:0:2} * 4500 + 10#${OFFSETTIME:3:2} * 75 + 10#${OFFSETTIME:6:2} ))"
2063                                                                 #OFFSETS[${#OFFSETS[*]}]=$(( 10#${OFFSETTIME:0:2} * 4500 + 10#${OFFSETTIME:3:2} * 75 + 10#${OFFSETTIME:6:2} ))
2064                                                         done
2065
2066                                                         LEADOUT=$(( $(echo "$CUESHEET" | grep lead-out | get_last) * 75 / 44100 ))
2067                                                         LEADIN=$(( $(echo "$CUESHEET" | grep lead-in | get_last) * 75 / 44100 ))
2068                                                         makeids
2069                                                 ;;
2070                                                 *)
2071                                                         #vecho "Using external python cue2discid implementation..."
2072                                                         CDDBTRACKINFO=$($METAFLAC $METAFLACOPTS --export-cuesheet-to=- "$CDROM" | $CUE2DISCID)
2073                                                 ;;
2074                                         esac
2075                                 else
2076                                         log error "the input flac file does not contain a cuesheet."
2077                                         exit 1
2078                                 fi
2079                                 ;;
2080                         cdparanoia|debug)
2081                                 CDPARANOIAOUTPUT="$( $CDROMREADER -"$CDPARANOIACDROMBUS" "$CDROM" -Q --verbose 2>&1 )"
2082                                 RET=$?
2083                                 if [ ! "$RET" = "0" ];then
2084                                         log warning "something went wrong while querying the CD... Maybe a DATA CD or the CD is not loaded?"
2085                                 fi
2086
2087                                 TRACKS="$(echo "$CDPARANOIAOUTPUT" | grep -E '^[[:space:]]+[[:digit:]]' | tail -n 1 | get_first | tr -d "." | tr '\n' ' ')"
2088                                 CDPARANOIAAUDIOTRACKS="$TRACKS"
2089
2090                                 LEADOUT="$(echo "$CDPARANOIAOUTPUT" | grep -Eo '^TOTAL[[:space:]]+([[:digit:]]+)' | get_last)"
2091                                 OFFSETS="$(echo "$CDPARANOIAOUTPUT" | sed -n -e's/^ .* \([0-9]\+\) \[.*/\1/p')"
2092                                 makeids
2093                                 ;;
2094                         *)
2095                                 # Calculate the cddb discid in all
2096                                 # cases now. We'll use the cddb discid
2097                                 # for reference in most cases for
2098                                 # consistency. Also calculate the
2099                                 # musicbrainz discid if we need it.
2100                                 CDDBTRACKINFO=$($CDDISCID "$CDROM")
2101                                 if [ "$CDDISCID_NEEDS_PAUSE"x = "y"x ]; then
2102                                         sleep 6
2103                                 fi
2104                                 CDDBDISCID=$(echo "$CDDBTRACKINFO" | cut -d' ' -f1)
2105                                 case "$CDDBMETHOD" in
2106                                         *musicbrainz*)
2107                                                 MBTRACKINFO=$($MUSICBRAINZ --command id --device "$CDROM")
2108                                                 error=$?
2109                                                 if [ $error != 0 ]; then
2110                                                         log error "$MUSICBRAINZ failed to run; ABORT"
2111                                                         exit $error
2112                                                 fi
2113                                                 MBDISCID=$(echo "$MBTRACKINFO" | cut -d' ' -f1)
2114                                                 ;;
2115                                 esac
2116                 esac
2117                 # Make sure there's a CD in there by checking cd-discid's return code
2118                 if [ ! "$?" = "0" ]; then
2119                         if [ "$CDROMREADERSYNTAX" = "flac" ] ; then
2120                                 log error "cuesheet information from the flac file could not be read."
2121                                 log error "Perhaps the flac file does not contain a cuesheet?."
2122                                 exit 1
2123                         else
2124                                 log error "CD could not be read. Perhaps there's no CD in the drive?"
2125                                 exit 1
2126                         fi
2127                 fi
2128                 # In OSX, remount the disc again
2129                 if [ "$OSFLAVOUR" = "OSX" ]; then
2130                         diskutil mount "${CDROM#/dev/}"
2131                 fi
2132                 WEHAVEACD=y
2133                 CDDBDISCID=$(echo "$CDDBTRACKINFO" | cut -f1 -d' ')
2134         else
2135                 CDDBTRACKINFO=$(cat "$WAVOUTPUTDIR/abcde.${CDDBDISCID}/cddbdiscid")
2136         fi
2137
2138         # Get a full enumeration of tracks, sort it, and put it in the TRACKQUEUE.
2139         # This needs to be done now because a section of the resuming code will need
2140         # it later.
2141
2142         # get the number of digits to pad TRACKNUM with - we'll use this later
2143         # a CD can only hold 99 tracks, but since we support a feature for starting
2144         # numbering the tracks from a given number, we might need to set it as a
2145         # variable for the user to define... or obtain it somehow.
2146         if [ "$PADTRACKS" = "y" ] ; then
2147                 TRACKNUMPADDING=2
2148         fi
2149
2150         ABCDETEMPDIR="$WAVOUTPUTDIR/abcde.$(echo "$CDDBTRACKINFO" | cut -f1 -d' ')"
2151         if [ -z "$TRACKQUEUE" ]; then
2152                 if [ ! "$STRIPDATATRACKS" = "n" ]; then
2153                         case "$CDROMREADERSYNTAX" in
2154                                 cdparanoia|libcdio|debug)
2155                                         if [ "$WEHAVEACD" = "y" ]; then
2156                                                 vecho "Querying the CD for audio tracks..."
2157                                                 CDPARANOIAOUTPUT="$( $CDROMREADER -"$CDPARANOIACDROMBUS" "$CDROM" -Q --verbose 2>&1 )"
2158                                                 RET=$?
2159                                                 if [ ! "$RET" = "0" ];then
2160                                                         log warning "something went wrong while querying the CD... Maybe a DATA CD?"
2161                                                 fi
2162                                                 TRACKS="$(echo "$CDPARANOIAOUTPUT" | grep -E '^[[:space:]]+[[:digit:]]' | tail -n 1 | get_first | tr -d "." | tr '\n' ' ')"
2163                                                 CDPARANOIAAUDIOTRACKS="$TRACKS"
2164                                         else
2165                                                 # Previous versions of abcde would store the tracks on a file, instead of the status record.
2166                                                 if [ -f "${ABCDETEMPDIR}/cdparanoia-audio-tracks" ]; then
2167                                                         echo "cdparanoia-audio-tracks=$( cat "${ABCDETEMPDIR}/cdparanoia-audio-tracks" )" >> "${ABCDETEMPDIR}/status"
2168                                                         rm -f "${ABCDETEMPDIR}/cdparanoia-audio-tracks"
2169                                                 fi
2170                                                 if [ -f "${ABCDETEMPDIR}/status" ] && TRACKS=$(checkstatus cdparanoia-audio-tracks); then :; else
2171                                                         TRACKS=$(echo "$CDDBTRACKINFO" | cut -f2 -d' ')
2172                                                 fi
2173                                         fi
2174                                         ;;
2175                                 *)      TRACKS=$(echo "$CDDBTRACKINFO" | cut -f2 -d' ') ;;
2176                         esac
2177                 else
2178                         TRACKS=$(echo "$CDDBTRACKINFO" | cut -f2 -d' ')
2179                 fi
2180                 if echo "$TRACKS" | grep "[[:digit:]]" > /dev/null 2>&1 ;then :;else
2181                         log info "The disc does not contain any tracks. Giving up..."
2182                         exit 0
2183                 fi
2184                 echo -n "Grabbing entire CD - tracks: "
2185                 if [ ! "$PADTRACKS" = "y" ] ; then
2186                         TRACKNUMPADDING=$(echo -n "$TRACKS" | wc -c | tr -d ' ')
2187                 fi
2188
2189                 TRACKS=$(printf "%0.${TRACKNUMPADDING}d" $TRACKS)
2190                 X=0
2191                 while [ "$X" -ne "$TRACKS" ]
2192                 do
2193                         PT=$(printf "%0.${TRACKNUMPADDING}d" $(($X + 1)))
2194                         TRACKQUEUE="$TRACKQUEUE $PT"
2195                         X=$(($X + 1))
2196                 done
2197                 echo "$TRACKQUEUE"
2198         else
2199                 TRACKS=$(echo "$CDDBTRACKINFO" | cut -f2 -d' ')
2200                 # User-supplied track queue.
2201                 # Weed out non-numbers, whitespace, then sort and weed out duplicates
2202                 TRACKQUEUE=$(echo "$TRACKQUEUE" | sed 's-[^0-9 ]--g' | tr ' ' '\n' | grep -v ^$ | sort -n | uniq | tr '\n' ' ' | sed 's- $--g')
2203                 # Once cleaned, obtain the highest value in the trackqueue for number padding
2204                 for LASTTRACK in $TRACKQUEUE; do :; done
2205                 if [ ! "$PADTRACKS" = "y" ] ; then
2206                         TRACKNUMPADDING=$(echo -n "$LASTTRACK" | wc -c | tr -d ' ')
2207                 fi
2208                 # Now we normalize the trackqueue
2209                 for TRACK in $TRACKQUEUE ; do
2210                         TRACKNUM=$(printf "%0.${TRACKNUMPADDING}d" $(($TRACK + 0)))
2211                         PADTRACKQUEUE="$PADTRACKQUEUE $TRACKNUM"
2212                 done
2213                 TRACKQUEUE="$PADTRACKQUEUE"
2214                 echo Grabbing tracks: "$TRACKQUEUE"
2215         fi
2216
2217         QUEUEDTRACKS=$(echo $TRACKQUEUE | wc -w | tr -d ' ')
2218
2219         # We have the discid, create a temp directory after it to store all the temp
2220         # info
2221
2222         if [ -e "${ABCDETEMPDIR}" ]; then
2223                 echo -n "abcde: attempting to resume from ${ABCDETEMPDIR}"
2224                 # It already exists, see if it's a directory
2225                 if [ ! -d "${ABCDETEMPDIR}" ]; then
2226                         # This is a file/socket/fifo/device/etc, not a directory
2227                         # Complain and exit
2228                         echo >&2
2229                         echo "abcde: file ${ABCDETEMPDIR} already exists and does not belong to abcde." >&2
2230                         echo "Please investigate, remove it, and rerun abcde." >&2
2231                         exit 1
2232                 fi
2233                 echo -n .
2234                 # It's a directory, let's see if it's writable by us
2235                 if [ ! -r "${ABCDETEMPDIR}" ] || [ ! -w "${ABCDETEMPDIR}" ] || [ ! -x "${ABCDETEMPDIR}" ]; then
2236                         # Nope, complain and exit
2237                         echo >&2
2238                         echo "abcde: directory ${ABCDETEMPDIR} already exists and is not writeable." >&2
2239                         echo "Please investigate, remove it, and rerun abcde." >&2
2240                         exit 1
2241                 fi
2242                 echo .
2243                 # See if it's populated
2244                 if [ ! -f "${ABCDETEMPDIR}/cddbdiscid" ]; then
2245                         # Wipe and start fresh
2246                         echo "abcde: ${ABCDETEMPDIR}/cddbdiscid not found. Abcde must remove and recreate" >&2
2247                         echo -n "this directory to continue. Continue [y/N]? " >&2
2248                         if [ "$INTERACTIVE" = "y" ]; then
2249                                 read ANSWER
2250                         else
2251                                 echo y >&2
2252                                 ANSWER=y
2253                         fi
2254                         if [ "$ANSWER" != "y" ]; then
2255                                 exit 1
2256                         fi
2257                         rm -rf "${ABCDETEMPDIR}" || exit 1
2258                         mkdir -p "${ABCDETEMPDIR}"
2259                         if [ "$?" -gt "0" ]; then
2260                                 # Directory already exists or could not be created
2261                                 echo "abcde: Temp directory ${ABCDETEMPDIR} could not be created." >&2
2262                                 exit 1
2263                         fi
2264                 else
2265                         # Everything is fine. Check for ^encodetracklocation-
2266                         # and encode-output entries in the status file and
2267                         # remove them. These are not relevant across sessions.
2268                         if [ -f "${ABCDETEMPDIR}/status" ]; then
2269                                 mv "${ABCDETEMPDIR}/status" "${ABCDETEMPDIR}/status.old"
2270                                 grep -v ^encodetracklocation- < "${ABCDETEMPDIR}/status.old" \
2271                                         | grep -v ^encode-output > "${ABCDETEMPDIR}/status"
2272                         fi
2273                         # Remove old error messages
2274                         if [ -f "${ABCDETEMPDIR}/errors" ]; then
2275                                 rm -f "${ABCDETEMPDIR}/errors"
2276                         fi
2277                 fi
2278         else
2279                 # We are starting from scratch
2280                 mkdir -p "${ABCDETEMPDIR}"
2281                 if [ "$?" -gt "0" ]; then
2282                         # Directory already exists or could not be created
2283                         echo "abcde: Temp directory ${ABCDETEMPDIR} could not be created." >&2
2284                         exit 1
2285                 fi
2286                 cat /dev/null > "${ABCDETEMPDIR}/status"
2287                 # Store the abcde version in the status file.
2288                 echo "abcde-version=$VERSION" >> "${ABCDETEMPDIR}/status"
2289         fi
2290         if [ X"$DOCUE" = "Xy" ] && [ X"$WEHAVEACD" = "Xy" ]; then
2291                 if checkstatus cuefile > /dev/null 2>&1 ; then :; else
2292                         CUEFILE=cue-$(echo "$CDDBTRACKINFO" | cut -f1 -d' ').txt
2293                         vecho "Creating cue file..."
2294                         case "$CDROMREADERSYNTAX" in
2295                                 flac)
2296                                         if $METAFLAC --export-cuesheet-to=- "$CDROM" > "${ABCDETEMPDIR}/$CUEFILE"; then
2297                                                 echo "cuefile=$CUEFILE" >> "${ABCDETEMPDIR}/status"
2298                                         else
2299                                                 log warning "the input flac file does not contain a cuesheet."
2300                                         fi
2301                                         ;;
2302                                 *)
2303                                         if $CUEREADER $CUEREADEROPTS > "${ABCDETEMPDIR}/$CUEFILE"; then
2304                                                 echo "cuefile=$CUEFILE" >> "${ABCDETEMPDIR}/status"
2305                                         else
2306                                                 log warning "reading the CUE sheet is still considered experimental"
2307                                                 log warning "and there was a problem with the CD reading. abcde will continue,"
2308                                                 log warning "but consider reporting the problem to the abcde author"
2309                                         fi
2310                                         ;;
2311                         esac
2312                 fi
2313         fi
2314         # If we got the CDPARANOIA status and it is not recorded, save it now
2315         if [ -n "$CDPARANOIAAUDIOTRACKS" ]; then
2316                 if checkstatus cdparanoia-audio-tracks > /dev/null 2>&1; then :; else
2317                         echo "cdparanoia-audio-tracks=$CDPARANOIAAUDIOTRACKS" >> "${ABCDETEMPDIR}/status"
2318                 fi
2319         fi
2320
2321         # Create the discid files
2322         echo "$CDDBTRACKINFO" > "${ABCDETEMPDIR}/cddbdiscid"
2323         case "$CDDBMETHOD" in
2324                 *musicbrainz*)
2325                         echo "$MBTRACKINFO" > "${ABCDETEMPDIR}/mbdiscid"
2326                         ;;
2327         esac
2328 }
2329
2330 # do_cleancue
2331 # Create a proper CUE file based on the CUE file we created before.
2332 do_cleancue()
2333 {
2334         if CUEFILE_IN="${ABCDETEMPDIR}"/$(checkstatus cuefile); then
2335                 CUEFILE_OUT=$CUEFILE_IN.out
2336                 ### FIXME ### checkstatus cddb
2337                 if [ -e "$CDDBDATA" ]; then
2338                         vecho "Adding metadata to the cue file..."
2339                         # FIXME It doesn't preserve spaces! Why?
2340                         # FIXME parse $track into PERFORMER and TITLE - abcde already has code for this?
2341                         n=1
2342                         echo "PERFORMER \"$DARTIST\"" >> "$CUEFILE_OUT"
2343                         echo "TITLE \"$DALBUM\"" >> "$CUEFILE_OUT"
2344                         # Set IFS to <newline> to prevent read from swallowing spaces and tabs
2345                         OIFS="$IFS"
2346                         IFS='
2347 '
2348                         cat "$CUEFILE_IN" | while read line
2349                         do
2350                                 if echo "$line" | grep "INDEX 01" > /dev/null 2>&1 ; then
2351 # FIXME # Possible patch: remove the line above, uncomment the 2 lines below.
2352 #                               echo "$line" >> "$CUEFILE_OUT"
2353 #                               if echo "$line" | grep "^[[:space:]]*TRACK" > /dev/null 2>&1 ; then
2354                                         eval track="\$TRACK$n"
2355                                         n=$(( $n + 1 ))
2356                                         echo "    TITLE \"$track\"" >> "$CUEFILE_OUT"
2357                                 # When making a single-track rip, put the
2358                                 # actual file name into the file declaration
2359                                 # in the cue file so that it is usable by
2360                                 # music players and the like
2361                                 elif [ "$ONETRACK" = "y" ] &&
2362                                                 echo "$line" | grep '^FILE "dummy.wav" WAVE' > /dev/null 2>&1 ; then
2363
2364                                         TRACKFILE="$(mungetrackname "$TRACKNAME")"
2365                                         ARTISTFILE="$(mungeartistname "$TRACKARTIST")"
2366                                         ALBUMFILE="$(mungealbumname "$DALBUM")"
2367
2368                                         if [ "$VARIOUSARTISTS" = "y" ]; then
2369                                                 OUTPUTFILE="$(eval echo \""$VAONETRACKOUTPUTFORMAT"\" | sed -e 's@^.*/@@').$OUTPUT"
2370                                         else
2371                                                 OUTPUTFILE="$(eval echo \""$ONETRACKOUTPUTFORMAT"\" | sed -e 's@^.*/@@').$OUTPUT"
2372                                         fi
2373
2374                                         echo "FILE \"$OUTPUTFILE\" WAVE" >> "$CUEFILE_OUT"
2375                                         continue
2376                                 fi
2377 # FIXME # If the lines above are uncommented, remove the line below.
2378                                 echo "$line" >> "$CUEFILE_OUT"
2379                         done
2380                         IFS="$OIFS"
2381                         mv "$CUEFILE_OUT" "$CUEFILE_IN"
2382                         echo "cleancuefile" >> "${ABCDETEMPDIR}/status"
2383                 fi
2384         fi
2385 }
2386
2387 # do_cddbparse
2388 # Parses a CDDB file and outputs the title and the track names.
2389 # Variables: CDDBFILE
2390 do_cddbparse ()
2391 {
2392         CDDBPARSEFILE="$1"
2393         # List out disc title/author and contents
2394         if [ "$ONETRACK" = "y" ]; then
2395                 vecho "ONETRACK mode selected: displaying only the title of the CD..."
2396         fi
2397         echo "---- $(grep -a DTITLE "${CDDBPARSEFILE}" | cut '-d=' -f2- | tr -d \\r\\n ) ----"
2398         if [ X"$SHOWCDDBYEAR" = "Xy" ]; then
2399                 PARSEDYEAR=$(grep -a DYEAR "${CDDBPARSEFILE}" | cut '-d=' -f2-)
2400                 if [ ! X"$PARSEDYEAR" = "X" ]; then
2401                         echo "Year: $PARSEDYEAR"
2402                 fi
2403         fi
2404         if [ X"$SHOWCDDBGENRE" = "Xy" ]; then
2405                 PARSEDGENRE=$(grep -a DGENRE "${CDDBPARSEFILE}" | cut '-d=' -f2-)
2406                 if [ ! X"$PARSEDGENRE" = "X" ]; then
2407                         echo "Genre: $PARSEDGENRE"
2408                 fi
2409         fi
2410         if [ ! "$ONETRACK" = "y" ]; then
2411                 for TRACK in $(f_seq_row 1 "$TRACKS")
2412                 do
2413                         echo "$TRACK": "$(grep -a ^TTITLE$(($TRACK - 1))= "${CDDBPARSEFILE}" | cut -f2- -d= | tr -d \\r\\n)"
2414                 done
2415         fi
2416 }
2417
2418 # do_localcddb_read
2419 # Check for a local CDDB file, and report success
2420 do_localcddb_read ()
2421 {
2422         if checkstatus cddb-readcomplete && checkstatus cddb-choice >/dev/null; then :; else
2423
2424                 CDDBLOCALSTATUS="notfound"
2425                 CDDBDISCID=$(echo "$CDDBTRACKINFO" | cut -d' ' -f1)
2426                 USELOCALRESP="y"
2427
2428                 if [ "$CDDBLOCALRECURSIVE" = "y" ]; then
2429                         CDDBLOCALRESULTS="$(find "${CDDBLOCALDIR}" -name "${CDDBDISCID}" -type f 2> /dev/null)"
2430                         if [ ! "${CDDBLOCALRESULTS}" = "" ]; then
2431                                 if   (( $(echo "${CDDBLOCALRESULTS}" | wc -l) == 1 )); then
2432                                         CDDBLOCALFILE="${CDDBLOCALRESULTS}"
2433                                         CDDBLOCALMATCH=single
2434                                 elif (( $(echo "${CDDBLOCALRESULTS}" | wc -l) > 1 )); then
2435                                         CDDBLOCALMATCH=multiple
2436                                 fi
2437                         else
2438                                 CDDBLOCALMATCH=none
2439                         fi
2440                 elif [ "$CDDBLOCALMATCH" = "none" ] && [ -r "${CDDBLOCALDIR}/${CDDBDISCID}" ]; then
2441                         CDDBLOCALFILE="${CDDBLOCALDIR}/${CDDBDISCID}"
2442                         CDDBLOCALMATCH=single
2443                 else
2444                         CDDBLOCALMATCH=none
2445                 fi
2446
2447                 # If the user has selected to check a local CDDB repo, we proceed with it
2448                 case $CDDBLOCALMATCH in
2449                         multiple)
2450                                 echo "Processing multiple matching CDDB entries..." > "${ABCDETEMPDIR}/cddblocalchoices"
2451                                 X=0
2452                                 echo "$CDDBLOCALRESULTS" | while read RESULT ; do
2453                                         X=$(( $X + 1 ))
2454                                         # List out disc title/author and contents
2455                                         CDDBLOCALREAD="${ABCDETEMPDIR}/cddblocalread.$X"
2456                                         cat "$RESULT" > "${CDDBLOCALREAD}"
2457                                         {
2458                                                 echo -n "#$X: "
2459                                                 do_cddbparse "${CDDBLOCALREAD}"
2460                                                 echo ""
2461                                                 ##FIXME## QUICK HACK !!!!
2462                                                 if [ ! "$INTERACTIVE" = "y" ]; then break ; fi
2463                                         } >> "${ABCDETEMPDIR}/cddblocalchoices"
2464                                 done
2465                                 page "${ABCDETEMPDIR}/cddblocalchoices"
2466                                 CDDBLOCALCHOICES=$( echo "$CDDBLOCALRESULTS" | wc -l )
2467                                 # Setting the choice to an impossible integer to avoid errors in the numeric comparisons
2468                                 CDDBLOCALCHOICENUM=-1
2469                                 if [ "$INTERACTIVE" = "y" ]; then
2470                                         while [ "$CDDBLOCALCHOICENUM" -lt 0 ] || [ "$CDDBLOCALCHOICENUM" -gt "$CDDBLOCALCHOICES" ]; do
2471                                                 echo -n "Locally cached CDDB entries found. Which one would you like to use (0 for none)? [0-$CDDBLOCALCHOICES]: " >&2
2472                                                 read CDDBLOCALCHOICE
2473                                                 [ x"$CDDBLOCALCHOICE" = "x" ] && CDDBLOCALCHOICE="1"
2474                                                 # FIXME # Introduce diff's
2475                                                 if echo $CDDBLOCALCHOICE | grep -E "[[:space:]]*[[:digit:]]+,[[:digit:]]+[[:space:]]*" > /dev/null 2>&1 ; then
2476                                                         diffentries cddblocalread "$CDDBLOCALCHOICES" "$CDDBLOCALCHOICE"
2477                                                 elif echo $CDDBLOCALCHOICE | grep -E "[[:space:]]*[[:digit:]]+[[:space:]]*" > /dev/null 2>&1 ; then
2478                                                         # Make sure we get a valid choice
2479                                                         CDDBLOCALCHOICENUM=$(echo $CDDBLOCALCHOICE | xargs printf %d 2>/dev/null)
2480                                                         if [ "$CDDBLOCALCHOICENUM" -lt 0 ] || [ "$CDDBLOCALCHOICENUM" -gt "$CDDBLOCALCHOICES" ]; then
2481                                                                 echo "Invalid selection. Please choose a number between 0 and $CDDBLOCALCHOICES." >&2
2482                                                         fi
2483                                                 fi
2484                                         done
2485                                 else
2486                                         CDDBLOCALCHOICENUM=1
2487                                 fi
2488                                 if [ ! "$CDDBLOCALCHOICENUM" = "0" ]; then
2489                                         #echo "Using local copy of CDDB data"
2490                                         echo "# DO NOT ERASE THIS LINE! Added by abcde to imitate cddb output" > "${ABCDETEMPDIR}/cddbread.1"
2491                                         cat "${ABCDETEMPDIR}/cddblocalread.$CDDBLOCALCHOICENUM" >> "${ABCDETEMPDIR}/cddbread.1"
2492                                         echo "local" > "${ABCDETEMPDIR}/datasource.1"
2493                                         echo 999 > "${ABCDETEMPDIR}/cddbquery" # Assuming 999 isn't used by CDDB
2494                                         echo cddb-readcomplete >> "${ABCDETEMPDIR}/status"
2495                                         do_cddbparse "${ABCDETEMPDIR}/cddbread.1" > "${ABCDETEMPDIR}/cddbchoices"
2496                                         echo cddb-choice=1 >> "${ABCDETEMPDIR}/status"
2497                                         CDDBLOCALSTATUS="found"
2498                                 else
2499                                         #echo "Not using local copy of CDDB data"
2500                                         CDDBLOCALSTATUS="notfound"
2501                                 fi
2502                                 ;;
2503                         single)
2504                                 # List out disc title/author and contents
2505                                 do_cddbparse "${CDDBLOCALFILE}"
2506                                 #if [ "$CDROMREADERSYNTAX" = "flac" ] ; then
2507                                 #       echo -n "Embedded cuesheet entry found, use it [Y/n]? " >&2
2508                                 #else
2509                                         echo -n "Locally cached CDDB entry found, use it [Y/n]? " >&2
2510                                 #fi
2511                                 if [ "$INTERACTIVE" = "y" ]; then
2512                                         read USELOCALRESP
2513                                         while [ "$USELOCALRESP" != "y" ] && [ "$USELOCALRESP" != "n" ] && [ "$USELOCALRESP" != "" ] ; do
2514                                                 echo -n 'Invalid selection. Please answer "y" or "n": ' >&2
2515                                                 read USELOCALRESP
2516                                         done
2517                                         [ x"$USELOCALRESP" = "x" ] && USELOCALRESP="y"
2518                                 else
2519                                         echo "y" >&2
2520                                 fi
2521                                 if [ "$USELOCALRESP" = "y" ]; then
2522                                         #echo "Using local copy of CDDB data"
2523                                         echo "# DO NOT ERASE THIS LINE! Added by abcde to imitate cddb output" > "${ABCDETEMPDIR}/cddbread.1"
2524                                         cat "${CDDBLOCALFILE}" >> "${ABCDETEMPDIR}/cddbread.1"
2525                                         echo "local" > "${ABCDETEMPDIR}/datasource.1"
2526                                         echo 999 > "${ABCDETEMPDIR}/cddbquery" # Assuming 999 isn't used by CDDB
2527                                         echo cddb-readcomplete >> "${ABCDETEMPDIR}/status"
2528                                         do_cddbparse "${CDDBLOCALFILE}" > "${ABCDETEMPDIR}/cddbchoices"
2529                                         echo cddb-choice=1 >> "${ABCDETEMPDIR}/status"
2530                                         CDDBLOCALSTATUS="single"
2531                                 else
2532                                         #echo "Not using local copy of CDDB data"
2533                                         CDDBLOCALSTATUS="notfound"
2534                                 fi
2535                                 ;;
2536                         none)
2537                                 CDDBLOCALSTATUS="notfound"
2538                                 ;;
2539                 esac
2540         fi
2541 }
2542
2543 # do_cdtext_read
2544 # Try to read CD-Text from the drive using icedax / cdda2wav
2545 do_cdtext_read ()
2546 {
2547         if new_checkexec icedax; then
2548                 CDTEXT_READER=icedax
2549         elif new_checkexec cdda2wav; then
2550                 CDTEXT_READER=cdda2wav
2551         else
2552                 # Didn't find either, bail
2553                 return 0
2554         fi
2555
2556         vecho "Obtaining CD-Text results..."
2557         local SOURCE_WORKDIR="${ABCDETEMPDIR}/data-cdtext"
2558         mkdir -p "${SOURCE_WORKDIR}"
2559
2560         if [ "$OSFLAVOUR" = "OSX" ] ; then
2561                 # Hei, we have to unmount the device before running anything like cdda2wav/icedax in OSX
2562                 diskutil unmount "${CDROM#/dev/}"
2563                 # Also, in OSX the cdrom device for cdda2wav/icedax changes...
2564                 CDDA2WAVCDROM="IODVDServices"
2565         elif [ "$OSFLAVOUR" = "FBSD" ] || [ "$OSFLAVOUR" = "IRIX" ]; then
2566                 CDDA2WAVCDROM="$CDROMID"
2567         else
2568                 if [ "$CDROMID" = "" ]; then
2569                         CDDA2WAVCDROM="$CDROM"
2570                 else
2571                         CDDA2WAVCDROM="$CDROMID"
2572                 fi
2573         fi
2574
2575         # Do we have CD-Text on the disc (and can the drive read it?)
2576         (
2577                 cd "${SOURCE_WORKDIR}" && rm -f audio.* audio_*
2578                 ${CDTEXT_READER} -J -v titles -D "${CDDA2WAVCDROM}" > "${SOURCE_WORKDIR}/cd-text" 2>&1
2579         )
2580         grep -a -q '^CD-Text: detected' "${SOURCE_WORKDIR}/cd-text"
2581         ERRORCODE=$?
2582         if [ $ERRORCODE -ne 0 ]; then
2583                 # No CD-Text found, bail
2584                 return 0
2585         fi
2586
2587         NUM_CDDB_MATCHES=$(($NUM_CDDB_MATCHES + 1))
2588         # Make an empty template
2589         $CDDBTOOL template "$(cat "${ABCDETEMPDIR}/cddbdiscid")" > "${SOURCE_WORKDIR}/cddbread.${NUM_CDDB_MATCHES}"
2590         echo "cddb-read-${NUM_CDDB_MATCHES}-complete" >> "${ABCDETEMPDIR}/status"
2591         rm -f "${SOURCE_WORKDIR}/cddbread.${NUM_CDDB_MATCHES}"
2592
2593         # XXX FIXME - this is a hack and should be replaced by proper
2594         # character set tracking for the CDDB data we have.
2595         if [ "$CDDBPROTO" -ge 6 ]; then
2596                 # convert to Unicode
2597                 iconv -f iso-8859-1 -t utf-8 <"${SOURCE_WORKDIR}/audio.cddb" >"${SOURCE_WORKDIR}/cddbread.${NUM_CDDB_MATCHES}"
2598         else
2599                 # copy verbatim, assuming CD-TEXT is in ISO-8859-1 format
2600                 # apparently icedax/cdda2wav have no support for 16-bit
2601                 # characters yet, either
2602                 cp -p "${SOURCE_WORKDIR}/audio.cddb" "${SOURCE_WORKDIR}/cddbread.${NUM_CDDB_MATCHES}"
2603         fi
2604
2605         CDDBDISCID=$(echo "$CDDBTRACKINFO" | cut -d' ' -f1)
2606         ATITLE=$(grep -a -e '^DTITLE=' "${SOURCE_WORKDIR}/cddbread.${NUM_CDDB_MATCHES}" | cut -c8- | tr -d \\r\\n)
2607         echo "CD-Text" > "${SOURCE_WORKDIR}/datasource.${NUM_CDDB_MATCHES}"
2608         echo "none ${CDDBDISCID} ${ATITLE}" >> "${SOURCE_WORKDIR}/cddbquery.${NUM_CDDB_MATCHES}"
2609
2610         ( cd "${SOURCE_WORKDIR}" && rm -f audio_* audio.* )
2611         for file in ${SOURCE_WORKDIR}/cddbread.* ${SOURCE_WORKDIR}/cddbquery.* ${SOURCE_WORKDIR}/datasource.*; do
2612                 if [ -f "$file" ]; then
2613                         cp "$file" "${ABCDETEMPDIR}"
2614                 fi
2615         done
2616         echo "cdtext-readcomplete" >> "${ABCDETEMPDIR}/status"
2617 }
2618
2619 # do_musicbrainz_read
2620 # Work with the musicbrainz WS API, then transform the results here so
2621 # they look (very) like the results from CDDB. Maybe not the best way
2622 # to go, but it Works For Me (TM)
2623 #
2624 # List out all the matches individually into $SOURCE_WORKDIR/cddbread.X
2625 #
2626 do_musicbrainz_read ()
2627 {
2628         if checkstatus musicbrainz-readcomplete; then :; else
2629                 vecho "Obtaining Musicbrainz results..."
2630                 # If MB is to be used, interpret the query results and read all
2631                 # the available entries.
2632                 CDDBDISCID=$(echo "$CDDBTRACKINFO" | cut -d' ' -f1)
2633                 MBDISCID=$(echo "$MBTRACKINFO" | cut -d' ' -f1)
2634                 local SOURCE_WORKDIR="${ABCDETEMPDIR}/data-musicbrainz"
2635                 mkdir -p "${SOURCE_WORKDIR}"
2636                 ${MUSICBRAINZ} --command data --discid "${MBDISCID}" --workdir "${SOURCE_WORKDIR}" --start ${NUM_CDDB_MATCHES}
2637                 error=$?
2638                 if [ $error != 0 ]; then
2639                         log error "$MUSICBRAINZ failed to run; ABORT"
2640                         exit $error
2641                 fi
2642
2643                 # Check for no matches.
2644                 # The helper script will write disc matches out to
2645                 # cddbread.*. Count how many we have
2646                 NUM_RESPONSES=$(echo "${SOURCE_WORKDIR}"/cddbread.* | wc -w)
2647                 if [ "$NUM_RESPONSES" -gt 0 ] ; then
2648                         # One or more exact matches
2649                         i=1
2650                         while [ $i -le "$NUM_RESPONSES" ]; do
2651                                 NUM_CDDB_MATCHES=$(($NUM_CDDB_MATCHES + 1))
2652                                 i=$(($i + 1))
2653                                 echo cddb-read-${NUM_CDDB_MATCHES}-complete >> "${ABCDETEMPDIR}/status"
2654                                 ATITLE=$(grep -a -e '^DTITLE=' "${SOURCE_WORKDIR}/cddbread.${NUM_CDDB_MATCHES}" | cut -c8- | tr -d \\r\\n)
2655                                 echo "none ${CDDBDISCID} ${ATITLE}" >> "${SOURCE_WORKDIR}/cddbquery.${NUM_CDDB_MATCHES}"
2656                                 echo "Musicbrainz" > "${SOURCE_WORKDIR}/datasource.${NUM_CDDB_MATCHES}"
2657                                 cp -f "${SOURCE_WORKDIR}/"*."${NUM_CDDB_MATCHES}" "${ABCDETEMPDIR}"
2658                         done
2659                 fi
2660                 echo "musicbrainz-readcomplete" >> "${ABCDETEMPDIR}/status"
2661         fi
2662 }
2663
2664 # do_cddb_read
2665 do_cddb_read ()
2666 {
2667         local SOURCE_WORKDIR="${ABCDETEMPDIR}/data-cddb"
2668         mkdir -p "${SOURCE_WORKDIR}"
2669
2670         ###########
2671         # cddbstat
2672         ###########
2673
2674         # Perform CDDB protocol version check if it hasn't already been done
2675         if checkstatus cddb-statcomplete; then :; else
2676                 if [ "$CDDBAVAIL" = "n" ]; then
2677                         ERRORCODE=no_query
2678                         echo 503 > "${SOURCE_WORKDIR}/cddbstat"
2679                 else
2680                         rc=1
2681                         CDDBUSER=$(echo "$HELLOINFO" | cut -f1 -d'@')
2682                         CDDBHOST=$(echo "$HELLOINFO" | cut -f2- -d'@')
2683                         while [ $rc -eq 1 ] && [ "$CDDBPROTO" -ge 3 ]; do
2684                                 vecho "Checking CDDB server status..."
2685                                 $CDDBTOOL stat "$CDDBURL" "$CDDBUSER" "$CDDBHOST" "$CDDBPROTO" > "${SOURCE_WORKDIR}/cddbstat"
2686                                 RESPONSECODE=$(head -n 1 "${SOURCE_WORKDIR}/cddbstat" | cut -f1 -d' ')
2687                                 case "$RESPONSECODE" in
2688                                 210)    # 210 OK, status information follows (until terminating `.')
2689                                         rc=0
2690                                         ;;
2691                                 501)  # 501 Illegal CDDB protocol level: <n>.
2692                                         CDDBPROTO=$(($CDDBPROTO - 1))
2693                                         ;;
2694                                 *)      # Try a cddb query, since freedb2.org doesn't support the stat or ver commands
2695                                         # FreeDB TESTCD disc-id is used for query
2696                                         $CDDBTOOL query "$CDDBURL" "$CDDBPROTO" "$CDDBUSER" "$CDDBHOST" 03015501 1 296 344 > "${SOURCE_WORKDIR}/cddbstat"
2697                                         RESPONSECODE=$(head -n 1 "${SOURCE_WORKDIR}/cddbstat" | cut -f1 -d' ')
2698                                         case "$RESPONSECODE" in
2699                                                 2??)    # Server responded, everything seems OK
2700                                                         rc=0
2701                                                         ;;
2702                                                 *)      # unknown error
2703                                                         break
2704                                                         ;;
2705                                         esac
2706                                         ;;
2707                                 esac
2708                         done
2709                         if [ $rc -eq 1 ]; then
2710                                 CDDBAVAIL="n"
2711                         fi
2712                 fi
2713                 echo cddb-statcomplete >> "${ABCDETEMPDIR}/status"
2714         fi
2715
2716         ###########
2717         # cddbquery
2718         ###########
2719
2720         CDDBDISCID=$(echo "$CDDBTRACKINFO" | cut -d' ' -f1)
2721         CDDBLOCALFILE="${CDDBLOCALDIR}/${CDDBDISCID}"
2722
2723         # Perform CDDB query if it hasn't already been done
2724         if checkstatus cddb-querycomplete; then :; else
2725                 if [ "$CDDBAVAIL" = "n" ]; then
2726                         ERRORCODE=no_query
2727                         echo 503 > "${SOURCE_WORKDIR}/cddbquery"
2728                 # The default CDDBLOCALSTATUS is "notfound"
2729                 # This part will be triggered if the user CDDB repo does not
2730                 # contain the entry, or if we are not trying to use the repo.
2731                 else
2732                         vecho "Querying the CDDB server..."
2733                         CDDBUSER=$(echo "$HELLOINFO" | cut -f1 -d'@')
2734                         CDDBHOST=$(echo "$HELLOINFO" | cut -f2- -d'@')
2735                         $CDDBTOOL query "$CDDBURL" "$CDDBPROTO" "$CDDBUSER" "$CDDBHOST" "$CDDBTRACKINFO" > "${SOURCE_WORKDIR}/cddbquery"
2736                         ERRORCODE=$?
2737                         case $ERRORCODE in
2738                                 0)  # success
2739                                 ;;
2740                                 12|13|14)
2741                                         # no match found in database, wget/fetch error,
2742                                         # or user requested not to use CDDB. Make up an
2743                                         # error code (503) that abcde will recognize later
2744                                         # and compensate by making a template
2745                                         echo 503 > "${SOURCE_WORKDIR}/cddbquery"
2746                                 ;;
2747                                 *) # strange and unknown error
2748                                         echo "ERRORCODE=$ERRORCODE"
2749                                         echo "abcde: $CDDBTOOL returned unknown error code"
2750                                 ;;
2751                         esac
2752                 fi
2753                 echo cddb-querycomplete >> "${ABCDETEMPDIR}/status"
2754         fi
2755
2756         ###########
2757         # cddbread
2758         ###########
2759
2760         # If it's not to be used, generate a template.
2761         # Then, display it (or them) and let the user choose/edit it
2762         if checkstatus cddb-readcomplete; then :; else
2763                 RESPONSECODE=$(head -n 1 "${SOURCE_WORKDIR}/cddbquery" | cut -f1 -d' ')
2764                 vecho "Obtaining CDDB results..."
2765                 case "$RESPONSECODE" in
2766                 200)
2767                         # One exact match, retrieve it
2768                         # 200 [section] [discid] [artist] / [title]
2769                         NUM_CDDB_MATCHES=$(($NUM_CDDB_MATCHES + 1))
2770                         $CDDBTOOL read "$CDDBURL" "$CDDBPROTO" "$CDDBUSER" "$CDDBHOST" \
2771                                           $(cut -f2,3 -d' ' "${SOURCE_WORKDIR}/cddbquery") \
2772                                           > "${SOURCE_WORKDIR}/cddbread.${NUM_CDDB_MATCHES}"
2773                         cat "${SOURCE_WORKDIR}/cddbquery" | cut -f2- -d' ' > "${SOURCE_WORKDIR}/cddbquery.${NUM_CDDB_MATCHES}"
2774                         echo "cddb" > "${SOURCE_WORKDIR}/datasource.${NUM_CDDB_MATCHES}"
2775                         echo "cddb-read-${NUM_CDDB_MATCHES}-complete" >> "${ABCDETEMPDIR}/status"
2776                         ;;
2777                 202|403|409|500|503)
2778                         # TODO: Explain these error codes a little more accurately:
2779                         # http://ftp.freedb.org/pub/freedb/misc/freedb_CDDB_protcoldoc.zip
2780                         # No match response:
2781                         ;;
2782                 210|211)
2783                         # Multiple exact, (possibly multiple) inexact matches
2784                         vecho -n "Retrieving multiple matches... "
2785                         grep -v '^[.]$' "${SOURCE_WORKDIR}/cddbquery" | (
2786                                 # IN A SUB-SHELL - VARIABLES MODIFIED
2787                                 # HERE DO NOT PERSIST IN THE PARENT
2788                                 read DISCINFO # eat top line
2789                                 while read DISCINFO
2790                                 do
2791                                         NUM_CDDB_MATCHES=$(($NUM_CDDB_MATCHES + 1))
2792                                         if checkstatus "cddb-read-${NUM_CDDB_MATCHES}-complete"; then :; else
2793                                                 $CDDBTOOL read "$CDDBURL" "$CDDBPROTO" "$CDDBUSER" "$CDDBHOST" \
2794                                                                   $(echo "$DISCINFO" | cut -f1,2 -d' ') \
2795                                                                   > "${SOURCE_WORKDIR}/cddbread.${NUM_CDDB_MATCHES}"
2796                                                 echo "$DISCINFO" > "${SOURCE_WORKDIR}/cddbquery.${NUM_CDDB_MATCHES}"
2797                                                 echo "cddb" > "${SOURCE_WORKDIR}/datasource.${NUM_CDDB_MATCHES}"
2798                                                 echo "cddb-read-${NUM_CDDB_MATCHES}-complete" >> "${ABCDETEMPDIR}/status"
2799                                         fi
2800                                 done )
2801                         # Need to re-count the entries here to be able
2802                         # to incrememnt $NUM_CDDB_MATCHES in the
2803                         # parent
2804                         NUM_CDDB_MATCHES=$(($NUM_CDDB_MATCHES + $(echo "${SOURCE_WORKDIR}/datasource.*" | wc -w)))
2805                         vecho "done."
2806                         ;;
2807                 999)
2808                         # Using local copy.
2809                         NUM_CDDB_MATCHES=$(($NUM_CDDB_MATCHES + 1))
2810                         echo "cddb-read-${NUM_CDDB_MATCHES}-complete" >> "${ABCDETEMPDIR}/status"
2811                         ;;
2812                 esac
2813                 echo "cddb-readcomplete" >> "${ABCDETEMPDIR}/status"
2814                 for file in ${SOURCE_WORKDIR}/cddbread.* ${SOURCE_WORKDIR}/cddbquery.* ${SOURCE_WORKDIR}/datasource.*; do
2815                         if [ -f "$file" ]; then
2816                                 cp "$file" "${ABCDETEMPDIR}"
2817                         fi
2818                 done
2819         fi
2820 }
2821
2822 # do_cddbedit
2823 do_cddbedit ()
2824 {
2825         if checkstatus cddb-edit >/dev/null; then
2826                 CDDBDATA="${ABCDETEMPDIR}/cddbread.$(checkstatus cddb-choice)"
2827                 VARIOUSARTISTS="$(checkstatus variousartists)"
2828                 VARIOUSARTISTSTYLE="$(checkstatus variousartiststyle)"
2829                 return 0
2830         fi
2831         if [ "$INTERACTIVE" = "y" ]; then
2832                 # We should show the CDDB results both when we are not using the local CDDB repo
2833                 # or when we are using it but we could not find a proper match
2834                 if [ "$CDDBUSELOCAL" = "y" ] && [ "$CDDBLOCALSTATUS" = "notfound" ] || [ ! "$CDDBUSELOCAL" = "y" ]; then
2835                         # Display the ${ABCDETEMPDIR}/cddbchoices file created above
2836                         if [ -r "${ABCDETEMPDIR}/cddbchoices" ]; then
2837                                 CHOICE=$(checkstatus cddb-choice)
2838                                 if [ -n "$CHOICE" ] ; then
2839                                         case $NUM_CDDB_MATCHES in
2840                                                 1) cat "${ABCDETEMPDIR}/cddbchoices" ;;
2841                                                 *)
2842                                                 ATITLE=$(grep -a ^DTITLE= "${ABCDETEMPDIR}/cddbread.$CHOICE" | cut -f2- -d= | tr -d \\r\\n)
2843                                                 SOURCE=$(cat "${ABCDETEMPDIR}/datasource.$CHOICE")
2844                                                 echo "Selected: #$CDCHOICENUM ($SOURCE) ($ATITLE)"
2845                                                 do_cddbparse "${ABCDETEMPDIR}/cddbread.$CHOICE"
2846                                                 ;;
2847                                         esac
2848                                 else
2849                                         page "${ABCDETEMPDIR}/cddbchoices"
2850                                         CDDBCHOICENUM=""
2851                                         # Setting the choice to an impossible integer to avoid errors in the numeric comparisons
2852                                         CDCHOICENUM=-1
2853                                         # I'll take CDDB read #3 for $400, Alex
2854                                         while [ $CDCHOICENUM -lt 0 ] || [ $CDCHOICENUM -gt $NUM_CDDB_MATCHES ]; do
2855                                                 echo -n "Which entry would you like abcde to use (0 for none)? [0-$NUM_CDDB_MATCHES]: " >&2
2856                                                 read CDDBCHOICE
2857                                                 [ X"$CDDBCHOICE" = "X" ] && CDDBCHOICE=1
2858                                                 if echo $CDDBCHOICE | grep -E "[[:space:]]*[[:digit:]]+,[[:digit:]]+[[:space:]]*" > /dev/null 2>&1 ; then
2859                                                         if [ ! X"$DIFF" = "X" ]; then
2860                                                                 PARSECHOICE1=$(echo $CDDBCHOICE | cut -d"," -f1 | xargs printf %d 2>/dev/null)
2861                                                                 PARSECHOICE2=$(echo $CDDBCHOICE | cut -d"," -f2 | xargs printf %d 2>/dev/null)
2862                                                                 if [ "$PARSECHOICE1" -lt 1 ] || [ "$PARSECHOICE1" -gt "$NUM_CDDB_MATCHES" ] || \
2863                                                                    [ "$PARSECHOICE2" -lt 1 ] || [ "$PARSECHOICE2" -gt "$NUM_CDDB_MATCHES" ] || \
2864                                                                    [ "$PARSECHOICE1" -eq "$PARSECHOICE2" ]; then
2865                                                                         echo "Invalid diff range. Please select two comma-separated numbers between 1 and $NUM_CDDB_MATCHES" >&2
2866                                                                 else
2867                                                                         # We parse the 2 choices to diff, store them in temporary files and diff them.
2868                                                                         for PARSECHOICE in $(echo $CDDBCHOICE | tr , \ ); do
2869                                                                                 do_cddbparse "${ABCDETEMPDIR}/cddbread.$PARSECHOICE" \
2870                                                                                                          > "${ABCDETEMPDIR}/cddbread.parsechoice.$PARSECHOICE"
2871                                                                         done
2872                                                                         echo "Showing diff between choices $PARSECHOICE1 and $PARSECHOICE2..." \
2873                                                                                  > "${ABCDETEMPDIR}/cddbread.diff"
2874                                                                         $DIFF $DIFFOPTS "${ABCDETEMPDIR}/cddbread.parsechoice.$PARSECHOICE1" \
2875                                                                                   "${ABCDETEMPDIR}/cddbread.parsechoice.$PARSECHOICE2" \
2876                                                                                   >> "${ABCDETEMPDIR}/cddbread.diff"
2877                                                                         page "${ABCDETEMPDIR}/cddbread.diff"
2878                                                                 fi
2879                                                         else
2880                                                                 echo "The diff program was not found in your path. Please choose a number between 0 and $NUM_CDDB_MATCHES." >&2
2881                                                         fi
2882                                                 elif echo $CDDBCHOICE | grep -E "[[:space:]]*[[:digit:]]+[[:space:]]*" > /dev/null 2>&1 ; then
2883                                                         # Make sure we get a valid choice
2884                                                         CDCHOICENUM=$(echo $CDDBCHOICE | xargs printf %d 2>/dev/null)
2885                                                         if [ "$CDCHOICENUM" -lt 0 ] || [ "$CDCHOICENUM" -gt "$NUM_CDDB_MATCHES" ]; then
2886                                                                 echo "Invalid selection. Please choose a number between 0 and $NUM_CDDB_MATCHES." >&2
2887                                                         fi
2888                                                 fi
2889                                         done
2890                                         if [ "$CDCHOICENUM" = "0" ]; then
2891                                                 vecho "Creating empty CDDB template..."
2892                                                 UNKNOWNDISK=y
2893                                                 $CDDBTOOL template $(cat "${ABCDETEMPDIR}/cddbdiscid") > "${ABCDETEMPDIR}/cddbread.0"
2894                                                 echo "template" > "${ABCDETEMPDIR}/datasource.0"
2895                                         else
2896                                                 ATITLE=$(grep -a ^DTITLE= "${ABCDETEMPDIR}/cddbread.$CDCHOICENUM" | cut -f2- -d= | tr -d \\r\\n)
2897                                                 SOURCE=$(cat "${ABCDETEMPDIR}/datasource.$CDCHOICENUM")
2898                                                 echo "Selected: #$CDCHOICENUM ($SOURCE) ($ATITLE)" >&2
2899                                         fi
2900                                         do_cddbparse "${ABCDETEMPDIR}/cddbread.$CDCHOICENUM"
2901                                         echo "cddb-choice=$CDCHOICENUM" >> "${ABCDETEMPDIR}/status"
2902                                 fi
2903                         fi
2904                 else
2905                         # We need some code to show the selected option when local repository is selected and we have found a match
2906                         vecho "Using cached CDDB match..." >&2
2907                         # Display the ${ABCDETEMPDIR}/cddbchoices file created above
2908                         if [ -r "${ABCDETEMPDIR}/cddbchoices" ]; then
2909                                 CHOICE=$(checkstatus cddb-choice)
2910                                 if [ "$USELOCALRESP" = "y" ]; then :; else
2911                                         if [ -n "$CHOICE" ] ; then
2912                                                 case $NUM_CDDB_MATCHES in
2913                                                         0)
2914                                                         UNKNOWNDISK=y
2915                                                         echo "Selected template."
2916                                                         ;;
2917                                                         1) cat "${ABCDETEMPDIR}/cddbchoices" ;;
2918                                                         *)
2919                                                         echo "Selected: #$CHOICE"
2920                                                         do_cddbparse "${ABCDETEMPDIR}/cddbread.$CHOICE"
2921                                       &n