package com.yfd.platform.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;

@Slf4j
public class VideoToImageUtil {



    public static void getVideoPicture(String ffmpegpath,String videoUrl, String imgfile) {
        FileUtil.touch(imgfile);
        // 确保文件存在
        try {

            // 构建命令数组
            String[] command = {
                    ffmpegpath + "ffmpeg",
                    "-loglevel", "quiet",
                    "-i", videoUrl,
                    "-vframes", "1",
                    "-y",
                    imgfile
            };

            log.info(Arrays.toString(command));
            // 启动FFmpeg进程
            Process process = new ProcessBuilder(command)
                    .redirectInput(ProcessBuilder.Redirect.INHERIT)
                    .redirectOutput(ProcessBuilder.Redirect.INHERIT)
                    .redirectError(ProcessBuilder.Redirect.INHERIT)
                    .start();

            // 等待FFmpeg进程完成
            boolean isFlag = process.waitFor(3, TimeUnit.SECONDS);
            if (isFlag) {
                log.info("视频帧提取完毕！");
            } else {
                log.info("FFmpeg进程出错");
                process.destroy();
                throw new RuntimeException("抓取视频失败");
            }

        } catch (Exception e) {
            log.error("发生错误", e);
            throw new RuntimeException("抓取视频失败");
        }
    }

    public static void saveCaptureAudioFile(String ffmpegpath, String videoUrl, String audiofile) {
        try {
            // 构建FFmpeg命令
            FileUtil.touch(audiofile);
            String[] command = {
                    ffmpegpath + "ffmpeg",
                    "-i", videoUrl,
                    "-acodec", "pcm_s16le", // 更改音频编码为pcm_s16le
                    "-ar", "44100",
                    "-t", "10",
                    "-y", // 强制覆盖已存在的文件
                    audiofile
            };
            // 启动FFmpeg进程
            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) {
                        log.info(line);
                    }
                } catch (IOException e) {
                    log.error(e.getMessage());;
                }
            });
          // 启动线程
            outputThread.start();

            Thread errorThread = new Thread(() -> {
                try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getErrorStream()))) {
                    String line;
                    while ((line = reader.readLine()) != null) {
                       log.error(line);
                    }
                } catch (IOException e) {
                    log.error(e.getMessage());;
                }
            });
            errorThread.start();

            // 等待FFmpeg进程完成
            int exitCode = process.waitFor();
            if (exitCode == 0) {
                log.info("声音录制完成！");
            } else {
                log.error("FFmpeg进程出错，退出码：" + exitCode);
            }

        } catch (Exception e) {
            log.error(e.getMessage());;
            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:31554/rtp/34020000001110000009_34020000001310000001";
            String audioPath = "D:/test.wav";
            VideoToImageUtil.saveCaptureAudioFile(ffmpegpath,videoUrl,audioPath);
        } catch (Exception e) {
            log.error(e.getMessage());;
        }
    }


}
