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