10 from ConfigParser
import NoOptionError
12 guid
= ''.join([random
.choice(string
.letters
) for i
in range(10)])
14 config
= ConfigParser
.ConfigParser()
16 p
= os
.path
.dirname(__file__
)
17 config_files
= ['/etc/pyTivo.conf', os
.path
.join(p
, 'pyTivo.conf')]
25 opts
, _
= getopt
.getopt(argv
, 'c:e:', ['config=', 'extraconf='])
26 except getopt
.GetoptError
, msg
:
29 for opt
, value
in opts
:
30 if opt
in ('-c', '--config'):
31 config_files
= [value
]
32 elif opt
in ('-e', '--extraconf'):
33 config_files
.append(value
)
35 configs_found
= config
.read(config_files
)
37 print ('ERROR: pyTivo.conf does not exist.\n' +
38 'You must create this file before running pyTivo.')
43 newconfig
= ConfigParser
.ConfigParser()
44 newconfig
.read(config_files
)
48 f
= open(configs_found
[-1], 'w')
53 if config
.has_option('Server', 'GUID'):
54 return config
.get('Server', 'GUID')
58 def getTivoUsername(tsn
=None):
59 return get_tsn('tivo_username', tsn
)
61 def getTivoPassword(tsn
=None):
62 return get_tsn('tivo_password', tsn
)
64 def getBeaconAddresses():
65 if config
.has_option('Server', 'beacon'):
66 beacon_ips
= config
.get('Server', 'beacon')
68 beacon_ips
= '255.255.255.255'
72 if config
.has_option('Server', 'Port'):
73 return config
.get('Server', 'Port')
77 def get169Blacklist(tsn
): # tivo does not pad 16:9 video
78 return tsn
and not isHDtivo(tsn
) and not get169Letterbox(tsn
)
79 # verified Blacklist Tivo's are ('130', '240', '540')
80 # It is assumed all remaining non-HD and non-Letterbox tivos are Blacklist
82 def get169Letterbox(tsn
): # tivo pads 16:9 video for 4:3 display
83 return tsn
and tsn
[:3] in ['649']
85 def get169Setting(tsn
):
89 tsnsect
= '_tivo_' + tsn
90 if config
.has_section(tsnsect
):
91 if config
.has_option(tsnsect
, 'aspect169'):
93 return config
.getboolean(tsnsect
, 'aspect169')
97 if get169Blacklist(tsn
) or get169Letterbox(tsn
):
102 def getAllowedClients():
103 if config
.has_option('Server', 'allowedips'):
104 return config
.get('Server', 'allowedips').split()
108 def getExternalUrl():
109 if config
.has_option('Server', 'externalurl'):
110 return config
.get('Server', 'externalurl')
114 def getIsExternal(tsn
):
115 tsnsect
= '_tivo_' + tsn
116 if tsnsect
in config
.sections():
117 if config
.has_option(tsnsect
, 'external'):
119 return config
.getboolean(tsnsect
, 'external')
125 def isTsnInConfig(tsn
):
126 return ('_tivo_' + tsn
) in config
.sections()
128 def getConfigTivoNames():
130 for section
in config
.sections():
131 if section
.startswith('_tivo_'):
133 if config
.has_option(section
, 'name'):
134 tivo_names
[tsn
] = config
.get(section
, 'name')
136 tivo_names
[tsn
] = tsn
139 def getShares(tsn
=''):
140 shares
= [(section
, dict(config
.items(section
)))
141 for section
in config
.sections()
142 if not (section
.startswith('_tivo_')
143 or section
.startswith('logger_')
144 or section
.startswith('handler_')
145 or section
.startswith('formatter_')
146 or section
in ('Server', 'loggers', 'handlers',
151 tsnsect
= '_tivo_' + tsn
152 if config
.has_section(tsnsect
) and config
.has_option(tsnsect
, 'shares'):
153 # clean up leading and trailing spaces & make sure ref is valid
155 for x
in config
.get(tsnsect
, 'shares').split(','):
157 if config
.has_section(y
):
158 tsnshares
.append((y
, dict(config
.items(y
))))
166 return config
.getboolean('Server', 'debug')
167 except NoOptionError
, ValueError:
170 def getOptres(tsn
=None):
171 if tsn
and config
.has_section('_tivo_' + tsn
):
173 return config
.getboolean('_tivo_' + tsn
, 'optres')
174 except NoOptionError
, ValueError:
176 section_name
= get_section(tsn
)
177 if config
.has_section(section_name
):
179 return config
.getboolean(section_name
, 'optres')
180 except NoOptionError
, ValueError:
183 return config
.getboolean('Server', 'optres')
184 except NoOptionError
, ValueError:
188 if config
.has_option('Server', 'par'):
190 return (True, config
.getfloat('Server', 'par'))[ref
]
191 except NoOptionError
, ValueError:
193 return (False, 1.0)[ref
]
196 return config
.get('Server', 'ffmpeg')
199 if config
.has_option('Server', 'ffmpeg_wait'):
200 return max(int(float(config
.get('Server', 'ffmpeg_wait'))), 1)
204 def getFFmpegTemplate(tsn
):
205 tmpl
= get_tsn('ffmpeg_tmpl', tsn
, True)
208 return '%(video_codec)s %(video_fps)s %(video_br)s %(max_video_br)s \
209 %(buff_size)s %(aspect_ratio)s %(audio_br)s \
210 %(audio_fr)s %(audio_ch)s %(audio_codec)s %(audio_lang)s \
211 %(ffmpeg_pram)s %(format)s'
213 def getFFmpegPrams(tsn
):
214 return get_tsn('ffmpeg_pram', tsn
, True)
216 def isHDtivo(tsn
): # tsn's of High Definition Tivo's
217 return bool(tsn
and tsn
[:3] in ['648', '652', '658', '663'])
219 def getValidWidths():
220 return [1920, 1440, 1280, 720, 704, 544, 480, 352]
222 def getValidHeights():
223 return [1080, 720, 480] # Technically 240 is also supported
225 # Return the number in list that is nearest to x
226 # if two values are equidistant, return the larger
227 def nearest(x
, list):
228 return reduce(lambda a
, b
: closest(x
, a
, b
), list)
230 def closest(x
, a
, b
):
233 if da
< db
or (da
== db
and a
> b
):
238 def nearestTivoHeight(height
):
239 return nearest(height
, getValidHeights())
241 def nearestTivoWidth(width
):
242 return nearest(width
, getValidWidths())
244 def getTivoHeight(tsn
):
245 height
= get_tsn('height', tsn
)
247 return nearestTivoHeight(int(height
))
248 return [480, 1080][isHDtivo(tsn
)]
250 def getTivoWidth(tsn
):
251 width
= get_tsn('width', tsn
)
253 return nearestTivoWidth(int(width
))
254 return [544, 1920][isHDtivo(tsn
)]
257 return max(int(strtod(i
)) / 64000, 1) * 64
259 def getAudioBR(tsn
=None):
260 rate
= get_tsn('audio_br', tsn
)
263 # convert to non-zero multiple of 64 to ensure ffmpeg compatibility
264 # compare audio_br to max_audio_br and return lowest
265 return str(min(_trunc64(rate
), getMaxAudioBR(tsn
))) + 'k'
268 return str(int(strtod(i
)) / 1000) + 'k'
270 def getVideoBR(tsn
=None):
271 rate
= get_tsn('video_br', tsn
)
274 return ['4096K', '16384K'][isHDtivo(tsn
)]
276 def getMaxVideoBR(tsn
=None):
277 rate
= get_tsn('max_video_br', tsn
)
282 def getVideoPCT(tsn
=None):
283 pct
= get_tsn('video_pct', tsn
)
288 def getBuffSize(tsn
=None):
289 size
= get_tsn('bufsize', tsn
)
292 return ['1024k', '4096k'][isHDtivo(tsn
)]
294 def getMaxAudioBR(tsn
=None):
295 rate
= get_tsn('max_audio_br', tsn
)
296 # convert to non-zero multiple of 64 for ffmpeg compatibility
298 return _trunc64(rate
)
301 def get_section(tsn
):
302 return ['_tivo_SD', '_tivo_HD'][isHDtivo(tsn
)]
304 def get_tsn(name
, tsn
=None, raw
=False):
305 if tsn
and config
.has_section('_tivo_' + tsn
):
307 return config
.get('_tivo_' + tsn
, name
, raw
)
308 except NoOptionError
:
310 section_name
= get_section(tsn
)
311 if config
.has_section(section_name
):
313 return config
.get(section_name
, name
, raw
)
314 except NoOptionError
:
317 return config
.get('Server', name
, raw
)
318 except NoOptionError
:
322 def getAudioCodec(tsn
=None):
323 return get_tsn('audio_codec', tsn
)
325 def getAudioCH(tsn
=None):
326 return get_tsn('audio_ch', tsn
)
328 def getAudioFR(tsn
=None):
329 return get_tsn('audio_fr', tsn
)
331 def getAudioLang(tsn
=None):
332 return get_tsn('audio_lang', tsn
)
334 def getCopyTS(tsn
=None):
335 return get_tsn('copy_ts', tsn
)
337 def getVideoFPS(tsn
=None):
338 return get_tsn('video_fps', tsn
)
340 # Parse a bitrate using the SI/IEEE suffix values as if by ffmpeg
341 # For example, 2K==2000, 2Ki==2048, 2MB==16000000, 2MiB==16777216
342 # Algorithm: http://svn.mplayerhq.hu/ffmpeg/trunk/libavcodec/eval.c
344 prefixes
= {'y': -24, 'z': -21, 'a': -18, 'f': -15, 'p': -12,
345 'n': -9, 'u': -6, 'm': -3, 'c': -2, 'd': -1,
346 'h': 2, 'k': 3, 'K': 3, 'M': 6, 'G': 9,
347 'T': 12, 'P': 15, 'E': 18, 'Z': 21, 'Y': 24}
348 p
= re
.compile(r
'^(\d+)(?:([yzafpnumcdhkKMGTPEZY])(i)?)?([Bb])?$')
351 raise SyntaxError('Invalid bit value syntax')
352 (coef
, prefix
, power
, byte
) = m
.groups()
356 exponent
= float(prefixes
[prefix
])
359 value
= float(coef
) * pow(2.0, exponent
/ 0.3)
362 value
= float(coef
) * pow(10.0, exponent
)
363 if byte
== 'B': # B == Byte, b == bit
368 if (config
.has_section('loggers') and
369 config
.has_section('handlers') and
370 config
.has_section('formatters')):
372 logging
.config
.fileConfig(config_files
)
375 logging
.basicConfig(level
=logging
.DEBUG
)
377 logging
.basicConfig(level
=logging
.INFO
)