package com.luqj.javacv.utils; import org.bytedeco.ffmpeg.global.avcodec; import org.bytedeco.javacv.FFmpegFrameGrabber; import org.bytedeco.javacv.FFmpegFrameRecorder; import org.bytedeco.javacv.Frame; import org.bytedeco.javacv.Java2DFrameConverter; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.UUID; import java.util.concurrent.atomic.AtomicReference; public class MjpegUtil { private static final int DEFAULT_TIMEOUT_MS = 10000; public String snapshop(String basePath) throws Exception { return ""; } public static void ffmpegRecord(String mjpegUrl, String outputFile, int seconds) throws Exception { ffmpegRecord(mjpegUrl, outputFile, seconds, DEFAULT_TIMEOUT_MS); } public static void ffmpegRecord(String mjpegUrl, String outputFile, int seconds, int timeoutMs) throws Exception { AtomicReference error = new AtomicReference<>(); Thread thread = new Thread(() -> { FFmpegFrameGrabber grabber = null; FFmpegFrameRecorder recorder = null; Frame frame = null; try { grabber = new FFmpegFrameGrabber(mjpegUrl); grabber.start(); int width = grabber.getImageWidth(); int height = grabber.getImageHeight(); recorder = new FFmpegFrameRecorder(outputFile, width, height); recorder.setVideoCodec(avcodec.AV_CODEC_ID_H264); recorder.setFormat("mp4"); recorder.setFrameRate(25); recorder.start(); long startTime = System.currentTimeMillis(); long duration = seconds * 1000L; long frameInterval = 40; while (System.currentTimeMillis() - startTime < duration) { frame = grabber.grabImage(); if (frame != null) { long timestamp = System.currentTimeMillis() - startTime; recorder.setTimestamp(timestamp * 1000); recorder.record(frame); frame.close(); frame = null; } Thread.sleep(frameInterval); } } catch (Exception e) { error.set(e); } finally { if (frame != null) { try { frame.close(); } catch (Exception ignored) { } } if (recorder != null) { try { recorder.stop(); recorder.release(); } catch (Exception ignored) { } } if (grabber != null) { try { grabber.stop(); grabber.release(); } catch (Exception ignored) { } } } }); thread.setDaemon(true); thread.start(); try { thread.join(timeoutMs); if (thread.isAlive()) { throw new Exception("ffmpegRecord timeout"); } if (error.get() != null) { throw error.get(); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new Exception("ffmpegRecord interrupted"); } } public static String ffmepgeSnapshot(String mjpegUrl, String path) throws Exception { return ffmepgeSnapshot(mjpegUrl, path, DEFAULT_TIMEOUT_MS); } public static String ffmepgeSnapshot(String mjpegUrl, String path, int timeoutMs) throws Exception { AtomicReference result = new AtomicReference<>(); AtomicReference error = new AtomicReference<>(); Thread thread = new Thread(() -> { FFmpegFrameGrabber grabber = null; Frame frame = null; Java2DFrameConverter converter = null; try { grabber = new FFmpegFrameGrabber(mjpegUrl); grabber.setOption("rtsp_transport", "tcp"); grabber.start(); for (int i = 0; i < 5; i++) { frame = grabber.grabImage(); if (frame != null) break; } if (frame != null) { converter = new Java2DFrameConverter(); BufferedImage img = converter.getBufferedImage(frame); String basePath = path; if (!basePath.endsWith("/")) { basePath = basePath + "/"; } String filename = uuid() + "_snapshot.jpg"; String savePathUrl = basePath + filename; ImageIO.write(img, "jpg", new File(savePathUrl)); result.set(filename); } } catch (Exception e) { error.set(e); } finally { if (frame != null) { try { frame.close(); } catch (Exception ignored) { } } if (converter != null) { try { converter.close(); } catch (Exception ignored) { } } if (grabber != null) { try { grabber.stop(); grabber.close(); } catch (Exception ignored) { } } } }); thread.setDaemon(true); thread.start(); try { thread.join(timeoutMs); if (thread.isAlive()) { throw new Exception("ffmepgeSnapshot timeout"); } if (error.get() != null) { throw error.get(); } return result.get(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new Exception("ffmepgeSnapshot interrupted"); } } public static String uuid() { return UUID.randomUUID().toString().replaceAll("-", ""); } public static String snapshot(String mjpegUrl, String path) throws Exception { return snapshot(mjpegUrl, path, DEFAULT_TIMEOUT_MS); } public static String snapshot(String mjpegUrl, String path, int timeoutMs) throws Exception { AtomicReference result = new AtomicReference<>(); AtomicReference error = new AtomicReference<>(); Thread thread = new Thread(() -> { HttpURLConnection conn = null; InputStream input = null; try { URL url = new URL(mjpegUrl); conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(10000); conn.setConnectTimeout(5000); input = conn.getInputStream(); ByteArrayOutputStream jpgBuffer = new ByteArrayOutputStream(); int prev = 0; int cur; boolean start = false; while ((cur = input.read()) != -1) { if (!start) { if (prev == 0xFF && cur == 0xD8) { start = true; jpgBuffer.write(0xFF); } } if (start) { jpgBuffer.write(cur); if (prev == 0xFF && cur == 0xD9) { break; } } prev = cur; } String basePath = path; if (!basePath.endsWith("/")) { basePath = basePath + "/"; } byte[] jpgBytes = jpgBuffer.toByteArray(); String filename = uuid() + "_snapshot.jpg"; String savePathUrl = basePath + filename; BufferedImage image = ImageIO.read(new ByteArrayInputStream(jpgBytes)); ImageIO.write(image, "jpg", new File(savePathUrl)); result.set(filename); } catch (Exception e) { error.set(e); } finally { if (input != null) { try { input.close(); } catch (Exception ignored) { } } if (conn != null) { conn.disconnect(); } } }); thread.setDaemon(true); thread.start(); try { thread.join(timeoutMs); if (thread.isAlive()) { throw new Exception("snapshot timeout"); } if (error.get() != null) { throw error.get(); } return result.get(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new Exception("snapshot interrupted"); } } }