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