Skip to content
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,17 @@ sealed class Metadata
};

readonly PlatformMediaElement player;
readonly Action play;

/// <summary>
/// Initializes a new instance of the <see cref="Metadata"/> class.
/// </summary>
/// <param name="player"></param>
public Metadata(PlatformMediaElement player)
/// <param name="play">Starts playback at the requested speed, <see cref="AVPlayer.Play"/> always starts playback at a rate of 1.</param>
public Metadata(PlatformMediaElement player, Action play)
{
this.player = player;
this.play = play;
MPNowPlayingInfoCenter.DefaultCenter.NowPlaying = nowPlayingInfoDefault;

var commandCenter = MPRemoteCommandCenter.Shared;
Expand Down Expand Up @@ -148,7 +151,7 @@ MPRemoteCommandHandlerStatus PlayCommand(MPRemoteCommandEvent? commandEvent)
return MPRemoteCommandHandlerStatus.CommandFailed;
}

player.Play();
play();
return MPRemoteCommandHandlerStatus.Success;
}

Expand All @@ -172,7 +175,7 @@ MPRemoteCommandHandlerStatus ToggleCommand(MPRemoteCommandEvent? commandEvent)

if (player.Rate is 0)
{
player.Play();
play();
}
else
{
Expand Down
80 changes: 61 additions & 19 deletions src/CommunityToolkit.Maui.MediaElement/Views/MediaManager.macios.cs
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ protected virtual partial void PlatformPlay()
return;
}

Player?.Play();
PlayAtSpeed();
}

protected virtual partial void PlatformPause()
Expand Down Expand Up @@ -232,7 +232,21 @@ protected virtual partial ValueTask PlatformUpdateSource()
streamResourceLoader = null;
}

metaData ??= new(Player);
// Metadata is retained for the app's lifetime by the shared MPRemoteCommandCenter, so pass a weak-reference
// playback callback. Passing PlayAtSpeed directly would give Metadata a strong reference to this MediaManager and,
// through it, its MediaElement and MauiContext, keeping them (and their managed view trees) alive after disposal.
metaData ??= new(Player, CreatePlaybackCallback(new WeakReference<MediaManager>(this)));

static Action CreatePlaybackCallback(WeakReference<MediaManager> manager)
{
return () =>
{
if (manager.TryGetTarget(out var target))
{
target.PlayAtSpeed();
}
};
}
Metadata.ClearNowPlaying();
PlayerViewController?.ContentOverlayView?.Subviews.FirstOrDefault()?.RemoveFromSuperview();

Expand Down Expand Up @@ -375,7 +389,17 @@ protected virtual partial void PlatformUpdateSpeed()
return;
}

PlayerViewController.Player.Rate = (float)MediaElement.Speed;
// RateChanged copies the player's rate into Speed, so don't send it back: setting the rate again starts a new rate change, and when
// two rates are set in the same main-loop turn AVPlayer reports the earlier one again afterwards, so the two would keep replacing each other.
// Skip only when the requested rate (as the same float AVPlayer last stored, Rate was set to (float)Speed) matches the native rate
// within a 0.005 rounding margin to handle floating point math.
var requestedRate = (float)MediaElement.Speed;
if (Math.Abs(requestedRate - PlayerViewController.Player.Rate) < .005)
{
return;
}

PlayerViewController.Player.Rate = requestedRate;
}

protected virtual partial void PlatformUpdateShouldShowPlaybackControls()
Expand Down Expand Up @@ -754,17 +778,10 @@ async ValueTask PlayerItemStatusChanged(AVPlayerItem playerItem, CancellationTok
// Start playback before raising MediaOpened so a Pause(), Stop() or SeekTo() from a MediaOpened handler isn't overridden
if (MediaElement.ShouldAutoPlay)
{
// Read Speed before Play(), which changes the rate and raises RateChanged
var speed = (float)MediaElement.Speed;
Player.Play();
// Start at the requested Speed with a single rate change. Play() followed by setting Rate changes the rate twice,
// and RateChanged, which copies the player's rate into Speed, then keeps switching Speed between 1 and the requested value
PlayAtSpeed();
token.ThrowIfCancellationRequested();

// Apply Speed unless a StateChanged handler raised by Play() paused playback
if (Player.Rate > 0)
{
Player.Rate = speed;
token.ThrowIfCancellationRequested();
}
}

MediaElement.CurrentStateChanged(Player.TimeControlStatus switch
Expand Down Expand Up @@ -882,7 +899,7 @@ void PlayedToEnd(object? sender, NSNotificationEventArgs args)
if (MediaElement.ShouldLoopPlayback)
{
PlayerViewController?.Player?.Seek(CMTime.Zero);
Player.Play();
PlayAtSpeed();
}
else
{
Expand All @@ -905,14 +922,39 @@ void RateChanged(object? sender, NSNotificationEventArgs args)
return;
}

// AVPlayer reports a rate of 0 while paused, that is not a change of the requested Speed
if (Player.Rate is 0)
{
return;
}

if (!AreFloatingPointNumbersEqual(MediaElement.Speed, Player.Rate))
{
MediaElement.Speed = Player.Rate;
if (metaData is not null)
{
metaData.NowPlayingInfo.PlaybackRate = (float)MediaElement.Speed;
MPNowPlayingInfoCenter.DefaultCenter.NowPlaying = metaData.NowPlayingInfo;
}
}

if (metaData is not null)
{
metaData.NowPlayingInfo.PlaybackRate = (float)MediaElement.Speed;
MPNowPlayingInfoCenter.DefaultCenter.NowPlaying = metaData.NowPlayingInfo;
}
}

void PlayAtSpeed()
{
if (Player is null)
{
return;
}

// AVPlayer.Play() always starts playback at a rate of 1, setting the rate starts playback at the requested Speed
if (MediaElement.Speed is 0)
{
Player.Play();
}
else
{
Player.Rate = (float)MediaElement.Speed;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ public MediaManager(Microsoft.Maui.IMauiContext context, IMediaElement mediaElem
/// <param name="number2"></param>
/// <param name="tolerance"></param>
/// <returns></returns>
public static bool AreFloatingPointNumbersEqual(in double number1, in double number2, double tolerance = 0.01) => Math.Abs(number1 - number2) > tolerance;
public static bool AreFloatingPointNumbersEqual(in double number1, in double number2, double tolerance = 0.01) => Math.Abs(number1 - number2) <= tolerance;

/// <summary>
/// Invokes the play operation on the platform element.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -591,7 +591,7 @@ void OnNaturalVideoSizeChanged(MediaPlaybackSession sender, object args)

void OnPlaybackSessionPlaybackRateChanged(MediaPlaybackSession sender, object args)
{
if (AreFloatingPointNumbersEqual(MediaElement.Speed, sender.PlaybackRate))
if (!AreFloatingPointNumbersEqual(MediaElement.Speed, sender.PlaybackRate))
{
if (Dispatcher.IsDispatchRequired)
{
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
using CommunityToolkit.Maui.Core.Views;
using FluentAssertions;
using Xunit;

namespace CommunityToolkit.Maui.UnitTests.Views;

public class MediaManagerTests : BaseViewTest
{
[Theory]
[InlineData(1, 1)]
[InlineData(0, 0)]
[InlineData(1.5, 1.5)]
[InlineData(1, 1.005)]
[InlineData(1.005, 1)]
[InlineData(-2, -2)]
public void AreFloatingPointNumbersEqual_NumbersWithinDefaultTolerance_ReturnsTrue(double number1, double number2)
{
MediaManager.AreFloatingPointNumbersEqual(number1, number2).Should().BeTrue();
}

[Theory]
[InlineData(1, 2)]
[InlineData(2, 1)]
[InlineData(0, 1)]
[InlineData(1, 1.02)]
[InlineData(1.5, -1.5)]
public void AreFloatingPointNumbersEqual_NumbersOutsideDefaultTolerance_ReturnsFalse(double number1, double number2)
{
MediaManager.AreFloatingPointNumbersEqual(number1, number2).Should().BeFalse();
}

[Theory]
[InlineData(1, 1.4, 0.5, true)]
[InlineData(1, 1.6, 0.5, false)]
[InlineData(1, 1.05, 0.1, true)]
[InlineData(1, 1.05, 0.001, false)]
public void AreFloatingPointNumbersEqual_CustomTolerance_ReturnsExpectedResult(double number1, double number2, double tolerance, bool expectedResult)
{
MediaManager.AreFloatingPointNumbersEqual(number1, number2, tolerance).Should().Be(expectedResult);
}
}
Loading