bytedeco/javacv

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

Open

#2,358 opened on 2025年9月26日

GitHub で見る
 (1 comment) (0 reactions) (0 assignees)Java (6,985 stars) (1,583 forks)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?

コントリビューターガイド