title: How to convert an FFMPEG AVFrame in YUVJ420P to AVFoundation cVPixelBufferRef?
body: <p>I have an FFMPEG <code>AVFrame</code> in <code>YUVJ420P</code> and I want to convert it to a <code>CVPixelBufferRef</code> with <code>CVPixelBufferCreateWithBytes</code>. The reason I want to do this is to use AVFoundation to show/encode the frames.</p>
  
  <p>I selected <code>kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange</code> and tried converting it since the AVFrame has the data in three planes
  <code>Y480</code> <code>Cb240</code> <code>Cr240</code>. And according to what I've researched this matches the selected <code>kCVPixelFormatType</code>. By being biplanar I need to convert it into a buffer that contains <code>Y480</code> and <code>CbCr480</code> Interleaved.</p>
  
  <p>I tried to create a buffer with 2 planes:</p>
  
  <ul>
  <li><code>frame-&gt;data[0]</code> on the first plane,</li>
  <li><code>frame-&gt;data[1]</code> and <code>frame-&gt;data[2]</code> interleaved on the second plane. </li>
  </ul>
  
  <p>However, I'm getting return error <code>-6661 (invalid a)</code> from <code>CVPixelBufferCreateWithBytes</code>:</p>
  
  <pre><code>"Invalid function parameter. For example, out of range or the wrong type."
  </code></pre>
  
  <p>I don't have expertise on image processing at all, so any pointers to documentation that can get me started in the right approach to this problem are appreciated. My C skills aren't top of the line either so maybe I'm making a basic mistake here.</p>
  
  <pre><code>    uint8_t **buffer = malloc(2*sizeof(int *));
      buffer[0] = frame-&gt;data[0];
      buffer[1] = malloc(frame-&gt;linesize[0]*sizeof(int));
      for(int i = 0; i&lt;frame-&gt;linesize[0]; i++){
          if(i%2){
              buffer[1][i]=frame-&gt;data[1][i/2];
          }else{
              buffer[1][i]=frame-&gt;data[2][i/2];
          }
      }
  
      int ret = CVPixelBufferCreateWithBytes(NULL, frame-&gt;width, frame-&gt;height, kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange, buffer, frame-&gt;linesize[0], NULL, 0, NULL, cvPixelBufferSample)
  </code></pre>
  
  <p>The frame is the <code>AVFrame</code> with the rawData from FFMPEG Decoding.</p>