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
)
60 config
= ConfigParser
.ConfigParser()
61 configs_found
= config
.read(config_files
)
63 print ('WARNING: pyTivo.conf does not exist.\n' +
64 'Assuming default values.')
65 configs_found
= config_files
[-1:]
67 for section
in config
.sections():
68 if section
.startswith('_tivo_'):
70 if tsn
.upper() not in ['SD', 'HD']:
71 if config
.has_option(section
, 'name'):
72 tivo_names
[tsn
] = config
.get(section
, 'name')
75 if config
.has_option(section
, 'address'):
76 tivos
[tsn
] = config
.get(section
, 'address')
78 for section
in ['Server', '_tivo_SD', '_tivo_HD']:
79 if not config
.has_section(section
):
80 config
.add_section(section
)
83 f
= open(configs_found
[-1], 'w')
87 def tivos_by_ip(tivoIP
):
88 for key
, value
in tivos
.items():
92 def get_server(name
, default
=None):
93 if config
.has_option('Server', name
):
94 return config
.get('Server', name
)
101 def get_ip(tsn
=None):
102 dest_ip
= tivos
.get(tsn
, '4.2.2.1')
103 s
= socket
.socket(socket
.AF_INET
, socket
.SOCK_DGRAM
)
104 s
.connect((dest_ip
, 123))
105 return s
.getsockname()[0]
108 opt
= get_server('zeroconf', 'auto').lower()
111 for section
in config
.sections():
112 if section
.startswith('_tivo_'):
113 if config
.has_option(section
, 'shares'):
114 logger
= logging
.getLogger('pyTivo.config')
115 logger
.info('Shares security in use -- zeroconf disabled')
117 elif opt
in ['false', 'no', 'off']:
123 if tsn
and tsn
.startswith('663'):
124 default
= 'symind.tivo.com:8181'
126 default
= 'mind.tivo.com:8181'
127 return get_server('tivo_mind', default
)
129 def getBeaconAddresses():
130 return get_server('beacon', '255.255.255.255')
133 return get_server('port', '9032')
135 def get169Blacklist(tsn
): # tivo does not pad 16:9 video
136 return tsn
and not isHDtivo(tsn
) and not get169Letterbox(tsn
)
137 # verified Blacklist Tivo's are ('130', '240', '540')
138 # It is assumed all remaining non-HD and non-Letterbox tivos are Blacklist
140 def get169Letterbox(tsn
): # tivo pads 16:9 video for 4:3 display
141 return tsn
and tsn
[:3] in ['649']
143 def get169Setting(tsn
):
147 tsnsect
= '_tivo_' + tsn
148 if config
.has_section(tsnsect
):
149 if config
.has_option(tsnsect
, 'aspect169'):
151 return config
.getboolean(tsnsect
, 'aspect169')
155 if get169Blacklist(tsn
) or get169Letterbox(tsn
):
160 def getAllowedClients():
161 return get_server('allowedips', '').split()
163 def getIsExternal(tsn
):
164 tsnsect
= '_tivo_' + tsn
165 if tsnsect
in config
.sections():
166 if config
.has_option(tsnsect
, 'external'):
168 return config
.getboolean(tsnsect
, 'external')
174 def isTsnInConfig(tsn
):
175 return ('_tivo_' + tsn
) in config
.sections()
177 def getShares(tsn
=''):
178 shares
= [(section
, Bdict(config
.items(section
)))
179 for section
in config
.sections()
180 if not (section
.startswith(('_tivo_', 'logger_', 'handler_',
182 or section
in ('Server', 'loggers', 'handlers',
187 tsnsect
= '_tivo_' + tsn
188 if config
.has_section(tsnsect
) and config
.has_option(tsnsect
, 'shares'):
189 # clean up leading and trailing spaces & make sure ref is valid
191 for x
in config
.get(tsnsect
, 'shares').split(','):
193 if config
.has_section(y
):
194 tsnshares
.append((y
, Bdict(config
.items(y
))))
199 if get_server('nosettings', 'false').lower() in ['false', 'no', 'off']:
200 shares
.append(('Settings', {'type': 'settings'}))
201 if get_server('tivo_mak') and get_server('togo_path'):
202 shares
.append(('ToGo', {'type': 'togo'}))
208 return config
.getboolean('Server', 'debug')
209 except NoOptionError
, ValueError:
212 def getOptres(tsn
=None):
214 return config
.getboolean('_tivo_' + tsn
, 'optres')
217 return config
.getboolean(get_section(tsn
), 'optres')
220 return config
.getboolean('Server', 'optres')
227 logger
= logging
.getLogger('pyTivo.config')
229 if fname
in bin_paths
:
230 return bin_paths
[fname
]
232 if config
.has_option('Server', fname
):
233 fpath
= config
.get('Server', fname
)
234 if os
.path
.exists(fpath
) and os
.path
.isfile(fpath
):
235 bin_paths
[fname
] = fpath
238 logger
.error('Bad %s path: %s' % (fname
, fpath
))
240 if sys
.platform
== 'win32':
245 for path
in ([os
.path
.join(os
.path
.dirname(__file__
), 'bin')] +
246 os
.getenv('PATH').split(os
.pathsep
)):
247 fpath
= os
.path
.join(path
, fname
+ fext
)
248 if os
.path
.exists(fpath
) and os
.path
.isfile(fpath
):
249 bin_paths
[fname
] = fpath
252 logger
.warn('%s not found' % fname
)
256 if config
.has_option('Server', 'ffmpeg_wait'):
257 return max(int(float(config
.get('Server', 'ffmpeg_wait'))), 1)
261 def getFFmpegTemplate(tsn
):
262 tmpl
= get_tsn('ffmpeg_tmpl', tsn
, True)
265 return '%(video_codec)s %(video_fps)s %(video_br)s %(max_video_br)s \
266 %(buff_size)s %(aspect_ratio)s %(audio_br)s \
267 %(audio_fr)s %(audio_ch)s %(audio_codec)s %(audio_lang)s \
268 %(ffmpeg_pram)s %(format)s'
270 def getFFmpegPrams(tsn
):
271 return get_tsn('ffmpeg_pram', tsn
, True)
273 def isHDtivo(tsn
): # tsn's of High Definition Tivo's
274 return bool(tsn
and tsn
[0] >= '6' and tsn
[:3] != '649')
278 return config
.getboolean('Server', 'ts')
279 except NoOptionError
, ValueError:
282 def is_ts_capable(tsn
): # tsn's of Tivos that support transport streams
283 return bool(tsn
and (tsn
[0] >= '7' or tsn
.startswith('663')))
285 def getValidWidths():
286 return [1920, 1440, 1280, 720, 704, 544, 480, 352]
288 def getValidHeights():
289 return [1080, 720, 480] # Technically 240 is also supported
291 # Return the number in list that is nearest to x
292 # if two values are equidistant, return the larger
293 def nearest(x
, list):
294 return reduce(lambda a
, b
: closest(x
, a
, b
), list)
296 def closest(x
, a
, b
):
299 if da
< db
or (da
== db
and a
> b
):
304 def nearestTivoHeight(height
):
305 return nearest(height
, getValidHeights())
307 def nearestTivoWidth(width
):
308 return nearest(width
, getValidWidths())
310 def getTivoHeight(tsn
):
311 height
= get_tsn('height', tsn
)
313 return nearestTivoHeight(int(height
))
314 return [480, 1080][isHDtivo(tsn
)]
316 def getTivoWidth(tsn
):
317 width
= get_tsn('width', tsn
)
319 return nearestTivoWidth(int(width
))
320 return [544, 1920][isHDtivo(tsn
)]
323 return max(int(strtod(i
)) / 64000, 1) * 64
325 def getAudioBR(tsn
=None):
326 rate
= get_tsn('audio_br', tsn
)
329 # convert to non-zero multiple of 64 to ensure ffmpeg compatibility
330 # compare audio_br to max_audio_br and return lowest
331 return str(min(_trunc64(rate
), getMaxAudioBR(tsn
))) + 'k'
334 return str(int(strtod(i
)) / 1000) + 'k'
336 def getVideoBR(tsn
=None):
337 rate
= get_tsn('video_br', tsn
)
340 return ['4096K', '16384K'][isHDtivo(tsn
)]
342 def getMaxVideoBR(tsn
=None):
343 rate
= get_tsn('max_video_br', tsn
)
348 def getBuffSize(tsn
=None):
349 size
= get_tsn('bufsize', tsn
)
352 return ['1024k', '4096k'][isHDtivo(tsn
)]
354 def getMaxAudioBR(tsn
=None):
355 rate
= get_tsn('max_audio_br', tsn
)
356 # convert to non-zero multiple of 64 for ffmpeg compatibility
358 return _trunc64(rate
)
361 def get_section(tsn
):
362 return ['_tivo_SD', '_tivo_HD'][isHDtivo(tsn
)]
364 def get_tsn(name
, tsn
=None, raw
=False):
366 return config
.get('_tivo_' + tsn
, name
, raw
)
369 return config
.get(get_section(tsn
), name
, raw
)
372 return config
.get('Server', name
, raw
)
376 # Parse a bitrate using the SI/IEEE suffix values as if by ffmpeg
377 # For example, 2K==2000, 2Ki==2048, 2MB==16000000, 2MiB==16777216
378 # Algorithm: http://svn.mplayerhq.hu/ffmpeg/trunk/libavcodec/eval.c
380 prefixes
= {'y': -24, 'z': -21, 'a': -18, 'f': -15, 'p': -12,
381 'n': -9, 'u': -6, 'm': -3, 'c': -2, 'd': -1,
382 'h': 2, 'k': 3, 'K': 3, 'M': 6, 'G': 9,
383 'T': 12, 'P': 15, 'E': 18, 'Z': 21, 'Y': 24}
384 p
= re
.compile(r
'^(\d+)(?:([yzafpnumcdhkKMGTPEZY])(i)?)?([Bb])?$')
387 raise SyntaxError('Invalid bit value syntax')
388 (coef
, prefix
, power
, byte
) = m
.groups()
392 exponent
= float(prefixes
[prefix
])
395 value
= float(coef
) * pow(2.0, exponent
/ 0.3)
398 value
= float(coef
) * pow(10.0, exponent
)
399 if byte
== 'B': # B == Byte, b == bit
404 if (config
.has_section('loggers') and
405 config
.has_section('handlers') and
406 config
.has_section('formatters')):
408 logging
.config
.fileConfig(config_files
)
411 logging
.basicConfig(level
=logging
.DEBUG
)
413 logging
.basicConfig(level
=logging
.INFO
)