#include <iostream>
using namespace std;
extern "C"
{
#include "libavcodec/avcodec.h"
#include "libavformat/avformat.h"
#include "libswscale/swscale.h"
#include <stdio.h>
}
int main(){
const char *in_filename="in2.mp4";
const char *h264_filename="out1.h264";
FILE *h264_fd=NULL;
h264_fd=fopen(h264_filename,"wb");
AVFormatContext *ifmt_ctx=NULL;
int video_index=-1;
AVPacket *pkt=NULL;
int ret=0;
ifmt_ctx=avformat_alloc_context();
ret=avformat_open_input(&ifmt_ctx,in_filename,NULL,NULL);
video_index=av_find_best_stream(ifmt_ctx,AVMEDIA_TYPE_VIDEO,-1,-1,NULL,0);
const AVBitStreamFilter *bsfilter=av_bsf_get_by_name("h264_mp4toannexb");
AVBSFContext *bsf_ctx=NULL;
ret=av_bsf_alloc(bsfilter,&bsf_ctx);
ret=avcodec_parameters_copy(bsf_ctx->par_in,ifmt_ctx->streams[video_index]->codecpar);
ret=av_bsf_init(bsf_ctx);
pkt=av_packet_alloc();
av_init_packet(pkt);
while(1){
ret=av_read_frame(ifmt_ctx,pkt);
if(ret<0){ //跳出循环
break;
}
if(pkt->stream_index==video_index){
ret=av_bsf_send_packet(bsf_ctx,pkt); //发一次
while(1){
ret=av_bsf_receive_packet(bsf_ctx,pkt); //读到返回eagain才继续send
if(ret!=0){ //跳出循环
break;
}
size_t size=fwrite(pkt->data,1,pkt->size,h264_fd);
if(size!=pkt->size){
av_log(NULL,AV_LOG_DEBUG,"warning, length of writed data isn't equal pkt->size(%d,%d)\n",size,pkt->size);
}
av_packet_unref(pkt);
}
}
else{
av_packet_unref(pkt); //释放buffer
}
}
printf("while finsh\n");
}
FFmpeg -Mp4解封装提取视频包写入out1.h264文件中(代码实现)
最新推荐文章于 2024-06-19 21:07:12 发布