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():
59 return config
.get('Server', 'tivo_username')
61 def getTivoPassword():
62 return config
.get('Server', 'tivo_password')
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 return config
.get('Server', 'Port')
74 def get169Blacklist(tsn
): # tivo does not pad 16:9 video
75 return tsn
and not isHDtivo(tsn
) and not get169Letterbox(tsn
)
76 # verified Blacklist Tivo's are ('130', '240', '540')
77 # It is assumed all remaining non-HD and non-Letterbox tivos are Blacklist
79 def get169Letterbox(tsn
): # tivo pads 16:9 video for 4:3 display
80 return tsn
and tsn
[:3] in ['649']
82 def get169Setting(tsn
):
86 tsnsect
= '_tivo_' + tsn
87 if config
.has_section(tsnsect
):
88 if config
.has_option(tsnsect
, 'aspect169'):
90 return config
.getboolean(tsnsect
, 'aspect169')
94 if get169Blacklist(tsn
) or get169Letterbox(tsn
):
99 def getShares(tsn
=''):
100 shares
= [(section
, dict(config
.items(section
)))
101 for section
in config
.sections()
102 if not (section
.startswith('_tivo_')
103 or section
.startswith('logger_')
104 or section
.startswith('handler_')
105 or section
.startswith('formatter_')
106 or section
in ('Server', 'loggers', 'handlers',
111 tsnsect
= '_tivo_' + tsn
112 if config
.has_section(tsnsect
) and config
.has_option(tsnsect
, 'shares'):
113 # clean up leading and trailing spaces & make sure ref is valid
115 for x
in config
.get(tsnsect
, 'shares').split(','):
117 if config
.has_section(y
):
118 tsnshares
.append((y
, dict(config
.items(y
))))
126 return config
.getboolean('Server', 'debug')
127 except NoOptionError
, ValueError:
130 def getOptres(tsn
=None):
131 if tsn
and config
.has_section('_tivo_' + tsn
):
133 return config
.getboolean('_tivo_' + tsn
, 'optres')
134 except NoOptionError
, ValueError:
136 section_name
= get_section(tsn
)
137 if config
.has_section(section_name
):
139 return config
.getboolean(section_name
, 'optres')
140 except NoOptionError
, ValueError:
143 return config
.getboolean('Server', 'optres')
144 except NoOptionError
, ValueError:
148 if config
.has_option('Server', 'par'):
150 return (True, config
.getfloat('Server', 'par'))[ref
]
151 except NoOptionError
, ValueError:
153 return (False, 1.0)[ref
]
155 def get(section
, key
):
156 return config
.get(section
, key
)
159 if config
.has_option('Server', 'ffmpeg_wait'):
160 return max(int(float(config
.get('Server', 'ffmpeg_wait'))), 1)
164 def getFFmpegTemplate(tsn
):
165 tmpl
= get_tsn('ffmpeg_tmpl', tsn
, True)
168 return '%(video_codec)s %(video_fps)s %(video_br)s %(max_video_br)s \
169 %(buff_size)s %(aspect_ratio)s %(audio_br)s \
170 %(audio_fr)s %(audio_ch)s %(audio_codec)s %(audio_lang)s \
171 %(ffmpeg_pram)s %(format)s'
173 def getFFmpegPrams(tsn
):
174 return get_tsn('ffmpeg_pram', tsn
, True)
176 def isHDtivo(tsn
): # tsn's of High Definition Tivo's
177 return bool(tsn
and tsn
[:3] in ['648', '652', '658', '663'])
179 def getValidWidths():
180 return [1920, 1440, 1280, 720, 704, 544, 480, 352]
182 def getValidHeights():
183 return [1080, 720, 480] # Technically 240 is also supported
185 # Return the number in list that is nearest to x
186 # if two values are equidistant, return the larger
187 def nearest(x
, list):
188 return reduce(lambda a
, b
: closest(x
, a
, b
), list)
190 def closest(x
, a
, b
):
193 if da
< db
or (da
== db
and a
> b
):
198 def nearestTivoHeight(height
):
199 return nearest(height
, getValidHeights())
201 def nearestTivoWidth(width
):
202 return nearest(width
, getValidWidths())
204 def getTivoHeight(tsn
):
205 height
= get_tsn('height', tsn
)
207 return nearestTivoHeight(int(height
))
208 return [480, 720][isHDtivo(tsn
)]
210 def getTivoWidth(tsn
):
211 width
= get_tsn('width', tsn
)
213 return nearestTivoWidth(int(width
))
214 return [544, 1280][isHDtivo(tsn
)]
217 return max(int(strtod(i
)) / 64000, 1) * 64
219 def getAudioBR(tsn
=None):
220 rate
= get_tsn('audio_br', tsn
)
223 # convert to non-zero multiple of 64 to ensure ffmpeg compatibility
224 # compare audio_br to max_audio_br and return lowest
225 return str(min(_trunc64(rate
), getMaxAudioBR(tsn
))) + 'k'
228 return str(int(strtod(i
)) / 1000) + 'k'
230 def getVideoBR(tsn
=None):
231 rate
= get_tsn('video_br', tsn
)
234 return ['4096K', '16384K'][isHDtivo(tsn
)]
236 def getMaxVideoBR(tsn
=None):
237 rate
= get_tsn('max_video_br', tsn
)
242 def getVideoPCT(tsn
=None):
243 pct
= get_tsn('video_pct', tsn
)
248 def getBuffSize(tsn
=None):
249 size
= get_tsn('bufsize', tsn
)
252 return ['1024k', '4096k'][isHDtivo(tsn
)]
254 def getMaxAudioBR(tsn
=None):
255 rate
= get_tsn('max_audio_br', tsn
)
256 # convert to non-zero multiple of 64 for ffmpeg compatibility
258 return _trunc64(rate
)
261 def get_section(tsn
):
262 return ['_tivo_SD', '_tivo_HD'][isHDtivo(tsn
)]
264 def get_tsn(name
, tsn
=None, raw
=False):
265 if tsn
and config
.has_section('_tivo_' + tsn
):
267 return config
.get('_tivo_' + tsn
, name
, raw
)
268 except NoOptionError
:
270 section_name
= get_section(tsn
)
271 if config
.has_section(section_name
):
273 return config
.get(section_name
, name
, raw
)
274 except NoOptionError
:
277 return config
.get('Server', name
, raw
)
278 except NoOptionError
:
282 def getAudioCodec(tsn
=None):
283 return get_tsn('audio_codec', tsn
)
285 def getAudioCH(tsn
=None):
286 return get_tsn('audio_ch', tsn
)
288 def getAudioFR(tsn
=None):
289 return get_tsn('audio_fr', tsn
)
291 def getAudioLang(tsn
=None):
292 return get_tsn('audio_lang', tsn
)
294 def getCopyTS(tsn
=None):
295 return get_tsn('copy_ts', tsn
)
297 def getVideoFPS(tsn
=None):
298 return get_tsn('video_fps', tsn
)
300 # Parse a bitrate using the SI/IEEE suffix values as if by ffmpeg
301 # For example, 2K==2000, 2Ki==2048, 2MB==16000000, 2MiB==16777216
302 # Algorithm: http://svn.mplayerhq.hu/ffmpeg/trunk/libavcodec/eval.c
304 prefixes
= {'y': -24, 'z': -21, 'a': -18, 'f': -15, 'p': -12,
305 'n': -9, 'u': -6, 'm': -3, 'c': -2, 'd': -1,
306 'h': 2, 'k': 3, 'K': 3, 'M': 6, 'G': 9,
307 'T': 12, 'P': 15, 'E': 18, 'Z': 21, 'Y': 24}
308 p
= re
.compile(r
'^(\d+)(?:([yzafpnumcdhkKMGTPEZY])(i)?)?([Bb])?$')
311 raise SyntaxError('Invalid bit value syntax')
312 (coef
, prefix
, power
, byte
) = m
.groups()
316 exponent
= float(prefixes
[prefix
])
319 value
= float(coef
) * pow(2.0, exponent
/ 0.3)
322 value
= float(coef
) * pow(10.0, exponent
)
323 if byte
== 'B': # B == Byte, b == bit
328 if (config
.has_section('loggers') and
329 config
.has_section('handlers') and
330 config
.has_section('formatters')):
332 logging
.config
.fileConfig(config_files
)
335 logging
.basicConfig(level
=logging
.DEBUG
)
337 logging
.basicConfig(level
=logging
.INFO
)