10 from ConfigParser
import NoOptionError
13 def getboolean(self
, x
):
14 return self
.get(x
, 'False').lower() in ('1', 'yes', 'true', 'on')
26 config_win_default
= ''
27 if sys
.platform
== "win32":
30 explorerFolders
= _winreg
.OpenKey(
31 _winreg
.HKEY_LOCAL_MACHINE
, 'Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders')
32 winCommonAppDataVal
, winCommonAppDataType
= _winreg
.QueryValueEx(explorerFolders
, 'Common AppData')
33 config_win_default
= os
.path
.join(winCommonAppDataVal
, 'pyTivo', 'pyTivo.conf')
35 print "Can't access Windows Registry to find common Application Data path."
37 p
= os
.path
.dirname(__file__
)
38 config_files
= ['/etc/pyTivo.conf', config_win_default
, os
.path
.join(p
, 'pyTivo.conf')]
41 opts
, _
= getopt
.getopt(argv
, 'c:e:', ['config=', 'extraconf='])
42 except getopt
.GetoptError
, msg
:
45 for opt
, value
in opts
:
46 if opt
in ('-c', '--config'):
47 config_files
= [value
]
48 elif opt
in ('-e', '--extraconf'):
49 config_files
.append(value
)
61 config
= ConfigParser
.ConfigParser()
62 configs_found
= config
.read(config_files
)
64 print ('WARNING: pyTivo.conf does not exist.\n' +
65 'Assuming default values.')
66 configs_found
= config_files
[-1:]
68 for section
in config
.sections():
69 if section
.startswith('_tivo_'):
71 if tsn
.upper() not in ['SD', 'HD']:
73 tivos
[tsn
] = Bdict(config
.items(section
))
75 for section
in ['Server', '_tivo_SD', '_tivo_HD']:
76 if not config
.has_section(section
):
77 config
.add_section(section
)
80 f
= open(configs_found
[-1], 'w')
84 def tivos_by_ip(tivoIP
):
85 for key
, value
in tivos
.items():
86 if value
['address'] == tivoIP
:
89 def get_server(name
, default
=None):
90 if config
.has_option('Server', name
):
91 return config
.get('Server', name
)
101 dest_ip
= tivos
[tsn
]['address']
104 s
= socket
.socket(socket
.AF_INET
, socket
.SOCK_DGRAM
)
105 s
.connect((dest_ip
, 123))
106 return s
.getsockname()[0]
109 opt
= get_server('zeroconf', 'auto').lower()
112 for section
in config
.sections():
113 if section
.startswith('_tivo_'):
114 if config
.has_option(section
, 'shares'):
115 logger
= logging
.getLogger('pyTivo.config')
116 logger
.info('Shares security in use -- zeroconf disabled')
118 elif opt
in ['false', 'no', 'off']:
124 if tsn
and tsn
.startswith('663'):
125 default
= 'symind.tivo.com:8181'
127 default
= 'mind.tivo.com:8181'
128 return get_server('tivo_mind', default
)
130 def getBeaconAddresses():
131 return get_server('beacon', '255.255.255.255')
134 return get_server('port', '9032')
136 def get169Blacklist(tsn
): # tivo does not pad 16:9 video
137 return tsn
and not isHDtivo(tsn
) and not get169Letterbox(tsn
)
138 # verified Blacklist Tivo's are ('130', '240', '540')
139 # It is assumed all remaining non-HD and non-Letterbox tivos are Blacklist
141 def get169Letterbox(tsn
): # tivo pads 16:9 video for 4:3 display
142 return tsn
and tsn
[:3] in ['649']
144 def get169Setting(tsn
):
148 tsnsect
= '_tivo_' + tsn
149 if config
.has_section(tsnsect
):
150 if config
.has_option(tsnsect
, 'aspect169'):
152 return config
.getboolean(tsnsect
, 'aspect169')
156 if get169Blacklist(tsn
) or get169Letterbox(tsn
):
161 def getAllowedClients():
162 return get_server('allowedips', '').split()
164 def getIsExternal(tsn
):
165 tsnsect
= '_tivo_' + tsn
166 if tsnsect
in config
.sections():
167 if config
.has_option(tsnsect
, 'external'):
169 return config
.getboolean(tsnsect
, 'external')
175 def isTsnInConfig(tsn
):
176 return ('_tivo_' + tsn
) in config
.sections()
178 def getShares(tsn
=''):
179 shares
= [(section
, Bdict(config
.items(section
)))
180 for section
in config
.sections()
181 if not (section
.startswith(('_tivo_', 'logger_', 'handler_',
183 or section
in ('Server', 'loggers', 'handlers',
188 tsnsect
= '_tivo_' + tsn
189 if config
.has_section(tsnsect
) and config
.has_option(tsnsect
, 'shares'):
190 # clean up leading and trailing spaces & make sure ref is valid
192 for x
in config
.get(tsnsect
, 'shares').split(','):
194 if config
.has_section(y
):
195 tsnshares
.append((y
, Bdict(config
.items(y
))))
200 if get_server('nosettings', 'false').lower() in ['false', 'no', 'off']:
201 shares
.append(('Settings', {'type': 'settings'}))
202 if get_server('tivo_mak') and get_server('togo_path'):
203 shares
.append(('ToGo', {'type': 'togo'}))
209 return config
.getboolean('Server', 'debug')
213 def getOptres(tsn
=None):
215 return config
.getboolean('_tivo_' + tsn
, 'optres')
218 return config
.getboolean(get_section(tsn
), 'optres')
221 return config
.getboolean('Server', 'optres')
228 logger
= logging
.getLogger('pyTivo.config')
230 if fname
in bin_paths
:
231 return bin_paths
[fname
]
233 if config
.has_option('Server', fname
):
234 fpath
= config
.get('Server', fname
)
235 if os
.path
.exists(fpath
) and os
.path
.isfile(fpath
):
236 bin_paths
[fname
] = fpath
239 logger
.error('Bad %s path: %s' % (fname
, fpath
))
241 if sys
.platform
== 'win32':
246 for path
in ([os
.path
.join(os
.path
.dirname(__file__
), 'bin')] +
247 os
.getenv('PATH').split(os
.pathsep
)):
248 fpath
= os
.path
.join(path
, fname
+ fext
)
249 if os
.path
.exists(fpath
) and os
.path
.isfile(fpath
):
250 bin_paths
[fname
] = fpath
253 logger
.warn('%s not found' % fname
)
257 if config
.has_option('Server', 'ffmpeg_wait'):
258 return max(int(float(config
.get('Server', 'ffmpeg_wait'))), 1)
262 def getFFmpegTemplate(tsn
):
263 tmpl
= get_tsn('ffmpeg_tmpl', tsn
, True)
266 return '%(video_codec)s %(video_fps)s %(video_br)s %(max_video_br)s \
267 %(buff_size)s %(aspect_ratio)s %(audio_br)s \
268 %(audio_fr)s %(audio_ch)s %(audio_codec)s %(audio_lang)s \
269 %(ffmpeg_pram)s %(format)s'
271 def getFFmpegPrams(tsn
):
272 return get_tsn('ffmpeg_pram', tsn
, True)
274 def isHDtivo(tsn
): # tsn's of High Definition Tivo's
275 return bool(tsn
and tsn
[0] >= '6' and tsn
[:3] != '649')
279 return config
.getboolean('Server', 'ts')
283 def is_ts_capable(tsn
): # tsn's of Tivos that support transport streams
284 return bool(tsn
and (tsn
[0] >= '7' or tsn
.startswith('663')))
286 def getValidWidths():
287 return [1920, 1440, 1280, 720, 704, 544, 480, 352]
289 def getValidHeights():
290 return [1080, 720, 480] # Technically 240 is also supported
292 # Return the number in list that is nearest to x
293 # if two values are equidistant, return the larger
294 def nearest(x
, list):
295 return reduce(lambda a
, b
: closest(x
, a
, b
), list)
297 def closest(x
, a
, b
):
300 if da
< db
or (da
== db
and a
> b
):
305 def nearestTivoHeight(height
):
306 return nearest(height
, getValidHeights())
308 def nearestTivoWidth(width
):
309 return nearest(width
, getValidWidths())
311 def getTivoHeight(tsn
):
312 height
= get_tsn('height', tsn
)
314 return nearestTivoHeight(int(height
))
315 return [480, 1080][isHDtivo(tsn
)]
317 def getTivoWidth(tsn
):
318 width
= get_tsn('width', tsn
)
320 return nearestTivoWidth(int(width
))
321 return [544, 1920][isHDtivo(tsn
)]
324 return max(int(strtod(i
)) / 64000, 1) * 64
326 def getAudioBR(tsn
=None):
327 rate
= get_tsn('audio_br', tsn
)
330 # convert to non-zero multiple of 64 to ensure ffmpeg compatibility
331 # compare audio_br to max_audio_br and return lowest
332 return str(min(_trunc64(rate
), getMaxAudioBR(tsn
))) + 'k'
335 return str(int(strtod(i
)) / 1000) + 'k'
337 def getVideoBR(tsn
=None):
338 rate
= get_tsn('video_br', tsn
)
341 return ['4096K', '16384K'][isHDtivo(tsn
)]
343 def getMaxVideoBR(tsn
=None):
344 rate
= get_tsn('max_video_br', tsn
)
349 def getBuffSize(tsn
=None):
350 size
= get_tsn('bufsize', tsn
)
353 return ['1024k', '4096k'][isHDtivo(tsn
)]
355 def getMaxAudioBR(tsn
=None):
356 rate
= get_tsn('max_audio_br', tsn
)
357 # convert to non-zero multiple of 64 for ffmpeg compatibility
359 return _trunc64(rate
)
362 def get_section(tsn
):
363 return ['_tivo_SD', '_tivo_HD'][isHDtivo(tsn
)]
365 def get_tsn(name
, tsn
=None, raw
=False):
367 return config
.get('_tivo_' + tsn
, name
, raw
)
370 return config
.get(get_section(tsn
), name
, raw
)
373 return config
.get('Server', name
, raw
)
377 # Parse a bitrate using the SI/IEEE suffix values as if by ffmpeg
378 # For example, 2K==2000, 2Ki==2048, 2MB==16000000, 2MiB==16777216
379 # Algorithm: http://svn.mplayerhq.hu/ffmpeg/trunk/libavcodec/eval.c
381 prefixes
= {'y': -24, 'z': -21, 'a': -18, 'f': -15, 'p': -12,
382 'n': -9, 'u': -6, 'm': -3, 'c': -2, 'd': -1,
383 'h': 2, 'k': 3, 'K': 3, 'M': 6, 'G': 9,
384 'T': 12, 'P': 15, 'E': 18, 'Z': 21, 'Y': 24}
385 p
= re
.compile(r
'^(\d+)(?:([yzafpnumcdhkKMGTPEZY])(i)?)?([Bb])?$')
388 raise SyntaxError('Invalid bit value syntax')
389 (coef
, prefix
, power
, byte
) = m
.groups()
393 exponent
= float(prefixes
[prefix
])
396 value
= float(coef
) * pow(2.0, exponent
/ 0.3)
399 value
= float(coef
) * pow(10.0, exponent
)
400 if byte
== 'B': # B == Byte, b == bit
405 if (config
.has_section('loggers') and
406 config
.has_section('handlers') and
407 config
.has_section('formatters')):
409 logging
.config
.fileConfig(config_files
)
412 logging
.basicConfig(level
=logging
.DEBUG
)
414 logging
.basicConfig(level
=logging
.INFO
)