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