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