FFmpeg" movflags" > "的fastStart"导致写入无效的MP4文件

时间:2016-06-28 07:55:43

标签: c# api video ffmpeg mp4

我按如下方式设置视频的格式布局:

AVOutputFormat* outputFormat = ffmpeg.av_guess_format(null, "output.mp4", null);

AVCodec* videoCodec = ffmpeg.avcodec_find_encoder(outputFormat->video_codec);

AVFormatContext* formatContext = ffmpeg.avformat_alloc_context();
formatContext->oformat = outputFormat;
formatContext->video_codec_id = videoCodec->id;

ffmpeg.avformat_new_stream(formatContext, videoCodec);

这就是我设置编解码器上下文的方式:

AVCodecContext* codecContext = ffmpeg.avcodec_alloc_context3(videoCodec);
codecContext->bit_rate = 400000;
codecContext->width = 1280;
codecContext->height = 720;
codecContext->gop_size = 12;
codecContext->max_b_frames = 1;
codecContext->pix_fmt = videoCodec->pix_fmts[0];
codecContext->codec_id = videoCodec->id;
codecContext->codec_type = videoCodec->type;
codecContext->time_base = new AVRational
{
    num = 1,
    den = 30
};

我使用以下代码设置" movflags" > "的fastStart"视频标题的选项:

AVDictionary* options = null;

int result = ffmpeg.av_dict_set(&options, "movflags", "faststart", 0);

int writeHeaderResult = ffmpeg.avformat_write_header(formatContext, &options);

打开文件,标题写如下:

if ((formatContext->oformat->flags & ffmpeg.AVFMT_NOFILE) == 0)
{
    int ioOptionResult = ffmpeg.avio_open(&formatContext->pb, "output.mp4", ffmpeg.AVIO_FLAG_WRITE);
}

int writeHeaderResult = ffmpeg.avformat_write_header(formatContext, &options);

在此之后,我按如下方式编写每个视频帧:

outputFrame->pts = frameIndex;

packet.flags |= ffmpeg.AV_PKT_FLAG_KEY;
packet.pts = frameIndex;
packet.dts = frameIndex;

int encodedFrame = 0;
int encodeVideoResult = ffmpeg.avcodec_encode_video2(codecContext, &packet, outputFrame, &encodedFrame);

if (encodedFrame != 0)
{
    packet.pts = ffmpeg.av_rescale_q(packet.pts, codecContext->time_base, m_videoStream->time_base);
    packet.dts = ffmpeg.av_rescale_q(packet.dts, codecContext->time_base, m_videoStream->time_base);
    packet.stream_index = m_videoStream->index;

    if (codecContext->coded_frame->key_frame > 0)
    {
        packet.flags |= ffmpeg.AV_PKT_FLAG_KEY;
    }

    int writeFrameResult = ffmpeg.av_interleaved_write_frame(formatContext, &packet);
}

之后,我写了预告片:

int writeTrailerResult = ffmpeg.av_write_trailer(formatContext);

文件完成写入,一切都关闭并正确释放。但是,MP4文件无法播放(甚至VLC无法播放)。 AtomicParsley.exe也不会显示有关该文件的任何信息。

用于AutoGen库的DLL是:

avcodec-56.dll
avdevice-56.dll
avfilter-5.dll
avformat-56.dll
avutil-54.dll
postproc-53.dll
swresample-1.dll
swscale-3.dll

1 个答案:

答案 0 :(得分:1)

似乎使用“faststart”会导致问题。只要您通过“movflags”(在我的情况下为“frag_duration”)正确设置分段大小,它应该没问题。

此外,最好确保视频中的两个流都正确同步。请参阅this问题以获取有关此问题的答案。