In get_bin(), fall through to search when a specified path is invalid.
[pyTivo/TheBayer.git] / config.py
blob54fd86281908682c2ac6bb6fb60fce01a8c85570
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 guid = ''.join([random.choice(string.letters) for i in range(10)])
14 our_ip = ''
15 config = ConfigParser.ConfigParser()
17 p = os.path.dirname(__file__)
18 config_files = ['/etc/pyTivo.conf', os.path.join(p, 'pyTivo.conf')]
19 configs_found = []
21 tivos = {}
22 tivo_names = {}
23 bin_paths = {}
25 def init(argv):
26 global config_files
27 global configs_found
28 global tivo_names
30 try:
31 opts, _ = getopt.getopt(argv, 'c:e:', ['config=', 'extraconf='])
32 except getopt.GetoptError, msg:
33 print msg
35 for opt, value in opts:
36 if opt in ('-c', '--config'):
37 config_files = [value]
38 elif opt in ('-e', '--extraconf'):
39 config_files.append(value)
41 configs_found = config.read(config_files)
42 if not configs_found:
43 print ('ERROR: pyTivo.conf does not exist.\n' +
44 'You must create this file before running pyTivo.')
45 sys.exit(1)
47 for section in config.sections():
48 if section.startswith('_tivo_'):
49 tsn = section[6:]
50 if tsn.upper() not in ['SD', 'HD']:
51 if config.has_option(section, 'name'):
52 tivo_names[tsn] = config.get(section, 'name')
53 else:
54 tivo_names[tsn] = tsn
56 def reset():
57 global config
58 newconfig = ConfigParser.ConfigParser()
59 newconfig.read(config_files)
60 config = newconfig
62 def write():
63 f = open(configs_found[-1], 'w')
64 config.write(f)
65 f.close()
67 def get_server(name, default=None):
68 if config.has_option('Server', name):
69 return config.get('Server', name)
70 else:
71 return default
73 def getGUID():
74 return guid
76 def get_ip():
77 global our_ip
78 if not our_ip:
79 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
80 s.connect(('4.2.2.1', 123))
81 our_ip = s.getsockname()[0]
82 return our_ip
84 def get_zc():
85 opt = get_server('zeroconf', 'auto').lower()
87 if opt == 'auto':
88 for section in config.sections():
89 if section.startswith('_tivo_'):
90 if config.has_option(section, 'shares'):
91 logger = logging.getLogger('pyTivo.config')
92 logger.info('Shares security in use -- zeroconf disabled')
93 return False
94 elif opt in ['false', 'no', 'off']:
95 return False
97 return True
99 def get_mind(tsn):
100 if tsn and tsn.startswith('663'):
101 default = 'symind.tivo.com:8181'
102 else:
103 default = 'mind.tivo.com:8181'
104 return get_server('tivo_mind', default)
106 def getBeaconAddresses():
107 return get_server('beacon', '255.255.255.255')
109 def getPort():
110 return get_server('port', '9032')
112 def get169Blacklist(tsn): # tivo does not pad 16:9 video
113 return tsn and not isHDtivo(tsn) and not get169Letterbox(tsn)
114 # verified Blacklist Tivo's are ('130', '240', '540')
115 # It is assumed all remaining non-HD and non-Letterbox tivos are Blacklist
117 def get169Letterbox(tsn): # tivo pads 16:9 video for 4:3 display
118 return tsn and tsn[:3] in ['649']
120 def get169Setting(tsn):
121 if not tsn:
122 return True
124 tsnsect = '_tivo_' + tsn
125 if config.has_section(tsnsect):
126 if config.has_option(tsnsect, 'aspect169'):
127 try:
128 return config.getboolean(tsnsect, 'aspect169')
129 except ValueError:
130 pass
132 if get169Blacklist(tsn) or get169Letterbox(tsn):
133 return False
135 return True
137 def getAllowedClients():
138 return get_server('allowedips', '').split()
140 def getIsExternal(tsn):
141 tsnsect = '_tivo_' + tsn
142 if tsnsect in config.sections():
143 if config.has_option(tsnsect, 'external'):
144 try:
145 return config.getboolean(tsnsect, 'external')
146 except ValueError:
147 pass
149 return False
151 def isTsnInConfig(tsn):
152 return ('_tivo_' + tsn) in config.sections()
154 def getShares(tsn=''):
155 shares = [(section, dict(config.items(section)))
156 for section in config.sections()
157 if not (section.startswith('_tivo_')
158 or section.startswith('logger_')
159 or section.startswith('handler_')
160 or section.startswith('formatter_')
161 or section in ('Server', 'loggers', 'handlers',
162 'formatters')
166 tsnsect = '_tivo_' + tsn
167 if config.has_section(tsnsect) and config.has_option(tsnsect, 'shares'):
168 # clean up leading and trailing spaces & make sure ref is valid
169 tsnshares = []
170 for x in config.get(tsnsect, 'shares').split(','):
171 y = x.strip()
172 if config.has_section(y):
173 tsnshares.append((y, dict(config.items(y))))
174 shares = tsnshares
176 shares.sort()
178 if get_server('nosettings', 'false').lower() in ['false', 'no', 'off']:
179 shares.append(('Settings', {'type': 'settings'}))
180 if get_server('tivo_mak') and get_server('togo_path'):
181 shares.append(('ToGo', {'type': 'togo'}))
183 return shares
185 def getDebug():
186 try:
187 return config.getboolean('Server', 'debug')
188 except NoOptionError, ValueError:
189 return False
191 def getOptres(tsn=None):
192 if tsn and config.has_section('_tivo_' + tsn):
193 try:
194 return config.getboolean('_tivo_' + tsn, 'optres')
195 except NoOptionError, ValueError:
196 pass
197 section_name = get_section(tsn)
198 if config.has_section(section_name):
199 try:
200 return config.getboolean(section_name, 'optres')
201 except NoOptionError, ValueError:
202 pass
203 try:
204 return config.getboolean('Server', 'optres')
205 except NoOptionError, ValueError:
206 return False
208 def getPixelAR(ref):
209 if config.has_option('Server', 'par'):
210 try:
211 return (True, config.getfloat('Server', 'par'))[ref]
212 except NoOptionError, ValueError:
213 pass
214 return (False, 1.0)[ref]
216 def get_bin(fname):
217 global bin_paths
218 if config.has_option('Server', fname):
219 fpath = config.get('Server', fname)
220 if os.path.exists(fpath) and os.path.isfile(fpath):
221 return fpath
222 else:
223 logger = logging.getLogger('pyTivo.config')
224 logger.error('Bad %s path: %s' % (fname, fpath))
226 if sys.platform == 'win32':
227 fname += '.exe'
228 if fname in bin_paths:
229 return bin_paths[fname]
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)
233 if os.path.exists(fpath) and os.path.isfile(fpath):
234 bin_paths[fname] = fpath
235 return fpath
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 10
244 def getFFmpegTemplate(tsn):
245 tmpl = get_tsn('ffmpeg_tmpl', tsn, True)
246 if tmpl:
247 return tmpl
248 return '%(video_codec)s %(video_fps)s %(video_br)s %(max_video_br)s \
249 %(buff_size)s %(aspect_ratio)s %(audio_br)s \
250 %(audio_fr)s %(audio_ch)s %(audio_codec)s %(audio_lang)s \
251 %(ffmpeg_pram)s %(format)s'
253 def getFFmpegPrams(tsn):
254 return get_tsn('ffmpeg_pram', tsn, True)
256 def isHDtivo(tsn): # tsn's of High Definition Tivo's
257 return bool(tsn and tsn[:3] in ['648', '652', '658', '663'])
259 def getValidWidths():
260 return [1920, 1440, 1280, 720, 704, 544, 480, 352]
262 def getValidHeights():
263 return [1080, 720, 480] # Technically 240 is also supported
265 # Return the number in list that is nearest to x
266 # if two values are equidistant, return the larger
267 def nearest(x, list):
268 return reduce(lambda a, b: closest(x, a, b), list)
270 def closest(x, a, b):
271 da = abs(x - a)
272 db = abs(x - b)
273 if da < db or (da == db and a > b):
274 return a
275 else:
276 return b
278 def nearestTivoHeight(height):
279 return nearest(height, getValidHeights())
281 def nearestTivoWidth(width):
282 return nearest(width, getValidWidths())
284 def getTivoHeight(tsn):
285 height = get_tsn('height', tsn)
286 if height:
287 return nearestTivoHeight(int(height))
288 return [480, 1080][isHDtivo(tsn)]
290 def getTivoWidth(tsn):
291 width = get_tsn('width', tsn)
292 if width:
293 return nearestTivoWidth(int(width))
294 return [544, 1920][isHDtivo(tsn)]
296 def _trunc64(i):
297 return max(int(strtod(i)) / 64000, 1) * 64
299 def getAudioBR(tsn=None):
300 rate = get_tsn('audio_br', tsn)
301 if not rate:
302 rate = '448k'
303 # convert to non-zero multiple of 64 to ensure ffmpeg compatibility
304 # compare audio_br to max_audio_br and return lowest
305 return str(min(_trunc64(rate), getMaxAudioBR(tsn))) + 'k'
307 def _k(i):
308 return str(int(strtod(i)) / 1000) + 'k'
310 def getVideoBR(tsn=None):
311 rate = get_tsn('video_br', tsn)
312 if rate:
313 return _k(rate)
314 return ['4096K', '16384K'][isHDtivo(tsn)]
316 def getMaxVideoBR(tsn=None):
317 rate = get_tsn('max_video_br', tsn)
318 if rate:
319 return _k(rate)
320 return '30000k'
322 def getVideoPCT(tsn=None):
323 pct = get_tsn('video_pct', tsn)
324 if pct:
325 return float(pct)
326 return 85
328 def getBuffSize(tsn=None):
329 size = get_tsn('bufsize', tsn)
330 if size:
331 return _k(size)
332 return ['1024k', '4096k'][isHDtivo(tsn)]
334 def getMaxAudioBR(tsn=None):
335 rate = get_tsn('max_audio_br', tsn)
336 # convert to non-zero multiple of 64 for ffmpeg compatibility
337 if rate:
338 return _trunc64(rate)
339 return 448
341 def get_section(tsn):
342 return ['_tivo_SD', '_tivo_HD'][isHDtivo(tsn)]
344 def get_tsn(name, tsn=None, raw=False):
345 if tsn and config.has_section('_tivo_' + tsn):
346 try:
347 return config.get('_tivo_' + tsn, name, raw)
348 except NoOptionError:
349 pass
350 section_name = get_section(tsn)
351 if config.has_section(section_name):
352 try:
353 return config.get(section_name, name, raw)
354 except NoOptionError:
355 pass
356 try:
357 return config.get('Server', name, raw)
358 except NoOptionError:
359 pass
360 return None
362 # Parse a bitrate using the SI/IEEE suffix values as if by ffmpeg
363 # For example, 2K==2000, 2Ki==2048, 2MB==16000000, 2MiB==16777216
364 # Algorithm: http://svn.mplayerhq.hu/ffmpeg/trunk/libavcodec/eval.c
365 def strtod(value):
366 prefixes = {'y': -24, 'z': -21, 'a': -18, 'f': -15, 'p': -12,
367 'n': -9, 'u': -6, 'm': -3, 'c': -2, 'd': -1,
368 'h': 2, 'k': 3, 'K': 3, 'M': 6, 'G': 9,
369 'T': 12, 'P': 15, 'E': 18, 'Z': 21, 'Y': 24}
370 p = re.compile(r'^(\d+)(?:([yzafpnumcdhkKMGTPEZY])(i)?)?([Bb])?$')
371 m = p.match(value)
372 if not m:
373 raise SyntaxError('Invalid bit value syntax')
374 (coef, prefix, power, byte) = m.groups()
375 if prefix is None:
376 value = float(coef)
377 else:
378 exponent = float(prefixes[prefix])
379 if power == 'i':
380 # Use powers of 2
381 value = float(coef) * pow(2.0, exponent / 0.3)
382 else:
383 # Use powers of 10
384 value = float(coef) * pow(10.0, exponent)
385 if byte == 'B': # B == Byte, b == bit
386 value *= 8;
387 return value
389 def init_logging():
390 if (config.has_section('loggers') and
391 config.has_section('handlers') and
392 config.has_section('formatters')):
394 logging.config.fileConfig(config_files)
396 elif getDebug():
397 logging.basicConfig(level=logging.DEBUG)
398 else:
399 logging.basicConfig(level=logging.INFO)