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