Skip to content

Instantly share code, notes, and snippets.

@misaelnieto
Created April 17, 2012 23:18
Show Gist options
  • Save misaelnieto/2409815 to your computer and use it in GitHub Desktop.
Save misaelnieto/2409815 to your computer and use it in GitHub Desktop.
Streaming MJPEG over HTTP with gstreamr and python - WSGI version, No need for external process
#!/usr/bin/env python
#Works nicely, but wsgiserver times out aftr some time
#Python imports
import sys
import signal
from wsgiref.simple_server import make_server
#GStreamer imports
import pygst
pygst.require("0.10")
import gst
MJPEG_PIPELINE = "videotestsrc pattern=ball ! "\
"video/x-raw-rgb, framerate=15/1, width=640, height=480 ! "\
"jpegenc ! multipartmux boundary=spionisto ! "\
"appsink name=endpoint"
class MJPEGCamera(object):
pipeline = gst.parse_launch(MJPEG_PIPELINE)
def __init__(self):
self.endpoint = self.pipeline.get_by_name('endpoint')
self.pipeline.set_state(gst.STATE_PLAYING)
def next(self):
boundary = self.endpoint.emit('pull-buffer').data
data = self.endpoint.emit('pull-buffer').data
return boundary+data
def stop(self):
self.pipeline.set_state(gst.STATE_NULL)
def __iter__(self):
return self
INDEX_PAGE = """
<html>
<head>
<title>Gstreamer testing</title>
</head>
<body>
<h1>Testing a dummy camera with GStreamer</h1>
<img src="/mjpeg_stream"/>
<hr />
</body>
</html>
"""
ERROR_404 = """
<html>
<head>
<title>404 - Not Found</title>
</head>
<body>
<h1>404 - Not Found</h1>
</body>
</html>
"""
def application(environ, start_response):
if environ['PATH_INFO'] == '/':
start_response("200 OK", [
("Content-Type", "text/html"),
("Content-Length", str(len(INDEX_PAGE)))
])
return iter([INDEX_PAGE])
elif environ['PATH_INFO'] == '/mjpeg_stream':
start_response("200 OK", [
("Content-Type", "multipart/x-mixed-replace; boundary=--spionisto"),
])
return iter(MJPEGCamera())
else:
start_response("404 Not Found", [
("Content-Type", "text/html"),
("Content-Length", str(len(ERROR_404)))
])
return iter([ERROR_404])
if __name__ == '__main__':
#This looks for the port number as a comandline argument
args = sys.argv[1:]
if not args :
sys.exit('Usage: %s port_number' % __file__)
port = int(args[0])
#Launch an instance of wsgi server
print 'Launching camera server on port', port
httpd = make_server('', port, application)
try:
httpd.serve_forever()
except KeyboardInterrupt:
httpd.kill()
print "Shutdown camera server ..."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment