bytedeco/javacv

MP4 Files Unplayable After Crash Despite Using frag_keyframe+empty_moov with FFmpegFrameRecorder

Open

#2,358 创建于 2025年9月26日

在 GitHub 查看
 (1 评论) (0 反应) (0 负责人)Java (6,985 star) (1,583 fork)batch import
help wantedquestion

描述

I’m currently using the following code to record video as an MP4 file:

String outputFile = outputDir + File.separator +
        "video_" + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()) + ".mp4";

recorder = new FFmpegFrameRecorder(outputFile, width, height, audioChannels);
recorder.setFormat("mp4");
recorder.setVideoCodec(avcodec.AV_CODEC_ID_H264);
recorder.setAudioCodec(avcodec.AV_CODEC_ID_AAC);
recorder.setSampleRate(grabber.getSampleRate());
recorder.setFrameRate(grabber.getFrameRate() <= 0 || grabber.getFrameRate() > 120 ? 25 : grabber.getFrameRate());
recorder.setAudioChannels(audioChannels);
recorder.start();

The problem is, if the service crashes during recording, the generated MP4 file becomes unplayable. From my research, this is because the MP4 moov atom is written at the end of the file. If the process crashes, the moov atom never gets written, which makes the file corrupt.

I also tried setting the following option to fix it:

recorder.setOption("movflags", "frag_keyframe+empty_moov+faststart");

However, it doesn’t seem to work. What could be causing this, and how can I reliably generate MP4 files that remain playable even if the recording is interrupted?

贡献者指南