2 * Copyright (c) 2018 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.
19 using System.ComponentModel;
20 using System.Diagnostics;
22 using System.Runtime.InteropServices;
23 using System.Threading;
24 using System.Threading.Tasks;
26 namespace Tizen.Multimedia
28 internal static class PlayerLog
30 internal const string Tag = "Tizen.Multimedia.Player";
34 /// Provides the ability to control media playback.
37 /// The player provides functions to play a media content.
38 /// It also provides functions to adjust the configurations of the player such as playback rate, volume, looping etc.
39 /// Note that only one video player can be played at one time.
41 public partial class Player : IDisposable, IDisplayable<PlayerErrorCode>
43 private readonly PlayerHandle _handle;
46 /// Initializes a new instance of the <see cref="Player"/> class.
48 /// <since_tizen> 3 </since_tizen>
51 NativePlayer.Create(out _handle).ThrowIfFailed(null, "Failed to create player");
53 Debug.Assert(_handle != null);
59 /// Initializes a new instance of the <see cref="Player"/> class with a native handle.
60 /// The class takes care of the life cycle of the handle.
61 /// Thus, it should not be closed/destroyed in another location.
63 /// <param name="handle">The handle for the media player.</param>
64 /// <param name="errorHandler">The handle for occuring error.</param>
66 /// This supports the product infrastructure and is not intended to be used directly from application code.
68 [EditorBrowsable(EditorBrowsableState.Never)]
69 protected Player(IntPtr handle, Action<int, string> errorHandler)
71 // This constructor is to support TV product player.
72 // Be careful with 'handle'. It must be wrapped in safe handle, first.
73 _handle = handle != IntPtr.Zero ? new PlayerHandle(handle) :
74 throw new ArgumentException("Handle is invalid.", nameof(handle));
76 _errorHandler = errorHandler;
79 private bool _initialized;
82 /// This supports the product infrastructure and is not intended to be used directly from application code.
84 [EditorBrowsable(EditorBrowsableState.Never)]
85 protected void Initialize()
89 throw new InvalidOperationException("It has already been initialized.");
92 if (Features.IsSupported(PlayerFeatures.AudioEffect))
94 _audioEffect = new AudioEffect(this);
97 if (Features.IsSupported(PlayerFeatures.RawVideo))
99 RegisterVideoFrameDecodedCallback();
104 _displaySettings = PlayerDisplaySettings.Create(this);
109 internal void ValidatePlayerState(params PlayerState[] desiredStates)
111 Debug.Assert(desiredStates.Length > 0);
113 ValidateNotDisposed();
115 var curState = State;
116 if (curState.IsAnyOf(desiredStates))
121 throw new InvalidOperationException($"The player is not in a valid state. " +
122 $"Current State : { curState }, Valid State : { string.Join(", ", desiredStates) }.");
125 #region Dispose support
126 private bool _disposed;
129 /// Releases all resources used by the current instance.
131 /// <since_tizen> 3 </since_tizen>
132 public void Dispose()
135 GC.SuppressFinalize(this);
139 /// Releases the unmanaged resources used by the <see cref="Player"/>.
141 /// <param name="disposing">
142 /// true to release both managed and unmanaged resources; false to release only unmanaged resources.
144 [EditorBrowsable(EditorBrowsableState.Never)]
145 protected virtual void Dispose(bool disposing)
154 ReplaceDisplay(null);
160 _source.DetachFrom(this);
165 Log.Error(PlayerLog.Tag, e.ToString());
177 internal void ValidateNotDisposed()
181 Log.Warn(PlayerLog.Tag, "player was disposed");
182 throw new ObjectDisposedException(nameof(Player));
186 internal bool IsDisposed => _disposed;
192 /// Gets the streaming download progress.
194 /// <returns>The <see cref="DownloadProgress"/> containing current download progress.</returns>
195 /// <remarks>The player must be in the <see cref="PlayerState.Ready"/>, <see cref="PlayerState.Playing"/>,
196 /// or <see cref="PlayerState.Paused"/> state.</remarks>
197 /// <exception cref="InvalidOperationException">
198 /// The player is not streaming.<br/>
200 /// The player is not in the valid state.
202 /// <exception cref="ObjectDisposedException">The player has already been disposed of.</exception>
203 /// <since_tizen> 3 </since_tizen>
204 public DownloadProgress GetDownloadProgress()
206 ValidatePlayerState(PlayerState.Ready, PlayerState.Playing, PlayerState.Paused);
210 NativePlayer.GetStreamingDownloadProgress(Handle, out start, out current).
211 ThrowIfFailed(this, "Failed to get download progress");
213 Log.Info(PlayerLog.Tag, $"get download progress : {start}, {current}");
215 return new DownloadProgress(start, current);
219 /// Sets the subtitle path for playback.
221 /// <param name="path">The absolute path of the subtitle file, it can be NULL in the <see cref="PlayerState.Idle"/> state.</param>
222 /// <remarks>Only MicroDVD/SubViewer(*.sub), SAMI(*.smi), and SubRip(*.srt) subtitle formats are supported.
223 /// <para>The mediastorage privilege(http://tizen.org/privilege/mediastorage) must be added if any files are used to play located in the internal storage.
224 /// The externalstorage privilege(http://tizen.org/privilege/externalstorage) must be added if any files are used to play located in the external storage.</para>
226 /// <exception cref="ObjectDisposedException">The player has already been disposed of.</exception>
227 /// <exception cref="ArgumentException"><paramref name="path"/> is an empty string.</exception>
228 /// <exception cref="FileNotFoundException">The specified path does not exist.</exception>
229 /// <exception cref="ArgumentNullException"><paramref name="path"/> is null.</exception>
230 /// <since_tizen> 3 </since_tizen>
231 public void SetSubtitle(string path)
233 ValidateNotDisposed();
237 throw new ArgumentNullException(nameof(path));
240 if (path.Length == 0)
242 throw new ArgumentException("The path is empty.", nameof(path));
245 if (!File.Exists(path))
247 throw new FileNotFoundException($"The specified file does not exist.", path);
250 NativePlayer.SetSubtitlePath(Handle, path).
251 ThrowIfFailed(this, "Failed to set the subtitle path to the player");
255 /// Removes the subtitle path.
257 /// <remarks>The player must be in the <see cref="PlayerState.Idle"/> state.</remarks>
258 /// <exception cref="ObjectDisposedException">The player has already been disposed of.</exception>
259 /// <exception cref="InvalidOperationException">The player is not in the valid state.</exception>
260 /// <since_tizen> 3 </since_tizen>
261 public void ClearSubtitle()
263 ValidatePlayerState(PlayerState.Idle);
265 NativePlayer.SetSubtitlePath(Handle, null).
266 ThrowIfFailed(this, "Failed to clear the subtitle of the player");
270 /// Sets the offset for the subtitle.
272 /// <param name="offset">The value indicating a desired offset in milliseconds.</param>
273 /// <remarks>The player must be in the <see cref="PlayerState.Playing"/> or <see cref="PlayerState.Paused"/> state.</remarks>
274 /// <exception cref="ObjectDisposedException">The player has already been disposed of.</exception>
275 /// <exception cref="InvalidOperationException">
276 /// The player is not in the valid state.<br/>
278 /// No subtitle is set.
280 /// <seealso cref="SetSubtitle(string)"/>
281 /// <since_tizen> 3 </since_tizen>
282 public void SetSubtitleOffset(int offset)
284 ValidatePlayerState(PlayerState.Playing, PlayerState.Paused);
286 var err = NativePlayer.SetSubtitlePositionOffset(Handle, offset);
288 if (err == PlayerErrorCode.FeatureNotSupported)
290 throw new InvalidOperationException("No subtitle set");
293 err.ThrowIfFailed(this, "Failed to the subtitle offset of the player");
296 private void Prepare()
298 NativePlayer.Prepare(Handle).ThrowIfFailed(this, "Failed to prepare the player");
302 /// Called when the <see cref="Prepare"/> is invoked.
304 /// <since_tizen> 3 </since_tizen>
305 protected virtual void OnPreparing()
310 /// Prepares the media player for playback, asynchronously.
312 /// <returns>A task that represents the asynchronous prepare operation.</returns>
313 /// <remarks>To prepare the player, the player must be in the <see cref="PlayerState.Idle"/> state,
314 /// and a source must be set.</remarks>
315 /// <exception cref="InvalidOperationException">No source is set.</exception>
316 /// <exception cref="ObjectDisposedException">The player has already been disposed of.</exception>
317 /// <exception cref="InvalidOperationException">The player is not in the valid state.</exception>
318 /// <seealso cref="PlayerState.Preparing"/>
319 /// <since_tizen> 3 </since_tizen>
320 public virtual Task PrepareAsync()
324 throw new InvalidOperationException("No source is set.");
327 ValidatePlayerState(PlayerState.Idle);
333 return Task.Factory.StartNew(() =>
343 }, CancellationToken.None,
344 TaskCreationOptions.DenyChildAttach | TaskCreationOptions.LongRunning,
345 TaskScheduler.Default);
349 /// Unprepares the player.
352 /// The most recently used source is reset and is no longer associated with the player. Playback is no longer possible.
353 /// If you want to use the player again, you have to set a source and call <see cref="PrepareAsync"/> again.
355 /// The player must be in the <see cref="PlayerState.Ready"/>, <see cref="PlayerState.Playing"/>, or <see cref="PlayerState.Paused"/> state.
356 /// It has no effect if the player is already in the <see cref="PlayerState.Idle"/> state.
359 /// <exception cref="ObjectDisposedException">The player has already been disposed of.</exception>
360 /// <exception cref="InvalidOperationException">The player is not in the valid state.</exception>
361 /// <since_tizen> 3 </since_tizen>
362 public virtual void Unprepare()
364 if (State == PlayerState.Idle)
366 Log.Warn(PlayerLog.Tag, "idle state already");
369 ValidatePlayerState(PlayerState.Ready, PlayerState.Paused, PlayerState.Playing);
371 NativePlayer.Unprepare(Handle).ThrowIfFailed(this, "Failed to unprepare the player");
377 /// Called after the <see cref="Player"/> is unprepared.
379 /// <seealso cref="Unprepare"/>
380 /// <since_tizen> 3 </since_tizen>
381 protected virtual void OnUnprepared()
383 _source?.DetachFrom(this);
388 /// Starts or resumes playback.
391 /// Sound can be mixed with other sounds if you don't control the stream focus using <see cref="ApplyAudioStreamPolicy"/>.<br/>
392 /// <para>Before Tizen 5.0, The player must be in the <see cref="PlayerState.Ready"/> or <see cref="PlayerState.Paused"/> state.
393 /// It has no effect if the player is already in the <see cref="PlayerState.Playing"/> state.</para>
394 /// <para>Since Tizen 5.0, The player must be in the <see cref="PlayerState.Ready"/>, <see cref="PlayerState.Playing"/>,
395 /// or <see cref="PlayerState.Paused"/> state.<br/>
396 /// In case of HTTP streaming playback, the player could be internally paused for buffering.
397 /// If the application calls this function during the buffering, the playback will be resumed by force
398 /// and the buffering message posting by <see cref="BufferingProgressChanged"/> will be stopped.<br/>
399 /// In other cases, the player will keep playing without returning error.</para>
401 /// <exception cref="ObjectDisposedException">The player has already been disposed of.</exception>
402 /// <exception cref="InvalidOperationException">The player is not in the valid state.</exception>
403 /// <seealso cref="PrepareAsync"/>
404 /// <seealso cref="Stop"/>
405 /// <seealso cref="Pause"/>
406 /// <seealso cref="PlaybackCompleted"/>
407 /// <seealso cref="ApplyAudioStreamPolicy"/>
408 /// <seealso cref="BufferingProgressChanged"/>
409 /// <since_tizen> 3 </since_tizen>
410 public virtual void Start()
412 ValidatePlayerState(PlayerState.Ready, PlayerState.Paused, PlayerState.Playing);
414 NativePlayer.Start(Handle).ThrowIfFailed(this, "Failed to start the player");
418 /// Stops playing the media content.
421 /// The player must be in the <see cref="PlayerState.Playing"/> or <see cref="PlayerState.Paused"/> state.
422 /// It has no effect if the player is already in the <see cref="PlayerState.Ready"/> state.
424 /// <exception cref="ObjectDisposedException">The player has already been disposed of.</exception>
425 /// <exception cref="InvalidOperationException">The player is not in the valid state.</exception>
426 /// <seealso cref="Start"/>
427 /// <seealso cref="Pause"/>
428 /// <since_tizen> 3 </since_tizen>
429 public virtual void Stop()
431 if (State == PlayerState.Ready)
433 Log.Warn(PlayerLog.Tag, "ready state already");
436 ValidatePlayerState(PlayerState.Paused, PlayerState.Playing);
438 NativePlayer.Stop(Handle).ThrowIfFailed(this, "Failed to stop the player");
442 /// Pauses the player.
445 /// The player must be in the <see cref="PlayerState.Playing"/> state.
446 /// It has no effect if the player is already in the <see cref="PlayerState.Paused"/> state.
448 /// <exception cref="ObjectDisposedException">The player has already been disposed of.</exception>
449 /// <exception cref="InvalidOperationException">The player is not in the valid state.</exception>
450 /// <seealso cref="Start"/>
451 /// <since_tizen> 3 </since_tizen>
452 public virtual void Pause()
454 if (State == PlayerState.Paused)
456 Log.Warn(PlayerLog.Tag, "pause state already");
460 ValidatePlayerState(PlayerState.Playing);
462 NativePlayer.Pause(Handle).ThrowIfFailed(this, "Failed to pause the player");
465 private MediaSource _source;
468 /// Determines whether MediaSource has set.
469 /// This supports the product infrastructure and is not intended to be used directly from application code.
471 [EditorBrowsable(EditorBrowsableState.Never)]
472 protected bool HasSource => _source != null;
475 /// Sets a media source for the player.
477 /// <param name="source">A <see cref="MediaSource"/> that specifies the source for playback.</param>
478 /// <remarks>The player must be in the <see cref="PlayerState.Idle"/> state.</remarks>
479 /// <exception cref="ObjectDisposedException">The player has already been disposed of.</exception>
480 /// <exception cref="InvalidOperationException">
481 /// The player is not in the valid state.<br/>
483 /// It is not able to assign the source to the player.
485 /// <seealso cref="PrepareAsync"/>
486 /// <since_tizen> 3 </since_tizen>
487 public void SetSource(MediaSource source)
489 ValidatePlayerState(PlayerState.Idle);
493 source.AttachTo(this);
498 _source.DetachFrom(this);
505 /// Captures a video frame, asynchronously.
507 /// <returns>A task that represents the asynchronous capture operation.</returns>
508 /// <feature>http://tizen.org/feature/multimedia.raw_video</feature>
509 /// <remarks>The player must be in the <see cref="PlayerState.Playing"/> or <see cref="PlayerState.Paused"/> state.</remarks>
510 /// <exception cref="ObjectDisposedException">The player has already been disposed of.</exception>
511 /// <exception cref="InvalidOperationException">The player is not in the valid state.</exception>
512 /// <exception cref="NotSupportedException">The required feature is not supported.</exception>
513 /// <since_tizen> 3 </since_tizen>
514 public async Task<CapturedFrame> CaptureVideoAsync()
516 ValidationUtil.ValidateFeatureSupported(PlayerFeatures.RawVideo);
518 ValidatePlayerState(PlayerState.Playing, PlayerState.Paused);
520 TaskCompletionSource<CapturedFrame> t = new TaskCompletionSource<CapturedFrame>();
522 NativePlayer.VideoCaptureCallback cb = (data, width, height, size, _) =>
524 Debug.Assert(size <= int.MaxValue);
526 byte[] buf = new byte[size];
527 Marshal.Copy(data, buf, 0, (int)size);
529 t.TrySetResult(new CapturedFrame(buf, width, height));
532 using (var cbKeeper = ObjectKeeper.Get(cb))
534 NativePlayer.CaptureVideo(Handle, cb)
535 .ThrowIfFailed(this, "Failed to capture the video");
542 /// Gets the play position in milliseconds.
544 /// <returns>The current position in milliseconds.</returns>
545 /// <remarks>The player must be in the <see cref="PlayerState.Ready"/>, <see cref="PlayerState.Playing"/>,
546 /// or <see cref="PlayerState.Paused"/> state.</remarks>
547 /// <exception cref="ObjectDisposedException">The player has already been disposed of.</exception>
548 /// <exception cref="InvalidOperationException">The player is not in the valid state.</exception>
549 /// <seealso cref="SetPlayPositionAsync(int, bool)"/>
550 /// <seealso cref="SetPlayPositionNanosecondsAsync(long, bool)"/>
551 /// <seealso cref="GetPlayPositionNanoseconds"/>
552 /// <since_tizen> 3 </since_tizen>
553 public int GetPlayPosition()
555 ValidatePlayerState(PlayerState.Ready, PlayerState.Paused, PlayerState.Playing);
557 int playPosition = 0;
559 NativePlayer.GetPlayPosition(Handle, out playPosition).
560 ThrowIfFailed(this, "Failed to get the play position of the player");
562 Log.Info(PlayerLog.Tag, $"get play position : {playPosition}");
567 private void NativeSetPlayPosition(long position, bool accurate, bool nanoseconds,
568 NativePlayer.SeekCompletedCallback cb)
570 //Check if it is nanoseconds or milliseconds.
571 var ret = !nanoseconds ? NativePlayer.SetPlayPosition(Handle, (int)position, accurate, cb, IntPtr.Zero) :
572 NativePlayer.SetPlayPositionNanoseconds(Handle, position, accurate, cb, IntPtr.Zero);
574 //Note that we assume invalid param error is returned only when the position value is invalid.
575 if (ret == PlayerErrorCode.InvalidArgument)
577 throw new ArgumentOutOfRangeException(nameof(position), position,
578 "The position is not valid.");
580 if (ret != PlayerErrorCode.None)
582 Log.Error(PlayerLog.Tag, "Failed to set play position, " + (PlayerError)ret);
584 ret.ThrowIfFailed(this, "Failed to set play position");
587 private async Task SetPlayPosition(long position, bool accurate, bool nanoseconds)
589 var taskCompletionSource = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
591 bool immediateResult = _source is MediaStreamSource;
593 NativePlayer.SeekCompletedCallback cb = _ => taskCompletionSource.TrySetResult(true);
595 using (var cbKeeper = ObjectKeeper.Get(cb))
597 NativeSetPlayPosition(position, accurate, nanoseconds, immediateResult ? null : cb);
601 taskCompletionSource.TrySetResult(true);
603 await taskCompletionSource.Task;
608 /// Sets the seek position for playback, asynchronously.
610 /// <param name="position">The value indicating a desired position in milliseconds.</param>
611 /// <param name="accurate">The value indicating whether the operation performs with accuracy.</param>
612 /// <returns>A task that represents the asynchronous operation.</returns>
614 /// <para>The player must be in the <see cref="PlayerState.Ready"/>, <see cref="PlayerState.Playing"/>,
615 /// or <see cref="PlayerState.Paused"/> state.</para>
616 /// <para>If the <paramref name="accurate"/> is true, the play position will be adjusted as the specified <paramref name="position"/> value,
617 /// but this might be considerably slow. If false, the play position will be a nearest keyframe position.</para>
619 /// <exception cref="ObjectDisposedException">The player has already been disposed of.</exception>
620 /// <exception cref="InvalidOperationException">The player is not in the valid state.<br/>
622 /// In case of non-seekable content, the player will return error and keep playing without changing the play position.</exception>
623 /// <exception cref="ArgumentOutOfRangeException">The specified position is not valid.</exception>
624 /// <seealso cref="SetPlayPositionNanosecondsAsync(long, bool)"/>
625 /// <seealso cref="GetPlayPosition"/>
626 /// <seealso cref="GetPlayPositionNanoseconds"/>
627 /// <since_tizen> 3 </since_tizen>
628 public async Task SetPlayPositionAsync(int position, bool accurate)
630 ValidatePlayerState(PlayerState.Ready, PlayerState.Playing, PlayerState.Paused);
632 await SetPlayPosition(position, accurate, false);
636 /// Gets the play position in nanoseconds.
638 /// <returns>The current position in nanoseconds.</returns>
639 /// <remarks>The player must be in the <see cref="PlayerState.Ready"/>, <see cref="PlayerState.Playing"/>,
640 /// or <see cref="PlayerState.Paused"/> state.</remarks>
641 /// <exception cref="ObjectDisposedException">The player has already been disposed of.</exception>
642 /// <exception cref="InvalidOperationException">The player is not in the valid state.</exception>
643 /// <seealso cref="SetPlayPositionAsync(int, bool)"/>
644 /// <seealso cref="SetPlayPositionNanosecondsAsync(long, bool)"/>
645 /// <seealso cref="GetPlayPosition"/>
646 /// <since_tizen> 5 </since_tizen>
647 public long GetPlayPositionNanoseconds()
649 ValidatePlayerState(PlayerState.Ready, PlayerState.Paused, PlayerState.Playing);
651 NativePlayer.GetPlayPositionNanoseconds(Handle, out long playPosition).
652 ThrowIfFailed(this, "Failed to get the play position(nsec) of the player");
654 Log.Info(PlayerLog.Tag, $"get play position(nsec) : {playPosition}");
660 /// Sets the seek position in nanoseconds for playback, asynchronously.
662 /// <param name="position">The value indicating a desired position in nanoseconds.</param>
663 /// <param name="accurate">The value indicating whether the operation performs with accuracy.</param>
664 /// <returns>A task that represents the asynchronous operation.</returns>
666 /// <para>The player must be in the <see cref="PlayerState.Ready"/>, <see cref="PlayerState.Playing"/>,
667 /// or <see cref="PlayerState.Paused"/> state.</para>
668 /// <para>If the <paramref name="accurate"/> is true, the play position will be adjusted as the specified <paramref name="position"/> value,
669 /// but this might be considerably slow. If false, the play position will be a nearest keyframe position.</para>
671 /// <exception cref="ObjectDisposedException">The player has already been disposed of.</exception>
672 /// <exception cref="InvalidOperationException">The player is not in the valid state.<br/>
674 /// In case of non-seekable content, the player will return error and keep playing without changing the play position.</exception>
675 /// <exception cref="ArgumentOutOfRangeException">The specified position is not valid.</exception>
676 /// <seealso cref="SetPlayPositionAsync(int, bool)"/>
677 /// <seealso cref="GetPlayPosition"/>
678 /// <seealso cref="GetPlayPositionNanoseconds"/>
679 /// <since_tizen> 5 </since_tizen>
680 public async Task SetPlayPositionNanosecondsAsync(long position, bool accurate)
682 ValidatePlayerState(PlayerState.Ready, PlayerState.Playing, PlayerState.Paused);
684 await SetPlayPosition(position, accurate, true);
688 /// Sets the playback rate.
690 /// <param name="rate">The value for the playback rate. Valid range is -5.0 to 5.0, inclusive.</param>
692 /// <para>The player must be in the <see cref="PlayerState.Ready"/>, <see cref="PlayerState.Playing"/>,
693 /// or <see cref="PlayerState.Paused"/> state.</para>
694 /// <para>The sound will be muted, when the playback rate is under 0.0 or over 2.0.</para>
696 /// <exception cref="ObjectDisposedException">The player has already been disposed of.</exception>
697 /// <exception cref="InvalidOperationException">
698 /// The player is not in the valid state.<br/>
700 /// Streaming playback.
702 /// <exception cref="ArgumentOutOfRangeException">
703 /// <paramref name="rate"/> is less than -5.0.<br/>
705 /// <paramref name="rate"/> is greater than 5.0.<br/>
707 /// <paramref name="rate"/> is zero.
709 /// <since_tizen> 3 </since_tizen>
710 public void SetPlaybackRate(float rate)
712 if (rate < -5.0F || 5.0F < rate || rate == 0.0F)
714 throw new ArgumentOutOfRangeException(nameof(rate), rate, "Valid range is -5.0 to 5.0 (except 0.0)");
717 ValidatePlayerState(PlayerState.Ready, PlayerState.Playing, PlayerState.Paused);
719 NativePlayer.SetPlaybackRate(Handle, rate).ThrowIfFailed(this, "Failed to set the playback rate.");
723 /// Applies the audio stream policy.
725 /// <param name="policy">The <see cref="AudioStreamPolicy"/> to apply.</param>
727 /// The player must be in the <see cref="PlayerState.Idle"/> state.<br/>
729 /// <see cref="Player"/> does not support all <see cref="AudioStreamType"/>.<br/>
730 /// Supported types are <see cref="AudioStreamType.Media"/>, <see cref="AudioStreamType.System"/>,
731 /// <see cref="AudioStreamType.Alarm"/>, <see cref="AudioStreamType.Notification"/>,
732 /// <see cref="AudioStreamType.Emergency"/>, <see cref="AudioStreamType.VoiceInformation"/>,
733 /// <see cref="AudioStreamType.RingtoneVoip"/> and <see cref="AudioStreamType.MediaExternalOnly"/>.
735 /// <exception cref="ObjectDisposedException">
736 /// The player has already been disposed of.<br/>
738 /// <paramref name="policy"/> has already been disposed of.
740 /// <exception cref="InvalidOperationException">The player is not in the valid state.</exception>
741 /// <exception cref="ArgumentNullException"><paramref name="policy"/> is null.</exception>
742 /// <exception cref="NotSupportedException">
743 /// The required feature is not supported.<br/>
745 /// <see cref="AudioStreamType"/> of <paramref name="policy"/> is not supported on the current platform.
747 /// <seealso cref="AudioStreamPolicy"/>
748 /// <feature>http://tizen.org/feature/multimedia.player.stream_info</feature>
749 /// <since_tizen> 3 </since_tizen>
750 public void ApplyAudioStreamPolicy(AudioStreamPolicy policy)
752 ValidationUtil.ValidateFeatureSupported("http://tizen.org/feature/multimedia.player.stream_info");
756 throw new ArgumentNullException(nameof(policy));
759 ValidatePlayerState(PlayerState.Idle);
761 var ret = NativePlayer.SetAudioPolicyInfo(Handle, policy.Handle);
763 if (ret == PlayerErrorCode.InvalidArgument)
765 throw new NotSupportedException("The specified policy is not supported on the current system.");
768 ret.ThrowIfFailed(this, "Failed to set the audio stream policy to the player");
772 /// Set the relative ROI (Region Of Interest) area as a decimal fraction based on the video source.
773 /// It can be regarded as zooming operation because the specified video area will be rendered to fit to the display.
775 /// <param name="scaleRectangle">The containing the ROI area information.</param>
777 /// This function requires the ratio of the each coordinate and size to the video resolution size
778 /// to guarantee of showing the same area for the dynamic resolution video content.
779 /// This function have to be called after setting <see cref="Display"/>
781 /// <exception cref="ObjectDisposedException">The player has already been disposed of.</exception>
782 /// <exception cref="InvalidOperationException">
783 /// Operation failed; internal error.
785 /// The <see cref="PlayerDisplayType"/> is not set to <see cref="PlayerDisplayType.Overlay"/>.
787 /// <exception cref="ArgumentOutOfRangeException">
788 /// <paramref name="scaleRectangle.ScaleX"/> is less than 0.0 or greater than 1.0.<br/>
790 /// <paramref name="scaleRectangle.ScaleY"/> is less than 0.0 or greater than 1.0.<br/>
792 /// <paramref name="scaleRectangle.ScaleWidth"/> is less than or equal to 0.0 or greater than 1.0.<br/>
794 /// <paramref name="scaleRectangle.ScaleHeight"/> is less than or equal to 0.0 or greater than 1.0.
796 /// <seealso cref="ScaleRectangle"/>
797 /// <seealso cref="Display"/>
798 /// <seealso cref="StreamInfo.GetVideoProperties"/>
799 /// <seealso cref="GetVideoRoi"/>
800 /// <since_tizen> 5 </since_tizen>
801 public void SetVideoRoi(ScaleRectangle scaleRectangle)
803 ValidateNotDisposed();
805 if (scaleRectangle.ScaleX < 0 || scaleRectangle.ScaleX > 1)
807 throw new ArgumentOutOfRangeException(nameof(scaleRectangle.ScaleX), scaleRectangle.ScaleX, "Valid range is 0 to 1.0");
809 if (scaleRectangle.ScaleY < 0 || scaleRectangle.ScaleY > 1)
811 throw new ArgumentOutOfRangeException(nameof(scaleRectangle.ScaleY), scaleRectangle.ScaleY, "Valid range is 0 to 1.0");
813 if (scaleRectangle.ScaleWidth <= 0 || scaleRectangle.ScaleWidth > 1)
815 throw new ArgumentOutOfRangeException(nameof(scaleRectangle.ScaleWidth), scaleRectangle.ScaleWidth, "Valid range is 0 to 1.0 (except 0.0)");
817 if (scaleRectangle.ScaleHeight <= 0 || scaleRectangle.ScaleHeight > 1)
819 throw new ArgumentOutOfRangeException(nameof(scaleRectangle.ScaleHeight), scaleRectangle.ScaleHeight, "Valid range is 0 to 1.0 (except 0.0)");
822 NativePlayer.SetVideoRoi(Handle, scaleRectangle.ScaleX, scaleRectangle.ScaleY, scaleRectangle.ScaleWidth, scaleRectangle.ScaleHeight).ThrowIfFailed(this, "Failed to set the video roi area.");
826 /// Get the relative ROI (Region Of Interest) area as a decimal fraction based on the video source.
828 /// <returns>The <see cref="ScaleRectangle"/> containing the ROI area information.</returns>
829 /// <remarks>The specified ROI area is valid only in <see cref="PlayerDisplayType.Overlay"/>.</remarks>
830 /// <exception cref="ObjectDisposedException">The player has already been disposed of.</exception>
831 /// <exception cref="InvalidOperationException">
832 /// Operation failed; internal error.
834 /// <seealso cref="Display"/>
835 /// <seealso cref="StreamInfo.GetVideoProperties"/>
836 /// <seealso cref="SetVideoRoi"/>
837 /// <since_tizen> 5 </since_tizen>
838 public ScaleRectangle GetVideoRoi()
840 ValidateNotDisposed();
842 NativePlayer.GetVideoRoi(Handle, out var scaleX, out var scaleY,
843 out var scaleWidth, out var scaleHeight).ThrowIfFailed(this, "Failed to get the video roi area");
845 return new ScaleRectangle(scaleX, scaleY, scaleWidth, scaleHeight);
849 /// This supports the product infrastructure and is not intended to be used directly from application code.
851 [EditorBrowsable(EditorBrowsableState.Never)]
852 protected MediaPacket GetMediaPacket(IntPtr handle)
854 MediaPacket mediaPacket = handle != IntPtr.Zero ? MediaPacket.From(handle) :
855 throw new ArgumentException("MediaPacket handle is invalid.", nameof(handle));
861 #region Preparing state
863 private int _isPreparing;
865 private bool IsPreparing()
867 return Interlocked.CompareExchange(ref _isPreparing, 1, 1) == 1;
871 /// This supports the product infrastructure and is not intended to be used directly from application code.
873 [EditorBrowsable(EditorBrowsableState.Never)]
874 protected void SetPreparing()
876 Interlocked.Exchange(ref _isPreparing, 1);
880 /// This supports the product infrastructure and is not intended to be used directly from application code.
882 [EditorBrowsable(EditorBrowsableState.Never)]
883 protected void ClearPreparing()
885 Interlocked.Exchange(ref _isPreparing, 0);
890 /// Enable to decode an audio data for exporting PCM from a data.
892 /// <param name="format">The media format handle about required audio PCM specification.
893 /// The format has to include <see cref="AudioMediaFormat.MimeType"/>,
894 /// <see cref="AudioMediaFormat.Channel"/> and <see cref="AudioMediaFormat.SampleRate"/>.
895 /// If the format is NULL, the original PCM format or platform default PCM format will be applied.</param>
896 /// <param name="option">The audio extract option.</param>
897 /// <remarks><para>The player must be in the <see cref="PlayerState.Idle"/> state.</para>
898 /// <para>A <see cref="AudioDataDecoded"/> event is called in a separate thread(not in the main loop).</para>
899 /// <para>The audio PCM data can be retrieved using a <see cref="AudioDataDecoded"/> event as a media packet
900 /// and it is available until it's destroyed by <see cref="MediaPacket.Dispose()"/>.
901 /// The packet has to be destroyed as quickly as possible after rendering the data
902 /// and all the packets have to be destroyed before <see cref="Unprepare"/> is called.</para></remarks>
903 /// <exception cref="ObjectDisposedException">The player has already been disposed of.</exception>
904 /// <exception cref="ArgumentException">The value is not valid.</exception>
905 /// <exception cref="InvalidOperationException">
906 /// Operation failed; internal error.
908 /// The player is not in the valid state.
910 /// <seealso cref="PlayerAudioExtractOption"/>
911 /// <seealso cref="DisableExportingAudioData"/>
912 /// <since_tizen> 6 </since_tizen>
913 public void EnableExportingAudioData(AudioMediaFormat format, PlayerAudioExtractOption option)
915 ValidatePlayerState(PlayerState.Idle);
916 ValidationUtil.ValidateEnum(typeof(PlayerAudioExtractOption), option, nameof(option));
918 IntPtr formatHandle = IntPtr.Zero;
920 _audioFrameDecodedCallback = (IntPtr packetHandle, IntPtr userData) =>
922 var handler = AudioDataDecoded;
925 Log.Debug(PlayerLog.Tag, "packet : " + packetHandle.ToString());
927 new AudioDataDecodedEventArgs(MediaPacket.From(packetHandle)));
931 MediaPacket.From(packetHandle).Dispose();
935 formatHandle = format.AsNativeHandle();
937 NativePlayer.SetAudioFrameDecodedCb(Handle, formatHandle, option, _audioFrameDecodedCallback, IntPtr.Zero).
938 ThrowIfFailed(this, "Failed to register the _audioFrameDecoded");
942 /// Disable to decode an audio data.
944 /// <remarks>The player must be in the <see cref="PlayerState.Idle"/> or <see cref="PlayerState.Ready"/>
946 /// <exception cref="ObjectDisposedException">The player has already been disposed of.</exception>
947 /// <exception cref="InvalidOperationException">The player is not in the valid state.</exception>
948 /// <seealso cref="EnableExportingAudioData"/>
949 /// <since_tizen> 6 </since_tizen>
950 public void DisableExportingAudioData()
952 ValidatePlayerState(PlayerState.Idle, PlayerState.Ready);
954 NativePlayer.UnsetAudioFrameDecodedCb(Handle).
955 ThrowIfFailed(this, "Failed to unset the AudioFrameDecoded");
957 _audioFrameDecodedCallback = null;