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