Use the now-blank column to show TotalItems, as on the TiVo. This could
[pyTivo/wgw.git] / config.py
blob0e59821fdccf50c7cbd2875389802a540a6f59da
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(ref):
122 if config.has_option('Server', 'debug'):
123 try:
124 return str2tuple(config.get('Server', 'debug')+',,')[ref]
125 except NoOptionError:
126 pass
127 return str2tuple('False,,')[ref]
129 def getHack83():
130 try:
131 debug = config.get('Server', 'hack83')
132 if debug.lower() == 'true':
133 return True
134 else:
135 return False
136 except NoOptionError:
137 return False
139 def getOptres(tsn = None):
140 if tsn and config.has_section('_tivo_' + tsn):
141 try:
142 return config.getboolean('_tivo_' + tsn, 'optres')
143 except NoOptionError, ValueError:
144 pass
145 try:
146 return config.getboolean('Server', 'optres')
147 except NoOptionError, ValueError:
148 return False
150 def getPixelAR(ref):
151 if config.has_option('Server', 'par'):
152 try:
153 return (True, config.getfloat('Server', 'par'))[ref]
154 except NoOptionError, ValueError:
155 pass
156 return (False, 1.0)[ref]
158 def get(section, key):
159 return config.get(section, key)
161 def getFFmpegTemplate(tsn):
162 if tsn and config.has_section('_tivo_' + tsn):
163 try:
164 return config.get('_tivo_' + tsn, 'ffmpeg_tmpl', raw=True)
165 except NoOptionError:
166 pass
167 try:
168 return config.get('Server', 'ffmpeg_tmpl', raw=True)
169 except NoOptionError: #default
170 return '%(video_codec)s %(video_fps)s %(video_br)s %(max_video_br)s \
171 %(buff_size)s %(aspect_ratio)s -comment pyTivo.py %(audio_br)s \
172 %(audio_fr)s %(audio_ch)s %(audio_codec)s %(audio_lang)s \
173 %(ffmpeg_pram)s %(format)s'
175 def getFFmpegPrams(tsn):
176 if tsn and config.has_section('_tivo_' + tsn):
177 try:
178 return config.get('_tivo_' + tsn, 'ffmpeg_pram', raw=True)
179 except NoOptionError:
180 pass
181 try:
182 return config.get('Server', 'ffmpeg_pram', raw=True)
183 except NoOptionError:
184 return None
186 def isHDtivo(tsn): # tsn's of High Definition Tivo's
187 return tsn != '' and tsn[:3] in ['648', '652']
189 def getValidWidths():
190 return [1920, 1440, 1280, 720, 704, 544, 480, 352]
192 def getValidHeights():
193 return [1080, 720, 480] # Technically 240 is also supported
195 # Return the number in list that is nearest to x
196 # if two values are equidistant, return the larger
197 def nearest(x, list):
198 return reduce(lambda a, b: closest(x, a, b), list)
200 def closest(x, a, b):
201 if abs(x - a) < abs(x - b) or (abs(x - a) == abs(x - b) and a > b):
202 return a
203 else:
204 return b
206 def nearestTivoHeight(height):
207 return nearest(height, getValidHeights())
209 def nearestTivoWidth(width):
210 return nearest(width, getValidWidths())
212 def getTivoHeight(tsn):
213 if tsn and config.has_section('_tivo_' + tsn):
214 try:
215 height = config.getint('_tivo_' + tsn, 'height')
216 return nearestTivoHeight(height)
217 except NoOptionError:
218 pass
219 try:
220 height = config.getint('Server', 'height')
221 return nearestTivoHeight(height)
222 except NoOptionError: #defaults for S3/S2 TiVo
223 if isHDtivo(tsn):
224 return 720
225 else:
226 return 480
228 def getTivoWidth(tsn):
229 if tsn and config.has_section('_tivo_' + tsn):
230 try:
231 width = config.getint('_tivo_' + tsn, 'width')
232 return nearestTivoWidth(width)
233 except NoOptionError:
234 pass
235 try:
236 width = config.getint('Server', 'width')
237 return nearestTivoWidth(width)
238 except NoOptionError: #defaults for S3/S2 TiVo
239 if isHDtivo(tsn):
240 return 1280
241 else:
242 return 544
244 def getAudioBR(tsn = None):
245 #convert to non-zero multiple of 64 to ensure ffmpeg compatibility
246 #compare audio_br to max_audio_br and return lowest
247 if tsn and config.has_section('_tivo_' + tsn):
248 try:
249 audiobr = int(max(int(strtod(config.get('_tivo_' + tsn, 'audio_br'))/1000), 64)/64)*64
250 return str(min(audiobr, getMaxAudioBR(tsn))) + 'k'
251 except NoOptionError:
252 pass
253 try:
254 audiobr = int(max(int(strtod(config.get('Server', 'audio_br'))/1000), 64)/64)*64
255 return str(min(audiobr, getMaxAudioBR(tsn))) + 'k'
256 except NoOptionError:
257 return str(min(384, getMaxAudioBR(tsn))) + 'k'
259 def getVideoBR(tsn = None):
260 if tsn and config.has_section('_tivo_' + tsn):
261 try:
262 return str(int(strtod(config.get('_tivo_' + tsn, 'video_br'))/1000)) + 'k'
263 except NoOptionError:
264 pass
265 try:
266 return str(int(strtod(config.get('Server', 'video_br'))/1000)) + 'k'
267 except NoOptionError: #defaults for S3/S2 TiVo
268 if isHDtivo(tsn):
269 return '8192k'
270 else:
271 return '4096K'
273 def getMaxVideoBR():
274 try:
275 return str(int(strtod(config.get('Server', 'max_video_br'))/1000)) + 'k'
276 except NoOptionError: #default to 30000k
277 return '30000k'
279 def getVideoPCT():
280 try:
281 return config.getfloat('Server', 'video_pct')
282 except NoOptionError:
283 return 70
285 def getBuffSize():
286 try:
287 return str(int(strtod(config.get('Server', 'bufsize'))/1000)) + 'k'
288 except NoOptionError: #default 1024k
289 return '1024k'
291 def getMaxAudioBR(tsn = None):
292 #convert to non-zero multiple of 64 for ffmpeg compatibility
293 if tsn and config.has_section('_tivo_' + tsn):
294 try:
295 return int(int(strtod(config.get('_tivo_' + tsn, 'max_audio_br'))/1000)/64)*64
296 except NoOptionError:
297 pass
298 try:
299 return int(int(strtod(config.get('Server', 'max_audio_br'))/1000)/64)*64
300 except NoOptionError:
301 return int(448) #default to 448
303 def getAudioCodec(tsn = None):
304 if tsn and config.has_section('_tivo_' + tsn):
305 try:
306 return config.get('_tivo_' + tsn, 'audio_codec')
307 except NoOptionError:
308 pass
309 try:
310 return config.get('Server', 'audio_codec')
311 except NoOptionError:
312 return None
314 def getAudioCH(tsn = None):
315 if tsn and config.has_section('_tivo_' + tsn):
316 try:
317 return config.get('_tivo_' + tsn, 'audio_ch')
318 except NoOptionError:
319 pass
320 try:
321 return config.get('Server', 'audio_ch')
322 except NoOptionError:
323 return None
325 def getAudioFR(tsn = None):
326 if tsn and config.has_section('_tivo_' + tsn):
327 try:
328 return config.get('_tivo_' + tsn, 'audio_fr')
329 except NoOptionError:
330 pass
331 try:
332 return config.get('Server', 'audio_fr')
333 except NoOptionError:
334 return None
336 def getAudioLang(tsn = None):
337 if tsn and config.has_section('_tivo_' + tsn):
338 try:
339 return config.get('_tivo_' + tsn, 'audio_lang')
340 except NoOptionError:
341 pass
342 try:
343 return config.get('Server', 'audio_lang')
344 except NoOptionError:
345 return None
347 def getCopyTS(tsn = None):
348 if tsn and config.has_section('_tivo_' + tsn):
349 if config.has_option('_tivo_' + tsn, 'copy_ts'):
350 try:
351 return config.get('_tivo_' + tsn, 'copy_ts')
352 except NoOptionError, ValueError:
353 pass
354 if config.has_option('Server', 'copy_ts'):
355 try:
356 return config.get('Server', 'copy_ts')
357 except NoOptionError, ValueError:
358 pass
359 return 'none'
361 def getVideoFPS(tsn = None):
362 if tsn and config.has_section('_tivo_' + tsn):
363 try:
364 return config.get('_tivo_' + tsn, 'video_fps')
365 except NoOptionError:
366 pass
367 try:
368 return config.get('Server', 'video_fps')
369 except NoOptionError:
370 return None
372 def getVideoCodec(tsn = None):
373 if tsn and config.has_section('_tivo_' + tsn):
374 try:
375 return config.get('_tivo_' + tsn, 'video_codec')
376 except NoOptionError:
377 pass
378 try:
379 return config.get('Server', 'video_codec')
380 except NoOptionError:
381 return None
383 def getFormat(tsn = None):
384 if tsn and config.has_section('_tivo_' + tsn):
385 try:
386 return config.get('_tivo_' + tsn, 'force_format')
387 except NoOptionError:
388 pass
389 try:
390 return config.get('Server', 'force_format')
391 except NoOptionError:
392 return None
394 def str2tuple(s):
395 items = s.split(',')
396 L = [x.strip() for x in items]
397 return tuple(L)
399 # Parse a bitrate using the SI/IEEE suffix values as if by ffmpeg
400 # For example, 2K==2000, 2Ki==2048, 2MB==16000000, 2MiB==16777216
401 # Algorithm: http://svn.mplayerhq.hu/ffmpeg/trunk/libavcodec/eval.c
402 def strtod(value):
403 prefixes = {'y': -24, 'z': -21, 'a': -18, 'f': -15, 'p': -12,
404 'n': -9, 'u': -6, 'm': -3, 'c': -2, 'd': -1,
405 'h': 2, 'k': 3, 'K': 3, 'M': 6, 'G': 9,
406 'T': 12, 'P': 15, 'E': 18, 'Z': 21, 'Y': 24}
407 p = re.compile(r'^(\d+)(?:([yzafpnumcdhkKMGTPEZY])(i)?)?([Bb])?$')
408 m = p.match(value)
409 if m is None:
410 raise SyntaxError('Invalid bit value syntax')
411 (coef, prefix, power, byte) = m.groups()
412 if prefix is None:
413 value = float(coef)
414 else:
415 exponent = float(prefixes[prefix])
416 if power == 'i':
417 # Use powers of 2
418 value = float(coef) * pow(2.0, exponent / 0.3)
419 else:
420 # Use powers of 10
421 value = float(coef) * pow(10.0, exponent)
422 if byte == 'B': # B == Byte, b == bit
423 value *= 8;
424 return value