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