package com.ema.common.utils;

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

import java.io.File;

@Slf4j
public class AudioVideoConverterUtil {

    /**
     * 音频转码到MP3
     *
     * @param source
     * @return
     */
    public static File convertToMp3(File source) {
        String sourcePath = source.getAbsolutePath();
        if (StrUtil.equalsIgnoreCase(FileUtil.getSuffix(sourcePath), "mp3")) {
            return source;
        }
        String targetPath = StrUtil.subBefore(sourcePath, ".", true) + CodeUtil.getCode(2) + ".mp3";
        String[] command = {
                "ffmpeg", "-y", "-i", sourcePath,
                "-c:a", "libmp3lame",
                "-b:a", "128k", targetPath
        };
        boolean ffmpeg = ffmpeg(command);
        if (ffmpeg) {
            FileUtil.del(source);
            return new File(targetPath);
        }
        return source;
    }

    /**
     * 视频转码到MP4
     *
     * @param source
     * @return
     */
    public static File convertToMp4(File source) {
        String sourcePath = source.getAbsolutePath();
        String targetPath = StrUtil.subBefore(sourcePath, ".", true) + CodeUtil.getCode(2) + ".mp4";
        String[] command = {
                "ffmpeg", "-y", "-i", sourcePath,
                "-c:v", "libx264", "-preset", "fast", "-crf", "23",
                "-c:a", "aac", targetPath
        };
        boolean ffmpeg = ffmpeg(command);
        if (ffmpeg) {
            FileUtil.del(source);
            return new File(targetPath);
        }
        return source;
    }

    /**
     * 执行FFmpeg命令
     *
     * @param command FFmpeg命令数组
     * @return 是否成功
     */
    private static boolean ffmpeg(String[] command) {
        try {
            Process process = new ProcessBuilder(command)
                    .redirectErrorStream(false)
                    .inheritIO()
                    .start();
            return process.waitFor() == 0;
        } catch (Exception e) {
            log.error("FFmpeg 转码失败: {}", e.getMessage());
            return false;
        }
    }


}
