title: Fastest way to render OpenGL texture into CGContext
body: <p>Here's the question in brief:</p>
  <p><strong>For some layer compositing, I have to render an OpenGL texture in a CGContext. What's the fastest way to do that?</strong></p>
  <p>Thoughts so far:</p>
  <p>Obviously,  calling renderInContext won't capture OpenGL content, and glReadPixels is too slow.</p>
  <p>For some 'context', I'm calling this method in a delegate class of a layer:</p>
  <pre><code>- (void) drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx
  </code></pre>
  <p>I've considered using a CVOpenGLESTextureCache, but that requires an additional rendering, and it seems like some complicated conversion would be necessary post-rendering.</p>
  <p>Here's my (terrible) implemention right now:</p>
  <pre><code>glBindRenderbuffer(GL_RENDERBUFFER, displayRenderbuffer);
  
  NSInteger x = 0, y = 0, width = backingWidth, height = backingHeight;
  NSInteger dataLength = width * height * 4;
  GLubyte *data = (GLubyte *) malloc(dataLength * sizeof(GLubyte));
  
  glPixelStorei(GL_PACK_ALIGNMENT, 4);
  glReadPixels(x, y, width, height, GL_RGBA, GL_UNSIGNED_BYTE, data);
  
  CGDataProviderRef ref = CGDataProviderCreateWithData(NULL, data, dataLength, NULL);
  CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB();
  CGImageRef iref = CGImageCreate(width, height, 8, 32, width * 4, colorspace, kCGBitmapByteOrder32Big | kCGImageAlphaPremultipliedLast,
                                  ref, NULL, true, kCGRenderingIntentDefault);
  
  CGFloat scale = self.contentScaleFactor;
  NSInteger widthInPoints, heightInPoints;
  widthInPoints = width / scale;
  heightInPoints = height / scale;
  
  CGContextSetBlendMode(context, kCGBlendModeCopy);
  CGContextDrawImage(context, CGRectMake(0.0, 0.0, widthInPoints, heightInPoints), iref);
  
  // Clean up
  free(data);
  CFRelease(ref);
  CFRelease(colorspace);
  CGImageRelease(iref);
  </code></pre>