Need this too.
[pyTivo/wgw.git] / config.py
blobff3119b68763037f9ca1c97f96dfb618b7cc6a50
1 import ConfigParser, os, sys
2 import re
3 import random
4 import string
5 from ConfigParser import NoOptionError
7 guid = ''.join([random.choice(string.letters) for i in range(10)])
9 config = ConfigParser.ConfigParser()
10 p = os.path.dirname(__file__)
12 config_files = [
13 '/etc/pyTivo.conf',
14 os.path.join(p, 'pyTivo.conf'),
16 config_exists = False
17 for config_file in config_files:
18 if os.path.exists(config_file):
19 config_exists = True
20 if not config_exists:
21 print 'ERROR: pyTivo.conf does not exist.\n' + \
22 'You must create this file before running pyTivo.'
23 sys.exit(1)
24 config.read(config_files)
26 def reset():
27 global config
28 del config
29 config = ConfigParser.ConfigParser()
30 config.read(config_files)
32 def getGUID():
33 if config.has_option('Server', 'GUID'):
34 return config.get('Server', 'GUID')
35 else:
36 return guid
38 def getTivoUsername():
39 return config.get('Server', 'tivo_username')
41 def getTivoPassword():
42 return config.get('Server', 'tivo_password')
44 def getBeaconAddresses():
45 if config.has_option('Server', 'beacon'):
46 beacon_ips = config.get('Server', 'beacon')
47 else:
48 beacon_ips = '255.255.255.255'
49 return beacon_ips
51 def getPort():
52 return config.get('Server', 'Port')
54 def get169Blacklist(tsn): # tivo does not pad 16:9 video
55 return tsn != '' and tsn[:3] in ('130', '540')
57 def get169Letterbox(tsn): # tivo pads 16:9 video for 4:3 display
58 return tsn != '' and tsn[:3] in ('649')
60 def get169Setting(tsn):
61 if not tsn:
62 return True
64 if config.has_section('_tivo_' + tsn):
65 if config.has_option('_tivo_' + tsn, 'aspect169'):
66 try:
67 return config.getboolean('_tivo_' + tsn, 'aspect169')
68 except ValueError:
69 pass
71 if get169Blacklist(tsn) or get169Letterbox(tsn):
72 return False
74 return True
76 def getShares(tsn=''):
77 shares = [(section, dict(config.items(section)))
78 for section in config.sections()
79 if not (
80 section.startswith('_tivo_')
81 or section in ('Server', 'loggers', 'handlers', 'formatters')
82 or section.startswith('logger_')
83 or section.startswith('handler_')
84 or section.startswith('formatter_')
88 if config.has_section('_tivo_' + tsn):
89 if config.has_option('_tivo_' + tsn, 'shares'):
90 # clean up leading and trailing spaces & make sure ref is valid
91 tsnshares = []
92 for x in config.get('_tivo_' + tsn, 'shares').split(','):
93 y = x.lstrip().rstrip()
94 if config.has_section(y):
95 tsnshares += [(y, dict(config.items(y)))]
96 if tsnshares:
97 shares = tsnshares
99 for name, data in shares:
100 if not data.get('auto_subshares', 'False').lower() == 'true':
101 continue
103 base_path = data['path']
104 try:
105 for item in os.listdir(base_path):
106 item_path = os.path.join(base_path, item)
107 if not os.path.isdir(item_path) or item.startswith('.'):
108 continue
110 new_name = name + '/' + item
111 new_data = dict(data)
112 new_data['path'] = item_path
114 shares.append((new_name, new_data))
115 except:
116 pass
118 return shares
120 def getDebug():
121 try:
122 return config.getboolean('Server', 'debug')
123 except NoOptionError, ValueError:
124 return False
126 def getHack83():
127 try:
128 return config.getboolean('Server', 'hack83')
129 except NoOptionError, ValueError:
130 return False
132 def getOptres(tsn = None):
133 if tsn and config.has_section('_tivo_' + tsn):
134 try:
135 return config.getboolean('_tivo_' + tsn, 'optres')
136 except NoOptionError, ValueError:
137 pass
138 try:
139 return config.getboolean('Server', 'optres')
140 except NoOptionError, ValueError:
141 return False
143 def getPixelAR(ref):
144 if config.has_option('Server', 'par'):
145 try:
146 return (True, config.getfloat('Server', 'par'))[ref]
147 except NoOptionError, ValueError:
148 pass
149 return (False, 1.0)[ref]
151 def get(section, key):
152 return config.get(section, key)
154 def getFFmpegTemplate(tsn):
155 if tsn and config.has_section('_tivo_' + tsn):
156 try:
157 return config.get('_tivo_' + tsn, 'ffmpeg_tmpl', raw=True)
158 except NoOptionError:
159 pass
160 try:
161 return config.get('Server', 'ffmpeg_tmpl', raw=True)
162 except NoOptionError: #default
163 return '%(video_codec)s %(video_fps)s %(video_br)s %(max_video_br)s \
164 %(buff_size)s %(aspect_ratio)s -comment pyTivo.py %(audio_br)s \
165 %(audio_fr)s %(audio_ch)s %(audio_codec)s %(audio_lang)s \
166 %(ffmpeg_pram)s %(format)s'
168 def getFFmpegPrams(tsn):
169 if tsn and config.has_section('_tivo_' + tsn):
170 try:
171 return config.get('_tivo_' + tsn, 'ffmpeg_pram', raw=True)
172 except NoOptionError:
173 pass
174 try:
175 return config.get('Server', 'ffmpeg_pram', raw=True)
176 except NoOptionError:
177 return None
179 def isHDtivo(tsn): # tsn's of High Definition Tivo's
180 return tsn != '' and tsn[:3] in ['648', '652']
182 def getValidWidths():
183 return [1920, 1440, 1280, 720, 704, 544, 480, 352]
185 def getValidHeights():
186 return [1080, 720, 480] # Technically 240 is also supported
188 # Return the number in list that is nearest to x
189 # if two values are equidistant, return the larger
190 def nearest(x, list):
191 return reduce(lambda a, b: closest(x, a, b), list)
193 def closest(x, a, b):
194 if abs(x - a) < abs(x - b) or (abs(x - a) == abs(x - b) and a > b):
195 return a
196 else:
197 return b
199 def nearestTivoHeight(height):
200 return nearest(height, getValidHeights())
202 def nearestTivoWidth(width):
203 return nearest(width, getValidWidths())
205 def getTivoHeight(tsn):
206 if tsn and config.has_section('_tivo_' + tsn):
207 try:
208 height = config.getint('_tivo_' + tsn, 'height')
209 return nearestTivoHeight(height)
210 except NoOptionError:
211 pass
212 try:
213 height = config.getint('Server', 'height')
214 return nearestTivoHeight(height)
215 except NoOptionError: #defaults for S3/S2 TiVo
216 if isHDtivo(tsn):
217 return 720
218 else:
219 return 480
221 def getTivoWidth(tsn):
222 if tsn and config.has_section('_tivo_' + tsn):
223 try:
224 width = config.getint('_tivo_' + tsn, 'width')
225 return nearestTivoWidth(width)
226 except NoOptionError:
227 pass
228 try:
229 width = config.getint('Server', 'width')
230 return nearestTivoWidth(width)
231 except NoOptionError: #defaults for S3/S2 TiVo
232 if isHDtivo(tsn):
233 return 1280
234 else:
235 return 544
237 def getAudioBR(tsn = None):
238 #convert to non-zero multiple of 64 to ensure ffmpeg compatibility
239 #compare audio_br to max_audio_br and return lowest
240 if tsn and config.has_section('_tivo_' + tsn):
241 try:
242 audiobr = int(max(int(strtod(config.get('_tivo_' + tsn, 'audio_br'))/1000), 64)/64)*64
243 return str(min(audiobr, getMaxAudioBR(tsn))) + 'k'
244 except NoOptionError:
245 pass
246 try:
247 audiobr = int(max(int(strtod(config.get('Server', 'audio_br'))/1000), 64)/64)*64
248 return str(min(audiobr, getMaxAudioBR(tsn))) + 'k'
249 except NoOptionError:
250 return str(min(384, getMaxAudioBR(tsn))) + 'k'
252 def getVideoBR(tsn = None):
253 if tsn and config.has_section('_tivo_' + tsn):
254 try:
255 return str(int(strtod(config.get('_tivo_' + tsn, 'video_br'))/1000)) + 'k'
256 except NoOptionError:
257 pass
258 try:
259 return str(int(strtod(config.get('Server', 'video_br'))/1000)) + 'k'
260 except NoOptionError: #defaults for S3/S2 TiVo
261 if isHDtivo(tsn):
262 return '8192k'
263 else:
264 return '4096K'
266 def getMaxVideoBR():
267 try:
268 return str(int(strtod(config.get('Server', 'max_video_br'))/1000)) + 'k'
269 except NoOptionError: #default to 30000k
270 return '30000k'
272 def getVideoPCT():
273 try:
274 return config.getfloat('Server', 'video_pct')
275 except NoOptionError:
276 return 70
278 def getBuffSize():
279 try:
280 return str(int(strtod(config.get('Server', 'bufsize'))/1000)) + 'k'
281 except NoOptionError: #default 1024k
282 return '1024k'
284 def getMaxAudioBR(tsn = None):
285 #convert to non-zero multiple of 64 for ffmpeg compatibility
286 if tsn and config.has_section('_tivo_' + tsn):
287 try:
288 return int(int(strtod(config.get('_tivo_' + tsn, 'max_audio_br'))/1000)/64)*64
289 except NoOptionError:
290 pass
291 try:
292 return int(int(strtod(config.get('Server', 'max_audio_br'))/1000)/64)*64
293 except NoOptionError:
294 return int(448) #default to 448
296 def get_tsn(name, tsn=None):
297 if tsn and config.has_section('_tivo_' + tsn):
298 try:
299 return config.get('_tivo_' + tsn, name)
300 except NoOptionError:
301 pass
302 try:
303 return config.get('Server', name)
304 except NoOptionError:
305 return None
307 def getAudioCodec(tsn=None):
308 return get_tsn('audio_codec', tsn)
310 def getAudioCH(tsn=None):
311 return get_tsn('audio_ch', tsn)
313 def getAudioFR(tsn=None):
314 return get_tsn('audio_fr', tsn)
316 def getAudioLang(tsn=None):
317 return get_tsn('audio_lang', tsn)
319 def getCopyTS(tsn = None):
320 if tsn and config.has_section('_tivo_' + tsn):
321 if config.has_option('_tivo_' + tsn, 'copy_ts'):
322 try:
323 return config.get('_tivo_' + tsn, 'copy_ts')
324 except NoOptionError, ValueError:
325 pass
326 if config.has_option('Server', 'copy_ts'):
327 try:
328 return config.get('Server', 'copy_ts')
329 except NoOptionError, ValueError:
330 pass
331 return 'none'
333 def getVideoFPS(tsn=None):
334 return get_tsn('video_fps', tsn)
336 def getVideoCodec(tsn=None):
337 return get_tsn('video_codec', tsn)
339 def getFormat(tsn = None):
340 return get_tsn('format', tsn)
342 # Parse a bitrate using the SI/IEEE suffix values as if by ffmpeg
343 # For example, 2K==2000, 2Ki==2048, 2MB==16000000, 2MiB==16777216
344 # Algorithm: http://svn.mplayerhq.hu/ffmpeg/trunk/libavcodec/eval.c
345 def strtod(value):
346 prefixes = {'y': -24, 'z': -21, 'a': -18, 'f': -15, 'p': -12,
347 'n': -9, 'u': -6, 'm': -3, 'c': -2, 'd': -1,
348 'h': 2, 'k': 3, 'K': 3, 'M': 6, 'G': 9,
349 'T': 12, 'P': 15, 'E': 18, 'Z': 21, 'Y': 24}
350 p = re.compile(r'^(\d+)(?:([yzafpnumcdhkKMGTPEZY])(i)?)?([Bb])?$')
351 m = p.match(value)
352 if m is None:
353 raise SyntaxError('Invalid bit value syntax')
354 (coef, prefix, power, byte) = m.groups()
355 if prefix is None:
356 value = float(coef)
357 else:
358 exponent = float(prefixes[prefix])
359 if power == 'i':
360 # Use powers of 2
361 value = float(coef) * pow(2.0, exponent / 0.3)
362 else:
363 # Use powers of 10
364 value = float(coef) * pow(10.0, exponent)
365 if byte == 'B': # B == Byte, b == bit
366 value *= 8;
367 return value