package com.foxx.androidcast.media.codec;

/*********************************************************************
 * LibvpxCapableVideoDecoder.java
 * Created at: Mon 18 May 2026 17:05:47 +0200
 * Updated at: Wed 20 May 2026 15:17:13 +0200 by Anton Afanasyeu <a.afanasieff@gmail.com>
 * Commit: 5d8e82d2e60a21fff3138d2a394ee4e8b4c6dcb8
 * class LibvpxCapableVideoDecoder
 * Contributors:
 *    - Anton Afanasyeu <a.afanasieff@gmail.com> (2 commits, 59 lines)
 *    - Cursor Agent (project assistant)
 * Digest: SHA256	26843b12f2436c44befd5fc8851b9ef41a507eb77e84434d07a51f1797cd717c
**********************************************************************/
import android.util.Log;
import android.view.Surface;

import com.foxx.androidcast.media.CodecNegotiator;
import com.foxx.androidcast.receiver.LibvpxVideoDecoder;
import com.foxx.androidcast.receiver.VideoDecoder;

import java.io.IOException;

/**
 * Uses libvpx for VP8/VP9 when linked; otherwise or on failure falls back to {@link VideoDecoder}.
 */
public final class LibvpxCapableVideoDecoder implements VideoDecoderSink {
    private static final String TAG = "LibvpxCapableVideoDecoder";

    private final VideoDecoder hwDecoder = new VideoDecoder();
    private final LibvpxVideoDecoder libvpxDecoder = new LibvpxVideoDecoder();
    private VideoDecoderSink active;

    @Override
    public void configure(String mime, int width, int height, byte[] csd0, byte[] csd1, Surface surface,
            Listener listener) throws IOException {
        if (CodecNegotiator.isVpx(mime)) {
            try {
                libvpxDecoder.configure(mime, width, height, csd0, csd1, surface, listener);
                active = libvpxDecoder;
                Log.i(TAG, "Using libvpx for " + mime);
                return;
            } catch (IOException e) {
                Log.w(TAG, "libvpx decode unavailable, trying MediaCodec: " + e.getMessage());
            }
        }
        hwDecoder.configure(mime, width, height, csd0, csd1, surface, listener);
        active = hwDecoder;
    }

    @Override
    public void queueFrame(long ptsUs, boolean keyFrame, byte[] data) {
        if (active != null) {
            active.queueFrame(ptsUs, keyFrame, data);
        }
    }

    @Override
    public void release() {
        hwDecoder.release();
        libvpxDecoder.release();
        active = null;
    }
}
