package com.usky.sas.common.dahua;

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

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

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

    public void invoke(Long lRealHandle, int dwDataType, Pointer pBuffer, int dwBufSize, Pointer dwUser) {
        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);
            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 = DahuaVideoStreamService.createRtpPacket(this.context.frameBuffer, offset, packetSize, marker, currentTimestamp, this.context.sequenceNumber, this.context.ssrc);
                byte[] tcpPacket = DahuaVideoStreamService.createTcpPacket(rtpPacket);
                this.context.sendExecutor.submit(() -> {
                    try {
                        this.context.rtpOutputStream.write(tcpPacket);
                        this.context.rtpOutputStream.flush();
                    } catch (IOException e) {
                        log.error("RTP数据发送失败: {}", e.getMessage(), e);
                    }

                });
                this.context.sequenceNumber = this.context.sequenceNumber + 1 & '\uffff';
                offset += packetSize;
            }
        } catch (Exception var15) {
            DahuaVideoStreamService.stopPlayStreamData(lRealHandle, this.macAddr);
            this.context.close();
        }

    }
}
