11 from ConfigParser
import NoOptionError
13 guid
= ''.join([random
.choice(string
.letters
) for i
in range(10)])
15 config
= ConfigParser
.ConfigParser()
17 p
= os
.path
.dirname(__file__
)
18 config_files
= ['/etc/pyTivo.conf', os
.path
.join(p
, 'pyTivo.conf')]
31 opts
, _
= getopt
.getopt(argv
, 'c:e:', ['config=', 'extraconf='])
32 except getopt
.GetoptError
, msg
:
35 for opt
, value
in opts
:
36 if opt
in ('-c', '--config'):
37 config_files
= [value
]
38 elif opt
in ('-e', '--extraconf'):
39 config_files
.append(value
)
41 configs_found
= config
.read(config_files
)
43 print ('ERROR: pyTivo.conf does not exist.\n' +
44 'You must create this file before running pyTivo.')
47 for section
in config
.sections():
48 if section
.startswith('_tivo_'):
50 if tsn
.upper() not in ['SD', 'HD']:
51 if config
.has_option(section
, 'name'):
52 tivo_names
[tsn
] = config
.get(section
, 'name')
58 newconfig
= ConfigParser
.ConfigParser()
59 newconfig
.read(config_files
)
63 f
= open(configs_found
[-1], 'w')
67 def get_server(name
, default
=None):
68 if config
.has_option('Server', name
):
69 return config
.get('Server', name
)
79 s
= socket
.socket(socket
.AF_INET
, socket
.SOCK_DGRAM
)
80 s
.connect(('4.2.2.1', 123))
81 our_ip
= s
.getsockname()[0]
85 opt
= get_server('zeroconf', 'auto').lower()
88 for section
in config
.sections():
89 if section
.startswith('_tivo_'):
90 if config
.has_option(section
, 'shares'):
91 logger
= logging
.getLogger('pyTivo.config')
92 logger
.info('Shares security in use -- zeroconf disabled')
94 elif opt
in ['false', 'no', 'off']:
100 if tsn
and tsn
.startswith('663'):
101 default
= 'symind.tivo.com:8181'
103 default
= 'mind.tivo.com:8181'
104 return get_server('tivo_mind', default
)
106 def getBeaconAddresses():
107 return get_server('beacon', '255.255.255.255')
110 return get_server('port', '9032')
112 def get169Blacklist(tsn
): # tivo does not pad 16:9 video
113 return tsn
and not isHDtivo(tsn
) and not get169Letterbox(tsn
)
114 # verified Blacklist Tivo's are ('130', '240', '540')
115 # It is assumed all remaining non-HD and non-Letterbox tivos are Blacklist
117 def get169Letterbox(tsn
): # tivo pads 16:9 video for 4:3 display
118 return tsn
and tsn
[:3] in ['649']
120 def get169Setting(tsn
):
124 tsnsect
= '_tivo_' + tsn
125 if config
.has_section(tsnsect
):
126 if config
.has_option(tsnsect
, 'aspect169'):
128 return config
.getboolean(tsnsect
, 'aspect169')
132 if get169Blacklist(tsn
) or get169Letterbox(tsn
):
137 def getAllowedClients():
138 return get_server('allowedips', '').split()
140 def getIsExternal(tsn
):
141 tsnsect
= '_tivo_' + tsn
142 if tsnsect
in config
.sections():
143 if config
.has_option(tsnsect
, 'external'):
145 return config
.getboolean(tsnsect
, 'external')
151 def isTsnInConfig(tsn
):
152 return ('_tivo_' + tsn
) in config
.sections()
154 def getShares(tsn
=''):
155 shares
= [(section
, dict(config
.items(section
)))
156 for section
in config
.sections()
157 if not (section
.startswith('_tivo_')
158 or section
.startswith('logger_')
159 or section
.startswith('handler_')
160 or section
.startswith('formatter_')
161 or section
in ('Server', 'loggers', 'handlers',
166 tsnsect
= '_tivo_' + tsn
167 if config
.has_section(tsnsect
) and config
.has_option(tsnsect
, 'shares'):
168 # clean up leading and trailing spaces & make sure ref is valid
170 for x
in config
.get(tsnsect
, 'shares').split(','):
172 if config
.has_section(y
):
173 tsnshares
.append((y
, dict(config
.items(y
))))
179 if get_server('nosettings', 'false').lower() in ['false', 'no', 'off']:
180 shares
.append(('Settings', {'type': 'settings'}))
181 if get_server('tivo_mak') and get_server('togo_path'):
182 shares
.append(('ToGo', {'type': 'togo'}))
188 return config
.getboolean('Server', 'debug')
189 except NoOptionError
, ValueError:
192 def getOptres(tsn
=None):
193 if tsn
and config
.has_section('_tivo_' + tsn
):
195 return config
.getboolean('_tivo_' + tsn
, 'optres')
196 except NoOptionError
, ValueError:
198 section_name
= get_section(tsn
)
199 if config
.has_section(section_name
):
201 return config
.getboolean(section_name
, 'optres')
202 except NoOptionError
, ValueError:
205 return config
.getboolean('Server', 'optres')
206 except NoOptionError
, ValueError:
210 if config
.has_option('Server', 'par'):
212 return (True, config
.getfloat('Server', 'par'))[ref
]
213 except NoOptionError
, ValueError:
215 return (False, 1.0)[ref
]
218 if config
.has_option('Server', fname
):
219 return config
.get('Server', fname
)
222 if fname
in bin_paths
:
223 return bin_paths
[fname
]
224 if sys
.platform
== 'win32':
226 for path
in ([os
.path
.join(os
.path
.dirname(__file__
), 'bin')] +
227 os
.getenv('PATH').split(os
.pathsep
)):
228 fpath
= os
.path
.join(path
, fname
)
229 if os
.path
.exists(fpath
) and os
.path
.isfile(fpath
):
230 bin_paths
[fname
] = fpath
235 if config
.has_option('Server', 'ffmpeg_wait'):
236 return max(int(float(config
.get('Server', 'ffmpeg_wait'))), 1)
240 def getFFmpegTemplate(tsn
):
241 tmpl
= get_tsn('ffmpeg_tmpl', tsn
, True)
244 return '%(video_codec)s %(video_fps)s %(video_br)s %(max_video_br)s \
245 %(buff_size)s %(aspect_ratio)s %(audio_br)s \
246 %(audio_fr)s %(audio_ch)s %(audio_codec)s %(audio_lang)s \
247 %(ffmpeg_pram)s %(format)s'
249 def getFFmpegPrams(tsn
):
250 return get_tsn('ffmpeg_pram', tsn
, True)
252 def isHDtivo(tsn
): # tsn's of High Definition Tivo's
253 return bool(tsn
and tsn
[:3] in ['648', '652', '658', '663'])
255 def getValidWidths():
256 return [1920, 1440, 1280, 720, 704, 544, 480, 352]
258 def getValidHeights():
259 return [1080, 720, 480] # Technically 240 is also supported
261 # Return the number in list that is nearest to x
262 # if two values are equidistant, return the larger
263 def nearest(x
, list):
264 return reduce(lambda a
, b
: closest(x
, a
, b
), list)
266 def closest(x
, a
, b
):
269 if da
< db
or (da
== db
and a
> b
):
274 def nearestTivoHeight(height
):
275 return nearest(height
, getValidHeights())
277 def nearestTivoWidth(width
):
278 return nearest(width
, getValidWidths())
280 def getTivoHeight(tsn
):
281 height
= get_tsn('height', tsn
)
283 return nearestTivoHeight(int(height
))
284 return [480, 1080][isHDtivo(tsn
)]
286 def getTivoWidth(tsn
):
287 width
= get_tsn('width', tsn
)
289 return nearestTivoWidth(int(width
))
290 return [544, 1920][isHDtivo(tsn
)]
293 return max(int(strtod(i
)) / 64000, 1) * 64
295 def getAudioBR(tsn
=None):
296 rate
= get_tsn('audio_br', tsn
)
299 # convert to non-zero multiple of 64 to ensure ffmpeg compatibility
300 # compare audio_br to max_audio_br and return lowest
301 return str(min(_trunc64(rate
), getMaxAudioBR(tsn
))) + 'k'
304 return str(int(strtod(i
)) / 1000) + 'k'
306 def getVideoBR(tsn
=None):
307 rate
= get_tsn('video_br', tsn
)
310 return ['4096K', '16384K'][isHDtivo(tsn
)]
312 def getMaxVideoBR(tsn
=None):
313 rate
= get_tsn('max_video_br', tsn
)
318 def getVideoPCT(tsn
=None):
319 pct
= get_tsn('video_pct', tsn
)
324 def getBuffSize(tsn
=None):
325 size
= get_tsn('bufsize', tsn
)
328 return ['1024k', '4096k'][isHDtivo(tsn
)]
330 def getMaxAudioBR(tsn
=None):
331 rate
= get_tsn('max_audio_br', tsn
)
332 # convert to non-zero multiple of 64 for ffmpeg compatibility
334 return _trunc64(rate
)
337 def get_section(tsn
):
338 return ['_tivo_SD', '_tivo_HD'][isHDtivo(tsn
)]
340 def get_tsn(name
, tsn
=None, raw
=False):
341 if tsn
and config
.has_section('_tivo_' + tsn
):
343 return config
.get('_tivo_' + tsn
, name
, raw
)
344 except NoOptionError
:
346 section_name
= get_section(tsn
)
347 if config
.has_section(section_name
):
349 return config
.get(section_name
, name
, raw
)
350 except NoOptionError
:
353 return config
.get('Server', name
, raw
)
354 except NoOptionError
:
358 # Parse a bitrate using the SI/IEEE suffix values as if by ffmpeg
359 # For example, 2K==2000, 2Ki==2048, 2MB==16000000, 2MiB==16777216
360 # Algorithm: http://svn.mplayerhq.hu/ffmpeg/trunk/libavcodec/eval.c
362 prefixes
= {'y': -24, 'z': -21, 'a': -18, 'f': -15, 'p': -12,
363 'n': -9, 'u': -6, 'm': -3, 'c': -2, 'd': -1,
364 'h': 2, 'k': 3, 'K': 3, 'M': 6, 'G': 9,
365 'T': 12, 'P': 15, 'E': 18, 'Z': 21, 'Y': 24}
366 p
= re
.compile(r
'^(\d+)(?:([yzafpnumcdhkKMGTPEZY])(i)?)?([Bb])?$')
369 raise SyntaxError('Invalid bit value syntax')
370 (coef
, prefix
, power
, byte
) = m
.groups()
374 exponent
= float(prefixes
[prefix
])
377 value
= float(coef
) * pow(2.0, exponent
/ 0.3)
380 value
= float(coef
) * pow(10.0, exponent
)
381 if byte
== 'B': # B == Byte, b == bit
386 if (config
.has_section('loggers') and
387 config
.has_section('handlers') and
388 config
.has_section('formatters')):
390 logging
.config
.fileConfig(config_files
)
393 logging
.basicConfig(level
=logging
.DEBUG
)
395 logging
.basicConfig(level
=logging
.INFO
)