package com.yfd.monitor.gdw2019.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

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

@Slf4j
@Component
public class StreamPusher {
    private Process process;
    private Thread outputThread;
    private Thread errorThread;

    public boolean pushStreamToParent(String ffmpeg_path,String fromRtsp, String parentRtsp) {
        String[] command = {
                ffmpeg_path + "ffmpeg",
                "-rtsp_transport", "tcp",
                "-i", fromRtsp,
                "-c:v", "copy",
                "-c:a", "copy",
                "-f", "rtsp",
                parentRtsp
        };
        try {
            process = new ProcessBuilder(command).start();

            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);
                }
            });

            errorThread = new Thread(() -> {
                try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getErrorStream()))) {
                    String line;
                    while ((line = reader.readLine()) != null) {
                        log.info(line);
                    }
                } catch (IOException e) {
                    log.error("发生错误", e);
                }
            });

            outputThread.start();
            errorThread.start();

            // 不再等待线程完成
        } catch (IOException e) {
            log.error("发生异常", e);
            return false;
        }
        return true;
    }

    // 新增停止推流的方法
    public void stopStreamProcess() {
        if (process != null) {
            process.destroy();
        }

        // 在这里中断两个线程
        if (outputThread != null) {
            outputThread.interrupt();
        }
        if (errorThread != null) {
            errorThread.interrupt();
        }
    }

    public static void main(String[] args) {
        StreamPusher streamPusher = new StreamPusher();
        String FFMPEG_PATH = "D:\\ZLMediaKit_Win\\ffmpeg\\bin\\ffmpeg";
        String FROM_RTSP = "rtsp://192.168.1.13:554/rtp/34020000001320000001_34020000001320000009";
        String PARENT_RTSP = "rtsp://192.168.1.13:554/live/test04?secret=035c73f7-bb6b-4889-a715-d9eb2d1925cc";
        boolean success = streamPusher.pushStreamToParent(FFMPEG_PATH, FROM_RTSP,PARENT_RTSP);

        if (success) {
            log.info("推流成功！");
        } else {
            log.info("推流失败！");
        }
        // 在需要停止推流的时候调用 stopStreamProcess 方法
        streamPusher.stopStreamProcess();
    }
}


