package com.foxx.androidcast.media;

/*********************************************************************
 * StreamDimensionResolver.java
 * Created at: Fri 15 May 2026 17:47:09 +0200
 * Updated at: Wed 20 May 2026 15:17:13 +0200 by Anton Afanasyeu <a.afanasieff@gmail.com>
 * Commit: 5d8e82d2e60a21fff3138d2a394ee4e8b4c6dcb8
 * class StreamDimensionResolver
 * Contributors:
 *    - Anton Afanasyeu <a.afanasieff@gmail.com> (2 commits, 49 lines)
 *    - Cursor Agent (project assistant)
 * Digest: SHA256	1630558a8817b3155c394d96aa9064ef6cad027ab28ed1727ed18a7d6842dc6d
**********************************************************************/
/**
 * Resolves display dimensions using STREAM_CONFIG and SPS (csd-0).
 * SPS confirms coded size; config reflects sender VirtualDisplay (preferred for rotation).
 */
public final class StreamDimensionResolver {
    private StreamDimensionResolver() {}

    public static final class Size {
        public final int width;
        public final int height;
        public final boolean fromSps;

        public Size(int width, int height, boolean fromSps) {
            this.width = width;
            this.height = height;
            this.fromSps = fromSps;
        }
    }

    public static Size resolve(int configWidth, int configHeight, byte[] csd0) {
        H264SpsParser.Dimensions sps = H264SpsParser.parseDimensions(csd0);
        if (configWidth > 0 && configHeight > 0) {
            if (sps != null && dimensionsSwapped(configWidth, configHeight, sps.width, sps.height)) {
                // Encoder SPS matches rotated buffer — use SPS for display aspect
                return new Size(sps.width, sps.height, true);
            }
            return new Size(configWidth, configHeight, false);
        }
        if (sps != null) {
            return new Size(sps.width, sps.height, true);
        }
        return new Size(Math.max(configWidth, 2), Math.max(configHeight, 2), false);
    }

    private static boolean dimensionsSwapped(int cw, int ch, int sw, int sh) {
        boolean configLandscape = cw >= ch;
        boolean spsLandscape = sw >= sh;
        return configLandscape != spsLandscape && cw != sw && ch != sh;
    }
}
