10f939ace453ef6aac878ac262e8fbe1d08bea63
[platform/core/csapi/tizenfx.git] / src / Tizen.Multimedia.MediaPlayer / Player / Player.cs
1 /*
2  * Copyright (c) 2018 Samsung Electronics Co., Ltd All Rights Reserved
3  *
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
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 using static Interop;
18 using System;
19 using System.ComponentModel;
20 using System.Diagnostics;
21 using System.IO;
22 using System.Runtime.InteropServices;
23 using System.Threading;
24 using System.Threading.Tasks;
25
26 namespace Tizen.Multimedia
27 {
28     internal static class PlayerLog
29     {
30         internal const string Tag = "Tizen.Multimedia.Player";
31     }
32
33     /// <summary>
34     /// Provides the ability to control media playback.
35     /// </summary>
36     /// <remarks>
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.
40     /// </remarks>
41     public partial class Player : IDisposable, IDisplayable<PlayerErrorCode>
42     {
43         private readonly PlayerHandle _handle;
44
45         /// <summary>
46         /// Initializes a new instance of the <see cref="Player"/> class.
47         /// </summary>
48         /// <since_tizen> 3 </since_tizen>
49         public Player()
50         {
51             NativePlayer.Create(out _handle).ThrowIfFailed(null, "Failed to create player");
52
53             Debug.Assert(_handle != null);
54
55             Initialize();
56         }
57
58         /// <summary>
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.
62         /// </summary>
63         /// <param name="handle">The handle for the media player.</param>
64         /// <param name="errorHandler">The handle for occuring error.</param>
65         /// <remarks>
66         /// This supports the product infrastructure and is not intended to be used directly from application code.
67         /// </remarks>
68         [EditorBrowsable(EditorBrowsableState.Never)]
69         protected Player(IntPtr handle, Action<int, string> errorHandler)
70         {
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));
75
76             _errorHandler = errorHandler;
77         }
78
79         private bool _initialized;
80
81         /// <summary>
82         /// This supports the product infrastructure and is not intended to be used directly from application code.
83         /// </summary>
84         [EditorBrowsable(EditorBrowsableState.Never)]
85         protected void Initialize()
86         {
87             if (_initialized)
88             {
89                 throw new InvalidOperationException("It has already been initialized.");
90             }
91
92             if (Features.IsSupported(PlayerFeatures.AudioEffect))
93             {
94                 _audioEffect = new AudioEffect(this);
95             }
96
97             if (Features.IsSupported(PlayerFeatures.RawVideo))
98             {
99                 RegisterVideoFrameDecodedCallback();
100             }
101
102             RegisterEvents();
103
104             _displaySettings = PlayerDisplaySettings.Create(this);
105
106             _initialized = true;
107         }
108
109         internal void ValidatePlayerState(params PlayerState[] desiredStates)
110         {
111             Debug.Assert(desiredStates.Length > 0);
112
113             ValidateNotDisposed();
114
115             var curState = State;
116             if (curState.IsAnyOf(desiredStates))
117             {
118                 return;
119             }
120
121             throw new InvalidOperationException($"The player is not in a valid state. " +
122                 $"Current State : { curState }, Valid State : { string.Join(", ", desiredStates) }.");
123         }
124
125         #region Dispose support
126         private bool _disposed;
127
128         /// <summary>
129         /// Releases all resources used by the current instance.
130         /// </summary>
131         /// <since_tizen> 3 </since_tizen>
132         public void Dispose()
133         {
134             Dispose(true);
135             GC.SuppressFinalize(this);
136         }
137
138         /// <summary>
139         /// Releases the unmanaged resources used by the <see cref="Player"/>.
140         /// </summary>
141         /// <param name="disposing">
142         /// true to release both managed and unmanaged resources; false to release only unmanaged resources.
143         /// </param>
144         [EditorBrowsable(EditorBrowsableState.Never)]
145         protected virtual void Dispose(bool disposing)
146         {
147             if (_disposed)
148             {
149                 return;
150             }
151
152             if (disposing)
153             {
154                 ReplaceDisplay(null);
155
156                 if (_source != null)
157                 {
158                     try
159                     {
160                         _source.DetachFrom(this);
161                         _source = null;
162                     }
163                     catch (Exception e)
164                     {
165                         Log.Error(PlayerLog.Tag, e.ToString());
166                     }
167                 }
168
169                 if (_handle != null)
170                 {
171                     _handle.Dispose();
172                     _disposed = true;
173                 }
174             }
175         }
176
177         internal void ValidateNotDisposed()
178         {
179             if (_disposed)
180             {
181                 Log.Warn(PlayerLog.Tag, "player was disposed");
182                 throw new ObjectDisposedException(nameof(Player));
183             }
184         }
185
186         internal bool IsDisposed => _disposed;
187         #endregion
188
189         #region Methods
190
191         /// <summary>
192         /// Gets the streaming download progress.
193         /// </summary>
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/>
199         ///     -or-<br/>
200         ///     The player is not in the valid state.
201         ///     </exception>
202         /// <exception cref="ObjectDisposedException">The player has already been disposed of.</exception>
203         /// <since_tizen> 3 </since_tizen>
204         public DownloadProgress GetDownloadProgress()
205         {
206             ValidatePlayerState(PlayerState.Ready, PlayerState.Playing, PlayerState.Paused);
207
208             int start = 0;
209             int current = 0;
210             NativePlayer.GetStreamingDownloadProgress(Handle, out start, out current).
211                 ThrowIfFailed(this, "Failed to get download progress");
212
213             Log.Info(PlayerLog.Tag, $"get download progress : {start}, {current}");
214
215             return new DownloadProgress(start, current);
216         }
217
218         /// <summary>
219         /// Sets the subtitle path for playback.
220         /// </summary>
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>
225         /// </remarks>
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)
232         {
233             ValidateNotDisposed();
234
235             if (path == null)
236             {
237                 throw new ArgumentNullException(nameof(path));
238             }
239
240             if (path.Length == 0)
241             {
242                 throw new ArgumentException("The path is empty.", nameof(path));
243             }
244
245             if (!File.Exists(path))
246             {
247                 throw new FileNotFoundException($"The specified file does not exist.", path);
248             }
249
250             NativePlayer.SetSubtitlePath(Handle, path).
251                 ThrowIfFailed(this, "Failed to set the subtitle path to the player");
252         }
253
254         /// <summary>
255         /// Removes the subtitle path.
256         /// </summary>
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()
262         {
263             ValidatePlayerState(PlayerState.Idle);
264
265             NativePlayer.SetSubtitlePath(Handle, null).
266                 ThrowIfFailed(this, "Failed to clear the subtitle of the player");
267         }
268
269         /// <summary>
270         /// Sets the offset for the subtitle.
271         /// </summary>
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/>
277         ///     -or-<br/>
278         ///     No subtitle is set.
279         /// </exception>
280         /// <seealso cref="SetSubtitle(string)"/>
281         /// <since_tizen> 3 </since_tizen>
282         public void SetSubtitleOffset(int offset)
283         {
284             ValidatePlayerState(PlayerState.Playing, PlayerState.Paused);
285
286             var err = NativePlayer.SetSubtitlePositionOffset(Handle, offset);
287
288             if (err == PlayerErrorCode.FeatureNotSupported)
289             {
290                 throw new InvalidOperationException("No subtitle set");
291             }
292
293             err.ThrowIfFailed(this, "Failed to the subtitle offset of the player");
294         }
295
296         private void Prepare()
297         {
298             NativePlayer.Prepare(Handle).ThrowIfFailed(this, "Failed to prepare the player");
299         }
300
301         /// <summary>
302         /// Called when the <see cref="Prepare"/> is invoked.
303         /// </summary>
304         /// <since_tizen> 3 </since_tizen>
305         protected virtual void OnPreparing()
306         {
307         }
308
309         /// <summary>
310         /// Prepares the media player for playback, asynchronously.
311         /// </summary>
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()
321         {
322             if (_source == null)
323             {
324                 throw new InvalidOperationException("No source is set.");
325             }
326
327             ValidatePlayerState(PlayerState.Idle);
328
329             OnPreparing();
330
331             SetPreparing();
332
333             return Task.Factory.StartNew(() =>
334             {
335                 try
336                 {
337                     Prepare();
338                 }
339                 finally
340                 {
341                     ClearPreparing();
342                 }
343             }, CancellationToken.None,
344                 TaskCreationOptions.DenyChildAttach | TaskCreationOptions.LongRunning,
345                 TaskScheduler.Default);
346         }
347
348         /// <summary>
349         /// Unprepares the player.
350         /// </summary>
351         /// <remarks>
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.
354         ///     <para>
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.
357         ///     </para>
358         /// </remarks>
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()
363         {
364             if (State == PlayerState.Idle)
365             {
366                 Log.Warn(PlayerLog.Tag, "idle state already");
367                 return;
368             }
369             ValidatePlayerState(PlayerState.Ready, PlayerState.Paused, PlayerState.Playing);
370
371             NativePlayer.Unprepare(Handle).ThrowIfFailed(this, "Failed to unprepare the player");
372
373             OnUnprepared();
374         }
375
376         /// <summary>
377         /// Called after the <see cref="Player"/> is unprepared.
378         /// </summary>
379         /// <seealso cref="Unprepare"/>
380         /// <since_tizen> 3 </since_tizen>
381         protected virtual void OnUnprepared()
382         {
383             _source?.DetachFrom(this);
384             _source = null;
385         }
386
387         /// <summary>
388         /// Starts or resumes playback.
389         /// </summary>
390         /// <remarks>
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>
400         /// </remarks>
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()
411         {
412             ValidatePlayerState(PlayerState.Ready, PlayerState.Paused, PlayerState.Playing);
413
414             NativePlayer.Start(Handle).ThrowIfFailed(this, "Failed to start the player");
415         }
416
417         /// <summary>
418         /// Stops playing the media content.
419         /// </summary>
420         /// <remarks>
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.
423         /// </remarks>
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()
430         {
431             if (State == PlayerState.Ready)
432             {
433                 Log.Warn(PlayerLog.Tag, "ready state already");
434                 return;
435             }
436             ValidatePlayerState(PlayerState.Paused, PlayerState.Playing);
437
438             NativePlayer.Stop(Handle).ThrowIfFailed(this, "Failed to stop the player");
439         }
440
441         /// <summary>
442         /// Pauses the player.
443         /// </summary>
444         /// <remarks>
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.
447         /// </remarks>
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()
453         {
454             if (State == PlayerState.Paused)
455             {
456                 Log.Warn(PlayerLog.Tag, "pause state already");
457                 return;
458             }
459
460             ValidatePlayerState(PlayerState.Playing);
461
462             NativePlayer.Pause(Handle).ThrowIfFailed(this, "Failed to pause the player");
463         }
464
465         private MediaSource _source;
466
467         /// <summary>
468         /// Determines whether MediaSource has set.
469         /// This supports the product infrastructure and is not intended to be used directly from application code.
470         /// </summary>
471         [EditorBrowsable(EditorBrowsableState.Never)]
472         protected bool HasSource => _source != null;
473
474         /// <summary>
475         /// Sets a media source for the player.
476         /// </summary>
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/>
482         ///     -or-<br/>
483         ///     It is not able to assign the source to the player.
484         ///     </exception>
485         /// <seealso cref="PrepareAsync"/>
486         /// <since_tizen> 3 </since_tizen>
487         public void SetSource(MediaSource source)
488         {
489             ValidatePlayerState(PlayerState.Idle);
490
491             if (source != null)
492             {
493                 source.AttachTo(this);
494             }
495
496             if (_source != null)
497             {
498                 _source.DetachFrom(this);
499             }
500
501             _source = source;
502         }
503
504         /// <summary>
505         /// Captures a video frame, asynchronously.
506         /// </summary>
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()
515         {
516             ValidationUtil.ValidateFeatureSupported(PlayerFeatures.RawVideo);
517
518             ValidatePlayerState(PlayerState.Playing, PlayerState.Paused);
519
520             TaskCompletionSource<CapturedFrame> t = new TaskCompletionSource<CapturedFrame>();
521
522             NativePlayer.VideoCaptureCallback cb = (data, width, height, size, _) =>
523             {
524                 Debug.Assert(size <= int.MaxValue);
525
526                 byte[] buf = new byte[size];
527                 Marshal.Copy(data, buf, 0, (int)size);
528
529                 t.TrySetResult(new CapturedFrame(buf, width, height));
530             };
531
532             using (var cbKeeper = ObjectKeeper.Get(cb))
533             {
534                 NativePlayer.CaptureVideo(Handle, cb)
535                     .ThrowIfFailed(this, "Failed to capture the video");
536
537                 return await t.Task;
538             }
539         }
540
541         /// <summary>
542         /// Gets the play position in milliseconds.
543         /// </summary>
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()
554         {
555             ValidatePlayerState(PlayerState.Ready, PlayerState.Paused, PlayerState.Playing);
556
557             int playPosition = 0;
558
559             NativePlayer.GetPlayPosition(Handle, out playPosition).
560                 ThrowIfFailed(this, "Failed to get the play position of the player");
561
562             Log.Info(PlayerLog.Tag, $"get play position : {playPosition}");
563
564             return playPosition;
565         }
566
567         private void NativeSetPlayPosition(long position, bool accurate, bool nanoseconds,
568             NativePlayer.SeekCompletedCallback cb)
569         {
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);
573
574             //Note that we assume invalid param error is returned only when the position value is invalid.
575             if (ret == PlayerErrorCode.InvalidArgument)
576             {
577                 throw new ArgumentOutOfRangeException(nameof(position), position,
578                     "The position is not valid.");
579             }
580             if (ret != PlayerErrorCode.None)
581             {
582                 Log.Error(PlayerLog.Tag, "Failed to set play position, " + (PlayerError)ret);
583             }
584             ret.ThrowIfFailed(this, "Failed to set play position");
585         }
586
587         private async Task SetPlayPosition(long position, bool accurate, bool nanoseconds)
588         {
589             var taskCompletionSource = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
590
591             bool immediateResult = _source is MediaStreamSource;
592
593             NativePlayer.SeekCompletedCallback cb = _ => taskCompletionSource.TrySetResult(true);
594
595             using (var cbKeeper = ObjectKeeper.Get(cb))
596             {
597                 NativeSetPlayPosition(position, accurate, nanoseconds, immediateResult ? null : cb);
598
599                 if (immediateResult)
600                 {
601                     taskCompletionSource.TrySetResult(true);
602                 }
603                 await taskCompletionSource.Task;
604             }
605         }
606
607         /// <summary>
608         /// Sets the seek position for playback, asynchronously.
609         /// </summary>
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>
613         /// <remarks>
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>
618         ///     </remarks>
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/>
621         ///     -or-<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)
629         {
630             ValidatePlayerState(PlayerState.Ready, PlayerState.Playing, PlayerState.Paused);
631
632             await SetPlayPosition(position, accurate, false);
633         }
634
635         /// <summary>
636         /// Gets the play position in nanoseconds.
637         /// </summary>
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()
648         {
649             ValidatePlayerState(PlayerState.Ready, PlayerState.Paused, PlayerState.Playing);
650
651             NativePlayer.GetPlayPositionNanoseconds(Handle, out long playPosition).
652                 ThrowIfFailed(this, "Failed to get the play position(nsec) of the player");
653
654             Log.Info(PlayerLog.Tag, $"get play position(nsec) : {playPosition}");
655
656             return playPosition;
657         }
658
659         /// <summary>
660         /// Sets the seek position in nanoseconds for playback, asynchronously.
661         /// </summary>
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>
665         /// <remarks>
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>
670         ///     </remarks>
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/>
673         ///     -or-<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)
681         {
682             ValidatePlayerState(PlayerState.Ready, PlayerState.Playing, PlayerState.Paused);
683
684             await SetPlayPosition(position, accurate, true);
685         }
686
687         /// <summary>
688         /// Sets the playback rate.
689         /// </summary>
690         /// <param name="rate">The value for the playback rate. Valid range is -5.0 to 5.0, inclusive.</param>
691         /// <remarks>
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>
695         /// </remarks>
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/>
699         ///     -or-<br/>
700         ///     Streaming playback.
701         /// </exception>
702         /// <exception cref="ArgumentOutOfRangeException">
703         ///     <paramref name="rate"/> is less than -5.0.<br/>
704         ///     -or-<br/>
705         ///     <paramref name="rate"/> is greater than 5.0.<br/>
706         ///     -or-<br/>
707         ///     <paramref name="rate"/> is zero.
708         /// </exception>
709         /// <since_tizen> 3 </since_tizen>
710         public void SetPlaybackRate(float rate)
711         {
712             if (rate < -5.0F || 5.0F < rate || rate == 0.0F)
713             {
714                 throw new ArgumentOutOfRangeException(nameof(rate), rate, "Valid range is -5.0 to 5.0 (except 0.0)");
715             }
716
717             ValidatePlayerState(PlayerState.Ready, PlayerState.Playing, PlayerState.Paused);
718
719             NativePlayer.SetPlaybackRate(Handle, rate).ThrowIfFailed(this, "Failed to set the playback rate.");
720         }
721
722         /// <summary>
723         /// Applies the audio stream policy.
724         /// </summary>
725         /// <param name="policy">The <see cref="AudioStreamPolicy"/> to apply.</param>
726         /// <remarks>
727         /// The player must be in the <see cref="PlayerState.Idle"/> state.<br/>
728         /// <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"/>.
734         /// </remarks>
735         /// <exception cref="ObjectDisposedException">
736         ///     The player has already been disposed of.<br/>
737         ///     -or-<br/>
738         ///     <paramref name="policy"/> has already been disposed of.
739         /// </exception>
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/>
744         ///     -or-<br/>
745         ///     <see cref="AudioStreamType"/> of <paramref name="policy"/> is not supported on the current platform.
746         /// </exception>
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)
751         {
752             ValidationUtil.ValidateFeatureSupported("http://tizen.org/feature/multimedia.player.stream_info");
753
754             if (policy == null)
755             {
756                 throw new ArgumentNullException(nameof(policy));
757             }
758
759             ValidatePlayerState(PlayerState.Idle);
760
761             var ret = NativePlayer.SetAudioPolicyInfo(Handle, policy.Handle);
762
763             if (ret == PlayerErrorCode.InvalidArgument)
764             {
765                 throw new NotSupportedException("The specified policy is not supported on the current system.");
766             }
767
768             ret.ThrowIfFailed(this, "Failed to set the audio stream policy to the player");
769         }
770
771         /// <summary>
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.
774         /// </summary>
775         /// <param name="scaleRectangle">The containing the ROI area information.</param>
776         /// <remarks>
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"/>
780         /// </remarks>
781         /// <exception cref="ObjectDisposedException">The player has already been disposed of.</exception>
782         /// <exception cref="InvalidOperationException">
783         ///     Operation failed; internal error.
784         ///     -or-<br/>
785         ///     The <see cref="PlayerDisplayType"/> is not set to <see cref="PlayerDisplayType.Overlay"/>.
786         ///     </exception>
787         /// <exception cref="ArgumentOutOfRangeException">
788         ///     <paramref name="scaleRectangle.ScaleX"/> is less than 0.0 or greater than 1.0.<br/>
789         ///     -or-<br/>
790         ///     <paramref name="scaleRectangle.ScaleY"/> is less than 0.0 or greater than 1.0.<br/>
791         ///     -or-<br/>
792         ///     <paramref name="scaleRectangle.ScaleWidth"/> is less than or equal to 0.0 or greater than 1.0.<br/>
793         ///     -or-<br/>
794         ///     <paramref name="scaleRectangle.ScaleHeight"/> is less than or equal to 0.0 or greater than 1.0.
795         /// </exception>
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)
802         {
803             ValidateNotDisposed();
804
805             if (scaleRectangle.ScaleX < 0 || scaleRectangle.ScaleX > 1)
806             {
807                 throw new ArgumentOutOfRangeException(nameof(scaleRectangle.ScaleX), scaleRectangle.ScaleX, "Valid range is 0 to 1.0");
808             }
809             if (scaleRectangle.ScaleY < 0 || scaleRectangle.ScaleY > 1)
810             {
811                 throw new ArgumentOutOfRangeException(nameof(scaleRectangle.ScaleY), scaleRectangle.ScaleY, "Valid range is 0 to 1.0");
812             }
813             if (scaleRectangle.ScaleWidth <= 0 || scaleRectangle.ScaleWidth > 1)
814             {
815                 throw new ArgumentOutOfRangeException(nameof(scaleRectangle.ScaleWidth), scaleRectangle.ScaleWidth, "Valid range is 0 to 1.0 (except 0.0)");
816             }
817             if (scaleRectangle.ScaleHeight <= 0 || scaleRectangle.ScaleHeight > 1)
818             {
819                 throw new ArgumentOutOfRangeException(nameof(scaleRectangle.ScaleHeight), scaleRectangle.ScaleHeight, "Valid range is 0 to 1.0 (except 0.0)");
820             }
821
822             NativePlayer.SetVideoRoi(Handle, scaleRectangle.ScaleX, scaleRectangle.ScaleY, scaleRectangle.ScaleWidth, scaleRectangle.ScaleHeight).ThrowIfFailed(this, "Failed to set the video roi area.");
823         }
824
825         /// <summary>
826         /// Get the relative ROI (Region Of Interest) area as a decimal fraction based on the video source.
827         /// </summary>
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.
833         ///     </exception>
834         /// <seealso cref="Display"/>
835         /// <seealso cref="StreamInfo.GetVideoProperties"/>
836         /// <seealso cref="SetVideoRoi"/>
837         /// <since_tizen> 5 </since_tizen>
838         public ScaleRectangle GetVideoRoi()
839         {
840             ValidateNotDisposed();
841
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");
844
845             return new ScaleRectangle(scaleX, scaleY, scaleWidth, scaleHeight);
846         }
847
848         /// <summary>
849         /// This supports the product infrastructure and is not intended to be used directly from application code.
850         /// </summary>
851         [EditorBrowsable(EditorBrowsableState.Never)]
852         protected MediaPacket GetMediaPacket(IntPtr handle)
853         {
854             MediaPacket mediaPacket = handle != IntPtr.Zero ? MediaPacket.From(handle) :
855                 throw new ArgumentException("MediaPacket handle is invalid.", nameof(handle));
856
857             return mediaPacket;
858         }
859         #endregion
860
861         #region Preparing state
862
863         private int _isPreparing;
864
865         private bool IsPreparing()
866         {
867             return Interlocked.CompareExchange(ref _isPreparing, 1, 1) == 1;
868         }
869
870         /// <summary>
871         /// This supports the product infrastructure and is not intended to be used directly from application code.
872         /// </summary>
873         [EditorBrowsable(EditorBrowsableState.Never)]
874         protected void SetPreparing()
875         {
876             Interlocked.Exchange(ref _isPreparing, 1);
877         }
878
879         /// <summary>
880         /// This supports the product infrastructure and is not intended to be used directly from application code.
881         /// </summary>
882         [EditorBrowsable(EditorBrowsableState.Never)]
883         protected void ClearPreparing()
884         {
885             Interlocked.Exchange(ref _isPreparing, 0);
886         }
887         #endregion
888
889         /// <summary>
890         /// Enable to decode an audio data for exporting PCM from a data.
891         /// </summary>
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.
907         ///     -or-<br/>
908         ///     The player is not in the valid state.
909         ///     </exception>
910         /// <seealso cref="PlayerAudioExtractOption"/>
911         /// <seealso cref="DisableExportingAudioData"/>
912         /// <since_tizen> 6 </since_tizen>
913         public void EnableExportingAudioData(AudioMediaFormat format, PlayerAudioExtractOption option)
914         {
915             ValidatePlayerState(PlayerState.Idle);
916             ValidationUtil.ValidateEnum(typeof(PlayerAudioExtractOption), option, nameof(option));
917
918             IntPtr formatHandle = IntPtr.Zero;
919
920             _audioFrameDecodedCallback = (IntPtr packetHandle, IntPtr userData) =>
921             {
922                 var handler = AudioDataDecoded;
923                 if (handler != null)
924                 {
925                     Log.Debug(PlayerLog.Tag, "packet : " + packetHandle.ToString());
926                     handler.Invoke(this,
927                         new AudioDataDecodedEventArgs(MediaPacket.From(packetHandle)));
928                 }
929                 else
930                 {
931                     MediaPacket.From(packetHandle).Dispose();
932                 }
933             };
934
935             formatHandle = format.AsNativeHandle();
936
937             NativePlayer.SetAudioFrameDecodedCb(Handle, formatHandle, option, _audioFrameDecodedCallback, IntPtr.Zero).
938                 ThrowIfFailed(this, "Failed to register the _audioFrameDecoded");
939         }
940
941         /// <summary>
942         /// Disable to decode an audio data.
943         /// </summary>
944         /// <remarks>The player must be in the <see cref="PlayerState.Idle"/> or <see cref="PlayerState.Ready"/>
945         /// state.</remarks>
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()
951         {
952             ValidatePlayerState(PlayerState.Idle, PlayerState.Ready);
953
954             NativePlayer.UnsetAudioFrameDecodedCb(Handle).
955                 ThrowIfFailed(this, "Failed to unset the AudioFrameDecoded");
956
957             _audioFrameDecodedCallback = null;
958         }
959     }
960 }