bytedeco/javacv

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

開放

#2,358 建立於 2025年9月26日

 (1 則留言) (0 個反應) (0 位負責人)Java (1,583 個分叉)batch import
help wantedquestion

倉庫指標

星標
 (6,985 顆星)
PR 合併指標
 (30 天內沒有已合併 PR)

描述

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?

貢獻者指南