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("gmyth-stream.transcoder")
23 priority = 0 # negative values have higher priorities
24 name = None # to be used in requests
26 def __init__(self, params):
31 def params_first(self, key, default=None):
33 return self.params[key][0]
36 return self.params[key][0]
42 def get_mimetype(self):
43 mux = self.params_first("mux", "mpg")
48 return "video/x-msvideo"
50 return "application/octet-stream"
54 def start(self, outfile):
65 return '%s("%s", mux="%s", params=%s)' % \
66 (self.__class__.__name__,
67 self.params_first("uri", "None"),
68 self.params_first("mux", "mpg"),
75 class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
76 log = log.getLogger("gmyth-stream.request")
78 transcoders = utils.PluginSet(Transcoder)
81 def load_plugins_transcoders(cls, directory):
82 cls.transcoders.load_from_directory(directory)
84 if cls.def_transcoder is None and cls.transcoders:
85 cls.def_transcoder = cls.transcoders[0].name
86 # load_plugins_transcoders()
89 def do_dispatch(self, body):
92 pieces = urlparse.urlparse(self.path)
94 self.query = cgi.parse_qs(pieces[4])
98 elif self.path == "/shutdown.do":
99 self.serve_shutdown(body)
100 elif self.path == "/stop-transcoder.do":
101 self.serve_stop_transcoder(body)
102 elif self.path == "/status.do":
103 self.serve_status(body)
104 elif self.path == "/play.do":
105 self.serve_play(body)
106 elif self.path == "/stream.do":
107 self.serve_stream(body)
109 self.send_error(404, "File not found")
114 self.do_dispatch(True)
119 self.do_dispatch(False)
123 def _nav_items(self):
124 self.wfile.write("""\
125 <li><a href="/play.do">Play</a></li>
126 <li><a href="/status.do">Status</a></li>
127 <li><a href="/stop-transcoder.do">Stop transcoders</a></li>
128 <li><a href="/shutdown.do">Shutdown Server</a></li>
133 def serve_main(self, body):
134 self.send_response(200)
135 self.send_header("Content-Type", "text/html")
136 self.send_header('Connection', 'close')
139 self.wfile.write("""\
141 <head><title>GMyth-Streamer Server</title></head>
143 <h1>Welcome to GMyth-Streamer Server</h1>
147 self.wfile.write("""\
155 def serve_play(self, body):
156 self.send_response(200)
157 self.send_header("Content-Type", "text/html")
158 self.send_header('Connection', 'close')
161 self.wfile.write("""\
163 <head><title>GMyth-Streamer Server</title></head>
166 <form action="/stream.do" method="GET">
167 <input type="text" name="type" value="file" />://<input type="text" name="location" value=""/>
168 <input type="submit" />
173 self.wfile.write("""\
181 def serve_shutdown(self, body):
182 self.send_response(200)
183 self.send_header("Content-Type", "text/html")
184 self.send_header('Connection', 'close')
187 self.wfile.write("""\
189 <head><title>GMyth-Streamer Server Exited</title></head>
191 <h1>GMyth-Streamer is not running anymore</h1>
195 self.server.server_close()
199 def serve_stop_all_transcoders(self, body):
200 self.send_response(200)
201 self.send_header("Content-Type", "text/html")
202 self.send_header('Connection', 'close')
205 self.server.stop_transcoders()
206 self.wfile.write("""\
208 <head><title>GMyth-Streamer Server Stopped Transcoders</title></head>
210 <h1>GMyth-Streamer stopped running transcoders</h1>
214 self.wfile.write("""\
219 # serve_stop_all_transcoders()
222 def serve_stop_selected_transcoders(self, body, requests):
223 self.send_response(200)
224 self.send_header("Content-Type", "text/html")
225 self.send_header('Connection', 'close')
228 self.wfile.write("""\
230 <head><title>GMyth-Streamer Server Stopped Transcoders</title></head>
232 <h1>GMyth-Streamer stopped running transcoders:</h1>
235 transcoders = self.server.get_transcoders()
239 host, port = req.split(":")
246 for t, r in transcoders:
247 if r.client_address == addr:
249 self.wfile.write("""\
251 """ % (t, addr[0], addr[1]))
254 self.wfile.write("""\
259 self.wfile.write("""\
264 # serve_stop_selected_transcoders()
267 def serve_stop_transcoder(self, body):
268 req = self.query.get("request", None)
269 if req and "all" in req:
270 self.serve_stop_all_transcoders(body)
272 self.serve_stop_selected_transcoders(body, req)
274 self.serve_status(body)
275 # serve_stop_transcoder()
278 def serve_status(self, body):
279 self.send_response(200)
280 self.send_header("Content-Type", "text/html")
281 self.send_header('Connection', 'close')
284 self.wfile.write("""\
286 <head><title>GMyth-Streamer Server Status</title></head>
288 <h1>GMyth-Streamer Status</h1>
290 tl = self.server.get_transcoders()
292 self.wfile.write("<p>No running transcoder.</p>\n")
294 self.wfile.write("<p>Running transcoders:</p>\n")
295 self.wfile.write("""\
297 <li><a href="/stop-transcoder.do?request=all">[STOP ALL]</a></li>
299 for transcoder, request in tl:
300 self.wfile.write("""\
301 <li>%s: %s:%s <a href="/stop-transcoder.do?request=%s:%s">[STOP]</a></li>
302 """ % (transcoder, request.client_address[0], request.client_address[1],
303 request.client_address[0], request.client_address[1]))
305 self.wfile.write("""\
310 self.wfile.write("""\
318 def _get_transcoder(self):
319 # get transcoder option: mencoder is the default
320 request_transcoders = self.query.get("transcoder", ["mencoder"])
322 for t in request_transcoders:
323 transcoder = self.transcoders.get(t)
328 return self.transcoders[self.def_transcoder]
332 def serve_stream(self, body):
333 transcoder = self._get_transcoder()
335 obj = transcoder(self.query)
337 self.send_error(500, str(e))
340 self.send_response(200)
341 self.send_header("Content-Type", obj.get_mimetype())
342 self.send_header('Connection', 'close')
346 self.server.add_transcoders(self, obj)
347 obj.start(self.wfile)
348 self.server.del_transcoders(self, obj)
352 def log_request(self, code='-', size='-'):
353 self.log.info('"%s" %s %s', self.requestline, str(code), str(size))
357 def log_error(self, format, *args):
358 self.log.error("%s: %s" % (self.address_string(), format % args))
362 def log_message(self, format, *args):
363 self.log.info("%s: %s" % (self.address_string(), format % args))
369 class Server(SocketServer.ThreadingMixIn, BaseHTTPServer.HTTPServer):
370 log = log.getLogger("gmyth-streamer.server")
373 _lock = threading.RLock()
375 def serve_forever(self):
376 self.log.info("GMyth-Streamer serving HTTP on %s:%s" %
377 self.socket.getsockname())
380 self.handle_request()
381 except KeyboardInterrupt, e:
384 self.log.debug("Stopping all remaining transcoders...")
385 self.stop_transcoders()
386 self.log.debug("Transcoders stopped!")
390 def get_request(self):
392 old = skt.gettimeout()
399 except socket.timeout, e:
401 raise socket.error("Not running")
405 def server_close(self):
407 self.stop_transcoders()
409 BaseHTTPServer.HTTPServer.server_close(self)
413 def stop_transcoders(self):
415 for transcoder, request in self._transcoders.iteritems():
416 self.log.info("Stop transcoder: %s, client=%s" %
417 (transcoder, request.client_address))
423 def get_transcoders(self):
426 return self._transcoders.items()
432 def add_transcoders(self, request, transcoder):
435 self._transcoders[transcoder] = request
441 def del_transcoders(self, request, transcoder):
444 del self._transcoders[transcoder]
452 def serve_forever(host="0.0.0.0", port=40000):
455 RequestHandler.protocol_version = "HTTP/1.0"
456 httpd = Server(addr, RequestHandler)
457 httpd.serve_forever()
461 def load_plugins_transcoders(directory):
462 RequestHandler.load_plugins_transcoders(directory)
463 # load_plugins_transcoders()