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