simpler, no need to check isepisode
[pyTivo/wgw.git] / config.py
blobff8f5e850a54ae6d1b6b6177554d54b5a47ef226
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_', 'logger_', 'handler_',
85 'formatter_'))
86 or section in ('Server', 'loggers', 'handlers',
87 'formatters')
91 tsnsect = '_tivo_' + tsn
92 if config.has_section(tsnsect) and config.has_option(tsnsect, 'shares'):
93 # clean up leading and trailing spaces & make sure ref is valid
94 tsnshares = []
95 for x in config.get(tsnsect, 'shares').split(','):
96 y = x.strip()
97 if config.has_section(y):
98 tsnshares.append((y, dict(config.items(y))))
99 if tsnshares:
100 shares = tsnshares
102 return shares
104 def getDebug():
105 try:
106 return config.getboolean('Server', 'debug')
107 except NoOptionError, ValueError:
108 return False
110 def getOptres(tsn=None):
111 if tsn and config.has_section('_tivo_' + tsn):
112 try:
113 return config.getboolean('_tivo_' + tsn, 'optres')
114 except NoOptionError, ValueError:
115 pass
116 try:
117 return config.getboolean('Server', 'optres')
118 except NoOptionError, ValueError:
119 return False
121 def getPixelAR(ref):
122 if config.has_option('Server', 'par'):
123 try:
124 return (True, config.getfloat('Server', 'par'))[ref]
125 except NoOptionError, ValueError:
126 pass
127 return (False, 1.0)[ref]
129 def get(section, key):
130 return config.get(section, key)
132 def getFFmpegTemplate(tsn):
133 if tsn and config.has_section('_tivo_' + tsn):
134 try:
135 return config.get('_tivo_' + tsn, 'ffmpeg_tmpl', raw=True)
136 except NoOptionError:
137 pass
138 try:
139 return config.get('Server', 'ffmpeg_tmpl', raw=True)
140 except NoOptionError: #default
141 return '%(video_codec)s %(video_fps)s %(video_br)s %(max_video_br)s \
142 %(buff_size)s %(aspect_ratio)s -comment pyTivo.py %(audio_br)s \
143 %(audio_fr)s %(audio_ch)s %(audio_codec)s %(audio_lang)s \
144 %(ffmpeg_pram)s %(format)s'
146 def getFFmpegPrams(tsn):
147 if tsn and config.has_section('_tivo_' + tsn):
148 try:
149 return config.get('_tivo_' + tsn, 'ffmpeg_pram', raw=True)
150 except NoOptionError:
151 pass
152 try:
153 return config.get('Server', 'ffmpeg_pram', raw=True)
154 except NoOptionError:
155 return None
157 def isHDtivo(tsn): # tsn's of High Definition Tivo's
158 return tsn and tsn[:3] in ['648', '652', '658']
160 def getValidWidths():
161 return [1920, 1440, 1280, 720, 704, 544, 480, 352]
163 def getValidHeights():
164 return [1080, 720, 480] # Technically 240 is also supported
166 # Return the number in list that is nearest to x
167 # if two values are equidistant, return the larger
168 def nearest(x, list):
169 return reduce(lambda a, b: closest(x, a, b), list)
171 def closest(x, a, b):
172 if abs(x - a) < abs(x - b) or (abs(x - a) == abs(x - b) and a > b):
173 return a
174 else:
175 return b
177 def nearestTivoHeight(height):
178 return nearest(height, getValidHeights())
180 def nearestTivoWidth(width):
181 return nearest(width, getValidWidths())
183 def getTivoHeight(tsn):
184 if tsn and config.has_section('_tivo_' + tsn):
185 try:
186 height = config.getint('_tivo_' + tsn, 'height')
187 return nearestTivoHeight(height)
188 except NoOptionError:
189 pass
190 try:
191 height = config.getint('Server', 'height')
192 return nearestTivoHeight(height)
193 except NoOptionError: #defaults for S3/S2 TiVo
194 if isHDtivo(tsn):
195 return 720
196 else:
197 return 480
199 def getTivoWidth(tsn):
200 if tsn and config.has_section('_tivo_' + tsn):
201 try:
202 width = config.getint('_tivo_' + tsn, 'width')
203 return nearestTivoWidth(width)
204 except NoOptionError:
205 pass
206 try:
207 width = config.getint('Server', 'width')
208 return nearestTivoWidth(width)
209 except NoOptionError: #defaults for S3/S2 TiVo
210 if isHDtivo(tsn):
211 return 1280
212 else:
213 return 544
215 def _trunc64(i):
216 return max(int(strtod(i)) / 64000, 1) * 64
218 def getAudioBR(tsn=None):
219 # convert to non-zero multiple of 64 to ensure ffmpeg compatibility
220 # compare audio_br to max_audio_br and return lowest
221 if tsn and config.has_section('_tivo_' + tsn):
222 try:
223 audiobr = _trunc64(config.get('_tivo_' + tsn, 'audio_br'))
224 return str(min(audiobr, getMaxAudioBR(tsn))) + 'k'
225 except NoOptionError:
226 pass
227 try:
228 audiobr = _trunc64(config.get('Server', 'audio_br'))
229 return str(min(audiobr, getMaxAudioBR(tsn))) + 'k'
230 except NoOptionError:
231 return str(min(384, getMaxAudioBR(tsn))) + 'k'
233 def _k(i):
234 return str(int(strtod(i)) / 1000) + 'k'
236 def getVideoBR(tsn=None):
237 if tsn and config.has_section('_tivo_' + tsn):
238 try:
239 return _k(config.get('_tivo_' + tsn, 'video_br'))
240 except NoOptionError:
241 pass
242 try:
243 return _k(config.get('Server', 'video_br'))
244 except NoOptionError: #defaults for S3/S2 TiVo
245 if isHDtivo(tsn):
246 return '8192k'
247 else:
248 return '4096K'
250 def getMaxVideoBR():
251 try:
252 return _k(config.get('Server', 'max_video_br'))
253 except NoOptionError: #default to 30000k
254 return '30000k'
256 def getVideoPCT():
257 try:
258 return config.getfloat('Server', 'video_pct')
259 except NoOptionError:
260 return 70
262 def getBuffSize(tsn=None):
263 tsnsect = '_tivo_' + tsn
264 if tsn and config.has_section(tsnsect):
265 if config.has_option(tsnsect, 'bufsize'):
266 try:
267 return _k(config.get(tsnsect, 'bufsize'))
268 except NoOptionError:
269 pass
270 if config.has_option('Server', 'bufsize'):
271 try:
272 return _k(config.get('Server', 'bufsize'))
273 except NoOptionError:
274 pass
275 if isHDtivo(tsn):
276 return '4096k'
277 else:
278 return '1024k'
280 def getMaxAudioBR(tsn=None):
281 # convert to non-zero multiple of 64 for ffmpeg compatibility
282 if tsn and config.has_section('_tivo_' + tsn):
283 try:
284 return _trunc64(config.get('_tivo_' + tsn, 'max_audio_br'))
285 except NoOptionError:
286 pass
287 try:
288 return _trunc64(config.get('Server', 'max_audio_br'))
289 except NoOptionError:
290 return int(448) # default to 448
292 def get_tsn(name, tsn=None):
293 if tsn and config.has_section('_tivo_' + tsn):
294 try:
295 return config.get('_tivo_' + tsn, name)
296 except NoOptionError:
297 pass
298 try:
299 return config.get('Server', name)
300 except NoOptionError:
301 return None
303 def getAudioCodec(tsn=None):
304 return get_tsn('audio_codec', tsn)
306 def getAudioCH(tsn=None):
307 return get_tsn('audio_ch', tsn)
309 def getAudioFR(tsn=None):
310 return get_tsn('audio_fr', tsn)
312 def getAudioLang(tsn=None):
313 return get_tsn('audio_lang', tsn)
315 def getCopyTS(tsn=None):
316 return get_tsn('copy_ts', tsn)
318 def getVideoFPS(tsn=None):
319 return get_tsn('video_fps', tsn)
321 def getVideoCodec(tsn=None):
322 return get_tsn('video_codec', tsn)
324 def getFormat(tsn=None):
325 return get_tsn('format', tsn)
327 # Parse a bitrate using the SI/IEEE suffix values as if by ffmpeg
328 # For example, 2K==2000, 2Ki==2048, 2MB==16000000, 2MiB==16777216
329 # Algorithm: http://svn.mplayerhq.hu/ffmpeg/trunk/libavcodec/eval.c
330 def strtod(value):
331 prefixes = {'y': -24, 'z': -21, 'a': -18, 'f': -15, 'p': -12,
332 'n': -9, 'u': -6, 'm': -3, 'c': -2, 'd': -1,
333 'h': 2, 'k': 3, 'K': 3, 'M': 6, 'G': 9,
334 'T': 12, 'P': 15, 'E': 18, 'Z': 21, 'Y': 24}
335 p = re.compile(r'^(\d+)(?:([yzafpnumcdhkKMGTPEZY])(i)?)?([Bb])?$')
336 m = p.match(value)
337 if not m:
338 raise SyntaxError('Invalid bit value syntax')
339 (coef, prefix, power, byte) = m.groups()
340 if prefix is None:
341 value = float(coef)
342 else:
343 exponent = float(prefixes[prefix])
344 if power == 'i':
345 # Use powers of 2
346 value = float(coef) * pow(2.0, exponent / 0.3)
347 else:
348 # Use powers of 10
349 value = float(coef) * pow(10.0, exponent)
350 if byte == 'B': # B == Byte, b == bit
351 value *= 8;
352 return value
354 def init_logging():
355 if (config.has_section('loggers') and
356 config.has_section('handlers') and
357 config.has_section('formatters')):
359 logging.config.fileConfig(config_files)
361 elif getDebug():
362 logging.basicConfig(level=logging.DEBUG)
363 else:
364 logging.basicConfig(level=logging.INFO)