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