11 from ConfigParser
import NoOptionError
13 guid
= ''.join([random
.choice(string
.letters
) for i
in range(10)])
15 config
= ConfigParser
.ConfigParser()
17 config_win_default
= ''
19 if sys
.platform
== "win32":
23 explorerFolders
= _winreg
.OpenKey(
24 _winreg
.HKEY_LOCAL_MACHINE
,
25 'Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders'
28 winCommonAppDataVal
, winCommonAppDataType
= _winreg
.QueryValueEx(explorerFolders
, 'Common AppData')
30 config_win_default
= os
.path
.join(winCommonAppDataVal
, 'pyTivo', 'pyTivo.conf')
33 print "Can't access Windows Registry to find common Application Data path."
35 p
= os
.path
.dirname(__file__
)
36 config_files
= ['/etc/pyTivo.conf', config_win_default
, os
.path
.join(p
, 'pyTivo.conf')]
49 opts
, _
= getopt
.getopt(argv
, 'c:e:', ['config=', 'extraconf='])
50 except getopt
.GetoptError
, msg
:
53 for opt
, value
in opts
:
54 if opt
in ('-c', '--config'):
55 config_files
= [value
]
56 elif opt
in ('-e', '--extraconf'):
57 config_files
.append(value
)
59 configs_found
= config
.read(config_files
)
61 print ('ERROR: pyTivo.conf does not exist.\n' +
62 'You must create this file before running pyTivo.')
65 for section
in config
.sections():
66 if section
.startswith('_tivo_'):
68 if tsn
.upper() not in ['SD', 'HD']:
69 if config
.has_option(section
, 'name'):
70 tivo_names
[tsn
] = config
.get(section
, 'name')
73 if config
.has_option(section
, 'address'):
74 tivos
[tsn
] = config
.get(section
, 'address')
80 newconfig
= ConfigParser
.ConfigParser()
81 newconfig
.read(config_files
)
85 f
= open(configs_found
[-1], 'w')
89 def get_server(name
, default
=None):
90 if config
.has_option('Server', name
):
91 return config
.get('Server', name
)
101 s
= socket
.socket(socket
.AF_INET
, socket
.SOCK_DGRAM
)
102 s
.connect(('4.2.2.1', 123))
103 our_ip
= s
.getsockname()[0]
107 opt
= get_server('zeroconf', 'auto').lower()
110 for section
in config
.sections():
111 if section
.startswith('_tivo_'):
112 if config
.has_option(section
, 'shares'):
113 logger
= logging
.getLogger('pyTivo.config')
114 logger
.info('Shares security in use -- zeroconf disabled')
116 elif opt
in ['false', 'no', 'off']:
122 if tsn
and tsn
.startswith('663'):
123 default
= 'symind.tivo.com:8181'
125 default
= 'mind.tivo.com:8181'
126 return get_server('tivo_mind', default
)
128 def getBeaconAddresses():
129 return get_server('beacon', '255.255.255.255')
132 return get_server('port', '9032')
134 def get169Blacklist(tsn
): # tivo does not pad 16:9 video
135 return tsn
and not isHDtivo(tsn
) and not get169Letterbox(tsn
)
136 # verified Blacklist Tivo's are ('130', '240', '540')
137 # It is assumed all remaining non-HD and non-Letterbox tivos are Blacklist
139 def get169Letterbox(tsn
): # tivo pads 16:9 video for 4:3 display
140 return tsn
and tsn
[:3] in ['649']
142 def get169Setting(tsn
):
146 tsnsect
= '_tivo_' + tsn
147 if config
.has_section(tsnsect
):
148 if config
.has_option(tsnsect
, 'aspect169'):
150 return config
.getboolean(tsnsect
, 'aspect169')
154 if get169Blacklist(tsn
) or get169Letterbox(tsn
):
159 def getAllowedClients():
160 return get_server('allowedips', '').split()
162 def getIsExternal(tsn
):
163 tsnsect
= '_tivo_' + tsn
164 if tsnsect
in config
.sections():
165 if config
.has_option(tsnsect
, 'external'):
167 return config
.getboolean(tsnsect
, 'external')
173 def isTsnInConfig(tsn
):
174 return ('_tivo_' + tsn
) in config
.sections()
176 def getShares(tsn
=''):
177 shares
= [(section
, dict(config
.items(section
)))
178 for section
in config
.sections()
179 if not (section
.startswith('_tivo_')
180 or section
.startswith('logger_')
181 or section
.startswith('handler_')
182 or section
.startswith('formatter_')
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
, dict(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')
210 except NoOptionError
, ValueError:
213 def getOptres(tsn
=None):
214 if tsn
and config
.has_section('_tivo_' + tsn
):
216 return config
.getboolean('_tivo_' + tsn
, 'optres')
217 except NoOptionError
, ValueError:
219 section_name
= get_section(tsn
)
220 if config
.has_section(section_name
):
222 return config
.getboolean(section_name
, 'optres')
223 except NoOptionError
, ValueError:
226 return config
.getboolean('Server', 'optres')
227 except NoOptionError
, ValueError:
231 if config
.has_option('Server', 'par'):
233 return (True, config
.getfloat('Server', 'par'))[ref
]
234 except NoOptionError
, ValueError:
236 return (False, 1.0)[ref
]
241 logger
= logging
.getLogger('pyTivo.config')
243 if fname
in bin_paths
:
244 return bin_paths
[fname
]
246 if config
.has_option('Server', fname
):
247 fpath
= config
.get('Server', fname
)
248 if os
.path
.exists(fpath
) and os
.path
.isfile(fpath
):
249 bin_paths
[fname
] = fpath
252 logger
.error('Bad %s path: %s' % (fname
, fpath
))
254 if sys
.platform
== 'win32':
259 for path
in ([os
.path
.join(os
.path
.dirname(__file__
), 'bin')] +
260 os
.getenv('PATH').split(os
.pathsep
)):
261 fpath
= os
.path
.join(path
, fname
+ fext
)
262 if os
.path
.exists(fpath
) and os
.path
.isfile(fpath
):
263 bin_paths
[fname
] = fpath
266 logger
.warn('%s not found' % fname
)
270 if config
.has_option('Server', 'ffmpeg_wait'):
271 return max(int(float(config
.get('Server', 'ffmpeg_wait'))), 1)
275 def getFFmpegTemplate(tsn
):
276 tmpl
= get_tsn('ffmpeg_tmpl', tsn
, True)
279 return '%(video_codec)s %(video_fps)s %(video_br)s %(max_video_br)s \
280 %(buff_size)s %(aspect_ratio)s %(audio_br)s \
281 %(audio_fr)s %(audio_ch)s %(audio_codec)s %(audio_lang)s \
282 %(ffmpeg_pram)s %(format)s'
284 def getFFmpegPrams(tsn
):
285 return get_tsn('ffmpeg_pram', tsn
, True)
287 def isHDtivo(tsn
): # tsn's of High Definition Tivo's
288 return bool(tsn
and tsn
[0] >= '6' and tsn
[:3] != '649')
290 def hasTStivo(tsn
): # tsn's of Tivos that support transport streams
292 return config
.getboolean('Server', 'ts')
293 except NoOptionError
, ValueError:
295 return bool(tsn
and (tsn
[0] >= '7' or tsn
.startswith('663')))
297 def getValidWidths():
298 return [1920, 1440, 1280, 720, 704, 544, 480, 352]
300 def getValidHeights():
301 return [1080, 720, 480] # Technically 240 is also supported
303 # Return the number in list that is nearest to x
304 # if two values are equidistant, return the larger
305 def nearest(x
, list):
306 return reduce(lambda a
, b
: closest(x
, a
, b
), list)
308 def closest(x
, a
, b
):
311 if da
< db
or (da
== db
and a
> b
):
316 def nearestTivoHeight(height
):
317 return nearest(height
, getValidHeights())
319 def nearestTivoWidth(width
):
320 return nearest(width
, getValidWidths())
322 def getTivoHeight(tsn
):
323 height
= get_tsn('height', tsn
)
325 return nearestTivoHeight(int(height
))
326 return [480, 1080][isHDtivo(tsn
)]
328 def getTivoWidth(tsn
):
329 width
= get_tsn('width', tsn
)
331 return nearestTivoWidth(int(width
))
332 return [544, 1920][isHDtivo(tsn
)]
335 return max(int(strtod(i
)) / 64000, 1) * 64
337 def getAudioBR(tsn
=None):
338 rate
= get_tsn('audio_br', tsn
)
341 # convert to non-zero multiple of 64 to ensure ffmpeg compatibility
342 # compare audio_br to max_audio_br and return lowest
343 return str(min(_trunc64(rate
), getMaxAudioBR(tsn
))) + 'k'
346 return str(int(strtod(i
)) / 1000) + 'k'
348 def getVideoBR(tsn
=None):
349 rate
= get_tsn('video_br', tsn
)
352 return ['4096K', '16384K'][isHDtivo(tsn
)]
354 def getMaxVideoBR(tsn
=None):
355 rate
= get_tsn('max_video_br', tsn
)
360 def getVideoPCT(tsn
=None):
361 pct
= get_tsn('video_pct', tsn
)
366 def getBuffSize(tsn
=None):
367 size
= get_tsn('bufsize', tsn
)
370 return ['1024k', '4096k'][isHDtivo(tsn
)]
372 def getMaxAudioBR(tsn
=None):
373 rate
= get_tsn('max_audio_br', tsn
)
374 # convert to non-zero multiple of 64 for ffmpeg compatibility
376 return _trunc64(rate
)
379 def get_section(tsn
):
380 return ['_tivo_SD', '_tivo_HD'][isHDtivo(tsn
)]
382 def get_tsn(name
, tsn
=None, raw
=False):
383 if tsn
and config
.has_section('_tivo_' + tsn
):
385 return config
.get('_tivo_' + tsn
, name
, raw
)
386 except NoOptionError
:
388 section_name
= get_section(tsn
)
389 if config
.has_section(section_name
):
391 return config
.get(section_name
, name
, raw
)
392 except NoOptionError
:
395 return config
.get('Server', name
, raw
)
396 except NoOptionError
:
400 # Parse a bitrate using the SI/IEEE suffix values as if by ffmpeg
401 # For example, 2K==2000, 2Ki==2048, 2MB==16000000, 2MiB==16777216
402 # Algorithm: http://svn.mplayerhq.hu/ffmpeg/trunk/libavcodec/eval.c
404 prefixes
= {'y': -24, 'z': -21, 'a': -18, 'f': -15, 'p': -12,
405 'n': -9, 'u': -6, 'm': -3, 'c': -2, 'd': -1,
406 'h': 2, 'k': 3, 'K': 3, 'M': 6, 'G': 9,
407 'T': 12, 'P': 15, 'E': 18, 'Z': 21, 'Y': 24}
408 p
= re
.compile(r
'^(\d+)(?:([yzafpnumcdhkKMGTPEZY])(i)?)?([Bb])?$')
411 raise SyntaxError('Invalid bit value syntax')
412 (coef
, prefix
, power
, byte
) = m
.groups()
416 exponent
= float(prefixes
[prefix
])
419 value
= float(coef
) * pow(2.0, exponent
/ 0.3)
422 value
= float(coef
) * pow(10.0, exponent
)
423 if byte
== 'B': # B == Byte, b == bit
428 if (config
.has_section('loggers') and
429 config
.has_section('handlers') and
430 config
.has_section('formatters')):
432 logging
.config
.fileConfig(config_files
)
435 logging
.basicConfig(level
=logging
.DEBUG
)
437 logging
.basicConfig(level
=logging
.INFO
)