Still need to skip "_tivo_4K" sections when building list of found TiVos.
[pyTivo/wmcbrine.git] / config.py
blob6ba2c6613a2184872de148b0e47031e7ad225b9a
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']:
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 getBeaconAddresses():
113 return get_server('beacon', '255.255.255.255')
115 def getPort():
116 return get_server('port', '9032')
118 def get169Blacklist(tsn): # tivo does not pad 16:9 video
119 return tsn and not isHDtivo(tsn) and not get169Letterbox(tsn)
120 # verified Blacklist Tivo's are ('130', '240', '540')
121 # It is assumed all remaining non-HD and non-Letterbox tivos are Blacklist
123 def get169Letterbox(tsn): # tivo pads 16:9 video for 4:3 display
124 return tsn and tsn[:3] in ['649']
126 def get169Setting(tsn):
127 if not tsn:
128 return True
130 tsnsect = '_tivo_' + tsn
131 if config.has_section(tsnsect):
132 if config.has_option(tsnsect, 'aspect169'):
133 try:
134 return config.getboolean(tsnsect, 'aspect169')
135 except ValueError:
136 pass
138 if get169Blacklist(tsn) or get169Letterbox(tsn):
139 return False
141 return True
143 def getAllowedClients():
144 return get_server('allowedips', '').split()
146 def getIsExternal(tsn):
147 tsnsect = '_tivo_' + tsn
148 if tsnsect in config.sections():
149 if config.has_option(tsnsect, 'external'):
150 try:
151 return config.getboolean(tsnsect, 'external')
152 except ValueError:
153 pass
155 return False
157 def isTsnInConfig(tsn):
158 return ('_tivo_' + tsn) in config.sections()
160 def getShares(tsn=''):
161 shares = [(section, Bdict(config.items(section)))
162 for section in config.sections()
163 if not (section.startswith(('_tivo_', 'logger_', 'handler_',
164 '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, Bdict(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:
193 return False
195 def getOptres(tsn=None):
196 try:
197 return config.getboolean('_tivo_' + tsn, 'optres')
198 except:
199 try:
200 return config.getboolean(get_section(tsn), 'optres')
201 except:
202 try:
203 return config.getboolean('Server', 'optres')
204 except:
205 return False
207 def get_bin(fname):
208 global bin_paths
210 logger = logging.getLogger('pyTivo.config')
212 if fname in bin_paths:
213 return bin_paths[fname]
215 if config.has_option('Server', fname):
216 fpath = config.get('Server', fname)
217 if os.path.exists(fpath) and os.path.isfile(fpath):
218 bin_paths[fname] = fpath
219 return fpath
220 else:
221 logger.error('Bad %s path: %s' % (fname, fpath))
223 if sys.platform == 'win32':
224 fext = '.exe'
225 else:
226 fext = ''
228 for path in ([os.path.join(os.path.dirname(__file__), 'bin')] +
229 os.getenv('PATH').split(os.pathsep)):
230 fpath = os.path.join(path, fname + fext)
231 if os.path.exists(fpath) and os.path.isfile(fpath):
232 bin_paths[fname] = fpath
233 return fpath
235 logger.warn('%s not found' % fname)
236 return None
238 def getFFmpegWait():
239 if config.has_option('Server', 'ffmpeg_wait'):
240 return max(int(float(config.get('Server', 'ffmpeg_wait'))), 1)
241 else:
242 return 0
244 def getFFmpegPrams(tsn):
245 return get_tsn('ffmpeg_pram', tsn, True)
247 def isHDtivo(tsn): # TSNs of High Definition TiVos
248 return bool(tsn and tsn[0] >= '6' and tsn[:3] != '649')
250 def get_ts_flag():
251 return get_server('ts', 'auto').lower()
253 def is_ts_capable(tsn): # tsn's of Tivos that support transport streams
254 return bool(tsn and (tsn[0] >= '7' or tsn.startswith('663')))
256 def getValidWidths():
257 return [1920, 1440, 1280, 720, 704, 544, 480, 352]
259 def getValidHeights():
260 return [1080, 720, 480] # Technically 240 is also supported
262 # Return the number in list that is nearest to x
263 # if two values are equidistant, return the larger
264 def nearest(x, list):
265 return reduce(lambda a, b: closest(x, a, b), list)
267 def closest(x, a, b):
268 da = abs(x - a)
269 db = abs(x - b)
270 if da < db or (da == db and a > b):
271 return a
272 else:
273 return b
275 def nearestTivoHeight(height):
276 return nearest(height, getValidHeights())
278 def nearestTivoWidth(width):
279 return nearest(width, getValidWidths())
281 def getTivoHeight(tsn):
282 return [480, 1080][isHDtivo(tsn)]
284 def getTivoWidth(tsn):
285 return [544, 1920][isHDtivo(tsn)]
287 def _trunc64(i):
288 return max(int(strtod(i)) / 64000, 1) * 64
290 def getAudioBR(tsn=None):
291 rate = get_tsn('audio_br', tsn)
292 if not rate:
293 rate = '448k'
294 # convert to non-zero multiple of 64 to ensure ffmpeg compatibility
295 # compare audio_br to max_audio_br and return lowest
296 return str(min(_trunc64(rate), getMaxAudioBR(tsn))) + 'k'
298 def _k(i):
299 return str(int(strtod(i)) / 1000) + 'k'
301 def getVideoBR(tsn=None):
302 rate = get_tsn('video_br', tsn)
303 if rate:
304 return _k(rate)
305 return ['4096K', '16384K'][isHDtivo(tsn)]
307 def getMaxVideoBR(tsn=None):
308 rate = get_tsn('max_video_br', tsn)
309 if rate:
310 return _k(rate)
311 return '30000k'
313 def getBuffSize(tsn=None):
314 size = get_tsn('bufsize', tsn)
315 if size:
316 return _k(size)
317 return ['1024k', '4096k'][isHDtivo(tsn)]
319 def getMaxAudioBR(tsn=None):
320 rate = get_tsn('max_audio_br', tsn)
321 # convert to non-zero multiple of 64 for ffmpeg compatibility
322 if rate:
323 return _trunc64(rate)
324 return 448
326 def get_section(tsn):
327 return ['_tivo_SD', '_tivo_HD'][isHDtivo(tsn)]
329 def get_tsn(name, tsn=None, raw=False):
330 try:
331 return config.get('_tivo_' + tsn, name, raw)
332 except:
333 try:
334 return config.get(get_section(tsn), name, raw)
335 except:
336 try:
337 return config.get('Server', name, raw)
338 except:
339 return None
341 # Parse a bitrate using the SI/IEEE suffix values as if by ffmpeg
342 # For example, 2K==2000, 2Ki==2048, 2MB==16000000, 2MiB==16777216
343 # Algorithm: http://svn.mplayerhq.hu/ffmpeg/trunk/libavcodec/eval.c
344 def strtod(value):
345 prefixes = {'y': -24, 'z': -21, 'a': -18, 'f': -15, 'p': -12,
346 'n': -9, 'u': -6, 'm': -3, 'c': -2, 'd': -1,
347 'h': 2, 'k': 3, 'K': 3, 'M': 6, 'G': 9,
348 'T': 12, 'P': 15, 'E': 18, 'Z': 21, 'Y': 24}
349 p = re.compile(r'^(\d+)(?:([yzafpnumcdhkKMGTPEZY])(i)?)?([Bb])?$')
350 m = p.match(value)
351 if not m:
352 raise SyntaxError('Invalid bit value syntax')
353 (coef, prefix, power, byte) = m.groups()
354 if prefix is None:
355 value = float(coef)
356 else:
357 exponent = float(prefixes[prefix])
358 if power == 'i':
359 # Use powers of 2
360 value = float(coef) * pow(2.0, exponent / 0.3)
361 else:
362 # Use powers of 10
363 value = float(coef) * pow(10.0, exponent)
364 if byte == 'B': # B == Byte, b == bit
365 value *= 8;
366 return value
368 def init_logging():
369 if (config.has_section('loggers') and
370 config.has_section('handlers') and
371 config.has_section('formatters')):
373 logging.config.fileConfig(config_files)
375 elif getDebug():
376 logging.basicConfig(level=logging.DEBUG)
377 else:
378 logging.basicConfig(level=logging.INFO)