2 # This file is part of mp3togo
4 # Convert audio files to play on a mp3 player
5 # Manage program options
7 # (c) Simeon Veldstra 2004, 2006 <reallifesim@gmail.com>
9 # This software is free.
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.
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
20 # requires python-pyvorbis and python-id3 and lame
26 import mp3togo.options as options
29 class Fail(options.Fail):
32 class Error(Exception):
35 class ErrorUnknownFileType(Error):
38 class ErrorNoFile(Error):
41 class ErrorNoCache(Error):
44 class ErrorBadFormat(Error):
47 class ErrorNoXMMSControl(Error):
50 class ErrorXMMSNotRunning(Error):
53 class ErrorNoDCOP(Error):
56 class ErrorAmarokNotRunning(Error):
59 class ErrorUnlocked(Error):
62 class TaskNotReadyError(Error):
65 class ErrorClusterProtocol(Error):
70 class Options(options.Options):
71 """Subclass options.Options and fill in application specific
73 def __init__(self, argv=None, conffile=None, readconf=True):
74 options.Options.__init__(self, '~/mp3togo')
77 # ((name, short option, long option, default value, hook, help text), ...)
79 ('brwarning', 't', 'file-tag', '.2go', None,
80 '''A string appended to the name of the file to indicate it has been recoded.'''),
81 ('tempdir', 'w', 'work-dir', '/tmp', self._absfile,
82 '''The path to store temporary files. This could need several hundred megabytes free.'''),
83 ('treedepth', 'd', 'tree-depth', 1, None,
84 '''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).'''),
85 ('treestructure', '', 'format', '', None,
86 '''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.'''),
87 ('notags', '', 'no-tags', False, None,
88 '''Do not try to write tags to the output files.'''),
89 ('maxunits', 'm', 'max-size', '0', self._units,
90 '''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.'''),
91 ('maxsize', '', '', 0L, None, ''),
92 ('maxtempunits', '', 'max-temp-size', '0', self._units,
93 '''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.'''),
94 ('maxtempsize', '', '', 0L, None, ''),
95 ('force', 'F', 'force', False, None,
96 '''Overwrite files if they already exist.'''),
97 ('encoder', 'C', 'encoder', 'lame', None,
98 '''The encoder to use to create the output files. Options are wav, lame or oggenc.'''),
99 ('encopts', 'E', 'encoder-options', '', None,
100 '''Compression options for the encoder.'''),
101 ('compfactor', 'z', 'compression-factor', 16.0, None,
102 '''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.'''),
103 ('makecache', '', 'make-cache', '', self._absfile, '''Make an output file cache at the given path.'''),
104 ('cachesize', '', '', 0L, None, ''),
105 ('cacheunits', '', 'cache-size', '0', self._units, '''The size for the new cache.'''),
106 ('usecache', '', 'use-cache', '', self._absfile, '''Use the cache stored at the given path.'''),
107 ('help', 'h', 'help', False, None, '''Print this message.'''),
108 ('playlist', 'p', 'playlist', '', None,
109 '''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.'''),
110 ('readxmms', 'x', 'import-xmms', False, None,
111 '''Get playlist from running instance of XMMS. (You must have the python-xmms module installed)'''),
112 ('readamarok', '', 'import-amarok', False, None,
113 '''Get playlist from running instance of Amarok.'''),
114 ('playerdir', 'o', 'output-dir', os.curdir, self._absfile,
115 '''Where to write the output files.'''),
116 ('index', '', 'index', False, None,
117 '''Create an index file when in wav output mode.'''),
118 ('nonormal', '', 'no-normalize', False, None,
119 '''Don't normalize the wav file before encoding.'''),
120 ('cluster', '', 'cluster', '', None,
121 '''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/'''),
122 ('clusternolocal', '', 'cluster-no-local-node', False, None,
123 '''Only use the remote nodes for processing files.'''),
124 ('clusterslave', '', 'cluster-slave', False, None,
125 '''Start a worker process for cluster mode. This option is used by the cluster master to start slave processes. Do not use.''')]
127 # Override hook defined in Base class
128 self._conffile = self._absfile
130 # Options to not save to the config file:
131 self._nosave_options += []
133 # Binaries to check for:
134 self.bin['wav'] = True
135 self.bin['lame'] = False
136 self.bin['oggenc'] = False
137 self.bin['mpg321'] = False
138 self.bin['ogg123'] = False
139 self.bin['flac'] = False
140 self.bin['metaflac'] = False
141 self.bin['normalize-audio'] = False
142 self.bin['dcop'] = False
144 self.version = mp3togo.version
145 self._help_preamble = """
147 mp3togo [-p playlist] [-o output-dir] [options] [input files]
150 mp3togo is a program for converting audio files of various
151 formats into a common format suitable for use on a portable
152 mp3 player or an mp3 CD. The files to convert can be
153 specified in a playlist file (m3u, pls and plain text are
154 supported) or given as arguments to the program. mp3togo
155 will go through the list and run mpg321, ogg123, flac and
156 lame to decode and reencode the files. The newly encoded
157 files will be written to the destination directory. The
158 software can retain as much of the subdirectory structure
162 # Check for Third party modules:
163 self.mod['ogg.vorbis'] = False
164 self.mod['ID3'] = False
165 self.mod['xmms'] = False
167 # Go ahead and read in the data:
168 self.getconf(argv, conffile, readconf)
172 # All hooks are called with the lock held
173 # and must reference the ._d dict directly
174 def _post_hook(self):
175 #Set up default encoder options if not specified:
176 if not self._d['encopts']:
177 self.reset_encoder_options()
179 def _absfile(self, name, value):
180 self._d[name] = absfile(value)
182 def _units(self, name, value):
183 #Calculate raw bytes and set [max|temp|cache]size
185 if value[-1] in ('m', 'M'):
186 max = long(value[:-1]) * 1048576L
187 elif value[-1] in ('g', 'G'):
188 max = long(value[:-1]) * 1073741824L
189 elif value[-1] in ('k', 'K'):
190 max = long(value[:-1]) * 1024L
194 raise Fail, "Bad %s option: %s " % (name, value)
195 sizename = name.replace('units', 'size')
196 self._d[sizename] = max # 'maxsize'
197 self._d[name] = value # 'maxunits'
199 def _arg_files(self, name, value):
203 if os.path.exists(f):
207 def reset_encoder_options(self):
208 """Reset encoder options to defaults."""
209 if self._d['encoder'] == 'lame':
210 self._d['encopts'] = '--abr 96'
211 elif self._d['encoder'] == 'oggenc':
212 self._d['encopts'] = '-m 96 -M 225 -b 100'
213 elif self._d['encoder'] == 'wav':
214 self._d['encopts'] = ''
216 def cleanfilename(self, name):
217 """Remove nasty characters from a filename"""
218 name = name.replace('"', "'")
219 name = name.replace(':', '.')
220 name = name.replace("?", "")
221 name = name.replace('*', '')
222 name = name.replace('`', "'")
223 name = name.replace('&', '+')
224 name = name.replace(';', '.')
225 name = name.replace('#', '-')
232 name = os.path.expanduser(name)
234 name = os.path.abspath(name)
237 def getfiletype(filename):
238 """Return the format of an audio file"""
239 # Could use some more magic here
240 ft = os.path.splitext(filename)[1][1:]
241 if ft not in ('mp3', 'ogg', 'flac', 'wav'):
242 raise ErrorUnknownFileType
246 """Verify the existence of an audio file"""
247 name = name.replace('\n', '')
248 if not os.path.exists(name):
251 getfiletype(name) # Throws exception if unknown
255 """Try to print a message to a nonblocking stdout"""
258 sys.stdout.write(msg)
261 time.sleep(0.01 ** (1.0 / i))