title: Extract JPEG from MJPEG stream and Publish base64 encoded image over websocket
body: <p>I'm writing an application that proxies an mjpeg video stream. I thought it would be cool to extract each frame from the mjpeg that is pushed from the mjpeg server (the one that I am proxying from), base64 encode it and publish the frame over websockets to be rendered with as a data-uri image on the front end. That way clients that don't support mjpeg would be able to view the live video as a sequence of images.</p>
  
  <p>The problem is that I cant figure out how to extract the jpeg data from between the MJPEG boundaries. Here's what the boundaries (along with the headers) look like:</p>
  
  <pre><code>--------JPEG_FRAME_BOUNDARY
  Content-Type: image/jpeg
  Content-Length: 33377
  X-Frame-Epoc-HiRes: 1383166748.031929
  X-Frame-Timestamp: 2013-10-30T20:59:08.031929Z
  X-Resource-Status: active
  </code></pre>
  
  <p>on either side of those boundaries and headers is a bunch of garbled data that I assume is a raw jpeg image.</p>
  
  <p>I am fetching the mjpeg with a http request that responds with a series of chunks until the stream ends (after a minute or so).</p>
  
  <pre><code>var boundary = extractBoundary(response.headers['content-type'])
    , buffer   = [];
  
  response.on('data', function(chunk) {
      buffer.push(chunk);
  
      var frames = getFrames(buffer, boundary);
  
      if(frames[0]) {
          camera.set('data', "data:image/jpeg;base64," + frames[0]);
      }
      if(frames[1]) {
          buffer = [new Buffer(frames[1])];
      }
  });
  
  response.on('end', function() {
      console.log('done');
  });
  </code></pre>
  
  <p>Now I just need to figure out what "getFrames" has to do to check if the buffer contains a complete image and then return that image as a base64 encoded string along with the remaining chunk of the buffer (the bit that contains the next image header, on).</p>