Implementation chapter · Coverage index
Each text entry includes the complete pinned file to write at the displayed path, plus an exact-byte download. Read the chapter for implementation order and behavior, then connect callers and reproduce the tests. Platform variants preserve their platform capabilities. Binary assets are retained with applicable licenses or independently recreated, not transcribed as code.
Pinned baseline for comparison. Use the reviewed listings in the implementation chapters and the reviewed source archive when reconstructing the app. See the architecture review for changes.
vendor/compose-mediaplayer/LICENSE
- Source · configuration / resource · 21 lines.
- Manual task: Recreate the keys, identifiers, build relationships or resource names used by the consuming code. Preserve serialized names and schema compatibility; omit machine-specific values.
Exact file bytes / download · SHA-256 9a941439f4e21198b695da7bea628541f52e754a6400c27ab5466dbd2351b159.
Complete file
MIT License
Copyright (c) 2025 Elie G.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
vendor/compose-mediaplayer/README.yokan.md
- Source · documentation / design asset · 9 lines.
- Manual task: Use as design/history/reference material; reconcile claims with current code and tests before reproducing behavior. Recreate relevant documentation after the implementation is verified.
Exact file bytes / download · SHA-256 9a38d30e9cedd832cf08d31e36e06b97c7620f76c6506cdbed097423fc4c22f9.
Complete file
# Yokan compatibility player fork
Based on [ComposeMediaPlayer v0.7.11](https://github.com/kdroidFilter/ComposeMediaPlayer/tree/v0.7.11), under the included MIT license. Sources are retained in their upstream layout. The local Gradle module uses Yokan's toolchain and dependency versions; playback behavior remains based on the pinned release.
Local changes add an awaited, retryable disposal contract and explicit browser video ownership. Yokan uses the awaited contract after its surface work and platform view disposal finish. Legacy immediate `dispose()` remains supported. Native backends join their worker scopes before releasing players; Linux bus/frame UI publications use owned work and cannot dispatch after disposal; iOS metadata extraction and queued UI work use an owned scope, and macOS retains allocated pointers before cancellation can discard the result. Browser bindings remove listeners and source attributes immediately, then join PiP requests and `AudioContext.close()` promises. Failed source initialization still retains its audio context for cleanup.
Desktop native libraries are copied unchanged from the published `io.github.kdroidfilter:composemediaplayer-jvm:0.7.11` artifact (SHA-256: 2c305638867ba55c949418a47c3e86e752a78bbf3b78884df69856af95badb68). They retain the upstream platform layout; this fork does not rebuild or modify native binaries.
The small toolchain compatibility adjustments use `kotlin.time.Clock` with Yokan's datetime version and read browser files through FileKit 0.16's `WebFile` wrapper. Imported source whitespace is normalized; upstream build/publishing/sample projects are omitted.
vendor/compose-mediaplayer/build.gradle.kts
- Source · configuration / resource · 59 lines.
- Manual task: Recreate the keys, identifiers, build relationships or resource names used by the consuming code. Preserve serialized names and schema compatibility; omit machine-specific values.
Exact file bytes / download · SHA-256 2d3c8ee5ed0b4488f08f07aaea7caec81a2c4831586ccdc58f6115994d02e905.
Complete file
plugins {
alias(libs.plugins.kotlin.multiplatform)
alias(libs.plugins.android.kotlin.multiplatform.library)
alias(libs.plugins.kotlin.compose)
alias(libs.plugins.jetbrains.compose)
}
kotlin {
compilerOptions {
freeCompilerArgs.add("-Xexpect-actual-classes")
}
android {
namespace = "io.github.kdroidfilter.composemediaplayer"
compileSdk = 37
minSdk = 21
withHostTest {}
}
jvm()
@OptIn(org.jetbrains.kotlin.gradle.ExperimentalWasmDsl::class)
wasmJs { browser { testTask { useKarma { useChromeHeadless() } } } }
iosArm64(); iosSimulatorArm64()
sourceSets {
commonMain.dependencies {
implementation(libs.compose.runtime)
implementation(libs.compose.foundation)
implementation(libs.kotlinx.coroutines.core)
api("io.github.vinceglb:filekit-core:0.16.0")
implementation(libs.kotlinx.datetime)
implementation("co.touchlab:kermit:2.2.0")
}
commonTest.dependencies {
implementation(kotlin("test"))
implementation(libs.kotlinx.coroutines.test)
}
androidMain.dependencies {
implementation("io.github.kdroidfilter:androidcontextprovider:1.0.1")
implementation(libs.kotlinx.coroutines.android)
implementation("androidx.media3:media3-exoplayer:1.11.1")
implementation("androidx.media3:media3-ui:1.11.1")
implementation(libs.androidx.activity.compose)
}
jvmMain.dependencies {
implementation(libs.kotlinx.coroutines.swing)
implementation("org.freedesktop.gstreamer:gst1-java-core:1.4.0")
implementation("net.java.dev.jna:jna-jpms:5.19.1")
implementation("net.java.dev.jna:jna-platform-jpms:5.19.1")
implementation("org.slf4j:slf4j-simple:2.0.20")
}
wasmJsMain.dependencies { implementation(libs.kotlinx.browser) }
}
}
tasks.withType<org.jetbrains.kotlin.gradle.tasks.KotlinJvmCompile>().configureEach {
compilerOptions.jvmTarget.set(org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17)
}
tasks.withType<JavaCompile>().configureEach {
sourceCompatibility = "17"
targetCompatibility = "17"
}
vendor/compose-mediaplayer/src/androidHostTest/kotlin/io/github/kdroidfilter/composemediaplayer/VideoPlayerStateTest.kt
- Source · test / fixture · 222 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
13: class VideoPlayerStateTest {
19: private fun skipIfContextProviderNotAvailable(): Boolean {
39: fun testCreateVideoPlayerState() {
65: fun testVolumeControl() {
92: fun testLoopSetting() {
115: fun testFullscreenToggle() {
138: fun testErrorHandling() {
161: fun testSubtitleFunctionality() {
200: fun testMetadataFunctionality() {
Exact file bytes / download · SHA-256 93202fbf98ae16acced513486e55fd4e5080e44b7cf1c114121bcff8cab21115.
Complete file
package io.github.kdroidfilter.composemediaplayer
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
import kotlin.test.assertFalse
import com.kdroid.androidcontextprovider.ContextProvider
/**
* Tests for the Android implementation of VideoPlayerState
*/
class VideoPlayerStateTest {
/**
* Helper function to check if ContextProvider is available and initialized
* If not, the test will be skipped
*/
private fun skipIfContextProviderNotAvailable(): Boolean {
try {
// Try to actually call getContext() to see if ContextProvider is initialized
ContextProvider.getContext()
return false // Don't skip, ContextProvider is available and initialized
} catch (e: IllegalStateException) {
// This is the expected exception when ContextProvider is not initialized
println("Skipping test: ContextProvider has not been initialized")
return true // Skip the test
} catch (e: Exception) {
// Any other exception means something else is wrong
println("Skipping test: Error accessing ContextProvider: ${e.message}")
return true // Skip the test
}
}
/**
* Test the creation of VideoPlayerState
*/
@Test
fun testCreateVideoPlayerState() {
if (skipIfContextProviderNotAvailable()) return
val playerState = VideoPlayerState()
// Verify the player state is initialized correctly
assertNotNull(playerState)
assertFalse(playerState.hasMedia)
assertFalse(playerState.isPlaying)
assertEquals(0f, playerState.sliderPos)
assertEquals(1f, playerState.volume)
assertFalse(playerState.loop)
assertEquals("00:00", playerState.positionText)
assertEquals("00:00", playerState.durationText)
assertEquals(0f, playerState.leftLevel)
assertEquals(0f, playerState.rightLevel)
assertFalse(playerState.isFullscreen)
// Clean up
playerState.dispose()
}
/**
* Test volume control
*/
@Test
fun testVolumeControl() {
if (skipIfContextProviderNotAvailable()) return
val playerState = VideoPlayerState()
// Test initial volume
assertEquals(1f, playerState.volume)
// Test setting volume
playerState.volume = 0.5f
assertEquals(0.5f, playerState.volume)
// Test volume bounds
playerState.volume = -0.1f
assertEquals(0f, playerState.volume, "Volume should be clamped to 0")
playerState.volume = 1.5f
assertEquals(1f, playerState.volume, "Volume should be clamped to 1")
// Clean up
playerState.dispose()
}
/**
* Test loop setting
*/
@Test
fun testLoopSetting() {
if (skipIfContextProviderNotAvailable()) return
val playerState = VideoPlayerState()
// Test initial loop setting
assertFalse(playerState.loop)
// Test setting loop
playerState.loop = true
assertTrue(playerState.loop)
playerState.loop = false
assertFalse(playerState.loop)
// Clean up
playerState.dispose()
}
/**
* Test fullscreen toggle
*/
@Test
fun testFullscreenToggle() {
if (skipIfContextProviderNotAvailable()) return
val playerState = VideoPlayerState()
// Test initial fullscreen state
assertFalse(playerState.isFullscreen)
// Test toggling fullscreen
playerState.toggleFullscreen()
assertTrue(playerState.isFullscreen)
playerState.toggleFullscreen()
assertFalse(playerState.isFullscreen)
// Clean up
playerState.dispose()
}
/**
* Test error handling
*/
@Test
fun testErrorHandling() {
if (skipIfContextProviderNotAvailable()) return
val playerState = VideoPlayerState()
// Initially there should be no error
assertEquals(null, playerState.error)
// Test opening a non-existent file (should cause an error)
playerState.openUri("non_existent_file.mp4")
// Test clearing the error
playerState.clearError()
assertEquals(null, playerState.error)
// Clean up
playerState.dispose()
}
/**
* Test subtitle functionality
*/
@Test
fun testSubtitleFunctionality() {
if (skipIfContextProviderNotAvailable()) return
val playerState = VideoPlayerState()
// Initially subtitles should be disabled
assertFalse(playerState.subtitlesEnabled)
assertEquals(null, playerState.currentSubtitleTrack)
assertTrue(playerState.availableSubtitleTracks.isEmpty())
// Create a test subtitle track
val testTrack = SubtitleTrack(
label = "English",
language = "en",
src = "test.vtt"
)
// Select the subtitle track
playerState.selectSubtitleTrack(testTrack)
// Verify subtitle state
assertTrue(playerState.subtitlesEnabled)
assertEquals(testTrack, playerState.currentSubtitleTrack)
// Disable subtitles
playerState.disableSubtitles()
// Verify subtitle state after disabling
assertFalse(playerState.subtitlesEnabled)
assertEquals(null, playerState.currentSubtitleTrack)
// Clean up
playerState.dispose()
}
/**
* Test metadata functionality
*/
@Test
fun testMetadataFunctionality() {
if (skipIfContextProviderNotAvailable()) return
val playerState = VideoPlayerState()
// Verify metadata object is initialized
assertNotNull(playerState.metadata)
// Initially metadata fields should be null
assertEquals(null, playerState.metadata.title)
assertEquals(null, playerState.metadata.duration)
assertEquals(null, playerState.metadata.width)
assertEquals(null, playerState.metadata.height)
assertEquals(null, playerState.metadata.bitrate)
assertEquals(null, playerState.metadata.frameRate)
assertEquals(null, playerState.metadata.mimeType)
assertEquals(null, playerState.metadata.audioChannels)
assertEquals(null, playerState.metadata.audioSampleRate)
// Clean up
playerState.dispose()
}
}
vendor/compose-mediaplayer/src/androidMain/AndroidManifest.xml
- Source · configuration / resource · 3 lines.
- Manual task: Recreate the keys, identifiers, build relationships or resource names used by the consuming code. Preserve serialized names and schema compatibility; omit machine-specific values.
Exact file bytes / download · SHA-256 2c1d1edd56acc7ff7097c2ed4e4d5a20cd4cdede6ca68b214eacd798decc1186.
Complete file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
</manifest>
vendor/compose-mediaplayer/src/androidMain/kotlin/io/github/kdroidfilter/composemediaplayer/AudioLevelProcessor.kt
- Source · implementation · 93 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
12: class AudioLevelProcessor : BaseAudioProcessor() {
18: fun setOnAudioLevelUpdateListener(listener: (Float, Float) -> Unit) {
22: override fun onConfigure(inputAudioFormat: AudioProcessor.AudioFormat): AudioProcessor.AudioFormat {
29: override fun queueInput(inputBuffer: ByteBuffer) {
77: private fun convertToPercentage(rms: Double): Float {
90: override fun onReset() {
Exact file bytes / download · SHA-256 e98149bffc964bcfcfc8cb74dc9566366f9b38d20f302dd05a5f9d86b83df6c0.
Complete file
package io.github.kdroidfilter.composemediaplayer
import androidx.media3.common.audio.AudioProcessor
import androidx.media3.common.audio.BaseAudioProcessor
import androidx.media3.common.util.UnstableApi
import java.nio.ByteBuffer
import kotlin.math.abs
import kotlin.math.log10
import kotlin.math.sqrt
@UnstableApi
class AudioLevelProcessor : BaseAudioProcessor() {
private var channelCount = 0
private var sampleRateHz = 0
private var bytesPerFrame = 0
private var onAudioLevelUpdate: ((Float, Float) -> Unit)? = null
fun setOnAudioLevelUpdateListener(listener: (Float, Float) -> Unit) {
onAudioLevelUpdate = listener
}
override fun onConfigure(inputAudioFormat: AudioProcessor.AudioFormat): AudioProcessor.AudioFormat {
channelCount = inputAudioFormat.channelCount
sampleRateHz = inputAudioFormat.sampleRate
bytesPerFrame = inputAudioFormat.bytesPerFrame
return inputAudioFormat
}
override fun queueInput(inputBuffer: ByteBuffer) {
if (!inputBuffer.hasRemaining()) {
return
}
var leftSum = 0.0
var rightSum = 0.0
var sampleCount = 0
// Copy the buffer so as not to affect the original position
val buffer = inputBuffer.duplicate()
while (buffer.remaining() >= 2) {
// Reading 16-bit samples
val sample = buffer.short / Short.MAX_VALUE.toFloat()
if (channelCount >= 2) {
// Stereo
if (sampleCount % 2 == 0) {
leftSum += abs(sample.toDouble())
} else {
rightSum += abs(sample.toDouble())
}
} else {
// Mono - same value for both channels
leftSum += abs(sample.toDouble())
rightSum += abs(sample.toDouble())
}
sampleCount++
}
// Calculate RMS and convert to dB
val samplesPerChannel = if (channelCount >= 2) sampleCount / 2 else sampleCount
val leftRms = if (samplesPerChannel > 0) sqrt(leftSum / samplesPerChannel) else 0.0
val rightRms = if (samplesPerChannel > 0) sqrt(rightSum / samplesPerChannel) else 0.0
// Convert to percentage (0-100)
val leftLevel = convertToPercentage(leftRms)
val rightLevel = convertToPercentage(rightRms)
onAudioLevelUpdate?.invoke(leftLevel, rightLevel)
// Pass the original buffer as is
val output = replaceOutputBuffer(inputBuffer.remaining())
output.put(inputBuffer)
output.flip()
}
private fun convertToPercentage(rms: Double): Float {
if (rms <= 0) return 0f
// Apply a scaling factor to make Android values more consistent with wasmjs
// wasmjs uses frequency domain data which typically results in lower values
val scaledRms = rms * 0.3 // Scale down the RMS value to be more in line with wasmjs
val db = 20 * log10(scaledRms)
// Convert from -60dB..0dB to 0..100%
// First normalize to 0..1 range
val normalized = ((db + 60) / 60).toFloat().coerceIn(0f, 1f)
// Then convert to percentage
return normalized * 100f
}
override fun onReset() {
onAudioLevelUpdate?.invoke(0f, 0f)
}
}
vendor/compose-mediaplayer/src/androidMain/kotlin/io/github/kdroidfilter/composemediaplayer/VideoPlayerState.android.kt
- Source · implementation · 535 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
38: actual open class VideoPlayerState {
79: actual fun selectSubtitleTrack(track: SubtitleTrack?) {
104: actual fun disableSubtitles() {
125: internal fun attachPlayerView(view: PlayerView) {
226: private fun initializePlayer() {
232: override fun buildAudioSink(
248: private fun createPlayerListener() = object : Player.Listener {
249: override fun onPlaybackStateChanged(playbackState: Int) {
279: override fun onIsPlayingChanged(playing: Boolean) {
288: override fun onVideoSizeChanged(videoSize: VideoSize) {
298: override fun onPlayerError(error: PlaybackException) {
318: private fun startPositionUpdates() {
335: private fun stopPositionUpdates() {
345: actual fun openUri(uri: String) {
360: actual fun openFile(file: PlatformFile) {
374: private fun openFromMediaItem(mediaItem: MediaItem) {
400: actual fun play() {
412: actual fun pause() {
417: actual fun stop() {
427: actual fun seekTo(value: Float) {
435: actual fun clearError() {
442: actual fun toggleFullscreen() {
449: private fun extractFormatMetadata(player: Player) {
503: private fun extractMediaItemMetadata(mediaItem: MediaItem?) {
514: private fun resetStates(keepMedia: Boolean = false) {
533: actual fun dispose() = disposal.dispose()
534: actual suspend fun disposeAndJoin() = disposal.disposeAndJoin()
Exact file bytes / download · SHA-256 ef9a66b62f952589e0618664019cf4de3c29bb71dfbc899ae8fb88c5fe1bd321.
Complete file
package io.github.kdroidfilter.composemediaplayer
import android.content.Context
import android.net.Uri
import androidx.compose.runtime.Stable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.sp
import androidx.media3.common.*
import androidx.media3.common.util.UnstableApi
import androidx.media3.exoplayer.DefaultRenderersFactory
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.exoplayer.audio.AudioSink
import androidx.media3.exoplayer.audio.DefaultAudioSink
import androidx.media3.ui.CaptionStyleCompat
import androidx.media3.ui.PlayerView
import co.touchlab.kermit.Logger
import co.touchlab.kermit.Severity
import com.kdroid.androidcontextprovider.ContextProvider
import io.github.kdroidfilter.composemediaplayer.util.formatTime
import io.github.vinceglb.filekit.AndroidFile
import io.github.vinceglb.filekit.PlatformFile
import kotlinx.coroutines.*
/**
* Logger for WebAssembly video player surface
*/
internal val androidVideoLogger = Logger.withTag("AndroidVideoPlayerSurface")
.apply { Logger.setMinSeverity(Severity.Warn) }
@UnstableApi
@Stable
actual open class VideoPlayerState {
private val context: Context = ContextProvider.getContext()
internal var exoPlayer: ExoPlayer? = null
private var updateJob: Job? = null
private val coroutineScope = CoroutineScope(Dispatchers.Main + SupervisorJob())
private val audioProcessor = AudioLevelProcessor()
private var _hasMedia by mutableStateOf(false)
actual val hasMedia: Boolean get() = _hasMedia
// State properties
private var _isPlaying by mutableStateOf(false)
actual val isPlaying: Boolean get() = _isPlaying
private var _isLoading by mutableStateOf(false)
actual val isLoading: Boolean get() = _isLoading
private var _error by mutableStateOf<VideoPlayerError?>(null)
actual val error: VideoPlayerError? get() = _error
private var _metadata = VideoMetadata()
actual val metadata: VideoMetadata get() = _metadata
// Subtitle state
actual var subtitlesEnabled by mutableStateOf(false)
actual var currentSubtitleTrack by mutableStateOf<SubtitleTrack?>(null)
actual val availableSubtitleTracks = mutableListOf<SubtitleTrack>()
actual var subtitleTextStyle by mutableStateOf(
TextStyle(
color = Color.White,
fontSize = 18.sp,
fontWeight = FontWeight.Normal,
textAlign = TextAlign.Center
)
)
actual var subtitleBackgroundColor by mutableStateOf(Color.Black.copy(alpha = 0.5f))
private var playerView: PlayerView? = null
// Select an external subtitle track
actual fun selectSubtitleTrack(track: SubtitleTrack?) {
if (track == null) {
disableSubtitles()
return
}
// Update current track and enable flag.
currentSubtitleTrack = track
subtitlesEnabled = true
// We're not using ExoPlayer's native subtitle rendering anymore
// Instead, we're using Compose-based subtitles
exoPlayer?.let { player ->
// Disable native subtitles in ExoPlayer
val trackParameters = player.trackSelectionParameters.buildUpon()
.setTrackTypeDisabled(C.TRACK_TYPE_TEXT, true)
.build()
player.trackSelectionParameters = trackParameters
// Hide the subtitle view
playerView?.subtitleView?.visibility = android.view.View.GONE
}
}
actual fun disableSubtitles() {
// Update state
currentSubtitleTrack = null
subtitlesEnabled = false
// We're not using ExoPlayer's native subtitle rendering anymore
// Instead, we're using Compose-based subtitles
exoPlayer?.let { player ->
// Disable native subtitles in ExoPlayer
val parameters = player.trackSelectionParameters.buildUpon()
.setPreferredTextLanguage(null)
.setTrackTypeDisabled(C.TRACK_TYPE_TEXT, true)
.build()
player.trackSelectionParameters = parameters
// Hide the subtitle view
playerView?.subtitleView?.visibility = android.view.View.GONE
}
}
internal fun attachPlayerView(view: PlayerView) {
playerView = view
exoPlayer?.let { player ->
view.player = player
// Set default subtitle style
view.subtitleView?.setStyle(CaptionStyleCompat.DEFAULT)
}
}
// Volume control
private var _volume by mutableStateOf(1f)
actual var volume: Float
get() = _volume
set(value) {
_volume = value.coerceIn(0f, 1f)
exoPlayer?.volume = _volume
}
// Slider position
private var _sliderPos by mutableStateOf(0f)
actual var sliderPos: Float
get() = _sliderPos
set(value) {
_sliderPos = value.coerceIn(0f, 1000f)
if (!userDragging) {
seekTo(value)
}
}
// User interaction states
actual var userDragging by mutableStateOf(false)
// Loop control
private var _loop by mutableStateOf(false)
actual var loop: Boolean
get() = _loop
set(value) {
_loop = value
exoPlayer?.repeatMode = if (value) Player.REPEAT_MODE_ALL else Player.REPEAT_MODE_OFF
}
// Playback speed control
private var _playbackSpeed by mutableStateOf(1.0f)
actual var playbackSpeed: Float
get() = _playbackSpeed
set(value) {
_playbackSpeed = value.coerceIn(0.5f, 2.0f)
exoPlayer?.let { player ->
player.playbackParameters = PlaybackParameters(_playbackSpeed)
}
}
// Audio levels
private var _leftLevel by mutableStateOf(0f)
private var _rightLevel by mutableStateOf(0f)
actual val leftLevel: Float get() = _leftLevel
actual val rightLevel: Float get() = _rightLevel
// Aspect ratio
private var _aspectRatio by mutableStateOf(16f / 9f)
actual val aspectRatio: Float get() = _aspectRatio
// Fullscreen state
private var _isFullscreen by mutableStateOf(false)
actual var isFullscreen: Boolean
get() = _isFullscreen
set(value) {
_isFullscreen = value
}
// Time tracking
private var _currentTime by mutableStateOf(0.0)
private var _duration by mutableStateOf(0.0)
actual val positionText: String get() = formatTime(_currentTime)
actual val durationText: String get() = formatTime(_duration)
private val disposal = AwaitedPlayerDisposal(
dispatcher = kotlinx.coroutines.Dispatchers.Main,
retire = { stopPositionUpdates(); coroutineScope.cancel() },
release = {
coroutineScope.coroutineContext[Job]?.join()
playerView?.player = null
playerView = null
exoPlayer?.let { player ->
player.stop()
player.release()
}
exoPlayer = null
resetStates()
},
)
init {
audioProcessor.setOnAudioLevelUpdateListener { left, right ->
_leftLevel = left
_rightLevel = right
}
initializePlayer()
}
private fun initializePlayer() {
val audioSink = DefaultAudioSink.Builder(context)
.setAudioProcessors(arrayOf(audioProcessor))
.build()
val renderersFactory = object : DefaultRenderersFactory(context) {
override fun buildAudioSink(
context: Context,
enableFloatOutput: Boolean,
enableAudioTrackPlaybackParams: Boolean
): AudioSink = audioSink
}.setExtensionRendererMode(DefaultRenderersFactory.EXTENSION_RENDERER_MODE_PREFER)
exoPlayer = ExoPlayer.Builder(context)
.setRenderersFactory(renderersFactory)
.build()
.apply {
addListener(createPlayerListener())
volume = _volume
}
}
private fun createPlayerListener() = object : Player.Listener {
override fun onPlaybackStateChanged(playbackState: Int) {
when (playbackState) {
Player.STATE_BUFFERING -> {
_isLoading = true
}
Player.STATE_READY -> {
_isLoading = false
exoPlayer?.let { player ->
_duration = player.duration.toDouble() / 1000.0
_isPlaying = player.isPlaying
if (player.isPlaying) startPositionUpdates()
// Extract format metadata when the player is ready
extractFormatMetadata(player)
}
}
Player.STATE_ENDED -> {
_isLoading = false
stopPositionUpdates()
_isPlaying = false
}
Player.STATE_IDLE -> {
_isLoading = false
}
}
}
override fun onIsPlayingChanged(playing: Boolean) {
_isPlaying = playing
if (playing) {
startPositionUpdates()
} else {
stopPositionUpdates()
}
}
override fun onVideoSizeChanged(videoSize: VideoSize) {
// Update aspect ratio when video size changes
if (videoSize.width > 0 && videoSize.height > 0) {
_aspectRatio = videoSize.width.toFloat() / videoSize.height.toFloat()
// Update metadata
_metadata.width = videoSize.width
_metadata.height = videoSize.height
}
}
override fun onPlayerError(error: PlaybackException) {
_error = when (error.errorCode) {
PlaybackException.ERROR_CODE_DECODER_INIT_FAILED ->
VideoPlayerError.CodecError("Decoder initialization failed: ${error.message}")
PlaybackException.ERROR_CODE_IO_NETWORK_CONNECTION_FAILED,
PlaybackException.ERROR_CODE_IO_NETWORK_CONNECTION_TIMEOUT ->
VideoPlayerError.NetworkError("Network error: ${error.message}")
PlaybackException.ERROR_CODE_IO_INVALID_HTTP_CONTENT_TYPE,
PlaybackException.ERROR_CODE_IO_BAD_HTTP_STATUS ->
VideoPlayerError.SourceError("Invalid media source: ${error.message}")
else -> VideoPlayerError.UnknownError("Playback error: ${error.message}")
}
_isPlaying = false
_isLoading = false
}
}
private fun startPositionUpdates() {
stopPositionUpdates()
updateJob = coroutineScope.launch {
while (isActive) {
exoPlayer?.let { player ->
if (player.playbackState == Player.STATE_READY) {
_currentTime = player.currentPosition.toDouble() / 1000.0
if (!userDragging && _duration > 0) {
_sliderPos = (_currentTime / _duration * 1000).toFloat()
}
}
}
delay(16) // ~60fps update rate
}
}
}
private fun stopPositionUpdates() {
updateJob?.cancel()
updateJob = null
}
/**
* Open a video URI.
* We're not using ExoPlayer's native subtitle rendering anymore,
* so we don't need to add subtitle configurations to the MediaItem.
*/
actual fun openUri(uri: String) {
if (disposal.isRequested) return
val mediaItemBuilder = MediaItem.Builder().setUri(uri)
// We're not using ExoPlayer's native subtitle rendering anymore
// Instead, we're using Compose-based subtitles
val mediaItem = mediaItemBuilder.build()
openFromMediaItem(mediaItem)
}
/**
* Open a video file.
* Converts the file into a URI.
* We're not using ExoPlayer's native subtitle rendering anymore,
* so we don't need to add subtitle configurations to the MediaItem.
*/
actual fun openFile(file: PlatformFile) {
val mediaItemBuilder = MediaItem.Builder()
val androidFile = file.androidFile
val videoUri: Uri = when (androidFile) {
is AndroidFile.UriWrapper -> androidFile.uri
is AndroidFile.FileWrapper -> Uri.fromFile(androidFile.file)
}
mediaItemBuilder.setUri(videoUri)
// We're not using ExoPlayer's native subtitle rendering anymore
// Instead, we're using Compose-based subtitles
val mediaItem = mediaItemBuilder.build()
openFromMediaItem(mediaItem)
}
private fun openFromMediaItem(mediaItem: MediaItem) {
exoPlayer?.let { player ->
player.stop()
player.clearMediaItems()
try {
_error = null
resetStates(keepMedia = true)
player.setMediaItem(mediaItem)
// Extract metadata from the MediaItem before preparing the player
extractMediaItemMetadata(mediaItem)
player.prepare()
player.volume = volume
player.repeatMode = if (loop) Player.REPEAT_MODE_ALL else Player.REPEAT_MODE_OFF
player.play()
_hasMedia = true // Set to true when media is loaded
} catch (e: Exception) {
androidVideoLogger.d { "Error opening media: ${e.message}" }
_isPlaying = false
_hasMedia = false // Set to false on error
_error = VideoPlayerError.SourceError("Failed to load media: ${e.message}")
}
}
}
actual fun play() {
if (disposal.isRequested) return
exoPlayer?.let { player ->
if (player.playbackState == Player.STATE_IDLE) {
// If the player is in IDLE state (after stop), prepare it again
player.prepare()
}
player.play()
}
_hasMedia = true
}
actual fun pause() {
if (disposal.isRequested) return
exoPlayer?.pause()
}
actual fun stop() {
if (disposal.isRequested) return
exoPlayer?.let { player ->
player.stop()
player.seekTo(0) // Reset position to beginning
}
_hasMedia = false
resetStates(keepMedia = true)
}
actual fun seekTo(value: Float) {
if (disposal.isRequested) return
if (_duration > 0) {
val targetTime = (value / 1000.0) * _duration
exoPlayer?.seekTo((targetTime * 1000).toLong())
}
}
actual fun clearError() {
_error = null
}
/**
* Toggles the fullscreen state of the video player
*/
actual fun toggleFullscreen() {
_isFullscreen = !_isFullscreen
}
/**
* Extracts metadata from the player
*/
private fun extractFormatMetadata(player: Player) {
try {
// Extract duration if available
if (player.duration > 0 && player.duration != C.TIME_UNSET) {
_metadata.duration = player.duration
}
// Extract format information from tracks
player.currentTracks.groups.forEach { group ->
for (i in 0 until group.length) {
val trackFormat = group.getTrackFormat(i)
when (group.getType()) {
C.TRACK_TYPE_VIDEO -> {
// Video format metadata
if (trackFormat.frameRate > 0) {
_metadata.frameRate = trackFormat.frameRate
}
if (trackFormat.bitrate > 0) {
_metadata.bitrate = trackFormat.bitrate.toLong()
}
trackFormat.sampleMimeType?.let {
_metadata.mimeType = it
}
}
C.TRACK_TYPE_AUDIO -> {
// Audio format metadata
if (trackFormat.channelCount > 0) {
_metadata.audioChannels = trackFormat.channelCount
}
if (trackFormat.sampleRate > 0) {
_metadata.audioSampleRate = trackFormat.sampleRate
}
}
}
}
}
// Extract media item metadata
extractMediaItemMetadata(player.currentMediaItem)
androidVideoLogger.d { "Metadata extracted: $_metadata" }
} catch (e: Exception) {
androidVideoLogger.e { "Error extracting format metadata: ${e.message}" }
}
}
/**
* Extracts metadata from the MediaItem
*/
private fun extractMediaItemMetadata(mediaItem: MediaItem?) {
try {
mediaItem?.mediaMetadata?.let { metadata ->
// Extract title if available
metadata.title?.toString()?.let { _metadata.title = it }
}
} catch (e: Exception) {
androidVideoLogger.e { "Error extracting media item metadata: ${e.message}" }
}
}
private fun resetStates(keepMedia: Boolean = false) {
_currentTime = 0.0
_duration = 0.0
_sliderPos = 0f
_leftLevel = 0f
_rightLevel = 0f
_isPlaying = false
_isLoading = false
_error = null
_aspectRatio = 16f / 9f // Reset aspect ratio to default
_playbackSpeed = 1.0f // Reset playback speed to default
_metadata = VideoMetadata() // Reset metadata to a new empty instance
exoPlayer?.playbackParameters = PlaybackParameters(_playbackSpeed)
if (!keepMedia) {
_hasMedia = false
}
}
actual fun dispose() = disposal.dispose()
actual suspend fun disposeAndJoin() = disposal.disposeAndJoin()
}
vendor/compose-mediaplayer/src/androidMain/kotlin/io/github/kdroidfilter/composemediaplayer/VideoPlayerSurface.android.kt
- Source · implementation · 140 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
28: actual fun VideoPlayerSurface(
62: private fun VideoPlayerContent(
Exact file bytes / download · SHA-256 dc88c49a5fc42cf3d5694208dbc6fed088de27df24bd7440dc97e8297f26e610.
Complete file
package io.github.kdroidfilter.composemediaplayer
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.viewinterop.AndroidView
import androidx.media3.common.util.UnstableApi
import androidx.media3.ui.AspectRatioFrameLayout
import androidx.media3.ui.PlayerView
import io.github.kdroidfilter.composemediaplayer.subtitle.ComposeSubtitleLayer
import io.github.kdroidfilter.composemediaplayer.util.FullScreenLayout
import io.github.kdroidfilter.composemediaplayer.util.toCanvasModifier
import io.github.kdroidfilter.composemediaplayer.util.toTimeMs
@UnstableApi
@Composable
actual fun VideoPlayerSurface(
playerState: VideoPlayerState,
modifier: Modifier,
contentScale: ContentScale,
overlay: @Composable () -> Unit
) {
if (playerState.isFullscreen) {
// Use FullScreenLayout for fullscreen mode
FullScreenLayout(
modifier = Modifier,
onDismissRequest = { playerState.toggleFullscreen() }
) {
Box(modifier = Modifier.fillMaxSize().background(Color.Black)) {
VideoPlayerContent(
playerState = playerState,
modifier = Modifier.fillMaxHeight(),
overlay = overlay,
contentScale = contentScale
)
}
}
} else {
// Regular non-fullscreen display
VideoPlayerContent(
playerState = playerState,
modifier = modifier,
overlay = overlay,
contentScale = contentScale
)
}
}
@UnstableApi
@Composable
private fun VideoPlayerContent(
playerState: VideoPlayerState,
modifier: Modifier,
overlay: @Composable () -> Unit,
contentScale: ContentScale
) {
Box(
modifier = modifier,
contentAlignment = Alignment.Center
) {
if (playerState.hasMedia) {
AndroidView(
modifier =
contentScale.toCanvasModifier(playerState.aspectRatio,playerState.metadata.width,playerState.metadata.height),
factory = { context ->
// Create PlayerView with subtitles support
PlayerView(context).apply {
// Attach the player from the state
player = playerState.exoPlayer
useController = false
defaultArtwork = null
setShutterBackgroundColor(android.graphics.Color.TRANSPARENT)
setBackgroundColor(android.graphics.Color.TRANSPARENT)
// Map Compose ContentScale to ExoPlayer resize modes
resizeMode = when (contentScale) {
ContentScale.Crop -> AspectRatioFrameLayout.RESIZE_MODE_ZOOM
ContentScale.FillBounds -> AspectRatioFrameLayout.RESIZE_MODE_FILL
ContentScale.Fit, ContentScale.Inside -> AspectRatioFrameLayout.RESIZE_MODE_FIT
ContentScale.FillWidth -> AspectRatioFrameLayout.RESIZE_MODE_FIXED_WIDTH
ContentScale.FillHeight -> AspectRatioFrameLayout.RESIZE_MODE_FIXED_HEIGHT
else -> AspectRatioFrameLayout.RESIZE_MODE_FIT
}
// Disable native subtitle view since we're using Compose-based subtitles
subtitleView?.visibility = android.view.View.GONE
// Attach this view to the player state
playerState.attachPlayerView(this)
}
},
update = { playerView ->
// Update the resize mode when contentScale changes
playerView.resizeMode = when (contentScale) {
ContentScale.Crop -> AspectRatioFrameLayout.RESIZE_MODE_ZOOM
ContentScale.FillBounds -> AspectRatioFrameLayout.RESIZE_MODE_FILL
ContentScale.Fit, ContentScale.Inside -> AspectRatioFrameLayout.RESIZE_MODE_FIT
ContentScale.FillWidth -> AspectRatioFrameLayout.RESIZE_MODE_FIXED_WIDTH
ContentScale.FillHeight -> AspectRatioFrameLayout.RESIZE_MODE_FIXED_HEIGHT
else -> AspectRatioFrameLayout.RESIZE_MODE_FIT
}
}
)
// Add Compose-based subtitle layer
if (playerState.subtitlesEnabled && playerState.currentSubtitleTrack != null) {
// Calculate current time in milliseconds
val currentTimeMs = (playerState.sliderPos / 1000f *
playerState.durationText.toTimeMs()).toLong()
// Calculate duration in milliseconds
val durationMs = playerState.durationText.toTimeMs()
ComposeSubtitleLayer(
currentTimeMs = currentTimeMs,
durationMs = durationMs,
isPlaying = playerState.isPlaying,
subtitleTrack = playerState.currentSubtitleTrack,
subtitlesEnabled = playerState.subtitlesEnabled,
textStyle = playerState.subtitleTextStyle,
backgroundColor = playerState.subtitleBackgroundColor
)
}
}
// Render the overlay content on top of the video
overlay()
}
}
vendor/compose-mediaplayer/src/androidMain/kotlin/io/github/kdroidfilter/composemediaplayer/subtitle/SubtitleLoader.android.kt
- Source · implementation · 73 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
20: actual suspend fun loadSubtitleContent(src: String): String = withContext(Dispatchers.IO) {
Exact file bytes / download · SHA-256 2de41f13ec9ca23878650830a0574d6c9ae0ffad199f2747b741639c74a34b3b.
Complete file
package io.github.kdroidfilter.composemediaplayer.subtitle
import android.net.Uri
import com.kdroid.androidcontextprovider.ContextProvider
import io.github.kdroidfilter.composemediaplayer.androidVideoLogger
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
/**
* Android implementation of the loadSubtitleContent function.
* Loads subtitle content from a local file or a remote URL.
*
* @param src The source URI of the subtitle file
* @return The content of the subtitle file as a string
*/
actual suspend fun loadSubtitleContent(src: String): String = withContext(Dispatchers.IO) {
try {
when {
// Handle HTTP/HTTPS URLs
src.startsWith("http://") || src.startsWith("https://") -> {
val url = URL(src)
val connection = url.openConnection() as HttpURLConnection
connection.connectTimeout = 10000
connection.readTimeout = 10000
val reader = BufferedReader(InputStreamReader(connection.inputStream))
val content = reader.use { it.readText() }
connection.disconnect()
content
}
// Handle content:// URIs
src.startsWith("content://") -> {
val context = ContextProvider.getContext()
val uri = Uri.parse(src)
context.contentResolver.openInputStream(uri)?.use { inputStream ->
inputStream.bufferedReader().use { it.readText() }
} ?: ""
}
// Handle file:// URIs or local file paths
else -> {
val context = ContextProvider.getContext()
val uri = if (src.startsWith("file://")) {
Uri.parse(src)
} else {
Uri.fromFile(java.io.File(src))
}
try {
context.contentResolver.openInputStream(uri)?.use { inputStream ->
inputStream.bufferedReader().use { it.readText() }
} ?: ""
} catch (e: Exception) {
// Fallback to direct file access if content resolver fails
try {
java.io.File(src).readText()
} catch (e2: Exception) {
androidVideoLogger.e { "Failed to load subtitle file: ${e2.message}" }
""
}
}
}
}
} catch (e: Exception) {
androidVideoLogger.e { "Error loading subtitle content: ${e.message}" }
""
}
}
vendor/compose-mediaplayer/src/androidMain/kotlin/io/github/kdroidfilter/composemediaplayer/util/Uri.kt
- Source · implementation · 11 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
6: actual fun PlatformFile.getUri(): String {
Exact file bytes / download · SHA-256 6caba1b3b3b5f131ddc762d6687c5e2ae3f03673924ec18d5d0218bf2051c503.
Complete file
package io.github.kdroidfilter.composemediaplayer.util
import io.github.vinceglb.filekit.AndroidFile
import io.github.vinceglb.filekit.PlatformFile
actual fun PlatformFile.getUri(): String {
return when (val androidFile = this.androidFile) {
is AndroidFile.UriWrapper -> androidFile.uri.toString()
is AndroidFile.FileWrapper -> androidFile.file.path
}
}
vendor/compose-mediaplayer/src/commonMain/kotlin/io/github/kdroidfilter/composemediaplayer/AwaitedPlayerDisposal.kt
- Source · implementation · 53 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
17: internal class AwaitedPlayerDisposal(
32: fun dispose() {
37: suspend fun disposeAndJoin() = withContext(NonCancellable) {
44: private suspend fun releaseOnce() = withContext(dispatcher + NonCancellable) {
Exact file bytes / download · SHA-256 afbc70d0bab28f341e047d26557acf41d8246de3c34d1b0f98449868e995382f.
Complete file
package io.github.kdroidfilter.composemediaplayer
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.async
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
/** Immediate admission closure plus owned, joined, retryable native cleanup. */
internal class AwaitedPlayerDisposal(
private val dispatcher: CoroutineDispatcher = Dispatchers.Default,
private val retire: () -> Unit = {},
private val release: suspend () -> Unit,
) {
private val requested = MutableStateFlow(false)
private val signal = CompletableDeferred<Unit>()
private val owner = SupervisorJob()
private val mutex = Mutex()
private var complete = false
private val cleanup = CoroutineScope(owner + dispatcher).async(start = CoroutineStart.UNDISPATCHED) {
signal.await()
releaseOnce()
}
val isRequested: Boolean get() = requested.value
fun dispose() {
if (requested.compareAndSet(false, true)) {
try { retire() } finally { signal.complete(Unit) }
}
}
suspend fun disposeAndJoin() = withContext(NonCancellable) {
dispose()
cleanup.join()
releaseOnce()
owner.complete()
owner.join()
}
private suspend fun releaseOnce() = withContext(dispatcher + NonCancellable) {
mutex.withLock {
if (!complete) {
release()
complete = true
owner.complete()
}
}
}
}
vendor/compose-mediaplayer/src/commonMain/kotlin/io/github/kdroidfilter/composemediaplayer/SubtitleTrack.kt
- Source · implementation · 11 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
7: data class SubtitleTrack(
Exact file bytes / download · SHA-256 40ac6671589e3ecd31e162ad712e53399d3314fe06ec2bd077740931203cd118.
Complete file
package io.github.kdroidfilter.composemediaplayer
import androidx.compose.runtime.Stable
@Stable
data class SubtitleTrack(
val label: String,
val language: String,
val src: String
)
vendor/compose-mediaplayer/src/commonMain/kotlin/io/github/kdroidfilter/composemediaplayer/VideoMetadata.kt
- Source · implementation · 52 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
25: data class VideoMetadata(
41: fun isAllNull(): Boolean {
Exact file bytes / download · SHA-256 c086a1ba8b666e68d3af4e66d1ba697ae8490b203ee9351d071c3d40f31d11ef.
Complete file
package io.github.kdroidfilter.composemediaplayer
import androidx.compose.runtime.Stable
/**
* Represents metadata information of a video file.
*
* This data class holds various attributes related to the video content,
* including its title, artist, duration, dimensions, codec details, and audio properties.
* This metadata is typically used to provide detailed information about a video
* during playback or for insights in media management systems.
*
* @property title The title of the video, if available.
* @property duration The length of the video in milliseconds, if known.
* @property width The width of the video in pixels, if available.
* @property height The height of the video in pixels, if available.
* @property bitrate The average data rate of the video in bits per second, if known.
* @property frameRate The frame rate of the video in frames per second, if available.
* @property mimeType The MIME type of the video file, indicating the format used.
* @property audioChannels The number of audio channels in the video's audio track, if available.
* @property audioSampleRate The sample rate of the audio track in the video, measured in Hz.
*/
@Stable
data class VideoMetadata(
var title: String? = null,
var duration: Long? = null, // Duration in milliseconds
var width: Int? = null,
var height: Int? = null,
var bitrate: Long? = null, // Bitrate in bits per second
var frameRate: Float? = null,
var mimeType: String? = null,
var audioChannels: Int? = null,
var audioSampleRate: Int? = null,
) {
/**
* Checks if all properties of this metadata object are null.
*
* @return true if all properties are null, false otherwise.
*/
fun isAllNull(): Boolean {
return title == null &&
duration == null &&
width == null &&
height == null &&
bitrate == null &&
frameRate == null &&
mimeType == null &&
audioChannels == null &&
audioSampleRate == null
}
}
vendor/compose-mediaplayer/src/commonMain/kotlin/io/github/kdroidfilter/composemediaplayer/VideoPlayerError.kt
- Source · implementation · 21 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
16: sealed class VideoPlayerError {
17: data class CodecError(val message: String): VideoPlayerError()
18: data class NetworkError(val message: String): VideoPlayerError()
19: data class SourceError(val message: String): VideoPlayerError()
20: data class UnknownError(val message: String): VideoPlayerError()
Exact file bytes / download · SHA-256 c0c9d3034d790d1a697960d4fb4cb41a5e809ff32f5b7c4115733f846e2b0c9c.
Complete file
package io.github.kdroidfilter.composemediaplayer
/**
* Represents different types of errors that can occur during video playback in a video player.
*
* This sealed class is used for error reporting and handling within the video player system.
* Each type of error is represented as a subclass of `VideoPlayerError` with an associated descriptive message.
*
* Subclasses:
* - `CodecError`: Indicates an issue with the codec, such as unsupported formats.
* - `NetworkError`: Represents network-related problems, like connectivity issues.
* - `SourceError`: Relates to issues with the video source, such as an invalid or unavailable file/URL.
* - `UnknownError`: Covers any issues that do not fit into the other categories.
*/
sealed class VideoPlayerError {
data class CodecError(val message: String): VideoPlayerError()
data class NetworkError(val message: String): VideoPlayerError()
data class SourceError(val message: String): VideoPlayerError()
data class UnknownError(val message: String): VideoPlayerError()
}
vendor/compose-mediaplayer/src/commonMain/kotlin/io/github/kdroidfilter/composemediaplayer/VideoPlayerState.kt
- Source · implementation · 90 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
23: expect open class VideoPlayerState() {
42: fun play()
43: fun pause()
44: fun stop()
45: fun seekTo(value: Float)
46: fun toggleFullscreen()
49: fun openUri(uri: String)
50: fun openFile(file: PlatformFile)
54: fun clearError()
65: fun selectSubtitleTrack(track: SubtitleTrack?)
66: fun disableSubtitles()
69: fun dispose()
70: suspend fun disposeAndJoin()
82: fun rememberVideoPlayerState(): VideoPlayerState {
Exact file bytes / download · SHA-256 394319dd563189d9b98177f666c4f31d89262a494ac9e6b1b922d2b3546758b9.
Complete file
package io.github.kdroidfilter.composemediaplayer
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.Stable
import androidx.compose.runtime.remember
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.TextStyle
import io.github.vinceglb.filekit.PlatformFile
/**
* Represents the state and controls for a video player. This class provides properties
* and methods to manage video playback, including play, pause, stop, seeking, and more.
* It maintains information about the playback state, such as whether the video is
* currently playing, volume levels, and playback position.
*
* Functions of this class are tied to managing and interacting with the underlying
* video player implementation.
*
* @constructor Initializes an instance of the video player state.
*/
@Stable
expect open class VideoPlayerState() {
// Properties related to media state
val hasMedia: Boolean
val isPlaying: Boolean
val isLoading: Boolean
var volume: Float
var sliderPos: Float
var userDragging: Boolean
var loop: Boolean
var playbackSpeed: Float
val leftLevel: Float
val rightLevel: Float
val positionText: String
val durationText: String
var isFullscreen: Boolean
val aspectRatio: Float
// Functions to control playback
fun play()
fun pause()
fun stop()
fun seekTo(value: Float)
fun toggleFullscreen()
// Functions to manage media sources
fun openUri(uri: String)
fun openFile(file: PlatformFile)
// Error handling
val error: VideoPlayerError?
fun clearError()
// Metadata
val metadata: VideoMetadata
// Subtitle management
var subtitlesEnabled: Boolean
var currentSubtitleTrack: SubtitleTrack?
val availableSubtitleTracks: MutableList<SubtitleTrack>
var subtitleTextStyle: TextStyle
var subtitleBackgroundColor: Color
fun selectSubtitleTrack(track: SubtitleTrack?)
fun disableSubtitles()
// Cleanup
fun dispose()
suspend fun disposeAndJoin()
}
/**
* Creates and manages an instance of `VideoPlayerState` within a composable function, ensuring
* proper disposal of the player state when the composable leaves the composition. This function
* is used to remember the video player state throughout the composition lifecycle.
*
* @return The remembered instance of `VideoPlayerState`, which provides functionalities for
* controlling and managing video playback, such as play, pause, stop, and seek.
*/
@Composable
fun rememberVideoPlayerState(): VideoPlayerState {
val playerState = remember { VideoPlayerState() }
DisposableEffect(Unit) {
onDispose {
playerState.dispose()
}
}
return playerState
}
vendor/compose-mediaplayer/src/commonMain/kotlin/io/github/kdroidfilter/composemediaplayer/VideoPlayerSurface.kt
- Source · implementation · 26 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
21: expect fun VideoPlayerSurface(
Exact file bytes / download · SHA-256 7b7b20518d43b47c979d43c95d6333cee137f579ec5ef9d9c3682606dce84d77.
Complete file
package io.github.kdroidfilter.composemediaplayer
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
/**
* Renders a video player surface that displays and controls video playback.
*
* @param playerState The state of the video player, which manages playback controls,
* video position, volume, and other related properties.
* @param modifier The modifier to be applied to the video player surface for
* layout and styling adjustments.
* @param contentScale Controls how the video content should be scaled inside the surface.
* This affects how the video is displayed when its dimensions don't match
* the surface dimensions.
* @param overlay Optional composable content to be displayed on top of the video surface.
* This can be used to add custom controls, information, or any UI elements.
*/
@Composable
expect fun VideoPlayerSurface(
playerState: VideoPlayerState,
modifier: Modifier = Modifier,
contentScale: ContentScale = ContentScale.Fit,
overlay: @Composable () -> Unit = {}
)
vendor/compose-mediaplayer/src/commonMain/kotlin/io/github/kdroidfilter/composemediaplayer/subtitle/ComposeSubtitleLayer.kt
- Source · implementation · 117 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
32: fun ComposeSubtitleLayer(
117: expect suspend fun loadSubtitleContent(src: String): String
Exact file bytes / download · SHA-256 89d15107387d0710061999d4a4786f422da75cd028c689cd98919b3c9b27c35c.
Complete file
package io.github.kdroidfilter.composemediaplayer.subtitle
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.sp
import io.github.kdroidfilter.composemediaplayer.SubtitleTrack
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
/**
* A composable function that displays subtitles over a video player.
* This component handles loading and parsing subtitle files, and displaying
* the active subtitles at the current playback time.
*
* @param currentTimeMs The current playback time in milliseconds
* @param durationMs The total duration of the media in milliseconds
* @param isPlaying Whether the video is currently playing
* @param subtitleTrack The current subtitle track, or null if no subtitle is selected
* @param subtitlesEnabled Whether subtitles are enabled
* @param modifier The modifier to be applied to the layout
* @param textStyle The text style to be applied to the subtitle text
* @param backgroundColor The background color of the subtitle box
*/
@Composable
fun ComposeSubtitleLayer(
currentTimeMs: Long,
durationMs: Long,
isPlaying: Boolean,
subtitleTrack: SubtitleTrack?,
subtitlesEnabled: Boolean,
modifier: Modifier = Modifier,
textStyle: TextStyle = TextStyle(
color = Color.White,
fontSize = 18.sp,
fontWeight = FontWeight.Normal,
textAlign = TextAlign.Center
),
backgroundColor: Color = Color.Black.copy(alpha = 0.5f)
) {
// State to hold the parsed subtitle cues
var subtitles by remember { mutableStateOf<SubtitleCueList?>(null) }
// Load subtitles when the subtitle track changes
LaunchedEffect(subtitleTrack) {
subtitles = if (subtitleTrack != null && subtitlesEnabled) {
try {
withContext(Dispatchers.Default) {
// Load and parse the subtitle file
val content = loadSubtitleContent(subtitleTrack.src)
// Determine the subtitle format based on file extension and content
val isSrtByExtension = subtitleTrack.src.endsWith(".srt", ignoreCase = true)
// Check content for SRT format (typically starts with a number followed by timing)
val isSrtByContent = content.trim().let {
val lines = it.lines()
lines.size >= 2 &&
lines[0].trim().toIntOrNull() != null &&
lines[1].contains("-->") &&
lines[1].contains(",") // SRT uses comma for milliseconds
}
// Check content for WebVTT format (starts with WEBVTT)
val isVttByContent = content.trim().startsWith("WEBVTT")
// Use the appropriate parser based on format detection
if (isSrtByExtension || (isSrtByContent && !isVttByContent)) {
SrtParser.parse(content)
} else {
// Default to WebVTT parser for other formats
WebVttParser.parse(content)
}
}
} catch (e: Exception) {
// If there's an error loading or parsing the subtitle file,
// return an empty subtitle list
SubtitleCueList()
}
} else {
// If no subtitle track is selected or subtitles are disabled,
// return null to hide the subtitle display
null
}
}
// Display the subtitles if available
Box(
modifier = modifier.fillMaxSize(),
contentAlignment = Alignment.BottomCenter
) {
subtitles?.let { cueList ->
if (subtitlesEnabled) {
AutoUpdatingSubtitleDisplay(
subtitles = cueList,
currentTimeMs = currentTimeMs,
isPlaying = isPlaying,
textStyle = textStyle,
backgroundColor = backgroundColor
)
}
}
}
}
/**
* Loads the content of a subtitle file from the given source.
* This is implemented in a platform-specific way.
*/
expect suspend fun loadSubtitleContent(src: String): String
vendor/compose-mediaplayer/src/commonMain/kotlin/io/github/kdroidfilter/composemediaplayer/subtitle/SrtParser.kt
- Source · implementation · 128 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
10: object SrtParser {
22: fun parse(content: String): SubtitleCueList {
96: private fun parseTimeToMillis(timeStr: String): Long {
117: suspend fun loadFromUrl(url: String): SubtitleCueList {
Exact file bytes / download · SHA-256 593466e65a8c13bb00a71b3cbe24aa9682f8dacac22d7f5b8c001a039348122d.
Complete file
package io.github.kdroidfilter.composemediaplayer.subtitle
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlin.io.encoding.ExperimentalEncodingApi
/**
* Parser for SRT (SubRip) subtitle files.
*/
object SrtParser {
// SRT time format uses comma instead of period for milliseconds: "00:00:00,000"
private val TIME_PATTERN = Regex("(\\d{2}):(\\d{2}):(\\d{2}),(\\d{3})")
// SRT timing line format: "00:00:00,000 --> 00:00:00,000"
private val CUE_TIMING_PATTERN = Regex("(\\d{2}:\\d{2}:\\d{2},\\d{3}) --> (\\d{2}:\\d{2}:\\d{2},\\d{3})")
/**
* Parses an SRT file content into a SubtitleCueList.
*
* @param content The SRT file content as a string
* @return A SubtitleCueList containing the parsed subtitle cues
*/
fun parse(content: String): SubtitleCueList {
val lines = content.lines()
val cues = mutableListOf<SubtitleCue>()
var i = 0
// SRT format: each entry consists of:
// 1. A sequence number
// 2. The timing line (start --> end)
// 3. The subtitle text (one or more lines)
// 4. A blank line separating entries
while (i < lines.size) {
// Skip empty lines
if (lines[i].isBlank()) {
i++
continue
}
// Try to parse as a sequence number (should be a positive integer)
val sequenceNumber = lines[i].trim().toIntOrNull()
if (sequenceNumber != null) {
i++ // Move to timing line
// Check if we're still within bounds and the next line is a timing line
if (i < lines.size) {
val timingLine = lines[i]
val timingMatch = CUE_TIMING_PATTERN.find(timingLine)
if (timingMatch != null) {
val startTimeStr = timingMatch.groupValues[1]
val endTimeStr = timingMatch.groupValues[2]
val startTime = parseTimeToMillis(startTimeStr)
val endTime = parseTimeToMillis(endTimeStr)
i++ // Move to subtitle text
val textBuilder = StringBuilder()
// Collect all lines until an empty line or end of file
while (i < lines.size && lines[i].isNotBlank()) {
if (textBuilder.isNotEmpty()) {
textBuilder.append("\n")
}
textBuilder.append(lines[i])
i++
}
val text = textBuilder.toString().trim()
if (text.isNotEmpty()) {
cues.add(SubtitleCue(startTime, endTime, text))
}
} else {
// Not a valid timing line, skip
i++
}
} else {
// End of file
break
}
} else {
// Not a sequence number, skip this line
i++
}
}
return SubtitleCueList(cues)
}
/**
* Parses a time string in the format "00:00:00,000" to milliseconds.
*
* @param timeStr The time string to parse
* @return The time in milliseconds
*/
private fun parseTimeToMillis(timeStr: String): Long {
val match = TIME_PATTERN.find(timeStr)
if (match != null) {
val hours = match.groupValues[1].toLong()
val minutes = match.groupValues[2].toLong()
val seconds = match.groupValues[3].toLong()
val millis = match.groupValues[4].toLong()
return (hours * 3600 + minutes * 60 + seconds) * 1000 + millis
}
return 0
}
/**
* Loads and parses an SRT file from a URL.
*
* @param url The URL of the SRT file
* @return A SubtitleCueList containing the parsed subtitle cues
*/
@OptIn(ExperimentalEncodingApi::class)
suspend fun loadFromUrl(url: String): SubtitleCueList {
return withContext(Dispatchers.Default) {
try {
// Use the platform-specific loadSubtitleContent function to fetch the content
val content = loadSubtitleContent(url)
parse(content)
} catch (e: Exception) {
SubtitleCueList() // Return empty list on error
}
}
}
}
vendor/compose-mediaplayer/src/commonMain/kotlin/io/github/kdroidfilter/composemediaplayer/subtitle/SubtitleCue.kt
- Source · implementation · 47 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
13: data class SubtitleCue(
24: fun isActive(currentTimeMs: Long): Boolean {
35: data class SubtitleCueList(
44: fun getActiveCues(currentTimeMs: Long): List<SubtitleCue> {
Exact file bytes / download · SHA-256 4add63efd501cfcb1490945a7a5ccc50a6f9977e16873dbe43e2e80904368831.
Complete file
package io.github.kdroidfilter.composemediaplayer.subtitle
import androidx.compose.runtime.Immutable
/**
* Represents a single subtitle cue with timing information and text content.
*
* @property startTime The start time of the subtitle in milliseconds
* @property endTime The end time of the subtitle in milliseconds
* @property text The text content of the subtitle
*/
@Immutable
data class SubtitleCue(
val startTime: Long,
val endTime: Long,
val text: String
) {
/**
* Checks if this subtitle cue should be displayed at the given time.
*
* @param currentTimeMs The current playback time in milliseconds
* @return True if the cue should be displayed, false otherwise
*/
fun isActive(currentTimeMs: Long): Boolean {
return currentTimeMs in startTime..endTime
}
}
/**
* Represents a collection of subtitle cues for a specific track.
*
* @property cues The list of subtitle cues
*/
@Immutable
data class SubtitleCueList(
val cues: List<SubtitleCue> = emptyList()
) {
/**
* Gets the active subtitle cues at the given time.
*
* @param currentTimeMs The current playback time in milliseconds
* @return The list of active subtitle cues
*/
fun getActiveCues(currentTimeMs: Long): List<SubtitleCue> {
return cues.filter { it.isActive(currentTimeMs) }
}
}
vendor/compose-mediaplayer/src/commonMain/kotlin/io/github/kdroidfilter/composemediaplayer/subtitle/SubtitleDisplay.kt
- Source · implementation · 125 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
36: fun SubtitleDisplay(
84: fun AutoUpdatingSubtitleDisplay(
Exact file bytes / download · SHA-256 8429e135493d5897d4e44e3857fede37621c43f561ab3ad08860a9e2c97a99db.
Complete file
package io.github.kdroidfilter.composemediaplayer.subtitle
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicText
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import kotlinx.coroutines.delay
import kotlin.time.Clock
/**
* A composable function that displays subtitles.
*
* @param subtitles The subtitle cue list to display
* @param currentTimeMs The current playback time in milliseconds
* @param modifier The modifier to be applied to the layout
* @param textStyle The text style to be applied to the subtitle text
* @param backgroundColor The background color of the subtitle box
*/
@Composable
fun SubtitleDisplay(
subtitles: SubtitleCueList,
currentTimeMs: Long,
modifier: Modifier = Modifier,
textStyle: TextStyle = TextStyle(
color = Color.White,
fontSize = 18.sp,
fontWeight = FontWeight.Normal,
textAlign = TextAlign.Center
),
backgroundColor: Color = Color.Black.copy(alpha = 0.5f)
) {
// Get active cues at the current time
val activeCues = subtitles.getActiveCues(currentTimeMs)
if (activeCues.isNotEmpty()) {
Box(
modifier = modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 8.dp),
contentAlignment = Alignment.BottomCenter
) {
// Join all active cue texts with line breaks
val subtitleText = activeCues.joinToString("\n") { it.text }
BasicText(
text = subtitleText,
style = textStyle,
modifier = Modifier
.background(backgroundColor, shape = RoundedCornerShape(4.dp))
.padding(horizontal = 8.dp, vertical = 4.dp)
)
}
}
}
/**
* A composable function that displays subtitles with automatic time tracking.
* This version automatically updates the display based on the current playback time.
*
* @param subtitles The subtitle cue list to display
* @param currentTimeMs The current playback time in milliseconds
* @param isPlaying Whether the video is currently playing
* @param modifier The modifier to be applied to the layout
* @param textStyle The text style to be applied to the subtitle text
* @param backgroundColor The background color of the subtitle box
*/
@Composable
fun AutoUpdatingSubtitleDisplay(
subtitles: SubtitleCueList,
currentTimeMs: Long,
isPlaying: Boolean,
modifier: Modifier = Modifier,
textStyle: TextStyle = TextStyle(
color = Color.White,
fontSize = 18.sp,
fontWeight = FontWeight.Normal,
textAlign = TextAlign.Center
),
backgroundColor: Color = Color.Black.copy(alpha = 0.5f)
) {
var displayTimeMs by remember { mutableStateOf(currentTimeMs) }
// Update display time when currentTimeMs changes
LaunchedEffect(currentTimeMs) {
displayTimeMs = currentTimeMs
}
// Periodically update display time when playing
LaunchedEffect(isPlaying, currentTimeMs) {
if (isPlaying) {
var lastUpdateTime = Clock.System.now().toEpochMilliseconds()
while (true) {
delay(16) // ~60fps
val now = Clock.System.now().toEpochMilliseconds()
val elapsed = now - lastUpdateTime
lastUpdateTime = now
displayTimeMs += elapsed
}
}
}
SubtitleDisplay(
subtitles = subtitles,
currentTimeMs = displayTimeMs,
modifier = modifier,
textStyle = textStyle,
backgroundColor = backgroundColor
)
}
vendor/compose-mediaplayer/src/commonMain/kotlin/io/github/kdroidfilter/composemediaplayer/subtitle/WebVttParser.kt
- Source · implementation · 122 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
10: object WebVttParser {
24: fun parse(content: String): SubtitleCueList {
79: private fun parseTimeToMillis(timeStr: String): Long {
111: suspend fun loadFromUrl(url: String): SubtitleCueList {
Exact file bytes / download · SHA-256 affc27ec6cd00eb7e1a8531d76ad22635342ef57ed9a20551a8b4033e69b89a2.
Complete file
package io.github.kdroidfilter.composemediaplayer.subtitle
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlin.io.encoding.ExperimentalEncodingApi
/**
* Parser for WebVTT subtitle files.
*/
object WebVttParser {
private const val WEBVTT_HEADER = "WEBVTT"
// Support both formats: "00:00:00.000" (with hours) and "00:00.000" (without hours)
private val TIME_PATTERN_WITH_HOURS = Regex("(\\d{2}):(\\d{2}):(\\d{2})\\.(\\d{3})")
private val TIME_PATTERN_WITHOUT_HOURS = Regex("(\\d{2}):(\\d{2})\\.(\\d{3})")
// Support both formats in the timing line
private val CUE_TIMING_PATTERN = Regex("(\\d{2}:\\d{2}:\\d{2}\\.\\d{3}|\\d{2}:\\d{2}\\.\\d{3}) --> (\\d{2}:\\d{2}:\\d{2}\\.\\d{3}|\\d{2}:\\d{2}\\.\\d{3})")
/**
* Parses a WebVTT file content into a SubtitleCueList.
*
* @param content The WebVTT file content as a string
* @return A SubtitleCueList containing the parsed subtitle cues
*/
fun parse(content: String): SubtitleCueList {
if (!content.trim().startsWith(WEBVTT_HEADER)) {
return SubtitleCueList() // Not a valid WebVTT file
}
val lines = content.lines()
val cues = mutableListOf<SubtitleCue>()
var i = 0
// Skip header and empty lines
while (i < lines.size && !CUE_TIMING_PATTERN.matches(lines[i])) {
i++
}
while (i < lines.size) {
val timingLine = lines[i]
val timingMatch = CUE_TIMING_PATTERN.find(timingLine)
if (timingMatch != null) {
val startTimeStr = timingMatch.groupValues[1]
val endTimeStr = timingMatch.groupValues[2]
val startTime = parseTimeToMillis(startTimeStr)
val endTime = parseTimeToMillis(endTimeStr)
i++
val textBuilder = StringBuilder()
// Collect all lines until an empty line or end of file
while (i < lines.size && lines[i].isNotEmpty()) {
if (textBuilder.isNotEmpty()) {
textBuilder.append("\n")
}
textBuilder.append(lines[i])
i++
}
val text = textBuilder.toString().trim()
if (text.isNotEmpty()) {
cues.add(SubtitleCue(startTime, endTime, text))
}
} else {
i++
}
}
return SubtitleCueList(cues)
}
/**
* Parses a time string in the format "00:00:00.000" or "00:00.000" to milliseconds.
*
* @param timeStr The time string to parse
* @return The time in milliseconds
*/
private fun parseTimeToMillis(timeStr: String): Long {
// Try to match the format with hours first
val matchWithHours = TIME_PATTERN_WITH_HOURS.find(timeStr)
if (matchWithHours != null) {
val hours = matchWithHours.groupValues[1].toLong()
val minutes = matchWithHours.groupValues[2].toLong()
val seconds = matchWithHours.groupValues[3].toLong()
val millis = matchWithHours.groupValues[4].toLong()
return (hours * 3600 + minutes * 60 + seconds) * 1000 + millis
}
// If that fails, try to match the format without hours
val matchWithoutHours = TIME_PATTERN_WITHOUT_HOURS.find(timeStr)
if (matchWithoutHours != null) {
val minutes = matchWithoutHours.groupValues[1].toLong()
val seconds = matchWithoutHours.groupValues[2].toLong()
val millis = matchWithoutHours.groupValues[3].toLong()
return (minutes * 60 + seconds) * 1000 + millis
}
return 0
}
/**
* Loads and parses a WebVTT file from a URL.
*
* @param url The URL of the WebVTT file
* @return A SubtitleCueList containing the parsed subtitle cues
*/
@OptIn(ExperimentalEncodingApi::class)
suspend fun loadFromUrl(url: String): SubtitleCueList {
return withContext(Dispatchers.Default) {
try {
// Use the platform-specific loadSubtitleContent function to fetch the content
val content = loadSubtitleContent(url)
parse(content)
} catch (e: Exception) {
SubtitleCueList() // Return empty list on error
}
}
}
}
vendor/compose-mediaplayer/src/commonMain/kotlin/io/github/kdroidfilter/composemediaplayer/util/Constants.kt
- Source · implementation · 3 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Exact file bytes / download · SHA-256 3f793f978d44172db9620605ad2a0715125c9925de2beb110e3cb144c1851cfe.
Complete file
package io.github.kdroidfilter.composemediaplayer.util
internal const val DEFAULT_ASPECT_RATIO = 16f / 9f
vendor/compose-mediaplayer/src/commonMain/kotlin/io/github/kdroidfilter/composemediaplayer/util/ContentScaleCanvasUtils.kt
- Source · implementation · 106 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
23: internal fun ContentScale.toCanvasModifier(aspectRatio: Float, width: Int?, height : Int?) : Modifier = when (this) {
64: internal fun DrawScope.drawScaledImage(
Exact file bytes / download · SHA-256 486a98d5557f81675bfac83c874df38a38c21a7364c9c09f2f7c6189b21dcb26.
Complete file
package io.github.kdroidfilter.composemediaplayer.util
import androidx.compose.foundation.layout.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.dp
/**
* Converts a [ContentScale] into a [Modifier] that adjusts the composable's size and scaling
* behavior based on the provided parameters.
*
* @param aspectRatio The aspect ratio to maintain when scaling the composable.
* @param width The width of the composable if using [ContentScale.None]. If `null`, defaults to 0.
* @param height The height of the composable if using [ContentScale.None]. If `null`, defaults to 0.
* @return A [Modifier] instance configured according to the given [ContentScale] and parameters.
*/
@Composable
internal fun ContentScale.toCanvasModifier(aspectRatio: Float, width: Int?, height : Int?) : Modifier = when (this) {
ContentScale.Fit,
ContentScale.Inside ->
Modifier
.fillMaxHeight()
.aspectRatio(aspectRatio)
// ↳ Fills the entire width, ratio preserved
ContentScale.FillWidth ->
Modifier
.fillMaxWidth()
.aspectRatio(aspectRatio)
// ↳ Fills the entire height, ratio preserved
ContentScale.FillHeight ->
Modifier
.fillMaxHeight()
.aspectRatio(aspectRatio)
// ↳ Fills the entire container; the excess will be clipped in drawImage
ContentScale.Crop,
ContentScale.FillBounds ->
Modifier.fillMaxSize()
// ↳ No resizing: we use the actual size of the media
ContentScale.None ->
Modifier
.width((width ?: 0).dp)
.height((height ?: 0).dp)
// ↳ Fallback value (should be impossible)
else -> Modifier
}
/**
* Draws [image] in this [DrawScope] respecting the requested [contentScale].
*
* @param image The source bitmap to draw.
* @param dstSize Destination size in pixels on the canvas (typically size.toIntSize()).
* @param contentScale How the image should be scaled inside [dstSize].
*/
internal fun DrawScope.drawScaledImage(
image: ImageBitmap,
dstSize: IntSize,
contentScale: ContentScale
) {
if (contentScale == ContentScale.Crop) {
/* --------------------------------------------------------------
* Central crop: scale the bitmap so it fully covers the canvas,
* then take the required source rectangle to fit the aspect.
* -------------------------------------------------------------- */
val frameW = image.width
val frameH = image.height
// Scale factor so that the image fully covers dstSize
val scale = maxOf(
dstSize.width / frameW.toFloat(),
dstSize.height / frameH.toFloat()
)
// Visible area of the source bitmap after the covering scale
val srcW = (dstSize.width / scale).toInt()
val srcH = (dstSize.height / scale).toInt()
val srcX = ((frameW - srcW) / 2).coerceAtLeast(0)
val srcY = ((frameH - srcH) / 2).coerceAtLeast(0)
drawImage(
image = image,
srcOffset = IntOffset(srcX, srcY),
srcSize = IntSize(srcW, srcH),
dstSize = dstSize // draw into full destination rect
)
} else {
/* --------------------------------------------------------------
* No cropping required (Fit / FillWidth / FillHeight / FillBounds).
* The selected ContentScale was already handled via caller’s
* graphicsLayer / Modifier.size, so we just draw the full bitmap.
* -------------------------------------------------------------- */
drawImage(
image = image,
dstSize = dstSize
)
}
}
vendor/compose-mediaplayer/src/commonMain/kotlin/io/github/kdroidfilter/composemediaplayer/util/FullScreenLayout.kt
- Source · implementation · 26 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.
Declaration checklist (source line numbers):
13: internal fun FullScreenLayout(
Exact file bytes / download · SHA-256 5da1f2be168d992bdfd8c65656d5151f37ac9eb00f6dc9d0f617b835bb61d169.
Complete file
package io.github.kdroidfilter.composemediaplayer.util
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
@Composable
internal fun FullScreenLayout(
modifier: Modifier = Modifier,
onDismissRequest: () -> Unit = {},
content: @Composable () -> Unit
) {
Dialog(
onDismissRequest = onDismissRequest,
properties = DialogProperties(usePlatformDefaultWidth = false)
) {
Box(modifier = modifier.fillMaxSize().background(Color.Black)) {
content()
}
}
}
vendor/compose-mediaplayer/src/commonMain/kotlin/io/github/kdroidfilter/composemediaplayer/util/TimeUtils.kt
- Source · implementation · 59 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
15: internal fun formatTime(value: Number, isNanoseconds: Boolean = false): String {
41: internal fun String.toTimeMs(): Long {
Exact file bytes / download · SHA-256 ef7bb10c69d7353086e5ebd75ff523c3099a44576db7d4d3e4508d90de1ddb74.
Complete file
package io.github.kdroidfilter.composemediaplayer.util
import kotlinx.datetime.Instant
import kotlinx.datetime.TimeZone
import kotlinx.datetime.toLocalDateTime
import kotlin.time.Duration.Companion.seconds
/**
* Formats a given time into either "HH:MM:SS" (if hours > 0) or "MM:SS".
*
* @param value The time value (if interpreting seconds, pass as Double;
* if interpreting nanoseconds, pass as Long).
* @param isNanoseconds Set to true when you're passing nanoseconds (Long) for [value].
*/
internal fun formatTime(value: Number, isNanoseconds: Boolean = false): String {
// Convert the input to seconds (Double) if it's nanoseconds
val totalSeconds = if (isNanoseconds) {
value.toLong() / 1_000_000_000.0
} else {
value.toDouble()
}
// Calculate hours, minutes, and seconds directly from total seconds
// This handles large time values correctly without date-time wrapping
val totalSecondsInt = totalSeconds.toLong()
val hours = totalSecondsInt / 3600
val minutes = (totalSecondsInt % 3600) / 60
val seconds = totalSecondsInt % 60
// Build the final string
return if (hours > 0) {
"${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}"
} else {
"${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}"
}
}
/**
* Converts a time string in the format "mm:ss" or "hh:mm:ss" to milliseconds.
*/
internal fun String.toTimeMs(): Long {
val parts = this.split(":")
return when (parts.size) {
2 -> {
// Format: "mm:ss"
val minutes = parts[0].toLongOrNull() ?: 0
val seconds = parts[1].toLongOrNull() ?: 0
(minutes * 60 + seconds) * 1000
}
3 -> {
// Format: "hh:mm:ss"
val hours = parts[0].toLongOrNull() ?: 0
val minutes = parts[1].toLongOrNull() ?: 0
val seconds = parts[2].toLongOrNull() ?: 0
(hours * 3600 + minutes * 60 + seconds) * 1000
}
else -> 0
}
}
vendor/compose-mediaplayer/src/commonMain/kotlin/io/github/kdroidfilter/composemediaplayer/util/Uri.kt
- Source · implementation · 5 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
5: expect fun PlatformFile.getUri(): String
Exact file bytes / download · SHA-256 fcf5aadfce960624607bc19ac716102355742b6475a557d16dc2696a991b09c3.
Complete file
package io.github.kdroidfilter.composemediaplayer.util
import io.github.vinceglb.filekit.PlatformFile
expect fun PlatformFile.getUri(): String
vendor/compose-mediaplayer/src/commonTest/kotlin/io/github/kdroidfilter/composemediaplayer/AwaitedPlayerDisposalTest.kt
- Source · test / fixture · 44 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
8: class AwaitedPlayerDisposalTest {
Exact file bytes / download · SHA-256 418b392eaf7d5e1bd20359b7a1d549f3d6e03fbf267c08c477433c4350a7a5d4.
Complete file
@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
package io.github.kdroidfilter.composemediaplayer
import kotlinx.coroutines.*
import kotlinx.coroutines.test.*
import kotlin.test.*
class AwaitedPlayerDisposalTest {
@Test fun immediateClosureStillJoinsDelayedCleanup() = runTest {
val entered = CompletableDeferred<Unit>(); val finish = CompletableDeferred<Unit>()
var retired = 0; var released = 0
val disposal = AwaitedPlayerDisposal(StandardTestDispatcher(testScheduler),
retire = { retired++ }, release = { entered.complete(Unit); finish.await(); released++ })
repeat(3) { disposal.dispose() }
entered.await(); val close = async { disposal.disposeAndJoin() }; runCurrent()
assertTrue(disposal.isRequested); assertEquals(1, retired); assertFalse(close.isCompleted)
finish.complete(Unit); close.await(); disposal.disposeAndJoin(); assertEquals(1, released)
}
@Test fun failedNativeReleaseRetriesWithoutReopeningAdmission() = runTest {
var attempts = 0; var fail = true
val disposal = AwaitedPlayerDisposal(StandardTestDispatcher(testScheduler), release = {
attempts++; if (fail) error("native close failed")
})
disposal.dispose(); runCurrent()
assertFailsWith<IllegalStateException> { disposal.disposeAndJoin() }
assertTrue(disposal.isRequested); assertEquals(2, attempts)
fail = false; disposal.disposeAndJoin(); disposal.disposeAndJoin(); assertEquals(3, attempts)
}
@Test fun cancelledAwaiterCannotAbandonNativeCleanup() = runTest {
val entered = CompletableDeferred<Unit>(); val finish = CompletableDeferred<Unit>()
val disposal = AwaitedPlayerDisposal(StandardTestDispatcher(testScheduler), release = {
entered.complete(Unit); finish.await()
})
val close = launch { disposal.disposeAndJoin() }; entered.await()
close.cancel(); runCurrent(); assertFalse(close.isCompleted)
finish.complete(Unit); close.join(); disposal.disposeAndJoin()
}
@Test fun concurrentAwaitersReleaseExactlyOnce() = runTest {
var released = 0
val disposal = AwaitedPlayerDisposal(StandardTestDispatcher(testScheduler), release = { delay(1); released++ })
val closes = List(10) { async { disposal.disposeAndJoin() } }
closes.awaitAll(); assertEquals(1, released)
}
}
vendor/compose-mediaplayer/src/commonTest/kotlin/io/github/kdroidfilter/composemediaplayer/SubtitleTrackTest.kt
- Source · test / fixture · 80 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
8: class SubtitleTrackTest {
11: fun testSubtitleTrackCreation() {
24: fun testSubtitleTrackEquality() {
48: fun testSubtitleTrackCopy() {
66: fun testSubtitleTrackToString() {
Exact file bytes / download · SHA-256 19e632686b7200239d03106562a1b54f0b7fe93f95cd69a8bc9b9dac31c125a2.
Complete file
package io.github.kdroidfilter.composemediaplayer
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotEquals
import kotlin.test.assertTrue
class SubtitleTrackTest {
@Test
fun testSubtitleTrackCreation() {
val track = SubtitleTrack(
label = "English",
language = "en",
src = "subtitles/en.vtt"
)
assertEquals("English", track.label)
assertEquals("en", track.language)
assertEquals("subtitles/en.vtt", track.src)
}
@Test
fun testSubtitleTrackEquality() {
val track1 = SubtitleTrack(
label = "English",
language = "en",
src = "subtitles/en.vtt"
)
val track2 = SubtitleTrack(
label = "English",
language = "en",
src = "subtitles/en.vtt"
)
val track3 = SubtitleTrack(
label = "French",
language = "fr",
src = "subtitles/fr.vtt"
)
assertEquals(track1, track2, "Identical subtitle tracks should be equal")
assertNotEquals(track1, track3, "Different subtitle tracks should not be equal")
}
@Test
fun testSubtitleTrackCopy() {
val original = SubtitleTrack(
label = "English",
language = "en",
src = "subtitles/en.vtt"
)
val copy = original.copy(label = "English (US)")
assertEquals("English (US)", copy.label)
assertEquals(original.language, copy.language)
assertEquals(original.src, copy.src)
// Original should remain unchanged
assertEquals("English", original.label)
}
@Test
fun testSubtitleTrackToString() {
val track = SubtitleTrack(
label = "English",
language = "en",
src = "subtitles/en.vtt"
)
val toString = track.toString()
// Verify that toString contains all the properties
assertTrue(toString.contains("English"))
assertTrue(toString.contains("en"))
assertTrue(toString.contains("subtitles/en.vtt"))
}
}
vendor/compose-mediaplayer/src/commonTest/kotlin/io/github/kdroidfilter/composemediaplayer/VideoMetadataTest.kt
- Source · test / fixture · 111 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
8: class VideoMetadataTest {
11: fun testEmptyMetadata() {
17: fun testPartialMetadata() {
38: fun testFullMetadata() {
64: fun testDataClassEquality() {
91: fun testCopyFunction() {
Exact file bytes / download · SHA-256 618176540a5be983c3ac0ed57d4aac6c14ee126cf5545c16d7da13f4071bd6bb.
Complete file
package io.github.kdroidfilter.composemediaplayer
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
class VideoMetadataTest {
@Test
fun testEmptyMetadata() {
val metadata = VideoMetadata()
assertTrue(metadata.isAllNull(), "A newly created metadata object should have all null properties")
}
@Test
fun testPartialMetadata() {
val metadata = VideoMetadata(
title = "Test Video",
duration = 60000L, // 1 minute
width = 1920,
height = 1080
)
assertFalse(metadata.isAllNull(), "Metadata with some properties set should not be all null")
assertEquals("Test Video", metadata.title)
assertEquals(60000L, metadata.duration)
assertEquals(1920, metadata.width)
assertEquals(1080, metadata.height)
assertEquals(null, metadata.bitrate)
assertEquals(null, metadata.frameRate)
assertEquals(null, metadata.mimeType)
assertEquals(null, metadata.audioChannels)
assertEquals(null, metadata.audioSampleRate)
}
@Test
fun testFullMetadata() {
val metadata = VideoMetadata(
title = "Complete Test Video",
duration = 120000L, // 2 minutes
width = 3840,
height = 2160,
bitrate = 5000000L, // 5 Mbps
frameRate = 30.0f,
mimeType = "video/mp4",
audioChannels = 2,
audioSampleRate = 48000
)
assertFalse(metadata.isAllNull(), "Fully populated metadata should not be all null")
assertEquals("Complete Test Video", metadata.title)
assertEquals(120000L, metadata.duration)
assertEquals(3840, metadata.width)
assertEquals(2160, metadata.height)
assertEquals(5000000L, metadata.bitrate)
assertEquals(30.0f, metadata.frameRate)
assertEquals("video/mp4", metadata.mimeType)
assertEquals(2, metadata.audioChannels)
assertEquals(48000, metadata.audioSampleRate)
}
@Test
fun testDataClassEquality() {
val metadata1 = VideoMetadata(
title = "Equality Test",
duration = 300000L, // 5 minutes
width = 1280,
height = 720
)
val metadata2 = VideoMetadata(
title = "Equality Test",
duration = 300000L,
width = 1280,
height = 720
)
val metadata3 = VideoMetadata(
title = "Different Title",
duration = 300000L,
width = 1280,
height = 720
)
assertEquals(metadata1, metadata2, "Identical metadata objects should be equal")
assertFalse(metadata1 == metadata3, "Metadata objects with different properties should not be equal")
}
@Test
fun testCopyFunction() {
val original = VideoMetadata(
title = "Original Video",
duration = 180000L, // 3 minutes
width = 1920,
height = 1080
)
val copy = original.copy(title = "Modified Video", bitrate = 3000000L)
assertEquals("Modified Video", copy.title)
assertEquals(original.duration, copy.duration)
assertEquals(original.width, copy.width)
assertEquals(original.height, copy.height)
assertEquals(3000000L, copy.bitrate)
// Original should remain unchanged
assertEquals("Original Video", original.title)
assertEquals(null, original.bitrate)
}
}
vendor/compose-mediaplayer/src/commonTest/kotlin/io/github/kdroidfilter/composemediaplayer/VideoPlayerErrorTest.kt
- Source · test / fixture · 80 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
8: class VideoPlayerErrorTest {
11: fun testCodecError() {
19: fun testNetworkError() {
27: fun testSourceError() {
35: fun testUnknownError() {
43: fun testErrorEquality() {
57: fun testErrorTypes() {
Exact file bytes / download · SHA-256 58334bb2be33da8d9ab9855a725a96f587c722501ac5d121119b9213f8ff99b4.
Complete file
package io.github.kdroidfilter.composemediaplayer
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotEquals
import kotlin.test.assertTrue
class VideoPlayerErrorTest {
@Test
fun testCodecError() {
val error = VideoPlayerError.CodecError("Unsupported codec")
assertTrue(error is VideoPlayerError.CodecError)
assertEquals("Unsupported codec", (error as VideoPlayerError.CodecError).message)
}
@Test
fun testNetworkError() {
val error = VideoPlayerError.NetworkError("Connection timeout")
assertTrue(error is VideoPlayerError.NetworkError)
assertEquals("Connection timeout", (error as VideoPlayerError.NetworkError).message)
}
@Test
fun testSourceError() {
val error = VideoPlayerError.SourceError("File not found")
assertTrue(error is VideoPlayerError.SourceError)
assertEquals("File not found", (error as VideoPlayerError.SourceError).message)
}
@Test
fun testUnknownError() {
val error = VideoPlayerError.UnknownError("Unexpected error")
assertTrue(error is VideoPlayerError.UnknownError)
assertEquals("Unexpected error", (error as VideoPlayerError.UnknownError).message)
}
@Test
fun testErrorEquality() {
val error1 = VideoPlayerError.CodecError("Same error")
val error2 = VideoPlayerError.CodecError("Same error")
val error3 = VideoPlayerError.CodecError("Different error")
val error4 = VideoPlayerError.NetworkError("Same error")
assertEquals(error1, error2, "Same error type and message should be equal")
assertNotEquals(error1, error3, "Same error type but different message should not be equal")
// For different types, we can just assert they're not the same object
assertTrue(error1 != error4, "Different error type should not be equal")
}
@Test
fun testErrorTypes() {
val codecError = VideoPlayerError.CodecError("Codec error")
val networkError = VideoPlayerError.NetworkError("Network error")
val sourceError = VideoPlayerError.SourceError("Source error")
val unknownError = VideoPlayerError.UnknownError("Unknown error")
// Verify that each error is an instance of VideoPlayerError
assertTrue(codecError is VideoPlayerError)
assertTrue(networkError is VideoPlayerError)
assertTrue(sourceError is VideoPlayerError)
assertTrue(unknownError is VideoPlayerError)
// Verify that errors of different types are not equal
val errors = listOf(codecError, networkError, sourceError, unknownError)
for (i in errors.indices) {
for (j in errors.indices) {
if (i != j) {
assertTrue(errors[i] != errors[j],
"Different error types should not be equal: ${errors[i]} vs ${errors[j]}")
}
}
}
}
}
vendor/compose-mediaplayer/src/commonTest/kotlin/io/github/kdroidfilter/composemediaplayer/util/TimeUtilsTest.kt
- Source · test / fixture · 78 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
6: class TimeUtilsTest {
9: fun testFormatTimeWithSeconds() {
24: fun testFormatTimeWithNanoseconds() {
38: fun testToTimeMs() {
58: fun testRoundTrip() {
Exact file bytes / download · SHA-256 b115aae56823ec6cc8b95c37790f070da445fe4ea88a9ca871a847e9beadf628.
Complete file
package io.github.kdroidfilter.composemediaplayer.util
import kotlin.test.Test
import kotlin.test.assertEquals
class TimeUtilsTest {
@Test
fun testFormatTimeWithSeconds() {
// Test with seconds (as Double)
assertEquals("00:00", formatTime(0.0))
assertEquals("00:01", formatTime(1.0))
assertEquals("00:59", formatTime(59.0))
assertEquals("01:00", formatTime(60.0))
assertEquals("01:01", formatTime(61.0))
assertEquals("59:59", formatTime(3599.0))
assertEquals("01:00:00", formatTime(3600.0))
assertEquals("01:00:01", formatTime(3601.0))
assertEquals("01:01:01", formatTime(3661.0))
assertEquals("99:59:59", formatTime(359999.0))
}
@Test
fun testFormatTimeWithNanoseconds() {
// Test with nanoseconds (as Long)
assertEquals("00:00", formatTime(0L, true))
assertEquals("00:01", formatTime(1_000_000_000L, true))
assertEquals("00:59", formatTime(59_000_000_000L, true))
assertEquals("01:00", formatTime(60_000_000_000L, true))
assertEquals("01:01", formatTime(61_000_000_000L, true))
assertEquals("59:59", formatTime(3599_000_000_000L, true))
assertEquals("01:00:00", formatTime(3600_000_000_000L, true))
assertEquals("01:00:01", formatTime(3601_000_000_000L, true))
assertEquals("01:01:01", formatTime(3661_000_000_000L, true))
}
@Test
fun testToTimeMs() {
// Test conversion from time string to milliseconds
assertEquals(0, "00:00".toTimeMs())
assertEquals(1000, "00:01".toTimeMs())
assertEquals(59000, "00:59".toTimeMs())
assertEquals(60000, "01:00".toTimeMs())
assertEquals(61000, "01:01".toTimeMs())
assertEquals(3599000, "59:59".toTimeMs())
assertEquals(3600000, "01:00:00".toTimeMs())
assertEquals(3601000, "01:00:01".toTimeMs())
assertEquals(3661000, "01:01:01".toTimeMs())
// Test invalid formats
assertEquals(0, "invalid".toTimeMs())
assertEquals(0, "".toTimeMs())
assertEquals(0, ":".toTimeMs())
assertEquals(0, "::".toTimeMs())
}
@Test
fun testRoundTrip() {
// Test that converting from seconds to string and back to milliseconds works correctly
val testSeconds = listOf(0.0, 1.0, 59.0, 60.0, 61.0, 3599.0, 3600.0, 3601.0, 3661.0)
for (seconds in testSeconds) {
val formatted = formatTime(seconds)
val milliseconds = formatted.toTimeMs()
// Allow for small rounding differences due to floating point
val expectedMs = (seconds * 1000).toLong()
val tolerance = 1000L // 1 second tolerance due to rounding to whole seconds in formatTime
assertEquals(
true,
kotlin.math.abs(expectedMs - milliseconds) <= tolerance,
"Round trip conversion failed for $seconds seconds. " +
"Expected ~$expectedMs ms, got $milliseconds ms (formatted as $formatted)"
)
}
}
}
vendor/compose-mediaplayer/src/iosMain/kotlin/io/github/kdroidfilter/composemediaplayer/FullscreenVideoPlayerView.kt
- Source · implementation · 70 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
25: fun openFullscreenView(
40: private fun FullscreenVideoPlayerView(
55: fun exitFullScreen() {
Exact file bytes / download · SHA-256 43780cd332f49781c17692c27963f9f18956775ec36facb42e5e19110bc2e190.
Complete file
@file:OptIn(ExperimentalForeignApi::class)
package io.github.kdroidfilter.composemediaplayer
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import io.github.kdroidfilter.composemediaplayer.util.FullScreenLayout
import io.github.kdroidfilter.composemediaplayer.util.VideoPlayerStateRegistry
import kotlinx.cinterop.ExperimentalForeignApi
/**
* Opens a fullscreen view for the video player on iOS.
* This function is called when the user toggles fullscreen mode.
*
* @param playerState The player state to use in the fullscreen view
* @param renderSurface A composable function that renders the video player surface
*/
@Composable
fun openFullscreenView(
playerState: VideoPlayerState,
renderSurface: @Composable (VideoPlayerState, Modifier, Boolean) -> Unit
) {
// Register the player state to be accessible from the fullscreen view
VideoPlayerStateRegistry.registerState(playerState)
FullscreenVideoPlayerView(renderSurface)
}
/**
* A composable function that creates a fullscreen view for the video player on iOS.
*
* @param renderSurface A composable function that renders the video player surface
*/
@Composable
private fun FullscreenVideoPlayerView(
renderSurface: @Composable (VideoPlayerState, Modifier, Boolean) -> Unit
) {
// Get the player state from the registry
val playerState = remember {
VideoPlayerStateRegistry.getRegisteredState()
}
// Handle view close to exit fullscreen
DisposableEffect(Unit) {
onDispose {
playerState?.isFullscreen = false
}
}
fun exitFullScreen() {
playerState?.isFullscreen = false
VideoPlayerStateRegistry.clearRegisteredState()
}
// Create a fullscreen view using FullScreenLayout
playerState?.let { state ->
FullScreenLayout(
onDismissRequest = { exitFullScreen() }
) {
Box(modifier = Modifier.fillMaxSize().background(Color.Black)) {
renderSurface(state, Modifier.fillMaxSize(), true)
}
}
}
}
vendor/compose-mediaplayer/src/iosMain/kotlin/io/github/kdroidfilter/composemediaplayer/VideoPlayerState.ios.kt
- Source · implementation · 564 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
31: actual open class VideoPlayerState {
158: private fun startPositionUpdates() {
210: private fun stopPositionUpdates() {
217: private fun removeObservers() {
229: actual fun openUri(uri: String) {
378: actual fun play() {
415: actual fun pause() {
425: actual fun stop() {
438: actual fun seekTo(value: Float) {
463: actual fun clearError() {
470: actual fun toggleFullscreen() {
490: actual fun dispose() = disposal.dispose()
491: actual suspend fun disposeAndJoin() = disposal.disposeAndJoin()
493: actual fun openFile(file: PlatformFile) {
537: actual fun selectSubtitleTrack(track: SubtitleTrack?) {
555: actual fun disableSubtitles() {
Exact file bytes / download · SHA-256 dcbea2287f559fa39cebf2488751e2d1c19bbead0a233532362f60e5265d0c98.
Complete file
@file:OptIn(ExperimentalForeignApi::class)
package io.github.kdroidfilter.composemediaplayer
import androidx.compose.runtime.Stable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.sp
import co.touchlab.kermit.Logger
import io.github.kdroidfilter.composemediaplayer.util.formatTime
import io.github.kdroidfilter.composemediaplayer.util.getUri
import io.github.vinceglb.filekit.PlatformFile
import kotlinx.cinterop.ExperimentalForeignApi
import kotlinx.cinterop.useContents
import platform.AVFoundation.*
import platform.CoreGraphics.CGFloat
import platform.CoreMedia.CMTimeGetSeconds
import platform.CoreMedia.CMTimeMakeWithSeconds
import platform.Foundation.NSNotificationCenter
import platform.Foundation.NSURL
import kotlinx.coroutines.*
import platform.darwin.dispatch_get_main_queue
@OptIn(ExperimentalForeignApi::class)
@Stable
actual open class VideoPlayerState {
private val playerScope = CoroutineScope(SupervisorJob() + Dispatchers.Main)
private var loadingJob: Job? = null
// Base states
private var _volume = mutableStateOf(1.0f)
actual var volume: Float
get() = _volume.value
set(value) {
val clampedValue = value.coerceIn(0f, 1f)
_volume.value = clampedValue
if (_isPlaying) {
player?.volume = clampedValue
}
}
actual var sliderPos: Float by mutableStateOf(0f) // value between 0 and 1000
actual var userDragging: Boolean = false
private var _loop by mutableStateOf(false)
actual var loop: Boolean
get() = _loop
set(value) {
_loop = value
Logger.d { "Loop setting changed to: $value" }
// If we have an active player, update its loop behavior
player?.let { player ->
// In iOS, we need to recreate the end observer with the new loop setting
// First, remove the existing observer
endObserver?.let {
NSNotificationCenter.defaultCenter.removeObserver(it)
endObserver = null
}
// Then create a new observer with the updated loop setting
endObserver = NSNotificationCenter.defaultCenter.addObserverForName(
name = AVPlayerItemDidPlayToEndTimeNotification,
`object` = player.currentItem,
queue = null
) { _ ->
if (disposal.isRequested || this@VideoPlayerState.player !== player || userInitiatedPause) return@addObserverForName
if (_duration > 0 && (_duration - _currentTime) > 0.1) {
return@addObserverForName
}
if (_loop) {
player.seekToTime(CMTimeMakeWithSeconds(0.0, 1))
player.rate = _playbackSpeed
player.play()
} else {
player.pause()
_isPlaying = false
}
}
}
}
// Playback speed control
private var _playbackSpeed by mutableStateOf(1.0f)
actual var playbackSpeed: Float
get() = _playbackSpeed
set(value) {
_playbackSpeed = value.coerceIn(0.5f, 2.0f)
player?.rate = _playbackSpeed
}
// Playback states
actual val hasMedia: Boolean get() = _hasMedia
actual val isPlaying: Boolean get() = _isPlaying
private var _hasMedia by mutableStateOf(false)
private var _isPlaying by mutableStateOf(false)
// Displayed texts for position and duration
private var _positionText: String by mutableStateOf("00:00")
actual val positionText: String get() = _positionText
private var _durationText: String by mutableStateOf("00:00")
actual val durationText: String get() = _durationText
// Loading state
private var _isLoading by mutableStateOf(false)
actual val isLoading: Boolean
get() = _isLoading
// Fullscreen state
private var _isFullscreen by mutableStateOf(false)
actual var isFullscreen: Boolean
get() = _isFullscreen
set(value) {
_isFullscreen = value
}
actual val error: VideoPlayerError? = null
// Observable instance of AVPlayer
var player: AVPlayer? by mutableStateOf(null)
private set
// Periodic observer for position updates (≈60 fps)
private var timeObserverToken: Any? = null
// End-of-playback notification observer
private var endObserver: Any? = null
// Stalled playback notification observer
private var stalledObserver: Any? = null
// Internal time values (in seconds)
private var _currentTime: Double = 0.0
private var _duration: Double = 0.0
// Flag to indicate user-initiated pause
private var userInitiatedPause: Boolean = false
// Audio levels (not yet implemented)
actual val leftLevel: Float = 0f
actual val rightLevel: Float = 0f
// Observable video aspect ratio (default to 16:9)
private var _videoAspectRatio by mutableStateOf(16.0 / 9.0)
val videoAspectRatio: CGFloat
get() = _videoAspectRatio
actual val aspectRatio: Float = _videoAspectRatio.toFloat()
// Video metadata
private var _metadata = VideoMetadata(audioChannels = 2)
private fun startPositionUpdates() {
stopPositionUpdates()
val observedPlayer = player ?: return
val interval = CMTimeMakeWithSeconds(1.0 / 60.0, 600) // approx. 60 fps
timeObserverToken = observedPlayer.addPeriodicTimeObserverForInterval(
interval = interval,
queue = dispatch_get_main_queue(),
usingBlock = update@ { time ->
if (disposal.isRequested || player !== observedPlayer) return@update
val currentSeconds = CMTimeGetSeconds(time)
val durationSeconds = player?.currentItem?.duration?.let { CMTimeGetSeconds(it) } ?: 0.0
_currentTime = currentSeconds
_duration = durationSeconds
// Update duration in metadata
if (durationSeconds > 0 && !durationSeconds.isNaN()) {
_metadata.duration = (durationSeconds * 1000).toLong()
}
if (!userDragging && durationSeconds > 0 && !currentSeconds.isNaN() && !durationSeconds.isNaN()) {
sliderPos = ((currentSeconds / durationSeconds) * 1000).toFloat()
}
_positionText = if (currentSeconds.isNaN()) "00:00" else formatTime(currentSeconds.toFloat())
_durationText = if (durationSeconds.isNaN()) "00:00" else formatTime(durationSeconds.toFloat())
player?.currentItem?.presentationSize?.useContents {
// Only update if dimensions are valid (greater than 0)
if (width > 0 && height > 0) {
// Try to use real aspect ratio if available, fallback to 16:9
val realAspect = width / height
_videoAspectRatio = realAspect
// Update width and height in metadata if they're not already set or if they're zero
if (_metadata.width == null || _metadata.width == 0 || _metadata.height == null || _metadata.height == 0) {
_metadata.width = width.toInt()
_metadata.height = height.toInt()
Logger.d { "Video resolution updated during playback: ${width.toInt()}x${height.toInt()}" }
}
}
}
player?.currentItem?.let { item ->
val isBufferEmpty = item.playbackBufferEmpty
val isLikelyToKeepUp = item.playbackLikelyToKeepUp
_isLoading = isBufferEmpty || !isLikelyToKeepUp
} ?: run {
_isLoading = false
}
}
)
}
private fun stopPositionUpdates() {
timeObserverToken?.let { token ->
player?.removeTimeObserver(token)
timeObserverToken = null
}
}
private fun removeObservers() {
endObserver?.let {
NSNotificationCenter.defaultCenter.removeObserver(it)
endObserver = null
}
stalledObserver?.let {
NSNotificationCenter.defaultCenter.removeObserver(it)
stalledObserver = null
}
}
actual fun openUri(uri: String) {
if (disposal.isRequested) return
Logger.d { "openUri called with uri: $uri" }
val nsUrl = NSURL.URLWithString(uri) ?: run {
Logger.d { "Failed to create NSURL from uri: $uri" }
return
}
loadingJob?.cancel()
stopPositionUpdates()
removeObservers()
player?.pause()
// Reset playback speed to 1.0f when opening a new video
_playbackSpeed = 1.0f
// Set loading state to true at the beginning of loading a new video
_isLoading = true
// Reset metadata to default values
_metadata = VideoMetadata(audioChannels = 2)
// Create a temporary player with minimal setup to show something immediately
val tempPlayerItem = AVPlayerItem(nsUrl)
player = AVPlayer(playerItem = tempPlayerItem).apply {
volume = this@VideoPlayerState.volume
rate = 0.0f // Don't start playing yet
}
_hasMedia = true
// Process the asset on a background thread to avoid blocking the UI
val capturedPlayer = player
val preparedMetadata = VideoMetadata(audioChannels = 2)
loadingJob = playerScope.launch {
withContext(Dispatchers.Default) {
// Create an AVAsset to extract metadata
val asset = AVURLAsset.URLAssetWithURL(nsUrl, null)
// Extract metadata from tracks
var videoAspectRatioTemp = 16.0 / 9.0
var widthTemp: Int? = null
var heightTemp: Int? = null
// Process video tracks
val videoTracks = asset.tracksWithMediaType(AVMediaTypeVideo)
if (videoTracks.isNotEmpty()) {
val videoTrack = videoTracks.firstOrNull() as? AVAssetTrack
videoTrack?.let { track ->
// Get frame rate
val nominalFrameRate = track.nominalFrameRate
if (nominalFrameRate > 0) {
preparedMetadata.frameRate = nominalFrameRate
}
// Get bitrate
val trackBitrate = track.estimatedDataRate
if (trackBitrate > 0) {
preparedMetadata.bitrate = trackBitrate.toLong()
}
// Get resolution from naturalSize
track.naturalSize.useContents {
if (width > 0 && height > 0) {
widthTemp = width.toInt()
heightTemp = height.toInt()
// Try to use real aspect ratio if available, fallback to 16:9
videoAspectRatioTemp = width / height
Logger.d { "Video resolution from track: ${width.toInt()}x${height.toInt()}" }
}
}
}
}
// Process audio tracks
val audioTracks = asset.tracksWithMediaType(AVMediaTypeAudio)
if (audioTracks.isNotEmpty()) {
// Set audio channels to 2 (stereo) as a more accurate default
// Most audio content is stereo, and we can't easily get the actual channel count
// from AVAssetTrack in Kotlin/Native
preparedMetadata.audioChannels = 2 // Default to stereo instead of using track count
// Try to get sample rate (simplified approach)
preparedMetadata.audioSampleRate = 44100 // Default to common value
}
// Create player item from asset to get more accurate metadata
val playerItem = AVPlayerItem(asset)
var durationSeconds = 0.0
// Try to get duration
durationSeconds = CMTimeGetSeconds(playerItem.duration)
if (durationSeconds > 0 && !durationSeconds.isNaN()) {
preparedMetadata.duration = (durationSeconds * 1000).toLong()
}
// Try to extract title from the file name
val fileName = nsUrl.lastPathComponent
if (fileName != null) {
preparedMetadata.title = fileName
}
// Update UI on the main thread
withContext(Dispatchers.Main) publish@ {
ensureActive()
if (disposal.isRequested || player !== capturedPlayer) return@publish
_metadata = preparedMetadata
// Update metadata
if (widthTemp != null && heightTemp != null) {
preparedMetadata.width = widthTemp
preparedMetadata.height = heightTemp
_videoAspectRatio = videoAspectRatioTemp
}
// Create the final player with the fully loaded asset
player = AVPlayer(playerItem = playerItem).apply {
volume = this@VideoPlayerState.volume
rate = if (userInitiatedPause) 0.0f else _playbackSpeed
actionAtItemEnd = AVPlayerActionAtItemEndNone
}
// Set up the end observer with the current loop setting
// This will be updated whenever the loop property changes
endObserver = NSNotificationCenter.defaultCenter.addObserverForName(
name = AVPlayerItemDidPlayToEndTimeNotification,
`object` = player?.currentItem,
queue = null
) { notification ->
if (notification?.`object` !== player?.currentItem) return@addObserverForName
if (disposal.isRequested || userInitiatedPause) return@addObserverForName
if (_duration > 0 && (_duration - _currentTime) > 0.1) {
return@addObserverForName
}
if (_loop) {
player?.seekToTime(CMTimeMakeWithSeconds(0.0, 1))
player?.rate = _playbackSpeed
player?.play()
} else {
player?.pause()
_isPlaying = false
}
}
startPositionUpdates()
if (!userInitiatedPause) play()
}
}
}
}
actual fun play() {
if (disposal.isRequested) return
Logger.d { "play called" }
userInitiatedPause = false
if (player == null) {
Logger.d { "play: player is null" }
return
}
// Set loading to true when play is called
_isLoading = true
player?.volume = volume
player?.rate = _playbackSpeed
player?.play()
_isPlaying = true
_hasMedia = true
// Add a listener to detect when the player is ready to play
player?.currentItem?.let { item ->
if (item.playbackLikelyToKeepUp) {
_isLoading = false
} else {
// If not ready yet, add a notification observer for when it becomes ready
stalledObserver = NSNotificationCenter.defaultCenter.addObserverForName(
name = AVPlayerItemPlaybackStalledNotification,
`object` = item,
queue = null
) { _ ->
if (disposal.isRequested || player?.currentItem !== item) return@addObserverForName
// Check if playback is likely to keep up now
if (item.playbackLikelyToKeepUp) {
_isLoading = false
}
}
}
}
}
actual fun pause() {
if (disposal.isRequested) return
Logger.d { "pause called" }
userInitiatedPause = true
// Ensure the pause call is on the main thread:
val capturedPlayer = player
playerScope.launch { if (!disposal.isRequested && player === capturedPlayer) capturedPlayer?.pause() }
_isPlaying = false
}
actual fun stop() {
if (disposal.isRequested) return
Logger.d { "stop called" }
loadingJob?.cancel()
player?.pause()
player?.seekToTime(CMTimeMakeWithSeconds(0.0, 1))
_isPlaying = false
_hasMedia = false
// Reset metadata
_metadata = VideoMetadata(audioChannels = 2)
}
actual fun seekTo(value: Float) {
if (disposal.isRequested) return
if (_duration > 0) {
// Set loading state to true to indicate seeking is happening
_isLoading = true
val targetTime = _duration * (value / 1000.0)
// First, perform a seek with a lower timescale (like in macOS)
player?.seekToTime(CMTimeMakeWithSeconds(targetTime, 1))
// Then immediately perform another seek with a higher timescale
// This ensures at least one of the seeks will work properly
player?.seekToTime(CMTimeMakeWithSeconds(targetTime, 600))
// Ensure playback speed is maintained after seeking
player?.rate = _playbackSpeed
// Reset loading state after a short delay
val capturedPlayer = player
playerScope.launch { if (!disposal.isRequested && player === capturedPlayer) _isLoading = false }
}
}
actual fun clearError() {
Logger.d { "clearError called" }
}
/**
* Toggles the fullscreen state of the video player
*/
actual fun toggleFullscreen() {
Logger.d { "toggleFullscreen called" }
_isFullscreen = !_isFullscreen
}
private val disposal = AwaitedPlayerDisposal(
dispatcher = kotlinx.coroutines.Dispatchers.Main,
retire = { playerScope.cancel(); stopPositionUpdates(); removeObservers(); player?.pause() },
release = {
playerScope.coroutineContext[Job]?.join()
Logger.d { "dispose called" }
stopPositionUpdates()
removeObservers()
player?.pause()
player = null
_hasMedia = false
_isPlaying = false
_metadata = VideoMetadata(audioChannels = 2)
},
)
actual fun dispose() = disposal.dispose()
actual suspend fun disposeAndJoin() = disposal.disposeAndJoin()
actual fun openFile(file: PlatformFile) {
Logger.d { "openFile called with file: $file" }
// Use the getUri extension function to get a proper file URL
val fileUrl = file.getUri()
Logger.d { "Opening file with URL: $fileUrl" }
openUri(fileUrl)
}
actual val metadata: VideoMetadata
get() = _metadata
// Subtitle state
private var _subtitlesEnabled by mutableStateOf(false)
actual var subtitlesEnabled: Boolean
get() = _subtitlesEnabled
set(value) {
_subtitlesEnabled = value
}
private var _currentSubtitleTrack by mutableStateOf<SubtitleTrack?>(null)
actual var currentSubtitleTrack: SubtitleTrack?
get() = _currentSubtitleTrack
set(value) {
_currentSubtitleTrack = value
}
private val _availableSubtitleTracks = mutableListOf<SubtitleTrack>()
actual val availableSubtitleTracks: MutableList<SubtitleTrack>
get() = _availableSubtitleTracks
actual var subtitleTextStyle: TextStyle = TextStyle(
color = Color.White,
fontSize = 18.sp,
fontWeight = FontWeight.Normal,
textAlign = TextAlign.Center
)
actual var subtitleBackgroundColor: Color = Color.Black.copy(alpha = 0.5f)
/**
* Selects a subtitle track for display.
* If track is null, disables subtitles.
*
* @param track The subtitle track to select, or null to disable subtitles
*/
actual fun selectSubtitleTrack(track: SubtitleTrack?) {
Logger.d { "selectSubtitleTrack called with track: $track" }
if (track == null) {
disableSubtitles()
return
}
// Update current track and enable flag
currentSubtitleTrack = track
subtitlesEnabled = true
// iOS uses Compose-based subtitles, so we don't need to configure
// the native player for subtitle display
}
/**
* Disables subtitle display.
*/
actual fun disableSubtitles() {
Logger.d { "disableSubtitles called" }
// Update state
currentSubtitleTrack = null
subtitlesEnabled = false
// iOS uses Compose-based subtitles, so we don't need to configure
// the native player for subtitle display
}
}
vendor/compose-mediaplayer/src/iosMain/kotlin/io/github/kdroidfilter/composemediaplayer/VideoPlayerSurface.ios.kt
- Source · implementation · 169 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
28: actual fun VideoPlayerSurface(
39: fun VideoPlayerSurfaceImpl(
Exact file bytes / download · SHA-256 875899804d1c39473f0c3ae6aa710bbf105982d48fccdbda9b8a45106aa7e899.
Complete file
@file:OptIn(ExperimentalForeignApi::class)
package io.github.kdroidfilter.composemediaplayer
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.viewinterop.UIKitView
import co.touchlab.kermit.Logger
import io.github.kdroidfilter.composemediaplayer.subtitle.ComposeSubtitleLayer
import io.github.kdroidfilter.composemediaplayer.util.toCanvasModifier
import io.github.kdroidfilter.composemediaplayer.util.toTimeMs
import kotlinx.cinterop.ExperimentalForeignApi
import platform.AVFoundation.AVLayerVideoGravityResizeAspect
import platform.AVFoundation.AVLayerVideoGravityResizeAspectFill
import platform.AVFoundation.AVLayerVideoGravityResize
import platform.AVKit.AVPlayerViewController
import platform.UIKit.*
@OptIn(ExperimentalForeignApi::class)
@Composable
actual fun VideoPlayerSurface(
playerState: VideoPlayerState,
modifier: Modifier,
contentScale: ContentScale,
overlay: @Composable () -> Unit
) {
VideoPlayerSurfaceImpl(playerState, modifier, contentScale, overlay, isInFullscreenView = false)
}
@OptIn(ExperimentalForeignApi::class)
@Composable
fun VideoPlayerSurfaceImpl(
playerState: VideoPlayerState,
modifier: Modifier,
contentScale: ContentScale,
overlay: @Composable () -> Unit,
isInFullscreenView: Boolean = false
) {
// Create and store the AVPlayerViewController
val avPlayerViewController = remember {
AVPlayerViewController().apply {
showsPlaybackControls = false
}
}
// Cleanup when deleting the view
DisposableEffect(Unit) {
onDispose {
Logger.d { "[VideoPlayerSurface] Disposing" }
playerState.pause()
avPlayerViewController.removeFromParentViewController()
}
}
// Update the player when it changes
DisposableEffect(playerState.player) {
Logger.d{"Video Player updated"}
avPlayerViewController.player = playerState.player
onDispose { }
}
if (playerState.hasMedia) {
Box(
modifier = modifier,
contentAlignment = Alignment.Center
) {
// Use the contentScale parameter to adjust the view's size and scaling behavior
UIKitView(
modifier = contentScale.toCanvasModifier(
playerState.videoAspectRatio.toFloat(),
playerState.metadata.width,
playerState.metadata.height
),
factory = {
UIView().apply {
backgroundColor = UIColor.blackColor
clipsToBounds = true
avPlayerViewController.view.translatesAutoresizingMaskIntoConstraints = false
addSubview(avPlayerViewController.view)
NSLayoutConstraint.activateConstraints(
listOf(
avPlayerViewController.view.topAnchor.constraintEqualToAnchor(this.topAnchor),
avPlayerViewController.view.leadingAnchor.constraintEqualToAnchor(this.leadingAnchor),
avPlayerViewController.view.trailingAnchor.constraintEqualToAnchor(this.trailingAnchor),
avPlayerViewController.view.bottomAnchor.constraintEqualToAnchor(this.bottomAnchor)
)
)
// Set the videoGravity based on the ContentScale
// Map ContentScale to AVLayerVideoGravity
val videoGravity = when (contentScale) {
ContentScale.Crop,
ContentScale.FillHeight -> AVLayerVideoGravityResizeAspectFill
ContentScale.FillWidth -> AVLayerVideoGravityResizeAspectFill
ContentScale.FillBounds -> AVLayerVideoGravityResize
ContentScale.Fit,
ContentScale.Inside -> AVLayerVideoGravityResizeAspect
else -> AVLayerVideoGravityResizeAspect
}
// Set the videoGravity directly on the AVPlayerViewController
avPlayerViewController.videoGravity = videoGravity
Logger.d { "View configured with contentScale: $contentScale, videoGravity: $videoGravity" }
}
},
update = { containerView ->
// Hide or show the view depending on the presence of media
containerView.hidden = !playerState.hasMedia
// Update the videoGravity when contentScale changes
val videoGravity = when (contentScale) {
ContentScale.Crop,
ContentScale.FillHeight -> AVLayerVideoGravityResizeAspectFill // ⬅️ changement
ContentScale.FillWidth -> AVLayerVideoGravityResizeAspectFill // (même logique)
ContentScale.FillBounds -> AVLayerVideoGravityResize // pas d’aspect-ratio
ContentScale.Fit,
ContentScale.Inside -> AVLayerVideoGravityResizeAspect
else -> AVLayerVideoGravityResizeAspect
}
avPlayerViewController.videoGravity = videoGravity
containerView.setNeedsLayout()
containerView.layoutIfNeeded()
avPlayerViewController.view.setFrame(containerView.bounds)
}
)
// Add Compose-based subtitle layer
if (playerState.subtitlesEnabled && playerState.currentSubtitleTrack != null) {
// Calculate current time in milliseconds
val currentTimeMs = (playerState.sliderPos / 1000f *
playerState.durationText.toTimeMs()).toLong()
// Calculate duration in milliseconds
val durationMs = playerState.durationText.toTimeMs()
ComposeSubtitleLayer(
currentTimeMs = currentTimeMs,
durationMs = durationMs,
isPlaying = playerState.isPlaying,
subtitleTrack = playerState.currentSubtitleTrack,
subtitlesEnabled = playerState.subtitlesEnabled,
textStyle = playerState.subtitleTextStyle,
backgroundColor = playerState.subtitleBackgroundColor
)
}
// Render the overlay content on top of the video
overlay()
}
}
// Handle fullscreen mode
if (playerState.isFullscreen && !isInFullscreenView) {
openFullscreenView(playerState) { state, mod, inFullscreen ->
VideoPlayerSurfaceImpl(state, mod, contentScale, overlay, inFullscreen)
}
}
}
vendor/compose-mediaplayer/src/iosMain/kotlin/io/github/kdroidfilter/composemediaplayer/subtitle/SubtitleLoader.ios.kt
- Source · implementation · 71 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
20: actual suspend fun loadSubtitleContent(src: String): String = withContext(Dispatchers.Default) {
Exact file bytes / download · SHA-256 4f602cf216b654329c3d4ce6b5289a24b3c644249f17a81056533a62b7511579.
Complete file
package io.github.kdroidfilter.composemediaplayer.subtitle
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlinx.cinterop.ExperimentalForeignApi
import platform.Foundation.NSString
import platform.Foundation.NSURL
import platform.Foundation.NSUTF8StringEncoding
import platform.Foundation.stringWithContentsOfFile
import platform.Foundation.stringWithContentsOfURL
/**
* iOS implementation of the loadSubtitleContent function.
* Loads subtitle content from a local file or a remote URL.
*
* @param src The source URI of the subtitle file
* @return The content of the subtitle file as a string
*/
@OptIn(ExperimentalForeignApi::class)
actual suspend fun loadSubtitleContent(src: String): String = withContext(Dispatchers.Default) {
try {
when {
// Handle HTTP/HTTPS URLs
src.startsWith("http://") || src.startsWith("https://") -> {
val nsUrl = NSURL(string = src)
nsUrl?.let {
try {
NSString.stringWithContentsOfURL(it, encoding = NSUTF8StringEncoding, error = null) ?: ""
} catch (e: Exception) {
println("Error loading URL: ${e.message}")
""
}
} ?: ""
}
// Handle file:// URIs
src.startsWith("file://") -> {
val nsUrl = NSURL(string = src)
nsUrl?.let {
try {
NSString.stringWithContentsOfURL(it, encoding = NSUTF8StringEncoding, error = null) ?: ""
} catch (e: Exception) {
println("Error loading file URL: ${e.message}")
""
}
} ?: ""
}
// Handle local file paths
else -> {
try {
NSString.stringWithContentsOfFile(src, encoding = NSUTF8StringEncoding, error = null) ?: ""
} catch (e: Exception) {
// Try as file URL
try {
val fileUrl = NSURL.fileURLWithPath(src)
fileUrl?.let {
NSString.stringWithContentsOfURL(it, encoding = NSUTF8StringEncoding, error = null) ?: ""
} ?: ""
} catch (e2: Exception) {
println("Error loading file path: ${e2.message}")
""
}
}
}
}
} catch (e: Exception) {
println("Error loading subtitle content: ${e.message}")
""
}
}
vendor/compose-mediaplayer/src/iosMain/kotlin/io/github/kdroidfilter/composemediaplayer/util/Uri.kt
- Source · implementation · 13 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
6: actual fun PlatformFile.getUri(): String {
Exact file bytes / download · SHA-256 d28f1b417a75bd49f5b5de6002b66c07d0c23d08911d025bdf367673278eaed0.
Complete file
package io.github.kdroidfilter.composemediaplayer.util
import io.github.vinceglb.filekit.PlatformFile
import io.github.vinceglb.filekit.path
actual fun PlatformFile.getUri(): String {
val filePath = this.path.toString()
return if (filePath.startsWith("file://")) {
filePath
} else {
"file://$filePath"
}
}
vendor/compose-mediaplayer/src/iosMain/kotlin/io/github/kdroidfilter/composemediaplayer/util/VideoPlayerStateRegistry.kt
- Source · implementation · 38 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
11: object VideoPlayerStateRegistry {
19: fun registerState(state: VideoPlayerState) {
28: fun getRegisteredState(): VideoPlayerState? {
35: fun clearRegisteredState() {
Exact file bytes / download · SHA-256 e87dafed20e777c23d021b7c2ebbdedf826c2e63614897b1b438e6f7ba0038e9.
Complete file
package io.github.kdroidfilter.composemediaplayer.util
import androidx.compose.runtime.Stable
import io.github.kdroidfilter.composemediaplayer.VideoPlayerState
/**
* Registry for sharing VideoPlayerState instances between views.
* This is used to pass the player state to the fullscreen view.
*/
@Stable
object VideoPlayerStateRegistry {
private var registeredState: VideoPlayerState? = null
/**
* Register a VideoPlayerState instance to be shared.
*
* @param state The VideoPlayerState to register
*/
fun registerState(state: VideoPlayerState) {
registeredState = state
}
/**
* Get the registered VideoPlayerState instance.
*
* @return The registered VideoPlayerState or null if none is registered
*/
fun getRegisteredState(): VideoPlayerState? {
return registeredState
}
/**
* Clear the registered VideoPlayerState instance.
*/
fun clearRegisteredState() {
registeredState = null
}
}
vendor/compose-mediaplayer/src/iosTest/kotlin/io/github/kdroidfilter/composemediaplayer/VideoPlayerStateTest.kt
- Source · test / fixture · 159 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
12: class VideoPlayerStateTest {
18: fun testCreateVideoPlayerState() {
42: fun testVolumeControl() {
67: fun testLoopSetting() {
88: fun testFullscreenToggle() {
110: fun testErrorHandling() {
127: fun testSubtitleFunctionality() {
Exact file bytes / download · SHA-256 5935681d83ca1eeee2c51980ef3a3fd131d4506199b97b693d9683c0a0402379.
Complete file
package io.github.kdroidfilter.composemediaplayer
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
import kotlin.test.assertFalse
/**
* Tests for the iOS implementation of VideoPlayerState
*/
class VideoPlayerStateTest {
/**
* Test the creation of VideoPlayerState
*/
@Test
fun testCreateVideoPlayerState() {
val playerState = VideoPlayerState()
// Verify the player state is initialized correctly
assertNotNull(playerState)
assertFalse(playerState.hasMedia)
assertFalse(playerState.isPlaying)
assertEquals(0f, playerState.sliderPos)
assertEquals(1f, playerState.volume)
assertFalse(playerState.loop)
assertEquals("00:00", playerState.positionText)
assertEquals("00:00", playerState.durationText)
assertEquals(0f, playerState.leftLevel)
assertEquals(0f, playerState.rightLevel)
assertFalse(playerState.isFullscreen)
// Clean up
playerState.dispose()
}
/**
* Test volume control
*/
@Test
fun testVolumeControl() {
val playerState = VideoPlayerState()
// Test initial volume
assertEquals(1f, playerState.volume)
// Test setting volume
playerState.volume = 0.5f
assertEquals(0.5f, playerState.volume)
// Test volume bounds
playerState.volume = -0.1f
assertEquals(0f, playerState.volume, "Volume should be clamped to 0")
playerState.volume = 1.5f
assertEquals(1f, playerState.volume, "Volume should be clamped to 1")
// Clean up
playerState.dispose()
}
/**
* Test loop setting
*/
@Test
fun testLoopSetting() {
val playerState = VideoPlayerState()
// Test initial loop setting
assertFalse(playerState.loop)
// Test setting loop
playerState.loop = true
assertTrue(playerState.loop)
playerState.loop = false
assertFalse(playerState.loop)
// Clean up
playerState.dispose()
}
/**
* Test fullscreen toggle
*/
@Test
fun testFullscreenToggle() {
val playerState = VideoPlayerState()
// Test initial fullscreen state
assertFalse(playerState.isFullscreen)
// Test toggling fullscreen
playerState.toggleFullscreen()
assertTrue(playerState.isFullscreen)
playerState.toggleFullscreen()
assertFalse(playerState.isFullscreen)
// Clean up
playerState.dispose()
}
/**
* Test error handling
* Note: Error handling in iOS implementation is minimal
*/
@Test
fun testErrorHandling() {
val playerState = VideoPlayerState()
// Test opening a non-existent file
playerState.openUri("non_existent_file.mp4")
// Test clearing the error
playerState.clearError()
// Clean up
playerState.dispose()
}
/**
* Test subtitle functionality
*/
@Test
fun testSubtitleFunctionality() {
val playerState = VideoPlayerState()
// Verify initial subtitle state
assertFalse(playerState.subtitlesEnabled)
assertEquals(null, playerState.currentSubtitleTrack)
assertTrue(playerState.availableSubtitleTracks.isEmpty())
// Create a test subtitle track
val testTrack = SubtitleTrack(
label = "English",
language = "en",
src = "test.vtt"
)
// Select the subtitle track
playerState.selectSubtitleTrack(testTrack)
// Verify subtitle state after selecting a track
assertTrue(playerState.subtitlesEnabled)
assertEquals(testTrack, playerState.currentSubtitleTrack)
// Disable subtitles
playerState.disableSubtitles()
// Verify subtitle state after disabling subtitles
assertFalse(playerState.subtitlesEnabled)
assertEquals(null, playerState.currentSubtitleTrack)
// Clean up
playerState.dispose()
}
}
vendor/compose-mediaplayer/src/jvmMain/kotlin/io/github/kdroidfilter/composemediaplayer/PlatformVideoPlayerState.kt
- Source · implementation · 69 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
32: interface PlatformVideoPlayerState {
57: fun selectSubtitleTrack(track: SubtitleTrack?)
58: fun disableSubtitles()
60: fun openUri(uri: String)
61: fun play()
62: fun pause()
63: fun stop()
64: fun seekTo(value: Float)
65: fun toggleFullscreen()
66: fun dispose()
67: suspend fun disposeAndJoin()
68: fun clearError()
Exact file bytes / download · SHA-256 658ae2ef7778c1f213b9877bf7e1ce56da279c55dc7ffe45523bade1af27c27f.
Complete file
package io.github.kdroidfilter.composemediaplayer
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.TextStyle
/**
* Defines a platform-specific video player state interface, providing the essential
* properties and operations needed for video playback management.
*
* The interface is intended to be implemented by platform-specific classes, acting as
* a layer to abstract the underlying behavior of video players across different operating systems.
*
* Properties:
* - `isPlaying`: Read-only property indicating whether the video is currently playing.
* - `volume`: Controls the playback volume, with values between 0.0 (mute) and 1.0 (full volume).
* - `sliderPos`: Represents the current playback position as a normalized value between 0.0 and 1.0.
* - `userDragging`: Tracks if the user is currently interacting with the playback position control.
* - `loop`: Specifies whether the video playback should loop continuously.
* - `leftLevel`: Read-only property giving the audio peak level of the left channel.
* - `rightLevel`: Read-only property giving the audio peak level of the right channel.
* - `positionText`: Provides a formatted text representation of the current playback position.
* - `durationText`: Provides a formatted text representation of the total duration of the video.
*
* Methods:
* - `openUri(uri: String)`: Opens a video resource (file or URL) for playback.
* - `play()`: Begins or resumes video playback.
* - `pause()`: Pauses the current video playback.
* - `stop()`: Stops playback and resets the playback position to the beginning.
* - `seekTo(value: Float)`: Seeks to a specific playback position based on the given normalized value.
* - `dispose()`: Releases resources and performs cleanup for the video player instance.
*/
interface PlatformVideoPlayerState {
val hasMedia : Boolean
val isPlaying: Boolean
var volume: Float
var sliderPos: Float
var userDragging: Boolean
var loop: Boolean
var playbackSpeed: Float
val leftLevel: Float
val rightLevel: Float
val positionText: String
val durationText: String
val isLoading: Boolean
val error: VideoPlayerError?
var isFullscreen: Boolean
val metadata: VideoMetadata
val aspectRatio: Float
// Subtitle management
var subtitlesEnabled: Boolean
var currentSubtitleTrack: SubtitleTrack?
val availableSubtitleTracks: MutableList<SubtitleTrack>
var subtitleTextStyle: TextStyle
var subtitleBackgroundColor: Color
fun selectSubtitleTrack(track: SubtitleTrack?)
fun disableSubtitles()
fun openUri(uri: String)
fun play()
fun pause()
fun stop()
fun seekTo(value: Float)
fun toggleFullscreen()
fun dispose()
suspend fun disposeAndJoin()
fun clearError()
}
vendor/compose-mediaplayer/src/jvmMain/kotlin/io/github/kdroidfilter/composemediaplayer/VideoPlayerState.jvm.kt
- Source · implementation · 122 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
42: actual open class VideoPlayerState {
103: actual fun selectSubtitleTrack(track: SubtitleTrack?) = delegate.selectSubtitleTrack(track)
104: actual fun disableSubtitles() = delegate.disableSubtitles()
111: actual open fun openUri(uri: String) = delegate.openUri(uri)
112: actual open fun openFile(file: PlatformFile) = delegate.openUri(file.file.path)
113: actual open fun play() = delegate.play()
114: actual open fun pause() = delegate.pause()
115: actual open fun stop() = delegate.stop()
116: actual open fun seekTo(value: Float) = delegate.seekTo(value)
117: actual open fun toggleFullscreen() = delegate.toggleFullscreen()
118: actual open fun dispose() = delegate.dispose()
119: actual open suspend fun disposeAndJoin() = delegate.disposeAndJoin()
120: actual open fun clearError() = delegate.clearError()
Exact file bytes / download · SHA-256 45a365234b6d932e4af59667da15ac93488b92d75973cc6e75e825b150651d3a.
Complete file
package io.github.kdroidfilter.composemediaplayer
import androidx.compose.runtime.Stable
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.TextStyle
import com.sun.jna.Platform
import io.github.kdroidfilter.composemediaplayer.linux.LinuxVideoPlayerState
import io.github.kdroidfilter.composemediaplayer.mac.MacVideoPlayerState
import io.github.kdroidfilter.composemediaplayer.windows.WindowsVideoPlayerState
import io.github.vinceglb.filekit.PlatformFile
/**
* Represents the state and behavior of a video player. This class provides properties
* and methods to control video playback, manage the playback state, and interact with
* platform-specific implementations.
*
* The actual implementation delegates its behavior to platform-specific video player
* states based on the detected operating system. Supported platforms include Windows,
* macOS, and Linux.
*
* Properties:
* - `isPlaying`: Indicates whether the video is currently playing.
* - `volume`: Controls the playback volume. Valid values are within the range of 0.0 (muted) to 1.0 (maximum volume).
* - `sliderPos`: Represents the current playback position as a normalized value between 0.0 and 1.0.
* - `userDragging`: Denotes whether the user is manually adjusting the playback position.
* - `loop`: Specifies if the video should loop when it reaches the end.
* - `leftLevel`: Provides the audio level for the left channel as a percentage.
* - `rightLevel`: Provides the audio level for the right channel as a percentage.
* - `positionText`: Returns the current playback position as a formatted string.
* - `durationText`: Returns the total duration of the video as a formatted string.
*
* Methods:
* - `openUri(uri: String)`: Opens a video file or URL for playback.
* - `play()`: Starts or resumes video playback.
* - `pause()`: Pauses video playback.
* - `stop()`: Stops playback and resets the player state.
* - `seekTo(value: Float)`: Seeks to a specific playback position based on the provided normalized value.
* - `dispose()`: Releases resources used by the video player and disposes of the state.
*/
@Stable
actual open class VideoPlayerState {
val delegate: PlatformVideoPlayerState = when {
Platform.isWindows() -> WindowsVideoPlayerState()
Platform.isMac() -> MacVideoPlayerState()
Platform.isLinux() -> LinuxVideoPlayerState()
else -> throw UnsupportedOperationException("Unsupported platform")
}
actual open val hasMedia: Boolean get() = delegate.hasMedia
actual open val isPlaying: Boolean get() = delegate.isPlaying
actual open val isLoading: Boolean get() = delegate.isLoading
actual open val error: VideoPlayerError? get() = delegate.error
actual open var volume: Float
get() = delegate.volume
set(value) {
delegate.volume = value
}
actual open var sliderPos: Float
get() = delegate.sliderPos
set(value) {
delegate.sliderPos = value
}
actual open var userDragging: Boolean
get() = delegate.userDragging
set(value) {
delegate.userDragging = value
}
actual open var loop: Boolean
get() = delegate.loop
set(value) {
delegate.loop = value
}
actual open var playbackSpeed: Float
get() = delegate.playbackSpeed
set(value) {
delegate.playbackSpeed = value
}
actual open var isFullscreen: Boolean
get() = delegate.isFullscreen
set(value) {
delegate.isFullscreen = value
}
actual open val metadata: VideoMetadata get() = delegate.metadata
actual open val aspectRatio: Float get() = delegate.aspectRatio
actual var subtitlesEnabled = delegate.subtitlesEnabled
actual var currentSubtitleTrack : SubtitleTrack? = delegate.currentSubtitleTrack
actual val availableSubtitleTracks = delegate.availableSubtitleTracks
actual var subtitleTextStyle: TextStyle
get() = delegate.subtitleTextStyle
set(value) {
delegate.subtitleTextStyle = value
}
actual var subtitleBackgroundColor: Color
get() = delegate.subtitleBackgroundColor
set(value) {
delegate.subtitleBackgroundColor = value
}
actual fun selectSubtitleTrack(track: SubtitleTrack?) = delegate.selectSubtitleTrack(track)
actual fun disableSubtitles() = delegate.disableSubtitles()
actual open val leftLevel: Float get() = delegate.leftLevel
actual open val rightLevel: Float get() = delegate.rightLevel
actual open val positionText: String get() = delegate.positionText
actual open val durationText: String get() = delegate.durationText
actual open fun openUri(uri: String) = delegate.openUri(uri)
actual open fun openFile(file: PlatformFile) = delegate.openUri(file.file.path)
actual open fun play() = delegate.play()
actual open fun pause() = delegate.pause()
actual open fun stop() = delegate.stop()
actual open fun seekTo(value: Float) = delegate.seekTo(value)
actual open fun toggleFullscreen() = delegate.toggleFullscreen()
actual open fun dispose() = delegate.dispose()
actual open suspend fun disposeAndJoin() = delegate.disposeAndJoin()
actual open fun clearError() = delegate.clearError()
}
vendor/compose-mediaplayer/src/jvmMain/kotlin/io/github/kdroidfilter/composemediaplayer/VideoPlayerSurface.kt
- Source · implementation · 41 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
29: actual fun VideoPlayerSurface(
Exact file bytes / download · SHA-256 528b48d7421db377d9dc33a7fb133228a4f2cdc2c79278e0b88de9a9eadba198.
Complete file
package io.github.kdroidfilter.composemediaplayer
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import io.github.kdroidfilter.composemediaplayer.linux.LinuxVideoPlayerState
import io.github.kdroidfilter.composemediaplayer.linux.LinuxVideoPlayerSurface
import io.github.kdroidfilter.composemediaplayer.mac.MacVideoPlayerState
import io.github.kdroidfilter.composemediaplayer.mac.MacVideoPlayerSurface
import io.github.kdroidfilter.composemediaplayer.windows.WindowsVideoPlayerState
import io.github.kdroidfilter.composemediaplayer.windows.WindowsVideoPlayerSurface
/**
* Composable function for rendering a video player surface.
*
* The function delegates the rendering logic to specific platform-specific implementations
* based on the type of the `delegate` within the provided `VideoPlayerState`.
*
* @param playerState The current state of the video player, encapsulating playback state
* and platform-specific implementation details.
* @param modifier A [Modifier] for styling or adjusting the layout of the video player surface.
* @param contentScale Controls how the video content should be scaled inside the surface.
* This affects how the video is displayed when its dimensions don't match
* the surface dimensions.
* @param overlay Optional composable content to be displayed on top of the video surface.
* This can be used to add custom controls, information, or any UI elements.
*/
@Composable
actual fun VideoPlayerSurface(
playerState: VideoPlayerState,
modifier: Modifier,
contentScale: ContentScale,
overlay: @Composable () -> Unit
) {
when (val delegate = playerState.delegate) {
is WindowsVideoPlayerState -> WindowsVideoPlayerSurface(delegate, modifier, contentScale, overlay)
is MacVideoPlayerState -> MacVideoPlayerSurface(delegate, modifier, contentScale, overlay)
is LinuxVideoPlayerState -> LinuxVideoPlayerSurface(delegate, modifier, contentScale, overlay)
else -> throw IllegalArgumentException("Unsupported player state type")
}
}
vendor/compose-mediaplayer/src/jvmMain/kotlin/io/github/kdroidfilter/composemediaplayer/common/FullscreenVideoPlayerWindow.kt
- Source · implementation · 89 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
28: fun openFullscreenWindow(
43: private fun FullscreenVideoPlayerWindow(
63: fun exitFullScreen() {
Exact file bytes / download · SHA-256 eb96ddcd16c8fb711b8cb8e5b7e578f653eff9f5fc61289192a390f8061951db.
Complete file
package io.github.kdroidfilter.composemediaplayer.common
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.key.Key
import androidx.compose.ui.input.key.KeyEventType
import androidx.compose.ui.input.key.key
import androidx.compose.ui.input.key.type
import androidx.compose.ui.window.Window
import androidx.compose.ui.window.WindowPlacement
import androidx.compose.ui.window.rememberWindowState
import com.sun.jna.Platform
import io.github.kdroidfilter.composemediaplayer.PlatformVideoPlayerState
import io.github.kdroidfilter.composemediaplayer.util.VideoPlayerStateRegistry
/**
* Opens a fullscreen window for the video player.
* This function is called when the user toggles fullscreen mode.
*
* @param playerState The player state to use in the fullscreen window
* @param renderSurface A composable function that renders the video player surface
*/
@Composable
fun openFullscreenWindow(
playerState: PlatformVideoPlayerState,
renderSurface: @Composable (PlatformVideoPlayerState, Modifier, Boolean) -> Unit
) {
// Register the player state to be accessible from the fullscreen window
VideoPlayerStateRegistry.registerState(playerState)
FullscreenVideoPlayerWindow(renderSurface)
}
/**
* A composable function that creates a fullscreen window for the video player.
*
* @param renderSurface A composable function that renders the video player surface
*/
@Composable
private fun FullscreenVideoPlayerWindow(
renderSurface: @Composable (PlatformVideoPlayerState, Modifier, Boolean) -> Unit
) {
// Get the player state from the registry
val playerState = remember {
VideoPlayerStateRegistry.getRegisteredState()
}
// Create a window state for fullscreen
val windowState = rememberWindowState(placement = WindowPlacement.Maximized)
var isVisible by mutableStateOf(true)
// Handle window close to exit fullscreen
DisposableEffect(Unit) {
onDispose {
playerState?.isFullscreen = false
}
}
fun exitFullScreen() {
isVisible = false
playerState?.isFullscreen = false
VideoPlayerStateRegistry.clearRegisteredState()
}
Window(
onCloseRequest = { exitFullScreen() },
visible = isVisible,
undecorated = true,
state = windowState,
title = "Fullscreen Player",
onKeyEvent = { keyEvent ->
if (keyEvent.key == Key.Escape && keyEvent.type == KeyEventType.KeyDown) {
exitFullScreen()
true
} else {
false
}
}) {
Box(modifier = Modifier.fillMaxSize().background(Color.Black)) {
playerState?.let { state ->
renderSurface(state, Modifier.fillMaxSize(), true)
}
}
}
}
vendor/compose-mediaplayer/src/jvmMain/kotlin/io/github/kdroidfilter/composemediaplayer/linux/GStreamerInit.kt
- Source · implementation · 94 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
24: object GStreamerInit {
34: fun setGStreamerPathWindows(path: String) {
43: fun setGStreamerPathMac(path: String) {
50: fun init() {
64: private fun configurePaths() {
Exact file bytes / download · SHA-256 03f26c98f127d1ee5846cf1e26aa2ef954dcb4bdb906923bd43cc81fa1111e98.
Complete file
package io.github.kdroidfilter.composemediaplayer.linux
import com.sun.jna.Platform
import com.sun.jna.platform.win32.Kernel32
import org.freedesktop.gstreamer.Gst
import org.freedesktop.gstreamer.Version
import java.io.File
/**
* GStreamerInit is a singleton object responsible for initializing the GStreamer library.
*
* This object ensures that the GStreamer library is initialized only once during the application's
* execution. The initialization process configures the library with the base version and a specific
* application name.
*
* It guarantees that GStreamer is properly prepared before any media-related operations,
* particularly with components such as media players.
*
* Features:
* - Tracks the initialization state to prevent duplicate initializations.
* - Configures GStreamer with a specified version and application identifier.
* - Allows the user to set custom paths to the GStreamer libraries for Windows and macOS.
*/
object GStreamerInit {
private var initialized = false
private var userGstPathWindows: String? = null
private var userGstPathMac: String? = null
/**
* Allows the user to set a custom path for GStreamer on Windows.
*
* @param path Path to the GStreamer bin directory.
*/
fun setGStreamerPathWindows(path: String) {
userGstPathWindows = path
}
/**
* Allows the user to set a custom path for GStreamer on macOS.
*
* @param path Path to the GStreamer Libraries directory.
*/
fun setGStreamerPathMac(path: String) {
userGstPathMac = path
}
/**
* Initializes GStreamer if it hasn't been initialized already.
*/
fun init() {
if (!initialized) {
configurePaths()
Gst.init(Version.BASELINE, "ComposeGStreamerPlayer")
initialized = true
}
}
/**
* Configures the paths to the GStreamer libraries.
* On Windows, uses the specified environment variables or default paths.
* On macOS, adds the path to jna.library.path or uses default values.
* On Linux, assumes that GStreamer is already in the PATH.
*/
private fun configurePaths() {
when {
Platform.isWindows() -> {
val gstPath = userGstPathWindows ?: System.getProperty("gstreamer.path", "C:\\gstreamer\\1.0\\msvc_x86_64\\bin")
if (gstPath.isNotEmpty()) {
val systemPath = System.getenv("PATH")
if (systemPath.isNullOrBlank()) {
Kernel32.INSTANCE.SetEnvironmentVariable("PATH", gstPath)
} else {
Kernel32.INSTANCE.SetEnvironmentVariable(
"PATH", "$gstPath${File.pathSeparator}$systemPath"
)
}
}
}
Platform.isMac() -> {
val gstPath = userGstPathMac ?: System.getProperty("gstreamer.path", "/Library/Frameworks/GStreamer.framework/Libraries/")
if (gstPath.isNotEmpty()) {
val jnaPath = System.getProperty("jna.library.path", "").trim()
if (jnaPath.isEmpty()) {
System.setProperty("jna.library.path", gstPath)
} else {
System.setProperty("jna.library.path", "$jnaPath${File.pathSeparator}$gstPath")
}
}
}
// For Linux, no action required if GStreamer is already in the PATH
}
}
}
vendor/compose-mediaplayer/src/jvmMain/kotlin/io/github/kdroidfilter/composemediaplayer/linux/LinuxFullscreenVideoPlayerWindow.kt
- Source · implementation · 33 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
16: fun openFullscreenWindow(
Exact file bytes / download · SHA-256 effb03145608fe78aea4dd999fa2853bccca98602e4f36f93b2aae1793d9286f.
Complete file
package io.github.kdroidfilter.composemediaplayer.linux
import androidx.compose.runtime.Composable
import androidx.compose.ui.layout.ContentScale
import io.github.kdroidfilter.composemediaplayer.common.openFullscreenWindow
/**
* Opens a fullscreen window for the video player.
* This function is called when the user toggles fullscreen mode.
*
* @param playerState The player state to use in the fullscreen window
* @param overlay Optional composable content to be displayed on top of the video surface.
* This can be used to add custom controls, information, or any UI elements.
*/
@Composable
fun openFullscreenWindow(
playerState: LinuxVideoPlayerState,
overlay: @Composable () -> Unit = {},
contentScale: ContentScale
) {
openFullscreenWindow(
playerState = playerState,
renderSurface = { state, modifier, isInFullscreenWindow ->
LinuxVideoPlayerSurface(
playerState = state as LinuxVideoPlayerState,
modifier = modifier,
overlay = overlay,
isInFullscreenWindow = isInFullscreenWindow,
contentScale = contentScale
)
}
)
}
vendor/compose-mediaplayer/src/jvmMain/kotlin/io/github/kdroidfilter/composemediaplayer/linux/LinuxVideoPlayerState.kt
- Source · implementation · 894 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
48: class LinuxVideoPlayerState : PlatformVideoPlayerState {
145: private fun applyPlaybackSpeed() {
252: private fun publish(action: () -> Unit) {
537: override fun selectSubtitleTrack(track: SubtitleTrack?) {
556: override fun disableSubtitles() {
576: private fun updateAspectRatio() {
608: private fun updateLoadingState() {
622: private fun updateVideoMetadata() {
710: override fun openUri(uri: String) {
748: override fun play() {
766: override fun pause() {
778: override fun stop() {
792: override fun seekTo(value: Float) {
815: override fun clearError() {
822: override fun toggleFullscreen() {
833: private fun processSample(sample: Sample) {
892: override fun dispose() = disposal.dispose()
893: override suspend fun disposeAndJoin() = disposal.disposeAndJoin()
Exact file bytes / download · SHA-256 efda89f00efbb51d607c033ba34d399a954594ee6309c480ee432ec692423360.
Complete file
package io.github.kdroidfilter.composemediaplayer.linux
import androidx.compose.runtime.Stable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.asComposeImageBitmap
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.sp
import io.github.kdroidfilter.composemediaplayer.PlatformVideoPlayerState
import io.github.kdroidfilter.composemediaplayer.SubtitleTrack
import io.github.kdroidfilter.composemediaplayer.VideoMetadata
import io.github.kdroidfilter.composemediaplayer.VideoPlayerError
import io.github.kdroidfilter.composemediaplayer.util.DEFAULT_ASPECT_RATIO
import io.github.kdroidfilter.composemediaplayer.util.formatTime
import org.freedesktop.gstreamer.*
import org.freedesktop.gstreamer.elements.AppSink
import org.freedesktop.gstreamer.elements.PlayBin
import org.freedesktop.gstreamer.Format
import org.freedesktop.gstreamer.event.SeekFlags
import org.freedesktop.gstreamer.event.SeekType
import org.freedesktop.gstreamer.message.MessageType
import org.jetbrains.skia.Bitmap
import org.jetbrains.skia.ColorAlphaType
import org.jetbrains.skia.ColorType
import org.jetbrains.skia.ImageInfo
import kotlinx.coroutines.*
import java.io.File
import java.net.URI
import java.util.EnumSet
import javax.swing.Timer
import kotlin.math.abs
import kotlin.math.pow
/**
* LinuxVideoPlayerState serves as the Linux-specific implementation for
* a video player using GStreamer.
*
* To dynamically change the subtitle source, the pipeline is set to READY,
* the source is updated, and then the pipeline is set back to PLAYING.
* A Timer performs a slight seek to reposition exactly at the saved position.
*/
@Stable
class LinuxVideoPlayerState : PlatformVideoPlayerState {
companion object {
// Flag to enable text subtitles (GST_PLAY_FLAG_TEXT)
const val GST_PLAY_FLAG_TEXT = 1 shl 2
}
init {
GStreamerInit.init()
}
// Use instance-specific unique identifiers for GStreamer elements
private val instanceId = System.nanoTime().toString()
private val playbin = PlayBin("playbin-$instanceId")
private val videoSink = ElementFactory.make("appsink", "videosink-$instanceId") as AppSink
private val sliderTimer = Timer(50, null)
private val uiScope = CoroutineScope(SupervisorJob() + Dispatchers.Main)
// ---- Internal states ----
private var _currentFrame by mutableStateOf<ImageBitmap?>(null)
val currentFrame: ImageBitmap?
get() = _currentFrame
private var frameWidth = 0
private var frameHeight = 0
private var bufferingPercent by mutableStateOf(100)
private var isUserPaused by mutableStateOf(false)
private var hasReceivedFirstFrame by mutableStateOf(false)
private var _sliderPos by mutableStateOf(0f)
override var sliderPos: Float
get() = _sliderPos
set(value) {
_sliderPos = value
}
// This variable will allow us to handle a potential delay before buffering is signaled
private var _isSeeking by mutableStateOf(false)
private var targetSeekPos: Float = 0f
private var _userDragging by mutableStateOf(false)
override var userDragging: Boolean
get() = _userDragging
set(value) {
_userDragging = value
// If user just finished dragging and we have a pending playback speed update, apply it now
if (!value && pendingPlaybackSpeedUpdate) {
applyPlaybackSpeed()
}
}
private var _loop by mutableStateOf(false)
override var loop: Boolean
get() = _loop
set(value) {
_loop = value
}
private var _playbackSpeed by mutableStateOf(1f)
private var pendingPlaybackSpeedUpdate = false
private var speedUpdateTimer: Timer? = null
private val PLAYBACK_SPEED_DEBOUNCE_MS = 200
override var playbackSpeed: Float
get() = _playbackSpeed
set(value) {
val newSpeed = value.coerceIn(0.5f, 2.0f)
// Update the UI immediately
_playbackSpeed = newSpeed
if (hasMedia) {
// If we're dragging, defer the actual seek operation
if (userDragging) {
pendingPlaybackSpeedUpdate = true
return
}
// Cancel any pending timer
speedUpdateTimer?.stop()
// Apply the speed change immediately for UI feedback
// but debounce the actual GStreamer operation
pendingPlaybackSpeedUpdate = true
// Create a new timer for debouncing
speedUpdateTimer = Timer(PLAYBACK_SPEED_DEBOUNCE_MS, {
if (pendingPlaybackSpeedUpdate) {
applyPlaybackSpeed()
}
})
speedUpdateTimer?.isRepeats = false
speedUpdateTimer?.start()
}
}
private fun applyPlaybackSpeed() {
pendingPlaybackSpeedUpdate = false
try {
// Get current position
val currentPosition = playbin.queryPosition(Format.TIME)
// Perform a seek operation with the new playback speed
// This is the proper way to change playback speed in GStreamer
playbin.seek(
_playbackSpeed.toDouble(), // Rate (speed multiplier)
Format.TIME, // Format
EnumSet.of(SeekFlags.FLUSH, SeekFlags.ACCURATE), // Flags
SeekType.SET, // Start seek type
currentPosition, // Start position
SeekType.NONE, // Stop seek type
-1L // Stop position (not used)
)
} catch (e: Exception) {
e.printStackTrace()
// Don't revert the speed value as it would cause UI inconsistency
}
}
private var _volume by mutableStateOf(1f)
override var volume: Float
get() = _volume
set(value) {
_volume = value.coerceIn(0f..1f)
playbin.set("volume", _volume.toDouble())
}
private var _leftLevel by mutableStateOf(0f)
override val leftLevel: Float
get() = _leftLevel
private var _rightLevel by mutableStateOf(0f)
override val rightLevel: Float
get() = _rightLevel
private var _positionText by mutableStateOf("00:00")
override val positionText: String
get() = _positionText
private var _durationText by mutableStateOf("00:00")
override val durationText: String
get() = _durationText
private var _isLoading by mutableStateOf(false)
override val isLoading: Boolean
get() = _isLoading
private var _hasMedia by mutableStateOf(false)
override val hasMedia: Boolean
get() = _hasMedia
private var _isPlaying by mutableStateOf(false)
override val isPlaying: Boolean
get() = _isPlaying
private var _error by mutableStateOf<VideoPlayerError?>(null)
override val error: VideoPlayerError?
get() = _error
private var _isFullscreen by mutableStateOf(false)
override var isFullscreen: Boolean
get() = _isFullscreen
set(value) {
_isFullscreen = value
}
override val metadata: VideoMetadata = VideoMetadata()
override var subtitlesEnabled: Boolean = false
override var currentSubtitleTrack: SubtitleTrack? = null
override val availableSubtitleTracks = mutableListOf<SubtitleTrack>()
override var subtitleTextStyle: TextStyle = TextStyle(
color = Color.White,
fontSize = 18.sp,
fontWeight = FontWeight.Normal,
textAlign = TextAlign.Center
)
override var subtitleBackgroundColor: Color = Color.Black.copy(alpha = 0.5f)
// ---- Aspect ratio management ----
private var lastAspectRatioUpdateTime: Long = 0
private val ASPECT_RATIO_DEBOUNCE_MS = 500
private var _aspectRatio by mutableStateOf(DEFAULT_ASPECT_RATIO)
override val aspectRatio: Float
get() = _aspectRatio
private val disposal = io.github.kdroidfilter.composemediaplayer.AwaitedPlayerDisposal(
dispatcher = Dispatchers.Main,
retire = { uiScope.cancel(); sliderTimer.stop(); speedUpdateTimer?.stop() },
release = {
uiScope.coroutineContext[Job]?.join()
sliderTimer.stop()
speedUpdateTimer?.stop()
// NULL stops GStreamer streaming threads before the elements are disposed.
playbin.stop()
playbin.dispose()
videoSink.dispose()
_currentFrame = null
// Gst.deinit() would affect other instances.
},
)
private fun publish(action: () -> Unit) {
if (disposal.isRequested) return
uiScope.launch { if (!disposal.isRequested) action() }
}
init {
// GStreamer configuration
val audiobin = Bin("audiobin-$instanceId")
// Create a scaletempo element for pitch-corrected playback speed
val scaletempo = ElementFactory.make("scaletempo", "scaletempo-$instanceId")
// Create the level element for volume monitoring
val levelElement = ElementFactory.make("level", "level-$instanceId")
// Add elements to audiobin
audiobin.addMany(scaletempo, levelElement)
// Link elements in sequence: scaletempo -> level
Element.linkMany(scaletempo, levelElement)
// Create sink and source ghost pads for the bin
val sinkPad = scaletempo.getStaticPad("sink")
val srcPad = levelElement.getStaticPad("src")
audiobin.addPad(GhostPad("sink", sinkPad))
audiobin.addPad(GhostPad("src", srcPad))
// Set the audiobin as the audio filter for playbin
playbin.set("audio-filter", audiobin)
// Configuration of the AppSink for video
// Requesting RGBA (R, G, B, A) without additional conversion.
val caps = Caps.fromString("video/x-raw,format=RGBA")
videoSink.caps = caps
videoSink.set("emit-signals", true)
videoSink.connect(AppSink.NEW_SAMPLE { appSink ->
val sample = appSink.pullSample()
if (sample != null) {
processSample(sample)
sample.dispose()
}
FlowReturn.OK
})
playbin.setVideoSink(videoSink)
// ---- GStreamer bus handling ----
// End of stream
playbin.bus.connect(Bus.EOS {
publish {
if (loop) {
// Restart from beginning if loop = true
playbin.seekSimple(Format.TIME, EnumSet.of(SeekFlags.FLUSH), 0)
} else {
stop()
}
_isPlaying = loop
}
})
// Errors
playbin.bus.connect(Bus.ERROR { source, code, message ->
publish {
_error = when {
message.contains("codec", ignoreCase = true) ||
message.contains("decode", ignoreCase = true) ->
VideoPlayerError.CodecError(message)
message.contains("network", ignoreCase = true) ||
message.contains("connection", ignoreCase = true) ||
message.contains("dns", ignoreCase = true) ||
message.contains("http", ignoreCase = true) ->
VideoPlayerError.NetworkError(message)
message.contains("source", ignoreCase = true) ||
message.contains("uri", ignoreCase = true) ||
message.contains("resource", ignoreCase = true) ->
VideoPlayerError.SourceError(message)
else ->
VideoPlayerError.UnknownError(message)
}
stop()
}
})
// Buffering
playbin.bus.connect(Bus.BUFFERING { source, percent ->
publish {
bufferingPercent = percent
// When reaching 100%, we consider that any seek has finished
if (percent == 100) {
_isSeeking = false
}
updateLoadingState()
}
})
// Pipeline state change
playbin.bus.connect { source, old, current, pending ->
publish {
when (current) {
State.PLAYING -> {
_isPlaying = true
isUserPaused = false
updateLoadingState()
updateAspectRatio()
}
State.PAUSED -> {
_isPlaying = false
updateLoadingState()
}
State.READY -> {
_isPlaying = false
updateLoadingState()
}
else -> {
_isPlaying = false
updateLoadingState()
}
}
}
}
// TAG (metadata)
playbin.bus.connect(Bus.TAG { source, tagList ->
if (tagList != null) {
publish {
try {
// Extract metadata from TagList
try {
// Try to extract title
val title = tagList.getString("title", 0)
if (title != null) {
metadata.title = title
}
} catch (_: Exception) {
// Ignore errors when getting title
}
try {
// Try to extract video bitrate first
val videoBitrate = tagList.getString("video-bitrate", 0)
if (videoBitrate != null) {
try {
// The bitrate is already in bps, no need to convert
metadata.bitrate = videoBitrate.toLong()
} catch (_: NumberFormatException) {
// Ignore if the string can't be converted to a long
}
} else {
// Fallback to generic bitrate if video-specific one is not available
val bitrate = tagList.getString("bitrate", 0)
if (bitrate != null) {
try {
// The bitrate is already in bps, no need to convert
metadata.bitrate = bitrate.toLong()
} catch (_: NumberFormatException) {
// Ignore if the string can't be converted to a long
}
}
}
} catch (_: Exception) {
// Ignore errors when getting bitrate
}
try {
// Try to extract MIME type from container format
val containerFormat = tagList.getString("container-format", 0)
if (containerFormat != null) {
metadata.mimeType = containerFormat
} else {
// Try audio codec as fallback
val audioCodec = tagList.getString("audio-codec", 0)
if (audioCodec != null) {
metadata.mimeType = audioCodec
} else {
// Try video codec as fallback
val videoCodec = tagList.getString("video-codec", 0)
if (videoCodec != null) {
metadata.mimeType = videoCodec
}
}
}
} catch (_: Exception) {
// Ignore errors when getting MIME type
}
try {
// Try to extract audio channels
val audioChannels = tagList.getString("audio-channels", 0)
if (audioChannels != null) {
try {
metadata.audioChannels = audioChannels.toInt()
} catch (_: NumberFormatException) {
// Ignore if the string can't be converted to an integer
}
}
} catch (_: Exception) {
// Ignore errors when getting audio channels
}
// We'll also update metadata from the pipeline
updateVideoMetadata()
} catch (e: Exception) {
e.printStackTrace()
}
}
}
})
// Measuring audio level (via the "level" element)
playbin.bus.connect("element") { _, message ->
if (message.source == levelElement) {
val struct = message.structure
if (struct != null && struct.hasField("peak")) {
val peaks = struct.getDoubles("peak")
if (peaks.isNotEmpty() && isPlaying) {
for (i in peaks.indices) {
peaks[i] = 10.0.pow(peaks[i] / 20.0)
}
val l = if (peaks.isNotEmpty()) peaks[0] else 0.0
val r = if (peaks.size > 1) peaks[1] else l
publish {
_leftLevel = (l.coerceIn(0.0, 1.0) * 100f).toFloat()
_rightLevel = (r.coerceIn(0.0, 1.0) * 100f).toFloat()
}
} else {
publish {
_leftLevel = 0f
_rightLevel = 0f
}
}
}
}
}
// Also monitoring the end of async transitions (e.g., after a seek)
playbin.bus.connect("async-done") { _, message ->
if (message.type == MessageType.ASYNC_DONE) {
publish {
_isSeeking = false
updateLoadingState()
// Update metadata after async operations (like seeking) complete
updateVideoMetadata()
}
}
}
// Timer for the slider position and duration
sliderTimer.addActionListener {
if (!disposal.isRequested && !userDragging) {
val dur = playbin.queryDuration(Format.TIME)
val pos = playbin.queryPosition(Format.TIME)
if (dur > 0) {
val relPos = pos.toDouble() / dur.toDouble()
val currentSliderPos = (relPos * 1000.0).toFloat()
if (targetSeekPos > 0f) {
if (abs(targetSeekPos - currentSliderPos) < 1f) {
_sliderPos = currentSliderPos
targetSeekPos = 0f
}
} else {
_sliderPos = currentSliderPos
}
if (pos > 0) {
publish {
_positionText = formatTime(pos, true)
_durationText = formatTime(dur, true)
}
}
}
}
}
sliderTimer.start()
}
// ---- Subtitle management ----
override fun selectSubtitleTrack(track: SubtitleTrack?) {
currentSubtitleTrack = track
subtitlesEnabled = track != null
// We're not using GStreamer's native subtitle rendering anymore
// Instead, we're using Compose-based subtitles
// So we don't need to set the suburi or enable the GST_PLAY_FLAG_TEXT flag
// Just for backward compatibility, we'll disable any existing subtitles in GStreamer
try {
// Disable native subtitles in GStreamer
playbin.set("suburi", "")
val currentFlags = playbin.get("flags") as Int
playbin.set("flags", currentFlags and GST_PLAY_FLAG_TEXT.inv())
} catch (_: Exception) {
// Ignore errors, as we're not using GStreamer's subtitle rendering anyway
}
}
override fun disableSubtitles() {
currentSubtitleTrack = null
subtitlesEnabled = false
// We're not using GStreamer's native subtitle rendering anymore
// Instead, we're using Compose-based subtitles
// So we don't need to disable the GST_PLAY_FLAG_TEXT flag
// Just for backward compatibility, we'll disable any existing subtitles in GStreamer
try {
// Disable native subtitles in GStreamer
playbin.set("suburi", "")
val currentFlags = playbin.get("flags") as Int
playbin.set("flags", currentFlags and GST_PLAY_FLAG_TEXT.inv())
} catch (_: Exception) {
// Ignore errors, as we're not using GStreamer's subtitle rendering anyway
}
}
// ---- Aspect ratio management ----
private fun updateAspectRatio() {
val currentTime = System.currentTimeMillis()
if (currentTime - lastAspectRatioUpdateTime < ASPECT_RATIO_DEBOUNCE_MS) {
return
}
lastAspectRatioUpdateTime = currentTime
try {
val videoSinkElement = playbin.get("video-sink") as? Element
val sinkPad = videoSinkElement?.getStaticPad("sink")
val caps = sinkPad?.currentCaps
val structure = caps?.getStructure(0)
if (structure != null) {
val width = structure.getInteger("width")
val height = structure.getInteger("height")
if (width > 0 && height > 0) {
val calculatedRatio = width.toFloat() / height.toFloat()
if (calculatedRatio != _aspectRatio) {
publish {
_aspectRatio = if (calculatedRatio > 0) calculatedRatio else 16f / 9f
}
}
}
}
} catch (e: Exception) {
e.printStackTrace()
_aspectRatio = 16f / 9f
}
}
private fun updateLoadingState() {
_isLoading = when {
bufferingPercent < 100 -> true
_isSeeking -> true
isUserPaused -> false
_hasMedia && !hasReceivedFirstFrame -> true
else -> false
}
}
/**
* Updates the video metadata from the pipeline.
* This extracts information like width, height, duration, and frame rate.
*/
private fun updateVideoMetadata() {
try {
// Get duration
val duration = playbin.queryDuration(Format.TIME)
if (duration > 0) {
metadata.duration = duration
}
// Get width and height from video sink
val videoSinkElement = playbin.get("video-sink") as? Element
val sinkPad = videoSinkElement?.getStaticPad("sink")
val caps = sinkPad?.currentCaps
val structure = caps?.getStructure(0)
if (structure != null) {
try {
val width = structure.getInteger("width")
val height = structure.getInteger("height")
if (width > 0 && height > 0) {
metadata.width = width
metadata.height = height
}
// Try to get frame rate if available
if (structure.hasField("framerate")) {
val fraction = structure.getFraction("framerate")
if (fraction != null && fraction.denominator > 0) {
val frameRate = fraction.numerator.toFloat() / fraction.denominator.toFloat()
metadata.frameRate = frameRate
}
}
} catch (_: Exception) {
// Ignore errors when getting specific fields
}
}
// Get audio channels and sample rate if available
// On Linux, we need to use a different approach to get audio metadata
try {
// Try to get audio information from the audio-filter element (level)
val levelElement = playbin.get("audio-filter") as? Element
if (levelElement != null) {
val sinkPad = levelElement.getStaticPad("sink")
val audioCaps = sinkPad?.currentCaps
val audioStructure = audioCaps?.getStructure(0)
if (audioStructure != null) {
if (audioStructure.hasField("channels")) {
val channels = audioStructure.getInteger("channels")
metadata.audioChannels = channels
}
if (audioStructure.hasField("rate")) {
val rate = audioStructure.getInteger("rate")
metadata.audioSampleRate = rate
}
}
}
// If we couldn't get the info from audio-filter, try the traditional approach
if (metadata.audioChannels == null || metadata.audioSampleRate == null) {
val audioSinkPad = playbin.getStaticPad("audio_sink")
val audioCaps = audioSinkPad?.currentCaps
val audioStructure = audioCaps?.getStructure(0)
if (audioStructure != null) {
if (audioStructure.hasField("channels") && metadata.audioChannels == null) {
val channels = audioStructure.getInteger("channels")
metadata.audioChannels = channels
}
if (audioStructure.hasField("rate") && metadata.audioSampleRate == null) {
val rate = audioStructure.getInteger("rate")
metadata.audioSampleRate = rate
}
}
}
} catch (e: Exception) {
// Ignore errors when getting specific fields
e.printStackTrace()
}
} catch (_: Exception) {
// Ignore general errors
}
}
// ---- Controls ----
override fun openUri(uri: String) {
if (disposal.isRequested) return
stop()
clearError()
_isLoading = true
_hasMedia = false
hasReceivedFirstFrame = false
playbackSpeed = 1.0f
try {
val uriObj = if (uri.startsWith("http://") || uri.startsWith("https://")) {
URI(uri)
} else {
File(uri).toURI()
}
playbin.setURI(uriObj)
_hasMedia = true
// Reset metadata for the new media
metadata.title = null
metadata.duration = null
metadata.width = null
metadata.height = null
metadata.bitrate = null
metadata.frameRate = null
metadata.mimeType = null
metadata.audioChannels = null
metadata.audioSampleRate = null
play()
} catch (e: Exception) {
_error = VideoPlayerError.SourceError("Unable to open URI: ${e.message}")
_isLoading = false
_isPlaying = false
_hasMedia = false
e.printStackTrace()
}
}
override fun play() {
if (disposal.isRequested) return
try {
playbin.play()
playbin.set("volume", volume.toDouble())
_hasMedia = true
_isPlaying = true
isUserPaused = false
updateLoadingState()
// Update metadata when starting playback
updateVideoMetadata()
} catch (e: Exception) {
_error = VideoPlayerError.UnknownError("Playback failed: ${e.message}")
_isPlaying = false
}
}
override fun pause() {
if (disposal.isRequested) return
try {
playbin.pause()
_isPlaying = false
isUserPaused = true
updateLoadingState()
} catch (e: Exception) {
_error = VideoPlayerError.UnknownError("Pause failed: ${e.message}")
}
}
override fun stop() {
if (disposal.isRequested) return
playbin.stop()
_isPlaying = false
_sliderPos = 0f
_positionText = "0:00"
_isLoading = false
isUserPaused = false
bufferingPercent = 100
_hasMedia = false
_isSeeking = false
hasReceivedFirstFrame = false
}
override fun seekTo(value: Float) {
if (disposal.isRequested) return
val dur = playbin.queryDuration(Format.TIME)
if (dur > 0) {
// Force the loading and seeking indicator before the operation
_isSeeking = true
_isLoading = true
_sliderPos = value
targetSeekPos = value
val relPos = value / 1000f
val seekPos = (relPos * dur).toLong()
_positionText = formatTime(seekPos, true)
playbin.seekSimple(Format.TIME, EnumSet.of(SeekFlags.FLUSH, SeekFlags.ACCURATE), seekPos)
publish {
_positionText = formatTime(seekPos, true)
}
}
}
override fun clearError() {
_error = null
}
/**
* Toggles the fullscreen state of the video player
*/
override fun toggleFullscreen() {
_isFullscreen = !_isFullscreen
}
// ---- Processing of a video sample ----
/**
* Directly reads in RGBA and copies to a Skia Bitmap in the RGBA_8888 format
* (non-premultiplied). This avoids redundant conversions to maintain accurate colors and performance.
*
* Optimized for better performance, especially in fullscreen mode.
*/
private fun processSample(sample: Sample) {
try {
val caps = sample.caps ?: return
val structure = caps.getStructure(0) ?: return
val width = structure.getInteger("width")
val height = structure.getInteger("height")
if (width != frameWidth || height != frameHeight) {
frameWidth = width
frameHeight = height
updateAspectRatio()
}
val buffer = sample.buffer ?: return
val byteBuffer = buffer.map(false) ?: return
byteBuffer.rewind()
// Prepare a Skia Bitmap
val imageInfo = ImageInfo(
width,
height,
ColorType.RGBA_8888,
ColorAlphaType.UNPREMUL
)
val bitmap = Bitmap()
bitmap.allocPixels(imageInfo)
// Get the byte array from the buffer directly
val totalBytes = width * height * 4
val byteArray = ByteArray(totalBytes)
// Bulk copy the bytes from the buffer to the array
// This is much more efficient than copying pixel by pixel
byteBuffer.get(byteArray, 0, totalBytes)
// Install these pixels into the Bitmap
bitmap.installPixels(imageInfo, byteArray, width * 4)
// Convert the Skia Bitmap into a Compose ImageBitmap
val imageBitmap = bitmap.asComposeImageBitmap()
// Update on the AWT thread
publish {
_currentFrame = imageBitmap
if (!hasReceivedFirstFrame) {
hasReceivedFirstFrame = true
updateLoadingState()
}
}
buffer.unmap()
} catch (e: Exception) {
e.printStackTrace()
}
}
override fun dispose() = disposal.dispose()
override suspend fun disposeAndJoin() = disposal.disposeAndJoin()
}
vendor/compose-mediaplayer/src/jvmMain/kotlin/io/github/kdroidfilter/composemediaplayer/linux/LinuxVideoPlayerSurface.jvm.kt
- Source · implementation · 93 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
36: fun LinuxVideoPlayerSurface(
Exact file bytes / download · SHA-256 f3ea3bf9dd9404c1eb8a280bfca3e352e18a217abe10072231f62dc00e64aa7e.
Complete file
package io.github.kdroidfilter.composemediaplayer.linux
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.Box
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.unit.IntSize
import io.github.kdroidfilter.composemediaplayer.subtitle.ComposeSubtitleLayer
import io.github.kdroidfilter.composemediaplayer.util.drawScaledImage
import io.github.kdroidfilter.composemediaplayer.util.toCanvasModifier
import io.github.kdroidfilter.composemediaplayer.util.toTimeMs
/**
* A composable function that renders a video player surface using GStreamer with offscreen rendering.
*
* This function creates a video rendering area using a Compose Canvas to draw video frames
* that are rendered offscreen by GStreamer. This approach avoids the rendering issues
* that can occur when using SwingPanel, especially with overlapping UI elements.
*
* @param playerState The state object that encapsulates the GStreamer player logic,
* including playback control, timeline management, and video frames.
* @param modifier An optional `Modifier` for customizing the layout and appearance of the
* composable container. Defaults to an empty `Modifier`.
* @param contentScale Controls how the video content should be scaled inside the surface.
* This affects how the video is displayed when its dimensions don't match
* the surface dimensions.
* @param overlay Optional composable content to be displayed on top of the video surface.
* This can be used to add custom controls, information, or any UI elements.
* @param isInFullscreenWindow Whether this surface is already being displayed in a fullscreen window.
*/
@Composable
fun LinuxVideoPlayerSurface(
playerState: LinuxVideoPlayerState,
modifier: Modifier = Modifier,
contentScale: ContentScale = ContentScale.Fit,
overlay: @Composable () -> Unit = {},
isInFullscreenWindow: Boolean = false
) {
Box(
modifier = modifier,
contentAlignment = Alignment.Center
) {
// Only render video in this surface if we're not in fullscreen mode or if this is the fullscreen window
if (playerState.hasMedia && (!playerState.isFullscreen || isInFullscreenWindow)) {
Canvas(
modifier = contentScale.toCanvasModifier(
aspectRatio = playerState.aspectRatio,
width = playerState.metadata.width,
height = playerState.metadata.height
)
) {
playerState.currentFrame?.let { frame ->
drawScaledImage(
image = frame,
dstSize = IntSize(size.width.toInt(), size.height.toInt()),
contentScale = contentScale
)
}
}
// Add Compose-based subtitle layer
// Always render the subtitle layer, but let it handle visibility internally
// This ensures it's properly recomposed when subtitles are enabled during playback
val currentTimeMs = (playerState.sliderPos / 1000f *
playerState.durationText.toTimeMs()).toLong()
// Calculate duration in milliseconds
val durationMs = playerState.durationText.toTimeMs()
ComposeSubtitleLayer(
currentTimeMs = currentTimeMs,
durationMs = durationMs,
isPlaying = playerState.isPlaying,
subtitleTrack = playerState.currentSubtitleTrack,
subtitlesEnabled = playerState.subtitlesEnabled,
textStyle = playerState.subtitleTextStyle,
backgroundColor = playerState.subtitleBackgroundColor
)
}
// Render the overlay content on top of the video
overlay()
}
if (playerState.isFullscreen && !isInFullscreenWindow) {
openFullscreenWindow(playerState, overlay = overlay, contentScale)
}
}
vendor/compose-mediaplayer/src/jvmMain/kotlin/io/github/kdroidfilter/composemediaplayer/mac/AvPlayerLib.kt
- Source · implementation · 44 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
11: internal interface SharedVideoPlayer : Library {
12: fun createVideoPlayer(): Pointer?
13: fun openUri(context: Pointer?, uri: String?)
14: fun playVideo(context: Pointer?)
15: fun pauseVideo(context: Pointer?)
16: fun setVolume(context: Pointer?, volume: Float)
17: fun getVolume(context: Pointer?): Float
18: fun getLatestFrame(context: Pointer?): Pointer?
19: fun getFrameWidth(context: Pointer?): Int
20: fun getFrameHeight(context: Pointer?): Int
21: fun getVideoFrameRate(context: Pointer?): Float
22: fun getScreenRefreshRate(context: Pointer?): Float
23: fun getCaptureFrameRate(context: Pointer?): Float
24: fun getVideoDuration(context: Pointer?): Double
25: fun getCurrentTime(context: Pointer?): Double
26: fun seekTo(context: Pointer?, time: Double)
27: fun disposeVideoPlayer(context: Pointer?)
28: fun getLeftAudioLevel(context: Pointer?): Float
29: fun getRightAudioLevel(context: Pointer?): Float
30: fun setPlaybackSpeed(context: Pointer?, speed: Float)
31: fun getPlaybackSpeed(context: Pointer?): Float
34: fun getVideoTitle(context: Pointer?): String?
35: fun getVideoBitrate(context: Pointer?): Long
36: fun getVideoMimeType(context: Pointer?): String?
37: fun getAudioChannels(context: Pointer?): Int
38: fun getAudioSampleRate(context: Pointer?): Int
Exact file bytes / download · SHA-256 7a9e1e4bbcdae1581d26d9db2bdce99540bb39c9761cdb39ece69d8237b0dfdd.
Complete file
package io.github.kdroidfilter.composemediaplayer.mac
import com.sun.jna.Library
import com.sun.jna.Native
import com.sun.jna.Pointer
/**
* JNA interface to the native library.
* Includes new methods to retrieve frame rate information.
*/
internal interface SharedVideoPlayer : Library {
fun createVideoPlayer(): Pointer?
fun openUri(context: Pointer?, uri: String?)
fun playVideo(context: Pointer?)
fun pauseVideo(context: Pointer?)
fun setVolume(context: Pointer?, volume: Float)
fun getVolume(context: Pointer?): Float
fun getLatestFrame(context: Pointer?): Pointer?
fun getFrameWidth(context: Pointer?): Int
fun getFrameHeight(context: Pointer?): Int
fun getVideoFrameRate(context: Pointer?): Float
fun getScreenRefreshRate(context: Pointer?): Float
fun getCaptureFrameRate(context: Pointer?): Float
fun getVideoDuration(context: Pointer?): Double
fun getCurrentTime(context: Pointer?): Double
fun seekTo(context: Pointer?, time: Double)
fun disposeVideoPlayer(context: Pointer?)
fun getLeftAudioLevel(context: Pointer?): Float
fun getRightAudioLevel(context: Pointer?): Float
fun setPlaybackSpeed(context: Pointer?, speed: Float)
fun getPlaybackSpeed(context: Pointer?): Float
// Metadata retrieval functions
fun getVideoTitle(context: Pointer?): String?
fun getVideoBitrate(context: Pointer?): Long
fun getVideoMimeType(context: Pointer?): String?
fun getAudioChannels(context: Pointer?): Int
fun getAudioSampleRate(context: Pointer?): Int
companion object {
val INSTANCE: SharedVideoPlayer =
Native.load("NativeVideoPlayer", SharedVideoPlayer::class.java)
}
}
vendor/compose-mediaplayer/src/jvmMain/kotlin/io/github/kdroidfilter/composemediaplayer/mac/MacFullscreenVideoPlayerWindow.kt
- Source · implementation · 33 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
16: fun openFullscreenWindow(
Exact file bytes / download · SHA-256 e0fac44a0d28c6ea75211e3ccf6487998d2e733dd44ab349f32d221ec0bb3bea.
Complete file
package io.github.kdroidfilter.composemediaplayer.mac
import androidx.compose.runtime.Composable
import androidx.compose.ui.layout.ContentScale
import io.github.kdroidfilter.composemediaplayer.common.openFullscreenWindow
/**
* Opens a fullscreen window for the video player.
* This function is called when the user toggles fullscreen mode.
*
* @param playerState The player state to use in the fullscreen window
* @param overlay Optional composable content to be displayed on top of the video surface.
* This can be used to add custom controls, information, or any UI elements.
*/
@Composable
fun openFullscreenWindow(
playerState: MacVideoPlayerState,
overlay: @Composable () -> Unit = {},
contentScale: ContentScale = ContentScale.Fit
) {
openFullscreenWindow(
playerState = playerState,
renderSurface = { state, modifier, isInFullscreenWindow ->
MacVideoPlayerSurface(
playerState = state as MacVideoPlayerState,
modifier = modifier,
contentScale = contentScale,
overlay = overlay,
isInFullscreenWindow = isInFullscreenWindow
)
}
)
}
vendor/compose-mediaplayer/src/jvmMain/kotlin/io/github/kdroidfilter/composemediaplayer/mac/MacVideoPlayerState.kt
- Source · implementation · 1004 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
40: class MacVideoPlayerState : PlatformVideoPlayerState {
176: private fun startUIUpdateJob() {
189: private suspend fun allocatePlayer() = withContext(NonCancellable) {
196: private suspend fun initPlayer() = ioScope.launch {
221: private suspend fun updateFrameRateInfo() {
236: override fun openUri(uri: String) {
319: private suspend fun cleanupCurrentPlayback() {
343: private suspend fun ensurePlayerInitialized() {
363: private suspend fun openMediaUri(uri: String): Boolean {
405: private suspend fun pollDimensionsUntilReady(ptr: Pointer, maxAttempts: Int = 20) {
421: private suspend fun updateMetadata() {
471: private fun startFrameUpdates() {
489: private fun stopFrameUpdates() {
496: private fun startBufferingCheck() {
509: private suspend fun checkBufferingState() {
524: private fun stopBufferingCheck() {
535: private suspend fun calculateFrameHash(data: IntArray): Int = withContext(Dispatchers.Default) {
548: private suspend fun updateFrameAsync() {
610: private suspend fun updateAudioLevelsAsync() {
621: fun convertToPercentage(level: Float): Float {
645: private suspend fun updatePositionAsync() {
687: private suspend fun checkLoopingAsync(current: Double, duration: Double) {
703: override fun play() {
724: private suspend fun playInBackground() {
743: override fun pause() {
752: private suspend fun pauseInBackground() {
772: override fun stop() {
788: override fun seekTo(value: Float) {
799: private suspend fun seekToAsync(value: Float) {
856: override fun dispose() = disposal.dispose()
857: override suspend fun disposeAndJoin() = disposal.disposeAndJoin()
860: private suspend fun resetState() {
877: private fun setPlayerError(error: VideoPlayerError) {
891: private suspend fun handleError(e: Exception) {
902: private suspend fun getPositionSafely(): Double {
914: private suspend fun getDurationSafely(): Double {
930: private suspend fun applyVolume() {
948: private suspend fun applyPlaybackSpeed() {
962: override fun selectSubtitleTrack(track: SubtitleTrack?) {
971: override fun disableSubtitles() {
980: override fun clearError() {
995: override fun toggleFullscreen() {
Exact file bytes / download · SHA-256 7c073d3e96f305666a1a22abca134d2945551ace376952f9b2344ce3b44ad283.
Complete file
package io.github.kdroidfilter.composemediaplayer.mac
import androidx.compose.runtime.*
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.toComposeImageBitmap
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.sp
import co.touchlab.kermit.Logger
import co.touchlab.kermit.Logger.Companion.setMinSeverity
import co.touchlab.kermit.Severity
import com.sun.jna.Pointer
import io.github.kdroidfilter.composemediaplayer.PlatformVideoPlayerState
import io.github.kdroidfilter.composemediaplayer.SubtitleTrack
import io.github.kdroidfilter.composemediaplayer.VideoMetadata
import io.github.kdroidfilter.composemediaplayer.VideoPlayerError
import io.github.kdroidfilter.composemediaplayer.util.formatTime
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import java.awt.image.BufferedImage
import java.awt.image.DataBufferInt
import kotlin.math.abs
import kotlin.math.log10
// Initialize logger using Kermit
internal val macLogger = Logger.withTag("MacVideoPlayerState")
.apply { setMinSeverity(Severity.Warn) }
/**
* MacVideoPlayerState handles the native Mac video player state.
*
* This implementation uses a native video player via SharedVideoPlayer.
* All debug logs are handled with Kermit.
*/
class MacVideoPlayerState : PlatformVideoPlayerState {
// Main state variables
private val mainMutex = Mutex()
private var playerPtr: Pointer? = null
private val _currentFrameState = MutableStateFlow<ImageBitmap?>(null)
internal val currentFrameState: State<ImageBitmap?> = mutableStateOf(null)
private var _bufferImage: BufferedImage? = null
// Audio level state variables (added for left and right levels)
private val _leftLevel = mutableStateOf(0.0f)
private val _rightLevel = mutableStateOf(0.0f)
override val leftLevel: Float get() = _leftLevel.value
override val rightLevel: Float get() = _rightLevel.value
// Background worker threads and jobs
private val ioScope = CoroutineScope(Dispatchers.IO + SupervisorJob())
private var playerScope = CoroutineScope(Dispatchers.IO + SupervisorJob())
private var frameUpdateJob: Job? = null
private var bufferingCheckJob: Job? = null
private var uiUpdateJob: Job? = null
// State tracking
private var lastFrameUpdateTime: Long = 0
private var seekInProgress = false
private var targetSeekTime: Double? = null
private var lastFrameHash: Int = 0
private var videoFrameRate: Float = 0.0f
private var screenRefreshRate: Float = 0.0f
private var captureFrameRate: Float = 0.0f
// UI State (Main thread)
override var hasMedia: Boolean by mutableStateOf(false)
override var isPlaying: Boolean by mutableStateOf(false)
override var sliderPos: Float by mutableStateOf(0.0f)
override var userDragging: Boolean by mutableStateOf(false)
override var loop: Boolean by mutableStateOf(false)
override var isLoading: Boolean by mutableStateOf(false)
override var error: VideoPlayerError? by mutableStateOf(null)
override var subtitlesEnabled: Boolean by mutableStateOf(false)
override var currentSubtitleTrack: SubtitleTrack? by mutableStateOf(null)
override val availableSubtitleTracks: MutableList<SubtitleTrack> = mutableListOf()
override var subtitleTextStyle: TextStyle by mutableStateOf(
TextStyle(
color = Color.White,
fontSize = 18.sp,
fontWeight = FontWeight.Normal,
textAlign = TextAlign.Center
)
)
override var subtitleBackgroundColor: Color by mutableStateOf(Color.Black.copy(alpha = 0.5f))
override val metadata: VideoMetadata = VideoMetadata()
override var isFullscreen: Boolean by mutableStateOf(false)
private var lastUri: String? = null
// Non-blocking text properties
private val _positionText = mutableStateOf("00:00")
override val positionText: String get() = _positionText.value
private val _durationText = mutableStateOf("00:00")
override val durationText: String get() = _durationText.value
// Non-blocking aspect ratio property
private val _aspectRatio = mutableStateOf(16f / 9f)
override val aspectRatio: Float get() = _aspectRatio.value
// Player settings
// Volume variable is stored independently so it can always be modified.
private val _volumeState = mutableStateOf(1.0f)
override var volume: Float
get() = _volumeState.value
set(value) {
val newValue = value.coerceIn(0f, 1f)
if (_volumeState.value != newValue) {
_volumeState.value = newValue
// Launch a coroutine to apply the volume if the native player is available.
ioScope.launch {
applyVolume()
}
}
}
// Playback speed control
private val _playbackSpeedState = mutableStateOf(1.0f)
override var playbackSpeed: Float
get() = _playbackSpeedState.value
set(value) {
val newValue = value.coerceIn(0.5f, 2.0f)
if (_playbackSpeedState.value != newValue) {
_playbackSpeedState.value = newValue
// Launch a coroutine to apply the playback speed if the native player is available.
ioScope.launch {
applyPlaybackSpeed()
}
}
}
private val updateInterval: Long
get() = if (captureFrameRate > 0) {
(1000.0f / captureFrameRate).toLong()
} else {
33L // Default value (in ms) if no valid capture rate is provided
}
// Buffering detection constants
private val bufferingCheckInterval = 200L // Increased from 100ms to reduce CPU usage
private val bufferingTimeoutThreshold = 500L
private val disposal = io.github.kdroidfilter.composemediaplayer.AwaitedPlayerDisposal(
dispatcher = Dispatchers.IO,
retire = { playerScope.cancel(); ioScope.cancel() },
release = {
playerScope.coroutineContext[Job]?.join()
ioScope.coroutineContext[Job]?.join()
mainMutex.withLock {
playerPtr?.let { SharedVideoPlayer.INSTANCE.disposeVideoPlayer(it) }
playerPtr = null
_bufferImage = null
}
resetState()
},
)
init {
macLogger.d { "Initializing video player" }
ioScope.launch {
initPlayer()
startUIUpdateJob()
}
}
/**
* Starts a job to update UI state based on frame updates. This is the only
* job that touches the main thread.
*/
@OptIn(FlowPreview::class)
private fun startUIUpdateJob() {
uiUpdateJob?.cancel()
uiUpdateJob = ioScope.launch {
_currentFrameState.debounce(1).collect { newFrame ->
ensureActive() // Checks that the coroutine is still active
withContext(Dispatchers.Main) {
(currentFrameState as MutableState).value = newFrame
}
}
}
}
private suspend fun allocatePlayer() = withContext(NonCancellable) {
mainMutex.withLock {
playerPtr ?: SharedVideoPlayer.INSTANCE.createVideoPlayer().also { playerPtr = it }
}
}
/** Initializes the native video player on the IO thread. */
private suspend fun initPlayer() = ioScope.launch {
macLogger.d { "initPlayer() - Creating native player" }
try {
val ptr = allocatePlayer()
currentCoroutineContext().ensureActive()
if (ptr != null) {
macLogger.d { "Native player created successfully" }
applyVolume()
applyPlaybackSpeed()
} else {
macLogger.e { "Error: Failed to create native player" }
withContext(Dispatchers.Main) {
error = VideoPlayerError.UnknownError("Failed to create native player")
}
}
} catch (e: Exception) {
if (e is CancellationException) throw e
macLogger.e { "Exception in initPlayer: ${e.message}" }
withContext(Dispatchers.Main) {
error = VideoPlayerError.UnknownError("Failed to initialize player: ${e.message}")
}
}
}.join()
/** Updates the frame rate information from the native player. */
private suspend fun updateFrameRateInfo() {
macLogger.d { "updateFrameRateInfo()" }
val ptr = mainMutex.withLock { playerPtr } ?: return
try {
videoFrameRate = SharedVideoPlayer.INSTANCE.getVideoFrameRate(ptr)
screenRefreshRate = SharedVideoPlayer.INSTANCE.getScreenRefreshRate(ptr)
captureFrameRate = SharedVideoPlayer.INSTANCE.getCaptureFrameRate(ptr)
macLogger.d { "Frame Rates - Video: $videoFrameRate, Screen: $screenRefreshRate, Capture: $captureFrameRate" }
} catch (e: Exception) {
if (e is CancellationException) throw e
macLogger.e { "Error updating frame rate info: ${e.message}" }
}
}
override fun openUri(uri: String) {
if (disposal.isRequested) return
macLogger.d { "openUri() - Opening URI: $uri" }
lastUri = uri
// Check if this is a local file that doesn't exist
// This handles both URIs with file:// scheme and simple filenames without a scheme
if (uri.startsWith("file://") || !uri.contains("://") || !uri.matches("^[a-zA-Z]+://.*".toRegex())) {
val filePath = uri.replace("file://", "")
val file = java.io.File(filePath)
if (!file.exists()) {
macLogger.e { "File does not exist: $filePath" }
setPlayerError(VideoPlayerError.SourceError("File not found: $filePath"))
return
}
}
// Update UI state first
ioScope.launch {
withContext(Dispatchers.Main) {
isLoading = true
error = null // Clear any previous errors only if we got this far
playbackSpeed = 1.0f
}
// Ensure heavy operations are performed in the background
try {
// Stop and clean up any existing playback
if (hasMedia) {
cleanupCurrentPlayback()
}
// Ensure player is initialized in the background
ensurePlayerInitialized()
// Open URI on IO thread and capture result
val result = openMediaUri(uri)
if (result) {
// Launch parallel background tasks
coroutineScope {
launch { updateFrameRateInfo() }
launch { updateMetadata() }
}
// Update UI state on main thread
withContext(Dispatchers.Main) {
hasMedia = true
isLoading = false
isPlaying = true
}
// Start background processes for frame updates
startFrameUpdates()
// First frame update in the background
updateFrameAsync()
// Start buffering check in the background
startBufferingCheck()
// Start playback if needed - in the background
if (isPlaying) {
playInBackground()
}
} else {
macLogger.e { "Failed to open URI" }
// Use withContext directly since we're already in a suspend function
withContext(Dispatchers.Main) {
isLoading = false
error = VideoPlayerError.SourceError("Failed to open media source")
}
}
} catch (e: Exception) {
if (e is CancellationException) throw e
macLogger.e { "openUri() - Exception: ${e.message}" }
handleError(e)
}
}
}
/** Cleans up current playback state. */
private suspend fun cleanupCurrentPlayback() {
macLogger.d { "cleanupCurrentPlayback() - Cleaning up current playback" }
pauseInBackground()
stopFrameUpdates()
stopBufferingCheck()
val ptrToDispose = mainMutex.withLock {
val ptr = playerPtr
playerPtr = null
ptr
}
// Release resources outside of the mutex lock
ptrToDispose?.let {
try {
SharedVideoPlayer.INSTANCE.disposeVideoPlayer(it)
} catch (e: Exception) {
if (e is CancellationException) throw e
macLogger.e { "Error disposing player: ${e.message}" }
}
}
}
/** Ensures the player is initialized. */
private suspend fun ensurePlayerInitialized() {
macLogger.d { "ensurePlayerInitialized() - Ensuring player is initialized" }
if (disposal.isRequested) throw CancellationException("Player is disposed")
playerScope.ensureActive()
val isPlayerNull = mainMutex.withLock { playerPtr == null }
if (isPlayerNull) {
val ptr = allocatePlayer()
currentCoroutineContext().ensureActive()
if (ptr != null) {
applyVolume()
applyPlaybackSpeed()
} else {
throw IllegalStateException("Failed to create native player")
}
}
}
/** Opens media URI and returns a success flag. */
private suspend fun openMediaUri(uri: String): Boolean {
macLogger.d { "openMediaUri() - Opening URI: $uri" }
val ptr = mainMutex.withLock { playerPtr } ?: return false
// Check if file exists (for local files)
// This handles both URIs with file:// scheme and simple filenames without a scheme
if (uri.startsWith("file://") || !uri.contains("://") || !uri.matches("^[a-zA-Z]+://.*".toRegex())) {
val filePath = uri.replace("file://", "")
val file = java.io.File(filePath)
if (!file.exists()) {
macLogger.e { "File does not exist: $filePath" }
// Use setPlayerError to ensure the error is set synchronously
setPlayerError(VideoPlayerError.SourceError("File not found: $filePath"))
return false
}
}
return try {
// Open video asynchronously
SharedVideoPlayer.INSTANCE.openUri(ptr, uri)
// Instead of directly calling `updateMetadata()`,
// we poll until valid dimensions are available
pollDimensionsUntilReady(ptr)
// Once dimensions are retrieved, call updateMetadata()
updateMetadata()
true
} catch (e: Exception) {
macLogger.e { "Failed to open URI: ${e.message}" }
// Use setPlayerError to ensure the error is set synchronously
setPlayerError(VideoPlayerError.SourceError("Error opening media: ${e.message}"))
false
}
}
/**
* Loops several times (every 250 ms) until width/height
* are no longer zero. If dimensions are still zero after
* a specified number of attempts, stop waiting.
*/
private suspend fun pollDimensionsUntilReady(ptr: Pointer, maxAttempts: Int = 20) {
for (attempt in 1..maxAttempts) {
val width = SharedVideoPlayer.INSTANCE.getFrameWidth(ptr)
val height = SharedVideoPlayer.INSTANCE.getFrameHeight(ptr)
if (width > 0 && height > 0) {
macLogger.d { "Dimensions validated (w=$width, h=$height) after $attempt attempts" }
return
}
macLogger.d { "Dimensions not ready yet (attempt $attempt/$maxAttempts), waiting..." }
delay(250)
}
macLogger.e { "Unable to retrieve valid dimensions after $maxAttempts attempts" }
}
/** Updates the metadata from the native player. */
private suspend fun updateMetadata() {
macLogger.d { "updateMetadata()" }
val ptr = mainMutex.withLock { playerPtr } ?: return
try {
val width = SharedVideoPlayer.INSTANCE.getFrameWidth(ptr)
val height = SharedVideoPlayer.INSTANCE.getFrameHeight(ptr)
val duration = SharedVideoPlayer.INSTANCE.getVideoDuration(ptr).toLong()
val frameRate = SharedVideoPlayer.INSTANCE.getVideoFrameRate(ptr)
// Calculate aspect ratio
val newAspectRatio = if (width > 0 && height > 0) {
width.toFloat() / height.toFloat()
} else {
// Au lieu de forcer 16f/9f, ne changez pas l’aspect si la vidéo n’est pas encore prête.
// Par exemple, on peut conserver l’ancien aspect ratio :
_aspectRatio.value
}
// Get additional metadata
val title = SharedVideoPlayer.INSTANCE.getVideoTitle(ptr)
val bitrate = SharedVideoPlayer.INSTANCE.getVideoBitrate(ptr)
val mimeType = SharedVideoPlayer.INSTANCE.getVideoMimeType(ptr)
val audioChannels = SharedVideoPlayer.INSTANCE.getAudioChannels(ptr)
val audioSampleRate = SharedVideoPlayer.INSTANCE.getAudioSampleRate(ptr)
withContext(Dispatchers.Main) {
// Update metadata
metadata.duration = duration
metadata.width = width
metadata.height = height
metadata.frameRate = frameRate
metadata.title = title
metadata.bitrate = bitrate
metadata.mimeType = mimeType
metadata.audioChannels = if (audioChannels == 0) null else audioChannels
metadata.audioSampleRate = if (audioSampleRate == 0) null else audioSampleRate
// Met à jour l’aspect ratio seulement si width/height valides
_aspectRatio.value = newAspectRatio
}
macLogger.d { "Metadata updated: $metadata" }
} catch (e: Exception) {
if (e is CancellationException) throw e
macLogger.e { "Error updating metadata: ${e.message}" }
}
}
/** Starts periodic frame updates on a background thread. */
private fun startFrameUpdates() {
macLogger.d { "startFrameUpdates() - Starting frame updates" }
stopFrameUpdates()
frameUpdateJob = ioScope.launch {
while (isActive) {
ensureActive() // Check if coroutine is still active
updateFrameAsync()
if (!userDragging) {
updatePositionAsync()
// Call the audio level update separately
updateAudioLevelsAsync()
}
delay(updateInterval)
}
}
}
/** Stops periodic frame updates. */
private fun stopFrameUpdates() {
macLogger.d { "stopFrameUpdates() - Stopping frame updates" }
frameUpdateJob?.cancel()
frameUpdateJob = null
}
/** Starts periodic buffering detection on a background thread. */
private fun startBufferingCheck() {
macLogger.d { "startBufferingCheck() - Starting buffering detection" }
stopBufferingCheck()
bufferingCheckJob = ioScope.launch {
while (isActive) {
ensureActive() // Check if coroutine is still active
checkBufferingState()
delay(bufferingCheckInterval)
}
}
}
/** Checks if the media is currently buffering. */
private suspend fun checkBufferingState() {
if (isPlaying && !isLoading) {
val currentTime = System.currentTimeMillis()
val timeSinceLastFrame = currentTime - lastFrameUpdateTime
if (timeSinceLastFrame > bufferingTimeoutThreshold) {
macLogger.d { "Buffering detected: $timeSinceLastFrame ms since last frame update" }
withContext(Dispatchers.Main) {
isLoading = true
}
}
}
}
/** Stops the buffering detection job. */
private fun stopBufferingCheck() {
macLogger.d { "stopBufferingCheck() - Stopping buffering detection" }
bufferingCheckJob?.cancel()
bufferingCheckJob = null
}
/**
* Calculates a simple hash of the image data to detect if the frame has
* changed. This runs on the compute dispatcher for CPU-intensive work and
* samples fewer pixels for better performance.
*/
private suspend fun calculateFrameHash(data: IntArray): Int = withContext(Dispatchers.Default) {
var hash = 0
// Sample a smaller subset of pixels for performance
val step = data.size / 200
if (step > 0) {
for (i in data.indices step step) {
hash = 31 * hash + data[i]
}
}
hash
}
/** Updates the current video frame on a background thread. */
private suspend fun updateFrameAsync() {
try {
// Safely get the player pointer
val ptr = mainMutex.withLock { playerPtr } ?: return
// Get frame dimensions
val width = SharedVideoPlayer.INSTANCE.getFrameWidth(ptr)
val height = SharedVideoPlayer.INSTANCE.getFrameHeight(ptr)
if (width <= 0 || height <= 0) {
return
}
// Get the latest frame to minimize mutex lock time
val framePtr = SharedVideoPlayer.INSTANCE.getLatestFrame(ptr) ?: return
// Create or reuse a buffered image on a compute thread
val bufferedImage = withContext(Dispatchers.Default) {
val existingBuffer = mainMutex.withLock { _bufferImage }
if (existingBuffer == null || existingBuffer.width != width || existingBuffer.height != height) {
val newBuffer = BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB)
mainMutex.withLock { _bufferImage = newBuffer }
newBuffer
} else {
existingBuffer
}
}
// Copy frame data on a compute thread for performance
withContext(Dispatchers.Default) {
val pixels = (bufferedImage.raster.dataBuffer as DataBufferInt).data
framePtr.getByteBuffer(0, (width * height * 4).toLong()).asIntBuffer().get(pixels)
// Calculate frame hash to detect changes
val newHash = calculateFrameHash(pixels)
val frameChanged = newHash != lastFrameHash
lastFrameHash = newHash
if (frameChanged) {
// Update timestamp
lastFrameUpdateTime = System.currentTimeMillis()
// Convert to ImageBitmap on a compute thread
val imageBitmap = bufferedImage.toComposeImageBitmap()
// Publish to flow
_currentFrameState.value = imageBitmap
// Update loading state if needed on the main thread
if (isLoading && !seekInProgress) {
withContext(Dispatchers.Main) {
isLoading = false
}
}
}
}
} catch (e: Exception) {
if (e is CancellationException) throw e
macLogger.e { "updateFrameAsync() - Exception: ${e.message}" }
}
}
private suspend fun updateAudioLevelsAsync() {
if (!hasMedia) return
try {
val ptr = mainMutex.withLock { playerPtr }
if (ptr != null) {
val newLeft = SharedVideoPlayer.INSTANCE.getLeftAudioLevel(ptr)
val newRight = SharedVideoPlayer.INSTANCE.getRightAudioLevel(ptr)
// macLogger.d { "Audio levels fetched: L=$newLeft, R=$newRight" }
// Converts the linear level to a percentage on a logarithmic scale.
fun convertToPercentage(level: Float): Float {
if (level <= 0f) return 0f
// Conversion to decibels: 20 * log10(level)
val db = 20 * log10(level)
// Assume that -60 dB corresponds to silence and 0 dB to maximum level.
val normalized = ((db + 60) / 60).coerceIn(0f, 1f)
return normalized * 100f
}
withContext(Dispatchers.Main) {
_leftLevel.value = convertToPercentage(newLeft)
_rightLevel.value = convertToPercentage(newRight)
}
}
} catch (e: Exception) {
if (e is CancellationException) throw e
macLogger.e { "Error updating audio levels: ${e.message}" }
}
}
/**
* Updates the playback position, slider, and audio levels on a background
* thread.
*/
private suspend fun updatePositionAsync() {
if (!hasMedia || userDragging) return
try {
val duration = getDurationSafely()
if (duration <= 0) return
val current = getPositionSafely()
// Update time text display on the main thread
withContext(Dispatchers.Main) {
_positionText.value = formatTime(current)
_durationText.value = formatTime(duration)
}
// Handle seek in progress
if (seekInProgress && targetSeekTime != null) {
if (abs(current - targetSeekTime!!) < 0.3) {
seekInProgress = false
targetSeekTime = null
withContext(Dispatchers.Main) {
isLoading = false
}
macLogger.d { "Seek completed, resetting loading state" }
}
} else {
// Update slider position, batched with other UI updates to reduce main thread calls
val newSliderPos = (current / duration * 1000).toFloat().coerceIn(0f, 1000f)
withContext(Dispatchers.Main) {
sliderPos = newSliderPos
}
}
// Check for looping
checkLoopingAsync(current, duration)
} catch (e: Exception) {
if (e is CancellationException) throw e
macLogger.e { "Error in updatePositionAsync: ${e.message}" }
}
}
/** Checks if looping is enabled and restarts the video if needed. */
private suspend fun checkLoopingAsync(current: Double, duration: Double) {
if (current >= duration - 0.5) {
if (loop) {
macLogger.d { "checkLoopingAsync() - Loop enabled, restarting video" }
seekToAsync(0f)
} else {
macLogger.d { "checkLoopingAsync() - Video completed, updating state" }
withContext(Dispatchers.Main) {
isPlaying = false
}
// Ensure native player state is consistent
pauseInBackground()
}
}
}
override fun play() {
if (disposal.isRequested) return
macLogger.d { "play() - Starting playback" }
ioScope.launch {
if (!hasMedia && lastUri != null) {
// Reload the media using the saved URI
openUri(lastUri!!)
// The openUri method will start reading if the opening is successful
} else if (hasMedia) {
// If the media is already loaded, start playing in the background
playInBackground()
} else {
withContext(Dispatchers.Main) {
isPlaying = false
isLoading = false
}
}
}
}
/** Plays video on a background thread. */
private suspend fun playInBackground() {
val ptr = mainMutex.withLock { playerPtr } ?: return
try {
SharedVideoPlayer.INSTANCE.playVideo(ptr)
withContext(Dispatchers.Main) {
isPlaying = true
}
startFrameUpdates()
startBufferingCheck()
} catch (e: Exception) {
if (e is CancellationException) throw e
macLogger.e { "Error in playInBackground: ${e.message}" }
handleError(e)
}
}
override fun pause() {
if (disposal.isRequested) return
macLogger.d { "pause() - Pausing playback" }
ioScope.launch {
pauseInBackground()
}
}
/** Pauses video on a background thread. */
private suspend fun pauseInBackground() {
val ptr = mainMutex.withLock { playerPtr } ?: return
try {
SharedVideoPlayer.INSTANCE.pauseVideo(ptr)
withContext(Dispatchers.Main) {
isPlaying = false
isLoading = false
}
updateFrameAsync()
stopFrameUpdates()
stopBufferingCheck()
} catch (e: Exception) {
if (e is CancellationException) throw e
macLogger.e { "Error in pauseInBackground: ${e.message}" }
}
}
override fun stop() {
if (disposal.isRequested) return
macLogger.d { "stop() - Stopping playback" }
ioScope.launch {
pauseInBackground()
if (hasMedia) {
seekToAsync(0f)
}
withContext(Dispatchers.Main) {
hasMedia = false
isLoading = false
resetState()
}
}
}
override fun seekTo(value: Float) {
if (disposal.isRequested) return
macLogger.d { "seekTo() - Seeking with slider value: $value" }
ioScope.launch {
// Throttle rapid seek operations
delay(10) // Small delay to coalesce rapid seek events
seekToAsync(value)
}
}
/** Seeks to a position on a background thread. */
private suspend fun seekToAsync(value: Float) {
withContext(Dispatchers.Main) {
isLoading = true
}
try {
val duration = getDurationSafely()
if (duration <= 0) {
withContext(Dispatchers.Main) {
isLoading = false
}
return
}
val seekTime = ((value / 1000f) * duration.toFloat()).coerceIn(0f, duration.toFloat())
withContext(Dispatchers.Main) {
seekInProgress = true
targetSeekTime = seekTime.toDouble()
sliderPos = value
}
lastFrameUpdateTime = System.currentTimeMillis()
val ptr = mainMutex.withLock { playerPtr } ?: return
SharedVideoPlayer.INSTANCE.seekTo(ptr, seekTime.toDouble())
if (isPlaying) {
SharedVideoPlayer.INSTANCE.playVideo(ptr)
// Reduce delay to update frame faster for local videos
delay(10)
updateFrameAsync()
// Reduced timeout delay from 2000ms to 300ms
ioScope.launch {
delay(300)
if (seekInProgress) {
macLogger.d { "seekToAsync() - Forcing end of seek after timeout" }
seekInProgress = false
targetSeekTime = null
withContext(Dispatchers.Main) {
isLoading = false
}
}
}
}
} catch (e: Exception) {
if (e is CancellationException) throw e
macLogger.e { "Error in seekToAsync: ${e.message}" }
withContext(Dispatchers.Main) {
isLoading = false
seekInProgress = false
targetSeekTime = null
}
}
}
override fun dispose() = disposal.dispose()
override suspend fun disposeAndJoin() = disposal.disposeAndJoin()
/** Resets the player's state. */
private suspend fun resetState() {
withContext(Dispatchers.Main) {
hasMedia = false
isPlaying = false
isLoading = false
_positionText.value = "00:00"
_durationText.value = "00:00"
_aspectRatio.value = 16f / 9f
error = null
}
_currentFrameState.value = null
}
/**
* Sets an error in a consistent way, ensuring it's always set on the main thread.
* For synchronous calls, this will block until the error is set.
*/
private fun setPlayerError(error: VideoPlayerError) {
macLogger.e { "setPlayerError() - Setting error: $error" }
// For properties that need to be updated on the main thread,
// use runBlocking to ensure the update happens immediately
runBlocking {
withContext(Dispatchers.Main) {
isLoading = false
this@MacVideoPlayerState.error = error
}
}
}
/** Handles errors by updating the state and logging the error. */
private suspend fun handleError(e: Exception) {
macLogger.e { "handleError() - Player error: ${e.message}" }
// Since this is called from a suspend function, we can use withContext directly
withContext(Dispatchers.Main) {
isLoading = false
error = VideoPlayerError.SourceError("Error: ${e.message}")
}
}
/** Retrieves the current playback time from the native player. */
private suspend fun getPositionSafely(): Double {
val ptr = mainMutex.withLock { playerPtr } ?: return 0.0
return try {
SharedVideoPlayer.INSTANCE.getCurrentTime(ptr)
} catch (e: Exception) {
if (e is CancellationException) throw e
macLogger.e { "Error getting position: ${e.message}" }
0.0
}
}
/** Retrieves the total duration of the video from the native player. */
private suspend fun getDurationSafely(): Double {
val ptr = mainMutex.withLock { playerPtr } ?: return 0.0
return try {
SharedVideoPlayer.INSTANCE.getVideoDuration(ptr)
} catch (e: Exception) {
if (e is CancellationException) throw e
macLogger.e { "Error getting duration: ${e.message}" }
0.0
}
}
/**
* Applies the current volume setting to the native player. If no player
* is available, the volume is simply stored in _volumeState and will be
* applied when the player is initialized.
*/
private suspend fun applyVolume() {
mainMutex.withLock {
playerPtr?.let { ptr ->
try {
SharedVideoPlayer.INSTANCE.setVolume(ptr, _volumeState.value)
} catch (e: Exception) {
if (e is CancellationException) throw e
macLogger.e { "Error applying volume: ${e.message}" }
}
}
}
}
/**
* Applies the current playback speed setting to the native player. If no player
* is available, the speed is simply stored in _playbackSpeedState and will be
* applied when the player is initialized.
*/
private suspend fun applyPlaybackSpeed() {
mainMutex.withLock {
playerPtr?.let { ptr ->
try {
SharedVideoPlayer.INSTANCE.setPlaybackSpeed(ptr, _playbackSpeedState.value)
} catch (e: Exception) {
if (e is CancellationException) throw e
macLogger.e { "Error applying playback speed: ${e.message}" }
}
}
}
}
// Subtitle methods (stub implementations)
override fun selectSubtitleTrack(track: SubtitleTrack?) {
ioScope.launch {
withContext(Dispatchers.Main) {
currentSubtitleTrack = track
subtitlesEnabled = track != null
}
}
}
override fun disableSubtitles() {
ioScope.launch {
withContext(Dispatchers.Main) {
subtitlesEnabled = false
currentSubtitleTrack = null
}
}
}
override fun clearError() {
macLogger.d { "clearError() - Clearing error" }
// Use runBlocking to ensure the error is cleared immediately
// This is important for tests that expect the error to be cleared synchronously
runBlocking {
withContext(Dispatchers.Main) {
error = null
}
}
}
/**
* Toggles the fullscreen state of the video player
*/
override fun toggleFullscreen() {
// Update the state immediately for test synchronization
isFullscreen = !isFullscreen
// Launch any additional background work if needed
ioScope.launch {
// Any additional work related to fullscreen toggle can go here
}
}
}
vendor/compose-mediaplayer/src/jvmMain/kotlin/io/github/kdroidfilter/composemediaplayer/mac/MacVideoPlayerSurface.kt
- Source · implementation · 88 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
32: fun MacVideoPlayerSurface(
Exact file bytes / download · SHA-256 ad67e7dc3e83291fe89242aa16ff8d0c866332fe28a5dbf73c72d78d9e17d934.
Complete file
package io.github.kdroidfilter.composemediaplayer.mac
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.Box
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.unit.IntSize
import io.github.kdroidfilter.composemediaplayer.subtitle.ComposeSubtitleLayer
import io.github.kdroidfilter.composemediaplayer.util.drawScaledImage
import io.github.kdroidfilter.composemediaplayer.util.toCanvasModifier
import io.github.kdroidfilter.composemediaplayer.util.toTimeMs
/**
* A Composable function that renders a video player surface for MacOS.
* Fills the entire canvas area with the video frame while maintaining aspect ratio.
*
* @param playerState The state object that encapsulates the AVPlayer logic for MacOS.
* @param modifier An optional Modifier for customizing the layout.
* @param contentScale Controls how the video content should be scaled inside the surface.
* This affects how the video is displayed when its dimensions don't match
* the surface dimensions.
* @param overlay Optional composable content to be displayed on top of the video surface.
* This can be used to add custom controls, information, or any UI elements.
* @param isInFullscreenWindow Whether this surface is already being displayed in a fullscreen window.
*/
@Composable
fun MacVideoPlayerSurface(
playerState: MacVideoPlayerState,
modifier: Modifier = Modifier,
contentScale: ContentScale = ContentScale.Fit,
overlay: @Composable () -> Unit = {},
isInFullscreenWindow: Boolean = false,
) {
Box(
modifier = modifier,
contentAlignment = Alignment.Center
) {
// Only render video in this surface if we're not in fullscreen mode or if this is the fullscreen window
if (playerState.hasMedia && (!playerState.isFullscreen || isInFullscreenWindow)) {
// Force recomposition when currentFrameState changes
val currentFrame by remember(playerState) { playerState.currentFrameState }
currentFrame?.let { frame ->
Canvas(
modifier = contentScale.toCanvasModifier(playerState.aspectRatio,playerState.metadata.width,playerState.metadata.height),
) {
drawScaledImage(
image = frame,
dstSize = IntSize(size.width.toInt(), size.height.toInt()),
contentScale = contentScale
)
}
}
// Add Compose-based subtitle layer
if (playerState.subtitlesEnabled && playerState.currentSubtitleTrack != null) {
// Calculate current time in milliseconds
val currentTimeMs = (playerState.sliderPos / 1000f *
playerState.durationText.toTimeMs()).toLong()
// Calculate duration in milliseconds
val durationMs = playerState.durationText.toTimeMs()
ComposeSubtitleLayer(
currentTimeMs = currentTimeMs,
durationMs = durationMs,
isPlaying = playerState.isPlaying,
subtitleTrack = playerState.currentSubtitleTrack,
subtitlesEnabled = playerState.subtitlesEnabled,
textStyle = playerState.subtitleTextStyle,
backgroundColor = playerState.subtitleBackgroundColor
)
}
}
// Render the overlay content on top of the video
overlay()
}
if (playerState.isFullscreen && !isInFullscreenWindow) {
openFullscreenWindow(playerState, overlay = overlay, contentScale = contentScale)
}
}
vendor/compose-mediaplayer/src/jvmMain/kotlin/io/github/kdroidfilter/composemediaplayer/mac/native/NativeVideoPlayer.swift
- Source · implementation · 1025 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
9: class SharedVideoPlayer {
Exact file bytes / download · SHA-256 cb1ad450ec91084b290878e691cce299c3d9467849dd83bfd37f74f76afec724.
Complete file
import AVFoundation
import CoreGraphics
import CoreVideo
import Foundation
import AppKit
/// Class that manages video playback and frame capture into an optimized shared buffer.
/// Frame capture rate adapts to the lower of screen refresh rate and video frame rate.
class SharedVideoPlayer {
private var player: AVPlayer?
private var videoOutput: AVPlayerItemVideoOutput?
// Timer for capturing frames at adaptive rate
private var displayLink: Timer?
// Track the video's native frame rate
private var videoFrameRate: Float = 0.0
// Track the screen's refresh rate
private var screenRefreshRate: Float = 60.0
// The actual capture frame rate (minimum of video and screen rates)
private var captureFrameRate: Float = 0.0
// Shared buffer to store the frame in BGRA format (no conversion needed)
private var frameBuffer: UnsafeMutablePointer<UInt32>?
private var bufferCapacity: Int = 0
// Frame dimensions
private var frameWidth: Int = 0
private var frameHeight: Int = 0
// Audio volume control (0.0 to 1.0)
private var volume: Float = 1.0
// Flag to track if playback is active
private var isPlaying: Bool = false
private var isReadyForPlayback = false
private var pendingPlay = false
///Two properties to store the left and right audio levels.
private var leftAudioLevel: Float = 0.0
private var rightAudioLevel: Float = 0.0
// Playback speed control (1.0 is normal speed)
private var playbackSpeed: Float = 1.0
// Metadata properties
private var videoTitle: String? = nil
private var videoBitrate: Int64 = 0
private var videoMimeType: String? = nil
private var audioChannels: Int = 0
private var audioSampleRate: Int = 0
init() {
// Detect screen refresh rate
detectScreenRefreshRate()
}
/// Detects the current screen refresh rate
private func detectScreenRefreshRate() {
if let mainScreen = NSScreen.main {
// Use CoreVideo DisplayLink to get refresh rate on macOS
var displayID: CGDirectDisplayID = CGMainDisplayID()
if let screenNumber = mainScreen.deviceDescription[
NSDeviceDescriptionKey("NSScreenNumber")] as? NSNumber
{
displayID = CGDirectDisplayID(screenNumber.uint32Value)
}
var displayLink: CVDisplayLink?
let error = CVDisplayLinkCreateWithCGDisplay(displayID, &displayLink)
if error == kCVReturnSuccess, let link = displayLink {
let period = CVDisplayLinkGetNominalOutputVideoRefreshPeriod(link)
let timeValue = period.timeValue
let timeScale = period.timeScale
if timeValue > 0 && timeScale > 0 {
// Convert to Hz (frames per second)
let refreshRate = Double(timeScale) / Double(timeValue)
screenRefreshRate = Float(refreshRate)
}
// No need to release the link as Core Foundation objects are automatically memory managed
} else {
// Fallback if we can't get the refresh rate
screenRefreshRate = 60.0
}
} else {
screenRefreshRate = 60.0
}
}
/// Extracts metadata from the asset
private func extractMetadata(from asset: AVAsset) {
// Reset metadata values
videoTitle = nil
videoBitrate = 0
videoMimeType = nil
audioChannels = 0
audioSampleRate = 0
// Extract title from metadata
if let commonMetadata = asset.commonMetadata as? [AVMetadataItem] {
if let titleItem = AVMetadataItem.metadataItems(from: commonMetadata, filteredByIdentifier: .commonIdentifierTitle).first,
let title = titleItem.value as? String {
videoTitle = title
}
}
// Try to get bitrate from the asset directly
if let urlAsset = asset as? AVURLAsset {
// Try to get file size
do {
let fileAttributes = try FileManager.default.attributesOfItem(atPath: urlAsset.url.path)
if let fileSize = fileAttributes[.size] as? NSNumber {
let fileSizeInBytes = fileSize.int64Value
// Get duration in seconds
let durationInSeconds = CMTimeGetSeconds(asset.duration)
if durationInSeconds > 0 {
// Calculate bitrate: (fileSize * 8) / durationInSeconds
let calculatedBitrate = Int64(Double(fileSizeInBytes * 8) / durationInSeconds)
videoBitrate = calculatedBitrate
print("Calculated bitrate from file size: \(calculatedBitrate) bits/s")
}
}
} catch {
print("Error getting file attributes: \(error.localizedDescription)")
}
}
// Extract format information
if #available(macOS 13.0, *) {
Task {
do {
// Load tracks asynchronously
let videoTracks = try await asset.loadTracks(withMediaType: .video)
let audioTracks = try await asset.loadTracks(withMediaType: .audio)
// Extract video bitrate and format
if let videoTrack = videoTracks.first {
// Try to get estimated data rate directly from the track
if #available(macOS 13.0, *) {
do {
let estimatedDataRate = try await videoTrack.load(.estimatedDataRate)
if estimatedDataRate > 0 {
videoBitrate = Int64(estimatedDataRate)
print("Got bitrate from estimatedDataRate: \(videoBitrate) bits/s")
}
} catch {
print("Error getting estimatedDataRate: \(error.localizedDescription)")
}
}
// Get estimated data rate (bitrate) from format description
let formatDescriptions = try await videoTrack.load(.formatDescriptions)
if let formatDescription = formatDescriptions.first {
let extensions = CMFormatDescriptionGetExtensions(formatDescription) as Dictionary?
if let dict = extensions,
let bitrate = dict[kCMFormatDescriptionExtension_VerbatimSampleDescription] as? Dictionary<String, Any>,
let avgBitrate = bitrate["avg-bitrate"] as? Int64 {
videoBitrate = avgBitrate
print("Got bitrate from format description: \(videoBitrate) bits/s")
}
// Get MIME type
let mediaSubType = CMFormatDescriptionGetMediaSubType(formatDescription)
let mediaType = CMFormatDescriptionGetMediaType(formatDescription)
if mediaType == kCMMediaType_Video {
switch mediaSubType {
case kCMVideoCodecType_H264:
videoMimeType = "video/h264"
case kCMVideoCodecType_HEVC:
videoMimeType = "video/hevc"
case kCMVideoCodecType_MPEG4Video:
videoMimeType = "video/mp4v-es"
case kCMVideoCodecType_MPEG2Video:
videoMimeType = "video/mpeg2"
default:
videoMimeType = "video/mp4"
}
}
}
}
// Extract audio channels and sample rate
if let audioTrack = audioTracks.first {
let formatDescriptions = try await audioTrack.load(.formatDescriptions)
if let formatDescription = formatDescriptions.first {
let basicDescription = CMAudioFormatDescriptionGetStreamBasicDescription(formatDescription)
if let basicDesc = basicDescription {
audioChannels = Int(basicDesc.pointee.mChannelsPerFrame)
audioSampleRate = Int(basicDesc.pointee.mSampleRate)
}
}
}
} catch {
print("Error extracting metadata: \(error.localizedDescription)")
}
}
} else {
// Fallback for older OS versions
// Extract video bitrate and format
if let videoTrack = asset.tracks(withMediaType: .video).first {
// Try to get estimated data rate directly from the track
let estimatedDataRate = videoTrack.estimatedDataRate
if estimatedDataRate > 0 {
videoBitrate = Int64(estimatedDataRate)
print("Got bitrate from estimatedDataRate (legacy): \(videoBitrate) bits/s")
}
if let formatDescriptions = videoTrack.formatDescriptions as? [CMFormatDescription],
let formatDescription = formatDescriptions.first {
let extensions = CMFormatDescriptionGetExtensions(formatDescription) as Dictionary?
if let dict = extensions,
let bitrate = dict[kCMFormatDescriptionExtension_VerbatimSampleDescription] as? Dictionary<String, Any>,
let avgBitrate = bitrate["avg-bitrate"] as? Int64 {
videoBitrate = avgBitrate
print("Got bitrate from format description (legacy): \(videoBitrate) bits/s")
}
// Get MIME type
let mediaSubType = CMFormatDescriptionGetMediaSubType(formatDescription)
let mediaType = CMFormatDescriptionGetMediaType(formatDescription)
if mediaType == kCMMediaType_Video {
switch mediaSubType {
case kCMVideoCodecType_H264:
videoMimeType = "video/h264"
case kCMVideoCodecType_HEVC:
videoMimeType = "video/hevc"
case kCMVideoCodecType_MPEG4Video:
videoMimeType = "video/mp4v-es"
case kCMVideoCodecType_MPEG2Video:
videoMimeType = "video/mpeg2"
default:
videoMimeType = "video/mp4"
}
}
}
}
// Extract audio channels and sample rate
if let audioTrack = asset.tracks(withMediaType: .audio).first {
if let formatDescriptions = audioTrack.formatDescriptions as? [CMAudioFormatDescription],
let formatDescription = formatDescriptions.first {
let basicDescription = CMAudioFormatDescriptionGetStreamBasicDescription(formatDescription)
if let basicDesc = basicDescription {
audioChannels = Int(basicDesc.pointee.mChannelsPerFrame)
audioSampleRate = Int(basicDesc.pointee.mSampleRate)
}
}
}
}
}
/// Detects the video's native frame rate from its asset
private func detectVideoFrameRate(from asset: AVAsset) {
asset.loadTracks(withMediaType: .video) { [self] tracks, error in
guard let videoTrack = tracks?.first, error == nil else {
print(
"Erreur lors du chargement des pistes vidéo : \(error?.localizedDescription ?? "Inconnue")"
)
return
}
// Replace deprecated nominalFrameRate property
if #available(macOS 13.0, *) {
Task {
do {
let frameRate = try await videoTrack.load(.nominalFrameRate)
self.videoFrameRate = Float(frameRate)
if self.videoFrameRate <= 0 {
// Fallback to common default if detection fails
self.videoFrameRate = 30.0
}
// Set capture rate to the lower of the two rates
self.updateCaptureFrameRate()
} catch {
print("Error loading nominal frame rate: \(error.localizedDescription)")
// Fallback to common default if detection fails
self.videoFrameRate = 30.0
self.updateCaptureFrameRate()
}
}
} else {
// Use deprecated property for older OS versions
videoFrameRate = Float(videoTrack.nominalFrameRate)
if videoFrameRate <= 0 {
// Fallback to common default if detection fails
videoFrameRate = 30.0
}
// Set capture rate to the lower of the two rates
updateCaptureFrameRate()
}
}
}
/// Updates the capture frame rate based on screen and video rates
private func updateCaptureFrameRate() {
captureFrameRate = min(screenRefreshRate, videoFrameRate)
// Update display link if it exists
if isPlaying {
configureDisplayLink()
}
}
/// Opens the video from the given URI (local or network)
func openUri(_ uri: String) {
isReadyForPlayback = false
pendingPlay = false
// Determine the URL (local or network)
let url: URL = {
if let parsedURL = URL(string: uri), parsedURL.scheme != nil {
return parsedURL
} else {
return URL(fileURLWithPath: uri)
}
}()
let asset = AVURLAsset(url: url)
// Extract metadata from the asset
extractMetadata(from: asset)
// Detect video frame rate
detectVideoFrameRate(from: asset)
// Retrieve the video track to obtain the actual dimensions
asset.loadTracks(withMediaType: .video) { [self] tracks, error in
guard let videoTrack = tracks?.first, error == nil else {
print(
"Erreur lors du chargement des pistes vidéo : \(error?.localizedDescription ?? "Inconnue")"
)
return
}
if #available(macOS 13.0, *) {
Task {
do {
// Use the modern API to load naturalSize and preferredTransform
let naturalSize = try await videoTrack.load(.naturalSize)
let transform = try await videoTrack.load(.preferredTransform)
let effectiveSize = naturalSize.applying(transform)
frameWidth = Int(abs(effectiveSize.width))
frameHeight = Int(abs(effectiveSize.height))
// Continue with buffer allocation and setup
setupFrameBuffer()
setupVideoOutputAndPlayer(with: asset)
} catch {
print("Error loading video track properties: \(error.localizedDescription)")
}
}
} else {
// Fallback for older OS versions using deprecated properties
let naturalSize = videoTrack.naturalSize
let transform = videoTrack.preferredTransform
let effectiveSize = naturalSize.applying(transform)
frameWidth = Int(abs(effectiveSize.width))
frameHeight = Int(abs(effectiveSize.height))
// Continue with buffer allocation and setup
setupFrameBuffer()
setupVideoOutputAndPlayer(with: asset)
}
}
}
// Helper method to setup frame buffer
private func setupFrameBuffer() {
// Allocate or reuse the shared buffer if capacity matches
let totalPixels = frameWidth * frameHeight
if let buffer = frameBuffer, bufferCapacity == totalPixels {
buffer.initialize(repeating: 0, count: totalPixels)
} else {
frameBuffer?.deallocate()
frameBuffer = UnsafeMutablePointer<UInt32>.allocate(capacity: totalPixels)
frameBuffer?.initialize(repeating: 0, count: totalPixels)
bufferCapacity = totalPixels
}
}
// Helper method to setup video output and player
private func setupVideoOutputAndPlayer(with asset: AVAsset) {
// Create attributes for the CVPixelBuffer (BGRA format) with IOSurface for better performance
let pixelBufferAttributes: [String: Any] = [
kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_32BGRA,
kCVPixelBufferWidthKey as String: frameWidth,
kCVPixelBufferHeightKey as String: frameHeight,
kCVPixelBufferIOSurfacePropertiesKey as String: [:],
]
videoOutput = AVPlayerItemVideoOutput(pixelBufferAttributes: pixelBufferAttributes)
let item = AVPlayerItem(asset: asset)
if let output = videoOutput {
item.add(output)
}
player = AVPlayer(playerItem: item)
setupAudioTap(for: item)
// Set initial volume
player?.volume = volume
// Capture initial frame
captureInitialFrame()
// Mark as ready for playback
self.isReadyForPlayback = true
// If playback was pending, start playback
if self.pendingPlay {
DispatchQueue.main.async {
self.play()
}
}
}
/// Captures initial frame to display without starting the display link
private func captureInitialFrame() {
guard let output = videoOutput, player?.currentItem != nil else { return }
// Seek to the beginning to ensure we have a frame
let zeroTime = CMTime.zero
player?.seek(to: zeroTime)
// Try to get the first frame
if output.hasNewPixelBuffer(forItemTime: zeroTime),
let pixelBuffer = output.copyPixelBuffer(forItemTime: zeroTime, itemTimeForDisplay: nil)
{
updateLatestFrameData(from: pixelBuffer)
}
}
/// Configures the timer with the appropriate frame rate
private func configureDisplayLink() {
stopDisplayLink() // Ensure previous link is invalidated
// For macOS, use a timer with the appropriate interval
let interval = 1.0 / Double(captureFrameRate)
Timer.scheduledTimer(withTimeInterval: interval, repeats: true) { [weak self] _ in
self?.captureFrame()
}
}
/// Stops the timer
private func stopDisplayLink() {
displayLink?.invalidate()
displayLink = nil
}
/// Captures the latest frame from the video output if available.
@objc private func captureFrame() {
guard let output = videoOutput,
let item = player?.currentItem,
isPlaying == true
else { return } // Skip capture if video is not playing
let currentTime = item.currentTime()
if output.hasNewPixelBuffer(forItemTime: currentTime),
let pixelBuffer = output.copyPixelBuffer(
forItemTime: currentTime, itemTimeForDisplay: nil)
{
updateLatestFrameData(from: pixelBuffer)
}
}
/// Directly copies the content of the pixelBuffer into the shared buffer without conversion.
private func updateLatestFrameData(from pixelBuffer: CVPixelBuffer) {
guard let destBuffer = frameBuffer else { return }
CVPixelBufferLockBaseAddress(pixelBuffer, .readOnly)
defer { CVPixelBufferUnlockBaseAddress(pixelBuffer, .readOnly) }
guard let srcBaseAddress = CVPixelBufferGetBaseAddress(pixelBuffer) else { return }
let width = CVPixelBufferGetWidth(pixelBuffer)
let height = CVPixelBufferGetHeight(pixelBuffer)
let srcBytesPerRow = CVPixelBufferGetBytesPerRow(pixelBuffer)
guard width == frameWidth, height == frameHeight else {
print("Unexpected dimensions: \(width)x\(height)")
return
}
if srcBytesPerRow == width * 4 {
memcpy(destBuffer, srcBaseAddress, height * srcBytesPerRow)
} else {
for row in 0..<height {
let srcRow = srcBaseAddress.advanced(by: row * srcBytesPerRow)
let destRow = destBuffer.advanced(by: row * width)
memcpy(destRow, srcRow, width * 4)
}
}
}
/// Retrieve the audio levels.
func getLeftAudioLevel() -> Float {
return leftAudioLevel
}
func getRightAudioLevel() -> Float {
return rightAudioLevel
}
// MARK: - Audio Tap Callbacks
/// Callback: Initialization of the tap.
private let tapInit: MTAudioProcessingTapInitCallback = { (tap, clientInfo, tapStorageOut) in
// Initialize tap storage (e.g. to store cumulative values if needed)
tapStorageOut.pointee = clientInfo
}
/// Callback: Finalize the tap.
private let tapFinalize: MTAudioProcessingTapFinalizeCallback = { (tap) in
// Cleanup if necessary.
}
/// Callback: Prepare the tap (called before processing).
private let tapPrepare: MTAudioProcessingTapPrepareCallback = {
(tap, maxFrames, processingFormat) in
// You can set up buffers or other resources here if needed.
}
/// Callback: Unprepare the tap (called after processing).
private let tapUnprepare: MTAudioProcessingTapUnprepareCallback = { (tap) in
// Release any resources allocated in prepare.
}
/// Callback: Process audio. This is where you calculate the audio levels.
private let tapProcess: MTAudioProcessingTapProcessCallback = {
(tap, numberFrames, flags, bufferListInOut, numberFramesOut, flagsOut) in
// Get the tap context (the SharedVideoPlayer instance)
let opaqueSelf = MTAudioProcessingTapGetStorage(tap)
let mySelf = Unmanaged<SharedVideoPlayer>.fromOpaque(opaqueSelf).takeUnretainedValue()
var localFrames = numberFrames
// Retrieve the audio buffers
let status = MTAudioProcessingTapGetSourceAudio(
tap, localFrames, bufferListInOut, flagsOut, nil, nil)
if status != noErr {
print("MTAudioProcessingTapGetSourceAudio failed with status: \(status)")
return
}
// Process the audio buffers to calculate left and right channel levels.
let bufferList = bufferListInOut.pointee
// Vérifier que les buffers sont valides
guard bufferList.mNumberBuffers > 0 else {
print("No audio buffers available")
return
}
// Vérifier le format audio (nous attendons du Float32)
guard let mBuffers = bufferList.mBuffers.mData,
bufferList.mBuffers.mDataByteSize > 0 else {
print("Invalid audio buffer data")
return
}
// Log des informations sur le format audio pour le débogage
//print("Audio buffer: numBuffers=\(bufferList.mNumberBuffers), size=\(bufferList.mBuffers.mDataByteSize), frames=\(localFrames)")
// Assuming interleaved float data (adjust if using a different format)
let data = mBuffers.bindMemory(
to: Float.self, capacity: Int(bufferList.mBuffers.mDataByteSize / 4))
let frameCount = Int(localFrames)
var leftSum: Float = 0.0
var rightSum: Float = 0.0
var leftCount = 0
var rightCount = 0
// Assuming stereo (2 channels)
if frameCount > 0 {
for frame in 0..<frameCount {
if frame * 2 + 1 < Int(bufferList.mBuffers.mDataByteSize / 4) {
let leftSample = data[frame * 2]
let rightSample = data[frame * 2 + 1]
leftSum += abs(leftSample)
rightSum += abs(rightSample)
leftCount += 1
rightCount += 1
}
}
// Calculate average level for each channel
let avgLeft = leftCount > 0 ? leftSum / Float(leftCount) : 0.0
let avgRight = rightCount > 0 ? rightSum / Float(rightCount) : 0.0
// Update the properties
//print("Audio levels: L=\(avgLeft), R=\(avgRight)")
mySelf.leftAudioLevel = avgLeft
mySelf.rightAudioLevel = avgRight
} else {
print("No audio frames to process")
}
numberFramesOut.pointee = localFrames
}
// Dans la méthode setupAudioTap, ajoutez une vérification du format audio et un log
private func setupAudioTap(for playerItem: AVPlayerItem) {
guard let asset = playerItem.asset as? AVURLAsset else {
print("Asset is not an AVURLAsset")
return
}
// Load audio tracks asynchronously
asset.loadTracks(withMediaType: .audio) { tracks, error in
guard let audioTrack = tracks?.first, error == nil else {
print("No audio track found or error: \(error?.localizedDescription ?? "unknown")")
return
}
print("Audio track found, setting up tap")
// Create input parameters with a processing tap
let inputParams = AVMutableAudioMixInputParameters(track: audioTrack)
var callbacks = MTAudioProcessingTapCallbacks(
version: kMTAudioProcessingTapCallbacksVersion_0,
clientInfo: UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque()),
init: self.tapInit,
finalize: self.tapFinalize,
prepare: self.tapPrepare,
unprepare: self.tapUnprepare,
process: self.tapProcess
)
var tap: Unmanaged<MTAudioProcessingTap>?
// Create the audio processing tap
let status = MTAudioProcessingTapCreate(
kCFAllocatorDefault, &callbacks, kMTAudioProcessingTapCreationFlag_PostEffects, &tap
)
if status == noErr, let tap = tap {
print("Audio tap created successfully")
inputParams.audioTapProcessor = tap.takeRetainedValue()
let audioMix = AVMutableAudioMix()
audioMix.inputParameters = [inputParams]
playerItem.audioMix = audioMix
} else {
print("Audio Tap creation failed with status: \(status)")
}
}
}
/// Starts video playback and begins frame capture at the optimized frame rate.
func play() {
if isReadyForPlayback {
isPlaying = true
player?.play()
configureDisplayLink()
} else {
// Marquer qu'une lecture est en attente
pendingPlay = true
}
}
/// Pauses video playback and stops frame capture.
func pause() {
isPlaying = false
player?.pause()
stopDisplayLink()
// Capture the current frame to display while paused
if let output = videoOutput, let item = player?.currentItem {
let currentTime = item.currentTime()
if output.hasNewPixelBuffer(forItemTime: currentTime),
let pixelBuffer = output.copyPixelBuffer(
forItemTime: currentTime, itemTimeForDisplay: nil)
{
updateLatestFrameData(from: pixelBuffer)
}
}
}
/// Sets the volume level (0.0 to 1.0)
func setVolume(level: Float) {
volume = max(0.0, min(1.0, level)) // Clamp between 0.0 and 1.0
// Manage the multi-channel case (>2 channels)
if let playerItem = player?.currentItem, audioChannels > 2 {
// Apply volume via an AudioMix if we have more than 2 channels
if let audioTrack = playerItem.asset.tracks(withMediaType: .audio).first {
let parameters = AVMutableAudioMixInputParameters(track: audioTrack)
parameters.setVolume(volume, at: CMTime.zero)
let audioMix = AVMutableAudioMix()
audioMix.inputParameters = [parameters]
playerItem.audioMix = audioMix
}
} else {
// For stereo and mono channels, use the standard method
player?.volume = volume
}
}
/// Gets the current volume level (0.0 to 1.0)
func getVolume() -> Float {
return volume
}
/// Sets the playback speed (0.5 to 2.0, where 1.0 is normal speed)
func setPlaybackSpeed(speed: Float) {
playbackSpeed = max(0.5, min(2.0, speed)) // Clamp between 0.5 and 2.0
player?.rate = playbackSpeed
}
/// Gets the current playback speed (0.5 to 2.0, where 1.0 is normal speed)
func getPlaybackSpeed() -> Float {
return playbackSpeed
}
/// Returns a pointer to the shared frame buffer. The caller should not free this pointer.
func getLatestFramePointer() -> UnsafeMutablePointer<UInt32>? {
return frameBuffer
}
/// Returns the width of the video frame in pixels
func getFrameWidth() -> Int { return frameWidth }
/// Returns the height of the video frame in pixels
func getFrameHeight() -> Int { return frameHeight }
/// Returns the detected video frame rate
func getVideoFrameRate() -> Float { return videoFrameRate }
/// Returns the detected screen refresh rate
func getScreenRefreshRate() -> Float { return screenRefreshRate }
/// Returns the current capture frame rate (minimum of video and screen rates)
func getCaptureFrameRate() -> Float { return captureFrameRate }
/// Returns the video title if available
func getVideoTitle() -> String? { return videoTitle }
/// Returns the video bitrate in bits per second
func getVideoBitrate() -> Int64 { return videoBitrate }
/// Returns the video MIME type if available
func getVideoMimeType() -> String? { return videoMimeType }
/// Returns the number of audio channels
func getAudioChannels() -> Int { return audioChannels }
/// Returns the audio sample rate in Hz
func getAudioSampleRate() -> Int { return audioSampleRate }
/// Returns the duration of the video in seconds.
func getDuration() -> Double {
guard let item = player?.currentItem else { return 0 }
if #available(macOS 13.0, *) {
// Use the modern API with async/await
Task {
do {
let duration = try await item.asset.load(.duration)
return CMTimeGetSeconds(duration)
} catch {
print("Error loading duration: \(error.localizedDescription)")
return 0
}
}
// Return the current value while the task is running
return CMTimeGetSeconds(item.asset.duration)
} else {
// Use deprecated property for older OS versions
return CMTimeGetSeconds(item.asset.duration)
}
}
/// Returns the current playback time in seconds.
func getCurrentTime() -> Double {
guard let item = player?.currentItem else { return 0 }
return CMTimeGetSeconds(item.currentTime())
}
/// Seeks to the specified time (in seconds).
func seekTo(time: Double) {
guard let player = player else { return }
let newTime = CMTime(seconds: time, preferredTimescale: 600)
player.seek(to: newTime)
// Update frame at the new position if paused
if !isPlaying, let output = videoOutput {
if output.hasNewPixelBuffer(forItemTime: newTime),
let pixelBuffer = output.copyPixelBuffer(
forItemTime: newTime, itemTimeForDisplay: nil)
{
updateLatestFrameData(from: pixelBuffer)
}
}
}
/// Disposes of the video player and releases resources.
func dispose() {
pause()
player = nil
videoOutput = nil
if let buffer = frameBuffer {
buffer.deallocate()
frameBuffer = nil
bufferCapacity = 0
}
}
}
/// MARK: - C Exported Functions for JNA
@_cdecl("createVideoPlayer")
public func createVideoPlayer() -> UnsafeMutableRawPointer? {
let player = SharedVideoPlayer()
return Unmanaged.passRetained(player).toOpaque()
}
@_cdecl("openUri")
public func openUri(_ context: UnsafeMutableRawPointer?, _ uri: UnsafePointer<CChar>?) {
guard let context = context,
let uriCStr = uri,
let swiftUri = String(validatingUTF8: uriCStr)
else {
print("Invalid parameters for openUri")
return
}
let player = Unmanaged<SharedVideoPlayer>.fromOpaque(context).takeUnretainedValue()
// Use a background queue for heavy operations to avoid blocking the main thread
DispatchQueue.global(qos: .userInitiated).async {
player.openUri(swiftUri)
}
}
@_cdecl("playVideo")
public func playVideo(_ context: UnsafeMutableRawPointer?) {
guard let context = context else { return }
let player = Unmanaged<SharedVideoPlayer>.fromOpaque(context).takeUnretainedValue()
DispatchQueue.main.async {
player.play()
}
}
@_cdecl("pauseVideo")
public func pauseVideo(_ context: UnsafeMutableRawPointer?) {
guard let context = context else { return }
let player = Unmanaged<SharedVideoPlayer>.fromOpaque(context).takeUnretainedValue()
DispatchQueue.main.async {
player.pause()
}
}
@_cdecl("setVolume")
public func setVolume(_ context: UnsafeMutableRawPointer?, _ volume: Float) {
guard let context = context else { return }
let player = Unmanaged<SharedVideoPlayer>.fromOpaque(context).takeUnretainedValue()
DispatchQueue.main.async {
player.setVolume(level: volume)
}
}
@_cdecl("getVolume")
public func getVolume(_ context: UnsafeMutableRawPointer?) -> Float {
guard let context = context else { return 0.0 }
let player = Unmanaged<SharedVideoPlayer>.fromOpaque(context).takeUnretainedValue()
return player.getVolume()
}
@_cdecl("getLatestFrame")
public func getLatestFrame(_ context: UnsafeMutableRawPointer?) -> UnsafeMutableRawPointer? {
guard let context = context else { return nil }
let player = Unmanaged<SharedVideoPlayer>.fromOpaque(context).takeUnretainedValue()
if let ptr = player.getLatestFramePointer() {
return UnsafeMutableRawPointer(ptr)
}
return nil
}
@_cdecl("getFrameWidth")
public func getFrameWidth(_ context: UnsafeMutableRawPointer?) -> Int32 {
guard let context = context else { return 0 }
let player = Unmanaged<SharedVideoPlayer>.fromOpaque(context).takeUnretainedValue()
return Int32(player.getFrameWidth())
}
@_cdecl("getFrameHeight")
public func getFrameHeight(_ context: UnsafeMutableRawPointer?) -> Int32 {
guard let context = context else { return 0 }
let player = Unmanaged<SharedVideoPlayer>.fromOpaque(context).takeUnretainedValue()
return Int32(player.getFrameHeight())
}
@_cdecl("getVideoFrameRate")
public func getVideoFrameRate(_ context: UnsafeMutableRawPointer?) -> Float {
guard let context = context else { return 0.0 }
let player = Unmanaged<SharedVideoPlayer>.fromOpaque(context).takeUnretainedValue()
return player.getVideoFrameRate()
}
@_cdecl("getScreenRefreshRate")
public func getScreenRefreshRate(_ context: UnsafeMutableRawPointer?) -> Float {
guard let context = context else { return 0.0 }
let player = Unmanaged<SharedVideoPlayer>.fromOpaque(context).takeUnretainedValue()
return player.getScreenRefreshRate()
}
@_cdecl("getCaptureFrameRate")
public func getCaptureFrameRate(_ context: UnsafeMutableRawPointer?) -> Float {
guard let context = context else { return 0.0 }
let player = Unmanaged<SharedVideoPlayer>.fromOpaque(context).takeUnretainedValue()
return player.getCaptureFrameRate()
}
@_cdecl("getVideoDuration")
public func getVideoDuration(_ context: UnsafeMutableRawPointer?) -> Double {
guard let context = context else { return 0 }
let player = Unmanaged<SharedVideoPlayer>.fromOpaque(context).takeUnretainedValue()
return player.getDuration()
}
@_cdecl("getCurrentTime")
public func getCurrentTime(_ context: UnsafeMutableRawPointer?) -> Double {
guard let context = context else { return 0 }
let player = Unmanaged<SharedVideoPlayer>.fromOpaque(context).takeUnretainedValue()
return player.getCurrentTime()
}
@_cdecl("seekTo")
public func seekTo(_ context: UnsafeMutableRawPointer?, _ time: Double) {
guard let context = context else { return }
let player = Unmanaged<SharedVideoPlayer>.fromOpaque(context).takeUnretainedValue()
DispatchQueue.main.async {
player.seekTo(time: time)
}
}
@_cdecl("disposeVideoPlayer")
public func disposeVideoPlayer(_ context: UnsafeMutableRawPointer?) {
guard let context = context else { return }
let player = Unmanaged<SharedVideoPlayer>.fromOpaque(context).takeRetainedValue()
DispatchQueue.main.async {
player.dispose()
}
}
@_cdecl("getLeftAudioLevel")
public func getLeftAudioLevel(_ context: UnsafeMutableRawPointer?) -> Float {
guard let context = context else { return 0.0 }
let player = Unmanaged<SharedVideoPlayer>.fromOpaque(context).takeUnretainedValue()
return player.getLeftAudioLevel()
}
@_cdecl("getRightAudioLevel")
public func getRightAudioLevel(_ context: UnsafeMutableRawPointer?) -> Float {
guard let context = context else { return 0.0 }
let player = Unmanaged<SharedVideoPlayer>.fromOpaque(context).takeUnretainedValue()
return player.getRightAudioLevel()
}
@_cdecl("setPlaybackSpeed")
public func setPlaybackSpeed(_ context: UnsafeMutableRawPointer?, _ speed: Float) {
guard let context = context else { return }
let player = Unmanaged<SharedVideoPlayer>.fromOpaque(context).takeUnretainedValue()
DispatchQueue.main.async {
player.setPlaybackSpeed(speed: speed)
}
}
@_cdecl("getPlaybackSpeed")
public func getPlaybackSpeed(_ context: UnsafeMutableRawPointer?) -> Float {
guard let context = context else { return 1.0 }
let player = Unmanaged<SharedVideoPlayer>.fromOpaque(context).takeUnretainedValue()
return player.getPlaybackSpeed()
}
@_cdecl("getVideoTitle")
public func getVideoTitle(_ context: UnsafeMutableRawPointer?) -> UnsafePointer<CChar>? {
guard let context = context else { return nil }
let player = Unmanaged<SharedVideoPlayer>.fromOpaque(context).takeUnretainedValue()
if let title = player.getVideoTitle() {
let cString = strdup(title)
return UnsafePointer<CChar>(cString)
}
return nil
}
@_cdecl("getVideoBitrate")
public func getVideoBitrate(_ context: UnsafeMutableRawPointer?) -> Int64 {
guard let context = context else { return 0 }
let player = Unmanaged<SharedVideoPlayer>.fromOpaque(context).takeUnretainedValue()
return player.getVideoBitrate()
}
@_cdecl("getVideoMimeType")
public func getVideoMimeType(_ context: UnsafeMutableRawPointer?) -> UnsafePointer<CChar>? {
guard let context = context else { return nil }
let player = Unmanaged<SharedVideoPlayer>.fromOpaque(context).takeUnretainedValue()
if let mimeType = player.getVideoMimeType() {
let cString = strdup(mimeType)
return UnsafePointer<CChar>(cString)
}
return nil
}
@_cdecl("getAudioChannels")
public func getAudioChannels(_ context: UnsafeMutableRawPointer?) -> Int32 {
guard let context = context else { return 0 }
let player = Unmanaged<SharedVideoPlayer>.fromOpaque(context).takeUnretainedValue()
return Int32(player.getAudioChannels())
}
@_cdecl("getAudioSampleRate")
public func getAudioSampleRate(_ context: UnsafeMutableRawPointer?) -> Int32 {
guard let context = context else { return 0 }
let player = Unmanaged<SharedVideoPlayer>.fromOpaque(context).takeUnretainedValue()
return Int32(player.getAudioSampleRate())
}
vendor/compose-mediaplayer/src/jvmMain/kotlin/io/github/kdroidfilter/composemediaplayer/subtitle/SubtitleLoader.jvm.kt
- Source · implementation · 63 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
19: actual suspend fun loadSubtitleContent(src: String): String = withContext(Dispatchers.IO) {
Exact file bytes / download · SHA-256 8a8bfc0a0347c9bdb0a5e01136f9fd8687a6241fcd01024cf933021ec9ffcffa.
Complete file
package io.github.kdroidfilter.composemediaplayer.subtitle
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.BufferedReader
import java.io.File
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URI
import java.net.URL
/**
* JVM implementation of the loadSubtitleContent function.
* Loads subtitle content from a local file or a remote URL.
*
* @param src The source URI of the subtitle file
* @return The content of the subtitle file as a string
*/
actual suspend fun loadSubtitleContent(src: String): String = withContext(Dispatchers.IO) {
try {
when {
// Handle HTTP/HTTPS URLs
src.startsWith("http://") || src.startsWith("https://") -> {
val url = URL(src)
val connection = url.openConnection() as HttpURLConnection
connection.connectTimeout = 10000
connection.readTimeout = 10000
val reader = BufferedReader(InputStreamReader(connection.inputStream))
val content = reader.use { it.readText() }
connection.disconnect()
content
}
// Handle file:// URIs
src.startsWith("file://") -> {
val file = File(URI(src))
file.readText()
}
// Handle local file paths
else -> {
val file = File(src)
if (file.exists()) {
file.readText()
} else {
// Try to interpret as a URI
try {
val uri = URI(src)
val uriFile = File(uri)
uriFile.readText()
} catch (e: Exception) {
println("Error loading subtitle file: ${e.message}")
""
}
}
}
}
} catch (e: Exception) {
println("Error loading subtitle content: ${e.message}")
""
}
}
vendor/compose-mediaplayer/src/jvmMain/kotlin/io/github/kdroidfilter/composemediaplayer/util/Uri.kt
- Source · implementation · 8 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
6: actual fun PlatformFile.getUri(): String {
Exact file bytes / download · SHA-256 8b13b32d3e0abbbc6f87c886aac39bec836c7899cd2d9ac06cdbaeace9e1e6ca.
Complete file
package io.github.kdroidfilter.composemediaplayer.util
import io.github.vinceglb.filekit.PlatformFile
import io.github.vinceglb.filekit.path
actual fun PlatformFile.getUri(): String {
return this.path.toString()
}
vendor/compose-mediaplayer/src/jvmMain/kotlin/io/github/kdroidfilter/composemediaplayer/util/VideoPlayerStateRegistry.kt
- Source · implementation · 40 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
12: object VideoPlayerStateRegistry {
21: fun registerState(state: PlatformVideoPlayerState) {
30: fun getRegisteredState(): PlatformVideoPlayerState? {
37: fun clearRegisteredState() {
Exact file bytes / download · SHA-256 8c5034867c4def40ecc6caf159e39c4a29af9fe3778bbb315c9039d6d72b2725.
Complete file
package io.github.kdroidfilter.composemediaplayer.util
import androidx.compose.runtime.Stable
import io.github.kdroidfilter.composemediaplayer.PlatformVideoPlayerState
import java.lang.ref.WeakReference
/**
* Registry for sharing WindowsVideoPlayerState instances between windows.
* This is used to pass the player state to the fullscreen window.
*/
@Stable
object VideoPlayerStateRegistry {
private var registeredState: WeakReference<PlatformVideoPlayerState>? = null
/**
* Register a WindowsVideoPlayerState instance to be shared between windows.
* Uses a WeakReference to avoid memory leaks.
*
* @param state The WindowsVideoPlayerState to register
*/
fun registerState(state: PlatformVideoPlayerState) {
registeredState = WeakReference(state)
}
/**
* Get the registered WindowsVideoPlayerState instance.
*
* @return The registered WindowsVideoPlayerState or null if none is registered
*/
fun getRegisteredState(): PlatformVideoPlayerState? {
return registeredState?.get()
}
/**
* Clear the registered WindowsVideoPlayerState instance.
*/
fun clearRegisteredState() {
registeredState = null
}
}
vendor/compose-mediaplayer/src/jvmMain/kotlin/io/github/kdroidfilter/composemediaplayer/windows/MediaFoundationLib.kt
- Source · implementation · 125 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
14: internal interface MediaFoundationLib : StdCallLibrary {
24: class NativeVideoMetadata : Structure() {
47: fun toVideoMetadata(): VideoMetadata {
71: fun createInstance(): Pointer? {
81: fun destroyInstance(instance: Pointer) {
90: fun getVideoMetadata(instance: Pointer): VideoMetadata? {
97: fun InitMediaFoundation(): Int
98: fun CreateVideoPlayerInstance(ppInstance: PointerByReference): Int
99: fun DestroyVideoPlayerInstance(pInstance: Pointer)
100: fun OpenMedia(pInstance: Pointer, url: WString): Int
101: fun ReadVideoFrame(pInstance: Pointer, pData: PointerByReference, pDataSize: IntByReference): Int
102: fun UnlockVideoFrame(pInstance: Pointer): Int
103: fun CloseMedia(pInstance: Pointer)
104: fun IsEOF(pInstance: Pointer): Boolean
105: fun GetVideoSize(pInstance: Pointer, pWidth: IntByReference, pHeight: IntByReference)
106: fun GetVideoFrameRate(pInstance: Pointer, pNum: IntByReference, pDenom: IntByReference): Int
107: fun SeekMedia(pInstance: Pointer, lPosition: Long): Int
108: fun GetMediaDuration(pInstance: Pointer, pDuration: LongByReference): Int
109: fun GetMediaPosition(pInstance: Pointer, pPosition: LongByReference): Int
110: fun SetPlaybackState(pInstance: Pointer, isPlaying: Boolean, bStop: Boolean = false): Int
111: fun ShutdownMediaFoundation(): Int
112: fun SetAudioVolume(pInstance: Pointer, volume: Float): Int
113: fun GetAudioVolume(pInstance: Pointer, volume: FloatByReference): Int
114: fun GetAudioLevels(pInstance: Pointer, pLeftLevel: FloatByReference, pRightLevel: FloatByReference): Int
115: fun SetPlaybackSpeed(pInstance: Pointer, speed: Float): Int
116: fun GetPlaybackSpeed(pInstance: Pointer, pSpeed: FloatByReference): Int
124: fun GetVideoMetadata(pInstance: Pointer, pMetadata: NativeVideoMetadata): Int
Exact file bytes / download · SHA-256 97c38eaa3d914782aaddaffe70f5c182f4bbbfdbcf95ef29a2173de0685537e2.
Complete file
package io.github.kdroidfilter.composemediaplayer.windows
import com.sun.jna.Native
import com.sun.jna.Pointer
import com.sun.jna.Structure
import com.sun.jna.WString
import com.sun.jna.ptr.FloatByReference
import com.sun.jna.ptr.IntByReference
import com.sun.jna.ptr.LongByReference
import com.sun.jna.ptr.PointerByReference
import com.sun.jna.win32.StdCallLibrary
import io.github.kdroidfilter.composemediaplayer.VideoMetadata
internal interface MediaFoundationLib : StdCallLibrary {
/**
* JNA structure that maps to the C++ VideoMetadata structure
*/
@Structure.FieldOrder(
"title", "duration", "width", "height", "bitrate", "frameRate", "mimeType",
"audioChannels", "audioSampleRate", "hasTitle", "hasDuration", "hasWidth",
"hasHeight", "hasBitrate", "hasFrameRate", "hasMimeType", "hasAudioChannels",
"hasAudioSampleRate"
)
class NativeVideoMetadata : Structure() {
@JvmField var title = CharArray(256)
@JvmField var duration: Long = 0
@JvmField var width: Int = 0
@JvmField var height: Int = 0
@JvmField var bitrate: Long = 0
@JvmField var frameRate: Float = 0f
@JvmField var mimeType = CharArray(64)
@JvmField var audioChannels: Int = 0
@JvmField var audioSampleRate: Int = 0
@JvmField var hasTitle: Boolean = false
@JvmField var hasDuration: Boolean = false
@JvmField var hasWidth: Boolean = false
@JvmField var hasHeight: Boolean = false
@JvmField var hasBitrate: Boolean = false
@JvmField var hasFrameRate: Boolean = false
@JvmField var hasMimeType: Boolean = false
@JvmField var hasAudioChannels: Boolean = false
@JvmField var hasAudioSampleRate: Boolean = false
/**
* Converts this native structure to a Kotlin VideoMetadata object
*/
fun toVideoMetadata(): VideoMetadata {
return VideoMetadata(
title = if (hasTitle) String(title).trim { it <= ' ' || it == '\u0000' } else null,
duration = if (hasDuration) duration / 10000 else null, // Convert from 100ns to ms
width = if (hasWidth) width else null,
height = if (hasHeight) height else null,
bitrate = if (hasBitrate) bitrate else null,
frameRate = if (hasFrameRate) frameRate else null,
mimeType = if (hasMimeType) String(mimeType).trim { it <= ' ' || it == '\u0000' } else null,
audioChannels = if (hasAudioChannels) audioChannels else null,
audioSampleRate = if (hasAudioSampleRate) audioSampleRate else null
)
}
}
companion object {
val INSTANCE: MediaFoundationLib by lazy {
Native.load("NativeVideoPlayer", MediaFoundationLib::class.java)
}
/**
* Creates a new instance of the native video player
* @return A pointer to the native instance or null if creation failed
*/
fun createInstance(): Pointer? {
val ptrRef = PointerByReference()
val hr = INSTANCE.CreateVideoPlayerInstance(ptrRef)
return if (hr >= 0 && ptrRef.value != null) ptrRef.value else null
}
/**
* Destroys a native video player instance
* @param instance The pointer to the native instance to destroy
*/
fun destroyInstance(instance: Pointer) {
INSTANCE.DestroyVideoPlayerInstance(instance)
}
/**
* Retrieves metadata for the current media
* @param instance Pointer to the native instance
* @return VideoMetadata object containing all available metadata, or null if retrieval failed
*/
fun getVideoMetadata(instance: Pointer): VideoMetadata? {
val metadata = NativeVideoMetadata()
val hr = INSTANCE.GetVideoMetadata(instance, metadata)
return if (hr >= 0) metadata.toVideoMetadata() else null
}
}
fun InitMediaFoundation(): Int
fun CreateVideoPlayerInstance(ppInstance: PointerByReference): Int
fun DestroyVideoPlayerInstance(pInstance: Pointer)
fun OpenMedia(pInstance: Pointer, url: WString): Int
fun ReadVideoFrame(pInstance: Pointer, pData: PointerByReference, pDataSize: IntByReference): Int
fun UnlockVideoFrame(pInstance: Pointer): Int
fun CloseMedia(pInstance: Pointer)
fun IsEOF(pInstance: Pointer): Boolean
fun GetVideoSize(pInstance: Pointer, pWidth: IntByReference, pHeight: IntByReference)
fun GetVideoFrameRate(pInstance: Pointer, pNum: IntByReference, pDenom: IntByReference): Int
fun SeekMedia(pInstance: Pointer, lPosition: Long): Int
fun GetMediaDuration(pInstance: Pointer, pDuration: LongByReference): Int
fun GetMediaPosition(pInstance: Pointer, pPosition: LongByReference): Int
fun SetPlaybackState(pInstance: Pointer, isPlaying: Boolean, bStop: Boolean = false): Int
fun ShutdownMediaFoundation(): Int
fun SetAudioVolume(pInstance: Pointer, volume: Float): Int
fun GetAudioVolume(pInstance: Pointer, volume: FloatByReference): Int
fun GetAudioLevels(pInstance: Pointer, pLeftLevel: FloatByReference, pRightLevel: FloatByReference): Int
fun SetPlaybackSpeed(pInstance: Pointer, speed: Float): Int
fun GetPlaybackSpeed(pInstance: Pointer, pSpeed: FloatByReference): Int
/**
* Retrieves all available metadata for the current media
* @param pInstance Pointer to the native instance
* @param pMetadata Pointer to receive the metadata structure
* @return S_OK on success, or an error code
*/
fun GetVideoMetadata(pInstance: Pointer, pMetadata: NativeVideoMetadata): Int
}
vendor/compose-mediaplayer/src/jvmMain/kotlin/io/github/kdroidfilter/composemediaplayer/windows/WindowsFullscreenVideoPlayerWindow.kt
- Source · implementation · 33 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
16: fun openFullscreenWindow(
Exact file bytes / download · SHA-256 2d5682f9208f3e811ba3b2492c614cee9d37cbd32568f1d53e428e3b86091d2c.
Complete file
package io.github.kdroidfilter.composemediaplayer.windows
import androidx.compose.runtime.Composable
import io.github.kdroidfilter.composemediaplayer.common.openFullscreenWindow
/**
* Opens a fullscreen window for the video player.
* This function is called when the user toggles fullscreen mode.
*
* @param playerState The player state to use in the fullscreen window
* @param contentScale Controls how the video content should be scaled inside the surface.
* @param overlay Optional composable content to be displayed on top of the video surface.
* This can be used to add custom controls, information, or any UI elements.
*/
@Composable
fun openFullscreenWindow(
playerState: WindowsVideoPlayerState,
contentScale: androidx.compose.ui.layout.ContentScale = androidx.compose.ui.layout.ContentScale.Fit,
overlay: @Composable () -> Unit = {}
) {
openFullscreenWindow(
playerState = playerState,
renderSurface = { state, modifier, isInFullscreenWindow ->
WindowsVideoPlayerSurface(
playerState = state as WindowsVideoPlayerState,
modifier = modifier,
contentScale = contentScale,
overlay = overlay,
isInFullscreenWindow = isInFullscreenWindow
)
}
)
}
vendor/compose-mediaplayer/src/jvmMain/kotlin/io/github/kdroidfilter/composemediaplayer/windows/WindowsVideoPlayerState.kt
- Source · implementation · 1033 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
56: class WindowsVideoPlayerState : PlatformVideoPlayerState {
67: private fun ensureMfInitialized() {
185: override fun clearError() { _error = null; errorMessage = null }
240: private data class FrameData(
293: override fun dispose() = disposal.dispose()
294: override suspend fun disposeAndJoin() = disposal.disposeAndJoin()
296: private fun releaseAllResources() {
320: private fun clearFrameChannel() {
332: override fun openUri(uri: String) {
357: private fun openUriInternal(uri: String) {
494: private suspend fun updateAudioLevels() {
508: private suspend fun produceFrames() {
621: private suspend fun consumeFrames() {
691: override fun play() {
745: override fun pause() {
760: override fun stop() {
783: override fun seekTo(value: Float) {
851: fun onResized() {
880: private fun setError(msg: String) {
892: private fun createVideoImageInfo() =
903: private fun setPlaybackState(playing: Boolean, errorMessage: String, bStop: Boolean = false): Boolean {
928: private suspend fun waitForPlaybackState() {
961: private suspend fun waitIfResizing(): Boolean {
980: private fun readyForPlayback(): Boolean {
991: private fun executeMediaOperation(
1009: override fun selectSubtitleTrack(track: SubtitleTrack?) {
1018: override fun disableSubtitles() {
1030: override fun toggleFullscreen() {
Exact file bytes / download · SHA-256 d596b95fc3304193462c0ee66a39698a243387caea8974063a34b6e6bf4feec2.
Complete file
package io.github.kdroidfilter.composemediaplayer.windows
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.asComposeImageBitmap
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.sp
import co.touchlab.kermit.Logger
import co.touchlab.kermit.Logger.Companion.setMinSeverity
import co.touchlab.kermit.Severity
import com.sun.jna.Pointer
import com.sun.jna.WString
import com.sun.jna.ptr.FloatByReference
import com.sun.jna.ptr.IntByReference
import com.sun.jna.ptr.LongByReference
import com.sun.jna.ptr.PointerByReference
import io.github.kdroidfilter.composemediaplayer.PlatformVideoPlayerState
import io.github.kdroidfilter.composemediaplayer.SubtitleTrack
import io.github.kdroidfilter.composemediaplayer.VideoMetadata
import io.github.kdroidfilter.composemediaplayer.VideoPlayerError
import io.github.kdroidfilter.composemediaplayer.util.formatTime
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import org.jetbrains.skia.Bitmap
import org.jetbrains.skia.ColorAlphaType
import org.jetbrains.skia.ColorType
import org.jetbrains.skia.ImageInfo
import java.io.File
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.locks.ReentrantReadWriteLock
import kotlin.concurrent.write
import kotlin.math.min
/**
* Logger for Windows video player implementation
*/
internal val windowsLogger = Logger.withTag("WindowsVideoPlayerState")
.apply { setMinSeverity(Severity.Warn) }
/**
* Windows implementation of the video player state.
* Handles media playback using Media Foundation on Windows platform.
*/
class WindowsVideoPlayerState : PlatformVideoPlayerState {
companion object {
private val isMfBootstrapped = AtomicBoolean(false)
/** Map to store volume settings for each player instance */
private val instanceVolumes = ConcurrentHashMap<Pointer, Float>()
/**
* Initialize Media Foundation only once for all instances.
* This is called automatically when the class is loaded.
*/
private fun ensureMfInitialized() {
if (!isMfBootstrapped.getAndSet(true)) {
val hr = MediaFoundationLib.INSTANCE.InitMediaFoundation()
if (hr < 0) {
windowsLogger.e { "Media Foundation initialization failed (hr=0x${hr.toString(16)})" }
}
}
}
init {
// Initialize Media Foundation when class is loaded
ensureMfInitialized()
}
}
/** Instance of the native Media Foundation player */
private val player = MediaFoundationLib.INSTANCE
/** Coroutine scope for all async operations */
private val scope = CoroutineScope(Dispatchers.Default + SupervisorJob())
/** Whether media has been loaded */
private var _hasMedia by mutableStateOf(false)
override val hasMedia get() = _hasMedia
/** Whether media is currently playing */
private var _isPlaying by mutableStateOf(false)
override val isPlaying get() = _isPlaying
/** Whether the user has intentionally paused the video */
private var userPaused = false
/** Video player instance handle */
private var videoPlayerInstance: Pointer? = null
/** Deferred completed when initialization is ready */
private val initReady = CompletableDeferred<Unit>()
/** Current volume level (0.0 to 1.0) */
private var _volume by mutableStateOf(1f)
/**
* Volume control for the player (0.0 to 1.0)
* Any modification triggers the native call SetAudioVolume
*/
override var volume: Float
get() = _volume
set(value) {
val newVolume = value.coerceIn(0f, 1f)
if (_volume != newVolume) {
_volume = newVolume
scope.launch {
mediaOperationMutex.withLock {
videoPlayerInstance?.let { instance ->
// Store the volume setting for this instance
instanceVolumes[instance] = newVolume
// Apply the volume setting to the native player
val hr = player.SetAudioVolume(instance, newVolume)
if (hr < 0) {
setError("Error updating volume (hr=0x${hr.toString(16)})")
}
}
}
}
}
}
private var _currentTime by mutableStateOf(0.0)
private var _duration by mutableStateOf(0.0)
private var _progress by mutableStateOf(0f)
override var sliderPos: Float
get() = _progress * 1000f
set(value) {
_progress = (value / 1000f).coerceIn(0f, 1f)
if (!userDragging) seekTo(value)
}
private var _userDragging by mutableStateOf(false)
override var userDragging: Boolean
get() = _userDragging
set(value) { _userDragging = value }
private var _loop by mutableStateOf(false)
override var loop: Boolean
get() = _loop
set(value) { _loop = value }
private var _playbackSpeed by mutableStateOf(1.0f)
override var playbackSpeed: Float
get() = _playbackSpeed
set(value) {
val newSpeed = value.coerceIn(0.5f, 2.0f)
if (_playbackSpeed != newSpeed) {
_playbackSpeed = newSpeed
scope.launch {
mediaOperationMutex.withLock {
videoPlayerInstance?.let { instance ->
val hr = player.SetPlaybackSpeed(instance, newSpeed)
if (hr < 0) {
setError("Error updating playback speed (hr=0x${hr.toString(16)})")
}
}
}
}
}
}
// Updating audio levels via GetAudioLevels
private var _leftLevel by mutableStateOf(0f)
override val leftLevel: Float get() = _leftLevel
private var _rightLevel by mutableStateOf(0f)
override val rightLevel: Float get() = _rightLevel
private var _error: VideoPlayerError? = null
override val error get() = _error
override fun clearError() { _error = null; errorMessage = null }
// Current frame management
private var _currentFrame: Bitmap? by mutableStateOf(null)
private val bitmapLock = ReentrantReadWriteLock()
internal val currentFrameState = mutableStateOf<ImageBitmap?>(null)
// Aspect ratio property
override val aspectRatio: Float
get() = if (videoWidth > 0 && videoHeight > 0)
videoWidth.toFloat() / videoHeight.toFloat()
else 16f / 9f
// Metadata and UI state
private var _metadata by mutableStateOf(VideoMetadata())
override val metadata: VideoMetadata get() = _metadata
override var subtitlesEnabled = false
override var currentSubtitleTrack: SubtitleTrack? = null
override val availableSubtitleTracks = mutableListOf<SubtitleTrack>()
override var subtitleTextStyle: TextStyle = TextStyle(
color = Color.White,
fontSize = 18.sp,
fontWeight = FontWeight.Normal,
textAlign = TextAlign.Center
)
override var subtitleBackgroundColor: Color = Color.Black.copy(alpha = 0.5f)
override var isLoading by mutableStateOf(false)
private set
override val positionText: String get() = formatTime(_currentTime)
override val durationText: String get() = formatTime(_duration)
private var errorMessage: String? by mutableStateOf(null)
// Fullscreen state
override var isFullscreen by mutableStateOf(false)
// Video properties
var videoWidth by mutableStateOf(0)
var videoHeight by mutableStateOf(0)
private var frameBufferSize = 1
// Synchronization
private val mediaOperationMutex = Mutex()
private val isResizing = AtomicBoolean(false)
private var videoJob: Job? = null
private var resizeJob: Job? = null
private var audioLevelsJob: Job? = null
// Memory optimization for frame processing
private val frameQueueSize = 1
private val frameChannel = Channel<FrameData>(
capacity = frameQueueSize,
onBufferOverflow = BufferOverflow.DROP_OLDEST
)
// Data structure for a frame
private data class FrameData(
val bitmap: Bitmap,
val timestamp: Double
)
// Singleton buffer to limit allocations
private var sharedFrameBuffer: ByteArray? = null
private var frameBitmapRecycler: Bitmap? = null
// Variable to store the last opened URI
private var lastUri: String? = null
private val disposal = io.github.kdroidfilter.composemediaplayer.AwaitedPlayerDisposal(
retire = { scope.cancel() },
release = {
scope.coroutineContext[Job]?.join()
mediaOperationMutex.withLock {
_isPlaying = false
videoPlayerInstance?.let { instance ->
player.SetPlaybackState(instance, false, true)
player.CloseMedia(instance)
MediaFoundationLib.destroyInstance(instance)
instanceVolumes.remove(instance)
videoPlayerInstance = null
}
releaseAllResources()
_hasMedia = false
}
},
)
init {
// Kick off native initialization immediately
scope.launch {
try {
val instance = MediaFoundationLib.createInstance()
if (instance == null) {
setError("Failed to create video player instance")
return@launch
}
videoPlayerInstance = instance
// Store default volume so that later instances inherit it
instanceVolumes[instance] = _volume
initReady.complete(Unit)
} catch (e: Exception) {
initReady.completeExceptionally(e)
setError("Exception during initialization: ${e.message}")
}
}
}
override fun dispose() = disposal.dispose()
override suspend fun disposeAndJoin() = disposal.disposeAndJoin()
private fun releaseAllResources() {
// Cancel any remaining jobs related to video processing
videoJob?.cancel()
audioLevelsJob?.cancel()
resizeJob?.cancel()
// Ensure the frame channel is emptied
clearFrameChannel()
// Free bitmaps and frame buffers
bitmapLock.write {
_currentFrame?.close() // Close the current frame bitmap if any
_currentFrame = null
// Reset the currentFrameState
currentFrameState.value = null
frameBitmapRecycler?.close() // Recycle the bitmap if any
frameBitmapRecycler = null
}
// Clear any shared buffer allocated for frames
sharedFrameBuffer = null
frameBufferSize = 0 // Reset frame buffer size
}
private fun clearFrameChannel() {
// Drain the frame channel to ensure all items are removed
while (frameChannel.tryReceive().isSuccess) {
// Intentionally empty - just draining the channel
}
}
/**
* Opens a media file or URL for playback
*
* @param uri The path to the media file or URL to open
*/
override fun openUri(uri: String) {
if (disposal.isRequested) return
lastUri = uri
playbackSpeed = 1.0f
scope.launch {
try {
// Wait for initialization to complete with a timeout
withTimeout(10_000) { initReady.await() }
// Here the native instance is guaranteed to be non-null
openUriInternal(uri)
} catch (_: TimeoutCancellationException) {
setError("Player initialization timed out after 10 s.")
} catch (e: Exception) {
setError("Error while waiting for initialization: ${e.message}")
}
}
}
/**
* Internal implementation of openUri that assumes the player is initialized
*
* @param uri The path to the media file or URL to open
*/
private fun openUriInternal(uri: String) {
scope.launch {
mediaOperationMutex.withLock {
try {
isLoading = true
// Stop playback and release existing resources
val wasPlaying = _isPlaying
val instance = videoPlayerInstance
if (instance == null) {
setError("Video player instance is null")
return@withLock
}
if (wasPlaying) {
player.SetPlaybackState(instance, false, false)
_isPlaying = false
delay(50)
}
videoJob?.cancelAndJoin()
releaseAllResources()
player.CloseMedia(instance)
_currentTime = 0.0
_progress = 0f
_duration = 0.0
_metadata = VideoMetadata()
_hasMedia = false
userPaused = false
// Check if the file or URL is valid
if (!uri.startsWith("http", ignoreCase = true) && !File(uri).exists()) {
setError("File not found: $uri")
return@withLock
}
// Open the media
val hrOpen = player.OpenMedia(instance, WString(uri))
if (hrOpen < 0) {
setError("Failed to open media (hr=0x${hrOpen.toString(16)}): $uri")
return@withLock
}
// Get the video dimensions
val wRef = IntByReference()
val hRef = IntByReference()
player.GetVideoSize(instance, wRef, hRef)
if (wRef.value <= 0 || hRef.value <= 0) {
setError("Failed to retrieve video size")
player.CloseMedia(instance)
return@withLock
}
videoWidth = wRef.value
videoHeight = hRef.value
// Calculate the buffer size for frames
frameBufferSize = videoWidth * videoHeight * 4
// Allocate the shared buffer
sharedFrameBuffer = ByteArray(frameBufferSize)
// Get the media duration
val durationRef = LongByReference()
val hrDuration = player.GetMediaDuration(instance, durationRef)
if (hrDuration < 0) {
setError("Failed to retrieve duration (hr=0x${hrDuration.toString(16)})")
player.CloseMedia(instance)
return@withLock
}
_duration = durationRef.value / 10000000.0
// Retrieve metadata using the native function
val retrievedMetadata = MediaFoundationLib.getVideoMetadata(instance)
if (retrievedMetadata != null) {
_metadata = retrievedMetadata
} else {
// If metadata retrieval failed, create a basic metadata object with what we know
_metadata = VideoMetadata(
width = videoWidth,
height = videoHeight,
duration = (_duration * 1000).toLong() // Convert to milliseconds
)
}
// Set _hasMedia to true only if everything succeeded
_hasMedia = true
// Explicitly seek to the beginning of the video
val hrSeek = player.SeekMedia(instance, 0)
if (hrSeek < 0) {
windowsLogger.e { "Failed to seek to beginning (hr=0x${hrSeek.toString(16)})" }
}
// Start video processing
videoJob = scope.launch {
launch { produceFrames() }
launch { consumeFrames() }
}
// Start a task to update audio levels
audioLevelsJob = scope.launch {
while (isActive && _hasMedia) {
updateAudioLevels()
delay(50)
}
}
// Restore the volume setting for this instance
val storedVolume = instanceVolumes[instance]
if (storedVolume != null) {
val volumeRef = FloatByReference()
val hr = player.GetAudioVolume(instance, volumeRef)
if (hr >= 0 && storedVolume != volumeRef.value) {
val setHr = player.SetAudioVolume(instance, storedVolume)
if (setHr < 0) {
windowsLogger.e { "Error restoring volume (hr=0x${setHr.toString(16)})" }
}
}
}
delay(100)
play()
} catch (e: Exception) {
setError("Error while opening media: ${e.message}")
_hasMedia = false
} finally {
if (!_hasMedia) isLoading = false
}
}
}
}
/**
* Updates the audio level meters
*/
private suspend fun updateAudioLevels() {
mediaOperationMutex.withLock {
videoPlayerInstance?.let { instance ->
val leftRef = FloatByReference()
val rightRef = FloatByReference()
val hr = player.GetAudioLevels(instance, leftRef, rightRef)
if (hr >= 0) {
_leftLevel = leftRef.value
_rightLevel = rightRef.value
}
}
}
}
private suspend fun produceFrames() {
while (scope.isActive && _hasMedia) {
val instance = videoPlayerInstance ?: break
if (player.IsEOF(instance)) {
if (loop) {
try {
userPaused = false // Reset userPaused when looping
seekTo(0f)
play()
} catch (e: Exception) {
setError("Error during SeekMedia for loop: ${e.message}")
}
} else {
pause()
break
}
}
try {
waitForPlaybackState()
} catch (e: CancellationException) {
break
}
if (waitIfResizing()) {
continue
}
try {
val ptrRef = PointerByReference()
val sizeRef = IntByReference()
val readResult = player.ReadVideoFrame(instance, ptrRef, sizeRef)
if (readResult < 0 || ptrRef.value == null || sizeRef.value <= 0) {
yield()
continue
}
// For 4K videos, we need to be careful with memory allocation
// Only allocate a new buffer if absolutely necessary
if (sharedFrameBuffer == null) {
// First allocation
sharedFrameBuffer = ByteArray(frameBufferSize)
} else if (sharedFrameBuffer!!.size < frameBufferSize) {
// Buffer is too small, release old one before allocating new one
sharedFrameBuffer = null
System.gc() // Hint to garbage collector
delay(10) // Give GC a chance to run
sharedFrameBuffer = ByteArray(frameBufferSize)
}
// Use the shared buffer with null safety check
val sharedBuffer = sharedFrameBuffer ?: run {
// Fallback if buffer is null (shouldn't happen)
ByteArray(frameBufferSize).also { sharedFrameBuffer = it }
}
try {
val buffer = ptrRef.value.getByteBuffer(0, sizeRef.value.toLong())
val copySize = min(sizeRef.value, frameBufferSize)
if (buffer != null && copySize > 0) {
buffer.get(sharedBuffer, 0, copySize)
}
} catch (e: Exception) {
setError("Error copying frame data: ${e.message}")
delay(100)
continue
}
player.UnlockVideoFrame(instance)
var bitmap = frameBitmapRecycler
if (bitmap == null) {
bitmap = Bitmap().apply {
allocPixels(createVideoImageInfo())
}
frameBitmapRecycler = bitmap
}
try {
bitmap.installPixels(
createVideoImageInfo(),
sharedBuffer,
videoWidth * 4
)
val frameBitmap = bitmap
val posRef = LongByReference()
val frameTime = if (player.GetMediaPosition(instance, posRef) >= 0) {
posRef.value / 10000000.0
} else {
0.0
}
frameChannel.trySend(FrameData(frameBitmap, frameTime))
frameBitmapRecycler = null
} catch (e: Exception) {
windowsLogger.e { "Error processing frame bitmap: ${e.message}" }
frameBitmapRecycler = bitmap
}
delay(1)
} catch (e: CancellationException) {
break
} catch (e: Exception) {
if (scope.isActive && _hasMedia) {
setError("Error while reading a frame: ${e.message}")
}
delay(100)
}
}
}
private suspend fun consumeFrames() {
// Timeout mechanism to prevent getting stuck in loading state
var frameReceived = false
var loadingTimeout = 0
while (scope.isActive && _hasMedia) {
try {
waitForPlaybackState()
} catch (e: CancellationException) {
break
}
if (waitIfResizing()) {
continue
}
try {
val frameData = frameChannel.tryReceive().getOrNull() ?: run {
// If we're still loading and haven't received a frame yet, increment timeout counter
if (isLoading && !frameReceived) {
loadingTimeout++
// After ~3 seconds (16ms * 200) of no frames while loading, force isLoading to false
if (loadingTimeout > 200) {
windowsLogger.w { "No frames received for 3 seconds, forcing isLoading to false" }
isLoading = false
loadingTimeout = 0
}
}
delay(16)
return@run null
} ?: continue
// Reset timeout counter and mark that we've received a frame
loadingTimeout = 0
frameReceived = true
bitmapLock.write {
_currentFrame?.let { oldBitmap ->
if (frameBitmapRecycler == null) {
frameBitmapRecycler = oldBitmap
} else {
oldBitmap.close()
}
}
_currentFrame = frameData.bitmap
// Update the currentFrameState with the new frame
currentFrameState.value = frameData.bitmap.asComposeImageBitmap()
}
_currentTime = frameData.timestamp
_progress = (_currentTime / _duration).toFloat().coerceIn(0f, 1f)
isLoading = false // Once frames start arriving, set isLoading to false
delay(1)
} catch (e: CancellationException) {
break
} catch (e: Exception) {
if (scope.isActive && _hasMedia) {
setError("Error while processing a frame: ${e.message}")
}
delay(100)
}
}
}
/**
* Starts or resumes playback
* If no media is loaded but a previous URI exists, it will try to open and play it
*/
override fun play() {
if (disposal.isRequested) return
if (!readyForPlayback()) {
lastUri?.takeIf { it.isNotEmpty() }?.let { uri ->
scope.launch {
openUri(uri)
delay(100)
if (readyForPlayback()) {
executeMediaOperation(
operation = "play after init",
precondition = true
) {
setPlaybackState(true, "Error while starting playback after initialization")
}
}
}
}
return
}
executeMediaOperation(
operation = "play",
precondition = true
) {
userPaused = false
setPlaybackState(true, "Error while starting playback")
if (_hasMedia && (videoJob == null || videoJob?.isActive == false)) {
videoJob = scope.launch {
launch { produceFrames() }
launch { consumeFrames() }
}
}
// Restore the volume setting for this instance
val instance = videoPlayerInstance
if (instance != null) {
val storedVolume = instanceVolumes[instance]
if (storedVolume != null) {
val volumeRef = FloatByReference()
val hr = player.GetAudioVolume(instance, volumeRef)
if (hr >= 0 && storedVolume != volumeRef.value) {
val setHr = player.SetAudioVolume(instance, storedVolume)
if (setHr < 0) {
windowsLogger.e { "Error restoring volume during play (hr=0x${setHr.toString(16)})" }
}
}
}
}
}
}
/**
* Pauses playback if currently playing
*/
override fun pause() {
if (disposal.isRequested) return
executeMediaOperation(
operation = "pause",
precondition = _isPlaying
) {
userPaused = true
setPlaybackState(false, "Error while pausing playback")
}
}
/**
* Stops playback and releases media resources
* This will close the media file but keep the player instance
*/
override fun stop() {
if (disposal.isRequested) return
executeMediaOperation(
operation = "stop"
) {
setPlaybackState(false, "Error while stopping playback", true)
delay(50)
videoJob?.cancelAndJoin()
releaseAllResources()
_hasMedia = false
_progress = 0f
_currentTime = 0.0
_duration = 0.0
isLoading = false
errorMessage = null
_error = null
userPaused = false
videoPlayerInstance?.let { instance ->
player.CloseMedia(instance)
}
}
}
override fun seekTo(value: Float) {
if (disposal.isRequested) return
executeMediaOperation(
operation = "seek",
precondition = _hasMedia && videoPlayerInstance != null
) {
val instance = videoPlayerInstance
if (instance != null) {
try {
isLoading = true
// If the video was playing before seeking, we should reset userPaused
if (_isPlaying) {
userPaused = false
}
videoJob?.cancelAndJoin()
clearFrameChannel()
// For 4K videos, we need to be careful with memory allocation
// Only allocate a new buffer if absolutely necessary
if (sharedFrameBuffer == null) {
// First allocation
sharedFrameBuffer = ByteArray(frameBufferSize)
} else if (sharedFrameBuffer!!.size < frameBufferSize) {
// Buffer is too small, release old one before allocating new one
sharedFrameBuffer = null
System.gc() // Hint to garbage collector
delay(10) // Give GC a chance to run
sharedFrameBuffer = ByteArray(frameBufferSize)
}
// If buffer exists and is large enough, reuse it
val targetPos = (_duration * (value / 1000f) * 10000000).toLong()
var hr = player.SeekMedia(instance, targetPos)
if (hr < 0) {
delay(50)
hr = player.SeekMedia(instance, targetPos)
if (hr < 0) {
setError("Seek failed (hr=0x${hr.toString(16)})")
return@executeMediaOperation
}
}
val posRef = LongByReference()
if (player.GetMediaPosition(instance, posRef) >= 0) {
_currentTime = posRef.value / 10000000.0
_progress = (_currentTime / _duration).toFloat().coerceIn(0f, 1f)
}
videoJob = scope.launch {
launch { produceFrames() }
launch { consumeFrames() }
}
delay(8)
} catch (e: Exception) {
setError("Error during seek: ${e.message}")
} finally {
isLoading = false
}
}
}
}
/**
* Called when the player surface is resized
* Temporarily pauses frame processing to avoid artifacts during resize
* For 4K videos, we need a longer delay to prevent memory pressure
*/
fun onResized() {
isResizing.set(true)
scope.launch {
try {
// Clear frame channel to stop processing frames during resize
clearFrameChannel()
// Release shared frame buffer to reduce memory pressure during resize
// This is especially important for 4K videos
sharedFrameBuffer = null
// Force garbage collection to free up memory
System.gc()
} finally {
resizeJob?.cancel()
resizeJob = scope.launch {
// Increased delay for 4K videos (was 200ms)
delay(500)
isResizing.set(false)
}
}
}
}
/**
* Sets an error state with the given message
*
* @param msg The error message
*/
private fun setError(msg: String) {
_error = VideoPlayerError.UnknownError(msg)
errorMessage = msg
isLoading = false
windowsLogger.e { msg }
}
/**
* Creates an ImageInfo object for the current video dimensions
*
* @return ImageInfo configured for the current video frame
*/
private fun createVideoImageInfo() =
ImageInfo(videoWidth, videoHeight, ColorType.BGRA_8888, ColorAlphaType.OPAQUE)
/**
* Sets the playback state (playing or paused)
*
* @param playing True to start playback, false to pause
* @param errorMessage Error message to display if the operation fails
* @param bStop True to stop playback completely, false to pause
* @return True if the operation succeeded, false otherwise
*/
private fun setPlaybackState(playing: Boolean, errorMessage: String, bStop: Boolean = false): Boolean {
return videoPlayerInstance?.let { instance ->
for (attempt in 1..3) {
val res = player.SetPlaybackState(instance, playing, bStop)
if (res >= 0) {
_isPlaying = playing
_error?.let { clearError() }
return true
}
if (attempt == 3) {
setError("$errorMessage (hr=0x${res.toString(16)}) after $attempt attempts")
}
}
false
} ?: run {
setError("$errorMessage: No player instance")
false
}
}
/**
* Waits for the playback state to become active
* If playback doesn't start within 5 seconds, attempts to restart it
* unless the user has intentionally paused the video
*/
private suspend fun waitForPlaybackState() {
if (!_isPlaying) {
try {
withTimeoutOrNull(5000) {
snapshotFlow { _isPlaying }.filter { it }.first()
} ?: run {
// Only attempt to restart playback if the user hasn't intentionally paused
if (_hasMedia && videoPlayerInstance != null && !userPaused) {
setPlaybackState(true, "Error while restarting playback after timeout")
delay(100)
if (!_isPlaying) {
yield()
}
} else {
// If user paused, just yield to allow other coroutines to run
yield()
}
}
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
windowsLogger.e { "Error in waitForPlaybackState: ${e.message}" }
yield()
}
}
}
/**
* Waits if the player is currently resizing
* Uses a longer delay for 4K videos to reduce memory pressure
*
* @return True if resizing is in progress and we waited, false otherwise
*/
private suspend fun waitIfResizing(): Boolean {
if (isResizing.get()) {
try {
// Increased delay for 4K videos (was 100ms)
// This helps reduce memory pressure during resizing
delay(200)
} catch (e: CancellationException) {
throw e
}
return true
}
return false
}
/**
* Checks if the player is ready for playback
*
* @return True if the player is initialized and has media loaded, false otherwise
*/
private fun readyForPlayback(): Boolean {
return initReady.isCompleted && videoPlayerInstance != null && _hasMedia
}
/**
* Executes a media operation with proper error handling and mutex locking
*
* @param operation Name of the operation for error reporting
* @param precondition Condition that must be true for the operation to execute
* @param block The operation to execute
*/
private fun executeMediaOperation(
operation: String,
precondition: Boolean = true,
block: suspend () -> Unit
) {
if (!precondition) return
scope.launch {
mediaOperationMutex.withLock {
try {
block()
} catch (e: Exception) {
setError("Error during $operation: ${e.message}")
}
}
}
}
override fun selectSubtitleTrack(track: SubtitleTrack?) {
scope.launch {
withContext(Dispatchers.Main) {
currentSubtitleTrack = track
subtitlesEnabled = track != null
}
}
}
override fun disableSubtitles() {
scope.launch {
withContext(Dispatchers.Main) {
subtitlesEnabled = false
currentSubtitleTrack = null
}
}
}
/**
* Toggles the fullscreen state of the video player
*/
override fun toggleFullscreen() {
isFullscreen = !isFullscreen
}
}
vendor/compose-mediaplayer/src/jvmMain/kotlin/io/github/kdroidfilter/composemediaplayer/windows/WindowsVideoPlayerSurface.kt
- Source · implementation · 103 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
35: fun WindowsVideoPlayerSurface(
Exact file bytes / download · SHA-256 6bc11813f30e807ba9c2d7dd7d7bd69e7faf6d052c918310410304967821b779.
Complete file
package io.github.kdroidfilter.composemediaplayer.windows
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.Box
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.unit.IntSize
import io.github.kdroidfilter.composemediaplayer.subtitle.ComposeSubtitleLayer
import io.github.kdroidfilter.composemediaplayer.util.drawScaledImage
import io.github.kdroidfilter.composemediaplayer.util.toCanvasModifier
import io.github.kdroidfilter.composemediaplayer.util.toTimeMs
/**
* A composable function that provides a surface for rendering video frames
* within the Windows video player. It adjusts to size changes and ensures the video
* is displayed properly with respect to its aspect ratio.
*
* @param playerState The state of the Windows video player, used to manage video playback and rendering.
* @param modifier The modifier to be used to adjust the layout or styling of the composable.
* @param contentScale Controls how the video content should be scaled inside the surface.
* This affects how the video is displayed when its dimensions don't match
* the surface dimensions.
* @param overlay Optional composable content to be displayed on top of the video surface.
* This can be used to add custom controls, information, or any UI elements.
* @param isInFullscreenWindow Whether this surface is already being displayed in a fullscreen window.
*/
@Composable
fun WindowsVideoPlayerSurface(
playerState: WindowsVideoPlayerState,
modifier: Modifier = Modifier,
contentScale: ContentScale = ContentScale.Fit,
overlay: @Composable () -> Unit = {},
isInFullscreenWindow: Boolean = false,
) {
// Keep track of when this instance is first composed with this player state
val isFirstComposition = remember(playerState) { true }
// Only trigger resizing on first composition with this player state
LaunchedEffect(playerState) {
if (isFirstComposition) {
playerState.onResized()
}
}
Box(
modifier = modifier.onSizeChanged {
playerState.onResized()
},
contentAlignment = Alignment.Center
) {
// Only render video in this surface if we're not in fullscreen mode or if this is the fullscreen window
if (playerState.hasMedia && (!playerState.isFullscreen || isInFullscreenWindow)) {
// Force recomposition when currentFrameState changes
val currentFrame by remember(playerState) { playerState.currentFrameState }
currentFrame?.let { frame ->
Canvas(
modifier = contentScale.toCanvasModifier(playerState.aspectRatio,playerState.metadata.width,playerState.metadata.height)
) {
drawScaledImage(
image = frame,
dstSize = IntSize(size.width.toInt(), size.height.toInt()),
contentScale = contentScale
)
}
}
// Add Compose-based subtitle layer
if (playerState.subtitlesEnabled && playerState.currentSubtitleTrack != null) {
// Calculate current time in milliseconds
val currentTimeMs = (playerState.sliderPos / 1000f *
playerState.durationText.toTimeMs()).toLong()
// Calculate duration in milliseconds
val durationMs = playerState.durationText.toTimeMs()
ComposeSubtitleLayer(
currentTimeMs = currentTimeMs,
durationMs = durationMs,
isPlaying = playerState.isPlaying,
subtitleTrack = playerState.currentSubtitleTrack,
subtitlesEnabled = playerState.subtitlesEnabled,
textStyle = playerState.subtitleTextStyle,
backgroundColor = playerState.subtitleBackgroundColor
)
}
}
// Render the overlay content on top of the video
overlay()
}
if (playerState.isFullscreen && !isInFullscreenWindow) {
openFullscreenWindow(playerState, contentScale = contentScale, overlay = overlay)
}
}
vendor/compose-mediaplayer/src/jvmMain/resources/darwin-aarch64/libNativeVideoPlayer.dylib
- Source · configuration / resource · binary/gitlink lines.
- Manual task: Recreate the keys, identifiers, build relationships or resource names used by the consuming code. Preserve serialized names and schema compatibility; omit machine-specific values.
Exact file bytes / download · SHA-256 0368d1613bac50afeb663993b53de7ef581b3dc2847d3f5101fa68c0fb24ba96.
Retain this binary at the path above. Binary images, fonts, wrapper JARs and native/tooling assets have no text listing; use the download or the source archive. complete-source-end: #
vendor/compose-mediaplayer/src/jvmMain/resources/darwin-x86-64/libNativeVideoPlayer.dylib
- Source · configuration / resource · binary/gitlink lines.
- Manual task: Recreate the keys, identifiers, build relationships or resource names used by the consuming code. Preserve serialized names and schema compatibility; omit machine-specific values.
Exact file bytes / download · SHA-256 3df6f6cd2ed261f1fbf97d3c8c0790d24278ff9ebd2e89485cf9b7e5179c0757.
Retain this binary at the path above. Binary images, fonts, wrapper JARs and native/tooling assets have no text listing; use the download or the source archive. complete-source-end: #
vendor/compose-mediaplayer/src/jvmMain/resources/win32-arm64/NativeVideoPlayer.dll
- Source · configuration / resource · binary/gitlink lines.
- Manual task: Recreate the keys, identifiers, build relationships or resource names used by the consuming code. Preserve serialized names and schema compatibility; omit machine-specific values.
Exact file bytes / download · SHA-256 370ea4573e4fd698a92d3910a88fc7085ba78d107178cc2339ecc93f642d62ec.
Retain this binary at the path above. Binary images, fonts, wrapper JARs and native/tooling assets have no text listing; use the download or the source archive. complete-source-end: #
vendor/compose-mediaplayer/src/jvmMain/resources/win32-x86-64/NativeVideoPlayer.dll
- Source · configuration / resource · binary/gitlink lines.
- Manual task: Recreate the keys, identifiers, build relationships or resource names used by the consuming code. Preserve serialized names and schema compatibility; omit machine-specific values.
Exact file bytes / download · SHA-256 482efeef5fad28edf289c5481d87bbd35a66a0db5f47f258890789fe2d4f986c.
Retain this binary at the path above. Binary images, fonts, wrapper JARs and native/tooling assets have no text listing; use the download or the source archive. complete-source-end: #
vendor/compose-mediaplayer/src/jvmTest/kotlin/io/github/kdroidfilter/composemediaplayer/VideoPlayerStateTest.kt
- Source · test / fixture · 197 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
18: class VideoPlayerStateTest {
25: private fun isGStreamerAvailable(): Boolean {
53: fun testCreateVideoPlayerState() {
84: fun testVolumeControl() {
115: fun testLoopSetting() {
142: fun testFullscreenToggle() {
169: fun testErrorHandling() {
Exact file bytes / download · SHA-256 243a1a2f55c0dfa5c5fd72419ca719fb9f9f6ab8e31675d3a3978af6cf167198.
Complete file
package io.github.kdroidfilter.composemediaplayer
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
import kotlin.test.assertFalse
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.delay
import com.sun.jna.Platform
import org.freedesktop.gstreamer.ElementFactory
import org.freedesktop.gstreamer.Gst
import org.freedesktop.gstreamer.Version
/**
* Tests for the JVM implementation of VideoPlayerState
*/
class VideoPlayerStateTest {
/**
* Checks if GStreamer is available and the playbin element can be created.
* This is used to skip tests when GStreamer is not properly installed or configured.
* GStreamer is only checked on Linux platforms.
*/
private fun isGStreamerAvailable(): Boolean {
// Only check for GStreamer on Linux platforms
if (!Platform.isLinux()) {
println("Skipping GStreamer check: Not on Linux platform")
return false
}
try {
// Try to initialize GStreamer if it's not already initialized
if (!Gst.isInitialized()) {
Gst.init(Version.BASELINE, "ComposeGStreamerPlayerTest")
}
// Try to create a playbin element
val element = ElementFactory.make("playbin", "testPlaybin")
val isAvailable = element != null
element?.dispose()
return isAvailable
} catch (e: Exception) {
println("GStreamer is not available: ${e.message}")
return false
}
}
/**
* Test the creation of VideoPlayerState
*/
@Test
fun testCreateVideoPlayerState() {
// Skip test if GStreamer is not available
if (!isGStreamerAvailable()) {
println("Skipping test: GStreamer is not available")
return
}
val playerState = VideoPlayerState()
// Verify the player state is initialized correctly
assertNotNull(playerState)
assertNotNull(playerState.delegate)
assertFalse(playerState.hasMedia)
assertFalse(playerState.isPlaying)
assertEquals(0f, playerState.sliderPos)
assertEquals(1f, playerState.volume)
assertFalse(playerState.loop)
assertEquals("00:00", playerState.positionText)
assertEquals("00:00", playerState.durationText)
assertEquals(0f, playerState.leftLevel)
assertEquals(0f, playerState.rightLevel)
assertFalse(playerState.isFullscreen)
// Clean up
playerState.dispose()
}
/**
* Test volume control
*/
@Test
fun testVolumeControl() {
// Skip test if GStreamer is not available
if (!isGStreamerAvailable()) {
println("Skipping test: GStreamer is not available")
return
}
val playerState = VideoPlayerState()
// Test initial volume
assertEquals(1f, playerState.volume)
// Test setting volume
playerState.volume = 0.5f
assertEquals(0.5f, playerState.volume)
// Test volume bounds
playerState.volume = -0.1f
assertEquals(0f, playerState.volume, "Volume should be clamped to 0")
playerState.volume = 1.5f
assertEquals(1f, playerState.volume, "Volume should be clamped to 1")
// Clean up
playerState.dispose()
}
/**
* Test loop setting
*/
@Test
fun testLoopSetting() {
// Skip test if GStreamer is not available
if (!isGStreamerAvailable()) {
println("Skipping test: GStreamer is not available")
return
}
val playerState = VideoPlayerState()
// Test initial loop setting
assertFalse(playerState.loop)
// Test setting loop
playerState.loop = true
assertTrue(playerState.loop)
playerState.loop = false
assertFalse(playerState.loop)
// Clean up
playerState.dispose()
}
/**
* Test fullscreen toggle
*/
@Test
fun testFullscreenToggle() {
// Skip test if GStreamer is not available
if (!isGStreamerAvailable()) {
println("Skipping test: GStreamer is not available")
return
}
val playerState = VideoPlayerState()
// Test initial fullscreen state
assertFalse(playerState.isFullscreen)
// Test toggling fullscreen
playerState.toggleFullscreen()
assertTrue(playerState.isFullscreen)
playerState.toggleFullscreen()
assertFalse(playerState.isFullscreen)
// Clean up
playerState.dispose()
}
/**
* Test error handling
*/
@Test
fun testErrorHandling() {
// Skip test if GStreamer is not available
if (!isGStreamerAvailable()) {
println("Skipping test: GStreamer is not available")
return
}
val playerState = VideoPlayerState()
// Initially there should be no error
assertEquals(null, playerState.error)
// Test opening a non-existent file (should cause an error)
runBlocking {
playerState.openUri("non_existent_file.mp4")
delay(500) // Give some time for the error to be set
}
// There should be an error now
assertNotNull(playerState.error)
// Test clearing the error
playerState.clearError()
assertEquals(null, playerState.error)
// Clean up
playerState.dispose()
}
}
vendor/compose-mediaplayer/src/jvmTest/kotlin/io/github/kdroidfilter/composemediaplayer/VideoPlayerSurfaceTest.kt
- Source · test / fixture · 29 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
15: class VideoPlayerSurfaceTest {
22: fun testVideoPlayerSurfaceExists() {
Exact file bytes / download · SHA-256 487c9bdfff15902fecc1f635b0f3898865a8e7bfb4a94abc36475bcfb489cedd.
Complete file
package io.github.kdroidfilter.composemediaplayer
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
/**
* Tests for the JVM implementation of VideoPlayerSurface
*
* Note: Since we can't easily test the actual rendering of the surface in a unit test,
* we're just testing that the VideoPlayerSurface function exists and can be referenced.
* More comprehensive testing would require integration tests with a real UI.
*/
class VideoPlayerSurfaceTest {
/**
* Test that the VideoPlayerSurface function exists.
* This is a simple existence test to ensure the function is available.
*/
@Test
fun testVideoPlayerSurfaceExists() {
// This test doesn't actually call the function, it just verifies
// that the class exists and can be instantiated.
// Since we can't easily test Compose functions without the proper setup,
// we'll just assert true to make the test pass.
assertTrue(true, "VideoPlayerSurface function should exist")
}
}
vendor/compose-mediaplayer/src/jvmTest/kotlin/io/github/kdroidfilter/composemediaplayer/common/SubtitleTrackTest.kt
- Source · test / fixture · 90 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
11: class SubtitleTrackTest {
17: fun testCreateSubtitleTrack() {
35: fun testSubtitleTrackCopy() {
63: fun testSubtitleTrackEquality() {
Exact file bytes / download · SHA-256 57b7d8226b56c775de399a3b061c61580a2fdf3b5d5f0326115d03a9063d26d3.
Complete file
package io.github.kdroidfilter.composemediaplayer.common
import io.github.kdroidfilter.composemediaplayer.SubtitleTrack
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
/**
* Tests for the SubtitleTrack class
*/
class SubtitleTrackTest {
/**
* Test the creation of SubtitleTrack
*/
@Test
fun testCreateSubtitleTrack() {
val track = SubtitleTrack(
label = "English",
language = "en",
src = "subtitles/english.vtt"
)
// Verify the track is initialized correctly
assertNotNull(track)
assertEquals("English", track.label)
assertEquals("en", track.language)
assertEquals("subtitles/english.vtt", track.src)
}
/**
* Test data class copy functionality
*/
@Test
fun testSubtitleTrackCopy() {
val track = SubtitleTrack(
label = "English",
language = "en",
src = "subtitles/english.vtt"
)
// Create a copy with some modified properties
val copy = track.copy(
label = "English (US)",
src = "subtitles/english_us.vtt"
)
// Verify the original track is unchanged
assertEquals("English", track.label)
assertEquals("en", track.language)
assertEquals("subtitles/english.vtt", track.src)
// Verify the copy has the expected properties
assertEquals("English (US)", copy.label)
assertEquals("en", copy.language)
assertEquals("subtitles/english_us.vtt", copy.src)
}
/**
* Test data class equality
*/
@Test
fun testSubtitleTrackEquality() {
val track1 = SubtitleTrack(
label = "English",
language = "en",
src = "subtitles/english.vtt"
)
val track2 = SubtitleTrack(
label = "English",
language = "en",
src = "subtitles/english.vtt"
)
val track3 = SubtitleTrack(
label = "French",
language = "fr",
src = "subtitles/french.vtt"
)
// Verify equality works as expected
assertEquals(track1, track2)
assertEquals(track1.hashCode(), track2.hashCode())
// Verify inequality works as expected
assert(track1 != track3)
assert(track1.hashCode() != track3.hashCode())
}
}
vendor/compose-mediaplayer/src/jvmTest/kotlin/io/github/kdroidfilter/composemediaplayer/common/VideoMetadataTest.kt
- Source · test / fixture · 117 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
12: class VideoMetadataTest {
18: fun testCreateVideoMetadataWithDefaults() {
38: fun testCreateVideoMetadataWithValues() {
67: fun testMetadataProperties() {
97: fun testMetadataCopy() {
Exact file bytes / download · SHA-256 74910fc0cbc51d2a63de9b8299e1d997fd0948a0911c36556f297200bfff81eb.
Complete file
package io.github.kdroidfilter.composemediaplayer.common
import io.github.kdroidfilter.composemediaplayer.VideoMetadata
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertNull
/**
* Tests for the VideoMetadata class
*/
class VideoMetadataTest {
/**
* Test the creation of VideoMetadata with default values
*/
@Test
fun testCreateVideoMetadataWithDefaults() {
val metadata = VideoMetadata()
// Verify the metadata is initialized with null values
assertNotNull(metadata)
assertNull(metadata.title)
assertNull(metadata.duration)
assertNull(metadata.width)
assertNull(metadata.height)
assertNull(metadata.bitrate)
assertNull(metadata.frameRate)
assertNull(metadata.mimeType)
assertNull(metadata.audioChannels)
assertNull(metadata.audioSampleRate)
}
/**
* Test the creation of VideoMetadata with specific values
*/
@Test
fun testCreateVideoMetadataWithValues() {
val metadata = VideoMetadata(
title = "Test Title",
duration = 120000L,
width = 1920,
height = 1080,
bitrate = 5000000L,
frameRate = 30.0f,
mimeType = "video/mp4",
audioChannels = 2,
audioSampleRate = 44100
)
// Verify the metadata properties
assertEquals("Test Title", metadata.title)
assertEquals(120000L, metadata.duration)
assertEquals(1920, metadata.width)
assertEquals(1080, metadata.height)
assertEquals(5000000L, metadata.bitrate)
assertEquals(30.0f, metadata.frameRate)
assertEquals("video/mp4", metadata.mimeType)
assertEquals(2, metadata.audioChannels)
assertEquals(44100, metadata.audioSampleRate)
}
/**
* Test setting and getting metadata properties
*/
@Test
fun testMetadataProperties() {
val metadata = VideoMetadata()
// Set metadata properties
metadata.title = "Test Title"
metadata.duration = 120000L
metadata.width = 1920
metadata.height = 1080
metadata.bitrate = 5000000L
metadata.frameRate = 30.0f
metadata.mimeType = "video/mp4"
metadata.audioChannels = 2
metadata.audioSampleRate = 44100
// Verify the metadata properties
assertEquals("Test Title", metadata.title)
assertEquals(120000L, metadata.duration)
assertEquals(1920, metadata.width)
assertEquals(1080, metadata.height)
assertEquals(5000000L, metadata.bitrate)
assertEquals(30.0f, metadata.frameRate)
assertEquals("video/mp4", metadata.mimeType)
assertEquals(2, metadata.audioChannels)
assertEquals(44100, metadata.audioSampleRate)
}
/**
* Test data class copy functionality
*/
@Test
fun testMetadataCopy() {
val metadata = VideoMetadata(
title = "Original Title",
duration = 60000L
)
// Create a copy with some modified properties
val copy = metadata.copy(
title = "New Title",
duration = 90000L
)
// Verify the original metadata is unchanged
assertEquals("Original Title", metadata.title)
assertEquals(60000L, metadata.duration)
// Verify the copy has the expected properties
assertEquals("New Title", copy.title)
assertEquals(90000L, copy.duration)
}
}
vendor/compose-mediaplayer/src/jvmTest/kotlin/io/github/kdroidfilter/composemediaplayer/common/VideoPlayerErrorTest.kt
- Source · test / fixture · 137 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
12: class VideoPlayerErrorTest {
18: fun testCodecError() {
37: fun testNetworkError() {
56: fun testSourceError() {
75: fun testUnknownError() {
94: fun testDifferentErrorTypes() {
113: fun testWhenExpression() {
Exact file bytes / download · SHA-256 94dd4583b4cadfd950ba940743649c3ea15790052abfeb33915dbebb74456f63.
Complete file
package io.github.kdroidfilter.composemediaplayer.common
import io.github.kdroidfilter.composemediaplayer.VideoPlayerError
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotEquals
import kotlin.test.assertTrue
/**
* Tests for the VideoPlayerError class
*/
class VideoPlayerErrorTest {
/**
* Test the creation of CodecError
*/
@Test
fun testCodecError() {
val error = VideoPlayerError.CodecError("Unsupported codec")
// Verify the error is initialized correctly
assertTrue(error is VideoPlayerError.CodecError)
assertEquals("Unsupported codec", error.message)
// Test equality
val sameError = VideoPlayerError.CodecError("Unsupported codec")
val differentError = VideoPlayerError.CodecError("Different codec error")
assertEquals(error, sameError)
assertNotEquals(error, differentError)
}
/**
* Test the creation of NetworkError
*/
@Test
fun testNetworkError() {
val error = VideoPlayerError.NetworkError("Connection timeout")
// Verify the error is initialized correctly
assertTrue(error is VideoPlayerError.NetworkError)
assertEquals("Connection timeout", error.message)
// Test equality
val sameError = VideoPlayerError.NetworkError("Connection timeout")
val differentError = VideoPlayerError.NetworkError("Network unavailable")
assertEquals(error, sameError)
assertNotEquals(error, differentError)
}
/**
* Test the creation of SourceError
*/
@Test
fun testSourceError() {
val error = VideoPlayerError.SourceError("File not found")
// Verify the error is initialized correctly
assertTrue(error is VideoPlayerError.SourceError)
assertEquals("File not found", error.message)
// Test equality
val sameError = VideoPlayerError.SourceError("File not found")
val differentError = VideoPlayerError.SourceError("Invalid URL")
assertEquals(error, sameError)
assertNotEquals(error, differentError)
}
/**
* Test the creation of UnknownError
*/
@Test
fun testUnknownError() {
val error = VideoPlayerError.UnknownError("Unexpected error")
// Verify the error is initialized correctly
assertTrue(error is VideoPlayerError.UnknownError)
assertEquals("Unexpected error", error.message)
// Test equality
val sameError = VideoPlayerError.UnknownError("Unexpected error")
val differentError = VideoPlayerError.UnknownError("Another error")
assertEquals(error, sameError)
assertNotEquals(error, differentError)
}
/**
* Test that different error types are not equal
*/
@Test
fun testDifferentErrorTypes() {
val codecError = VideoPlayerError.CodecError("Codec error")
val networkError = VideoPlayerError.NetworkError("Network error")
val sourceError = VideoPlayerError.SourceError("Source error")
val unknownError = VideoPlayerError.UnknownError("Unknown error")
// Verify different error types are not equal
assertTrue(codecError != networkError)
assertTrue(codecError != sourceError)
assertTrue(codecError != unknownError)
assertTrue(networkError != sourceError)
assertTrue(networkError != unknownError)
assertTrue(sourceError != unknownError)
}
/**
* Test when used in a when expression
*/
@Test
fun testWhenExpression() {
val errors = listOf(
VideoPlayerError.CodecError("Codec error"),
VideoPlayerError.NetworkError("Network error"),
VideoPlayerError.SourceError("Source error"),
VideoPlayerError.UnknownError("Unknown error")
)
for (error in errors) {
val message = when (error) {
is VideoPlayerError.CodecError -> "Codec: ${error.message}"
is VideoPlayerError.NetworkError -> "Network: ${error.message}"
is VideoPlayerError.SourceError -> "Source: ${error.message}"
is VideoPlayerError.UnknownError -> "Unknown: ${error.message}"
}
when (error) {
is VideoPlayerError.CodecError -> assertEquals("Codec: Codec error", message)
is VideoPlayerError.NetworkError -> assertEquals("Network: Network error", message)
is VideoPlayerError.SourceError -> assertEquals("Source: Source error", message)
is VideoPlayerError.UnknownError -> assertEquals("Unknown: Unknown error", message)
}
}
}
}
vendor/compose-mediaplayer/src/jvmTest/kotlin/io/github/kdroidfilter/composemediaplayer/linux/LinuxVideoPlayerStateTest.kt
- Source · test / fixture · 181 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
29: class LinuxVideoPlayerStateTest {
37: fun setup() {
67: fun testCreateLinuxVideoPlayerState() {
92: fun testVolumeControl() {
117: fun testLoopSetting() {
138: fun testFullscreenToggle() {
159: fun testErrorHandling() {
Exact file bytes / download · SHA-256 8537fda7f7207843791b0f5cbecb50744be4ba0a3deaf14dd50cf90495f121c1.
Complete file
package io.github.kdroidfilter.composemediaplayer.linux
import io.github.kdroidfilter.composemediaplayer.PlatformVideoPlayerState
import io.github.kdroidfilter.composemediaplayer.VideoPlayerError
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.assertTrue
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.delay
import com.sun.jna.Platform
import org.junit.Before
import org.junit.Assume
import org.freedesktop.gstreamer.Gst
import org.freedesktop.gstreamer.Version
/**
* Tests for the Linux implementation of PlatformVideoPlayerState
*
* Note: These tests will only run on Linux platforms. On other platforms,
* the tests will be skipped.
*
* Additionally, these tests require GStreamer to be properly installed and
* the "playbin" element to be available. If GStreamer is not available,
* the tests will be skipped.
*/
class LinuxVideoPlayerStateTest {
/**
* Setup method to check if GStreamer is available before running tests.
* If GStreamer is not available or the "playbin" element is not found,
* the tests will be skipped.
*/
@Before
fun setup() {
// Skip test if not running on Linux
Assume.assumeTrue("Skipping Linux-specific test on non-Linux platform", Platform.isLinux())
// Try to initialize GStreamer
try {
// Initialize GStreamer
if (!Gst.isInitialized()) {
Gst.init(Version.BASELINE, "TestGStreamerPlayer")
}
// Try to create a "playbin" element to check if it's available
try {
val playbin = org.freedesktop.gstreamer.ElementFactory.make("playbin", "testplaybin")
Assume.assumeNotNull("GStreamer 'playbin' element not available", playbin)
playbin.dispose() // Clean up the test element
} catch (e: Exception) {
// If playbin creation fails, skip the test
Assume.assumeNoException("GStreamer 'playbin' element not available", e)
}
} catch (e: Exception) {
// If GStreamer initialization fails, skip the test
Assume.assumeNoException("GStreamer initialization failed", e)
}
}
/**
* Test the creation of LinuxVideoPlayerState
*/
@Test
fun testCreateLinuxVideoPlayerState() {
val playerState = LinuxVideoPlayerState()
// Verify the player state is initialized correctly
assertNotNull(playerState)
assertFalse(playerState.hasMedia)
assertFalse(playerState.isPlaying)
assertEquals(0f, playerState.sliderPos)
assertEquals(1f, playerState.volume)
assertFalse(playerState.loop)
assertEquals("00:00", playerState.positionText)
assertEquals("00:00", playerState.durationText)
assertEquals(0f, playerState.leftLevel)
assertEquals(0f, playerState.rightLevel)
assertFalse(playerState.isFullscreen)
assertNull(playerState.error)
// Clean up
playerState.dispose()
}
/**
* Test volume control
*/
@Test
fun testVolumeControl() {
val playerState = LinuxVideoPlayerState()
// Test initial volume
assertEquals(1f, playerState.volume)
// Test setting volume
playerState.volume = 0.5f
assertEquals(0.5f, playerState.volume)
// Test volume bounds
playerState.volume = -0.1f
assertEquals(0f, playerState.volume, "Volume should be clamped to 0")
playerState.volume = 1.5f
assertEquals(1f, playerState.volume, "Volume should be clamped to 1")
// Clean up
playerState.dispose()
}
/**
* Test loop setting
*/
@Test
fun testLoopSetting() {
val playerState = LinuxVideoPlayerState()
// Test initial loop setting
assertFalse(playerState.loop)
// Test setting loop
playerState.loop = true
assertTrue(playerState.loop)
playerState.loop = false
assertFalse(playerState.loop)
// Clean up
playerState.dispose()
}
/**
* Test fullscreen toggle
*/
@Test
fun testFullscreenToggle() {
val playerState = LinuxVideoPlayerState()
// Test initial fullscreen state
assertFalse(playerState.isFullscreen)
// Test toggling fullscreen
playerState.toggleFullscreen()
assertTrue(playerState.isFullscreen)
playerState.toggleFullscreen()
assertFalse(playerState.isFullscreen)
// Clean up
playerState.dispose()
}
/**
* Test error handling
*/
@Test
fun testErrorHandling() {
val playerState = LinuxVideoPlayerState()
// Initially there should be no error
assertNull(playerState.error)
// Test opening a non-existent file (should cause an error)
runBlocking {
playerState.openUri("non_existent_file.mp4")
delay(500) // Give some time for the error to be set
}
// There should be an error now
assertNotNull(playerState.error)
// Test clearing the error
playerState.clearError()
assertNull(playerState.error)
// Clean up
playerState.dispose()
}
}
vendor/compose-mediaplayer/src/jvmTest/kotlin/io/github/kdroidfilter/composemediaplayer/mac/MacVideoPlayerStateTest.kt
- Source · test / fixture · 171 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
21: class MacVideoPlayerStateTest {
27: fun testCreateMacVideoPlayerState() {
58: fun testVolumeControl() {
89: fun testLoopSetting() {
116: fun testFullscreenToggle() {
143: fun testErrorHandling() {
Exact file bytes / download · SHA-256 a3e8fa6b76212180e24a832e7f1a8e54a15a73c3368f9d89c0a722bd4bba853a.
Complete file
package io.github.kdroidfilter.composemediaplayer.mac
import io.github.kdroidfilter.composemediaplayer.PlatformVideoPlayerState
import io.github.kdroidfilter.composemediaplayer.VideoPlayerError
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.assertTrue
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.delay
import com.sun.jna.Platform
/**
* Tests for the Mac implementation of PlatformVideoPlayerState
*
* Note: These tests will only run on Mac platforms. On other platforms,
* the tests will be skipped.
*/
class MacVideoPlayerStateTest {
/**
* Test the creation of MacVideoPlayerState
*/
@Test
fun testCreateMacVideoPlayerState() {
// Skip test if not running on Mac
if (!Platform.isMac()) {
println("Skipping Mac-specific test on non-Mac platform")
return
}
val playerState = MacVideoPlayerState()
// Verify the player state is initialized correctly
assertNotNull(playerState)
assertFalse(playerState.hasMedia)
assertFalse(playerState.isPlaying)
assertEquals(0f, playerState.sliderPos)
assertEquals(1f, playerState.volume)
assertFalse(playerState.loop)
assertEquals("00:00", playerState.positionText)
assertEquals("00:00", playerState.durationText)
assertEquals(0f, playerState.leftLevel)
assertEquals(0f, playerState.rightLevel)
assertFalse(playerState.isFullscreen)
assertNull(playerState.error)
// Clean up
playerState.dispose()
}
/**
* Test volume control
*/
@Test
fun testVolumeControl() {
// Skip test if not running on Mac
if (!Platform.isMac()) {
println("Skipping Mac-specific test on non-Mac platform")
return
}
val playerState = MacVideoPlayerState()
// Test initial volume
assertEquals(1f, playerState.volume)
// Test setting volume
playerState.volume = 0.5f
assertEquals(0.5f, playerState.volume)
// Test volume bounds
playerState.volume = -0.1f
assertEquals(0f, playerState.volume, "Volume should be clamped to 0")
playerState.volume = 1.5f
assertEquals(1f, playerState.volume, "Volume should be clamped to 1")
// Clean up
playerState.dispose()
}
/**
* Test loop setting
*/
@Test
fun testLoopSetting() {
// Skip test if not running on Mac
if (!Platform.isMac()) {
println("Skipping Mac-specific test on non-Mac platform")
return
}
val playerState = MacVideoPlayerState()
// Test initial loop setting
assertFalse(playerState.loop)
// Test setting loop
playerState.loop = true
assertTrue(playerState.loop)
playerState.loop = false
assertFalse(playerState.loop)
// Clean up
playerState.dispose()
}
/**
* Test fullscreen toggle
*/
@Test
fun testFullscreenToggle() {
// Skip test if not running on Mac
if (!Platform.isMac()) {
println("Skipping Mac-specific test on non-Mac platform")
return
}
val playerState = MacVideoPlayerState()
// Test initial fullscreen state
assertFalse(playerState.isFullscreen)
// Test toggling fullscreen
playerState.toggleFullscreen()
assertTrue(playerState.isFullscreen)
playerState.toggleFullscreen()
assertFalse(playerState.isFullscreen)
// Clean up
playerState.dispose()
}
/**
* Test error handling
*/
@Test
fun testErrorHandling() {
// Skip test if not running on Mac
if (!Platform.isMac()) {
println("Skipping Mac-specific test on non-Mac platform")
return
}
val playerState = MacVideoPlayerState()
// Initially there should be no error
assertNull(playerState.error)
// Test opening a non-existent file (should cause an error)
runBlocking {
playerState.openUri("non_existent_file.mp4")
delay(500) // Give some time for the error to be set
}
// There should be an error now
assertNotNull(playerState.error)
// Test clearing the error
playerState.clearError()
assertNull(playerState.error)
// Clean up
playerState.dispose()
}
}
vendor/compose-mediaplayer/src/jvmTest/kotlin/io/github/kdroidfilter/composemediaplayer/subtitle/SrtParserTest.kt
- Source · test / fixture · 128 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
11: class SrtParserTest {
17: fun testParseSrtContent() {
60: fun testParseInvalidSrtContent() {
99: fun testActiveCues() {
Exact file bytes / download · SHA-256 c8b57564676c0623f566088a68c4277dcb15afbc17c521069a852574049966ae.
Complete file
package io.github.kdroidfilter.composemediaplayer.subtitle
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
/**
* Tests for the SrtParser class
*/
class SrtParserTest {
/**
* Test parsing a simple SRT subtitle file
*/
@Test
fun testParseSrtContent() {
// Sample SRT content
val srtContent = """
1
00:00:01,000 --> 00:00:04,000
This is the first subtitle
2
00:00:05,500 --> 00:00:07,500
This is the second subtitle
3
00:01:00,000 --> 00:01:30,000
This is the third subtitle
with multiple lines
""".trimIndent()
val subtitles = SrtParser.parse(srtContent)
// Verify the parsed subtitles
assertNotNull(subtitles)
assertEquals(3, subtitles.cues.size, "Should parse 3 subtitle cues")
// Check first subtitle
assertEquals(1000, subtitles.cues[0].startTime, "First subtitle should start at 1000ms")
assertEquals(4000, subtitles.cues[0].endTime, "First subtitle should end at 4000ms")
assertEquals("This is the first subtitle", subtitles.cues[0].text)
// Check second subtitle
assertEquals(5500, subtitles.cues[1].startTime, "Second subtitle should start at 5500ms")
assertEquals(7500, subtitles.cues[1].endTime, "Second subtitle should end at 7500ms")
assertEquals("This is the second subtitle", subtitles.cues[1].text)
// Check third subtitle (with multiple lines)
assertEquals(60000, subtitles.cues[2].startTime, "Third subtitle should start at 60000ms")
assertEquals(90000, subtitles.cues[2].endTime, "Third subtitle should end at 90000ms")
assertEquals("This is the third subtitle\nwith multiple lines", subtitles.cues[2].text)
}
/**
* Test parsing an SRT file with some invalid entries
*/
@Test
fun testParseInvalidSrtContent() {
// Sample SRT content with some invalid entries
val srtContent = """
Invalid line
1
00:00:01,000 --> 00:00:04,000
Valid subtitle
Not a sequence number
00:00:05,500 --> 00:00:07,500
This should be skipped
2
Invalid timing line
This should be skipped
3
00:01:00,000 --> 00:01:30,000
Valid subtitle again
""".trimIndent()
val subtitles = SrtParser.parse(srtContent)
// Verify the parsed subtitles
assertNotNull(subtitles)
assertEquals(2, subtitles.cues.size, "Should parse only 2 valid subtitle cues")
// Check first valid subtitle
assertEquals("Valid subtitle", subtitles.cues[0].text)
// Check second valid subtitle
assertEquals("Valid subtitle again", subtitles.cues[1].text)
}
/**
* Test the active cues functionality
*/
@Test
fun testActiveCues() {
// Sample SRT content
val srtContent = """
1
00:00:01,000 --> 00:00:04,000
First subtitle
2
00:00:05,000 --> 00:00:08,000
Second subtitle
""".trimIndent()
val subtitles = SrtParser.parse(srtContent)
// Test active cues at different times
val activeCuesAt500ms = subtitles.getActiveCues(500)
assertEquals(0, activeCuesAt500ms.size, "No subtitles should be active at 500ms")
val activeCuesAt2000ms = subtitles.getActiveCues(2000)
assertEquals(1, activeCuesAt2000ms.size, "One subtitle should be active at 2000ms")
assertEquals("First subtitle", activeCuesAt2000ms[0].text)
val activeCuesAt4500ms = subtitles.getActiveCues(4500)
assertEquals(0, activeCuesAt4500ms.size, "No subtitles should be active at 4500ms")
val activeCuesAt6000ms = subtitles.getActiveCues(6000)
assertEquals(1, activeCuesAt6000ms.size, "One subtitle should be active at 6000ms")
assertEquals("Second subtitle", activeCuesAt6000ms[0].text)
}
}
vendor/compose-mediaplayer/src/jvmTest/kotlin/io/github/kdroidfilter/composemediaplayer/windows/WindowsVideoPlayerStateTest.kt
- Source · test / fixture · 172 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
21: class WindowsVideoPlayerStateTest {
27: fun testCreateWindowsVideoPlayerState() {
58: fun testVolumeControl() {
89: fun testLoopSetting() {
116: fun testFullscreenToggle() {
143: fun testErrorHandling() {
Exact file bytes / download · SHA-256 8cba535660aed3c02195ae09bf2f24b363c674a69089fe359a1ab424b224fd76.
Complete file
package io.github.kdroidfilter.composemediaplayer.windows
import io.github.kdroidfilter.composemediaplayer.PlatformVideoPlayerState
import io.github.kdroidfilter.composemediaplayer.VideoPlayerError
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.assertTrue
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.delay
import com.sun.jna.Platform
/**
* Tests for the Windows implementation of PlatformVideoPlayerState
*
* Note: These tests will only run on Windows platforms. On other platforms,
* the tests will be skipped.
*/
class WindowsVideoPlayerStateTest {
/**
* Test the creation of WindowsVideoPlayerState
*/
@Test
fun testCreateWindowsVideoPlayerState() {
// Skip test if not running on Windows
if (!Platform.isWindows()) {
println("Skipping Windows-specific test on non-Windows platform")
return
}
val playerState = WindowsVideoPlayerState()
// Verify the player state is initialized correctly
assertNotNull(playerState)
assertFalse(playerState.hasMedia)
assertFalse(playerState.isPlaying)
assertEquals(0f, playerState.sliderPos)
assertEquals(1f, playerState.volume)
assertFalse(playerState.loop)
assertEquals("00:00", playerState.positionText)
assertEquals("00:00", playerState.durationText)
assertEquals(0f, playerState.leftLevel)
assertEquals(0f, playerState.rightLevel)
assertFalse(playerState.isFullscreen)
assertNull(playerState.error)
// Clean up
playerState.dispose()
}
/**
* Test volume control
*/
@Test
fun testVolumeControl() {
// Skip test if not running on Windows
if (!Platform.isWindows()) {
println("Skipping Windows-specific test on non-Windows platform")
return
}
val playerState = WindowsVideoPlayerState()
// Test initial volume
assertEquals(1f, playerState.volume)
// Test setting volume
playerState.volume = 0.5f
assertEquals(0.5f, playerState.volume)
// Test volume bounds
playerState.volume = -0.1f
assertEquals(0f, playerState.volume, "Volume should be clamped to 0")
playerState.volume = 1.5f
assertEquals(1f, playerState.volume, "Volume should be clamped to 1")
// Clean up
playerState.dispose()
}
/**
* Test loop setting
*/
@Test
fun testLoopSetting() {
// Skip test if not running on Windows
if (!Platform.isWindows()) {
println("Skipping Windows-specific test on non-Windows platform")
return
}
val playerState = WindowsVideoPlayerState()
// Test initial loop setting
assertFalse(playerState.loop)
// Test setting loop
playerState.loop = true
assertTrue(playerState.loop)
playerState.loop = false
assertFalse(playerState.loop)
// Clean up
playerState.dispose()
}
/**
* Test fullscreen toggle
*/
@Test
fun testFullscreenToggle() {
// Skip test if not running on Windows
if (!Platform.isWindows()) {
println("Skipping Windows-specific test on non-Windows platform")
return
}
val playerState = WindowsVideoPlayerState()
// Test initial fullscreen state
assertFalse(playerState.isFullscreen)
// Test toggling fullscreen
playerState.toggleFullscreen()
assertTrue(playerState.isFullscreen)
playerState.toggleFullscreen()
assertFalse(playerState.isFullscreen)
// Clean up
playerState.dispose()
}
/**
* Test error handling
*/
@Test
fun testErrorHandling() {
// Skip test if not running on Windows
if (!Platform.isWindows()) {
println("Skipping Windows-specific test on non-Windows platform")
return
}
val playerState = WindowsVideoPlayerState()
// Initially there should be no error
assertNull(playerState.error)
// Test opening a non-existent file (should cause an error)
runBlocking {
playerState.openUri("non_existent_file.mp4")
delay(500) // Give some time for the error to be set
}
// There should be an error now
assertNotNull(playerState.error)
assertTrue(playerState.error is VideoPlayerError.UnknownError)
// Test clearing the error
playerState.clearError()
assertNull(playerState.error)
// Clean up
playerState.dispose()
}
}
vendor/compose-mediaplayer/src/wasmJsMain/kotlin/io/github/kdroidfilter/composemediaplayer/AudioLevelProcessor.kt
- Source · implementation · 158 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
20: internal class AudioLevelProcessor(private val video: HTMLVideoElement) {
49: fun initialize(): Boolean {
102: suspend fun closeAndJoin() {
118: fun getAudioLevels(): Pair<Float, Float> {
144: fun convertToPercentage(level: Float): Float {
Exact file bytes / download · SHA-256 562415f821520852e0f9fda7679b8ff8654f7215b5d7a89725c5cfe41cfaf688.
Complete file
package io.github.kdroidfilter.composemediaplayer
import co.touchlab.kermit.Logger
import co.touchlab.kermit.Severity
import io.github.kdroidfilter.composemediaplayer.jsinterop.AnalyserNode
import io.github.kdroidfilter.composemediaplayer.jsinterop.AudioContext
import io.github.kdroidfilter.composemediaplayer.jsinterop.ChannelSplitterNode
import io.github.kdroidfilter.composemediaplayer.jsinterop.MediaElementAudioSourceNode
import kotlinx.coroutines.await
import org.khronos.webgl.Uint8Array
import org.khronos.webgl.get
import org.w3c.dom.HTMLVideoElement
/**
* Logger for WebAssembly audio level processor
*/
internal val wasmAudioLogger = Logger.withTag("WasmAudioProcessor")
.apply { Logger.setMinSeverity(Severity.Warn) }
internal class AudioLevelProcessor(private val video: HTMLVideoElement) {
private var initializationAttempted = false
private var initialized = false
private var audioContext: AudioContext? = null
private var sourceNode: MediaElementAudioSourceNode? = null
private var splitterNode: ChannelSplitterNode? = null
private var leftAnalyser: AnalyserNode? = null
private var rightAnalyser: AnalyserNode? = null
private var leftData: Uint8Array? = null
private var rightData: Uint8Array? = null
// Audio properties
private var _audioChannels: Int = 0
private var _audioSampleRate: Int = 0
// Getters for audio properties
val audioChannels: Int get() = _audioChannels
val audioSampleRate: Int get() = _audioSampleRate
/**
* Initializes Web Audio (creates a source, a splitter, etc.)
* In case of error (CORS), we simply return false => the video remains managed by HTML
* and audio levels will be set to 0
*
* @return true if initialization was successful, false if there was a CORS error
*/
fun initialize(): Boolean {
if (initializationAttempted) return initialized
initializationAttempted = true
val ctx = AudioContext()
audioContext = ctx
val source = try {
ctx.createMediaElementSource(video)
} catch (e: Throwable) {
wasmAudioLogger.w { "CORS/format error: Video doesn't have CORS headers. Audio levels will be set to 0. Error: ${e.message}" }
// Clean up the audio context since we won't be using it
return false
}
sourceNode = source
splitterNode = ctx.createChannelSplitter(2)
leftAnalyser = ctx.createAnalyser().apply { fftSize = 256 }
rightAnalyser = ctx.createAnalyser().apply { fftSize = 256 }
// Chaining
source.connect(splitterNode!!)
splitterNode!!.connect(leftAnalyser!!, 0, 0)
splitterNode!!.connect(rightAnalyser!!, 1, 0)
// To hear the sound via Web Audio
splitterNode!!.connect(ctx.destination)
val size = leftAnalyser!!.frequencyBinCount
leftData = Uint8Array(size)
rightData = Uint8Array(size)
// Extract audio properties
_audioSampleRate = ctx.sampleRate
_audioChannels = source.channelCount
initialized = true
wasmAudioLogger.d { "Web Audio successfully initialized and capturing audio. Sample rate: $_audioSampleRate Hz, Channels: $_audioChannels" }
return true
}
/**
* Returns (left%, right%) in range 0..100
*
* Uses a logarithmic scale to match the Mac implementation:
* 1. Calculate average level from frequency data
* 2. Normalize to 0..1 range
* 3. Convert to decibels: 20 * log10(level)
* 4. Normalize: ((db + 60) / 60).coerceIn(0f, 1f)
* 5. Convert to percentage: normalized * 100f
*/
suspend fun closeAndJoin() {
sourceNode?.disconnect()
splitterNode?.disconnect()
leftAnalyser?.disconnect()
rightAnalyser?.disconnect()
audioContext?.close()?.await<kotlin.js.JsAny?>()
audioContext = null
initialized = false
sourceNode = null
splitterNode = null
leftAnalyser = null
rightAnalyser = null
leftData = null
rightData = null
}
fun getAudioLevels(): Pair<Float, Float> {
val la = leftAnalyser ?: return 0f to 0f
val ra = rightAnalyser ?: return 0f to 0f
val lb = leftData ?: return 0f to 0f
val rb = rightData ?: return 0f to 0f
la.getByteFrequencyData(lb)
ra.getByteFrequencyData(rb)
var sumLeft = 0
for (i in 0 until lb.length) {
sumLeft += lb[i].toInt()
}
var sumRight = 0
for (i in 0 until rb.length) {
sumRight += rb[i].toInt()
}
val avgLeft = sumLeft.toFloat() / lb.length
val avgRight = sumRight.toFloat() / rb.length
// Normalize to 0..1 range
val normalizedLeft = avgLeft / 255f
val normalizedRight = avgRight / 255f
// Convert to logarithmic scale (same as Mac implementation)
fun convertToPercentage(level: Float): Float {
if (level <= 0f) return 0f
// Conversion to decibels: 20 * log10(level)
val db = 20 * kotlin.math.log10(level)
// Assume that -60 dB corresponds to silence and 0 dB to maximum level.
val normalized = ((db + 60) / 60).coerceIn(0f, 1f)
return normalized * 100f
}
val leftPercent = convertToPercentage(normalizedLeft)
val rightPercent = convertToPercentage(normalizedRight)
return leftPercent to rightPercent
}
}
vendor/compose-mediaplayer/src/wasmJsMain/kotlin/io/github/kdroidfilter/composemediaplayer/BrowserVideoBinding.kt
- Source · implementation · 84 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
13: internal class BrowserVideoBinding(
42: fun listen(name: String, listener: (Event) -> Unit) {
48: fun dispose() = disposal.dispose()
49: suspend fun disposeAndJoin() = disposal.disposeAndJoin()
50: fun requestPictureInPicture(): Boolean {
74: internal fun usablePictureInPicture(video: HTMLVideoElement): Boolean = js(
78: private fun toggleOwnedPictureInPicture(video: HTMLVideoElement): Promise<JsAny?>? = js(
82: private fun exitOwnedPictureInPicture(video: HTMLVideoElement): Promise<JsAny?>? = js(
Exact file bytes / download · SHA-256 84dd988bcfad342c4c39d0847c6d05845a88e3de52b980b7447954098cbe29f0.
Complete file
@file:OptIn(kotlin.js.ExperimentalWasmJsInterop::class)
package io.github.kdroidfilter.composemediaplayer
import kotlinx.coroutines.*
import org.w3c.dom.HTMLVideoElement
import org.w3c.dom.events.Event
import kotlin.js.JsAny
import kotlin.js.Promise
import kotlin.js.js
/** Own one DOM element, its callbacks, audio jobs and pending PiP promises. */
internal class BrowserVideoBinding(
val video: HTMLVideoElement,
parent: CoroutineScope,
private val changed: (Boolean) -> Unit,
) {
private val job = SupervisorJob(parent.coroutineContext[Job])
val scope = CoroutineScope(parent.coroutineContext + job)
private val listeners = mutableListOf<Pair<String, (Event) -> Unit>>()
var releaseAudio: suspend () -> Unit = {}
private val disposal = AwaitedPlayerDisposal(Dispatchers.Main,
retire = {
job.cancel()
listeners.forEach { (name, listener) -> video.removeEventListener(name, listener) }
listeners.clear()
video.pause()
video.removeAttribute("src")
video.load()
},
release = {
job.join()
exitOwnedPictureInPicture(video)?.await<kotlin.js.JsAny?>()
releaseAudio()
},
)
val active: Boolean get() = !disposal.isRequested && job.isActive
init {
listen("enterpictureinpicture") { changed(true) }
listen("leavepictureinpicture") { changed(false) }
}
fun listen(name: String, listener: (Event) -> Unit) {
if (!active) return
val guarded: (Event) -> Unit = { event -> if (active) listener(event) }
listeners += name to guarded
video.addEventListener(name, guarded)
}
fun dispose() = disposal.dispose()
suspend fun disposeAndJoin() = disposal.disposeAndJoin()
fun requestPictureInPicture(): Boolean {
if (!active || !usablePictureInPicture(video) || PendingPictureInPicture != null) return false
var accepted = false
PendingPictureInPicture = this
// Register the owned job before calling the browser, preserving the user gesture.
scope.launch(start = CoroutineStart.UNDISPATCHED) {
withContext(NonCancellable) {
try {
val request = toggleOwnedPictureInPicture(video) ?: return@withContext
accepted = true
request.await<JsAny?>()
if (!active) exitOwnedPictureInPicture(video)?.await<JsAny?>()
} catch (_: Throwable) { /* Platform rejection is reflected by DOM events. */ }
finally {
if (PendingPictureInPicture === this@BrowserVideoBinding) PendingPictureInPicture = null
}
}
}
return accepted
}
}
private var PendingPictureInPicture: BrowserVideoBinding? = null
internal fun usablePictureInPicture(video: HTMLVideoElement): Boolean = js(
"document.pictureInPictureEnabled === true && video.isConnected && " +
"(document.pictureInPictureElement === video || (video.readyState >= 2 && typeof video.requestPictureInPicture === 'function'))",
)
private fun toggleOwnedPictureInPicture(video: HTMLVideoElement): Promise<JsAny?>? = js(
"document.pictureInPictureElement === video ? document.exitPictureInPicture() : " +
"(document.pictureInPictureElement == null ? video.requestPictureInPicture() : null)",
)
private fun exitOwnedPictureInPicture(video: HTMLVideoElement): Promise<JsAny?>? = js(
"document.pictureInPictureElement === video ? document.exitPictureInPicture() : null",
)
vendor/compose-mediaplayer/src/wasmJsMain/kotlin/io/github/kdroidfilter/composemediaplayer/FullscreenManager.kt
- Source · implementation · 46 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
12: object FullscreenManager {
16: fun exitFullscreen() {
25: fun requestFullScreen() {
35: fun toggleFullscreen(isCurrentlyFullscreen: Boolean, onFullscreenChange: (Boolean) -> Unit) {
Exact file bytes / download · SHA-256 6a0ff8fdf731aa563b81ba5c765e59d5f602177942f9a1d225227940edbbdc12.
Complete file
package io.github.kdroidfilter.composemediaplayer
import kotlinx.browser.document
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
/**
* Manages fullscreen functionality for the video player
*/
object FullscreenManager {
/**
* Exit fullscreen if document is in fullscreen mode
*/
fun exitFullscreen() {
if (document.fullscreenElement != null) {
document.exitFullscreen()
}
}
/**
* Request fullscreen mode
*/
fun requestFullScreen() {
val document = document.documentElement
document?.requestFullscreen()
}
/**
* Toggle fullscreen mode
* @param isCurrentlyFullscreen Whether the player is currently in fullscreen mode
* @param onFullscreenChange Callback to update the fullscreen state
*/
fun toggleFullscreen(isCurrentlyFullscreen: Boolean, onFullscreenChange: (Boolean) -> Unit) {
if (!isCurrentlyFullscreen) {
requestFullScreen()
CoroutineScope(Dispatchers.Default).launch {
delay(500)
}
} else {
exitFullscreen()
}
onFullscreenChange(!isCurrentlyFullscreen)
}
}
vendor/compose-mediaplayer/src/wasmJsMain/kotlin/io/github/kdroidfilter/composemediaplayer/VideoPlayerState.wasmjs.kt
- Source · implementation · 446 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
28: actual open class VideoPlayerState {
146: fun forcePositionRecalculation() {
153: private fun applyVolumeChangeWithThrottle(value: Float) {
177: private fun applyPlaybackSpeedWithThrottle(value: Float) {
203: actual fun selectSubtitleTrack(track: SubtitleTrack?) {
211: actual fun disableSubtitles() {
221: actual fun openUri(uri: String) {
254: actual fun openFile(file: PlatformFile) {
263: actual fun play() {
276: actual fun pause() {
287: actual fun stop() {
304: actual fun seekTo(value: Float) {
313: actual fun clearError() {
320: actual fun toggleFullscreen() {
331: fun setError(error: VideoPlayerError) {
341: fun updateAudioLevels(left: Float, right: Float) {
353: fun updatePosition(currentTime: Float, duration: Float, forceUpdate: Boolean = false) {
392: fun onTimeUpdate(currentTime: Float, duration: Float, forceUpdate: Boolean = false) {
404: internal fun bindVideo(video: org.w3c.dom.HTMLVideoElement): BrowserVideoBinding {
411: internal fun releaseVideo(video: org.w3c.dom.HTMLVideoElement) {
415: fun isPictureInPictureSupported(): Boolean = videoElement?.let(::usablePictureInPicture) == true
416: fun requestPictureInPicture(): Boolean = currentBinding?.requestPictureInPicture() == true
430: actual fun dispose() = disposal.dispose()
431: actual suspend fun disposeAndJoin() = disposal.disposeAndJoin()
443: fun PlatformFile.toUriString(): String {
Exact file bytes / download · SHA-256 7a6601a1d4c4d23dee5e21875d6f009f8f397d03ccbdfac0f1a645212fc2a180.
Complete file
package io.github.kdroidfilter.composemediaplayer
import androidx.compose.runtime.Stable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.sp
import io.github.kdroidfilter.composemediaplayer.util.formatTime
import io.github.vinceglb.filekit.PlatformFile
import io.github.vinceglb.filekit.WebFile
import kotlinx.coroutines.*
import kotlinx.io.IOException
import org.w3c.dom.url.URL
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.Duration.Companion.seconds
import kotlin.time.TimeSource
/**
* Implementation of VideoPlayerState for WebAssembly/JavaScript platform.
* Manages the state of a video player including playback controls, media information,
* and error handling.
*/
@Stable
actual open class VideoPlayerState {
// Variable to store the last opened URI for potential replay
private var lastUri: String? = null
// Coroutine scope for managing async operations
private val playerScope = CoroutineScope(Dispatchers.Main + SupervisorJob())
private var lastUpdateTime = TimeSource.Monotonic.markNow()
// Throttling for control changes
private var lastVolumeChangeTime = TimeSource.Monotonic.markNow()
private var lastSpeedChangeTime = TimeSource.Monotonic.markNow()
private var pendingVolumeChange: Job? = null
private var pendingSpeedChange: Job? = null
// Source URI of the current media
private var _sourceUri by mutableStateOf<String?>(null)
val sourceUri: String? get() = _sourceUri
// Playback state properties
private var _isPlaying by mutableStateOf(false)
actual val isPlaying: Boolean get() = _isPlaying
private var _hasMedia by mutableStateOf(false)
actual val hasMedia: Boolean get() = _hasMedia
internal var _isLoading by mutableStateOf(false)
actual val isLoading: Boolean get() = _isLoading
// Error handling
private var _error by mutableStateOf<VideoPlayerError?>(null)
actual val error: VideoPlayerError? get() = _error
// Media metadata
actual val metadata = VideoMetadata()
actual val aspectRatio : Float = 16f / 9f //TO DO: Get from video source
// Subtitle management
actual var subtitlesEnabled by mutableStateOf(false)
actual var currentSubtitleTrack by mutableStateOf<SubtitleTrack?>(null)
actual val availableSubtitleTracks = mutableListOf<SubtitleTrack>()
actual var subtitleTextStyle by mutableStateOf(
TextStyle(
color = Color.White,
fontSize = 18.sp,
fontWeight = FontWeight.Normal,
textAlign = TextAlign.Center
)
)
actual var subtitleBackgroundColor by mutableStateOf(Color.Black.copy(alpha = 0.5f))
// Playback control properties
private var _volume by mutableStateOf(1.0f)
actual var volume: Float
get() = _volume
set(value) {
val newValue = value.coerceIn(0f, 1f)
if (_volume != newValue) {
_volume = newValue
applyVolumeChangeWithThrottle(newValue)
}
}
actual var sliderPos by mutableStateOf(0.0f)
actual var userDragging by mutableStateOf(false)
actual var loop by mutableStateOf(false)
private var _playbackSpeed by mutableStateOf(1.0f)
actual var playbackSpeed: Float
get() = _playbackSpeed
set(value) {
val newValue = value.coerceIn(0.5f, 2.0f)
if (_playbackSpeed != newValue) {
_playbackSpeed = newValue
applyPlaybackSpeedWithThrottle(newValue)
}
}
actual var isFullscreen by mutableStateOf(false)
// Audio level indicators
private var _leftLevel by mutableStateOf(0f)
private var _rightLevel by mutableStateOf(0f)
actual val leftLevel: Float get() = _leftLevel
actual val rightLevel: Float get() = _rightLevel
// Time display properties
private var _positionText by mutableStateOf("00:00")
private var _durationText by mutableStateOf("00:00")
actual val positionText: String get() = _positionText
actual val durationText: String get() = _durationText
// Current duration of the media
private var _currentDuration: Float = 0f
// Job for handling seek operations
internal var seekJob: Job? = null
/**
* Callback function to force recalculation of the HTML view position.
* This is set by the VideoPlayerSurface when the HTML view is created.
*/
var positionRecalculationCallback: (() -> Unit)? = null
/**
* Callback to apply volume changes to the underlying media player
*/
var applyVolumeCallback: ((Float) -> Unit)? = null
/**
* Callback to apply playback speed changes to the underlying media player
*/
var applyPlaybackSpeedCallback: ((Float) -> Unit)? = null
/**
* Forces recalculation of the HTML view position.
* This is useful when the layout changes and the HTML view needs to be repositioned.
*/
fun forcePositionRecalculation() {
positionRecalculationCallback?.invoke()
}
/**
* Applies volume changes with throttling to prevent performance issues
*/
private fun applyVolumeChangeWithThrottle(value: Float) {
val now = TimeSource.Monotonic.markNow()
val timeSinceLastChange = now - lastVolumeChangeTime
// Cancel any pending volume change
pendingVolumeChange?.cancel()
if (timeSinceLastChange < 100.milliseconds) {
// If changes are coming too rapidly, schedule them with a delay
pendingVolumeChange = playerScope.launch {
delay(100.milliseconds.minus(timeSinceLastChange).inWholeMilliseconds)
applyVolumeCallback?.invoke(value)
lastVolumeChangeTime = TimeSource.Monotonic.markNow()
}
} else {
// Apply immediately if we're not throttling
applyVolumeCallback?.invoke(value)
lastVolumeChangeTime = now
}
}
/**
* Applies playback speed changes with throttling to prevent performance issues
*/
private fun applyPlaybackSpeedWithThrottle(value: Float) {
val now = TimeSource.Monotonic.markNow()
val timeSinceLastChange = now - lastSpeedChangeTime
// Cancel any pending speed change
pendingSpeedChange?.cancel()
if (timeSinceLastChange < 100.milliseconds) {
// If changes are coming too rapidly, schedule them with a delay
pendingSpeedChange = playerScope.launch {
delay(100.milliseconds.minus(timeSinceLastChange).inWholeMilliseconds)
applyPlaybackSpeedCallback?.invoke(value)
lastSpeedChangeTime = TimeSource.Monotonic.markNow()
}
} else {
// Apply immediately if we're not throttling
applyPlaybackSpeedCallback?.invoke(value)
lastSpeedChangeTime = now
}
}
/**
* Selects a subtitle track and enables subtitles.
*
* @param track The subtitle track to select, or null to disable subtitles
*/
actual fun selectSubtitleTrack(track: SubtitleTrack?) {
currentSubtitleTrack = track
subtitlesEnabled = (track != null)
}
/**
* Disables subtitles by clearing the current track and setting subtitlesEnabled to false.
*/
actual fun disableSubtitles() {
currentSubtitleTrack = null
subtitlesEnabled = false
}
/**
* Opens a media source from the given URI.
*
* @param uri The URI of the media to open
*/
actual fun openUri(uri: String) {
if (disposal.isRequested) return
playerScope.coroutineContext.cancelChildren()
// Store the URI for potential replay after stop
lastUri = uri
_sourceUri = uri
_hasMedia = true
_isLoading = true // Set initial loading state
_error = null
_isPlaying = false
_playbackSpeed = 1.0f
// Don't set isLoading to false here - let the video events handle it
playerScope.launch {
try {
_isPlaying = true
} catch (e: Exception) {
_isLoading = false
_error = when (e) {
is IOException -> VideoPlayerError.NetworkError(e.message ?: "Network error")
else -> VideoPlayerError.UnknownError(e.message ?: "Unknown error")
}
}
}
}
/**
* Opens a media file.
*
* @param file The file to open
*/
actual fun openFile(file: PlatformFile) {
val fileUri = file.toUriString()
openUri(fileUri)
}
/**
* Starts or resumes playback of the current media.
* If no media is loaded but a previous URI exists, reopens that media.
*/
actual fun play() {
if (disposal.isRequested) return
if (_hasMedia && !_isPlaying) {
_isPlaying = true
} else if (!_hasMedia && lastUri != null) {
// If we have a stored URI but no media, reopen the media
openUri(lastUri!!)
}
}
/**
* Pauses playback of the current media.
*/
actual fun pause() {
if (disposal.isRequested) return
if (_isPlaying) {
_isPlaying = false
}
}
/**
* Stops playback and resets the player state.
* Note: lastUri is preserved for potential replay.
*/
actual fun stop() {
if (disposal.isRequested) return
_isPlaying = false
_sourceUri = null
_hasMedia = false
_isLoading = false
sliderPos = 0.0f
_positionText = "00:00"
_durationText = "00:00"
// Note: We don't clear lastUri, so it can be used to replay the video
}
/**
* Seeks to a specific position in the media.
*
* @param value The position to seek to, as a percentage (0-1000)
*/
actual fun seekTo(value: Float) {
if (disposal.isRequested) return
sliderPos = value
seekJob?.cancel()
}
/**
* Clears any error state.
*/
actual fun clearError() {
_error = null
}
/**
* Toggles the fullscreen state of the video player
*/
actual fun toggleFullscreen() {
FullscreenManager.toggleFullscreen(isFullscreen) { newFullscreenState ->
isFullscreen = newFullscreenState
}
}
/**
* Sets the error state.
*
* @param error The error to set
*/
fun setError(error: VideoPlayerError) {
_error = error
}
/**
* Updates the audio level indicators.
*
* @param left The left channel audio level
* @param right The right channel audio level
*/
fun updateAudioLevels(left: Float, right: Float) {
_leftLevel = left
_rightLevel = right
}
/**
* Updates the position and duration display.
*
* @param currentTime The current playback position in seconds
* @param duration The total duration of the media in seconds
* @param forceUpdate If true, bypasses the rate limiting check (useful for tests)
*/
fun updatePosition(currentTime: Float, duration: Float, forceUpdate: Boolean = false) {
val now = TimeSource.Monotonic.markNow()
if (forceUpdate || now - lastUpdateTime >= 1.seconds) {
// Calculate a dynamic threshold based on video duration (10% of duration or at least 0.5 seconds)
val threshold = if (duration > 0f && !duration.isNaN()) {
maxOf(duration * 0.1f, 0.5f)
} else {
0.5f
}
// Check if we're very close to the end of the video
val isNearEnd = duration > 0f && !duration.isNaN() && !currentTime.isNaN() &&
(duration - currentTime < threshold)
// If we're near the end, use the duration as the current time
val displayTime = if (isNearEnd) duration else currentTime
_positionText = if (displayTime.isNaN()) "00:00" else formatTime(displayTime)
_durationText = if (duration.isNaN()) "00:00" else formatTime(duration)
if (!userDragging && duration > 0f && !duration.isNaN() && !_isLoading) {
sliderPos = if (isNearEnd) {
PERCENTAGE_MULTIPLIER // Set to 100% if near end
} else {
(currentTime / duration) * PERCENTAGE_MULTIPLIER
}
}
_currentDuration = duration
lastUpdateTime = now
}
}
/**
* Callback for time update events from the media player.
*
* @param currentTime The current playback position in seconds
* @param duration The total duration of the media in seconds
* @param forceUpdate If true, bypasses the rate limiting check (useful for tests)
*/
fun onTimeUpdate(currentTime: Float, duration: Float, forceUpdate: Boolean = false) {
updatePosition(currentTime, duration, forceUpdate)
}
/**
* Disposes of resources used by the player.
*/
private val bindings = mutableSetOf<BrowserVideoBinding>()
internal var currentBinding: BrowserVideoBinding? = null
private set
val videoElement: org.w3c.dom.HTMLVideoElement? get() = currentBinding?.takeIf { it.active }?.video
var onPictureInPictureChanged: (Boolean) -> Unit = {}
internal fun bindVideo(video: org.w3c.dom.HTMLVideoElement): BrowserVideoBinding {
currentBinding?.dispose()
return BrowserVideoBinding(video, playerScope) { active -> onPictureInPictureChanged(active) }.also {
bindings += it
currentBinding = it
}
}
internal fun releaseVideo(video: org.w3c.dom.HTMLVideoElement) {
bindings.firstOrNull { it.video === video }?.dispose()
if (currentBinding?.video === video) currentBinding = null
}
fun isPictureInPictureSupported(): Boolean = videoElement?.let(::usablePictureInPicture) == true
fun requestPictureInPicture(): Boolean = currentBinding?.requestPictureInPicture() == true
private val disposal = AwaitedPlayerDisposal(Dispatchers.Main,
retire = {
bindings.forEach { it.dispose() }
currentBinding = null
applyVolumeCallback = null
applyPlaybackSpeedCallback = null
playerScope.cancel()
},
release = {
playerScope.coroutineContext[Job]?.join()
bindings.toList().forEach { binding -> binding.disposeAndJoin(); bindings.remove(binding) }
},
)
actual fun dispose() = disposal.dispose()
actual suspend fun disposeAndJoin() = disposal.disposeAndJoin()
companion object {
internal const val PERCENTAGE_MULTIPLIER = 1000f
}
}
/**
* Converts a PlatformFile to a URI string that can be used by the media player.
*
* @return A URI string representing the file
*/
fun PlatformFile.toUriString(): String {
val file = checkNotNull((webFile as? WebFile.FileWrapper)?.file) { "Only files can be played, not directories" }
return URL.createObjectURL(file)
}
vendor/compose-mediaplayer/src/wasmJsMain/kotlin/io/github/kdroidfilter/composemediaplayer/VideoPlayerSurface.wasmjs.kt
- Source · implementation · 790 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
45: private fun HTMLVideoElement.safePlay() {
53: private fun HTMLVideoElement.safePause() {
61: private fun HTMLVideoElement.safeSetPlaybackRate(rate: Float) {
69: private fun HTMLVideoElement.safeSetCurrentTime(time: Double) {
77: private fun BrowserVideoBinding.addEventListeners(
94: fun Modifier.videoRatioClip(videoRatio: Float?, contentScale: ContentScale = ContentScale.Fit): Modifier =
98: private fun DrawScope.drawVideoRatioRect(ratio: Float, contentScale: ContentScale) {
223: private fun SubtitleOverlay(playerState: VideoPlayerState) {
252: actual fun VideoPlayerSurface(
497: private fun VideoContent(
510: fun VideoBox(isFullscreenMode: Boolean = false) {
608: private fun createVideoElement(useCors: Boolean = true): HTMLVideoElement {
634: internal fun setupVideoElement(
654: fun initAudioAnalyzer() {
786: private fun VideoPlayerState.onTimeUpdateEvent(event: Event) {
Exact file bytes / download · SHA-256 db40bb8a08da82be8a66d601f7aa78181a66fc2caffc3648fcc8ac9e6416e554.
Complete file
package io.github.kdroidfilter.composemediaplayer
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.BlendMode
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.DrawScope
import co.touchlab.kermit.Logger
import co.touchlab.kermit.Severity
import io.github.kdroidfilter.composemediaplayer.htmlinterop.HtmlView
import io.github.kdroidfilter.composemediaplayer.jsinterop.MediaError
import io.github.kdroidfilter.composemediaplayer.subtitle.ComposeSubtitleLayer
import io.github.kdroidfilter.composemediaplayer.util.FullScreenLayout
import io.github.kdroidfilter.composemediaplayer.util.toTimeMs
import kotlinx.browser.document
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.w3c.dom.HTMLVideoElement
import org.w3c.dom.events.Event
import kotlin.math.abs
internal val wasmVideoLogger = Logger.withTag("WasmVideoPlayerSurface").apply { Logger.setMinSeverity(Severity.Warn) }
// Cache mime type mappings for better performance
private val EXTENSION_TO_MIME_TYPE = mapOf(
"mp4" to "video/mp4",
"webm" to "video/webm",
"ogg" to "video/ogg",
"mov" to "video/quicktime",
"avi" to "video/x-msvideo",
"mkv" to "video/x-matroska"
)
// Helper functions for common operations
private fun HTMLVideoElement.safePlay() {
try {
play()
} catch (e: Exception) {
wasmVideoLogger.e { "Error playing video: ${e.message}" }
}
}
private fun HTMLVideoElement.safePause() {
try {
pause()
} catch (e: Exception) {
wasmVideoLogger.e { "Error pausing video: ${e.message}" }
}
}
private fun HTMLVideoElement.safeSetPlaybackRate(rate: Float) {
try {
playbackRate = rate.toDouble()
} catch (e: Exception) {
wasmVideoLogger.e { "Error setting playback rate: ${e.message}" }
}
}
private fun HTMLVideoElement.safeSetCurrentTime(time: Double) {
try {
currentTime = time
} catch (e: Exception) {
wasmVideoLogger.e { "Error seeking to ${time}s: ${e.message}" }
}
}
private fun BrowserVideoBinding.addEventListeners(
scope: CoroutineScope,
playerState: VideoPlayerState,
events: Map<String, (Event) -> Unit>,
loadingEvents: Map<String, Boolean> = emptyMap()
) {
events.forEach { (event, handler) ->
listen(event, handler)
}
loadingEvents.forEach { (event, isLoading) ->
listen(event) {
scope.launch { playerState._isLoading = isLoading }
}
}
}
fun Modifier.videoRatioClip(videoRatio: Float?, contentScale: ContentScale = ContentScale.Fit): Modifier =
drawBehind { videoRatio?.let { drawVideoRatioRect(it, contentScale) } }
// Optimized drawing function to reduce calculations during rendering
private fun DrawScope.drawVideoRatioRect(ratio: Float, contentScale: ContentScale) {
val containerWidth = size.width
val containerHeight = size.height
val containerRatio = containerWidth / containerHeight
when (contentScale) {
ContentScale.Fit, ContentScale.Inside -> {
// Fit behavior - maintain aspect ratio and fit within container
val (rectWidth, rectHeight) = if (containerRatio > ratio) {
// Container is wider than video
val height = containerHeight
val width = height * ratio
width to height
} else {
// Container is taller than or equal to video
val width = containerWidth
val height = width / ratio
width to height
}
// Calculate offset only once
val xOffset = (containerWidth - rectWidth) / 2f
val yOffset = (containerHeight - rectHeight) / 2f
// Use pre-calculated values
drawRect(
color = Color.Transparent,
blendMode = BlendMode.Clear,
topLeft = Offset(xOffset, yOffset),
size = Size(rectWidth, rectHeight)
)
}
ContentScale.Crop -> {
// Crop behavior - maintain aspect ratio and fill container
val (rectWidth, rectHeight) = if (containerRatio < ratio) {
// Container is taller than video
val height = containerHeight
val width = height * ratio
width to height
} else {
// Container is wider than or equal to video
val width = containerWidth
val height = width / ratio
width to height
}
// Calculate offset only once
val xOffset = (containerWidth - rectWidth) / 2f
val yOffset = (containerHeight - rectHeight) / 2f
// Use pre-calculated values
drawRect(
color = Color.Transparent,
blendMode = BlendMode.Clear,
topLeft = Offset(xOffset, yOffset),
size = Size(rectWidth, rectHeight)
)
}
ContentScale.FillWidth -> {
// Fill width behavior - maintain aspect ratio and fill width
val width = containerWidth
val height = width / ratio
val yOffset = (containerHeight - height) / 2f
drawRect(
color = Color.Transparent,
blendMode = BlendMode.Clear,
topLeft = Offset(0f, yOffset),
size = Size(width, height)
)
}
ContentScale.FillHeight -> {
// Fill height behavior - maintain aspect ratio and fill height
val height = containerHeight
val width = height * ratio
val xOffset = (containerWidth - width) / 2f
drawRect(
color = Color.Transparent,
blendMode = BlendMode.Clear,
topLeft = Offset(xOffset, 0f),
size = Size(width, height)
)
}
ContentScale.FillBounds -> {
// Fill bounds behavior - fill entire container without maintaining aspect ratio
drawRect(
color = Color.Transparent,
blendMode = BlendMode.Clear,
topLeft = Offset(0f, 0f),
size = Size(containerWidth, containerHeight)
)
}
else -> {
// Default to Fit behavior
val (rectWidth, rectHeight) = if (containerRatio > ratio) {
// Container is wider than video
val height = containerHeight
val width = height * ratio
width to height
} else {
// Container is taller than or equal to video
val width = containerWidth
val height = width / ratio
width to height
}
// Calculate offset only once
val xOffset = (containerWidth - rectWidth) / 2f
val yOffset = (containerHeight - rectHeight) / 2f
// Use pre-calculated values
drawRect(
color = Color.Transparent,
blendMode = BlendMode.Clear,
topLeft = Offset(xOffset, yOffset),
size = Size(rectWidth, rectHeight)
)
}
}
}
@Composable
private fun SubtitleOverlay(playerState: VideoPlayerState) {
// Early return if subtitles are disabled or no track is selected
if (!playerState.subtitlesEnabled || playerState.currentSubtitleTrack == null) {
return
}
// Cache duration calculation to avoid repeated conversions
val durationMs = remember(playerState.durationText) {
playerState.durationText.toTimeMs()
}
// Calculate current time only once per composition
val currentTimeMs = remember(playerState.sliderPos, durationMs) {
((playerState.sliderPos / 1000f) * durationMs).toLong()
}
ComposeSubtitleLayer(
currentTimeMs = currentTimeMs,
durationMs = durationMs,
isPlaying = playerState.isPlaying,
subtitleTrack = playerState.currentSubtitleTrack,
subtitlesEnabled = true, // We already checked this above
textStyle = playerState.subtitleTextStyle,
backgroundColor = playerState.subtitleBackgroundColor
)
}
@Composable
actual fun VideoPlayerSurface(
playerState: VideoPlayerState,
modifier: Modifier,
contentScale: ContentScale,
overlay: @Composable () -> Unit
) {
if (playerState.hasMedia) {
var videoElement by remember { mutableStateOf<HTMLVideoElement?>(null) }
var videoRatio by remember { mutableStateOf<Float?>(null) }
// Track if we're using CORS mode (initially true, will be set to false if CORS errors occur)
var useCors by remember { mutableStateOf(true) }
val scope = rememberCoroutineScope()
// Use VideoContent composable for video display logic
VideoContent(
playerState = playerState,
modifier = modifier,
videoRatio = videoRatio,
useCors = useCors,
onVideoElementChange = { videoElement = it },
onVideoRatioChange = { videoRatio = it },
onCorsChange = { useCors = it },
scope = scope,
contentScale = contentScale,
overlay = overlay
)
// Handle fullscreen
LaunchedEffect(playerState.isFullscreen) {
try {
if (!playerState.isFullscreen) {
FullscreenManager.exitFullscreen()
}
} catch (e: Exception) {
wasmVideoLogger.e { "Error handling fullscreen: ${e.message}" }
}
}
// Listen for fullscreen change events
DisposableEffect(Unit) {
val fullscreenChangeListener: (Event) -> Unit = {
videoElement?.let { video ->
val isDocumentFullscreen = video.ownerDocument?.fullscreenElement != null
if (!isDocumentFullscreen && playerState.isFullscreen) {
playerState.isFullscreen = false
}
}
}
val fullscreenEvents = listOf(
"fullscreenchange", "webkitfullscreenchange",
"mozfullscreenchange", "MSFullscreenChange"
)
fullscreenEvents.forEach { event ->
document.addEventListener(event, fullscreenChangeListener)
}
onDispose {
fullscreenEvents.forEach { event ->
document.removeEventListener(event, fullscreenChangeListener)
}
}
}
// Handle source change effect
LaunchedEffect(playerState.sourceUri) {
videoElement?.let { video ->
val sourceUri = playerState.sourceUri ?: ""
if (sourceUri.isNotEmpty()) {
playerState.clearError()
video.src = sourceUri
video.load()
// Don't set playback speed directly, it will be handled by the applyPlaybackSpeedCallback
if (playerState.isPlaying) video.safePlay() else video.safePause()
}
}
}
// Handle play/pause
LaunchedEffect(playerState.isPlaying) {
videoElement?.let { video ->
if (playerState.isPlaying) video.safePlay() else video.safePause()
}
}
// Handle property updates - combined for better performance
// Store pending changes to apply after seeking is complete
var pendingVolumeChange by remember { mutableStateOf<Double?>(null) }
var pendingPlaybackSpeedChange by remember { mutableStateOf<Float?>(null) }
LaunchedEffect(playerState.loop) {
videoElement?.let { video ->
// Always update loop property immediately
video.loop = playerState.loop
}
}
// Apply pending volume change when seeking is complete
DisposableEffect(videoElement) {
val video = videoElement ?: return@DisposableEffect onDispose {}
// Set the volume callback to respect seeking state
playerState.applyVolumeCallback = { value ->
if (playerState._isLoading) {
// Store the volume change to apply after seeking is complete
pendingVolumeChange = value.toDouble()
} else {
// Apply volume change immediately if not seeking
video.volume = value.toDouble()
pendingVolumeChange = null
}
}
// Apply current volume immediately if needed
if (!playerState._isLoading) {
video.volume = playerState.volume.toDouble()
} else {
pendingVolumeChange = playerState.volume.toDouble()
}
// Set the playback speed callback to respect seeking state
playerState.applyPlaybackSpeedCallback = { value ->
if (playerState._isLoading) {
// Store the playback speed change to apply after seeking is complete
pendingPlaybackSpeedChange = value
} else {
// Apply playback speed change immediately if not seeking
video.safeSetPlaybackRate(value)
pendingPlaybackSpeedChange = null
}
}
// Apply current playback speed immediately if needed
if (!playerState._isLoading) {
video.safeSetPlaybackRate(playerState.playbackSpeed)
} else {
pendingPlaybackSpeedChange = playerState.playbackSpeed
}
val seekedListener: (Event) -> Unit = {
pendingVolumeChange?.let { volume ->
video.volume = volume
pendingVolumeChange = null
}
pendingPlaybackSpeedChange?.let { speed ->
video.safeSetPlaybackRate(speed)
pendingPlaybackSpeedChange = null
}
}
video.addEventListener("seeked", seekedListener)
onDispose {
video.removeEventListener("seeked", seekedListener)
playerState.applyVolumeCallback = null
playerState.applyPlaybackSpeedCallback = null
}
}
// State for CORS mode changes
var lastPosition by remember { mutableStateOf(0.0) }
var wasPlaying by remember { mutableStateOf(false) }
var lastPlaybackSpeed by remember { mutableStateOf(1.0f) }
// Store state before video element recreation
LaunchedEffect(useCors) {
videoElement?.let {
lastPosition = it.currentTime
wasPlaying = playerState.isPlaying
lastPlaybackSpeed = playerState.playbackSpeed
}
}
// Restore state after video element recreation
LaunchedEffect(videoElement, useCors) {
videoElement?.let { video ->
if (lastPosition > 0) {
video.safeSetCurrentTime(lastPosition)
lastPosition = 0.0
}
if (lastPlaybackSpeed != 1.0f) {
video.safeSetPlaybackRate(lastPlaybackSpeed)
lastPlaybackSpeed = 1.0f
}
if (wasPlaying) {
video.safePlay()
wasPlaying = false
}
}
}
// Handle seeking - optimized to reduce job creation
LaunchedEffect(playerState.sliderPos) {
if (!playerState.userDragging && playerState.hasMedia) {
// Cancel previous seek job if it exists
playerState.seekJob?.cancel()
// Create a new seek job only if needed
videoElement?.let { video ->
val duration = video.duration.toFloat()
if (duration > 0f) {
val newTime = (playerState.sliderPos / VideoPlayerState.PERCENTAGE_MULTIPLIER) * duration
val currentTime = video.currentTime
// Only seek if the difference is significant (> 0.5 seconds)
if (abs(currentTime - newTime) > 0.5) {
playerState.seekJob = scope.launch {
video.safeSetCurrentTime(newTime.toDouble())
}
}
}
}
}
}
// Listen for external play/pause events
DisposableEffect(videoElement) {
val video = videoElement ?: return@DisposableEffect onDispose {}
val playListener: (Event) -> Unit = {
if (!playerState.isPlaying) scope.launch { playerState.play() }
}
val pauseListener: (Event) -> Unit = {
if (playerState.isPlaying) scope.launch { playerState.pause() }
}
video.addEventListener("play", playListener)
video.addEventListener("pause", pauseListener)
onDispose {
video.removeEventListener("play", playListener)
video.removeEventListener("pause", pauseListener)
}
}
}
}
@Composable
private fun VideoContent(
playerState: VideoPlayerState,
modifier: Modifier,
videoRatio: Float?,
useCors: Boolean,
onVideoElementChange: (HTMLVideoElement?) -> Unit,
onVideoRatioChange: (Float?) -> Unit,
onCorsChange: (Boolean) -> Unit,
scope: CoroutineScope,
contentScale: ContentScale,
overlay: @Composable () -> Unit = {}
) {
@Composable
fun VideoBox(isFullscreenMode: Boolean = false) {
Box(
modifier = Modifier
.fillMaxSize()
.background(if (isFullscreenMode) Color.Black else Color.Transparent)
.videoRatioClip(videoRatio, contentScale)
) {
SubtitleOverlay(playerState)
overlay()
}
}
Box(modifier = Modifier.fillMaxSize()) {
VideoBox(isFullscreenMode = false)
if (playerState.isFullscreen) {
FullScreenLayout(onDismissRequest = { playerState.isFullscreen = false }) {
Box(
modifier = Modifier.fillMaxSize().background(Color.Black),
contentAlignment = Alignment.Center
) {
VideoBox(isFullscreenMode = true)
}
}
}
// Create HTML video element
key(useCors) {
HtmlView(
factory = { createVideoElement(useCors) },
modifier = modifier,
onRelease = { video -> playerState.releaseVideo(video) },
update = { video ->
if (playerState.currentBinding?.video === video) return@HtmlView
val binding = playerState.bindVideo(video)
onVideoElementChange(video)
binding.listen("loadedmetadata") {
val width = video.videoWidth
val height = video.videoHeight
if (height != 0) {
onVideoRatioChange(width.toFloat() / height.toFloat())
// Update metadata properties
with(playerState.metadata) {
this.width = width
this.height = height
duration = (video.duration * 1000).toLong()
// Try to get mimeType and title from the video source - optimized
val src = video.src
if (src.isNotEmpty()) {
// Optimize extension extraction
val lastDotIndex = src.lastIndexOf('.')
if (lastDotIndex > 0 && lastDotIndex < src.length - 1) {
val extension = src.substring(lastDotIndex + 1).lowercase()
// Use map for faster lookup
mimeType = EXTENSION_TO_MIME_TYPE[extension]
}
// Extract title from filename - optimized
try {
val lastSlashIndex = src.lastIndexOf('/')
val lastBackslashIndex = src.lastIndexOf('\\')
val startIndex = maxOf(lastSlashIndex, lastBackslashIndex) + 1
if (startIndex > 0 && startIndex < src.length) {
val endIndex = if (lastDotIndex > startIndex) lastDotIndex else src.length
val filename = src.substring(startIndex, endIndex)
if (filename.isNotEmpty()) {
title = filename
}
}
} catch (e: Exception) {
wasmVideoLogger.w { "Failed to extract title from filename: ${e.message}" }
}
}
}
}
}
setupVideoElement(
video,
playerState,
binding,
enableAudioDetection = true,
useCors = useCors,
onCorsError = { onCorsChange(false) }
)
},
isFullscreen = playerState.isFullscreen,
contentScale = contentScale,
videoRatio = videoRatio
)
}
}
}
private fun createVideoElement(useCors: Boolean = true): HTMLVideoElement {
return (document.createElement("video") as HTMLVideoElement).apply {
controls = false
style.position = "absolute"
style.zIndex = "-1"
style.width = "100%"
style.height = "100%"
style.backgroundColor = "black" // Always set background color to black
// Don't set objectFit here, it will be set by setElementPosition based on contentScale
// Handle CORS mode
if (useCors) {
crossOrigin = "anonymous"
} else {
removeAttribute("crossorigin")
}
// Set attributes for better compatibility
setAttribute("playsinline", "")
setAttribute("webkit-playsinline", "")
setAttribute("preload", "auto")
setAttribute("x-webkit-airplay", "allow")
}
}
internal fun setupVideoElement(
video: HTMLVideoElement,
playerState: VideoPlayerState,
binding: BrowserVideoBinding,
enableAudioDetection: Boolean = true,
useCors: Boolean = true,
onCorsError: () -> Unit = {},
) {
val scope = binding.scope
val audioAnalyzer = if (enableAudioDetection) AudioLevelProcessor(video) else null
binding.releaseAudio = { audioAnalyzer?.closeAndJoin() }
var initializationJob: Job? = null
var corsErrorDetected = false
// Reset state
playerState.clearError()
playerState.metadata.audioChannels = null
playerState.metadata.audioSampleRate = null
// Initialize audio analyzer
fun initAudioAnalyzer() {
if (!enableAudioDetection || corsErrorDetected) return
initializationJob?.cancel()
initializationJob = scope.launch {
val success = audioAnalyzer?.initialize() ?: false
if (!success) {
corsErrorDetected = true
} else {
audioAnalyzer.let { analyzer ->
playerState.metadata.audioChannels = analyzer.audioChannels
playerState.metadata.audioSampleRate = analyzer.audioSampleRate
}
}
}
}
// Setup loading state events
binding.addEventListeners(
scope = scope,
playerState = playerState,
events = mapOf(
"timeupdate" to playerState::onTimeUpdateEvent,
"ended" to { scope.launch { playerState.pause() } }
),
loadingEvents = mapOf(
"seeking" to true,
"waiting" to true,
"playing" to false,
"seeked" to false,
"canplaythrough" to false,
"canplay" to false
)
)
// Optimize event handling by combining related events
// Map of events that can set loading state to false based on conditions
val conditionalLoadingEvents = mapOf(
"suspend" to { video.readyState >= 3 },
"loadedmetadata" to { true }
)
// Add conditional loading event listeners
conditionalLoadingEvents.forEach { (event, condition) ->
binding.listen(event) {
// For loadedmetadata, also initialize audio analyzer
if (event == "loadedmetadata") {
initAudioAnalyzer()
}
// Single coroutine launch for all events
scope.launch {
if (condition()) {
playerState._isLoading = false
}
// Additional actions for loadedmetadata
if (event == "loadedmetadata") {
// Don't set playback speed directly, it will be handled by the applyPlaybackSpeedCallback
if (playerState.isPlaying) {
video.safePlay()
}
}
}
}
}
// Handle play event and audio level updates
var audioLevelJob: Job? = null
binding.listen("play") {
if (enableAudioDetection && !corsErrorDetected && initializationJob?.isActive != true) {
initAudioAnalyzer()
}
if (enableAudioDetection && audioLevelJob?.isActive != true) {
audioLevelJob = scope.launch {
while (video.paused.not()) {
val (left, right) = if (!corsErrorDetected) {
audioAnalyzer?.getAudioLevels() ?: (0f to 0f)
} else {
0f to 0f
}
playerState.updateAudioLevels(left, right)
delay(100)
}
}
}
}
// Cancel audio level job when paused
binding.listen("pause") {
audioLevelJob?.cancel()
audioLevelJob = null
}
// Handle errors
binding.listen("error") {
scope.launch {
playerState._isLoading = false
corsErrorDetected = true
val error = video.error
if (error != null) {
val isCorsRelatedError = error.code == MediaError.MEDIA_ERR_NETWORK ||
(error.code == MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED && useCors)
if (useCors) {
playerState.clearError()
onCorsError()
} else {
val errorMsg = if (error.code == MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED) {
"Failed to load because the video format is not supported"
} else {
"Failed to load because no supported source was found"
}
playerState.setError(VideoPlayerError.SourceError(errorMsg))
}
}
}
}
// Set initial properties
// Don't set volume or playback speed here, they will be handled by the callbacks in the DisposableEffect
// This avoids potential race conditions with the seeking state
video.loop = playerState.loop
// Play if needed
if (video.src.isNotEmpty() && playerState.isPlaying) {
video.safePlay()
}
}
private fun VideoPlayerState.onTimeUpdateEvent(event: Event) {
(event.target as? HTMLVideoElement)?.let {
onTimeUpdate(it.currentTime.toFloat(), it.duration.toFloat())
}
}
vendor/compose-mediaplayer/src/wasmJsMain/kotlin/io/github/kdroidfilter/composemediaplayer/htmlinterop/HtmlView.kt
- Source · implementation · 267 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
22: private class ComponentInfo<T : Element> {
28: private class FocusSwitcher<T : Element>(private val info: ComponentInfo<T>, private val focusManager: FocusManager) {
33: private fun requestFocusAndMove(requester: FocusRequester, direction: FocusDirection) {
43: fun moveBackward() = requestFocusAndMove(backwardRequester, FocusDirection.Previous)
44: fun moveForward() = requestFocusAndMove(forwardRequester, FocusDirection.Next)
47: fun Content() {
71: private fun setElementPosition(
180: internal fun <T : Element> HtmlView(
236: private class Updater<T : Element>(
251: private fun performUpdate() {
262: fun dispose() {
Exact file bytes / download · SHA-256 c66260d7f3fd081dc588c3bc3a31ac9642664db98ac21d2f08526beb9a6005d6.
Complete file
package io.github.kdroidfilter.composemediaplayer.htmlinterop
import androidx.compose.foundation.layout.Box
import androidx.compose.runtime.*
import androidx.compose.runtime.snapshots.SnapshotStateObserver
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.*
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.layout.positionInWindow
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.unit.round
import kotlinx.browser.document
import org.w3c.dom.Document
import org.w3c.dom.Element
import org.w3c.dom.HTMLElement
val LocalLayerContainer = staticCompositionLocalOf<Element> { document.body ?: error("Document body unavailable") }
val NoOpUpdate: Element.() -> Unit = {}
private class ComponentInfo<T : Element> {
lateinit var container: Element
lateinit var component: T
lateinit var updater: Updater<T>
}
private class FocusSwitcher<T : Element>(private val info: ComponentInfo<T>, private val focusManager: FocusManager) {
private val backwardRequester = FocusRequester()
private val forwardRequester = FocusRequester()
private var isRequesting = false
private fun requestFocusAndMove(requester: FocusRequester, direction: FocusDirection) {
try {
isRequesting = true
requester.requestFocus()
} finally {
isRequesting = false
}
focusManager.moveFocus(direction)
}
fun moveBackward() = requestFocusAndMove(backwardRequester, FocusDirection.Previous)
fun moveForward() = requestFocusAndMove(forwardRequester, FocusDirection.Next)
@Composable
fun Content() {
Box(Modifier
.focusRequester(backwardRequester)
.onFocusChanged {
if (it.isFocused && !isRequesting) {
focusManager.clearFocus(force = true)
info.container.firstElementChild?.let { (it as HTMLElement).focus() } ?: moveForward()
}
}
.focusTarget()
)
Box(Modifier
.focusRequester(forwardRequester)
.onFocusChanged {
if (it.isFocused && !isRequesting) {
focusManager.clearFocus(force = true)
info.container.lastElementChild?.let { (it as HTMLElement).focus() } ?: moveBackward()
}
}
.focusTarget()
)
}
}
private fun setElementPosition(
element: HTMLElement,
width: Float,
height: Float,
x: Float,
y: Float,
isFullscreen: Boolean = false,
contentScale: ContentScale = ContentScale.Fit,
videoRatio: Float? = null
) {
element.style.apply {
position = "absolute"
margin = "0px"
backgroundColor = "black" // Always set background color to black
if (isFullscreen) {
// In fullscreen mode, make the element fill the entire screen
this.width = "100%"
this.height = "100%"
left = "0"
top = "0"
// Set object-fit based on contentScale even in fullscreen mode
when (contentScale) {
ContentScale.FillWidth -> objectFit = "contain"
ContentScale.FillHeight -> objectFit = "contain"
ContentScale.FillBounds -> objectFit = "fill"
ContentScale.Crop -> objectFit = "cover"
else -> objectFit = "contain"
}
} else {
// Calculate dimensions based on contentScale and container size
val containerWidth = width
val containerHeight = height
if (videoRatio != null) {
val containerRatio = containerWidth / containerHeight
when (contentScale) {
ContentScale.Fit, ContentScale.Inside -> {
// Scale to fit within container while maintaining aspect ratio
this.width = "${containerWidth}px"
this.height = "${containerHeight}px"
left = "${x}px"
top = "${y}px"
objectFit = "contain" // Use CSS object-fit to maintain aspect ratio and fit within container
}
ContentScale.Crop -> {
// Scale to cover container while maintaining aspect ratio
this.width = "${containerWidth}px"
this.height = "${containerHeight}px"
left = "${x}px"
top = "${y}px"
objectFit = "cover" // Use CSS object-fit to maintain aspect ratio and cover container
}
ContentScale.FillWidth -> {
// Fill width, maintain aspect ratio
val scaledHeight = containerWidth / videoRatio
this.width = "${containerWidth}px"
this.height = "${scaledHeight}px"
left = "${x}px"
top = "${y + (containerHeight - scaledHeight) / 2}px"
objectFit = "contain" // Use contain to preserve aspect ratio
}
ContentScale.FillHeight -> {
// Fill height, maintain aspect ratio
val scaledWidth = containerHeight * videoRatio
this.width = "${scaledWidth}px"
this.height = "${containerHeight}px"
left = "${x + (containerWidth - scaledWidth) / 2}px"
top = "${y}px"
objectFit = "contain" // Use contain to preserve aspect ratio
}
ContentScale.FillBounds -> {
// Fill the entire container without respecting aspect ratio
this.width = "${containerWidth}px"
this.height = "${containerHeight}px"
left = "${x}px"
top = "${y}px"
objectFit = "fill" // Use CSS object-fit to stretch without preserving ratio
}
else -> {
// Default positioning based on the container
this.width = "${width}px"
this.height = "${height}px"
left = "${x}px"
top = "${y}px"
objectFit = "contain" // Default to maintain aspect ratio
}
}
} else {
// No video ratio available, use default positioning
this.width = "${width}px"
this.height = "${height}px"
left = "${x}px"
top = "${y}px"
// Set object-fit based on contentScale even when ratio is unknown
when (contentScale) {
ContentScale.FillBounds -> objectFit = "fill" // Stretch without preserving ratio
ContentScale.Crop -> objectFit = "cover" // Cover while maintaining aspect ratio
else -> objectFit = "contain" // Default to maintain aspect ratio
}
}
}
}
}
@Composable
internal fun <T : Element> HtmlView(
factory: Document.() -> T,
modifier: Modifier = Modifier,
update: (T) -> Unit = NoOpUpdate,
onRelease: (T) -> Unit = {},
isFullscreen: Boolean = false,
contentScale: ContentScale = ContentScale.Fit,
videoRatio: Float? = null
) {
val info = remember { ComponentInfo<T>() }
val root = LocalLayerContainer.current
val density = LocalDensity.current.density
val focusManager = LocalFocusManager.current
val focusSwitcher = remember { FocusSwitcher(info, focusManager) }
Box(modifier.onGloballyPositioned { coords ->
val pos = coords.positionInWindow().round()
val size = coords.size
setElementPosition(
info.component as HTMLElement,
size.width / density,
size.height / density,
pos.x / density,
pos.y / density,
isFullscreen,
contentScale,
videoRatio
)
}) {
focusSwitcher.Content()
}
val release by rememberUpdatedState(onRelease)
DisposableEffect(Unit) {
info.apply {
container = document.createElement("div")
component = document.factory()
updater = Updater(component, update)
}
root.insertBefore(info.container, root.firstChild)
info.container.append(info.component)
setElementPosition(info.component as HTMLElement, 0f, 0f, 0f, 0f, false, contentScale, videoRatio)
onDispose {
info.updater.dispose()
release(info.component)
root.removeChild(info.container)
}
}
SideEffect {
info.updater.update = update
}
}
private class Updater<T : Element>(
private val component: T,
update: (T) -> Unit
) {
private var isDisposed = false
private val observer = SnapshotStateObserver { it() }
var update: (T) -> Unit = update
set(value) {
if (field != value) {
field = value
performUpdate()
}
}
private fun performUpdate() {
observer.observeReads(component, { if(!isDisposed) performUpdate() }) {
update(component)
}
}
init {
observer.start()
performUpdate()
}
fun dispose() {
observer.stop()
observer.clear()
isDisposed = true
}
}
vendor/compose-mediaplayer/src/wasmJsMain/kotlin/io/github/kdroidfilter/composemediaplayer/jsinterop/AudioContextApi.kt
- Source · implementation · 96 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
13: external class AudioContext : JsAny {
19: fun createMediaElementSource(mediaElement: HTMLMediaElement): MediaElementAudioSourceNode
20: fun createChannelSplitter(numberOfOutputs: Int = definedExternally): ChannelSplitterNode
21: fun createAnalyser(): AnalyserNode
22: fun resume()
23: fun close(): kotlin.js.Promise<kotlin.js.JsAny?>
29: external open class AudioNode : JsAny {
30: fun connect(destination: AudioNode, output: Int = definedExternally, input: Int = definedExternally): AudioNode
31: fun disconnect()
37: external class AudioDestinationNode : AudioNode {
44: external class MediaElementAudioSourceNode : AudioNode {
52: external class ChannelSplitterNode : AudioNode
57: external class AnalyserNode : AudioNode {
83: fun getByteFrequencyData(array: Uint8Array)
89: fun getByteTimeDomainData(array: Uint8Array)
94: fun getFloatFrequencyData(array: Float32Array)
95: fun getFloatTimeDomainData(array: Float32Array)
Exact file bytes / download · SHA-256 81ce15882421d5c7eebe4dc1bea0454f0a3fa7bf80ea746dfb3f25f5be1626a5.
Complete file
@file:Suppress("unused")
package io.github.kdroidfilter.composemediaplayer.jsinterop
import kotlin.js.JsAny
import org.khronos.webgl.Float32Array
import org.khronos.webgl.Uint8Array
import org.w3c.dom.HTMLMediaElement
/**
* Represents the main audio context
*/
external class AudioContext : JsAny {
constructor()
val destination: AudioDestinationNode
val state: String
val sampleRate: Int
fun createMediaElementSource(mediaElement: HTMLMediaElement): MediaElementAudioSourceNode
fun createChannelSplitter(numberOfOutputs: Int = definedExternally): ChannelSplitterNode
fun createAnalyser(): AnalyserNode
fun resume()
fun close(): kotlin.js.Promise<kotlin.js.JsAny?>
}
/**
* Represents a generic node of the Web Audio API
*/
external open class AudioNode : JsAny {
fun connect(destination: AudioNode, output: Int = definedExternally, input: Int = definedExternally): AudioNode
fun disconnect()
}
/**
* Audio context output
*/
external class AudioDestinationNode : AudioNode {
val maxChannelCount: Int
}
/**
* Audio source based on a media element (audio or video)
*/
external class MediaElementAudioSourceNode : AudioNode {
/** Number of channels actually présentes dans la piste audio. */
val channelCount: Int
}
/**
* Allows channel separation
*/
external class ChannelSplitterNode : AudioNode
/**
* Analysis node to retrieve information about the spectrum or wave
*/
external class AnalyserNode : AudioNode {
var fftSize: Int
val frequencyBinCount: Int
/**
* dB value below which the signal is cut off (for frequency display).
* Default is -100 dB.
*/
var minDecibels: Double
/**
* dB value above which the signal is cut off (for frequency display).
* Default is -30 dB.
*/
var maxDecibels: Double
/**
* The smoothingTimeConstant (0..1) allows smoothing of data between two analyses
* (values close to 1 => smoother, values close to 0 => more reactive).
* Default is 0.8.
*/
var smoothingTimeConstant: Double
/**
* Retrieves the frequency amplitude in a byte array (0..255).
*/
fun getByteFrequencyData(array: Uint8Array)
/**
* Retrieves the raw waveform (time domain) in a byte array (0..255).
* By default, 128 represents axis 0, so [0..255] -> [-1..+1].
*/
fun getByteTimeDomainData(array: Uint8Array)
/**
* Additional methods if needed: retrieval in Float32.
*/
fun getFloatFrequencyData(array: Float32Array)
fun getFloatTimeDomainData(array: Float32Array)
}
vendor/compose-mediaplayer/src/wasmJsMain/kotlin/io/github/kdroidfilter/composemediaplayer/jsinterop/MediaError.kt
- Source · implementation · 40 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
10: external class MediaError : JsAny {
Exact file bytes / download · SHA-256 1497eea2bd5934336671518a9f0c14c04648eab09106876921815788ccde3888.
Complete file
@file:Suppress("unused")
package io.github.kdroidfilter.composemediaplayer.jsinterop
import kotlin.js.JsAny
/**
* Represents a media error in the HTMLMediaElement
*/
external class MediaError : JsAny {
/**
* Error code for the media error
*/
val code: Short
companion object {
/**
* The fetching process for the media resource was aborted by the user agent at the user's request.
*/
val MEDIA_ERR_ABORTED: Short
/**
* A network error of some description caused the user agent to stop fetching the media resource,
* after the resource was established to be usable.
*/
val MEDIA_ERR_NETWORK: Short
/**
* An error of some description occurred while decoding the media resource,
* after the resource was established to be usable.
*/
val MEDIA_ERR_DECODE: Short
/**
* The media resource indicated by the src attribute or assigned media provider object
* was not suitable.
*/
val MEDIA_ERR_SRC_NOT_SUPPORTED: Short
}
}
vendor/compose-mediaplayer/src/wasmJsMain/kotlin/io/github/kdroidfilter/composemediaplayer/subtitle/SubtitleLoader.wasmjs.kt
- Source · implementation · 85 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
17: actual suspend fun loadSubtitleContent(src: String): String = suspendCancellableCoroutine { continuation ->
Exact file bytes / download · SHA-256 8558c930272f62f28326b95ab551051fe8ef3fea425d93f7952c937e544e6e1f.
Complete file
package io.github.kdroidfilter.composemediaplayer.subtitle
import io.github.kdroidfilter.composemediaplayer.wasmVideoLogger
import kotlinx.browser.window
import kotlinx.coroutines.suspendCancellableCoroutine
import org.w3c.dom.url.URL
import org.w3c.xhr.XMLHttpRequest
import kotlin.coroutines.resume
/**
* WASM JS implementation of the loadSubtitleContent function.
* Loads subtitle content from a URL using XMLHttpRequest.
*
* @param src The source URI of the subtitle file
* @return The content of the subtitle file as a string
*/
actual suspend fun loadSubtitleContent(src: String): String = suspendCancellableCoroutine { continuation ->
try {
// Handle different types of URLs
val url = when {
// Handle HTTP/HTTPS URLs directly
src.startsWith("http://") || src.startsWith("https://") -> src
// Handle blob: URLs directly
src.startsWith("blob:") -> src
// Handle data: URLs directly
src.startsWith("data:") -> src
// Handle file: URLs
src.startsWith("file:") -> {
wasmVideoLogger.d { "File URLs are not directly supported in browser. Using as-is: $src" }
src
}
// For any other format, assume it's a relative path
else -> {
try {
// Try to resolve relative to the current page
URL(src, window.location.href).toString()
} catch (e: Exception) {
wasmVideoLogger.e { "Failed to resolve URL: $src - ${e.message}" }
src // Use as-is if resolution fails
}
}
}
// Log the URL we're fetching
wasmVideoLogger.d { "Fetching subtitle content from: $url" }
// Use XMLHttpRequest to fetch the content
val xhr = XMLHttpRequest()
xhr.open("GET", url, true)
// We want text response, which is the default, so no need to set responseType
xhr.onload = {
if (xhr.status.toInt() in 200..299) {
val content = xhr.responseText ?: ""
continuation.resume(content)
} else {
wasmVideoLogger.e { "Failed to fetch subtitle content: ${xhr.status} ${xhr.statusText}" }
continuation.resume("")
}
}
xhr.onerror = {
wasmVideoLogger.e { "Error fetching subtitle content" }
continuation.resume("")
}
xhr.send()
// Register cancellation handler
continuation.invokeOnCancellation {
try {
xhr.abort()
} catch (e: Exception) {
// Ignore abort errors
}
}
} catch (e: Exception) {
wasmVideoLogger.e { "Error loading subtitle content: ${e.message}" }
continuation.resume("")
}
}
vendor/compose-mediaplayer/src/wasmJsMain/kotlin/io/github/kdroidfilter/composemediaplayer/util/Uri.kt
- Source · implementation · 8 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
6: actual fun PlatformFile.getUri(): String {
Exact file bytes / download · SHA-256 366daadeddfe1eb5c31ce9aa7eaacd64b777b2bf7accdbb9de7ed621586e210d.
Complete file
package io.github.kdroidfilter.composemediaplayer.util
import io.github.kdroidfilter.composemediaplayer.toUriString
import io.github.vinceglb.filekit.PlatformFile
actual fun PlatformFile.getUri(): String {
return this.toUriString()
}
vendor/compose-mediaplayer/src/wasmJsTest/kotlin/io/github/kdroidfilter/composemediaplayer/AudioLevelProcessorDisposalTest.kt
- Source · test / fixture · 65 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
13: class AudioLevelProcessorDisposalTest {
38: private suspend fun audioDrain() { repeat(4) { audioTick().await<JsAny?>(); yield() } }
39: private fun audioTick(): Promise<JsAny?> = js("new Promise(resolve => setTimeout(resolve, 0))")
40: private external interface AudioFixture : JsAny {
45: fun resolveClose()
46: fun restore()
48: private fun audioFixture(fail: Boolean): AudioFixture = js("""(() => {
Exact file bytes / download · SHA-256 40ac9b309ffe1d948cf7e65b9047592b370ad6181beb29bd2613ca5f36f82afe.
Complete file
@file:OptIn(kotlin.js.ExperimentalWasmJsInterop::class)
package io.github.kdroidfilter.composemediaplayer
import kotlinx.coroutines.*
import kotlinx.coroutines.test.runTest
import org.w3c.dom.HTMLVideoElement
import kotlin.js.JsAny
import kotlin.js.Promise
import kotlin.js.js
import kotlin.test.*
class AudioLevelProcessorDisposalTest {
@Test fun bindingReleaseAwaitsActualAudioContextClosePromise() = runTest {
val audio = audioFixture(false); val parent = CoroutineScope(SupervisorJob() + Dispatchers.Main)
val processor = AudioLevelProcessor(audio.video)
val binding = BrowserVideoBinding(audio.video, parent) {}
binding.releaseAudio = processor::closeAndJoin
try {
assertTrue(processor.initialize()); assertEquals(48000, processor.audioSampleRate)
val close = async { binding.disposeAndJoin() }; audioDrain()
assertEquals(1, audio.closes); assertEquals(4, audio.disconnects); assertFalse(close.isCompleted)
audio.resolveClose(); close.await(); binding.disposeAndJoin(); assertEquals(1, audio.closes)
assertFalse(processor.initialize())
} finally { audio.resolveClose(); binding.disposeAndJoin(); parent.cancel(); audio.restore() }
}
@Test fun failedSourceInitializationStillRetainsItsContextForAwaitedRelease() = runTest {
val audio = audioFixture(true); val processor = AudioLevelProcessor(audio.video)
try {
assertFalse(processor.initialize()); assertFalse(processor.initialize()); assertEquals(1, audio.contexts)
val close = async { processor.closeAndJoin() }; audioDrain()
assertFalse(close.isCompleted); assertEquals(1, audio.closes)
audio.resolveClose(); close.await(); processor.closeAndJoin(); assertEquals(1, audio.closes)
} finally { audio.resolveClose(); processor.closeAndJoin(); audio.restore() }
}
}
private suspend fun audioDrain() { repeat(4) { audioTick().await<JsAny?>(); yield() } }
private fun audioTick(): Promise<JsAny?> = js("new Promise(resolve => setTimeout(resolve, 0))")
private external interface AudioFixture : JsAny {
val video: HTMLVideoElement
val contexts: Int
val closes: Int
val disconnects: Int
fun resolveClose()
fun restore()
}
private fun audioFixture(fail: Boolean): AudioFixture = js("""(() => {
const original = window.AudioContext;
let finish = null;
const f = { video: document.createElement('video'), contexts: 0, closes: 0, disconnects: 0 };
f.video.pause = () => {}; f.video.load = () => {};
const node = () => ({ connect: target => target, disconnect: () => { f.disconnects++; }, channelCount: 2,
frequencyBinCount: 128, fftSize: 256, getByteFrequencyData: data => data.fill(0) });
window.AudioContext = class {
constructor() { f.contexts++; this.destination = node(); this.sampleRate = 48000; }
createMediaElementSource() { if (fail) throw new Error('source rejected'); return node(); }
createChannelSplitter() { return node(); }
createAnalyser() { return node(); }
close() { f.closes++; return new Promise(resolve => { finish = resolve; }); }
};
f.resolveClose = () => { const resolve = finish; finish = null; if (resolve) resolve(null); };
f.restore = () => { window.AudioContext = original; };
return f;
})()""")
vendor/compose-mediaplayer/src/wasmJsTest/kotlin/io/github/kdroidfilter/composemediaplayer/BrowserVideoBindingTest.kt
- Source · test / fixture · 117 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
14: class BrowserVideoBindingTest {
76: private suspend fun drain() { repeat(6) { browserTick().await<JsAny?>(); yield() } }
77: private fun browserTick(): Promise<JsAny?> = js("new Promise(resolve => setTimeout(resolve, 0))")
78: private external interface BrowserFixture : JsAny {
83: fun resolveEntry()
84: fun resolveExit()
85: fun showB()
86: fun restore()
88: private fun fixture(): BrowserFixture = js("""(() => {
Exact file bytes / download · SHA-256 995041a692f1c93fd5ecf2f8fc092e9b7a243f568f602d2708a03c5d75b2c600.
Complete file
@file:OptIn(kotlin.js.ExperimentalWasmJsInterop::class)
package io.github.kdroidfilter.composemediaplayer
import kotlinx.coroutines.*
import kotlinx.coroutines.test.runTest
import org.w3c.dom.HTMLVideoElement
import org.w3c.dom.events.Event
import kotlin.js.JsAny
import kotlin.js.Promise
import kotlin.js.js
import kotlin.test.*
class BrowserVideoBindingTest {
@Test fun retirementRemovesCallbacksAndJoinsElementWork() = runTest {
val dom = fixture(); val parent = CoroutineScope(SupervisorJob() + Dispatchers.Main)
val entered = CompletableDeferred<Unit>(); val finish = CompletableDeferred<Unit>(); var events = 0
val binding = BrowserVideoBinding(dom.a, parent) { events++ }
try {
binding.listen("loadedmetadata") { events++ }
binding.scope.launch(start = CoroutineStart.UNDISPATCHED) {
try { awaitCancellation() }
finally { withContext(NonCancellable) { entered.complete(Unit); finish.await() } }
}
dom.a.setAttribute("src", "movie.mp4")
dom.a.dispatchEvent(Event("loadedmetadata")); assertEquals(1, events)
binding.dispose(); entered.await()
dom.a.dispatchEvent(Event("loadedmetadata")); dom.a.dispatchEvent(Event("enterpictureinpicture"))
assertEquals(1, events); assertNull(dom.a.getAttribute("src")); assertFalse(binding.active)
val close = async { binding.disposeAndJoin() }; drain()
assertFalse(close.isCompleted); finish.complete(Unit); close.await()
assertFalse(binding.requestPictureInPicture())
} finally { finish.complete(Unit); binding.disposeAndJoin(); parent.cancel(); dom.restore() }
}
@Test fun lateEntryIsExitedAndJoinedBeforeAnotherElementCanRequestPip() = runTest {
val dom = fixture(); val parent = CoroutineScope(SupervisorJob() + Dispatchers.Main)
val old = BrowserVideoBinding(dom.a, parent) {}; val fresh = BrowserVideoBinding(dom.b, parent) {}
try {
assertTrue(old.requestPictureInPicture()); assertEquals(1, dom.requests)
val close = async { old.disposeAndJoin() }; drain()
assertFalse(close.isCompleted); assertFalse(fresh.requestPictureInPicture())
dom.resolveEntry(); drain(); assertEquals(1, dom.exits); assertFalse(close.isCompleted)
dom.resolveExit(); close.await()
assertTrue(fresh.requestPictureInPicture()); assertEquals(2, dom.requests)
dom.resolveEntry(); drain()
val closeFresh = async { fresh.disposeAndJoin() }; drain()
assertFalse(closeFresh.isCompleted); dom.resolveExit(); closeFresh.await()
} finally { dom.resolveEntry(); dom.resolveExit(); old.disposeAndJoin(); fresh.disposeAndJoin(); parent.cancel(); dom.restore() }
}
@Test fun oldElementCannotExitAnotherElementsPipAndPausedOwnerCanExit() = runTest {
val dom = fixture(); val parent = CoroutineScope(SupervisorJob() + Dispatchers.Main)
val old = BrowserVideoBinding(dom.a, parent) {}; val fresh = BrowserVideoBinding(dom.b, parent) {}
try {
dom.showB(); old.disposeAndJoin(); assertEquals(0, dom.exits)
assertTrue(usablePictureInPicture(dom.b)); assertTrue(fresh.requestPictureInPicture())
assertEquals(1, dom.exits); dom.resolveExit(); drain(); fresh.disposeAndJoin()
} finally { dom.resolveExit(); old.disposeAndJoin(); fresh.disposeAndJoin(); parent.cancel(); dom.restore() }
}
@Test fun audioCleanupIsAwaitedAndRetriedWithoutReactivatingDom() = runTest {
val dom = fixture(); val parent = CoroutineScope(SupervisorJob() + Dispatchers.Main)
val entered = CompletableDeferred<Unit>(); val finish = CompletableDeferred<Unit>(); var fail = true; var attempts = 0
val binding = BrowserVideoBinding(dom.a, parent) {}
binding.releaseAudio = { attempts++; entered.complete(Unit); finish.await(); if (fail) error("audio close failed") }
try {
binding.dispose(); entered.await(); val close = async { runCatching { binding.disposeAndJoin() } }; drain()
assertFalse(close.isCompleted); finish.complete(Unit)
assertIs<IllegalStateException>(close.await().exceptionOrNull()); assertFalse(binding.active)
fail = false; binding.disposeAndJoin(); assertTrue(attempts >= 2); assertFalse(binding.active)
} finally { fail = false; finish.complete(Unit); binding.disposeAndJoin(); parent.cancel(); dom.restore() }
}
}
private suspend fun drain() { repeat(6) { browserTick().await<JsAny?>(); yield() } }
private fun browserTick(): Promise<JsAny?> = js("new Promise(resolve => setTimeout(resolve, 0))")
private external interface BrowserFixture : JsAny {
val a: HTMLVideoElement
val b: HTMLVideoElement
val requests: Int
val exits: Int
fun resolveEntry()
fun resolveExit()
fun showB()
fun restore()
}
private fun fixture(): BrowserFixture = js("""(() => {
const enabled = Object.getOwnPropertyDescriptor(document, 'pictureInPictureEnabled');
const element = Object.getOwnPropertyDescriptor(document, 'pictureInPictureElement');
const exit = Object.getOwnPropertyDescriptor(document, 'exitPictureInPicture');
let current = null, entryResolve = null, exitResolve = null;
const f = { a: document.createElement('video'), b: document.createElement('video'), requests: 0, exits: 0 };
Object.defineProperty(document, 'pictureInPictureEnabled', { configurable: true, value: true });
Object.defineProperty(document, 'pictureInPictureElement', { configurable: true, get: () => current });
Object.defineProperty(document, 'exitPictureInPicture', { configurable: true, value: () => {
f.exits++; return new Promise(resolve => { exitResolve = () => { current = null; resolve(null); }; });
}});
[f.a, f.b].forEach(video => {
document.body.appendChild(video);
Object.defineProperty(video, 'readyState', { configurable: true, value: 2 });
video.pause = () => {}; video.load = () => {};
video.requestPictureInPicture = () => { f.requests++; return new Promise(resolve => {
entryResolve = () => { current = video; resolve(null); };
}); };
});
f.resolveEntry = () => { const run = entryResolve; entryResolve = null; if (run) run(); };
f.resolveExit = () => { const run = exitResolve; exitResolve = null; if (run) run(); };
f.showB = () => { current = f.b; Object.defineProperty(f.b, 'readyState', { configurable: true, value: 0 }); };
f.restore = () => {
f.a.remove(); f.b.remove();
[['pictureInPictureEnabled', enabled], ['pictureInPictureElement', element], ['exitPictureInPicture', exit]].forEach(([name, descriptor]) => {
if (descriptor) Object.defineProperty(document, name, descriptor); else delete document[name];
});
};
return f;
})()""")
vendor/compose-mediaplayer/src/wasmJsTest/kotlin/io/github/kdroidfilter/composemediaplayer/VideoPlayerStateTest.kt
- Source · test / fixture · 188 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
12: class VideoPlayerStateTest {
18: fun testCreateVideoPlayerState() {
42: fun testVolumeControl() {
67: fun testLoopSetting() {
88: fun testFullscreenToggle() {
109: fun testErrorHandling() {
133: fun testSubtitleFunctionality() {
170: fun testPositionUpdates() {
Exact file bytes / download · SHA-256 e4700893691cb3290ccf6352aeafd90cf1c08d72c96349b7a2ed0db9fbeff346.
Complete file
package io.github.kdroidfilter.composemediaplayer
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
import kotlin.test.assertFalse
/**
* Tests for the WebAssembly/JavaScript implementation of VideoPlayerState
*/
class VideoPlayerStateTest {
/**
* Test the creation of VideoPlayerState
*/
@Test
fun testCreateVideoPlayerState() {
val playerState = VideoPlayerState()
// Verify the player state is initialized correctly
assertNotNull(playerState)
assertFalse(playerState.hasMedia)
assertFalse(playerState.isPlaying)
assertEquals(0f, playerState.sliderPos)
assertEquals(1f, playerState.volume)
assertFalse(playerState.loop)
assertEquals("00:00", playerState.positionText)
assertEquals("00:00", playerState.durationText)
assertEquals(0f, playerState.leftLevel)
assertEquals(0f, playerState.rightLevel)
assertFalse(playerState.isFullscreen)
// Clean up
playerState.dispose()
}
/**
* Test volume control
*/
@Test
fun testVolumeControl() {
val playerState = VideoPlayerState()
// Test initial volume
assertEquals(1f, playerState.volume)
// Test setting volume
playerState.volume = 0.5f
assertEquals(0.5f, playerState.volume)
// Test volume bounds
playerState.volume = -0.1f
assertEquals(0f, playerState.volume, "Volume should be clamped to 0")
playerState.volume = 1.5f
assertEquals(1f, playerState.volume, "Volume should be clamped to 1")
// Clean up
playerState.dispose()
}
/**
* Test loop setting
*/
@Test
fun testLoopSetting() {
val playerState = VideoPlayerState()
// Test initial loop setting
assertFalse(playerState.loop)
// Test setting loop
playerState.loop = true
assertTrue(playerState.loop)
playerState.loop = false
assertFalse(playerState.loop)
// Clean up
playerState.dispose()
}
/**
* Test fullscreen toggle
*/
@Test
fun testFullscreenToggle() {
val playerState = VideoPlayerState()
// Test initial fullscreen state
assertFalse(playerState.isFullscreen)
// Test toggling fullscreen
playerState.toggleFullscreen()
assertTrue(playerState.isFullscreen)
playerState.toggleFullscreen()
assertFalse(playerState.isFullscreen)
// Clean up
playerState.dispose()
}
/**
* Test error handling
*/
@Test
fun testErrorHandling() {
val playerState = VideoPlayerState()
// Initially there should be no error
assertEquals(null, playerState.error)
// Test setting an error manually (since we can't easily trigger a real error in tests)
playerState.setError(VideoPlayerError.NetworkError("Test error"))
// There should be an error now
assertNotNull(playerState.error)
// Test clearing the error
playerState.clearError()
assertEquals(null, playerState.error)
// Clean up
playerState.dispose()
}
/**
* Test subtitle functionality
*/
@Test
fun testSubtitleFunctionality() {
val playerState = VideoPlayerState()
// Initially subtitles should be disabled
assertFalse(playerState.subtitlesEnabled)
assertEquals(null, playerState.currentSubtitleTrack)
assertTrue(playerState.availableSubtitleTracks.isEmpty())
// Create a test subtitle track
val testTrack = SubtitleTrack(
label = "English",
language = "en",
src = "test.vtt"
)
// Select the subtitle track
playerState.selectSubtitleTrack(testTrack)
// Verify subtitle state
assertTrue(playerState.subtitlesEnabled)
assertEquals(testTrack, playerState.currentSubtitleTrack)
// Disable subtitles
playerState.disableSubtitles()
// Verify subtitle state after disabling
assertFalse(playerState.subtitlesEnabled)
assertEquals(null, playerState.currentSubtitleTrack)
// Clean up
playerState.dispose()
}
/**
* Test position updates
*/
@Test
fun testPositionUpdates() {
val playerState = VideoPlayerState()
// Test initial position
assertEquals(0f, playerState.sliderPos)
assertEquals("00:00", playerState.positionText)
assertEquals("00:00", playerState.durationText)
// Test updating position manually with forceUpdate to bypass rate limiting
playerState.updatePosition(30f, 120f, forceUpdate = true)
// Verify position was updated
assertEquals("00:30", playerState.positionText)
assertEquals("02:00", playerState.durationText)
// Clean up
playerState.dispose()
}
}