I'm trying to use libavcodec to encode h264 video but avcodec_open2 returns -22 "Invalid argument" and I can't figure out why. Here is my code, which is mostly a copy from the encode example from libavcodec.
/* find the mpeg1video encoder */
const AVCodec* codec = avcodec_find_encoder(AV_CODEC_ID_H264);
if (!codec) {
fprintf(stderr, "Codec '%s' not found\n", "h.264");
exit(1);
}
AVCodecContext* codecContext = avcodec_alloc_context3(codec);
if (!codecContext) {
fprintf(stderr, "Could not allocate video codec context\n");
exit(1);
}
AVPacket* pkt = av_packet_alloc();
if (!pkt)
exit(1);
/* put sample parameters */
codecContext->bit_rate = 400000;
/* resolution must be a multiple of two */
codecContext->width = 1920;
codecContext->height = 1080;
/* frames per second */
codecContext->time_base = { 1, 25 };
codecContext->framerate = { 25, 1 };
/* emit one intra frame every ten frames
* check frame pict_type before passing frame
* to encoder, if frame->pict_type is AV_PICTURE_TYPE_I
* then gop_size is ignored and the output of encoder
* will always be I frame irrespective to gop_size
*/
codecContext->gop_size = 10;
codecContext->max_b_frames = 1;
codecContext->codec_type = AVMEDIA_TYPE_VIDEO;
codecContext->pix_fmt = AV_PIX_FMT_YUV420P;
if (codec->id == AV_CODEC_ID_H264)
av_opt_set(codecContext->priv_data, "profile", "baseline", 0);
/* open it */
int ret = avcodec_open2(codecContext, codec, nullptr);
if (ret < 0) {
char eb[AV_ERROR_MAX_STRING_SIZE];
fprintf(stderr, "Could not open codec: %s\n", av_make_error_string(eb, AV_ERROR_MAX_STRING_SIZE, ret));
exit(1);
}
Does anyone know what I'm doing wrong?
Turns out that for "h264_mf" codec you need a capital "B" in "Baseline".