Use a temporary file for the audio bitrate check, instead of the
[pyTivo/TheBayer.git] / config.py
blobd920076a464fe21921b81eeebf432fbee86279e6
1 import ConfigParser
2 import getopt
3 import logging
4 import logging.config
5 import os
6 import re
7 import random
8 import string
9 import sys
10 from ConfigParser import NoOptionError
12 guid = ''.join([random.choice(string.letters) for i in range(10)])
14 config = ConfigParser.ConfigParser()
16 p = os.path.dirname(__file__)
17 config_files = ['/etc/pyTivo.conf', os.path.join(p, 'pyTivo.conf')]
18 configs_found = []
20 def init(argv):
21 global config_files
22 global configs_found
24 try:
25 opts, _ = getopt.getopt(argv, 'c:e:', ['config=', 'extraconf='])
26 except getopt.GetoptError, msg:
27 print msg
29 for opt, value in opts:
30 if opt in ('-c', '--config'):
31 config_files = [value]
32 elif opt in ('-e', '--extraconf'):
33 config_files.append(value)
35 configs_found = config.read(config_files)
36 if not configs_found:
37 print ('ERROR: pyTivo.conf does not exist.\n' +
38 'You must create this file before running pyTivo.')
39 sys.exit(1)
41 def reset():
42 global config
43 newconfig = ConfigParser.ConfigParser()
44 newconfig.read(config_files)
45 config = newconfig
47 def write():
48 f = open(configs_found[-1], 'w')
49 config.write(f)
50 f.close()
52 def getGUID():
53 if config.has_option('Server', 'GUID'):
54 return config.get('Server', 'GUID')
55 else:
56 return guid
58 def getTivoUsername():
59 return config.get('Server', 'tivo_username')
61 def getTivoPassword():
62 return config.get('Server', 'tivo_password')
64 def getBeaconAddresses():
65 if config.has_option('Server', 'beacon'):
66 beacon_ips = config.get('Server', 'beacon')
67 else:
68 beacon_ips = '255.255.255.255'
69 return beacon_ips
71 def getPort():
72 return config.get('Server', 'Port')
74 def get169Blacklist(tsn): # tivo does not pad 16:9 video
75 return tsn and not isHDtivo(tsn) and not get169Letterbox(tsn)
76 # verified Blacklist Tivo's are ('130', '240', '540')
77 # It is assumed all remaining non-HD and non-Letterbox tivos are Blacklist
79 def get169Letterbox(tsn): # tivo pads 16:9 video for 4:3 display
80 return tsn and tsn[:3] in ['649']
82 def get169Setting(tsn):
83 if not tsn:
84 return True
86 tsnsect = '_tivo_' + tsn
87 if config.has_section(tsnsect):
88 if config.has_option(tsnsect, 'aspect169'):
89 try:
90 return config.getboolean(tsnsect, 'aspect169')
91 except ValueError:
92 pass
94 if get169Blacklist(tsn) or get169Letterbox(tsn):
95 return False
97 return True
99 def getShares(tsn=''):
100 shares = [(section, dict(config.items(section)))
101 for section in config.sections()
102 if not (section.startswith('_tivo_')
103 or section.startswith('logger_')
104 or section.startswith('handler_')
105 or section.startswith('formatter_')
106 or section in ('Server', 'loggers', 'handlers',
107 'formatters')
111 tsnsect = '_tivo_' + tsn
112 if config.has_section(tsnsect) and config.has_option(tsnsect, 'shares'):
113 # clean up leading and trailing spaces & make sure ref is valid
114 tsnshares = []
115 for x in config.get(tsnsect, 'shares').split(','):
116 y = x.strip()
117 if config.has_section(y):
118 tsnshares.append((y, dict(config.items(y))))
119 if tsnshares:
120 shares = tsnshares
122 return shares
124 def getDebug():
125 try:
126 return config.getboolean('Server', 'debug')
127 except NoOptionError, ValueError:
128 return False
130 def getOptres(tsn=None):
131 if tsn and config.has_section('_tivo_' + tsn):
132 try:
133 return config.getboolean('_tivo_' + tsn, 'optres')
134 except NoOptionError, ValueError:
135 pass
136 section_name = get_section(tsn)
137 if config.has_section(section_name):
138 try:
139 return config.getboolean(section_name, 'optres')
140 except NoOptionError, ValueError:
141 pass
142 try:
143 return config.getboolean('Server', 'optres')
144 except NoOptionError, ValueError:
145 return False
147 def getPixelAR(ref):
148 if config.has_option('Server', 'par'):
149 try:
150 return (True, config.getfloat('Server', 'par'))[ref]
151 except NoOptionError, ValueError:
152 pass
153 return (False, 1.0)[ref]
155 def get(section, key):
156 return config.get(section, key)
158 def getFFmpegWait():
159 if config.has_option('Server', 'ffmpeg_wait'):
160 return max(int(float(config.get('Server', 'ffmpeg_wait'))), 1)
161 else:
162 return 10
164 def getFFmpegTemplate(tsn):
165 tmpl = get_tsn('ffmpeg_tmpl', tsn, True)
166 if tmpl:
167 return tmpl
168 return '%(video_codec)s %(video_fps)s %(video_br)s %(max_video_br)s \
169 %(buff_size)s %(aspect_ratio)s %(audio_br)s \
170 %(audio_fr)s %(audio_ch)s %(audio_codec)s %(audio_lang)s \
171 %(ffmpeg_pram)s %(format)s'
173 def getFFmpegPrams(tsn):
174 return get_tsn('ffmpeg_pram', tsn, True)
176 def isHDtivo(tsn): # tsn's of High Definition Tivo's
177 return bool(tsn and tsn[:3] in ['648', '652', '658', '663'])
179 def getValidWidths():
180 return [1920, 1440, 1280, 720, 704, 544, 480, 352]
182 def getValidHeights():
183 return [1080, 720, 480] # Technically 240 is also supported
185 # Return the number in list that is nearest to x
186 # if two values are equidistant, return the larger
187 def nearest(x, list):
188 return reduce(lambda a, b: closest(x, a, b), list)
190 def closest(x, a, b):
191 da = abs(x - a)
192 db = abs(x - b)
193 if da < db or (da == db and a > b):
194 return a
195 else:
196 return b
198 def nearestTivoHeight(height):
199 return nearest(height, getValidHeights())
201 def nearestTivoWidth(width):
202 return nearest(width, getValidWidths())
204 def getTivoHeight(tsn):
205 height = get_tsn('height', tsn)
206 if height:
207 return nearestTivoHeight(int(height))
208 return [480, 720][isHDtivo(tsn)]
210 def getTivoWidth(tsn):
211 width = get_tsn('width', tsn)
212 if width:
213 return nearestTivoWidth(int(width))
214 return [544, 1280][isHDtivo(tsn)]
216 def _trunc64(i):
217 return max(int(strtod(i)) / 64000, 1) * 64
219 def getAudioBR(tsn=None):
220 rate = get_tsn('audio_br', tsn)
221 if not rate:
222 rate = '448k'
223 # convert to non-zero multiple of 64 to ensure ffmpeg compatibility
224 # compare audio_br to max_audio_br and return lowest
225 return str(min(_trunc64(rate), getMaxAudioBR(tsn))) + 'k'
227 def _k(i):
228 return str(int(strtod(i)) / 1000) + 'k'
230 def getVideoBR(tsn=None):
231 rate = get_tsn('video_br', tsn)
232 if rate:
233 return _k(rate)
234 return ['4096K', '16384K'][isHDtivo(tsn)]
236 def getMaxVideoBR(tsn=None):
237 rate = get_tsn('max_video_br', tsn)
238 if rate:
239 return _k(rate)
240 return '30000k'
242 def getVideoPCT(tsn=None):
243 pct = get_tsn('video_pct', tsn)
244 if pct:
245 return float(pct)
246 return 85
248 def getBuffSize(tsn=None):
249 size = get_tsn('bufsize', tsn)
250 if size:
251 return _k(size)
252 return ['1024k', '4096k'][isHDtivo(tsn)]
254 def getMaxAudioBR(tsn=None):
255 rate = get_tsn('max_audio_br', tsn)
256 # convert to non-zero multiple of 64 for ffmpeg compatibility
257 if rate:
258 return _trunc64(rate)
259 return 448
261 def get_section(tsn):
262 return ['_tivo_SD', '_tivo_HD'][isHDtivo(tsn)]
264 def get_tsn(name, tsn=None, raw=False):
265 if tsn and config.has_section('_tivo_' + tsn):
266 try:
267 return config.get('_tivo_' + tsn, name, raw)
268 except NoOptionError:
269 pass
270 section_name = get_section(tsn)
271 if config.has_section(section_name):
272 try:
273 return config.get(section_name, name, raw)
274 except NoOptionError:
275 pass
276 try:
277 return config.get('Server', name, raw)
278 except NoOptionError:
279 pass
280 return None
282 def getAudioCodec(tsn=None):
283 return get_tsn('audio_codec', tsn)
285 def getAudioCH(tsn=None):
286 return get_tsn('audio_ch', tsn)
288 def getAudioFR(tsn=None):
289 return get_tsn('audio_fr', tsn)
291 def getAudioLang(tsn=None):
292 return get_tsn('audio_lang', tsn)
294 def getCopyTS(tsn=None):
295 return get_tsn('copy_ts', tsn)
297 def getVideoFPS(tsn=None):
298 return get_tsn('video_fps', tsn)
300 # Parse a bitrate using the SI/IEEE suffix values as if by ffmpeg
301 # For example, 2K==2000, 2Ki==2048, 2MB==16000000, 2MiB==16777216
302 # Algorithm: http://svn.mplayerhq.hu/ffmpeg/trunk/libavcodec/eval.c
303 def strtod(value):
304 prefixes = {'y': -24, 'z': -21, 'a': -18, 'f': -15, 'p': -12,
305 'n': -9, 'u': -6, 'm': -3, 'c': -2, 'd': -1,
306 'h': 2, 'k': 3, 'K': 3, 'M': 6, 'G': 9,
307 'T': 12, 'P': 15, 'E': 18, 'Z': 21, 'Y': 24}
308 p = re.compile(r'^(\d+)(?:([yzafpnumcdhkKMGTPEZY])(i)?)?([Bb])?$')
309 m = p.match(value)
310 if not m:
311 raise SyntaxError('Invalid bit value syntax')
312 (coef, prefix, power, byte) = m.groups()
313 if prefix is None:
314 value = float(coef)
315 else:
316 exponent = float(prefixes[prefix])
317 if power == 'i':
318 # Use powers of 2
319 value = float(coef) * pow(2.0, exponent / 0.3)
320 else:
321 # Use powers of 10
322 value = float(coef) * pow(10.0, exponent)
323 if byte == 'B': # B == Byte, b == bit
324 value *= 8;
325 return value
327 def init_logging():
328 if (config.has_section('loggers') and
329 config.has_section('handlers') and
330 config.has_section('formatters')):
332 logging.config.fileConfig(config_files)
334 elif getDebug():
335 logging.basicConfig(level=logging.DEBUG)
336 else:
337 logging.basicConfig(level=logging.INFO)