package com.usky.sas.common.hik.sdk;


import com.usky.sas.common.hik.sdk.HCNetSDK.FRealDataCallBack_V30;
import com.sun.jna.Pointer;
import java.io.IOException;
import java.nio.ByteBuffer;
import com.usky.sas.common.global.StreamContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FRealDataCallBack implements FRealDataCallBack_V30 {
    private static final Logger log = LoggerFactory.getLogger(FRealDataCallBack.class);
    StreamContext context;
    String macAddr;

    public FRealDataCallBack(StreamContext context, String macAddr) {
        this.context = context;
        this.macAddr = macAddr;
    }

    public void invoke(int lRealHandle, int dwDataType, Pointer pBuffer, int dwBufSize, Pointer pUser) {
        try {
            if (dwBufSize > 2097152) {
                log.warn("Frame size too large ({}) - truncating to {}", dwBufSize, 2097152);
                dwBufSize = 2097152;
            }

            ByteBuffer buffer = pBuffer.getByteBuffer(0L, (long)dwBufSize);
            buffer.get(this.context.frameBuffer, 0, dwBufSize);
            if (dwDataType == 2) {
                long currentTimestamp = (long)this.context.baseTimestamp;
                StreamContext var10000 = this.context;
                var10000.baseTimestamp += 3600;
                int offset = 0;

                int packetSize;
                for(int remaining = dwBufSize; remaining > 0; remaining -= packetSize) {
                    packetSize = Math.min(remaining, 1400);
                    boolean marker = remaining == packetSize;
                    byte[] rtpPacket = HikVideoStreamService.createRtpPacket(this.context.frameBuffer, offset, packetSize, marker, currentTimestamp, this.context.sequenceNumber, this.context.ssrc);
                    byte[] tcpPacket = HikVideoStreamService.createTcpPacket(rtpPacket);
                    this.context.sendExecutor.submit(() -> {
                        try {
                            this.context.rtpOutputStream.write(tcpPacket);
                            this.context.rtpOutputStream.flush();
                        } catch (IOException var3) {
                            log.error("RTP数据发送失败: {}", var3.getMessage(), var3);
                        }

                    });
                    this.context.sequenceNumber = this.context.sequenceNumber + 1 & '\uffff';
                    offset += packetSize;
                }
            }
        } catch (Exception var15) {
            log.error("设备 {} 数据发送失败: {}", this.macAddr, var15.getMessage());
            HikVideoStreamService.stopRealStreamData(lRealHandle, this.macAddr);
            this.context.close();
        }

    }
}
