Preliminary support for metadata from DVR-MS/WMV/ASF, via mutagen. Much
[pyTivo/TheBayer.git] / config.py
blob6d0a5f1e5afff7f1e0a2c30653e67d7054fa58a7
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():
100 return get_server('tivo_mind', 'mind.tivo.com:8181')
102 def getBeaconAddresses():
103 return get_server('beacon', '255.255.255.255')
105 def getPort():
106 return get_server('port', '9032')
108 def get169Blacklist(tsn): # tivo does not pad 16:9 video
109 return tsn and not isHDtivo(tsn) and not get169Letterbox(tsn)
110 # verified Blacklist Tivo's are ('130', '240', '540')
111 # It is assumed all remaining non-HD and non-Letterbox tivos are Blacklist
113 def get169Letterbox(tsn): # tivo pads 16:9 video for 4:3 display
114 return tsn and tsn[:3] in ['649']
116 def get169Setting(tsn):
117 if not tsn:
118 return True
120 tsnsect = '_tivo_' + tsn
121 if config.has_section(tsnsect):
122 if config.has_option(tsnsect, 'aspect169'):
123 try:
124 return config.getboolean(tsnsect, 'aspect169')
125 except ValueError:
126 pass
128 if get169Blacklist(tsn) or get169Letterbox(tsn):
129 return False
131 return True
133 def getAllowedClients():
134 return get_server('allowedips', '').split()
136 def getIsExternal(tsn):
137 tsnsect = '_tivo_' + tsn
138 if tsnsect in config.sections():
139 if config.has_option(tsnsect, 'external'):
140 try:
141 return config.getboolean(tsnsect, 'external')
142 except ValueError:
143 pass
145 return False
147 def isTsnInConfig(tsn):
148 return ('_tivo_' + tsn) in config.sections()
150 def getShares(tsn=''):
151 shares = [(section, dict(config.items(section)))
152 for section in config.sections()
153 if not (section.startswith('_tivo_')
154 or section.startswith('logger_')
155 or section.startswith('handler_')
156 or section.startswith('formatter_')
157 or section in ('Server', 'loggers', 'handlers',
158 'formatters')
162 tsnsect = '_tivo_' + tsn
163 if config.has_section(tsnsect) and config.has_option(tsnsect, 'shares'):
164 # clean up leading and trailing spaces & make sure ref is valid
165 tsnshares = []
166 for x in config.get(tsnsect, 'shares').split(','):
167 y = x.strip()
168 if config.has_section(y):
169 tsnshares.append((y, dict(config.items(y))))
170 if tsnshares:
171 shares = tsnshares
173 shares.sort()
175 if get_server('nosettings', 'false').lower() in ['false', 'no', 'off']:
176 shares.append(('Settings', {'type': 'settings'}))
177 if get_server('tivo_mak') and get_server('togo_path'):
178 shares.append(('ToGo', {'type': 'togo'}))
180 return shares
182 def getDebug():
183 try:
184 return config.getboolean('Server', 'debug')
185 except NoOptionError, ValueError:
186 return False
188 def getOptres(tsn=None):
189 if tsn and config.has_section('_tivo_' + tsn):
190 try:
191 return config.getboolean('_tivo_' + tsn, 'optres')
192 except NoOptionError, ValueError:
193 pass
194 section_name = get_section(tsn)
195 if config.has_section(section_name):
196 try:
197 return config.getboolean(section_name, 'optres')
198 except NoOptionError, ValueError:
199 pass
200 try:
201 return config.getboolean('Server', 'optres')
202 except NoOptionError, ValueError:
203 return False
205 def getPixelAR(ref):
206 if config.has_option('Server', 'par'):
207 try:
208 return (True, config.getfloat('Server', 'par'))[ref]
209 except NoOptionError, ValueError:
210 pass
211 return (False, 1.0)[ref]
213 def get_bin(fname):
214 if config.has_option('Server', fname):
215 return config.get('Server', fname)
216 else:
217 global bin_paths
218 if fname in bin_paths:
219 return bin_paths[fname]
220 if sys.platform == 'win32':
221 fname += '.exe'
222 for path in ([os.path.join(os.path.dirname(__file__), 'bin')] +
223 os.getenv('PATH').split(os.pathsep)):
224 fpath = os.path.join(path, fname)
225 if os.path.exists(fpath) and os.path.isfile(fpath):
226 bin_paths[fname] = fpath
227 return fpath
228 return None
230 def getFFmpegWait():
231 if config.has_option('Server', 'ffmpeg_wait'):
232 return max(int(float(config.get('Server', 'ffmpeg_wait'))), 1)
233 else:
234 return 10
236 def getFFmpegTemplate(tsn):
237 tmpl = get_tsn('ffmpeg_tmpl', tsn, True)
238 if tmpl:
239 return tmpl
240 return '%(video_codec)s %(video_fps)s %(video_br)s %(max_video_br)s \
241 %(buff_size)s %(aspect_ratio)s %(audio_br)s \
242 %(audio_fr)s %(audio_ch)s %(audio_codec)s %(audio_lang)s \
243 %(ffmpeg_pram)s %(format)s'
245 def getFFmpegPrams(tsn):
246 return get_tsn('ffmpeg_pram', tsn, True)
248 def isHDtivo(tsn): # tsn's of High Definition Tivo's
249 return bool(tsn and tsn[:3] in ['648', '652', '658', '663'])
251 def getValidWidths():
252 return [1920, 1440, 1280, 720, 704, 544, 480, 352]
254 def getValidHeights():
255 return [1080, 720, 480] # Technically 240 is also supported
257 # Return the number in list that is nearest to x
258 # if two values are equidistant, return the larger
259 def nearest(x, list):
260 return reduce(lambda a, b: closest(x, a, b), list)
262 def closest(x, a, b):
263 da = abs(x - a)
264 db = abs(x - b)
265 if da < db or (da == db and a > b):
266 return a
267 else:
268 return b
270 def nearestTivoHeight(height):
271 return nearest(height, getValidHeights())
273 def nearestTivoWidth(width):
274 return nearest(width, getValidWidths())
276 def getTivoHeight(tsn):
277 height = get_tsn('height', tsn)
278 if height:
279 return nearestTivoHeight(int(height))
280 return [480, 1080][isHDtivo(tsn)]
282 def getTivoWidth(tsn):
283 width = get_tsn('width', tsn)
284 if width:
285 return nearestTivoWidth(int(width))
286 return [544, 1920][isHDtivo(tsn)]
288 def _trunc64(i):
289 return max(int(strtod(i)) / 64000, 1) * 64
291 def getAudioBR(tsn=None):
292 rate = get_tsn('audio_br', tsn)
293 if not rate:
294 rate = '448k'
295 # convert to non-zero multiple of 64 to ensure ffmpeg compatibility
296 # compare audio_br to max_audio_br and return lowest
297 return str(min(_trunc64(rate), getMaxAudioBR(tsn))) + 'k'
299 def _k(i):
300 return str(int(strtod(i)) / 1000) + 'k'
302 def getVideoBR(tsn=None):
303 rate = get_tsn('video_br', tsn)
304 if rate:
305 return _k(rate)
306 return ['4096K', '16384K'][isHDtivo(tsn)]
308 def getMaxVideoBR(tsn=None):
309 rate = get_tsn('max_video_br', tsn)
310 if rate:
311 return _k(rate)
312 return '30000k'
314 def getVideoPCT(tsn=None):
315 pct = get_tsn('video_pct', tsn)
316 if pct:
317 return float(pct)
318 return 85
320 def getBuffSize(tsn=None):
321 size = get_tsn('bufsize', tsn)
322 if size:
323 return _k(size)
324 return ['1024k', '4096k'][isHDtivo(tsn)]
326 def getMaxAudioBR(tsn=None):
327 rate = get_tsn('max_audio_br', tsn)
328 # convert to non-zero multiple of 64 for ffmpeg compatibility
329 if rate:
330 return _trunc64(rate)
331 return 448
333 def get_section(tsn):
334 return ['_tivo_SD', '_tivo_HD'][isHDtivo(tsn)]
336 def get_tsn(name, tsn=None, raw=False):
337 if tsn and config.has_section('_tivo_' + tsn):
338 try:
339 return config.get('_tivo_' + tsn, name, raw)
340 except NoOptionError:
341 pass
342 section_name = get_section(tsn)
343 if config.has_section(section_name):
344 try:
345 return config.get(section_name, name, raw)
346 except NoOptionError:
347 pass
348 try:
349 return config.get('Server', name, raw)
350 except NoOptionError:
351 pass
352 return None
354 # Parse a bitrate using the SI/IEEE suffix values as if by ffmpeg
355 # For example, 2K==2000, 2Ki==2048, 2MB==16000000, 2MiB==16777216
356 # Algorithm: http://svn.mplayerhq.hu/ffmpeg/trunk/libavcodec/eval.c
357 def strtod(value):
358 prefixes = {'y': -24, 'z': -21, 'a': -18, 'f': -15, 'p': -12,
359 'n': -9, 'u': -6, 'm': -3, 'c': -2, 'd': -1,
360 'h': 2, 'k': 3, 'K': 3, 'M': 6, 'G': 9,
361 'T': 12, 'P': 15, 'E': 18, 'Z': 21, 'Y': 24}
362 p = re.compile(r'^(\d+)(?:([yzafpnumcdhkKMGTPEZY])(i)?)?([Bb])?$')
363 m = p.match(value)
364 if not m:
365 raise SyntaxError('Invalid bit value syntax')
366 (coef, prefix, power, byte) = m.groups()
367 if prefix is None:
368 value = float(coef)
369 else:
370 exponent = float(prefixes[prefix])
371 if power == 'i':
372 # Use powers of 2
373 value = float(coef) * pow(2.0, exponent / 0.3)
374 else:
375 # Use powers of 10
376 value = float(coef) * pow(10.0, exponent)
377 if byte == 'B': # B == Byte, b == bit
378 value *= 8;
379 return value
381 def init_logging():
382 if (config.has_section('loggers') and
383 config.has_section('handlers') and
384 config.has_section('formatters')):
386 logging.config.fileConfig(config_files)
388 elif getDebug():
389 logging.basicConfig(level=logging.DEBUG)
390 else:
391 logging.basicConfig(level=logging.INFO)