package com.usky.cdi.service.sip.rtp;

import java.util.ArrayList;
import java.util.List;

/**
 * H264 NAL 单元 RTP 封装（Single NAL / FU-A）
 */
public final class H264RtpPacketizer {

    private static final int MAX_PAYLOAD = 1400;

    private H264RtpPacketizer() {
    }

    public static List<byte[]> packetize(byte[] nal, int payloadType, int startSequence,
                                         long timestamp, long ssrc) {
        List<byte[]> packets = new ArrayList<>();
        if (nal == null || nal.length == 0) {
            return packets;
        }
        if (nal.length <= MAX_PAYLOAD) {
            packets.add(RtpPacketBuilder.build(nal, payloadType, startSequence, timestamp, ssrc, true));
            return packets;
        }
        int nalType = nal[0] & 0x1F;
        int nalHeader = nal[0] & 0xE0;
        int offset = 1;
        int remaining = nal.length - 1;
        int seq = startSequence;
        boolean first = true;
        while (remaining > 0) {
            int chunk = Math.min(remaining, MAX_PAYLOAD - 2);
            boolean last = chunk == remaining;
            byte[] payload = new byte[2 + chunk];
            payload[0] = (byte) (nalHeader | 28);
            payload[1] = (byte) ((first ? 0x80 : 0) | (last ? 0x40 : 0) | nalType);
            System.arraycopy(nal, offset, payload, 2, chunk);
            packets.add(RtpPacketBuilder.build(payload, payloadType, seq++, timestamp, ssrc, last));
            offset += chunk;
            remaining -= chunk;
            first = false;
        }
        return packets;
    }
}
