Merge branch 'master' of git://repo.or.cz/pyTivo/wgw
[pyTivo.git] / config.py
blob9c858c6b14b1a56358711817c8a630d15f63be85
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(ref):
89 if config.has_option('Server', 'debug'):
90 try:
91 return str2tuple(config.get('Server', 'debug')+',,')[ref]
92 except NoOptionError:
93 pass
94 return str2tuple('False,,')[ref]
96 def getHack83():
97 try:
98 debug = config.get('Server', 'hack83')
99 if debug.lower() == 'true':
100 return True
101 else:
102 return False
103 except NoOptionError:
104 return False
106 def getOptres():
107 try:
108 return config.getboolean('Server', 'optres')
109 except NoOptionError, ValueError:
110 return False
112 def get(section, key):
113 return config.get(section, key)
115 def getFFMPEGTemplate(tsn):
116 if tsn and config.has_section('_tivo_' + tsn):
117 try:
118 return config.get('_tivo_' + tsn, 'ffmpeg_prams', raw=True)
119 except NoOptionError:
120 pass
121 try:
122 return config.get('Server', 'ffmpeg_prams', raw=True)
123 except NoOptionError: #default
124 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 -'
126 def isHDtivo(tsn): # tsn's of High Definition Tivo's
127 return tsn != '' and tsn[:3] in ['648', '652']
129 def getValidWidths():
130 return [1920, 1440, 1280, 720, 704, 544, 480, 352]
132 def getValidHeights():
133 return [1080, 720, 480] # Technically 240 is also supported
135 # Return the number in list that is nearest to x
136 # if two values are equidistant, return the larger
137 def nearest(x, list):
138 return reduce(lambda a, b: closest(x, a, b), list)
140 def closest(x, a, b):
141 if abs(x - a) < abs(x - b) or (abs(x - a) == abs(x - b) and a > b):
142 return a
143 else:
144 return b
146 def nearestTivoHeight(height):
147 return nearest(height, getValidHeights())
149 def nearestTivoWidth(width):
150 return nearest(width, getValidWidths())
152 def getTivoHeight(tsn):
153 if tsn and config.has_section('_tivo_' + tsn):
154 try:
155 height = config.getint('_tivo_' + tsn, 'height')
156 return nearestTivoHeight(height)
157 except NoOptionError:
158 pass
159 try:
160 height = config.getint('Server', 'height')
161 return nearestTivoHeight(height)
162 except NoOptionError: #defaults for S3/S2 TiVo
163 if isHDtivo(tsn):
164 return 720
165 else:
166 return 480
168 def getTivoWidth(tsn):
169 if tsn and config.has_section('_tivo_' + tsn):
170 try:
171 width = config.getint('_tivo_' + tsn, 'width')
172 return nearestTivoWidth(width)
173 except NoOptionError:
174 pass
175 try:
176 width = config.getint('Server', 'width')
177 return nearestTivoWidth(width)
178 except NoOptionError: #defaults for S3/S2 TiVo
179 if isHDtivo(tsn):
180 return 1280
181 else:
182 return 544
184 def getAudioBR(tsn = None):
185 #convert to non-zero multiple of 64 to ensure ffmpeg compatibility
186 #compare audio_br to max_audio_br and return lowest
187 if tsn and config.has_section('_tivo_' + tsn):
188 try:
189 audiobr = int(max(int(strtod(config.get('_tivo_' + tsn, 'audio_br'))/1000), 64)/64)*64
190 return str(min(audiobr, getMaxAudioBR(tsn))) + 'k'
191 except NoOptionError:
192 pass
193 try:
194 audiobr = int(max(int(strtod(config.get('Server', 'audio_br'))/1000), 64)/64)*64
195 return str(min(audiobr, getMaxAudioBR(tsn))) + 'k'
196 except NoOptionError: #defaults for S3/S2 TiVo
197 if isHDtivo(tsn):
198 return '384k'
199 else:
200 return '192k'
202 def getVideoBR(tsn = None):
203 if tsn and config.has_section('_tivo_' + tsn):
204 try:
205 return config.get('_tivo_' + tsn, 'video_br')
206 except NoOptionError:
207 pass
208 try:
209 return config.get('Server', 'video_br')
210 except NoOptionError: #defaults for S3/S2 TiVo
211 if isHDtivo(tsn):
212 return '8192k'
213 else:
214 return '4096K'
216 def getMaxVideoBR():
217 try:
218 return str(int(strtod(config.get('Server', 'max_video_br'))/1000)) + 'k'
219 except NoOptionError: #default to 17Mi
220 return '17408k'
222 def getBuffSize():
223 try:
224 return str(int(strtod(config.get('Server', 'bufsize'))))
225 except NoOptionError: #default 1024k
226 return '1024k'
228 def getMaxAudioBR(tsn = None):
229 #convert to non-zero multiple of 64 for ffmpeg compatibility
230 if tsn and config.has_section('_tivo_' + tsn):
231 try:
232 return int(int(strtod(config.get('_tivo_' + tsn, 'max_audio_br'))/1000)/64)*64
233 except NoOptionError:
234 pass
235 try:
236 return int(int(strtod(config.get('Server', 'max_audio_br'))/1000)/64)*64
237 except NoOptionError:
238 return int(448) #default to 448
240 def str2tuple(s):
241 items = s.split(',')
242 L = [x.strip() for x in items]
243 return tuple(L)
245 # Parse a bitrate using the SI/IEEE suffix values as if by ffmpeg
246 # For example, 2K==2000, 2Ki==2048, 2MB==16000000, 2MiB==16777216
247 # Algorithm: http://svn.mplayerhq.hu/ffmpeg/trunk/libavcodec/eval.c
248 def strtod(value):
249 prefixes = {'y': -24, 'z': -21, 'a': -18, 'f': -15, 'p': -12,
250 'n': -9, 'u': -6, 'm': -3, 'c': -2, 'd': -1,
251 'h': 2, 'k': 3, 'K': 3, 'M': 6, 'G': 9,
252 'T': 12, 'P': 15, 'E': 18, 'Z': 21, 'Y': 24}
253 p = re.compile(r'^(\d+)(?:([yzafpnumcdhkKMGTPEZY])(i)?)?([Bb])?$')
254 m = p.match(value)
255 if m is None:
256 raise SyntaxError('Invalid bit value syntax')
257 (coef, prefix, power, byte) = m.groups()
258 if prefix is None:
259 value = float(coef)
260 else:
261 exponent = float(prefixes[prefix])
262 if power == 'i':
263 # Use powers of 2
264 value = float(coef) * pow(2.0, exponent / 0.3)
265 else:
266 # Use powers of 10
267 value = float(coef) * pow(10.0, exponent)
268 if byte == 'B': # B == Byte, b == bit
269 value *= 8;
270 return value