package com.yfd.monitor.gdw2019.utils;

import cn.hutool.core.io.FileUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

@Slf4j
public class VideoToImageUtil {

    public static void getVideoPicture(String ffmpegpath,String videoUrl, String imgfile) {
        try {
            System.out.println("ffmpegpath"+ffmpegpath);
            System.out.println("videoUrl"+videoUrl);
            System.out.println("imgfile"+imgfile);
            FileUtil.touch(imgfile);
            String[] command = {
                    ffmpegpath + "ffmpeg",
                    "-rtsp_transport", "tcp",
                    "-i", videoUrl,
                    "-f", "mjpeg",
                    "-t", "0.001",
                    "-y", // 强制覆盖已存在的文件
                    imgfile
            };
            Process process = new ProcessBuilder(command).start();
            // 创建并启动线程处理标准输出流
            Thread outputThread = new Thread(() -> {
                try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
                    String line;
                    while ((line = reader.readLine()) != null) {
                        System.err.println(line);
                    }
                } catch (IOException e) {
                    log.error("发生错误", e);
                    throw new RuntimeException(e.getMessage());
                }
            });
            // 启动线程
            outputThread.start();
            Thread errorThread = new Thread(() -> {
                try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getErrorStream()))) {
                    String line;
                    while ((line = reader.readLine()) != null) {
                    }
                } catch (IOException e) {
                    log.error("发生错误", e);
                    throw new RuntimeException(e.getMessage());
                }
            });
            errorThread.start();
            // 等待FFmpeg进程完成
            int exitCode = process.waitFor();
            if (exitCode == 0) {
                log.info("视频帧提取完毕！");
            } else {
                log.info("FFmpeg进程出错");
            }
        } catch (Exception e) {
            log.error("发生错误", e);
            throw new RuntimeException("抓取视频失败");
        }
    }

    public static void main(String[] args) {
        try {
            String ffmpegpath = "d:\\ZLMediaKit_Win\\ffmpeg\\bin\\";
            //String videoUrl = "rtsp://admin:JY123456@192.168.1.66:554/Streaming/Channels/101";
            String videoUrl = "rtsp://192.168.1.13:554/rtp/34020000001110000009_34020000001310000001";
            String audioPath = "D:/test.wav";
            VideoToImageUtil.getVideoPicture(ffmpegpath,videoUrl,audioPath);
        } catch (Exception e) {
            log.error("发生错误", e);
            throw new RuntimeException(e.getMessage());
        }
    }


}
