You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
[PR] Fix iOS/macOS MediaElement.MediaOpened Fires Before AVPlayerItem is ReadyToPlay
Description of Change
This PR fixes a bug on iOS and macOS where MediaElement.MediaOpened fires prematurely — immediately after the AVPlayerItem object is created, before the native AVFoundation player signals that the media is actually ready to play. MediaElement reports itself as "opened" with zero duration and 0x0 dimensions, and (as reported in #3249) playback operations issued from that point can fail because the underlying media hasn't loaded.
The Problem
In MediaManager.PlatformUpdateSource(), MediaElement.MediaOpened() was called right after Player.ReplaceCurrentItemWithPlayerItem(), gated only by PlayerItem is not null && PlayerItem.Error is null:
// OLD (buggy) codePlayerItem=assetis not null?newAVPlayerItem(asset):null;Player.ReplaceCurrentItemWithPlayerItem(PlayerItem);if(PlayerItemis not null&&PlayerItem.Errorisnull){MediaElement.MediaOpened();// ❌ Too early! Media isn't ready yet...}
PlayerItem.Error is null only confirms that the AVPlayerItem object was created without immediate failure — it does not mean the media has loaded, has a valid duration, or is ready for playback. The correct AVFoundation readiness signal is AVPlayerItem.Status == AVPlayerItemStatus.ReadyToPlay.
The Fix
MediaElement.MediaOpened() now fires from a KVO observer on AVPlayerItem.Status, only once the item reaches AVPlayerItemStatus.ReadyToPlay:
Change
Description
CurrentItemErrorObserver now observes status instead of error
One observer handles both ReadyToPlay and Failed; it is still disposed when switching sources and in Dispose()
Added PlayerItemStatusChanged(AVPlayerItem)
Raises MediaOpened / MediaFailed at the correct times. Returns Task and is invoked with SafeFireAndForget, so exceptions are logged rather than thrown from async void
Callback is bound to the item it observes
A callback from a superseded item (or one arriving after disposal) is ignored, both on entry and after the await on GetVideoDimensions
Added hasMediaOpened field
Prevents duplicate MediaOpened events for the same item; reset on every source change
Removed premature MediaOpened() call
PlatformUpdateSource() no longer raises it, and is no longer async (it returns ValueTask.CompletedTask)
Duration/position set via PlatformUpdatePosition()
Handles CMTime.Indefinite durations (HLS/live) through the seekable range
PlatformUpdateSpeed() always skips the first call
Auto-play is started from PlayerItemStatusChanged after ReadyToPlay, which then applies MediaElement.Speed
Failed status sets MediaElementState.Failed
Reported together with MediaFailed, with a fallback message when Error is null
PlayerItemStatusChanged() (abridged)
asyncTaskPlayerItemStatusChanged(AVPlayerItemplayerItem){// Ignore callbacks from an item that is no longer current, or that arrive after disposalif(Playerisnull||!ReferenceEquals(PlayerItem,playerItem))return;switch(playerItem.Status){caseAVPlayerItemStatus.ReadyToPlay:if(hasMediaOpened)return;hasMediaOpened=true;PlatformUpdatePosition();MediaElement.CurrentStateChanged(Player.Rate>0?MediaElementState.Playing:MediaElementState.Paused);var(mediaWidth,mediaHeight)=awaitGetVideoDimensions(playerItem);if(Playerisnull||!ReferenceEquals(PlayerItem,playerItem))return;(MediaElement.MediaWidth,MediaElement.MediaHeight)=(mediaWidth,mediaHeight);MediaElement.MediaOpened();if(MediaElement.ShouldAutoPlay){Player.Play();Player.Rate=(float)MediaElement.Speed;}awaitSetPoster();break;caseAVPlayerItemStatus.Failed:// CurrentStateChanged(Failed), MediaFailed(...), Logger.LogError(...)break;}}
Behavior Before vs After
Measured on the iOS simulator by running the same scenarios against main (c220724) and this branch (0c7db30). See Verification for the setup.
Scenario
Before (main)
After (this PR)
Any source, values at MediaOpened
State Opening, duration 0, 0x0
State Paused/Playing, real duration and dimensions
Invalid URL (HTTP 404)
MediaOpened fires, then MediaFailed
Only MediaFailed; state Failed
Source changed during playback
MediaOpened reports the previous item's duration, position and dimensions
Reports the new item
Three source changes in a row
MediaOpened fires 3 times; MediaWidth/MediaHeight end up as a superseded item's (1920x1080 for a 1280x720 video)
Fires once, with the final item's 1280x720
HLS stream
MediaWidth/MediaHeight stay 0x0
1280x720
ShouldAutoPlay = true with Speed = 2
Plays at 1x while Speed reports 2
Plays at 2x
ShouldAutoPlay = false (with or without Speed set)
Stays paused
Stays paused; Play() then starts playback
Unchanged between main and this branch: Play() called before the item is ready, audio-only sources (MediaEnded still fires), Source = null, and pause / speed change during playback. Time from setting the source to Playing is also unchanged (about 650 ms for the remote MP4 on both), so deferring Play() to ReadyToPlay adds no measurable start-up delay.
Has a linked Issue, and the Issue has been approved (bug) — #3249 approved by @ne0rrmatrix
Has tests — no automated test covers this change: the unit tests target net10.0 and do not compile MediaManager.macios.cs. It was verified on the iOS simulator instead (see Verification)
Documentation created or updated — n/a (no API change)
Additional Information
Root Cause Detail
The AVFoundation framework uses an asynchronous loading model. Creating an AVPlayerItem with new AVPlayerItem(asset) starts loading the media asynchronously. The item's Status property transitions through:
Unknown → ReadyToPlay (or Failed)
Calling MediaOpened() immediately after creation meant it fired during the Unknown state, before the media was loaded, so handlers saw a zero duration and 0x0 dimensions, and on multi-element pages every MediaOpened fired before any element was actually ready.
Verification
Build and unit tests (.NET SDK 10.0.401, Xcode 26.6)
CommunityToolkit.Maui.MediaElement builds with 0 errors for net10.0-ios (Debug) and for all target frameworks in Release, with no warnings from MediaManager.macios.cs.
CommunityToolkit.Maui.UnitTests: 11,664 passed, 0 failed. These tests do not exercise the changed file.
An earlier run of the same suite passed every test it ran but the test host exited with code 134, from an unhandled NullReferenceException in ValidationBehavior.UpdateStateAsync on a thread-pool thread. It did not repeat on the next run and is unrelated to this change.
A small MAUI harness app referenced the MediaElement project twice — once from this branch, once from main — and ran 14 scripted scenarios, logging StateChanged, MediaOpened, MediaFailed, MediaEnded and PositionChanged with the element's state, position, duration, dimensions and speed. Sources were a bundled MP4 (ResourceMediaSource), remote MP4s, an HLS stream, a remote MP3 and a URL that returns 404. Two full runs per build gave the same results, summarised in Behavior Before vs After.
Example, three source changes in a row (ShouldAutoPlay = true):
main:
MediaOpened | state=Opening pos=0.00s dur=0.00s dims=0x0
MediaOpened | state=Opening pos=0.00s dur=0.00s dims=0x0
MediaOpened | state=Opening pos=0.00s dur=0.00s dims=0x0
after 5s | state=Playing pos=4.86s dur=24.87s dims=1920x1080 <- playing the 1280x720 video
this PR:
MediaOpened | state=Paused pos=0.00s dur=24.87s dims=1280x720
after 5s | state=Playing pos=4.83s dur=24.87s dims=1280x720
Not verified
Mac Catalyst: compiles, but was not run.
Physical iOS device: not tested.
The SetPoster artwork overlay was not checked.
The sample app's MediaElement pages were not run against this branch.
Behavior change to be aware of
With ShouldAutoPlay = true, an initial Speed other than 1 is now applied when playback starts. On main the element plays at 1x while Speed reports the requested value.
Existing issue, not addressed here
With ShouldAutoPlay = false and Speed = 1.5, calling Play() plays at 1x while Speed still reports 1.5, because PlatformPlay calls Player.Play() without reapplying the speed. This is identical on main. It is reported in #3326 and fixed in #3327.
#3327 also edits MediaManager.macios.cs. The two PRs touch different things except for one spot: the auto-play start. On main that call lives in PlatformUpdateSource; this PR moves it into PlayerItemStatusChanged, and #3327 changes it in place to a new PlayAtSpeed() helper. Git will report a conflict there for whichever PR merges second.
Resolution, in either order: keep this PR's structure (auto-play started from PlayerItemStatusChanged after ReadyToPlay) and start playback with #3327's helper, so the block reads:
The replacement is required, not optional. Resolving the conflict by keeping the Player.Play(); Player.Rate = (float)MediaElement.Speed; pair was also tested: with auto-play and Speed = 2, Speed is overwritten with 1 and playback runs at 1x (3.03s after 4s). #3327 makes RateChanged copy the player's rate into MediaElement.Speed, and Player.Play() sets the rate to 1 before the pair reapplies it.
Introduced IDisposable? PlayerItemStatusObserver to track AVPlayerItem status and ensure proper disposal in PlatformUpdateSource and Dispose methods. Refactored status observation to trigger MediaOpened, error handling, and video dimension updates only when ReadyToPlay. Moved video dimension, autoplay, and poster logic to OnPlayerItemReady. Improved error handling and logging for Failed status.
Removed the unnecessary 'using CommunityToolkit.Maui.Media.Services;' directive from MediaManager.macios.cs. This cleanup reduces dependencies and improves code clarity without affecting functionality.
The reason will be displayed to describe this comment to others. Learn more.
Pull request overview
This PR adjusts the iOS/macOS (Mac Catalyst) MediaManager implementation so MediaElement.MediaOpened is raised only after the underlying AVPlayerItem reports ReadyToPlay, preventing “opened” state from being reported before duration/dimensions are available and before playback operations can safely succeed.
Changes:
Adds an AVPlayerItem.Status observer and routes MediaOpened/MediaFailed decisions through that status transition instead of firing immediately after item creation.
Introduces a hasMediaOpened guard and disposes the new observer when switching sources and during Dispose().
Updates speed initialization flow to defer initial behavior until item readiness.
The observer callback is not bound to the item being observed; PlayerItemStatusChanged repeatedly reads the mutable PlayerItem property. If a source is replaced while an old KVO callback is queued/running, the old callback can inspect the new item and report it opened or failed incorrectly. Capture the observed AVPlayerItem in the registration callback, pass it into the handler, and discard it immediately when it is no longer the current item.
Prevent stale media dimensions after source changes or disposal
The dimensions are written before checking whether the awaited item is still current, so a rapid source change can expose dimensions from the previous media even though the callback then returns. The same continuation can outlive disposal because PlayerItem remains assigned; include the Player disposal check and only apply the locally captured result after both checks pass.
@TheCodeTraveler I went through the Copilot review and all three findings are addressed in 6d007c0:
async without await (CS1998):PlatformUpdateSource is no longer async and returns ValueTask.CompletedTask. The previous commit did still build locally for iOS with 0 errors, so I could not reproduce the build break, but the finding was correct.
KVO callback not bound to the observed item: the status observer now captures the AVPlayerItem it was registered on and passes it to PlayerItemStatusChanged, which returns early if that item is no longer current or the player has been disposed.
Stale media dimensions: the dimensions are read into locals and only applied to MediaElement after the post-await check passes. That check now also covers disposal.
The MediaElement project builds for net10.0-ios and net10.0-maccatalyst with 0 warnings and 0 errors. I have not run this on a device or simulator yet.
Improve MediaManager item-status handling by binding observer callbacks to a cancellable token and centralizing observer teardown to prevent stale async work after source changes or disposal. The ReadyToPlay flow now handles track-loading failures more safely, computes dimensions without unnecessary async work, and applies autoplay/speed in a safer order so ShouldAutoPlay and MediaOpened handlers are respected. It also maps state from TimeControlStatus and ignores expected cancellation exceptions.
… registration
The status observer is registered with the Initial option, so its first
notification runs before AddObserver returns. If a handler raised from
that notification changes the source, the nested update installs the new
item's observer and the outer assignment then replaced it with the
superseded one, leaking the current observer. Check the item is still
current after registering and dispose the observer otherwise.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…s during registration"
This reverts commit f167ca6, restoring the observer registration from
7207c53 unchanged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…es during registration"
This reverts commit 9d916d3, bringing back the change from f167ca6:
after registering the status observer, check the item is still current
and dispose the observer otherwise.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
MediaManager.macios.cs: keep main's early return in PlatformUpdateSource;
the PR's MediaOpened/GetVideoDimensions/PlayAtSpeed/SetPoster block there
is superseded by CommunityToolkit#3281's PlayerItemStatusChanged.
Autoplay in PlayerItemStatusChanged now calls PlayAtSpeed() instead of
Play() then Rate = speed, whose two rate changes made RateChanged flip
Speed between 1 and the requested value and stall playback.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
MediaManager.macios.cs: keep both sides of the field-block conflict.
From main (CommunityToolkit#3281): the rewritten isInitialSpeedSet comment and hasMediaOpened.
From this PR: fullScreenDelegate, OnScreenStateChanged and the moved
public Dispose() (its old copy is removed by an auto-merged hunk).
MediaElementPage.xaml.cs auto-merged cleanly; no other changes.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
MediaManager.macios.cs: take main (keeps CommunityToolkit#3281 fields incl. hasMediaOpened)
and re-add the PR's ShowsPlaybackControls line in CreatePlatformView.
MauiMediaElement.macios.cs: take the PR's responder-chain version.
PageExtensions.shared.cs: main's layout with the PR's CurrentPage expression.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
[PR] Fix iOS/macOS MediaElement.MediaOpened Fires Before AVPlayerItem is ReadyToPlay
Description of Change
This PR fixes a bug on iOS and macOS where
MediaElement.MediaOpenedfires prematurely — immediately after theAVPlayerItemobject is created, before the native AVFoundation player signals that the media is actually ready to play.MediaElementreports itself as "opened" with zero duration and 0x0 dimensions, and (as reported in #3249) playback operations issued from that point can fail because the underlying media hasn't loaded.The Problem
In
MediaManager.PlatformUpdateSource(),MediaElement.MediaOpened()was called right afterPlayer.ReplaceCurrentItemWithPlayerItem(), gated only byPlayerItem is not null && PlayerItem.Error is null:PlayerItem.Error is nullonly confirms that theAVPlayerItemobject was created without immediate failure — it does not mean the media has loaded, has a valid duration, or is ready for playback. The correct AVFoundation readiness signal isAVPlayerItem.Status == AVPlayerItemStatus.ReadyToPlay.The Fix
MediaElement.MediaOpened()now fires from a KVO observer onAVPlayerItem.Status, only once the item reachesAVPlayerItemStatus.ReadyToPlay:CurrentItemErrorObservernow observesstatusinstead oferrorReadyToPlayandFailed; it is still disposed when switching sources and inDispose()PlayerItemStatusChanged(AVPlayerItem)MediaOpened/MediaFailedat the correct times. ReturnsTaskand is invoked withSafeFireAndForget, so exceptions are logged rather than thrown fromasync voidawaitonGetVideoDimensionshasMediaOpenedfieldMediaOpenedevents for the same item; reset on every source changeMediaOpened()callPlatformUpdateSource()no longer raises it, and is no longerasync(it returnsValueTask.CompletedTask)PlatformUpdatePosition()CMTime.Indefinitedurations (HLS/live) through the seekable rangePlatformUpdateSpeed()always skips the first callPlayerItemStatusChangedafterReadyToPlay, which then appliesMediaElement.SpeedFailedstatus setsMediaElementState.FailedMediaFailed, with a fallback message whenErroris nullPlayerItemStatusChanged()(abridged)Behavior Before vs After
Measured on the iOS simulator by running the same scenarios against
main(c220724) and this branch (0c7db30). See Verification for the setup.main)MediaOpenedOpening, duration 0, 0x0Paused/Playing, real duration and dimensionsMediaOpenedfires, thenMediaFailedMediaFailed; stateFailedMediaOpenedreports the previous item's duration, position and dimensionsMediaOpenedfires 3 times;MediaWidth/MediaHeightend up as a superseded item's (1920x1080 for a 1280x720 video)MediaWidth/MediaHeightstay 0x0ShouldAutoPlay = truewithSpeed = 2Speedreports 2ShouldAutoPlay = false(with or withoutSpeedset)Play()then starts playbackUnchanged between
mainand this branch:Play()called before the item is ready, audio-only sources (MediaEndedstill fires),Source = null, and pause / speed change during playback. Time from setting the source toPlayingis also unchanged (about 650 ms for the remote MP4 on both), so deferringPlay()toReadyToPlayadds no measurable start-up delay.Files Changed
src/CommunityToolkit.Maui.MediaElement/Views/MediaManager.macios.csLinked Issues
PR Checklist
approved(bug) — #3249 approved by @ne0rrmatrixnet10.0and do not compileMediaManager.macios.cs. It was verified on the iOS simulator instead (see Verification)mainat time of PRAdditional Information
Root Cause Detail
The AVFoundation framework uses an asynchronous loading model. Creating an
AVPlayerItemwithnew AVPlayerItem(asset)starts loading the media asynchronously. The item'sStatusproperty transitions through:Calling
MediaOpened()immediately after creation meant it fired during theUnknownstate, before the media was loaded, so handlers saw a zero duration and 0x0 dimensions, and on multi-element pages everyMediaOpenedfired before any element was actually ready.Verification
Build and unit tests (.NET SDK 10.0.401, Xcode 26.6)
CommunityToolkit.Maui.MediaElementbuilds with 0 errors fornet10.0-ios(Debug) and for all target frameworks in Release, with no warnings fromMediaManager.macios.cs.CommunityToolkit.Maui.UnitTests: 11,664 passed, 0 failed. These tests do not exercise the changed file.NullReferenceExceptioninValidationBehavior.UpdateStateAsyncon a thread-pool thread. It did not repeat on the next run and is unrelated to this change.Simulator comparison (iPhone 17 simulator, iOS 26.5)
A small MAUI harness app referenced the MediaElement project twice — once from this branch, once from
main— and ran 14 scripted scenarios, loggingStateChanged,MediaOpened,MediaFailed,MediaEndedandPositionChangedwith the element's state, position, duration, dimensions and speed. Sources were a bundled MP4 (ResourceMediaSource), remote MP4s, an HLS stream, a remote MP3 and a URL that returns 404. Two full runs per build gave the same results, summarised in Behavior Before vs After.Example, three source changes in a row (
ShouldAutoPlay = true):Not verified
SetPosterartwork overlay was not checked.Behavior change to be aware of
With
ShouldAutoPlay = true, an initialSpeedother than 1 is now applied when playback starts. Onmainthe element plays at 1x whileSpeedreports the requested value.Existing issue, not addressed here
With
ShouldAutoPlay = falseandSpeed = 1.5, callingPlay()plays at 1x whileSpeedstill reports 1.5, becausePlatformPlaycallsPlayer.Play()without reapplying the speed. This is identical onmain. It is reported in #3326 and fixed in #3327.Overlap with #3327
#3327 also edits
MediaManager.macios.cs. The two PRs touch different things except for one spot: the auto-play start. Onmainthat call lives inPlatformUpdateSource; this PR moves it intoPlayerItemStatusChanged, and #3327 changes it in place to a newPlayAtSpeed()helper. Git will report a conflict there for whichever PR merges second.Resolution, in either order: keep this PR's structure (auto-play started from
PlayerItemStatusChangedafterReadyToPlay) and start playback with #3327's helper, so the block reads:PlatformUpdateSourcehunk, and replaces thePlayer.Play(); Player.Rate = (float)MediaElement.Speed;pair above withPlayAtSpeed().PlayerItemStatusChanged.Verified locally (iPhone 17 simulator, iOS 26.5). Both branches were merged onto
main(c8740a8) with the resolution above:CommunityToolkit.Maui.UnitTestspasses (11,679 tests).Speed = 2,Play()without auto-play: 5.70s of media after 3s; auto-play atSpeed = 2: 3.47s after 2s).The replacement is required, not optional. Resolving the conflict by keeping the
Player.Play(); Player.Rate = (float)MediaElement.Speed;pair was also tested: with auto-play andSpeed = 2,Speedis overwritten with 1 and playback runs at 1x (3.03s after 4s). #3327 makesRateChangedcopy the player's rate intoMediaElement.Speed, andPlayer.Play()sets the rate to 1 before the pair reapplies it.Platforms Tested