allow 2 channel AAC audio to transfer (without) reencoding while
[pyTivo/wmcbrine/lucasnz.git] / config.py
blobcf1d8f3cbcfb17021b0281ab01be2c1431c60ba9
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 p = os.path.dirname(__file__)
18 config_files = ['/etc/pyTivo.conf', os.path.join(p, 'pyTivo.conf')]
19 configs_found = []
21 tivos = {}
22 tivo_names = {}
23 bin_paths = {}
25 def init(argv):
26 global config_files
27 global configs_found
28 global tivo_names
30 try:
31 opts, _ = getopt.getopt(argv, 'c:e:', ['config=', 'extraconf='])
32 except getopt.GetoptError, msg:
33 print msg
35 for opt, value in opts:
36 if opt in ('-c', '--config'):
37 config_files = [value]
38 elif opt in ('-e', '--extraconf'):
39 config_files.append(value)
41 configs_found = config.read(config_files)
42 if not configs_found:
43 print ('ERROR: pyTivo.conf does not exist.\n' +
44 'You must create this file before running pyTivo.')
45 sys.exit(1)
47 for section in config.sections():
48 if section.startswith('_tivo_'):
49 tsn = section[6:]
50 if tsn.upper() not in ['SD', 'HD']:
51 if config.has_option(section, 'name'):
52 tivo_names[tsn] = config.get(section, 'name')
53 else:
54 tivo_names[tsn] = tsn
55 if config.has_option(section, 'address'):
56 tivos[tsn] = config.get(section, 'address')
58 def reset():
59 global config
60 global bin_paths
61 bin_paths.clear()
62 newconfig = ConfigParser.ConfigParser()
63 newconfig.read(config_files)
64 config = newconfig
66 def write():
67 f = open(configs_found[-1], 'w')
68 config.write(f)
69 f.close()
71 def get_server(name, default=None):
72 if config.has_option('Server', name):
73 return config.get('Server', name)
74 else:
75 return default
77 def getGUID():
78 return guid
80 def get_ip():
81 global our_ip
82 if not our_ip:
83 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
84 s.connect(('4.2.2.1', 123))
85 our_ip = s.getsockname()[0]
86 return our_ip
88 def get_zc():
89 opt = get_server('zeroconf', 'auto').lower()
91 if opt == 'auto':
92 for section in config.sections():
93 if section.startswith('_tivo_'):
94 if config.has_option(section, 'shares'):
95 logger = logging.getLogger('pyTivo.config')
96 logger.info('Shares security in use -- zeroconf disabled')
97 return False
98 elif opt in ['false', 'no', 'off']:
99 return False
101 return True
103 def get_mind(tsn):
104 if tsn and tsn.startswith('663'):
105 default = 'symind.tivo.com:8181'
106 else:
107 default = 'mind.tivo.com:8181'
108 return get_server('tivo_mind', default)
110 def getBeaconAddresses():
111 return get_server('beacon', '255.255.255.255')
113 def getPort():
114 return get_server('port', '9032')
116 def get169Blacklist(tsn): # tivo does not pad 16:9 video
117 return tsn and not isHDtivo(tsn) and not get169Letterbox(tsn)
118 # verified Blacklist Tivo's are ('130', '240', '540')
119 # It is assumed all remaining non-HD and non-Letterbox tivos are Blacklist
121 def get169Letterbox(tsn): # tivo pads 16:9 video for 4:3 display
122 return tsn and tsn[:3] in ['649']
124 def get169Setting(tsn):
125 if not tsn:
126 return True
128 tsnsect = '_tivo_' + tsn
129 if config.has_section(tsnsect):
130 if config.has_option(tsnsect, 'aspect169'):
131 try:
132 return config.getboolean(tsnsect, 'aspect169')
133 except ValueError:
134 pass
136 if get169Blacklist(tsn) or get169Letterbox(tsn):
137 return False
139 return True
141 def getAllowedClients():
142 return get_server('allowedips', '').split()
144 def getIsExternal(tsn):
145 tsnsect = '_tivo_' + tsn
146 if tsnsect in config.sections():
147 if config.has_option(tsnsect, 'external'):
148 try:
149 return config.getboolean(tsnsect, 'external')
150 except ValueError:
151 pass
153 return False
155 def isTsnInConfig(tsn):
156 return ('_tivo_' + tsn) in config.sections()
158 def getShares(tsn=''):
159 shares = [(section, dict(config.items(section)))
160 for section in config.sections()
161 if not (section.startswith('_tivo_')
162 or section.startswith('logger_')
163 or section.startswith('handler_')
164 or section.startswith('formatter_')
165 or section in ('Server', 'loggers', 'handlers',
166 'formatters')
170 tsnsect = '_tivo_' + tsn
171 if config.has_section(tsnsect) and config.has_option(tsnsect, 'shares'):
172 # clean up leading and trailing spaces & make sure ref is valid
173 tsnshares = []
174 for x in config.get(tsnsect, 'shares').split(','):
175 y = x.strip()
176 if config.has_section(y):
177 tsnshares.append((y, dict(config.items(y))))
178 shares = tsnshares
180 shares.sort()
182 if get_server('nosettings', 'false').lower() in ['false', 'no', 'off']:
183 shares.append(('Settings', {'type': 'settings'}))
184 if get_server('tivo_mak') and get_server('togo_path'):
185 shares.append(('ToGo', {'type': 'togo'}))
187 return shares
189 def getDebug():
190 try:
191 return config.getboolean('Server', 'debug')
192 except NoOptionError, ValueError:
193 return False
195 def getOptres(tsn=None):
196 if tsn and config.has_section('_tivo_' + tsn):
197 try:
198 return config.getboolean('_tivo_' + tsn, 'optres')
199 except NoOptionError, ValueError:
200 pass
201 section_name = get_section(tsn)
202 if config.has_section(section_name):
203 try:
204 return config.getboolean(section_name, 'optres')
205 except NoOptionError, ValueError:
206 pass
207 try:
208 return config.getboolean('Server', 'optres')
209 except NoOptionError, ValueError:
210 return False
212 def getPixelAR(ref):
213 if config.has_option('Server', 'par'):
214 try:
215 return (True, config.getfloat('Server', 'par'))[ref]
216 except NoOptionError, ValueError:
217 pass
218 return (False, 1.0)[ref]
220 def get_bin(fname):
221 global bin_paths
223 logger = logging.getLogger('pyTivo.config')
225 if fname in bin_paths:
226 return bin_paths[fname]
228 if config.has_option('Server', fname):
229 fpath = config.get('Server', fname)
230 if os.path.exists(fpath) and os.path.isfile(fpath):
231 bin_paths[fname] = fpath
232 return fpath
233 else:
234 logger.error('Bad %s path: %s' % (fname, fpath))
236 if sys.platform == 'win32':
237 fext = '.exe'
238 else:
239 fext = ''
241 for path in ([os.path.join(os.path.dirname(__file__), 'bin')] +
242 os.getenv('PATH').split(os.pathsep)):
243 fpath = os.path.join(path, fname + fext)
244 if os.path.exists(fpath) and os.path.isfile(fpath):
245 bin_paths[fname] = fpath
246 return fpath
248 logger.warn('%s not found' % fname)
249 return None
251 def getFFmpegWait():
252 if config.has_option('Server', 'ffmpeg_wait'):
253 return max(int(float(config.get('Server', 'ffmpeg_wait'))), 1)
254 else:
255 return 10
257 def getFFmpegTemplate(tsn):
258 tmpl = get_tsn('ffmpeg_tmpl', tsn, True)
259 if tmpl:
260 return tmpl
261 return '%(video_codec)s %(video_fps)s %(video_br)s %(max_video_br)s \
262 %(buff_size)s %(aspect_ratio)s %(audio_br)s \
263 %(audio_fr)s %(audio_ch)s %(audio_codec)s %(audio_lang)s \
264 %(ffmpeg_pram)s %(format)s'
266 def getFFmpegPrams(tsn):
267 return get_tsn('ffmpeg_pram', tsn, True)
269 def isHDtivo(tsn): # tsn's of High Definition Tivo's
270 return bool(tsn and tsn[0] >= '6' and tsn[:3] != '649')
272 def getValidWidths():
273 return [1920, 1440, 1280, 720, 704, 544, 480, 352]
275 def getValidHeights():
276 return [1080, 720, 480] # Technically 240 is also supported
278 # Return the number in list that is nearest to x
279 # if two values are equidistant, return the larger
280 def nearest(x, list):
281 return reduce(lambda a, b: closest(x, a, b), list)
283 def closest(x, a, b):
284 da = abs(x - a)
285 db = abs(x - b)
286 if da < db or (da == db and a > b):
287 return a
288 else:
289 return b
291 def nearestTivoHeight(height):
292 return nearest(height, getValidHeights())
294 def nearestTivoWidth(width):
295 return nearest(width, getValidWidths())
297 def getTivoHeight(tsn):
298 height = get_tsn('height', tsn)
299 if height:
300 return nearestTivoHeight(int(height))
301 return [480, 1080][isHDtivo(tsn)]
303 def getTivoWidth(tsn):
304 width = get_tsn('width', tsn)
305 if width:
306 return nearestTivoWidth(int(width))
307 return [544, 1920][isHDtivo(tsn)]
309 def _trunc64(i):
310 return max(int(strtod(i)) / 64000, 1) * 64
312 def getAudioBR(tsn=None):
313 rate = get_tsn('audio_br', tsn)
314 if not rate:
315 rate = '448k'
316 # convert to non-zero multiple of 64 to ensure ffmpeg compatibility
317 # compare audio_br to max_audio_br and return lowest
318 return str(min(_trunc64(rate), getMaxAudioBR(tsn))) + 'k'
320 def _k(i):
321 return str(int(strtod(i)) / 1000) + 'k'
323 def getVideoBR(tsn=None):
324 rate = get_tsn('video_br', tsn)
325 if rate:
326 return _k(rate)
327 return ['4096K', '16384K'][isHDtivo(tsn)]
329 def getMaxVideoBR(tsn=None):
330 rate = get_tsn('max_video_br', tsn)
331 if rate:
332 return _k(rate)
333 return '30000k'
335 def getVideoPCT(tsn=None):
336 pct = get_tsn('video_pct', tsn)
337 if pct:
338 return float(pct)
339 return 85
341 def getBuffSize(tsn=None):
342 size = get_tsn('bufsize', tsn)
343 if size:
344 return _k(size)
345 return ['1024k', '4096k'][isHDtivo(tsn)]
347 def getMaxAudioBR(tsn=None):
348 rate = get_tsn('max_audio_br', tsn)
349 # convert to non-zero multiple of 64 for ffmpeg compatibility
350 if rate:
351 return _trunc64(rate)
352 return 448
354 def get_section(tsn):
355 return ['_tivo_SD', '_tivo_HD'][isHDtivo(tsn)]
357 def get_tsn(name, tsn=None, raw=False):
358 if tsn and config.has_section('_tivo_' + tsn):
359 try:
360 return config.get('_tivo_' + tsn, name, raw)
361 except NoOptionError:
362 pass
363 section_name = get_section(tsn)
364 if config.has_section(section_name):
365 try:
366 return config.get(section_name, name, raw)
367 except NoOptionError:
368 pass
369 try:
370 return config.get('Server', name, raw)
371 except NoOptionError:
372 pass
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)