3 __author__ = "Gustavo Sverzut Barbieri / Artur Duque de Souza"
4 __author_email__ = "barbieri@gmail.com / artur.souza@indt.org.br"
15 import lib.utils as utils
18 __all__ = ("Transcoder", "RequestHandler", "Server", "serve_forever",
19 "load_plugins_transcoders")
21 class Transcoder(object):
22 log = log.getLogger("gms.transcoder")
23 priority = 0 # negative values have higher priorities
24 name = None # to be used in requests
27 def __init__(self, params):
32 def params_first(self, key, default=None):
34 return self.params[key][0]
37 return self.params[key][0]
43 def get_mimetype(self):
44 mux = self.params_first("mux", "mpg")
49 return "video/x-msvideo"
51 return "application/octet-stream"
55 def start(self, outfile):
66 return '%s( params=%s )' % \
67 (self.__class__.__name__,
74 class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
75 log = log.getLogger("gms.request")
77 transcoders = utils.PluginSet(Transcoder)
80 "Stop": "/stop-transcoder.do",
81 "Status": "/status.do",
82 "Version": "/version.do",
83 "Shutdown": "/shutdown.do"
87 def load_plugins_transcoders(cls, directory):
88 cls.transcoders.load_from_directory(directory)
90 if cls.def_transcoder is None and cls.transcoders:
91 cls.def_transcoder = cls.transcoders[0].name
92 # load_plugins_transcoders()
95 def do_dispatch(self, body):
98 pieces = urlparse.urlparse(self.path)
100 self.query = cgi.parse_qs(pieces[4])
103 self.serve_main(body)
104 elif self.path == "/shutdown.do":
105 self.serve_shutdown(body)
106 elif self.path == "/stop-transcoder.do":
107 self.serve_stop_transcoder(body)
108 elif self.path == "/status.do":
109 self.serve_status(body)
110 elif self.path == "/version.do":
111 self.serve_version(body)
112 elif self.path == "/stream.do":
113 self.serve_stream(body)
115 action = self.query.get("action", None)
116 if "stream.do" in action:
117 self.serve_stream(body)
119 self.send_error(404, "File not found")
124 self.do_dispatch(True)
129 self.do_dispatch(False)
133 def _nav_items(self):
135 for name, url in self.menu.items():
136 ret += utils.getHTML("menu", {"name": name, "url": url})
141 def serve_main(self, body):
142 self.send_response(200)
143 self.send_header("Content-Type", "text/html")
144 self.send_header('Connection', 'close')
147 self.wfile.write(utils.getHTML("index", {"menu": self._nav_items()}))
150 def serve_version(self, body):
151 self.send_response(200)
152 self.send_header("Content-Type", "text/html")
153 self.send_header('Connection', 'close')
156 self.wfile.write("Version: %s" % __version__)
159 def serve_shutdown(self, body):
160 self.send_response(200)
161 self.send_header("Content-Type", "text/html")
162 self.send_header('Connection', 'close')
165 self.wfile.write(utils.getHTML("shutdown"))
166 self.server.server_close()
170 def serve_stop_all_transcoders(self, body):
171 self.send_response(200)
172 self.send_header("Content-Type", "text/html")
173 self.send_header('Connection', 'close')
176 self.server.stop_transcoders()
177 self.wfile.write(utils.getHTML("stop_all", {"menu": self._nav_items()}))
178 # serve_stop_all_transcoders()
181 def serve_stop_selected_transcoders(self, body, requests):
182 self.send_response(200)
183 self.send_header("Content-Type", "text/html")
184 self.send_header('Connection', 'close')
188 transcoders = self.server.get_transcoders()
192 host, port = req.split(":")
199 for t, r in transcoders:
200 if r.client_address == addr:
204 self.log.info("Plugin already stopped")
206 opts += self._create_html_item("%s: %s:%s" % (
207 t, addr[0], addr[1]))
211 self.wfile.write(utils.getHTML("stop_selected",
212 {"menu": self._nav_items(),
214 # serve_stop_selected_transcoders()
217 def serve_stop_transcoder(self, body):
218 req = self.query.get("request", None)
219 if req and "all" in req:
220 self.serve_stop_all_transcoders(body)
222 self.serve_stop_selected_transcoders(body, req)
224 self.serve_status(body)
225 # serve_stop_transcoder()
228 def serve_status(self, body):
229 self.send_response(200)
230 self.send_header("Content-Type", "text/html")
231 self.send_header('Connection', 'close')
236 tl = self.server.get_transcoders()
238 running = "<p>No running transcoder.</p>\n"
241 elif self.query.get("ip") and self.query.get("file"):
242 for transcoder, request in tl:
243 filename = "%s" % self.query.get("file")[0]
244 tfilename = "%s" % transcoder.params_first("uri")
246 if tfilename.find(filename) >= 0 and \
247 request.client_address[0] == self.query.get("ip")[0]:
248 self.wfile.write("Status: %s %%" % transcoder.status)
254 running = "<p>Running transcoders:</p>\n"
255 stopall = utils._create_html_item("<a href='%s?request=all'>"
259 for transcoder, request in tl:
260 stopone += utils._create_html_item("%s: %s:%s<a href='%s?"
265 transcoder, request.client_address[0],
266 request.client_address[1],
267 self.menu["Stop"], request.client_address[0],
268 request.client_address[1],
271 self.wfile.write(utils.getHTML("status",
272 {"menu": self._nav_items(),
275 "stopone": stopone}))
279 def _get_transcoder(self):
280 # get transcoder option: mencoder is the default
281 request_transcoders = self.query.get("transcoder", ["mencoder"])
283 for t in request_transcoders:
284 transcoder = self.transcoders.get(t)
289 return self.transcoders[self.def_transcoder]
293 def serve_stream(self, body):
294 transcoder = self._get_transcoder()
296 obj = transcoder(self.query)
298 self.send_error(500, str(e))
301 self.send_response(200)
302 self.send_header("Content-Type", obj.get_mimetype())
303 self.send_header('Connection', 'close')
307 self.server.add_transcoders(self, obj)
308 obj.start(self.wfile)
309 self.server.del_transcoders(self, obj)
313 def log_request(self, code='-', size='-'):
314 self.log.info('"%s" %s %s', self.requestline, str(code), str(size))
318 def log_error(self, format, *args):
319 self.log.error("%s: %s" % (self.address_string(), format % args))
323 def log_message(self, format, *args):
324 self.log.info("%s: %s" % (self.address_string(), format % args))
330 class Server(SocketServer.ThreadingMixIn, BaseHTTPServer.HTTPServer):
331 log = log.getLogger("gms.server")
334 _lock = threading.RLock()
336 def serve_forever(self):
337 self.log.info("GMyth-Streamer serving HTTP on %s:%s" %
338 self.socket.getsockname())
341 self.handle_request()
342 except KeyboardInterrupt, e:
345 self.log.debug("Stopping all remaining transcoders...")
346 self.stop_transcoders()
347 self.log.debug("Transcoders stopped!")
351 def get_request(self):
353 old = skt.gettimeout()
360 except socket.timeout, e:
362 raise socket.error("Not running")
366 def server_close(self):
368 self.stop_transcoders()
370 BaseHTTPServer.HTTPServer.server_close(self)
374 def stop_transcoders(self):
376 for transcoder, request in self._transcoders.iteritems():
377 self.log.info("Stop transcoder: %s, client=%s" %
378 (transcoder, request.client_address))
384 def get_transcoders(self):
387 return self._transcoders.items()
393 def add_transcoders(self, request, transcoder):
396 self._transcoders[transcoder] = request
402 def del_transcoders(self, request, transcoder):
405 del self._transcoders[transcoder]
413 def serve_forever(host="0.0.0.0", port=40000):
415 RequestHandler.protocol_version = "HTTP/1.0"
416 httpd = Server(addr, RequestHandler)
417 httpd.serve_forever()
421 def load_plugins_transcoders(directory):
422 RequestHandler.load_plugins_transcoders(directory)
423 # load_plugins_transcoders()