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