package com.foxx.androidcast.media;

/*********************************************************************
 * AacAdtsHelper.java
 * Created at: Sat 16 May 2026 13:35:48 +0200
 * Updated at: Wed 20 May 2026 15:17:13 +0200 by Anton Afanasyeu <a.afanasieff@gmail.com>
 * Commit: 5d8e82d2e60a21fff3138d2a394ee4e8b4c6dcb8
 * class AacAdtsHelper
 * Contributors:
 *    - Anton Afanasyeu <a.afanasieff@gmail.com> (2 commits, 67 lines)
 *    - Cursor Agent (project assistant)
 * Digest: SHA256	801727a4bf81e2b3538fcacffd5434d5e9f834052b29da4728a860caf98d44a9
**********************************************************************/
/** Prepends ADTS sync word so AAC decoders accept encoder access units. */
public final class AacAdtsHelper {
    private AacAdtsHelper() {}

    public static byte[] wrapIfNeeded(byte[] aacFrame, int sampleRate, int channelCount) {
        if (aacFrame == null || aacFrame.length == 0) {
            return aacFrame;
        }
        if (aacFrame.length >= 2 && (aacFrame[0] & 0xFF) == 0xFF && (aacFrame[1] & 0xF0) == 0xF0) {
            return aacFrame;
        }
        int profile = 2;
        int freqIdx = sampleRateIndex(sampleRate);
        int chanCfg = Math.max(1, Math.min(7, channelCount));
        int frameLen = aacFrame.length + 7;
        byte[] adts = new byte[frameLen];
        adts[0] = (byte) 0xFF;
        adts[1] = (byte) 0xF1;
        adts[2] = (byte) (((profile - 1) << 6) + (freqIdx << 2) + (chanCfg >> 2));
        adts[3] = (byte) (((chanCfg & 3) << 6) + (frameLen >> 11));
        adts[4] = (byte) ((frameLen & 0x7FF) >> 3);
        adts[5] = (byte) (((frameLen & 7) << 5) + 0x1F);
        adts[6] = (byte) 0xFC;
        System.arraycopy(aacFrame, 0, adts, 7, aacFrame.length);
        return adts;
    }

    private static int sampleRateIndex(int sampleRate) {
        switch (sampleRate) {
            case 96000:
                return 0;
            case 88200:
                return 1;
            case 64000:
                return 2;
            case 48000:
                return 3;
            case 44100:
                return 4;
            case 32000:
                return 5;
            case 24000:
                return 6;
            case 22050:
                return 7;
            case 16000:
                return 8;
            case 12000:
                return 9;
            case 11025:
                return 10;
            case 8000:
                return 11;
            default:
                return 4;
        }
    }
}
