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