Strip the Tribune notice from the descriptions.
[pyTivo/wmcbrine.git] / config.py
blob158a6cd918de341dc1e8cbe04be1a519f9051051
1 import ConfigParser, os, sys
2 import re
3 import random
4 import string
5 from ConfigParser import NoOptionError
7 BLACKLIST_169 = ('540', '649')
8 guid = ''.join([random.choice(string.letters) for i in range(10)])
10 config = ConfigParser.ConfigParser()
11 p = os.path.dirname(__file__)
13 config_files = [
14 '/etc/pyTivo.conf',
15 os.path.join(p, 'pyTivo.conf'),
17 config_exists = False
18 for config_file in config_files:
19 if os.path.exists(config_file):
20 config_exists = True
21 if not config_exists:
22 print 'ERROR: pyTivo.conf does not exist.\n' + \
23 'You must create this file before running pyTivo.'
24 sys.exit(1)
25 config.read(config_files)
27 def reset():
28 global config
29 del config
30 config = ConfigParser.ConfigParser()
31 config.read(config_files)
33 def getGUID():
34 if config.has_option('Server', 'GUID'):
35 return config.get('Server', 'GUID')
36 else:
37 return guid
39 def getTivoUsername():
40 return config.get('Server', 'tivo_username')
42 def getTivoPassword():
43 return config.get('Server', 'tivo_password')
45 def getBeaconAddresses():
46 if config.has_option('Server', 'beacon'):
47 beacon_ips = config.get('Server', 'beacon')
48 else:
49 beacon_ips = '255.255.255.255'
50 return beacon_ips
52 def getPort():
53 return config.get('Server', 'Port')
55 def get169Blacklist(tsn): # tivo does not pad 16:9 video
56 return tsn != '' and tsn[:3] in ('540')
58 def get169Letterbox(tsn): # tivo pads 16:9 video for 4:3 display
59 return tsn != '' and tsn[:3] in ('649')
61 def get169Setting(tsn):
62 if not tsn:
63 return True
65 if config.has_section('_tivo_' + tsn):
66 if config.has_option('_tivo_' + tsn, 'aspect169'):
67 try:
68 return config.getboolean('_tivo_' + tsn, 'aspect169')
69 except ValueError:
70 pass
72 if get169Blacklist(tsn) or get169Letterbox(tsn):
73 return False
75 return True
77 def getShares(tsn=''):
78 shares = [(section, dict(config.items(section)))
79 for section in config.sections()
80 if not (
81 section.startswith('_tivo_')
82 or section in ('Server', 'loggers', 'handlers', 'formatters')
83 or section.startswith('logger_')
84 or section.startswith('handler_')
85 or section.startswith('formatter_')
89 if config.has_section('_tivo_' + tsn):
90 if config.has_option('_tivo_' + tsn, 'shares'):
91 # clean up leading and trailing spaces & make sure ref is valid
92 tsnshares = []
93 for x in config.get('_tivo_' + tsn, 'shares').split(','):
94 y = x.lstrip().rstrip()
95 if config.has_section(y):
96 tsnshares += [(y, dict(config.items(y)))]
97 if tsnshares:
98 shares = tsnshares
100 for name, data in shares:
101 if not data.get('auto_subshares', 'False').lower() == 'true':
102 continue
104 base_path = data['path']
105 try:
106 for item in os.listdir(base_path):
107 item_path = os.path.join(base_path, item)
108 if not os.path.isdir(item_path) or item.startswith('.'):
109 continue
111 new_name = name + '/' + item
112 new_data = dict(data)
113 new_data['path'] = item_path
115 shares.append((new_name, new_data))
116 except:
117 pass
119 return shares
121 def getDebug():
122 try:
123 return config.getboolean('Server', 'debug')
124 except NoOptionError, ValueError:
125 return False
127 def getHack83():
128 try:
129 debug = config.get('Server', 'hack83')
130 if debug.lower() == 'true':
131 return True
132 else:
133 return False
134 except NoOptionError:
135 return False
137 def getOptres(tsn = None):
138 if tsn and config.has_section('_tivo_' + tsn):
139 try:
140 return config.getboolean('_tivo_' + tsn, 'optres')
141 except NoOptionError, ValueError:
142 pass
143 try:
144 return config.getboolean('Server', 'optres')
145 except NoOptionError, ValueError:
146 return False
148 def getPixelAR(ref):
149 if config.has_option('Server', 'par'):
150 try:
151 return (True, config.getfloat('Server', 'par'))[ref]
152 except NoOptionError, ValueError:
153 pass
154 return (False, 1.0)[ref]
156 def get(section, key):
157 return config.get(section, key)
159 def getFFmpegTemplate(tsn):
160 if tsn and config.has_section('_tivo_' + tsn):
161 try:
162 return config.get('_tivo_' + tsn, 'ffmpeg_tmpl', raw=True)
163 except NoOptionError:
164 pass
165 try:
166 return config.get('Server', 'ffmpeg_tmpl', raw=True)
167 except NoOptionError: #default
168 return '%(video_codec)s %(video_fps)s %(video_br)s %(max_video_br)s \
169 %(buff_size)s %(aspect_ratio)s -comment pyTivo.py %(audio_br)s \
170 %(audio_fr)s %(audio_ch)s %(audio_codec)s %(audio_lang)s \
171 %(ffmpeg_pram)s %(format)s'
173 def getFFmpegPrams(tsn):
174 if tsn and config.has_section('_tivo_' + tsn):
175 try:
176 return config.get('_tivo_' + tsn, 'ffmpeg_pram', raw=True)
177 except NoOptionError:
178 pass
179 try:
180 return config.get('Server', 'ffmpeg_pram', raw=True)
181 except NoOptionError:
182 return None
184 def isHDtivo(tsn): # tsn's of High Definition Tivo's
185 return tsn != '' and tsn[:3] in ['648', '652']
187 def getValidWidths():
188 return [1920, 1440, 1280, 720, 704, 544, 480, 352]
190 def getValidHeights():
191 return [1080, 720, 480] # Technically 240 is also supported
193 # Return the number in list that is nearest to x
194 # if two values are equidistant, return the larger
195 def nearest(x, list):
196 return reduce(lambda a, b: closest(x, a, b), list)
198 def closest(x, a, b):
199 if abs(x - a) < abs(x - b) or (abs(x - a) == abs(x - b) and a > b):
200 return a
201 else:
202 return b
204 def nearestTivoHeight(height):
205 return nearest(height, getValidHeights())
207 def nearestTivoWidth(width):
208 return nearest(width, getValidWidths())
210 def getTivoHeight(tsn):
211 if tsn and config.has_section('_tivo_' + tsn):
212 try:
213 height = config.getint('_tivo_' + tsn, 'height')
214 return nearestTivoHeight(height)
215 except NoOptionError:
216 pass
217 try:
218 height = config.getint('Server', 'height')
219 return nearestTivoHeight(height)
220 except NoOptionError: #defaults for S3/S2 TiVo
221 if isHDtivo(tsn):
222 return 720
223 else:
224 return 480
226 def getTivoWidth(tsn):
227 if tsn and config.has_section('_tivo_' + tsn):
228 try:
229 width = config.getint('_tivo_' + tsn, 'width')
230 return nearestTivoWidth(width)
231 except NoOptionError:
232 pass
233 try:
234 width = config.getint('Server', 'width')
235 return nearestTivoWidth(width)
236 except NoOptionError: #defaults for S3/S2 TiVo
237 if isHDtivo(tsn):
238 return 1280
239 else:
240 return 544
242 def getAudioBR(tsn = None):
243 #convert to non-zero multiple of 64 to ensure ffmpeg compatibility
244 #compare audio_br to max_audio_br and return lowest
245 if tsn and config.has_section('_tivo_' + tsn):
246 try:
247 audiobr = int(max(int(strtod(config.get('_tivo_' + tsn, 'audio_br'))/1000), 64)/64)*64
248 return str(min(audiobr, getMaxAudioBR(tsn))) + 'k'
249 except NoOptionError:
250 pass
251 try:
252 audiobr = int(max(int(strtod(config.get('Server', 'audio_br'))/1000), 64)/64)*64
253 return str(min(audiobr, getMaxAudioBR(tsn))) + 'k'
254 except NoOptionError:
255 return str(min(384, getMaxAudioBR(tsn))) + 'k'
257 def getVideoBR(tsn = None):
258 if tsn and config.has_section('_tivo_' + tsn):
259 try:
260 return str(int(strtod(config.get('_tivo_' + tsn, 'video_br'))/1000)) + 'k'
261 except NoOptionError:
262 pass
263 try:
264 return str(int(strtod(config.get('Server', 'video_br'))/1000)) + 'k'
265 except NoOptionError: #defaults for S3/S2 TiVo
266 if isHDtivo(tsn):
267 return '8192k'
268 else:
269 return '4096K'
271 def getMaxVideoBR():
272 try:
273 return str(int(strtod(config.get('Server', 'max_video_br'))/1000)) + 'k'
274 except NoOptionError: #default to 30000k
275 return '30000k'
277 def getVideoPCT():
278 try:
279 return config.getfloat('Server', 'video_pct')
280 except NoOptionError:
281 return 70
283 def getBuffSize():
284 try:
285 return str(int(strtod(config.get('Server', 'bufsize'))/1000)) + 'k'
286 except NoOptionError: #default 1024k
287 return '1024k'
289 def getMaxAudioBR(tsn = None):
290 #convert to non-zero multiple of 64 for ffmpeg compatibility
291 if tsn and config.has_section('_tivo_' + tsn):
292 try:
293 return int(int(strtod(config.get('_tivo_' + tsn, 'max_audio_br'))/1000)/64)*64
294 except NoOptionError:
295 pass
296 try:
297 return int(int(strtod(config.get('Server', 'max_audio_br'))/1000)/64)*64
298 except NoOptionError:
299 return int(448) #default to 448
301 def get_tsn(name, tsn=None):
302 if tsn and config.has_section('_tivo_' + tsn):
303 try:
304 return config.get('_tivo_' + tsn, name)
305 except NoOptionError:
306 pass
307 try:
308 return config.get('Server', name)
309 except NoOptionError:
310 return None
312 def getAudioCodec(tsn=None):
313 return get_tsn('audio_codec', tsn)
315 def getAudioCH(tsn=None):
316 return get_tsn('audio_ch', tsn)
318 def getAudioFR(tsn=None):
319 return get_tsn('audio_fr', tsn)
321 def getAudioLang(tsn=None):
322 return get_tsn('audio_lang', tsn)
324 def getCopyTS(tsn = None):
325 if tsn and config.has_section('_tivo_' + tsn):
326 if config.has_option('_tivo_' + tsn, 'copy_ts'):
327 try:
328 return config.get('_tivo_' + tsn, 'copy_ts')
329 except NoOptionError, ValueError:
330 pass
331 if config.has_option('Server', 'copy_ts'):
332 try:
333 return config.get('Server', 'copy_ts')
334 except NoOptionError, ValueError:
335 pass
336 return 'none'
338 def getVideoFPS(tsn=None):
339 return get_tsn('video_fps', tsn)
341 def getVideoCodec(tsn=None):
342 return get_tsn('video_codec', tsn)
344 def getFormat(tsn = None):
345 return get_tsn('force_format', tsn)
347 # Parse a bitrate using the SI/IEEE suffix values as if by ffmpeg
348 # For example, 2K==2000, 2Ki==2048, 2MB==16000000, 2MiB==16777216
349 # Algorithm: http://svn.mplayerhq.hu/ffmpeg/trunk/libavcodec/eval.c
350 def strtod(value):
351 prefixes = {'y': -24, 'z': -21, 'a': -18, 'f': -15, 'p': -12,
352 'n': -9, 'u': -6, 'm': -3, 'c': -2, 'd': -1,
353 'h': 2, 'k': 3, 'K': 3, 'M': 6, 'G': 9,
354 'T': 12, 'P': 15, 'E': 18, 'Z': 21, 'Y': 24}
355 p = re.compile(r'^(\d+)(?:([yzafpnumcdhkKMGTPEZY])(i)?)?([Bb])?$')
356 m = p.match(value)
357 if m is None:
358 raise SyntaxError('Invalid bit value syntax')
359 (coef, prefix, power, byte) = m.groups()
360 if prefix is None:
361 value = float(coef)
362 else:
363 exponent = float(prefixes[prefix])
364 if power == 'i':
365 # Use powers of 2
366 value = float(coef) * pow(2.0, exponent / 0.3)
367 else:
368 # Use powers of 10
369 value = float(coef) * pow(10.0, exponent)
370 if byte == 'B': # B == Byte, b == bit
371 value *= 8;
372 return value