Describe force_ffmpeg.
[pyTivo/wmcbrine.git] / config.py
blob573646a3d69d13b7fcd500824c8f5763565df317
1 import ConfigParser
2 import getopt
3 import logging
4 import logging.config
5 import os
6 import re
7 import socket
8 import sys
9 import uuid
10 from ConfigParser import NoOptionError
12 def init(argv):
13 global tivos
14 global tivo_names
15 global guid
16 global config_files
18 tivos = {}
19 tivo_names = {}
20 guid = uuid.uuid4()
22 p = os.path.dirname(__file__)
23 config_files = ['/etc/pyTivo.conf', os.path.join(p, 'pyTivo.conf')]
25 try:
26 opts, _ = getopt.getopt(argv, 'c:e:', ['config=', 'extraconf='])
27 except getopt.GetoptError, msg:
28 print msg
30 for opt, value in opts:
31 if opt in ('-c', '--config'):
32 config_files = [value]
33 elif opt in ('-e', '--extraconf'):
34 config_files.append(value)
36 reset()
38 def reset():
39 global bin_paths
40 global config
41 global configs_found
43 bin_paths = {}
45 config = ConfigParser.ConfigParser()
46 configs_found = config.read(config_files)
47 if not configs_found:
48 print ('WARNING: pyTivo.conf does not exist.\n' +
49 'Assuming default values.')
50 configs_found = config_files[-1:]
52 for section in config.sections():
53 if section.startswith('_tivo_'):
54 tsn = section[6:]
55 if tsn.upper() not in ['SD', 'HD']:
56 if config.has_option(section, 'name'):
57 tivo_names[tsn] = config.get(section, 'name')
58 else:
59 tivo_names[tsn] = tsn
60 if config.has_option(section, 'address'):
61 tivos[tsn] = config.get(section, 'address')
63 for section in ['Server', '_tivo_SD', '_tivo_HD']:
64 if not config.has_section(section):
65 config.add_section(section)
67 def write():
68 f = open(configs_found[-1], 'w')
69 config.write(f)
70 f.close()
72 def tivos_by_ip(tivoIP):
73 for key, value in tivos.items():
74 if value == tivoIP:
75 return key
77 def get_server(name, default=None):
78 if config.has_option('Server', name):
79 return config.get('Server', name)
80 else:
81 return default
83 def getGUID():
84 return str(guid)
86 def get_ip(tsn=None):
87 dest_ip = tivos.get(tsn, '4.2.2.1')
88 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
89 s.connect((dest_ip, 123))
90 return s.getsockname()[0]
92 def get_zc():
93 opt = get_server('zeroconf', 'auto').lower()
95 if opt == 'auto':
96 for section in config.sections():
97 if section.startswith('_tivo_'):
98 if config.has_option(section, 'shares'):
99 logger = logging.getLogger('pyTivo.config')
100 logger.info('Shares security in use -- zeroconf disabled')
101 return False
102 elif opt in ['false', 'no', 'off']:
103 return False
105 return True
107 def get_mind(tsn):
108 if tsn and tsn.startswith('663'):
109 default = 'symind.tivo.com:8181'
110 else:
111 default = 'mind.tivo.com:8181'
112 return get_server('tivo_mind', default)
114 def getBeaconAddresses():
115 return get_server('beacon', '255.255.255.255')
117 def getPort():
118 return get_server('port', '9032')
120 def get169Blacklist(tsn): # tivo does not pad 16:9 video
121 return tsn and not isHDtivo(tsn) and not get169Letterbox(tsn)
122 # verified Blacklist Tivo's are ('130', '240', '540')
123 # It is assumed all remaining non-HD and non-Letterbox tivos are Blacklist
125 def get169Letterbox(tsn): # tivo pads 16:9 video for 4:3 display
126 return tsn and tsn[:3] in ['649']
128 def get169Setting(tsn):
129 if not tsn:
130 return True
132 tsnsect = '_tivo_' + tsn
133 if config.has_section(tsnsect):
134 if config.has_option(tsnsect, 'aspect169'):
135 try:
136 return config.getboolean(tsnsect, 'aspect169')
137 except ValueError:
138 pass
140 if get169Blacklist(tsn) or get169Letterbox(tsn):
141 return False
143 return True
145 def getAllowedClients():
146 return get_server('allowedips', '').split()
148 def getIsExternal(tsn):
149 tsnsect = '_tivo_' + tsn
150 if tsnsect in config.sections():
151 if config.has_option(tsnsect, 'external'):
152 try:
153 return config.getboolean(tsnsect, 'external')
154 except ValueError:
155 pass
157 return False
159 def isTsnInConfig(tsn):
160 return ('_tivo_' + tsn) in config.sections()
162 def getShares(tsn=''):
163 shares = [(section, dict(config.items(section)))
164 for section in config.sections()
165 if not (section.startswith(('_tivo_', 'logger_', 'handler_',
166 'formatter_'))
167 or section in ('Server', 'loggers', 'handlers',
168 'formatters')
172 tsnsect = '_tivo_' + tsn
173 if config.has_section(tsnsect) and config.has_option(tsnsect, 'shares'):
174 # clean up leading and trailing spaces & make sure ref is valid
175 tsnshares = []
176 for x in config.get(tsnsect, 'shares').split(','):
177 y = x.strip()
178 if config.has_section(y):
179 tsnshares.append((y, dict(config.items(y))))
180 shares = tsnshares
182 shares.sort()
184 if get_server('nosettings', 'false').lower() in ['false', 'no', 'off']:
185 shares.append(('Settings', {'type': 'settings'}))
186 if get_server('tivo_mak') and get_server('togo_path'):
187 shares.append(('ToGo', {'type': 'togo'}))
189 return shares
191 def getDebug():
192 try:
193 return config.getboolean('Server', 'debug')
194 except NoOptionError, ValueError:
195 return False
197 def getOptres(tsn=None):
198 try:
199 return config.getboolean('_tivo_' + tsn, 'optres')
200 except:
201 try:
202 return config.getboolean(get_section(tsn), 'optres')
203 except:
204 try:
205 return config.getboolean('Server', 'optres')
206 except:
207 return False
209 def get_bin(fname):
210 global bin_paths
212 logger = logging.getLogger('pyTivo.config')
214 if fname in bin_paths:
215 return bin_paths[fname]
217 if config.has_option('Server', fname):
218 fpath = config.get('Server', fname)
219 if os.path.exists(fpath) and os.path.isfile(fpath):
220 bin_paths[fname] = fpath
221 return fpath
222 else:
223 logger.error('Bad %s path: %s' % (fname, fpath))
225 if sys.platform == 'win32':
226 fext = '.exe'
227 else:
228 fext = ''
230 for path in ([os.path.join(os.path.dirname(__file__), 'bin')] +
231 os.getenv('PATH').split(os.pathsep)):
232 fpath = os.path.join(path, fname + fext)
233 if os.path.exists(fpath) and os.path.isfile(fpath):
234 bin_paths[fname] = fpath
235 return fpath
237 logger.warn('%s not found' % fname)
238 return None
240 def getFFmpegWait():
241 if config.has_option('Server', 'ffmpeg_wait'):
242 return max(int(float(config.get('Server', 'ffmpeg_wait'))), 1)
243 else:
244 return 0
246 def getFFmpegTemplate(tsn):
247 tmpl = get_tsn('ffmpeg_tmpl', tsn, True)
248 if tmpl:
249 return tmpl
250 return '%(video_codec)s %(video_fps)s %(video_br)s %(max_video_br)s \
251 %(buff_size)s %(aspect_ratio)s %(audio_br)s \
252 %(audio_fr)s %(audio_ch)s %(audio_codec)s %(audio_lang)s \
253 %(ffmpeg_pram)s %(format)s'
255 def getFFmpegPrams(tsn):
256 return get_tsn('ffmpeg_pram', tsn, True)
258 def isHDtivo(tsn): # tsn's of High Definition Tivo's
259 return bool(tsn and tsn[0] >= '6' and tsn[:3] != '649')
261 def has_ts_flag():
262 try:
263 return config.getboolean('Server', 'ts')
264 except NoOptionError, ValueError:
265 return False
267 def is_ts_capable(tsn): # tsn's of Tivos that support transport streams
268 return bool(tsn and (tsn[0] >= '7' or tsn.startswith('663')))
270 def getValidWidths():
271 return [1920, 1440, 1280, 720, 704, 544, 480, 352]
273 def getValidHeights():
274 return [1080, 720, 480] # Technically 240 is also supported
276 # Return the number in list that is nearest to x
277 # if two values are equidistant, return the larger
278 def nearest(x, list):
279 return reduce(lambda a, b: closest(x, a, b), list)
281 def closest(x, a, b):
282 da = abs(x - a)
283 db = abs(x - b)
284 if da < db or (da == db and a > b):
285 return a
286 else:
287 return b
289 def nearestTivoHeight(height):
290 return nearest(height, getValidHeights())
292 def nearestTivoWidth(width):
293 return nearest(width, getValidWidths())
295 def getTivoHeight(tsn):
296 height = get_tsn('height', tsn)
297 if height:
298 return nearestTivoHeight(int(height))
299 return [480, 1080][isHDtivo(tsn)]
301 def getTivoWidth(tsn):
302 width = get_tsn('width', tsn)
303 if width:
304 return nearestTivoWidth(int(width))
305 return [544, 1920][isHDtivo(tsn)]
307 def _trunc64(i):
308 return max(int(strtod(i)) / 64000, 1) * 64
310 def getAudioBR(tsn=None):
311 rate = get_tsn('audio_br', tsn)
312 if not rate:
313 rate = '448k'
314 # convert to non-zero multiple of 64 to ensure ffmpeg compatibility
315 # compare audio_br to max_audio_br and return lowest
316 return str(min(_trunc64(rate), getMaxAudioBR(tsn))) + 'k'
318 def _k(i):
319 return str(int(strtod(i)) / 1000) + 'k'
321 def getVideoBR(tsn=None):
322 rate = get_tsn('video_br', tsn)
323 if rate:
324 return _k(rate)
325 return ['4096K', '16384K'][isHDtivo(tsn)]
327 def getMaxVideoBR(tsn=None):
328 rate = get_tsn('max_video_br', tsn)
329 if rate:
330 return _k(rate)
331 return '30000k'
333 def getBuffSize(tsn=None):
334 size = get_tsn('bufsize', tsn)
335 if size:
336 return _k(size)
337 return ['1024k', '4096k'][isHDtivo(tsn)]
339 def getMaxAudioBR(tsn=None):
340 rate = get_tsn('max_audio_br', tsn)
341 # convert to non-zero multiple of 64 for ffmpeg compatibility
342 if rate:
343 return _trunc64(rate)
344 return 448
346 def get_section(tsn):
347 return ['_tivo_SD', '_tivo_HD'][isHDtivo(tsn)]
349 def get_tsn(name, tsn=None, raw=False):
350 try:
351 return config.get('_tivo_' + tsn, name, raw)
352 except:
353 try:
354 return config.get(get_section(tsn), name, raw)
355 except:
356 try:
357 return config.get('Server', name, raw)
358 except:
359 return None
361 # Parse a bitrate using the SI/IEEE suffix values as if by ffmpeg
362 # For example, 2K==2000, 2Ki==2048, 2MB==16000000, 2MiB==16777216
363 # Algorithm: http://svn.mplayerhq.hu/ffmpeg/trunk/libavcodec/eval.c
364 def strtod(value):
365 prefixes = {'y': -24, 'z': -21, 'a': -18, 'f': -15, 'p': -12,
366 'n': -9, 'u': -6, 'm': -3, 'c': -2, 'd': -1,
367 'h': 2, 'k': 3, 'K': 3, 'M': 6, 'G': 9,
368 'T': 12, 'P': 15, 'E': 18, 'Z': 21, 'Y': 24}
369 p = re.compile(r'^(\d+)(?:([yzafpnumcdhkKMGTPEZY])(i)?)?([Bb])?$')
370 m = p.match(value)
371 if not m:
372 raise SyntaxError('Invalid bit value syntax')
373 (coef, prefix, power, byte) = m.groups()
374 if prefix is None:
375 value = float(coef)
376 else:
377 exponent = float(prefixes[prefix])
378 if power == 'i':
379 # Use powers of 2
380 value = float(coef) * pow(2.0, exponent / 0.3)
381 else:
382 # Use powers of 10
383 value = float(coef) * pow(10.0, exponent)
384 if byte == 'B': # B == Byte, b == bit
385 value *= 8;
386 return value
388 def init_logging():
389 if (config.has_section('loggers') and
390 config.has_section('handlers') and
391 config.has_section('formatters')):
393 logging.config.fileConfig(config_files)
395 elif getDebug():
396 logging.basicConfig(level=logging.DEBUG)
397 else:
398 logging.basicConfig(level=logging.INFO)