[Libav-user] How to get interleaved raw RGB data from AVFrame objects?

B Aleck aleck099 at outlook.com
Sun Apr 10 06:53:04 EEST 2022

"interleaved raw RGB data" means:
<-- width-->

We can show that image by
$ ffplay -f rawvideo -pixel_format rgb24 -video_size WxH input.rgb

I wrote the following code trying to save an AVFrame object to file

f: the frame to save
px: pixel_format of f
width: width of target image
height: height of target image
fn: file name of target image
void save_rgb(const AVFrame* f, enum AVPixelFormat px, int width, int height, const char* fn) {
    struct SwsContext* sws = sws_getContext(f->width, f->height, px,
            width, height, AV_PIX_FMT_RGB24, SWS_BILINEAR, NULL, NULL, NULL);
    size_t imbufsize = width * height * 3;
    unsigned char* im_buf = (unsigned char*) malloc(imbufsize);
    uint8_t *rdata[4] = {im_buf, 0, 0, 0};
    int rlinesize[4] = {width, 0, 0, 0};
    sws_scale(sws, (const uint8_t* const*)(f->data), f->linesize, 0, f->height,
              rdata, rlinesize);

    FILE* fobj = fopen(fn, "wb");
    if (fobj) {
        fwrite(im_buf, 1, imbufsize, fobj);

But it gave strange output:
(What I expected is: https://imgur.com/nqaDp0r)

What's wrong with my code?

Reproduce steps:
$ git clone https://github.com/aleck099/santest
$ cd santest
$ gcc minimal.c -lavformat -lavcodec -lswscale -lavutil
$ ./a.out example.mp4 out.yuv out.rgb

More information about the Libav-user mailing list