# Migrate from ComposeMediaPlayer

Move an app from ComposeMediaPlayer to the Nucleus media modules. Swap the coordinates and the package, run desktop video under nucleusApplication, and adapt the few APIs that were renamed or removed.

ComposeMediaPlayer (`io.github.kdroidfilter:composemediaplayer` and `composemediaplayer-audio`)
now lives in the Nucleus repository as the [media modules](/docs/media). Most of its API is
unchanged: the same `VideoPlayerState`, `VideoPlayerSurface` and `AudioPlayer`, under a new
package. This page lists what you change and what behaves differently.

Its code moved. Nucleus imported it from `kdroidFilter/ComposeMediaPlayer` (MIT, same author) and
rebuilt it: one implementation of the player shared by every platform instead of six, with only
the decoding engine left per platform. New work happens in Nucleus.

## Why the code moved

The player now builds on other parts of Nucleus. On the desktop, the video is a
[`TextureView`](/docs/native-content/texture-view) of the Nucleus window runtime: the decoder's GPU
texture is composited in the Compose scene without a CPU copy, and the fullscreen player is a
Nucleus window. In one repository, the player, the window runtime, the packaging and the other
modules are built, tested and released together:

- **One version.** Every module ships with the same Nucleus version, so the player always matches
  the window runtime it renders through.
- **One CI pipeline.** It builds the natives of every platform (Windows, macOS, Linux, x64 and
  arm64) and publishes every target (JVM, Android, iOS, JS, Wasm) in the same release.
- **One conformance suite.** The same scenarios check each engine against the same rules: frame
  read back from the screen, exact positions, state traces.

A change to the window runtime that would break the video surface fails in the same pull request.

## What's new

ComposeMediaPlayer covered the basics: open, play, pause, seek, volume, loop, speed, fullscreen,
picture-in-picture, external subtitles and metadata. The Nucleus media modules add far more, on
every platform unless [Platform support](/docs/media/platform-support) says otherwise:

- **[Playback](/docs/media/playback)**: playlists, exact or key-frame seek modes, speed with or
  without pitch, skipped silences, a loudness boost and an equalizer, playback stats.
- **[Streaming](/docs/media/streaming)**: HLS on every platform, MPEG-DASH and Smooth Streaming,
  live streams with a DVR window, audio languages and video variants to choose from, in-stream
  subtitles, request headers (tokens, cookies) on every request, timed metadata.
- **[Offline](/docs/media/offline)**: download files and HLS for offline playback with
  `MediaDownloads`, with progress.
- **[System media controls](/docs/media/system-session)** with `media-session`: lock screen,
  notification and background playback on Android, Now Playing on macOS and iOS, SMTC on Windows,
  MPRIS on Linux.
- **[Thumbnails](/docs/media/video)**: `loadVideoThumbnail` reads a frame at a position, without
  a player.
- **[Audio](/docs/media/audio)**: `AudioPlayer` runs on the same engine as the video, so it plays
  what the video player plays and behaves the same way.
- **Behaviour you can rely on**: one implementation shared by every platform, checked by the same
  conformance scenarios: the frame shown after a seek is the frame asked for, a failed media no
  longer blocks the next one, rotated videos are upright, and the desktop composites the video on
  the GPU without copying frames on the CPU.

## You don't need the whole framework

Nucleus is modular: each media module is a separate artifact, and only one case needs the rest of
Nucleus.

- **Android, iOS and the web**: the media modules are a library like any other. No Nucleus
  application, plugin or window.
- **Audio on the desktop**: `audio-player` (and `media-engine`) work in any JVM app, Compose
  Desktop included.
- **Video on the desktop** is the exception: it needs Nucleus windows (`nucleusApplication`).
  The video is a GPU texture composited in the Compose scene by the Nucleus window runtime, so
  it scales, clips, blurs and draws under Compose content like any other node, without copying a
  frame on the CPU. Doing the same on AWT, the backend of Compose Desktop's windows, took hack
  after hack (a heavyweight `SwingPanel` that Compose cannot draw over, or a CPU copy of every
  frame into a bitmap), each one paid for in performance, and too much to keep working alone.
  The Nucleus window runtime is built for this kind of use.

## Before you start

- **Compose Multiplatform 1.13 or later.** The web surface draws each frame through a WebGL texture
  shared with Compose, which needs 1.13.
- **Desktop video needs the Nucleus window runtime.** `VideoPlayerSurface` draws through
  `TextureView`, which only renders inside a Nucleus window: in a Compose Desktop (AWT) `Window` it
  shows an empty box. Run the app with `nucleusApplication` and Nucleus windows; see
  [Migrate from JetBrains Compose Desktop](/docs/migrate/from-jb-compose). `audio-player` and
  `media-engine` need no window runtime and work in any JVM app.
- **Linux needs the system's GStreamer** (1.20 or later, with the base, good, bad and libav
  plugins). The video player already used it; `AudioPlayer` now does too, instead of its own Rust
  decoder (Rodio). It is not bundled: without it, opening a media reports an error.

## Swap the dependencies

| ComposeMediaPlayer | Nucleus | Use it for |
| ------------------ | ------- | ---------- |
| `io.github.kdroidfilter:composemediaplayer` | `dev.nucleusframework:nucleus.media-player` | Video: `VideoPlayerState`, `VideoPlayerSurface`, subtitles, fullscreen, picture-in-picture |
| `io.github.kdroidfilter:composemediaplayer-audio` | `dev.nucleusframework:nucleus.audio-player` | Audio only: `AudioPlayer` |
| `androidx.media3:media3-exoplayer-hls`, added by hand on Android | `dev.nucleusframework:nucleus.media-hls` | HLS (`.m3u8`) on Android and the web |
| — | `dev.nucleusframework:nucleus.media-dash` | MPEG-DASH (`.mpd`) |
| — | `dev.nucleusframework:nucleus.media-smoothstreaming` | Smooth Streaming (`.ism/Manifest`) |
| — | `dev.nucleusframework:nucleus.media-session` | The system's media controls: lock screen, notification, Now Playing, SMTC |
| — | `dev.nucleusframework:nucleus.media-engine` | The playback state without UI and `MediaDownloads`; the two players bring it |

```diff title="build.gradle.kts"
 kotlin {
     sourceSets {
         commonMain.dependencies {
-            implementation("io.github.kdroidfilter:composemediaplayer:0.11.4")
-            implementation("io.github.kdroidfilter:composemediaplayer-audio:0.11.4")
+            implementation("dev.nucleusframework:nucleus.media-player:3.0.0")
+            implementation("dev.nucleusframework:nucleus.audio-player:3.0.0")
+            // Optional: the streaming formats you play and the system's media controls
+            implementation("dev.nucleusframework:nucleus.media-hls:3.0.0")
+            implementation("dev.nucleusframework:nucleus.media-session:3.0.0")
         }
-        androidMain.dependencies {
-            implementation("androidx.media3:media3-exoplayer-hls:<version>")
-        }
+        jvmMain.dependencies {
+            // nucleusApplication and the Nucleus windows the desktop surface renders in
+            implementation("dev.nucleusframework:nucleus.nucleus-application:3.0.0")
+        }
     }
 }
```

Use Nucleus 3.0.0 or later. The modules cover the same targets as before: JVM desktop, Android,
iOS (`iosArm64`, `iosSimulatorArm64`), JS and Wasm. Nucleus publishes no CocoaPods spec for them.

## Update the imports

Every package keeps its structure under a new root:

| ComposeMediaPlayer | Nucleus | Holds |
| ------------------ | ------- | ----- |
| `io.github.kdroidfilter.composemediaplayer` | `dev.nucleusframework.mediaplayer` | `VideoPlayerState`, `VideoPlayerSurface`, `rememberVideoPlayerState`, `InitialPlayerState`, `VideoPlayerError`, `VideoMetadata`, `SubtitleTrack`, `AudioMode`, `CacheConfig`, `SurfaceType`, `AutoPipEffect` |
| `io.github.kdroidfilter.composemediaplayer.subtitle` | `dev.nucleusframework.mediaplayer.subtitle` | `SrtParser`, `WebVttParser`, `SubtitleCue`, `SubtitleDisplay`, `ComposeSubtitleLayer` |
| `io.github.kdroidfilter.composemediaplayer.util` | `dev.nucleusframework.mediaplayer.util` | `PipResult`, `PlatformFile.getUri()`, the logging switches |
| `io.github.kdroidfilter.composemediaplayer.audio` | `dev.nucleusframework.mediaplayer.audio` | `AudioPlayer`, `AudioPlayerState`, `ErrorListener`, `rememberAudioPlayerLiveState` |
| `…composemediaplayer.windows`, `.mac`, `.linux`, `.common`, `.jsinterop` | — | Removed: per-platform classes, see [Removed APIs](#removed-apis) |

A search and replace of the root moves them all:

```bash
grep -rl 'io.github.kdroidfilter.composemediaplayer' --include='*.kt' src \
  | xargs sed -i 's/io\.github\.kdroidfilter\.composemediaplayer/dev.nucleusframework.mediaplayer/g'
```

On macOS, write `sed -i ''`. What still fails to compile afterwards is on the lists below.

## Move the video player

The video API is the same: `rememberVideoPlayerState(audioMode, cacheConfig)`,
`createVideoPlayerState()`, `openUri`, `openFile`, `openAsset`, `play`, `pause`, `stop`, `restart`,
`seekTo`, `seekStart` / `seekFinished`, `sliderPos`, `volume`, `loop`, `playbackSpeed`,
`onPlaybackEnded`, `onRestart`, `isLoading`, `error` / `clearError()`, `metadata`, the subtitle
members, `isFullscreen` / `toggleFullscreen()`, the picture-in-picture members, `clearCache()` and
`VideoPlayerSurface(playerState, modifier, contentScale, overlay)`. Common code changes its imports
only:

```diff
-import io.github.kdroidfilter.composemediaplayer.InitialPlayerState
-import io.github.kdroidfilter.composemediaplayer.VideoPlayerSurface
-import io.github.kdroidfilter.composemediaplayer.rememberVideoPlayerState
+import dev.nucleusframework.mediaplayer.InitialPlayerState
+import dev.nucleusframework.mediaplayer.VideoPlayerSurface
+import dev.nucleusframework.mediaplayer.rememberVideoPlayerState

 @Composable
 fun Player(url: String) {
     val player = rememberVideoPlayerState()
     LaunchedEffect(url) { player.openUri(url, InitialPlayerState.PAUSE) }
     VideoPlayerSurface(player, Modifier.fillMaxSize()) {
         PlayerControls(player)
     }
 }
```

| Area | ComposeMediaPlayer | Nucleus |
| ---- | ------------------ | ------- |
| Create | `rememberVideoPlayerState()`, `createVideoPlayerState()` | Same |
| Open | `openUri(uri, initializeplayerState)`, `openFile(platformFile)`, `openAsset(name)` | Same, plus `openUri(uri, headers)` and `setPlaylist(items)` |
| Transport | `play()`, `pause()`, `stop()`, `restart()` | Same; `stop()` rewinds to 0 and keeps the media loaded on every platform |
| Seek | `seekTo(0..1000)`, `seekStart` / `seekFinished` | Same, plus `seekMode` |
| Volume, loop, speed | `volume`, `loop`, `playbackSpeed` (0.25 to 2) | Same; kept across opens |
| End and loop events | `onPlaybackEnded`, `onRestart` | Same |
| Errors | `error` (`CodecError`, `NetworkError`, `SourceError`, `UnknownError`), `clearError()` | Same classes; the next open plays normally after an error |
| Metadata | `metadata` (`VideoMetadata`) | Same fields; a field the platform cannot report stays `null` |
| Subtitles | `selectSubtitleTrack(SubtitleTrack(…))`, `subtitleTextStyle`, `subtitleBackgroundColor`, `disableSubtitles()` | Same; subtitles carried by a stream are [tracks](/docs/media/streaming) |
| Fullscreen | `toggleFullscreen()`, `isFullscreen`; `openFullscreenWindow` (desktop), `openFullscreenView` (iOS) | `toggleFullscreen()` and `isFullscreen` on every platform |
| Surface | `VideoPlayerSurface(playerState, modifier, contentScale, overlay)` | Same |
| Android surface | `VideoPlayerSurface(…, surfaceType = SurfaceType.SurfaceView)` | Same |
| Picture-in-picture | `isPipSupported`, `isPipEnabled`, `isPipActive`, `enterPip()`, `AutoPipEffect` | Same; see [Android picture-in-picture](#android-picture-in-picture) |
| Cache | `CacheConfig`, `clearCache()` | Same (Android and iOS) |
| Audio focus | `AudioMode`, `InterruptionMode` | Same (Android and iOS) |
| Previews | `PreviewableVideoPlayerState` | Same |

### Desktop: run under nucleusApplication

A desktop video renders only inside a Nucleus window. Replace Compose Desktop's `application` and
`Window`:

```diff
-import androidx.compose.ui.window.Window
-import androidx.compose.ui.window.application
+import dev.nucleusframework.application.Window
+import dev.nucleusframework.application.nucleusApplication

-fun main() = application {
+fun main(args: Array<String>) = nucleusApplication(args) {
     Window(onCloseRequest = ::exitApplication, title = "Player") {
         Player("https://example.com/movie.mp4")
     }
 }
```

The rest of the app's move (Gradle plugin, dialogs, tray) is in
[Migrate from JetBrains Compose Desktop](/docs/migrate/from-jb-compose). In exchange, the video is
ordinary Compose content: overlays, subtitles, `blur()`, clipping and `ContentScale.Crop` compose
with it on Windows, macOS and Linux, with no `SwingPanel`.

The fullscreen player is a Nucleus window in real fullscreen. Esc or closing it sets `isFullscreen`
to `false`.

### Android picture-in-picture

The Android player class is now `AndroidVideoPlayerState`. Its companion holds the hooks that were
on `DefaultVideoPlayerState`:

```diff
 class MainActivity : ComponentActivity() {
     override fun onCreate(savedInstanceState: Bundle?) {
         super.onCreate(savedInstanceState)
-        DefaultVideoPlayerState.activity = WeakReference(this)
+        AndroidVideoPlayerState.activity = WeakReference(this)
     }

     override fun onPictureInPictureModeChanged(isInPipMode: Boolean, newConfig: Configuration) {
         super.onPictureInPictureModeChanged(isInPipMode, newConfig)
-        DefaultVideoPlayerState.onPictureInPictureModeChanged(isInPipMode)
+        AndroidVideoPlayerState.onPictureInPictureModeChanged(isInPipMode)
     }
 }
```

`VideoPlayerSurface` already applies `AutoPipEffect`: call it yourself only around a surface of your
own. Picture-in-picture is still Android and iOS only.

### Removed APIs

| ComposeMediaPlayer | Nucleus |
| ------------------ | ------- |
| `WindowsVideoPlayerState`, `MacVideoPlayerState`, `LinuxVideoPlayerState` | `createVideoPlayerState()` / `rememberVideoPlayerState()`: one player on every platform |
| `WindowsVideoPlayerSurface`, `MacVideoPlayerSurface`, `LinuxVideoPlayerSurface` | `VideoPlayerSurface` |
| `openFullscreenWindow` (desktop), `openFullscreenView` (iOS), `FullscreenManager` (web) | `isFullscreen` / `toggleFullscreen()` |
| `VideoPlayerStateRegistry` (desktop, iOS) | Nothing: the fullscreen surface reads the same state |
| `Modifier.videoRatioClip` (web) | Nothing: the web video is drawn by Compose, with no hole to cut in the canvas |
| `DefaultVideoPlayerState.activity`, `DefaultVideoPlayerState.onPictureInPictureModeChanged` (Android) | `AndroidVideoPlayerState.activity`, `AndroidVideoPlayerState.onPictureInPictureModeChanged` |

If you implement `VideoPlayerState` yourself (a fake for tests), it now also needs
`val playback: MediaPlaybackState`, the playback underneath every player.

### Behaviour that changed

The player now follows one written contract on every platform, so a few platform-specific
behaviours are gone:

- **`stop()`** pauses and rewinds to exactly 0, the media stays loaded and frame 0 shows. Android
  used to drop the media.
- **After an error** the next open plays normally (#253). A decoder error on Android is reported
  as an error instead of silently re-creating the player.
- **Volume** applies at once, also while paused (iOS applied it only while playing).
- **Metadata** reports only what the platform knows: iOS no longer reports 2 channels and 44.1 kHz
  for every file. Sizes are the displayed ones, rotation applied (#202).
- **Seeks** show the frame whose interval contains the target, also while paused (#139); paused,
  the position is the start of the frame on screen.
- **Loops** are the engine's own where it has one (Media Foundation, ExoPlayer, `<video loop>`), so
  the restart is near gapless (#126).
- **The web** updates `currentTime` every 100 ms instead of about once a second (#228), and no longer
  retries a refused cross-origin media without CORS.
- **Fullscreen on the web** is the browser's: leaving it with Esc or the browser's UI turns
  `isFullscreen` off (#251).
- **Windows** decodes through the Media Foundation media engine (no more CPU copies into Skia
  bitmaps nor its own WASAPI renderer): WMV plays (#254), and a 24-bit / 96 kHz output device gets
  audio (#269).
- **Linux** accepts every `file:` URI form (#6), and `VideoMetadata.duration` is in milliseconds
  (#153).

See [Platform support](/docs/media/platform-support) for what each engine does differently.

## Move the audio player

`AudioPlayer` keeps its methods: `play(url, loop)`, `play()`, `pause()`, `stop()`,
`seekTo(ms)`, `setVolume`, `setRate`, `currentPosition()`, `currentDuration()`,
`currentPlayerState()`, `currentVolume()`, `setOnErrorListener`, `release()`, and
`rememberAudioPlayerLiveState()`.

```diff
-import io.github.kdroidfilter.composemediaplayer.audio.ErrorListener
-import io.github.kdroidfilter.composemediaplayer.audio.isPlaying
-import io.github.kdroidfilter.composemediaplayer.audio.rememberAudioPlayerLiveState
+import dev.nucleusframework.mediaplayer.audio.rememberAudioPlayerLiveState

 val live = rememberAudioPlayerLiveState()
-live.player.setOnErrorListener(object : ErrorListener {
-    override fun onError(message: String?) { println(message) }
-})
-if (live.player.isPlaying()) live.player.pause()
+live.player.setOnErrorListener { message -> println(message) }
+if (live.player.isPlaying) live.player.pause()
```

What changed:

- **`isPlaying()`**, an extension function, is now the `isPlaying` property.
- **`ErrorListener`** is a `fun interface`: pass a lambda. `setOnErrorListener(null)` stops the
  calls.
- **State reads are Compose state.** `state`, `positionMs`, `durationMs`, `volume`, `rate`, `error`
  and `isPlaying` recompose as they change. `rememberAudioPlayerLiveState` no longer polls every
  300 ms, and takes the same `AudioMode` and `CacheConfig` as the video player.
- **`currentPlayerState()` and `currentVolume()`** no longer return `null`.
- **`AudioPlayerState.PAUSED`** also covers stopped and ended; `IDLE` is no media (never opened,
  failed or released).
- **`stop()`** pauses and rewinds to 0 in every state.
- **The desktop decodes with the OS**: Media Foundation on Windows, AVFoundation on macOS,
  GStreamer on Linux, instead of Rodio. MP3, AAC (M4A), FLAC and WAV play on every platform; other
  formats depend on the platform's decoders. `setRate` now works on the desktop.
- **New**: `loop`, playlists (`play(items)`, `next()`, `previous()`, `skipTo()`, `repeatMode`,
  `shuffle`), `tracks` and `selectTrack`, `isLive`. A video file plays without decoding its picture.

## Streaming

HLS played natively on the desktop and iOS, through a Media3 module you added on Android, and not
at all on the web. Now each streaming format is a Nucleus module: add `media-hls`, `media-dash` or
`media-smoothstreaming` and the players open its URLs on every platform where an engine supports
it. `media-hls` brings `media3-exoplayer-hls` on Android and hls.js on the web, so drop your own
Media3 HLS dependency. The desktop and iOS play HLS natively, with or without the module. See
[Streaming](/docs/media/streaming).

## Logging

| ComposeMediaPlayer | Nucleus |
| ------------------ | ------- |
| `allowComposeMediaPlayerLogging` | `allowMediaPlayerLogging` |
| `composeMediaPlayerLoggingLevel` | `mediaPlayerLoggingLevel` |
| `ComposeMediaPlayerLoggingLevel.VERBOSE` … `ERROR` | `MediaPlayerLoggingLevel.VERBOSE` … `ERROR` (an enum) |

The switches apply to Android, iOS and the web. On the desktop every message goes to
`java.util.logging` under the `dev.nucleusframework.mediaplayer` logger, whose level your app
controls; the switches are ignored there.

## Checklist

- Replace `composemediaplayer` and `composemediaplayer-audio` with `nucleus.media-player` and
  `nucleus.audio-player`; add `media-hls`, `media-dash`, `media-smoothstreaming` or
  `media-session` if you use them.
- Remove `androidx.media3:media3-exoplayer-hls` if you added it for HLS: `media-hls` brings it.
- Replace `io.github.kdroidfilter.composemediaplayer` with `dev.nucleusframework.mediaplayer`
  in the imports.
- Desktop: run under `nucleusApplication` with Nucleus windows, and use Compose Multiplatform
  1.13 or later.
- Linux: install GStreamer 1.20+ and its plugins, now also for `AudioPlayer`.
- Replace the per-platform states, surfaces and fullscreen helpers with `VideoPlayerState`,
  `VideoPlayerSurface` and `isFullscreen`.
- Android: call `AndroidVideoPlayerState.activity` and
  `AndroidVideoPlayerState.onPictureInPictureModeChanged` from the activity.
- Audio: `isPlaying()` becomes `isPlaying`, `ErrorListener` becomes a lambda.
- Rename the logging switches.
- Check what depended on the old `stop()`, error or metadata behaviour.
