How to change the settings of AVCodecContext after initialization (FFMPEG)

I have a question about Libavcodec that I can't find the answer to online. I'm trying to use H.264 to encode frames. The issue I'm having is that the frames I wish to encode have variable widths and heights. I understand that to encode frames in Libavcodec, you need to pass a "width" and "height" parameter to the AvCodecContext struct, and then initialize it as such:

AVCodec *codec = codec = avcodec_find_encoder(AV_CODEC_ID_H264);
AVCodecContext *context = avcodec_alloc_context3(encoder->codec);
context->width = 1920;
//OTHER SETTINGS HERE
//FINALLY...
avcodec_open2(context, codec, NULL);

Let's say that, after I've initialized this context, I need to encode a different frame that now has a width of 900. I can't simply just do context->width = 900 because the context has already been set to width 1920 and initialized. I could create an entirely new AvCodecContext and delete the previous one with avcodec_close() as follows:

AVCodec *codec = codec = avcodec_find_encoder(AV_CODEC_ID_H264);
AVCodecContext *context = avcodec_alloc_context3(encoder->codec);
context->width = 900;
//OTHER SETTINGS HERE
//FINALLY...
avcodec_open2(context, codec, NULL);

// DO THE ENCODING HERE

avcodec_close(context);

But my program has been crashing unexpectedly when I do this, and I feel like recreating the AVCodecContext every time I need to change a simple width/height setting is inefficient to begin with. Does anyone have any suggestions as to how I can go about doing this? Thank you very much!


Solution 1:

That’s not a thing. You must reinitialize the encoder, or scale/pad the frames to the same size