Use 'ts' = 'on' in server section instead of togo_mpegts to align
[pyTivo/wmcbrine/lucasnz.git] / config.py
blob48be28470704936914bad9d6560336916d140d78
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 getPixelAR(ref):
224 if config.has_option('Server', 'par'):
225 try:
226 return (True, config.getfloat('Server', 'par'))[ref]
227 except NoOptionError, ValueError:
228 pass
229 return (False, 1.0)[ref]
231 def get_bin(fname):
232 global bin_paths
234 logger = logging.getLogger('pyTivo.config')
236 if fname in bin_paths:
237 return bin_paths[fname]
239 if config.has_option('Server', fname):
240 fpath = config.get('Server', fname)
241 if os.path.exists(fpath) and os.path.isfile(fpath):
242 bin_paths[fname] = fpath
243 return fpath
244 else:
245 logger.error('Bad %s path: %s' % (fname, fpath))
247 if sys.platform == 'win32':
248 fext = '.exe'
249 else:
250 fext = ''
252 for path in ([os.path.join(os.path.dirname(__file__), 'bin')] +
253 os.getenv('PATH').split(os.pathsep)):
254 fpath = os.path.join(path, fname + fext)
255 if os.path.exists(fpath) and os.path.isfile(fpath):
256 bin_paths[fname] = fpath
257 return fpath
259 logger.warn('%s not found' % fname)
260 return None
262 def getFFmpegWait():
263 if config.has_option('Server', 'ffmpeg_wait'):
264 return max(int(float(config.get('Server', 'ffmpeg_wait'))), 1)
265 else:
266 return 10
268 def getFFmpegTemplate(tsn):
269 tmpl = get_tsn('ffmpeg_tmpl', tsn, True)
270 if tmpl:
271 return tmpl
272 return '%(video_codec)s %(video_fps)s %(video_br)s %(max_video_br)s \
273 %(buff_size)s %(aspect_ratio)s %(audio_br)s \
274 %(audio_fr)s %(audio_ch)s %(audio_codec)s %(audio_lang)s \
275 %(ffmpeg_pram)s %(format)s'
277 def getFFmpegPrams(tsn):
278 return get_tsn('ffmpeg_pram', tsn, True)
280 def isHDtivo(tsn): # tsn's of High Definition Tivo's
281 return bool(tsn and tsn[0] >= '6' and tsn[:3] != '649')
283 def hasTStivo(tsn): # tsn's of Tivos that support transport streams
284 try:
285 return config.getboolean('Server', 'ts')
286 except NoOptionError, ValueError:
287 return False
288 return bool(tsn and (tsn[0] >= '7' or tsn.startswith('663')))
290 def getValidWidths():
291 return [1920, 1440, 1280, 720, 704, 544, 480, 352]
293 def getValidHeights():
294 return [1080, 720, 480] # Technically 240 is also supported
296 # Return the number in list that is nearest to x
297 # if two values are equidistant, return the larger
298 def nearest(x, list):
299 return reduce(lambda a, b: closest(x, a, b), list)
301 def closest(x, a, b):
302 da = abs(x - a)
303 db = abs(x - b)
304 if da < db or (da == db and a > b):
305 return a
306 else:
307 return b
309 def nearestTivoHeight(height):
310 return nearest(height, getValidHeights())
312 def nearestTivoWidth(width):
313 return nearest(width, getValidWidths())
315 def getTivoHeight(tsn):
316 height = get_tsn('height', tsn)
317 if height:
318 return nearestTivoHeight(int(height))
319 return [480, 1080][isHDtivo(tsn)]
321 def getTivoWidth(tsn):
322 width = get_tsn('width', tsn)
323 if width:
324 return nearestTivoWidth(int(width))
325 return [544, 1920][isHDtivo(tsn)]
327 def _trunc64(i):
328 return max(int(strtod(i)) / 64000, 1) * 64
330 def getAudioBR(tsn=None):
331 rate = get_tsn('audio_br', tsn)
332 if not rate:
333 rate = '448k'
334 # convert to non-zero multiple of 64 to ensure ffmpeg compatibility
335 # compare audio_br to max_audio_br and return lowest
336 return str(min(_trunc64(rate), getMaxAudioBR(tsn))) + 'k'
338 def _k(i):
339 return str(int(strtod(i)) / 1000) + 'k'
341 def getVideoBR(tsn=None):
342 rate = get_tsn('video_br', tsn)
343 if rate:
344 return _k(rate)
345 return ['4096K', '16384K'][isHDtivo(tsn)]
347 def getMaxVideoBR(tsn=None):
348 rate = get_tsn('max_video_br', tsn)
349 if rate:
350 return _k(rate)
351 return '30000k'
353 def getVideoPCT(tsn=None):
354 pct = get_tsn('video_pct', tsn)
355 if pct:
356 return float(pct)
357 return 85
359 def getBuffSize(tsn=None):
360 size = get_tsn('bufsize', tsn)
361 if size:
362 return _k(size)
363 return ['1024k', '4096k'][isHDtivo(tsn)]
365 def getMaxAudioBR(tsn=None):
366 rate = get_tsn('max_audio_br', tsn)
367 # convert to non-zero multiple of 64 for ffmpeg compatibility
368 if rate:
369 return _trunc64(rate)
370 return 448
372 def get_section(tsn):
373 return ['_tivo_SD', '_tivo_HD'][isHDtivo(tsn)]
375 def get_tsn(name, tsn=None, raw=False):
376 try:
377 return config.get('_tivo_' + tsn, name, raw)
378 except:
379 try:
380 return config.get(get_section(tsn), name, raw)
381 except:
382 try:
383 return config.get('Server', name, raw)
384 except:
385 return None
387 # Parse a bitrate using the SI/IEEE suffix values as if by ffmpeg
388 # For example, 2K==2000, 2Ki==2048, 2MB==16000000, 2MiB==16777216
389 # Algorithm: http://svn.mplayerhq.hu/ffmpeg/trunk/libavcodec/eval.c
390 def strtod(value):
391 prefixes = {'y': -24, 'z': -21, 'a': -18, 'f': -15, 'p': -12,
392 'n': -9, 'u': -6, 'm': -3, 'c': -2, 'd': -1,
393 'h': 2, 'k': 3, 'K': 3, 'M': 6, 'G': 9,
394 'T': 12, 'P': 15, 'E': 18, 'Z': 21, 'Y': 24}
395 p = re.compile(r'^(\d+)(?:([yzafpnumcdhkKMGTPEZY])(i)?)?([Bb])?$')
396 m = p.match(value)
397 if not m:
398 raise SyntaxError('Invalid bit value syntax')
399 (coef, prefix, power, byte) = m.groups()
400 if prefix is None:
401 value = float(coef)
402 else:
403 exponent = float(prefixes[prefix])
404 if power == 'i':
405 # Use powers of 2
406 value = float(coef) * pow(2.0, exponent / 0.3)
407 else:
408 # Use powers of 10
409 value = float(coef) * pow(10.0, exponent)
410 if byte == 'B': # B == Byte, b == bit
411 value *= 8;
412 return value
414 def init_logging():
415 if (config.has_section('loggers') and
416 config.has_section('handlers') and
417 config.has_section('formatters')):
419 logging.config.fileConfig(config_files)
421 elif getDebug():
422 logging.basicConfig(level=logging.DEBUG)
423 else:
424 logging.basicConfig(level=logging.INFO)