Support for WavPack added. Closes issue 123.
[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). 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 $MPPGAIN --auto "${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                         case "$ID3SYNTAX" in
821                                 id3);;
822                                 eyed3*)
823                                         # FIXME # track numbers in mp3 come with 1/10, so we cannot
824                                         # happily substitute them with $TRACKNUM
825                                         case "$ID3SYNTAX" in
826                                                 eyed3_06) addopts=( \
827                                                         ${ENCODING:+--set-encoding="$ENCODING"} \
828                                                         ${TPE2:+--set-text-frame=TPE2:"$TPE2"} \
829                                                         ${COMMENTOUTPUT:+--comment=::"$COMMENTOUTPUT"} \
830                                                         );;
831                                                 *) addopts=( \
832                                                         ${ENCODING:+--encoding="$ENCODING"} \
833                                                         ${TPE2:+--text-frame=TPE2:"$TPE2"} \
834                                                         ${COMMENTOUTPUT:+--comment "$COMMENTOUTPUT"} \
835                                                         );;
836                                         esac
837                                         run_command tagtrack-$OUTPUT-$1 nice $ENCNICE $TAGGER $TAGGEROPTS \
838                                             -A "$DALBUM" \
839                                                 -a "$TRACKARTIST" -t "$TRACKNAME" ${CDYEAR:+-Y "$CDYEAR"} \
840                                                 -G "$GENREID" -n "${TRACKNUM:-$1}" \
841                                                 ${TRACKNUM:+-N "$TRACKS"} \
842                                                 "${addopts[@]}" \
843                                                 "$ABCDETEMPDIR/track$1.$OUTPUT"
844                                         ;;
845                                 # FIXME # Still not activated...
846                                 id3ed)
847                                         run_command tagtrack-$OUTPUT-$1 nice $ENCNICE \
848                                                 $TAGGER $TAGGEROPTS -c "$COMMENTOUTPUT" \
849                                                 -a "$DALBUM" -n "$TRACKARTIST" -s "$TRACKNAME" \
850                                                 -y "$CDYEAR" -g "$GENREID" -k "${TRACKNUM:-$1}" \
851                                                 "$ABCDETEMPDIR/track$1.$OUTPUT"
852                                         ;;
853                                 *)
854                                         # FIXME # track numbers in mp3 come with 1/10, so we cannot
855                                         # happily substitute them with $TRACKNUM
856                                         run_command tagtrack-$OUTPUT-$1 nice $ENCNICE \
857                                                 $TAGGER $TAGGEROPTS -c "$COMMENTOUTPUT" \
858                                                 -A "$DALBUM" -a "$TRACKARTIST" -t "$TRACKNAME" \
859                                                 -y "$CDYEAR" -g "$GENREID" \
860                                                 -T "${TRACKNUM:-$1}/$TRACKS" \
861                                                 ${TPE2:+--TPE2 "$TPE2"} \
862                                                 "$ABCDETEMPDIR/track$1.$OUTPUT"
863                                         ;;
864                         esac
865                         ;;
866                 vorbis|ogg)
867                         case "$OGGENCODERSYNTAX" in
868                                 vorbize|oggenc)
869                                         # vorbiscomment can't do in-place modification, mv the file first
870                                         if [ -f "$ABCDETEMPDIR/track$1.$OGGOUTPUTCONTAINER" -a ! -f "$ABCDETEMPDIR/track$1.uncommented.$OGGOUTPUTCONTAINER" ]; then
871                                                 mv "$ABCDETEMPDIR/track$1.$OGGOUTPUTCONTAINER" "$ABCDETEMPDIR/track$1.uncommented.$OGGOUTPUTCONTAINER"
872                                         fi
873                                         (
874                                         # These are from
875                                         # http://www.xiph.org/ogg/vorbis/doc/v-comment.html
876
877                                         echo ARTIST="$TRACKARTIST"
878                                         echo ALBUM="$DALBUM"
879                                         echo TITLE="$TRACKNAME"
880                                         if [ -n "$CDYEAR" ]; then
881                                                 echo DATE="$CDYEAR"
882                                         fi
883                                         if [ -n "$CDGENRE" ]; then
884                                                 echo GENRE="$CDGENRE"
885                                         fi
886                                         echo TRACKNUMBER=${TRACKNUM:-$1}
887                                         if [ -n "$DISCNUMBER" ]; then
888                                                 echo DISCNUMBER="$DISCNUMBER"
889                                         fi
890                                         echo CDDB=$CDDBDISCID
891                                         if [ "$(eval echo ${COMMENT})" != "" ]; then
892                                                 case "$COMMENTOUTPUT" in
893                                                         *=*) echo "$COMMENTOUTPUT";;
894                                                         *)   echo COMMENT="$COMMENTOUTPUT";;
895                                                 esac
896                                         fi
897                                         ) | run_command tagtrack-$OUTPUT-$1 nice $ENCNICE \
898                                                 $VORBISCOMMENT $VORBISCOMMENTOPTS -w \
899                                                 "$ABCDETEMPDIR/track$1.uncommented.$OGGOUTPUTCONTAINER" "$ABCDETEMPDIR/track$1.$OGGOUTPUTCONTAINER"
900                                         # Doublecheck that the commented file was created
901                                         # successfully before wiping the original
902                                         if [ -f "$ABCDETEMPDIR/track$1.$OGGOUTPUTCONTAINER" ]; then
903                                                 rm -f "$ABCDETEMPDIR/track$1.uncommented.$OGGOUTPUTCONTAINER"
904                                         else
905                                                 mv "$ABCDETEMPDIR/track$1.uncommented.$OGGOUTPUTCONTAINER" "$ABCDETEMPDIR/track$1.$OGGOUTPUTCONTAINER"
906                                         fi
907                                         ;;
908                         esac
909                         ;;
910                 opus)
911                         run_command tagtrack-$OUTPUT-$1 true
912                         ;;
913
914                 flac)
915                         (
916                         echo ARTIST="$TRACKARTIST"
917                         echo ALBUM="$DALBUM"
918                         echo TITLE="$TRACKNAME"
919                         if [ -n "$CDYEAR" ]; then
920                                 echo DATE="$CDYEAR"
921                         fi
922                         if [ -n "$CDGENRE" ]; then
923                                 echo GENRE="$CDGENRE"
924                         fi
925                         echo TRACKNUMBER="${TRACKNUM:-$1}"
926                         if [ -n "$DISCNUMBER" ]; then
927                                 echo DISCNUMBER="$DISCNUMBER"
928                         fi
929                         echo CDDB="$CDDBDISCID"
930                         if [ "$(eval echo ${COMMENT})" != "" ]; then
931                                 case "$COMMENTOUTPUT" in
932                                         *=*) echo "$COMMENTOUTPUT";;
933                                         *)   echo COMMENT="$COMMENTOUTPUT";;
934                                 esac
935                         fi
936                         ) | run_command tagtrack-$OUTPUT-$1 nice $ENCNICE $METAFLAC $METAFLACOPTS ${IMPORTCUESHEET:+--import-cuesheet-from="$ABCDETEMPDIR/$CUEFILE"} --import-tags-from=- "$ABCDETEMPDIR/track$1.$FLACOUTPUTCONTAINER"
937                         ;;
938                 spx)
939                         run_command tagtrack-$OUTPUT-$1 true
940                         ;;
941                 mpc)
942                         run_command tagtrack-$OUTPUT-$1 true
943                         ;;
944         wv)
945             run_command tagtrack-$OUTPUT-$1 true
946                         ;;
947                 aac)
948                         run_command tagtrack-$OUTPUT-$1 true
949                 ;;
950                 m4a)
951                   case "$AACENCODERSYNTAX" in
952                     fdkaac) # We will use inline tagging...
953                         run_command tagtrack-$OUTPUT-$1 true
954                         ;;
955                     neroAacEnc) # Tag post encode with neroAacTag...
956                      run_command tagtrack-$OUTPUT-$1 nice $ENCNICE "$NEROAACTAG" "$ABCDETEMPDIR/track$1.m4a" \
957                      -meta:artist="$TRACKARTIST" -meta:album="$DALBUM" -meta:title="$TRACKNAME" -meta:track=${TRACKNUM:-$1} \
958                      -meta:year="$CDYEAR" -meta:genre="$CDGENRE" -meta:comment="$COMMENT"
959                       ;;
960                    faac)
961                      run_command tagtrack-$OUTPUT-$1 true                   
962                         ;;
963                 esac                    
964                         ;;
965                 wav)
966                         run_command tagtrack-$OUTPUT-$1 true
967                         ;;
968                 esac
969         done
970         if checkerrors "tagtrack-(.{3,6})-$1"; then :; else
971                 run_command tagtrack-$1 true
972         fi
973
974 }
975
976 # do_nogap_encode
977 # variables used:
978 # OUTPUTTYPE, {FOO}ENCODERSYNTAX, ENCNICE, ENCODER, ENCODEROPTS
979 do_nogap_encode ()
980 {
981         # The commands here don't go through run_command because they're never
982         # supposed to be silenced
983         echo "Encoding gapless MP3 tracks: $TRACKQUEUE"
984         for OUTPUT in $(echo $OUTPUTTYPE | tr , \ )
985         do
986                 case "$OUTPUT" in
987                 mp3)
988                         case "$MP3ENCODERSYNTAX" in
989                         lame|toolame)
990                                 (
991                                 cd "$ABCDETEMPDIR"
992                                 TRACKFILES=
993                                 for UTRACKNUM in $TRACKQUEUE
994                                 do
995                                         TRACKFILES="$TRACKFILES track$UTRACKNUM.wav"
996                                 done
997                                 nice $ENCNICE $MP3ENCODER $MP3ENCODEROPTS --nogap $TRACKFILES
998                                 RETURN=$?
999                                 if [ "$RETURN" != "0" ]; then
1000                                         echo "nogap-encode: $ENCODER returned code $RETURN" >> errors
1001                                 else
1002                                         for UTRACKNUM in $TRACKQUEUE
1003                                         do
1004                                                 run_command encodetrack-$OUTPUT-$UTRACKNUM true
1005                                                 #run_command encodetrack-$UTRACKNUM true
1006                                         done
1007                                 fi
1008                                 )
1009                                 ;;
1010                         esac
1011                         ;;
1012                 esac
1013         done
1014         if checkerrors "nogap-encode"; then :; else
1015                 if [ ! "$KEEPWAVS" = "y" ] ; then
1016                         if [ ! "$KEEPWAVS" = "move" ] ; then
1017                                 rm -f "$IN"
1018                         fi
1019                 fi
1020         fi
1021         # Other encoders fall through to normal encoding as the tracks have not
1022         # been entered in the status file.
1023 }
1024
1025 # do_encode [tracknumber] [hostname]
1026 # If no hostname is specified, encode locally
1027 # variables used:
1028 # TRACKS, TRACKNAME, TRACKARTIST, DISTMP3, DISTMP3OPTS, {FOO}ENCODERSYNTAX, OUTPUTTYPE, ENCODEROPTS, DALBUM, DARTIST, ENCNICE, CDYEAR, CDGENRE, COMMENT
1029 do_encode ()
1030 {
1031         if [ "$USEPIPES" = "y" ]; then
1032                 case "$OUTPUT" in
1033                         mp3)
1034                                 TEMPARG="PIPE_$MP3ENCODERSYNTAX"
1035                                 ;;
1036                         vorbis|ogg)
1037                                 TEMPARG="PIPE_$OGGENCODERSYNTAX"
1038                                 ;;
1039                         opus)
1040                                 TEMPARG="PIPE_$OPUSENCODERSYNTAX"
1041                                 ;;
1042                         flac)
1043                                 TEMPARG="PIPE_$FLACENCODERSYNTAX"
1044                                 ;;
1045                         spx)
1046                                 TEMPARG="PIPE_$SPEEXENCODER"
1047                                 ;;
1048                         mpc)
1049                                 TEMPARG="PIPE_$MPCENCODER"
1050                                 ;;
1051                         wv)
1052                                 TEMPARG="PIPE_$WVCENCODERSYNTAX"
1053                                 ;;
1054                         aac)
1055                                 TEMPARG="PIPE_$AACENCODERSYNTAX"
1056                                 ;;
1057                         m4a)
1058                                 TEMPARG="PIPE_$AACENCODERSYNTAX"
1059                                 ;;
1060                 esac
1061                 IN="$( eval echo "\$$TEMPARG" )"
1062         else
1063                 IN="$ABCDETEMPDIR/track$1.wav"
1064                 case "$OUTPUT" in
1065                         mp3)
1066                                 case "$MP3ENCODERSYNTAX" in
1067                                         # FIXME # check if mp3enc needs -if for pipes
1068                                         # FIXME # I have not been able to find a working mp3enc binary
1069                                         mp3enc)
1070                                                 FILEARG="-if $IN"
1071                                                 ;;
1072                                         *)
1073                                                 FILEARG="$IN"
1074                                                 ;;
1075                                 esac
1076                                 ;;
1077                         *)
1078                                 FILEARG="$IN"
1079                                 ;;
1080                 esac
1081         fi
1082         # We need IN to proceed, if we are not using pipes.
1083         if [ -s "$IN" -o X"$USEPIPES" = "Xy" ] ; then
1084                 for TMPOUTPUT in $(echo $OUTPUTTYPE | tr , \ )
1085                 do
1086                         case "$TMPOUTPUT" in
1087                                 vorbis|ogg)
1088                                         OUTPUT=$OGGOUTPUTCONTAINER
1089                                         ;;
1090                                 opus)
1091                                         OUTPUT=$OPUSOUTPUTCONTAINER
1092                                         ;;
1093                                 flac)
1094                                         OUTPUT=$FLACOUTPUTCONTAINER
1095                                         ;;
1096                                 *)
1097                                         OUTPUT=$TMPOUTPUT
1098                                         ;;
1099                         esac
1100                         OUT="$ABCDETEMPDIR/track$1.$OUTPUT"
1101                         if [ "$NOGAP" = "y" ] && checkstatus encodetrack-$OUTPUT-$1 ; then
1102                                 continue
1103                         fi
1104                         if [ X"$USEPIPES" = "Xy" ]; then
1105                                 RUN_COMMAND=""
1106                                 # We need a way to store the creation of the files when using PIPES
1107                                 RUN_COMMAND_PIPES="run_command encodetrack-$OUTPUT-$1 true"
1108                                 # When pipping it does not make sense to have a higher nice for
1109                                 # reading than for encoding, since it will be hold by the
1110                                 # encoding process. Setting an effective nice, to calm down a
1111                                 # bit the reading process.
1112                                 EFFECTIVE_NICE=$READNICE
1113                         else
1114                                 run_command '' echo "Encoding track $1 of $TRACKS: $TRACKNAME..."
1115                                 RUN_COMMAND="run_command encodetrack-$OUTPUT-$1"
1116                                 EFFECTIVE_NICE=$ENCNICE
1117                         fi
1118                         case "$OUTPUT" in
1119                         mp3)
1120                                 case "$2" in
1121                                 %local*%)
1122                                         case "$MP3ENCODERSYNTAX" in
1123                                         lame|toolame|gogo) $RUN_COMMAND nice $EFFECTIVE_NICE $MP3ENCODER $MP3ENCODEROPTS "$IN" "$OUT" ;;
1124                                         bladeenc) $RUN_COMMAND nice $EFFECTIVE_NICE $MP3ENCODER $MP3ENCODEROPTS -quit "$IN" ;;
1125                                         l3enc|xingmp3enc) $RUN_COMMAND nice $EFFECTIVE_NICE $MP3ENCODER "$IN" "$OUT" $MP3ENCODEROPTS ;;
1126                                         # FIXME # Relates to the previous FIXME since it might need the "-if" removed.
1127                                         mp3enc) $RUN_COMMAND nice $EFFECTIVE_NICE $MP3ENCODER -if "$IN" -of "$OUT" $MP3ENCODEROPTS ;;
1128                                         esac
1129                                         ;;
1130                                 *)
1131                                         $RUN_COMMAND nice $DISTMP3NICE $DISTMP3 $DISTMP3OPTS "$2" "$IN" "$OUT" >/dev/null 2>&1
1132                                         ;;
1133                                 esac
1134                                 ;;
1135                         vorbis|ogg)
1136                                 case "$2" in
1137                                 %local*%)
1138                                         case "$OGGENCODERSYNTAX" in
1139                                         vorbize) $RUN_COMMAND nice $EFFECTIVE_NICE $OGGENCODER $OGGENCODEROPTS -w "$OUT" "$IN" ;;
1140                                         oggenc) $RUN_COMMAND nice $EFFECTIVE_NICE $OGGENCODER $OGGENCODEROPTS -o "$OUT" "$IN" ;;
1141                                         esac
1142                                         ;;
1143                                 *)
1144                                         $RUN_COMMAND nice $DISTMP3NICE $DISTMP3 $DISTMP3OPTS "$2" "$IN" "$OUT" >/dev/null 2>&1
1145                                         ;;
1146                                 esac
1147                                 ;;
1148                         opus)
1149                                 case "$2" in
1150                                 %local*%)
1151                                         case "$OPUSENCODERSYNTAX" in
1152                                         opusenc)
1153
1154                                             if [ "$(eval echo ${COMMENT})" != "" ]; then
1155                                                 case "$COMMENT" in
1156                                                     *=*) ;;
1157                                                      *)   COMMENT="COMMENT=$COMMENT" ;;
1158                                                 esac
1159                                             fi
1160                                             # Tag the file at encode time, as it can't be done after encoding.
1161                                             if [ "$DOTAG" = "y" ]; then
1162                                                $RUN_COMMAND nice $EFFECTIVE_NICE $OPUSENCODER $OPUSENCODEROPTS --artist "$TRACKARTIST" --album "$DALBUM" --title "$TRACKNAME" --genre "$CDGENRE" --date "$CDYEAR" --comment TRACKNUMBER="$1" ${COMMENT:+--comment "$COMMENT"} "$IN" "$OUT"
1163                                             else
1164                                               $RUN_COMMAND nice $EFFECTIVE_NICE $OPUSENCODER $OPUSENCODEROPTS "$IN" "$OUT"
1165                                             fi
1166                                               ;;
1167                                         esac
1168                                         ;;
1169                                 *)
1170                                         $RUN_COMMAND nice $DISTMP3NICE $DISTMP3 $DISTMP3OPTS "$2" "$IN" "$OUT" >/dev/null 2>&1
1171                                         ;;
1172                                 esac
1173                                 ;;
1174                         flac)
1175                                 case "$2" in
1176                                 %local*%)
1177                                         case "$FLACENCODERSYNTAX" in
1178                                         flac) $RUN_COMMAND nice $EFFECTIVE_NICE $FLACENCODER -f $FLACENCODEROPTS -o "$OUT" "$IN" ;;
1179                                                 esac
1180                                                 ;;
1181                                         *)
1182                                                 vecho -n "DISTMP3:"
1183                                                 vecho "$DISTMP3 $DISTMP3OPTS $2 $IN $OUT >/dev/null 2>&1"
1184                                                 $RUN_COMMAND nice $DISTMP3NICE $DISTMP3 $DISTMP3OPTS "$2" "$IN" "$OUT" > /dev/null 2>&1
1185                                         ;;
1186                                 esac
1187                                 ;;
1188                         spx)
1189                                 if [ "$(eval echo ${COMMENT})" != "" ]; then
1190                                         case "$COMMENT" in
1191                                                 *=*) ;;
1192                                                 *)   COMMENT="COMMENT=$COMMENT" ;;
1193                                         esac
1194                                 fi
1195                                 # Tag the file at encode time, as it can't be done after encoding.
1196                                 if [ "$DOTAG" = "y" ]; then
1197                                         $RUN_COMMAND nice $EFFECTIVE_NICE $SPEEXENCODER $SPEEXENCODEROPTS --author "$TRACKARTIST" --title "$TRACKNAME" ${COMMENT:+--comment "$COMMENT"} "$IN" "$OUT"
1198                                 else
1199                                         $RUN_COMMAND nice $EFFECTIVE_NICE $SPEEXENCODER $SPEEXENCODEROPTS "$IN" "$OUT"
1200                                 fi
1201                                 ;;
1202                         mpc)
1203                                 # MPP/MP+(Musepack) format (.mpc) is done locally, with inline
1204                                 # tagging. Uses mpcenc for Musepack SV8 encoding, changed from
1205                                 # Musepack SV7 which used mppenc....
1206                                 $RUN_COMMAND nice $EFFECTIVE_NICE $MPCENCODER $MPCENCODEROPTS --artist "$TRACKARTIST" --album "$DALBUM" --title "$TRACKNAME" --track "$1" --genre "$CDGENRE" --year "$CDYEAR" --comment "$COMMENT" "$IN" "$OUT"
1207                                 ;;
1208                         wv)
1209                          if [ "$DOTAG" = "y" ]; then
1210              # wavpack tagging is done inline using Apev2 tags:
1211                                 $RUN_COMMAND nice $EFFECTIVE_NICE $WVENCODER $WVENCODEROPTS -w Artist="$TRACKARTIST" -w Album="$DALBUM" -w Title="$TRACKNAME" \
1212                                 -w Track="$1" -w Genre="$CDGENRE" -w Year="$CDYEAR" -w Comment="$COMMENT" "$IN" -o "$OUT"
1213                         else
1214                            $RUN_COMMAND nice $EFFECTIVE_NICE $WVENCODER $WVENCODEROPTS "$IN" -o "$OUT"
1215                          fi
1216                                 ;;
1217                         aac)
1218                         # aac container is only used to catch faac encoded files where faac 
1219                         # is compiled without mp4 support (with libmp4v2).           Andrew.
1220                           $RUN_COMMAND nice $EFFECTIVE_NICE $AACENCODER $AACENCODEROPTS -o "$OUT" "$IN"
1221                          ;;
1222                         m4a)
1223                          case "$AACENCODERSYNTAX" in
1224                            faac)
1225                              if [ "$DOTAG" = "y" ]; then
1226                    $RUN_COMMAND nice $EFFECTIVE_NICE $AACENCODER $AACENCODEROPTS  --artist "$TRACKARTIST" \
1227                    --album "$DALBUM" --title "$TRACKNAME" --track ${TRACKNUM:-$1} --year "$CDYEAR" \
1228                    --genre "$CDGENRE" --comment "$COMMENT" -o "$OUT" "$IN"                                
1229                  else                    
1230                    $RUN_COMMAND nice $EFFECTIVE_NICE $AACENCODER $AACENCODEROPTS -o "$OUT" "$IN"        
1231                  fi
1232                            ;;
1233                            neroAacEnc)
1234                     $RUN_COMMAND nice $EFFECTIVE_NICE $AACENCODER $AACENCODEROPTS -if "$IN" -of "$OUT"
1235                            ;;
1236                          fdkaac)                     
1237                         if [ "$DOTAG" = "y" ]; then
1238                           $RUN_COMMAND nice $EFFECTIVE_NICE $AACENCODER $AACENCODEROPTS --artist "$TRACKARTIST" --album "$DALBUM" \
1239                           --title "$TRACKNAME" --track "$1" --genre "$CDGENRE" --long-tag Year:"$CDYEAR" --comment "$COMMENT" "$IN" -o "$OUT"
1240                             else
1241                      $RUN_COMMAND nice $EFFECTIVE_NICE $AACENCODER $AACENCODEROPTS "$IN" -o "$OUT"      
1242                             fi
1243                  ;;
1244                           esac  
1245                                 ;;
1246                         wav)
1247                                 # In case of wav output we need nothing. Just keep the wavs.
1248                                 ;;
1249                         esac
1250                         $RUN_COMMAND_PIPES
1251                 done
1252                 # Only remove .wav if the encoding succeeded
1253                 if checkerrors "encodetrack-(.{3,6})-$1"; then :; else
1254                         run_command encodetrack-$1 true
1255                         if [ ! "$KEEPWAVS" = "y" ] ; then
1256                                 if [ ! "$KEEPWAVS" = "move" ] ; then
1257                                         rm -f "$IN"
1258                                 fi
1259                         fi
1260                 fi
1261         else
1262                 run_command "" echo "HEH! The file we were about to encode disappeared:"
1263                 run_command "" echo ">> $IN"
1264                 run_command encodetrack-$1 false
1265         fi
1266 }
1267
1268 # do_preprocess [tracknumber]
1269 # variables used:
1270 # TRACKS, TRACKNAME, TRACKARTIST, DISTMP3, DISTMP3OPTS, {FOO}ENCODERSYNTAX, OUTPUTTYPE, ENCODEROPTS, DALBUM, DARTIST, ENCNICE, CDYEAR, CDGENRE, COMMENT
1271 #do_preprocess ()
1272 #{
1273 #       IN="$ABCDETEMPDIR/track$1.wav"
1274 #       # We need IN to proceed.
1275 #       if [ -s "$IN" ] ; then
1276 #               for OUTPUT in $(echo $OUTPUTTYPE | tr , \ )
1277 #               do
1278 #                       #OUT="$ABCDETEMPDIR/track$1.$OUTPUT"
1279 #                       run_command '' echo "Pre-processing track $1 of $TRACKS..."
1280 #                       case "$POSTPROCESSFORMAT" in
1281 #                       all|wav*)
1282 #                               run_command preprocess-$OUTPUT-$1 nice $PRENICE $WAV_PRE $IF $OF ;;
1283 #                       mp3)
1284 #                               run_command preprocess-$OUTPUT-$1 nice $PRENICE $MP3_PRE $IF $OF ;;
1285 #                       ogg)
1286 #                               run_command preprocess-$OUTPUT-$1 nice $PRENICE $OGG_PRE $IF $OF ;;
1287 #                       flac)
1288 #                               run_command preprocess-$OUTPUT-$1 nice $PRENICE $FLAC_PRE $IF $OF ;;
1289 #                       spx)
1290 #                               run_command preprocess-$OUTPUT-$1 nice $PRENICE $SPX_PRE $IF $OF ;;
1291 #                       esac
1292 #               done
1293 #               # Only remove .wav if the encoding succeeded
1294 #               if checkerrors "preprocess-(.{3,4})-$1"; then
1295 #                       run_command preprocess-$1 false
1296 #               else
1297 #                       run_command preprocess-$1 true
1298 #               fi
1299 #       else
1300 #               if [ "$(checkstatus encode-output)" = "loud" ]; then
1301 #                       echo "HEH! The file we were about to pre-process disappeared:"
1302 #                       echo ">> $IN"
1303 #               fi
1304 #               run_command preprocess-$1 false
1305 #       fi
1306 #}
1307
1308
1309 # do_postprocess [tracknumber]
1310 # variables used:
1311 # TRACKS, TRACKNAME, TRACKARTIST, DISTMP3, DISTMP3OPTS, {FOO}ENCODERSYNTAX, OUTPUTTYPE, ENCODEROPTS, DALBUM, DARTIST, ENCNICE, CDYEAR, CDGENRE, COMMENT
1312 #do_postprocess ()
1313 #{
1314 #       for POSTPROCESSFORMAT in $(echo $POSTPROCESSFORMATS | tr , \ )
1315 #       do
1316 #               IN="$ABCDETEMPDIR/track$1.$POSTPROCESSFORMAT"
1317 #               # We need IN to proceed.
1318 #               if [ -s "$IN" ] ; then
1319 #                       #OUT="$ABCDETEMPDIR/track$1.$OUTPUT"
1320 #                       run_command '' echo "Post-processing track $1 of $TRACKS..."
1321 #                       case "$POSTPROCESSFORMAT" in
1322 #                               mp3)
1323 #                                       run_command postprocess-$OUTPUT-$1 nice $POSTNICE $MP3_POST $IF $OF ;;
1324 #                               ogg)
1325 #                                       run_command postprocess-$OUTPUT-$1 nice $POSTNICE $OGG_POST $IF $OF ;;
1326 #                               flac)
1327 #                                       run_command postprocess-$OUTPUT-$1 nice $POSTNICE $FLAC_POST $IF $OF ;;
1328 #                               spx)
1329 #                                       run_command postprocess-$OUTPUT-$1 nice $POSTNICE $SPX_POST $IF $OF ;;
1330 #                       esac
1331 #                       # Only remove .wav if the encoding succeeded
1332 #                       if checkerrors "postprocess-(.{3,4})-$1"; then
1333 #                               run_command postprocess-$1 false
1334 #                       else
1335 #                               run_command postprocess-$1 true
1336 #                       fi
1337 #               else
1338 #                       if [ "$(checkstatus encode-output)" = "loud" ]; then
1339 #                               echo "HEH! The file we were about to post-process disappeared:"
1340 #                               echo ">> $IN"
1341 #                       fi
1342 #                       run_command postprocess-$1 false
1343 #               fi
1344 #       done
1345 #}
1346
1347 # do_single_gain
1348 # variables used:
1349 # FIXME #
1350 do_single_gain ()
1351 {
1352 :
1353 }
1354
1355 # do_batch_gain
1356 # variables used:
1357 # MP3GAIN, MP3GAINOPTS, VORBISGAIN, VORBISGAINOPTS, MPPGAIN, MPPGAINOPTS
1358 # FIXME #
1359 do_batch_gain ()
1360 {
1361         # The commands here don't go through run_command because they're never supposed to be silenced
1362         echo "Batch analizing gain in tracks: $TRACKQUEUE"
1363         (
1364         cd "$ABCDETEMPDIR"
1365         BLURB=
1366         TRACKFILES=
1367         for UTRACKNUM in $TRACKQUEUE
1368         do
1369                 MP3FILES="$TRACKFILES track$UTRACKNUM.mp3"
1370         done
1371         # FIXME # Hard-coded batch option!
1372         $NORMALIZER -b $NORMALIZEROPTS $TRACKFILES
1373         RETURN=$?
1374         if [ "$RETURN" != "0" ]; then
1375                 echo "batch-normalize: $NORMALIZER returned code $RETURN" >> errors
1376         else
1377                 for UTRACKNUM in $TRACKQUEUE
1378                 do
1379                         echo normalizetrack-$UTRACKNUM >> status
1380                 done
1381         fi
1382         )
1383 }
1384
1385 # do_batch_normalize
1386 # variables used:
1387 # NORMALIZER, NORMALIZEROPTS
1388 do_batch_normalize ()
1389 {
1390         # The commands here don't go through run_command because they're never supposed to be silenced
1391         echo "Batch normalizing tracks: $TRACKQUEUE"
1392         (
1393         cd "$ABCDETEMPDIR"
1394         BLURB=
1395         TRACKFILES=
1396         for UTRACKNUM in $TRACKQUEUE
1397         do
1398                 TRACKFILES="$TRACKFILES track$UTRACKNUM.wav"
1399         done
1400         # XXX: Hard-coded batch option!
1401         $NORMALIZER -b $NORMALIZEROPTS $TRACKFILES
1402         RETURN=$?
1403         if [ "$RETURN" != "0" ]; then
1404                 echo "batch-normalize: $NORMALIZER returned code $RETURN" >> errors
1405         else
1406                 for UTRACKNUM in $TRACKQUEUE
1407                 do
1408                         echo normalizetrack-$UTRACKNUM >> status
1409                 done
1410         fi
1411         )
1412 }
1413
1414 # do_normalize [tracknumber]
1415 # variables used:
1416 # TRACKS, TRACKNAME, NORMALIZER, NORMALIZEROPTS
1417 do_normalize ()
1418 {
1419         IN="$ABCDETEMPDIR/track$1.wav"
1420         if [ -e "$IN" ] ; then
1421                 run_command '' echo "Normalizing track $1 of $TRACKS: $TRACKNAME..."
1422                 run_command normalizetrack-$1 $NORMALIZER $NORMALIZEROPTS "$IN"
1423         else
1424                 if [ "$(checkstatus encode-output)" = "loud" ]; then
1425                         echo "HEH! The file we were about to normalize disappeared:"
1426                         echo ">> $IN"
1427                 fi
1428                 run_command normalizetrack-$1 false "File $IN was not found"
1429         fi
1430 }
1431
1432 # do_move [tracknumber]
1433 # Deduces the outfile from environment variables
1434 # Creates directory if necessary
1435 # variables used:
1436 # TRACKNUM, TRACKNAME, TRACKARTIST, DALBUM, OUTPUTFORMAT, CDGENRE, CDYEAR
1437 do_move ()
1438 {
1439         for TMPOUTPUT in $(echo $OUTPUTTYPE | tr , \ )
1440         do
1441                 # For now, set OUTPUT as TMPOUTPUT, and then change it once we have
1442                 # defined the OUTPUTFILE:
1443                 OUTPUT="$TMPOUTPUT"
1444
1445                 # Create ALBUMFILE, ARTISTFILE, TRACKFILE
1446                 # Munge filenames as follows:
1447                 # ' ' -> '_'
1448                 # '/' -> '_'
1449                 # ''' -> ''
1450                 # '?' -> ''
1451                 # Eat control characters
1452                 ALBUMFILE="$(mungefilename "$DALBUM")"
1453                 ARTISTFILE="$(mungefilename "$TRACKARTIST")"
1454                 TRACKFILE="$(mungefilename "$TRACKNAME")"
1455                 GENRE="$(mungegenre "$GENRE")"
1456                 YEAR=${CDYEAR:-$CDYEAR}
1457                 # If we want to start the tracks with a given number, we need to modify
1458                 # the TRACKNUM value before evaluation
1459                 gettracknum
1460                 # Supported variables for OUTPUTFORMAT are GENRE, YEAR, ALBUMFILE,
1461                 # ARTISTFILE, TRACKFILE, and TRACKNUM.
1462                 if [ "$ONETRACK" = "y" ]; then
1463                         if [ "$VARIOUSARTISTS" = "y" ]; then
1464                                 OUTPUTFILE="$(eval echo \""$VAONETRACKOUTPUTFORMAT"\")"
1465                         else
1466                                 OUTPUTFILE="$(eval echo \""$ONETRACKOUTPUTFORMAT"\")"
1467                         fi
1468                 else
1469                         if [ "$VARIOUSARTISTS" = "y" ]; then
1470                                 OUTPUTFILE="$(eval echo \""$VAOUTPUTFORMAT"\")"
1471                         else
1472                                 OUTPUTFILE="$(eval echo \""$OUTPUTFORMAT"\")"
1473                         fi
1474                 fi
1475                 if checkerrors "tagtrack-$OUTPUT-$1"; then :; else
1476                         # Once we know the specific output was successful, we can change
1477                         # the OUTPUT to the value containing the container
1478                         case $TMPOUTPUT in
1479                                 vorbis|ogg)
1480                                         OUTPUT=$OGGOUTPUTCONTAINER
1481                                         ;;
1482                                 opus)
1483                                         OUTPUT=$OPUSOUTPUTCONTAINER
1484                                         ;;
1485                                 flac)
1486                                         OUTPUT=$FLACOUTPUTCONTAINER
1487                                         ;;
1488                                 *)
1489                                         OUTPUT=$TMPOUTPUT
1490                                         ;;
1491                         esac
1492                         # Check that the directory for OUTPUTFILE exists, if it doesn't, create it
1493                         OUTPUTFILEDIR="$(dirname "$OUTPUTDIR/$OUTPUTFILE")"
1494                         case $OUTPUT in
1495                                 wav)
1496                                         if [ "$DOCLEAN" != "y" ] && [ "$FORCE" != "y" ]; then
1497                                                 # FIXME # introduce warnings?
1498                                                 :
1499                                         else
1500                                                 # mkdir -p shouldn't return an error if the directory already exists
1501                                                 mkdir -p "$OUTPUTFILEDIR"
1502                                                 run_command movetrack-$1 mv "$ABCDETEMPDIR/track$1.$OUTPUT" "$OUTPUTDIR/$OUTPUTFILE.$OUTPUT"
1503                                                 if checkstatus movetrack-output-$OUTPUT; then :; else
1504                                                         run_command movetrack-output-$OUTPUT true
1505                                                 fi
1506                                         fi
1507                                         ;;
1508                                 *)
1509                                         # mkdir -p shouldn't return an error if the directory already exists
1510                                         mkdir -p "$OUTPUTFILEDIR"
1511                                         run_command movetrack-$1 mv "$ABCDETEMPDIR/track$1.$OUTPUT" "$OUTPUTDIR/$OUTPUTFILE.$OUTPUT"
1512                                         if checkstatus movetrack-output-$OUTPUT; then :; else
1513                                                 run_command movetrack-output-$OUTPUT true
1514                                         fi
1515                                         ;;
1516                         esac
1517                         # Lets move the cue file
1518                         if CUEFILE=$(checkstatus cuefile) >/dev/null ; then
1519                                 if [ -r "$ABCDETEMPDIR/$CUEFILE" ]; then
1520                                         if checkstatus movecue-$OUTPUT; then :; else
1521                                                 # Silence the Copying output since it overlaps with encoding processes...
1522                                                 #run_command '' vecho "Copying cue file to its destination directory..."
1523                                                 if checkstatus onetrack >/dev/null ; then
1524                                                         case $OUTPUT in
1525                                                                 wav)
1526                                                                         if [ "$DOCLEAN" != "y" ] && [ "$FORCE" != "y" ]; then
1527                                                                                 # We dont have the dir, since it was not created before.
1528                                                                                 :
1529                                                                         else
1530                                                                                 run_command movecue-$OUTPUT cp "$ABCDETEMPDIR/$CUEFILE" "$OUTPUTDIR/$OUTPUTFILE.cue"
1531                                                                         fi
1532                                                                         ;;
1533                                                                 # NOTE: Creating a cue file with the 3-char-extension files is to comply with
1534                                                                 # http://brianvictor.tripod.com/mp3cue.htm#details
1535                                                                 [a-z0-9][a-z0-9][a-z0-9])
1536                                                                         run_command movecue-$OUTPUT cp "$ABCDETEMPDIR/$CUEFILE" "$OUTPUTDIR/$OUTPUTFILE.cue"
1537                                                                         ;;
1538                                                                 *)
1539                                                                         run_command movecue-$OUTPUT cp "$ABCDETEMPDIR/$CUEFILE" "$OUTPUTDIR/$OUTPUTFILE.$OUTPUT.cue"
1540                                                                         ;;
1541                                                         esac
1542                                                 else
1543                                                         run_command movecue-$OUTPUT cp "$ABCDETEMPDIR/$CUEFILE" "$OUTPUTFILEDIR/$CUEFILE"
1544                                                 fi
1545                                                 echo movecue-$OUTPUT >> "$ABCDETEMPDIR/status"
1546                                         fi
1547                                 fi
1548                         fi
1549                 fi
1550         done
1551 }
1552
1553 # do_playlist
1554 # Create the playlist if wanted
1555 # Variables used:
1556 # PLAYLISTFORMAT, PLAYLISTDATAPREFIX, VAPLAYLISTFORMAT, VAPLAYLISTDATAPREFIX,
1557 # VARIOUSARTISTS, OUTPUTDIR
1558 do_playlist ()
1559 {
1560         for TMPOUTPUT in $(echo $OUTPUTTYPE | tr , \ )
1561         do
1562                 case $TMPOUTPUT in
1563                         vorbis|ogg)
1564                                 OUTPUT=$OGGOUTPUTCONTAINER
1565                                 ;;
1566                         opus)
1567                                 OUTPUT=$OPUSOUTPUTCONTAINER
1568                                 ;;
1569                         flac)
1570                                 OUTPUT=$FLACOUTPUTCONTAINER
1571                                 ;;
1572                         *)
1573                                 OUTPUT=$TMPOUTPUT
1574                                 ;;
1575                 esac
1576                 # Create a playlist file for the playlist data to go into.
1577                 # We used to wipe it out if it existed. Now we request permission if interactive.
1578                 for LASTTRACK in $TRACKQUEUE; do :; done
1579                 ALBUMFILE="$(mungefilename "$DALBUM")"
1580                 ARTISTFILE="$(mungefilename "$DARTIST")"
1581                 GENRE="$(mungegenre "$GENRE")"
1582                 YEAR=${CDYEAR:-$CDYEAR}
1583                 if [ "$VARIOUSARTISTS" = "y" ] ; then
1584                         PLAYLISTFILE="$(eval echo "$VAPLAYLISTFORMAT")"
1585                 else
1586                         PLAYLISTFILE="$(eval echo "$PLAYLISTFORMAT")"
1587                 fi
1588                 FINALPLAYLISTDIR="$(dirname "$OUTPUTDIR/$PLAYLISTFILE")"
1589                 mkdir -p "$FINALPLAYLISTDIR"
1590                 if [ -s "$OUTPUTDIR/$PLAYLISTFILE" ]; then
1591                         echo -n "Erase, Append to, or Keep the existing playlist file? [e/a/k] (e): " >&2
1592                         if [ "$INTERACTIVE" = "y" ]; then
1593                                 while [ "$DONE" != "y" ]; do
1594                                         read ERASEPLAYLIST
1595                                         case $ERASEPLAYLIST in
1596                                                 e|E|a|A|k|K) DONE=y ;;
1597                                                 "") ERASEPLAYLIST=e ; DONE=y ;;
1598                                                 *) ;;
1599                                         esac
1600                                 done
1601                         else
1602                                 echo e >&2
1603                                 ERASEPLAYLIST=e
1604                         fi
1605                         # Once we erase the playlist, we use append to create the new one.
1606                         [ "$ERASEPLAYLIST" = "e" -o "$ERASEPLAYLIST" = "E" ] && rm -f "$OUTPUTDIR/$PLAYLISTFILE" && ERASEPLAYLIST=a
1607                 else
1608                         # The playlist does not exist, so we can safelly use append to create the new list
1609                         ERASEPLAYLIST=a
1610                 fi
1611                 if [ "$ERASEPLAYLIST" = "a" -o "$ERASEPLAYLIST" = "A" ]; then
1612                         touch "$OUTPUTDIR/$PLAYLISTFILE"
1613                         for UTRACKNUM in $TRACKQUEUE
1614                         do
1615                                 # Shares some code with do_move since the filenames have to match
1616                                 CDDBTRACKNUM=$(expr $UTRACKNUM - 1)
1617                                 getcddbinfo TRACKNAME
1618                                 splitvarious
1619                                 TRACKFILE="$(mungefilename "$TRACKNAME")"
1620                                 ARTISTFILE="$(mungefilename "$TRACKARTIST")"
1621                                 ALBUMFILE="$(mungefilename "$DALBUM")"
1622                                 # If we want to start the tracks with a given number, we need to modify the
1623                                 # TRACKNUM value before evaluation
1624                                 gettracknum
1625                                 if [ "$VARIOUSARTISTS" = "y" ]; then
1626                                         OUTPUTFILE="$(eval echo \""$VAOUTPUTFORMAT\"")"
1627                                 else
1628                                         OUTPUTFILE="$(eval echo \""$OUTPUTFORMAT\"")"
1629                                 fi
1630                                 if [ "$VARIOUSARTISTS" = "y" ]; then
1631                                         if [ "$VAPLAYLISTDATAPREFIX" ] ; then
1632                                                 echo ${VAPLAYLISTDATAPREFIX}$OUTPUTFILE.$OUTPUT >> "$OUTPUTDIR/$PLAYLISTFILE"
1633                                         else
1634                                                 relpath "$PLAYLISTFILE", "$OUTPUTFILE.$OUTPUT" >> "$OUTPUTDIR/$PLAYLISTFILE"
1635                                         fi
1636                                 else
1637                                         if [ "$PLAYLISTDATAPREFIX" ]; then
1638                                                 echo ${PLAYLISTDATAPREFIX}$OUTPUTFILE.$OUTPUT >> "$OUTPUTDIR/$PLAYLISTFILE"
1639                                         else
1640                                                 relpath "$PLAYLISTFILE", "$OUTPUTFILE.$OUTPUT" >> "$OUTPUTDIR/$PLAYLISTFILE"
1641                                         fi
1642                                 fi
1643                         done
1644                 fi
1645                 ## this will convert the playlist to have CRLF line-endings, if specified
1646                 ## (some hardware players insist on CRLF endings)
1647                 if [ "$DOSPLAYLIST" = "y" ]; then
1648                         awk '{sub("\r$",""); printf "%s\r\n", $0}' "$OUTPUTDIR/$PLAYLISTFILE" > "$ABCDETEMPDIR/PLAYLISTFILE.tmp"
1649 #                       mv -f "$ABCDETEMPDIR/PLAYLISTFILE.tmp" "$OUTPUTDIR/$PLAYLISTFILE"
1650                         cat "$ABCDETEMPDIR/PLAYLISTFILE.tmp" | sed 's/\//\\/' > "$OUTPUTDIR/$PLAYLISTFILE"
1651                 fi
1652                 echo "playlistcomplete" >> "$ABCDETEMPDIR/status"
1653         done
1654 }
1655
1656 # abcde.cue2discid
1657 # This function reads a cuefile on stdin and writes an extended
1658 # cddb query on stdout.  Any PREGAP for track 1 is properly
1659 # handled, although cue files embedded in FLAC files do not
1660 # appear to properly store the PREGAP setting. :(
1661 abcde.cue2discid () {
1662
1663         cddb_sum () {
1664                 val=$1
1665                 ret=0
1666                 while [ $val -gt 0 ] ; do
1667                         ret=$(( $ret + ( $val % 10) ))
1668                         val=$(( $val / 10 ))
1669                 done
1670                 echo $ret
1671         }
1672
1673         msf2lba () {
1674                 OIFS="$IFS"
1675                 IFS=":"
1676                 set -- $1
1677                 IFS="$OIFS"
1678                 local first second third
1679                 first=$(expr ${1} + 0 )
1680                 second=$(expr ${2} + 0 )
1681                 third=$(expr ${3} + 0 )
1682
1683                 echo $(( ((($first * 60) + $second) * 75) + $third ))
1684         }
1685
1686         OFFSET=150
1687         PREGAP=0
1688         LEADOUT=0
1689         LEADIN=88200
1690         i=0
1691         N=0
1692
1693         while read line ; do
1694                 set -- $line
1695                 case "$1" in
1696                 TRACK)  i=$(( i + 1 ))
1697                         ;;
1698                 INDEX)  if [ "$2" -eq 1 ] ; then
1699                                 LBA=$(msf2lba $3)
1700                                 START=$(( $LBA + $PREGAP + $OFFSET ))
1701                                 eval TRACK$i=$START
1702                                 X=$(cddb_sum $(( $START / 75 )) )
1703                                 N=$(( $N + $X ))
1704                         fi
1705                         ;;
1706                 PREGAP) PREGAP=$(msf2lba $2)
1707                         ;;
1708                 REM)    case "$2" in
1709                         FLAC__lead-out)
1710                                 LEADOUT=$(( $4 / 588 ))
1711                                 ;;
1712                         FLAC__lead-in)
1713                                 LEADIN=$(( $3 / 588 ))
1714                                 ;;
1715                         esac
1716                         ;;
1717                 esac
1718
1719         done
1720
1721         TRACKS=$i
1722         LEADOUT=$(( $LEADOUT + $LEADIN ))
1723
1724         LENGTH=$(( $LEADOUT/75 - $TRACK1/75 ))
1725         DISCID=$(( ( $N % 255 ) * 2**24 | $LENGTH * 2**8 | $TRACKS ))
1726         printf "%08x %i" $DISCID $TRACKS
1727
1728         j=1
1729         while [ $j -le $TRACKS ] ; do
1730                 eval echo -n "\" \$TRACK$j\""
1731                 j=$((j+1))
1732         done
1733         echo " $(( $LEADOUT / 75 ))"
1734 }
1735
1736 # abcde.mkcue
1737 # abcde.mkcue [--wholedisk]
1738 # This creates a cuefile directly from the extended discid information
1739 # The --wholedisk option controls whether we're ripping data from the
1740 # start of track one or from the start of the disk (usually, but not
1741 # always the same thing!)
1742 #
1743 # Track one leadin/pregap (if any) handeling:
1744 # --wholedisk specified:
1745 #   TRACK 01 AUDIO
1746 #     INDEX 00 00:00:00
1747 #     INDEX 01 <pregap value>
1748 #   Remaining track index values unchanged from disc TOC
1749 #
1750 # --wholedisk not specified
1751 #   TRACK 01 AUDIO
1752 #     PREGAP <pregap value>
1753 #     INDEX 01 00:00:00
1754 #   Remaining track index values offset by <pregap value>
1755 #
1756 # Variables used:
1757 # TRACKINFO
1758 abcde.mkcue () {
1759
1760         echomsf () {
1761                 printf "$1%02i:%02i:%02i\n" $(($2/4500)) $((($2/75)%60)) $(($2%75))
1762         }
1763
1764         local MODE DISCID TRACKS
1765         local i OFFSET LBA
1766         local CUEWAVFILE
1767
1768         if [ "$1" = --wholedisc ] ; then
1769                 MODE=INDEX
1770         else
1771                 MODE=PREGAP
1772         fi
1773
1774         vecho "One track is $ONETRACK"
1775         TRACKFILE="$(mungefilename "$TRACKNAME")"
1776         ARTISTFILE="$(mungefilename "$TRACKARTIST")"
1777         ALBUMFILE="$(mungefilename "$DALBUM")"
1778         if [ "$ONETRACK" = "y" ]; then
1779                 if [ "$VARIOUSARTISTS" = "y" ]; then
1780                         CUEWAVFILE="$(eval echo \""$VAONETRACKOUTPUTFORMAT"\" | sed -e 's@^.*/@@').$OUTPUT"
1781                 else
1782                         CUEWAVFILE="$(eval echo \""$ONETRACKOUTPUTFORMAT"\" | sed -e 's@^.*/@@').$OUTPUT"
1783                 fi
1784                 vecho "Cue wav file is $CUEWAVFILE"
1785         else
1786                 CUEWAVFILE="dummy.wav"
1787         fi
1788
1789         set -- $TRACKINFO
1790
1791         DISCID=$1
1792         TRACKS=$2
1793         shift 2
1794
1795         echo REM DISCID $DISCID
1796         echo FILE \""$CUEWAVFILE"\" WAVE
1797
1798         if [ $1 -ne 150 ] && [ $MODE = "PREGAP" ] ; then
1799                 OFFSET=$1
1800         else
1801                 OFFSET=150
1802         fi
1803
1804         i=1
1805         while [ $i -le "$TRACKS" ] ; do
1806                 LBA=$(( $1 - $OFFSET ))
1807                 printf "  TRACK %02i AUDIO\n" $i
1808                 if [ $i -eq 1 -a $1 -ne 150 ] ; then
1809                         if [ $MODE = PREGAP ] ; then
1810                                 echomsf "    PREGAP " $(($OFFSET-150))
1811                         else
1812                                 echo    "    INDEX 00 00:00:00"
1813                         fi
1814                 fi
1815                 echomsf "    INDEX 01 " $LBA
1816                 i=$(($i+1))
1817                 shift
1818         done
1819 }
1820
1821 # do_discid
1822 # This essentially the start of things
1823 do_discid ()
1824 {
1825         # Query the CD to get the track info, unless the user specified -C
1826         # or we are using some actions which do not need the CDDB data at all
1827         #if [ ! X"$EXPACTIONS" = "X" ]; then
1828         #       :
1829         #elif [ -z "$DISCID" ]; then
1830         if [ -z "$DISCID" ]; then
1831                 vecho -n "Getting CD track info... "
1832                 # In OSX, unmount the disc before a query
1833                 if [ "$OSFLAVOUR" = "OSX" ]; then
1834                         diskutil unmount ${CDROM#/dev/}
1835                 fi
1836                 case "$CDROMREADERSYNTAX" in
1837                         flac)
1838                                 if $METAFLAC $METAFLACOPTS --export-cuesheet-to=- "$CDROM" > /dev/null 2>&1 ; then
1839                                         case "$CUE2DISCID" in
1840                                                 # FIXME # right now we have 2 cue2discid internal
1841                                                 # implementations: builtin and abcde.cue2discid. Test
1842                                                 # both of them and decide which one we want to use.
1843                                                 builtin)
1844                                                         #vecho "Using builtin cue2discid implementation..."
1845                                                         CUESHEET="$(metaflac $METAFLACOPTS --export-cuesheet-to=- "$CDROM")"
1846
1847                                                         #TRACKS=$(echo $CUESHEET | grep -E "TRACK \+[[:digit:]]\+ \+AUDIO" |wc -l)
1848                                                         #TRACKS=0
1849                                                         OFFSETTIMES=( $(echo "$CUESHEET" | sed -n -e's/\ *INDEX 01\ \+//p' ) )
1850                                                         TRACKS=${#OFFSETTIMES[@]}
1851                                                         unset OFFSETS
1852                                                         #echo "processing offsetimes ${OFFSETTIMES[@]}"
1853                                                         for OFFSETTIME in ${OFFSETTIMES[@]}; do
1854                                                                 OFFSETS="$OFFSETS $(( 10#${OFFSETTIME:0:2} * 4500 + 10#${OFFSETTIME:3:2} * 75 + 10#${OFFSETTIME:6:2} ))"
1855                                                                 #OFFSETS[${#OFFSETS[*]}]=$(( 10#${OFFSETTIME:0:2} * 4500 + 10#${OFFSETTIME:3:2} * 75 + 10#${OFFSETTIME:6:2} ))
1856                                                         done
1857
1858                                                         LEADOUT=$(( $(echo "$CUESHEET" | grep lead-out | get_last) * 75 / 44100 ))
1859                                                         LEADIN=$(( $(echo "$CUESHEET" | grep lead-in | get_last) * 75 / 44100 ))
1860                                                         makeids
1861                                                 ;;
1862                                                 *)
1863                                                         #vecho "Using external python cue2discid implementation..."
1864                                                         TRACKINFO=$($METAFLAC $METAFLACOPTS --export-cuesheet-to=- "$CDROM" | $CUE2DISCID)
1865                                                 ;;
1866                                         esac
1867                                 else
1868                                         log error "the input flac file does not contain a cuesheet."
1869                                         exit 1
1870                                 fi
1871                                 ;;
1872 #                       cdparanoia|debug)
1873 #                               CDPARANOIAOUTPUT="$( $CDROMREADER -$CDPARANOIACDROMBUS "$CDROM" -Q --verbose 2>&1 )"
1874 #                               RET=$?
1875 #                               if [ ! "$RET" = "0" ];then
1876 #                                       log warning "something went wrong while querying the CD... Maybe a DATA CD?"
1877 #                               fi
1878 #
1879 #                               TRACKS="$(echo "$CDPARANOIAOUTPUT" | grep -E '^[[:space:]]+[[:digit:]]' | tail -n 1 | get_first | tr -d "." | tr '\n' ' ')"
1880 #                               CDPARANOIAAUDIOTRACKS="$TRACKS"
1881 #
1882 #                               LEADOUT="$(echo "$CDPARANOIAOUTPUT" | grep -Eo '^TOTAL[[:space:]]+([[:digit:]]+)' | get_last)"
1883 #                               OFFSETS="$(echo "$CDPARANOIAOUTPUT" | sed -n -e's/^ .* \([0-9]\+\) \[.*/\1/p')"
1884 #                               makeids
1885 #                               ;;
1886                         *)
1887                                 case "$CDDBMETHOD" in
1888                                         cddb) TRACKINFO=$($CDDISCID "$CDROM") ;;
1889                                         musicbrainz) TRACKINFO=$($MUSICBRAINZ --command id --device "$CDROM") ;;
1890                                 esac
1891                                 ;;
1892                 esac
1893                 # Make sure there's a CD in there by checking cd-discid's return code
1894                 if [ ! "$?" = "0" ]; then
1895                         if [ "$CDROMREADERSYNTAX" = "flac" ] ; then
1896                                 log error "cuesheet information from the flac file could not be read."
1897                                 log error "Perhaps the flac file does not contain a cuesheet?."
1898                                 exit 1
1899                         else
1900                                 log error "CD could not be read. Perhaps there's no CD in the drive?"
1901                                 exit 1
1902                         fi
1903                 fi
1904                 # In OSX, remount the disc again
1905                 if [ "$OSFLAVOUR" = "OSX" ]; then
1906                         diskutil mount ${CDROM#/dev/}
1907                 fi
1908                 WEHAVEACD=y
1909                 DISCID=$(echo $TRACKINFO | cut -f1 -d' ')
1910         else
1911                 TRACKINFO=$(cat "$WAVOUTPUTDIR/abcde.$DISCID/discid")
1912         fi
1913
1914         # Get a full enumeration of tracks, sort it, and put it in the TRACKQUEUE.
1915         # This needs to be done now because a section of the resuming code will need
1916         # it later.
1917
1918         # get the number of digits to pad TRACKNUM with - we'll use this later
1919         # a CD can only hold 99 tracks, but since we support a feature for starting
1920         # numbering the tracks from a given number, we might need to set it as a
1921         # variable for the user to define... or obtain it somehow.
1922         if [ "$PADTRACKS" = "y" ] ; then
1923                 TRACKNUMPADDING=2
1924         fi
1925
1926         ABCDETEMPDIR="$WAVOUTPUTDIR/abcde.$(echo $TRACKINFO | cut -f1 -d' ')"
1927         if [ -z "$TRACKQUEUE" ]; then
1928                 if [ ! "$STRIPDATATRACKS" = "n" ]; then
1929                         case "$CDROMREADERSYNTAX" in
1930                                 cdparanoia|debug)
1931                                         if [ "$WEHAVEACD" = "y" ]; then
1932                                                 vecho "Querying the CD for audio tracks..."
1933                                                 CDPARANOIAOUTPUT="$( $CDROMREADER -$CDPARANOIACDROMBUS "$CDROM" -Q --verbose 2>&1 )"
1934                                                 RET=$?
1935                                                 if [ ! "$RET" = "0" ];then
1936                                                         log warning "something went wrong while querying the CD... Maybe a DATA CD?"
1937                                                 fi
1938                                                 TRACKS="$(echo "$CDPARANOIAOUTPUT" | grep -E '^[[:space:]]+[[:digit:]]' | tail -n 1 | get_first | tr -d "." | tr '\n' ' ')"
1939                                                 CDPARANOIAAUDIOTRACKS="$TRACKS"
1940                                         else
1941                                                 # Previous versions of abcde would store the tracks on a file, instead of the status record.
1942                                                 if [ -f "$ABCDETEMPDIR/cdparanoia-audio-tracks" ]; then
1943                                                         echo cdparanoia-audio-tracks=$( cat "$ABCDETEMPDIR/cdparanoia-audio-tracks" ) >> "$ABCDETEMPDIR/status"
1944                                                         rm -f "$ABCDETEMPDIR/cdparanoia-audio-tracks"
1945                                                 fi
1946                                                 if [ -f "$ABCDETEMPDIR/status" ] && TRACKS=$(checkstatus cdparanoia-audio-tracks); then :; else
1947                                                         TRACKS=$(echo $TRACKINFO | cut -f2 -d' ')
1948                                                 fi
1949                                         fi
1950                                         ;;
1951                                 *)      TRACKS=$(echo $TRACKINFO | cut -f2 -d' ') ;;
1952                         esac
1953                 else
1954                         TRACKS=$(echo $TRACKINFO | cut -f2 -d' ')
1955                 fi
1956                 if echo "$TRACKS" | grep "[[:digit:]]" > /dev/null 2>&1 ;then :;else
1957                         log info "The disc does not contain any tracks. Giving up..."
1958                         exit 0
1959                 fi
1960                 echo -n "Grabbing entire CD - tracks: "
1961                 if [ ! "$PADTRACKS" = "y" ] ; then
1962                         TRACKNUMPADDING=$(echo -n $TRACKS | wc -c | tr -d ' ')
1963                 fi
1964                 TRACKS=$(printf "%0.${TRACKNUMPADDING}d" $TRACKS)
1965                 X=0
1966                 while [ "$X" -ne "$TRACKS" ]
1967                 do
1968                         X=$(printf "%0.${TRACKNUMPADDING}d" $(expr $X + 1))
1969                         TRACKQUEUE=$(echo $TRACKQUEUE $X)
1970                 done
1971                 echo $TRACKQUEUE
1972         else
1973                 TRACKS=$(echo $TRACKINFO | cut -f2 -d' ')
1974                 # User-supplied track queue.
1975                 # Weed out non-numbers, whitespace, then sort and weed out duplicates
1976                 TRACKQUEUE=$(echo $TRACKQUEUE | sed 's-[^0-9 ]--g' | tr ' ' '\n' | grep -v ^$ | sort -n | uniq | tr '\n' ' ' | sed 's- $--g')
1977                 # Once cleaned, obtain the highest value in the trackqueue for number padding
1978                 for LASTTRACK in $TRACKQUEUE; do :; done
1979                 if [ ! "$PADTRACKS" = "y" ] ; then
1980                         TRACKNUMPADDING=$(echo -n $LASTTRACK | wc -c | tr -d ' ')
1981                 fi
1982                 # Now we normalize the trackqueue
1983                 for TRACK in $TRACKQUEUE ; do
1984                         TRACKNUM=$(printf %0.${TRACKNUMPADDING}d $(expr ${TRACK} + 0 ))
1985                         PADTRACKQUEUE=$(echo $PADTRACKQUEUE $TRACKNUM)
1986                 done
1987                 TRACKQUEUE=$PADTRACKQUEUE
1988                 echo Grabbing tracks: "$TRACKQUEUE"
1989         fi
1990
1991         QUEUEDTRACKS=$(echo $TRACKQUEUE | wc -w | tr -d ' ')
1992
1993         # We have the discid, create a temp directory after it to store all the temp
1994         # info
1995
1996         if [ -e "$ABCDETEMPDIR" ]; then
1997                 echo -n "abcde: attempting to resume from $ABCDETEMPDIR"
1998                 # It already exists, see if it's a directory
1999                 if [ ! -d "$ABCDETEMPDIR" ]; then
2000                         # This is a file/socket/fifo/device/etc, not a directory
2001                         # Complain and exit
2002                         echo >&2
2003                         echo "abcde: file $ABCDETEMPDIR already exists and does not belong to abcde." >&2
2004                         echo "Please investigate, remove it, and rerun abcde." >&2
2005                         exit 1
2006                 fi
2007                 echo -n .
2008                 # It's a directory, let's see if it's writable by us
2009                 if [ ! -r "$ABCDETEMPDIR" ] || [ ! -w "$ABCDETEMPDIR" ] || [ ! -x "$ABCDETEMPDIR" ]; then
2010                         # Nope, complain and exit
2011                         echo >&2
2012                         echo "abcde: directory $ABCDETEMPDIR already exists and is not writeable." >&2
2013                         echo "Please investigate, remove it, and rerun abcde." >&2
2014                         exit 1
2015                 fi
2016                 echo .
2017                 # See if it's populated
2018                 if [ ! -f "$ABCDETEMPDIR/discid" ]; then
2019                         # Wipe and start fresh
2020                         echo "abcde: $ABCDETEMPDIR/discid not found. Abcde must remove and recreate" >&2
2021                         echo -n "this directory to continue. Continue [y/N]? " >&2
2022                         if [ "$INTERACTIVE" = "y" ]; then
2023                                 read ANSWER
2024                         else
2025                                 echo y >&2
2026                                 ANSWER=y
2027                         fi
2028                         if [ "$ANSWER" != "y" ]; then
2029                                 exit 1
2030                         fi
2031                         rm -rf "$ABCDETEMPDIR" || exit 1
2032                         mkdir -p "$ABCDETEMPDIR"
2033                         if [ "$?" -gt "0" ]; then
2034                                 # Directory already exists or could not be created
2035                                 echo "abcde: Temp directory $ABCDETEMPDIR could not be created." >&2
2036                                 exit 1
2037                         fi
2038                 else
2039                         # Everything is fine. Check for ^encodetracklocation-
2040                         # and encode-output entries in the status file and
2041                         # remove them. These are not relevant across sessions.
2042                         if [ -f "$ABCDETEMPDIR/status" ]; then
2043                                 mv "$ABCDETEMPDIR/status" "$ABCDETEMPDIR/status.old"
2044                                 grep -v ^encodetracklocation- < "$ABCDETEMPDIR/status.old" \
2045                                         | grep -v ^encode-output > "$ABCDETEMPDIR/status"
2046                         fi
2047                         # Remove old error messages
2048                         if [ -f "$ABCDETEMPDIR/errors" ]; then
2049                                 rm -f "$ABCDETEMPDIR/errors"
2050                         fi
2051                 fi
2052         else
2053                 # We are starting from scratch
2054                 mkdir -p "$ABCDETEMPDIR"
2055                 if [ "$?" -gt "0" ]; then
2056                         # Directory already exists or could not be created
2057                         echo "abcde: Temp directory $ABCDETEMPDIR could not be created." >&2
2058                         exit 1
2059                 fi
2060                 cat /dev/null > "$ABCDETEMPDIR/status"
2061                 # Store the abcde version in the status file.
2062                 echo "abcde-version=$VERSION" >> "$ABCDETEMPDIR/status"
2063         fi
2064         if [ X"$DOCUE" = "Xy" -a X"$WEHAVEACD" = "Xy" ]; then
2065                 if checkstatus cuefile > /dev/null 2>&1 ; then :; else
2066                         CUEFILE=cue-$(echo "$TRACKINFO" | cut -f1 -d' ').txt
2067                         vecho "Creating cue file..."
2068                         case $CDROMREADERSYNTAX in
2069                                 flac)
2070                                         if $METAFLAC --export-cuesheet-to=- "$CDROM" > "$ABCDETEMPDIR/$CUEFILE"; then
2071                                                 echo cuefile=$CUEFILE >> "$ABCDETEMPDIR/status"
2072                                         else
2073                                                 log warning "the input flac file does not contain a cuesheet."
2074                                         fi
2075                                         ;;
2076                                 *)
2077                                         if $CUEREADER $CUEREADEROPTS > "$ABCDETEMPDIR/$CUEFILE"; then
2078                                                 echo cuefile=$CUEFILE >> "$ABCDETEMPDIR/status"
2079                                         else
2080                                                 log warning "reading the CUE sheet is still considered experimental"
2081                                                 log warning "and there was a problem with the CD reading. abcde will continue,"
2082                                                 log warning "but consider reporting the problem to the abcde author"
2083                                         fi
2084                                         ;;
2085                         esac
2086                 fi
2087         fi
2088         # If we got the CDPARANOIA status and it is not recorded, save it now
2089         if [ -n "$CDPARANOIAAUDIOTRACKS" ]; then
2090                 if checkstatus cdparanoia-audio-tracks > /dev/null 2>&1; then :; else
2091                         echo cdparanoia-audio-tracks=$CDPARANOIAAUDIOTRACKS >> "$ABCDETEMPDIR/status"
2092                 fi
2093         fi
2094
2095         # Create the discid file
2096         echo "$TRACKINFO" > "$ABCDETEMPDIR/discid"
2097         if checkstatus cddbmethod > /dev/null 2>&1 ; then :; else
2098                 echo "cddbmethod=$CDDBMETHOD" >> "$ABCDETEMPDIR/status"
2099         fi
2100 }
2101
2102 # do_cleancue
2103 # Create a proper CUE file based on the CUE file we created before.
2104 do_cleancue()
2105 {
2106         if CUEFILE_IN="$ABCDETEMPDIR"/$(checkstatus cuefile); then
2107                 CUEFILE_OUT=$CUEFILE_IN.out
2108                 ### FIXME ### checkstatus cddb
2109                 if [ -e "$CDDBDATA" ]; then
2110                         vecho "Adding metadata to the cue file..."
2111                         # FIXME It doesn't preserve spaces! Why?
2112                         # FIXME parse $track into PERFORMER and TITLE - abcde already has code for this?
2113                         n=1
2114                         echo "PERFORMER \"$DARTIST\"" >> "$CUEFILE_OUT"
2115                         echo "TITLE \"$DALBUM\"" >> "$CUEFILE_OUT"
2116                         # Set IFS to <newline> to prevent read from swallowing spaces and tabs
2117                         OIFS="$IFS"
2118                         IFS='
2119 '
2120                         cat "$CUEFILE_IN" | while read line
2121                         do
2122                                 if echo "$line" | grep "INDEX 01" > /dev/null 2>&1 ; then
2123 # FIXME # Possible patch: remove the line above, uncomment the 2 lines below.
2124 #                               echo "$line" >> "$CUEFILE_OUT"
2125 #                               if echo "$line" | grep "^[[:space:]]*TRACK" > /dev/null 2>&1 ; then
2126                                         eval track="\$TRACK$n"
2127                                         n=$(expr $n + 1)
2128                                         echo "    TITLE \"$track\"" >> "$CUEFILE_OUT"
2129                                 # When making a single-track rip, put the
2130                                 # actual file name into the file declaration
2131                                 # in the cue file so that it is usable by
2132                                 # music players and the like
2133                                 elif [ "$ONETRACK" = "y" ] &&
2134                                                 echo "$line" | grep '^FILE "dummy.wav" WAVE' > /dev/null 2>&1 ; then
2135
2136                                         TRACKFILE="$(mungefilename "$TRACKNAME")"
2137                                         ARTISTFILE="$(mungefilename "$TRACKARTIST")"
2138                                         ALBUMFILE="$(mungefilename "$DALBUM")"
2139
2140                                         if [ "$VARIOUSARTISTS" = "y" ]; then
2141                                                 OUTPUTFILE="$(eval echo \""$VAONETRACKOUTPUTFORMAT"\" | sed -e 's@^.*/@@').$OUTPUT"
2142                                         else
2143                                                 OUTPUTFILE="$(eval echo \""$ONETRACKOUTPUTFORMAT"\" | sed -e 's@^.*/@@').$OUTPUT"
2144                                         fi
2145
2146                                         echo "FILE \"$OUTPUTFILE\" WAVE" >> "$CUEFILE_OUT"
2147                                         continue
2148                                 fi
2149 # FIXME # If the lines above are uncommented, remove the line below.
2150                                 echo "$line" >> "$CUEFILE_OUT"
2151                         done
2152                         IFS="$OIFS"
2153                         mv "$CUEFILE_OUT" "$CUEFILE_IN"
2154                         echo "cleancuefile" >> "$ABCDETEMPDIR/status"
2155                 fi
2156         fi
2157 }
2158
2159 # do_cddbparse
2160 # Parses a CDDB file and outputs the title and the track names.
2161 # Variables: CDDBFILE
2162 do_cddbparse ()
2163 {
2164         CDDBPARSEFILE="$1"
2165         # List out disc title/author and contents
2166         if [ "$ONETRACK" = "y" ]; then
2167                 vecho "ONETRACK mode selected: displaying only the title of the CD..."
2168         fi
2169         echo "---- $(grep DTITLE "${CDDBPARSEFILE}" | cut '-d=' -f2- | tr -d \\r\\n ) ----"
2170         if [ X"$SHOWCDDBYEAR" = "Xy" ]; then
2171                 PARSEDYEAR=$(grep DYEAR "${CDDBPARSEFILE}" | cut '-d=' -f2-)
2172                 if [ ! X"$PARSEDYEAR" = "X" ]; then
2173                         echo "Year: $PARSEDYEAR"
2174                 fi
2175         fi
2176         if [ X"$SHOWCDDBGENRE" = "Xy" ]; then
2177                 PARSEDGENRE=$(grep DGENRE "${CDDBPARSEFILE}" | cut '-d=' -f2-)
2178                 if [ ! X"$PARSEDGENRE" = "X" ]; then
2179                         echo "Genre: $PARSEDGENRE"
2180                 fi
2181         fi
2182         if [ ! "$ONETRACK" = "y" ]; then
2183                 for TRACK in $(f_seq_row 1 $TRACKS)
2184                 do
2185                         echo $TRACK: "$(grep ^TTITLE$(expr $TRACK - 1)= "${CDDBPARSEFILE}" | cut -f2- -d= | tr -d \\r\\n)"
2186                 done
2187         fi
2188 }
2189
2190 # do_localcddb
2191 # Check for a local CDDB file, and report success
2192 do_localcddb ()
2193 {
2194         if checkstatus cddb-readcomplete && checkstatus cddb-choice >/dev/null; then :; else
2195
2196                 CDDBLOCALSTATUS="notfound"
2197                 CDDBDISCID=$(echo $TRACKINFO | cut -d' ' -f1)
2198                 USELOCALRESP="y"
2199
2200                 if [ "$CDDBLOCALRECURSIVE" = "y" ]; then
2201                         CDDBLOCALRESULTS="$(find ${CDDBLOCALDIR} -name "${CDDBDISCID}" -type f 2> /dev/null)"
2202                         if [ ! "${CDDBLOCALRESULTS}" = "" ]; then
2203                                 if   (( $(echo "${CDDBLOCALRESULTS}" | wc -l) == 1 )); then
2204                                         CDDBLOCALFILE="${CDDBLOCALRESULTS}"
2205                                         CDDBLOCALMATCH=single
2206                                 elif (( $(echo "${CDDBLOCALRESULTS}" | wc -l) > 1 )); then
2207                                         CDDBLOCALMATCH=multiple
2208                                 fi
2209                         else
2210                                 CDDBLOCALMATCH=none
2211                         fi
2212                 elif [ "$CDDBLOCALMATCH" = "none" ] && [ -r "${CDDBLOCALDIR}/${CDDBDISCID}" ]; then
2213                         CDDBLOCALFILE="${CDDBLOCALDIR}/${CDDBDISCID}"
2214                         CDDBLOCALMATCH=single
2215                 else
2216                         CDDBLOCALMATCH=none
2217                 fi
2218
2219                 # If the user has selected to check a local CDDB repo, we proceed with it
2220                 case $CDDBLOCALMATCH in
2221                         multiple)
2222                                 echo "Processing multiple matching CDDB entries..." > "$ABCDETEMPDIR/cddblocalchoices"
2223                                 X=0
2224                                 echo "$CDDBLOCALRESULTS" | while read RESULT ; do
2225                                         X=$(expr $X + 1)
2226                                         # List out disc title/author and contents
2227                                         CDDBLOCALREAD="$ABCDETEMPDIR/cddblocalread.$X"
2228                                         cat "$RESULT" > "${CDDBLOCALREAD}"
2229                                         {
2230                                                 echo -n "#$X: "
2231                                                 do_cddbparse "${CDDBLOCALREAD}"
2232                                                 echo ""
2233                                                 ##FIXME## QUICK HACK !!!!
2234                                                 if [ ! "$INTERACTIVE" = "y" ]; then break ; fi
2235                                         } >> "$ABCDETEMPDIR/cddblocalchoices"
2236                                 done
2237                                 if [ $(cat "$ABCDETEMPDIR/cddblocalchoices" | wc -l) -ge 24 ] && [ "$INTERACTIVE" = "y" ]; then
2238                                         page "$ABCDETEMPDIR/cddblocalchoices"
2239                                 else
2240                                         # It's all going to fit in one page, cat it
2241                                         cat "$ABCDETEMPDIR/cddblocalchoices" >&2
2242                                 fi
2243                                 CDDBLOCALCHOICES=$( echo "$CDDBLOCALRESULTS" | wc -l )
2244                                 # Setting the choice to an impossible integer to avoid errors in the numeric comparisons
2245                                 CDDBLOCALCHOICENUM=-1
2246                                 if [ "$INTERACTIVE" = "y" ]; then
2247                                         while [ $CDDBLOCALCHOICENUM -lt 0 ] || [ $CDDBLOCALCHOICENUM -gt $CDDBLOCALCHOICES ]; do
2248                                                 echo -n "Locally cached CDDB entries found. Which one would you like to use (0 for none)? [0-$CDDBLOCALCHOICES]: " >&2
2249                                                 read CDDBLOCALCHOICE
2250                                                 [ x"$CDDBLOCALCHOICE" = "x" ] && CDDBLOCALCHOICE="1"
2251                                                 # FIXME # Introduce diff's
2252                                                 if echo $CDDBLOCALCHOICE | grep -E "[[:space:]]*[[:digit:]]+,[[:digit:]]+[[:space:]]*" > /dev/null 2>&1 ; then
2253                                                         diffentries cddblocalread "$CDDBLOCALCHOICES" "$CDDBLOCALCHOICE"
2254                                                 elif echo $CDDBLOCALCHOICE | grep -E "[[:space:]]*[[:digit:]]+[[:space:]]*" > /dev/null 2>&1 ; then
2255                                                         # Make sure we get a valid choice
2256                                                         CDDBLOCALCHOICENUM=$(echo $CDDBLOCALCHOICE | xargs printf %d 2>/dev/null)
2257                                                         if [ $CDDBLOCALCHOICENUM -lt 0 ] || [ $CDDBLOCALCHOICENUM -gt $CDDBLOCALCHOICES ]; then
2258                                                                 echo "Invalid selection. Please choose a number between 0 and $CDDBLOCALCHOICES." >&2
2259                                                         fi
2260                                                 fi
2261                                         done
2262                                 else
2263                                         ### FIXME ###
2264                                         #echo "Selected ..."
2265                                         CDDBLOCALRESP=y
2266                                         CDDBLOCALCHOICENUM=1
2267                                 fi
2268                                 if [ ! "$CDDBLOCALCHOICENUM" = "0" ]; then
2269                                         #echo "Using local copy of CDDB data"
2270                                         echo "# DO NOT ERASE THIS LINE! Added by abcde to imitate cddb output" > "$ABCDETEMPDIR/cddbread.1"
2271                                         cat "$ABCDETEMPDIR/cddblocalread.$CDDBLOCALCHOICENUM" >> "$ABCDETEMPDIR/cddbread.1"
2272                                         echo 999 > "$ABCDETEMPDIR/cddbquery" # Assuming 999 isn't used by CDDB
2273                                         echo cddb-readcomplete >> "$ABCDETEMPDIR/status"
2274                                         do_cddbparse "$ABCDETEMPDIR/cddbread.1" > "$ABCDETEMPDIR/cddbchoices"
2275                                         echo cddb-choice=1 >> "$ABCDETEMPDIR/status"
2276                                         CDDBLOCALSTATUS="found"
2277                                 else
2278                                         #echo "Not using local copy of CDDB data"
2279                                         CDDBLOCALSTATUS="notfound"
2280                                 fi
2281                                 ;;
2282                         single)
2283                                 # List out disc title/author and contents
2284                                 do_cddbparse "${CDDBLOCALFILE}"
2285                                 #if [ "$CDROMREADERSYNTAX" = "flac" ] ; then
2286                                 #       echo -n "Embedded cuesheet entry found, use it [Y/n]? " >&2
2287                                 #else
2288                                         echo -n "Locally cached CDDB entry found, use it [Y/n]? " >&2
2289                                 #fi
2290                                 if [ "$INTERACTIVE" = "y" ]; then
2291                                         read USELOCALRESP
2292                                         while [ "$USELOCALRESP" != "y" ] && [ "$USELOCALRESP" != "n" ] && [ "$USELOCALRESP" != "" ] ; do
2293                                                 echo -n 'Invalid selection. Please answer "y" or "n": ' >&2
2294                                                 read USELOCALRESP
2295                                         done
2296                                         [ x"$USELOCALRESP" = "x" ] && USELOCALRESP="y"
2297                                 else
2298                                         echo "y" >&2
2299                                 fi
2300                                 if [ "$USELOCALRESP" = "y" ]; then
2301                                         #echo "Using local copy of CDDB data"
2302                                         echo "# DO NOT ERASE THIS LINE! Added by abcde to imitate cddb output" > "$ABCDETEMPDIR/cddbread.1"
2303                                         cat "${CDDBLOCALFILE}" >> "$ABCDETEMPDIR/cddbread.1"
2304                                         echo 999 > "$ABCDETEMPDIR/cddbquery" # Assuming 999 isn't used by CDDB
2305                                         echo cddb-readcomplete >> "$ABCDETEMPDIR/status"
2306                                         do_cddbparse "${CDDBLOCALFILE}" > "$ABCDETEMPDIR/cddbchoices"
2307                                         echo cddb-choice=1 >> "$ABCDETEMPDIR/status"
2308                                         CDDBLOCALSTATUS="single"
2309                                 else
2310                                         #echo "Not using local copy of CDDB data"
2311                                         CDDBLOCALSTATUS="notfound"
2312                                 fi
2313                                 ;;
2314                         none)
2315                                 CDDBLOCALSTATUS="notfound"
2316                                 ;;
2317                 esac
2318         fi
2319 }
2320
2321 # do_cdtext
2322 # Try to read CD-Text from the drive using icedax / cdda2wav
2323 do_cdtext ()
2324 {
2325         if new_checkexec icedax; then
2326                 CDTEXT_READER=icedax
2327         elif new_checkexec cdda2wav; then
2328                 CDTEXT_READER=cdda2wav
2329     else
2330                 # Didn't find either, bail
2331                 return 0
2332         fi
2333
2334         if [ "$OSFLAVOUR" = "OSX" ] ; then
2335                 # Hei, we have to unmount the device before running anything like cdda2wav/icedax in OSX
2336                 diskutil unmount ${CDROM#/dev/}
2337                 # Also, in OSX the cdrom device for cdda2wav/icedax changes...
2338                 CDDA2WAVCDROM="IODVDServices"
2339         elif [ "$OSFLAVOUR" = "FBSD" ] ; then
2340                 CDDA2WAVCDROM="$CDROMID"
2341         else
2342                 if [ "$CDROMID" = "" ]; then
2343                         CDDA2WAVCDROM="$CDROM"
2344                 else
2345                         CDDA2WAVCDROM="$CDROMID"
2346                 fi
2347         fi
2348
2349         # Do we have CD-Text on the disc (and can the drive read it?)
2350         ${CDTEXT_READER} -J -N -D ${CDDA2WAVCDROM} > "$ABCDETEMPDIR/cd-text" 2>&1
2351         grep -q '^CD-Text: detected' "$ABCDETEMPDIR/cd-text"
2352         ERRORCODE=$?
2353         if [ $ERRORCODE -ne 0 ]; then
2354                 # No CD-Text found, bail
2355                 return 0
2356         fi
2357
2358         rm -f "$ABCDETEMPDIR/cddbchoices"
2359         CDDBCHOICES=1
2360         # Make an empty template
2361         $CDDBTOOL template $(cat "$ABCDETEMPDIR/discid") > "$ABCDETEMPDIR/cddbread.1"
2362         echo -n "Retrieved 1 CD-Text match..." >> "$ABCDETEMPDIR/cddbchoices"
2363         echo "done." >> "$ABCDETEMPDIR/cddbchoices"
2364         echo cddb-read-1-complete >> "$ABCDETEMPDIR/status"
2365         echo cddb-choice=1 >> "$ABCDETEMPDIR/status"
2366         ATITLE=$(grep -e '^Album title:' "${ABCDETEMPDIR}/cd-text" | cut -c14- )
2367         echo "200 none ${ATITLE}" >> "$ABCDETEMPDIR/cddbquery"
2368         # List out disc title/author and contents
2369         echo ---- ${ATITLE} ---- >> "$ABCDETEMPDIR/cddbchoices"
2370         for TRACK in $(f_seq_row 1 $TRACKS)
2371         do
2372                 TRACKM1=$(($TRACK - 1))
2373                 TITLE="$(grep -E ^Track\ +$TRACK: "$ABCDETEMPDIR/cd-text" | tr -d \\r\\n | sed 's~^Track ..: .~~g;'"s~'$~~g")"
2374                 echo "$TRACK: $TITLE" >> "$ABCDETEMPDIR/cddbchoices"
2375                 sed "s~^TTITLE${TRACKM1}=.*~TTITLE${TRACKM1}=${TITLE}~" "$ABCDETEMPDIR/cddbread.1" > "$ABCDETEMPDIR/cddbread.new"
2376         mv -f "$ABCDETEMPDIR/cddbread.new" "$ABCDETEMPDIR/cddbread.1"
2377         done
2378         sed "s~^DTITLE=.*~DTITLE=${ATITLE}~" "$ABCDETEMPDIR/cddbread.1" > "$ABCDETEMPDIR/cddbread.new"
2379     mv -f "$ABCDETEMPDIR/cddbread.new" "$ABCDETEMPDIR/cddbread.1"
2380         echo >> "$ABCDETEMPDIR/cddbchoices"
2381         echo "cdtext-readcomplete" >> "$ABCDETEMPDIR/status"
2382 }
2383
2384 # do_musicbrainz
2385 # Work with the musicbrainz WS API, then transform the results here so
2386 # they look (very) like the results from CDDB. Maybe not the best way
2387 # to go, but it Works For Me (TM)
2388
2389 do_musicbrainz ()
2390 {
2391         if checkstatus musicbrainz-readcomplete; then :; else
2392                 vecho "Obtaining Musicbrainz results..."
2393                 # If MB is to be used, interpret the query results and read all
2394                 # the available entries.
2395                 rm -f "$ABCDETEMPDIR/cddbchoices"
2396                 CDDBCHOICES=1 # Overridden by multiple matches
2397                 MBDISCID=$(echo $TRACKINFO | cut -d' ' -f1)
2398                 ${MUSICBRAINZ} --command data --discid "$MBDISCID" --workdir "$ABCDETEMPDIR"
2399
2400                 # The helper script will write disc matches out to
2401                 # cddbread.*. Count how many we have
2402                 if [ ! -f "${ABCDETEMPDIR}/cddbread.1" ] ; then
2403                         # No matches. Use the normal cddb template for the user to
2404                         # fill in
2405                         echo "No Musicbrainz match." >> "$ABCDETEMPDIR/cddbchoices"
2406                         $CDDBTOOL template $(cat "$ABCDETEMPDIR/discid") > "$ABCDETEMPDIR/cddbread.0"
2407                         # List out disc title/author and contents of template
2408                         echo ---- Unknown Artist / Unknown Album ---- >> "$ABCDETEMPDIR/cddbchoices"
2409                         UNKNOWNDISK=y
2410                         for TRACK in $(f_seq_row 1 $TRACKS)
2411                         do
2412                                 echo $TRACK: "$(grep ^TTITLE$(expr $TRACK - 1)= "$ABCDETEMPDIR/cddbread.0" | cut -f2- -d= | tr -d \\r\\n)" >> "$ABCDETEMPDIR/cddbchoices"
2413                         done
2414                         echo >> "$ABCDETEMPDIR/cddbchoices"
2415                         echo cddb-read-0-complete >> "$ABCDETEMPDIR/status"
2416                         echo cddb-choice=0 >> "$ABCDETEMPDIR/status"
2417                         echo 503 > "$ABCDETEMPDIR/cddbquery"
2418                 else
2419                         # We have some matches
2420                         NUM_RESPONSES=$(echo "${ABCDETEMPDIR}"/cddbread.* | wc -w)
2421                         if [ "$NUM_RESPONSES" -eq 1 ] ; then
2422                                 # One exact match
2423                                 echo -n "Retrieved 1 Musicbrainz match..." >> "$ABCDETEMPDIR/cddbchoices"
2424                                 echo "done." >> "$ABCDETEMPDIR/cddbchoices"
2425                                 echo cddb-read-1-complete >> "$ABCDETEMPDIR/status"
2426                                 echo cddb-choice=1 >> "$ABCDETEMPDIR/status"
2427                                 ATITLE=$(grep -e '^DTITLE=' "${ABCDETEMPDIR}/cddbread.1" | cut -c8- )
2428                                 echo "200 none ${ATITLE}" >> "$ABCDETEMPDIR/cddbquery"
2429                                 # List out disc title/author and contents
2430                                 echo ---- ${ATITLE} ---- >> "$ABCDETEMPDIR/cddbchoices"
2431                                 for TRACK in $(f_seq_row 1 $TRACKS)
2432                                 do
2433                                         echo $TRACK: "$(grep ^TTITLE$(expr $TRACK - 1)= "$ABCDETEMPDIR/cddbread.1" | cut -f2- -d= | tr -d \\r\\n)" >> "$ABCDETEMPDIR/cddbchoices"
2434                                 done
2435                                 echo >> "$ABCDETEMPDIR/cddbchoices"
2436                         else
2437                                 echo "210 Found exact matches, list follows (until terminating .)" > "$ABCDETEMPDIR/cddbquery"
2438                                 echo "Multiple Musicbrainz matches:" >> "$ABCDETEMPDIR/cddbchoices"
2439                                 for file in "$ABCDETEMPDIR"/cddbread.*
2440                                 do
2441                                         X=$(echo $file | sed 's/^.*cddbread\.//g')
2442                                         echo cddb-read-$X-complete >> "$ABCDETEMPDIR/status"
2443                                         ATITLE=$(grep -e '^DTITLE=' "${ABCDETEMPDIR}"/cddbread.$X | cut -c8- )
2444                                         echo "none ${ATITLE}" >> "$ABCDETEMPDIR/cddbquery"
2445                                         # List out disc title/author and contents
2446                                         echo "#$X: ---- ${ATITLE} ----" >> "$ABCDETEMPDIR/cddbchoices"
2447                                         for TRACK in $(f_seq_row 1 $TRACKS)
2448                                         do
2449                                                 echo $TRACK: "$(grep ^TTITLE$(expr $TRACK - 1)= "$ABCDETEMPDIR/cddbread.$X" | cut -f2- -d= | tr -d \\r\\n)" >> "$ABCDETEMPDIR/cddbchoices"
2450                                         done
2451                                         echo >> "$ABCDETEMPDIR/cddbchoices"
2452                                 done
2453                                 echo "." >> "$ABCDETEMPDIR/cddbquery"
2454                         fi
2455                 fi
2456                 echo "musicbrainz-readcomplete" >> "$ABCDETEMPDIR/status"
2457         fi
2458 }
2459
2460 # do_cddbstat
2461 do_cddbstat ()
2462 {
2463         # Perform CDDB protocol version check if it hasn't already been done
2464         if checkstatus cddb-statcomplete; then :; else
2465                 if [ "$CDDBAVAIL" = "n" ]; then
2466                         ERRORCODE=no_query
2467                         echo 503 > "$ABCDETEMPDIR/cddbstat"
2468                 else
2469                         rc=1
2470                         CDDBUSER=$(echo $HELLOINFO | cut -f1 -d'@')
2471                         CDDBHOST=$(echo $HELLOINFO | cut -f2- -d'@')
2472                         while test $rc -eq 1 -a $CDDBPROTO -ge 3; do
2473                                 vecho "Checking CDDB server status..."
2474                                 $CDDBTOOL stat $CDDBURL $CDDBUSER $CDDBHOST $CDDBPROTO > "$ABCDETEMPDIR/cddbstat"
2475                                 RESPONSECODE=$(head -n 1 "$ABCDETEMPDIR/cddbstat" | cut -f1 -d' ')
2476                                 case "$RESPONSECODE" in
2477                                 210)    # 210 OK, status information follows (until terminating `.')
2478                                         rc=0
2479                                         ;;
2480                                 501)  # 501 Illegal CDDB protocol level: <n>.
2481                                         CDDBPROTO=`expr $CDDBPROTO - 1`
2482                                         ;;
2483                                 *)      # Try a cddb query, since freedb2.org doesn't support the stat or ver commands
2484                                         # FreeDB TESTCD disc-id is used for query
2485                                         $CDDBTOOL query $CDDBURL $CDDBPROTO $CDDBUSER $CDDBHOST 03015501 1 296 344 > "$ABCDETEMPDIR/cddbstat"
2486                                         RESPONSECODE=$(head -n 1 "$ABCDETEMPDIR/cddbstat" | cut -f1 -d' ')
2487                                         case "$RESPONSECODE" in
2488                                                 2??)    # Server responded, everything seems OK
2489                                                         rc=0
2490                                                         ;;
2491                                                 *)      # unknown error
2492                                                         break
2493                                                         ;;
2494                                         esac
2495                                         ;;
2496                                 esac
2497                         done
2498                         if test $rc -eq 1; then
2499                                 CDDBAVAIL="n"
2500                         fi
2501                 fi
2502                 echo cddb-statcomplete >> "$ABCDETEMPDIR/status"
2503         fi
2504 }
2505
2506
2507 # do_cddbquery
2508 do_cddbquery ()
2509 {
2510         CDDBDISCID=$(echo $TRACKINFO | cut -d' ' -f1)
2511         CDDBLOCALFILE="${CDDBLOCALDIR}/${CDDBDISCID}"
2512
2513         # Perform CDDB query if it hasn't already been done
2514         if checkstatus cddb-querycomplete; then :; else
2515                 if [ "$CDDBAVAIL" = "n" ]; then
2516                         ERRORCODE=no_query
2517                         echo 503 > "$ABCDETEMPDIR/cddbquery"
2518                 # The default CDDBLOCALSTATUS is "notfound"
2519                 # This part will be triggered if the user CDDB repo does not
2520                 # contain the entry, or if we are not trying to use the repo.
2521                 else
2522                         vecho "Querying the CDDB server..."
2523                         CDDBUSER=$(echo $HELLOINFO | cut -f1 -d'@')
2524                         CDDBHOST=$(echo $HELLOINFO | cut -f2- -d'@')
2525                         $CDDBTOOL query $CDDBURL $CDDBPROTO $CDDBUSER $CDDBHOST $TRACKINFO > "$ABCDETEMPDIR/cddbquery"
2526                         ERRORCODE=$?
2527                         case $ERRORCODE in
2528                                 0)  # success
2529                                 ;;
2530                                 12|13|14)
2531                                         # no match found in database,
2532                                         # wget/fetch error, or user requested not to use CDDB
2533                                         # Make up an error code (503) that abcde
2534                                         # will recognize in do_cddbread
2535                                         # and compensate by making a template
2536                                         echo 503 > "$ABCDETEMPDIR/cddbquery"
2537                                 ;;
2538                                 *) # strange and unknown error
2539                                         echo ERRORCODE=$ERRORCODE
2540                                         echo "abcde: $CDDBTOOL returned unknown error code"
2541                                 ;;
2542                         esac
2543                 fi
2544                 echo cddb-querycomplete >> "$ABCDETEMPDIR/status"
2545         fi
2546 }
2547
2548 # do_cddbread
2549 do_cddbread ()
2550 {
2551         # If it's not to be used, generate a template.
2552         # Then, display it (or them) and let the user choose/edit it
2553         if checkstatus cddb-readcomplete; then :; else
2554                 vecho "Obtaining CDDB results..."
2555                 # If CDDB is to be used, interpret the query results and read all
2556                 # the available entries.
2557                 rm -f "$ABCDETEMPDIR/cddbchoices"
2558                 CDDBCHOICES=1 # Overridden by multiple matches
2559                 RESPONSECODE=$(head -n 1 "$ABCDETEMPDIR/cddbquery" | cut -f1 -d' ')
2560                 case "$RESPONSECODE" in
2561                 200)
2562                         # One exact match, retrieve it
2563                         # 200 [section] [discid] [artist] / [title]
2564                         if checkstatus cddb-read-1-complete; then :; else
2565                                 echo -n "Retrieving 1 CDDB match..." >> "$ABCDETEMPDIR/cddbchoices"
2566                                 $CDDBTOOL read $CDDBURL $CDDBPROTO $CDDBUSER $CDDBHOST $(cut -f2,3 -d' ' "$ABCDETEMPDIR/cddbquery") > "$ABCDETEMPDIR/cddbread.1"
2567                                 echo "done." >> "$ABCDETEMPDIR/cddbchoices"
2568                                 echo cddb-read-1-complete >> "$ABCDETEMPDIR/status"
2569                                 echo cddb-choice=1 >> "$ABCDETEMPDIR/status"
2570                         fi
2571                         # List out disc title/author and contents
2572                         echo ---- "$(cut '-d ' -f4- "$ABCDETEMPDIR/cddbquery")" ---- >> "$ABCDETEMPDIR/cddbchoices"
2573                         for TRACK in $(f_seq_row 1 $TRACKS)
2574                         do
2575                                 echo $TRACK: "$(grep ^TTITLE$(expr $TRACK - 1)= "$ABCDETEMPDIR/cddbread.1" | cut -f2- -d= | tr -d \\r\\n)" >> "$ABCDETEMPDIR/cddbchoices"
2576                         done
2577                         echo >> "$ABCDETEMPDIR/cddbchoices"
2578                         ;;
2579                 202|403|409|503)
2580                         # No match
2581                         case "$RESPONSECODE" in
2582                         202) echo "No CDDB match." >> "$ABCDETEMPDIR/cddbchoices" ;;
2583                         403|409) echo "CDDB entry is corrupt, or the handshake failed." >> "$ABCDETEMPDIR/cddbchoices" ;;
2584                         503) echo "CDDB unavailable." >> "$ABCDETEMPDIR/cddbchoices" ;;
2585                         esac
2586                         $CDDBTOOL template $(cat "$ABCDETEMPDIR/discid") > "$ABCDETEMPDIR/cddbread.0"
2587                         # List out disc title/author and contents of template
2588                         echo ---- Unknown Artist / Unknown Album ---- >> "$ABCDETEMPDIR/cddbchoices"
2589                         UNKNOWNDISK=y
2590                         for TRACK in $(f_seq_row 1 $TRACKS)
2591                         do
2592                                 echo $TRACK: "$(grep ^TTITLE$(expr $TRACK - 1)= "$ABCDETEMPDIR/cddbread.0" | cut -f2- -d= | tr -d \\r\\n)" >> "$ABCDETEMPDIR/cddbchoices"
2593                         done
2594                         echo >> "$ABCDETEMPDIR/cddbchoices"
2595                         echo cddb-read-0-complete >> "$ABCDETEMPDIR/status"
2596                         echo cddb-choice=0 >> "$ABCDETEMPDIR/status"
2597                         ;;
2598                 210|211)
2599                         # Multiple exact, (possibly multiple) inexact matches
2600                         IN=
2601                         if [ "$RESPONSECODE" = "211" ]; then IN=in; fi
2602                         if [ "$(wc -l < "$ABCDETEMPDIR/cddbquery" | tr -d ' ')" -eq 3 ]; then
2603                                 echo "One ${IN}exact match:" >> "$ABCDETEMPDIR/cddbchoices"
2604                                 tail -n +2 "$ABCDETEMPDIR/cddbquery" | head -n 1 >> "$ABCDETEMPDIR/cddbchoices"
2605                                                         echo cddb-choice=1 >> "$ABCDETEMPDIR/status"
2606                         else
2607                                 echo "Multiple ${IN}exact matches:" >> "$ABCDETEMPDIR/cddbchoices"
2608                         fi
2609                         vecho -n "Retrieving multiple matches... "
2610                         grep -v ^[.]$ "$ABCDETEMPDIR/cddbquery" | ( X=0
2611                         read DISCINFO # eat top line
2612                         while read DISCINFO
2613                         do
2614                                 X=$(expr $X + 1)
2615                                 if checkstatus cddb-read-$X-complete; then :; else
2616                                         $CDDBTOOL read $CDDBURL $CDDBPROTO $CDDBUSER $CDDBHOST $(echo $DISCINFO | cut -f1,2 -d' ') > "$ABCDETEMPDIR/cddbread.$X"
2617                                         echo cddb-read-$X-complete >> "$ABCDETEMPDIR/status"
2618                                 fi
2619                                 # List out disc title/author and contents
2620                                 echo \#$X: ---- "$DISCINFO" ---- >> "$ABCDETEMPDIR/cddbchoices"
2621                                 for TRACK in $(f_seq_row 1 $TRACKS)
2622                                 do
2623                                         echo $TRACK: "$(grep ^TTITLE$(expr $TRACK - 1)= "$ABCDETEMPDIR/cddbread.$X" | cut -f2- -d= | tr -d \\r\\n)" >> "$ABCDETEMPDIR/cddbchoices"
2624                                 done
2625                                 echo >> "$ABCDETEMPDIR/cddbchoices"
2626                         done )
2627                         vecho "done."
2628                         CDDBCHOICES=$(expr $(cat "$ABCDETEMPDIR/cddbquery" | wc -l) - 2)
2629                         ;;
2630                 999)
2631                         # Using local copy.
2632                         for TRACK in $(f_seq_row 1 $TRACKS)
2633                         do
2634                                 echo $TRACK: "$(grep ^TTITLE$(expr $TRACK - 1)= "$ABCDETEMPDIR/cddbread.1" | cut -f2- -d= | tr -d \\r\\n)" >> "$ABCDETEMPDIR/cddbchoices"
2635                         done
2636                         echo >> "$ABCDETEMPDIR/cddbchoices"
2637                         echo cddb-read-1-complete >> "$ABCDETEMPDIR/status"
2638                         echo cddb-choice=1 >> "$ABCDETEMPDIR/status"
2639                         ;;
2640                 esac
2641                 echo "cddb-readcomplete" >> "$ABCDETEMPDIR/status"
2642         fi
2643 }
2644
2645 # do_cddbedit
2646 do_cddbedit ()
2647 {
2648         if checkstatus cddb-edit >/dev/null; then
2649                 CDDBDATA="$ABCDETEMPDIR/cddbread.$(checkstatus cddb-choice)"
2650                 VARIOUSARTISTS="$(checkstatus variousartists)"
2651                 VARIOUSARTISTSTYLE="$(checkstatus variousartiststyle)"
2652                 return 0
2653         fi
2654         if [ "$INTERACTIVE" = "y" ]; then
2655                 # We should show the CDDB results both when we are not using the local CDDB repo
2656                 # or when we are using it but we could not find a proper match
2657                 if [ "$CDDBUSELOCAL" = "y" ] && [ "$CDDBLOCALSTATUS" = "notfound" ] || [ ! "$CDDBUSELOCAL" = "y" ]; then
2658                         # Display the $ABCDETEMPDIR/cddbchoices file created above
2659                         # Pick a pager so that if the tracks overflow the screen the user can still view everything
2660                         if [ -r "$ABCDETEMPDIR/cddbchoices" ]; then
2661                                 CDDBCHOICES=$(expr $(cat "$ABCDETEMPDIR/cddbquery" | wc -l) - 2)
2662                                 CHOICE=$(checkstatus cddb-choice)
2663                                 if [ -n "$CHOICE" ] ; then
2664                                         case $CDDBCHOICES in
2665                                                 -1) if head -1 "$ABCDETEMPDIR/cddbquery" | grep "^$" > /dev/null 2>&1 ; then
2666                                                                 log error "CDDB query failed!"
2667                                                                 exit 1
2668                                                         else
2669                                                                 cat "$ABCDETEMPDIR/cddbchoices"
2670                                                         fi
2671                                                         ;;
2672                                                 1) cat "$ABCDETEMPDIR/cddbchoices" ;;
2673                                                 *)
2674                                                 echo "Selected: #$CHOICE"
2675                                                 do_cddbparse "$ABCDETEMPDIR/cddbread.$CHOICE"
2676                                                 ;;
2677                                         esac
2678                                 else
2679                                         # The user has a choice to make, display the info in a pager if necessary
2680                                         if [ $(cat "$ABCDETEMPDIR/cddbchoices" | wc -l) -ge 24 ]; then
2681                                                 page "$ABCDETEMPDIR/cddbchoices"
2682                                         else
2683                                                 # It's all going to fit in one page, cat it
2684                                                 cat "$ABCDETEMPDIR/cddbchoices" >&2
2685                                         fi
2686
2687                                         CDDBCHOICENUM=""
2688                                         # Setting the choice to an impossible integer to avoid errors in the numeric comparisons
2689                                         CDCHOICENUM=-1
2690                                         # I'll take CDDB read #3 for $400, Alex
2691                                         while [ $CDCHOICENUM -lt 0 ] || [ $CDCHOICENUM -gt $CDDBCHOICES ]; do
2692                                                 echo -n "Which entry would you like abcde to use (0 for none)? [0-$CDDBCHOICES]: " >&2
2693                                                 read CDDBCHOICE
2694                                                 [ X"$CDDBCHOICE" = "X" ] && CDDBCHOICE=1
2695                                                 if echo $CDDBCHOICE | grep -E "[[:space:]]*[[:digit:]]+,[[:digit:]]+[[:space:]]*" > /dev/null 2>&1 ; then
2696                                                         if [ ! X"$DIFF" = "X" ]; then
2697                                                                 PARSECHOICE1=$(echo $CDDBCHOICE | cut -d"," -f1 | xargs printf %d 2>/dev/null)
2698                                                                 PARSECHOICE2=$(echo $CDDBCHOICE | cut -d"," -f2 | xargs printf %d 2>/dev/null)
2699                                                                 if [ $PARSECHOICE1&nbs