More trivial stuff that bugs me.
[pyTivo/wgw.git] / config.py
blob6d5c6c3a540e597aff02045584bb8dfb44c1eca9
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 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 (section.startswith(('_tivo_', 'logger_', 'handler_',
80 'formatter_'))
81 or section in ('Server', 'loggers', 'handlers',
82 'formatters')
86 tsnsect = '_tivo_' + tsn
87 if config.has_section(tsnsect) and config.has_option(tsnsect, 'shares'):
88 # clean up leading and trailing spaces & make sure ref is valid
89 tsnshares = []
90 for x in config.get(tsnsect, 'shares').split(','):
91 y = x.strip()
92 if config.has_section(y):
93 tsnshares.append((y, dict(config.items(y))))
94 if tsnshares:
95 shares = tsnshares
97 return shares
99 def getDebug():
100 try:
101 return config.getboolean('Server', 'debug')
102 except NoOptionError, ValueError:
103 return False
105 def getOptres(tsn = None):
106 if tsn and config.has_section('_tivo_' + tsn):
107 try:
108 return config.getboolean('_tivo_' + tsn, 'optres')
109 except NoOptionError, ValueError:
110 pass
111 try:
112 return config.getboolean('Server', 'optres')
113 except NoOptionError, ValueError:
114 return False
116 def getPixelAR(ref):
117 if config.has_option('Server', 'par'):
118 try:
119 return (True, config.getfloat('Server', 'par'))[ref]
120 except NoOptionError, ValueError:
121 pass
122 return (False, 1.0)[ref]
124 def get(section, key):
125 return config.get(section, key)
127 def getFFmpegTemplate(tsn):
128 if tsn and config.has_section('_tivo_' + tsn):
129 try:
130 return config.get('_tivo_' + tsn, 'ffmpeg_tmpl', raw=True)
131 except NoOptionError:
132 pass
133 try:
134 return config.get('Server', 'ffmpeg_tmpl', raw=True)
135 except NoOptionError: #default
136 return '%(video_codec)s %(video_fps)s %(video_br)s %(max_video_br)s \
137 %(buff_size)s %(aspect_ratio)s -comment pyTivo.py %(audio_br)s \
138 %(audio_fr)s %(audio_ch)s %(audio_codec)s %(audio_lang)s \
139 %(ffmpeg_pram)s %(format)s'
141 def getFFmpegPrams(tsn):
142 if tsn and config.has_section('_tivo_' + tsn):
143 try:
144 return config.get('_tivo_' + tsn, 'ffmpeg_pram', raw=True)
145 except NoOptionError:
146 pass
147 try:
148 return config.get('Server', 'ffmpeg_pram', raw=True)
149 except NoOptionError:
150 return None
152 def isHDtivo(tsn): # tsn's of High Definition Tivo's
153 return tsn and tsn[:3] in ['648', '652', '658']
155 def getValidWidths():
156 return [1920, 1440, 1280, 720, 704, 544, 480, 352]
158 def getValidHeights():
159 return [1080, 720, 480] # Technically 240 is also supported
161 # Return the number in list that is nearest to x
162 # if two values are equidistant, return the larger
163 def nearest(x, list):
164 return reduce(lambda a, b: closest(x, a, b), list)
166 def closest(x, a, b):
167 if abs(x - a) < abs(x - b) or (abs(x - a) == abs(x - b) and a > b):
168 return a
169 else:
170 return b
172 def nearestTivoHeight(height):
173 return nearest(height, getValidHeights())
175 def nearestTivoWidth(width):
176 return nearest(width, getValidWidths())
178 def getTivoHeight(tsn):
179 if tsn and config.has_section('_tivo_' + tsn):
180 try:
181 height = config.getint('_tivo_' + tsn, 'height')
182 return nearestTivoHeight(height)
183 except NoOptionError:
184 pass
185 try:
186 height = config.getint('Server', 'height')
187 return nearestTivoHeight(height)
188 except NoOptionError: #defaults for S3/S2 TiVo
189 if isHDtivo(tsn):
190 return 720
191 else:
192 return 480
194 def getTivoWidth(tsn):
195 if tsn and config.has_section('_tivo_' + tsn):
196 try:
197 width = config.getint('_tivo_' + tsn, 'width')
198 return nearestTivoWidth(width)
199 except NoOptionError:
200 pass
201 try:
202 width = config.getint('Server', 'width')
203 return nearestTivoWidth(width)
204 except NoOptionError: #defaults for S3/S2 TiVo
205 if isHDtivo(tsn):
206 return 1280
207 else:
208 return 544
210 def _trunc64(i):
211 return max(int(strtod(i)) / 64000, 1) * 64
213 def getAudioBR(tsn = None):
214 #convert to non-zero multiple of 64 to ensure ffmpeg compatibility
215 #compare audio_br to max_audio_br and return lowest
216 if tsn and config.has_section('_tivo_' + tsn):
217 try:
218 audiobr = _trunc64(config.get('_tivo_' + tsn, 'audio_br'))
219 return str(min(audiobr, getMaxAudioBR(tsn))) + 'k'
220 except NoOptionError:
221 pass
222 try:
223 audiobr = _trunc64(config.get('Server', 'audio_br'))
224 return str(min(audiobr, getMaxAudioBR(tsn))) + 'k'
225 except NoOptionError:
226 return str(min(384, getMaxAudioBR(tsn))) + 'k'
228 def _k(i):
229 return str(int(strtod(i)) / 1000) + 'k'
231 def getVideoBR(tsn = None):
232 if tsn and config.has_section('_tivo_' + tsn):
233 try:
234 return _k(config.get('_tivo_' + tsn, 'video_br'))
235 except NoOptionError:
236 pass
237 try:
238 return _k(config.get('Server', 'video_br'))
239 except NoOptionError: #defaults for S3/S2 TiVo
240 if isHDtivo(tsn):
241 return '8192k'
242 else:
243 return '4096K'
245 def getMaxVideoBR():
246 try:
247 return _k(config.get('Server', 'max_video_br'))
248 except NoOptionError: #default to 30000k
249 return '30000k'
251 def getVideoPCT():
252 try:
253 return config.getfloat('Server', 'video_pct')
254 except NoOptionError:
255 return 70
257 def getBuffSize(tsn = None):
258 if tsn and config.has_section('_tivo_' + tsn):
259 if config.has_option('_tivo_' + tsn, 'bufsize'):
260 try:
261 return _k(config.get('_tivo_' + tsn, 'bufsize'))
262 except NoOptionError:
263 pass
264 if config.has_option('Server', 'bufsize'):
265 try:
266 return _k(config.get('Server', 'bufsize'))
267 except NoOptionError:
268 pass
269 if isHDtivo(tsn):
270 return '4096k'
271 else:
272 return '1024k'
274 def getMaxAudioBR(tsn = None):
275 #convert to non-zero multiple of 64 for ffmpeg compatibility
276 if tsn and config.has_section('_tivo_' + tsn):
277 try:
278 return _trunc64(config.get('_tivo_' + tsn, 'max_audio_br'))
279 except NoOptionError:
280 pass
281 try:
282 return _trunc64(config.get('Server', 'max_audio_br'))
283 except NoOptionError:
284 return int(448) #default to 448
286 def get_tsn(name, tsn=None):
287 if tsn and config.has_section('_tivo_' + tsn):
288 try:
289 return config.get('_tivo_' + tsn, name)
290 except NoOptionError:
291 pass
292 try:
293 return config.get('Server', name)
294 except NoOptionError:
295 return None
297 def getAudioCodec(tsn=None):
298 return get_tsn('audio_codec', tsn)
300 def getAudioCH(tsn=None):
301 return get_tsn('audio_ch', tsn)
303 def getAudioFR(tsn=None):
304 return get_tsn('audio_fr', tsn)
306 def getAudioLang(tsn=None):
307 return get_tsn('audio_lang', tsn)
309 def getCopyTS(tsn = None):
310 if tsn and config.has_section('_tivo_' + tsn):
311 if config.has_option('_tivo_' + tsn, 'copy_ts'):
312 try:
313 return config.get('_tivo_' + tsn, 'copy_ts')
314 except NoOptionError, ValueError:
315 pass
316 if config.has_option('Server', 'copy_ts'):
317 try:
318 return config.get('Server', 'copy_ts')
319 except NoOptionError, ValueError:
320 pass
321 return 'none'
323 def getVideoFPS(tsn=None):
324 return get_tsn('video_fps', tsn)
326 def getVideoCodec(tsn=None):
327 return get_tsn('video_codec', tsn)
329 def getFormat(tsn = None):
330 return get_tsn('format', tsn)
332 # Parse a bitrate using the SI/IEEE suffix values as if by ffmpeg
333 # For example, 2K==2000, 2Ki==2048, 2MB==16000000, 2MiB==16777216
334 # Algorithm: http://svn.mplayerhq.hu/ffmpeg/trunk/libavcodec/eval.c
335 def strtod(value):
336 prefixes = {'y': -24, 'z': -21, 'a': -18, 'f': -15, 'p': -12,
337 'n': -9, 'u': -6, 'm': -3, 'c': -2, 'd': -1,
338 'h': 2, 'k': 3, 'K': 3, 'M': 6, 'G': 9,
339 'T': 12, 'P': 15, 'E': 18, 'Z': 21, 'Y': 24}
340 p = re.compile(r'^(\d+)(?:([yzafpnumcdhkKMGTPEZY])(i)?)?([Bb])?$')
341 m = p.match(value)
342 if m is None:
343 raise SyntaxError('Invalid bit value syntax')
344 (coef, prefix, power, byte) = m.groups()
345 if prefix is None:
346 value = float(coef)
347 else:
348 exponent = float(prefixes[prefix])
349 if power == 'i':
350 # Use powers of 2
351 value = float(coef) * pow(2.0, exponent / 0.3)
352 else:
353 # Use powers of 10
354 value = float(coef) * pow(10.0, exponent)
355 if byte == 'B': # B == Byte, b == bit
356 value *= 8;
357 return value