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