package com.cottondb.android.ui.media.video import android.content.Context import android.media.AudioAttributes import android.media.AudioFocusRequest import android.media.AudioManager import android.media.MediaPlayer import android.os.Handler import android.os.Looper import android.view.SurfaceHolder import com.cottondb.android.media.LocalMediaFile import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow /** Playback facts intentionally carry no media key or filesystem path. */ sealed interface VideoPlaybackState { data object Idle : VideoPlaybackState data object Preparing : VideoPlaybackState data class Paused(val positionMs: Int, val durationMs: Int) : VideoPlaybackState data class Playing(val positionMs: Int, val durationMs: Int) : VideoPlaybackState data class Completed(val durationMs: Int) : VideoPlaybackState data class Failed(val message: String) : VideoPlaybackState } /** * Main-thread owner of one locally validated video file and one SurfaceHolder. * It has no Cotton core, media key, resolver, or fetch capability. */ class AndroidVideoPlayerController( context: Context, private val focus: VideoAudioFocus = AndroidVideoAudioFocus(context), ) { private val main = Handler(Looper.getMainLooper()) private val _state = MutableStateFlow(VideoPlaybackState.Idle) val state: StateFlow = _state.asStateFlow() private var generation = 0L private var player: MediaPlayer? = null private var holder: SurfaceHolder? = null private var holderCallback: SurfaceHolder.Callback? = null private var disposed = false private var progressScheduled = false fun bind(file: LocalMediaFile) { checkMainThread() if (disposed) return stopAndReleasePlayer() val request = ++generation if (!file.file.isFile) { _state.value = VideoPlaybackState.Failed("This video file is no longer available.") return } _state.value = VideoPlaybackState.Preparing val made = MediaPlayer() try { made.setAudioAttributes( AudioAttributes.Builder() .setUsage(AudioAttributes.USAGE_MEDIA) .setContentType(AudioAttributes.CONTENT_TYPE_MOVIE) .build(), ) made.setDataSource(file.file.absolutePath) made.setOnPreparedListener { prepared -> if (!isCurrent(request, prepared)) { runCatching { prepared.release() } return@setOnPreparedListener } if (!attachDisplay(prepared)) return@setOnPreparedListener try { _state.value = VideoPlaybackState.Paused(0, prepared.duration.coerceAtLeast(0)) } catch (_: IllegalStateException) { fail("This video could not be prepared.") } } made.setOnCompletionListener { completed -> if (!isCurrent(request, completed)) return@setOnCompletionListener stopProgress() abandonAudioFocus() try { _state.value = VideoPlaybackState.Completed(completed.duration.coerceAtLeast(0)) } catch (_: IllegalStateException) { fail("This video could not be played.") } } made.setOnErrorListener { failed, _, _ -> if (isCurrent(request, failed)) fail("This video could not be played.") true } player = made if (!attachDisplay(made)) return made.prepareAsync() } catch (_: Throwable) { if (player === made) player = null runCatching { made.release() } if (request == generation) _state.value = VideoPlaybackState.Failed("This video could not be opened.") } } fun attach(surfaceHolder: SurfaceHolder) { checkMainThread() if (disposed || holder === surfaceHolder) return detachHolder() holder = surfaceHolder val callback = object : SurfaceHolder.Callback { override fun surfaceCreated(holder: SurfaceHolder) { if (!disposed && this@AndroidVideoPlayerController.holder === holder) player?.let(::attachDisplay) } override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) = Unit override fun surfaceDestroyed(holder: SurfaceHolder) { if (this@AndroidVideoPlayerController.holder === holder) player?.let(::clearDisplay) } } holderCallback = callback surfaceHolder.addCallback(callback) player?.let(::attachDisplay) } fun detach(surfaceHolder: SurfaceHolder) { checkMainThread() if (holder === surfaceHolder) detachHolder() } fun toggle() { checkMainThread() val active = player ?: return when (_state.value) { is VideoPlaybackState.Paused, is VideoPlaybackState.Completed -> start(active) is VideoPlaybackState.Playing -> pause(active) else -> Unit } } fun seekTo(positionMs: Int) { checkMainThread() val phase = _state.value if (phase !is VideoPlaybackState.Paused && phase !is VideoPlaybackState.Playing && phase !is VideoPlaybackState.Completed) return val active = player ?: return try { val duration = active.duration.coerceAtLeast(0) val position = positionMs.coerceIn(0, duration) active.seekTo(position) _state.value = if (phase is VideoPlaybackState.Playing) { VideoPlaybackState.Playing(position, duration) } else { VideoPlaybackState.Paused(position, duration) } } catch (_: IllegalStateException) { fail("This video could not be played.") } } /** A video never continues after the app leaves the foreground. */ fun onAppBackgrounded() { checkMainThread() // Preparing has no started playback to pause. Its prepared callback publishes Paused, // so a video that finishes preparing in the background never autoplays on return. if (_state.value is VideoPlaybackState.Playing) player?.let(::pause) } fun dispose() { checkMainThread() if (disposed) return disposed = true generation += 1 detachHolder() stopAndReleasePlayer() _state.value = VideoPlaybackState.Idle } private fun start(active: MediaPlayer) { val request = generation val focused = try { focus.request { main.post { if (isCurrent(request, active) && _state.value is VideoPlaybackState.Playing) pause(active) } } } catch (_: Throwable) { fail("Audio focus could not be requested.") return } if (!focused) { // There is no retained player after a denied request. The caller explicitly rebinds to retry. fail("Audio focus is unavailable.") return } try { if (_state.value is VideoPlaybackState.Completed) active.seekTo(0) active.start() publishProgress(active) } catch (_: IllegalStateException) { fail("This video could not be played.") } } private fun pause(active: MediaPlayer) { try { if (active.isPlaying) active.pause() stopProgress() abandonAudioFocus() _state.value = VideoPlaybackState.Paused( active.currentPosition.coerceAtLeast(0), active.duration.coerceAtLeast(0), ) } catch (_: IllegalStateException) { fail("This video could not be played.") } } private fun publishProgress(active: MediaPlayer) { if (player !== active || disposed) return try { _state.value = VideoPlaybackState.Playing( active.currentPosition.coerceAtLeast(0), active.duration.coerceAtLeast(0), ) } catch (_: IllegalStateException) { fail("This video could not be played.") return } if (!progressScheduled) { progressScheduled = true main.postDelayed(progressTick, PROGRESS_INTERVAL_MS) } } private val progressTick = object : Runnable { override fun run() { progressScheduled = false val active = player ?: return try { if (active.isPlaying) publishProgress(active) } catch (_: IllegalStateException) { fail("This video could not be played.") } } } private fun fail(message: String) { stopProgress() abandonAudioFocus() val active = player player = null runCatching { active?.release() } _state.value = VideoPlaybackState.Failed(message) } private fun stopAndReleasePlayer() { stopProgress() abandonAudioFocus() val active = player player = null runCatching { active?.stop() } runCatching { active?.release() } } private fun attachDisplay(active: MediaPlayer): Boolean = try { active.setDisplay(if (holder?.surface?.isValid == true) holder else null) true } catch (_: IllegalStateException) { if (player === active) fail("This video surface is unavailable.") false } private fun clearDisplay(active: MediaPlayer) { try { active.setDisplay(null) } catch (_: IllegalStateException) { if (player === active) fail("This video surface is unavailable.") } } private fun detachHolder() { val current = holder val callback = holderCallback holder = null holderCallback = null if (current != null && callback != null) current.removeCallback(callback) player?.let(::clearDisplay) } private fun abandonAudioFocus() { // A platform focus release must not turn a completed/failed player into an app crash. runCatching { focus.abandon() } } private fun isCurrent(request: Long, candidate: MediaPlayer): Boolean = !disposed && request == generation && candidate === player private fun stopProgress() { main.removeCallbacks(progressTick) progressScheduled = false } private fun checkMainThread() { check(Looper.myLooper() == Looper.getMainLooper()) { "AndroidVideoPlayerController must be called on the main thread." } } private companion object { const val PROGRESS_INTERVAL_MS = 250L } } /** Audio focus is injectable so the player can be verified with a real MediaPlayer without audio hardware. */ interface VideoAudioFocus { fun request(onLost: () -> Unit): Boolean fun abandon() } class AndroidVideoAudioFocus(context: Context) : VideoAudioFocus { private val manager = context.applicationContext.getSystemService(AudioManager::class.java) private var request: AudioFocusRequest? = null override fun request(onLost: () -> Unit): Boolean { if (request != null) return true val focus = AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN) .setAudioAttributes( AudioAttributes.Builder() .setUsage(AudioAttributes.USAGE_MEDIA) .setContentType(AudioAttributes.CONTENT_TYPE_MOVIE) .build(), ) .setOnAudioFocusChangeListener { change -> if (change < 0) onLost() } .build() val granted = manager.requestAudioFocus(focus) == AudioManager.AUDIOFOCUS_REQUEST_GRANTED if (granted) request = focus return granted } override fun abandon() { request?.let(manager::abandonAudioFocusRequest) request = null } }