11 from ConfigParser
import NoOptionError
21 guid
= ''.join([random
.choice(string
.ascii_letters
) for i
in range(10)])
23 config_win_default
= ''
24 if sys
.platform
== "win32":
27 explorerFolders
= _winreg
.OpenKey(
28 _winreg
.HKEY_LOCAL_MACHINE
, 'Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders')
29 winCommonAppDataVal
, winCommonAppDataType
= _winreg
.QueryValueEx(explorerFolders
, 'Common AppData')
30 config_win_default
= os
.path
.join(winCommonAppDataVal
, 'pyTivo', 'pyTivo.conf')
32 print "Can't access Windows Registry to find common Application Data path."
34 p
= os
.path
.dirname(__file__
)
35 config_files
= ['/etc/pyTivo.conf', config_win_default
, os
.path
.join(p
, 'pyTivo.conf')]
38 opts
, _
= getopt
.getopt(argv
, 'c:e:', ['config=', 'extraconf='])
39 except getopt
.GetoptError
, msg
:
42 for opt
, value
in opts
:
43 if opt
in ('-c', '--config'):
44 config_files
= [value
]
45 elif opt
in ('-e', '--extraconf'):
46 config_files
.append(value
)
57 config
= ConfigParser
.ConfigParser()
58 configs_found
= config
.read(config_files
)
60 print ('WARNING: pyTivo.conf does not exist.\n' +
61 'Assuming default values.')
62 configs_found
= config_files
[-1:]
64 for section
in config
.sections():
65 if section
.startswith('_tivo_'):
67 if tsn
.upper() not in ['SD', 'HD']:
68 if config
.has_option(section
, 'name'):
69 tivo_names
[tsn
] = config
.get(section
, 'name')
72 if config
.has_option(section
, 'address'):
73 tivos
[tsn
] = config
.get(section
, 'address')
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():
89 def get_server(name
, default
=None):
90 if config
.has_option('Server', name
):
91 return config
.get('Server', name
)
99 dest_ip
= tivos
.get(tsn
, '4.2.2.1')
100 s
= socket
.socket(socket
.AF_INET
, socket
.SOCK_DGRAM
)
101 s
.connect((dest_ip
, 123))
102 return s
.getsockname()[0]
105 opt
= get_server('zeroconf', 'auto').lower()
108 for section
in config
.sections():
109 if section
.startswith('_tivo_'):
110 if config
.has_option(section
, 'shares'):
111 logger
= logging
.getLogger('pyTivo.config')
112 logger
.info('Shares security in use -- zeroconf disabled')
114 elif opt
in ['false', 'no', 'off']:
120 if tsn
and tsn
.startswith('663'):
121 default
= 'symind.tivo.com:8181'
123 default
= 'mind.tivo.com:8181'
124 return get_server('tivo_mind', default
)
126 def getBeaconAddresses():
127 return get_server('beacon', '255.255.255.255')
130 return get_server('port', '9032')
132 def get169Blacklist(tsn
): # tivo does not pad 16:9 video
133 return tsn
and not isHDtivo(tsn
) and not get169Letterbox(tsn
)
134 # verified Blacklist Tivo's are ('130', '240', '540')
135 # It is assumed all remaining non-HD and non-Letterbox tivos are Blacklist
137 def get169Letterbox(tsn
): # tivo pads 16:9 video for 4:3 display
138 return tsn
and tsn
[:3] in ['649']
140 def get169Setting(tsn
):
144 tsnsect
= '_tivo_' + tsn
145 if config
.has_section(tsnsect
):
146 if config
.has_option(tsnsect
, 'aspect169'):
148 return config
.getboolean(tsnsect
, 'aspect169')
152 if get169Blacklist(tsn
) or get169Letterbox(tsn
):
157 def getAllowedClients():
158 return get_server('allowedips', '').split()
160 def getIsExternal(tsn
):
161 tsnsect
= '_tivo_' + tsn
162 if tsnsect
in config
.sections():
163 if config
.has_option(tsnsect
, 'external'):
165 return config
.getboolean(tsnsect
, 'external')
171 def isTsnInConfig(tsn
):
172 return ('_tivo_' + tsn
) in config
.sections()
174 def getShares(tsn
=''):
175 shares
= [(section
, dict(config
.items(section
)))
176 for section
in config
.sections()
177 if not (section
.startswith('_tivo_')
178 or section
.startswith('logger_')
179 or section
.startswith('handler_')
180 or section
.startswith('formatter_')
181 or section
in ('Server', 'loggers', 'handlers',
186 tsnsect
= '_tivo_' + tsn
187 if config
.has_section(tsnsect
) and config
.has_option(tsnsect
, 'shares'):
188 # clean up leading and trailing spaces & make sure ref is valid
190 for x
in config
.get(tsnsect
, 'shares').split(','):
192 if config
.has_section(y
):
193 tsnshares
.append((y
, dict(config
.items(y
))))
198 if get_server('nosettings', 'false').lower() in ['false', 'no', 'off']:
199 shares
.append(('Settings', {'type': 'settings'}))
200 if get_server('tivo_mak') and get_server('togo_path'):
201 shares
.append(('ToGo', {'type': 'togo'}))
207 return config
.getboolean('Server', 'debug')
208 except NoOptionError
, ValueError:
211 def getOptres(tsn
=None):
213 return config
.getboolean('_tivo_' + tsn
, 'optres')
216 return config
.getboolean(get_section(tsn
), 'optres')
219 return config
.getboolean('Server', 'optres')
226 logger
= logging
.getLogger('pyTivo.config')
228 if fname
in bin_paths
:
229 return bin_paths
[fname
]
231 if config
.has_option('Server', fname
):
232 fpath
= config
.get('Server', fname
)
233 if os
.path
.exists(fpath
) and os
.path
.isfile(fpath
):
234 bin_paths
[fname
] = fpath
237 logger
.error('Bad %s path: %s' % (fname
, fpath
))
239 if sys
.platform
== 'win32':
244 for path
in ([os
.path
.join(os
.path
.dirname(__file__
), 'bin')] +
245 os
.getenv('PATH').split(os
.pathsep
)):
246 fpath
= os
.path
.join(path
, fname
+ fext
)
247 if os
.path
.exists(fpath
) and os
.path
.isfile(fpath
):
248 bin_paths
[fname
] = fpath
251 logger
.warn('%s not found' % fname
)
255 if config
.has_option('Server', 'ffmpeg_wait'):
256 return max(int(float(config
.get('Server', 'ffmpeg_wait'))), 1)
260 def getFFmpegTemplate(tsn
):
261 tmpl
= get_tsn('ffmpeg_tmpl', tsn
, True)
264 return '%(video_codec)s %(video_fps)s %(video_br)s %(max_video_br)s \
265 %(buff_size)s %(aspect_ratio)s %(audio_br)s \
266 %(audio_fr)s %(audio_ch)s %(audio_codec)s %(audio_lang)s \
267 %(ffmpeg_pram)s %(format)s'
269 def getFFmpegPrams(tsn
):
270 return get_tsn('ffmpeg_pram', tsn
, True)
272 def isHDtivo(tsn
): # tsn's of High Definition Tivo's
273 return bool(tsn
and tsn
[0] >= '6' and tsn
[:3] != '649')
277 return config
.getboolean('Server', 'ts')
278 except NoOptionError
, ValueError:
281 def is_ts_capable(tsn
): # tsn's of Tivos that support transport streams
282 return bool(tsn
and (tsn
[0] >= '7' or tsn
.startswith('663')))
284 def getValidWidths():
285 return [1920, 1440, 1280, 720, 704, 544, 480, 352]
287 def getValidHeights():
288 return [1080, 720, 480] # Technically 240 is also supported
290 # Return the number in list that is nearest to x
291 # if two values are equidistant, return the larger
292 def nearest(x
, list):
293 return reduce(lambda a
, b
: closest(x
, a
, b
), list)
295 def closest(x
, a
, b
):
298 if da
< db
or (da
== db
and a
> b
):
303 def nearestTivoHeight(height
):
304 return nearest(height
, getValidHeights())
306 def nearestTivoWidth(width
):
307 return nearest(width
, getValidWidths())
309 def getTivoHeight(tsn
):
310 height
= get_tsn('height', tsn
)
312 return nearestTivoHeight(int(height
))
313 return [480, 1080][isHDtivo(tsn
)]
315 def getTivoWidth(tsn
):
316 width
= get_tsn('width', tsn
)
318 return nearestTivoWidth(int(width
))
319 return [544, 1920][isHDtivo(tsn
)]
322 return max(int(strtod(i
)) / 64000, 1) * 64
324 def getAudioBR(tsn
=None):
325 rate
= get_tsn('audio_br', tsn
)
328 # convert to non-zero multiple of 64 to ensure ffmpeg compatibility
329 # compare audio_br to max_audio_br and return lowest
330 return str(min(_trunc64(rate
), getMaxAudioBR(tsn
))) + 'k'
333 return str(int(strtod(i
)) / 1000) + 'k'
335 def getVideoBR(tsn
=None):
336 rate
= get_tsn('video_br', tsn
)
339 return ['4096K', '16384K'][isHDtivo(tsn
)]
341 def getMaxVideoBR(tsn
=None):
342 rate
= get_tsn('max_video_br', tsn
)
347 def getBuffSize(tsn
=None):
348 size
= get_tsn('bufsize', tsn
)
351 return ['1024k', '4096k'][isHDtivo(tsn
)]
353 def getMaxAudioBR(tsn
=None):
354 rate
= get_tsn('max_audio_br', tsn
)
355 # convert to non-zero multiple of 64 for ffmpeg compatibility
357 return _trunc64(rate
)
360 def get_section(tsn
):
361 return ['_tivo_SD', '_tivo_HD'][isHDtivo(tsn
)]
363 def get_tsn(name
, tsn
=None, raw
=False):
365 return config
.get('_tivo_' + tsn
, name
, raw
)
368 return config
.get(get_section(tsn
), name
, raw
)
371 return config
.get('Server', name
, raw
)
375 # Parse a bitrate using the SI/IEEE suffix values as if by ffmpeg
376 # For example, 2K==2000, 2Ki==2048, 2MB==16000000, 2MiB==16777216
377 # Algorithm: http://svn.mplayerhq.hu/ffmpeg/trunk/libavcodec/eval.c
379 prefixes
= {'y': -24, 'z': -21, 'a': -18, 'f': -15, 'p': -12,
380 'n': -9, 'u': -6, 'm': -3, 'c': -2, 'd': -1,
381 'h': 2, 'k': 3, 'K': 3, 'M': 6, 'G': 9,
382 'T': 12, 'P': 15, 'E': 18, 'Z': 21, 'Y': 24}
383 p
= re
.compile(r
'^(\d+)(?:([yzafpnumcdhkKMGTPEZY])(i)?)?([Bb])?$')
386 raise SyntaxError('Invalid bit value syntax')
387 (coef
, prefix
, power
, byte
) = m
.groups()
391 exponent
= float(prefixes
[prefix
])
394 value
= float(coef
) * pow(2.0, exponent
/ 0.3)
397 value
= float(coef
) * pow(10.0, exponent
)
398 if byte
== 'B': # B == Byte, b == bit
403 if (config
.has_section('loggers') and
404 config
.has_section('handlers') and
405 config
.has_section('formatters')):
407 logging
.config
.fileConfig(config_files
)
410 logging
.basicConfig(level
=logging
.DEBUG
)
412 logging
.basicConfig(level
=logging
.INFO
)