Makefile: add pickrand
[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 $children = Hash.new
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=#{$opts.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! (line:#{line})"
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 #{$opts.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   # If there are too many processes, wait for one of them to terminate
79   if ($children.keys.length > $opts.max_children) then
80     pid, status = Process.wait2(-1)
81     if (status.exitstatus != 0) then
82       raise "process #{pid} failed with exitstatus #{status.exitstatus}"
83     end
84     $children.delete(pid)
85   end
86
87   pid = Process.fork
88   if (pid == nil) then
89     retcode = 0
90     begin
91       process_wav(track)
92     rescue Exception => e
93       puts "*** FATAL ERROR: #{e}"
94       retcode = 1
95     end
96     Kernel.exit(retcode)
97   else
98     $children[pid] = 1
99   end
100 end
101
102 #-----------------------------------------------------------------
103 # classes
104 #-----------------------------------------------------------------
105 class MyOptions
106   def self.parse(args)
107     opts = OpenStruct.new
108     opts.dry_run = false
109     opts.max_children = 4
110     opts.cd_dev = "/dev/cdrom"
111     $fu_args = { :verbose => true }
112
113     # Fill in opts values
114     parser = OptionParser.new do |myparser|
115       myparser.banner = "Usage: #{ File.basename($0) } [opts]"
116       myparser.separator("Specific options:")
117       myparser.on("--dev [DEV]", "-D",
118                   "choose the cdrom device file to use") do |dev|
119         opts.cd_dev = dev
120       end
121       myparser.on("--dry-run", "-d",
122             "Show what would be done, without doing it.") do |a|
123         opts.dry_run = true
124         $fu_args = { :verbose => true, :noop => true }
125       end
126       myparser.on("--tracklist [FILE]", "-t",
127             "Provide a list of tracks to use.") do |file|
128         opts.manifest_file = file
129         opts.partial = false
130       end
131       myparser.on("--partial-tracklist [FILE]", "-T",
132             "Provide a partial list of tracks to use.") do |file|
133         opts.manifest_file = file
134         opts.partial = true
135       end
136       myparser.on("--max-children [NCHILD]", "-j",
137             "The maximum number of child processes to allow at any \
138 given time") do |nchild|
139         opts.max_children = nchild.to_i
140         if (opts.max_children < 1) then
141           raise "can't set max_children to #{opts.max_children}"
142         end
143       end
144     end
145     parser.parse!(args)
146
147     raise "you must provide a tracklist" unless opts.manifest_file != nil
148     return opts
149   end
150 end
151
152 class Track
153   attr_accessor :name, :flac_dir, :flac_file_name, :mp3_dir, :mp3_file_name,
154     :wav_file_name
155   def initialize(name)
156     if name =~ /\[LL\]/ then
157       raise "you can't include [LL] in a track name" 
158     end
159     if name =~ /\.mp3/ then
160       raise "don't include .mp3 in the track name; that will be added"
161     end
162     if name =~ /\.flac/ then
163       raise "don't include .flac in the track name; that will be added"
164     end
165     (name =~ /([^\/][^\/]*)\/([^\/]*[^\/])/) or \
166       raise "track name must be of the form 'foo/bar'"
167     @name = name
168     @flac_dir = "#{$1} [LL]"
169     @flac_file_name = "#{@flac_dir}/#{$2}.flac"
170     @mp3_dir = "#{$1}"
171     @mp3_file_name = "#{@mp3_dir}/#{$2}.mp3"
172     @wav_file_name = "#{$1}__#{$2}.wav"
173   end
174
175   def inspect
176     "track(\"#{@name}\")"
177   end
178 end
179
180 class Manifest
181   def initialize(filename)
182     @t = Hash.new
183     eval(File.new(filename).read)
184     @t.each do |key, val|
185       @t[key] = Track.new(val)
186     end
187     # TODO: implement some shortcuts that make manifests easier to type.
188     # Probably avoiding the necessity to continue typing the album name if it is the same as the
189     # previous track's name would make things a lot easier without complicating everything too much.
190   end
191
192   def validate(num_tracks)
193     if (@t.empty?) then
194       raise "you must define some tracks"
195     end
196     if ($opts.partial) then
197       highest_track = @t.keys.sort[-1]
198       if (num_tracks < highest_track) then
199         raise "can't rip track #{highest_track}, because there are \
200 only #{num_tracks} tracks"
201       end
202     else
203       (1..num_tracks).each do |tnum|
204         if not @t.has_key?(tnum)
205           raise "don't know what to do with track #{tnum}"
206         end
207       end
208     end
209     # TODO: make sure that tracks inside albums are in order
210     # i.e. we don't map track 2 to a name that sorts to before track 1
211   end
212
213   def rip(num_tracks)
214     (1..num_tracks).each do |tnum|
215       next unless @t.has_key?(tnum)
216       audiorip(tnum, @t[tnum])
217     end
218     prc = Process.waitall
219     prc.each do |pair|
220       if (pair[1].exitstatus != 0) then
221         raise "process #{pair[0]} failed with exitstatus #{pair[1].exitstatus}"
222       end
223     end
224   end
225
226   def inspect
227     ret = ""
228     @t.keys.sort.each do |key|
229       ret = "#{ret}#{key}:'#{@t[key].inspect()}'\n"
230     end
231     return ret
232   end
233 end
234
235 #-----------------------------------------------------------------
236 # main
237 #-----------------------------------------------------------------
238 # Parse options.
239 begin
240   begin
241     $opts = MyOptions.parse(ARGV)
242   rescue ArgumentError => msg
243   $stderr.puts("#{msg} Type --help to see usage information.\n")
244   exit 1
245   end
246 end
247
248 die_unless_installed("lame")
249 die_unless_installed("flac")
250 die_unless_installed("cdparanoia")
251 die_unless_installed("cdda2wav")
252
253 manifest = Manifest.new($opts.manifest_file)
254 puts manifest.inspect
255 num_tracks = get_number_of_tracks_on_cd()
256 puts "found #{num_tracks} tracks"
257 manifest.validate(num_tracks)
258 manifest.rip(num_tracks)
259 puts "*** FINISHED ***"
260 exit 0