使用ffmpeg将mp4转为ts(代码实现)

使用ffmpeg将mp4转为ts的命令格式如下
ffmpeg - i b.mp4 -codec copy -bsf h264_mp4toannexb a.ts

如果不使用-bsf h264_mp4toannexb参数 会提示错误
主要是因为使用了mp4中的h264编码 而h264有两种封装:
一种是annexb模式 传统模式 有statrtcode SPS和PPS是在ES中 另一种是mp4模式 一般mp4 mkv avi会没有startcode SPS和PPS以及其他信息被封装在container中 每一个frame前面是这个frame的长度 很多解码器只支持annexb这种模式 因此需要将mp4做转换 在ffmpeg中用h264_mp4toannexb_filter可以做转换 所以需要使用-bsf h264_mp4toannexb来进行转换

代码实现主要分为三个步骤:
1.初始化filter av_bitstream_filter_init
2.使用filter转换av_bitstream_filter_filter
3.关闭filter av_bitstream_filter_close

其他与正常的转封装相同

#include <stdio.h>
#include <stdlib.h>
#include <libavformat/avformat.h>
#include <libavutil/avutil.h>
#define  FORMAT "mpegts"
#define  OUTPUT_FILE  "./fuck.ts"
#define  INPUT_FILE  "./a.mp4"
int main(int argc ,char *argv[])
{
    AVPacket pkt;//压缩帧
    AVFormatContext *input_fmtctx=NULL;//封装格式上下文
    AVFormatContext *output_fmtctx=NULL;//输出视频封装格式上下文
    AVCodecContext *enc_ctx=NULL;
    AVCodevContext *dec_ctx=NULL;//编解码上下文
    AVCodec *encoder=NULL;//每种编解码器对应一个该结构体
    AVBitStreamFilterContext *vbsf=NULL;
    int ret=0;
    int i=0;
    int have_key=0;
    static int first_pkt=1;
    av_register_all();
    if(avformat_open_input(&input_fmtctx,INPUT_FILE,NULL,NULL)<0){
      av_log(NULL,AV_LOG_ERROR,"Cannot open the file %s\n","./a.mp4");
      return  -ENOENT;
    } 


}

猜你喜欢

转载自blog.csdn.net/xujaiwei/article/details/77774403