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')
224 if config
.has_option('Server', 'par'):
226 return (True, config
.getfloat('Server', 'par'))[ref
]
227 except NoOptionError
, ValueError:
229 return (False, 1.0)[ref
]
234 logger
= logging
.getLogger('pyTivo.config')
236 if fname
in bin_paths
:
237 return bin_paths
[fname
]
239 if config
.has_option('Server', fname
):
240 fpath
= config
.get('Server', fname
)
241 if os
.path
.exists(fpath
) and os
.path
.isfile(fpath
):
242 bin_paths
[fname
] = fpath
245 logger
.error('Bad %s path: %s' % (fname
, fpath
))
247 if sys
.platform
== 'win32':
252 for path
in ([os
.path
.join(os
.path
.dirname(__file__
), 'bin')] +
253 os
.getenv('PATH').split(os
.pathsep
)):
254 fpath
= os
.path
.join(path
, fname
+ fext
)
255 if os
.path
.exists(fpath
) and os
.path
.isfile(fpath
):
256 bin_paths
[fname
] = fpath
259 logger
.warn('%s not found' % fname
)
263 if config
.has_option('Server', 'ffmpeg_wait'):
264 return max(int(float(config
.get('Server', 'ffmpeg_wait'))), 1)
268 def getFFmpegTemplate(tsn
):
269 tmpl
= get_tsn('ffmpeg_tmpl', tsn
, True)
272 return '%(video_codec)s %(video_fps)s %(video_br)s %(max_video_br)s \
273 %(buff_size)s %(aspect_ratio)s %(audio_br)s \
274 %(audio_fr)s %(audio_ch)s %(audio_codec)s %(audio_lang)s \
275 %(ffmpeg_pram)s %(format)s'
277 def getFFmpegPrams(tsn
):
278 return get_tsn('ffmpeg_pram', tsn
, True)
280 def isHDtivo(tsn
): # tsn's of High Definition Tivo's
281 return bool(tsn
and tsn
[0] >= '6' and tsn
[:3] != '649')
283 def hasTStivo(tsn
): # tsn's of Tivos that support transport streams
285 return config
.getboolean('Server', 'ts')
286 except NoOptionError
, ValueError:
288 return bool(tsn
and (tsn
[0] >= '7' or tsn
.startswith('663')))
290 def getValidWidths():
291 return [1920, 1440, 1280, 720, 704, 544, 480, 352]
293 def getValidHeights():
294 return [1080, 720, 480] # Technically 240 is also supported
296 # Return the number in list that is nearest to x
297 # if two values are equidistant, return the larger
298 def nearest(x
, list):
299 return reduce(lambda a
, b
: closest(x
, a
, b
), list)
301 def closest(x
, a
, b
):
304 if da
< db
or (da
== db
and a
> b
):
309 def nearestTivoHeight(height
):
310 return nearest(height
, getValidHeights())
312 def nearestTivoWidth(width
):
313 return nearest(width
, getValidWidths())
315 def getTivoHeight(tsn
):
316 height
= get_tsn('height', tsn
)
318 return nearestTivoHeight(int(height
))
319 return [480, 1080][isHDtivo(tsn
)]
321 def getTivoWidth(tsn
):
322 width
= get_tsn('width', tsn
)
324 return nearestTivoWidth(int(width
))
325 return [544, 1920][isHDtivo(tsn
)]
328 return max(int(strtod(i
)) / 64000, 1) * 64
330 def getAudioBR(tsn
=None):
331 rate
= get_tsn('audio_br', tsn
)
334 # convert to non-zero multiple of 64 to ensure ffmpeg compatibility
335 # compare audio_br to max_audio_br and return lowest
336 return str(min(_trunc64(rate
), getMaxAudioBR(tsn
))) + 'k'
339 return str(int(strtod(i
)) / 1000) + 'k'
341 def getVideoBR(tsn
=None):
342 rate
= get_tsn('video_br', tsn
)
345 return ['4096K', '16384K'][isHDtivo(tsn
)]
347 def getMaxVideoBR(tsn
=None):
348 rate
= get_tsn('max_video_br', tsn
)
353 def getVideoPCT(tsn
=None):
354 pct
= get_tsn('video_pct', tsn
)
359 def getBuffSize(tsn
=None):
360 size
= get_tsn('bufsize', tsn
)
363 return ['1024k', '4096k'][isHDtivo(tsn
)]
365 def getMaxAudioBR(tsn
=None):
366 rate
= get_tsn('max_audio_br', tsn
)
367 # convert to non-zero multiple of 64 for ffmpeg compatibility
369 return _trunc64(rate
)
372 def get_section(tsn
):
373 return ['_tivo_SD', '_tivo_HD'][isHDtivo(tsn
)]
375 def get_tsn(name
, tsn
=None, raw
=False):
377 return config
.get('_tivo_' + tsn
, name
, raw
)
380 return config
.get(get_section(tsn
), name
, raw
)
383 return config
.get('Server', name
, raw
)
387 # Parse a bitrate using the SI/IEEE suffix values as if by ffmpeg
388 # For example, 2K==2000, 2Ki==2048, 2MB==16000000, 2MiB==16777216
389 # Algorithm: http://svn.mplayerhq.hu/ffmpeg/trunk/libavcodec/eval.c
391 prefixes
= {'y': -24, 'z': -21, 'a': -18, 'f': -15, 'p': -12,
392 'n': -9, 'u': -6, 'm': -3, 'c': -2, 'd': -1,
393 'h': 2, 'k': 3, 'K': 3, 'M': 6, 'G': 9,
394 'T': 12, 'P': 15, 'E': 18, 'Z': 21, 'Y': 24}
395 p
= re
.compile(r
'^(\d+)(?:([yzafpnumcdhkKMGTPEZY])(i)?)?([Bb])?$')
398 raise SyntaxError('Invalid bit value syntax')
399 (coef
, prefix
, power
, byte
) = m
.groups()
403 exponent
= float(prefixes
[prefix
])
406 value
= float(coef
) * pow(2.0, exponent
/ 0.3)
409 value
= float(coef
) * pow(10.0, exponent
)
410 if byte
== 'B': # B == Byte, b == bit
415 if (config
.has_section('loggers') and
416 config
.has_section('handlers') and
417 config
.has_section('formatters')):
419 logging
.config
.fileConfig(config_files
)
422 logging
.basicConfig(level
=logging
.DEBUG
)
424 logging
.basicConfig(level
=logging
.INFO
)