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