Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions packages/video_player/video_player_android/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
## 2.14.0

* Adds `VideoPlayerAndroidExternalApi`, a native API that lets apps and packages supply the Media3
`MediaItem` and `MediaSource.Factory` used for a player.
* Releases a player's native resources when creating it fails.

## 2.13.0

* Converts native implementation code to Kotlin.
Expand Down
77 changes: 77 additions & 0 deletions packages/video_player/video_player_android/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,83 @@ so you do not need to add it to your `pubspec.yaml`.
However, if you `import` this package to use any of its APIs directly, you
should add it to your `pubspec.yaml` as usual.

## External Native API

The plugin also provides a native API accessible by the native code of Android applications or
packages. This API follows the convention of breaking changes of the Dart API, which means that any
changes to the class that are not backwards compatible will only be made with a major version change
of the plugin. Native code other than this external API does not follow breaking change conventions,
so app or plugin clients should not use any other native APIs.

The API can be accessed by importing the native class `VideoPlayerAndroidExternalApi`. A package
that uses it must list `video_player_android` as a dependency in its own `pubspec.yaml`, since
depending on `video_player` alone does not make this plugin's native classes available to the
package's Android code.

Kotlin:

```kotlin
import io.flutter.plugins.videoplayer.VideoPlayerAndroidExternalApi
```

### Supplying the media configuration

A `MediaConfigProvider` can supply the Media3 `MediaItem` and `MediaSource.Factory` used for a
player, for example to play a download from a Media3 cache. It is consulted whenever a player is
created in the engine it was registered for, and returning `null` lets the plugin handle the player
as usual. Only one provider is supported per engine.

A returned configuration replaces all of the plugin's own loading setup, so a provider should:

* Apply the request's `httpHeaders` and `userAgent`, and allow cross-protocol redirects, in any data
source that can reach the network.
* Set the request's `mimeType`, which comes from the app's format hint, on the `MediaItem` if the
item does not already have one.
* Return a new `MediaSource.Factory` for each request. Factories hold per-player state, and sharing
one breaks DRM playback in every player after the first. Data source factories and caches can be
shared.
* Keep anything the factory reads, such as a cache, usable until the players created from it are
disposed. Removing the provider only affects players created afterwards.

Media3's download and cache APIs are marked `@UnstableApi`, so code using them needs
`@OptIn(UnstableApi::class)`:

```kotlin
@OptIn(UnstableApi::class)
override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
VideoPlayerAndroidExternalApi.setMediaConfigProvider(binding) { request ->
val downloadRequest =
downloadTracker.getDownloadRequest(Uri.parse(request.uri))
?: return@setMediaConfigProvider null
val upstreamFactory =
DefaultHttpDataSource.Factory()
.setUserAgent(request.userAgent)
.setAllowCrossProtocolRedirects(true)
.setDefaultRequestProperties(request.httpHeaders)
VideoPlayerAndroidExternalApi.MediaConfig(
mediaItem = downloadRequest.toMediaItem(),
mediaSourceFactory =
DefaultMediaSourceFactory(request.context)
.setDataSourceFactory(
CacheDataSource.Factory()
.setCache(downloadCache)
.setUpstreamDataSourceFactory(upstreamFactory)
.setCacheWriteDataSinkFactory(null)),
)
}
}

override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
VideoPlayerAndroidExternalApi.setMediaConfigProvider(binding, null)
}
```

Here `downloadTracker` and `downloadCache` stand for the package's own download index and the
Media3 cache it downloads into.

The provider can be set before or after `video_player_android` is attached to the engine. It stays
registered until it is removed, so remove it when the package detaches from the engine.

## Known issues

Using `VideoViewType.platformView` is not currently recommended on Android due to a known [issue][3] affecting platform views on Android.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,8 @@ android {

dependencies {
val exoplayerVersion = "1.9.2"
implementation("androidx.media3:media3-exoplayer:${exoplayerVersion}")
// Part of the public signature of VideoPlayerAndroidExternalApi.
api("androidx.media3:media3-exoplayer:${exoplayerVersion}")
implementation("androidx.media3:media3-exoplayer-hls:${exoplayerVersion}")
implementation("androidx.media3:media3-exoplayer-dash:${exoplayerVersion}")
implementation("androidx.media3:media3-exoplayer-rtsp:${exoplayerVersion}")
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// Copyright 2013 The Flutter Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.videoplayer

import android.content.Context
import androidx.media3.common.MediaItem
import androidx.media3.exoplayer.source.MediaSource

/** An asset configured by a [VideoPlayerAndroidExternalApi.MediaConfigProvider]. */
internal class ExternalVideoAsset(
assetUrl: String,
private val config: VideoPlayerAndroidExternalApi.MediaConfig
) : VideoAsset(assetUrl) {
override val mediaItem: MediaItem
get() = config.mediaItem

override fun getMediaSourceFactory(context: Context): MediaSource.Factory {
return config.mediaSourceFactory
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import android.content.Context
import androidx.annotation.OptIn
import androidx.annotation.VisibleForTesting
import androidx.media3.common.MediaItem
import androidx.media3.common.MimeTypes
import androidx.media3.common.util.UnstableApi
import androidx.media3.datasource.DataSource
import androidx.media3.datasource.DefaultDataSource
Expand All @@ -24,13 +23,7 @@ internal class HttpVideoAsset(
override val mediaItem: MediaItem
get() {
val builder = MediaItem.Builder().setUri(assetUrl)
val mimeType: String? =
when (streamingFormat) {
StreamingFormat.SMOOTH -> MimeTypes.APPLICATION_SS
StreamingFormat.DYNAMIC_ADAPTIVE -> MimeTypes.APPLICATION_MPD
StreamingFormat.HTTP_LIVE -> MimeTypes.APPLICATION_M3U8
else -> null
}
val mimeType = streamingFormat.mimeType
if (mimeType != null) {
builder.setMimeType(mimeType)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ package io.flutter.plugins.videoplayer

import android.content.Context
import androidx.media3.common.MediaItem
import androidx.media3.common.MimeTypes
import androidx.media3.exoplayer.source.MediaSource

/** A video to be played by [VideoPlayer]. */
Expand All @@ -26,18 +27,18 @@ protected constructor(@JvmField protected val assetUrl: String?) {
abstract fun getMediaSourceFactory(context: Context): MediaSource.Factory

/** Streaming formats that can be provided to the video player as a hint. */
internal enum class StreamingFormat {
internal enum class StreamingFormat(val mimeType: String?) {
/** Default, if the format is either not known or not another valid format. */
UNKNOWN,
UNKNOWN(null),

/** Smooth Streaming. */
SMOOTH,
SMOOTH(MimeTypes.APPLICATION_SS),

/** MPEG-DASH (Dynamic Adaptive over HTTP). */
DYNAMIC_ADAPTIVE,
DYNAMIC_ADAPTIVE(MimeTypes.APPLICATION_MPD),

/** HTTP Live Streaming (HLS). */
HTTP_LIVE
HTTP_LIVE(MimeTypes.APPLICATION_M3U8)
}

companion object {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,12 +47,19 @@ constructor(

// TODO: Migrate to stable API, see https://github.com/flutter/flutter/issues/147039.
init {
exoPlayer.setMediaItem(mediaItem)
exoPlayer.prepare()
val listener = createExoPlayerEventListener(exoPlayer, surfaceProducer)
exoPlayerEventListener = listener
exoPlayer.addListener(listener)
setAudioAttributes(exoPlayer, options.mixWithOthers)
try {
exoPlayer.setMediaItem(mediaItem)
exoPlayer.prepare()
val listener = createExoPlayerEventListener(exoPlayer, surfaceProducer)
exoPlayerEventListener = listener
exoPlayer.addListener(listener)
setAudioAttributes(exoPlayer, options.mixWithOthers)
} catch (e: Throwable) {
// The player is never handed out if construction fails, so nothing else would release it and
// its playback thread.
exoPlayer.release()
throw e
}
}

fun setDisposeHandler(handler: (() -> Unit)?) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
// Copyright 2013 The Flutter Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.videoplayer

import android.content.Context
import androidx.annotation.RestrictTo
import androidx.media3.common.MediaItem
import androidx.media3.exoplayer.source.MediaSource
import io.flutter.Log
import io.flutter.embedding.engine.plugins.FlutterPlugin.FlutterPluginBinding
import io.flutter.plugin.common.BinaryMessenger
import java.util.WeakHashMap

/**
* App and package facing native API provided by the `video_player_android` plugin.
*
* This class follows the convention of breaking changes of the Dart API, which means that any
* changes to the class that are not backwards compatible will only be made with a major version
* change of the plugin.
*
* Native code other than this external API does not follow breaking change conventions, so app or
* plugin clients should not use any other native APIs.
*/
object VideoPlayerAndroidExternalApi {
private const val TAG = "VideoPlayerExternalApi"

/**
* Providers by the binary messenger of the engine they were registered for.
*
* Weak keys let the entry of a destroyed engine be collected only if the provider does not itself
* reference that engine, for example through its plugin's channels, so callers must still remove
* their provider. Binary messengers do not override `equals`, so lookups are by identity.
*/
private val providers = WeakHashMap<BinaryMessenger, MediaConfigProvider>()

/**
* Sets the [MediaConfigProvider] consulted for every player created in the engine that `binding`
* belongs to.
*
* Only one provider is supported per engine. Setting a provider replaces any previously set one,
* including one set by another package, and passing `null` removes whichever provider is current.
*
* This can be called from `onAttachedToEngine` regardless of whether `VideoPlayerPlugin` has been
* attached to the engine yet, since the provider is only looked up when a player is created.
*
* The provider stays registered until it is replaced or removed, so callers must pass `null` from
* their own `onDetachedFromEngine`; otherwise the provider and everything it references are kept
* for the lifetime of the process.
*
* Removing a provider only affects players created afterwards. Players that already exist keep
* using the [MediaConfig] they were given, so anything its [MediaConfig.mediaSourceFactory]
* reads, such as a cache, must stay usable until those players are disposed.
*
* Can be called from any thread. A provider removed from another thread may still receive a call
* that was already in progress.
*
* @param binding the binding of the calling plugin, which identifies the engine.
* @param provider the provider, or `null` to remove the current one.
*/
@JvmStatic
fun setMediaConfigProvider(binding: FlutterPluginBinding, provider: MediaConfigProvider?) {
val messenger = binding.binaryMessenger
synchronized(providers) {
if (provider == null) {
providers.remove(messenger)
} else {
val previous = providers.put(messenger, provider)
if (previous != null && previous !== provider) {
Log.w(TAG, "Replacing the MediaConfigProvider previously set for this engine.")
}
}
}
}

@JvmSynthetic
internal fun getMediaConfigProvider(messenger: BinaryMessenger): MediaConfigProvider? {
synchronized(providers) {
return providers[messenger]
}
}

/** Supplies the media configuration for players that the plugin should not configure itself. */
fun interface MediaConfigProvider {
/**
* Returns the configuration to play `request` with, or `null` to let the plugin handle it as it
* would without a provider.
*
* A returned configuration replaces all of the plugin's own loading setup for that player. That
* includes applying [MediaConfigRequest.httpHeaders] and [MediaConfigRequest.userAgent] and
* following cross-protocol redirects, so a provider whose media source can reach the network
* must do those itself.
*
* Called on the platform thread while a player is being created, so this should not block. An
* exception thrown here fails the creation of the player.
*/
fun getMediaConfig(request: MediaConfigRequest): MediaConfig?
}

/** Describes a player that is about to be created. */
class MediaConfigRequest
private constructor(
/** The application context. */
val context: Context,
/**
* The URI of the video.
*
* For network, file, and content sources this is the URI the app supplied. For assets it is
* `asset:///` followed by the asset's lookup key, for example
* `asset:///flutter_assets/assets/video.mp4`.
*/
val uri: String,
/**
* The MIME type implied by the app's format hint, such as
* [androidx.media3.common.MimeTypes.APPLICATION_M3U8], or `null` if no hint was given.
*
* Media3 infers the format from the URI when a [MediaItem] has no MIME type, so set this on
* the returned item to honor the hint.
*/
val mimeType: String?,
/** The HTTP headers the player was created with, as a read-only map. */
val httpHeaders: Map<String, String>,
/**
* The user agent for HTTP requests.
*
* This is the `User-Agent` entry of [httpHeaders] if there is one, and otherwise the plugin's
* default, currently `ExoPlayer`.
*/
val userAgent: String?
) {
// Requests are only created by the plugin. The factory is hidden from Java, so adding a field
// cannot break code that constructs requests.
@RestrictTo(RestrictTo.Scope.LIBRARY)
internal companion object {
@JvmSynthetic
internal fun create(
context: Context,
uri: String,
mimeType: String?,
httpHeaders: Map<String, String>,
userAgent: String?
): MediaConfigRequest = MediaConfigRequest(context, uri, mimeType, httpHeaders, userAgent)
}
}

// Any field added later must have a default value and be added together with @JvmOverloads, so
// that Java callers of this two-argument constructor keep working.
/** The media a player should play, and how to load it. */
class MediaConfig(
/** The media item to play. */
val mediaItem: MediaItem,
/**
* The factory used to create the media source for [mediaItem].
*
* Return a new factory for each request rather than sharing one between players. Media3
* factories hold per-player state; for example, a shared factory fails DRM playback in every
* player after the first. Data source factories and caches can be shared.
*/
val mediaSourceFactory: MediaSource.Factory
)
}
Loading