Per-TiVo buffer size, per wgw.
[pyTivo/wgw.git] / config.py
blob9a435fb61e3b7468a9b52a035b021aef129251bc
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', '240', '540')) or (not isHDtivo(tsn) and not get169Letterbox(tsn))
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', '658']
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 _trunc64(i):
238 return max(int(strtod(i)) / 64000, 1) * 64
240 def getAudioBR(tsn = None):
241 #convert to non-zero multiple of 64 to ensure ffmpeg compatibility
242 #compare audio_br to max_audio_br and return lowest
243 if tsn and config.has_section('_tivo_' + tsn):
244 try:
245 audiobr = _trunc64(config.get('_tivo_' + tsn, 'audio_br'))
246 return str(min(audiobr, getMaxAudioBR(tsn))) + 'k'
247 except NoOptionError:
248 pass
249 try:
250 audiobr = _trunc64(config.get('Server', 'audio_br'))
251 return str(min(audiobr, getMaxAudioBR(tsn))) + 'k'
252 except NoOptionError:
253 return str(min(384, getMaxAudioBR(tsn))) + 'k'
255 def _k(i):
256 return str(int(strtod(i)) / 1000) + 'k'
258 def getVideoBR(tsn = None):
259 if tsn and config.has_section('_tivo_' + tsn):
260 try:
261 return _k(config.get('_tivo_' + tsn, 'video_br'))
262 except NoOptionError:
263 pass
264 try:
265 return _k(config.get('Server', 'video_br'))
266 except NoOptionError: #defaults for S3/S2 TiVo
267 if isHDtivo(tsn):
268 return '8192k'
269 else:
270 return '4096K'
272 def getMaxVideoBR():
273 try:
274 return _k(config.get('Server', 'max_video_br'))
275 except NoOptionError: #default to 30000k
276 return '30000k'
278 def getVideoPCT():
279 try:
280 return config.getfloat('Server', 'video_pct')
281 except NoOptionError:
282 return 70
284 def getBuffSize(tsn = None):
285 if tsn and config.has_section('_tivo_' + tsn):
286 if config.has_option('_tivo_' + tsn, 'bufsize'):
287 try:
288 return _k(config.get('_tivo_' + tsn, 'bufsize'))
289 except NoOptionError:
290 pass
291 if config.has_option('Server', 'bufsize'):
292 try:
293 return _k(config.get('Server', 'bufsize'))
294 except NoOptionError:
295 pass
296 if isHDtivo(tsn):
297 return '4096k'
298 else:
299 return '1024k'
301 def getMaxAudioBR(tsn = None):
302 #convert to non-zero multiple of 64 for ffmpeg compatibility
303 if tsn and config.has_section('_tivo_' + tsn):
304 try:
305 return _trunc64(config.get('_tivo_' + tsn, 'max_audio_br'))
306 except NoOptionError:
307 pass
308 try:
309 return _trunc64(config.get('Server', 'max_audio_br'))
310 except NoOptionError:
311 return int(448) #default to 448
313 def get_tsn(name, tsn=None):
314 if tsn and config.has_section('_tivo_' + tsn):
315 try:
316 return config.get('_tivo_' + tsn, name)
317 except NoOptionError:
318 pass
319 try:
320 return config.get('Server', name)
321 except NoOptionError:
322 return None
324 def getAudioCodec(tsn=None):
325 return get_tsn('audio_codec', tsn)
327 def getAudioCH(tsn=None):
328 return get_tsn('audio_ch', tsn)
330 def getAudioFR(tsn=None):
331 return get_tsn('audio_fr', tsn)
333 def getAudioLang(tsn=None):
334 return get_tsn('audio_lang', tsn)
336 def getCopyTS(tsn = None):
337 if tsn and config.has_section('_tivo_' + tsn):
338 if config.has_option('_tivo_' + tsn, 'copy_ts'):
339 try:
340 return config.get('_tivo_' + tsn, 'copy_ts')
341 except NoOptionError, ValueError:
342 pass
343 if config.has_option('Server', 'copy_ts'):
344 try:
345 return config.get('Server', 'copy_ts')
346 except NoOptionError, ValueError:
347 pass
348 return 'none'
350 def getVideoFPS(tsn=None):
351 return get_tsn('video_fps', tsn)
353 def getVideoCodec(tsn=None):
354 return get_tsn('video_codec', tsn)
356 def getFormat(tsn = None):
357 return get_tsn('format', tsn)
359 # Parse a bitrate using the SI/IEEE suffix values as if by ffmpeg
360 # For example, 2K==2000, 2Ki==2048, 2MB==16000000, 2MiB==16777216
361 # Algorithm: http://svn.mplayerhq.hu/ffmpeg/trunk/libavcodec/eval.c
362 def strtod(value):
363 prefixes = {'y': -24, 'z': -21, 'a': -18, 'f': -15, 'p': -12,
364 'n': -9, 'u': -6, 'm': -3, 'c': -2, 'd': -1,
365 'h': 2, 'k': 3, 'K': 3, 'M': 6, 'G': 9,
366 'T': 12, 'P': 15, 'E': 18, 'Z': 21, 'Y': 24}
367 p = re.compile(r'^(\d+)(?:([yzafpnumcdhkKMGTPEZY])(i)?)?([Bb])?$')
368 m = p.match(value)
369 if m is None:
370 raise SyntaxError('Invalid bit value syntax')
371 (coef, prefix, power, byte) = m.groups()
372 if prefix is None:
373 value = float(coef)
374 else:
375 exponent = float(prefixes[prefix])
376 if power == 'i':
377 # Use powers of 2
378 value = float(coef) * pow(2.0, exponent / 0.3)
379 else:
380 # Use powers of 10
381 value = float(coef) * pow(10.0, exponent)
382 if byte == 'B': # B == Byte, b == bit
383 value *= 8;
384 return value