Latest version of Cheetah -- 2.0.1.
[pyTivo/wgw.git] / config.py
blob064a470e1da8756c7e78e821b42d60fe9d58b5fa
1 import ConfigParser
2 import logging
3 import os
4 import re
5 import random
6 import string
7 import sys
8 from ConfigParser import NoOptionError
10 guid = ''.join([random.choice(string.letters) for i in range(10)])
12 config = ConfigParser.ConfigParser()
13 p = os.path.dirname(__file__)
15 config_files = [
16 '/etc/pyTivo.conf',
17 os.path.join(p, 'pyTivo.conf'),
19 config_exists = False
20 for config_file in config_files:
21 if os.path.exists(config_file):
22 config_exists = True
23 if not config_exists:
24 print 'ERROR: pyTivo.conf does not exist.\n' + \
25 'You must create this file before running pyTivo.'
26 sys.exit(1)
27 config.read(config_files)
29 def reset():
30 global config
31 del config
32 config = ConfigParser.ConfigParser()
33 config.read(config_files)
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)
60 def get169Letterbox(tsn): # tivo pads 16:9 video for 4:3 display
61 return tsn and tsn[:3] in ('649')
63 def get169Setting(tsn):
64 if not tsn:
65 return True
67 if config.has_section('_tivo_' + tsn):
68 if config.has_option('_tivo_' + tsn, 'aspect169'):
69 try:
70 return config.getboolean('_tivo_' + tsn, 'aspect169')
71 except ValueError:
72 pass
74 if get169Blacklist(tsn) or get169Letterbox(tsn):
75 return False
77 return True
79 def getShares(tsn=''):
80 shares = [(section, dict(config.items(section)))
81 for section in config.sections()
82 if not (section.startswith(('_tivo_', 'logger_', 'handler_',
83 'formatter_'))
84 or section in ('Server', 'loggers', 'handlers',
85 'formatters')
89 tsnsect = '_tivo_' + tsn
90 if config.has_section(tsnsect) and config.has_option(tsnsect, 'shares'):
91 # clean up leading and trailing spaces & make sure ref is valid
92 tsnshares = []
93 for x in config.get(tsnsect, 'shares').split(','):
94 y = x.strip()
95 if config.has_section(y):
96 tsnshares.append((y, dict(config.items(y))))
97 if tsnshares:
98 shares = tsnshares
100 return shares
102 def getDebug():
103 try:
104 return config.getboolean('Server', 'debug')
105 except NoOptionError, ValueError:
106 return False
108 def getOptres(tsn = None):
109 if tsn and config.has_section('_tivo_' + tsn):
110 try:
111 return config.getboolean('_tivo_' + tsn, 'optres')
112 except NoOptionError, ValueError:
113 pass
114 try:
115 return config.getboolean('Server', 'optres')
116 except NoOptionError, ValueError:
117 return False
119 def getPixelAR(ref):
120 if config.has_option('Server', 'par'):
121 try:
122 return (True, config.getfloat('Server', 'par'))[ref]
123 except NoOptionError, ValueError:
124 pass
125 return (False, 1.0)[ref]
127 def get(section, key):
128 return config.get(section, key)
130 def getFFmpegTemplate(tsn):
131 if tsn and config.has_section('_tivo_' + tsn):
132 try:
133 return config.get('_tivo_' + tsn, 'ffmpeg_tmpl', raw=True)
134 except NoOptionError:
135 pass
136 try:
137 return config.get('Server', 'ffmpeg_tmpl', raw=True)
138 except NoOptionError: #default
139 return '%(video_codec)s %(video_fps)s %(video_br)s %(max_video_br)s \
140 %(buff_size)s %(aspect_ratio)s -comment pyTivo.py %(audio_br)s \
141 %(audio_fr)s %(audio_ch)s %(audio_codec)s %(audio_lang)s \
142 %(ffmpeg_pram)s %(format)s'
144 def getFFmpegPrams(tsn):
145 if tsn and config.has_section('_tivo_' + tsn):
146 try:
147 return config.get('_tivo_' + tsn, 'ffmpeg_pram', raw=True)
148 except NoOptionError:
149 pass
150 try:
151 return config.get('Server', 'ffmpeg_pram', raw=True)
152 except NoOptionError:
153 return None
155 def isHDtivo(tsn): # tsn's of High Definition Tivo's
156 return tsn and tsn[:3] in ['648', '652', '658']
158 def getValidWidths():
159 return [1920, 1440, 1280, 720, 704, 544, 480, 352]
161 def getValidHeights():
162 return [1080, 720, 480] # Technically 240 is also supported
164 # Return the number in list that is nearest to x
165 # if two values are equidistant, return the larger
166 def nearest(x, list):
167 return reduce(lambda a, b: closest(x, a, b), list)
169 def closest(x, a, b):
170 if abs(x - a) < abs(x - b) or (abs(x - a) == abs(x - b) and a > b):
171 return a
172 else:
173 return b
175 def nearestTivoHeight(height):
176 return nearest(height, getValidHeights())
178 def nearestTivoWidth(width):
179 return nearest(width, getValidWidths())
181 def getTivoHeight(tsn):
182 if tsn and config.has_section('_tivo_' + tsn):
183 try:
184 height = config.getint('_tivo_' + tsn, 'height')
185 return nearestTivoHeight(height)
186 except NoOptionError:
187 pass
188 try:
189 height = config.getint('Server', 'height')
190 return nearestTivoHeight(height)
191 except NoOptionError: #defaults for S3/S2 TiVo
192 if isHDtivo(tsn):
193 return 720
194 else:
195 return 480
197 def getTivoWidth(tsn):
198 if tsn and config.has_section('_tivo_' + tsn):
199 try:
200 width = config.getint('_tivo_' + tsn, 'width')
201 return nearestTivoWidth(width)
202 except NoOptionError:
203 pass
204 try:
205 width = config.getint('Server', 'width')
206 return nearestTivoWidth(width)
207 except NoOptionError: #defaults for S3/S2 TiVo
208 if isHDtivo(tsn):
209 return 1280
210 else:
211 return 544
213 def _trunc64(i):
214 return max(int(strtod(i)) / 64000, 1) * 64
216 def getAudioBR(tsn = None):
217 #convert to non-zero multiple of 64 to ensure ffmpeg compatibility
218 #compare audio_br to max_audio_br and return lowest
219 if tsn and config.has_section('_tivo_' + tsn):
220 try:
221 audiobr = _trunc64(config.get('_tivo_' + tsn, 'audio_br'))
222 return str(min(audiobr, getMaxAudioBR(tsn))) + 'k'
223 except NoOptionError:
224 pass
225 try:
226 audiobr = _trunc64(config.get('Server', 'audio_br'))
227 return str(min(audiobr, getMaxAudioBR(tsn))) + 'k'
228 except NoOptionError:
229 return str(min(384, getMaxAudioBR(tsn))) + 'k'
231 def _k(i):
232 return str(int(strtod(i)) / 1000) + 'k'
234 def getVideoBR(tsn = None):
235 if tsn and config.has_section('_tivo_' + tsn):
236 try:
237 return _k(config.get('_tivo_' + tsn, 'video_br'))
238 except NoOptionError:
239 pass
240 try:
241 return _k(config.get('Server', 'video_br'))
242 except NoOptionError: #defaults for S3/S2 TiVo
243 if isHDtivo(tsn):
244 return '8192k'
245 else:
246 return '4096K'
248 def getMaxVideoBR():
249 try:
250 return _k(config.get('Server', 'max_video_br'))
251 except NoOptionError: #default to 30000k
252 return '30000k'
254 def getVideoPCT():
255 try:
256 return config.getfloat('Server', 'video_pct')
257 except NoOptionError:
258 return 70
260 def getBuffSize(tsn = None):
261 if tsn and config.has_section('_tivo_' + tsn):
262 if config.has_option('_tivo_' + tsn, 'bufsize'):
263 try:
264 return _k(config.get('_tivo_' + tsn, 'bufsize'))
265 except NoOptionError:
266 pass
267 if config.has_option('Server', 'bufsize'):
268 try:
269 return _k(config.get('Server', 'bufsize'))
270 except NoOptionError:
271 pass
272 if isHDtivo(tsn):
273 return '4096k'
274 else:
275 return '1024k'
277 def getMaxAudioBR(tsn = None):
278 #convert to non-zero multiple of 64 for ffmpeg compatibility
279 if tsn and config.has_section('_tivo_' + tsn):
280 try:
281 return _trunc64(config.get('_tivo_' + tsn, 'max_audio_br'))
282 except NoOptionError:
283 pass
284 try:
285 return _trunc64(config.get('Server', 'max_audio_br'))
286 except NoOptionError:
287 return int(448) #default to 448
289 def get_tsn(name, tsn=None):
290 if tsn and config.has_section('_tivo_' + tsn):
291 try:
292 return config.get('_tivo_' + tsn, name)
293 except NoOptionError:
294 pass
295 try:
296 return config.get('Server', name)
297 except NoOptionError:
298 return None
300 def getAudioCodec(tsn=None):
301 return get_tsn('audio_codec', tsn)
303 def getAudioCH(tsn=None):
304 return get_tsn('audio_ch', tsn)
306 def getAudioFR(tsn=None):
307 return get_tsn('audio_fr', tsn)
309 def getAudioLang(tsn=None):
310 return get_tsn('audio_lang', tsn)
312 def getCopyTS(tsn = None):
313 if tsn and config.has_section('_tivo_' + tsn):
314 if config.has_option('_tivo_' + tsn, 'copy_ts'):
315 try:
316 return config.get('_tivo_' + tsn, 'copy_ts')
317 except NoOptionError, ValueError:
318 pass
319 if config.has_option('Server', 'copy_ts'):
320 try:
321 return config.get('Server', 'copy_ts')
322 except NoOptionError, ValueError:
323 pass
324 return 'none'
326 def getVideoFPS(tsn=None):
327 return get_tsn('video_fps', tsn)
329 def getVideoCodec(tsn=None):
330 return get_tsn('video_codec', tsn)
332 def getFormat(tsn = None):
333 return get_tsn('format', tsn)
335 # Parse a bitrate using the SI/IEEE suffix values as if by ffmpeg
336 # For example, 2K==2000, 2Ki==2048, 2MB==16000000, 2MiB==16777216
337 # Algorithm: http://svn.mplayerhq.hu/ffmpeg/trunk/libavcodec/eval.c
338 def strtod(value):
339 prefixes = {'y': -24, 'z': -21, 'a': -18, 'f': -15, 'p': -12,
340 'n': -9, 'u': -6, 'm': -3, 'c': -2, 'd': -1,
341 'h': 2, 'k': 3, 'K': 3, 'M': 6, 'G': 9,
342 'T': 12, 'P': 15, 'E': 18, 'Z': 21, 'Y': 24}
343 p = re.compile(r'^(\d+)(?:([yzafpnumcdhkKMGTPEZY])(i)?)?([Bb])?$')
344 m = p.match(value)
345 if m is None:
346 raise SyntaxError('Invalid bit value syntax')
347 (coef, prefix, power, byte) = m.groups()
348 if prefix is None:
349 value = float(coef)
350 else:
351 exponent = float(prefixes[prefix])
352 if power == 'i':
353 # Use powers of 2
354 value = float(coef) * pow(2.0, exponent / 0.3)
355 else:
356 # Use powers of 10
357 value = float(coef) * pow(10.0, exponent)
358 if byte == 'B': # B == Byte, b == bit
359 value *= 8;
360 return value
362 def init_logging():
363 if (config.has_section('loggers') and
364 config.has_section('handlers') and
365 config.has_section('formatters')):
367 logging.config.fileConfig(config_files)
369 elif getDebug():
370 logging.basicConfig(level=logging.DEBUG)
371 else:
372 logging.basicConfig(level=logging.INFO)