284 lines · 11.2 KB · KotlinRaw
package com.cottondb.android.ui.meetingsimport android.content.BroadcastReceiverimport android.content.Contextimport android.content.Intentimport android.content.IntentFilterimport android.media.AudioAttributesimport android.media.AudioFocusRequestimport android.media.AudioManagerimport android.media.MediaPlayerimport android.os.Buildimport android.os.Handlerimport android.os.Looperimport com.cottondb.android.media.LocalMediaFileimport kotlinx.coroutines.flow.MutableStateFlowimport kotlinx.coroutines.flow.StateFlowimport kotlinx.coroutines.flow.asStateFlowsealed interface MeetingPlaybackState { data object Idle : MeetingPlaybackState data object Preparing : MeetingPlaybackState data class Paused(val positionMs: Int, val durationMs: Int) : MeetingPlaybackState data class Playing(val positionMs: Int, val durationMs: Int) : MeetingPlaybackState data class Completed(val durationMs: Int) : MeetingPlaybackState data class Failed(val message: String) : MeetingPlaybackState}/** Injectable focus/noisy boundary; controller owns no receiver or core/media fetch seam. */interface MeetingAudioFocus { fun request(onInterrupted: () -> Unit): Boolean fun abandon()}/** * Main-thread owner of exactly one validated local meeting recording. It has no key, MediaSource, * Cotton call, or `ensure` capability. Hosts resolve a meeting audio key before binding its file. */class AndroidMeetingPlayerController( context: Context, private val focus: MeetingAudioFocus = AndroidMeetingAudioFocus(context),) { private val main = Handler(Looper.getMainLooper()) private val mutableState = MutableStateFlow<MeetingPlaybackState>(MeetingPlaybackState.Idle) val state: StateFlow<MeetingPlaybackState> = mutableState.asStateFlow() private var player: PlayerSlot? = null private var request = 0L private var disposed = false private var ticking = false fun bind(file: LocalMediaFile) { checkMain() if (disposed) return releasePlayer() val generation = ++request if (!file.file.isFile) { mutableState.value = MeetingPlaybackState.Failed("This recording file is no longer available.") return } mutableState.value = MeetingPlaybackState.Preparing val slot = PlayerSlot(MediaPlayer()) val made = slot.mediaPlayer try { made.setAudioAttributes( AudioAttributes.Builder() .setUsage(AudioAttributes.USAGE_MEDIA) .setContentType(AudioAttributes.CONTENT_TYPE_SPEECH) .build(), ) made.setDataSource(file.file.absolutePath) made.setOnPreparedListener { prepared -> if (!current(generation, prepared)) return@setOnPreparedListener try { mutableState.value = MeetingPlaybackState.Paused( positionMs = 0, durationMs = prepared.duration.coerceAtLeast(0), ) } catch (_: IllegalStateException) { if (current(generation, prepared)) fail("This recording could not be played.") } } made.setOnCompletionListener { completed -> if (!current(generation, completed)) return@setOnCompletionListener try { stopTicks() focus.abandon() mutableState.value = MeetingPlaybackState.Completed( durationMs = completed.duration.coerceAtLeast(0), ) } catch (_: IllegalStateException) { if (current(generation, completed)) fail("This recording could not be played.") } } made.setOnErrorListener { failed, _, _ -> if (current(generation, failed)) fail("This recording could not be played.") true } player = slot made.prepareAsync() } catch (_: Throwable) { if (player === slot) player = null releaseSlot(slot) if (generation == request) mutableState.value = MeetingPlaybackState.Failed("This recording could not be opened.") } } /** Play/pause only. Seeking deliberately never starts playback. */ fun toggle() { checkMain() val active = player?.mediaPlayer ?: return when (mutableState.value) { is MeetingPlaybackState.Paused, is MeetingPlaybackState.Completed -> play(active) is MeetingPlaybackState.Playing -> pause(active) else -> Unit } } /** Transcript interaction may seek and explicitly play; waveform interaction calls [seekTo]. */ fun playFromTranscript(positionMs: Int) { checkMain() when (mutableState.value) { is MeetingPlaybackState.Paused, is MeetingPlaybackState.Completed -> { seekTo(positionMs) player?.mediaPlayer?.let(::play) } is MeetingPlaybackState.Playing -> seekTo(positionMs) else -> Unit } } fun seekTo(positionMs: Int) { checkMain() val phase = mutableState.value if (phase !is MeetingPlaybackState.Paused && phase !is MeetingPlaybackState.Playing && phase !is MeetingPlaybackState.Completed) return val active = player?.mediaPlayer ?: return try { val duration = active.duration.coerceAtLeast(0) val position = positionMs.coerceIn(0, duration) active.seekTo(position) mutableState.value = if (phase is MeetingPlaybackState.Playing) MeetingPlaybackState.Playing(position, duration) else MeetingPlaybackState.Paused(position, duration) } catch (_: IllegalStateException) { fail("This recording could not be played.") } } /** Focus loss and headphones becoming noisy only pause an active player. */ fun onInterrupted() { checkMain() if (mutableState.value is MeetingPlaybackState.Playing) player?.mediaPlayer?.let(::pause) } /** * Android's host releases the decoder and focus when backgrounded. A foreground visit must * explicitly bind the still-local file again. Swift only specifies terminal release on route * disappearance; its Meeting player has no independent background hook. */ fun onAppBackgrounded() = release() /** Route exit is terminal; callers bind a local file again to retry. */ fun release() { checkMain() request += 1 releasePlayer() mutableState.value = MeetingPlaybackState.Idle } fun dispose() { checkMain() if (disposed) return disposed = true release() } private fun play(active: MediaPlayer) { val generation = request val granted = try { focus.request { main.post { if (current(generation, active)) onInterrupted() } } } catch (_: Throwable) { fail("Audio focus could not be requested."); return } if (!granted) return fail("Audio focus is unavailable.") try { if (mutableState.value is MeetingPlaybackState.Completed) active.seekTo(0) active.start() publish(active) } catch (_: IllegalStateException) { fail("This recording could not be played.") } } private fun pause(active: MediaPlayer) { try { if (active.isPlaying) active.pause() stopTicks() focus.abandon() mutableState.value = MeetingPlaybackState.Paused(active.currentPosition.coerceAtLeast(0), active.duration.coerceAtLeast(0)) } catch (_: IllegalStateException) { fail("This recording could not be played.") } } private fun publish(active: MediaPlayer) { if (active !== player?.mediaPlayer || disposed) return try { mutableState.value = MeetingPlaybackState.Playing(active.currentPosition.coerceAtLeast(0), active.duration.coerceAtLeast(0)) if (!ticking) { ticking = true; main.postDelayed(tick, 250L) } } catch (_: IllegalStateException) { fail("This recording could not be played.") } } private val tick = object : Runnable { override fun run() { ticking = false val active = player?.mediaPlayer ?: return try { if (active.isPlaying) publish(active) } catch (_: IllegalStateException) { fail("This recording could not be played.") } } } private fun fail(message: String) { releasePlayer() mutableState.value = MeetingPlaybackState.Failed(message) } private fun releasePlayer() { stopTicks() focus.abandon() val active = player player = null active?.let(::releaseSlot) } private fun releaseSlot(slot: PlayerSlot) { if (slot.released) return slot.released = true runCatching { slot.mediaPlayer.stop() } runCatching { slot.mediaPlayer.release() } } private fun stopTicks() { main.removeCallbacks(tick); ticking = false } private fun current(generation: Long, candidate: MediaPlayer) = !disposed && generation == request && candidate === player?.mediaPlayer private class PlayerSlot(val mediaPlayer: MediaPlayer) { var released = false } private fun checkMain() = check(Looper.myLooper() == Looper.getMainLooper()) { "AndroidMeetingPlayerController must run on the main thread." }}class AndroidMeetingAudioFocus(context: Context) : MeetingAudioFocus { private val app = context.applicationContext private val main = Handler(Looper.getMainLooper()) private val manager = app.getSystemService(AudioManager::class.java) private var request: AudioFocusRequest? = null private var noisyReceiver: BroadcastReceiver? = null override fun request(onInterrupted: () -> Unit): Boolean { if (request != null) return true val made = AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN) .setAudioAttributes(AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_MEDIA).setContentType(AudioAttributes.CONTENT_TYPE_SPEECH).build()) .setOnAudioFocusChangeListener { change -> if (change < 0) main.post(onInterrupted) } .build() val granted = manager.requestAudioFocus(made) == AudioManager.AUDIOFOCUS_REQUEST_GRANTED if (!granted) return false request = made val receiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { if (intent.action == AudioManager.ACTION_AUDIO_BECOMING_NOISY) main.post(onInterrupted) } } noisyReceiver = receiver val filter = IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY) if (Build.VERSION.SDK_INT >= 33) { app.registerReceiver(receiver, filter, Context.RECEIVER_NOT_EXPORTED) } else { @Suppress("DEPRECATION") app.registerReceiver(receiver, filter) } return true } override fun abandon() { request?.let(manager::abandonAudioFocusRequest) request = null noisyReceiver?.let { receiver -> runCatching { app.unregisterReceiver(receiver) } } noisyReceiver = null }}