Added a default metadata
[pyTivo.git] / plugins / video / video.py
blobf75e5dc1d6cd662b13f9f92990c407afa9e4fb5e
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 __getMetadataFromTxt(self, full_path):
60 metadata = {}
62 default_file = os.path.join(os.path.split(full_path)[0], 'default.txt')
63 description_file = full_path + '.txt'
65 metadata.update(self.__getMetadataFromFile(default_file))
66 metadata.update(self.__getMetadataFromFile(description_file))
68 return metadata
70 def __getMetadataFromFile(self, file):
71 metadata = {}
73 if os.path.exists(file):
74 for line in open(file):
75 if line.strip().startswith('#'):
76 continue
77 if not ':' in line:
78 continue
80 key, value = line.split(':', 1)
81 key = key.strip()
82 value = value.strip()
84 if key.startswith('v'):
85 if key in metadata:
86 metadata[key].append(value)
87 else:
88 metadata[key] = [value]
89 else:
90 metadata[key] = value
92 return metadata
94 def __metadata(self, full_path):
96 metadata = {}
98 base_path, title = os.path.split(full_path)
99 now = datetime.now()
100 originalAirDate = datetime.fromtimestamp(os.stat(full_path).st_ctime)
101 duration = self.__duration(full_path)
102 duration_delta = timedelta(milliseconds = duration)
104 metadata['title'] = '.'.join(title.split('.')[:-1])
105 metadata['seriesTitle'] = os.path.split(base_path)[1]
106 metadata['originalAirDate'] = originalAirDate.isoformat()
107 metadata['time'] = now.isoformat()
108 metadata['startTime'] = now.isoformat()
109 metadata['stopTime'] = (now + duration_delta).isoformat()
111 metadata.update( self.__getMetadataFromTxt(full_path) )
113 metadata['size'] = self.__est_size(full_path)
114 metadata['duration'] = duration
116 min = duration_delta.seconds / 60
117 sec = duration_delta.seconds % 60
118 hours = min / 60
119 min = min % 60
120 metadata['iso_durarion'] = 'P' + str(duration_delta.days) + 'DT' + str(hours) + 'H' + str(min) + 'M' + str(sec) + 'S'
122 return metadata
124 def QueryContainer(self, handler, query):
126 subcname = query['Container'][0]
127 cname = subcname.split('/')[0]
129 if not handler.server.containers.has_key(cname) or not self.get_local_path(handler, query):
130 handler.send_response(404)
131 handler.end_headers()
132 return
134 def video_file_filter(file, type = None):
135 full_path = file
136 if os.path.isdir(full_path):
137 return True
138 return transcode.suported_format(full_path)
140 files, total, start = self.get_files(handler, query, video_file_filter)
142 videos = []
143 for file in files:
144 video = VideoDetails()
145 video['name'] = os.path.split(file)[1]
146 video['path'] = file
147 video['title'] = os.path.split(file)[1]
148 video['is_dir'] = self.__isdir(file)
149 if not video['is_dir']:
150 video.update(self.__metadata(file))
152 videos.append(video)
154 handler.send_response(200)
155 handler.end_headers()
156 t = Template(file=os.path.join(SCRIPTDIR,'templates', 'container.tmpl'))
157 t.name = subcname
158 t.total = total
159 t.start = start
160 t.videos = videos
161 t.quote = quote
162 t.escape = escape
163 handler.wfile.write(t)
165 def TVBusQuery(self, handler, query):
167 file = query['File'][0]
168 path = self.get_local_path(handler, query)
169 file_path = os.path.join(path, file)
171 file_info = VideoDetails()
172 file_info.update(self.__metadata(file_path))
174 handler.send_response(200)
175 handler.end_headers()
176 t = Template(file=os.path.join(SCRIPTDIR,'templates', 'TvBus.tmpl'))
177 t.video = file_info
178 t.escape = escape
179 handler.wfile.write(t)
181 class VideoDetails(DictMixin):
183 def __init__(self, d = None):
184 if d:
185 self.d = d
186 else:
187 self.d = {}
189 def __getitem__(self, key):
190 if key not in self.d:
191 self.d[key] = self.default(key)
192 return self.d[key]
194 def __contains__(self, key):
195 return True
197 def __setitem__(self, key, value):
198 self.d[key] = value
200 def __delitem__(self):
201 del self.d[key]
203 def keys(self):
204 return self.d.keys()
206 def __iter__(self):
207 return self.d.__iter__()
209 def iteritems(self):
210 return self.d.iteritems()
212 def default(self, key):
213 defaults = {
214 'showingBits' : '0',
215 'episodeNumber' : '0',
216 'displayMajorNumber' : '0',
217 'displayMinorNumber' : '0',
218 'isEpisode' : 'true',
219 'colorCode' : ('COLOR', '4'),
220 'showType' : ('SERIES', '5'),
221 'tvRating' : ('NR', '7'),
223 if key in defaults:
224 return defaults[key]
225 elif key.startswith('v'):
226 return []
227 else:
228 return ''
231 # Parse a bitrate using the SI/IEEE suffix values as if by ffmpeg
232 # For example, 2K==2000, 2Ki==2048, 2MB==16000000, 2MiB==16777216
233 # Algorithm: http://svn.mplayerhq.hu/ffmpeg/trunk/libavcodec/eval.c
234 def strtod(value):
235 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}
236 p = re.compile(r'^(\d+)(?:([yzafpnumcdhkKMGTPEZY])(i)?)?([Bb])?$')
237 m = p.match(value)
238 if m is None:
239 raise SyntaxError('Invalid bit value syntax')
240 (coef, prefix, power, byte) = m.groups()
241 if prefix is None:
242 value = float(coef)
243 else:
244 exponent = float(prefixes[prefix])
245 if power == "i":
246 # Use powers of 2
247 value = float(coef) * pow(2.0, exponent/0.3)
248 else:
249 # Use powers of 10
250 value = float(coef) * pow(10.0, exponent)
251 if byte == "B": # B==Byte, b=bit
252 value *= 8;
253 return value