c++ffmpeglibavvideo-conversionvideo-codecs

FFmpeg avcodec_open2 throws -22 ("Invalid Argument")


I got stuck trying to write a simple video conversion using C++ and ffmpeg.

When trying to convert a video using FFmpeg, calling avcodec_open2 fails with the code "-22" which seems to be an "Invalid Argument"-error.

I can't figure out why it fails, nor what the invalid argument is. In the following snippet I create the output codec and pass its context the information from the source (code further down below).

The check for the "outputCodec" works and does not throw an error. As far as I know an "AVDictionary"-argument is optional. So I guess the reason for the error is the context.

    const AVCodec* outputCodec = avcodec_find_encoder_by_name(codecName.c_str());

    if (!outputCodec)
    {
        std::cout << "Zielformat-Codec nicht gefunden" << std::endl;
        return -1;
    }

    AVCodecContext* outputCodecContext = avcodec_alloc_context3(outputCodec);
    outputCodecContext->bit_rate = bitRate;
    outputCodecContext->width = inputCodecContext->width;
    outputCodecContext->height = inputCodecContext->height;
    outputCodecContext->pix_fmt = outputCodec->pix_fmts[0];
    outputCodecContext->time_base = inputCodecContext->time_base;

    **int errorCode = avcodec_open2(outputCodecContext, outputCodec, NULL); //THIS RETURNS -22**
    if (errorCode != 0)
    {
        std::cout << "Fehler beim Öffnen des Zielformat-Codecs" << std::endl;
        return -1;
    }

Here is the code for getting the input file & context:

    std::string inputFilename = "input_video.mp4";
    std::string outputFilename = "output.avi";
    std::string codecName = "mpeg4";
    int bitRate = 400000;

    AVFormatContext* inputFormatContext = NULL;
    if (avformat_open_input(&inputFormatContext, inputFilename.c_str(), NULL, NULL) != 0)
    {
        std::cout << "Fehler beim Öffnen der Eingabedatei" << std::endl;
        return -1;
    }

    [Do Video Stream Search)

    AVCodecParameters* inputCodecParameters = inputFormatContext->streams[videoStreamIndex]->codecpar;
    const AVCodec* inputCodec = avcodec_find_decoder(inputCodecParameters->codec_id);
    AVCodecContext* inputCodecContext = avcodec_alloc_context3(inputCodec);
    if (avcodec_parameters_to_context(inputCodecContext, inputCodecParameters) != 0)
    {
        std::cout << "Fehler beim Setzen des Eingabecodecs" << std::endl;
        return -1;
    }
    if (avcodec_open2(inputCodecContext, inputCodec, NULL) != 0)
    {
        std::cout << "Fehler beim Öffnen des Eingabecodecs" << std::endl;
        return -1;
    }

The purpose was simply to get started with ffmpeg in an own C++ project.

If it is of any need, I downloaded the ffmpeg libs from here. I used the gpl shared ones. The architecture is win x64. I referenced them through the project properties (additional libraries and so on).

I tried to convert a .mp4 video to an .avi video with an "mpeg4" compression. I also tried other compressions like "libx264" but none worked.

I searched for the problem on stackoverflow but could not find the exact same problem. While its purpose is different this post is about the same error code when calling avcodec_open2. But its solution is not working for me. I inspected the watch for the "outputContext" while running the code and the codec_id, codec_type and format is set. I use the time_base from the input file. According to my understanding, this should be equal to the source. So I can not find out what I am missing.

Thanks in advance and sorry for my english.

And for completion, here is the whole method:

int TestConvert()
{
    std::string inputFilename = "input_video.mp4";
    std::string outputFilename = "output.avi";
    std::string codecName = "mpeg4";
    int bitRate = 400000;

    AVFormatContext* inputFormatContext = NULL;
    if (avformat_open_input(&inputFormatContext, inputFilename.c_str(), NULL, NULL) != 0)
    {
        std::cout << "Fehler beim Öffnen der Eingabedatei" << std::endl;
        return -1;
    }

    int videoStreamIndex = -1;
    for (unsigned int i = 0; i < inputFormatContext->nb_streams; i++)
    {
        if (inputFormatContext->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
        {
            videoStreamIndex = i;
            break;
        }
    }

    AVCodecParameters* inputCodecParameters = inputFormatContext->streams[videoStreamIndex]->codecpar;
    const AVCodec* inputCodec = avcodec_find_decoder(inputCodecParameters->codec_id);
    AVCodecContext* inputCodecContext = avcodec_alloc_context3(inputCodec);
    if (avcodec_parameters_to_context(inputCodecContext, inputCodecParameters) != 0)
    {
        std::cout << "Fehler beim Setzen des Eingabecodecs" << std::endl;
        return -1;
    }
    if (avcodec_open2(inputCodecContext, inputCodec, NULL) != 0)
    {
        std::cout << "Fehler beim Öffnen des Eingabecodecs" << std::endl;
        return -1;
    }

    const AVCodec* outputCodec = avcodec_find_encoder_by_name(codecName.c_str());

    if (!outputCodec)
    {
        std::cout << "Zielformat-Codec nicht gefunden" << std::endl;
        return -1;
    }

    AVCodecContext* outputCodecContext = avcodec_alloc_context3(outputCodec);
    outputCodecContext->bit_rate = bitRate;
    outputCodecContext->width = inputCodecContext->width;
    outputCodecContext->height = inputCodecContext->height;
    outputCodecContext->pix_fmt = outputCodec->pix_fmts[0];
    outputCodecContext->time_base = inputCodecContext->time_base;

    int errorCode = avcodec_open2(outputCodecContext, outputCodec, NULL);
    if (errorCode != 0)
    {
        std::cout << "Fehler beim Öffnen des Zielformat-Codecs" << std::endl;
        return -1;
    }

    AVFormatContext* outputFormatContext = NULL;
    if (avformat_alloc_output_context2(&outputFormatContext, NULL, NULL, outputFilename.c_str()) != 0)
    {
        std::cout << "Fehler beim Erstellen des Ausgabe-Formats" << std::endl;
        return -1;
    }

    AVStream* outputVideoStream = avformat_new_stream(outputFormatContext, outputCodec);
    if (outputVideoStream == NULL)
    {
        std::cout << "Fehler beim Hinzufügen des Video-Streams zum Ausgabe-Format" << std::endl;
        return -1;
    }
    outputVideoStream->id = outputFormatContext->nb_streams - 1;
    AVCodecParameters* outputCodecParameters = outputVideoStream->codecpar;
    if (avcodec_parameters_from_context(outputCodecParameters, outputCodecContext) != 0)
    {
        std::cout << "Fehler beim Setzen des Ausgabe-Codecs" << std::endl;
        return -1;
    }

    if (!(outputFormatContext->oformat->flags & AVFMT_NOFILE))
    {
        if (avio_open(&outputFormatContext->pb, outputFilename.c_str(), AVIO_FLAG_WRITE) != 0)
        {
            std::cout << "Fehler beim Öffnen der Ausgabedatei" << std::endl;
            return -1;
        }
    }

    if (avformat_write_header(outputFormatContext, NULL) != 0)
    {
        std::cout << "Fehler beim Schreiben des Ausgabe-Formats in die Ausgabedatei" << std::endl;
        return -1;
    }

    AVPacket packet;
    int response;
    AVFrame* frame = av_frame_alloc();
    AVFrame* outputFrame = av_frame_alloc();
    while (av_read_frame(inputFormatContext, &packet) == 0)
    {
        if (packet.stream_index == videoStreamIndex)
        {
            response = avcodec_send_packet(inputCodecContext, &packet);
            while (response >= 0)
            {
                response = avcodec_receive_frame(inputCodecContext, frame);
                if (response == AVERROR(EAGAIN) || response == AVERROR_EOF)
                {
                    break;
                }
                else if (response < 0)
                {
                    std::cout << "Fehler beim Dekodieren des Video-Pakets" << std::endl;
                    return -1;
                }

                struct SwsContext* swsContext = sws_getContext(inputCodecContext->width, inputCodecContext->height, inputCodecContext->pix_fmt, outputCodecContext->width, outputCodecContext->height, outputCodecContext->pix_fmt, SWS_BILINEAR, NULL, NULL, NULL); if (!swsContext)
                {
                    std::cout << "Fehler beim Erstellen des SwsContext" << std::endl;
                    return -1;
                }
                sws_scale(swsContext, frame->data, frame->linesize, 0, inputCodecContext->height, outputFrame->data, outputFrame->linesize);
                sws_freeContext(swsContext);

                outputFrame->pts = frame->pts;
                outputFrame->pkt_dts = frame->pkt_dts;
                //outputFrame->pkt_duration = frame->pkt_duration;
                response = avcodec_send_frame(outputCodecContext, outputFrame);
                while (response >= 0)
                {
                    response = avcodec_receive_packet(outputCodecContext, &packet);
                    if (response == AVERROR(EAGAIN) || response == AVERROR_EOF)
                    {
                        break;
                    }
                    else if (response < 0)
                    {
                        std::cout << "Fehler beim Kodieren des Ausgabe-Frames" << std::endl;
                        return -1;
                    }

                    packet.stream_index = outputVideoStream->id;
                    av_packet_rescale_ts(&packet, outputCodecContext->time_base, outputVideoStream->time_base);
                    if (av_interleaved_write_frame(outputFormatContext, &packet) != 0)
                    {
                        std::cout << "Fehler beim Schreiben des Ausgabe-Pakets" << std::endl;
                        return -1;
                    }
                    av_packet_unref(&packet);
                }
            }
        }
        av_packet_unref(&packet);
    }

    av_write_trailer(outputFormatContext);
    avcodec_free_context(&inputCodecContext);
    avcodec_free_context(&outputCodecContext);
    avformat_close_input(&inputFormatContext);
    avformat_free_context(inputFormatContext);
    avformat_free_context(outputFormatContext);
    av_frame_free(&frame);
    av_frame_free(&outputFrame);

    return 0;

}

Solution

  • In this case, based on your imgur link, outputCodecContext->time_base is set to AVRational{0, 2} which is apparently invalid. I guess this is the cause.

    I use the time_base from the input file. According to my understanding, this should be equal to the source.

    I don't think so. The encoder timebase should be set according to your desired fps of the output video. If you want a 30fps video, your encoder timebase should be like AVRational{1, 30}. And you should also set the right framerate to the context.

    After all, you should rewrite your code as follows.

    int output_fps = 30; // Change this as you will
    outputCodecContext->time_base = AVRational{1, output_fps};
    outputCodecContext->framerate = AVRational{output_fps, 1};