Skip to content

Instantly share code, notes, and snippets.

@mic159
Created January 20, 2015 13:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mic159/fa2181a69f9119871b87 to your computer and use it in GitHub Desktop.
Save mic159/fa2181a69f9119871b87 to your computer and use it in GitHub Desktop.
MJPEG client in PyGtk+
import pygtk
pygtk.require('2.0')
import gtk
import urllib
import gobject
import threading
STREAM_URL = 'http://10.10.1.1:8196/'
class VideoThread(threading.Thread):
'''
A background thread that takes the MJPEG stream and
updates the GTK image.
'''
def __init__(self, widget):
super(VideoThread, self).__init__()
self.widget = widget
self.quit = False
print 'connecting to', STREAM_URL
self.stream = urllib.urlopen(STREAM_URL)
def get_raw_frame(self):
'''
Parse an MJPEG http stream and yield each frame.
Source: http://stackoverflow.com/a/21844162
:return: generator of JPEG images
'''
raw_buffer = ''
while True:
new = self.stream.read(1034)
if not new:
# Connection dropped
yield None
raw_buffer += new
a = raw_buffer.find('\xff\xd8')
b = raw_buffer.find('\xff\xd9')
if a != -1 and b != -1:
frame = raw_buffer[a:b+2]
raw_buffer = raw_buffer[b+2:]
yield frame
def run(self):
for frame in self.get_raw_frame():
if self.quit or frame is None:
return
loader = gtk.gdk.PixbufLoader('jpeg')
loader.write(frame)
loader.close()
pixbuf = loader.get_pixbuf()
# Schedule image update to happen in main thread
gobject.idle_add(self.widget.set_from_pixbuf, pixbuf)
if __name__ == '__main__':
gobject.threads_init()
window = gtk.Window(gtk.WINDOW_TOPLEVEL)
window.connect("destroy", gtk.main_quit)
window.set_border_width(10)
img = gtk.Image()
img.show()
window.add(img)
t = VideoThread(img)
window.show()
t.start()
gtk.main()
t.quit = True
@Nick223
Copy link

Nick223 commented Jan 15, 2017

How can I stop reading the stream ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment