package com.foxx.androidcast.sender;

/*********************************************************************
 * EncoderKeepalive.java
 * Created at: Fri 15 May 2026 20:37:44 +0200
 * Updated at: Wed 20 May 2026 15:17:13 +0200 by Anton Afanasyeu <a.afanasieff@gmail.com>
 * Commit: 5d8e82d2e60a21fff3138d2a394ee4e8b4c6dcb8
 * class EncoderKeepalive
 * Contributors:
 *    - Anton Afanasyeu <a.afanasieff@gmail.com> (4 commits, 62 lines)
 *    - Cursor Agent (project assistant)
 * Digest: SHA256	04bcde62a3a1122d433e0fefdd1aa469f841cc89aed8f0ddfd2327814bf58131
**********************************************************************/
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import com.foxx.androidcast.CastConfig;
import com.foxx.androidcast.media.codec.VideoEncoderSink;

/**
 * Periodic keyframe requests so Mediatek/others don't stall on a static screen
 * (encoder stops emitting; receiver hits idle overlay).
 */
public final class EncoderKeepalive {
    private static final String TAG = "EncoderKeepalive";

    private final Handler handler;
    private VideoEncoderSink encoder;
    private boolean running;

    public EncoderKeepalive() {
        this(new Handler(Looper.getMainLooper()));
    }

    public EncoderKeepalive(Handler handler) {
        this.handler = handler != null ? handler : new Handler(Looper.getMainLooper());
    }

    private final Runnable tick = new Runnable() {
        @Override
        public void run() {
            if (!running || encoder == null) {
                return;
            }
            encoder.requestKeyframe();
            Log.d(TAG, "Keepalive keyframe requested");
            handler.postDelayed(this, CastConfig.KEYFRAME_KEEPALIVE_MS);
        }
    };

    public void start(VideoEncoderSink encoder) {
        this.encoder = encoder;
        if (running) {
            return;
        }
        running = true;
        handler.postDelayed(tick, CastConfig.KEYFRAME_KEEPALIVE_MS);
    }

    public void stop() {
        running = false;
        handler.removeCallbacks(tick);
        encoder = null;
    }
}
