Update MP4 remuxing code to allow it to re-encode the audio.
[pyTivo/wmcbrine/lucasnz.git] / config.py
blob18321670e6c875145baa1119c8fb26defb51c835
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 p = os.path.dirname(__file__)
24 config_files = ['/etc/pyTivo.conf', os.path.join(p, 'pyTivo.conf')]
26 try:
27 opts, _ = getopt.getopt(argv, 'c:e:', ['config=', 'extraconf='])
28 except getopt.GetoptError, msg:
29 print msg
31 for opt, value in opts:
32 if opt in ('-c', '--config'):
33 config_files = [value]
34 elif opt in ('-e', '--extraconf'):
35 config_files.append(value)
37 reset()
39 def reset():
40 global bin_paths
41 global config
42 global configs_found
44 bin_paths = {}
46 config = ConfigParser.ConfigParser()
47 configs_found = config.read(config_files)
48 if not configs_found:
49 print ('WARNING: pyTivo.conf does not exist.\n' +
50 'Assuming default values.')
51 configs_found = config_files[-1:]
53 for section in config.sections():
54 if section.startswith('_tivo_'):
55 tsn = section[6:]
56 if tsn.upper() not in ['SD', 'HD']:
57 if config.has_option(section, 'name'):
58 tivo_names[tsn] = config.get(section, 'name')
59 else:
60 tivo_names[tsn] = tsn
61 if config.has_option(section, 'address'):
62 tivos[tsn] = config.get(section, 'address')
64 for section in ['Server', '_tivo_SD', '_tivo_HD']:
65 if not config.has_section(section):
66 config.add_section(section)
68 def write():
69 f = open(configs_found[-1], 'w')
70 config.write(f)
71 f.close()
73 def tivos_by_ip(tivoIP):
74 for key, value in tivos.items():
75 if value == tivoIP:
76 return key
78 def get_server(name, default=None):
79 if config.has_option('Server', name):
80 return config.get('Server', name)
81 else:
82 return default
84 def getGUID():
85 return guid
87 def get_ip(tsn=None):
88 dest_ip = tivos.get(tsn, '4.2.2.1')
89 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
90 s.connect((dest_ip, 123))
91 return s.getsockname()[0]
93 def get_zc():
94 opt = get_server('zeroconf', 'auto').lower()
96 if opt == 'auto':
97 for section in config.sections():
98 if section.startswith('_tivo_'):
99 if config.has_option(section, 'shares'):
100 logger = logging.getLogger('pyTivo.config')
101 logger.info('Shares security in use -- zeroconf disabled')
102 return False
103 elif opt in ['false', 'no', 'off']:
104 return False
106 return True
108 def get_mind(tsn):
109 if tsn and tsn.startswith('663'):
110 default = 'symind.tivo.com:8181'
111 else:
112 default = 'mind.tivo.com:8181'
113 return get_server('tivo_mind', default)
115 def getBeaconAddresses():
116 return get_server('beacon', '255.255.255.255')
118 def getPort():
119 return get_server('port', '9032')
121 def get169Blacklist(tsn): # tivo does not pad 16:9 video
122 return tsn and not isHDtivo(tsn) and not get169Letterbox(tsn)
123 # verified Blacklist Tivo's are ('130', '240', '540')
124 # It is assumed all remaining non-HD and non-Letterbox tivos are Blacklist
126 def get169Letterbox(tsn): # tivo pads 16:9 video for 4:3 display
127 return tsn and tsn[:3] in ['649']
129 def get169Setting(tsn):
130 if not tsn:
131 return True
133 tsnsect = '_tivo_' + tsn
134 if config.has_section(tsnsect):
135 if config.has_option(tsnsect, 'aspect169'):
136 try:
137 return config.getboolean(tsnsect, 'aspect169')
138 except ValueError:
139 pass
141 if get169Blacklist(tsn) or get169Letterbox(tsn):
142 return False
144 return True
146 def getAllowedClients():
147 return get_server('allowedips', '').split()
149 def getIsExternal(tsn):
150 tsnsect = '_tivo_' + tsn
151 if tsnsect in config.sections():
152 if config.has_option(tsnsect, 'external'):
153 try:
154 return config.getboolean(tsnsect, 'external')
155 except ValueError:
156 pass
158 return False
160 def isTsnInConfig(tsn):
161 return ('_tivo_' + tsn) in config.sections()
163 def getShares(tsn=''):
164 shares = [(section, dict(config.items(section)))
165 for section in config.sections()
166 if not (section.startswith('_tivo_')
167 or section.startswith('logger_')
168 or section.startswith('handler_')
169 or section.startswith('formatter_')
170 or section in ('Server', 'loggers', 'handlers',
171 'formatters')
175 tsnsect = '_tivo_' + tsn
176 if config.has_section(tsnsect) and config.has_option(tsnsect, 'shares'):
177 # clean up leading and trailing spaces & make sure ref is valid
178 tsnshares = []
179 for x in config.get(tsnsect, 'shares').split(','):
180 y = x.strip()
181 if config.has_section(y):
182 tsnshares.append((y, dict(config.items(y))))
183 shares = tsnshares
185 shares.sort()
187 if get_server('nosettings', 'false').lower() in ['false', 'no', 'off']:
188 shares.append(('Settings', {'type': 'settings'}))
189 if get_server('tivo_mak') and get_server('togo_path'):
190 shares.append(('ToGo', {'type': 'togo'}))
192 return shares
194 def getDebug():
195 try:
196 return config.getboolean('Server', 'debug')
197 except NoOptionError, ValueError:
198 return False
200 def getOptres(tsn=None):
201 try:
202 return config.getboolean('_tivo_' + tsn, 'optres')
203 except:
204 try:
205 return config.getboolean(get_section(tsn), 'optres')
206 except:
207 try:
208 return config.getboolean('Server', 'optres')
209 except:
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 hasTStivo(tsn): # tsn's of Tivos that support transport streams
273 try:
274 return config.getboolean('Server', 'ts')
275 except NoOptionError, ValueError:
276 return False
277 return bool(tsn and (tsn[0] >= '7' or tsn.startswith('663')))
279 def getValidWidths():
280 return [1920, 1440, 1280, 720, 704, 544, 480, 352]
282 def getValidHeights():
283 return [1080, 720, 480] # Technically 240 is also supported
285 # Return the number in list that is nearest to x
286 # if two values are equidistant, return the larger
287 def nearest(x, list):
288 return reduce(lambda a, b: closest(x, a, b), list)
290 def closest(x, a, b):
291 da = abs(x - a)
292 db = abs(x - b)
293 if da < db or (da == db and a > b):
294 return a
295 else:
296 return b
298 def nearestTivoHeight(height):
299 return nearest(height, getValidHeights())
301 def nearestTivoWidth(width):
302 return nearest(width, getValidWidths())
304 def getTivoHeight(tsn):
305 height = get_tsn('height', tsn)
306 if height:
307 return nearestTivoHeight(int(height))
308 return [480, 1080][isHDtivo(tsn)]
310 def getTivoWidth(tsn):
311 width = get_tsn('width', tsn)
312 if width:
313 return nearestTivoWidth(int(width))
314 return [544, 1920][isHDtivo(tsn)]
316 def _trunc64(i):
317 return max(int(strtod(i)) / 64000, 1) * 64
319 def getAudioBR(tsn=None):
320 rate = get_tsn('audio_br', tsn)
321 if not rate:
322 rate = '448k'
323 # convert to non-zero multiple of 64 to ensure ffmpeg compatibility
324 # compare audio_br to max_audio_br and return lowest
325 return str(min(_trunc64(rate), getMaxAudioBR(tsn))) + 'k'
327 def _k(i):
328 return str(int(strtod(i)) / 1000) + 'k'
330 def getVideoBR(tsn=None):
331 rate = get_tsn('video_br', tsn)
332 if rate:
333 return _k(rate)
334 return ['4096K', '16384K'][isHDtivo(tsn)]
336 def getMaxVideoBR(tsn=None):
337 rate = get_tsn('max_video_br', tsn)
338 if rate:
339 return _k(rate)
340 return '30000k'
342 def getVideoPCT(tsn=None):
343 pct = get_tsn('video_pct', tsn)
344 if pct:
345 return float(pct)
346 return 85
348 def getBuffSize(tsn=None):
349 size = get_tsn('bufsize', tsn)
350 if size:
351 return _k(size)
352 return ['1024k', '4096k'][isHDtivo(tsn)]
354 def getMaxAudioBR(tsn=None):
355 rate = get_tsn('max_audio_br', tsn)
356 # convert to non-zero multiple of 64 for ffmpeg compatibility
357 if rate:
358 return _trunc64(rate)
359 return 448
361 def get_section(tsn):
362 return ['_tivo_SD', '_tivo_HD'][isHDtivo(tsn)]
364 def get_tsn(name, tsn=None, raw=False):
365 try:
366 return config.get('_tivo_' + tsn, name, raw)
367 except:
368 try:
369 return config.get(get_section(tsn), name, raw)
370 except:
371 try:
372 return config.get('Server', name, raw)
373 except:
374 return None
376 # Parse a bitrate using the SI/IEEE suffix values as if by ffmpeg
377 # For example, 2K==2000, 2Ki==2048, 2MB==16000000, 2MiB==16777216
378 # Algorithm: http://svn.mplayerhq.hu/ffmpeg/trunk/libavcodec/eval.c
379 def strtod(value):
380 prefixes = {'y': -24, 'z': -21, 'a': -18, 'f': -15, 'p': -12,
381 'n': -9, 'u': -6, 'm': -3, 'c': -2, 'd': -1,
382 'h': 2, 'k': 3, 'K': 3, 'M': 6, 'G': 9,
383 'T': 12, 'P': 15, 'E': 18, 'Z': 21, 'Y': 24}
384 p = re.compile(r'^(\d+)(?:([yzafpnumcdhkKMGTPEZY])(i)?)?([Bb])?$')
385 m = p.match(value)
386 if not m:
387 raise SyntaxError('Invalid bit value syntax')
388 (coef, prefix, power, byte) = m.groups()
389 if prefix is None:
390 value = float(coef)
391 else:
392 exponent = float(prefixes[prefix])
393 if power == 'i':
394 # Use powers of 2
395 value = float(coef) * pow(2.0, exponent / 0.3)
396 else:
397 # Use powers of 10
398 value = float(coef) * pow(10.0, exponent)
399 if byte == 'B': # B == Byte, b == bit
400 value *= 8;
401 return value
403 def init_logging():
404 if (config.has_section('loggers') and
405 config.has_section('handlers') and
406 config.has_section('formatters')):
408 logging.config.fileConfig(config_files)
410 elif getDebug():
411 logging.basicConfig(level=logging.DEBUG)
412 else:
413 logging.basicConfig(level=logging.INFO)