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