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