Skip to content

[video_player_android] Add VideoPlayerAndroidExternalApi for supplying media configuration - #12491

Open
a1rwulf wants to merge 1 commit into
flutter:mainfrom
a1rwulf:upstream_video-asset-provider-v2
Open

a1rwulf wants to merge 1 commit into
flutter:mainfrom
a1rwulf:upstream_video-asset-provider-v2

Conversation

@a1rwulf

@a1rwulf a1rwulf commented Aug 17, 2026 •

Copy link
Copy Markdown
Contributor

Adds VideoPlayerAndroidExternalApi, a documented native API modeled on WebViewFlutterAndroidExternalApi, that lets another package supply the Media3 MediaItem and MediaSource.Factory for a player. A package registers a MediaConfigProvider for its engine with setMediaConfigProvider(binding, provider); it is asked for every player created in that engine, and returning null keeps the plugin's own handling.

  • Only stable Media3 types are part of the signature; VideoAsset stays internal.
  • Providers are looked up when a player is created, so registration works regardless of plugin attachment order. The registering package removes its provider in onDetachedFromEngine.
  • The request passes the context, URI, the MIME type implied by the format hint, a read-only view of the HTTP headers, and the user agent. Its constructor is hidden from Java so fields can be added later.
  • Creating a player now releases the surface, event channel, and ExoPlayer if construction fails, which a provider's configuration can cause.
  • media3-exoplayer is now an api dependency, since MediaItem and MediaSource.Factory are in the public signature.
  • The README documents the API and what a provider is responsible for.

This lets a companion package play HLS downloads from a Media3 download cache (provider: https://github.com/a1rwulf/video_player_offline/blob/video-player-external-api/packages/video_player_offline_android/android/src/main/java/io/flutter/plugins/videoplayeroffline/OfflineMediaConfigProvider.java); offline playback was verified on an Android emulator in airplane mode.

Companion package: https://github.com/a1rwulf/video_player_offline/tree/video-player-external-api

Fixes flutter/flutter#59759

Pre-Review Checklist

If you need help, consider asking for advice on the #hackers-new channel on Discord.

Note: The Flutter team is currently trialing the use of Gemini Code Assist for GitHub. Comments from the gemini-code-assist bot should not be taken as authoritative feedback from the Flutter team. If you find its comments useful you can update your code accordingly, but if you are unsure or disagree with the feedback, please feel free to wait for a Flutter team member's review for guidance on which automated comments should be addressed.

Footnotes

  1. Regular contributors who have demonstrated familiarity with the repository guidelines only need to comment if the PR is not auto-exempted by repo tooling. ↩ ↩2

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces VideoAssetProvider and VideoPlayerPlugin.setVideoAssetProvider to the Android video player plugin, enabling custom video asset resolution for URIs. It also adds unit tests to verify this behavior and bumps the package version to 2.13.0. The reviewer recommended marking the static videoAssetProvider field as volatile to ensure thread visibility and prevent stale reads.

private final VideoPlayerOptions sharedOptions = new VideoPlayerOptions();
private long nextPlayerIdentifier = 1;

private static @Nullable VideoAssetProvider videoAssetProvider;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Since videoAssetProvider is a static field that can be set from any thread (e.g., during background initialization or dependency injection) and read on the main thread, it should be marked as volatile to ensure thread visibility and prevent stale reads.

Suggested change
private static @Nullable VideoAssetProvider videoAssetProvider;
private static volatile @Nullable VideoAssetProvider videoAssetProvider;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is valid.

@stuartmorgan-g

Copy link
Copy Markdown
Contributor

Adding @mboetger to review for whether allowing modification of ExoPlayer internals like this is something we want to expose; generally we minimize native hook points as they can significantly reduce our ability to make non-breaking updates in the future.

VideoAsset is already public and already exposes MediaItem and MediaSource.Factory, so this adds no new type surface; it only makes the existing one reachable.

Adding @bparrishMines to guide the design here if this does move forward. We traditionally do not consider our native plugin code to be a public API surface, and instead consider it equivalent to lib/src/. When we deviate from that we do so in limited and clearly documented ways, and @bparrishMines can point to examples of what that would look like.

@mboetger

Copy link
Copy Markdown
Contributor

I am not a fan on exposing the internal implementation as a public extension point.

@a1rwulf

a1rwulf commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor Author

I am not a fan on exposing the internal implementation as a public extension point.

Unfortunately I'm pretty much out of ideas on how to support offline playback on Android then, without making the whole download mechanism a feature of the player itself - which I think is even more unacceptable.

One approach that came to mind, was to use CreationOptions, something like this:

  offlineCache: {
    cacheDirectory: String,
    cacheKey: String?,
    streamKeys: [ {periodIndex, groupIndex, streamIndex}, … ],
  }

But this approach fails to the fact that SimpleCache is a single-instance-per-directory, so the very same plugin that does the download needs to own the cache for playback.

The last thing that would also make some sense:
Instead of a whole VideoAsset, the plugin could take a Cache plus the stream keys and still build the MediaItem and MediaSource.Factory itself. Then only one media3 interface is exposed instead of the asset class.

Edit:
I found flutter_plugin_android_lifecycle is doing something similar to what we'd need. Seems it's a helper package used by 4 other packages in this repository to share a native object between plugins. So a dedicated package holding the Cache would be another considerable option.

Would that be acceptable instead?

@bparrishMines

bparrishMines commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

In webview_flutter we expose the main class WebView/WKWebView in the native code of the platform implementations using an identifier:

https://pub.dev/packages/webview_flutter_android#external-native-api
https://github.com/flutter/packages/blob/main/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/WebViewFlutterAndroidExternalApi.java

Plugins are instanced because multiple could exist in an add-to-app Flutter app, so an instance method is recommended.

webview_flutter implementations also already use an identifier to reference a specific WebView. I don't think the video_player implementations do this, but there looks to be player identifiers.

@mboetger mboetger added the CICD Run CI/CD label Sep 15, 2026
@flutter-dashboard

Copy link
Copy Markdown

This pull request is not mergeable in its current state, likely because of a merge conflict. Pre-submit CI jobs were not triggered. Pushing a new commit to this branch that resolves the issue will result in pre-submit jobs being scheduled.

@elliette

Copy link
Copy Markdown
Member

[from triage] @mboetger what does the Android team think of the proposed approach above? Thanks!

@bparrishMines

Copy link
Copy Markdown
Contributor

@a1rwulf You stated that this is only and issue on Android, right? Do you know how this is handled on iOS?

Also, would it help if video_player supported adding VideoAssets to already initialized VideoPlayerControllerss?Similar to ExoPlayer.addMediaItem. So that you could use third party cache packages like flutter_cache_manager?

@a1rwulf

a1rwulf commented Oct 8, 2026

Copy link
Copy Markdown
Contributor Author

@bparrishMines Yes, this only affects Android. The reason is where each platform’s downloader puts the data.

iOS:
AVAssetDownloadURLSession writes a self-contained .movpkg bundle to disk. AVFoundation treats that bundle as a normal asset, so a file: URL pointing at it is all a player needs. The companion package just maps the source URL to the bundle’s location (and checks AVURLAsset.assetCache.isPlayableOffline). The app then passes that URL to an unmodified video_player, and video_player_avfoundation plays it like any other URL. Nothing has to be configured inside the player.

Android:
media3’s DownloadManager doesn’t produce a file. It writes segments into a SimpleCache as cache spans keyed by their original URIs, plus an index. There’s no path you could hand to a player. Playing a download requires two things inside the player:

A CacheDataSource over the same SimpleCache instance. SimpleCache allows only one instance per directory, so the player can’t open its own over the download directory. It has to use the downloader’s instance.
A MediaItem carrying the download’s stream keys (DownloadRequest.toMediaItem()). Without them, adaptive bitrate selection is free to pick a rendition that was never downloaded. That’s a cache miss, and offline it means a playback error.

Both live in the player’s MediaSource.Factory and MediaItem, which is why I ended up needing a hook into how video_player_android builds its VideoAsset. On iOS the downloader’s output is already something the player understands.

On addMediaItem + flutter_cache_manager: I don’t think it helps, for two reasons:

When the item is added isn’t the problem. The problem is which DataSource reads it. A VideoAsset added after initialization would still be read through the plugin’s own data source factory, which knows nothing about the download cache.
flutter_cache_manager caches single URLs as single files. That’s fine for progressive MP4, and that case already works today via VideoPlayerController.file. HLS/DASH is different: a manifest, per-rendition playlists, init segments, hundreds of media segments with relative URIs, and possibly key URIs. Caching that as plain files means writing an HLS downloader that picks a variant and rewrites the playlists to local paths. That’s exactly what media3’s DownloadManager/DownloadHelper already does, along with the parts that matter for real offline use: a foreground download service, resuming after process death, and requirements handling.

So the real need on Android is narrow: let playback for a given URL read through a Cache that something else owns, using a known set of stream keys. That’s why I asked about the shared-package route (in the style of flutter_plugin_android_lifecycle) holding the Cache. video_player_android would only need to accept that cache and the stream keys, not expose VideoAsset as an extension point.

I’m happy to move to an instance-based registration following the WebViewFlutterAndroidExternalApi pattern (one documented class, provider registered per engine via the plugin instance rather than a static). Identifier-keyed lookup on its own wouldn’t be enough here, though: the player id is assigned in the same call that builds and prepares the ExoPlayer, so by the time an id exists, playback has already started loading from the network. The cache has to be chosen before preparation, which is why the hook is keyed by URL at creation time.

@tarrinneal

Copy link
Copy Markdown
Contributor

@mboetger this is still waiting on your feedback

@mboetger

Copy link
Copy Markdown
Contributor
  1. I really don't think we should expose video_player_android's internal classes (VideoAsset is internal to the plugin and is becoming internal in [video_player] Convert implementation to Kotlin #13683).
  2. I also don't think we should expose Cache (or a shared Cache package) in the public API considering it's an @UnstableApi in Media3.
  3. I am open to the instance-based registration pattern via a documented VideoPlayerAndroidExternalApi (modeled on WebViewFlutterAndroidExternalApi) that only uses stable Media3 types (MediaItem and MediaSource.Factory) — something like this:
VideoPlayerAndroidExternalApi.setMediaConfigProvider(binding) { request ->
  val downloadRequest =
      downloadTracker.getDownloadRequest(Uri.parse(request.uri))
          ?: return@setMediaConfigProvider null
  VideoPlayerAndroidExternalApi.MediaConfig(
      mediaItem = downloadRequest.toMediaItem(),
      mediaSourceFactory = DefaultMediaSourceFactory(request.context)
          .setDataSourceFactory(cacheDataSourceFactory),
  )
}

A few implementation details if you go this route:

  • Pass a request object (context, uri, httpHeaders, userAgent) rather than positional args so we can add fields in the future without breaking the callback signature.
  • Write VideoPlayerAndroidExternalApi in Kotlin (ideally rebased once [video_player] Convert implementation to Kotlin #13683 lands), document it in README.md with the same breaking-change notice as WebViewFlutterAndroidExternalApi, and change media3-exoplayer from implementation(...) to api(...) in build.gradle.kts since MediaItem / MediaSource.Factory will be part of the public signature.
  • Watch out for plugin registration order in GeneratedPluginRegistrant: if another plugin calls setMediaConfigProvider(binding) inside onAttachedToEngine, binding.getPlugin(VideoPlayerPlugin::class.java) may still be null if that plugin attaches before VideoPlayerPlugin, so make sure the per-engine registration works regardless of attachment order and is cleaned up in onDetachedFromEngine.

…g media configuration

Adds a documented native API, modeled on WebViewFlutterAndroidExternalApi,
that lets other packages supply the Media3 MediaItem and MediaSource.Factory
for a player. A package registers a MediaConfigProvider for its engine with
setMediaConfigProvider(binding, provider); the provider is asked for every
player created in that engine, and returning null keeps the plugin's own
handling. This is what an offline-download package needs to play content
from a Media3 download cache.

- Providers are looked up when a player is created, so registration works
  regardless of plugin attachment order. They stay registered until the
  registering package removes them.
- The request carries the context, URI, the MIME type implied by the format
  hint, a read-only view of the HTTP headers, and the user agent. Its
  factory is hidden from Java so fields can be added later.
- Creating a player now releases the surface, event channel, and ExoPlayer
  if construction fails, which a provider's configuration can cause.
- media3-exoplayer becomes an api dependency because MediaItem and
  MediaSource.Factory are part of the public signature.
@a1rwulf
a1rwulf force-pushed the upstream_video-asset-provider-v2 branch from fa57d78 to 73926a5 Compare November 23, 2026 09:40
@flutter-dashboard flutter-dashboard Bot removed the CICD Run CI/CD label Nov 23, 2026
@github-actions
github-actions Bot marked this pull request as draft November 23, 2026 09:41
@github-actions github-actions Bot added the waiting for response The Flutter team cannot make further progress on this PR until the author responds label Nov 23, 2026
@github-actions

Copy link
Copy Markdown

Hi @a1rwulf, thank you for your contribution!

This pull request has been converted to a draft because it does not appear to follow our pull request template:

  • Unchecked checklist items (1 of 11): All items in the Pre-Review Checklist must be completed and checked off (- [x]) before the PR can be reviewed:
    • - [ ] I updated/added any relevant documentation (doc comments with `///`).

How to fix this

  1. Click the ... menu in the top-right corner of your PR description above and select Edit.
  2. Address the issues listed above. Make sure every item in the Pre-Review Checklist is present without modifications and checked off (- [x]).
  3. Save your changes, then click the "Ready for review" button at the bottom of the PR.
Click here for the raw Markdown of the Pre-Review Checklist to copy and paste
## Pre-Review Checklist

- [ ] I read the [Contributor Guide] and followed the process outlined there for submitting PRs.
- [ ] I read the [AI contribution guidelines] and understand my responsibilities, or I am not using AI tools.
- [ ] I read the [Tree Hygiene] page, which explains my responsibilities.
- [ ] I read and followed the [relevant style guides] and ran [the auto-formatter].
- [ ] I signed the [CLA].
- [ ] The title of the PR starts with the name of the package surrounded by square brackets, e.g. `[shared_preferences]`
- [ ] I [linked to at least one issue that this PR fixes] in the description above.
- [ ] I followed [the version and CHANGELOG instructions], using [semantic versioning] and the [repository CHANGELOG style], or I have commented below to indicate which documented exception this PR falls under[^1].
- [ ] I updated/added any relevant documentation (doc comments with `///`).
- [ ] I added new tests to check the change I am making, or I have commented below to indicate which [test exemption] this PR falls under[^1].
- [ ] All existing and new tests are passing.

If you need help, consider asking for advice on the #hackers-new channel on [Discord].

**Note**: The Flutter team is currently trialing the use of [Gemini Code Assist for GitHub](https://developers.google.com/gemini-code-assist/docs/review-github-code). Comments from the `gemini-code-assist` bot should not be taken as authoritative feedback from the Flutter team. If you find its comments useful you can update your code accordingly, but if you are unsure or disagree with the feedback, please feel free to wait for a Flutter team member's review for guidance on which automated comments should be addressed.

[^1]: Regular contributors who have demonstrated familiarity with the repository guidelines only need to comment if the PR is not auto-exempted by repo tooling.

<!-- Links -->
[Contributor Guide]: https://github.com/flutter/packages/blob/main/CONTRIBUTING.md
[AI contribution guidelines]: https://github.com/flutter/flutter/blob/master/CONTRIBUTING.ai.md#pull-requests
[Tree Hygiene]: https://github.com/flutter/flutter/blob/master/docs/contributing/Tree-hygiene.md
[relevant style guides]: https://github.com/flutter/packages/blob/main/CONTRIBUTING.md#style
[the auto-formatter]: https://github.com/flutter/packages/blob/main/script/tool/README.md#format-code
[CLA]: https://cla.developers.google.com/
[Discord]: https://github.com/flutter/flutter/blob/master/docs/contributing/Chat.md
[linked to at least one issue that this PR fixes]: https://github.com/flutter/flutter/blob/master/docs/contributing/Tree-hygiene.md#overview
[the version and CHANGELOG instructions]: https://github.com/flutter/flutter/blob/master/docs/ecosystem/contributing/README.md#version-and-changelog-updates
[semantic versioning]: https://dart.dev/tools/pub/versioning#semantic-versions
[repository CHANGELOG style]: https://github.com/flutter/flutter/blob/master/docs/ecosystem/contributing/README.md#changelog-style
[test exemption]: https://github.com/flutter/flutter/blob/master/docs/contributing/Tree-hygiene.md#tests

@github-actions github-actions Bot added the P3 Issues that are less important to the Flutter project label Nov 23, 2026
@a1rwulf

a1rwulf commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author
  1. I really don't think we should expose video_player_android's internal classes (VideoAsset is internal to the plugin and is becoming internal in [video_player] Convert implementation to Kotlin #13683).
  2. I also don't think we should expose Cache (or a shared Cache package) in the public API considering it's an @UnstableApi in Media3.
  3. I am open to the instance-based registration pattern via a documented VideoPlayerAndroidExternalApi (modeled on WebViewFlutterAndroidExternalApi) that only uses stable Media3 types (MediaItem and MediaSource.Factory) — something like this:
VideoPlayerAndroidExternalApi.setMediaConfigProvider(binding) { request ->
  val downloadRequest =
      downloadTracker.getDownloadRequest(Uri.parse(request.uri))
          ?: return@setMediaConfigProvider null
  VideoPlayerAndroidExternalApi.MediaConfig(
      mediaItem = downloadRequest.toMediaItem(),
      mediaSourceFactory = DefaultMediaSourceFactory(request.context)
          .setDataSourceFactory(cacheDataSourceFactory),
  )
}

A few implementation details if you go this route:

  • Pass a request object (context, uri, httpHeaders, userAgent) rather than positional args so we can add fields in the future without breaking the callback signature.
  • Write VideoPlayerAndroidExternalApi in Kotlin (ideally rebased once [video_player] Convert implementation to Kotlin #13683 lands), document it in README.md with the same breaking-change notice as WebViewFlutterAndroidExternalApi, and change media3-exoplayer from implementation(...) to api(...) in build.gradle.kts since MediaItem / MediaSource.Factory will be part of the public signature.
  • Watch out for plugin registration order in GeneratedPluginRegistrant: if another plugin calls setMediaConfigProvider(binding) inside onAttachedToEngine, binding.getPlugin(VideoPlayerPlugin::class.java) may still be null if that plugin attaches before VideoPlayerPlugin, so make sure the per-engine registration works regardless of attachment order and is cleaned up in onDetachedFromEngine.

@mboetger Thanks, I reworked the PR along those lines:

  • VideoPlayerAndroidExternalApi (Kotlin, rebased onto the Kotlin conversion) with setMediaConfigProvider(binding) { request -> MediaConfig(mediaItem, mediaSourceFactory)? }, using only MediaItem and MediaSource.Factory.
  • The callback receives a MediaConfigRequest (context, uri, mimeType from the format hint, httpHeaders, userAgent); its constructor isn't visible to Java, so fields can be added later.
  • Registration is per engine and works regardless of attachment order: providers are looked up when a player is created, and the registering plugin removes its provider in onDetachedFromEngine.
  • Documented in the README with the same breaking-change notice as WebViewFlutterAndroidExternalApi, and media3-exoplayer is now api(...).

@github-actions github-actions Bot removed the waiting for response The Flutter team cannot make further progress on this PR until the author responds label Nov 23, 2026
@a1rwulf
a1rwulf marked this pull request as ready for review November 23, 2026 10:22

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces VideoPlayerAndroidExternalApi to allow Android applications and packages to supply custom Media3 MediaItem and MediaSource.Factory configurations. It also adds resource cleanup logic to release ExoPlayer resources if player construction fails, refactors StreamingFormat to associate MIME types directly, and includes comprehensive unit and integration tests. Feedback on the changes highlights a potential NullPointerException in VideoPlayerPlugin.kt when wrapping options.httpHeaders with Collections.unmodifiableMap without a null check.

uri,
streamingFormat.mimeType,
// Read-only, so that a provider cannot change the headers of the fallback below.
Collections.unmodifiableMap(options.httpHeaders),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

options.httpHeaders can be null at runtime (for example, if no headers are provided or if the map is omitted). Passing a null map to Collections.unmodifiableMap will throw a NullPointerException. To prevent this, safely handle the nullability of options.httpHeaders by defaulting to an empty map.

Suggested change
Collections.unmodifiableMap(options.httpHeaders),
Collections.unmodifiableMap(options.httpHeaders ?: emptyMap()),

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CreationOptions.httpHeaders is non-nullable end to end: it's a required non-null Map<String, String> in the Pigeon definition (defaulting to const {} on the Dart side), and the generated Kotlin decoder casts it with as Map<String, String>, so it can't be null here. ?: emptyMap() would just be a no-op the compiler warns about.

@a1rwulf a1rwulf changed the title [video_player_android] allow supplying a custom VideoAsset [video_player_android] Add VideoPlayerAndroidExternalApi for supplying media configuration Nov 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

p: video_player P3 Issues that are less important to the Flutter project platform-android triage-android Should be looked at in Android triage

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Support for downloading videos and offline playback

6 participants