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