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