superrip: Fork a new process to do lame and flac
[cmccabe-bin] / superrip.rb
1 #!/usr/bin/ruby -w
2
3 #
4 # superrip.rb
5 #
6 # Advanced CD-ROM ripping program
7
8 # Copyright 2010, Colin McCabe
9 #
10
11 require 'fileutils'
12 require 'optparse'
13 require 'optparse/time'
14 require 'ostruct'
15
16 #-----------------------------------------------------------------
17 # constants
18 #-----------------------------------------------------------------
19 $cd_dev = "/dev/cdrom"
20
21 #-----------------------------------------------------------------
22 # functions
23 #-----------------------------------------------------------------
24 def my_system(cmd)
25   puts cmd
26   system(cmd) unless $opts.dry_run == true
27   ($?.exitstatus == 0) or raise "#{cmd} failed"
28 end
29
30 def die_unless_installed(cmd)
31   system("which #{cmd} > /dev/null")
32   ($?.exitstatus == 0) or raise "you need to install the #{cmd} program"
33 end
34
35 def get_number_of_tracks_on_cd
36   look_for_tracks = false
37   lines = Array.new
38   IO.popen("cdda2wav -v summary -J dev=#{$cd_dev} 2>&1", "r") do |io|
39     io.readlines.each do |line|
40       line.chomp!
41       lines << line
42       if (line =~ /^AUDIOtrack/) then
43         look_for_tracks = true
44       elsif (look_for_tracks == true) then
45         look_for_tracks = false
46         line =~ /[ \t]*1-([1234567890][1234567890]*)[^1234567890]/ \
47           or raise "couldn't understand cdda2wav output!"
48         return $1.to_i
49       end
50     end
51   end
52   raise "couldn't find what we were looking for in cdda2wav output! \
53 output:#{lines.join('\n')}"
54 end
55
56 # Process the WAV file into an MP3 and FLAC file.
57 # This is done in a background process.
58 def process_wav(track)
59   FileUtils.mkdir_p(track.flac_dir, $fu_args)
60   my_system("flac -f '#{track.wav_file_name}' \
61 --output-name='#{track.flac_file_name}' &>/dev/null")
62   my_system("flac --test '#{track.flac_file_name}' &>/dev/null")
63   FileUtils.mkdir_p(track.mp3_dir, $fu_args)
64   my_system("lame -q 1 -b 192 '#{track.wav_file_name}' \
65 '#{track.mp3_file_name}' &>/dev/null")
66   FileUtils.rm_f(track.wav_file_name, $fu_args)
67 end
68
69 def audiorip(tnum, track)
70   begin
71     my_system("nice -1 cdparanoia -w -d #{$cd_dev} #{tnum}")
72   rescue
73     raise "failed to rip track #{tnum} (#{track.name})"
74   end
75   # cdparanoia always outputs to cdda.wav
76   FileUtils.mv("cdda.wav", track.wav_file_name, $fu_args)
77
78   # TODO: if there are more than N processes, wait for one of them to terminate
79   pid = Process.fork
80   if (pid == nil) then
81     begin
82       process_wav(track)
83       Kernel.exit(0)
84     rescue
85       Kernel.exit(1)
86     end
87   end
88 end
89
90 #-----------------------------------------------------------------
91 # classes
92 #-----------------------------------------------------------------
93 class MyOptions
94   def self.parse(args)
95     opts = OpenStruct.new
96     opts.dry_run = false
97     $fu_args = { :verbose => true }
98
99     # Fill in opts values
100     parser = OptionParser.new do |myparser|
101       myparser.banner = "Usage: #{ File.basename($0) } [opts]"
102       myparser.separator("Specific options:")
103       myparser.on("--dry-run", "-d",
104             "Show what would be done, without doing it.") do |a|
105         opts.dry_run = true
106         $fu_args = { :verbose => true, :noop => true }
107       end
108       myparser.on("--tracklist [FILE]", "-t",
109             "Provide a list of tracks to use.") do |file|
110         opts.manifest_file = file
111         opts.partial = false
112       end
113       myparser.on("--partial-tracklist [FILE]", "-T",
114             "Provide a partial list of tracks to use.") do |file|
115         opts.manifest_file = file
116         opts.partial = true
117       end
118     end
119     parser.parse!(args)
120
121     raise "you must provide a tracklist" unless opts.manifest_file != nil
122     return opts
123   end
124 end
125
126 class Track
127   attr_accessor :name, :flac_dir, :flac_file_name, :mp3_dir, :mp3_file_name,
128     :wav_file_name
129   def initialize(name)
130     if name =~ /\[LL\]/ then
131       raise "you can't include [LL] in a track name" 
132     end
133     if name =~ /\.mp3/ then
134       raise "don't include .mp3 in the track name; that will be added"
135     end
136     if name =~ /\.flac/ then
137       raise "don't include .flac in the track name; that will be added"
138     end
139     (name =~ /([^\/][^\/]*)\/([^\/]*[^\/])/) or \
140       raise "track name must be of the form 'foo/bar'"
141     @name = name
142     @flac_dir = "#{$1} [LL]"
143     @flac_file_name = "#{@flac_dir}/#{$2}.flac"
144     @mp3_dir = "#{$1}"
145     @mp3_file_name = "#{@mp3_dir}/#{$2}.mp3"
146     @wav_file_name = "#{$1}__#{$2}.wav"
147   end
148
149   def inspect
150     "track(\"#{@name}\")"
151   end
152 end
153
154 class Manifest
155   def initialize(filename)
156     @t = Hash.new
157     eval(File.new(filename).read)
158     @t.each do |key, val|
159       @t[key] = Track.new(val)
160     end
161     # TODO: implement some shortcuts that make manifests easier to type.
162     # Probably avoiding the necessity to continue typing the album name if it is the same as the
163     # previous track's name would make things a lot easier without complicating everything too much.
164   end
165
166   def validate(num_tracks)
167     if (@t.empty?) then
168       raise "you must define some tracks"
169     end
170     @t.each { |t| t.validate }
171     if (not $opts.partial) then
172       (1..num_tracks).each do |t|
173         if not @t[t].defined?
174           raise "don't know what to do with track #{t}"
175         end
176       end
177     end
178     # TODO: make sure that tracks inside albums are in order
179     # i.e. we don't map track 2 to a name that sorts to before track 1
180   end
181
182   def rip(num_tracks)
183     (1..num_tracks).each do |tnum|
184       next unless @t.has_key?(tnum)
185       audiorip(tnum, @t[tnum])
186     end
187   end
188
189   def inspect
190     ret = ""
191     @t.keys.sort.each do |key|
192       ret = "#{ret}#{key}:'#{@t[key].inspect()}'\n"
193     end
194     return ret
195   end
196 end
197
198 #-----------------------------------------------------------------
199 # main
200 #-----------------------------------------------------------------
201 # Parse options.
202 begin
203   begin
204     $opts = MyOptions.parse(ARGV)
205   rescue ArgumentError => msg
206   $stderr.puts("#{msg} Type --help to see usage information.\n")
207   exit 1
208   end
209 end
210
211 die_unless_installed("lame")
212 die_unless_installed("flac")
213 die_unless_installed("cdparanoia")
214 die_unless_installed("cdda2wav")
215
216 manifest = Manifest.new($opts.manifest_file)
217 puts manifest.inspect
218 num_tracks = get_number_of_tracks_on_cd()
219 puts "found #{num_tracks} tracks"
220 manifest.rip(num_tracks)
221 exit 0