Pith - timber
package com.vgmlr.timber

import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.pm.PackageManager
import android.media.AudioDeviceInfo
import android.media.AudioManager
import android.net.Uri
import android.os.Build
import android.os.ParcelFileDescriptor
import android.os.SystemClock
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
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
import android.media.AudioFormat
import android.media.AudioRecord
import android.media.MediaRecorder

private const val TICK_MS = 50L
private const val SILENCE_EVERY = 10
private const val AAC_HI_RATE = 48_000
private const val AAC_LO_RATE = 22_050
private const val AAC_HI_BITS = 192_000
private const val AAC_LO_BITS = 64_000
private const val WAV_HI_RATE = 48_000
private const val WAV_LO_RATE = 16_000
private const val PROBE_RATE = 16_000
private const val PROBE_READS = 6

internal enum class Src { PHONE, HEADSET, OFF }

internal object TimberRoute {
    private val WIRED = setOf(AudioDeviceInfo.TYPE_WIRED_HEADSET, AudioDeviceInfo.TYPE_USB_HEADSET)
    private val BT = buildSet {
        add(AudioDeviceInfo.TYPE_BLUETOOTH_SCO)
        if (Build.VERSION.SDK_INT >= 31) add(AudioDeviceInfo.TYPE_BLE_HEADSET)
    }
    private var bound = false

    private fun audio(ctx: Context): AudioManager = ctx.getSystemService(AudioManager::class.java)

    fun hasMic(ctx: Context) =
        ctx.checkSelfPermission(Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED

    fun input(ctx: Context): AudioDeviceInfo? {
        val ins = audio(ctx).getDevices(AudioManager.GET_DEVICES_INPUTS)
        return ins.firstOrNull { it.type in WIRED } ?: ins.firstOrNull { it.type in BT }
    }

    fun kind(ctx: Context): Src = when {
        !hasMic(ctx) -> Src.OFF
        input(ctx) != null -> Src.HEADSET
        else -> Src.PHONE
    }

    // privacy toggle check
    @SuppressLint("MissingPermission")
    fun blocked(ctx: Context): Boolean {
        if (!hasMic(ctx)) return false
        val min = AudioRecord.getMinBufferSize(
            PROBE_RATE, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT
        )
        if (min <= 0) return false
        val r = runCatching {
            AudioRecord.Builder()
                .setAudioSource(MediaRecorder.AudioSource.MIC)
                .setAudioFormat(
                    AudioFormat.Builder()
                        .setEncoding(AudioFormat.ENCODING_PCM_16BIT)
                        .setSampleRate(PROBE_RATE)
                        .setChannelMask(AudioFormat.CHANNEL_IN_MONO)
                        .build()
                )
                .setBufferSizeInBytes(min * 2)
                .setPrivacySensitive(true)
                .build()
        }.getOrNull() ?: return false
        return try {
            if (r.state != AudioRecord.STATE_INITIALIZED) return false
            r.startRecording()
            val buf = ShortArray(min / 2)
            var zero = true
            var silenced = false
            for (i in 0 until PROBE_READS) {
                val n = r.read(buf, 0, buf.size)
                if (n < 0) return false
                if (r.activeRecordingConfiguration?.isClientSilenced == true) {
                    silenced = true
                    break
                }
                for (k in 0 until n) if (buf[k].toInt() != 0) {
                    zero = false
                    break
                }
            }
            silenced || zero
        } catch (_: Exception) {
            false
        } finally {
            runCatching { r.stop() }
            r.release()
        }
    }

    @SuppressLint("MissingPermission")
    @Suppress("DEPRECATION")
    fun bind(ctx: Context, dev: AudioDeviceInfo?) {
        if (dev == null || dev.type !in BT) return
        val am = audio(ctx)
        bound = runCatching {
            if (Build.VERSION.SDK_INT >= 31) {
                am.availableCommunicationDevices
                    .firstOrNull { it.type == dev.type }
                    ?.let { am.setCommunicationDevice(it) } ?: false
            } else {
                am.startBluetoothSco()
                am.isBluetoothScoOn = true
                true
            }
        }.getOrDefault(false)
    }

    @Suppress("DEPRECATION")
    fun release(ctx: Context) {
        if (!bound) return
        bound = false
        val am = audio(ctx)
        runCatching {
            if (Build.VERSION.SDK_INT >= 31) am.clearCommunicationDevice()
            else {
                am.stopBluetoothSco()
                am.isBluetoothScoOn = false
            }
        }
    }
}

internal object TimberRecorder {
    var active by mutableStateOf(false); private set
    var paused by mutableStateOf(false); private set
    var elapsed by mutableLongStateOf(0L); private set
    var spectrum by mutableStateOf(NO_BINS); private set
    var silenced by mutableStateOf(false); private set
    var saved by mutableIntStateOf(0); private set

    private val scope = MainScope()
    private var tick: Job? = null
    private var capture: Capture? = null
    private var pfd: ParcelFileDescriptor? = null
    private var uri: Uri? = null
    private var runMs = 0L
    private var baseMs = 0L

    private fun now() = SystemClock.elapsedRealtime()

    fun start(ctx: Context): Boolean {
        if (active || !TimberRoute.hasMic(ctx)) return false
        TimberPlayer.stop()
        val prefs = TimberPrefs(ctx)
        val ext = if (prefs.format == FMT_WAV) FMT_WAV else FMT_M4A
        val name = prefs.prefix.ifBlank { PREFIX_DEFAULT } +
                TimberOTCClock.getFileNameTimestamp() + "." + ext
        val target = TimberStore.create(ctx, name, TimberStore.mime(ext)) ?: return false
        val fd = runCatching { ctx.contentResolver.openFileDescriptor(target, "rw") }.getOrNull()
        if (fd == null) {
            TimberStore.delete(ctx, target)
            return false
        }
        val dev = TimberRoute.input(ctx)
        TimberRoute.bind(ctx, dev)
        if (!open(fd, ext, prefs.high, dev)) {
            capture = null
            TimberRoute.release(ctx)
            runCatching { fd.close() }
            TimberStore.delete(ctx, target)
            return false
        }
        TimberStore.claim(ctx, target)
        uri = target
        pfd = fd
        runMs = 0L
        baseMs = now()
        elapsed = 0L
        paused = false
        silenced = false
        active = true
        tick = scope.launch {
            var n = 0
            while (isActive) {
                sample(n++ % SILENCE_EVERY == 0)
                delay(TICK_MS)
            }
        }
        return true
    }

    private fun open(
        fd: ParcelFileDescriptor,
        ext: String,
        high: Boolean,
        dev: AudioDeviceInfo?
    ): Boolean {
        val wav = ext == FMT_WAV
        val rate = when {
            wav -> if (high) WAV_HI_RATE else WAV_LO_RATE
            else -> if (high) AAC_HI_RATE else AAC_LO_RATE
        }
        val sink = try {
            if (wav) WavSink(fd, rate) else AacSink(
                fd,
                rate,
                if (high) AAC_HI_BITS else AAC_LO_BITS
            )
        } catch (_: Exception) {
            return false
        }
        return try {
            capture = Capture(rate, dev, sink).also { it.start() }
            true
        } catch (_: Exception) {
            runCatching { sink.finish() }
            false
        }
    }

    private fun sample(check: Boolean) {
        if (!paused) elapsed = runMs + (now() - baseMs)
        spectrum = smooth(spectrum, if (paused) null else capture?.bins)
        if (check) silenced = runCatching {
            capture?.silenced() ?: false
        }.getOrDefault(false)
    }

    fun togglePause(ctx: Context) {
        if (!active) return
        if (paused) {
            capture?.paused = false
            baseMs = now()
            paused = false
        } else {
            capture?.paused = true
            runMs += now() - baseMs
            elapsed = runMs
            paused = true
        }
        TimberService.refresh(ctx)
    }

    fun stop(ctx: Context) {
        if (!active) return
        active = false
        tick?.cancel()
        tick = null
        val c = capture
        val fd = pfd
        val u = uri
        capture = null
        pfd = null
        uri = null
        val ok = c?.stop() ?: false
        runCatching { fd?.close() }
        TimberRoute.release(ctx)
        if (u != null) {
            if (ok) TimberStore.publish(ctx, u) else TimberStore.delete(ctx, u)
        }
        paused = false
        spectrum = NO_BINS
        elapsed = 0L
        silenced = false
        saved++
        ctx.stopService(android.content.Intent(ctx, TimberService::class.java))
    }
}