MediaPlayerExtension.cs 13.9 KB
Newer Older
1 2 3 4 5
#nullable enable

using System;
using System.Collections.Generic;
using System.Linq;
6
using System.Reflection.Metadata;
R
Rafael Rosa 已提交
7 8 9 10 11
using Uno.Foundation.Extensibility;
using Uno.Foundation.Logging;
using Uno.Media.Playback;
using Windows.Foundation;
using Windows.Media.Core;
12 13
using Windows.Media.Playback;
using Windows.Storage;
14
using Windows.Storage.Helpers;
15
using Windows.Storage.Streams;
16 17 18
using Windows.UI.Xaml;
using Uno.Extensions;
using Uno.Helpers;
19 20 21 22 23 24 25 26 27

[assembly: ApiExtension(typeof(IMediaPlayerExtension), typeof(Uno.UI.Media.MediaPlayerExtension))]

namespace Uno.UI.Media;

public partial class MediaPlayerExtension : IMediaPlayerExtension
{
	private static Dictionary<MediaPlayer, MediaPlayerExtension> _instances = new();

28
	private readonly MediaPlayer _owner;
29 30 31 32 33 34 35 36 37 38 39
	private HtmlMediaPlayer? _player;

	private bool _updatingPosition;
	private bool _isPlayRequested;
	private bool _isPlayerPrepared;
	private List<Uri>? _playlistItems;
	private int _playlistIndex;
	private TimeSpan _naturalDuration;
	private Uri? _uri;
	private bool _anonymousCors = FeatureConfiguration.AnonymousCorsDefault;

40 41
	const string MsAppXScheme = "ms-appx";

42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
	public MediaPlayerExtension(object owner)
	{
		if (owner is MediaPlayer player)
		{
			_owner = player;
		}
		else
		{
			throw new InvalidOperationException($"MediaPlayerPresenterExtension must be initialized with a MediaPlayer instance");
		}

		lock (_instances)
		{
			_instances[_owner] = this;
		}
	}

	~MediaPlayerExtension()
	{
		lock (_instances)
		{
			_instances.Remove(_owner);
		}
	}

	internal static MediaPlayerExtension? GetByMediaPlayer(MediaPlayer mediaPlayer)
	{
		lock (_instances)
		{
			return _instances.TryGetValue(mediaPlayer, out var instance) ? instance : null;
		}
	}

	internal HtmlMediaPlayer? HtmlPlayer
	{
		get => _player;
		set
		{
			if (value != null)
			{
				_player = value;
				InitializePlayer();
			}
		}
	}

	void IMediaPlayerExtension.OnOptionChanged(string name, object value)
	{
		switch (name)
		{
			case "AnonymousCORS" when value is bool enabled:
				_anonymousCors = enabled;
				ApplyAnonymousCors();
				break;
		}
	}

	private void ApplyAnonymousCors()
		=> _player?.SetAnonymousCORS(_anonymousCors);

	public IMediaPlayerEventsExtension? Events { get; set; }

104 105 106 107 108 109 110 111 112 113 114 115 116
	private double _playbackRate;
	public double PlaybackRate
	{
		get => _playbackRate;
		set
		{
			_playbackRate = value;
			if (_player is not null)
			{
				_player.PlaybackRate = value;
			}
		}
	}
117

118 119 120 121 122 123 124 125 126 127 128 129 130
	private bool _isLoopingEnabled;
	public bool IsLoopingEnabled
	{
		get => _isLoopingEnabled;
		set
		{
			_isLoopingEnabled = value;
			if (_player is not null)
			{
				_player.SetIsLoopingEnabled(value);
			}
		}
	}
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156

	public MediaPlayerState CurrentState { get; private set; }

	public TimeSpan NaturalDuration
	{
		get => _naturalDuration;
		internal set
		{
			_naturalDuration = value;

			Events?.NaturalDurationChanged();
		}
	}

	public bool IsProtected
		=> false;

	public double BufferingProgress
		=> 0.0;

	public bool CanPause
		=> true;

	public bool CanSeek
		=> true;

157 158
	public bool? IsVideo { get; set; }

159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
	public MediaPlayerAudioDeviceType AudioDeviceType { get; set; }

	public MediaPlayerAudioCategory AudioCategory { get; set; }

	public TimeSpan TimelineControllerPositionOffset
	{
		get => Position;
		set => Position = value;
	}

	public bool RealTimePlayback { get; set; }

	public double AudioBalance { get; set; }

	public TimeSpan Position
	{
		get => TimeSpan.FromSeconds(_player?.CurrentPosition ?? 0);
		set
		{
			if (!_updatingPosition)
			{
				_updatingPosition = true;

				try
				{
184
					if (_owner.PlaybackSession.PlaybackState != MediaPlaybackState.None && _player is not null && _player.Source is not null)
185
					{
186 187 188 189
						if (this.Log().IsEnabled(Uno.Foundation.Logging.LogLevel.Debug))
						{
							this.Log().Debug($"Position {value.TotalSeconds}");
						}
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
						_player.CurrentPosition = (int)value.TotalSeconds;
						OnSeekComplete();
					}
				}
				finally
				{
					_updatingPosition = false;
				}
			}
		}
	}

	public void Dispose()
	{
		_instances.Remove(_owner);

		TryDisposePlayer();
	}

	public void Initialize()
		=> InitializePlayer();

	private void InitializePlayer()
	{
		if (this.Log().IsEnabled(LogLevel.Debug))
		{
			this.Log().Debug($"MediaPlayerExtension.InitializePlayer ({_player})");
		}

		if (_player is null)
		{
			return;
		}

		_player.OnSourceFailed -= OnError;
		_player.OnSourceLoaded -= OnPrepared;
		_player.OnSourceEnded -= OnCompletion;
		_player.OnTimeUpdate -= OnTimeUpdate;
		_player.OnSourceFailed += OnError;
		_player.OnSourceLoaded += OnPrepared;
		_player.OnSourceEnded += OnCompletion;
		_player.OnTimeUpdate += OnTimeUpdate;

233
		_player.OnStatusChanged -= OnStatusMediaChanged;
R
Rafael Rosa 已提交
234 235
		_player.OnStatusChanged += OnStatusMediaChanged;

236 237 238 239 240 241 242
		_owner.PlaybackSession.PlaybackStateChanged -= OnStatusChanged;
		_owner.PlaybackSession.PlaybackStateChanged += OnStatusChanged;

		ApplyAnonymousCors();
		ApplyVideoSource();
	}

R
Rafael Rosa 已提交
243 244 245 246
	private void OnStatusMediaChanged(object? sender, object e)
	{
		if (this.Log().IsEnabled(LogLevel.Debug))
		{
247
			this.Log().Debug($"MediaPlayerExtension.OnStatusMediaChanged to state {_player?.PlayerState.ToString()}");
R
Rafael Rosa 已提交
248 249
		}

250
		if (_player?.PlayerState == HtmlMediaPlayerState.Paused && _owner.PlaybackSession.PlaybackState == MediaPlaybackState.Playing)
R
Rafael Rosa 已提交
251
		{
252 253
			_owner.PlaybackSession.PlaybackState = MediaPlaybackState.Paused;
		}
254
		else if (_player?.PlayerState == HtmlMediaPlayerState.Playing && _owner.PlaybackSession.PlaybackState == MediaPlaybackState.Paused)
255 256
		{
			_owner.PlaybackSession.PlaybackState = MediaPlaybackState.Playing;
R
Rafael Rosa 已提交
257 258 259
		}
	}

260 261 262 263 264 265 266 267 268
	private void SetPlaylistItems(MediaPlaybackList playlist)
	{
		_playlistItems = playlist.Items
			.Select(i => i.Source.Uri)
			.ToList();
	}

	public void InitializeSource()
	{
R
Rafael Rosa 已提交
269 270 271 272
		if (this.Log().IsEnabled(LogLevel.Debug))
		{
			this.Log().LogDebug("Enter MediaPlayerExtension.InitializeSource().");
		}
273 274

		NaturalDuration = TimeSpan.Zero;
275 276 277 278
		if (Position != TimeSpan.Zero)
		{
			Position = TimeSpan.Zero;
		}
279 280 281 282 283 284 285 286 287 288 289 290

		// Reset player
		TryDisposePlayer();

		if (_owner.Source == null)
		{
			return;
		}

		try
		{
			_owner.PlaybackSession.PlaybackState = MediaPlaybackState.Opening;
291
			InitializePlayer();
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312

			switch (_owner.Source)
			{
				case MediaPlaybackList playlist when playlist.Items.Count > 0 && _playlistItems is not null:
					SetPlaylistItems(playlist);
					_uri = _playlistItems[0];
					break;

				case MediaPlaybackItem item:
					_uri = item.Source.Uri;
					break;

				case MediaSource source:
					_uri = source.Uri;
					break;

				default:
					throw new InvalidOperationException("Unsupported media source type");
			}

			ApplyVideoSource();
313
			Events?.RaiseSourceChanged();
314 315 316
		}
		catch (global::System.Exception ex)
		{
317 318

			this.Log().Debug($"MediaPlayerElementExtension.InitializeSource({ex.Message})");
319 320 321 322 323 324 325 326 327 328 329 330 331
			OnMediaFailed(ex);
		}
	}

	private void ApplyVideoSource()
	{
		if (this.Log().IsEnabled(LogLevel.Debug))
		{
			this.Log().Debug($"MediaPlayerElementExtension.SetVideoSource({_uri})");
		}

		if (_player is not null && _uri is not null)
		{
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
			if (!_uri.IsAbsoluteUri || _uri.Scheme == "")
			{
				_uri = new Uri(MsAppXScheme + ":///" + _uri.OriginalString.TrimStart(new char[] { '/' }));
			}

			if (_uri.IsLocalResource())
			{
				_player.Source = AssetsPathBuilder.BuildAssetUri(_uri?.PathAndQuery);
				return;
			}

			if (_uri.IsAppData())
			{
				var filePath = AppDataUriEvaluator.ToPath(_uri);
				_player.Source = filePath;
				return;
			}

			if (_uri.IsFile)
			{
				_player.Source = _uri.OriginalString;
				return;
			}

356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
			_player.Source = _uri.OriginalString;
		}
		else
		{
			if (this.Log().IsEnabled(LogLevel.Debug))
			{
				this.Log().Debug($"MediaPlayerElementExtension.SetVideoSource: failed (Player is not available)");
			}
		}
	}

	public void Pause()
	{
		if (this.Log().IsEnabled(LogLevel.Debug))
		{
			this.Log().Debug($"MediaPlayerExtension.Pause()");
		}

		if (_owner.PlaybackSession.PlaybackState == MediaPlaybackState.Playing)
		{
			_player?.Pause();
			_owner.PlaybackSession.PlaybackState = MediaPlaybackState.Paused;
		}
	}

	public void Play()
	{
		if (this.Log().IsEnabled(LogLevel.Debug))
		{
			this.Log().Debug($"MediaPlayerExtension.Play()");
		}

		if (_owner.Source == null || _player == null)
		{
			if (this.Log().IsEnabled(LogLevel.Debug))
			{
				this.Log().Debug($"MediaPlayerExtension.Play(): Failed {_owner.Source} / {_player}");
			}
			return;
		}

		try
		{
			// If we reached the end of media, we need to reset position to 0
			if (_owner.PlaybackSession.PlaybackState == MediaPlaybackState.None)
			{
				_owner.PlaybackSession.Position = TimeSpan.Zero;
			}

			_isPlayRequested = true;

			if (_isPlayerPrepared)
			{
409
				_player.PlaybackRate = 1;
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472
				_player.Play();
				_owner.PlaybackSession.PlaybackState = MediaPlaybackState.Playing;
			}
			else
			{
				if (this.Log().IsEnabled(LogLevel.Debug))
				{
					this.Log().Debug($"MediaPlayerExtension.Play(): Player was not prepared");
				}
			}
		}
		catch (global::System.Exception ex)
		{
			if (this.Log().IsEnabled(LogLevel.Debug))
			{
				this.Log().Debug($"MediaPlayerExtension.Play(): Failed {ex}");
			}
			OnMediaFailed(ex);
		}
	}

	public void SetFileSource(IStorageFile file)
		=> throw new NotSupportedException($"IStorageFile is not supported");

	public void SetMediaSource(IMediaSource source)
		=> throw new NotSupportedException($"IMediaSource is not supported");

	public void SetStreamSource(IRandomAccessStream stream)
		=> throw new NotSupportedException($"IRandomAccessStream is not supported");

	public void SetSurfaceSize(Size size)
		=> throw new NotSupportedException($"SetSurfaceSize is not supported");

	public void SetUriSource(Uri uri)
	{
		if (this.Log().IsEnabled(LogLevel.Debug))
		{
			this.Log().Debug($"MediaPlayerExtension.SetUriSource({uri})");
		}

		if (_player is not null)
		{
			_player.Source = uri.OriginalString;
		}
	}

	public void StepBackwardOneFrame()
		=> throw new NotSupportedException($"StepBackwardOneFrame is not supported");

	public void StepForwardOneFrame()
		=> throw new NotSupportedException($"StepForwardOneFrame is not supported");

	public void Stop()
	{
		if (this.Log().IsEnabled(LogLevel.Debug))
		{
			this.Log().Debug($"MediaPlayerExtension.Stop()");
		}

		if (_owner.PlaybackSession.PlaybackState == MediaPlaybackState.Playing
			|| _owner.PlaybackSession.PlaybackState == MediaPlaybackState.Paused)
		{
			_player?.Pause(); // Do not call stop, otherwise player will need to be prepared again
473
			_owner.PlaybackSession.Position = TimeSpan.Zero;
474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514
			_owner.PlaybackSession.PlaybackState = MediaPlaybackState.None;
		}
	}

	public void ToggleMute()
	{
		if (_owner.IsMuted)
		{
			_player?.SetVolume(0);
		}
		else
		{
			var volume = (float)_owner.Volume / 100;
			_player?.SetVolume(volume);
		}
	}

	private void OnStatusChanged(MediaPlaybackSession? sender, object args)
	{
		if (this.Log().IsEnabled(LogLevel.Debug))
		{
			this.Log().Debug($"OnStatusChanged: {args}");
		}

		if ((MediaPlaybackState)args == MediaPlaybackState.Playing)
		{
			_player?.Play();
		}
	}

	public void OnPrepared(object? sender, object what)
	{
		if (sender is HtmlMediaPlayer mp && _player is not null)
		{
			if (this.Log().IsEnabled(LogLevel.Debug))
			{
				this.Log().Debug($"OnPrepared: {_player.Duration}");
			}

			NaturalDuration = TimeSpan.FromSeconds(_player.Duration);

R
Rafael Rosa 已提交
515
			IsVideo = !_player.IsAudio;
516

R
Rafael Rosa 已提交
517
			if (!mp.IsAudio && Events is not null)
518
			{
519
				try
520
				{
521 522 523 524
					if (this.Log().IsEnabled(LogLevel.Debug))
					{
						this.Log().Debug($"OnPrepared: {mp.VideoWidth}x{mp.VideoHeight}");
					}
525

526 527 528
					Events.RaiseVideoRatioChanged((double)mp.VideoWidth / global::System.Math.Max(mp.VideoHeight, 1));
				}
				catch { }
529 530 531 532 533 534 535 536 537
			}

			if (_owner.PlaybackSession.PlaybackState == MediaPlaybackState.Opening)
			{
				if (_isPlayRequested)
				{
					_player.Play();
					_owner.PlaybackSession.PlaybackState = MediaPlaybackState.Playing;
				}
538 539 540 541
				else
				{
					_owner.PlaybackSession.PlaybackState = MediaPlaybackState.Paused;
				}
542 543 544 545
			}

			_isPlayerPrepared = true;
		}
546 547 548 549 550

		if (Events is not null)
		{
			Events?.RaiseMediaOpened();
		}
551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590
	}

	void OnError(object? sender, object what)
	{
		if (_owner.PlaybackSession.PlaybackState != MediaPlaybackState.None)
		{
			_player?.Stop();
			_owner.PlaybackSession.PlaybackState = MediaPlaybackState.None;
		}

		if (this.Log().IsEnabled(LogLevel.Debug))
		{
			this.Log().Debug($"OnError: {what}");
		}

		OnMediaFailed(message: $"MediaPlayer Error: {(string)what}");
	}

	public void OnCompletion(object? sender, object what)
	{
		if (this.Log().IsEnabled(LogLevel.Debug))
		{
			this.Log().Debug($"OnCompletion: {_owner.Position}");
		}

		Events?.RaiseMediaEnded();
		_owner.PlaybackSession.PlaybackState = MediaPlaybackState.None;

		// Play next item in playlist, if any
		if (_playlistItems != null && _playlistIndex < _playlistItems.Count - 1)
		{
			_uri = _playlistItems[++_playlistIndex];
			ApplyVideoSource();
		}
	}

	private void OnMediaFailed(global::System.Exception? ex = null, string? message = null)
	{
		Events?.RaiseMediaFailed(MediaPlayerError.Unknown, message ?? ex?.Message, ex);

591
		this.Log().Debug($"MediaPlayerElementExtension.OnMediaFailed({message})");
592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642
		_owner.PlaybackSession.PlaybackState = MediaPlaybackState.None;
	}

	public void OnVolumeChanged()
	{
		if (this.Log().IsEnabled(LogLevel.Debug))
		{
			this.Log().Debug($"OnVolumeChanged: {_owner.Volume}");
		}

		var volume = (float)_owner.Volume / 100;
		_player?.SetVolume(volume);
	}

	private void OnTimeUpdate(object? sender, object what)
	{
		try
		{
			_updatingPosition = true;

			if (this.Log().IsEnabled(LogLevel.Trace))
			{
				this.Log().Trace($"OnTimeUpdate: {Position}");
			}

			Events?.RaisePositionChanged();
		}
		finally
		{
			_updatingPosition = false;
		}
	}

	public void OnSeekComplete()
	{
		if (this.Log().IsEnabled(LogLevel.Trace))
		{
			this.Log().Trace($"OnSeekComplete: {Position}");
		}

		Events?.RaiseSeekCompleted();
	}

	private void TryDisposePlayer()
	{
		if (_player != null)
		{
			_isPlayRequested = false;
			_isPlayerPrepared = false;
		}
	}
643

644 645 646 647
	public void SetTransportControlsBounds(Rect bounds)
	{
		// No effect on WebAssembly.
	}
648
}