package com.fuyuanshen.global.mqtt.utils;

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

public class FfmpegVolumeUtil {

    /**
     * 使用FFmpeg增加MP3文件的音量
     *
     * @param inputFilePath  输入MP3文件路径
     * @param outputFilePath 输出MP3文件路径
     * @param volumeGain     音量增益（例如：1.5表示增加50%音量，2.0表示翻倍）
     */
    public static void increaseMp3Volume(String inputFilePath, String outputFilePath, int volumeGain) {
        boolean ffmpegAvailable = isFfmpegAvailable();
        if (!ffmpegAvailable) {
            System.err.println("FFmpeg未安装或未找到！请安装FFmpeg并确保在系统路径中。");
            return;
        }

        // 检查输入文件
        File inputFile = new File(inputFilePath);
        if (!inputFile.exists()) {
            System.err.println("输入文件不存在：" + inputFilePath);
            return;
        }
        if (!inputFile.canRead()) {
            System.err.println("输入文件不可读：" + inputFilePath);
            return;
        }

        // 创建输出目录
        File outputFile = new File(outputFilePath);
        File parentDir = outputFile.getParentFile();
        if (parentDir != null) {
            parentDir.mkdirs();
            if (!parentDir.canWrite()) {
                System.err.println("输出目录不可写：" + parentDir.getAbsolutePath());
                return;
            }
        }

        Process process = null;
        try {
            String command = String.format(
                    "ffmpeg -y -i \"%s\" -af \"volume=%sdB\" \"%s\"",
                    inputFilePath,
                    volumeGain,
                    outputFilePath
            );

            System.out.println("执行命令: " + command);

            // 使用 ProcessBuilder 提供更好的控制
            ProcessBuilder processBuilder = new ProcessBuilder("ffmpeg", "-y",
                    "-i", inputFilePath, "-af", "volume=" + volumeGain + "dB", outputFilePath);
            processBuilder.redirectErrorStream(false);
            process = processBuilder.start();

            // 同时读取标准输出和错误输出
            Process finalProcess = process;
            Thread stdOutThread = new Thread(() -> {
                try (BufferedReader reader = new BufferedReader(
                        new InputStreamReader(finalProcess.getInputStream()))) {
                    String line;
                    while ((line = reader.readLine()) != null) {
                        System.out.println("[FFmpeg STDOUT] " + line);
                    }
                } catch (IOException e) {
                    System.err.println("读取标准输出时出错: " + e.getMessage());
                }finally {
                    finalProcess.destroy();
                }
            });

            Process finalProcess1 = process;
            Thread stdErrThread = new Thread(() -> {
                try (BufferedReader reader = new BufferedReader(
                        new InputStreamReader(finalProcess1.getErrorStream()))) {
                    String line;
                    while ((line = reader.readLine()) != null) {
                        System.err.println("[FFmpeg STDERR] " + line);
                    }
                } catch (IOException e) {
                    System.err.println("读取错误输出时出错: " + e.getMessage());
                }finally {
                    finalProcess1.destroy();
                }
            });

            stdOutThread.start();
            stdErrThread.start();

            int exitCode = process.waitFor();
            stdOutThread.join();
            stdErrThread.join();

            if (exitCode == 0) {
                System.out.println("音量调整成功！输出文件：" + outputFilePath);
            } else {
                System.err.println("FFmpeg命令执行失败，退出码：" + exitCode);
            }
        } catch (IOException | InterruptedException e) {
            System.err.println("执行FFmpeg命令时发生错误: " + e.getMessage());
            e.printStackTrace();
        } finally {
            if (process != null) {
                System.out.println("已销毁进程");
                process.destroy();
            }
        }
    }


    public static void main(String[] args) {

        // 示例用法
        String inputPath = "/app/input.mp3";
        String outputPath = "/app/output17.mp3";
        int volumeGain = 12;

        increaseMp3Volume(inputPath, outputPath, volumeGain);
    }

    private static boolean isFfmpegAvailable() {
        try {
            Process process = Runtime.getRuntime().exec("ffmpeg -version");
            int exitCode = process.waitFor();
            return exitCode == 0;
        } catch (Exception e) {
            return false;
        }
    }

}

