FFMPEG with Java Wrapper











up vote
3
down vote

favorite
1












In this java application, I am trying to convert an video into small clips.



Here is the implementation class for the same



package ffmpeg.clip.process;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Paths;
import java.time.Duration;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;

import ffmpeg.clip.utils.VideoConstant;
import ffmpeg.clip.utils.VideoUtils;

/*
* @author Nitishkumar Singh
* @Description: class will use ffmpeg to break an source video into clips
*/
public class VideoToClip {

/*
* Prevent from creating instance
*/
private VideoToClip() {
}

/**
* Get Video Duration is milliseconds
*
* @Exception IOException - File does not exist VideoException- Video File have data issues
*/
static LocalTime getDuration(String sourceVideoFile) throws Exception {
if (!Paths.get(sourceVideoFile).toFile().exists())
throw new Exception("File does not exist!!");

Process proc = new ProcessBuilder(VideoConstant.SHELL, VideoConstant.SHELL_COMMAND_STRING_ARGUMENT,
String.format(VideoConstant.DURATION_COMMAND, sourceVideoFile)).start();
boolean errorOccured = (new BufferedReader(new InputStreamReader(proc.getErrorStream())).lines()
.count() > VideoConstant.ZERO);
String durationInSeconds = new BufferedReader(new InputStreamReader(proc.getInputStream())).lines()
.collect(Collectors.joining(System.lineSeparator()));
proc.destroy();
if (errorOccured || (durationInSeconds.length() == VideoConstant.ZERO))
throw new Exception("Video File have some issues!");
else
return VideoUtils.parseHourMinuteSecondMillisecondFormat(durationInSeconds);
}

/**
* Create Clips for Video Using Start and End Second
*
* @Exception IOException - Clip Creation Process Failed InterruptedException - Clip Creation task get's failed
*/
static String toClipProcess(String sourceVideo, String outputDirectory, LocalTime start, LocalTime end,
String fileExtension) throws IOException, InterruptedException, ExecutionException {

String clipName = String.format(VideoConstant.CLIP_FILE_NAME,
VideoUtils.getHourMinuteSecondMillisecondFormat(start),
VideoUtils.getHourMinuteSecondMillisecondFormat(end), fileExtension);

String command = String.format(VideoConstant.FFMPEG_OUTPUT_COMMAND, sourceVideo,
VideoUtils.getHourMinuteSecondMillisecondFormat(start),
VideoUtils.getHourMinuteSecondMillisecondFormat(end.minus(start.toNanoOfDay(), ChronoUnit.NANOS)),
outputDirectory, clipName);
LocalTime startTime = LocalTime.now();
System.out.println("Clip Name: " + clipName);
System.out.println("FFMPEG Process Execution Started");
CompletableFuture<Process> completableFuture = CompletableFuture.supplyAsync(() -> {
try {
return executeProcess(command);
} catch (InterruptedException | IOException ex) {
throw new RuntimeException(ex);
}
});
completableFuture.get();
// remove
LocalTime endTime = LocalTime.now();
System.out.println("Clip Name: " + clipName);
System.out.println("FFMPEG Process Execution Finished");
System.out.println("Duration: " + Duration.between(startTime, endTime).toMillis() / 1000);

return clipName;
}

/**
* Create and Execute Process for each command
*/
static Process executeProcess(String command) throws InterruptedException, IOException {
Process clipProcess = Runtime.getRuntime().exec(command);
clipProcess.waitFor();
return clipProcess;
}
}


The Entire Solution is availble at Github. I am actually using CompletableFuture and running FFMPEG command by creating Java Process. The time it takes is too much. For a 40 minutes video, it takes more than 49 minutes, on a 64 CPU machine. I am trying to reduce the core size to 8 or something, as well improve its performance, as this kind of performance won't be acceptable for any kind of application.



22-jan-2017 update

One Update, I have changed the FFMPEG command to create clips and updated to FFMPEG 3, but there is no improvement.




ffmpeg -y -i INPUT_FILE_PATH -ss TIME_STAMP -t DURATION_TO_CLIP OUTPUT_FILE_PATH











share|improve this question
























  • I posted some examples using JavaCV I didn't tried with a long video video but for short videos (i.e. 5 mins) the processing time is near 1 minute approximately.
    – Teocci
    10 mins ago















up vote
3
down vote

favorite
1












In this java application, I am trying to convert an video into small clips.



Here is the implementation class for the same



package ffmpeg.clip.process;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Paths;
import java.time.Duration;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;

import ffmpeg.clip.utils.VideoConstant;
import ffmpeg.clip.utils.VideoUtils;

/*
* @author Nitishkumar Singh
* @Description: class will use ffmpeg to break an source video into clips
*/
public class VideoToClip {

/*
* Prevent from creating instance
*/
private VideoToClip() {
}

/**
* Get Video Duration is milliseconds
*
* @Exception IOException - File does not exist VideoException- Video File have data issues
*/
static LocalTime getDuration(String sourceVideoFile) throws Exception {
if (!Paths.get(sourceVideoFile).toFile().exists())
throw new Exception("File does not exist!!");

Process proc = new ProcessBuilder(VideoConstant.SHELL, VideoConstant.SHELL_COMMAND_STRING_ARGUMENT,
String.format(VideoConstant.DURATION_COMMAND, sourceVideoFile)).start();
boolean errorOccured = (new BufferedReader(new InputStreamReader(proc.getErrorStream())).lines()
.count() > VideoConstant.ZERO);
String durationInSeconds = new BufferedReader(new InputStreamReader(proc.getInputStream())).lines()
.collect(Collectors.joining(System.lineSeparator()));
proc.destroy();
if (errorOccured || (durationInSeconds.length() == VideoConstant.ZERO))
throw new Exception("Video File have some issues!");
else
return VideoUtils.parseHourMinuteSecondMillisecondFormat(durationInSeconds);
}

/**
* Create Clips for Video Using Start and End Second
*
* @Exception IOException - Clip Creation Process Failed InterruptedException - Clip Creation task get's failed
*/
static String toClipProcess(String sourceVideo, String outputDirectory, LocalTime start, LocalTime end,
String fileExtension) throws IOException, InterruptedException, ExecutionException {

String clipName = String.format(VideoConstant.CLIP_FILE_NAME,
VideoUtils.getHourMinuteSecondMillisecondFormat(start),
VideoUtils.getHourMinuteSecondMillisecondFormat(end), fileExtension);

String command = String.format(VideoConstant.FFMPEG_OUTPUT_COMMAND, sourceVideo,
VideoUtils.getHourMinuteSecondMillisecondFormat(start),
VideoUtils.getHourMinuteSecondMillisecondFormat(end.minus(start.toNanoOfDay(), ChronoUnit.NANOS)),
outputDirectory, clipName);
LocalTime startTime = LocalTime.now();
System.out.println("Clip Name: " + clipName);
System.out.println("FFMPEG Process Execution Started");
CompletableFuture<Process> completableFuture = CompletableFuture.supplyAsync(() -> {
try {
return executeProcess(command);
} catch (InterruptedException | IOException ex) {
throw new RuntimeException(ex);
}
});
completableFuture.get();
// remove
LocalTime endTime = LocalTime.now();
System.out.println("Clip Name: " + clipName);
System.out.println("FFMPEG Process Execution Finished");
System.out.println("Duration: " + Duration.between(startTime, endTime).toMillis() / 1000);

return clipName;
}

/**
* Create and Execute Process for each command
*/
static Process executeProcess(String command) throws InterruptedException, IOException {
Process clipProcess = Runtime.getRuntime().exec(command);
clipProcess.waitFor();
return clipProcess;
}
}


The Entire Solution is availble at Github. I am actually using CompletableFuture and running FFMPEG command by creating Java Process. The time it takes is too much. For a 40 minutes video, it takes more than 49 minutes, on a 64 CPU machine. I am trying to reduce the core size to 8 or something, as well improve its performance, as this kind of performance won't be acceptable for any kind of application.



22-jan-2017 update

One Update, I have changed the FFMPEG command to create clips and updated to FFMPEG 3, but there is no improvement.




ffmpeg -y -i INPUT_FILE_PATH -ss TIME_STAMP -t DURATION_TO_CLIP OUTPUT_FILE_PATH











share|improve this question
























  • I posted some examples using JavaCV I didn't tried with a long video video but for short videos (i.e. 5 mins) the processing time is near 1 minute approximately.
    – Teocci
    10 mins ago













up vote
3
down vote

favorite
1









up vote
3
down vote

favorite
1






1





In this java application, I am trying to convert an video into small clips.



Here is the implementation class for the same



package ffmpeg.clip.process;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Paths;
import java.time.Duration;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;

import ffmpeg.clip.utils.VideoConstant;
import ffmpeg.clip.utils.VideoUtils;

/*
* @author Nitishkumar Singh
* @Description: class will use ffmpeg to break an source video into clips
*/
public class VideoToClip {

/*
* Prevent from creating instance
*/
private VideoToClip() {
}

/**
* Get Video Duration is milliseconds
*
* @Exception IOException - File does not exist VideoException- Video File have data issues
*/
static LocalTime getDuration(String sourceVideoFile) throws Exception {
if (!Paths.get(sourceVideoFile).toFile().exists())
throw new Exception("File does not exist!!");

Process proc = new ProcessBuilder(VideoConstant.SHELL, VideoConstant.SHELL_COMMAND_STRING_ARGUMENT,
String.format(VideoConstant.DURATION_COMMAND, sourceVideoFile)).start();
boolean errorOccured = (new BufferedReader(new InputStreamReader(proc.getErrorStream())).lines()
.count() > VideoConstant.ZERO);
String durationInSeconds = new BufferedReader(new InputStreamReader(proc.getInputStream())).lines()
.collect(Collectors.joining(System.lineSeparator()));
proc.destroy();
if (errorOccured || (durationInSeconds.length() == VideoConstant.ZERO))
throw new Exception("Video File have some issues!");
else
return VideoUtils.parseHourMinuteSecondMillisecondFormat(durationInSeconds);
}

/**
* Create Clips for Video Using Start and End Second
*
* @Exception IOException - Clip Creation Process Failed InterruptedException - Clip Creation task get's failed
*/
static String toClipProcess(String sourceVideo, String outputDirectory, LocalTime start, LocalTime end,
String fileExtension) throws IOException, InterruptedException, ExecutionException {

String clipName = String.format(VideoConstant.CLIP_FILE_NAME,
VideoUtils.getHourMinuteSecondMillisecondFormat(start),
VideoUtils.getHourMinuteSecondMillisecondFormat(end), fileExtension);

String command = String.format(VideoConstant.FFMPEG_OUTPUT_COMMAND, sourceVideo,
VideoUtils.getHourMinuteSecondMillisecondFormat(start),
VideoUtils.getHourMinuteSecondMillisecondFormat(end.minus(start.toNanoOfDay(), ChronoUnit.NANOS)),
outputDirectory, clipName);
LocalTime startTime = LocalTime.now();
System.out.println("Clip Name: " + clipName);
System.out.println("FFMPEG Process Execution Started");
CompletableFuture<Process> completableFuture = CompletableFuture.supplyAsync(() -> {
try {
return executeProcess(command);
} catch (InterruptedException | IOException ex) {
throw new RuntimeException(ex);
}
});
completableFuture.get();
// remove
LocalTime endTime = LocalTime.now();
System.out.println("Clip Name: " + clipName);
System.out.println("FFMPEG Process Execution Finished");
System.out.println("Duration: " + Duration.between(startTime, endTime).toMillis() / 1000);

return clipName;
}

/**
* Create and Execute Process for each command
*/
static Process executeProcess(String command) throws InterruptedException, IOException {
Process clipProcess = Runtime.getRuntime().exec(command);
clipProcess.waitFor();
return clipProcess;
}
}


The Entire Solution is availble at Github. I am actually using CompletableFuture and running FFMPEG command by creating Java Process. The time it takes is too much. For a 40 minutes video, it takes more than 49 minutes, on a 64 CPU machine. I am trying to reduce the core size to 8 or something, as well improve its performance, as this kind of performance won't be acceptable for any kind of application.



22-jan-2017 update

One Update, I have changed the FFMPEG command to create clips and updated to FFMPEG 3, but there is no improvement.




ffmpeg -y -i INPUT_FILE_PATH -ss TIME_STAMP -t DURATION_TO_CLIP OUTPUT_FILE_PATH











share|improve this question















In this java application, I am trying to convert an video into small clips.



Here is the implementation class for the same



package ffmpeg.clip.process;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Paths;
import java.time.Duration;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;

import ffmpeg.clip.utils.VideoConstant;
import ffmpeg.clip.utils.VideoUtils;

/*
* @author Nitishkumar Singh
* @Description: class will use ffmpeg to break an source video into clips
*/
public class VideoToClip {

/*
* Prevent from creating instance
*/
private VideoToClip() {
}

/**
* Get Video Duration is milliseconds
*
* @Exception IOException - File does not exist VideoException- Video File have data issues
*/
static LocalTime getDuration(String sourceVideoFile) throws Exception {
if (!Paths.get(sourceVideoFile).toFile().exists())
throw new Exception("File does not exist!!");

Process proc = new ProcessBuilder(VideoConstant.SHELL, VideoConstant.SHELL_COMMAND_STRING_ARGUMENT,
String.format(VideoConstant.DURATION_COMMAND, sourceVideoFile)).start();
boolean errorOccured = (new BufferedReader(new InputStreamReader(proc.getErrorStream())).lines()
.count() > VideoConstant.ZERO);
String durationInSeconds = new BufferedReader(new InputStreamReader(proc.getInputStream())).lines()
.collect(Collectors.joining(System.lineSeparator()));
proc.destroy();
if (errorOccured || (durationInSeconds.length() == VideoConstant.ZERO))
throw new Exception("Video File have some issues!");
else
return VideoUtils.parseHourMinuteSecondMillisecondFormat(durationInSeconds);
}

/**
* Create Clips for Video Using Start and End Second
*
* @Exception IOException - Clip Creation Process Failed InterruptedException - Clip Creation task get's failed
*/
static String toClipProcess(String sourceVideo, String outputDirectory, LocalTime start, LocalTime end,
String fileExtension) throws IOException, InterruptedException, ExecutionException {

String clipName = String.format(VideoConstant.CLIP_FILE_NAME,
VideoUtils.getHourMinuteSecondMillisecondFormat(start),
VideoUtils.getHourMinuteSecondMillisecondFormat(end), fileExtension);

String command = String.format(VideoConstant.FFMPEG_OUTPUT_COMMAND, sourceVideo,
VideoUtils.getHourMinuteSecondMillisecondFormat(start),
VideoUtils.getHourMinuteSecondMillisecondFormat(end.minus(start.toNanoOfDay(), ChronoUnit.NANOS)),
outputDirectory, clipName);
LocalTime startTime = LocalTime.now();
System.out.println("Clip Name: " + clipName);
System.out.println("FFMPEG Process Execution Started");
CompletableFuture<Process> completableFuture = CompletableFuture.supplyAsync(() -> {
try {
return executeProcess(command);
} catch (InterruptedException | IOException ex) {
throw new RuntimeException(ex);
}
});
completableFuture.get();
// remove
LocalTime endTime = LocalTime.now();
System.out.println("Clip Name: " + clipName);
System.out.println("FFMPEG Process Execution Finished");
System.out.println("Duration: " + Duration.between(startTime, endTime).toMillis() / 1000);

return clipName;
}

/**
* Create and Execute Process for each command
*/
static Process executeProcess(String command) throws InterruptedException, IOException {
Process clipProcess = Runtime.getRuntime().exec(command);
clipProcess.waitFor();
return clipProcess;
}
}


The Entire Solution is availble at Github. I am actually using CompletableFuture and running FFMPEG command by creating Java Process. The time it takes is too much. For a 40 minutes video, it takes more than 49 minutes, on a 64 CPU machine. I am trying to reduce the core size to 8 or something, as well improve its performance, as this kind of performance won't be acceptable for any kind of application.



22-jan-2017 update

One Update, I have changed the FFMPEG command to create clips and updated to FFMPEG 3, but there is no improvement.




ffmpeg -y -i INPUT_FILE_PATH -ss TIME_STAMP -t DURATION_TO_CLIP OUTPUT_FILE_PATH








java performance multithreading child-process video






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 22 at 9:55

























asked Jan 20 at 15:21









Nitishkumar Singh

1185




1185












  • I posted some examples using JavaCV I didn't tried with a long video video but for short videos (i.e. 5 mins) the processing time is near 1 minute approximately.
    – Teocci
    10 mins ago


















  • I posted some examples using JavaCV I didn't tried with a long video video but for short videos (i.e. 5 mins) the processing time is near 1 minute approximately.
    – Teocci
    10 mins ago
















I posted some examples using JavaCV I didn't tried with a long video video but for short videos (i.e. 5 mins) the processing time is near 1 minute approximately.
– Teocci
10 mins ago




I posted some examples using JavaCV I didn't tried with a long video video but for short videos (i.e. 5 mins) the processing time is near 1 minute approximately.
– Teocci
10 mins ago










2 Answers
2






active

oldest

votes

















up vote
3
down vote



accepted










That is a natural restriction on video encoding. On modern machines 1 minute of 720p video is encoded approximately in 1 minute.



You can save a lot of time if you do not need re-encoding (i.e. changing codec or video size) by using -codec copy ffmpeg option.



Also you said you have 64 cores, but your code use only 1 thread for encoding. Use -threads 0 to allow ffmpeg to choose by itself.



Also, if you need to perform this in Java - give Jaffree a chance (I'm an author).






share|improve this answer























  • If you wrote Jaffree, please, state so explicitly.
    – Mast
    Feb 11 at 23:42










  • github.com/bramp/ffmpeg-cli-wrapper might be a better solution for you.
    – thekevshow
    Nov 20 at 3:45










  • I started Jaffree exactly because of several issues with ffmpeg-cli-wrapper.
    – Denis Kokorin
    Nov 20 at 5:46


















up vote
0
down vote













I know this is an old question but I think this might be useful for Java Developers.



There is a nice library called JavaCV this live is a wrapper for multiple C and C++ libraries like FFmpeg.



This is a simple example of how to implement a Converter:



import org.bytedeco.javacpp.avcodec;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class PacketRecorderTest {

private static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyyMMdd__hhmmSSS");

private static final int RECORD_LENGTH = 5000;

private static final boolean AUDIO_ENABLED = false;

public static void main(String args) throws FrameRecorder.Exception, FrameGrabber.Exception {

String inputFile = "/home/usr/videos/VIDEO_FILE_NAME.mp4";

// Decodes-encodes
String outputFile = "/tmp/" + DATE_FORMAT.format(new Date()) + "_frameRecord.mp4";
PacketRecorderTest.frameRecord(inputFile, outputFile);

// copies codec (no need to re-encode)
outputFile = "/tmp/" + DATE_FORMAT.format(new Date()) + "_packetRecord.mp4";
PacketRecorderTest.packetRecord(inputFile, outputFile);

}

public static void frameRecord(String inputFile, String outputFile) throws FrameGrabber.Exception, FrameRecorder.Exception {

int audioChannel = AUDIO_ENABLED ? 1 : 0;

FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(inputFile);
FFmpegFrameRecorder recorder = new FFmpegFrameRecorder(outputFile, 1280, 720, audioChannel);

grabber.start();
recorder.start();

Frame frame;
long t1 = System.currentTimeMillis();
while ((frame = grabber.grabFrame(AUDIO_ENABLED, true, true, false)) != null) {
recorder.record(frame);
if ((System.currentTimeMillis() - t1) > RECORD_LENGTH) {
break;
}
}
recorder.stop();
grabber.stop();
}

public static void packetRecord(String inputFile, String outputFile) throws FrameGrabber.Exception, FrameRecorder.Exception {

int audioChannel = AUDIO_ENABLED ? 1 : 0;

FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(inputFile);
FFmpegFrameRecorder recorder = new FFmpegFrameRecorder(outputFile, 1280, 720, audioChannel);

grabber.start();
recorder.start(grabber.getFormatContext());

avcodec.AVPacket packet;
long t1 = System.currentTimeMillis();
while ((packet = grabber.grabPacket()) != null) {
recorder.recordPacket(packet);
if ((System.currentTimeMillis() - t1) > RECORD_LENGTH) {
break;
}
}

recorder.stop();
grabber.stop();
}
}


This basic implementation shows how to convert a video using a FFmpeg packet or a JavaCV frame.






share|improve this answer








New contributor




Teocci is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.


















    Your Answer





    StackExchange.ifUsing("editor", function () {
    return StackExchange.using("mathjaxEditing", function () {
    StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
    StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
    });
    });
    }, "mathjax-editing");

    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "196"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f185545%2fffmpeg-with-java-wrapper%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    3
    down vote



    accepted










    That is a natural restriction on video encoding. On modern machines 1 minute of 720p video is encoded approximately in 1 minute.



    You can save a lot of time if you do not need re-encoding (i.e. changing codec or video size) by using -codec copy ffmpeg option.



    Also you said you have 64 cores, but your code use only 1 thread for encoding. Use -threads 0 to allow ffmpeg to choose by itself.



    Also, if you need to perform this in Java - give Jaffree a chance (I'm an author).






    share|improve this answer























    • If you wrote Jaffree, please, state so explicitly.
      – Mast
      Feb 11 at 23:42










    • github.com/bramp/ffmpeg-cli-wrapper might be a better solution for you.
      – thekevshow
      Nov 20 at 3:45










    • I started Jaffree exactly because of several issues with ffmpeg-cli-wrapper.
      – Denis Kokorin
      Nov 20 at 5:46















    up vote
    3
    down vote



    accepted










    That is a natural restriction on video encoding. On modern machines 1 minute of 720p video is encoded approximately in 1 minute.



    You can save a lot of time if you do not need re-encoding (i.e. changing codec or video size) by using -codec copy ffmpeg option.



    Also you said you have 64 cores, but your code use only 1 thread for encoding. Use -threads 0 to allow ffmpeg to choose by itself.



    Also, if you need to perform this in Java - give Jaffree a chance (I'm an author).






    share|improve this answer























    • If you wrote Jaffree, please, state so explicitly.
      – Mast
      Feb 11 at 23:42










    • github.com/bramp/ffmpeg-cli-wrapper might be a better solution for you.
      – thekevshow
      Nov 20 at 3:45










    • I started Jaffree exactly because of several issues with ffmpeg-cli-wrapper.
      – Denis Kokorin
      Nov 20 at 5:46













    up vote
    3
    down vote



    accepted







    up vote
    3
    down vote



    accepted






    That is a natural restriction on video encoding. On modern machines 1 minute of 720p video is encoded approximately in 1 minute.



    You can save a lot of time if you do not need re-encoding (i.e. changing codec or video size) by using -codec copy ffmpeg option.



    Also you said you have 64 cores, but your code use only 1 thread for encoding. Use -threads 0 to allow ffmpeg to choose by itself.



    Also, if you need to perform this in Java - give Jaffree a chance (I'm an author).






    share|improve this answer














    That is a natural restriction on video encoding. On modern machines 1 minute of 720p video is encoded approximately in 1 minute.



    You can save a lot of time if you do not need re-encoding (i.e. changing codec or video size) by using -codec copy ffmpeg option.



    Also you said you have 64 cores, but your code use only 1 thread for encoding. Use -threads 0 to allow ffmpeg to choose by itself.



    Also, if you need to perform this in Java - give Jaffree a chance (I'm an author).







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Feb 12 at 10:19

























    answered Feb 11 at 19:29









    Denis Kokorin

    1463




    1463












    • If you wrote Jaffree, please, state so explicitly.
      – Mast
      Feb 11 at 23:42










    • github.com/bramp/ffmpeg-cli-wrapper might be a better solution for you.
      – thekevshow
      Nov 20 at 3:45










    • I started Jaffree exactly because of several issues with ffmpeg-cli-wrapper.
      – Denis Kokorin
      Nov 20 at 5:46


















    • If you wrote Jaffree, please, state so explicitly.
      – Mast
      Feb 11 at 23:42










    • github.com/bramp/ffmpeg-cli-wrapper might be a better solution for you.
      – thekevshow
      Nov 20 at 3:45










    • I started Jaffree exactly because of several issues with ffmpeg-cli-wrapper.
      – Denis Kokorin
      Nov 20 at 5:46
















    If you wrote Jaffree, please, state so explicitly.
    – Mast
    Feb 11 at 23:42




    If you wrote Jaffree, please, state so explicitly.
    – Mast
    Feb 11 at 23:42












    github.com/bramp/ffmpeg-cli-wrapper might be a better solution for you.
    – thekevshow
    Nov 20 at 3:45




    github.com/bramp/ffmpeg-cli-wrapper might be a better solution for you.
    – thekevshow
    Nov 20 at 3:45












    I started Jaffree exactly because of several issues with ffmpeg-cli-wrapper.
    – Denis Kokorin
    Nov 20 at 5:46




    I started Jaffree exactly because of several issues with ffmpeg-cli-wrapper.
    – Denis Kokorin
    Nov 20 at 5:46












    up vote
    0
    down vote













    I know this is an old question but I think this might be useful for Java Developers.



    There is a nice library called JavaCV this live is a wrapper for multiple C and C++ libraries like FFmpeg.



    This is a simple example of how to implement a Converter:



    import org.bytedeco.javacpp.avcodec;

    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.Date;

    public class PacketRecorderTest {

    private static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyyMMdd__hhmmSSS");

    private static final int RECORD_LENGTH = 5000;

    private static final boolean AUDIO_ENABLED = false;

    public static void main(String args) throws FrameRecorder.Exception, FrameGrabber.Exception {

    String inputFile = "/home/usr/videos/VIDEO_FILE_NAME.mp4";

    // Decodes-encodes
    String outputFile = "/tmp/" + DATE_FORMAT.format(new Date()) + "_frameRecord.mp4";
    PacketRecorderTest.frameRecord(inputFile, outputFile);

    // copies codec (no need to re-encode)
    outputFile = "/tmp/" + DATE_FORMAT.format(new Date()) + "_packetRecord.mp4";
    PacketRecorderTest.packetRecord(inputFile, outputFile);

    }

    public static void frameRecord(String inputFile, String outputFile) throws FrameGrabber.Exception, FrameRecorder.Exception {

    int audioChannel = AUDIO_ENABLED ? 1 : 0;

    FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(inputFile);
    FFmpegFrameRecorder recorder = new FFmpegFrameRecorder(outputFile, 1280, 720, audioChannel);

    grabber.start();
    recorder.start();

    Frame frame;
    long t1 = System.currentTimeMillis();
    while ((frame = grabber.grabFrame(AUDIO_ENABLED, true, true, false)) != null) {
    recorder.record(frame);
    if ((System.currentTimeMillis() - t1) > RECORD_LENGTH) {
    break;
    }
    }
    recorder.stop();
    grabber.stop();
    }

    public static void packetRecord(String inputFile, String outputFile) throws FrameGrabber.Exception, FrameRecorder.Exception {

    int audioChannel = AUDIO_ENABLED ? 1 : 0;

    FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(inputFile);
    FFmpegFrameRecorder recorder = new FFmpegFrameRecorder(outputFile, 1280, 720, audioChannel);

    grabber.start();
    recorder.start(grabber.getFormatContext());

    avcodec.AVPacket packet;
    long t1 = System.currentTimeMillis();
    while ((packet = grabber.grabPacket()) != null) {
    recorder.recordPacket(packet);
    if ((System.currentTimeMillis() - t1) > RECORD_LENGTH) {
    break;
    }
    }

    recorder.stop();
    grabber.stop();
    }
    }


    This basic implementation shows how to convert a video using a FFmpeg packet or a JavaCV frame.






    share|improve this answer








    New contributor




    Teocci is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.






















      up vote
      0
      down vote













      I know this is an old question but I think this might be useful for Java Developers.



      There is a nice library called JavaCV this live is a wrapper for multiple C and C++ libraries like FFmpeg.



      This is a simple example of how to implement a Converter:



      import org.bytedeco.javacpp.avcodec;

      import java.text.DateFormat;
      import java.text.SimpleDateFormat;
      import java.util.Date;

      public class PacketRecorderTest {

      private static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyyMMdd__hhmmSSS");

      private static final int RECORD_LENGTH = 5000;

      private static final boolean AUDIO_ENABLED = false;

      public static void main(String args) throws FrameRecorder.Exception, FrameGrabber.Exception {

      String inputFile = "/home/usr/videos/VIDEO_FILE_NAME.mp4";

      // Decodes-encodes
      String outputFile = "/tmp/" + DATE_FORMAT.format(new Date()) + "_frameRecord.mp4";
      PacketRecorderTest.frameRecord(inputFile, outputFile);

      // copies codec (no need to re-encode)
      outputFile = "/tmp/" + DATE_FORMAT.format(new Date()) + "_packetRecord.mp4";
      PacketRecorderTest.packetRecord(inputFile, outputFile);

      }

      public static void frameRecord(String inputFile, String outputFile) throws FrameGrabber.Exception, FrameRecorder.Exception {

      int audioChannel = AUDIO_ENABLED ? 1 : 0;

      FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(inputFile);
      FFmpegFrameRecorder recorder = new FFmpegFrameRecorder(outputFile, 1280, 720, audioChannel);

      grabber.start();
      recorder.start();

      Frame frame;
      long t1 = System.currentTimeMillis();
      while ((frame = grabber.grabFrame(AUDIO_ENABLED, true, true, false)) != null) {
      recorder.record(frame);
      if ((System.currentTimeMillis() - t1) > RECORD_LENGTH) {
      break;
      }
      }
      recorder.stop();
      grabber.stop();
      }

      public static void packetRecord(String inputFile, String outputFile) throws FrameGrabber.Exception, FrameRecorder.Exception {

      int audioChannel = AUDIO_ENABLED ? 1 : 0;

      FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(inputFile);
      FFmpegFrameRecorder recorder = new FFmpegFrameRecorder(outputFile, 1280, 720, audioChannel);

      grabber.start();
      recorder.start(grabber.getFormatContext());

      avcodec.AVPacket packet;
      long t1 = System.currentTimeMillis();
      while ((packet = grabber.grabPacket()) != null) {
      recorder.recordPacket(packet);
      if ((System.currentTimeMillis() - t1) > RECORD_LENGTH) {
      break;
      }
      }

      recorder.stop();
      grabber.stop();
      }
      }


      This basic implementation shows how to convert a video using a FFmpeg packet or a JavaCV frame.






      share|improve this answer








      New contributor




      Teocci is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.




















        up vote
        0
        down vote










        up vote
        0
        down vote









        I know this is an old question but I think this might be useful for Java Developers.



        There is a nice library called JavaCV this live is a wrapper for multiple C and C++ libraries like FFmpeg.



        This is a simple example of how to implement a Converter:



        import org.bytedeco.javacpp.avcodec;

        import java.text.DateFormat;
        import java.text.SimpleDateFormat;
        import java.util.Date;

        public class PacketRecorderTest {

        private static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyyMMdd__hhmmSSS");

        private static final int RECORD_LENGTH = 5000;

        private static final boolean AUDIO_ENABLED = false;

        public static void main(String args) throws FrameRecorder.Exception, FrameGrabber.Exception {

        String inputFile = "/home/usr/videos/VIDEO_FILE_NAME.mp4";

        // Decodes-encodes
        String outputFile = "/tmp/" + DATE_FORMAT.format(new Date()) + "_frameRecord.mp4";
        PacketRecorderTest.frameRecord(inputFile, outputFile);

        // copies codec (no need to re-encode)
        outputFile = "/tmp/" + DATE_FORMAT.format(new Date()) + "_packetRecord.mp4";
        PacketRecorderTest.packetRecord(inputFile, outputFile);

        }

        public static void frameRecord(String inputFile, String outputFile) throws FrameGrabber.Exception, FrameRecorder.Exception {

        int audioChannel = AUDIO_ENABLED ? 1 : 0;

        FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(inputFile);
        FFmpegFrameRecorder recorder = new FFmpegFrameRecorder(outputFile, 1280, 720, audioChannel);

        grabber.start();
        recorder.start();

        Frame frame;
        long t1 = System.currentTimeMillis();
        while ((frame = grabber.grabFrame(AUDIO_ENABLED, true, true, false)) != null) {
        recorder.record(frame);
        if ((System.currentTimeMillis() - t1) > RECORD_LENGTH) {
        break;
        }
        }
        recorder.stop();
        grabber.stop();
        }

        public static void packetRecord(String inputFile, String outputFile) throws FrameGrabber.Exception, FrameRecorder.Exception {

        int audioChannel = AUDIO_ENABLED ? 1 : 0;

        FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(inputFile);
        FFmpegFrameRecorder recorder = new FFmpegFrameRecorder(outputFile, 1280, 720, audioChannel);

        grabber.start();
        recorder.start(grabber.getFormatContext());

        avcodec.AVPacket packet;
        long t1 = System.currentTimeMillis();
        while ((packet = grabber.grabPacket()) != null) {
        recorder.recordPacket(packet);
        if ((System.currentTimeMillis() - t1) > RECORD_LENGTH) {
        break;
        }
        }

        recorder.stop();
        grabber.stop();
        }
        }


        This basic implementation shows how to convert a video using a FFmpeg packet or a JavaCV frame.






        share|improve this answer








        New contributor




        Teocci is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.









        I know this is an old question but I think this might be useful for Java Developers.



        There is a nice library called JavaCV this live is a wrapper for multiple C and C++ libraries like FFmpeg.



        This is a simple example of how to implement a Converter:



        import org.bytedeco.javacpp.avcodec;

        import java.text.DateFormat;
        import java.text.SimpleDateFormat;
        import java.util.Date;

        public class PacketRecorderTest {

        private static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyyMMdd__hhmmSSS");

        private static final int RECORD_LENGTH = 5000;

        private static final boolean AUDIO_ENABLED = false;

        public static void main(String args) throws FrameRecorder.Exception, FrameGrabber.Exception {

        String inputFile = "/home/usr/videos/VIDEO_FILE_NAME.mp4";

        // Decodes-encodes
        String outputFile = "/tmp/" + DATE_FORMAT.format(new Date()) + "_frameRecord.mp4";
        PacketRecorderTest.frameRecord(inputFile, outputFile);

        // copies codec (no need to re-encode)
        outputFile = "/tmp/" + DATE_FORMAT.format(new Date()) + "_packetRecord.mp4";
        PacketRecorderTest.packetRecord(inputFile, outputFile);

        }

        public static void frameRecord(String inputFile, String outputFile) throws FrameGrabber.Exception, FrameRecorder.Exception {

        int audioChannel = AUDIO_ENABLED ? 1 : 0;

        FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(inputFile);
        FFmpegFrameRecorder recorder = new FFmpegFrameRecorder(outputFile, 1280, 720, audioChannel);

        grabber.start();
        recorder.start();

        Frame frame;
        long t1 = System.currentTimeMillis();
        while ((frame = grabber.grabFrame(AUDIO_ENABLED, true, true, false)) != null) {
        recorder.record(frame);
        if ((System.currentTimeMillis() - t1) > RECORD_LENGTH) {
        break;
        }
        }
        recorder.stop();
        grabber.stop();
        }

        public static void packetRecord(String inputFile, String outputFile) throws FrameGrabber.Exception, FrameRecorder.Exception {

        int audioChannel = AUDIO_ENABLED ? 1 : 0;

        FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(inputFile);
        FFmpegFrameRecorder recorder = new FFmpegFrameRecorder(outputFile, 1280, 720, audioChannel);

        grabber.start();
        recorder.start(grabber.getFormatContext());

        avcodec.AVPacket packet;
        long t1 = System.currentTimeMillis();
        while ((packet = grabber.grabPacket()) != null) {
        recorder.recordPacket(packet);
        if ((System.currentTimeMillis() - t1) > RECORD_LENGTH) {
        break;
        }
        }

        recorder.stop();
        grabber.stop();
        }
        }


        This basic implementation shows how to convert a video using a FFmpeg packet or a JavaCV frame.







        share|improve this answer








        New contributor




        Teocci is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.









        share|improve this answer



        share|improve this answer






        New contributor




        Teocci is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.









        answered 12 mins ago









        Teocci

        1011




        1011




        New contributor




        Teocci is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.





        New contributor





        Teocci is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.






        Teocci is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Code Review Stack Exchange!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            Use MathJax to format equations. MathJax reference.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f185545%2fffmpeg-with-java-wrapper%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Costa Masnaga

            Fotorealismo

            Sidney Franklin