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