Allow for .TiVo files with unencrypted metadata. Cleaner anyway.
[pyTivo/wmcbrine/lucasnz.git] / config.py
blob68c8ad411a0609361e45d84349af63770663a184
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 tivo_names
19 global guid
20 global config_files
22 tivos = {}
23 tivo_names = {}
24 guid = uuid.uuid4()
26 config_win_default = ''
27 if sys.platform == "win32":
28 import _winreg
29 try:
30 explorerFolders = _winreg.OpenKey(
31 _winreg.HKEY_LOCAL_MACHINE, 'Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders')
32 winCommonAppDataVal, winCommonAppDataType = _winreg.QueryValueEx(explorerFolders, 'Common AppData')
33 config_win_default = os.path.join(winCommonAppDataVal, 'pyTivo', 'pyTivo.conf')
34 except WindowsError:
35 print "Can't access Windows Registry to find common Application Data path."
37 p = os.path.dirname(__file__)
38 config_files = ['/etc/pyTivo.conf', config_win_default, os.path.join(p, 'pyTivo.conf')]
40 try:
41 opts, _ = getopt.getopt(argv, 'c:e:', ['config=', 'extraconf='])
42 except getopt.GetoptError, msg:
43 print msg
45 for opt, value in opts:
46 if opt in ('-c', '--config'):
47 config_files = [value]
48 elif opt in ('-e', '--extraconf'):
49 config_files.append(value)
51 reset()
53 def reset():
54 global bin_paths
55 global config
56 global configs_found
58 bin_paths = {}
60 config = ConfigParser.ConfigParser()
61 configs_found = config.read(config_files)
62 if not configs_found:
63 print ('WARNING: pyTivo.conf does not exist.\n' +
64 'Assuming default values.')
65 configs_found = config_files[-1:]
67 for section in config.sections():
68 if section.startswith('_tivo_'):
69 tsn = section[6:]
70 if tsn.upper() not in ['SD', 'HD']:
71 if config.has_option(section, 'name'):
72 tivo_names[tsn] = config.get(section, 'name')
73 else:
74 tivo_names[tsn] = tsn
75 if config.has_option(section, 'address'):
76 tivos[tsn] = config.get(section, 'address')
78 for section in ['Server', '_tivo_SD', '_tivo_HD']:
79 if not config.has_section(section):
80 config.add_section(section)
82 def write():
83 f = open(configs_found[-1], 'w')
84 config.write(f)
85 f.close()
87 def tivos_by_ip(tivoIP):
88 for key, value in tivos.items():
89 if value == tivoIP:
90 return key
92 def get_server(name, default=None):
93 if config.has_option('Server', name):
94 return config.get('Server', name)
95 else:
96 return default
98 def getGUID():
99 return str(guid)
101 def get_ip(tsn=None):
102 dest_ip = tivos.get(tsn, '4.2.2.1')
103 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
104 s.connect((dest_ip, 123))
105 return s.getsockname()[0]
107 def get_zc():
108 opt = get_server('zeroconf', 'auto').lower()
110 if opt == 'auto':
111 for section in config.sections():
112 if section.startswith('_tivo_'):
113 if config.has_option(section, 'shares'):
114 logger = logging.getLogger('pyTivo.config')
115 logger.info('Shares security in use -- zeroconf disabled')
116 return False
117 elif opt in ['false', 'no', 'off']:
118 return False
120 return True
122 def get_mind(tsn):
123 if tsn and tsn.startswith('663'):
124 default = 'symind.tivo.com:8181'
125 else:
126 default = 'mind.tivo.com:8181'
127 return get_server('tivo_mind', default)
129 def getBeaconAddresses():
130 return get_server('beacon', '255.255.255.255')
132 def getPort():
133 return get_server('port', '9032')
135 def get169Blacklist(tsn): # tivo does not pad 16:9 video
136 return tsn and not isHDtivo(tsn) and not get169Letterbox(tsn)
137 # verified Blacklist Tivo's are ('130', '240', '540')
138 # It is assumed all remaining non-HD and non-Letterbox tivos are Blacklist
140 def get169Letterbox(tsn): # tivo pads 16:9 video for 4:3 display
141 return tsn and tsn[:3] in ['649']
143 def get169Setting(tsn):
144 if not tsn:
145 return True
147 tsnsect = '_tivo_' + tsn
148 if config.has_section(tsnsect):
149 if config.has_option(tsnsect, 'aspect169'):
150 try:
151 return config.getboolean(tsnsect, 'aspect169')
152 except ValueError:
153 pass
155 if get169Blacklist(tsn) or get169Letterbox(tsn):
156 return False
158 return True
160 def getAllowedClients():
161 return get_server('allowedips', '').split()
163 def getIsExternal(tsn):
164 tsnsect = '_tivo_' + tsn
165 if tsnsect in config.sections():
166 if config.has_option(tsnsect, 'external'):
167 try:
168 return config.getboolean(tsnsect, 'external')
169 except ValueError:
170 pass
172 return False
174 def isTsnInConfig(tsn):
175 return ('_tivo_' + tsn) in config.sections()
177 def getShares(tsn=''):
178 shares = [(section, Bdict(config.items(section)))
179 for section in config.sections()
180 if not (section.startswith(('_tivo_', 'logger_', 'handler_',
181 'formatter_'))
182 or section in ('Server', 'loggers', 'handlers',
183 'formatters')
187 tsnsect = '_tivo_' + tsn
188 if config.has_section(tsnsect) and config.has_option(tsnsect, 'shares'):
189 # clean up leading and trailing spaces & make sure ref is valid
190 tsnshares = []
191 for x in config.get(tsnsect, 'shares').split(','):
192 y = x.strip()
193 if config.has_section(y):
194 tsnshares.append((y, Bdict(config.items(y))))
195 shares = tsnshares
197 shares.sort()
199 if get_server('nosettings', 'false').lower() in ['false', 'no', 'off']:
200 shares.append(('Settings', {'type': 'settings'}))
201 if get_server('tivo_mak') and get_server('togo_path'):
202 shares.append(('ToGo', {'type': 'togo'}))
204 return shares
206 def getDebug():
207 try:
208 return config.getboolean('Server', 'debug')
209 except NoOptionError, ValueError:
210 return False
212 def getOptres(tsn=None):
213 try:
214 return config.getboolean('_tivo_' + tsn, 'optres')
215 except:
216 try:
217 return config.getboolean(get_section(tsn), 'optres')
218 except:
219 try:
220 return config.getboolean('Server', 'optres')
221 except:
222 return False
224 def get_bin(fname):
225 global bin_paths
227 logger = logging.getLogger('pyTivo.config')
229 if fname in bin_paths:
230 return bin_paths[fname]
232 if config.has_option('Server', fname):
233 fpath = config.get('Server', fname)
234 if os.path.exists(fpath) and os.path.isfile(fpath):
235 bin_paths[fname] = fpath
236 return fpath
237 else:
238 logger.error('Bad %s path: %s' % (fname, fpath))
240 if sys.platform == 'win32':
241 fext = '.exe'
242 else:
243 fext = ''
245 for path in ([os.path.join(os.path.dirname(__file__), 'bin')] +
246 os.getenv('PATH').split(os.pathsep)):
247 fpath = os.path.join(path, fname + fext)
248 if os.path.exists(fpath) and os.path.isfile(fpath):
249 bin_paths[fname] = fpath
250 return fpath
252 logger.warn('%s not found' % fname)
253 return None
255 def getFFmpegWait():
256 if config.has_option('Server', 'ffmpeg_wait'):
257 return max(int(float(config.get('Server', 'ffmpeg_wait'))), 1)
258 else:
259 return 0
261 def getFFmpegTemplate(tsn):
262 tmpl = get_tsn('ffmpeg_tmpl', tsn, True)
263 if tmpl:
264 return tmpl
265 return '%(video_codec)s %(video_fps)s %(video_br)s %(max_video_br)s \
266 %(buff_size)s %(aspect_ratio)s %(audio_br)s \
267 %(audio_fr)s %(audio_ch)s %(audio_codec)s %(audio_lang)s \
268 %(ffmpeg_pram)s %(format)s'
270 def getFFmpegPrams(tsn):
271 return get_tsn('ffmpeg_pram', tsn, True)
273 def isHDtivo(tsn): # tsn's of High Definition Tivo's
274 return bool(tsn and tsn[0] >= '6' and tsn[:3] != '649')
276 def has_ts_flag():
277 try:
278 return config.getboolean('Server', 'ts')
279 except NoOptionError, ValueError:
280 return False
282 def is_ts_capable(tsn): # tsn's of Tivos that support transport streams
283 return bool(tsn and (tsn[0] >= '7' or tsn.startswith('663')))
285 def getValidWidths():
286 return [1920, 1440, 1280, 720, 704, 544, 480, 352]
288 def getValidHeights():
289 return [1080, 720, 480] # Technically 240 is also supported
291 # Return the number in list that is nearest to x
292 # if two values are equidistant, return the larger
293 def nearest(x, list):
294 return reduce(lambda a, b: closest(x, a, b), list)
296 def closest(x, a, b):
297 da = abs(x - a)
298 db = abs(x - b)
299 if da < db or (da == db and a > b):
300 return a
301 else:
302 return b
304 def nearestTivoHeight(height):
305 return nearest(height, getValidHeights())
307 def nearestTivoWidth(width):
308 return nearest(width, getValidWidths())
310 def getTivoHeight(tsn):
311 height = get_tsn('height', tsn)
312 if height:
313 return nearestTivoHeight(int(height))
314 return [480, 1080][isHDtivo(tsn)]
316 def getTivoWidth(tsn):
317 width = get_tsn('width', tsn)
318 if width:
319 return nearestTivoWidth(int(width))
320 return [544, 1920][isHDtivo(tsn)]
322 def _trunc64(i):
323 return max(int(strtod(i)) / 64000, 1) * 64
325 def getAudioBR(tsn=None):
326 rate = get_tsn('audio_br', tsn)
327 if not rate:
328 rate = '448k'
329 # convert to non-zero multiple of 64 to ensure ffmpeg compatibility
330 # compare audio_br to max_audio_br and return lowest
331 return str(min(_trunc64(rate), getMaxAudioBR(tsn))) + 'k'
333 def _k(i):
334 return str(int(strtod(i)) / 1000) + 'k'
336 def getVideoBR(tsn=None):
337 rate = get_tsn('video_br', tsn)
338 if rate:
339 return _k(rate)
340 return ['4096K', '16384K'][isHDtivo(tsn)]
342 def getMaxVideoBR(tsn=None):
343 rate = get_tsn('max_video_br', tsn)
344 if rate:
345 return _k(rate)
346 return '30000k'
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)