MJPEG Streaming Protocol

MJPEG is a popular format for webcam streams. It's probably popular because it's so simple to do and the performance is surprisingly good. Unfortunately, I found it quite difficult to scrape together enough information to implement a streamer myself. In an effort to help the next poor, frustrated soul, here's a simple method for streaming an MJPEG to a socket in Java.
public void handleConnection(Socket socket, JpegProvider jpegProvider) throws Exception {
  byte[] data = jpegProvider.getJpeg();
  OutputStream outputStream = socket.getOutputStream();
  outputStream.write((
      "HTTP/1.0 200 OK\r\n" +
      "Server: YourServerName\r\n" +
      "Connection: close\r\n" +
      "Max-Age: 0\r\n" +
      "Expires: 0\r\n" +
      "Cache-Control: no-cache, private\r\n" + 
      "Pragma: no-cache\r\n" + 
      "Content-Type: multipart/x-mixed-replace; " +
      "boundary=--BoundaryString\r\n\r\n").getBytes());
  while (true) {
    data = jpegProvider.getJpeg();
    outputStream.write((
        "--BoundaryString\r\n" +
        "Content-type: image/jpg\r\n". +
        "Content-Length: " +
        data.length +
        "\r\n\r\n").getBytes());
    outputStream.write(data);
    outputStream.write("\r\n\r\n".getBytes());
    outputStream.flush();
  }
}

2 comments:

  1. Hi,

    Good at least you can control yourself the stream and not from other application.
    You know how to do the reverse? Receive the stream and show the video stream on the LCD of the Tablet or smartphone.

    ReplyDelete