Missed this when moving init_logging() from pyTivo.py to config.py.
[pyTivo/wgw.git] / config.py
blobccd35c46bb6410def4dee20ae478711ff5391a96
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 try:
120 return config.getboolean('Server', 'optres')
121 except NoOptionError, ValueError:
122 return False
124 def getPixelAR(ref):
125 if config.has_option('Server', 'par'):
126 try:
127 return (True, config.getfloat('Server', 'par'))[ref]
128 except NoOptionError, ValueError:
129 pass
130 return (False, 1.0)[ref]
132 def get(section, key):
133 return config.get(section, key)
135 def getFFmpegWait():
136 if config.has_option('Server', 'ffmpeg_wait'):
137 return max(int(float(config.get('Server', 'ffmpeg_wait'))), 1)
138 else:
139 return 10
141 def getFFmpegTemplate(tsn):
142 if tsn and config.has_section('_tivo_' + tsn):
143 try:
144 return config.get('_tivo_' + tsn, 'ffmpeg_tmpl', raw=True)
145 except NoOptionError:
146 pass
147 try:
148 return config.get('Server', 'ffmpeg_tmpl', raw=True)
149 except NoOptionError: #default
150 return '%(video_codec)s %(video_fps)s %(video_br)s %(max_video_br)s \
151 %(buff_size)s %(aspect_ratio)s -comment pyTivo.py %(audio_br)s \
152 %(audio_fr)s %(audio_ch)s %(audio_codec)s %(audio_lang)s \
153 %(ffmpeg_pram)s %(format)s'
155 def getFFmpegPrams(tsn):
156 if tsn and config.has_section('_tivo_' + tsn):
157 try:
158 return config.get('_tivo_' + tsn, 'ffmpeg_pram', raw=True)
159 except NoOptionError:
160 pass
161 try:
162 return config.get('Server', 'ffmpeg_pram', raw=True)
163 except NoOptionError:
164 return None
166 def isHDtivo(tsn): # tsn's of High Definition Tivo's
167 return tsn and tsn[:3] in ['648', '652', '658']
169 def getValidWidths():
170 return [1920, 1440, 1280, 720, 704, 544, 480, 352]
172 def getValidHeights():
173 return [1080, 720, 480] # Technically 240 is also supported
175 # Return the number in list that is nearest to x
176 # if two values are equidistant, return the larger
177 def nearest(x, list):
178 return reduce(lambda a, b: closest(x, a, b), list)
180 def closest(x, a, b):
181 if abs(x - a) < abs(x - b) or (abs(x - a) == abs(x - b) and a > b):
182 return a
183 else:
184 return b
186 def nearestTivoHeight(height):
187 return nearest(height, getValidHeights())
189 def nearestTivoWidth(width):
190 return nearest(width, getValidWidths())
192 def getTivoHeight(tsn):
193 if tsn and config.has_section('_tivo_' + tsn):
194 try:
195 height = config.getint('_tivo_' + tsn, 'height')
196 return nearestTivoHeight(height)
197 except NoOptionError:
198 pass
199 try:
200 height = config.getint('Server', 'height')
201 return nearestTivoHeight(height)
202 except NoOptionError: #defaults for S3/S2 TiVo
203 if isHDtivo(tsn):
204 return 720
205 else:
206 return 480
208 def getTivoWidth(tsn):
209 if tsn and config.has_section('_tivo_' + tsn):
210 try:
211 width = config.getint('_tivo_' + tsn, 'width')
212 return nearestTivoWidth(width)
213 except NoOptionError:
214 pass
215 try:
216 width = config.getint('Server', 'width')
217 return nearestTivoWidth(width)
218 except NoOptionError: #defaults for S3/S2 TiVo
219 if isHDtivo(tsn):
220 return 1280
221 else:
222 return 544
224 def _trunc64(i):
225 return max(int(strtod(i)) / 64000, 1) * 64
227 def getAudioBR(tsn=None):
228 # convert to non-zero multiple of 64 to ensure ffmpeg compatibility
229 # compare audio_br to max_audio_br and return lowest
230 if tsn and config.has_section('_tivo_' + tsn):
231 try:
232 audiobr = _trunc64(config.get('_tivo_' + tsn, 'audio_br'))
233 return str(min(audiobr, getMaxAudioBR(tsn))) + 'k'
234 except NoOptionError:
235 pass
236 try:
237 audiobr = _trunc64(config.get('Server', 'audio_br'))
238 return str(min(audiobr, getMaxAudioBR(tsn))) + 'k'
239 except NoOptionError:
240 return str(min(384, getMaxAudioBR(tsn))) + 'k'
242 def _k(i):
243 return str(int(strtod(i)) / 1000) + 'k'
245 def getVideoBR(tsn=None):
246 if tsn and config.has_section('_tivo_' + tsn):
247 try:
248 return _k(config.get('_tivo_' + tsn, 'video_br'))
249 except NoOptionError:
250 pass
251 try:
252 return _k(config.get('Server', 'video_br'))
253 except NoOptionError: #defaults for S3/S2 TiVo
254 if isHDtivo(tsn):
255 return '8192k'
256 else:
257 return '4096K'
259 def getMaxVideoBR():
260 try:
261 return _k(config.get('Server', 'max_video_br'))
262 except NoOptionError: #default to 30000k
263 return '30000k'
265 def getVideoPCT():
266 try:
267 return config.getfloat('Server', 'video_pct')
268 except NoOptionError:
269 return 70
271 def getBuffSize(tsn=None):
272 tsnsect = '_tivo_' + tsn
273 if tsn and config.has_section(tsnsect):
274 if config.has_option(tsnsect, 'bufsize'):
275 try:
276 return _k(config.get(tsnsect, 'bufsize'))
277 except NoOptionError:
278 pass
279 if config.has_option('Server', 'bufsize'):
280 try:
281 return _k(config.get('Server', 'bufsize'))
282 except NoOptionError:
283 pass
284 if isHDtivo(tsn):
285 return '4096k'
286 else:
287 return '1024k'
289 def getMaxAudioBR(tsn=None):
290 # convert to non-zero multiple of 64 for ffmpeg compatibility
291 if tsn and config.has_section('_tivo_' + tsn):
292 try:
293 return _trunc64(config.get('_tivo_' + tsn, 'max_audio_br'))
294 except NoOptionError:
295 pass
296 try:
297 return _trunc64(config.get('Server', 'max_audio_br'))
298 except NoOptionError:
299 return int(448) # default to 448
301 def get_tsn(name, tsn=None):
302 if tsn and config.has_section('_tivo_' + tsn):
303 try:
304 return config.get('_tivo_' + tsn, name)
305 except NoOptionError:
306 pass
307 try:
308 return config.get('Server', name)
309 except NoOptionError:
310 return None
312 def getAudioCodec(tsn=None):
313 return get_tsn('audio_codec', tsn)
315 def getAudioCH(tsn=None):
316 return get_tsn('audio_ch', tsn)
318 def getAudioFR(tsn=None):
319 return get_tsn('audio_fr', tsn)
321 def getAudioLang(tsn=None):
322 return get_tsn('audio_lang', tsn)
324 def getCopyTS(tsn=None):
325 return get_tsn('copy_ts', tsn)
327 def getVideoFPS(tsn=None):
328 return get_tsn('video_fps', tsn)
330 def getVideoCodec(tsn=None):
331 return get_tsn('video_codec', tsn)
333 def getFormat(tsn=None):
334 return get_tsn('format', tsn)
336 # Parse a bitrate using the SI/IEEE suffix values as if by ffmpeg
337 # For example, 2K==2000, 2Ki==2048, 2MB==16000000, 2MiB==16777216
338 # Algorithm: http://svn.mplayerhq.hu/ffmpeg/trunk/libavcodec/eval.c
339 def strtod(value):
340 prefixes = {'y': -24, 'z': -21, 'a': -18, 'f': -15, 'p': -12,
341 'n': -9, 'u': -6, 'm': -3, 'c': -2, 'd': -1,
342 'h': 2, 'k': 3, 'K': 3, 'M': 6, 'G': 9,
343 'T': 12, 'P': 15, 'E': 18, 'Z': 21, 'Y': 24}
344 p = re.compile(r'^(\d+)(?:([yzafpnumcdhkKMGTPEZY])(i)?)?([Bb])?$')
345 m = p.match(value)
346 if not m:
347 raise SyntaxError('Invalid bit value syntax')
348 (coef, prefix, power, byte) = m.groups()
349 if prefix is None:
350 value = float(coef)
351 else:
352 exponent = float(prefixes[prefix])
353 if power == 'i':
354 # Use powers of 2
355 value = float(coef) * pow(2.0, exponent / 0.3)
356 else:
357 # Use powers of 10
358 value = float(coef) * pow(10.0, exponent)
359 if byte == 'B': # B == Byte, b == bit
360 value *= 8;
361 return value
363 def init_logging():
364 if (config.has_section('loggers') and
365 config.has_section('handlers') and
366 config.has_section('formatters')):
368 logging.config.fileConfig(config_files)
370 elif getDebug():
371 logging.basicConfig(level=logging.DEBUG)
372 else:
373 logging.basicConfig(level=logging.INFO)