Create cache of TiVos
[pyTivo.git] / config.py
blob8f637bc944fc9ecb7ebb9617fc87e192404e060f
1 import ConfigParser, os
2 import re
3 from ConfigParser import NoOptionError
5 BLACKLIST_169 = ('540', '649')
7 config = ConfigParser.ConfigParser()
8 p = os.path.dirname(__file__)
9 config_file = os.path.join(p, 'pyTivo.conf')
10 config.read(config_file)
12 def reset():
13 global config
14 del config
15 config = ConfigParser.ConfigParser()
16 config.read(config_file)
18 def getGUID():
19 if config.has_option('Server', 'GUID'):
20 guid = config.get('Server', 'GUID')
21 else:
22 guid = '123456'
23 return guid
25 def getBeaconAddresses():
26 if config.has_option('Server', 'beacon'):
27 beacon_ips = config.get('Server', 'beacon')
28 else:
29 beacon_ips = '255.255.255.255'
30 return beacon_ips
32 def getPort():
33 return config.get('Server', 'Port')
35 def get169Setting(tsn):
36 if not tsn:
37 return True
39 if config.has_section('_tivo_' + tsn):
40 if config.has_option('_tivo_' + tsn, 'aspect169'):
41 try:
42 return config.getboolean('_tivo_' + tsn, 'aspect169')
43 except ValueError:
44 pass
46 if tsn[:3] in BLACKLIST_169:
47 return False
49 return True
51 def getShares(tsn=''):
52 shares = [(section, dict(config.items(section)))
53 for section in config.sections()
54 if not(section.startswith('_tivo_') or section == 'Server')]
56 if config.has_section('_tivo_' + tsn):
57 if config.has_option('_tivo_' + tsn, 'shares'):
58 # clean up leading and trailing spaces & make sure ref is valid
59 tsnshares = []
60 for x in config.get('_tivo_' + tsn, 'shares').split(','):
61 y = x.lstrip().rstrip()
62 if config.has_section(y):
63 tsnshares += [(y, dict(config.items(y)))]
64 if tsnshares:
65 shares = tsnshares
67 for name, data in shares:
68 if not data.get('auto_subshares', 'False').lower() == 'true':
69 continue
71 base_path = data['path']
72 try:
73 for item in os.listdir(base_path):
74 item_path = os.path.join(base_path, item)
75 if not os.path.isdir(item_path):
76 continue
78 new_name = name + '/' + item
79 new_data = dict(data)
80 new_data['path'] = item_path
82 shares.append((new_name, new_data))
83 except:
84 pass
86 return shares
88 def getDebug():
89 try:
90 return config.getboolean('Server', 'debug')
91 except NoOptionError, ValueError:
92 return False
94 def getHack83():
95 try:
96 debug = config.get('Server', 'hack83')
97 if debug.lower() == 'true':
98 return True
99 else:
100 return False
101 except NoOptionError:
102 return False
104 def getOptres():
105 try:
106 return config.getboolean('Server', 'optres')
107 except NoOptionError, ValueError:
108 return False
110 def get(section, key):
111 return config.get(section, key)
113 def getFFMPEGTemplate(tsn):
114 if tsn and config.has_section('_tivo_' + tsn):
115 try:
116 return config.get('_tivo_' + tsn, 'ffmpeg_prams', raw=True)
117 except NoOptionError:
118 pass
119 try:
120 return config.get('Server', 'ffmpeg_prams', raw=True)
121 except NoOptionError: #default
122 return '-vcodec mpeg2video %(video_fps)s -b %(video_br)s -maxrate %(max_video_br)s -bufsize %(buff_size)s %(aspect_ratio)s -comment pyTivo.py -ab %(audio_br)s %(audio_fr)s %(audio_codec)s -f vob -'
124 def isHDtivo(tsn): # tsn's of High Definition Tivo's
125 return tsn != '' and tsn[:3] in ['648', '652']
127 def getValidWidths():
128 return [1920, 1440, 1280, 720, 704, 544, 480, 352]
130 def getValidHeights():
131 return [1080, 720, 480] # Technically 240 is also supported
133 # Return the number in list that is nearest to x
134 # if two values are equidistant, return the larger
135 def nearest(x, list):
136 return reduce(lambda a, b: closest(x, a, b), list)
138 def closest(x, a, b):
139 if abs(x - a) < abs(x - b) or (abs(x - a) == abs(x - b) and a > b):
140 return a
141 else:
142 return b
144 def nearestTivoHeight(height):
145 return nearest(height, getValidHeights())
147 def nearestTivoWidth(width):
148 return nearest(width, getValidWidths())
150 def getTivoHeight(tsn):
151 if tsn and config.has_section('_tivo_' + tsn):
152 try:
153 height = config.getint('_tivo_' + tsn, 'height')
154 return nearestTivoHeight(height)
155 except NoOptionError:
156 pass
157 try:
158 height = config.getint('Server', 'height')
159 return nearestTivoHeight(height)
160 except NoOptionError: #defaults for S3/S2 TiVo
161 if isHDtivo(tsn):
162 return 720
163 else:
164 return 480
166 def getTivoWidth(tsn):
167 if tsn and config.has_section('_tivo_' + tsn):
168 try:
169 width = config.getint('_tivo_' + tsn, 'width')
170 return nearestTivoWidth(width)
171 except NoOptionError:
172 pass
173 try:
174 width = config.getint('Server', 'width')
175 return nearestTivoWidth(width)
176 except NoOptionError: #defaults for S3/S2 TiVo
177 if isHDtivo(tsn):
178 return 1280
179 else:
180 return 544
182 def getAudioBR(tsn = None):
183 #convert to non-zero multiple of 64 to ensure ffmpeg compatibility
184 #compare audio_br to max_audio_br and return lowest
185 if tsn and config.has_section('_tivo_' + tsn):
186 try:
187 audiobr = int(max(int(strtod(config.get('_tivo_' + tsn, 'audio_br'))/1000), 64)/64)*64
188 return str(min(audiobr, getMaxAudioBR(tsn))) + 'k'
189 except NoOptionError:
190 pass
191 try:
192 audiobr = int(max(int(strtod(config.get('Server', 'audio_br'))/1000), 64)/64)*64
193 return str(min(audiobr, getMaxAudioBR(tsn))) + 'k'
194 except NoOptionError: #defaults for S3/S2 TiVo
195 if isHDtivo(tsn):
196 return '384k'
197 else:
198 return '192k'
200 def getVideoBR(tsn = None):
201 if tsn and config.has_section('_tivo_' + tsn):
202 try:
203 return config.get('_tivo_' + tsn, 'video_br')
204 except NoOptionError:
205 pass
206 try:
207 return config.get('Server', 'video_br')
208 except NoOptionError: #defaults for S3/S2 TiVo
209 if isHDtivo(tsn):
210 return '8192k'
211 else:
212 return '4096K'
214 def getMaxVideoBR():
215 try:
216 return str(int(strtod(config.get('Server', 'max_video_br'))/1000)) + 'k'
217 except NoOptionError: #default to 17Mi
218 return '17408k'
220 def getBuffSize():
221 try:
222 return config.get('Server', 'bufsize')
223 except NoOptionError: #default 1024k
224 return '1024k'
226 def getMaxAudioBR(tsn = None):
227 #convert to non-zero multiple of 64 for ffmpeg compatibility
228 if tsn and config.has_section('_tivo_' + tsn):
229 try:
230 return int(int(strtod(config.get('_tivo_' + tsn, 'max_audio_br'))/1000)/64)*64
231 except NoOptionError:
232 pass
233 try:
234 return int(int(strtod(config.get('Server', 'max_audio_br'))/1000)/64)*64
235 except NoOptionError:
236 return int(448) #default to 448
238 # Parse a bitrate using the SI/IEEE suffix values as if by ffmpeg
239 # For example, 2K==2000, 2Ki==2048, 2MB==16000000, 2MiB==16777216
240 # Algorithm: http://svn.mplayerhq.hu/ffmpeg/trunk/libavcodec/eval.c
241 def strtod(value):
242 prefixes = {'y': -24, 'z': -21, 'a': -18, 'f': -15, 'p': -12,
243 'n': -9, 'u': -6, 'm': -3, 'c': -2, 'd': -1,
244 'h': 2, 'k': 3, 'K': 3, 'M': 6, 'G': 9,
245 'T': 12, 'P': 15, 'E': 18, 'Z': 21, 'Y': 24}
246 p = re.compile(r'^(\d+)(?:([yzafpnumcdhkKMGTPEZY])(i)?)?([Bb])?$')
247 m = p.match(value)
248 if m is None:
249 raise SyntaxError('Invalid bit value syntax')
250 (coef, prefix, power, byte) = m.groups()
251 if prefix is None:
252 value = float(coef)
253 else:
254 exponent = float(prefixes[prefix])
255 if power == 'i':
256 # Use powers of 2
257 value = float(coef) * pow(2.0, exponent / 0.3)
258 else:
259 # Use powers of 10
260 value = float(coef) * pow(10.0, exponent)
261 if byte == 'B': # B == Byte, b == bit
262 value *= 8;
263 return value