Search code examples
cimage-processingffmpeglibavcodeclibav

libav: Filling AVFrame with RGB24 sample data?


I am trying to fill sample data for a AVFrame initialized with RGB24 format. I use following code snippet to populate RGB data. But in the encoded video,I can only see grayscale strip covering only 1/3 of the videoframe. This code snippet suppose to fill only Red color. Any tips what Im doing wrong here ?

AVFrame *targetFrame=.....
int height=imageHeight();
int width=imageWidth();


  for(y=0;y<encoder.getVideoParams().height ;y++){   
       for(x=0;x< encoder.getVideoParams().width;x++){


   targetFrame->data[0][(y* width)+x]=(x%255); //R  
   targetFrame->data[0][(y* width)+x+1]=0;     //G
   targetFrame->data[0][(y* width)+x+2]=0;     //B


  }
   }

Solution

  • If you're using RGB24, you need to scale the coordinates before indexing into the data buffer. Here's a version of your inner loop that'll do it properly:

    int offset = 3 * (x + y * width);
    targetFrame->data[0][offset + 0] = x % 255; // R
    targetFrame->data[0][offset + 1] = 0; // G
    targetFrame->data[0][offset + 2] = 0; // B
    

    And here's a simpler approach:

    uint8_t *p = targetFrame->data[0];
    for(y = 0; y < encoder.getVideoParams().height; y++) {  
        for(x = 0; x < encoder.getVideoParams().width; x++) {
            *p++ = x % 255; // R
            *p++ = 0; // G
            *p++ = 0; // B
        }
    }