Encode to m4a container with either FFmpeg or avconv
[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.7.1-UNRELEASED'
15
16 usage ()
17 {
18 echo "This is abcde v$VERSION."
19 echo "Usage: abcde [options] [tracks]"
20 echo "Options:"
21 echo "-1     Encode the whole CD in a single file"
22 echo "-a <action1[,action2]...>"
23 echo "       Actions to perform:"
24 echo "       cddb,read,getalbumart,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,wv,ape). 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_release ] ; then
360                                 case $X in
361                                         oggenc)         MISSING_PACKAGE=vorbis-tools ;;
362                                         lame|flac)      MISSING_PACKAGE=$X ;;
363                                 esac
364                                 log info "Hint: 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 ^TTITLE$CDDBTRACKNUM= "$CDDBDATA" | head -n 1 | cut -f2- -d= | tr -d \[:cntrl:\] | sed 's/\ \+$//')"
415                 ;;
416         TRACKNAME)
417                 TRACKNAME="$(grep ^TTITLE$CDDBTRACKNUM= "$CDDBDATA" | cut -f2- -d= | tr -d \[:cntrl:\] | sed 's/\ \+$//')"
418                 ;;
419         TRACK-INFO)
420                 grep ^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="$(mungefilename "$TRACKNAME")"
530                                 ARTISTFILE="$(mungefilename "$TRACKARTIST")"
531                                 ALBUMFILE="$(mungefilename "$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                 *)                       return 1 ;;
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                                 eyed3*)
843                                         # FIXME # track numbers in mp3 come with 1/10, so we cannot
844                                         # happily substitute them with $TRACKNUM
845                                         case "$ID3SYNTAX" in
846                                                 eyed3_06) addopts=( \
847                                                         ${ENCODING:+--set-encoding="$ENCODING"} \
848                                                         ${TPE2:+--set-text-frame=TPE2:"$TPE2"} \
849                                         # We set 'recording-date' so the date tag will show 
850                                         # in Audacious, vlc and friends...          Andrew.
851                                                         ${CDYEAR:+--set-text-frame="TDRC:$CDYEAR"} \
852                                                         ${COMMENTOUTPUT:+--comment=::"$COMMENTOUTPUT"} \
853                                                         );;
854                                                 *) addopts=( \
855                                                         ${ENCODING:+--encoding="$ENCODING"} \
856                                                         ${TPE2:+--text-frame=TPE2:"$TPE2"} \
857                                         # We set 'recording-date' so the date tag will show 
858                                         # in Audacious, vlc and friends...           Andrew.
859                                                         ${CDYEAR:+--text-frame="TDRC:$CDYEAR"} \
860                                                         ${COMMENTOUTPUT:+--comment "$COMMENTOUTPUT"} \
861                                                         );;
862                                         esac
863                                         run_command tagtrack-$OUTPUT-$1 nice $ENCNICE $TAGGER $TAGGEROPTS \
864                                                 -A "$DALBUM" \
865                                                 -a "$TRACKARTIST" -t "$TRACKNAME" \
866                                                 -G "$GENREID" -n "${TRACKNUM:-$1}" \
867                                                 ${TRACKNUM:+-N "$TRACKS"} \
868                                                 "${addopts[@]}" \
869                                                 "$ABCDETEMPDIR/track$1.$OUTPUT"
870                                         ;;
871                                 *)
872                                         log error "Internal error: ID3SYNTAX has an illegal value"
873                                         exit 1
874                                         ;;
875                         esac
876                         ;;
877                 vorbis|ogg)
878                         case "$OGGENCODERSYNTAX" in
879                                 vorbize|oggenc)
880                                         # vorbiscomment can't do in-place modification, mv the file first
881                                         if [ -f "$ABCDETEMPDIR/track$1.$OGGOUTPUTCONTAINER" -a ! -f "$ABCDETEMPDIR/track$1.uncommented.$OGGOUTPUTCONTAINER" ]; then
882                                                 mv "$ABCDETEMPDIR/track$1.$OGGOUTPUTCONTAINER" "$ABCDETEMPDIR/track$1.uncommented.$OGGOUTPUTCONTAINER"
883                                         fi
884                                         (
885                                         # These are from
886                                         # http://www.xiph.org/vorbis/doc/v-comment.html
887
888                                         echo ARTIST="$TRACKARTIST"
889                                         echo ALBUM="$DALBUM"
890                                         echo TITLE="$TRACKNAME"
891                                         if [ -n "$CDYEAR" ]; then
892                                                 echo DATE="$CDYEAR"
893                                         fi
894                                         if [ -n "$CDGENRE" ]; then
895                                                 echo GENRE="$CDGENRE"
896                                         fi
897                                         echo TRACKNUMBER=${TRACKNUM:-$1}
898                                         # TRACKTOTAL is not in the proposed, minimal list of standard field names from
899                                         # xiph.org: http://www.xiph.org/vorbis/doc/v-comment.html but is in common usage
900                                         # and read by mediainfo, ffprobe, vlc, Aqualung, ogg123, Foobar. And now abcde :)
901                                         # The tag is quietly ignored by  Audacious, MPlayer, mpv, XMMS....
902                                         echo TRACKTOTAL="${TRACKS}"
903                                         if [ -n "$DISCNUMBER" ]; then
904                                                 echo DISCNUMBER="$DISCNUMBER"
905                                         fi
906                                         echo CDDB=$CDDBDISCID
907                                         if [ "$(eval echo ${COMMENT})" != "" ]; then
908                                                 case "$COMMENTOUTPUT" in
909                                                         *=*) echo "$COMMENTOUTPUT";;
910                                                         *)   echo COMMENT="$COMMENTOUTPUT";;
911                                                 esac
912                                         fi
913                                         ) | run_command tagtrack-$OUTPUT-$1 nice $ENCNICE \
914                                                 $VORBISCOMMENT $VORBISCOMMENTOPTS -w \
915                                                 "$ABCDETEMPDIR/track$1.uncommented.$OGGOUTPUTCONTAINER" "$ABCDETEMPDIR/track$1.$OGGOUTPUTCONTAINER"
916                                         # Doublecheck that the commented file was created
917                                         # successfully before wiping the original
918                                         if [ -f "$ABCDETEMPDIR/track$1.$OGGOUTPUTCONTAINER" ]; then
919                                                 rm -f "$ABCDETEMPDIR/track$1.uncommented.$OGGOUTPUTCONTAINER"
920                                         else
921                                                 mv "$ABCDETEMPDIR/track$1.uncommented.$OGGOUTPUTCONTAINER" "$ABCDETEMPDIR/track$1.$OGGOUTPUTCONTAINER"
922                                         fi
923                                         ;;
924                         esac
925                         ;;
926                 opus)
927                         run_command tagtrack-$OUTPUT-$1 true
928                         ;;
929                 flac)
930                         (
931                         echo ARTIST="$TRACKARTIST"
932                         echo ALBUM="$DALBUM"
933                         echo TITLE="$TRACKNAME"
934                         if [ -n "$CDYEAR" ]; then
935                                 echo DATE="$CDYEAR"
936                         fi
937                         if [ -n "$CDGENRE" ]; then
938                                 echo GENRE="$CDGENRE"
939                         fi
940                         echo TRACKNUMBER="${TRACKNUM:-$1}"
941                         # TRACKTOTAL is not in the proposed, minimal list of standard field names from
942                         # xiph.org: http://www.xiph.org/vorbis/doc/v-comment.html but is in common usage
943                         # and read by mediainfo, ffprobe, vlc, Aqualung, ogg123, Foobar. And now abcde :)
944                         # The tag is quietly ignored by  Audacious, MPlayer, mpv, XMMS....
945                         echo TRACKTOTAL="${TRACKS}"
946                         if [ -n "$DISCNUMBER" ]; then
947                                 echo DISCNUMBER="$DISCNUMBER"
948                         fi
949                         echo CDDB="$CDDBDISCID"
950                         if [ "$(eval echo ${COMMENT})" != "" ]; then
951                                 case "$COMMENTOUTPUT" in
952                                         *=*) echo "$COMMENTOUTPUT";;
953                                         *)   echo COMMENT="$COMMENTOUTPUT";;
954                                 esac
955                         fi
956                         ) | run_command tagtrack-$OUTPUT-$1 nice $ENCNICE $METAFLAC $METAFLACOPTS ${IMPORTCUESHEET:+--import-cuesheet-from="$ABCDETEMPDIR/$CUEFILE"} \
957                         --import-tags-from=- "$ABCDETEMPDIR/track$1.$FLACOUTPUTCONTAINER"
958                         ;;
959                 spx)
960                         run_command tagtrack-$OUTPUT-$1 true
961                         ;;
962                 mpc)
963                         run_command tagtrack-$OUTPUT-$1 true
964                         ;;
965                 wv)
966                         run_command tagtrack-$OUTPUT-$1 true
967                         ;;
968                 ape)
969                         # This tagging syntax is suitable for Robert Muth's application 'apetag', the Monkey's Audio 
970                         # Console port (mac) used for encoding does not have the ability to tag.
971                         run_command tagtrack-$OUTPUT-$1 nice $ENCNICE "$APETAG" -i "$ABCDETEMPDIR/track$1.ape" -m overwrite \
972                         -p artist="$TRACKARTIST" -p album="$DALBUM" -p title="$TRACKNAME" -p track=${TRACKNUM:-$1} \
973                         -p year="$CDYEAR" -p genre="$CDGENRE" ${COMMENTOUTPUT:+-p comment="$COMMENTOUTPUT"} 
974                         ;;
975                 aac)
976                         run_command tagtrack-$OUTPUT-$1 true
977                         ;;
978                 m4a)
979                         case "$AACENCODERSYNTAX" in
980                                 fdkaac)
981                                         # We will use inline tagging...
982                                         run_command tagtrack-$OUTPUT-$1 true
983                                         ;;
984                                 neroAacEnc)
985                                         # Tag post encode with neroAacTag...
986                                         run_command tagtrack-$OUTPUT-$1 nice $ENCNICE "$NEROAACTAG" "$ABCDETEMPDIR/track$1.m4a" \
987                                         -meta:artist="$TRACKARTIST" -meta:album="$DALBUM" -meta:title="$TRACKNAME" -meta:track=${TRACKNUM:-$1} \
988                                         -meta:year="$CDYEAR" -meta:genre="$CDGENRE" -meta:comment="$COMMENT"
989                                         ;;
990                                 faac)
991                                         run_command tagtrack-$OUTPUT-$1 true   
992                                         ;;
993                                 qaac)
994                                         run_command tagtrack-$OUTPUT-$1 true   
995                                         ;;
996                                 fhgaacenc)
997                                         # Tag post encode with AtomicParsley. Note that previous problems with seg fault when using
998                                         # 'overWrite' cannot be reproduced with newer versions: https://bitbucket.org/wez/atomicparsley
999                                         run_command tagtrack-$OUTPUT-$1 nice $ENCNICE "$ATOMICPARSLEY" "$ABCDETEMPDIR/track$1.m4a" \
1000                                         --artist="$TRACKARTIST" --album="$DALBUM" --title="$TRACKNAME" --tracknum=${TRACKNUM:-$1} \
1001                                         --year="$CDYEAR" --genre="$CDGENRE" --comment="$COMMENT" $ATOMICPARSLEYOPTS --overWrite
1002                                         ;;
1003                                 ffmpeg)
1004                                         run_command tagtrack-$OUTPUT-$1 true   
1005                                 ;;
1006                         esac
1007                         ;;
1008                 wav)
1009                         run_command tagtrack-$OUTPUT-$1 true
1010                         ;;
1011                 esac
1012         done
1013         if checkerrors "tagtrack-(.{3,6})-$1"; then :; else
1014                 run_command tagtrack-$1 true
1015         fi
1016 }
1017
1018 # do_nogap_encode
1019 # variables used:
1020 # OUTPUTTYPE, {FOO}ENCODERSYNTAX, ENCNICE, ENCODER, ENCODEROPTS
1021 do_nogap_encode ()
1022 {
1023         # The commands here don't go through run_command because they're never
1024         # supposed to be silenced
1025         echo "Encoding gapless MP3 tracks: $TRACKQUEUE"
1026         for OUTPUT in $(echo $OUTPUTTYPE | tr , \ )
1027         do
1028                 case "$OUTPUT" in
1029                 mp3)
1030                         case "$MP3ENCODERSYNTAX" in
1031                         lame|toolame)
1032                                 (
1033                                 cd "$ABCDETEMPDIR"
1034                                 TRACKFILES=
1035                                 for UTRACKNUM in $TRACKQUEUE
1036                                 do
1037                                         TRACKFILES="$TRACKFILES track$UTRACKNUM.wav"
1038                                 done
1039                                 nice $ENCNICE $MP3ENCODER $MP3ENCODEROPTS --nogap $TRACKFILES
1040                                 RETURN=$?
1041                                 if [ "$RETURN" != "0" ]; then
1042                                         echo "nogap-encode: $ENCODER returned code $RETURN" >> errors
1043                                 else
1044                                         for UTRACKNUM in $TRACKQUEUE
1045                                         do
1046                                                 run_command encodetrack-$OUTPUT-$UTRACKNUM true
1047                                                 #run_command encodetrack-$UTRACKNUM true
1048                                         done
1049                                 fi
1050                                 )
1051                                 ;;
1052                         esac
1053                         ;;
1054                 esac
1055         done
1056         if checkerrors "nogap-encode"; then :; else
1057                 if [ ! "$KEEPWAVS" = "y" ] ; then
1058                         if [ ! "$KEEPWAVS" = "move" ] ; then
1059                                 rm -f "$IN"
1060                         fi
1061                 fi
1062         fi
1063         # Other encoders fall through to normal encoding as the tracks have not
1064         # been entered in the status file.
1065 }
1066
1067 # do_encode [tracknumber] [hostname]
1068 # If no hostname is specified, encode locally
1069 # variables used:
1070 # TRACKS, TRACKNAME, TRACKARTIST, DISTMP3, DISTMP3OPTS, {FOO}ENCODERSYNTAX, OUTPUTTYPE, ENCODEROPTS, 
1071 # DALBUM, DARTIST, ENCNICE, CDYEAR, CDGENRE, COMMENT
1072 do_encode ()
1073 {
1074         if [ "$USEPIPES" = "y" ]; then
1075                 case "$OUTPUT" in
1076                         mp3)
1077                                 TEMPARG="PIPE_$MP3ENCODERSYNTAX"
1078                                 ;;
1079                         vorbis|ogg)
1080                                 TEMPARG="PIPE_$OGGENCODERSYNTAX"
1081                                 ;;
1082                         opus)
1083                                 TEMPARG="PIPE_$OPUSENCODERSYNTAX"
1084                                 ;;
1085                         flac)
1086                                 TEMPARG="PIPE_$FLACENCODERSYNTAX"
1087                                 ;;
1088                         spx)
1089                                 TEMPARG="PIPE_$SPEEXENCODER"
1090                                 ;;
1091                         mpc)
1092                                 TEMPARG="PIPE_$MPCENCODER"
1093                                 ;;
1094                         wv)
1095                                 TEMPARG="PIPE_$WVENCODERSYNTAX"
1096                                 ;;
1097                         aac)
1098                                 TEMPARG="PIPE_$AACENCODERSYNTAX"
1099                                 ;;
1100                         m4a)
1101                                 TEMPARG="PIPE_$AACENCODERSYNTAX"
1102                                 ;;
1103                 esac
1104                 IN="$( eval echo "\$$TEMPARG" )"
1105         else
1106                 IN="$ABCDETEMPDIR/track$1.wav"
1107         fi
1108         # We need IN to proceed, if we are not using pipes.
1109         if [ -s "$IN" -o X"$USEPIPES" = "Xy" ] ; then
1110                 for TMPOUTPUT in $(echo $OUTPUTTYPE | tr , \ )
1111                 do
1112                         case "$TMPOUTPUT" in
1113                                 vorbis|ogg)
1114                                         OUTPUT=$OGGOUTPUTCONTAINER
1115                                         ;;
1116                                 opus)
1117                                         OUTPUT=$OPUSOUTPUTCONTAINER
1118                                         ;;
1119                                 flac)
1120                                         OUTPUT=$FLACOUTPUTCONTAINER
1121                                         ;;
1122                                 *)
1123                                         OUTPUT=$TMPOUTPUT
1124                                         ;;
1125                         esac
1126                         OUT="$ABCDETEMPDIR/track$1.$OUTPUT"
1127                         if [ "$NOGAP" = "y" ] && checkstatus encodetrack-$OUTPUT-$1 ; then
1128                                 continue
1129                         fi
1130                         if [ X"$USEPIPES" = "Xy" ]; then
1131                                 RUN_COMMAND=""
1132                                 # We need a way to store the creation of the files when using PIPES
1133                                 RUN_COMMAND_PIPES="run_command encodetrack-$OUTPUT-$1 true"
1134                                 # When piping it does not make sense to have a higher nice for
1135                                 # reading than for encoding, since it will be hold by the
1136                                 # encoding process. Setting an effective nice, to calm down a
1137                                 # bit the reading process.
1138                                 EFFECTIVE_NICE=$READNICE
1139                         else
1140                                 run_command '' echo "Encoding track $1 of $TRACKS: $TRACKNAME..."
1141                                 RUN_COMMAND="run_command encodetrack-$OUTPUT-$1"
1142                                 EFFECTIVE_NICE=$ENCNICE
1143                         fi
1144                         case "$OUTPUT" in
1145                         mp3)
1146                                 case "$2" in
1147                                 %local*%)
1148                                         case "$MP3ENCODERSYNTAX" in
1149                                         lame|toolame|gogo) $RUN_COMMAND nice $EFFECTIVE_NICE $MP3ENCODER $MP3ENCODEROPTS "$IN" "$OUT" ;;
1150                                         bladeenc) $RUN_COMMAND nice $EFFECTIVE_NICE $MP3ENCODER $MP3ENCODEROPTS -quit "$IN" "$OUT" ;;
1151                                         l3enc|xingmp3enc) $RUN_COMMAND nice $EFFECTIVE_NICE $MP3ENCODER "$IN" "$OUT" $MP3ENCODEROPTS ;;
1152                                         mp3enc) $RUN_COMMAND nice $EFFECTIVE_NICE $MP3ENCODER -if "$IN" -of "$OUT" $MP3ENCODEROPTS ;;
1153                                         esac
1154                                         ;;
1155                                 *)
1156                                         $RUN_COMMAND nice $DISTMP3NICE $DISTMP3 $DISTMP3OPTS "$2" "$IN" "$OUT" >/dev/null 2>&1
1157                                         ;;
1158                                 esac
1159                                 ;;
1160                         vorbis|ogg)
1161                                 case "$2" in
1162                                 %local*%)
1163                                         case "$OGGENCODERSYNTAX" in
1164                                         vorbize) $RUN_COMMAND nice $EFFECTIVE_NICE $OGGENCODER $OGGENCODEROPTS -w "$OUT" "$IN" ;;
1165                                         oggenc) $RUN_COMMAND nice $EFFECTIVE_NICE $OGGENCODER $OGGENCODEROPTS -o "$OUT" "$IN" ;;
1166                                         esac
1167                                         ;;
1168                                 *)
1169                                         $RUN_COMMAND nice $DISTMP3NICE $DISTMP3 $DISTMP3OPTS "$2" "$IN" "$OUT" >/dev/null 2>&1
1170                                         ;;
1171                                 esac
1172                                 ;;
1173                         opus)
1174                                 case "$2" in
1175                                 %local*%)
1176                                         case "$OPUSENCODERSYNTAX" in
1177                                         opusenc)
1178                                         # Tag the file at encode time, as it can't be done after encoding.
1179                                                 if [ "$DOTAG" = "y" ]; then
1180                                                         $RUN_COMMAND nice $EFFECTIVE_NICE $OPUSENCODER $OPUSENCODEROPTS --artist "$TRACKARTIST" \
1181                                                         --album "$DALBUM" --title "$TRACKNAME" --genre "$CDGENRE" --date "$CDYEAR" --comment TRACKNUMBER="$1" \
1182                                                         ${COMMENT:+--comment COMMENT="$COMMENT"} "$IN" "$OUT"
1183                                                 else
1184                                                         $RUN_COMMAND nice $EFFECTIVE_NICE $OPUSENCODER $OPUSENCODEROPTS "$IN" "$OUT"
1185                                                 fi
1186                                         ;;
1187                                         esac
1188                                         ;;
1189                                 *)
1190                                         $RUN_COMMAND nice $DISTMP3NICE $DISTMP3 $DISTMP3OPTS "$2" "$IN" "$OUT" >/dev/null 2>&1
1191                                         ;;
1192                                 esac
1193                                 ;;
1194                         flac)
1195                                 case "$2" in
1196                                 %local*%)
1197                                         case "$FLACENCODERSYNTAX" in
1198                                         flac) $RUN_COMMAND nice $EFFECTIVE_NICE $FLACENCODER -f $FLACENCODEROPTS -o "$OUT" "$IN" ;;
1199                                                 esac
1200                                                 ;;
1201                                         *)
1202                                                 vecho -n "DISTMP3:"
1203                                                 vecho "$DISTMP3 $DISTMP3OPTS $2 $IN $OUT >/dev/null 2>&1"
1204                                                 $RUN_COMMAND nice $DISTMP3NICE $DISTMP3 $DISTMP3OPTS "$2" "$IN" "$OUT" > /dev/null 2>&1
1205                                         ;;
1206                                 esac
1207                                 ;;
1208                         spx)
1209                                 if [ "$(eval echo ${COMMENT})" != "" ]; then
1210                                         case "$COMMENT" in
1211                                                 *=*) ;;
1212                                                 *)   COMMENT="COMMENT=$COMMENT" ;;
1213                                         esac
1214                                 fi
1215                                 # Tag the file at encode time, as it can't be done after encoding.
1216                                 if [ "$DOTAG" = "y" ]; then
1217                                         $RUN_COMMAND nice $EFFECTIVE_NICE $SPEEXENCODER $SPEEXENCODEROPTS --author "$TRACKARTIST" --title "$TRACKNAME" \
1218                                         ${COMMENT:+--comment "$COMMENT"} "$IN" "$OUT"
1219                                 else
1220                                         $RUN_COMMAND nice $EFFECTIVE_NICE $SPEEXENCODER $SPEEXENCODEROPTS "$IN" "$OUT"
1221                                 fi
1222                                 ;;
1223                         mpc)
1224                                 # Tag the file inline at encode time.
1225                                 if [ "$DOTAG" = "y" ]; then
1226                                         $RUN_COMMAND nice $EFFECTIVE_NICE $MPCENCODER $MPCENCODEROPTS --artist "$TRACKARTIST" --album "$DALBUM" \
1227                                         --title "$TRACKNAME" --track "$1" --genre "$CDGENRE" --year "$CDYEAR" ${COMMENT:+--comment "$COMMENT"} "$IN" "$OUT"
1228                                 else
1229                                         $RUN_COMMAND nice $EFFECTIVE_NICE $MPCENCODER $MPCENCODEROPTS "$IN" "$OUT"
1230                                 fi
1231                                 ;;
1232                         wv)
1233                                 if [ "$DOTAG" = "y" ]; then
1234                                         $RUN_COMMAND nice $EFFECTIVE_NICE $WVENCODER $WVENCODEROPTS -w Artist="$TRACKARTIST" -w Album="$DALBUM" \
1235                                         -w Title="$TRACKNAME" -w Track="$1" -w Genre="$CDGENRE" -w Year="$CDYEAR" ${COMMENT:+-w Comment="$COMMENT"} "$IN" -o "$OUT"
1236                                 else
1237                                         $RUN_COMMAND nice $EFFECTIVE_NICE $WVENCODER $WVENCODEROPTS "$IN" -o "$OUT"
1238                                 fi
1239                                 ;;
1240                         ape)
1241                                 $RUN_COMMAND nice $EFFECTIVE_NICE $APENCODER "$IN" "$OUT" $APENCODEROPTS
1242                                 ;;
1243                         aac)
1244                                 # aac container is only used to catch faac encoded files where faac 
1245                                 # is compiled without mp4 support (with libmp4v2).
1246                                 $RUN_COMMAND nice $EFFECTIVE_NICE $AACENCODER $AACENCODEROPTS -o "$OUT" "$IN"
1247                                 ;;
1248                         m4a)
1249                                 case "$AACENCODERSYNTAX" in
1250                                         faac)
1251                                                 if [ "$DOTAG" = "y" ]; then
1252                                                         $RUN_COMMAND nice $EFFECTIVE_NICE $AACENCODER $AACENCODEROPTS  --artist "$TRACKARTIST" --album "$DALBUM" \
1253                                                         --title "$TRACKNAME" --track ${TRACKNUM:-$1} --year "$CDYEAR" --genre "$CDGENRE" --comment "$COMMENT" -o "$OUT" "$IN"
1254                                                 else 
1255                                                         $RUN_COMMAND nice $EFFECTIVE_NICE $AACENCODER $AACENCODEROPTS -o "$OUT" "$IN"   
1256                                                 fi
1257                                                 ;;
1258                                         neroAacEnc)
1259                                                 $RUN_COMMAND nice $EFFECTIVE_NICE $AACENCODER $AACENCODEROPTS -if "$IN" -of "$OUT"
1260                                                 ;;
1261                                         fdkaac)      
1262                                                 if [ "$DOTAG" = "y" ]; then
1263                                                         $RUN_COMMAND nice $EFFECTIVE_NICE $AACENCODER $AACENCODEROPTS --artist "$TRACKARTIST" --album "$DALBUM" \
1264                                                         --title "$TRACKNAME" --track "$1" --genre "$CDGENRE" --date "$CDYEAR" --comment "$COMMENT" "$IN" -o "$OUT"
1265                                                 else
1266                                                         $RUN_COMMAND nice $EFFECTIVE_NICE $AACENCODER $AACENCODEROPTS "$IN" -o "$OUT"
1267                                                 fi
1268                                                 ;;
1269                                         qaac)
1270                                                 if [ "$DOTAG" = "y" ]; then
1271                                                         $RUN_COMMAND nice $EFFECTIVE_NICE $WINE $AACENCODER $AACENCODEROPTS  --artist "$TRACKARTIST" --album "$DALBUM" \
1272                                                         --title "$TRACKNAME" --track ${TRACKNUM:-$1} --date "$CDYEAR" --genre "$CDGENRE" --comment "$COMMENT" -o "$OUT" "$IN"
1273                                                 else 
1274                                                         $RUN_COMMAND nice $EFFECTIVE_NICE $WINE $AACENCODER $AACENCODEROPTS -o "$OUT" "$IN"
1275                                                 fi
1276                                                 ;;
1277                                         fhgaacenc)
1278                                                 $RUN_COMMAND nice $EFFECTIVE_NICE $WINE $AACENCODER $AACENCODEROPTS "$IN" "$OUT"
1279                                                 ;;
1280                                         ffmpeg)
1281                                                 if [ "$DOTAG" = "y" ]; then
1282                                                         $RUN_COMMAND nice $EFFECTIVE_NICE $AACENCODER -i "$IN" $AACENCODEROPTS -metadata artist="$TRACKARTIST" \
1283                                                         -metadata album="$DALBUM" -metadata title="$TRACKNAME" -metadata track=${TRACKNUM:-$1} -metadata date="$CDYEAR" \
1284                                                         -metadata genre="$CDGENRE" -metadata comment="$COMMENT" "$OUT" 
1285                                                 else 
1286                                                         $RUN_COMMAND nice $EFFECTIVE_NICE -i "$IN" $AACENCODER $AACENCODEROPTS "$OUT"
1287                                                 fi
1288                                                 ;;
1289                                         esac
1290                                 ;;
1291                         wav)
1292                                 # In case of wav output we need nothing. Just keep the wavs.
1293                                 # But we need the following to allow full logging and subsequent 
1294                                 # successful cleaning of $ABCDETEMPDIR.
1295                                 echo "encodetrack-$OUTPUT-$UTRACKNUM" >> "$ABCDETEMPDIR/status"
1296                                 ;;
1297                         esac
1298                         $RUN_COMMAND_PIPES
1299                 done
1300                 # Only remove .wav if the encoding succeeded
1301                 if checkerrors "encodetrack-(.{3,6})-$1"; then :; else
1302                         run_command encodetrack-$1 true
1303                         if [ ! "$KEEPWAVS" = "y" ] ; then
1304                                 if [ ! "$KEEPWAVS" = "move" ] ; then
1305                                         rm -f "$IN"
1306                                 fi
1307                         fi
1308                 fi
1309         else
1310                 run_command "" echo "HEH! The file we were about to encode disappeared:"
1311                 run_command "" echo ">> $IN"
1312                 run_command encodetrack-$1 false
1313         fi
1314 }
1315
1316 # do_preprocess [tracknumber]
1317 # variables used:
1318 # TRACKS, TRACKNAME, TRACKARTIST, DISTMP3, DISTMP3OPTS, {FOO}ENCODERSYNTAX, OUTPUTTYPE, ENCODEROPTS, DALBUM, DARTIST, ENCNICE, CDYEAR, CDGENRE, COMMENT
1319 #do_preprocess ()
1320 #{
1321 #       IN="$ABCDETEMPDIR/track$1.wav"
1322 #       # We need IN to proceed.
1323 #       if [ -s "$IN" ] ; then
1324 #               for OUTPUT in $(echo $OUTPUTTYPE | tr , \ )
1325 #               do
1326 #                       #OUT="$ABCDETEMPDIR/track$1.$OUTPUT"
1327 #                       run_command '' echo "Pre-processing track $1 of $TRACKS..."
1328 #                       case "$POSTPROCESSFORMAT" in
1329 #                       all|wav*)
1330 #                               run_command preprocess-$OUTPUT-$1 nice $PRENICE $WAV_PRE $IF $OF ;;
1331 #                       mp3)
1332 #                               run_command preprocess-$OUTPUT-$1 nice $PRENICE $MP3_PRE $IF $OF ;;
1333 #                       ogg)
1334 #                               run_command preprocess-$OUTPUT-$1 nice $PRENICE $OGG_PRE $IF $OF ;;
1335 #                       flac)
1336 #                               run_command preprocess-$OUTPUT-$1 nice $PRENICE $FLAC_PRE $IF $OF ;;
1337 #                       spx)
1338 #                               run_command preprocess-$OUTPUT-$1 nice $PRENICE $SPX_PRE $IF $OF ;;
1339 #                       esac
1340 #               done
1341 #               # Only remove .wav if the encoding succeeded
1342 #               if checkerrors "preprocess-(.{3,4})-$1"; then
1343 #                       run_command preprocess-$1 false
1344 #               else
1345 #                       run_command preprocess-$1 true
1346 #               fi
1347 #       else
1348 #               if [ "$(checkstatus encode-output)" = "loud" ]; then
1349 #                       echo "HEH! The file we were about to pre-process disappeared:"
1350 #                       echo ">> $IN"
1351 #               fi
1352 #               run_command preprocess-$1 false
1353 #       fi
1354 #}
1355
1356
1357 # do_postprocess [tracknumber]
1358 # variables used:
1359 # TRACKS, TRACKNAME, TRACKARTIST, DISTMP3, DISTMP3OPTS, {FOO}ENCODERSYNTAX, OUTPUTTYPE, ENCODEROPTS, DALBUM, DARTIST, ENCNICE, CDYEAR, CDGENRE, COMMENT
1360 #do_postprocess ()
1361 #{
1362 #       for POSTPROCESSFORMAT in $(echo $POSTPROCESSFORMATS | tr , \ )
1363 #       do
1364 #               IN="$ABCDETEMPDIR/track$1.$POSTPROCESSFORMAT"
1365 #               # We need IN to proceed.
1366 #               if [ -s "$IN" ] ; then
1367 #                       #OUT="$ABCDETEMPDIR/track$1.$OUTPUT"
1368 #                       run_command '' echo "Post-processing track $1 of $TRACKS..."
1369 #                       case "$POSTPROCESSFORMAT" in
1370 #                               mp3)
1371 #                                       run_command postprocess-$OUTPUT-$1 nice $POSTNICE $MP3_POST $IF $OF ;;
1372 #                               ogg)
1373 #                                       run_command postprocess-$OUTPUT-$1 nice $POSTNICE $OGG_POST $IF $OF ;;
1374 #                               flac)
1375 #                                       run_command postprocess-$OUTPUT-$1 nice $POSTNICE $FLAC_POST $IF $OF ;;
1376 #                               spx)
1377 #                                       run_command postprocess-$OUTPUT-$1 nice $POSTNICE $SPX_POST $IF $OF ;;
1378 #                       esac
1379 #                       # Only remove .wav if the encoding succeeded
1380 #                       if checkerrors "postprocess-(.{3,4})-$1"; then
1381 #                               run_command postprocess-$1 false
1382 #                       else
1383 #                               run_command postprocess-$1 true
1384 #                       fi
1385 #               else
1386 #                       if [ "$(checkstatus encode-output)" = "loud" ]; then
1387 #                               echo "HEH! The file we were about to post-process disappeared:"
1388 #                               echo ">> $IN"
1389 #                       fi
1390 #                       run_command postprocess-$1 false
1391 #               fi
1392 #       done
1393 #}
1394
1395 # do_single_gain
1396 # variables used:
1397 # FIXME #
1398 do_single_gain ()
1399 {
1400 :
1401 }
1402
1403 # do_batch_gain
1404 # variables used:
1405 # MP3GAIN, MP3GAINOPTS, VORBISGAIN, VORBISGAINOPTS, MPCGAIN
1406 # FIXME #
1407 do_batch_gain ()
1408 {
1409         # The commands here don't go through run_command because they're never supposed to be silenced
1410         echo "Batch analizing gain in tracks: $TRACKQUEUE"
1411         (
1412         cd "$ABCDETEMPDIR"
1413         BLURB=
1414         TRACKFILES=
1415         for UTRACKNUM in $TRACKQUEUE
1416         do
1417                 MP3FILES="$TRACKFILES track$UTRACKNUM.mp3"
1418         done
1419         # FIXME # Hard-coded batch option!
1420         $NORMALIZER -b $NORMALIZEROPTS $TRACKFILES
1421         RETURN=$?
1422         if [ "$RETURN" != "0" ]; then
1423                 echo "batch-normalize: $NORMALIZER returned code $RETURN" >> errors
1424         else
1425                 for UTRACKNUM in $TRACKQUEUE
1426                 do
1427                         echo normalizetrack-$UTRACKNUM >> status
1428                 done
1429         fi
1430         )
1431 }
1432
1433 # do_batch_normalize
1434 # variables used:
1435 # NORMALIZER, NORMALIZEROPTS
1436 do_batch_normalize ()
1437 {
1438         # The commands here don't go through run_command because they're never supposed to be silenced
1439         echo "Batch normalizing tracks: $TRACKQUEUE"
1440         (
1441         cd "$ABCDETEMPDIR"
1442         BLURB=
1443         TRACKFILES=
1444         for UTRACKNUM in $TRACKQUEUE
1445         do
1446                 TRACKFILES="$TRACKFILES track$UTRACKNUM.wav"
1447         done
1448         # XXX: Hard-coded batch option!
1449         $NORMALIZER -b $NORMALIZEROPTS $TRACKFILES
1450         RETURN=$?
1451         if [ "$RETURN" != "0" ]; then
1452                 echo "batch-normalize: $NORMALIZER returned code $RETURN" >> errors
1453         else
1454                 for UTRACKNUM in $TRACKQUEUE
1455                 do
1456                         echo normalizetrack-$UTRACKNUM >> status
1457                 done
1458         fi
1459         )
1460 }
1461
1462 # do_normalize [tracknumber]
1463 # variables used:
1464 # TRACKS, TRACKNAME, NORMALIZER, NORMALIZEROPTS
1465 do_normalize ()
1466 {
1467         IN="$ABCDETEMPDIR/track$1.wav"
1468         if [ -e "$IN" ] ; then
1469                 run_command '' echo "Normalizing track $1 of $TRACKS: $TRACKNAME..."
1470                 run_command normalizetrack-$1 $NORMALIZER $NORMALIZEROPTS "$IN"
1471         else
1472                 if [ "$(checkstatus encode-output)" = "loud" ]; then
1473                         echo "HEH! The file we were about to normalize disappeared:"
1474                         echo ">> $IN"
1475                 fi
1476                 run_command normalizetrack-$1 false "File $IN was not found"
1477         fi
1478 }
1479
1480 # do_move [tracknumber]
1481 # Deduces the outfile from environment variables
1482 # Creates directory if necessary
1483 # variables used:
1484 # TRACKNUM, TRACKNAME, TRACKARTIST, DALBUM, OUTPUTFORMAT, CDGENRE, CDYEAR
1485 do_move ()
1486 {
1487         for TMPOUTPUT in $(echo $OUTPUTTYPE | tr , \ )
1488         do
1489                 # For now, set OUTPUT as TMPOUTPUT, and then change it once we have
1490                 # defined the OUTPUTFILE:
1491                 OUTPUT="$TMPOUTPUT"
1492
1493                 # Create ALBUMFILE, ARTISTFILE, TRACKFILE
1494                 ALBUMFILE="$(mungefilename "$DALBUM")"
1495                 ARTISTFILE="$(mungefilename "$TRACKARTIST")"
1496                 TRACKFILE="$(mungefilename "$TRACKNAME")"
1497                 GENRE="$(mungegenre "$GENRE")"
1498                 YEAR=${CDYEAR:-$CDYEAR}
1499                 # If we want to start the tracks with a given number, we need to modify
1500                 # the TRACKNUM value before evaluation
1501                 gettracknum
1502                 # Supported variables for OUTPUTFORMAT are GENRE, YEAR, ALBUMFILE,
1503                 # ARTISTFILE, TRACKFILE, and TRACKNUM.
1504                 if [ "$ONETRACK" = "y" ]; then
1505                         if [ "$VARIOUSARTISTS" = "y" ]; then
1506                                 OUTPUTFILE="$(eval echo \""$VAONETRACKOUTPUTFORMAT"\")"
1507                         else
1508                                 OUTPUTFILE="$(eval echo \""$ONETRACKOUTPUTFORMAT"\")"
1509                         fi
1510                 else
1511                         if [ "$VARIOUSARTISTS" = "y" ]; then
1512                                 OUTPUTFILE="$(eval echo \""$VAOUTPUTFORMAT"\")"
1513                         else
1514                                 OUTPUTFILE="$(eval echo \""$OUTPUTFORMAT"\")"
1515                         fi
1516                 fi
1517                 if checkerrors "tagtrack-$OUTPUT-$1"; then :; else
1518                         # Once we know the specific output was successful, we can change
1519                         # the OUTPUT to the value containing the container
1520                         case $TMPOUTPUT in
1521                                 vorbis|ogg)
1522                                         OUTPUT=$OGGOUTPUTCONTAINER
1523                                         ;;
1524                                 opus)
1525                                         OUTPUT=$OPUSOUTPUTCONTAINER
1526                                         ;;
1527                                 flac)
1528                                         OUTPUT=$FLACOUTPUTCONTAINER
1529                                         ;;
1530                                 *)
1531                                         OUTPUT=$TMPOUTPUT
1532                                         ;;
1533                         esac
1534                         # Check that the directory for OUTPUTFILE exists, if it doesn't, create it
1535                         OUTPUTFILEDIR="$(dirname "$OUTPUTDIR/$OUTPUTFILE")"
1536                         case $OUTPUT in
1537                                 wav)
1538                                         if [ "$DOCLEAN" != "y" ] && [ "$FORCE" != "y" ]; then
1539                                                 # FIXME # introduce warnings?
1540                                                 :
1541                                         else
1542                                                 # mkdir -p shouldn't return an error if the directory already exists
1543                                                 mkdir -p "$OUTPUTFILEDIR"
1544                                                 run_command movetrack-$1 mv "$ABCDETEMPDIR/track$1.$OUTPUT" "$OUTPUTDIR/$OUTPUTFILE.$OUTPUT"
1545                                                 if checkstatus movetrack-output-$OUTPUT; then :; else
1546                                                         run_command movetrack-output-$OUTPUT true
1547                                                 fi
1548                                         fi
1549                                         ;;
1550                                 *)
1551                                         # mkdir -p shouldn't return an error if the directory already exists
1552                                         mkdir -p "$OUTPUTFILEDIR"
1553                                         run_command movetrack-$1 mv "$ABCDETEMPDIR/track$1.$OUTPUT" "$OUTPUTDIR/$OUTPUTFILE.$OUTPUT"
1554                                         if checkstatus movetrack-output-$OUTPUT; then :; else
1555                                                 run_command movetrack-output-$OUTPUT true
1556                                         fi
1557                                         ;;
1558                         esac
1559                         # Lets move the cue file
1560                         if CUEFILE=$(checkstatus cuefile) >/dev/null ; then
1561                                 if [ -r "$ABCDETEMPDIR/$CUEFILE" ]; then
1562                                         if checkstatus movecue-$OUTPUT; then :; else
1563                                                 # Silence the Copying output since it overlaps with encoding processes...
1564                                                 #run_command '' vecho "Copying cue file to its destination directory..."
1565                                                 if checkstatus onetrack >/dev/null ; then
1566                                                         case $OUTPUT in
1567                                                                 wav)
1568                                                                         if [ "$DOCLEAN" != "y" ] && [ "$FORCE" != "y" ]; then
1569                                                                                 # We dont have the dir, since it was not created before.
1570                                                                                 :
1571                                                                         else
1572                                                                                 run_command movecue-$OUTPUT cp "$ABCDETEMPDIR/$CUEFILE" "$OUTPUTDIR/$OUTPUTFILE.cue"
1573                                                                         fi
1574                                                                         ;;
1575                                                                 # NOTE: Creating a cue file with the 3-char-extension files is to comply with
1576                                                                 # http://brianvictor.tripod.com/mp3cue.htm#details
1577                                                                 [a-z0-9][a-z0-9][a-z0-9])
1578                                                                         run_command movecue-$OUTPUT cp "$ABCDETEMPDIR/$CUEFILE" "$OUTPUTDIR/$OUTPUTFILE.cue"
1579                                                                         ;;
1580                                                                 *)
1581                                                                         run_command movecue-$OUTPUT cp "$ABCDETEMPDIR/$CUEFILE" "$OUTPUTDIR/$OUTPUTFILE.$OUTPUT.cue"
1582                                                                         ;;
1583                                                         esac
1584                                                 else
1585                                                         run_command movecue-$OUTPUT cp "$ABCDETEMPDIR/$CUEFILE" "$OUTPUTFILEDIR/$CUEFILE"
1586                                                 fi
1587                                                 echo movecue-$OUTPUT >> "$ABCDETEMPDIR/status"
1588                                         fi
1589                                 fi
1590                         fi
1591                 fi
1592         done
1593 }
1594
1595 # do_playlist
1596 # Create the playlist if wanted
1597 # Variables used:
1598 # PLAYLISTFORMAT, PLAYLISTDATAPREFIX, VAPLAYLISTFORMAT, VAPLAYLISTDATAPREFIX,
1599 # VARIOUSARTISTS, OUTPUTDIR
1600 do_playlist ()
1601 {
1602         for TMPOUTPUT in $(echo $OUTPUTTYPE | tr , \ )
1603         do
1604                 case $TMPOUTPUT in
1605                         vorbis|ogg)
1606                                 OUTPUT=$OGGOUTPUTCONTAINER
1607                                 ;;
1608                         opus)
1609                                 OUTPUT=$OPUSOUTPUTCONTAINER
1610                                 ;;
1611                         flac)
1612                                 OUTPUT=$FLACOUTPUTCONTAINER
1613                                 ;;
1614                         *)
1615                                 OUTPUT=$TMPOUTPUT
1616                                 ;;
1617                 esac
1618                 # Create a playlist file for the playlist data to go into.
1619                 # We used to wipe it out if it existed. Now we request permission if interactive.
1620                 for LASTTRACK in $TRACKQUEUE; do :; done
1621                 ALBUMFILE="$(mungefilename "$DALBUM")"
1622                 ARTISTFILE="$(mungefilename "$DARTIST")"
1623                 GENRE="$(mungegenre "$GENRE")"
1624                 YEAR=${CDYEAR:-$CDYEAR}
1625                 if [ "$VARIOUSARTISTS" = "y" ] ; then
1626                         PLAYLISTFILE="$(eval echo "$VAPLAYLISTFORMAT")"
1627                 else
1628                         PLAYLISTFILE="$(eval echo "$PLAYLISTFORMAT")"
1629                 fi
1630                 FINALPLAYLISTDIR="$(dirname "$OUTPUTDIR/$PLAYLISTFILE")"
1631                 mkdir -p "$FINALPLAYLISTDIR"
1632                 if [ -s "$OUTPUTDIR/$PLAYLISTFILE" ]; then
1633                         echo -n "Erase, Append to, or Keep the existing playlist file? [e/a/k] (e): " >&2
1634                         if [ "$INTERACTIVE" = "y" ]; then
1635                                 while [ "$DONE" != "y" ]; do
1636                                         read ERASEPLAYLIST
1637                                         case $ERASEPLAYLIST in
1638                                                 e|E|a|A|k|K) DONE=y ;;
1639                                                 "") ERASEPLAYLIST=e ; DONE=y ;;
1640                                                 *) ;;
1641                                         esac
1642                                 done
1643                         else
1644                                 echo e >&2
1645                                 ERASEPLAYLIST=e
1646                         fi
1647                         # Once we erase the playlist, we use append to create the new one.
1648                         [ "$ERASEPLAYLIST" = "e" -o "$ERASEPLAYLIST" = "E" ] && rm -f "$OUTPUTDIR/$PLAYLISTFILE" && ERASEPLAYLIST=a
1649                 else
1650                         # The playlist does not exist, so we can safelly use append to create the new list
1651                         ERASEPLAYLIST=a
1652                 fi
1653                 if [ "$ERASEPLAYLIST" = "a" -o "$ERASEPLAYLIST" = "A" ]; then
1654                         touch "$OUTPUTDIR/$PLAYLISTFILE"
1655                         for UTRACKNUM in $TRACKQUEUE
1656                         do
1657                                 # Shares some code with do_move since the filenames have to match
1658                                 CDDBTRACKNUM=$(expr $UTRACKNUM - 1)
1659                                 getcddbinfo TRACKNAME
1660                                 splitvarious
1661                                 TRACKFILE="$(mungefilename "$TRACKNAME")"
1662                                 ARTISTFILE="$(mungefilename "$TRACKARTIST")"
1663                                 ALBUMFILE="$(mungefilename "$DALBUM")"
1664                                 # If we want to start the tracks with a given number, we need to modify the
1665                                 # TRACKNUM value before evaluation
1666                                 gettracknum
1667                                 if [ "$VARIOUSARTISTS" = "y" ]; then
1668                                         OUTPUTFILE="$(eval echo \""$VAOUTPUTFORMAT\"")"
1669                                 else
1670                                         OUTPUTFILE="$(eval echo \""$OUTPUTFORMAT\"")"
1671                                 fi
1672                                 if [ "$VARIOUSARTISTS" = "y" ]; then
1673                                         if [ "$VAPLAYLISTDATAPREFIX" ] ; then
1674                                                 echo ${VAPLAYLISTDATAPREFIX}$OUTPUTFILE.$OUTPUT >> "$OUTPUTDIR/$PLAYLISTFILE"
1675                                         else
1676                                                 relpath "$PLAYLISTFILE", "$OUTPUTFILE.$OUTPUT" >> "$OUTPUTDIR/$PLAYLISTFILE"
1677                                         fi
1678                                 else
1679                                         if [ "$PLAYLISTDATAPREFIX" ]; then
1680                                                 echo ${PLAYLISTDATAPREFIX}$OUTPUTFILE.$OUTPUT >> "$OUTPUTDIR/$PLAYLISTFILE"
1681                                         else
1682                                                 relpath "$PLAYLISTFILE", "$OUTPUTFILE.$OUTPUT" >> "$OUTPUTDIR/$PLAYLISTFILE"
1683                                         fi
1684                                 fi
1685                         done
1686                 fi
1687                 ## this will convert the playlist to have CRLF line-endings, if specified
1688                 ## (some hardware players insist on CRLF endings)
1689                 if [ "$DOSPLAYLIST" = "y" ]; then
1690                         awk '{sub("\r$",""); printf "%s\r\n", $0}' "$OUTPUTDIR/$PLAYLISTFILE" > "$ABCDETEMPDIR/PLAYLISTFILE.tmp"
1691 #                       mv -f "$ABCDETEMPDIR/PLAYLISTFILE.tmp" "$OUTPUTDIR/$PLAYLISTFILE"
1692                         cat "$ABCDETEMPDIR/PLAYLISTFILE.tmp" | sed 's/\//\\/' > "$OUTPUTDIR/$PLAYLISTFILE"
1693                 fi
1694                 echo "playlistcomplete" >> "$ABCDETEMPDIR/status"
1695         done
1696 }
1697
1698 # abcde.cue2discid
1699 # This function reads a cuefile on stdin and writes an extended
1700 # cddb query on stdout.  Any PREGAP for track 1 is properly
1701 # handled, although cue files embedded in FLAC files do not
1702 # appear to properly store the PREGAP setting. :(
1703 abcde.cue2discid () {
1704
1705         cddb_sum () {
1706                 val=$1
1707                 ret=0
1708                 while [ $val -gt 0 ] ; do
1709                         ret=$(( $ret + ( $val % 10) ))
1710                         val=$(( $val / 10 ))
1711                 done
1712                 echo $ret
1713         }
1714
1715         msf2lba () {
1716                 OIFS="$IFS"
1717                 IFS=":"
1718                 set -- $1
1719                 IFS="$OIFS"
1720                 local first second third
1721                 first=$(expr ${1} + 0 )
1722                 second=$(expr ${2} + 0 )
1723                 third=$(expr ${3} + 0 )
1724
1725                 echo $(( ((($first * 60) + $second) * 75) + $third ))
1726         }
1727
1728         OFFSET=150
1729         PREGAP=0
1730         LEADOUT=0
1731         LEADIN=88200
1732         i=0
1733         N=0
1734
1735         while read line ; do
1736                 set -- $line
1737                 case "$1" in
1738                 TRACK)  i=$(( i + 1 ))
1739                         ;;
1740                 INDEX)  if [ "$2" -eq 1 ] ; then
1741                                 LBA=$(msf2lba $3)
1742                                 START=$(( $LBA + $PREGAP + $OFFSET ))
1743                                 eval TRACK$i=$START
1744                                 X=$(cddb_sum $(( $START / 75 )) )
1745                                 N=$(( $N + $X ))
1746                         fi
1747                         ;;
1748                 PREGAP) PREGAP=$(msf2lba $2)
1749                         ;;
1750                 REM)    case "$2" in
1751                         FLAC__lead-out)
1752                                 LEADOUT=$(( $4 / 588 ))
1753                                 ;;
1754                         FLAC__lead-in)
1755                                 LEADIN=$(( $3 / 588 ))
1756                                 ;;
1757                         esac
1758                         ;;
1759                 esac
1760
1761         done
1762
1763         TRACKS=$i
1764         LEADOUT=$(( $LEADOUT + $LEADIN ))
1765
1766         LENGTH=$(( $LEADOUT/75 - $TRACK1/75 ))
1767         DISCID=$(( ( $N % 255 ) * 2**24 | $LENGTH * 2**8 | $TRACKS ))
1768         printf "%08x %i" $DISCID $TRACKS
1769
1770         j=1
1771         while [ $j -le $TRACKS ] ; do
1772                 eval echo -n "\" \$TRACK$j\""
1773                 j=$((j+1))
1774         done
1775         echo " $(( $LEADOUT / 75 ))"
1776 }
1777
1778 # abcde.mkcue
1779 # abcde.mkcue [--wholedisk]
1780 # This creates a cuefile directly from the extended discid information
1781 # The --wholedisk option controls whether we're ripping data from the
1782 # start of track one or from the start of the disk (usually, but not
1783 # always the same thing!)
1784 #
1785 # Track one leadin/pregap (if any) handeling:
1786 # --wholedisk specified:
1787 #   TRACK 01 AUDIO
1788 #     INDEX 00 00:00:00
1789 #     INDEX 01 <pregap value>
1790 #   Remaining track index values unchanged from disc TOC
1791 #
1792 # --wholedisk not specified
1793 #   TRACK 01 AUDIO
1794 #     PREGAP <pregap value>
1795 #     INDEX 01 00:00:00
1796 #   Remaining track index values offset by <pregap value>
1797 #
1798 # Variables used:
1799 # TRACKINFO
1800 abcde.mkcue () {
1801
1802         echomsf () {
1803                 printf "$1%02i:%02i:%02i\n" $(($2/4500)) $((($2/75)%60)) $(($2%75))
1804         }
1805
1806         local MODE DISCID TRACKS
1807         local i OFFSET LBA
1808         local CUEWAVFILE
1809
1810         if [ "$1" = --wholedisc ] ; then
1811                 MODE=INDEX
1812         else
1813                 MODE=PREGAP
1814         fi
1815
1816         vecho "One track is $ONETRACK"
1817         TRACKFILE="$(mungefilename "$TRACKNAME")"
1818         ARTISTFILE="$(mungefilename "$TRACKARTIST")"
1819         ALBUMFILE="$(mungefilename "$DALBUM")"
1820         if [ "$ONETRACK" = "y" ]; then
1821                 if [ "$VARIOUSARTISTS" = "y" ]; then
1822                         CUEWAVFILE="$(eval echo \""$VAONETRACKOUTPUTFORMAT"\" | sed -e 's@^.*/@@').$OUTPUT"
1823                 else
1824                         CUEWAVFILE="$(eval echo \""$ONETRACKOUTPUTFORMAT"\" | sed -e 's@^.*/@@').$OUTPUT"
1825                 fi
1826                 vecho "Cue wav file is $CUEWAVFILE"
1827         else
1828                 CUEWAVFILE="dummy.wav"
1829         fi
1830
1831         set -- $TRACKINFO
1832
1833         DISCID=$1
1834         TRACKS=$2
1835         shift 2
1836
1837         echo REM DISCID $DISCID
1838         echo FILE \""$CUEWAVFILE"\" WAVE
1839
1840         if [ $1 -ne 150 ] && [ $MODE = "PREGAP" ] ; then
1841                 OFFSET=$1
1842         else
1843                 OFFSET=150
1844         fi
1845
1846         i=1
1847         while [ $i -le "$TRACKS" ] ; do
1848                 LBA=$(( $1 - $OFFSET ))
1849                 printf "  TRACK %02i AUDIO\n" $i
1850                 if [ $i -eq 1 -a $1 -ne 150 ] ; then
1851                         if [ $MODE = PREGAP ] ; then
1852                                 echomsf "    PREGAP " $(($OFFSET-150))
1853                         else
1854                                 echo    "    INDEX 00 00:00:00"
1855                         fi
1856                 fi
1857                 echomsf "    INDEX 01 " $LBA
1858                 i=$(($i+1))
1859                 shift
1860         done
1861 }
1862
1863 # do_discid
1864 # This essentially the start of things
1865 do_discid ()
1866 {
1867         # Query the CD to get the track info, unless the user specified -C
1868         # or we are using some actions which do not need the CDDB data at all
1869         #if [ ! X"$EXPACTIONS" = "X" ]; then
1870         #       :
1871         #elif [ -z "$DISCID" ]; then
1872         if [ -z "$DISCID" ]; then
1873                 vecho -n "Getting CD track info... "
1874                 # In OSX, unmount the disc before a query
1875                 if [ "$OSFLAVOUR" = "OSX" ]; then
1876                         diskutil unmount ${CDROM#/dev/}
1877                 fi
1878                 case "$CDROMREADERSYNTAX" in
1879                         flac)
1880                                 if $METAFLAC $METAFLACOPTS --export-cuesheet-to=- "$CDROM" > /dev/null 2>&1 ; then
1881                                         case "$CUE2DISCID" in
1882                                                 # FIXME # right now we have 2 cue2discid internal
1883                                                 # implementations: builtin and abcde.cue2discid. Test
1884                                                 # both of them and decide which one we want to use.
1885                                                 builtin)
1886                                                         #vecho "Using builtin cue2discid implementation..."
1887                                                         CUESHEET="$(metaflac $METAFLACOPTS --export-cuesheet-to=- "$CDROM")"
1888
1889                                                         #TRACKS=$(echo $CUESHEET | grep -E "TRACK \+[[:digit:]]\+ \+AUDIO" |wc -l)
1890                                                         #TRACKS=0
1891                                                         OFFSETTIMES=( $(echo "$CUESHEET" | sed -n -e's/\ *INDEX 01\ \+//p' ) )
1892                                                         TRACKS=${#OFFSETTIMES[@]}
1893                                                         unset OFFSETS
1894                                                         #echo "processing offsetimes ${OFFSETTIMES[@]}"
1895                                                         for OFFSETTIME in ${OFFSETTIMES[@]}; do
1896                                                                 OFFSETS="$OFFSETS $(( 10#${OFFSETTIME:0:2} * 4500 + 10#${OFFSETTIME:3:2} * 75 + 10#${OFFSETTIME:6:2} ))"
1897                                                                 #OFFSETS[${#OFFSETS[*]}]=$(( 10#${OFFSETTIME:0:2} * 4500 + 10#${OFFSETTIME:3:2} * 75 + 10#${OFFSETTIME:6:2} ))
1898                                                         done
1899
1900                                                         LEADOUT=$(( $(echo "$CUESHEET" | grep lead-out | get_last) * 75 / 44100 ))
1901                                                         LEADIN=$(( $(echo "$CUESHEET" | grep lead-in | get_last) * 75 / 44100 ))
1902                                                         makeids
1903                                                 ;;
1904                                                 *)
1905                                                         #vecho "Using external python cue2discid implementation..."
1906                                                         TRACKINFO=$($METAFLAC $METAFLACOPTS --export-cuesheet-to=- "$CDROM" | $CUE2DISCID)
1907                                                 ;;
1908                                         esac
1909                                 else
1910                                         log error "the input flac file does not contain a cuesheet."
1911                                         exit 1
1912                                 fi
1913                                 ;;
1914 #                       cdparanoia|debug)
1915 #                               CDPARANOIAOUTPUT="$( $CDROMREADER -$CDPARANOIACDROMBUS "$CDROM" -Q --verbose 2>&1 )"
1916 #                               RET=$?
1917 #                               if [ ! "$RET" = "0" ];then
1918 #                                       log warning "something went wrong while querying the CD... Maybe a DATA CD?"
1919 #                               fi
1920 #
1921 #                               TRACKS="$(echo "$CDPARANOIAOUTPUT" | grep -E '^[[:space:]]+[[:digit:]]' | tail -n 1 | get_first | tr -d "." | tr '\n' ' ')"
1922 #                               CDPARANOIAAUDIOTRACKS="$TRACKS"
1923 #
1924 #                               LEADOUT="$(echo "$CDPARANOIAOUTPUT" | grep -Eo '^TOTAL[[:space:]]+([[:digit:]]+)' | get_last)"
1925 #                               OFFSETS="$(echo "$CDPARANOIAOUTPUT" | sed -n -e's/^ .* \([0-9]\+\) \[.*/\1/p')"
1926 #                               makeids
1927 #                               ;;
1928                         *)
1929                                 case "$CDDBMETHOD" in
1930                                         cddb) TRACKINFO=$($CDDISCID "$CDROM") ;;
1931                                         musicbrainz) TRACKINFO=$($MUSICBRAINZ --command id --device "$CDROM") ;;
1932                                 esac
1933                                 ;;
1934                 esac
1935                 # Make sure there's a CD in there by checking cd-discid's return code
1936                 if [ ! "$?" = "0" ]; then
1937                         if [ "$CDROMREADERSYNTAX" = "flac" ] ; then
1938                                 log error "cuesheet information from the flac file could not be read."
1939                                 log error "Perhaps the flac file does not contain a cuesheet?."
1940                                 exit 1
1941                         else
1942                                 log error "CD could not be read. Perhaps there's no CD in the drive?"
1943                                 exit 1
1944                         fi
1945                 fi
1946                 # In OSX, remount the disc again
1947                 if [ "$OSFLAVOUR" = "OSX" ]; then
1948                         diskutil mount ${CDROM#/dev/}
1949                 fi
1950                 WEHAVEACD=y
1951                 DISCID=$(echo $TRACKINFO | cut -f1 -d' ')
1952         else
1953                 TRACKINFO=$(cat "$WAVOUTPUTDIR/abcde.$DISCID/discid")
1954         fi
1955
1956         # Get a full enumeration of tracks, sort it, and put it in the TRACKQUEUE.
1957         # This needs to be done now because a section of the resuming code will need
1958         # it later.
1959
1960         # get the number of digits to pad TRACKNUM with - we'll use this later
1961         # a CD can only hold 99 tracks, but since we support a feature for starting
1962         # numbering the tracks from a given number, we might need to set it as a
1963         # variable for the user to define... or obtain it somehow.
1964         if [ "$PADTRACKS" = "y" ] ; then
1965                 TRACKNUMPADDING=2
1966         fi
1967
1968         ABCDETEMPDIR="$WAVOUTPUTDIR/abcde.$(echo $TRACKINFO | cut -f1 -d' ')"
1969         if [ -z "$TRACKQUEUE" ]; then
1970                 if [ ! "$STRIPDATATRACKS" = "n" ]; then
1971                         case "$CDROMREADERSYNTAX" in
1972                                 cdparanoia|libcdio|debug)
1973                                         if [ "$WEHAVEACD" = "y" ]; then
1974                                                 vecho "Querying the CD for audio tracks..."
1975                                                 CDPARANOIAOUTPUT="$( $CDROMREADER -$CDPARANOIACDROMBUS "$CDROM" -Q --verbose 2>&1 )"
1976                                                 RET=$?
1977                                                 if [ ! "$RET" = "0" ];then
1978                                                         log warning "something went wrong while querying the CD... Maybe a DATA CD?"
1979                                                 fi
1980                                                 TRACKS="$(echo "$CDPARANOIAOUTPUT" | grep -E '^[[:space:]]+[[:digit:]]' | tail -n 1 | get_first | tr -d "." | tr '\n' ' ')"
1981                                                 CDPARANOIAAUDIOTRACKS="$TRACKS"
1982                                         else
1983                                                 # Previous versions of abcde would store the tracks on a file, instead of the status record.
1984                                                 if [ -f "$ABCDETEMPDIR/cdparanoia-audio-tracks" ]; then
1985                                                         echo cdparanoia-audio-tracks=$( cat "$ABCDETEMPDIR/cdparanoia-audio-tracks" ) >> "$ABCDETEMPDIR/status"
1986                                                         rm -f "$ABCDETEMPDIR/cdparanoia-audio-tracks"
1987                                                 fi
1988                                                 if [ -f "$ABCDETEMPDIR/status" ] && TRACKS=$(checkstatus cdparanoia-audio-tracks); then :; else
1989                                                         TRACKS=$(echo $TRACKINFO | cut -f2 -d' ')
1990                                                 fi
1991                                         fi
1992                                         ;;
1993                                 *)      TRACKS=$(echo $TRACKINFO | cut -f2 -d' ') ;;
1994                         esac
1995                 else
1996                         TRACKS=$(echo $TRACKINFO | cut -f2 -d' ')
1997                 fi
1998                 if echo "$TRACKS" | grep "[[:digit:]]" > /dev/null 2>&1 ;then :;else
1999                         log info "The disc does not contain any tracks. Giving up..."
2000                         exit 0
2001                 fi
2002                 echo -n "Grabbing entire CD - tracks: "
2003                 if [ ! "$PADTRACKS" = "y" ] ; then
2004                         TRACKNUMPADDING=$(echo -n $TRACKS | wc -c | tr -d ' ')
2005                 fi
2006                 TRACKS=$(printf "%0.${TRACKNUMPADDING}d" $TRACKS)
2007                 X=0
2008                 while [ "$X" -ne "$TRACKS" ]
2009                 do
2010                         X=$(printf "%0.${TRACKNUMPADDING}d" $(expr $X + 1))
2011                         TRACKQUEUE=$(echo $TRACKQUEUE $X)
2012                 done
2013                 echo $TRACKQUEUE
2014         else
2015                 TRACKS=$(echo $TRACKINFO | cut -f2 -d' ')
2016                 # User-supplied track queue.
2017                 # Weed out non-numbers, whitespace, then sort and weed out duplicates
2018                 TRACKQUEUE=$(echo $TRACKQUEUE | sed 's-[^0-9 ]--g' | tr ' ' '\n' | grep -v ^$ | sort -n | uniq | tr '\n' ' ' | sed 's- $--g')
2019                 # Once cleaned, obtain the highest value in the trackqueue for number padding
2020                 for LASTTRACK in $TRACKQUEUE; do :; done
2021                 if [ ! "$PADTRACKS" = "y" ] ; then
2022                         TRACKNUMPADDING=$(echo -n $LASTTRACK | wc -c | tr -d ' ')
2023                 fi
2024                 # Now we normalize the trackqueue
2025                 for TRACK in $TRACKQUEUE ; do
2026                         TRACKNUM=$(printf %0.${TRACKNUMPADDING}d $(expr ${TRACK} + 0 ))
2027                         PADTRACKQUEUE=$(echo $PADTRACKQUEUE $TRACKNUM)
2028                 done
2029                 TRACKQUEUE=$PADTRACKQUEUE
2030                 echo Grabbing tracks: "$TRACKQUEUE"
2031         fi
2032
2033         QUEUEDTRACKS=$(echo $TRACKQUEUE | wc -w | tr -d ' ')
2034
2035         # We have the discid, create a temp directory after it to store all the temp
2036         # info
2037
2038         if [ -e "$ABCDETEMPDIR" ]; then
2039                 echo -n "abcde: attempting to resume from $ABCDETEMPDIR"
2040                 # It already exists, see if it's a directory
2041                 if [ ! -d "$ABCDETEMPDIR" ]; then
2042                         # This is a file/socket/fifo/device/etc, not a directory
2043                         # Complain and exit
2044                         echo >&2
2045                         echo "abcde: file $ABCDETEMPDIR already exists and does not belong to abcde." >&2
2046                         echo "Please investigate, remove it, and rerun abcde." >&2
2047                         exit 1
2048                 fi
2049                 echo -n .
2050                 # It's a directory, let's see if it's writable by us
2051                 if [ ! -r "$ABCDETEMPDIR" ] || [ ! -w "$ABCDETEMPDIR" ] || [ ! -x "$ABCDETEMPDIR" ]; then
2052                         # Nope, complain and exit
2053                         echo >&2
2054                         echo "abcde: directory $ABCDETEMPDIR already exists and is not writeable." >&2
2055                         echo "Please investigate, remove it, and rerun abcde." >&2
2056                         exit 1
2057                 fi
2058                 echo .
2059                 # See if it's populated
2060                 if [ ! -f "$ABCDETEMPDIR/discid" ]; then
2061                         # Wipe and start fresh
2062                         echo "abcde: $ABCDETEMPDIR/discid not found. Abcde must remove and recreate" >&2
2063                         echo -n "this directory to continue. Continue [y/N]? " >&2
2064                         if [ "$INTERACTIVE" = "y" ]; then
2065                                 read ANSWER
2066                         else
2067                                 echo y >&2
2068                                 ANSWER=y
2069                         fi
2070                         if [ "$ANSWER" != "y" ]; then
2071                                 exit 1
2072                         fi
2073                         rm -rf "$ABCDETEMPDIR" || exit 1
2074                         mkdir -p "$ABCDETEMPDIR"
2075                         if [ "$?" -gt "0" ]; then
2076                                 # Directory already exists or could not be created
2077                                 echo "abcde: Temp directory $ABCDETEMPDIR could not be created." >&2
2078                                 exit 1
2079                         fi
2080                 else
2081                         # Everything is fine. Check for ^encodetracklocation-
2082                         # and encode-output entries in the status file and
2083                         # remove them. These are not relevant across sessions.
2084                         if [ -f "$ABCDETEMPDIR/status" ]; then
2085                                 mv "$ABCDETEMPDIR/status" "$ABCDETEMPDIR/status.old"
2086                                 grep -v ^encodetracklocation- < "$ABCDETEMPDIR/status.old" \
2087                                         | grep -v ^encode-output > "$ABCDETEMPDIR/status"
2088                         fi
2089                         # Remove old error messages
2090                         if [ -f "$ABCDETEMPDIR/errors" ]; then
2091                                 rm -f "$ABCDETEMPDIR/errors"
2092                         fi
2093                 fi
2094         else
2095                 # We are starting from scratch
2096                 mkdir -p "$ABCDETEMPDIR"
2097                 if [ "$?" -gt "0" ]; then
2098                         # Directory already exists or could not be created
2099                         echo "abcde: Temp directory $ABCDETEMPDIR could not be created." >&2
2100                         exit 1
2101                 fi
2102                 cat /dev/null > "$ABCDETEMPDIR/status"
2103                 # Store the abcde version in the status file.
2104                 echo "abcde-version=$VERSION" >> "$ABCDETEMPDIR/status"
2105         fi
2106         if [ X"$DOCUE" = "Xy" -a X"$WEHAVEACD" = "Xy" ]; then
2107                 if checkstatus cuefile > /dev/null 2>&1 ; then :; else
2108                         CUEFILE=cue-$(echo "$TRACKINFO" | cut -f1 -d' ').txt
2109                         vecho "Creating cue file..."
2110                         case $CDROMREADERSYNTAX in
2111                                 flac)
2112                                         if $METAFLAC --export-cuesheet-to=- "$CDROM" > "$ABCDETEMPDIR/$CUEFILE"; then
2113                                                 echo cuefile=$CUEFILE >> "$ABCDETEMPDIR/status"
2114                                         else
2115                                                 log warning "the input flac file does not contain a cuesheet."
2116                                         fi
2117                                         ;;
2118                                 *)
2119                                         if $CUEREADER $CUEREADEROPTS > "$ABCDETEMPDIR/$CUEFILE"; then
2120                                                 echo cuefile=$CUEFILE >> "$ABCDETEMPDIR/status"
2121                                         else
2122                                                 log warning "reading the CUE sheet is still considered experimental"
2123                                                 log warning "and there was a problem with the CD reading. abcde will continue,"
2124                                                 log warning "but consider reporting the problem to the abcde author"
2125                                         fi
2126                                         ;;
2127                         esac
2128                 fi
2129         fi
2130         # If we got the CDPARANOIA status and it is not recorded, save it now
2131         if [ -n "$CDPARANOIAAUDIOTRACKS" ]; then
2132                 if checkstatus cdparanoia-audio-tracks > /dev/null 2>&1; then :; else
2133                         echo cdparanoia-audio-tracks=$CDPARANOIAAUDIOTRACKS >> "$ABCDETEMPDIR/status"
2134                 fi
2135         fi
2136
2137         # Create the discid file
2138         echo "$TRACKINFO" > "$ABCDETEMPDIR/discid"
2139         if checkstatus cddbmethod > /dev/null 2>&1 ; then :; else
2140                 echo "cddbmethod=$CDDBMETHOD" >> "$ABCDETEMPDIR/status"
2141         fi
2142 }
2143
2144 # do_cleancue
2145 # Create a proper CUE file based on the CUE file we created before.
2146 do_cleancue()
2147 {
2148         if CUEFILE_IN="$ABCDETEMPDIR"/$(checkstatus cuefile); then
2149                 CUEFILE_OUT=$CUEFILE_IN.out
2150                 ### FIXME ### checkstatus cddb
2151                 if [ -e "$CDDBDATA" ]; then
2152                         vecho "Adding metadata to the cue file..."
2153                         # FIXME It doesn't preserve spaces! Why?
2154                         # FIXME parse $track into PERFORMER and TITLE - abcde already has code for this?
2155                         n=1
2156                         echo "PERFORMER \"$DARTIST\"" >> "$CUEFILE_OUT"
2157                         echo "TITLE \"$DALBUM\"" >> "$CUEFILE_OUT"
2158                         # Set IFS to <newline> to prevent read from swallowing spaces and tabs
2159                         OIFS="$IFS"
2160                         IFS='
2161 '
2162                         cat "$CUEFILE_IN" | while read line
2163                         do
2164                                 if echo "$line" | grep "INDEX 01" > /dev/null 2>&1 ; then
2165 # FIXME # Possible patch: remove the line above, uncomment the 2 lines below.
2166 #                               echo "$line" >> "$CUEFILE_OUT"
2167 #                               if echo "$line" | grep "^[[:space:]]*TRACK" > /dev/null 2>&1 ; then
2168                                         eval track="\$TRACK$n"
2169                                         n=$(expr $n + 1)
2170                                         echo "    TITLE \"$track\"" >> "$CUEFILE_OUT"
2171                                 # When making a single-track rip, put the
2172                                 # actual file name into the file declaration
2173                                 # in the cue file so that it is usable by
2174                                 # music players and the like
2175                                 elif [ "$ONETRACK" = "y" ] &&
2176                                                 echo "$line" | grep '^FILE "dummy.wav" WAVE' > /dev/null 2>&1 ; then
2177
2178                                         TRACKFILE="$(mungefilename "$TRACKNAME")"
2179                                         ARTISTFILE="$(mungefilename "$TRACKARTIST")"
2180                                         ALBUMFILE="$(mungefilename "$DALBUM")"
2181
2182                                         if [ "$VARIOUSARTISTS" = "y" ]; then
2183                                                 OUTPUTFILE="$(eval echo \""$VAONETRACKOUTPUTFORMAT"\" | sed -e 's@^.*/@@').$OUTPUT"
2184                                         else
2185                                                 OUTPUTFILE="$(eval echo \""$ONETRACKOUTPUTFORMAT"\" | sed -e 's@^.*/@@').$OUTPUT"
2186                                         fi
2187
2188                                         echo "FILE \"$OUTPUTFILE\" WAVE" >> "$CUEFILE_OUT"
2189                                         continue
2190                                 fi
2191 # FIXME # If the lines above are uncommented, remove the line below.
2192                                 echo "$line" >> "$CUEFILE_OUT"
2193                         done
2194                         IFS="$OIFS"
2195                         mv "$CUEFILE_OUT" "$CUEFILE_IN"
2196                         echo "cleancuefile" >> "$ABCDETEMPDIR/status"
2197                 fi
2198         fi
2199 }
2200
2201 # do_cddbparse
2202 # Parses a CDDB file and outputs the title and the track names.
2203 # Variables: CDDBFILE
2204 do_cddbparse ()
2205 {
2206         CDDBPARSEFILE="$1"
2207         # List out disc title/author and contents
2208         if [ "$ONETRACK" = "y" ]; then
2209                 vecho "ONETRACK mode selected: displaying only the title of the CD..."
2210         fi
2211         echo "---- $(grep DTITLE "${CDDBPARSEFILE}" | cut '-d=' -f2- | tr -d \\r\\n ) ----"
2212         if [ X"$SHOWCDDBYEAR" = "Xy" ]; then
2213                 PARSEDYEAR=$(grep DYEAR "${CDDBPARSEFILE}" | cut '-d=' -f2-)
2214                 if [ ! X"$PARSEDYEAR" = "X" ]; then
2215                         echo "Year: $PARSEDYEAR"
2216                 fi
2217         fi
2218         if [ X"$SHOWCDDBGENRE" = "Xy" ]; then
2219                 PARSEDGENRE=$(grep DGENRE "${CDDBPARSEFILE}" | cut '-d=' -f2-)
2220                 if [ ! X"$PARSEDGENRE" = "X" ]; then
2221                         echo "Genre: $PARSEDGENRE"
2222                 fi
2223         fi
2224         if [ ! "$ONETRACK" = "y" ]; then
2225                 for TRACK in $(f_seq_row 1 $TRACKS)
2226                 do
2227                         echo $TRACK: "$(grep ^TTITLE$(expr $TRACK - 1)= "${CDDBPARSEFILE}" | cut -f2- -d= | tr -d \\r\\n)"
2228                 done
2229         fi
2230 }
2231
2232 # do_localcddb
2233 # Check for a local CDDB file, and report success
2234 do_localcddb ()
2235 {
2236         if checkstatus cddb-readcomplete && checkstatus cddb-choice >/dev/null; then :; else
2237
2238                 CDDBLOCALSTATUS="notfound"
2239                 CDDBDISCID=$(echo $TRACKINFO | cut -d' ' -f1)
2240                 USELOCALRESP="y"
2241
2242                 if [ "$CDDBLOCALRECURSIVE" = "y" ]; then
2243                         CDDBLOCALRESULTS="$(find ${CDDBLOCALDIR} -name "${CDDBDISCID}" -type f 2> /dev/null)"
2244                         if [ ! "${CDDBLOCALRESULTS}" = "" ]; then
2245                                 if   (( $(echo "${CDDBLOCALRESULTS}" | wc -l) == 1 )); then
2246                                         CDDBLOCALFILE="${CDDBLOCALRESULTS}"
2247                                         CDDBLOCALMATCH=single
2248                                 elif (( $(echo "${CDDBLOCALRESULTS}" | wc -l) > 1 )); then
2249                                         CDDBLOCALMATCH=multiple
2250                                 fi
2251                         else
2252                                 CDDBLOCALMATCH=none
2253                         fi
2254                 elif [ "$CDDBLOCALMATCH" = "none" ] && [ -r "${CDDBLOCALDIR}/${CDDBDISCID}" ]; then
2255                         CDDBLOCALFILE="${CDDBLOCALDIR}/${CDDBDISCID}"
2256                         CDDBLOCALMATCH=single
2257                 else
2258                         CDDBLOCALMATCH=none
2259                 fi
2260
2261                 # If the user has selected to check a local CDDB repo, we proceed with it
2262                 case $CDDBLOCALMATCH in
2263                         multiple)
2264                                 echo "Processing multiple matching CDDB entries..." > "$ABCDETEMPDIR/cddblocalchoices"
2265                                 X=0
2266                                 echo "$CDDBLOCALRESULTS" | while read RESULT ; do
2267                                         X=$(expr $X + 1)
2268                                         # List out disc title/author and contents
2269                                         CDDBLOCALREAD="$ABCDETEMPDIR/cddblocalread.$X"
2270                                         cat "$RESULT" > "${CDDBLOCALREAD}"
2271                                         {
2272                                                 echo -n "#$X: "
2273                                                 do_cddbparse "${CDDBLOCALREAD}"
2274                                                 echo ""
2275                                                 ##FIXME## QUICK HACK !!!!
2276                                                 if [ ! "$INTERACTIVE" = "y" ]; then break ; fi
2277                                         } >> "$ABCDETEMPDIR/cddblocalchoices"
2278                                 done
2279                                 if [ $(cat "$ABCDETEMPDIR/cddblocalchoices" | wc -l) -ge 24 ] && [ "$INTERACTIVE" = "y" ]; then
2280                                         page "$ABCDETEMPDIR/cddblocalchoices"
2281                                 else
2282                                         # It's all going to fit in one page, cat it
2283                                         cat "$ABCDETEMPDIR/cddblocalchoices" >&2
2284                                 fi
2285                                 CDDBLOCALCHOICES=$( echo "$CDDBLOCALRESULTS" | wc -l )
2286                                 # Setting the choice to an impossible integer to avoid errors in the numeric comparisons
2287                                 CDDBLOCALCHOICENUM=-1
2288                                 if [ "$INTERACTIVE" = "y" ]; then
2289                                         while [ $CDDBLOCALCHOICENUM -lt 0 ] || [ $CDDBLOCALCHOICENUM -gt $CDDBLOCALCHOICES ]; do
2290                                                 echo -n "Locally cached CDDB entries found. Which one would you like to use (0 for none)? [0-$CDDBLOCALCHOICES]: " >&2
2291                                                 read CDDBLOCALCHOICE
2292                                                 [ x"$CDDBLOCALCHOICE" = "x" ] && CDDBLOCALCHOICE="1"
2293                                                 # FIXME # Introduce diff's
2294                                                 if echo $CDDBLOCALCHOICE | grep -E "[[:space:]]*[[:digit:]]+,[[:digit:]]+[[:space:]]*" > /dev/null 2>&1 ; then
2295                                                         diffentries cddblocalread "$CDDBLOCALCHOICES" "$CDDBLOCALCHOICE"
2296                                                 elif echo $CDDBLOCALCHOICE | grep -E "[[:space:]]*[[:digit:]]+[[:space:]]*" > /dev/null 2>&1 ; then
2297                                                         # Make sure we get a valid choice
2298                                                         CDDBLOCALCHOICENUM=$(echo $CDDBLOCALCHOICE | xargs printf %d 2>/dev/null)
2299                                                         if [ $CDDBLOCALCHOICENUM -lt 0 ] || [ $CDDBLOCALCHOICENUM -gt $CDDBLOCALCHOICES ]; then
2300                                                                 echo "Invalid selection. Please choose a number between 0 and $CDDBLOCALCHOICES." >&2
2301                                                         fi
2302                                                 fi
2303                                         done
2304                                 else
2305                                         ### FIXME ###
2306                                         #echo "Selected ..."
2307                                         CDDBLOCALRESP=y
2308                                         CDDBLOCALCHOICENUM=1
2309                                 fi
2310                                 if [ ! "$CDDBLOCALCHOICENUM" = "0" ]; then
2311                                         #echo "Using local copy of CDDB data"
2312                                         echo "# DO NOT ERASE THIS LINE! Added by abcde to imitate cddb output" > "$ABCDETEMPDIR/cddbread.1"
2313                                         cat "$ABCDETEMPDIR/cddblocalread.$CDDBLOCALCHOICENUM" >> "$ABCDETEMPDIR/cddbread.1"
2314                                         echo 999 > "$ABCDETEMPDIR/cddbquery" # Assuming 999 isn't used by CDDB
2315                                         echo cddb-readcomplete >> "$ABCDETEMPDIR/status"
2316                                         do_cddbparse "$ABCDETEMPDIR/cddbread.1" > "$ABCDETEMPDIR/cddbchoices"
2317                                         echo cddb-choice=1 >> "$ABCDETEMPDIR/status"
2318                                         CDDBLOCALSTATUS="found"
2319                                 else
2320                                         #echo "Not using local copy of CDDB data"
2321                                         CDDBLOCALSTATUS="notfound"
2322                                 fi
2323                                 ;;
2324                         single)
2325                                 # List out disc title/author and contents
2326                                 do_cddbparse "${CDDBLOCALFILE}"
2327                                 #if [ "$CDROMREADERSYNTAX" = "flac" ] ; then
2328                                 #       echo -n "Embedded cuesheet entry found, use it [Y/n]? " >&2
2329                                 #else
2330                                         echo -n "Locally cached CDDB entry found, use it [Y/n]? " >&2
2331                                 #fi
2332                                 if [ "$INTERACTIVE" = "y" ]; then
2333                                         read USELOCALRESP
2334                                         while [ "$USELOCALRESP" != "y" ] && [ "$USELOCALRESP" != "n" ] && [ "$USELOCALRESP" != "" ] ; do
2335                                                 echo -n 'Invalid selection. Please answer "y" or "n": ' >&2
2336                                                 read USELOCALRESP
2337                                         done
2338                                         [ x"$USELOCALRESP" = "x" ] && USELOCALRESP="y"
2339                                 else
2340                                         echo "y" >&2
2341                                 fi
2342                                 if [ "$USELOCALRESP" = "y" ]; then
2343                                         #echo "Using local copy of CDDB data"
2344                                         echo "# DO NOT ERASE THIS LINE! Added by abcde to imitate cddb output" > "$ABCDETEMPDIR/cddbread.1"
2345                                         cat "${CDDBLOCALFILE}" >> "$ABCDETEMPDIR/cddbread.1"
2346                                         echo 999 > "$ABCDETEMPDIR/cddbquery" # Assuming 999 isn't used by CDDB
2347                                         echo cddb-readcomplete >> "$ABCDETEMPDIR/status"
2348                                         do_cddbparse "${CDDBLOCALFILE}" > "$ABCDETEMPDIR/cddbchoices"
2349                                         echo cddb-choice=1 >> "$ABCDETEMPDIR/status"
2350                                         CDDBLOCALSTATUS="single"
2351                                 else
2352                                         #echo "Not using local copy of CDDB data"
2353                                         CDDBLOCALSTATUS="notfound"
2354                                 fi
2355                                 ;;
2356                         none)
2357                                 CDDBLOCALSTATUS="notfound"
2358                                 ;;
2359                 esac
2360         fi
2361 }
2362
2363 # do_cdtext
2364 # Try to read CD-Text from the drive using icedax / cdda2wav
2365 do_cdtext ()
2366 {
2367         if new_checkexec icedax; then
2368                 CDTEXT_READER=icedax
2369         elif new_checkexec cdda2wav; then
2370                 CDTEXT_READER=cdda2wav
2371         else
2372                 # Didn't find either, bail
2373                 return 0
2374         fi
2375
2376         if [ "$OSFLAVOUR" = "OSX" ] ; then
2377                 # Hei, we have to unmount the device before running anything like cdda2wav/icedax in OSX
2378                 diskutil unmount ${CDROM#/dev/}
2379                 # Also, in OSX the cdrom device for cdda2wav/icedax changes...
2380                 CDDA2WAVCDROM="IODVDServices"
2381         elif [ "$OSFLAVOUR" = "FBSD" ] ; then
2382                 CDDA2WAVCDROM="$CDROMID"
2383         else
2384                 if [ "$CDROMID" = "" ]; then
2385                         CDDA2WAVCDROM="$CDROM"
2386                 else
2387                         CDDA2WAVCDROM="$CDROMID"
2388                 fi
2389         fi
2390
2391         # Do we have CD-Text on the disc (and can the drive read it?)
2392         ${CDTEXT_READER} -J -N -D ${CDDA2WAVCDROM} > "$ABCDETEMPDIR/cd-text" 2>&1
2393         grep -q '^CD-Text: detected' "$ABCDETEMPDIR/cd-text"
2394         ERRORCODE=$?
2395         if [ $ERRORCODE -ne 0 ]; then
2396                 # No CD-Text found, bail
2397                 return 0
2398         fi
2399
2400         rm -f "$ABCDETEMPDIR/cddbchoices"
2401         CDDBCHOICES=1
2402         # Make an empty template
2403         $CDDBTOOL template $(cat "$ABCDETEMPDIR/discid") > "$ABCDETEMPDIR/cddbread.1"
2404         echo -n "Retrieved 1 CD-Text match..." >> "$ABCDETEMPDIR/cddbchoices"
2405         echo "done." >> "$ABCDETEMPDIR/cddbchoices"
2406         echo cddb-read-1-complete >> "$ABCDETEMPDIR/status"
2407         echo cddb-choice=1 >> "$ABCDETEMPDIR/status"
2408         ATITLE=$(grep -e '^Album title:' "${ABCDETEMPDIR}/cd-text" | cut -c14- )
2409         echo "200 none ${ATITLE}" >> "$ABCDETEMPDIR/cddbquery"
2410         # List out disc title/author and contents
2411         echo ---- ${ATITLE} ---- >> "$ABCDETEMPDIR/cddbchoices"
2412         for TRACK in $(f_seq_row 1 $TRACKS)
2413         do
2414                 TRACKM1=$(($TRACK - 1))
2415                 TITLE="$(grep -E ^Track\ +$TRACK: "$ABCDETEMPDIR/cd-text" | tr -d \\r\\n | sed 's~^Track ..: .~~g;'"s~'$~~g")"
2416                 echo "$TRACK: $TITLE" >> "$ABCDETEMPDIR/cddbchoices"
2417                 sed "s~^TTITLE${TRACKM1}=.*~TTITLE${TRACKM1}=${TITLE}~" "$ABCDETEMPDIR/cddbread.1" > "$ABCDETEMPDIR/cddbread.new"
2418         mv -f "$ABCDETEMPDIR/cddbread.new" "$ABCDETEMPDIR/cddbread.1"
2419         done
2420         sed "s~^DTITLE=.*~DTITLE=${ATITLE}~" "$ABCDETEMPDIR/cddbread.1" > "$ABCDETEMPDIR/cddbread.new"
2421     mv -f "$ABCDETEMPDIR/cddbread.new" "$ABCDETEMPDIR/cddbread.1"
2422         echo >> "$ABCDETEMPDIR/cddbchoices"
2423         echo "cdtext-readcomplete" >> "$ABCDETEMPDIR/status"
2424 }
2425
2426 # do_musicbrainz
2427 # Work with the musicbrainz WS API, then transform the results here so
2428 # they look (very) like the results from CDDB. Maybe not the best way
2429 # to go, but it Works For Me (TM)
2430
2431 do_musicbrainz ()
2432 {
2433         if checkstatus musicbrainz-readcomplete; then :; else
2434                 vecho "Obtaining Musicbrainz results..."
2435                 # If MB is to be used, interpret the query results and read all
2436                 # the available entries.
2437                 rm -f "$ABCDETEMPDIR/cddbchoices"
2438                 CDDBCHOICES=1 # Overridden by multiple matches
2439                 MBDISCID=$(echo $TRACKINFO | cut -d' ' -f1)
2440                 ${MUSICBRAINZ} --command data --discid "$MBDISCID" --workdir "$ABCDETEMPDIR"
2441
2442                 # The helper script will write disc matches out to
2443                 # cddbread.*. Count how many we have
2444                 if [ ! -f "${ABCDETEMPDIR}/cddbread.1" ] ; then
2445                         # No matches. Use the normal cddb template for the user to
2446                         # fill in
2447                         echo "No Musicbrainz match." >> "$ABCDETEMPDIR/cddbchoices"
2448                         $CDDBTOOL template $(cat "$ABCDETEMPDIR/discid") > "$ABCDETEMPDIR/cddbread.0"
2449                         # List out disc title/author and contents of template
2450                         echo ---- Unknown Artist / Unknown Album ---- >> "$ABCDETEMPDIR/cddbchoices"
2451                         UNKNOWNDISK=y
2452                         for TRACK in $(f_seq_row 1 $TRACKS)
2453                         do
2454                                 echo $TRACK: "$(grep ^TTITLE$(expr $TRACK - 1)= "$ABCDETEMPDIR/cddbread.0" | cut -f2- -d= | tr -d \\r\\n)" >> "$ABCDETEMPDIR/cddbchoices"
2455                         done
2456                         echo >> "$ABCDETEMPDIR/cddbchoices"
2457                         echo cddb-read-0-complete >> "$ABCDETEMPDIR/status"
2458                         echo cddb-choice=0 >> "$ABCDETEMPDIR/status"
2459                         echo 503 > "$ABCDETEMPDIR/cddbquery"
2460                 else
2461                         # We have some matches
2462                         NUM_RESPONSES=$(echo "${ABCDETEMPDIR}"/cddbread.* | wc -w)
2463                         if [ "$NUM_RESPONSES" -eq 1 ] ; then
2464                                 # One exact match
2465                                 echo -n "Retrieved 1 Musicbrainz match..." >> "$ABCDETEMPDIR/cddbchoices"
2466                                 echo "done." >> "$ABCDETEMPDIR/cddbchoices"
2467                                 echo cddb-read-1-complete >> "$ABCDETEMPDIR/status"
2468                                 echo cddb-choice=1 >> "$ABCDETEMPDIR/status"
2469                                 ATITLE=$(grep -e '^DTITLE=' "${ABCDETEMPDIR}/cddbread.1" | cut -c8- )
2470                                 echo "200 none ${ATITLE}" >> "$ABCDETEMPDIR/cddbquery"
2471                                 # List out disc title/author and contents
2472                                 echo ---- ${ATITLE} ---- >> "$ABCDETEMPDIR/cddbchoices"
2473                                 for TRACK in $(f_seq_row 1 $TRACKS)
2474                                 do
2475                                         echo $TRACK: "$(grep ^TTITLE$(expr $TRACK - 1)= "$ABCDETEMPDIR/cddbread.1" | cut -f2- -d= | tr -d \\r\\n)" >> "$ABCDETEMPDIR/cddbchoices"
2476                                 done
2477                                 echo >> "$ABCDETEMPDIR/cddbchoices"
2478                         else
2479                                 echo "210 Found exact matches, list follows (until terminating .)" > "$ABCDETEMPDIR/cddbquery"
2480                                 echo "Multiple Musicbrainz matches:" >> "$ABCDETEMPDIR/cddbchoices"
2481                                 for file in "$ABCDETEMPDIR"/cddbread.*
2482                                 do
2483                                         X=$(echo $file | sed 's/^.*cddbread\.//g')
2484                                         echo cddb-read-$X-complete >> "$ABCDETEMPDIR/status"
2485                                         ATITLE=$(grep -e '^DTITLE=' "${ABCDETEMPDIR}"/cddbread.$X | cut -c8- )
2486                                         echo "none ${ATITLE}" >> "$ABCDETEMPDIR/cddbquery"
2487                                         # List out disc title/author and contents
2488                                         echo "#$X: ---- ${ATITLE} ----" >> "$ABCDETEMPDIR/cddbchoices"
2489                                         for TRACK in $(f_seq_row 1 $TRACKS)
2490                                         do
2491                                                 echo $TRACK: "$(grep ^TTITLE$(expr $TRACK - 1)= "$ABCDETEMPDIR/cddbread.$X" | cut -f2- -d= | tr -d \\r\\n)" >> "$ABCDETEMPDIR/cddbchoices"
2492                                         done
2493                                         echo >> "$ABCDETEMPDIR/cddbchoices"
2494                                 done
2495                                 echo "." >> "$ABCDETEMPDIR/cddbquery"
2496                         fi
2497                 fi
2498                 echo "musicbrainz-readcomplete" >> "$ABCDETEMPDIR/status"
2499         fi
2500 }
2501
2502 # do_cddbstat
2503 do_cddbstat ()
2504 {
2505         # Perform CDDB protocol version check if it hasn't already been done
2506         if checkstatus cddb-statcomplete; then :; else
2507                 if [ "$CDDBAVAIL" = "n" ]; then
2508                         ERRORCODE=no_query
2509                         echo 503 > "$ABCDETEMPDIR/cddbstat"
2510                 else
2511                         rc=1
2512                         CDDBUSER=$(echo $HELLOINFO | cut -f1 -d'@')
2513                         CDDBHOST=$(echo $HELLOINFO | cut -f2- -d'@')
2514                         while test $rc -eq 1 -a $CDDBPROTO -ge 3; do
2515                                 vecho "Checking CDDB server status..."
2516                                 $CDDBTOOL stat $CDDBURL $CDDBUSER $CDDBHOST $CDDBPROTO > "$ABCDETEMPDIR/cddbstat"
2517                                 RESPONSECODE=$(head -n 1 "$ABCDETEMPDIR/cddbstat" | cut -f1 -d' ')
2518                                 case "$RESPONSECODE" in
2519                                 210)    # 210 OK, status information follows (until terminating `.')
2520                                         rc=0
2521                                         ;;
2522                                 501)  # 501 Illegal CDDB protocol level: <n>.
2523                                         CDDBPROTO=`expr $CDDBPROTO - 1`
2524                                         ;;
2525                                 *)      # Try a cddb query, since freedb2.org doesn't support the stat or ver commands
2526                                         # FreeDB TESTCD disc-id is used for query
2527                                         $CDDBTOOL query $CDDBURL $CDDBPROTO $CDDBUSER $CDDBHOST 03015501 1 296 344 > "$ABCDETEMPDIR/cddbstat"
2528                                         RESPONSECODE=$(head -n 1 "$ABCDETEMPDIR/cddbstat" | cut -f1 -d' ')
2529                                         case "$RESPONSECODE" in
2530                                                 2??)    # Server responded, everything seems OK
2531                                                         rc=0
2532                                                         ;;
2533                                                 *)      # unknown error
2534                                                         break
2535                                                         ;;
2536                                         esac
2537                                         ;;
2538                                 esac
2539                         done
2540                         if test $rc -eq 1; then
2541                                 CDDBAVAIL="n"
2542                         fi
2543                 fi
2544                 echo cddb-statcomplete >> "$ABCDETEMPDIR/status"
2545         fi
2546 }
2547
2548
2549 # do_cddbquery
2550 do_cddbquery ()
2551 {
2552         CDDBDISCID=$(echo $TRACKINFO | cut -d' ' -f1)
2553         CDDBLOCALFILE="${CDDBLOCALDIR}/${CDDBDISCID}"
2554
2555         # Perform CDDB query if it hasn't already been done
2556         if checkstatus cddb-querycomplete; then :; else
2557                 if [ "$CDDBAVAIL" = "n" ]; then
2558                         ERRORCODE=no_query
2559                         echo 503 > "$ABCDETEMPDIR/cddbquery"
2560                 # The default CDDBLOCALSTATUS is "notfound"
2561                 # This part will be triggered if the user CDDB repo does not
2562                 # contain the entry, or if we are not trying to use the repo.
2563                 else
2564                         vecho "Querying the CDDB server..."
2565                         CDDBUSER=$(echo $HELLOINFO | cut -f1 -d'@')
2566                         CDDBHOST=$(echo $HELLOINFO | cut -f2- -d'@')
2567                         $CDDBTOOL query $CDDBURL $CDDBPROTO $CDDBUSER $CDDBHOST $TRACKINFO > "$ABCDETEMPDIR/cddbquery"
2568                         ERRORCODE=$?
2569                         case $ERRORCODE in
2570                                 0)  # success
2571                                 ;;
2572                                 12|13|14)
2573                                         # no match found in database,
2574                                         # wget/fetch error, or user requested not to use CDDB
2575                                         # Make up an error code (503) that abcde
2576                                         # will recognize in do_cddbread
2577                                         # and compensate by making a template
2578                                         echo 503 > "$ABCDETEMPDIR/cddbquery"
2579                                 ;;
2580                                 *) # strange and unknown error
2581                                         echo ERRORCODE=$ERRORCODE
2582                                         echo "abcde: $CDDBTOOL returned unknown error code"
2583                                 ;;
2584                         esac
2585                 fi
2586                 echo cddb-querycomplete >> "$ABCDETEMPDIR/status"
2587         fi
2588 }
2589
2590 # do_cddbread
2591 do_cddbread ()
2592 {
2593         # If it's not to be used, generate a template.
2594         # Then, display it (or them) and let the user choose/edit it
2595         if checkstatus cddb-readcomplete; then :; else
2596                 vecho "Obtaining CDDB results..."
2597                 # If CDDB is to be used, interpret the query results and read all
2598                 # the available entries.
2599                 rm -f "$ABCDETEMPDIR/cddbchoices"
2600                 CDDBCHOICES=1 # Overridden by multiple matches
2601                 RESPONSECODE=$(head -n 1 "$ABCDETEMPDIR/cddbquery" | cut -f1 -d' ')
2602                 case "$RESPONSECODE" in
2603                 200)
2604                         # One exact match, retrieve it
2605                         # 200 [section] [discid] [artist] / [title]
2606                         if checkstatus cddb-read-1-complete; then :; else
2607                                 echo -n "Retrieving 1 CDDB match..." >> "$ABCDETEMPDIR/cddbchoices"
2608                                 $CDDBTOOL read $CDDBURL $CDDBPROTO $CDDBUSER $CDDBHOST $(cut -f2,3 -d' ' "$ABCDETEMPDIR/cddbquery") > "$ABCDETEMPDIR/cddbread.1"
2609                                 echo "done." >> "$ABCDETEMPDIR/cddbchoices"
2610                                 echo cddb-read-1-complete >> "$ABCDETEMPDIR/status"
2611                                 echo cddb-choice=1 >> "$ABCDETEMPDIR/status"
2612                         fi
2613                         # List out disc title/author and contents
2614                         echo ---- "$(cut '-d ' -f4- "$ABCDETEMPDIR/cddbquery")" ---- >> "$ABCDETEMPDIR/cddbchoices"
2615                         for TRACK in $(f_seq_row 1 $TRACKS)
2616                         do
2617                                 echo $TRACK: "$(grep ^TTITLE$(expr $TRACK - 1)= "$ABCDETEMPDIR/cddbread.1" | cut -f2- -d= | tr -d \\r\\n)" >> "$ABCDETEMPDIR/cddbchoices"
2618                         done
2619                         echo >> "$ABCDETEMPDIR/cddbchoices"
2620                         ;;
2621                 202|403|409|503)
2622                         # No match
2623                         case "$RESPONSECODE" in
2624                         202) echo "No CDDB match." >> "$ABCDETEMPDIR/cddbchoices" ;;
2625                         403|409) echo "CDDB entry is corrupt, or the handshake failed." >> "$ABCDETEMPDIR/cddbchoices" ;;
2626                         503) echo "CDDB unavailable." >> "$ABCDETEMPDIR/cddbchoices" ;;
2627                         esac
2628                         $CDDBTOOL template $(cat "$ABCDETEMPDIR/discid") > "$ABCDETEMPDIR/cddbread.0"
2629                         # List out disc title/author and contents of template
2630                         echo ---- Unknown Artist / Unknown Album ---- >> "$ABCDETEMPDIR/cddbchoices"
2631                         UNKNOWNDISK=y
2632                         for TRACK in $(f_seq_row 1 $TRACKS)
2633                         do
2634                                 echo $TRACK: "$(grep ^TTITLE$(expr $TRACK - 1)= "$ABCDETEMPDIR/cddbread.0" | cut -f2- -d= | tr -d \\r\\n)" >> "$ABCDETEMPDIR/cddbchoices"
2635                         done
2636                         echo >> "$ABCDETEMPDIR/cddbchoices"
2637                         echo cddb-read-0-complete >> "$ABCDETEMPDIR/status"
2638                         echo cddb-choice=0 >> "$ABCDETEMPDIR/status"
2639                         ;;
2640                 210|211)
2641                         # Multiple exact, (possibly multiple) inexact matches
2642                         IN=
2643                         if [ "$RESPONSECODE" = "211" ]; then IN=in; fi
2644                         if [ "$(wc -l < "$ABCDETEMPDIR/cddbquery" | tr -d ' ')" -eq 3 ]; then
2645                                 echo "One ${IN}exact match:" >> "$ABCDETEMPDIR/cddbchoices"
2646                                 tail -n +2 "$ABCDETEMPDIR/cddbquery" | head -n 1 >> "$ABCDETEMPDIR/cddbchoices"
2647                                                         echo cddb-choice=1 >> "$ABCDETEMPDIR/status"
2648                         else
2649                                 echo "Multiple ${IN}exact matches:" >> "$ABCDETEMPDIR/cddbchoices"
2650                         fi
2651                         vecho -n "Retrieving multiple matches... "
2652                         grep -v ^[.]$ "$ABCDETEMPDIR/cddbquery" | ( X=0
2653                         read DISCINFO # eat top line
2654                         while read DISCINFO
2655                         do
2656                                 X=$(expr $X + 1)
2657                                 if checkstatus cddb-read-$X-complete; then :; else
2658                                         $CDDBTOOL read $CDDBURL $CDDBPROTO $CDDBUSER $CDDBHOST $(echo $DISCINFO | cut -f1,2 -d' ') > "$ABCDETEMPDIR/cddbread.$X"
2659                                         echo cddb-read-$X-complete >> "$ABCDETEMPDIR/status"
2660                                 fi
2661                                 # List out disc title/author and contents
2662                                 echo \#$X: ---- "$DISCINFO" ---- >> "$ABCDETEMPDIR/cddbchoices"
2663                                 for TRACK in $(f_seq_row 1 $TRACKS)
2664                                 do
2665                                         echo $TRACK: "$(grep ^TTITLE$(expr $TRACK - 1)= "$ABCDETEMPDIR/cddbread.$X" | cut -f2- -d= | tr -d \\r\\n)" >> "$ABCDETEMPDIR/cddbchoices"
2666                                 done
2667                                 echo >> "$ABCDETEMPDIR/cddbchoices"
2668                         done )
2669                         vecho "done."
2670                         CDDBCHOICES=$(expr $(cat "$ABCDETEMPDIR/cddbquery" | wc -l) - 2)
2671                         ;;
2672                 999)
2673                         # Using local copy.
2674                         for TRACK in $(f_seq_row 1 $TRACKS)
2675                         do
2676                                 echo $TRACK: "$(grep ^TTITLE$(expr $TRACK - 1)= "$ABCDETEMPDIR/cddbread.1" | cut -f2- -d= | tr -d \\r\\n)" >> "$ABCDETEMPDIR/cddbchoices"
2677                         done
2678                         echo >> "$ABCDETEMPDIR/cddbchoices"
2679                         echo cddb-read-1-complete >> "$ABCDETEMPDIR/status"
2680                         echo cddb-choice=1 >> "$ABCDETEMPDIR/status"
2681                         ;;
2682                 esac
2683                 echo "cddb-readcomplete" >> "$ABCDETEMPDIR/status"
2684         fi
2685 }
2686
2687 # do_cddbedit
2688 do_cddbedit ()
2689 {
2690         if checkstatus cddb-edit >/dev/null; then
2691                 CDDBDATA="$ABCDETEMPDIR/cddbread.$(checkstatus cddb-choice)"
2692                 VARIOUSARTISTS="$(checkstatus variousartists)"
2693                 VARIOUSARTISTSTYLE="$(checkstatus variousartiststyle)"
2694                 return 0
2695         fi
2696         if [ "$INTERACTIVE" = "y" ]; then
2697                 # We should show the CDDB results both when we are not using the local CDDB repo
2698                 # or when we are using it but we could not find a proper match
2699                 if [ "$CDDBUSELOCAL" = "y" ] && [ "$CDDBLOCALSTATUS" = "notfound" ] || [ ! "$CDDBUSELOCAL" = "y" ]; then
2700                         # Display the $ABCDETEMPDIR/cddbchoices file created above
2701                         # Pick a pager so that if the tracks overflow the screen the user can still view everything
2702                         if [ -r "$ABCDETEMPDIR/cddbchoices" ]; then
2703                                 CDDBCHOICES=$(expr $(cat "$ABCDETEMPDIR/cddbquery" | wc -l) - 2)
2704                                 CHOICE=$(checkstatus cddb-choice)
2705                                 if [ -n "$CHOICE" ] ; then
2706                                         case $CDDBCHOICES in
2707                                                 -1) if head -1 "$ABCDETEMPDIR/cddbquery" | grep "^$" > /dev/null 2>&1 ; then
2708                                                                 log error "CDDB query failed!"
2709                                                                 exit 1
2710                                                         else
2711                                                                 cat "$ABCDETEMPDIR/cddbchoices"
2712                                                         fi
2713                                                         ;;
2714                                                 1) cat "$ABCDETEMPDIR/cddbchoices" ;;
2715                                                 *)
2716                                                 echo "Selected: #$CHOICE"
2717                                                 do_cddbparse "$ABCDETEMPDIR/cddbread.$CHOICE"
2718                                                 ;;
2719                                         esac
2720                                 else
2721                                         # The user has a choice to make, display the info in a pager if necessary
2722                                         if [ $(cat "$ABCDETEMPDIR/cddbchoices" | wc -l) -ge 24 ]; then
2723                                                 page "$ABCDETEMPDIR/cddbchoices"
2724                                         else
2725                                                 # It's all going to fit in one page, cat it
2726                                                 cat "$ABCDETEMPDIR/cddbchoices" >&2
2727                                         fi
2728
2729                                         CDDBCHOICENUM=""
2730                                         # Setting the choice to an impossible integer to avoid errors in the numeric comparisons
2731                                         CDCHOICENUM=-1
2732                                         # I'll take CDDB read #3 for $400, Alex
2733                                         while [ $CDCHOICENUM -lt 0 ] || [ $CDCHOICENUM -gt $CDDBCHOICES ]; do
2734                                                 echo -n "Which entry would you like abcde to use (0 for none)? [0-$CDDBCHOICES]: " >&2
2735                                                 read CDDBCHOICE
2736                                                 [ X"$CDDBCHOICE" = "X" ] && CDDBCHOICE=1
2737                                                 if echo $CDDBCHOICE | grep -E "[[:space:]]*[[:digit:]]+,[[:digit:]]+[[:space:]]*" > /dev/null 2>&1 ; then
2738                                                         if [ ! X"$DIFF" = "X" ]; then
2739                                                                 PARSECHOICE1=$(echo $CDDBCHOICE | cut -d"," -f1 | xargs printf %d 2>/dev/null)
2740                                                                 PARSECHOICE2=$(echo $CDDBCHOICE | cut -d"," -f2 | xargs printf %d 2>/dev/null)
2741                                                                 if [ $PARSECHOICE1 -lt 1 ] || [ $PARSECHOICE1 -gt $CDDBCHOICES ] || \
2742                                                                    [ $PARSECHOICE2 -lt 1 ] || [ $PARSECHOICE2 -gt $CDDBCHOICES ] || \
2743                                                                    [ $PARSECHOICE1 -eq $PARSECHOICE2 ]; then
2744                                                                         echo "Invalid diff range. Please select two comma-separated numbers between 1 and $CDDBCHOICES" >&2
2745                                                                 else
2746                                                                         # We parse the 2 choices to diff, store them in temporary files and diff them.
2747                                                                         for PARSECHOICE in $(echo $CDDBCHOICE | tr , \ ); do
2748                                                                                 do_cddbparse "$ABCDETEMPDIR/cddbread.$PARSECHOICE" > "$ABCDETEMPDIR/cddbread.parsechoice.$PARSECHOICE"
2749                                                                         done
2750                                                                         echo "Showing diff between choices $PARSECHOICE1 and $PARSECHOICE2..." > "$ABCDETEMPDIR/cddbread.diff"
2751                                                                         $DIFF $DIFFOPTS "$ABCDETEMPDIR/cddbread.parsechoice.$PARSECHOICE1" "$ABCDETEMPDIR/cddbread.parsechoice.$PARSECHOICE2" >> "$ABCDETEMPDIR/cddbread.diff"
2752                                                                         if [ $(cat "$ABCDETEMPDIR/cddbread.diff" | wc -l) -ge 24 ]; then
2753                                                                                 page "$ABCDETEMPDIR/cddbread.diff"
2754                                                                         else
2755                                                                                 cat "$ABCDETEMPDIR/cddbread.diff" >&2
2756                                                                         fi
2757                                                                 fi
2758                                                         else
2759                                                                 echo "The diff program was not found in your path. Please choose a number between 0 and $CDDBCHOICES." >&2
2760                                                         fi
2761                                                 elif echo $CDDBCHOICE | grep -E "[[:space:]]*[[:digit:]]+[[:space:]]*" > /dev/null 2>&1 ; then
2762                                                         # Make sure we get a valid choice
2763                                                         CDCHOICENUM=$(echo $CDDBCHOICE | xargs printf %d 2>/dev/null)
2764                                                         if [ $CDCHOICENUM -lt 0 ] || [ $CDCHOICENUM -gt $CDDBCHOICES ]; then
2765                                                                 echo "Invalid selection. Please choose a number between 0 and $CDDBCHOICES." >&2
2766                                                         fi
2767                                                 fi
2768                                         done
2769                                         if [ "$CDCHOICENUM" = "0" ]; then
2770                                                 vecho "Creating empty CDDB template..."
2771                                                 UNKNOWNDISK=y
2772                                                 $CDDBTOOL template $(cat "$ABCDETEMPDIR/discid") > "$ABCDETEMPDIR/cddbread.0"
2773                                         else
2774                                                 echo "Selected: #$CDCHOICENUM ($(grep ^DTITLE= "$ABCDETEMPDIR/cddbread.$CDCHOICENUM" | cut -f2- -d= | tr -d \\r\\n))" >&2
2775                                                 do_cddbparse "$ABCDETEMPDIR/cddbread.$CDCHOICENUM"
2776                                         fi
2777                                         echo "cddb-choice=$CDCHOICENUM" >> "$ABCDETEMPDIR/status"
2778                                 fi
2779                         fi
2780                 else
2781                         # We need some code to show the selected option when local repository is selected and we have found a match
2782                         vecho "Using cached CDDB match..." >&2
2783                         # Display the $ABCDETEMPDIR/cddbchoices file created above
2784                         # Pick a pager so that if the tracks overflow the screen the user can still view everything
2785                         if [ -r "$ABCDETEMPDIR/cddbchoices" ]; then
2786                                 CDDBCHOICES=$(expr $(cat "$ABCDETEMPDIR/cddbquery" | wc -l) - 2)
2787                                 CHOICE=$(checkstatus cddb-choice)
2788                                 if [ "$USELOCALRESP" = "y" ]; then :; else
2789                                         if [ -n "$CHOICE" ] ; then
2790                                                 case $CDDBCHOICES in
2791                                                         0)
2792                                                         UNKNOWNDISK=y
2793                                                         echo "Selected template."
2794                                                         ;;
2795                                                         1) cat "$ABCDETEMPDIR/cddbchoices" ;;
2796                                                         *)
2797                                                         echo "Selected: #$CHOICE"
2798                                                         do_cddbparse "$ABCDETEMPDIR/cddbread.$CHOICE"
2799                                                         ;;
2800                                                 esac
2801                                         fi
2802                                 fi
2803                         fi
2804                 fi
2805         else
2806                 # We're noninteractive - pick the first choice.
2807                 # But in case we run a previous instance and selected a choice, use it.
2808                 if [ -r "$ABCDETEMPDIR/cddbchoices" ]; then
2809                         # Show the choice if we are not using the locally stored one
2810                         # or when the local search failed to find a match.
2811                         PREVIOUSCHOICE=$(checkstatus cddb-choice)
2812                         if [ "$CDDBUSELOCAL" = "y" ] && [ "$CDDBLOCALSTATUS" = "notfound" ] || [ ! "$CDDBUSELOCAL" = "y" ]; then
2813                                 #if [ "$PREVIOUSCHOICE" ]; then
2814                                         cat "$ABCDETEMPDIR/cddbchoices"
2815                                 #fi
2816                         fi
2817                         if [ ! -z "$PREVIOUSCHOICE" ] ; then
2818                                 CDCHOICENUM=$PREVIOUSCHOICE
2819                         else
2820                                 CDCHOICENUM=1
2821                                 echo "cddb-choice=$CDCHOICENUM" >> "$ABCDETEMPDIR/status"
2822                         fi
2823                         echo "Selected: #$CDCHOICENUM ($(grep ^DTITLE= "$ABCDETEMPDIR/cddbread.$CDCHOICENUM" | cut -f2- -d= | tr -d \\r\\n))" >&2
2824                 fi
2825         fi
2826
2827         # sanity check
2828         if checkstatus cddb-choice >/dev/null; then :; else
2829                 echo "abcde: internal error: cddb-choice not recorded." >&2
2830                 exit 1
2831         fi
2832         CDDBDATA="$ABCDETEMPDIR/cddbread.$(checkstatus cddb-choice)"
2833         echo -n "Edit selected CDDB data " >&2
2834         if [ "$INTERACTIVE" = "y" ]; then
2835                 if [ "$UNKNOWNDISK" = "y" ]; then
2836                         echo -n "[Y/n]? " >&2
2837                         read EDITCDDB
2838                         [ "$EDITCDDB" != "n" ] && EDITCDDB=y
2839                 else
2840                         echo -n "[y/N]? " >&2
2841                         read EDITCDDB
2842                 fi
2843         else
2844                 echo "[y/N]? " >&2
2845                 EDITCDDB=n
2846         fi
2847         if [ "$EDITCDDB" = "y" ]; then
2848                 CDDBDATAMD5SUM=$($MD5SUM "$CDDBDATA" | cut -d " " -f 1);
2849
2850                 # Use the debian sensible-editor wrapper to pick the editor that the
2851                 # user has requested via their $EDITOR environment variable
2852                 if [ -x "/usr/bin/sensible-editor" ]; then
2853                         /usr/bin/sensible-editor "$CDDBDATA"
2854                 elif [ -n "$EDITOR" ]; then
2855                         if [ -x $(which "${EDITOR%%\ *}") ]; then
2856                                 # That failed, try to load the preferred editor, starting
2857                                 # with their EDITOR variable
2858                                 eval $(echo "$EDITOR") \"$CDDBDATA\"
2859                         fi
2860                 # If that fails, check for a vi
2861                 elif which vi >/dev/null 2>&1; then
2862                         vi "$CDDBDATA"
2863                 elif [ -x /usr/bin/vim ]; then
2864                         /usr/bin/vim "$CDDBDATA"
2865                 elif [ -x /usr/bin/vi ]; then
2866                         /usr/bin/vi "$CDDBDATA"
2867                 elif [ -x /bin/vi ]; then
2868                         /bin/vi "$CDDBDATA"
2869                 # nano should be on all (modern, i.e., sarge) debian systems
2870                 elif which nano >/dev/null 2>&1 ; then
2871                         nano "$CDDBDATA"
2872                 elif [ -x /usr/bin/nano ]; then
2873                         /usr/bin/nano "$CDDBDATA"
2874                 # mg should be on all OpenBSD systems
2875                 elif which mg >/dev/null 2>&1 ; then
2876                         mg "$CDDBDATA"
2877                 elif [ -x /usr/bin/mg ]; then
2878                         /usr/bin/mg "$CDDBDATA"
2879                 # bomb out
2880                 else
2881                         log warning "no editor available. Check your EDITOR environment variable."
2882                 fi
2883                 # delete editor backup file if it exists
2884                 if [ -w "$CDDBDATA~" ]; then
2885                         rm -f "$CDDBDATA~"
2886                 fi
2887         fi
2888
2889         # Some heuristics first. Look at Disc Title, and if it starts with
2890         # "Various", then we'll assume Various Artists
2891         if [ "$(grep ^DTITLE= "$CDDBDATA" | cut -f2- -d= | grep -Eci '^(various|soundtrack|varios|sonora|ost)')" != "0" ]; then
2892                 echo "Looks like a Multi-Artist CD" >&2
2893                 VARIOUSARTISTS=y
2894         else
2895                 echo -n "Is the CD multi-artist [y/N]? " >&2
2896                 if [ "$INTERACTIVE" = "y" ]; then
2897                         read VARIOUSARTISTS
2898                 else
2899                         echo n >&2
2900                         VARIOUSARTISTS=n
2901                 fi
2902         fi
2903         if [ "$VARIOUSARTISTS" = "y" ] && [ ! "$ONETRACK" = "y" ]; then
2904                 # Set a default
2905                 DEFAULTSTYLE=1
2906                 # Need NUMTRACKS before cddb-tool will return it:
2907                 NUMTRACKS=$(grep -E '^TTITLE[0-9]+=' "$CDDBDATA" | wc -l)
2908                 if [ "$(grep -c "^TTITLE.*\/" "$CDDBDATA")" -gt "$(expr $NUMTRACKS / 2 )" ]; then
2909                         # More than 1/2 tracks contain a "/", so guess forward
2910                         DEFAULTSTYLE=1
2911                 elif [ "$(grep -c "^TTITLE.*\-" "$CDDBDATA")" -gt "$(expr $NUMTRACKS / 2 )" ]; then
2912                         # More than 1/2 contain a "-", so guess forward-dash
2913                         DEFAULTSTYLE=2
2914                 elif [ "$(grep -c "^TTITLE.*(.*)" "$CDDBDATA")" -gt "$(expr $NUMTRACKS / 2 )" ]; then
2915                         # More than 1/2 contain something in parens, so guess trailing-paren
2916                         DEFAULTSTYLE=6
2917                 fi
2918
2919                 echo "1) Artist / Title" >&2
2920                 echo "2) Artist - Title" >&2
2921                 echo "3) Title / Artist" >&2
2922                 echo "4) Title - Artist" >&2
2923                 echo "5) Artist: Title" >&2
2924                 echo "6) Title (Artist)" >&2
2925                 echo "7) This is a single-artist CD" >&2
2926                 echo -n "Which style of multiple artist entries is it? [1-7] ($DEFAULTSTYLE): " >&2
2927                 if [ "$INTERACTIVE" = "y" ]; then
2928                         read VARIOUSARTISTSTYLE
2929                 else
2930                         echo $DEFAULTSTYLE >&2
2931                         VARIOUSARTISTSTYLE=$DEFAULTSTYLE
2932                 fi
2933                 VARIOUSARTISTSTYLE=$(echo 0$VARIOUSARTISTSTYLE | xargs printf %d)
2934                 # If they press Enter, then the default style (0) was chosen
2935                 while [ $VARIOUSARTISTSTYLE -lt 0 ] || [ $VARIOUSARTISTSTYLE -gt 7 ]; do
2936                         echo "Invalid selection. Please choose a number between 1 and 7."
2937                         echo -n "Selection [1-7]: "
2938                         read VARIOUSARTISTSTYLE
2939                         VARIOUSARTISTSTYLE=$(echo 0$VARIOUSARTISTSTYLE | xargs printf %d)
2940                 done
2941                 if [ "$VARIOUSARTISTSTYLE" = "0" ]; then
2942                         VARIOUSARTISTSTYLE=$DEFAULTSTYLE
2943                 fi
2944                 vecho "Selected: $VARIOUSARTISTSTYLE"
2945                 case "$VARIOUSARTISTSTYLE" in
2946                 1) # Artist / Title
2947                         VARIOUSARTISTSTYLE=forward
2948                         ;;
2949                 2) # Artist - Title
2950                         VARIOUSARTISTSTYLE=forward-dash
2951                         ;;
2952                 3) # Title / Artist
2953                         VARIOUSARTISTSTYLE=reverse
2954                         ;;
2955                 4) # Title - Artist
2956                         VARIOUSARTISTSTYLE=reverse-dash
2957                         ;;
2958                 5) # Artist: Title
2959                         VARIOUSARTISTSTYLE=colon
2960                         ;;
2961                 6) # Title (Artist)
2962                         VARIOUSARTISTSTYLE=trailing-paren
2963                         ;;
2964                 7) # Single Artist
2965                         VARIOUSARTISTS=n
2966                         ;;
2967                 esac
2968         fi
2969