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