FFMPEG 用H264编码封装mp4 有声音无图像。或者解码错误

来源:互联网 发布:淘宝产品视频拍摄 编辑:程序博客网 时间:2024/05/16 06:21

那是因为解码时用到的sps,pps信息缺失。

 out_stream = avformat_new_stream(ptrBoxObj->ofmt_ctx, NULL);
  if (!out_stream) {
   av_log(NULL, AV_LOG_ERROR, "Failedallocating output stream\n");
   return AVERROR_UNKNOWN;
  }
  in_stream = ptrBoxObj->ifmt_ctx->streams[i];
  dec_ctx = in_stream->codec;
  enc_ctx = out_stream->codec;
  if (dec_ctx->codec_type == AVMEDIA_TYPE_VIDEO
   || dec_ctx->codec_type == AVMEDIA_TYPE_AUDIO) {

   if (dec_ctx->codec_type == AVMEDIA_TYPE_VIDEO) {

    encoder = avcodec_find_encoder(ptrBoxObj->output_video_codec_id);
    if (encoder <= 0)
    {
     av_log(NULL, AV_LOG_ERROR, "not found fitable video encoder\n");
     return ret;
    }

    enc_ctx->codec_type = AVMEDIA_TYPE_VIDEO;

    enc_ctx->height = dec_ctx->height;
    enc_ctx->width = dec_ctx->width;
    enc_ctx->sample_aspect_ratio = dec_ctx->sample_aspect_ratio;
    // take first format from list of supported formats
    enc_ctx->pix_fmt = encoder->pix_fmts[0];
    // video time_base can be set to whatever is handy andsupported by encoder
    enc_ctx->time_base = dec_ctx->time_base;


    //enc_ctx->gop_size = dec_ctx->gop_size;
    //enc_ctx->gop_size = 50;

    enc_ctx->max_b_frames = 0;
    enc_ctx->thread_count = 0;

 enc_ctx->qmin = 3;
    enc_ctx->qmax = 30;
    enc_ctx->me_range = 16;
    enc_ctx->max_qdiff = 4;
   }


 if (ptrBoxObj->ofmt_ctx->oformat->flags &AVFMT_GLOBALHEADER)
    enc_ctx->flags |= CODEC_FLAG_GLOBAL_HEADER;


   ret = avcodec_open2(enc_ctx, encoder, NULL);
   if (ret < 0) {
    av_log(NULL, AV_LOG_ERROR, "Cannot openvideo encoder for stream #%u\n", i);
    return ret;
   }


创建完H264编码器以后,enc_ctx中的extradata并没有数据,只有当调用avcodec_open2时候,才会把spspps数据写入extradata,

但是有个条件,必须设置了CODEC_FLAG_GLOBAL_HEADER标志,avcodec_open2才会写入extradata,否则,avcodec_open2并不会写入。

所以, if (ptrBoxObj->ofmt_ctx->oformat->flags &AVFMT_GLOBALHEADER)
    enc_ctx->flags |= CODEC_FLAG_GLOBAL_HEADER;这个调用必须放到avcodec_open2之前。

否则,就会产生,不报错,一切正常,生成了文件,但是没法播放的错误。


1 0