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