MediaPlayerExtension.cs 15.6 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
	private HtmlMediaPlayer? _player;

	private bool _updatingPosition;
	private bool _isPlayRequested;
	private bool _isPlayerPrepared;
34 35
	private bool _isLoopingEnabled;
	private bool _isLoopingAllEnabled;
36 37 38 39 40 41
	private List<Uri>? _playlistItems;
	private int _playlistIndex;
	private TimeSpan _naturalDuration;
	private Uri? _uri;
	private bool _anonymousCors = FeatureConfiguration.AnonymousCorsDefault;

42 43
	const string MsAppXScheme = "ms-appx";

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 104 105
	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; }

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

120 121 122 123 124 125
	public bool IsLoopingEnabled
	{
		get => _isLoopingEnabled;
		set
		{
			_isLoopingEnabled = value;
126 127 128 129 130 131 132 133 134
		}
	}

	public bool IsLoopingAllEnabled
	{
		get => _isLoopingAllEnabled;
		set
		{
			_isLoopingAllEnabled = value;
135 136
		}
	}
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162

	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;

163 164
	public bool? IsVideo { get; set; }

165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
	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
				{
190
					if (_owner.PlaybackSession.PlaybackState != MediaPlaybackState.None && _player is not null && _player.Source is not null)
191
					{
192 193 194 195
						if (this.Log().IsEnabled(Uno.Foundation.Logging.LogLevel.Debug))
						{
							this.Log().Debug($"Position {value.TotalSeconds}");
						}
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 233 234 235 236 237 238
						_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;

239
		_player.OnStatusChanged -= OnStatusMediaChanged;
R
Rafael Rosa 已提交
240 241
		_player.OnStatusChanged += OnStatusMediaChanged;

242 243 244 245 246 247 248
		_owner.PlaybackSession.PlaybackStateChanged -= OnStatusChanged;
		_owner.PlaybackSession.PlaybackStateChanged += OnStatusChanged;

		ApplyAnonymousCors();
		ApplyVideoSource();
	}

R
Rafael Rosa 已提交
249 250 251 252
	private void OnStatusMediaChanged(object? sender, object e)
	{
		if (this.Log().IsEnabled(LogLevel.Debug))
		{
253
			this.Log().Debug($"MediaPlayerExtension.OnStatusMediaChanged to state {_player?.PlayerState.ToString()}");
R
Rafael Rosa 已提交
254
			this.Log().Debug($"MediaPlayerExtension owner PlaybackSession PlaybackState {_owner?.PlaybackSession?.PlaybackState.ToString()}");
R
Rafael Rosa 已提交
255 256
		}

R
Rafael Rosa 已提交
257
		if (_player?.PlayerState == HtmlMediaPlayerState.Paused && _owner?.PlaybackSession.PlaybackState == MediaPlaybackState.Playing)
R
Rafael Rosa 已提交
258
		{
259 260
			_owner.PlaybackSession.PlaybackState = MediaPlaybackState.Paused;
		}
R
Rafael Rosa 已提交
261
		else if (_player?.PlayerState == HtmlMediaPlayerState.Playing && _owner?.PlaybackSession.PlaybackState == MediaPlaybackState.Paused)
262 263
		{
			_owner.PlaybackSession.PlaybackState = MediaPlaybackState.Playing;
R
Rafael Rosa 已提交
264 265 266
		}
	}

267 268 269 270 271 272 273 274 275
	private void SetPlaylistItems(MediaPlaybackList playlist)
	{
		_playlistItems = playlist.Items
			.Select(i => i.Source.Uri)
			.ToList();
	}

	public void InitializeSource()
	{
R
Rafael Rosa 已提交
276 277 278 279
		if (this.Log().IsEnabled(LogLevel.Debug))
		{
			this.Log().LogDebug("Enter MediaPlayerExtension.InitializeSource().");
		}
280 281

		NaturalDuration = TimeSpan.Zero;
282 283 284 285
		if (Position != TimeSpan.Zero)
		{
			Position = TimeSpan.Zero;
		}
286 287 288 289 290 291 292 293 294 295 296 297

		// Reset player
		TryDisposePlayer();

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

		try
		{
			_owner.PlaybackSession.PlaybackState = MediaPlaybackState.Opening;
298
			InitializePlayer();
299 300 301

			switch (_owner.Source)
			{
302
				case MediaPlaybackList playlist when playlist.Items.Count > 0:
303
					SetPlaylistItems(playlist);
R
Rafael Rosa 已提交
304
					if (_playlistItems is not null && _playlistItems.Any())
305 306 307 308 309 310 311
					{
						_uri = _playlistItems[0];
					}
					else
					{
						throw new InvalidOperationException("Playlist Items could not be set");
					}
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
					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();
327
			Events?.RaiseSourceChanged();
328 329 330
		}
		catch (global::System.Exception ex)
		{
331 332

			this.Log().Debug($"MediaPlayerElementExtension.InitializeSource({ex.Message})");
333 334 335 336
			OnMediaFailed(ex);
		}
	}

337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
	public void ReInitializeSource()
	{
		NaturalDuration = TimeSpan.Zero;
		if (Position != TimeSpan.Zero)
		{
			Position = TimeSpan.Zero;
		}

		if (_owner.Source == null)
		{
			return;
		}
		_owner.PlaybackSession.PlaybackState = MediaPlaybackState.Opening;
		InitializePlayer();
		ApplyVideoSource();
		Events?.RaiseSourceChanged();
	}

355 356 357 358 359 360 361 362 363
	private void ApplyVideoSource()
	{
		if (this.Log().IsEnabled(LogLevel.Debug))
		{
			this.Log().Debug($"MediaPlayerElementExtension.SetVideoSource({_uri})");
		}

		if (_player is not null && _uri is not null)
		{
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
			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;
			}

388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 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
			_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)
			{
441
				_player.PlaybackRate = 1;
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 473 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
				_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
505
			_owner.PlaybackSession.Position = TimeSpan.Zero;
506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535
			_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();
		}
	}

R
Rafael Rosa 已提交
536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552
	private void SetPrepared(HtmlMediaPlayer _player)
	{
		if (_owner.PlaybackSession.PlaybackState == MediaPlaybackState.Opening)
		{
			if (_isPlayRequested)
			{
				_player.Play();
				_owner.PlaybackSession.PlaybackState = MediaPlaybackState.Playing;
			}
			else
			{
				_owner.PlaybackSession.PlaybackState = MediaPlaybackState.Paused;
			}
		}
		_isPlayerPrepared = true;
	}

553 554 555 556 557 558 559 560 561 562 563
	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 已提交
564
			IsVideo = !_player.IsAudio;
565

R
Rafael Rosa 已提交
566
			if (!mp.IsAudio && Events is not null)
567
			{
568
				try
569
				{
570 571 572 573
					if (this.Log().IsEnabled(LogLevel.Debug))
					{
						this.Log().Debug($"OnPrepared: {mp.VideoWidth}x{mp.VideoHeight}");
					}
574

575 576 577
					Events.RaiseVideoRatioChanged((double)mp.VideoWidth / global::System.Math.Max(mp.VideoHeight, 1));
				}
				catch { }
578
			}
R
Rafael Rosa 已提交
579
			if (NaturalDuration > TimeSpan.Zero)
580
			{
R
Rafael Rosa 已提交
581
				SetPrepared(_player);
582 583
			}
		}
584 585 586 587 588

		if (Events is not null)
		{
			Events?.RaiseMediaOpened();
		}
589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606
	}

	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}");
	}

607

608 609 610 611 612 613 614 615 616
	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;
617
		if (IsLoopingEnabled && !IsLoopingAllEnabled)
618
		{
619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640
			Play();
		}
		else
		{
			// Play first item in playlist, if any and repeat all
			if (_playlistItems != null && _playlistIndex >= _playlistItems.Count - 1 && IsLoopingAllEnabled)
			{
				_playlistIndex = 0;
				_uri = _playlistItems[_playlistIndex];
				ReInitializeSource();
				Play();
			}
			else
			{
				// Play next item in playlist, if any
				if (_playlistItems != null && _playlistIndex < _playlistItems.Count - 1)
				{
					_uri = _playlistItems[++_playlistIndex];
					ReInitializeSource();
					Play();
				}
			}
641 642 643
		}
	}

644

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

649
		this.Log().Debug($"MediaPlayerElementExtension.OnMediaFailed({message})");
650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700
		_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;
		}
	}
701

702 703 704 705
	public void SetTransportControlsBounds(Rect bounds)
	{
		// No effect on WebAssembly.
	}
706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729

	public void PreviousTrack()
	{
		// Play prev item in playlist, if any
		if (_playlistItems != null && _playlistIndex > 0)
		{
			Pause();
			_uri = _playlistItems[--_playlistIndex];
			ReInitializeSource();
			Play();
		}
	}

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