package com.usky.sas.common.global;

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class StreamContext {
    private static final Logger log = LoggerFactory.getLogger(StreamContext.class);
    public final ExecutorService sendExecutor = Executors.newSingleThreadExecutor((r) -> {
        return new Thread(r, "RTP-Data-Writer");
    });
    public static final int MAX_FRAME_SIZE = 2097152;
    public final byte[] frameBuffer = new byte[2097152];
    Socket rtpSocket;
    public OutputStream rtpOutputStream;
    public int sequenceNumber;
    public int baseTimestamp;
    public long ssrc;

    public StreamContext(String serverIp, int serverPort) throws IOException {
        this.rtpSocket = new Socket(serverIp, serverPort);
        this.rtpOutputStream = this.rtpSocket.getOutputStream();
        this.sequenceNumber = (new Random()).nextInt(10000);
        this.baseTimestamp = (new Random()).nextInt(100000);
    }

    public synchronized void close() {
        try {
            if (this.rtpOutputStream != null) {
                this.rtpOutputStream.close();
            }
        } catch (IOException var4) {
            log.error("关闭输出流失败: {}", var4.getMessage());
        }

        try {
            if (this.rtpSocket != null) {
                this.rtpSocket.close();
            }
        } catch (IOException var3) {
            log.error("关闭Socket失败: {}", var3.getMessage());
        }

        this.sendExecutor.shutdown();
        log.info("关闭{}线程池成功", this.sendExecutor.getClass());

        try {
            if (!this.sendExecutor.awaitTermination(5L, TimeUnit.SECONDS)) {
                log.info("线程池关闭超时，强制终止");
                this.sendExecutor.shutdownNow();
            }
        } catch (InterruptedException var2) {
            this.sendExecutor.shutdownNow();
            Thread.currentThread().interrupt();
        }

    }
}
