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