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(Features.AudioEffect))
58 _audioEffect = new AudioEffect(this);
61 if (Features.IsSupported(Features.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);
276 var completionSource = new TaskCompletionSource<bool>();
286 completionSource.SetResult(true);
291 completionSource.TrySetException(e);
295 return completionSource.Task;
299 /// Unprepares the player.
302 /// The most recently used source is reset and is no longer associated with the player. Playback is no longer possible.
303 /// If you want to use the player again, you have to set a source and call <see cref="PrepareAsync"/> again.
305 /// The player must be in the <see cref="PlayerState.Ready"/>, <see cref="PlayerState.Playing"/>, or <see cref="PlayerState.Paused"/> state.
306 /// It has no effect if the player is already in the <see cref="PlayerState.Idle"/> state.
309 /// <exception cref="ObjectDisposedException">The player has already been disposed of.</exception>
310 /// <exception cref="InvalidOperationException">The player is not in the valid state.</exception>
311 /// <since_tizen> 3 </since_tizen>
312 public virtual void Unprepare()
314 if (State == PlayerState.Idle)
316 Log.Warn(PlayerLog.Tag, "idle state already");
319 ValidatePlayerState(PlayerState.Ready, PlayerState.Paused, PlayerState.Playing);
321 NativePlayer.Unprepare(Handle).ThrowIfFailed("Failed to unprepare the player");
327 /// Called after the <see cref="Player"/> is unprepared.
329 /// <seealso cref="Unprepare"/>
330 /// <since_tizen> 3 </since_tizen>
331 protected virtual void OnUnprepared()
333 _source?.DetachFrom(this);
338 /// Starts or resumes playback.
341 /// The player must be in the <see cref="PlayerState.Ready"/> or <see cref="PlayerState.Paused"/> state.
342 /// It has no effect if the player is already in the <see cref="PlayerState.Playing"/> state.<br/>
344 /// Sound can be mixed with other sounds if you don't control the stream focus using <see cref="ApplyAudioStreamPolicy"/>.
346 /// <exception cref="ObjectDisposedException">The player has already been disposed of.</exception>
347 /// <exception cref="InvalidOperationException">The player is not in the valid state.</exception>
348 /// <seealso cref="PrepareAsync"/>
349 /// <seealso cref="Stop"/>
350 /// <seealso cref="Pause"/>
351 /// <seealso cref="PlaybackCompleted"/>
352 /// <seealso cref="ApplyAudioStreamPolicy"/>
353 /// <since_tizen> 3 </since_tizen>
354 public virtual void Start()
356 if (State == PlayerState.Playing)
358 Log.Warn(PlayerLog.Tag, "playing state already");
361 ValidatePlayerState(PlayerState.Ready, PlayerState.Paused);
363 NativePlayer.Start(Handle).ThrowIfFailed("Failed to start the player");
367 /// Stops playing the media content.
370 /// The player must be in the <see cref="PlayerState.Playing"/> or <see cref="PlayerState.Paused"/> state.
371 /// It has no effect if the player is already in the <see cref="PlayerState.Ready"/> state.
373 /// <exception cref="ObjectDisposedException">The player has already been disposed of.</exception>
374 /// <exception cref="InvalidOperationException">The player is not in the valid state.</exception>
375 /// <seealso cref="Start"/>
376 /// <seealso cref="Pause"/>
377 /// <since_tizen> 3 </since_tizen>
378 public virtual void Stop()
380 if (State == PlayerState.Ready)
382 Log.Warn(PlayerLog.Tag, "ready state already");
385 ValidatePlayerState(PlayerState.Paused, PlayerState.Playing);
387 NativePlayer.Stop(Handle).ThrowIfFailed("Failed to stop the player");
391 /// Pauses the player.
394 /// The player must be in the <see cref="PlayerState.Playing"/> state.
395 /// It has no effect if the player is already in the <see cref="PlayerState.Paused"/> state.
397 /// <exception cref="ObjectDisposedException">The player has already been disposed of.</exception>
398 /// <exception cref="InvalidOperationException">The player is not in the valid state.</exception>
399 /// <seealso cref="Start"/>
400 /// <since_tizen> 3 </since_tizen>
401 public virtual void Pause()
403 if (State == PlayerState.Paused)
405 Log.Warn(PlayerLog.Tag, "pause state already");
409 ValidatePlayerState(PlayerState.Playing);
411 NativePlayer.Pause(Handle).ThrowIfFailed("Failed to pause the player");
414 private MediaSource _source;
417 /// Sets a media source for the player.
419 /// <param name="source">A <see cref="MediaSource"/> that specifies the source for playback.</param>
420 /// <remarks>The player must be in the <see cref="PlayerState.Idle"/> state.</remarks>
421 /// <exception cref="ObjectDisposedException">The player has already been disposed of.</exception>
422 /// <exception cref="InvalidOperationException">
423 /// The player is not in the valid state.<br/>
425 /// It is not able to assign the source to the player.
427 /// <seealso cref="PrepareAsync"/>
428 /// <since_tizen> 3 </since_tizen>
429 public void SetSource(MediaSource source)
431 ValidatePlayerState(PlayerState.Idle);
435 source.AttachTo(this);
440 _source.DetachFrom(this);
447 /// Captures a video frame, asynchronously.
449 /// <returns>A task that represents the asynchronous capture operation.</returns>
450 /// <feature>http://tizen.org/feature/multimedia.raw_video</feature>
451 /// <remarks>The player must be in the <see cref="PlayerState.Playing"/> or <see cref="PlayerState.Paused"/> state.</remarks>
452 /// <exception cref="ObjectDisposedException">The player has already been disposed of.</exception>
453 /// <exception cref="InvalidOperationException">The player is not in the valid state.</exception>
454 /// <exception cref="NotSupportedException">The required feature is not supported.</exception>
455 /// <since_tizen> 3 </since_tizen>
456 public async Task<CapturedFrame> CaptureVideoAsync()
458 ValidationUtil.ValidateFeatureSupported(Features.RawVideo);
460 ValidatePlayerState(PlayerState.Playing, PlayerState.Paused);
462 TaskCompletionSource<CapturedFrame> t = new TaskCompletionSource<CapturedFrame>();
464 NativePlayer.VideoCaptureCallback cb = (data, width, height, size, _) =>
466 Debug.Assert(size <= int.MaxValue);
468 byte[] buf = new byte[size];
469 Marshal.Copy(data, buf, 0, (int)size);
471 t.TrySetResult(new CapturedFrame(buf, width, height));
474 using (var cbKeeper = ObjectKeeper.Get(cb))
476 NativePlayer.CaptureVideo(Handle, cb)
477 .ThrowIfFailed("Failed to capture the video");
484 /// Gets the play position in milliseconds.
486 /// <remarks>The player must be in the <see cref="PlayerState.Ready"/>, <see cref="PlayerState.Playing"/>,
487 /// or <see cref="PlayerState.Paused"/> state.</remarks>
488 /// <exception cref="ObjectDisposedException">The player has already been disposed of.</exception>
489 /// <exception cref="InvalidOperationException">The player is not in the valid state.</exception>
490 /// <seealso cref="SetPlayPositionAsync(int, bool)"/>
491 /// <since_tizen> 3 </since_tizen>
492 public int GetPlayPosition()
494 ValidatePlayerState(PlayerState.Ready, PlayerState.Paused, PlayerState.Playing);
496 int playPosition = 0;
498 NativePlayer.GetPlayPosition(Handle, out playPosition).
499 ThrowIfFailed("Failed to get the play position of the player");
501 Log.Info(PlayerLog.Tag, "get play position : " + playPosition);
506 private void SetPlayPosition(int milliseconds, bool accurate,
507 NativePlayer.SeekCompletedCallback cb)
509 var ret = NativePlayer.SetPlayPosition(Handle, milliseconds, accurate, cb, IntPtr.Zero);
511 //Note that we assume invalid param error is returned only when the position value is invalid.
512 if (ret == PlayerErrorCode.InvalidArgument)
514 throw new ArgumentOutOfRangeException(nameof(milliseconds), milliseconds,
515 "The position is not valid.");
517 if (ret != PlayerErrorCode.None)
519 Log.Error(PlayerLog.Tag, "Failed to set play position, " + (PlayerError)ret);
521 ret.ThrowIfFailed("Failed to set play position");
525 /// Sets the seek position for playback, asynchronously.
527 /// <param name="position">The value indicating a desired position in milliseconds.</param>
528 /// <param name="accurate">The value indicating whether the operation performs with accuracy.</param>
530 /// <para>The player must be in the <see cref="PlayerState.Ready"/>, <see cref="PlayerState.Playing"/>,
531 /// or <see cref="PlayerState.Paused"/> state.</para>
532 /// <para>If the <paramref name="accurate"/> is true, the play position will be adjusted as the specified <paramref name="position"/> value,
533 /// but this might be considerably slow. If false, the play position will be a nearest keyframe position.</para>
535 /// <exception cref="ObjectDisposedException">The player has already been disposed of.</exception>
536 /// <exception cref="InvalidOperationException">The player is not in the valid state.</exception>
537 /// <exception cref="ArgumentOutOfRangeException">The specified position is not valid.</exception>
538 /// <seealso cref="GetPlayPosition"/>
539 /// <since_tizen> 3 </since_tizen>
540 public async Task SetPlayPositionAsync(int position, bool accurate)
542 ValidatePlayerState(PlayerState.Ready, PlayerState.Playing, PlayerState.Paused);
544 var taskCompletionSource = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
546 bool immediateResult = _source is MediaStreamSource;
548 NativePlayer.SeekCompletedCallback cb = _ => taskCompletionSource.TrySetResult(true);
550 using (var cbKeeper = ObjectKeeper.Get(cb))
552 SetPlayPosition(position, accurate, cb);
555 taskCompletionSource.TrySetResult(true);
558 await taskCompletionSource.Task;
563 /// Sets the playback rate.
565 /// <param name="rate">The value for the playback rate. Valid range is -5.0 to 5.0, inclusive.</param>
567 /// <para>The player must be in the <see cref="PlayerState.Ready"/>, <see cref="PlayerState.Playing"/>,
568 /// or <see cref="PlayerState.Paused"/> state.</para>
569 /// <para>The sound will be muted, when the playback rate is under 0.0 or over 2.0.</para>
571 /// <exception cref="ObjectDisposedException">The player has already been disposed of.</exception>
572 /// <exception cref="InvalidOperationException">
573 /// The player is not in the valid state.<br/>
575 /// Streaming playback.
577 /// <exception cref="ArgumentOutOfRangeException">
578 /// <paramref name="rate"/> is less than 5.0.<br/>
580 /// <paramref name="rate"/> is greater than 5.0.<br/>
582 /// <paramref name="rate"/> is zero.
584 /// <since_tizen> 3 </since_tizen>
585 public void SetPlaybackRate(float rate)
587 if (rate < -5.0F || 5.0F < rate || rate == 0.0F)
589 throw new ArgumentOutOfRangeException(nameof(rate), rate, "Valid range is -5.0 to 5.0 (except 0.0)");
592 ValidatePlayerState(PlayerState.Ready, PlayerState.Playing, PlayerState.Paused);
594 NativePlayer.SetPlaybackRate(Handle, rate).ThrowIfFailed("Failed to set the playback rate.");
598 /// Applies the audio stream policy.
600 /// <param name="policy">The <see cref="AudioStreamPolicy"/> to apply.</param>
602 /// The player must be in the <see cref="PlayerState.Idle"/> state.<br/>
604 /// <see cref="Player"/> does not support all <see cref="AudioStreamType"/>.<br/>
605 /// Supported types are <see cref="AudioStreamType.Media"/>, <see cref="AudioStreamType.System"/>,
606 /// <see cref="AudioStreamType.Alarm"/>, <see cref="AudioStreamType.Notification"/>,
607 /// <see cref="AudioStreamType.Emergency"/>, <see cref="AudioStreamType.VoiceInformation"/>,
608 /// <see cref="AudioStreamType.RingtoneVoip"/> and <see cref="AudioStreamType.MediaExternalOnly"/>.
610 /// <exception cref="ObjectDisposedException">
611 /// The player has already been disposed of.<br/>
613 /// <paramref name="policy"/> has already been disposed of.
615 /// <exception cref="InvalidOperationException">The player is not in the valid state.</exception>
616 /// <exception cref="ArgumentNullException"><paramref name="policy"/> is null.</exception>
617 /// <exception cref="NotSupportedException">
618 /// <see cref="AudioStreamType"/> of <paramref name="policy"/> is not supported by <see cref="Player"/>.
620 /// <seealso cref="AudioStreamPolicy"/>
621 /// <since_tizen> 3 </since_tizen>
622 public void ApplyAudioStreamPolicy(AudioStreamPolicy policy)
626 throw new ArgumentNullException(nameof(policy));
629 ValidatePlayerState(PlayerState.Idle);
631 NativePlayer.SetAudioPolicyInfo(Handle, policy.Handle).
632 ThrowIfFailed("Failed to set the audio stream policy to the player");
636 #region Preparing state
638 private int _isPreparing;
640 private bool IsPreparing()
642 return Interlocked.CompareExchange(ref _isPreparing, 1, 1) == 1;
645 private void SetPreparing()
647 Interlocked.Exchange(ref _isPreparing, 1);
650 private void ClearPreparing()
652 Interlocked.Exchange(ref _isPreparing, 0);
658 /// This method supports the product infrastructure and is not intended to be used directly from application code.
660 /// <since_tizen> 4 </since_tizen>
661 [EditorBrowsable(EditorBrowsableState.Never)]
662 protected static Exception GetException(int errorCode, string message) =>
663 ((PlayerErrorCode)errorCode).GetException(message);