Increase default video_pct to 85
[pyTivo/wgw.git] / config.py
blob73db0a471e77c20229766595f605c18bae0fd7bd
1 import ConfigParser
2 import logging
3 import logging.config
4 import os
5 import re
6 import random
7 import string
8 import sys
9 from ConfigParser import NoOptionError
11 guid = ''.join([random.choice(string.letters) for i in range(10)])
13 config = ConfigParser.ConfigParser()
15 p = os.path.dirname(__file__)
16 config_files = ['/etc/pyTivo.conf', os.path.join(p, 'pyTivo.conf')]
18 configs_found = config.read(config_files)
19 if not configs_found:
20 print ('ERROR: pyTivo.conf does not exist.\n' +
21 'You must create this file before running pyTivo.')
22 sys.exit(1)
24 def reset():
25 global config
26 newconfig = ConfigParser.ConfigParser()
27 newconfig.read(config_files)
28 config = newconfig
30 def write():
31 f = open(configs_found[-1], 'w')
32 config.write(f)
33 f.close()
35 if not config.has_section('_tivo_HD'):
36 f = open(configs_found[-1], 'a')
37 f.write('\n\n[_tivo_HD]'\
38 '\n# section for default video options applicable to all HD TiVos'\
39 '\n# see pyTivo Web Configuration for all available settings')
40 f.close()
41 reset()
43 if not config.has_section('_tivo_SD'):
44 f = open(configs_found[-1], 'a')
45 f.write('\n\n[_tivo_SD]'\
46 '\n# section for default video options applicable to all SD TiVos'\
47 '\n# see pyTivo Web Configuration for all available settings')
48 f.close()
49 reset()
52 def getGUID():
53 if config.has_option('Server', 'GUID'):
54 return config.get('Server', 'GUID')
55 else:
56 return guid
58 def getTivoUsername():
59 return config.get('Server', 'tivo_username')
61 def getTivoPassword():
62 return config.get('Server', 'tivo_password')
64 def getBeaconAddresses():
65 if config.has_option('Server', 'beacon'):
66 beacon_ips = config.get('Server', 'beacon')
67 else:
68 beacon_ips = '255.255.255.255'
69 return beacon_ips
71 def getPort():
72 return config.get('Server', 'Port')
74 def get169Blacklist(tsn): # tivo does not pad 16:9 video
75 return tsn and not isHDtivo(tsn) and not get169Letterbox(tsn)
76 # verified Blacklist Tivo's are ('130', '240', '540')
77 # It is assumed all remaining non-HD and non-Letterbox tivos are Blacklist
79 def get169Letterbox(tsn): # tivo pads 16:9 video for 4:3 display
80 return tsn and tsn[:3] in ['649']
82 def get169Setting(tsn):
83 if not tsn:
84 return True
86 tsnsect = '_tivo_' + tsn
87 if config.has_section(tsnsect):
88 if config.has_option(tsnsect, 'aspect169'):
89 try:
90 return config.getboolean(tsnsect, 'aspect169')
91 except ValueError:
92 pass
94 if get169Blacklist(tsn) or get169Letterbox(tsn):
95 return False
97 return True
99 def getShares(tsn=''):
100 shares = [(section, dict(config.items(section)))
101 for section in config.sections()
102 if not (section.startswith('_tivo_')
103 or section.startswith('logger_')
104 or section.startswith('handler_')
105 or section.startswith('formatter_')
106 or section in ('Server', 'loggers', 'handlers',
107 'formatters')
111 tsnsect = '_tivo_' + tsn
112 if config.has_section(tsnsect) and config.has_option(tsnsect, 'shares'):
113 # clean up leading and trailing spaces & make sure ref is valid
114 tsnshares = []
115 for x in config.get(tsnsect, 'shares').split(','):
116 y = x.strip()
117 if config.has_section(y):
118 tsnshares.append((y, dict(config.items(y))))
119 if tsnshares:
120 shares = tsnshares
122 return shares
124 def getDebug():
125 try:
126 return config.getboolean('Server', 'debug')
127 except NoOptionError, ValueError:
128 return False
130 def getOptres(tsn=None):
131 if tsn and config.has_section('_tivo_' + tsn):
132 try:
133 return config.getboolean('_tivo_' + tsn, 'optres')
134 except NoOptionError, ValueError:
135 pass
136 if isHDtivo(tsn):
137 try:
138 return config.getboolean('_tivo_HD', 'optres')
139 except NoOptionError, ValueError:
140 return False
141 else:
142 try:
143 return config.getboolean('_tivo_SD', 'optres')
144 except NoOptionError, ValueError:
145 return False
147 def getPixelAR(ref):
148 if config.has_option('Server', 'par'):
149 try:
150 return (True, config.getfloat('Server', 'par'))[ref]
151 except NoOptionError, ValueError:
152 pass
153 return (False, 1.0)[ref]
155 def get(section, key):
156 return config.get(section, key)
158 def getFFmpegWait():
159 if config.has_option('Server', 'ffmpeg_wait'):
160 return max(int(float(config.get('Server', 'ffmpeg_wait'))), 1)
161 else:
162 return 10
164 def getFFmpegTemplate(tsn):
165 if tsn and config.has_section('_tivo_' + tsn):
166 try:
167 return config.get('_tivo_' + tsn, 'ffmpeg_tmpl', raw=True)
168 except NoOptionError:
169 pass
170 if isHDtivo(tsn):
171 try:
172 return config.get('_tivo_HD', 'ffmpeg_tmpl', raw=True)
173 except NoOptionError:
174 pass
175 else:
176 try:
177 return config.get('_tivo_SD', 'ffmpeg_tmpl', raw=True)
178 except NoOptionError:
179 pass
180 try:
181 return config.get('Server', 'ffmpeg_tmpl', raw=True)
182 except NoOptionError: #default
183 return '%(video_codec)s %(video_fps)s %(video_br)s %(max_video_br)s \
184 %(buff_size)s %(aspect_ratio)s -comment pyTivo.py %(audio_br)s \
185 %(audio_fr)s %(audio_ch)s %(audio_codec)s %(audio_lang)s \
186 %(ffmpeg_pram)s %(format)s'
188 def getFFmpegPrams(tsn):
189 if tsn and config.has_section('_tivo_' + tsn):
190 try:
191 return config.get('_tivo_' + tsn, 'ffmpeg_pram', raw=True)
192 except NoOptionError:
193 pass
194 if isHDtivo(tsn):
195 try:
196 return config.get('_tivo_HD', 'ffmpeg_pram', raw=True)
197 except NoOptionError:
198 pass
199 else:
200 try:
201 return config.get('_tivo_SD', 'ffmpeg_pram', raw=True)
202 except NoOptionError:
203 pass
204 try:
205 return config.get('Server', 'ffmpeg_pram', raw=True)
206 except NoOptionError:
207 return None
209 def isHDtivo(tsn): # tsn's of High Definition Tivo's
210 return tsn and tsn[:3] in ['648', '652', '658']
212 def getValidWidths():
213 return [1920, 1440, 1280, 720, 704, 544, 480, 352]
215 def getValidHeights():
216 return [1080, 720, 480] # Technically 240 is also supported
218 # Return the number in list that is nearest to x
219 # if two values are equidistant, return the larger
220 def nearest(x, list):
221 return reduce(lambda a, b: closest(x, a, b), list)
223 def closest(x, a, b):
224 if abs(x - a) < abs(x - b) or (abs(x - a) == abs(x - b) and a > b):
225 return a
226 else:
227 return b
229 def nearestTivoHeight(height):
230 return nearest(height, getValidHeights())
232 def nearestTivoWidth(width):
233 return nearest(width, getValidWidths())
235 def getTivoHeight(tsn):
236 if tsn and config.has_section('_tivo_' + tsn):
237 try:
238 height = config.getint('_tivo_' + tsn, 'height')
239 return nearestTivoHeight(height)
240 except NoOptionError:
241 pass
242 if isHDtivo(tsn):
243 try:
244 height = config.getint('_tivo_HD', 'height')
245 return nearestTivoHeight(height)
246 except NoOptionError:
247 return 720
248 else:
249 try:
250 height = config.getint('_tivo_SD', 'height')
251 return nearestTivoHeight(height)
252 except NoOptionError:
253 return 480
255 def getTivoWidth(tsn):
256 if tsn and config.has_section('_tivo_' + tsn):
257 try:
258 width = config.getint('_tivo_' + tsn, 'width')
259 return nearestTivoWidth(width)
260 except NoOptionError:
261 pass
262 if isHDtivo(tsn):
263 try:
264 width = config.getint('_tivo_HD', 'width')
265 return nearestTivoWidth(width)
266 except NoOptionError:
267 return 1280
268 else:
269 try:
270 width = config.getint('_tivo_SD', 'width')
271 return nearestTivoWidth(width)
272 except NoOptionError:
273 return 544
275 def _trunc64(i):
276 return max(int(strtod(i)) / 64000, 1) * 64
278 def getAudioBR(tsn=None):
279 # convert to non-zero multiple of 64 to ensure ffmpeg compatibility
280 # compare audio_br to max_audio_br and return lowest
281 if tsn and config.has_section('_tivo_' + tsn):
282 try:
283 audiobr = _trunc64(config.get('_tivo_' + tsn, 'audio_br'))
284 return str(min(audiobr, getMaxAudioBR(tsn))) + 'k'
285 except NoOptionError:
286 pass
287 if isHDtivo(tsn):
288 try:
289 audiobr = _trunc64(config.get('_tivo_HD', 'audio_br'))
290 return str(min(audiobr, getMaxAudioBR(tsn))) + 'k'
291 except NoOptionError:
292 pass
293 else:
294 try:
295 audiobr = _trunc64(config.get('_tivo_SD', 'audio_br'))
296 return str(min(audiobr, getMaxAudioBR(tsn))) + 'k'
297 except NoOptionError:
298 pass
299 return str(min(384, getMaxAudioBR(tsn))) + 'k'
301 def _k(i):
302 return str(int(strtod(i)) / 1000) + 'k'
304 def getVideoBR(tsn=None):
305 if tsn and config.has_section('_tivo_' + tsn):
306 try:
307 return _k(config.get('_tivo_' + tsn, 'video_br'))
308 except NoOptionError:
309 pass
310 if isHDtivo(tsn):
311 try:
312 return _k(config.get('_tivo_HD', 'video_br'))
313 except NoOptionError:
314 return '16384k'
315 else:
316 try:
317 return _k(config.get('_tivo_SD', 'video_br'))
318 except NoOptionError:
319 return '4096K'
321 def getMaxVideoBR(tsn=None):
322 if tsn and config.has_section('_tivo_' + tsn):
323 try:
324 return _k(config.get('_tivo_' + tsn, 'max_video_br'))
325 except NoOptionError:
326 pass
327 if isHDtivo(tsn):
328 try:
329 return _k(config.get('_tivo_HD', 'max_video_br'))
330 except NoOptionError:
331 pass
332 else:
333 try:
334 return _k(config.get('_tivo_SD', 'max_video_br'))
335 except NoOptionError:
336 pass
337 return '30000k'
339 def getVideoPCT(tsn=None):
340 if tsn and config.has_section('_tivo_' + tsn):
341 try:
342 return config.getfloat('_tivo_' + tsn, 'video_pct')
343 except NoOptionError:
344 pass
345 if isHDtivo(tsn):
346 try:
347 return config.getfloat('_tivo_HD', 'video_pct')
348 except NoOptionError:
349 pass
350 else:
351 try:
352 return config.getfloat('_tivo_SD', 'video_pct')
353 except NoOptionError:
354 pass
355 return 85
357 def getBuffSize(tsn=None):
358 tsnsect = '_tivo_' + tsn
359 if tsn and config.has_section(tsnsect):
360 if config.has_option(tsnsect, 'bufsize'):
361 try:
362 return _k(config.get(tsnsect, 'bufsize'))
363 except NoOptionError:
364 pass
365 if isHDtivo(tsn):
366 if config.has_option('_tivo_HD', 'bufsize'):
367 try:
368 return _k(config.get('_tivo_HD', 'bufsize'))
369 except NoOptionError:
370 pass
371 return '4096k'
372 else:
373 if config.has_option('_tivo_SD', 'bufsize'):
374 try:
375 return _k(config.get('_tivo_SD', 'bufsize'))
376 except NoOptionError:
377 pass
378 return '1024k'
380 def getMaxAudioBR(tsn=None):
381 # convert to non-zero multiple of 64 for ffmpeg compatibility
382 if tsn and config.has_section('_tivo_' + tsn):
383 try:
384 return _trunc64(config.get('_tivo_' + tsn, 'max_audio_br'))
385 except NoOptionError:
386 pass
387 if isHDtivo(tsn):
388 try:
389 return _trunc64(config.get('_tivo_HD', 'max_audio_br'))
390 except NoOptionError:
391 pass
392 else:
393 try:
394 return _trunc64(config.get('_tivo_SD', 'max_audio_br'))
395 except NoOptionError:
396 pass
397 return int(448)
399 def get_tsn(name, tsn=None):
400 if tsn and config.has_section('_tivo_' + tsn):
401 try:
402 return config.get('_tivo_' + tsn, name)
403 except NoOptionError:
404 pass
405 if isHDtivo(tsn):
406 try:
407 return config.get('_tivo_HD', name)
408 except NoOptionError:
409 pass
410 else:
411 try:
412 return config.get('_tivo_SD', name)
413 except NoOptionError:
414 pass
415 return None
417 def getAudioCodec(tsn=None):
418 return get_tsn('audio_codec', tsn)
420 def getAudioCH(tsn=None):
421 return get_tsn('audio_ch', tsn)
423 def getAudioFR(tsn=None):
424 return get_tsn('audio_fr', tsn)
426 def getAudioLang(tsn=None):
427 return get_tsn('audio_lang', tsn)
429 def getCopyTS(tsn=None):
430 return get_tsn('copy_ts', tsn)
432 def getVideoFPS(tsn=None):
433 return get_tsn('video_fps', tsn)
435 def getVideoCodec(tsn=None):
436 return get_tsn('video_codec', tsn)
438 def getFormat(tsn=None):
439 return get_tsn('format', tsn)
441 # Parse a bitrate using the SI/IEEE suffix values as if by ffmpeg
442 # For example, 2K==2000, 2Ki==2048, 2MB==16000000, 2MiB==16777216
443 # Algorithm: http://svn.mplayerhq.hu/ffmpeg/trunk/libavcodec/eval.c
444 def strtod(value):
445 prefixes = {'y': -24, 'z': -21, 'a': -18, 'f': -15, 'p': -12,
446 'n': -9, 'u': -6, 'm': -3, 'c': -2, 'd': -1,
447 'h': 2, 'k': 3, 'K': 3, 'M': 6, 'G': 9,
448 'T': 12, 'P': 15, 'E': 18, 'Z': 21, 'Y': 24}
449 p = re.compile(r'^(\d+)(?:([yzafpnumcdhkKMGTPEZY])(i)?)?([Bb])?$')
450 m = p.match(value)
451 if not m:
452 raise SyntaxError('Invalid bit value syntax')
453 (coef, prefix, power, byte) = m.groups()
454 if prefix is None:
455 value = float(coef)
456 else:
457 exponent = float(prefixes[prefix])
458 if power == 'i':
459 # Use powers of 2
460 value = float(coef) * pow(2.0, exponent / 0.3)
461 else:
462 # Use powers of 10
463 value = float(coef) * pow(10.0, exponent)
464 if byte == 'B': # B == Byte, b == bit
465 value *= 8;
466 return value
468 def init_logging():
469 if (config.has_section('loggers') and
470 config.has_section('handlers') and
471 config.has_section('formatters')):
473 logging.config.fileConfig(config_files)
475 elif getDebug():
476 logging.basicConfig(level=logging.DEBUG)
477 else:
478 logging.basicConfig(level=logging.INFO)