Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

running ffmpeg command in java Process hangs in waitFor()

Tags:

java

ffmpeg

I'm running ffmpeg command to generate video for given images (img001.jpg, img002.jpg ...) it's creating slide.mp4, but it waits infinitely:

public class Ffmpeg {

public static void main(String[] args) throws IOException, InterruptedException {
    String path = "E:\\pics\\Santhosh\\FadeOut\\testing";       
    String cmd = "ffmpeg -r 1/5 -i img%03d.jpg -c:v libx264 -r 30 -y -pix_fmt yuv420p slide.mp4";
    runScript (path, cmd);
}

private static boolean runScript(String path, String cmd) throws IOException, InterruptedException {       
    List<String> commands = new ArrayList<String>();
    commands.add("cmd");
    commands.add("/c");
    commands.add(cmd);
    ProcessBuilder pb = new ProcessBuilder(commands);
    pb.directory(new File(path));
    pb.redirectErrorStream(true);
    Process process = pb.start();   
    flushInputStreamReader(process);                
    int exitCode = process.waitFor();
    return exitCode == 0;
}    
}

private static void flushInputStreamReader (Process process) throws IOException, InterruptedException {
            BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line=null;
            StringBuilder s = new StringBuilder();
            while((line=input.readLine()) != null) {            
                s.append(line);
            }
        }

Any suggestions?

After writing the function flushInputStreamReader, its working

like image 541
Mahesha M Avatar asked Nov 01 '22 02:11

Mahesha M


1 Answers

Aside from reading the ErrorStream, there's a better way to handle this.

Add -loglevel quiet to the command, so that the ErrorStream won't overflow and blocking the process at the first place.

like image 192
knucle Avatar answered Nov 04 '22 12:11

knucle