FFMPEG 用H264編碼封裝mp4 有聲音無影象。或者解碼錯誤
那是因為解碼時用到的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之前。
否則,就會產生,不報錯,一切正常,生成了檔案,但是沒法播放的錯誤。