一、問題描述
流程描述:我把每一幀原始YUV圖像數據,構造成Y4M(YUV4MPEG2)格式的流,然後使用ffmpeg編碼成h264格式進行RTMP推流。
ffmpeg執行avformat_open_input打開文件和執行avformat_find_stream_info探測流都正常,但在執行avformat_write_header報錯:Invalid data found when processing input。
二、原因
編碼器參數設置錯誤
// enc_ctx編碼器上下文,dec_ctx解碼器上下文
AVCodecContext *dec_ctx, *enc_ctx;
...
dec_ctx = pFormatCtx->streams[i]->codec;
...
if (dec_ctx->codec_type == AVMEDIA_TYPE_VIDEO) {
LOGD_DEBUG("height = %d, width = %d, sample_aspect_ratio = %d/%d, pix_fmt = %d, framerate = %d/%d, time_base = %d/%d",
dec_ctx->height, dec_ctx->width,
dec_ctx->sample_aspect_ratio.num,
dec_ctx->sample_aspect_ratio.den,
dec_ctx->pix_fmt,
dec_ctx->framerate.num, dec_ctx->framerate.den,
dec_ctx->time_base.num, dec_ctx->time_base.den);
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 */
if (encoder->pix_fmts)
enc_ctx->pix_fmt = encoder->pix_fmts[0];
else
enc_ctx->pix_fmt = dec_ctx->pix_fmt;
/* video time_base can be set to whatever is handy and supported by encoder */
enc_ctx->time_base = dec_ctx->framerate;
enc_ctx->codec_type = AVMEDIA_TYPE_VIDEO;
}
我這裏的編碼器參數是根據解碼器裏參數進行設置的,但解碼器取得的部分參數時不準確的,推測原因可能和我構造的Y4M(YUV4MPEG2)流格式有關。
三、解決方案
將上面的代碼修改爲:
// enc_ctx編碼器上下文,dec_ctx解碼器上下文
AVCodecContext *dec_ctx, *enc_ctx;
...
dec_ctx = pFormatCtx->streams[i]->codec;
...
if (dec_ctx->codec_type == AVMEDIA_TYPE_VIDEO) {
LOGD_DEBUG("height = %d, width = %d, sample_aspect_ratio = %d/%d, pix_fmt = %d, framerate = %d/%d, time_base = %d/%d",
dec_ctx->height, dec_ctx->width,
dec_ctx->sample_aspect_ratio.num,
dec_ctx->sample_aspect_ratio.den,
dec_ctx->pix_fmt,
dec_ctx->framerate.num, dec_ctx->framerate.den,
dec_ctx->time_base.num, dec_ctx->time_base.den);
enc_ctx->height = dec_ctx->height;
enc_ctx->width = dec_ctx->width;
enc_ctx->sample_aspect_ratio = {476, 477};//dec_ctx->sample_aspect_ratio;
/* take first format from list of supported formats */
if (encoder->pix_fmts)
enc_ctx->pix_fmt = encoder->pix_fmts[0];
else
enc_ctx->pix_fmt = dec_ctx->pix_fmt;
/* video time_base can be set to whatever is handy and supported by encoder */
enc_ctx->time_base = av_inv_q({25, 1});//dec_ctx->framerate);
enc_ctx->codec_type = AVMEDIA_TYPE_VIDEO;
}