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

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

/**
 * GB28181 PS over RTP：同一 PS 帧分片共用 timestamp，末包置 M 位。
 */
public final class PsRtpPacketizer {

    /** GB28181 常用 RTP 负载上限 */
    public static final int MAX_PAYLOAD = 1400;

    private PsRtpPacketizer() {
    }

    public static List<byte[]> packetize(byte[] psFrame, int payloadType, int startSequence,
                                         long timestamp, long ssrc) {
        List<byte[]> packets = new ArrayList<>();
        if (psFrame == null || psFrame.length == 0) {
            return packets;
        }
        int offset = 0;
        int seq = startSequence;
        while (offset < psFrame.length) {
            int chunk = Math.min(psFrame.length - offset, MAX_PAYLOAD);
            boolean marker = offset + chunk >= psFrame.length;
            byte[] payload = Arrays.copyOfRange(psFrame, offset, offset + chunk);
            packets.add(RtpPacketBuilder.build(payload, payloadType, seq++, timestamp, ssrc, marker));
            offset += chunk;
        }
        return packets;
    }
}
