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