package com.foxx.androidcast.sender;

/*********************************************************************
 * SenderAudioMetrics.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 SenderAudioMetrics
 * Contributors:
 *    - Anton Afanasyeu <a.afanasieff@gmail.com> (2 commits, 68 lines)
 *    - Cursor Agent (project assistant)
 * Digest: SHA256	e9fabee1f157bc069f89481a2f5d9bb0b503e7dcf77a8282ebce6974089b1cf8
**********************************************************************/
import com.foxx.androidcast.media.PcmLevelAnalyzer;

/** Pre-encode PCM level stats on the sender. */
public final class SenderAudioMetrics {
    private long silentBlocks;
    private long audibleBlocks;
    private float vuSmoothed;
    private float lastPeakDb = -96f;
    private float lastRmsDb = -96f;

    public synchronized void onPcm(PcmLevelAnalyzer.Levels levels) {
        if (levels == null) {
            return;
        }
        if (levels.silent) {
            silentBlocks++;
        } else {
            audibleBlocks++;
        }
        float instant = Math.max(levels.peak, levels.rms);
        vuSmoothed = instant > vuSmoothed
                ? instant * 0.35f + vuSmoothed * 0.65f
                : instant * 0.12f + vuSmoothed * 0.88f;
        if (levels.peak > 1e-9f) {
            lastPeakDb = levels.peakDb();
        }
        if (levels.rms > 1e-9f) {
            lastRmsDb = (float) (20.0 * Math.log10(levels.rms));
        }
    }

    public synchronized void reset() {
        silentBlocks = 0;
        audibleBlocks = 0;
        vuSmoothed = 0f;
        lastPeakDb = -96f;
        lastRmsDb = -96f;
    }

    public synchronized long getSilentBlocks() {
        return silentBlocks;
    }

    public synchronized long getAudibleBlocks() {
        return audibleBlocks;
    }

    public synchronized int getVuPercent() {
        return PcmLevelAnalyzer.vuPercent(vuSmoothed);
    }

    public synchronized float getLastPeakDb() {
        return lastPeakDb;
    }

    public synchronized float getLastRmsDb() {
        return lastRmsDb;
    }
}
