Pith - timber
package com.vgmlr.timber

import android.annotation.SuppressLint
import android.content.Context
import android.media.AudioAttributes
import android.media.MediaPlayer
import android.media.audiofx.Visualizer
import android.net.Uri
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableLongStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import kotlinx.coroutines.Job
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch

private const val PLAY_TICK = 50L
private const val VIZ_SIZE = 512

internal object TimberPlayer {
    var uri by mutableStateOf<Uri?>(null); private set
    var paused by mutableStateOf(false); private set
    var position by mutableLongStateOf(0L); private set
    var length by mutableLongStateOf(0L); private set
    var spectrum by mutableStateOf(NO_BINS); private set

    private val scope = MainScope()
    private var mp: MediaPlayer? = null
    private var viz: Visualizer? = null
    private var tick: Job? = null
    private var fftBuf = ByteArray(0)
    private var vizRate = 0

    @SuppressLint("MissingPermission")
    fun play(ctx: Context, target: Uri): Boolean {
        stop()
        val p = MediaPlayer()
        val ok = runCatching {
            p.setAudioAttributes(
                AudioAttributes.Builder()
                    .setUsage(AudioAttributes.USAGE_MEDIA)
                    .setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
                    .setAllowedCapturePolicy(AudioAttributes.ALLOW_CAPTURE_BY_NONE)
                    .build()
            )
            p.setDataSource(ctx, target)
            p.prepare()
        }.isSuccess
        if (!ok) {
            p.release()
            return false
        }
        p.setOnCompletionListener { stop() }
        p.start()
        mp = p
        viz = runCatching {
            Visualizer(p.audioSessionId).apply {
                val range = Visualizer.getCaptureSizeRange()
                captureSize = VIZ_SIZE.coerceIn(range[0], range[1])
                enabled = true
            }
        }.getOrNull()
        fftBuf = ByteArray(viz?.captureSize ?: 0)
        vizRate = (viz?.samplingRate ?: 0) / 1000 // mHz to Hz
        uri = target
        paused = false
        length = p.duration.toLong().coerceAtLeast(0L)
        position = 0L
        tick = scope.launch {
            while (isActive) {
                sample()
                delay(PLAY_TICK)
            }
        }
        return true
    }

    private fun sample() {
        val p = mp ?: return
        position = runCatching { p.currentPosition.toLong() }.getOrDefault(position)
        val fresh = if (paused) null else viz?.let { v ->
            runCatching {
                if (v.getFft(fftBuf) == Visualizer.SUCCESS) vizBins(fftBuf, vizRate) else null
            }.getOrNull()
        }
        spectrum = smooth(spectrum, fresh)
    }

    fun togglePause() {
        val p = mp ?: return
        runCatching { if (paused) p.start() else p.pause() }
        paused = !paused
    }

    fun stop() {
        tick?.cancel()
        tick = null
        runCatching { viz?.release() }
        viz = null
        mp?.let {
            runCatching { it.stop() }
            it.release()
        }
        mp = null
        uri = null
        paused = false
        position = 0L
        length = 0L
        spectrum = NO_BINS
    }
}