Added favicon.ico from tivo.com
[pyTivo/wmcbrine/lucasnz.git] / config.py
blobe6084dc7e015d1b8e31f2a097ce5e8593c326f86
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 guid = ''.join([random.choice(string.letters) for i in range(10)])
14 our_ip = ''
15 config = ConfigParser.ConfigParser()
17 config_win_default = ''
19 if sys.platform == "win32":
20 import _winreg
22 try:
23 explorerFolders = _winreg.OpenKey(
24 _winreg.HKEY_LOCAL_MACHINE,
25 'Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders'
28 winCommonAppDataVal, winCommonAppDataType = _winreg.QueryValueEx(explorerFolders, 'Common AppData')
30 config_win_default = os.path.join(winCommonAppDataVal, 'pyTivo', 'pyTivo.conf')
32 except WindowsError:
33 print "Can't access Windows Registry to find common Application Data path."
35 p = os.path.dirname(__file__)
36 config_files = ['/etc/pyTivo.conf', config_win_default, os.path.join(p, 'pyTivo.conf')]
37 configs_found = []
39 tivos = {}
40 tivo_names = {}
41 bin_paths = {}
43 def init(argv):
44 global config_files
45 global configs_found
46 global tivo_names
48 try:
49 opts, _ = getopt.getopt(argv, 'c:e:', ['config=', 'extraconf='])
50 except getopt.GetoptError, msg:
51 print msg
53 for opt, value in opts:
54 if opt in ('-c', '--config'):
55 config_files = [value]
56 elif opt in ('-e', '--extraconf'):
57 config_files.append(value)
59 configs_found = config.read(config_files)
60 if not configs_found:
61 print ('ERROR: pyTivo.conf does not exist.\n' +
62 'You must create this file before running pyTivo.')
63 sys.exit(1)
65 for section in config.sections():
66 if section.startswith('_tivo_'):
67 tsn = section[6:]
68 if tsn.upper() not in ['SD', 'HD']:
69 if config.has_option(section, 'name'):
70 tivo_names[tsn] = config.get(section, 'name')
71 else:
72 tivo_names[tsn] = tsn
73 if config.has_option(section, 'address'):
74 tivos[tsn] = config.get(section, 'address')
76 def reset():
77 global config
78 global bin_paths
79 bin_paths.clear()
80 newconfig = ConfigParser.ConfigParser()
81 newconfig.read(config_files)
82 config = newconfig
84 def write():
85 f = open(configs_found[-1], 'w')
86 config.write(f)
87 f.close()
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():
99 global our_ip
100 if not our_ip:
101 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
102 s.connect(('4.2.2.1', 123))
103 our_ip = s.getsockname()[0]
104 return our_ip
106 def get_zc():
107 opt = get_server('zeroconf', 'auto').lower()
109 if opt == 'auto':
110 for section in config.sections():
111 if section.startswith('_tivo_'):
112 if config.has_option(section, 'shares'):
113 logger = logging.getLogger('pyTivo.config')
114 logger.info('Shares security in use -- zeroconf disabled')
115 return False
116 elif opt in ['false', 'no', 'off']:
117 return False
119 return True
121 def get_mind(tsn):
122 if tsn and tsn.startswith('663'):
123 default = 'symind.tivo.com:8181'
124 else:
125 default = 'mind.tivo.com:8181'
126 return get_server('tivo_mind', default)
128 def getBeaconAddresses():
129 return get_server('beacon', '255.255.255.255')
131 def getPort():
132 return get_server('port', '9032')
134 def get169Blacklist(tsn): # tivo does not pad 16:9 video
135 return tsn and not isHDtivo(tsn) and not get169Letterbox(tsn)
136 # verified Blacklist Tivo's are ('130', '240', '540')
137 # It is assumed all remaining non-HD and non-Letterbox tivos are Blacklist
139 def get169Letterbox(tsn): # tivo pads 16:9 video for 4:3 display
140 return tsn and tsn[:3] in ['649']
142 def get169Setting(tsn):
143 if not tsn:
144 return True
146 tsnsect = '_tivo_' + tsn
147 if config.has_section(tsnsect):
148 if config.has_option(tsnsect, 'aspect169'):
149 try:
150 return config.getboolean(tsnsect, 'aspect169')
151 except ValueError:
152 pass
154 if get169Blacklist(tsn) or get169Letterbox(tsn):
155 return False
157 return True
159 def getAllowedClients():
160 return get_server('allowedips', '').split()
162 def getIsExternal(tsn):
163 tsnsect = '_tivo_' + tsn
164 if tsnsect in config.sections():
165 if config.has_option(tsnsect, 'external'):
166 try:
167 return config.getboolean(tsnsect, 'external')
168 except ValueError:
169 pass
171 return False
173 def isTsnInConfig(tsn):
174 return ('_tivo_' + tsn) in config.sections()
176 def getShares(tsn=''):
177 shares = [(section, dict(config.items(section)))
178 for section in config.sections()
179 if not (section.startswith('_tivo_')
180 or section.startswith('logger_')
181 or section.startswith('handler_')
182 or section.startswith('formatter_')
183 or section in ('Server', 'loggers', 'handlers',
184 'formatters')
188 tsnsect = '_tivo_' + tsn
189 if config.has_section(tsnsect) and config.has_option(tsnsect, 'shares'):
190 # clean up leading and trailing spaces & make sure ref is valid
191 tsnshares = []
192 for x in config.get(tsnsect, 'shares').split(','):
193 y = x.strip()
194 if config.has_section(y):
195 tsnshares.append((y, dict(config.items(y))))
196 shares = tsnshares
198 shares.sort()
200 if get_server('nosettings', 'false').lower() in ['false', 'no', 'off']:
201 shares.append(('Settings', {'type': 'settings'}))
202 if get_server('tivo_mak') and get_server('togo_path'):
203 shares.append(('ToGo', {'type': 'togo'}))
205 return shares
207 def getDebug():
208 try:
209 return config.getboolean('Server', 'debug')
210 except NoOptionError, ValueError:
211 return False
213 def getOptres(tsn=None):
214 if tsn and config.has_section('_tivo_' + tsn):
215 try:
216 return config.getboolean('_tivo_' + tsn, 'optres')
217 except NoOptionError, ValueError:
218 pass
219 section_name = get_section(tsn)
220 if config.has_section(section_name):
221 try:
222 return config.getboolean(section_name, 'optres')
223 except NoOptionError, ValueError:
224 pass
225 try:
226 return config.getboolean('Server', 'optres')
227 except NoOptionError, ValueError:
228 return False
230 def getPixelAR(ref):
231 if config.has_option('Server', 'par'):
232 try:
233 return (True, config.getfloat('Server', 'par'))[ref]
234 except NoOptionError, ValueError:
235 pass
236 return (False, 1.0)[ref]
238 def get_bin(fname):
239 global bin_paths
241 logger = logging.getLogger('pyTivo.config')
243 if fname in bin_paths:
244 return bin_paths[fname]
246 if config.has_option('Server', fname):
247 fpath = config.get('Server', fname)
248 if os.path.exists(fpath) and os.path.isfile(fpath):
249 bin_paths[fname] = fpath
250 return fpath
251 else:
252 logger.error('Bad %s path: %s' % (fname, fpath))
254 if sys.platform == 'win32':
255 fext = '.exe'
256 else:
257 fext = ''
259 for path in ([os.path.join(os.path.dirname(__file__), 'bin')] +
260 os.getenv('PATH').split(os.pathsep)):
261 fpath = os.path.join(path, fname + fext)
262 if os.path.exists(fpath) and os.path.isfile(fpath):
263 bin_paths[fname] = fpath
264 return fpath
266 logger.warn('%s not found' % fname)
267 return None
269 def getFFmpegWait():
270 if config.has_option('Server', 'ffmpeg_wait'):
271 return max(int(float(config.get('Server', 'ffmpeg_wait'))), 1)
272 else:
273 return 10
275 def getFFmpegTemplate(tsn):
276 tmpl = get_tsn('ffmpeg_tmpl', tsn, True)
277 if tmpl:
278 return tmpl
279 return '%(video_codec)s %(video_fps)s %(video_br)s %(max_video_br)s \
280 %(buff_size)s %(aspect_ratio)s %(audio_br)s \
281 %(audio_fr)s %(audio_ch)s %(audio_codec)s %(audio_lang)s \
282 %(ffmpeg_pram)s %(format)s'
284 def getFFmpegPrams(tsn):
285 return get_tsn('ffmpeg_pram', tsn, True)
287 def isHDtivo(tsn): # tsn's of High Definition Tivo's
288 return bool(tsn and tsn[0] >= '6' and tsn[:3] != '649')
290 def hasTStivo(tsn): # tsn's of Tivos that support transport streams
291 try:
292 return config.getboolean('Server', 'ts')
293 except NoOptionError, ValueError:
294 return False
295 return bool(tsn and (tsn[0] >= '7' or tsn.startswith('663')))
297 def getValidWidths():
298 return [1920, 1440, 1280, 720, 704, 544, 480, 352]
300 def getValidHeights():
301 return [1080, 720, 480] # Technically 240 is also supported
303 # Return the number in list that is nearest to x
304 # if two values are equidistant, return the larger
305 def nearest(x, list):
306 return reduce(lambda a, b: closest(x, a, b), list)
308 def closest(x, a, b):
309 da = abs(x - a)
310 db = abs(x - b)
311 if da < db or (da == db and a > b):
312 return a
313 else:
314 return b
316 def nearestTivoHeight(height):
317 return nearest(height, getValidHeights())
319 def nearestTivoWidth(width):
320 return nearest(width, getValidWidths())
322 def getTivoHeight(tsn):
323 height = get_tsn('height', tsn)
324 if height:
325 return nearestTivoHeight(int(height))
326 return [480, 1080][isHDtivo(tsn)]
328 def getTivoWidth(tsn):
329 width = get_tsn('width', tsn)
330 if width:
331 return nearestTivoWidth(int(width))
332 return [544, 1920][isHDtivo(tsn)]
334 def _trunc64(i):
335 return max(int(strtod(i)) / 64000, 1) * 64
337 def getAudioBR(tsn=None):
338 rate = get_tsn('audio_br', tsn)
339 if not rate:
340 rate = '448k'
341 # convert to non-zero multiple of 64 to ensure ffmpeg compatibility
342 # compare audio_br to max_audio_br and return lowest
343 return str(min(_trunc64(rate), getMaxAudioBR(tsn))) + 'k'
345 def _k(i):
346 return str(int(strtod(i)) / 1000) + 'k'
348 def getVideoBR(tsn=None):
349 rate = get_tsn('video_br', tsn)
350 if rate:
351 return _k(rate)
352 return ['4096K', '16384K'][isHDtivo(tsn)]
354 def getMaxVideoBR(tsn=None):
355 rate = get_tsn('max_video_br', tsn)
356 if rate:
357 return _k(rate)
358 return '30000k'
360 def getVideoPCT(tsn=None):
361 pct = get_tsn('video_pct', tsn)
362 if pct:
363 return float(pct)
364 return 85
366 def getBuffSize(tsn=None):
367 size = get_tsn('bufsize', tsn)
368 if size:
369 return _k(size)
370 return ['1024k', '4096k'][isHDtivo(tsn)]
372 def getMaxAudioBR(tsn=None):
373 rate = get_tsn('max_audio_br', tsn)
374 # convert to non-zero multiple of 64 for ffmpeg compatibility
375 if rate:
376 return _trunc64(rate)
377 return 448
379 def get_section(tsn):
380 return ['_tivo_SD', '_tivo_HD'][isHDtivo(tsn)]
382 def get_tsn(name, tsn=None, raw=False):
383 if tsn and config.has_section('_tivo_' + tsn):
384 try:
385 return config.get('_tivo_' + tsn, name, raw)
386 except NoOptionError:
387 pass
388 section_name = get_section(tsn)
389 if config.has_section(section_name):
390 try:
391 return config.get(section_name, name, raw)
392 except NoOptionError:
393 pass
394 try:
395 return config.get('Server', name, raw)
396 except NoOptionError:
397 pass
398 return None
400 # Parse a bitrate using the SI/IEEE suffix values as if by ffmpeg
401 # For example, 2K==2000, 2Ki==2048, 2MB==16000000, 2MiB==16777216
402 # Algorithm: http://svn.mplayerhq.hu/ffmpeg/trunk/libavcodec/eval.c
403 def strtod(value):
404 prefixes = {'y': -24, 'z': -21, 'a': -18, 'f': -15, 'p': -12,
405 'n': -9, 'u': -6, 'm': -3, 'c': -2, 'd': -1,
406 'h': 2, 'k': 3, 'K': 3, 'M': 6, 'G': 9,
407 'T': 12, 'P': 15, 'E': 18, 'Z': 21, 'Y': 24}
408 p = re.compile(r'^(\d+)(?:([yzafpnumcdhkKMGTPEZY])(i)?)?([Bb])?$')
409 m = p.match(value)
410 if not m:
411 raise SyntaxError('Invalid bit value syntax')
412 (coef, prefix, power, byte) = m.groups()
413 if prefix is None:
414 value = float(coef)
415 else:
416 exponent = float(prefixes[prefix])
417 if power == 'i':
418 # Use powers of 2
419 value = float(coef) * pow(2.0, exponent / 0.3)
420 else:
421 # Use powers of 10
422 value = float(coef) * pow(10.0, exponent)
423 if byte == 'B': # B == Byte, b == bit
424 value *= 8;
425 return value
427 def init_logging():
428 if (config.has_section('loggers') and
429 config.has_section('handlers') and
430 config.has_section('formatters')):
432 logging.config.fileConfig(config_files)
434 elif getDebug():
435 logging.basicConfig(level=logging.DEBUG)
436 else:
437 logging.basicConfig(level=logging.INFO)