An 'a' went missing. (Also, why the change from "Alternate" to "Alternative"?)
[pyTivo/wgw.git] / config.py
blobddc9ad4d1896dd63740fb94ad4ade85ed7983475
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()
14 p = os.path.dirname(__file__)
15 config_files = ['/etc/pyTivo.conf', os.path.join(p, 'pyTivo.conf')]
17 configs_found = config.read(config_files)
18 if not configs_found:
19 print ('ERROR: pyTivo.conf does not exist.\n' +
20 'You must create this file before running pyTivo.')
21 sys.exit(1)
23 def reset():
24 global config
25 newconfig = ConfigParser.ConfigParser()
26 newconfig.read(config_files)
27 config = newconfig
29 def write():
30 f = open(configs_found[-1], 'w')
31 config.write(f)
32 f.close()
34 def getGUID():
35 if config.has_option('Server', 'GUID'):
36 return config.get('Server', 'GUID')
37 else:
38 return guid
40 def getTivoUsername():
41 return config.get('Server', 'tivo_username')
43 def getTivoPassword():
44 return config.get('Server', 'tivo_password')
46 def getBeaconAddresses():
47 if config.has_option('Server', 'beacon'):
48 beacon_ips = config.get('Server', 'beacon')
49 else:
50 beacon_ips = '255.255.255.255'
51 return beacon_ips
53 def getPort():
54 return config.get('Server', 'Port')
56 def get169Blacklist(tsn): # tivo does not pad 16:9 video
57 return tsn and not isHDtivo(tsn) and not get169Letterbox(tsn)
58 # verified Blacklist Tivo's are ('130', '240', '540')
59 # It is assumed all remaining non-HD and non-Letterbox tivos are Blacklist
61 def get169Letterbox(tsn): # tivo pads 16:9 video for 4:3 display
62 return tsn and tsn[:3] in ['649']
64 def get169Setting(tsn):
65 if not tsn:
66 return True
68 tsnsect = '_tivo_' + tsn
69 if config.has_section(tsnsect):
70 if config.has_option(tsnsect, 'aspect169'):
71 try:
72 return config.getboolean(tsnsect, 'aspect169')
73 except ValueError:
74 pass
76 if get169Blacklist(tsn) or get169Letterbox(tsn):
77 return False
79 return True
81 def getShares(tsn=''):
82 shares = [(section, dict(config.items(section)))
83 for section in config.sections()
84 if not (section.startswith(('_tivo_', 'logger_', 'handler_',
85 'formatter_'))
86 or section in ('Server', 'loggers', 'handlers',
87 'formatters')
91 tsnsect = '_tivo_' + tsn
92 if config.has_section(tsnsect) and config.has_option(tsnsect, 'shares'):
93 # clean up leading and trailing spaces & make sure ref is valid
94 tsnshares = []
95 for x in config.get(tsnsect, 'shares').split(','):
96 y = x.strip()
97 if config.has_section(y):
98 tsnshares.append((y, dict(config.items(y))))
99 if tsnshares:
100 shares = tsnshares
102 return shares
104 def getDebug():
105 try:
106 return config.getboolean('Server', 'debug')
107 except NoOptionError, ValueError:
108 return False
110 def getOptres(tsn=None):
111 if tsn and config.has_section('_tivo_' + tsn):
112 try:
113 return config.getboolean('_tivo_' + tsn, 'optres')
114 except NoOptionError, ValueError:
115 pass
116 try:
117 return config.getboolean('Server', 'optres')
118 except NoOptionError, ValueError:
119 return False
121 def getPixelAR(ref):
122 if config.has_option('Server', 'par'):
123 try:
124 return (True, config.getfloat('Server', 'par'))[ref]
125 except NoOptionError, ValueError:
126 pass
127 return (False, 1.0)[ref]
129 def get(section, key):
130 return config.get(section, key)
132 def getFFmpegWait():
133 if config.has_option('Server', 'ffmpeg_wait'):
134 return max(int(float(config.get('Server', 'ffmpeg_wait'))), 1)
135 else:
136 return 10
138 def getFFmpegTemplate(tsn):
139 if tsn and config.has_section('_tivo_' + tsn):
140 try:
141 return config.get('_tivo_' + tsn, 'ffmpeg_tmpl', raw=True)
142 except NoOptionError:
143 pass
144 try:
145 return config.get('Server', 'ffmpeg_tmpl', raw=True)
146 except NoOptionError: #default
147 return '%(video_codec)s %(video_fps)s %(video_br)s %(max_video_br)s \
148 %(buff_size)s %(aspect_ratio)s -comment pyTivo.py %(audio_br)s \
149 %(audio_fr)s %(audio_ch)s %(audio_codec)s %(audio_lang)s \
150 %(ffmpeg_pram)s %(format)s'
152 def getFFmpegPrams(tsn):
153 if tsn and config.has_section('_tivo_' + tsn):
154 try:
155 return config.get('_tivo_' + tsn, 'ffmpeg_pram', raw=True)
156 except NoOptionError:
157 pass
158 try:
159 return config.get('Server', 'ffmpeg_pram', raw=True)
160 except NoOptionError:
161 return None
163 def isHDtivo(tsn): # tsn's of High Definition Tivo's
164 return tsn and tsn[:3] in ['648', '652', '658']
166 def getValidWidths():
167 return [1920, 1440, 1280, 720, 704, 544, 480, 352]
169 def getValidHeights():
170 return [1080, 720, 480] # Technically 240 is also supported
172 # Return the number in list that is nearest to x
173 # if two values are equidistant, return the larger
174 def nearest(x, list):
175 return reduce(lambda a, b: closest(x, a, b), list)
177 def closest(x, a, b):
178 if abs(x - a) < abs(x - b) or (abs(x - a) == abs(x - b) and a > b):
179 return a
180 else:
181 return b
183 def nearestTivoHeight(height):
184 return nearest(height, getValidHeights())
186 def nearestTivoWidth(width):
187 return nearest(width, getValidWidths())
189 def getTivoHeight(tsn):
190 if tsn and config.has_section('_tivo_' + tsn):
191 try:
192 height = config.getint('_tivo_' + tsn, 'height')
193 return nearestTivoHeight(height)
194 except NoOptionError:
195 pass
196 try:
197 height = config.getint('Server', 'height')
198 return nearestTivoHeight(height)
199 except NoOptionError: #defaults for S3/S2 TiVo
200 if isHDtivo(tsn):
201 return 720
202 else:
203 return 480
205 def getTivoWidth(tsn):
206 if tsn and config.has_section('_tivo_' + tsn):
207 try:
208 width = config.getint('_tivo_' + tsn, 'width')
209 return nearestTivoWidth(width)
210 except NoOptionError:
211 pass
212 try:
213 width = config.getint('Server', 'width')
214 return nearestTivoWidth(width)
215 except NoOptionError: #defaults for S3/S2 TiVo
216 if isHDtivo(tsn):
217 return 1280
218 else:
219 return 544
221 def _trunc64(i):
222 return max(int(strtod(i)) / 64000, 1) * 64
224 def getAudioBR(tsn=None):
225 # convert to non-zero multiple of 64 to ensure ffmpeg compatibility
226 # compare audio_br to max_audio_br and return lowest
227 if tsn and config.has_section('_tivo_' + tsn):
228 try:
229 audiobr = _trunc64(config.get('_tivo_' + tsn, 'audio_br'))
230 return str(min(audiobr, getMaxAudioBR(tsn))) + 'k'
231 except NoOptionError:
232 pass
233 try:
234 audiobr = _trunc64(config.get('Server', 'audio_br'))
235 return str(min(audiobr, getMaxAudioBR(tsn))) + 'k'
236 except NoOptionError:
237 return str(min(384, getMaxAudioBR(tsn))) + 'k'
239 def _k(i):
240 return str(int(strtod(i)) / 1000) + 'k'
242 def getVideoBR(tsn=None):
243 if tsn and config.has_section('_tivo_' + tsn):
244 try:
245 return _k(config.get('_tivo_' + tsn, 'video_br'))
246 except NoOptionError:
247 pass
248 try:
249 return _k(config.get('Server', 'video_br'))
250 except NoOptionError: #defaults for S3/S2 TiVo
251 if isHDtivo(tsn):
252 return '8192k'
253 else:
254 return '4096K'
256 def getMaxVideoBR():
257 try:
258 return _k(config.get('Server', 'max_video_br'))
259 except NoOptionError: #default to 30000k
260 return '30000k'
262 def getVideoPCT():
263 try:
264 return config.getfloat('Server', 'video_pct')
265 except NoOptionError:
266 return 70
268 def getBuffSize(tsn=None):
269 tsnsect = '_tivo_' + tsn
270 if tsn and config.has_section(tsnsect):
271 if config.has_option(tsnsect, 'bufsize'):
272 try:
273 return _k(config.get(tsnsect, 'bufsize'))
274 except NoOptionError:
275 pass
276 if config.has_option('Server', 'bufsize'):
277 try:
278 return _k(config.get('Server', 'bufsize'))
279 except NoOptionError:
280 pass
281 if isHDtivo(tsn):
282 return '4096k'
283 else:
284 return '1024k'
286 def getMaxAudioBR(tsn=None):
287 # convert to non-zero multiple of 64 for ffmpeg compatibility
288 if tsn and config.has_section('_tivo_' + tsn):
289 try:
290 return _trunc64(config.get('_tivo_' + tsn, 'max_audio_br'))
291 except NoOptionError:
292 pass
293 try:
294 return _trunc64(config.get('Server', 'max_audio_br'))
295 except NoOptionError:
296 return int(448) # default to 448
298 def get_tsn(name, tsn=None):
299 if tsn and config.has_section('_tivo_' + tsn):
300 try:
301 return config.get('_tivo_' + tsn, name)
302 except NoOptionError:
303 pass
304 try:
305 return config.get('Server', name)
306 except NoOptionError:
307 return None
309 def getAudioCodec(tsn=None):
310 return get_tsn('audio_codec', tsn)
312 def getAudioCH(tsn=None):
313 return get_tsn('audio_ch', tsn)
315 def getAudioFR(tsn=None):
316 return get_tsn('audio_fr', tsn)
318 def getAudioLang(tsn=None):
319 return get_tsn('audio_lang', tsn)
321 def getCopyTS(tsn=None):
322 return get_tsn('copy_ts', tsn)
324 def getVideoFPS(tsn=None):
325 return get_tsn('video_fps', tsn)
327 def getVideoCodec(tsn=None):
328 return get_tsn('video_codec', tsn)
330 def getFormat(tsn=None):
331 return get_tsn('format', tsn)
333 # Parse a bitrate using the SI/IEEE suffix values as if by ffmpeg
334 # For example, 2K==2000, 2Ki==2048, 2MB==16000000, 2MiB==16777216
335 # Algorithm: http://svn.mplayerhq.hu/ffmpeg/trunk/libavcodec/eval.c
336 def strtod(value):
337 prefixes = {'y': -24, 'z': -21, 'a': -18, 'f': -15, 'p': -12,
338 'n': -9, 'u': -6, 'm': -3, 'c': -2, 'd': -1,
339 'h': 2, 'k': 3, 'K': 3, 'M': 6, 'G': 9,
340 'T': 12, 'P': 15, 'E': 18, 'Z': 21, 'Y': 24}
341 p = re.compile(r'^(\d+)(?:([yzafpnumcdhkKMGTPEZY])(i)?)?([Bb])?$')
342 m = p.match(value)
343 if not m:
344 raise SyntaxError('Invalid bit value syntax')
345 (coef, prefix, power, byte) = m.groups()
346 if prefix is None:
347 value = float(coef)
348 else:
349 exponent = float(prefixes[prefix])
350 if power == 'i':
351 # Use powers of 2
352 value = float(coef) * pow(2.0, exponent / 0.3)
353 else:
354 # Use powers of 10
355 value = float(coef) * pow(10.0, exponent)
356 if byte == 'B': # B == Byte, b == bit
357 value *= 8;
358 return value
360 def init_logging():
361 if (config.has_section('loggers') and
362 config.has_section('handlers') and
363 config.has_section('formatters')):
365 logging.config.fileConfig(config_files)
367 elif getDebug():
368 logging.basicConfig(level=logging.DEBUG)
369 else:
370 logging.basicConfig(level=logging.INFO)