Accomodate the absence of the '_tivo_HD' and '_tivo_SD' sections in the
[pyTivo/wmcbrine.git] / config.py
blob41a79bdf86093b6ea2a478c5eb2de44bde0c1dc7
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 def getGUID():
36 if config.has_option('Server', 'GUID'):
37 return config.get('Server', 'GUID')
38 else:
39 return guid
41 def getTivoUsername():
42 return config.get('Server', 'tivo_username')
44 def getTivoPassword():
45 return config.get('Server', 'tivo_password')
47 def getBeaconAddresses():
48 if config.has_option('Server', 'beacon'):
49 beacon_ips = config.get('Server', 'beacon')
50 else:
51 beacon_ips = '255.255.255.255'
52 return beacon_ips
54 def getPort():
55 return config.get('Server', 'Port')
57 def get169Blacklist(tsn): # tivo does not pad 16:9 video
58 return tsn and not isHDtivo(tsn) and not get169Letterbox(tsn)
59 # verified Blacklist Tivo's are ('130', '240', '540')
60 # It is assumed all remaining non-HD and non-Letterbox tivos are Blacklist
62 def get169Letterbox(tsn): # tivo pads 16:9 video for 4:3 display
63 return tsn and tsn[:3] in ['649']
65 def get169Setting(tsn):
66 if not tsn:
67 return True
69 tsnsect = '_tivo_' + tsn
70 if config.has_section(tsnsect):
71 if config.has_option(tsnsect, 'aspect169'):
72 try:
73 return config.getboolean(tsnsect, 'aspect169')
74 except ValueError:
75 pass
77 if get169Blacklist(tsn) or get169Letterbox(tsn):
78 return False
80 return True
82 def getShares(tsn=''):
83 shares = [(section, dict(config.items(section)))
84 for section in config.sections()
85 if not (section.startswith('_tivo_')
86 or section.startswith('logger_')
87 or section.startswith('handler_')
88 or section.startswith('formatter_')
89 or section in ('Server', 'loggers', 'handlers',
90 'formatters')
94 tsnsect = '_tivo_' + tsn
95 if config.has_section(tsnsect) and config.has_option(tsnsect, 'shares'):
96 # clean up leading and trailing spaces & make sure ref is valid
97 tsnshares = []
98 for x in config.get(tsnsect, 'shares').split(','):
99 y = x.strip()
100 if config.has_section(y):
101 tsnshares.append((y, dict(config.items(y))))
102 if tsnshares:
103 shares = tsnshares
105 return shares
107 def getDebug():
108 try:
109 return config.getboolean('Server', 'debug')
110 except NoOptionError, ValueError:
111 return False
113 def getOptres(tsn=None):
114 if tsn and config.has_section('_tivo_' + tsn):
115 try:
116 return config.getboolean('_tivo_' + tsn, 'optres')
117 except NoOptionError, ValueError:
118 pass
119 section_name = get_section(tsn)
120 if config.has_section(section_name):
121 try:
122 return config.getboolean(section_name, 'optres')
123 except NoOptionError, ValueError:
124 pass
125 try:
126 return config.getboolean('Server', 'optres')
127 except NoOptionError, ValueError:
128 return False
130 def getPixelAR(ref):
131 if config.has_option('Server', 'par'):
132 try:
133 return (True, config.getfloat('Server', 'par'))[ref]
134 except NoOptionError, ValueError:
135 pass
136 return (False, 1.0)[ref]
138 def get(section, key):
139 return config.get(section, key)
141 def getFFmpegWait():
142 if config.has_option('Server', 'ffmpeg_wait'):
143 return max(int(float(config.get('Server', 'ffmpeg_wait'))), 1)
144 else:
145 return 10
147 def getFFmpegTemplate(tsn):
148 if tsn and config.has_section('_tivo_' + tsn):
149 try:
150 return config.get('_tivo_' + tsn, 'ffmpeg_tmpl', raw=True)
151 except NoOptionError:
152 pass
153 section_name = get_section(tsn)
154 if config.has_section(section_name):
155 try:
156 return config.get(section_name, 'ffmpeg_tmpl', raw=True)
157 except NoOptionError:
158 pass
159 try:
160 return config.get('Server', 'ffmpeg_tmpl', raw=True)
161 except NoOptionError: #default
162 return '%(video_codec)s %(video_fps)s %(video_br)s %(max_video_br)s \
163 %(buff_size)s %(aspect_ratio)s -comment pyTivo.py %(audio_br)s \
164 %(audio_fr)s %(audio_ch)s %(audio_codec)s %(audio_lang)s \
165 %(ffmpeg_pram)s %(format)s'
167 def getFFmpegPrams(tsn):
168 if tsn and config.has_section('_tivo_' + tsn):
169 try:
170 return config.get('_tivo_' + tsn, 'ffmpeg_pram', raw=True)
171 except NoOptionError:
172 pass
173 section_name = get_section(tsn)
174 if config.has_section(section_name):
175 try:
176 return config.get(section_name, '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 bool(tsn and tsn[:3] in ['648', '652', '658'])
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 section_name = get_section(tsn)
218 if config.has_section(section_name):
219 try:
220 height = config.getint(section_name, 'height')
221 return nearestTivoHeight(height)
222 except NoOptionError:
223 pass
224 try:
225 width = config.getint('Server', 'height')
226 return nearestTivoHeight(height)
227 except NoOptionError:
228 pass
229 return [480, 720][isHDtivo(tsn)]
231 def getTivoWidth(tsn):
232 if tsn and config.has_section('_tivo_' + tsn):
233 try:
234 width = config.getint('_tivo_' + tsn, 'width')
235 return nearestTivoWidth(width)
236 except NoOptionError:
237 pass
238 section_name = get_section(tsn)
239 if config.has_section(section_name):
240 try:
241 width = config.getint(section_name, 'width')
242 return nearestTivoWidth(width)
243 except NoOptionError:
244 pass
245 try:
246 width = config.getint('Server', 'width')
247 return nearestTivoWidth(width)
248 except NoOptionError:
249 pass
250 return [544, 1280][isHDtivo(tsn)]
252 def _trunc64(i):
253 return max(int(strtod(i)) / 64000, 1) * 64
255 def getAudioBR(tsn=None):
256 rate = get_tsn('audio_br', tsn)
257 if not rate:
258 rate = '448k'
259 # convert to non-zero multiple of 64 to ensure ffmpeg compatibility
260 # compare audio_br to max_audio_br and return lowest
261 return str(min(_trunc64(rate), getMaxAudioBR(tsn))) + 'k'
263 def _k(i):
264 return str(int(strtod(i)) / 1000) + 'k'
266 def getVideoBR(tsn=None):
267 rate = get_tsn('video_br', tsn)
268 if rate:
269 return _k(rate)
270 return ['4096K', '16384K'][isHDtivo(tsn)]
272 def getMaxVideoBR(tsn=None):
273 rate = get_tsn('max_video_br', tsn)
274 if rate:
275 return _k(rate)
276 return '30000k'
278 def getVideoPCT(tsn=None):
279 if tsn and config.has_section('_tivo_' + tsn):
280 try:
281 return config.getfloat('_tivo_' + tsn, 'video_pct')
282 except NoOptionError:
283 pass
284 section_name = get_section(tsn)
285 if config.has_section(section_name):
286 try:
287 return config.getfloat(section_name, 'video_pct')
288 except NoOptionError:
289 pass
290 try:
291 return config.getfloat('Server', 'video_pct')
292 except NoOptionError:
293 pass
294 return 85
296 def getBuffSize(tsn=None):
297 size = get_tsn('bufsize', tsn)
298 if size:
299 return _k(size)
300 return ['1024k', '4096k'][isHDtivo(tsn)]
302 def getMaxAudioBR(tsn=None):
303 rate = get_tsn('max_audio_br', tsn)
304 # convert to non-zero multiple of 64 for ffmpeg compatibility
305 if rate:
306 return _trunc64(rate)
307 return 448
309 def get_section(tsn):
310 return ['_tivo_SD', '_tivo_HD'][isHDtivo(tsn)]
312 def get_tsn(name, tsn=None):
313 if tsn and config.has_section('_tivo_' + tsn):
314 try:
315 return config.get('_tivo_' + tsn, name)
316 except NoOptionError:
317 pass
318 section_name = get_section(tsn)
319 if config.has_section(section_name):
320 try:
321 return config.get(section_name, name)
322 except NoOptionError:
323 pass
324 try:
325 return config.get('Server', name)
326 except NoOptionError:
327 pass
328 return None
330 def getAudioCodec(tsn=None):
331 return get_tsn('audio_codec', tsn)
333 def getAudioCH(tsn=None):
334 return get_tsn('audio_ch', tsn)
336 def getAudioFR(tsn=None):
337 return get_tsn('audio_fr', tsn)
339 def getAudioLang(tsn=None):
340 return get_tsn('audio_lang', tsn)
342 def getCopyTS(tsn=None):
343 return get_tsn('copy_ts', tsn)
345 def getVideoFPS(tsn=None):
346 return get_tsn('video_fps', tsn)
348 def getVideoCodec(tsn=None):
349 return get_tsn('video_codec', tsn)
351 def getFormat(tsn=None):
352 return get_tsn('format', tsn)
354 # Parse a bitrate using the SI/IEEE suffix values as if by ffmpeg
355 # For example, 2K==2000, 2Ki==2048, 2MB==16000000, 2MiB==16777216
356 # Algorithm: http://svn.mplayerhq.hu/ffmpeg/trunk/libavcodec/eval.c
357 def strtod(value):
358 prefixes = {'y': -24, 'z': -21, 'a': -18, 'f': -15, 'p': -12,
359 'n': -9, 'u': -6, 'm': -3, 'c': -2, 'd': -1,
360 'h': 2, 'k': 3, 'K': 3, 'M': 6, 'G': 9,
361 'T': 12, 'P': 15, 'E': 18, 'Z': 21, 'Y': 24}
362 p = re.compile(r'^(\d+)(?:([yzafpnumcdhkKMGTPEZY])(i)?)?([Bb])?$')
363 m = p.match(value)
364 if not m:
365 raise SyntaxError('Invalid bit value syntax')
366 (coef, prefix, power, byte) = m.groups()
367 if prefix is None:
368 value = float(coef)
369 else:
370 exponent = float(prefixes[prefix])
371 if power == 'i':
372 # Use powers of 2
373 value = float(coef) * pow(2.0, exponent / 0.3)
374 else:
375 # Use powers of 10
376 value = float(coef) * pow(10.0, exponent)
377 if byte == 'B': # B == Byte, b == bit
378 value *= 8;
379 return value
381 def init_logging():
382 if (config.has_section('loggers') and
383 config.has_section('handlers') and
384 config.has_section('formatters')):
386 logging.config.fileConfig(config_files)
388 elif getDebug():
389 logging.basicConfig(level=logging.DEBUG)
390 else:
391 logging.basicConfig(level=logging.INFO)