I'm trying to trim video length with ffmpeg implementation of FrameGrabber and FrameRecorder, but getting corrupted file of smaller size then it's going to be. Maybe there is other way to trim video from start time to end time, also updating trim progress. Seems like it's not recording changes between frames. Maybe there are some other ways to trim videos of different formats like mp4, flv and others. Here is code snippet:
FrameGrabber grabber = new FFmpegFrameGrabber(mClip.getPath());
grabber.start();
grabber.setTimestamp(mClip.getClipStartMs()); // Write from specific moment
File out = new File(mClip.getOutPutPath(params[0])); // Set destination to write
FrameRecorder recorder = new FFmpegFrameRecorder(out, grabber.getImageWidth(), grabber.getImageHeight());
recorder.setFormat(grabber.getFormat());
recorder.setFrameRate(grabber.getFrameRate());
recorder.setSampleRate(grabber.getSampleRate());
recorder.setAspectRatio(grabber.getAspectRatio());
recorder.setSampleFormat(grabber.getSampleFormat());
recorder.setAudioCodec(grabber.getAudioCodec());
recorder.setAudioBitrate(grabber.getAudioBitrate());
recorder.setAudioChannels(grabber.getAudioChannels());
recorder.setVideoCodec(grabber.getVideoCodec());
recorder.setVideoBitrate(grabber.getVideoBitrate());
recorder.start();
Frame frame;
Long timestamp;
Long fullLength = mClip.getClipEndMs() - mClip.getClipStartMs();
double percent = 0d, oldPercent = 0d;
while ((frame = grabber.grabFrame()) != null && (timestamp = grabber.getTimestamp()) <= mClip.getClipEndMs()) {
Log.d(ASYNC_SAVE_TAG, "Started command : ffmpeg " + mClip.toString());
if (timestamp != 0d) {
oldPercent = percent;
percent = timestamp.doubleValue() / fullLength.doubleValue();
if (MathUtil.compare(percent, oldPercent) != 0) {
publishProgress(percent);
}
}
recorder.setTimestamp(grabber.getTimestamp() - mClip.getClipStartMs());
recorder.record(frame);
}
grabber.close();
recorder.close();
You can use a ffmpeg wrapper like (https://github.com/WritingMinds/ffmpeg-android-java) and then use the command line ffmpeg trim approach.
The advantage of a wrapper is that it should hide much of the complexity of integrating ffmpeg, and also it allows you use the command line syntax and leverage all the general ffmpeg discussion and support for this.
You can then use the regular ffmpeg trim syntax:
ffmpeg -i INPUT -vf trim=60:120
Morte info including the above example: