All most wotking TVBus stuff. Just need some stuff with times
[pyTivo.git] / plugins / video / video.py
blobbf1324c10d67ad6042971d34058a598ef885c94e
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
10 import config
12 SCRIPTDIR = os.path.dirname(__file__)
14 CLASS_NAME = 'Video'
16 class Video(Plugin):
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')
29 handler.end_headers()
30 handler.wfile.write("\x30\x0D\x0A")
31 return
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)
38 handler.end_headers()
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):
60 metadata = {}
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('#'):
66 continue
67 if not ':' in line:
68 continue
70 key, value = line.split(':', 1)
71 key = key.strip()
72 value = value.strip()
74 if key.startswith('v'):
75 if key in metadata:
76 metadata[key].append(value)
77 else:
78 metadata[key] = [value]
79 else:
80 metadata[key] = value
82 return metadata
84 def __metadata(self, full_path):
86 metadata = {}
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'
96 return metadata
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()
106 return
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):
112 return True
113 return transcode.suported_format(full_path)
115 files, total, start = self.get_files(handler, query, video_file_filter)
117 videos = []
118 for file in files:
119 path = self.get_local_path(handler, query)
120 full_path = os.path.join(path, file)
122 video = VideoDetails()
123 video['name'] = file
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))
130 videos.append(video)
132 handler.send_response(200)
133 handler.end_headers()
134 t = Template(file=os.path.join(SCRIPTDIR,'templates', 'container.tmpl'))
135 t.name = subcname
136 t.total = total
137 t.start = start
138 t.videos = videos
139 t.quote = quote
140 t.escape = escape
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))
155 print file_info
157 handler.send_response(200)
158 handler.end_headers()
159 t = Template(file=os.path.join(SCRIPTDIR,'templates', 'TvBus.tmpl'))
160 t.video = file_info
161 handler.wfile.write(t)
163 class VideoDetails(DictMixin):
165 def __init__(self, d = None):
166 if d:
167 self.d = d
168 else:
169 self.d = {}
171 def __getitem__(self, key):
172 if key not in self.d:
173 self.d[key] = self.default(key)
174 return self.d[key]
176 def __contains__(self, key):
177 return True
179 def __setitem__(self, key, value):
180 self.d[key] = value
182 def __delitem__(self):
183 del self.d[key]
185 def keys(self):
186 return self.d.keys()
188 def __iter__(self):
189 return self.d.__iter__()
191 def iteritems(self):
192 return self.d.iteritems()
194 def default(self, key):
195 defaults = {
196 'showingBits' : '0',
197 'episodeNumber' : '0',
198 'displayMajorNumber' : '0',
199 'displayMinorNumber' : '0',
200 'isEpisode' : 'true',
201 'colorCode' : ('COLOR', '4'),
202 'showType' : ('SERIES', '5'),
203 'tvRating' : ('NR', '7'),
205 if key in defaults:
206 return defaults[key]
207 elif key.startswith('v'):
208 return ['Default']
209 else:
210 return 'Default'
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
216 def strtod(value):
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])?$')
219 m = p.match(value)
220 if m is None:
221 raise SyntaxError('Invalid bit value syntax')
222 (coef, prefix, power, byte) = m.groups()
223 if prefix is None:
224 value = float(coef)
225 else:
226 exponent = float(prefixes[prefix])
227 if power == "i":
228 # Use powers of 2
229 value = float(coef) * pow(2.0, exponent/0.3)
230 else:
231 # Use powers of 10
232 value = float(coef) * pow(10.0, exponent)
233 if byte == "B": # B==Byte, b=bit
234 value *= 8;
235 return value