title: Saving the openGL context as a video output
body: <p>I am currently trying to save the animation made in <code>openGL</code> to a video file. I have tried using <code>openCV</code>'s <code>videowriter</code> but to no advantage. I have successfully been able to generate a snapshot and save it as <code>bmp</code> using the <code>SDL</code> library. If I save all snapshots and then generate the video using <code>ffmpeg</code>, that is like collecting 4 GB worth of images. Not practical.
  How can I write video frames directly during rendering?
  Here the code i use to take snapshots when I require:</p>
  
  <pre><code>void snapshot(){
  SDL_Surface* snap = SDL_CreateRGBSurface(SDL_SWSURFACE,WIDTH,HEIGHT,24, 0x000000FF, 0x0000FF00, 0x00FF0000, 0);
  char * pixels = new char [3 *WIDTH * HEIGHT];
  glReadPixels(0, 0,WIDTH, HEIGHT, GL_RGB, GL_UNSIGNED_BYTE, pixels);
  
  for (int i = 0 ; i &lt;HEIGHT ; i++)
      std::memcpy( ((char *) snap-&gt;pixels) + snap-&gt;pitch * i, pixels + 3 * WIDTH * (HEIGHT-i - 1), WIDTH*3 );
  
  delete [] pixels;
  SDL_SaveBMP(snap, "snapshot.bmp");
  SDL_FreeSurface(snap);
  }
  </code></pre>
  
  <p>I need the video output. I have discovered that <code>ffmpeg</code> can be used to create videos from C++ code but have not been able to figure out the process. Please help!</p>
  
  <p><strong>EDIT</strong> : I have tried using <code>openCV</code> <code>CvVideoWriter</code> class but the program crashes ("<code>segmentation fault</code>") the moment it is declared.Compilation shows no errors ofcourse. Any suggestions to that?</p>
  
  <p><strong>SOLUTION FOR PYTHON USERS</strong> (Requires <code>Python2.7</code>,<code>python-imaging</code>,<code>python-opengl</code>,<code>python-opencv</code>, codecs of format you want to write to, I am on <code>Ubuntu 14.04 64-bit</code>): </p>
  
  <pre><code>def snap():
      pixels=[]
      screenshot = glReadPixels(0,0,W,H,GL_RGBA,GL_UNSIGNED_BYTE)
      snapshot = Image.frombuffer("RGBA",W,H),screenshot,"raw","RGBA",0,0)
      snapshot.save(os.path.dirname(videoPath) + "/temp.jpg")
      load = cv2.cv.LoadImage(os.path.dirname(videoPath) + "/temp.jpg")
      cv2.cv.WriteFrame(videoWriter,load)
  </code></pre>
  
  <p>Here <code>W</code> and <code>H</code> are the window dimensions (width,height). What is happening is I am using PIL to convert the raw pixels read from the <code>glReadPixels</code> command into a <code>JPEG</code> image. I am loading that JPEG into the <code>openCV</code> image and writing to the videowriter. I was having certain issues by directly using the PIL image into the videowriter (which would save millions of clock cycles of <code>I/O</code>), but right now I am not working on that. <code>Image</code> is a <code>PIL</code> module <code>cv2</code> is a <code>python-opencv</code> module.</p>