Common code.
[pyTivo/wmcbrine/lucasnz.git] / config.py
bloba22da4dd3f8e242caefc4cedb0344942c25ed5f2
1 import ConfigParser
2 import getopt
3 import logging
4 import logging.config
5 import os
6 import re
7 import random
8 import socket
9 import string
10 import sys
11 from ConfigParser import NoOptionError
13 def init(argv):
14 global tivos
15 global tivo_names
16 global guid
17 global config_files
19 tivos = {}
20 tivo_names = {}
21 guid = ''.join([random.choice(string.ascii_letters) for i in range(10)])
23 config_win_default = ''
24 if sys.platform == "win32":
25 import _winreg
26 try:
27 explorerFolders = _winreg.OpenKey(
28 _winreg.HKEY_LOCAL_MACHINE, 'Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders')
29 winCommonAppDataVal, winCommonAppDataType = _winreg.QueryValueEx(explorerFolders, 'Common AppData')
30 config_win_default = os.path.join(winCommonAppDataVal, 'pyTivo', 'pyTivo.conf')
31 except WindowsError:
32 print "Can't access Windows Registry to find common Application Data path."
34 p = os.path.dirname(__file__)
35 config_files = ['/etc/pyTivo.conf', config_win_default, os.path.join(p, 'pyTivo.conf')]
37 try:
38 opts, _ = getopt.getopt(argv, 'c:e:', ['config=', 'extraconf='])
39 except getopt.GetoptError, msg:
40 print msg
42 for opt, value in opts:
43 if opt in ('-c', '--config'):
44 config_files = [value]
45 elif opt in ('-e', '--extraconf'):
46 config_files.append(value)
48 reset()
50 def reset():
51 global bin_paths
52 global config
53 global configs_found
55 bin_paths = {}
57 config = ConfigParser.ConfigParser()
58 configs_found = config.read(config_files)
59 if not configs_found:
60 print ('WARNING: pyTivo.conf does not exist.\n' +
61 'Assuming default values.')
62 configs_found = config_files[-1:]
64 for section in config.sections():
65 if section.startswith('_tivo_'):
66 tsn = section[6:]
67 if tsn.upper() not in ['SD', 'HD']:
68 if config.has_option(section, 'name'):
69 tivo_names[tsn] = config.get(section, 'name')
70 else:
71 tivo_names[tsn] = tsn
72 if config.has_option(section, 'address'):
73 tivos[tsn] = config.get(section, 'address')
75 for section in ['Server', '_tivo_SD', '_tivo_HD']:
76 if not config.has_section(section):
77 config.add_section(section)
79 def write():
80 f = open(configs_found[-1], 'w')
81 config.write(f)
82 f.close()
84 def tivos_by_ip(tivoIP):
85 for key, value in tivos.items():
86 if value == tivoIP:
87 return key
89 def get_server(name, default=None):
90 if config.has_option('Server', name):
91 return config.get('Server', name)
92 else:
93 return default
95 def getGUID():
96 return guid
98 def get_ip(tsn=None):
99 dest_ip = tivos.get(tsn, '4.2.2.1')
100 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
101 s.connect((dest_ip, 123))
102 return s.getsockname()[0]
104 def get_zc():
105 opt = get_server('zeroconf', 'auto').lower()
107 if opt == 'auto':
108 for section in config.sections():
109 if section.startswith('_tivo_'):
110 if config.has_option(section, 'shares'):
111 logger = logging.getLogger('pyTivo.config')
112 logger.info('Shares security in use -- zeroconf disabled')
113 return False
114 elif opt in ['false', 'no', 'off']:
115 return False
117 return True
119 def get_mind(tsn):
120 if tsn and tsn.startswith('663'):
121 default = 'symind.tivo.com:8181'
122 else:
123 default = 'mind.tivo.com:8181'
124 return get_server('tivo_mind', default)
126 def getBeaconAddresses():
127 return get_server('beacon', '255.255.255.255')
129 def getPort():
130 return get_server('port', '9032')
132 def get169Blacklist(tsn): # tivo does not pad 16:9 video
133 return tsn and not isHDtivo(tsn) and not get169Letterbox(tsn)
134 # verified Blacklist Tivo's are ('130', '240', '540')
135 # It is assumed all remaining non-HD and non-Letterbox tivos are Blacklist
137 def get169Letterbox(tsn): # tivo pads 16:9 video for 4:3 display
138 return tsn and tsn[:3] in ['649']
140 def get169Setting(tsn):
141 if not tsn:
142 return True
144 tsnsect = '_tivo_' + tsn
145 if config.has_section(tsnsect):
146 if config.has_option(tsnsect, 'aspect169'):
147 try:
148 return config.getboolean(tsnsect, 'aspect169')
149 except ValueError:
150 pass
152 if get169Blacklist(tsn) or get169Letterbox(tsn):
153 return False
155 return True
157 def getAllowedClients():
158 return get_server('allowedips', '').split()
160 def getIsExternal(tsn):
161 tsnsect = '_tivo_' + tsn
162 if tsnsect in config.sections():
163 if config.has_option(tsnsect, 'external'):
164 try:
165 return config.getboolean(tsnsect, 'external')
166 except ValueError:
167 pass
169 return False
171 def isTsnInConfig(tsn):
172 return ('_tivo_' + tsn) in config.sections()
174 def getShares(tsn=''):
175 shares = [(section, dict(config.items(section)))
176 for section in config.sections()
177 if not (section.startswith('_tivo_')
178 or section.startswith('logger_')
179 or section.startswith('handler_')
180 or section.startswith('formatter_')
181 or section in ('Server', 'loggers', 'handlers',
182 'formatters')
186 tsnsect = '_tivo_' + tsn
187 if config.has_section(tsnsect) and config.has_option(tsnsect, 'shares'):
188 # clean up leading and trailing spaces & make sure ref is valid
189 tsnshares = []
190 for x in config.get(tsnsect, 'shares').split(','):
191 y = x.strip()
192 if config.has_section(y):
193 tsnshares.append((y, dict(config.items(y))))
194 shares = tsnshares
196 shares.sort()
198 if get_server('nosettings', 'false').lower() in ['false', 'no', 'off']:
199 shares.append(('Settings', {'type': 'settings'}))
200 if get_server('tivo_mak') and get_server('togo_path'):
201 shares.append(('ToGo', {'type': 'togo'}))
203 return shares
205 def getDebug():
206 try:
207 return config.getboolean('Server', 'debug')
208 except NoOptionError, ValueError:
209 return False
211 def getOptres(tsn=None):
212 try:
213 return config.getboolean('_tivo_' + tsn, 'optres')
214 except:
215 try:
216 return config.getboolean(get_section(tsn), 'optres')
217 except:
218 try:
219 return config.getboolean('Server', 'optres')
220 except:
221 return False
223 def get_bin(fname):
224 global bin_paths
226 logger = logging.getLogger('pyTivo.config')
228 if fname in bin_paths:
229 return bin_paths[fname]
231 if config.has_option('Server', fname):
232 fpath = config.get('Server', fname)
233 if os.path.exists(fpath) and os.path.isfile(fpath):
234 bin_paths[fname] = fpath
235 return fpath
236 else:
237 logger.error('Bad %s path: %s' % (fname, fpath))
239 if sys.platform == 'win32':
240 fext = '.exe'
241 else:
242 fext = ''
244 for path in ([os.path.join(os.path.dirname(__file__), 'bin')] +
245 os.getenv('PATH').split(os.pathsep)):
246 fpath = os.path.join(path, fname + fext)
247 if os.path.exists(fpath) and os.path.isfile(fpath):
248 bin_paths[fname] = fpath
249 return fpath
251 logger.warn('%s not found' % fname)
252 return None
254 def getFFmpegWait():
255 if config.has_option('Server', 'ffmpeg_wait'):
256 return max(int(float(config.get('Server', 'ffmpeg_wait'))), 1)
257 else:
258 return 0
260 def getFFmpegTemplate(tsn):
261 tmpl = get_tsn('ffmpeg_tmpl', tsn, True)
262 if tmpl:
263 return tmpl
264 return '%(video_codec)s %(video_fps)s %(video_br)s %(max_video_br)s \
265 %(buff_size)s %(aspect_ratio)s %(audio_br)s \
266 %(audio_fr)s %(audio_ch)s %(audio_codec)s %(audio_lang)s \
267 %(ffmpeg_pram)s %(format)s'
269 def getFFmpegPrams(tsn):
270 return get_tsn('ffmpeg_pram', tsn, True)
272 def isHDtivo(tsn): # tsn's of High Definition Tivo's
273 return bool(tsn and tsn[0] >= '6' and tsn[:3] != '649')
275 def has_ts_flag():
276 try:
277 return config.getboolean('Server', 'ts')
278 except NoOptionError, ValueError:
279 return False
281 def is_ts_capable(tsn): # tsn's of Tivos that support transport streams
282 return bool(tsn and (tsn[0] >= '7' or tsn.startswith('663')))
284 def getValidWidths():
285 return [1920, 1440, 1280, 720, 704, 544, 480, 352]
287 def getValidHeights():
288 return [1080, 720, 480] # Technically 240 is also supported
290 # Return the number in list that is nearest to x
291 # if two values are equidistant, return the larger
292 def nearest(x, list):
293 return reduce(lambda a, b: closest(x, a, b), list)
295 def closest(x, a, b):
296 da = abs(x - a)
297 db = abs(x - b)
298 if da < db or (da == db and a > b):
299 return a
300 else:
301 return b
303 def nearestTivoHeight(height):
304 return nearest(height, getValidHeights())
306 def nearestTivoWidth(width):
307 return nearest(width, getValidWidths())
309 def getTivoHeight(tsn):
310 height = get_tsn('height', tsn)
311 if height:
312 return nearestTivoHeight(int(height))
313 return [480, 1080][isHDtivo(tsn)]
315 def getTivoWidth(tsn):
316 width = get_tsn('width', tsn)
317 if width:
318 return nearestTivoWidth(int(width))
319 return [544, 1920][isHDtivo(tsn)]
321 def _trunc64(i):
322 return max(int(strtod(i)) / 64000, 1) * 64
324 def getAudioBR(tsn=None):
325 rate = get_tsn('audio_br', tsn)
326 if not rate:
327 rate = '448k'
328 # convert to non-zero multiple of 64 to ensure ffmpeg compatibility
329 # compare audio_br to max_audio_br and return lowest
330 return str(min(_trunc64(rate), getMaxAudioBR(tsn))) + 'k'
332 def _k(i):
333 return str(int(strtod(i)) / 1000) + 'k'
335 def getVideoBR(tsn=None):
336 rate = get_tsn('video_br', tsn)
337 if rate:
338 return _k(rate)
339 return ['4096K', '16384K'][isHDtivo(tsn)]
341 def getMaxVideoBR(tsn=None):
342 rate = get_tsn('max_video_br', tsn)
343 if rate:
344 return _k(rate)
345 return '30000k'
347 def getBuffSize(tsn=None):
348 size = get_tsn('bufsize', tsn)
349 if size:
350 return _k(size)
351 return ['1024k', '4096k'][isHDtivo(tsn)]
353 def getMaxAudioBR(tsn=None):
354 rate = get_tsn('max_audio_br', tsn)
355 # convert to non-zero multiple of 64 for ffmpeg compatibility
356 if rate:
357 return _trunc64(rate)
358 return 448
360 def get_section(tsn):
361 return ['_tivo_SD', '_tivo_HD'][isHDtivo(tsn)]
363 def get_tsn(name, tsn=None, raw=False):
364 try:
365 return config.get('_tivo_' + tsn, name, raw)
366 except:
367 try:
368 return config.get(get_section(tsn), name, raw)
369 except:
370 try:
371 return config.get('Server', name, raw)
372 except:
373 return None
375 # Parse a bitrate using the SI/IEEE suffix values as if by ffmpeg
376 # For example, 2K==2000, 2Ki==2048, 2MB==16000000, 2MiB==16777216
377 # Algorithm: http://svn.mplayerhq.hu/ffmpeg/trunk/libavcodec/eval.c
378 def strtod(value):
379 prefixes = {'y': -24, 'z': -21, 'a': -18, 'f': -15, 'p': -12,
380 'n': -9, 'u': -6, 'm': -3, 'c': -2, 'd': -1,
381 'h': 2, 'k': 3, 'K': 3, 'M': 6, 'G': 9,
382 'T': 12, 'P': 15, 'E': 18, 'Z': 21, 'Y': 24}
383 p = re.compile(r'^(\d+)(?:([yzafpnumcdhkKMGTPEZY])(i)?)?([Bb])?$')
384 m = p.match(value)
385 if not m:
386 raise SyntaxError('Invalid bit value syntax')
387 (coef, prefix, power, byte) = m.groups()
388 if prefix is None:
389 value = float(coef)
390 else:
391 exponent = float(prefixes[prefix])
392 if power == 'i':
393 # Use powers of 2
394 value = float(coef) * pow(2.0, exponent / 0.3)
395 else:
396 # Use powers of 10
397 value = float(coef) * pow(10.0, exponent)
398 if byte == 'B': # B == Byte, b == bit
399 value *= 8;
400 return value
402 def init_logging():
403 if (config.has_section('loggers') and
404 config.has_section('handlers') and
405 config.has_section('formatters')):
407 logging.config.fileConfig(config_files)
409 elif getDebug():
410 logging.basicConfig(level=logging.DEBUG)
411 else:
412 logging.basicConfig(level=logging.INFO)