2016-06-28 498 views
5

我的视频设置的格式布局如下:FFmpeg的“movflags”>“的fastStart”导致无效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 
+0

如何创建formatContext? – szatmary

+0

更新的问题。 – williamtroup

+0

io环境在哪里?数据在哪里写入?如果您正在使用流媒体io(如粗壮),则无法快速启动该文件,因为查找不适用于流。 – szatmary

回答

1

这样看来使用“的fastStart”自身原因导致的问题。只要你通过“movflags”(在我的例子中是“frag_duration”)正确设置你的段大小,它应该没问题。

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