2 * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
4 * Licensed under the Apache License, Version 2.0 (the License);
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an AS IS BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 using System.Threading.Tasks;
18 using System.Runtime.InteropServices;
19 using System.Diagnostics;
21 using System.Threading;
23 using System.ComponentModel;
25 namespace Tizen.Multimedia
27 internal static class PlayerLog
29 internal const string Tag = "Tizen.Multimedia.Player";
33 /// Provides the ability to control media playback.
36 /// The player provides functions to play a media content.
37 /// It also provides functions to adjust the configurations of the player such as playback rate, volume, looping etc.
38 /// Note that only one video player can be played at one time.
40 public partial class Player : IDisposable, IDisplayable<PlayerErrorCode>
42 private PlayerHandle _handle;
45 /// Initializes a new instance of the <see cref="Player"/> class.
47 /// <since_tizen> 3 </since_tizen>
50 NativePlayer.Create(out _handle).ThrowIfFailed("Failed to create player");
52 Debug.Assert(_handle != null);
56 if (Features.IsSupported(PlayerFeatures.AudioEffect))
58 _audioEffect = new AudioEffect(this);
61 if (Features.IsSupported(PlayerFeatures.RawVideo))
63 RegisterVideoFrameDecodedCallback();
66 DisplaySettings = PlayerDisplaySettings.Create(this);
69 internal void ValidatePlayerState(params PlayerState[] desiredStates)
71 Debug.Assert(desiredStates.Length > 0);
73 ValidateNotDisposed();
76 if (curState.IsAnyOf(desiredStates))
81 throw new InvalidOperationException($"The player is not in a valid state. " +
82 $"Current State : { curState }, Valid State : { string.Join(", ", desiredStates) }.");
85 #region Dispose support
86 private bool _disposed;
89 /// Releases all resources used by the current instance.
91 /// <since_tizen> 3 </since_tizen>
97 private void Dispose(bool disposing)
101 ReplaceDisplay(null);
107 _source.DetachFrom(this);
111 Log.Error(PlayerLog.Tag, e.ToString());
124 internal void ValidateNotDisposed()
128 Log.Warn(PlayerLog.Tag, "player was disposed");
129 throw new ObjectDisposedException(nameof(Player));
133 internal bool IsDisposed => _disposed;
139 /// Gets the streaming download progress.
141 /// <returns>The <see cref="DownloadProgress"/> containing current download progress.</returns>
142 /// <remarks>The player must be in the <see cref="PlayerState.Playing"/> or <see cref="PlayerState.Paused"/> state.</remarks>
143 /// <exception cref="InvalidOperationException">
144 /// The player is not streaming.<br/>
146 /// The player is not in the valid state.
148 /// <exception cref="ObjectDisposedException">The player has already been disposed of.</exception>
149 /// <since_tizen> 3 </since_tizen>
150 public DownloadProgress GetDownloadProgress()
152 ValidatePlayerState(PlayerState.Playing, PlayerState.Paused);
156 NativePlayer.GetStreamingDownloadProgress(Handle, out start, out current).
157 ThrowIfFailed("Failed to get download progress");
159 Log.Info(PlayerLog.Tag, "get download progress : " + start + ", " + current);
161 return new DownloadProgress(start, current);
165 /// Sets the subtitle path for playback.
167 /// <remarks>Only MicroDVD/SubViewer(*.sub), SAMI(*.smi), and SubRip(*.srt) subtitle formats are supported.
168 /// <para>The mediastorage privilege(http://tizen.org/privilege/mediastorage) must be added if any files are used to play located in the internal storage.
169 /// The externalstorage privilege(http://tizen.org/privilege/externalstorage) must be added if any files are used to play located in the external storage.</para>
171 /// <exception cref="ObjectDisposedException">The player has already been disposed of.</exception>
172 /// <exception cref="ArgumentException"><paramref name="path"/> is an empty string.</exception>
173 /// <exception cref="FileNotFoundException">The specified path does not exist.</exception>
174 /// <exception cref="ArgumentNullException"><paramref name="path"/> is null.</exception>
175 /// <since_tizen> 3 </since_tizen>
176 public void SetSubtitle(string path)
178 ValidateNotDisposed();
182 throw new ArgumentNullException(nameof(path));
185 if (path.Length == 0)
187 throw new ArgumentException("The path is empty.", nameof(path));
190 if (!File.Exists(path))
192 throw new FileNotFoundException($"The specified file does not exist.", path);
195 NativePlayer.SetSubtitlePath(Handle, path).
196 ThrowIfFailed("Failed to set the subtitle path to the player");
200 /// Removes the subtitle path.
202 /// <remarks>The player must be in the <see cref="PlayerState.Idle"/> state.</remarks>
203 /// <exception cref="ObjectDisposedException">The player has already been disposed of.</exception>
204 /// <exception cref="InvalidOperationException">The player is not in the valid state.</exception>
205 /// <since_tizen> 3 </since_tizen>
206 public void ClearSubtitle()
208 ValidatePlayerState(PlayerState.Idle);
210 NativePlayer.SetSubtitlePath(Handle, null).
211 ThrowIfFailed("Failed to clear the subtitle of the player");
215 /// Sets the offset for the subtitle.
217 /// <param name="offset">The value indicating a desired offset in milliseconds.</param>
218 /// <remarks>The player must be in the <see cref="PlayerState.Playing"/> or <see cref="PlayerState.Paused"/> state.</remarks>
219 /// <exception cref="ObjectDisposedException">The player has already been disposed of.</exception>
220 /// <exception cref="InvalidOperationException">
221 /// The player is not in the valid state.<br/>
223 /// No subtitle is set.
225 /// <seealso cref="SetSubtitle(string)"/>
226 /// <since_tizen> 3 </since_tizen>
227 public void SetSubtitleOffset(int offset)
229 ValidatePlayerState(PlayerState.Playing, PlayerState.Paused);
231 var err = NativePlayer.SetSubtitlePositionOffset(Handle, offset);
233 if (err == PlayerErrorCode.FeatureNotSupported)
235 throw new InvalidOperationException("No subtitle set");
238 err.ThrowIfFailed("Failed to the subtitle offset of the player");
241 private void Prepare()
243 NativePlayer.Prepare(Handle).ThrowIfFailed("Failed to prepare the player");
247 /// Called when the <see cref="Prepare"/> is invoked.
249 /// <since_tizen> 3 </since_tizen>
250 protected virtual void OnPreparing()
256 /// Prepares the media player for playback, asynchronously.
258 /// <returns>A task that represents the asynchronous prepare operation.</returns>
259 /// <remarks>To prepare the player, the player must be in the <see cref="PlayerState.Idle"/> state,
260 /// and a source must be set.</remarks>
261 /// <exception cref="InvalidOperationException">No source is set.</exception>
262 /// <exception cref="ObjectDisposedException">The player has already been disposed of.</exception>
263 /// <exception cref="InvalidOperationException">The player is not in the valid state.</exception>
264 /// <since_tizen> 3 </since_tizen>
265 public virtual Task PrepareAsync()
269 throw new InvalidOperationException("No source is set.");
272 ValidatePlayerState(PlayerState.Idle);
274 SetDisplay(_display).ThrowIfFailed("Failed to configure display of the player");
278 var completionSource = new TaskCompletionSource<bool>();
288 completionSource.SetResult(true);
293 completionSource.TrySetException(e);
297 return completionSource.Task;
301 /// Unprepares the player.
304 /// The most recently used source is reset and is no longer associated with the player. Playback is no longer possible.
305 /// If you want to use the player again, you have to set a source and call <see cref="PrepareAsync"/> again.
307 /// The player must be in the <see cref="PlayerState.Ready"/>, <see cref="PlayerState.Playing"/>, or <see cref="PlayerState.Paused"/> state.
308 /// It has no effect if the player is already in the <see cref="PlayerState.Idle"/> state.
311 /// <exception cref="ObjectDisposedException">The player has already been disposed of.</exception>
312 /// <exception cref="InvalidOperationException">The player is not in the valid state.</exception>
313 /// <since_tizen> 3 </since_tizen>
314 public virtual void Unprepare()
316 if (State == PlayerState.Idle)
318 Log.Warn(PlayerLog.Tag, "idle state already");
321 ValidatePlayerState(PlayerState.Ready, PlayerState.Paused, PlayerState.Playing);
323 NativePlayer.Unprepare(Handle).ThrowIfFailed("Failed to unprepare the player");
329 /// Called after the <see cref="Player"/> is unprepared.
331 /// <seealso cref="Unprepare"/>
332 /// <since_tizen> 3 </since_tizen>
333 protected virtual void OnUnprepared()
335 _source?.DetachFrom(this);
340 /// Starts or resumes playback.
343 /// The player must be in the <see cref="PlayerState.Ready"/> or <see cref="PlayerState.Paused"/> state.
344 /// It has no effect if the player is already in the <see cref="PlayerState.Playing"/> state.<br/>
346 /// Sound can be mixed with other sounds if you don't control the stream focus using <see cref="ApplyAudioStreamPolicy"/>.
348 /// <exception cref="ObjectDisposedException">The player has already been disposed of.</exception>
349 /// <exception cref="InvalidOperationException">The player is not in the valid state.</exception>
350 /// <seealso cref="PrepareAsync"/>
351 /// <seealso cref="Stop"/>
352 /// <seealso cref="Pause"/>
353 /// <seealso cref="PlaybackCompleted"/>
354 /// <seealso cref="ApplyAudioStreamPolicy"/>
355 /// <since_tizen> 3 </since_tizen>
356 public virtual void Start()
358 if (State == PlayerState.Playing)
360 Log.Warn(PlayerLog.Tag, "playing state already");
363 ValidatePlayerState(PlayerState.Ready, PlayerState.Paused);
365 NativePlayer.Start(Handle).ThrowIfFailed("Failed to start the player");
369 /// Stops playing the media content.
372 /// The player must be in the <see cref="PlayerState.Playing"/> or <see cref="PlayerState.Paused"/> state.
373 /// It has no effect if the player is already in the <see cref="PlayerState.Ready"/> state.
375 /// <exception cref="ObjectDisposedException">The player has already been disposed of.</exception>
376 /// <exception cref="InvalidOperationException">The player is not in the valid state.</exception>
377 /// <seealso cref="Start"/>
378 /// <seealso cref="Pause"/>
379 /// <since_tizen> 3 </since_tizen>
380 public virtual void Stop()
382 if (State == PlayerState.Ready)
384 Log.Warn(PlayerLog.Tag, "ready state already");
387 ValidatePlayerState(PlayerState.Paused, PlayerState.Playing);
389 NativePlayer.Stop(Handle).ThrowIfFailed("Failed to stop the player");
393 /// Pauses the player.
396 /// The player must be in the <see cref="PlayerState.Playing"/> state.
397 /// It has no effect if the player is already in the <see cref="PlayerState.Paused"/> state.
399 /// <exception cref="ObjectDisposedException">The player has already been disposed of.</exception>
400 /// <exception cref="InvalidOperationException">The player is not in the valid state.</exception>
401 /// <seealso cref="Start"/>
402 /// <since_tizen> 3 </since_tizen>
403 public virtual void Pause()
405 if (State == PlayerState.Paused)
407 Log.Warn(PlayerLog.Tag, "pause state already");
411 ValidatePlayerState(PlayerState.Playing);
413 NativePlayer.Pause(Handle).ThrowIfFailed("Failed to pause the player");
416 private MediaSource _source;
419 /// Sets a media source for the player.
421 /// <param name="source">A <see cref="MediaSource"/> that specifies the source for playback.</param>
422 /// <remarks>The player must be in the <see cref="PlayerState.Idle"/> state.</remarks>
423 /// <exception cref="ObjectDisposedException">The player has already been disposed of.</exception>
424 /// <exception cref="InvalidOperationException">
425 /// The player is not in the valid state.<br/>
427 /// It is not able to assign the source to the player.
429 /// <seealso cref="PrepareAsync"/>
430 /// <since_tizen> 3 </since_tizen>
431 public void SetSource(MediaSource source)
433 ValidatePlayerState(PlayerState.Idle);
437 source.AttachTo(this);
442 _source.DetachFrom(this);
449 /// Captures a video frame, asynchronously.
451 /// <returns>A task that represents the asynchronous capture operation.</returns>
452 /// <feature>http://tizen.org/feature/multimedia.raw_video</feature>
453 /// <remarks>The player must be in the <see cref="PlayerState.Playing"/> or <see cref="PlayerState.Paused"/> state.</remarks>
454 /// <exception cref="ObjectDisposedException">The player has already been disposed of.</exception>
455 /// <exception cref="InvalidOperationException">The player is not in the valid state.</exception>
456 /// <exception cref="NotSupportedException">The required feature is not supported.</exception>
457 /// <since_tizen> 3 </since_tizen>
458 public async Task<CapturedFrame> CaptureVideoAsync()
460 ValidationUtil.ValidateFeatureSupported(PlayerFeatures.RawVideo);
462 ValidatePlayerState(PlayerState.Playing, PlayerState.Paused);
464 TaskCompletionSource<CapturedFrame> t = new TaskCompletionSource<CapturedFrame>();
466 NativePlayer.VideoCaptureCallback cb = (data, width, height, size, _) =>
468 Debug.Assert(size <= int.MaxValue);
470 byte[] buf = new byte[size];
471 Marshal.Copy(data, buf, 0, (int)size);
473 t.TrySetResult(new CapturedFrame(buf, width, height));
476 using (var cbKeeper = ObjectKeeper.Get(cb))
478 NativePlayer.CaptureVideo(Handle, cb)
479 .ThrowIfFailed("Failed to capture the video");
486 /// Gets the play position in milliseconds.
488 /// <remarks>The player must be in the <see cref="PlayerState.Ready"/>, <see cref="PlayerState.Playing"/>,
489 /// or <see cref="PlayerState.Paused"/> state.</remarks>
490 /// <exception cref="ObjectDisposedException">The player has already been disposed of.</exception>
491 /// <exception cref="InvalidOperationException">The player is not in the valid state.</exception>
492 /// <seealso cref="SetPlayPositionAsync(int, bool)"/>
493 /// <since_tizen> 3 </since_tizen>
494 public int GetPlayPosition()
496 ValidatePlayerState(PlayerState.Ready, PlayerState.Paused, PlayerState.Playing);
498 int playPosition = 0;
500 NativePlayer.GetPlayPosition(Handle, out playPosition).
501 ThrowIfFailed("Failed to get the play position of the player");
503 Log.Info(PlayerLog.Tag, "get play position : " + playPosition);
508 private void SetPlayPosition(int milliseconds, bool accurate,
509 NativePlayer.SeekCompletedCallback cb)
511 var ret = NativePlayer.SetPlayPosition(Handle, milliseconds, accurate, cb, IntPtr.Zero);
513 //Note that we assume invalid param error is returned only when the position value is invalid.
514 if (ret == PlayerErrorCode.InvalidArgument)
516 throw new ArgumentOutOfRangeException(nameof(milliseconds), milliseconds,
517 "The position is not valid.");
519 if (ret != PlayerErrorCode.None)
521 Log.Error(PlayerLog.Tag, "Failed to set play position, " + (PlayerError)ret);
523 ret.ThrowIfFailed("Failed to set play position");
527 /// Sets the seek position for playback, asynchronously.
529 /// <param name="position">The value indicating a desired position in milliseconds.</param>
530 /// <param name="accurate">The value indicating whether the operation performs with accuracy.</param>
532 /// <para>The player must be in the <see cref="PlayerState.Ready"/>, <see cref="PlayerState.Playing"/>,
533 /// or <see cref="PlayerState.Paused"/> state.</para>
534 /// <para>If the <paramref name="accurate"/> is true, the play position will be adjusted as the specified <paramref name="position"/> value,
535 /// but this might be considerably slow. If false, the play position will be a nearest keyframe position.</para>
537 /// <exception cref="ObjectDisposedException">The player has already been disposed of.</exception>
538 /// <exception cref="InvalidOperationException">The player is not in the valid state.</exception>
539 /// <exception cref="ArgumentOutOfRangeException">The specified position is not valid.</exception>
540 /// <seealso cref="GetPlayPosition"/>
541 /// <since_tizen> 3 </since_tizen>
542 public async Task SetPlayPositionAsync(int position, bool accurate)
544 ValidatePlayerState(PlayerState.Ready, PlayerState.Playing, PlayerState.Paused);
546 var taskCompletionSource = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
548 bool immediateResult = _source is MediaStreamSource;
550 NativePlayer.SeekCompletedCallback cb = _ => taskCompletionSource.TrySetResult(true);
552 using (var cbKeeper = ObjectKeeper.Get(cb))
554 SetPlayPosition(position, accurate, cb);
557 taskCompletionSource.TrySetResult(true);
560 await taskCompletionSource.Task;
565 /// Sets the playback rate.
567 /// <param name="rate">The value for the playback rate. Valid range is -5.0 to 5.0, inclusive.</param>
569 /// <para>The player must be in the <see cref="PlayerState.Ready"/>, <see cref="PlayerState.Playing"/>,
570 /// or <see cref="PlayerState.Paused"/> state.</para>
571 /// <para>The sound will be muted, when the playback rate is under 0.0 or over 2.0.</para>
573 /// <exception cref="ObjectDisposedException">The player has already been disposed of.</exception>
574 /// <exception cref="InvalidOperationException">
575 /// The player is not in the valid state.<br/>
577 /// Streaming playback.
579 /// <exception cref="ArgumentOutOfRangeException">
580 /// <paramref name="rate"/> is less than 5.0.<br/>
582 /// <paramref name="rate"/> is greater than 5.0.<br/>
584 /// <paramref name="rate"/> is zero.
586 /// <since_tizen> 3 </since_tizen>
587 public void SetPlaybackRate(float rate)
589 if (rate < -5.0F || 5.0F < rate || rate == 0.0F)
591 throw new ArgumentOutOfRangeException(nameof(rate), rate, "Valid range is -5.0 to 5.0 (except 0.0)");
594 ValidatePlayerState(PlayerState.Ready, PlayerState.Playing, PlayerState.Paused);
596 NativePlayer.SetPlaybackRate(Handle, rate).ThrowIfFailed("Failed to set the playback rate.");
600 /// Applies the audio stream policy.
602 /// <param name="policy">The <see cref="AudioStreamPolicy"/> to apply.</param>
604 /// The player must be in the <see cref="PlayerState.Idle"/> state.<br/>
606 /// <see cref="Player"/> does not support all <see cref="AudioStreamType"/>.<br/>
607 /// Supported types are <see cref="AudioStreamType.Media"/>, <see cref="AudioStreamType.System"/>,
608 /// <see cref="AudioStreamType.Alarm"/>, <see cref="AudioStreamType.Notification"/>,
609 /// <see cref="AudioStreamType.Emergency"/>, <see cref="AudioStreamType.VoiceInformation"/>,
610 /// <see cref="AudioStreamType.RingtoneVoip"/> and <see cref="AudioStreamType.MediaExternalOnly"/>.
612 /// <exception cref="ObjectDisposedException">
613 /// The player has already been disposed of.<br/>
615 /// <paramref name="policy"/> has already been disposed of.
617 /// <exception cref="InvalidOperationException">The player is not in the valid state.</exception>
618 /// <exception cref="ArgumentNullException"><paramref name="policy"/> is null.</exception>
619 /// <exception cref="NotSupportedException">
620 /// The required feature is not supported.<br/>
622 /// <see cref="AudioStreamType"/> of <paramref name="policy"/> is not supported on the current platform.
624 /// <seealso cref="AudioStreamPolicy"/>
625 /// <feature>http://tizen.org/feature/multimedia.player.stream_info</feature>
626 /// <since_tizen> 3 </since_tizen>
627 public void ApplyAudioStreamPolicy(AudioStreamPolicy policy)
629 ValidationUtil.ValidateFeatureSupported("http://tizen.org/feature/multimedia.player.stream_info");
633 throw new ArgumentNullException(nameof(policy));
636 ValidatePlayerState(PlayerState.Idle);
638 var ret = NativePlayer.SetAudioPolicyInfo(Handle, policy.Handle);
640 if (ret == PlayerErrorCode.InvalidArgument)
642 throw new NotSupportedException("The specified policy is not supported on the current system.");
645 ret.ThrowIfFailed("Failed to set the audio stream policy to the player");
649 #region Preparing state
651 private int _isPreparing;
653 private bool IsPreparing()
655 return Interlocked.CompareExchange(ref _isPreparing, 1, 1) == 1;
658 private void SetPreparing()
660 Interlocked.Exchange(ref _isPreparing, 1);
663 private void ClearPreparing()
665 Interlocked.Exchange(ref _isPreparing, 0);
671 /// This method supports the product infrastructure and is not intended to be used directly from application code.
673 /// <since_tizen> 4 </since_tizen>
674 [EditorBrowsable(EditorBrowsableState.Never)]
675 protected static Exception GetException(int errorCode, string message) =>
676 ((PlayerErrorCode)errorCode).GetException(message);