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