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