10 from ConfigParser
import NoOptionError
22 p
= os
.path
.dirname(__file__
)
23 config_files
= ['/etc/pyTivo.conf', os
.path
.join(p
, 'pyTivo.conf')]
26 opts
, _
= getopt
.getopt(argv
, 'c:e:', ['config=', 'extraconf='])
27 except getopt
.GetoptError
, msg
:
30 for opt
, value
in opts
:
31 if opt
in ('-c', '--config'):
32 config_files
= [value
]
33 elif opt
in ('-e', '--extraconf'):
34 config_files
.append(value
)
45 config
= ConfigParser
.ConfigParser()
46 configs_found
= config
.read(config_files
)
48 print ('WARNING: pyTivo.conf does not exist.\n' +
49 'Assuming default values.')
50 configs_found
= config_files
[-1:]
52 for section
in config
.sections():
53 if section
.startswith('_tivo_'):
55 if tsn
.upper() not in ['SD', 'HD']:
56 if config
.has_option(section
, 'name'):
57 tivo_names
[tsn
] = config
.get(section
, 'name')
60 if config
.has_option(section
, 'address'):
61 tivos
[tsn
] = config
.get(section
, 'address')
63 for section
in ['Server', '_tivo_SD', '_tivo_HD']:
64 if not config
.has_section(section
):
65 config
.add_section(section
)
68 f
= open(configs_found
[-1], 'w')
72 def tivos_by_ip(tivoIP
):
73 for key
, value
in tivos
.items():
77 def get_server(name
, default
=None):
78 if config
.has_option('Server', name
):
79 return config
.get('Server', name
)
87 dest_ip
= tivos
.get(tsn
, '4.2.2.1')
88 s
= socket
.socket(socket
.AF_INET
, socket
.SOCK_DGRAM
)
89 s
.connect((dest_ip
, 123))
90 return s
.getsockname()[0]
93 opt
= get_server('zeroconf', 'auto').lower()
96 for section
in config
.sections():
97 if section
.startswith('_tivo_'):
98 if config
.has_option(section
, 'shares'):
99 logger
= logging
.getLogger('pyTivo.config')
100 logger
.info('Shares security in use -- zeroconf disabled')
102 elif opt
in ['false', 'no', 'off']:
108 if tsn
and tsn
.startswith('663'):
109 default
= 'symind.tivo.com:8181'
111 default
= 'mind.tivo.com:8181'
112 return get_server('tivo_mind', default
)
114 def getBeaconAddresses():
115 return get_server('beacon', '255.255.255.255')
118 return get_server('port', '9032')
120 def get169Blacklist(tsn
): # tivo does not pad 16:9 video
121 return tsn
and not isHDtivo(tsn
) and not get169Letterbox(tsn
)
122 # verified Blacklist Tivo's are ('130', '240', '540')
123 # It is assumed all remaining non-HD and non-Letterbox tivos are Blacklist
125 def get169Letterbox(tsn
): # tivo pads 16:9 video for 4:3 display
126 return tsn
and tsn
[:3] in ['649']
128 def get169Setting(tsn
):
132 tsnsect
= '_tivo_' + tsn
133 if config
.has_section(tsnsect
):
134 if config
.has_option(tsnsect
, 'aspect169'):
136 return config
.getboolean(tsnsect
, 'aspect169')
140 if get169Blacklist(tsn
) or get169Letterbox(tsn
):
145 def getAllowedClients():
146 return get_server('allowedips', '').split()
148 def getIsExternal(tsn
):
149 tsnsect
= '_tivo_' + tsn
150 if tsnsect
in config
.sections():
151 if config
.has_option(tsnsect
, 'external'):
153 return config
.getboolean(tsnsect
, 'external')
159 def isTsnInConfig(tsn
):
160 return ('_tivo_' + tsn
) in config
.sections()
162 def getShares(tsn
=''):
163 shares
= [(section
, dict(config
.items(section
)))
164 for section
in config
.sections()
165 if not (section
.startswith(('_tivo_', 'logger_', 'handler_',
167 or section
in ('Server', 'loggers', 'handlers',
172 tsnsect
= '_tivo_' + tsn
173 if config
.has_section(tsnsect
) and config
.has_option(tsnsect
, 'shares'):
174 # clean up leading and trailing spaces & make sure ref is valid
176 for x
in config
.get(tsnsect
, 'shares').split(','):
178 if config
.has_section(y
):
179 tsnshares
.append((y
, dict(config
.items(y
))))
184 if get_server('nosettings', 'false').lower() in ['false', 'no', 'off']:
185 shares
.append(('Settings', {'type': 'settings'}))
186 if get_server('tivo_mak') and get_server('togo_path'):
187 shares
.append(('ToGo', {'type': 'togo'}))
193 return config
.getboolean('Server', 'debug')
194 except NoOptionError
, ValueError:
197 def getOptres(tsn
=None):
199 return config
.getboolean('_tivo_' + tsn
, 'optres')
202 return config
.getboolean(get_section(tsn
), 'optres')
205 return config
.getboolean('Server', 'optres')
212 logger
= logging
.getLogger('pyTivo.config')
214 if fname
in bin_paths
:
215 return bin_paths
[fname
]
217 if config
.has_option('Server', fname
):
218 fpath
= config
.get('Server', fname
)
219 if os
.path
.exists(fpath
) and os
.path
.isfile(fpath
):
220 bin_paths
[fname
] = fpath
223 logger
.error('Bad %s path: %s' % (fname
, fpath
))
225 if sys
.platform
== 'win32':
230 for path
in ([os
.path
.join(os
.path
.dirname(__file__
), 'bin')] +
231 os
.getenv('PATH').split(os
.pathsep
)):
232 fpath
= os
.path
.join(path
, fname
+ fext
)
233 if os
.path
.exists(fpath
) and os
.path
.isfile(fpath
):
234 bin_paths
[fname
] = fpath
237 logger
.warn('%s not found' % fname
)
241 if config
.has_option('Server', 'ffmpeg_wait'):
242 return max(int(float(config
.get('Server', 'ffmpeg_wait'))), 1)
246 def getFFmpegTemplate(tsn
):
247 tmpl
= get_tsn('ffmpeg_tmpl', tsn
, True)
250 return '%(video_codec)s %(video_fps)s %(video_br)s %(max_video_br)s \
251 %(buff_size)s %(aspect_ratio)s %(audio_br)s \
252 %(audio_fr)s %(audio_ch)s %(audio_codec)s %(audio_lang)s \
253 %(ffmpeg_pram)s %(format)s'
255 def getFFmpegPrams(tsn
):
256 return get_tsn('ffmpeg_pram', tsn
, True)
258 def isHDtivo(tsn
): # tsn's of High Definition Tivo's
259 return bool(tsn
and tsn
[0] >= '6' and tsn
[:3] != '649')
263 return config
.getboolean('Server', 'ts')
264 except NoOptionError
, ValueError:
267 def is_ts_capable(tsn
): # tsn's of Tivos that support transport streams
268 return bool(tsn
and (tsn
[0] >= '7' or tsn
.startswith('663')))
270 def getValidWidths():
271 return [1920, 1440, 1280, 720, 704, 544, 480, 352]
273 def getValidHeights():
274 return [1080, 720, 480] # Technically 240 is also supported
276 # Return the number in list that is nearest to x
277 # if two values are equidistant, return the larger
278 def nearest(x
, list):
279 return reduce(lambda a
, b
: closest(x
, a
, b
), list)
281 def closest(x
, a
, b
):
284 if da
< db
or (da
== db
and a
> b
):
289 def nearestTivoHeight(height
):
290 return nearest(height
, getValidHeights())
292 def nearestTivoWidth(width
):
293 return nearest(width
, getValidWidths())
295 def getTivoHeight(tsn
):
296 height
= get_tsn('height', tsn
)
298 return nearestTivoHeight(int(height
))
299 return [480, 1080][isHDtivo(tsn
)]
301 def getTivoWidth(tsn
):
302 width
= get_tsn('width', tsn
)
304 return nearestTivoWidth(int(width
))
305 return [544, 1920][isHDtivo(tsn
)]
308 return max(int(strtod(i
)) / 64000, 1) * 64
310 def getAudioBR(tsn
=None):
311 rate
= get_tsn('audio_br', tsn
)
314 # convert to non-zero multiple of 64 to ensure ffmpeg compatibility
315 # compare audio_br to max_audio_br and return lowest
316 return str(min(_trunc64(rate
), getMaxAudioBR(tsn
))) + 'k'
319 return str(int(strtod(i
)) / 1000) + 'k'
321 def getVideoBR(tsn
=None):
322 rate
= get_tsn('video_br', tsn
)
325 return ['4096K', '16384K'][isHDtivo(tsn
)]
327 def getMaxVideoBR(tsn
=None):
328 rate
= get_tsn('max_video_br', tsn
)
333 def getBuffSize(tsn
=None):
334 size
= get_tsn('bufsize', tsn
)
337 return ['1024k', '4096k'][isHDtivo(tsn
)]
339 def getMaxAudioBR(tsn
=None):
340 rate
= get_tsn('max_audio_br', tsn
)
341 # convert to non-zero multiple of 64 for ffmpeg compatibility
343 return _trunc64(rate
)
346 def get_section(tsn
):
347 return ['_tivo_SD', '_tivo_HD'][isHDtivo(tsn
)]
349 def get_tsn(name
, tsn
=None, raw
=False):
351 return config
.get('_tivo_' + tsn
, name
, raw
)
354 return config
.get(get_section(tsn
), name
, raw
)
357 return config
.get('Server', name
, raw
)
361 # Parse a bitrate using the SI/IEEE suffix values as if by ffmpeg
362 # For example, 2K==2000, 2Ki==2048, 2MB==16000000, 2MiB==16777216
363 # Algorithm: http://svn.mplayerhq.hu/ffmpeg/trunk/libavcodec/eval.c
365 prefixes
= {'y': -24, 'z': -21, 'a': -18, 'f': -15, 'p': -12,
366 'n': -9, 'u': -6, 'm': -3, 'c': -2, 'd': -1,
367 'h': 2, 'k': 3, 'K': 3, 'M': 6, 'G': 9,
368 'T': 12, 'P': 15, 'E': 18, 'Z': 21, 'Y': 24}
369 p
= re
.compile(r
'^(\d+)(?:([yzafpnumcdhkKMGTPEZY])(i)?)?([Bb])?$')
372 raise SyntaxError('Invalid bit value syntax')
373 (coef
, prefix
, power
, byte
) = m
.groups()
377 exponent
= float(prefixes
[prefix
])
380 value
= float(coef
) * pow(2.0, exponent
/ 0.3)
383 value
= float(coef
) * pow(10.0, exponent
)
384 if byte
== 'B': # B == Byte, b == bit
389 if (config
.has_section('loggers') and
390 config
.has_section('handlers') and
391 config
.has_section('formatters')):
393 logging
.config
.fileConfig(config_files
)
396 logging
.basicConfig(level
=logging
.DEBUG
)
398 logging
.basicConfig(level
=logging
.INFO
)