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