1 import transcode
, os
, socket
, re
2 from Cheetah
.Template
import Template
3 from plugin
import Plugin
4 from urllib
import unquote_plus
, quote
, unquote
5 from urlparse
import urlparse
6 from xml
.sax
.saxutils
import escape
7 from lrucache
import LRUCache
8 from UserDict
import DictMixin
9 from datetime
import timedelta
12 SCRIPTDIR
= os
.path
.dirname(__file__
)
18 CONTENT_TYPE
= 'x-container/tivo-videos'
20 def send_file(self
, handler
, container
, name
):
22 #No longer a 'cheep' hack :p
23 if handler
.headers
.getheader('Range') and not handler
.headers
.getheader('Range') == 'bytes=0-':
24 handler
.send_response(206)
25 handler
.send_header('Connection', 'close')
26 handler
.send_header('Content-Type', 'video/x-tivo-mpeg')
27 handler
.send_header('Transfer-Encoding', 'chunked')
28 handler
.send_header('Server', 'TiVo Server/1.4.257.475')
30 handler
.wfile
.write("\x30\x0D\x0A")
33 tsn
= handler
.headers
.getheader('tsn', '')
35 o
= urlparse("http://fake.host" + handler
.path
)
36 path
= unquote_plus(o
[2])
37 handler
.send_response(200)
39 transcode
.output_video(container
['path'] + path
[len(name
)+1:], handler
.wfile
, tsn
)
42 def __isdir(self
, full_path
):
43 return os
.path
.isdir(full_path
)
45 def __duration(self
, full_path
):
46 return transcode
.video_info(full_path
)[4]
48 def __est_size(self
, full_path
):
49 #Size is estimated by taking audio and video bit rate adding 2%
51 if transcode
.tivo_compatable(full_path
): # Is TiVo compatible mpeg2
52 return int(os
.stat(full_path
).st_size
)
53 else: # Must be re-encoded
54 audioBPS
= strtod(config
.getAudioBR())
55 videoBPS
= strtod(config
.getVideoBR())
56 bitrate
= audioBPS
+ videoBPS
57 return int((self
.__duration
(full_path
)/1000)*(bitrate
* 1.02 / 8))
59 def __getMetadateFromTxt(self
, full_path
):
62 description_file
= full_path
+ '.txt'
63 if os
.path
.exists(description_file
):
64 for line
in open(description_file
):
65 if line
.strip().startswith('#'):
70 key
, value
= line
.split(':', 1)
74 if key
.startswith('v'):
76 metadata
[key
].append(value
)
78 metadata
[key
] = [value
]
84 def __metadata(self
, full_path
):
88 metadata
.update( self
.__getMetadateFromTxt
(full_path
) )
90 metadata
['size'] = self
.__est
_size
(full_path
)
91 metadata
['duration'] = self
.__duration
(full_path
)
93 duration
= timedelta(milliseconds
= metadata
['duration'])
94 metadata
['iso_durarion'] = 'P' + str(duration
.days
) + 'DT' + str(duration
.seconds
) + 'S'
98 def QueryContainer(self
, handler
, query
):
100 subcname
= query
['Container'][0]
101 cname
= subcname
.split('/')[0]
103 if not handler
.server
.containers
.has_key(cname
) or not self
.get_local_path(handler
, query
):
104 handler
.send_response(404)
105 handler
.end_headers()
108 def video_file_filter(file):
109 path
= self
.get_local_path(handler
, query
)
110 full_path
= os
.path
.join(path
, file)
111 if os
.path
.isdir(full_path
):
113 return transcode
.suported_format(full_path
)
115 files
, total
, start
= self
.get_files(handler
, query
, video_file_filter
)
119 path
= self
.get_local_path(handler
, query
)
120 full_path
= os
.path
.join(path
, file)
122 video
= VideoDetails()
124 video
['title'] = file
125 video
['is_dir'] = self
.__isdir
(full_path
)
126 if not video
['is_dir']:
127 video
['title'] = '.'.join(file.split('.')[:-1])
128 video
.update(self
.__metadata
(full_path
))
132 handler
.send_response(200)
133 handler
.end_headers()
134 t
= Template(file=os
.path
.join(SCRIPTDIR
,'templates', 'container.tmpl'))
141 handler
.wfile
.write(t
)
143 def TVBusQuery(self
, handler
, query
):
145 file = query
['File'][0]
146 path
= self
.get_local_path(handler
, query
)
147 file_path
= os
.path
.join(path
, file)
150 file_info
= VideoDetails()
151 file_info
['seriesTitle'] = os
.path
.split(path
)[-1]
152 file_info
['title'] = '.'.join(file.split('.')[:-1])
153 file_info
.update(self
.__metadata
(file_path
))
157 handler
.send_response(200)
158 handler
.end_headers()
159 t
= Template(file=os
.path
.join(SCRIPTDIR
,'templates', 'TvBus.tmpl'))
161 handler
.wfile
.write(t
)
163 class VideoDetails(DictMixin
):
165 def __init__(self
, d
= None):
171 def __getitem__(self
, key
):
172 if key
not in self
.d
:
173 self
.d
[key
] = self
.default(key
)
176 def __contains__(self
, key
):
179 def __setitem__(self
, key
, value
):
182 def __delitem__(self
):
189 return self
.d
.__iter
__()
192 return self
.d
.iteritems()
194 def default(self
, key
):
197 'episodeNumber' : '0',
198 'displayMajorNumber' : '0',
199 'displayMinorNumber' : '0',
200 'isEpisode' : 'true',
201 'colorCode' : ('COLOR', '4'),
202 'showType' : ('SERIES', '5'),
203 'tvRating' : ('NR', '7'),
207 elif key
.startswith('v'):
213 # Parse a bitrate using the SI/IEEE suffix values as if by ffmpeg
214 # For example, 2K==2000, 2Ki==2048, 2MB==16000000, 2MiB==16777216
215 # Algorithm: http://svn.mplayerhq.hu/ffmpeg/trunk/libavcodec/eval.c
217 prefixes
= {"y":-24,"z":-21,"a":-18,"f":-15,"p":-12,"n":-9,"u":-6,"m":-3,"c":-2,"d":-1,"h":2,"k":3,"K":3,"M":6,"G":9,"T":12,"P":15,"E":18,"Z":21,"Y":24}
218 p
= re
.compile(r
'^(\d+)(?:([yzafpnumcdhkKMGTPEZY])(i)?)?([Bb])?$')
221 raise SyntaxError('Invalid bit value syntax')
222 (coef
, prefix
, power
, byte
) = m
.groups()
226 exponent
= float(prefixes
[prefix
])
229 value
= float(coef
) * pow(2.0, exponent
/0.3)
232 value
= float(coef
) * pow(10.0, exponent
)
233 if byte
== "B": # B==Byte, b=bit