Eliminate audio_ch, audio_fr, copy_ts and video_fps. Preparatory to
[pyTivo/wmcbrine.git] / config.py
blob2d750058bb39394bae1807035758b0027007a039
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 class Bdict(dict):
13 def getboolean(self, x):
14 return self.get(x, 'False').lower() in ('1', 'yes', 'true', 'on')
16 def init(argv):
17 global tivos
18 global guid
19 global config_files
20 global tivos_found
22 tivos = {}
23 guid = uuid.uuid4()
24 tivos_found = False
26 p = os.path.dirname(__file__)
27 config_files = ['/etc/pyTivo.conf', os.path.join(p, 'pyTivo.conf')]
29 try:
30 opts, _ = getopt.getopt(argv, 'c:e:', ['config=', 'extraconf='])
31 except getopt.GetoptError, msg:
32 print msg
34 for opt, value in opts:
35 if opt in ('-c', '--config'):
36 config_files = [value]
37 elif opt in ('-e', '--extraconf'):
38 config_files.append(value)
40 reset()
42 def reset():
43 global bin_paths
44 global config
45 global configs_found
46 global tivos_found
48 bin_paths = {}
50 config = ConfigParser.ConfigParser()
51 configs_found = config.read(config_files)
52 if not configs_found:
53 print ('WARNING: pyTivo.conf does not exist.\n' +
54 'Assuming default values.')
55 configs_found = config_files[-1:]
57 for section in config.sections():
58 if section.startswith('_tivo_'):
59 tsn = section[6:]
60 if tsn.upper() not in ['SD', 'HD', '4K']:
61 tivos_found = True
62 tivos[tsn] = Bdict(config.items(section))
64 for section in ['Server', '_tivo_SD', '_tivo_HD', '_tivo_4K']:
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['address'] == 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 str(guid)
87 def get_ip(tsn=None):
88 try:
89 assert(tsn)
90 dest_ip = tivos[tsn]['address']
91 except:
92 dest_ip = '4.2.2.1'
93 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
94 s.connect((dest_ip, 123))
95 return s.getsockname()[0]
97 def get_zc():
98 opt = get_server('zeroconf', 'auto').lower()
100 if opt == 'auto':
101 for section in config.sections():
102 if section.startswith('_tivo_'):
103 if config.has_option(section, 'shares'):
104 logger = logging.getLogger('pyTivo.config')
105 logger.info('Shares security in use -- zeroconf disabled')
106 return False
107 elif opt in ['false', 'no', 'off']:
108 return False
110 return True
112 def get_mind(tsn):
113 if tsn and tsn.startswith('663'):
114 default = 'symind.tivo.com:8181'
115 else:
116 default = 'mind.tivo.com:8181'
117 return get_server('tivo_mind', default)
119 def getBeaconAddresses():
120 return get_server('beacon', '255.255.255.255')
122 def getPort():
123 return get_server('port', '9032')
125 def get169Blacklist(tsn): # tivo does not pad 16:9 video
126 return tsn and not isHDtivo(tsn) and not get169Letterbox(tsn)
127 # verified Blacklist Tivo's are ('130', '240', '540')
128 # It is assumed all remaining non-HD and non-Letterbox tivos are Blacklist
130 def get169Letterbox(tsn): # tivo pads 16:9 video for 4:3 display
131 return tsn and tsn[:3] in ['649']
133 def get169Setting(tsn):
134 if not tsn:
135 return True
137 tsnsect = '_tivo_' + tsn
138 if config.has_section(tsnsect):
139 if config.has_option(tsnsect, 'aspect169'):
140 try:
141 return config.getboolean(tsnsect, 'aspect169')
142 except ValueError:
143 pass
145 if get169Blacklist(tsn) or get169Letterbox(tsn):
146 return False
148 return True
150 def getAllowedClients():
151 return get_server('allowedips', '').split()
153 def getIsExternal(tsn):
154 tsnsect = '_tivo_' + tsn
155 if tsnsect in config.sections():
156 if config.has_option(tsnsect, 'external'):
157 try:
158 return config.getboolean(tsnsect, 'external')
159 except ValueError:
160 pass
162 return False
164 def isTsnInConfig(tsn):
165 return ('_tivo_' + tsn) in config.sections()
167 def getShares(tsn=''):
168 shares = [(section, Bdict(config.items(section)))
169 for section in config.sections()
170 if not (section.startswith(('_tivo_', 'logger_', 'handler_',
171 'formatter_'))
172 or section in ('Server', 'loggers', 'handlers',
173 'formatters')
177 tsnsect = '_tivo_' + tsn
178 if config.has_section(tsnsect) and config.has_option(tsnsect, 'shares'):
179 # clean up leading and trailing spaces & make sure ref is valid
180 tsnshares = []
181 for x in config.get(tsnsect, 'shares').split(','):
182 y = x.strip()
183 if config.has_section(y):
184 tsnshares.append((y, Bdict(config.items(y))))
185 shares = tsnshares
187 shares.sort()
189 if get_server('nosettings', 'false').lower() in ['false', 'no', 'off']:
190 shares.append(('Settings', {'type': 'settings'}))
191 if get_server('tivo_mak') and get_server('togo_path'):
192 shares.append(('ToGo', {'type': 'togo'}))
194 return shares
196 def getDebug():
197 try:
198 return config.getboolean('Server', 'debug')
199 except:
200 return False
202 def getOptres(tsn=None):
203 try:
204 return config.getboolean('_tivo_' + tsn, 'optres')
205 except:
206 try:
207 return config.getboolean(get_section(tsn), 'optres')
208 except:
209 try:
210 return config.getboolean('Server', 'optres')
211 except:
212 return False
214 def get_bin(fname):
215 global bin_paths
217 logger = logging.getLogger('pyTivo.config')
219 if fname in bin_paths:
220 return bin_paths[fname]
222 if config.has_option('Server', fname):
223 fpath = config.get('Server', fname)
224 if os.path.exists(fpath) and os.path.isfile(fpath):
225 bin_paths[fname] = fpath
226 return fpath
227 else:
228 logger.error('Bad %s path: %s' % (fname, fpath))
230 if sys.platform == 'win32':
231 fext = '.exe'
232 else:
233 fext = ''
235 for path in ([os.path.join(os.path.dirname(__file__), 'bin')] +
236 os.getenv('PATH').split(os.pathsep)):
237 fpath = os.path.join(path, fname + fext)
238 if os.path.exists(fpath) and os.path.isfile(fpath):
239 bin_paths[fname] = fpath
240 return fpath
242 logger.warn('%s not found' % fname)
243 return None
245 def getFFmpegWait():
246 if config.has_option('Server', 'ffmpeg_wait'):
247 return max(int(float(config.get('Server', 'ffmpeg_wait'))), 1)
248 else:
249 return 0
251 def getFFmpegPrams(tsn):
252 return get_tsn('ffmpeg_pram', tsn, True)
254 def isHDtivo(tsn): # TSNs of High Definition TiVos
255 return bool(tsn and tsn[0] >= '6' and tsn[:3] != '649')
257 def is4Ktivo(tsn): # TSNs of 4K TiVos
258 return bool(tsn[:3] in ('849', '8F9'))
260 def has_ts_flag():
261 try:
262 return config.getboolean('Server', 'ts')
263 except:
264 return False
266 def is_ts_capable(tsn): # tsn's of Tivos that support transport streams
267 return bool(tsn and (tsn[0] >= '7' or tsn.startswith('663')))
269 def getValidWidths():
270 return [1920, 1440, 1280, 720, 704, 544, 480, 352]
272 def getValidHeights():
273 return [1080, 720, 480] # Technically 240 is also supported
275 # Return the number in list that is nearest to x
276 # if two values are equidistant, return the larger
277 def nearest(x, list):
278 return reduce(lambda a, b: closest(x, a, b), list)
280 def closest(x, a, b):
281 da = abs(x - a)
282 db = abs(x - b)
283 if da < db or (da == db and a > b):
284 return a
285 else:
286 return b
288 def nearestTivoHeight(height):
289 return nearest(height, getValidHeights())
291 def nearestTivoWidth(width):
292 return nearest(width, getValidWidths())
294 def getTivoHeight(tsn):
295 height = get_tsn('height', tsn)
296 if height:
297 return nearestTivoHeight(int(height))
298 if is4Ktivo(tsn):
299 return 2160
300 else:
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 if is4Ktivo(tsn):
308 return 3840
309 else:
310 return [544, 1920][isHDtivo(tsn)]
312 def _trunc64(i):
313 return max(int(strtod(i)) / 64000, 1) * 64
315 def getAudioBR(tsn=None):
316 rate = get_tsn('audio_br', tsn)
317 if not rate:
318 rate = '448k'
319 # convert to non-zero multiple of 64 to ensure ffmpeg compatibility
320 # compare audio_br to max_audio_br and return lowest
321 return str(min(_trunc64(rate), getMaxAudioBR(tsn))) + 'k'
323 def _k(i):
324 return str(int(strtod(i)) / 1000) + 'k'
326 def getVideoBR(tsn=None):
327 rate = get_tsn('video_br', tsn)
328 if rate:
329 return _k(rate)
330 if is4Ktivo(tsn):
331 return getMaxVideoBR(tsn)
332 else:
333 return ['4096K', '16384K'][isHDtivo(tsn)]
335 def getMaxVideoBR(tsn=None):
336 rate = get_tsn('max_video_br', tsn)
337 if rate:
338 return _k(rate)
339 return '30000k'
341 def getBuffSize(tsn=None):
342 size = get_tsn('bufsize', tsn)
343 if size:
344 return _k(size)
345 if is4Ktivo(tsn):
346 return '8192k'
347 else:
348 return ['1024k', '4096k'][isHDtivo(tsn)]
350 def getMaxAudioBR(tsn=None):
351 rate = get_tsn('max_audio_br', tsn)
352 # convert to non-zero multiple of 64 for ffmpeg compatibility
353 if rate:
354 return _trunc64(rate)
355 return 448
357 def get_section(tsn):
358 if is4Ktivo(tsn):
359 return '_tivo_4K'
360 else:
361 return ['_tivo_SD', '_tivo_HD'][isHDtivo(tsn)]
363 def get_tsn(name, tsn=None, raw=False):
364 try:
365 return config.get('_tivo_' + tsn, name, raw)
366 except:
367 try:
368 return config.get(get_section(tsn), name, raw)
369 except:
370 try:
371 return config.get('Server', name, raw)
372 except:
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)