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