Add partCount and partIndex to video template
[pyTivo/wgw.git] / config.py
blob86671c5f2227b9b191eff69e0ea96a59b3bda881
1 import ConfigParser
2 import logging
3 import os
4 import re
5 import random
6 import string
7 import sys
8 from ConfigParser import NoOptionError
10 guid = ''.join([random.choice(string.letters) for i in range(10)])
12 config = ConfigParser.ConfigParser()
14 p = os.path.dirname(__file__)
15 config_files = ['/etc/pyTivo.conf', os.path.join(p, 'pyTivo.conf')]
17 configs_found = config.read(config_files)
18 if not configs_found:
19 print ('ERROR: pyTivo.conf does not exist.\n' +
20 'You must create this file before running pyTivo.')
21 sys.exit(1)
23 def reset():
24 global config
25 newconfig = ConfigParser.ConfigParser()
26 newconfig.read(config_files)
27 config = newconfig
29 def write():
30 f = open(configs_found[-1], 'w')
31 config.write(f)
32 f.close()
34 def getGUID():
35 if config.has_option('Server', 'GUID'):
36 return config.get('Server', 'GUID')
37 else:
38 return guid
40 def getTivoUsername():
41 return config.get('Server', 'tivo_username')
43 def getTivoPassword():
44 return config.get('Server', 'tivo_password')
46 def getBeaconAddresses():
47 if config.has_option('Server', 'beacon'):
48 beacon_ips = config.get('Server', 'beacon')
49 else:
50 beacon_ips = '255.255.255.255'
51 return beacon_ips
53 def getPort():
54 return config.get('Server', 'Port')
56 def get169Blacklist(tsn): # tivo does not pad 16:9 video
57 return tsn and not isHDtivo(tsn) and not get169Letterbox(tsn)
58 # verified Blacklist Tivo's are ('130', '240', '540')
59 # It is assumed all remaining non-HD and non-Letterbox tivos are Blacklist
61 def get169Letterbox(tsn): # tivo pads 16:9 video for 4:3 display
62 return tsn and tsn[:3] in ['649']
64 def get169Setting(tsn):
65 if not tsn:
66 return True
68 tsnsect = '_tivo_' + tsn
69 if config.has_section(tsnsect):
70 if config.has_option(tsnsect, 'aspect169'):
71 try:
72 return config.getboolean(tsnsect, 'aspect169')
73 except ValueError:
74 pass
76 if get169Blacklist(tsn) or get169Letterbox(tsn):
77 return False
79 return True
81 def getShares(tsn=''):
82 shares = [(section, dict(config.items(section)))
83 for section in config.sections()
84 if not (section.startswith('_tivo_')
85 or section.startswith('logger_')
86 or section.startswith('handler_')
87 or section.startswith('formatter_')
88 or section in ('Server', 'loggers', 'handlers',
89 'formatters')
93 tsnsect = '_tivo_' + tsn
94 if config.has_section(tsnsect) and config.has_option(tsnsect, 'shares'):
95 # clean up leading and trailing spaces & make sure ref is valid
96 tsnshares = []
97 for x in config.get(tsnsect, 'shares').split(','):
98 y = x.strip()
99 if config.has_section(y):
100 tsnshares.append((y, dict(config.items(y))))
101 if tsnshares:
102 shares = tsnshares
104 return shares
106 def getDebug():
107 try:
108 return config.getboolean('Server', 'debug')
109 except NoOptionError, ValueError:
110 return False
112 def getOptres(tsn=None):
113 if tsn and config.has_section('_tivo_' + tsn):
114 try:
115 return config.getboolean('_tivo_' + tsn, 'optres')
116 except NoOptionError, ValueError:
117 pass
118 try:
119 return config.getboolean('Server', 'optres')
120 except NoOptionError, ValueError:
121 return False
123 def getPixelAR(ref):
124 if config.has_option('Server', 'par'):
125 try:
126 return (True, config.getfloat('Server', 'par'))[ref]
127 except NoOptionError, ValueError:
128 pass
129 return (False, 1.0)[ref]
131 def get(section, key):
132 return config.get(section, key)
134 def getFFmpegWait():
135 if config.has_option('Server', 'ffmpeg_wait'):
136 return max(int(float(config.get('Server', 'ffmpeg_wait'))), 1)
137 else:
138 return 10
140 def getFFmpegTemplate(tsn):
141 if tsn and config.has_section('_tivo_' + tsn):
142 try:
143 return config.get('_tivo_' + tsn, 'ffmpeg_tmpl', raw=True)
144 except NoOptionError:
145 pass
146 try:
147 return config.get('Server', 'ffmpeg_tmpl', raw=True)
148 except NoOptionError: #default
149 return '%(video_codec)s %(video_fps)s %(video_br)s %(max_video_br)s \
150 %(buff_size)s %(aspect_ratio)s -comment pyTivo.py %(audio_br)s \
151 %(audio_fr)s %(audio_ch)s %(audio_codec)s %(audio_lang)s \
152 %(ffmpeg_pram)s %(format)s'
154 def getFFmpegPrams(tsn):
155 if tsn and config.has_section('_tivo_' + tsn):
156 try:
157 return config.get('_tivo_' + tsn, 'ffmpeg_pram', raw=True)
158 except NoOptionError:
159 pass
160 try:
161 return config.get('Server', 'ffmpeg_pram', raw=True)
162 except NoOptionError:
163 return None
165 def isHDtivo(tsn): # tsn's of High Definition Tivo's
166 return tsn and tsn[:3] in ['648', '652', '658']
168 def getValidWidths():
169 return [1920, 1440, 1280, 720, 704, 544, 480, 352]
171 def getValidHeights():
172 return [1080, 720, 480] # Technically 240 is also supported
174 # Return the number in list that is nearest to x
175 # if two values are equidistant, return the larger
176 def nearest(x, list):
177 return reduce(lambda a, b: closest(x, a, b), list)
179 def closest(x, a, b):
180 if abs(x - a) < abs(x - b) or (abs(x - a) == abs(x - b) and a > b):
181 return a
182 else:
183 return b
185 def nearestTivoHeight(height):
186 return nearest(height, getValidHeights())
188 def nearestTivoWidth(width):
189 return nearest(width, getValidWidths())
191 def getTivoHeight(tsn):
192 if tsn and config.has_section('_tivo_' + tsn):
193 try:
194 height = config.getint('_tivo_' + tsn, 'height')
195 return nearestTivoHeight(height)
196 except NoOptionError:
197 pass
198 try:
199 height = config.getint('Server', 'height')
200 return nearestTivoHeight(height)
201 except NoOptionError: #defaults for S3/S2 TiVo
202 if isHDtivo(tsn):
203 return 720
204 else:
205 return 480
207 def getTivoWidth(tsn):
208 if tsn and config.has_section('_tivo_' + tsn):
209 try:
210 width = config.getint('_tivo_' + tsn, 'width')
211 return nearestTivoWidth(width)
212 except NoOptionError:
213 pass
214 try:
215 width = config.getint('Server', 'width')
216 return nearestTivoWidth(width)
217 except NoOptionError: #defaults for S3/S2 TiVo
218 if isHDtivo(tsn):
219 return 1280
220 else:
221 return 544
223 def _trunc64(i):
224 return max(int(strtod(i)) / 64000, 1) * 64
226 def getAudioBR(tsn=None):
227 # convert to non-zero multiple of 64 to ensure ffmpeg compatibility
228 # compare audio_br to max_audio_br and return lowest
229 if tsn and config.has_section('_tivo_' + tsn):
230 try:
231 audiobr = _trunc64(config.get('_tivo_' + tsn, 'audio_br'))
232 return str(min(audiobr, getMaxAudioBR(tsn))) + 'k'
233 except NoOptionError:
234 pass
235 try:
236 audiobr = _trunc64(config.get('Server', 'audio_br'))
237 return str(min(audiobr, getMaxAudioBR(tsn))) + 'k'
238 except NoOptionError:
239 return str(min(384, getMaxAudioBR(tsn))) + 'k'
241 def _k(i):
242 return str(int(strtod(i)) / 1000) + 'k'
244 def getVideoBR(tsn=None):
245 if tsn and config.has_section('_tivo_' + tsn):
246 try:
247 return _k(config.get('_tivo_' + tsn, 'video_br'))
248 except NoOptionError:
249 pass
250 try:
251 return _k(config.get('Server', 'video_br'))
252 except NoOptionError: #defaults for S3/S2 TiVo
253 if isHDtivo(tsn):
254 return '8192k'
255 else:
256 return '4096K'
258 def getMaxVideoBR():
259 try:
260 return _k(config.get('Server', 'max_video_br'))
261 except NoOptionError: #default to 30000k
262 return '30000k'
264 def getVideoPCT():
265 try:
266 return config.getfloat('Server', 'video_pct')
267 except NoOptionError:
268 return 70
270 def getBuffSize(tsn=None):
271 tsnsect = '_tivo_' + tsn
272 if tsn and config.has_section(tsnsect):
273 if config.has_option(tsnsect, 'bufsize'):
274 try:
275 return _k(config.get(tsnsect, 'bufsize'))
276 except NoOptionError:
277 pass
278 if config.has_option('Server', 'bufsize'):
279 try:
280 return _k(config.get('Server', 'bufsize'))
281 except NoOptionError:
282 pass
283 if isHDtivo(tsn):
284 return '4096k'
285 else:
286 return '1024k'
288 def getMaxAudioBR(tsn=None):
289 # convert to non-zero multiple of 64 for ffmpeg compatibility
290 if tsn and config.has_section('_tivo_' + tsn):
291 try:
292 return _trunc64(config.get('_tivo_' + tsn, 'max_audio_br'))
293 except NoOptionError:
294 pass
295 try:
296 return _trunc64(config.get('Server', 'max_audio_br'))
297 except NoOptionError:
298 return int(448) # default to 448
300 def get_tsn(name, tsn=None):
301 if tsn and config.has_section('_tivo_' + tsn):
302 try:
303 return config.get('_tivo_' + tsn, name)
304 except NoOptionError:
305 pass
306 try:
307 return config.get('Server', name)
308 except NoOptionError:
309 return None
311 def getAudioCodec(tsn=None):
312 return get_tsn('audio_codec', tsn)
314 def getAudioCH(tsn=None):
315 return get_tsn('audio_ch', tsn)
317 def getAudioFR(tsn=None):
318 return get_tsn('audio_fr', tsn)
320 def getAudioLang(tsn=None):
321 return get_tsn('audio_lang', tsn)
323 def getCopyTS(tsn=None):
324 return get_tsn('copy_ts', tsn)
326 def getVideoFPS(tsn=None):
327 return get_tsn('video_fps', tsn)
329 def getVideoCodec(tsn=None):
330 return get_tsn('video_codec', tsn)
332 def getFormat(tsn=None):
333 return get_tsn('format', tsn)
335 # Parse a bitrate using the SI/IEEE suffix values as if by ffmpeg
336 # For example, 2K==2000, 2Ki==2048, 2MB==16000000, 2MiB==16777216
337 # Algorithm: http://svn.mplayerhq.hu/ffmpeg/trunk/libavcodec/eval.c
338 def strtod(value):
339 prefixes = {'y': -24, 'z': -21, 'a': -18, 'f': -15, 'p': -12,
340 'n': -9, 'u': -6, 'm': -3, 'c': -2, 'd': -1,
341 'h': 2, 'k': 3, 'K': 3, 'M': 6, 'G': 9,
342 'T': 12, 'P': 15, 'E': 18, 'Z': 21, 'Y': 24}
343 p = re.compile(r'^(\d+)(?:([yzafpnumcdhkKMGTPEZY])(i)?)?([Bb])?$')
344 m = p.match(value)
345 if not m:
346 raise SyntaxError('Invalid bit value syntax')
347 (coef, prefix, power, byte) = m.groups()
348 if prefix is None:
349 value = float(coef)
350 else:
351 exponent = float(prefixes[prefix])
352 if power == 'i':
353 # Use powers of 2
354 value = float(coef) * pow(2.0, exponent / 0.3)
355 else:
356 # Use powers of 10
357 value = float(coef) * pow(10.0, exponent)
358 if byte == 'B': # B == Byte, b == bit
359 value *= 8;
360 return value
362 def init_logging():
363 if (config.has_section('loggers') and
364 config.has_section('handlers') and
365 config.has_section('formatters')):
367 logging.config.fileConfig(config_files)
369 elif getDebug():
370 logging.basicConfig(level=logging.DEBUG)
371 else:
372 logging.basicConfig(level=logging.INFO)