10 from ConfigParser
import NoOptionError
13 def getboolean(self
, x
):
14 return self
.get(x
, 'False').lower() in ('1', 'yes', 'true', 'on')
26 p
= os
.path
.dirname(__file__
)
27 config_files
= ['/etc/pyTivo.conf', os
.path
.join(p
, 'pyTivo.conf')]
30 opts
, _
= getopt
.getopt(argv
, 'c:e:', ['config=', 'extraconf='])
31 except getopt
.GetoptError
, msg
:
34 for opt
, value
in opts
:
35 if opt
in ('-c', '--config'):
36 config_files
= [value
]
37 elif opt
in ('-e', '--extraconf'):
38 config_files
.append(value
)
49 config
= ConfigParser
.ConfigParser()
50 configs_found
= config
.read(config_files
)
52 print ('WARNING: pyTivo.conf does not exist.\n' +
53 'Assuming default values.')
54 configs_found
= config_files
[-1:]
56 for section
in config
.sections():
57 if section
.startswith('_tivo_'):
59 if tsn
.upper() not in ['SD', 'HD']:
60 if config
.has_option(section
, 'name'):
61 tivo_names
[tsn
] = config
.get(section
, 'name')
64 if config
.has_option(section
, 'address'):
65 tivos
[tsn
] = config
.get(section
, 'address')
67 for section
in ['Server', '_tivo_SD', '_tivo_HD']:
68 if not config
.has_section(section
):
69 config
.add_section(section
)
72 f
= open(configs_found
[-1], 'w')
76 def tivos_by_ip(tivoIP
):
77 for key
, value
in tivos
.items():
81 def get_server(name
, default
=None):
82 if config
.has_option('Server', name
):
83 return config
.get('Server', name
)
91 dest_ip
= tivos
.get(tsn
, '4.2.2.1')
92 s
= socket
.socket(socket
.AF_INET
, socket
.SOCK_DGRAM
)
93 s
.connect((dest_ip
, 123))
94 return s
.getsockname()[0]
97 opt
= get_server('zeroconf', 'auto').lower()
100 for section
in config
.sections():
101 if section
.startswith('_tivo_'):
102 if config
.has_option(section
, 'shares'):
103 logger
= logging
.getLogger('pyTivo.config')
104 logger
.info('Shares security in use -- zeroconf disabled')
106 elif opt
in ['false', 'no', 'off']:
112 if tsn
and tsn
.startswith('663'):
113 default
= 'symind.tivo.com:8181'
115 default
= 'mind.tivo.com:8181'
116 return get_server('tivo_mind', default
)
118 def getBeaconAddresses():
119 return get_server('beacon', '255.255.255.255')
122 return get_server('port', '9032')
124 def get169Blacklist(tsn
): # tivo does not pad 16:9 video
125 return tsn
and not isHDtivo(tsn
) and not get169Letterbox(tsn
)
126 # verified Blacklist Tivo's are ('130', '240', '540')
127 # It is assumed all remaining non-HD and non-Letterbox tivos are Blacklist
129 def get169Letterbox(tsn
): # tivo pads 16:9 video for 4:3 display
130 return tsn
and tsn
[:3] in ['649']
132 def get169Setting(tsn
):
136 tsnsect
= '_tivo_' + tsn
137 if config
.has_section(tsnsect
):
138 if config
.has_option(tsnsect
, 'aspect169'):
140 return config
.getboolean(tsnsect
, 'aspect169')
144 if get169Blacklist(tsn
) or get169Letterbox(tsn
):
149 def getAllowedClients():
150 return get_server('allowedips', '').split()
152 def getIsExternal(tsn
):
153 tsnsect
= '_tivo_' + tsn
154 if tsnsect
in config
.sections():
155 if config
.has_option(tsnsect
, 'external'):
157 return config
.getboolean(tsnsect
, 'external')
163 def isTsnInConfig(tsn
):
164 return ('_tivo_' + tsn
) in config
.sections()
166 def getShares(tsn
=''):
167 shares
= [(section
, Bdict(config
.items(section
)))
168 for section
in config
.sections()
169 if not (section
.startswith(('_tivo_', 'logger_', 'handler_',
171 or section
in ('Server', 'loggers', 'handlers',
176 tsnsect
= '_tivo_' + tsn
177 if config
.has_section(tsnsect
) and config
.has_option(tsnsect
, 'shares'):
178 # clean up leading and trailing spaces & make sure ref is valid
180 for x
in config
.get(tsnsect
, 'shares').split(','):
182 if config
.has_section(y
):
183 tsnshares
.append((y
, Bdict(config
.items(y
))))
188 if get_server('nosettings', 'false').lower() in ['false', 'no', 'off']:
189 shares
.append(('Settings', {'type': 'settings'}))
190 if get_server('tivo_mak') and get_server('togo_path'):
191 shares
.append(('ToGo', {'type': 'togo'}))
197 return config
.getboolean('Server', 'debug')
198 except NoOptionError
, ValueError:
201 def getOptres(tsn
=None):
203 return config
.getboolean('_tivo_' + tsn
, 'optres')
206 return config
.getboolean(get_section(tsn
), 'optres')
209 return config
.getboolean('Server', 'optres')
216 logger
= logging
.getLogger('pyTivo.config')
218 if fname
in bin_paths
:
219 return bin_paths
[fname
]
221 if config
.has_option('Server', fname
):
222 fpath
= config
.get('Server', fname
)
223 if os
.path
.exists(fpath
) and os
.path
.isfile(fpath
):
224 bin_paths
[fname
] = fpath
227 logger
.error('Bad %s path: %s' % (fname
, fpath
))
229 if sys
.platform
== 'win32':
234 for path
in ([os
.path
.join(os
.path
.dirname(__file__
), 'bin')] +
235 os
.getenv('PATH').split(os
.pathsep
)):
236 fpath
= os
.path
.join(path
, fname
+ fext
)
237 if os
.path
.exists(fpath
) and os
.path
.isfile(fpath
):
238 bin_paths
[fname
] = fpath
241 logger
.warn('%s not found' % fname
)
245 if config
.has_option('Server', 'ffmpeg_wait'):
246 return max(int(float(config
.get('Server', 'ffmpeg_wait'))), 1)
250 def getFFmpegTemplate(tsn
):
251 tmpl
= get_tsn('ffmpeg_tmpl', tsn
, True)
254 return '%(video_codec)s %(video_fps)s %(video_br)s %(max_video_br)s \
255 %(buff_size)s %(aspect_ratio)s %(audio_br)s \
256 %(audio_fr)s %(audio_ch)s %(audio_codec)s %(audio_lang)s \
257 %(ffmpeg_pram)s %(format)s'
259 def getFFmpegPrams(tsn
):
260 return get_tsn('ffmpeg_pram', tsn
, True)
262 def isHDtivo(tsn
): # tsn's of High Definition Tivo's
263 return bool(tsn
and tsn
[0] >= '6' and tsn
[:3] != '649')
267 return config
.getboolean('Server', 'ts')
268 except NoOptionError
, ValueError:
271 def is_ts_capable(tsn
): # tsn's of Tivos that support transport streams
272 return bool(tsn
and (tsn
[0] >= '7' or tsn
.startswith('663')))
274 def getValidWidths():
275 return [1920, 1440, 1280, 720, 704, 544, 480, 352]
277 def getValidHeights():
278 return [1080, 720, 480] # Technically 240 is also supported
280 # Return the number in list that is nearest to x
281 # if two values are equidistant, return the larger
282 def nearest(x
, list):
283 return reduce(lambda a
, b
: closest(x
, a
, b
), list)
285 def closest(x
, a
, b
):
288 if da
< db
or (da
== db
and a
> b
):
293 def nearestTivoHeight(height
):
294 return nearest(height
, getValidHeights())
296 def nearestTivoWidth(width
):
297 return nearest(width
, getValidWidths())
299 def getTivoHeight(tsn
):
300 height
= get_tsn('height', tsn
)
302 return nearestTivoHeight(int(height
))
303 return [480, 1080][isHDtivo(tsn
)]
305 def getTivoWidth(tsn
):
306 width
= get_tsn('width', tsn
)
308 return nearestTivoWidth(int(width
))
309 return [544, 1920][isHDtivo(tsn
)]
312 return max(int(strtod(i
)) / 64000, 1) * 64
314 def getAudioBR(tsn
=None):
315 rate
= get_tsn('audio_br', tsn
)
318 # convert to non-zero multiple of 64 to ensure ffmpeg compatibility
319 # compare audio_br to max_audio_br and return lowest
320 return str(min(_trunc64(rate
), getMaxAudioBR(tsn
))) + 'k'
323 return str(int(strtod(i
)) / 1000) + 'k'
325 def getVideoBR(tsn
=None):
326 rate
= get_tsn('video_br', tsn
)
329 return ['4096K', '16384K'][isHDtivo(tsn
)]
331 def getMaxVideoBR(tsn
=None):
332 rate
= get_tsn('max_video_br', tsn
)
337 def getBuffSize(tsn
=None):
338 size
= get_tsn('bufsize', tsn
)
341 return ['1024k', '4096k'][isHDtivo(tsn
)]
343 def getMaxAudioBR(tsn
=None):
344 rate
= get_tsn('max_audio_br', tsn
)
345 # convert to non-zero multiple of 64 for ffmpeg compatibility
347 return _trunc64(rate
)
350 def get_section(tsn
):
351 return ['_tivo_SD', '_tivo_HD'][isHDtivo(tsn
)]
353 def get_tsn(name
, tsn
=None, raw
=False):
355 return config
.get('_tivo_' + tsn
, name
, raw
)
358 return config
.get(get_section(tsn
), name
, raw
)
361 return config
.get('Server', name
, raw
)
365 # Parse a bitrate using the SI/IEEE suffix values as if by ffmpeg
366 # For example, 2K==2000, 2Ki==2048, 2MB==16000000, 2MiB==16777216
367 # Algorithm: http://svn.mplayerhq.hu/ffmpeg/trunk/libavcodec/eval.c
369 prefixes
= {'y': -24, 'z': -21, 'a': -18, 'f': -15, 'p': -12,
370 'n': -9, 'u': -6, 'm': -3, 'c': -2, 'd': -1,
371 'h': 2, 'k': 3, 'K': 3, 'M': 6, 'G': 9,
372 'T': 12, 'P': 15, 'E': 18, 'Z': 21, 'Y': 24}
373 p
= re
.compile(r
'^(\d+)(?:([yzafpnumcdhkKMGTPEZY])(i)?)?([Bb])?$')
376 raise SyntaxError('Invalid bit value syntax')
377 (coef
, prefix
, power
, byte
) = m
.groups()
381 exponent
= float(prefixes
[prefix
])
384 value
= float(coef
) * pow(2.0, exponent
/ 0.3)
387 value
= float(coef
) * pow(10.0, exponent
)
388 if byte
== 'B': # B == Byte, b == bit
393 if (config
.has_section('loggers') and
394 config
.has_section('handlers') and
395 config
.has_section('formatters')):
397 logging
.config
.fileConfig(config_files
)
400 logging
.basicConfig(level
=logging
.DEBUG
)
402 logging
.basicConfig(level
=logging
.INFO
)