Merge with bugfix-0.5
mp3togo/conf.py
1 # - conf.py -
2 # This file is part of mp3togo
3
4 # Convert audio files to play on a mp3 player
5 # Manage program options
6 #
7 # (c) Simeon Veldstra 2004, 2006 <reallifesim@gmail.com>
8 #
9 # This software is free.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
15 #
16 # You may redistribute this program under the terms of the
17 # GNU General Public Licence version 2
18 # Available in this package or at http://www.fsf.org
19
20 # requires python-pyvorbis and python-id3 and lame
21 # and mpg321
22
23 import sys
24 import os
25 import time
26
27 import mp3togo
28 import mp3togo.options as options
29
30 from mp3togo.helpers import helpers
31
32
33 class Fail(options.Fail):
34 pass
35
36 class Error(Exception):
37 pass
38
39 class ErrorUnknownFileType(Error):
40 pass
41
42 class ErrorNoFile(Error):
43 pass
44
45 class ErrorNoCache(Error):
46 pass
47
48 class ErrorBadFormat(Error):
49 pass
50
51 class ErrorNoXMMSControl(Error):
52 pass
53
54 class ErrorXMMSNotRunning(Error):
55 pass
56
57 class ErrorNoDCOP(Error):
58 pass
59
60 class ErrorAmarokNotRunning(Error):
61 pass
62
63 class ErrorUnlocked(Error):
64 pass
65
66 class TaskNotReadyError(Error):
67 pass
68
69 class ErrorClusterProtocol(Error):
70 pass
71
72
73
74 class Options(options.Options):
75 """Subclass options.Options and fill in application specific
76 information."""
77 def __init__(self, argv=None, conffile=None, readconf=True):
78 self.argv = argv
79 options.Options.__init__(self, absfile('~/.mp3togo'))
80
81 # Options to add:
82 # ((name, short option, long option, default value, hook, help text), ...)
83 self._set += [
84 ('gui', 'X', 'gui-mode', False, None,
85 '''Start mp3togo GTK interface.'''),
86 ('brwarning', 't', 'file-tag', '.2go', None,
87 '''A string appended to the name of the file to indicate it has been recoded.'''),
88 ('tempdir', 'w', 'work-dir', '/tmp', self._absfile,
89 '''The path to store temporary files. This could need several hundred megabytes free.'''),
90 ('treedepth', 'd', 'tree-depth', 1, None,
91 '''The number of directory levels to preserve in the output tree. Use 0 to put all output files directly into the target directory. Use 2 to create a directory for the Artist and then the Album (Assuming your music collection is organized in directories by artist then album).'''),
92 ('treestructure', '', 'format', '', None,
93 '''A string specifying the format for the output files. The format string can contain the following escapes:<li>%a - Artist<li>%l - Album<li>%t - Title<li>%y - Year<li>%g - Genre<li>%% - Literal '%'<br>Overrides --tree-depth.'''),
94 ('notags', '', 'no-tags', False, None,
95 '''Do not try to write tags to the output files.'''),
96 ('maxunits', 'm', 'max-size', '0', self._units,
97 '''The disk space available to use in bytes. Append 'M' for megabytes, 'G' for gigabytes or 'K' for kilobytes. Use 0 to use all available space on the filesystem.'''),
98 ('maxsize', '', '', 0L, None, ''),
99 ('maxtempunits', '', 'max-temp-size', '0', self._units,
100 '''The disk space available to use for temporary files in bytes. Append 'M' for megabytes, 'G' for gigabytes or 'K' for kilobytes. Use 0 to use all available space on the filesystem.'''),
101 ('maxtempsize', '', '', 0L, None, ''),
102 ('force', 'F', 'force', False, None,
103 '''Overwrite files if they already exist.'''),
104 ('encoder', 'C', 'encoder', 'lame', None,
105 '''The encoder to use to create the output files. Options are wav, lame or oggenc.'''),
106 ('encopts', 'E', 'encoder-options', '', None,
107 '''Compression options for the encoder.'''),
108 ('compfactor', 'z', 'compression-factor', 16.0, None,
109 '''If you change the lame options, you must change this factor to match the compression rate of the new options. This is used to estimate completed file size.'''),
110 ('makecache', '', 'make-cache', '', self._absfile, '''Make an output file cache at the given path.'''),
111 ('cachesize', '', '', 0L, None, ''),
112 ('cacheunits', '', 'cache-size', '0', self._units, '''The size for the new cache.'''),
113 ('usecache', '', 'use-cache', '', self._absfile, '''Use the cache stored at the given path.'''),
114 ('help', 'h', 'help', False, None, '''Print this message.'''),
115 ('playlist', 'p', 'playlist', '', None,
116 '''The playlist to convert. Playlists can be simple lists of file paths, one per line, or .m3u files or the native XMMS playlist file format. Playlists can be also listed on the command line as free arguments after all of the options if they have a recognizable extension. Currently .m3u and .pls are recognized.'''),
117 ('readxmms', 'x', 'import-xmms', False, None,
118 '''Get playlist from running instance of XMMS. (You must have the python-xmms module installed)'''),
119 ('readamarok', '', 'import-amarok', False, None,
120 '''Get playlist from running instance of Amarok.'''),
121 ('playerdir', 'o', 'output-dir', os.curdir, self._absfile,
122 '''Where to write the output files.'''),
123 ('index', '', 'index', False, None,
124 '''Create an index file when in wav output mode.'''),
125 ('nonormal', '', 'no-normalize', False, None,
126 '''Don't normalize the wav file before encoding.'''),
127 ('cluster', '', 'cluster', '', None,
128 '''Manage a cluster of worker machines. Cluster mode distributes tracks between multiple computers connected to a LAN. Provide a comma separated list of IP addresses or hostnames. The master machine must be able to log in to the slaves without a password and the slaves must have shared access to the filesystem. See the website for an example of how to set it up.<li>http://puddle.ca/mp3togo/'''),
129 ('clusternolocal', '', 'cluster-no-local-node', False, None,
130 '''Only use the remote nodes for processing files.'''),
131 ('clusterslave', '', 'cluster-slave', False, None,
132 '''Start a worker process for cluster mode. This option is used by the cluster master to start slave processes. Do not use.''')]
133
134 # Override hook defined in Base class
135 self._conffile = self._absfile
136
137 # Options to not save to the config file:
138 self._nosave_options += []
139
140 # Binaries to check for:
141 self.bin['wav'] = True
142 self.bin['lame'] = False
143 self.bin['oggenc'] = False
144 self.bin['mpg321'] = False
145 self.bin['ogg123'] = False
146 self.bin['flac'] = False
147 self.bin['faad'] = False
148 self.bin['metaflac'] = False
149 self.bin['normalize-audio'] = False
150 self.bin['dcop'] = False
151
152 # What input types are supported on this system?
153 self.types = []
154 for helper in helpers.values():
155 if helper['action'] == 'decode':
156 bin = helper['cmd'].split()[0]
157 for path in map(lambda x: os.path.join(x, bin),
158 os.environ['PATH'].split(':')):
159 if os.path.exists(path):
160 if isinstance(helper['type'], (tuple, list)):
161 self.types.extend(helper['type'])
162 else:
163 self.types.append(helper['type'])
164 break
165
166 self.version = mp3togo.version
167 self._help_preamble = """
168 Synopsis:
169 mp3togo [-p playlist] [-o output-dir] [options] [input files]
170
171 Description:
172 mp3togo is a program for converting audio files of various
173 formats into a common format suitable for use on a portable
174 mp3 player or an mp3 CD. The files to convert can be
175 specified in a playlist file (m3u, pls and plain text are
176 supported) or given as arguments to the program. mp3togo
177 will go through the list and run mpg321, ogg123, flac, faad and
178 lame to decode and reencode the files. The newly encoded
179 files will be written to the destination directory. The
180 software can retain as much of the subdirectory structure
181 as desired.
182 """
183
184 # Check for Third party modules:
185 self.mod['ogg.vorbis'] = False
186 self.mod['ID3'] = False
187 self.mod['eyeD3'] = False
188 self.mod['xmms'] = False
189
190 # Go ahead and read in the data:
191 self.getconf(argv, conffile, readconf)
192
193
194
195 # All hooks are called with the lock held
196 # and must reference the ._d dict directly
197 def _post_hook(self):
198 #Set up default encoder options if not specified:
199 if not self._d['encopts']:
200 self.reset_encoder_options()
201
202 def _absfile(self, name, value):
203 self._d[name] = absfile(value)
204
205 def _units(self, name, value):
206 #Calculate raw bytes and set [max|temp|cache]size
207 try:
208 if value[-1] in ('m', 'M'):
209 max = long(value[:-1]) * 1048576L
210 elif value[-1] in ('g', 'G'):
211 max = long(value[:-1]) * 1073741824L
212 elif value[-1] in ('k', 'K'):
213 max = long(value[:-1]) * 1024L
214 else:
215 max = long(value)
216 except ValueError:
217 raise Fail, "Bad %s option: %s " % (name, value)
218 sizename = name.replace('units', 'size')
219 self._d[sizename] = max # 'maxsize'
220 self._d[name] = value # 'maxunits'
221
222 def _arg_files(self, name, value):
223 l = []
224 for f in value:
225 f = absfile(f)
226 if os.path.exists(f):
227 l.append(f)
228 self._d[name] = l
229
230 def reset_encoder_options(self):
231 """Reset encoder options to defaults."""
232 if self._d['encoder'] == 'lame':
233 self._d['encopts'] = '--abr 96'
234 elif self._d['encoder'] == 'oggenc':
235 self._d['encopts'] = '-m 96 -M 225 -b 100'
236 elif self._d['encoder'] == 'wav':
237 self._d['encopts'] = ''
238
239 def cleanfilename(self, name):
240 """Remove nasty characters from a filename"""
241 name = name.replace('"', "'")
242 name = name.replace(':', '.')
243 name = name.replace("?", "")
244 name = name.replace('*', '')
245 name = name.replace('`', "'")
246 name = name.replace('&', '+')
247 name = name.replace(';', '.')
248 name = name.replace('#', '-')
249 name = name.replace('|', '-')
250 if name[0] == '.':
251 name = '_' + name
252 return name
253
254 def getfiletype(self, filename):
255 """Return the format of an audio file"""
256 # Could use some more magic here
257 ft = os.path.splitext(filename)[1][1:]
258 #if ft not in ('mp3', 'ogg', 'flac', 'wav', 'm4a'):
259 if ft not in self.types:
260 raise ErrorUnknownFileType
261 return ft
262
263 def checkfile(self, name):
264 """Verify the existence of an audio file"""
265 name = name.replace('\n', '')
266 name = name.replace('\r', '')
267 name = name.replace('\f', '')
268 if not os.path.exists(name):
269 raise ErrorNoFile
270 name = absfile(name)
271 self.getfiletype(name) # Throws exception if unknown
272 return name
273
274 def est_decoded_size(self, filename):
275 """Estimate size of decoded wav file."""
276 tp = self.getfiletype(filename)
277 helper = find_helper(tp, 'decode')
278 return os.stat(filename).st_size * helpers[helper]['factor']
279
280
281
282
283 def try_print(msg):
284 """Try to print a message to a nonblocking stdout"""
285 for i in range(1, 6):
286 try:
287 sys.stdout.write(msg)
288 return
289 except:
290 time.sleep(0.01 ** (1.0 / i))
291
292 def absfile(name):
293 name = name.strip()
294 name = os.path.expanduser(name)
295 if name:
296 name = os.path.abspath(name)
297 return name
298
299 def find_helper(type, action):
300 """Return the name of the best helper that performs 'action' on 'type'
301
302 Raises KeyError if type or action is unknown."""
303 for helper in helpers.keys():
304 if helpers[helper]['action'] == action and \
305 type in helpers[helper]['type']:
306 return helper
307 raise KeyError
308
309 def make_args(helper, input, output, args=''):
310 """Substitute for command line args"""
311 esc = {'z': '%', 'i': "###input###", 'o': "###output###", 'a': args}
312 out = ""
313 fmt = helpers[helper]['cmd']
314 fmt = fmt.replace('%%', '%z')
315 fmt = fmt.split('%')
316 while fmt:
317 out += fmt[0]
318 if len(fmt) <= 1:
319 break
320 fmt = fmt[1:]
321 code = fmt[0] and fmt[0][0]
322 if code in esc.keys():
323 fmt[0] = esc[code] + fmt[0][1:]
324 else:
325 raise ErrorBadFormat
326 out = out.split()
327 # This foolishness is to prevent splitting
328 # filenames with whitespace in them.
329 if "###input###" in out:
330 out[out.index("###input###")] = input
331 if "###output###" in out:
332 out[out.index("###output###")] = output
333 return out
334
335