Extension-based video_file_filter -- massive speedup
[pyTivo.git] / plugins / video / video.py
blob77401214c739a3f326113b95c180e987209255bd
1 import transcode, os, socket, re, urllib
2 from Cheetah.Template import Template
3 from plugin import Plugin, quote, unquote
4 from urlparse import urlparse
5 from xml.sax.saxutils import escape
6 from lrucache import LRUCache
7 from UserDict import DictMixin
8 from datetime import datetime, timedelta
9 import config
11 SCRIPTDIR = os.path.dirname(__file__)
13 CLASS_NAME = 'Video'
15 extfile = os.path.join(SCRIPTDIR, 'video.ext')
16 try:
17 extensions = file(extfile).read().split()
18 except:
19 extensions = None
21 class Video(Plugin):
23 CONTENT_TYPE = 'x-container/tivo-videos'
25 def video_file_filter(self, full_path, type=None):
26 if os.path.isdir(full_path):
27 return True
28 if extensions:
29 return os.path.splitext(full_path)[1].lower() in extensions
30 else:
31 return transcode.supported_format(full_path)
33 def send_file(self, handler, container, name):
34 if handler.headers.getheader('Range') and \
35 handler.headers.getheader('Range') != 'bytes=0-':
36 handler.send_response(206)
37 handler.send_header('Connection', 'close')
38 handler.send_header('Content-Type', 'video/x-tivo-mpeg')
39 handler.send_header('Transfer-Encoding', 'chunked')
40 handler.end_headers()
41 handler.wfile.write("\x30\x0D\x0A")
42 return
44 tsn = handler.headers.getheader('tsn', '')
46 o = urlparse("http://fake.host" + handler.path)
47 path = unquote(o[2])
48 handler.send_response(200)
49 handler.end_headers()
50 transcode.output_video(container['path'] + path[len(name) + 1:],
51 handler.wfile, tsn)
53 def __isdir(self, full_path):
54 return os.path.isdir(full_path)
56 def __duration(self, full_path):
57 return transcode.video_info(full_path)[4]
59 def __est_size(self, full_path, tsn = ''):
60 # Size is estimated by taking audio and video bit rate adding 2%
62 if transcode.tivo_compatable(full_path, tsn):
63 # Is TiVo-compatible mpeg2
64 return int(os.stat(full_path).st_size)
65 else:
66 # Must be re-encoded
67 audioBPS = config.strtod(config.getAudioBR(tsn))
68 videoBPS = config.strtod(config.getVideoBR(tsn))
69 bitrate = audioBPS + videoBPS
70 return int((self.__duration(full_path) / 1000) *
71 (bitrate * 1.02 / 8))
73 def __getMetadataFromTxt(self, full_path):
74 metadata = {}
76 default_file = os.path.join(os.path.split(full_path)[0], 'default.txt')
77 description_file = full_path + '.txt'
79 metadata.update(self.__getMetadataFromFile(default_file))
80 metadata.update(self.__getMetadataFromFile(description_file))
82 return metadata
84 def __getMetadataFromFile(self, file):
85 metadata = {}
87 if os.path.exists(file):
88 for line in open(file):
89 if line.strip().startswith('#'):
90 continue
91 if not ':' in line:
92 continue
94 key, value = line.split(':', 1)
95 key = key.strip()
96 value = value.strip()
98 if key.startswith('v'):
99 if key in metadata:
100 metadata[key].append(value)
101 else:
102 metadata[key] = [value]
103 else:
104 metadata[key] = value
106 return metadata
108 def __metadata(self, full_path, tsn =''):
109 metadata = {}
111 base_path, title = os.path.split(full_path)
112 now = datetime.now()
113 originalAirDate = datetime.fromtimestamp(os.stat(full_path).st_ctime)
114 duration = self.__duration(full_path)
115 duration_delta = timedelta(milliseconds = duration)
117 metadata['title'] = '.'.join(title.split('.')[:-1])
118 metadata['seriesTitle'] = metadata['title'] # default to the filename
119 metadata['originalAirDate'] = originalAirDate.isoformat()
120 metadata['time'] = now.isoformat()
121 metadata['startTime'] = now.isoformat()
122 metadata['stopTime'] = (now + duration_delta).isoformat()
124 metadata.update( self.__getMetadataFromTxt(full_path) )
126 metadata['size'] = self.__est_size(full_path, tsn)
127 metadata['duration'] = duration
129 min = duration_delta.seconds / 60
130 sec = duration_delta.seconds % 60
131 hours = min / 60
132 min = min % 60
133 metadata['iso_duration'] = 'P' + str(duration_delta.days) + \
134 'DT' + str(hours) + 'H' + str(min) + \
135 'M' + str(sec) + 'S'
136 return metadata
138 def QueryContainer(self, handler, query):
139 tsn = handler.headers.getheader('tsn', '')
140 subcname = query['Container'][0]
141 cname = subcname.split('/')[0]
143 if not handler.server.containers.has_key(cname) or \
144 not self.get_local_path(handler, query):
145 handler.send_response(404)
146 handler.end_headers()
147 return
149 files, total, start = self.get_files(handler, query,
150 self.video_file_filter)
152 videos = []
153 local_base_path = self.get_local_base_path(handler, query)
154 for file in files:
155 video = VideoDetails()
156 video['name'] = os.path.split(file)[1]
157 video['path'] = file
158 video['part_path'] = file.replace(local_base_path, '', 1)
159 video['title'] = os.path.split(file)[1]
160 video['is_dir'] = self.__isdir(file)
161 if not video['is_dir']:
162 video.update(self.__metadata(file, tsn))
164 videos.append(video)
166 handler.send_response(200)
167 handler.end_headers()
168 t = Template(file=os.path.join(SCRIPTDIR,'templates', 'container.tmpl'))
169 t.container = cname
170 t.name = subcname
171 t.total = total
172 t.start = start
173 t.videos = videos
174 t.quote = quote
175 t.escape = escape
176 handler.wfile.write(t)
178 def TVBusQuery(self, handler, query):
179 tsn = handler.headers.getheader('tsn', '')
180 file = query['File'][0]
181 path = self.get_local_path(handler, query)
182 file_path = path + file
184 file_info = VideoDetails()
185 file_info.update(self.__metadata(file_path, tsn))
187 handler.send_response(200)
188 handler.end_headers()
189 t = Template(file=os.path.join(SCRIPTDIR,'templates', 'TvBus.tmpl'))
190 t.video = file_info
191 t.escape = escape
192 handler.wfile.write(t)
194 class VideoDetails(DictMixin):
196 def __init__(self, d=None):
197 if d:
198 self.d = d
199 else:
200 self.d = {}
202 def __getitem__(self, key):
203 if key not in self.d:
204 self.d[key] = self.default(key)
205 return self.d[key]
207 def __contains__(self, key):
208 return True
210 def __setitem__(self, key, value):
211 self.d[key] = value
213 def __delitem__(self):
214 del self.d[key]
216 def keys(self):
217 return self.d.keys()
219 def __iter__(self):
220 return self.d.__iter__()
222 def iteritems(self):
223 return self.d.iteritems()
225 def default(self, key):
226 defaults = {
227 'showingBits' : '0',
228 'episodeNumber' : '0',
229 'displayMajorNumber' : '0',
230 'displayMinorNumber' : '0',
231 'isEpisode' : 'true',
232 'colorCode' : ('COLOR', '4'),
233 'showType' : ('SERIES', '5'),
234 'tvRating' : ('NR', '7')
236 if key in defaults:
237 return defaults[key]
238 elif key.startswith('v'):
239 return []
240 else:
241 return ''