FFmpeg将编码后数据保存成mp4

这篇具有很好参考价值的文章主要介绍了FFmpeg将编码后数据保存成mp4。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

      以下测试代码实现的功能是:持续从内存块中获取原始数据,然后依次进行解码、编码、最后保存成mp4视频文件。

      可保存成单个视频文件,也可指定每个视频文件的总帧数,保存多个视频文件。

      为了便于查看和修改,这里将可独立的程序段存放在单个函数中:

      1.线程函数set_packet:独立线程,用于用户向指定的内存块中持续写入数据,这里通过调用队列类PacketScaleQueue,可参考:https://blog.csdn.net/fengbingchun/article/details/132128885 中说明。这里填充的数据参考FFmpeg源码中的doc/examples/encode_video.c:每次向队列中写入一帧数据

void set_packet(PacketScaleQueue& packet_encode)
{
    while (packet_encode_flag) {
        Buffer buffer;
        packet_encode.popPacket(buffer);
        static int i = 0;
    
        // refrence: ffmpeg/doc/examples/encode_video.c
        // prepare a dummy image: Y
        unsigned char* p1 = buffer.data;
        for (auto y = 0; y < height; ++y) {
            for (auto x = 0; x < width; ++x) {
                p1[y * width + x] = x + y + i * 3;
            }
        }

        // Cb and Cr
        unsigned char* p2 = buffer.data + width * height;
        unsigned char* p3 = buffer.data + width * height + width * height / 4;
        for (auto y = 0; y < height / 2; ++y) {
            for (auto x = 0; x < width / 2; ++x) {
                p2[y * width / 2 + x] = 128 + y + i * 2;
                p3[y * width / 2 + x] = 64 + x + i * 5;
            }
        }

        packet_encode.pushScale(buffer);

        if (++i > 25) i = 0;
        std::this_thread::sleep_for(std::chrono::milliseconds(40));
    }
}

      2.回调函数read_packet:avio_alloc_context中使用,不断从队列中获取数据,av_read_frame中也会从这里获取数据:每次从队列中获取一帧数据

int read_packet(void* opaque, uint8_t* buf, int buf_size)
{
    PacketScaleQueue* packet_encode = static_cast<PacketScaleQueue*>(opaque);
    Buffer buffer;
    packet_encode->popScale(buffer);
    memcpy(buf, buffer.data, buf_size);
    packet_encode->pushPacket(buffer);

    return buf_size;
}

      3.函数get_input_format_context:创建输入AVFormatContext,需要调用av_dict_set设置video_size和pixel_format

AVFormatContext* get_input_format_context(AVIOContext* avio_ctx)
{
    AVFormatContext* ifmt_ctx = avformat_alloc_context();
    if (!ifmt_ctx) {
        print_error_string(AVERROR(ENOMEM));
        return nullptr;
    }
    ifmt_ctx->pb = avio_ctx;

    AVDictionary* dict = nullptr;
    av_dict_set(&dict, "video_size", video_size, 0);
    av_dict_set(&dict, "pixel_format", pixel_format, 0);

    auto ret = avformat_open_input(&ifmt_ctx, nullptr, av_find_input_format("rawvideo"), &dict);
    if (ret < 0) {
        fprintf(stderr, "Could not open input\n");
        print_error_string(ret);
        return nullptr;
    }
    av_dict_free(&dict);

    ret = avformat_find_stream_info(ifmt_ctx, nullptr);
    if (ret < 0) {
        fprintf(stderr, "Could not find stream information\n");
        print_error_string(ret);
        return nullptr;
    }

    for (unsigned int i = 0; i < ifmt_ctx->nb_streams; ++i) {
        const AVStream* stream = ifmt_ctx->streams[i];
        if (stream->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
            video_stream_index = i;
            fprintf(stdout, "type of the encoded data: %d, dimensions of the video frame in pixels: width: %d, height: %d, pixel format: %d\n",
                stream->codecpar->codec_id, stream->codecpar->width, stream->codecpar->height, stream->codecpar->format);
        }
    }

    if (video_stream_index == -1) {
        fprintf(stderr, "error: no video stream\n");
        return nullptr;
    }

    if (ifmt_ctx->streams[video_stream_index]->codecpar->codec_id != AV_CODEC_ID_RAWVIDEO) {
        fprintf(stderr, "error: this test code only support rawvideo encode: %d\n", ifmt_ctx->streams[video_stream_index]->codecpar->codec_id);
        return nullptr;
    }

    av_dump_format(ifmt_ctx, 0, "nothing", 0);
    return ifmt_ctx;
}

      4.函数get_decode_context:创建解码AVCodecContext

AVCodecContext* get_decode_context(AVFormatContext* ifmt_ctx)
{
    AVCodec* decoder = nullptr;
    auto ret = av_find_best_stream(ifmt_ctx, AVMEDIA_TYPE_VIDEO, -1, -1, &decoder, 0);
    if (ret < 0) {
        fprintf(stderr, "fail to av_find_best_stream: %d\n", ret);
        print_error_string(ret);
        return nullptr;
    }

    AVCodecContext* dec_ctx = avcodec_alloc_context3(decoder);
    if (!dec_ctx) {
        fprintf(stderr, "fail to avcodec_alloc_context3\n");
        return nullptr;
    }

    ret = avcodec_parameters_to_context(dec_ctx, ifmt_ctx->streams[video_stream_index]->codecpar);
    if (ret < 0) {
        fprintf(stderr, "fail to avcodec_parameters_to_context: %d\n", ret);
        print_error_string(ret);
        return nullptr;
    }

    dec_ctx->framerate = av_guess_frame_rate(ifmt_ctx, ifmt_ctx->streams[video_stream_index], nullptr);
    ret = avcodec_open2(dec_ctx, decoder, nullptr);
    if (ret != 0) {
        fprintf(stderr, "fail to avcodec_open2: %d\n", ret);
        print_error_string(ret);
        return nullptr;
    }

    return dec_ctx;
}

      5.函数get_encode_context:创建编码AVCodecContext,注意对enc_ctx的相关成员的赋值

AVCodecContext* get_encode_context(AVFormatContext* ifmt_ctx)
{
    AVCodec* encodec = avcodec_find_encoder_by_name("mpeg1video"); // ffmpeg.exe -encoders
    if (!encodec) {
        fprintf(stderr, "fail to avcodec_find_encoder_by_name\n");
        return nullptr;
    }

    AVCodecContext* enc_ctx = avcodec_alloc_context3(encodec);
    if (!enc_ctx) {
        fprintf(stderr, "fail to avcodec_alloc_context3\n");
        return nullptr;
    }

    enc_ctx->bit_rate = 400000;
    enc_ctx->framerate = ifmt_ctx->streams[video_stream_index]->r_frame_rate;
    enc_ctx->pix_fmt = AV_PIX_FMT_YUV420P;
    enc_ctx->height = ifmt_ctx->streams[video_stream_index]->codecpar->height;
    enc_ctx->width = ifmt_ctx->streams[video_stream_index]->codecpar->width;
    enc_ctx->time_base = av_inv_q(av_d2q(frame_rate, 4096));
    enc_ctx->max_b_frames = 1;

    //if (ofmt_ctx->oformat->flags & AVFMT_GLOBALHEADER) // true
    enc_ctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;

    auto ret = avcodec_open2(enc_ctx, encodec, nullptr);
    if (ret != 0) {
        fprintf(stderr, "fail to avcodec_open2: %d\n", ret);
        print_error_string(ret);
        return nullptr;
    }

    return enc_ctx;
}

      6.函数get_output_format_context:创建输出AVFormatContext

AVFormatContext* get_output_format_context(const AVCodecContext* enc_ctx, const char* filename)
{
    AVFormatContext* ofmt_ctx = nullptr;
    auto ret = avformat_alloc_output_context2(&ofmt_ctx, nullptr, nullptr, filename);
    if (ret < 0 || !ofmt_ctx) {
        fprintf(stderr, "fail to avformat_alloc_output_context2: %d\n", ret);
        print_error_string(ret);
        return nullptr;
    }

    AVStream* out_stream = avformat_new_stream(ofmt_ctx, nullptr);
    if (!out_stream) {
        fprintf(stderr, "fail to avformat_new_stream\n");
        return nullptr;
    }

    ret = avcodec_parameters_from_context(out_stream->codecpar, enc_ctx);
    if (ret < 0) {
        fprintf(stderr, "fail to avcodec_parameters_from_context: %d\n", ret);
        print_error_string(ret);
        return nullptr;
    }

    out_stream->time_base = enc_ctx->time_base;

    if (!(ofmt_ctx->oformat->flags & AVFMT_NOFILE)) { // true
        ret = avio_open(&ofmt_ctx->pb, filename, AVIO_FLAG_WRITE);
        if (ret < 0) {
            fprintf(stderr, "fail to avio_open: %d\n", ret);
            print_error_string(ret);
            return nullptr;
        }
    }

    ret = avformat_write_header(ofmt_ctx, nullptr);
    if (ret < 0) {
        fprintf(stderr, "fail to avformat_write_header: %d\n", ret);
        print_error_string(ret);
        return nullptr;
    }

    av_dump_format(ofmt_ctx, 0, filename, 1);
    return ofmt_ctx;
}

      7.函数decode: 注意对packet的判断,它有可能为nullptr;调用一次avcodec_send_packet,可能需调用多次avcodec_receive_frame,因此需要将avcodec_receive_frame放在while中;需要对dec_ctx->time_base进行设置

int decode(AVPacket* packet, AVFormatContext* ifmt_ctx, AVCodecContext* dec_ctx, AVFrame* frame)
{
    if (packet)
        av_packet_rescale_ts(packet, ifmt_ctx->streams[video_stream_index]->time_base, dec_ctx->time_base);

    auto ret = avcodec_send_packet(dec_ctx, packet);
    if (ret < 0) {
        fprintf(stderr, "fail to avcodec_send_packet: %d\n", ret);
        print_error_string(ret);
        return -1;
    }

    while (1) {
        ret = avcodec_receive_frame(dec_ctx, frame);
        if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) { // AVERROR(EAGAIN): decode is not yet complete
            //fprintf(stderr, "Warning: avcodec_receive_frame: %d\n", ret);
            //print_error_string(ret);
            break;
        }
        else if (ret < 0) {
            fprintf(stderr, "fail to avcodec_receive_frame: %d\n", ret);
            print_error_string(ret);
            return ret;
        }

        frame->pts = frame->best_effort_timestamp;
        break;
    }

    if (packet)
        av_packet_unref(packet);

    return 0;
}

      8.函数encode:注意:调用一次avcodec_send_frame,可能需要调用多次avcodec_receive_packet,因此需要将avcodec_receive_packet放在while中;需要对ofmt_ctx->streams[0]->time_base进行设置,否则生成的mp4中无法获取帧速率;也可在调用avformat_write_header时设置video_track_timescale指定

int encode(AVCodecContext* enc_ctx, AVFrame* frame, AVPacket* packet, AVFormatContext* ifmt_ctx, AVFormatContext* ofmt_ctx)
{
    auto ret = avcodec_send_frame(enc_ctx, frame);
    if (ret < 0) {
        if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
            fprintf(stderr, "Warning: avcodec_send_frame: %d\n", ret);
            print_error_string(ret);
            ret = 0;
        }
        else {
            fprintf(stderr, "fail to avcodec_send_frame: %d\n", ret);
            print_error_string(ret);
            return ret;
        }
    }

    while (1) {
        ret = avcodec_receive_packet(enc_ctx, packet);
        if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) { // AVERROR(EAGAIN): encode is not yet complete
            //fprintf(stderr, "Warning: avcodec_receive_packet: %d\n", ret);
            //print_error_string(ret);
            break;
        }

        if (ret < 0) {
            fprintf(stderr, "fail to avcodec_receive_packet: %d\n", ret);
            print_error_string(ret);
            return ret;
        }

        packet->stream_index = 0;
        av_packet_rescale_ts(packet, ifmt_ctx->streams[video_stream_index]->time_base, ofmt_ctx->streams[0]->time_base);
        //packet2->pts = packet2->dts = frame->pts *
        //    ofmt_ctx->streams[0]->time_base.den / ofmt_ctx->streams[0]->time_base.num / 
        //    (enc_ctx->framerate.num / enc_ctx->framerate.den);

        ret = av_interleaved_write_frame(ofmt_ctx, packet);
        if (ret < 0) {
            print_error_string(ret);
            return ret;
        }

        av_packet_unref(packet);
    }

    return 0;
}

      9.主函数test_ffmpeg_save_video_slice:注意:在退出前需要flush decoder和encoder;写入视频文件需先调用avformat_write_header,然后持续调用av_interleaved_write_frame,退出前再需调用av_write_trailer;每次新文件的写入,需重新调用get_decode_context、get_encode_context、get_output_format_context并在之前作相应free

int test_ffmpeg_save_video_slice()
{
    PacketScaleQueue packet_encode;
    packet_encode.init(queue_size, block_size);

    std::thread thread_packet(set_packet, std::ref(packet_encode));

    uint8_t* avio_ctx_buffer = static_cast<uint8_t*>(av_malloc(block_size));
    if (!avio_ctx_buffer) {
        print_error_string(AVERROR(ENOMEM));
        return -1;
    }

    AVIOContext* avio_ctx = avio_alloc_context(avio_ctx_buffer, block_size, 0, &packet_encode, &read_packet, nullptr, nullptr);
    if (!avio_ctx) {
        print_error_string(AVERROR(ENOMEM));
        return -1;
    }

    AVFormatContext* ifmt_ctx = get_input_format_context(avio_ctx);
    if (!ifmt_ctx) {
        fprintf(stderr, "fail to get_input_format_context\n");
        return -1;
    }

    AVPacket *packet = av_packet_alloc(), *packet2 = av_packet_alloc();
    if (!packet || !packet2) {
        fprintf(stderr, "fail to av_packet_alloc\n");
        return -1;
    }

    AVFrame* frame = av_frame_alloc();
    if (!frame) {
        fprintf(stderr, "fail to av_frame_alloc\n");
        return -1;
    }

    int count = 0, name = 1;
    AVCodecContext* enc_ctx = nullptr;
    AVFormatContext* ofmt_ctx = nullptr;
    AVCodecContext* dec_ctx = nullptr;

    while (1) {
        auto ret = av_read_frame(ifmt_ctx, packet);
        if (ret < 0) {
            break;
        }

        if (packet->stream_index != video_stream_index) {
            av_packet_unref(packet);
            continue;
        }

        if (count % slice_size == 0) {
            enc_ctx = get_encode_context(ifmt_ctx);
            if (!enc_ctx) {
                fprintf(stderr, "fail to avcodec_alloc_context3\n");
                return -1;
            }

            std::string filename = std::to_string(name) + ".mp4";
            filename = std::string(path) + filename;
            ofmt_ctx = get_output_format_context(enc_ctx, filename.c_str());
            if (!ofmt_ctx) {
                fprintf(stderr, "fail to get_output_format_context\n");
                return -1;
            }

            dec_ctx = get_decode_context(ifmt_ctx);
            if (!dec_ctx) {
                fprintf(stderr, "fail to get_decode_context\n");
                return -1;
            }

            ++name;
        }

        if (decode(packet, ifmt_ctx, dec_ctx, frame) != 0) return -1;

        if (encode(enc_ctx, frame, packet2, ifmt_ctx, ofmt_ctx) != 0) return -1;

        //fprintf(stdout, "count: %d\n", count);
        if (count + 1 == total_frames) { // terminate loop
            packet_encode_flag = false;

            // flush the decoder
            decode(nullptr, ifmt_ctx, dec_ctx, frame);
            if (frame->data[0])
                encode(enc_ctx, frame, packet2, ifmt_ctx, ofmt_ctx);

            // flush the encoder
            encode(enc_ctx, nullptr, packet2, ifmt_ctx, ofmt_ctx);

            av_write_trailer(ofmt_ctx);
            break;
        }

        ++count;

        if (count > 1 && count % slice_size == 0) {
            // flush the decoder
            decode(nullptr, ifmt_ctx, dec_ctx, frame);
            if (frame->data[0])
                encode(enc_ctx, frame, packet2, ifmt_ctx, ofmt_ctx);

            // flush the encoder
            encode(enc_ctx, nullptr, packet2, ifmt_ctx, ofmt_ctx);

            av_write_trailer(ofmt_ctx);

            avcodec_free_context(&dec_ctx);
            avcodec_free_context(&enc_ctx);
            avio_closep(&ofmt_ctx->pb);
            avformat_free_context(ofmt_ctx);
        }
    }

    av_packet_free(&packet);
    av_packet_free(&packet2);
    av_frame_free(&frame);

    avcodec_free_context(&dec_ctx);
    avcodec_free_context(&enc_ctx);
    avio_closep(&ofmt_ctx->pb);
    avformat_close_input(&ofmt_ctx);
    avformat_close_input(&ifmt_ctx);

    // note: the internal buffer could have changed, and be != avio_ctx_buffer
    if (avio_ctx) {
        av_freep(&avio_ctx->buffer);
        av_freep(&avio_ctx);
    }

    thread_packet.join();
    fprintf(stdout, "test finish\n");

    return 0;
}

      执行结果如下图所示:

FFmpeg将编码后数据保存成mp4,VLC/FFmpeg/LIVE555,ffmpeg

      可调用ffprobe.exe验证每个生成的视频文件的总帧数,如1.mp4,执行如下命令:

ffprobe.exe -v error -select_streams v:0 -show_entries stream=nb_frames -of default=nokey=1:noprint_wrappers=1 1.mp4

      GitHub:https://github.com/fengbingchun/OpenCV_Test文章来源地址https://www.toymoban.com/news/detail-638912.html

到了这里,关于FFmpeg将编码后数据保存成mp4的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Qt+FFmpeg简单实现录屏并保存为MP4视频

            最近需要实现一个录屏功能,网上查了好多资料,最可靠的方案当然还是用FFmpeg实现,但是也踩了很多坑,包括FFmpeg版本问题,vs2019里相关编译问题,FFmpeg也不太熟悉,很多代码不太容易看懂,想要按自己熟悉的方式实现录屏功能,花了一番功夫。         如果你进

    2024年02月15日
    浏览(41)
  • 「Python|音视频处理|场景案例」如何使用ffmpeg下载m3u8视频到本地并保存成mp4

    本文主要介绍如何使用ffmpeg批量下载视频到本地并保存成指定格式。 当我们希望将网页上的视频下载到本地的时候,我们可能获取到的视频地址是指向 .m3u8 格式的,当视频多的时候,手动下载并使用工具转换格式就显得工作量过大。 ffmpeg 是一个强大的音视频处理工具,具体

    2024年02月16日
    浏览(54)
  • FFmpeg h.265 MP4编码告警:deprecated pixel format used, make sure you did set range correctly

    “使用了不赞成使用的像素格式,请确保您已使用ffmpeg正确设置了范围\\\" 直接忽略这个警告就可以了,我们取的海康摄像头的rtsp流的像素格式是yuv j420p,估计这种像素格式现在不太那啥,所以不赞成使用 但是x264和x265编码器目前都支持这种像素类型,我们平时只用到x264和x2

    2024年02月16日
    浏览(41)
  • DXGI高帧率屏幕录像软件源码解析(声音捕获,抓屏,ffmpeg录像,MP4录像,flv录像,麦克风采集)(第4篇编码,录像部分)

    本文DEMO源码下载: https://download.csdn.net/download/xjb2006/85109025 dxgi桌面屏幕录像(windows屏幕录像,硬件编码,声音捕获,音视频同步) 由于篇幅有限,分为4篇发表: 1、SDK接口一览: 2、声音采集部分: 3、屏幕捕获部分: 4、编码,录像部分: 距离上篇文章已经过了快1年了,才

    2023年04月17日
    浏览(38)
  • 音视频编码实战-------pcm+yuv数据转成MP4

    avcodec_find_encoder: 根据编码器ID查找编码器 avcodec_alloc_context3:创建编码器上下文 avcodec_open2:打开编码器 avformat_alloc_output_context2:为输出格式创建复用器上下文 avformat_new_stream:创建音视频流 avcodec_parameters_from_context:将编码器上下文中的参数拷贝到音视频流中的编码器参数中AVCodec

    2024年02月15日
    浏览(47)
  • 使用FFMPEG库封装264视频和acc音频数据到MP4文件中

    ffmepeg 4.4 一段H264的视频文件 一段acc格式的音频文件 1.使用avformat_open_input分别打开视频和音频文件,初始化其AVFormatContext,使用avformat_find_stream_info获取编码器基本信息 2.使用avformat_alloc_output_context2初始化输出的AVFormatContext结构 3.使用函数avformat_new_stream给输出的AVFormatContext结

    2024年02月11日
    浏览(34)
  • 保存rosbag中的图像与点云数据,输出为png pcd mp4文件

    1.保存图像数据 使用  image_view image_saver 打开一个终端输入以下指令 rosrun image_view image_saver image:=/usb_cam/image_raw  _filename_format:= \\\"%04i.png\\\" _encoding:=bgr8 参数分别为:图像的topic、文件名( %04i 是指4位数的数字)、文件的编码  32FC1 和 bgr8 然后再起一个终端播放需要保持的图像数

    2024年01月17日
    浏览(36)
  • FFMPEG mp4封装实现

    FFMPEG mp4录像 author:lyn date:2022.09.28 version: ffmpeg4.1.3 1.mp4数据结构 2.ffmpeg mp4封装实现 3.mp4函数调用关系 4.参考资料 1.mp4数据结构 1.1mp4简介 MP4或称MPEG-4第14部分(英语:MPEG-4 Part 14)是一种标准的数字多媒体容器格式。MPEG-4第14部分的扩展名为 .mp4 ,以存储数字音频及数字视频

    2023年04月08日
    浏览(22)
  • ffmpeg操作MP4视频封面

    提取视频封面 视频流中提取帧图 3.重新设置视频封面 更多参考: https://blog.csdn.net/m0_37624402/article/details/125123818

    2024年02月04日
    浏览(31)
  • 20231005使用ffmpeg旋转MP4视频

    20231005使用ffmpeg旋转MP4视频 2023/10/5 12:21 百度搜搜:ffmpeg 旋转90度 https://zhuanlan.zhihu.com/p/637790915 【FFmpeg实战】FFMPEG常用命令行 https://blog.csdn.net/weixin_37515325/article/details/127817057 FFMPEG常用命令行 5.视频旋转 顺时针旋转90度:ffmpeg -i test.mp4 -vf \\\"transpose=1\\\" out.mp4//顺时针旋转90° 逆时针

    2024年02月07日
    浏览(31)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包