Now sending good datetimes, title fixed on display
[pyTivo.git] / plugins / video / video.py
blobadf5b1302f5c6e36f15995254f6d7ad80f2af9d0
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 datetime, 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 base_path, title = os.path.split(full_path)
89 now = datetime.now()
90 originalAirDate = datetime.fromtimestamp(os.stat(full_path).st_ctime)
91 duration = self.__duration(full_path)
92 duration_delta = timedelta(milliseconds = duration)
94 metadata['title'] = '.'.join(title.split('.')[:-1])
95 metadata['seriesTitle'] = os.path.split(base_path)[1]
96 metadata['originalAirDate'] = originalAirDate.isoformat()
97 metadata['time'] = now.isoformat()
98 metadata['startTime'] = now.isoformat()
99 metadata['stopTime'] = (now + duration_delta).isoformat()
101 metadata.update( self.__getMetadateFromTxt(full_path) )
103 metadata['size'] = self.__est_size(full_path)
104 metadata['duration'] = duration
106 min = duration_delta.seconds / 60
107 sec = duration_delta.seconds % 60
108 hours = min / 60
109 min = min % 60
110 metadata['iso_durarion'] = 'P' + str(duration_delta.days) + 'DT' + str(hours) + 'H' + str(min) + 'M' + str(sec) + 'S'
112 return metadata
114 def QueryContainer(self, handler, query):
116 subcname = query['Container'][0]
117 cname = subcname.split('/')[0]
119 if not handler.server.containers.has_key(cname) or not self.get_local_path(handler, query):
120 handler.send_response(404)
121 handler.end_headers()
122 return
124 def video_file_filter(file):
125 path = self.get_local_path(handler, query)
126 full_path = os.path.join(path, file)
127 if os.path.isdir(full_path):
128 return True
129 return transcode.suported_format(full_path)
131 files, total, start = self.get_files(handler, query, video_file_filter)
133 videos = []
134 for file in files:
135 path = self.get_local_path(handler, query)
136 full_path = os.path.join(path, file)
138 video = VideoDetails()
139 video['name'] = file
140 video['title'] = file
141 video['is_dir'] = self.__isdir(full_path)
142 if not video['is_dir']:
143 video['title'] = '.'.join(file.split('.')[:-1])
144 video.update(self.__metadata(full_path))
146 videos.append(video)
148 handler.send_response(200)
149 handler.end_headers()
150 t = Template(file=os.path.join(SCRIPTDIR,'templates', 'container.tmpl'))
151 t.name = subcname
152 t.total = total
153 t.start = start
154 t.videos = videos
155 t.quote = quote
156 t.escape = escape
157 handler.wfile.write(t)
159 def TVBusQuery(self, handler, query):
161 file = query['File'][0]
162 path = self.get_local_path(handler, query)
163 file_path = os.path.join(path, file)
166 file_info = VideoDetails()
167 file_info.update(self.__metadata(file_path))
169 print file_info
171 handler.send_response(200)
172 handler.end_headers()
173 t = Template(file=os.path.join(SCRIPTDIR,'templates', 'TvBus.tmpl'))
174 t.video = file_info
175 handler.wfile.write(t)
177 class VideoDetails(DictMixin):
179 def __init__(self, d = None):
180 if d:
181 self.d = d
182 else:
183 self.d = {}
185 def __getitem__(self, key):
186 if key not in self.d:
187 self.d[key] = self.default(key)
188 return self.d[key]
190 def __contains__(self, key):
191 return True
193 def __setitem__(self, key, value):
194 self.d[key] = value
196 def __delitem__(self):
197 del self.d[key]
199 def keys(self):
200 return self.d.keys()
202 def __iter__(self):
203 return self.d.__iter__()
205 def iteritems(self):
206 return self.d.iteritems()
208 def default(self, key):
209 defaults = {
210 'showingBits' : '0',
211 'episodeNumber' : '0',
212 'displayMajorNumber' : '0',
213 'displayMinorNumber' : '0',
214 'isEpisode' : 'true',
215 'colorCode' : ('COLOR', '4'),
216 'showType' : ('SERIES', '5'),
217 'tvRating' : ('NR', '7'),
219 if key in defaults:
220 return defaults[key]
221 elif key.startswith('v'):
222 return [key + '1', key + '2']
223 else:
224 return key
227 # Parse a bitrate using the SI/IEEE suffix values as if by ffmpeg
228 # For example, 2K==2000, 2Ki==2048, 2MB==16000000, 2MiB==16777216
229 # Algorithm: http://svn.mplayerhq.hu/ffmpeg/trunk/libavcodec/eval.c
230 def strtod(value):
231 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}
232 p = re.compile(r'^(\d+)(?:([yzafpnumcdhkKMGTPEZY])(i)?)?([Bb])?$')
233 m = p.match(value)
234 if m is None:
235 raise SyntaxError('Invalid bit value syntax')
236 (coef, prefix, power, byte) = m.groups()
237 if prefix is None:
238 value = float(coef)
239 else:
240 exponent = float(prefixes[prefix])
241 if power == "i":
242 # Use powers of 2
243 value = float(coef) * pow(2.0, exponent/0.3)
244 else:
245 # Use powers of 10
246 value = float(coef) * pow(10.0, exponent)
247 if byte == "B": # B==Byte, b=bit
248 value *= 8;
249 return value