FFMpeg will not output a 15 fps mpeg2
[pyTivo/krkeegan.git] / config.py
blob5e370b9966bf2417704985c5bfaf853bee5a7f89
1 import ConfigParser, os
2 import re
3 import random
4 import string
5 from ConfigParser import NoOptionError
7 BLACKLIST_169 = ('540', '649')
9 config = ConfigParser.ConfigParser()
10 p = os.path.dirname(__file__)
11 config_file = os.path.join(p, 'pyTivo.conf')
12 config.read(config_file)
14 def reset():
15 global config
16 del config
17 config = ConfigParser.ConfigParser()
18 config.read(config_file)
20 def getGUID():
21 if config.has_option('Server', 'GUID'):
22 return config.get('Server', 'GUID')
23 else:
24 return ''.join([random.choice(string.letters) for i in range(10)])
25 return guid
27 def getTivoUsername():
28 return config.get('Server', 'tivo_username')
30 def getTivoPassword():
31 return config.get('Server', 'tivo_password')
33 def getBeaconAddresses():
34 if config.has_option('Server', 'beacon'):
35 beacon_ips = config.get('Server', 'beacon')
36 else:
37 beacon_ips = '255.255.255.255'
38 return beacon_ips
40 def getPort():
41 return config.get('Server', 'Port')
43 def get169Setting(tsn):
44 if not tsn:
45 return True
47 if config.has_section('_tivo_' + tsn):
48 if config.has_option('_tivo_' + tsn, 'aspect169'):
49 try:
50 return config.getboolean('_tivo_' + tsn, 'aspect169')
51 except ValueError:
52 pass
54 if tsn[:3] in BLACKLIST_169:
55 return False
57 return True
59 def getShares(tsn=''):
60 shares = [(section, dict(config.items(section)))
61 for section in config.sections()
62 if not(section.startswith('_tivo_') or section == 'Server')]
64 if config.has_section('_tivo_' + tsn):
65 if config.has_option('_tivo_' + tsn, 'shares'):
66 # clean up leading and trailing spaces & make sure ref is valid
67 tsnshares = []
68 for x in config.get('_tivo_' + tsn, 'shares').split(','):
69 y = x.lstrip().rstrip()
70 if config.has_section(y):
71 tsnshares += [(y, dict(config.items(y)))]
72 if tsnshares:
73 shares = tsnshares
75 for name, data in shares:
76 if not data.get('auto_subshares', 'False').lower() == 'true':
77 continue
79 base_path = data['path']
80 try:
81 for item in os.listdir(base_path):
82 item_path = os.path.join(base_path, item)
83 if not os.path.isdir(item_path):
84 continue
86 new_name = name + '/' + item
87 new_data = dict(data)
88 new_data['path'] = item_path
90 shares.append((new_name, new_data))
91 except:
92 pass
94 return shares
96 def getDebug(ref):
97 if config.has_option('Server', 'debug'):
98 try:
99 return str2tuple(config.get('Server', 'debug')+',,')[ref]
100 except NoOptionError:
101 pass
102 return str2tuple('False,,')[ref]
104 def getHack83():
105 try:
106 debug = config.get('Server', 'hack83')
107 if debug.lower() == 'true':
108 return True
109 else:
110 return False
111 except NoOptionError:
112 return False
114 def getOptres(tsn = None):
115 if tsn and config.has_section('_tivo_' + tsn):
116 try:
117 return config.getboolean('_tivo_' + tsn, 'optres')
118 except NoOptionError, ValueError:
119 pass
120 try:
121 return config.getboolean('Server', 'optres')
122 except NoOptionError, ValueError:
123 return False
125 def getPixelAR(ref):
126 if config.has_option('Server', 'par'):
127 try:
128 return (True, config.getfloat('Server', 'par'))[ref]
129 except NoOptionError, ValueError:
130 pass
131 return (False, 1.0)[ref]
133 def get(section, key):
134 return config.get(section, key)
136 def getFFmpegTemplate(tsn):
137 if tsn and config.has_section('_tivo_' + tsn):
138 try:
139 return config.get('_tivo_' + tsn, 'ffmpeg_tmpl', raw=True)
140 except NoOptionError:
141 pass
142 try:
143 return config.get('Server', 'ffmpeg_tmpl', raw=True)
144 except NoOptionError: #default
145 return '%(video_codec)s %(video_fps)s %(video_br)s %(max_video_br)s \
146 %(buff_size)s %(aspect_ratio)s -comment pyTivo.py %(audio_br)s \
147 %(audio_fr)s %(audio_ch)s %(audio_codec)s %(ffmpeg_pram)s %(format)s'
149 def getFFmpegPrams(tsn):
150 if tsn and config.has_section('_tivo_' + tsn):
151 try:
152 return config.get('_tivo_' + tsn, 'ffmpeg_pram', raw=True)
153 except NoOptionError:
154 pass
155 try:
156 return config.get('Server', 'ffmpeg_pram', raw=True)
157 except NoOptionError:
158 return None
160 def isHDtivo(tsn): # tsn's of High Definition Tivo's
161 return tsn != '' and tsn[:3] in ['648', '652']
163 def getValidWidths():
164 return [1920, 1440, 1280, 720, 704, 544, 480, 352]
166 def getValidHeights():
167 return [1080, 720, 480] # Technically 240 is also supported
169 # Return the number in list that is nearest to x
170 # if two values are equidistant, return the larger
171 def nearest(x, list):
172 return reduce(lambda a, b: closest(x, a, b), list)
174 def closest(x, a, b):
175 if abs(x - a) < abs(x - b) or (abs(x - a) == abs(x - b) and a > b):
176 return a
177 else:
178 return b
180 def nearestTivoHeight(height):
181 return nearest(height, getValidHeights())
183 def nearestTivoWidth(width):
184 return nearest(width, getValidWidths())
186 def getTivoHeight(tsn):
187 if tsn and config.has_section('_tivo_' + tsn):
188 try:
189 height = config.getint('_tivo_' + tsn, 'height')
190 return nearestTivoHeight(height)
191 except NoOptionError:
192 pass
193 try:
194 height = config.getint('Server', 'height')
195 return nearestTivoHeight(height)
196 except NoOptionError: #defaults for S3/S2 TiVo
197 if isHDtivo(tsn):
198 return 720
199 else:
200 return 480
202 def getTivoWidth(tsn):
203 if tsn and config.has_section('_tivo_' + tsn):
204 try:
205 width = config.getint('_tivo_' + tsn, 'width')
206 return nearestTivoWidth(width)
207 except NoOptionError:
208 pass
209 try:
210 width = config.getint('Server', 'width')
211 return nearestTivoWidth(width)
212 except NoOptionError: #defaults for S3/S2 TiVo
213 if isHDtivo(tsn):
214 return 1280
215 else:
216 return 544
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 = int(max(int(strtod(config.get('_tivo_' + tsn, 'audio_br'))/1000), 64)/64)*64
224 return str(min(audiobr, getMaxAudioBR(tsn))) + 'k'
225 except NoOptionError:
226 pass
227 try:
228 audiobr = int(max(int(strtod(config.get('Server', 'audio_br'))/1000), 64)/64)*64
229 return str(min(audiobr, getMaxAudioBR(tsn))) + 'k'
230 except NoOptionError:
231 return str(min(384, getMaxAudioBR(tsn))) + 'k'
233 def getVideoBR(tsn = None):
234 if tsn and config.has_section('_tivo_' + tsn):
235 try:
236 return config.get('_tivo_' + tsn, 'video_br')
237 except NoOptionError:
238 pass
239 try:
240 return config.get('Server', 'video_br')
241 except NoOptionError: #defaults for S3/S2 TiVo
242 if isHDtivo(tsn):
243 return '8192k'
244 else:
245 return '4096K'
247 def getMaxVideoBR():
248 try:
249 return str(int(strtod(config.get('Server', 'max_video_br'))/1000)) + 'k'
250 except NoOptionError: #default to 17Mi
251 return '17408k'
253 def getBuffSize():
254 try:
255 return str(int(strtod(config.get('Server', 'bufsize'))))
256 except NoOptionError: #default 1024k
257 return '1024k'
259 def getMaxAudioBR(tsn = None):
260 #convert to non-zero multiple of 64 for ffmpeg compatibility
261 if tsn and config.has_section('_tivo_' + tsn):
262 try:
263 return int(int(strtod(config.get('_tivo_' + tsn, 'max_audio_br'))/1000)/64)*64
264 except NoOptionError:
265 pass
266 try:
267 return int(int(strtod(config.get('Server', 'max_audio_br'))/1000)/64)*64
268 except NoOptionError:
269 return int(448) #default to 448
271 def getAudioCodec(tsn = None):
272 if tsn and config.has_section('_tivo_' + tsn):
273 try:
274 return config.get('_tivo_' + tsn, 'audio_codec')
275 except NoOptionError:
276 pass
277 try:
278 return config.get('Server', 'audio_codec')
279 except NoOptionError:
280 return None
282 def getAudioCH(tsn = None):
283 if tsn and config.has_section('_tivo_' + tsn):
284 try:
285 return config.get('_tivo_' + tsn, 'audio_ch')
286 except NoOptionError:
287 pass
288 try:
289 return config.get('Server', 'audio_ch')
290 except NoOptionError:
291 return None
293 def getAudioFR(tsn = None):
294 if tsn and config.has_section('_tivo_' + tsn):
295 try:
296 return config.get('_tivo_' + tsn, 'audio_fr')
297 except NoOptionError:
298 pass
299 try:
300 return config.get('Server', 'audio_fr')
301 except NoOptionError:
302 return None
304 def getVideoFPS(tsn = None):
305 if tsn and config.has_section('_tivo_' + tsn):
306 try:
307 return config.get('_tivo_' + tsn, 'video_fps')
308 except NoOptionError:
309 pass
310 try:
311 return config.get('Server', 'video_fps')
312 except NoOptionError:
313 return None
315 def getVideoCodec(tsn = None):
316 if tsn and config.has_section('_tivo_' + tsn):
317 try:
318 return config.get('_tivo_' + tsn, 'video_codec')
319 except NoOptionError:
320 pass
321 try:
322 return config.get('Server', 'video_codec')
323 except NoOptionError:
324 return None
326 def getFormat(tsn = None):
327 if tsn and config.has_section('_tivo_' + tsn):
328 try:
329 return config.get('_tivo_' + tsn, 'force_format')
330 except NoOptionError:
331 pass
332 try:
333 return config.get('Server', 'force_format')
334 except NoOptionError:
335 return None
337 def str2tuple(s):
338 items = s.split(',')
339 L = [x.strip() for x in items]
340 return tuple(L)
342 # Parse a bitrate using the SI/IEEE suffix values as if by ffmpeg
343 # For example, 2K==2000, 2Ki==2048, 2MB==16000000, 2MiB==16777216
344 # Algorithm: http://svn.mplayerhq.hu/ffmpeg/trunk/libavcodec/eval.c
345 def strtod(value):
346 prefixes = {'y': -24, 'z': -21, 'a': -18, 'f': -15, 'p': -12,
347 'n': -9, 'u': -6, 'm': -3, 'c': -2, 'd': -1,
348 'h': 2, 'k': 3, 'K': 3, 'M': 6, 'G': 9,
349 'T': 12, 'P': 15, 'E': 18, 'Z': 21, 'Y': 24}
350 p = re.compile(r'^(\d+)(?:([yzafpnumcdhkKMGTPEZY])(i)?)?([Bb])?$')
351 m = p.match(value)
352 if m is None:
353 raise SyntaxError('Invalid bit value syntax')
354 (coef, prefix, power, byte) = m.groups()
355 if prefix is None:
356 value = float(coef)
357 else:
358 exponent = float(prefixes[prefix])
359 if power == 'i':
360 # Use powers of 2
361 value = float(coef) * pow(2.0, exponent / 0.3)
362 else:
363 # Use powers of 10
364 value = float(coef) * pow(10.0, exponent)
365 if byte == 'B': # B == Byte, b == bit
366 value *= 8;
367 return value