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