FFmpeg将视频包AVPacket通过视频流方式写入本地文件

1.写视频头

cpp 复制代码
void writeVideoHeader(const char* videoFileName){
    int r = avformat_alloc_output_context2(&pFormatCtx, nullptr, nullptr,videoFileName);
    if(r < 0){
        qDebug()<<"Error: avformat_alloc_output_context2: "<<av_err2str(r);
        return;
    }
    pStream = avformat_new_stream(pFormatCtx,nullptr);
    qDebug()<<"创建视频流成功";
    pFormatCtx->streams[0]->codecpar->width = 1280;
    pFormatCtx->streams[0]->codecpar->height = 720;
    AVCodecContext *c= pStream->codec;
    c->codec_type = AVMEDIA_TYPE_VIDEO;
    c->codec_id = AV_CODEC_ID_H264;
    c->bit_rate = 2000000;
    c->width = 1080;
    c->height = 720;
    c->time_base.num = 1;
    c->time_base.den = 30;
    qDebug()<<"配置解码器选项成功";
    r = avio_open(&pFormatCtx->pb, videoFileName, AVIO_FLAG_WRITE);
    if(r < 0){
        qDebug()<<"Error: avio_open: "<<av_err2str(r);
        return;
    }
    qDebug()<<"打开视频流成功";
    r = avformat_write_header(pFormatCtx, nullptr);
    if(r < 0){
        qDebug()<<"Error: avformat_write_header error"<<av_err2str(r)<<r;
        return;
    }
    qDebug()<<"写入视频头部信息成功";
}

2.写视频帧

cpp 复制代码
void writeAVFrame(AVPacket *packet){
    qDebug()<<"原始视频帧信息:"<<packet->pts<<packet->dts<<packet->size;
    int64_t video_max_pts = 0;
    av_packet_rescale_ts(packet, pStream->time_base, pStream->time_base);
    packet->stream_index = 0;
    video_max_pts = qMax(packet->pts, video_max_pts);
    qDebug("视频:PTS-> %d %d %d",packet->pts,packet->dts, &pStream->time_base);
    qDebug()<<"计算时间基成功";
    int r=av_write_frame(pFormatCtx, packet);
    if (r<0) {
        qDebug()<<"Error: av_write_frame: "<<av_err2str(r);
        return;
    }
    qDebug()<<"写入视频帧成功";
}

3.关闭视频流

cpp 复制代码
if(pFormatCtx){
                    av_write_trailer(pFormatCtx);
                    avio_close(pFormatCtx->pb);
                    avformat_free_context(pFormatCtx);
                }
相关推荐
浮华落定6 小时前
DeepSeek+即梦 做AI视频
人工智能·chatgpt·音视频
Black蜡笔小新11 小时前
从中心化到点对点:视频通话SDK组件EasyRTC如何通过WebP2P技术实现低延迟通信
网络协议·音视频·p2p
清月电子16 小时前
BT401双模音频蓝牙模块如何开启ble的透传,有什么注意事项
单片机·嵌入式硬件·物联网·音视频
深圳市青牛科技实业有限公司16 小时前
芯麦 GC1808:高性能、低成本的立体声音频模数转换器
人工智能·嵌入式硬件·算法·音视频·能源·新能源·电动工具
cuijiecheng201816 小时前
音视频入门基础:RTP专题(9)——FFmpeg接收RTP流的原理和内部实现
ffmpeg·音视频
京河小蚁17 小时前
微信云开发小程序音频播放踩坑记录 - 从熄屏播放到iOS静音
微信·小程序·音视频
9527华安18 小时前
FPGA实现SDI视频解码转GTY光口传输,基于GS2971+Aurora 8b/10b编解码架构,提供工程源码和技术支持
fpga开发·架构·音视频·8b/10b·sdi·gty·gs2971
shawn·xiao18 小时前
Android:播放Rtsp视频流的两种方式
android·音视频·视频
偶是老李头18 小时前
Ubuntu虚拟机NDK编译ffmpeg
linux·ubuntu·ffmpeg·android ndk
忘不了情19 小时前
前端如何播放二进制音频数据
javascript·react.js·音视频