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 FRealDataCallBackEx implements NetSDKLib.fRealDataCallBackEx {
    private static final Logger log = LoggerFactory.getLogger(FRealDataCallBackEx.class);
    StreamContext context;
    String macAddr;

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

    public void invoke(Long lRealHandle, int dwDataType, Pointer pBuffer, int dwBufSize, int param, Pointer dwUser) {
        try {
            log.info("实时预览回调");
            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 == 0) {
                log.info("原始数据");
                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 e) {
            log.error("设备 {} 数据发送失败: {}", this.macAddr, e.getMessage());
            this.context.close();
        }

    }
}
