[MediaController] Replace native api with new one (#609)
[platform/core/csapi/tizenfx.git] / src / Tizen.Multimedia.Remoting / MediaController / MediaControlServer.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 System;
18 using System.Collections.Generic;
19 using System.Threading.Tasks;
20 using Tizen.Applications;
21 using Native = Interop.MediaControllerServer;
22
23 namespace Tizen.Multimedia.Remoting
24 {
25     /// <summary>
26     /// Provides a means to set playback information and metadata and receive commands from clients.
27     /// </summary>
28     /// <seealso cref="MediaControllerManager"/>
29     /// <seealso cref="MediaController"/>
30     /// <since_tizen> 4 </since_tizen>
31     public static partial class MediaControlServer
32     {
33         private static IntPtr _handle = IntPtr.Zero;
34         private static bool? _isRunning;
35
36         /// <summary>
37         /// Gets a value indicating whether the server is running.
38         /// </summary>
39         /// <value>true if the server has started; otherwise, false.</value>
40         /// <seealso cref="Start"/>
41         /// <seealso cref="Stop"/>
42         /// <since_tizen> 4 </since_tizen>
43         public static bool IsRunning
44         {
45             get
46             {
47                 if (_isRunning.HasValue == false)
48                 {
49                     _isRunning = GetRunningState();
50                 }
51
52                 return _isRunning.Value;
53             }
54         }
55
56         private static bool GetRunningState()
57         {
58             IntPtr handle = IntPtr.Zero;
59             try
60             {
61                 Native.ConnectDb(out handle).ThrowIfError("Failed to retrieve the running state.");
62
63                 Native.CheckServerExist(handle, Applications.Application.Current.ApplicationInfo.ApplicationId,
64                     out var value).ThrowIfError("Failed to retrieve the running state.");
65
66                 return value;
67             }
68             finally
69             {
70                 if (handle != IntPtr.Zero)
71                 {
72                     Native.DisconnectDb(handle);
73                 }
74             }
75         }
76
77         private static void EnsureInitializedIfRunning()
78         {
79             if (_handle != IntPtr.Zero)
80             {
81                 return;
82             }
83
84             if (IsRunning == false)
85             {
86                 throw new InvalidOperationException("The server is not running.");
87             }
88
89             Initialize();
90         }
91
92         private static IntPtr Handle
93         {
94             get
95             {
96                 EnsureInitializedIfRunning();
97
98                 return _handle;
99             }
100         }
101
102         private static void Initialize()
103         {
104             Native.Create(out _handle).ThrowIfError("Failed to create media controller server.");
105
106             try
107             {
108                 RegisterPlaybackActionCommandReceivedEvent();
109                 RegisterPlaybackPositionCommandReceivedEvent();
110                 RegisterPlaylistCommandReceivedEvent();
111                 RegisterShuffleModeCommandReceivedEvent();
112                 RegisterRepeatModeCommandReceivedEvent();
113                 RegisterCustomCommandReceivedEvent();
114                 RegisterCommandCompletedEvent();
115                 RegisterSearchCommandReceivedEvent();
116
117                 _isRunning = true;
118             }
119             catch
120             {
121                 Native.Destroy(_handle);
122                 _playbackCommandCallback = null;
123                 _handle = IntPtr.Zero;
124                 throw;
125             }
126         }
127
128         /// <summary>
129         /// Starts the media control server.
130         /// </summary>
131         /// <remarks>
132         /// When the server starts, <see cref="MediaControllerManager.ServerStarted"/> will be raised.
133         /// </remarks>
134         /// <privilege>http://tizen.org/privilege/mediacontroller.server</privilege>
135         /// <exception cref="InvalidOperationException">An internal error occurs.</exception>
136         /// <exception cref="UnauthorizedAccessException">Caller does not have required privilege.</exception>
137         /// <seealso cref="MediaControllerManager.ServerStarted"/>
138         /// <since_tizen> 4 </since_tizen>
139         public static void Start()
140         {
141             Initialize();
142         }
143
144         /// <summary>
145         /// Stops the media control server.
146         /// </summary>
147         /// <remarks>
148         /// When the server stops, <see cref="MediaControllerManager.ServerStopped"/> will be raised.
149         /// </remarks>
150         /// <exception cref="InvalidOperationException">
151         ///     The server is not running .<br/>
152         ///     -or-<br/>
153         ///     An internal error occurs.
154         /// </exception>
155         /// <seealso cref="MediaControllerManager.ServerStopped"/>
156         /// <since_tizen> 4 </since_tizen>
157         public static void Stop()
158         {
159             EnsureInitializedIfRunning();
160
161             Native.Destroy(_handle).ThrowIfError("Failed to stop the server.");
162
163             _handle = IntPtr.Zero;
164             _playbackCommandCallback = null;
165             _isRunning = false;
166         }
167
168         /// <summary>
169         /// Updates playback state and playback position.</summary>
170         /// <param name="state">The playback state.</param>
171         /// <param name="position">The playback position in milliseconds.</param>
172         /// <exception cref="ArgumentException"><paramref name="state"/> is not valid.</exception>
173         /// <exception cref="ArgumentOutOfRangeException"><paramref name="position"/> is less than zero.</exception>
174         /// <exception cref="InvalidOperationException">
175         ///     The server is not running .<br/>
176         ///     -or-<br/>
177         ///     An internal error occurs.
178         /// </exception>
179         /// <since_tizen> 4 </since_tizen>
180         public static void SetPlaybackState(MediaControlPlaybackState state, long position)
181         {
182             ValidationUtil.ValidateEnum(typeof(MediaControlPlaybackState), state, nameof(state));
183
184             if (position < 0)
185             {
186                 throw new ArgumentOutOfRangeException(nameof(position), position, "position can't be less than zero.");
187             }
188
189             Native.SetPlaybackState(Handle, state.ToNative()).ThrowIfError("Failed to set playback state.");
190
191             Native.SetPlaybackPosition(Handle, (ulong)position).ThrowIfError("Failed to set playback position.");
192
193             Native.UpdatePlayback(Handle).ThrowIfError("Failed to set playback.");
194         }
195
196         private static void SetMetadata(MediaControllerNativeAttribute attribute, string value)
197         {
198             Native.SetMetadata(Handle, attribute, value).ThrowIfError($"Failed to set metadata({attribute}).");
199         }
200
201         /// <summary>
202         /// Updates metadata information.
203         /// </summary>
204         /// <param name="metadata">The metadata to update.</param>
205         /// <exception cref="ArgumentNullException"><paramref name="metadata"/> is null.</exception>
206         /// <exception cref="InvalidOperationException">
207         ///     The server is not running .<br/>
208         ///     -or-<br/>
209         ///     An internal error occurs.
210         /// </exception>
211         /// <since_tizen> 4 </since_tizen>
212         public static void SetMetadata(MediaControlMetadata metadata)
213         {
214             if (metadata == null)
215             {
216                 throw new ArgumentNullException(nameof(metadata));
217             }
218
219             SetMetadata(MediaControllerNativeAttribute.Title, metadata.Title);
220             SetMetadata(MediaControllerNativeAttribute.Artist, metadata.Artist);
221             SetMetadata(MediaControllerNativeAttribute.Album, metadata.Album);
222             SetMetadata(MediaControllerNativeAttribute.Author, metadata.Author);
223             SetMetadata(MediaControllerNativeAttribute.Genre, metadata.Genre);
224             SetMetadata(MediaControllerNativeAttribute.Duration, metadata.Duration);
225             SetMetadata(MediaControllerNativeAttribute.Date, metadata.Date);
226             SetMetadata(MediaControllerNativeAttribute.Copyright, metadata.Copyright);
227             SetMetadata(MediaControllerNativeAttribute.Description, metadata.Description);
228             SetMetadata(MediaControllerNativeAttribute.TrackNumber, metadata.TrackNumber);
229             SetMetadata(MediaControllerNativeAttribute.Picture, metadata.AlbumArtPath);
230
231             Native.UpdateMetadata(Handle).ThrowIfError("Failed to set metadata.");
232         }
233
234         /// <summary>
235         /// Updates the shuffle mode.
236         /// </summary>
237         /// <param name="enabled">A value indicating whether the shuffle mode is enabled.</param>
238         /// <exception cref="InvalidOperationException">
239         ///     The server is not running .<br/>
240         ///     -or-<br/>
241         ///     An internal error occurs.
242         /// </exception>
243         /// <since_tizen> 4 </since_tizen>
244         public static void SetShuffleModeEnabled(bool enabled)
245         {
246             Native.UpdateShuffleMode(Handle, enabled ? MediaControllerNativeShuffleMode.On : MediaControllerNativeShuffleMode.Off).
247                 ThrowIfError("Failed to set shuffle mode.");
248         }
249
250         /// <summary>
251         /// Updates the repeat mode.
252         /// </summary>
253         /// <param name="mode">A value indicating the repeat mode.</param>
254         /// <exception cref="InvalidOperationException">
255         ///     The server is not running .<br/>
256         ///     -or-<br/>
257         ///     An internal error occurs.
258         /// </exception>
259         /// <exception cref="ArgumentException"><paramref name="mode"/> is invalid.</exception>
260         /// <since_tizen> 4 </since_tizen>
261         public static void SetRepeatMode(MediaControlRepeatMode mode)
262         {
263             ValidationUtil.ValidateEnum(typeof(MediaControlRepeatMode), mode, nameof(mode));
264
265             Native.UpdateRepeatMode(Handle, mode.ToNative()).ThrowIfError("Failed to set repeat mode.");
266         }
267
268         /// <summary>
269         /// Sets the index of current playing media.
270         /// </summary>
271         /// <param name="index">The index of current playing media.</param>
272         /// <exception cref="ArgumentNullException"><paramref name="index"/> is null.</exception>
273         /// <exception cref="InvalidOperationException">
274         ///     The server is not running .<br/>
275         ///     -or-<br/>
276         ///     An internal error occurs.
277         /// </exception>
278         /// <since_tizen> 5 </since_tizen>
279         [Obsolete("Please do not use! This will be deprecated. Please use SetInfoOfCurrentPlayingMedia instead.")]
280         public static void SetIndexOfCurrentPlayingMedia(string index)
281         {
282             if (index == null)
283             {
284                 throw new ArgumentNullException(nameof(index));
285             }
286
287             Native.SetIndexOfCurrentPlayingMedia(Handle, index)
288                 .ThrowIfError("Failed to set the index of current playing media");
289
290             Native.UpdatePlayback(Handle).ThrowIfError("Failed to set playback.");
291         }
292
293         /// <summary>
294         /// Sets the playlist name and index of current playing media.
295         /// </summary>
296         /// <param name="playlistName">The playlist name of current playing media.</param>
297         /// <param name="index">The index of current playing media.</param>
298         /// <exception cref="ArgumentNullException">
299         /// <paramref name="playlistName"/> or <paramref name="index"/> is null.
300         /// </exception>
301         /// <exception cref="InvalidOperationException">
302         ///     The server is not running .<br/>
303         ///     -or-<br/>
304         ///     An internal error occurs.
305         /// </exception>
306         /// <since_tizen> 5 </since_tizen>
307         public static void SetInfoOfCurrentPlayingMedia(string playlistName, string index)
308         {
309             if (playlistName == null)
310             {
311                 throw new ArgumentNullException(nameof(playlistName));
312             }
313             if (index == null)
314             {
315                 throw new ArgumentNullException(nameof(index));
316             }
317
318             Native.SetInfoOfCurrentPlayingMedia(Handle, playlistName, index)
319                 .ThrowIfError("Failed to set the playlist name and index of current playing media");
320
321             Native.UpdatePlayback(Handle).ThrowIfError("Failed to set playback.");
322         }
323
324         /// <summary>
325         /// Delete playlist.
326         /// </summary>
327         /// <param name="playlist">The name of playlist.</param>
328         /// <exception cref="ArgumentNullException"><paramref name="playlist"/> is null.</exception>
329         /// <exception cref="InvalidOperationException">
330         ///     The server is not running .<br/>
331         ///     -or-<br/>
332         ///     An internal error occurs.
333         /// </exception>
334         /// <since_tizen> 5 </since_tizen>
335         public static void RemovePlaylist(MediaControlPlaylist playlist)
336         {
337             if (playlist == null)
338             {
339                 throw new ArgumentNullException(nameof(playlist));
340             }
341
342             Native.DeletePlaylist(Handle, playlist.Handle);
343             playlist.Dispose();
344         }
345
346         // Saves the playlist to the persistent storage.
347         internal static void SavePlaylist(IntPtr playlistHandle)
348         {
349             Native.SavePlaylist(Handle, playlistHandle).ThrowIfError("Failed to save playlist");
350         }
351
352         // Gets the playlist handle by name.
353         internal static IntPtr GetPlaylistHandle(string name)
354         {
355             Native.GetPlaylistHandle(Handle, name, out IntPtr playlistHandle)
356                 .ThrowIfError("Failed to get playlist handle by name");
357
358             return playlistHandle;
359         }
360
361         /// <summary>
362         /// Gets the active clients.
363         /// </summary>
364         /// <exception cref="InvalidOperationException">
365         ///     The server is not running .<br/>
366         ///     -or-<br/>
367         ///     An internal error occurs.
368         /// </exception>
369         /// <returns>the activated client ids.</returns>
370         /// <since_tizen> 5 </since_tizen>
371         public static IEnumerable<string> GetActivatedClients()
372         {
373             var clientIds = new List<string>();
374
375             Native.ActivatedClientCallback activatedClientCallback = (name, _) =>
376             {
377                 clientIds.Add(name);
378                 return true;
379             };
380
381             Native.ForeachActivatedClient(Handle, activatedClientCallback).
382                 ThrowIfError("Failed to get activated client.");
383
384             return clientIds.AsReadOnly();
385         }
386
387         /// <summary>
388         /// Requests commands to the client.
389         /// </summary>
390         /// <remarks>
391         /// The client can request the command to execute <see cref="Command"/>, <br/>
392         /// and then, the server receive the result of each request(command).
393         /// </remarks>
394         /// <param name="command">A <see cref="Command"/> class.</param>
395         /// <param name="clientId">The client Id to send command.</param>
396         /// <returns><see cref="Bundle"/> represents the extra data from client and it can be null.</returns>
397         /// <exception cref="ArgumentNullException">
398         /// <paramref name="command"/> or <paramref name="clientId"/> is null.
399         /// </exception>
400         /// <exception cref="InvalidOperationException">
401         ///     The server has already been stopped.<br/>
402         ///     -or-<br/>
403         ///     An internal error occurs.
404         /// </exception>
405         /// <since_tizen> 5 </since_tizen>
406         public static async Task<Bundle> RequestAsync(Command command, string clientId)
407         {
408             if (command == null)
409             {
410                 throw new ArgumentNullException(nameof(command));
411             }
412             if (clientId == null)
413             {
414                 throw new ArgumentNullException(nameof(clientId));
415             }
416
417             command.SetRequestInformation(clientId);
418
419             var tcs = new TaskCompletionSource<MediaControllerError>();
420             string reqeustId = null;
421             Bundle bundle = null;
422
423             EventHandler<CommandCompletedEventArgs> eventHandler = (s, e) =>
424             {
425                 if (e.RequestId == reqeustId)
426                 {
427                     bundle = e.Bundle;
428                     tcs.TrySetResult(e.Result);
429                 }
430             };
431
432             try
433             {
434                 CommandCompleted += eventHandler;
435
436                 reqeustId = command.Request(Handle);
437
438                 (await tcs.Task).ThrowIfError("Failed to request event.");
439
440                 return bundle;
441             }
442             finally
443             {
444                 CommandCompleted -= eventHandler;
445             }
446         }
447
448         /// <summary>
449         /// Sends the result of each command.
450         /// </summary>
451         /// <param name="command">The command that return to client.</param>
452         /// <param name="result">The result of <paramref name="command"/>.</param>
453         /// <param name="bundle">The extra data.</param>
454         /// <exception cref="ArgumentNullException"><paramref name="command"/> is null.</exception>
455         /// <exception cref="InvalidOperationException">
456         ///     The server is not running .<br/>
457         ///     -or-<br/>
458         ///     An internal error occurs.
459         /// </exception>
460         /// <since_tizen> 5 </since_tizen>
461         public static void Response(Command command, int result, Bundle bundle)
462         {
463             if (command == null)
464             {
465                 throw new ArgumentNullException(nameof(command));
466             }
467
468             command.Response(Handle, result, bundle);
469         }
470
471         /// <summary>
472         /// Sends the result of each command.
473         /// </summary>
474         /// <param name="command">The command that return to client.</param>
475         /// <param name="result">The result of <paramref name="command"/>.</param>
476         /// <exception cref="ArgumentNullException"><paramref name="command"/> is null.</exception>
477         /// <exception cref="InvalidOperationException">
478         ///     The server is not running .<br/>
479         ///     -or-<br/>
480         ///     An internal error occurs.
481         /// </exception>
482         /// <since_tizen> 5 </since_tizen>
483         public static void Response(Command command, int result)
484         {
485             if (command == null)
486             {
487                 throw new ArgumentNullException(nameof(command));
488             }
489
490             command.Response(Handle, result, null);
491         }
492
493         #region Capabilities
494         /// <summary>
495         /// Sets the content type of latest played media.
496         /// </summary>
497         /// <param name="type">A value indicating the content type of the latest played media.</param>
498         /// <exception cref="InvalidOperationException">
499         ///     The server is not running .<br/>
500         ///     -or-<br/>
501         ///     An internal error occurs.
502         /// </exception>
503         /// <exception cref="ArgumentException"><paramref name="type"/> is invalid.</exception>
504         /// <since_tizen> 5 </since_tizen>
505         public static void SetPlaybackContentType(MediaControlContentType type)
506         {
507             ValidationUtil.ValidateEnum(typeof(MediaControlContentType), type, nameof(type));
508
509             Native.SetPlaybackContentType(Handle, type).ThrowIfError("Failed to set playback content type.");
510
511             Native.UpdatePlayback(Handle).ThrowIfError("Failed to set playback.");
512         }
513
514         /// <summary>
515         /// Sets the path of icon.
516         /// </summary>
517         /// <param name="path">The path of icon.</param>
518         /// <exception cref="InvalidOperationException">
519         ///     The server is not running .<br/>
520         ///     -or-<br/>
521         ///     An internal error occurs.
522         /// </exception>
523         /// <exception cref="ArgumentNullException"><paramref name="path"/> is invalid.</exception>
524         /// <since_tizen> 5 </since_tizen>
525         public static void SetIconPath(string path)
526         {
527             if (path == null)
528             {
529                 throw new ArgumentNullException(nameof(path));
530             }
531
532             Native.SetIconPath(Handle, path).ThrowIfError("Failed to set uri path.");
533         }
534
535         /// <summary>
536         /// Sets the capabilities by <see cref="MediaControlPlaybackCommand"/>.
537         /// </summary>
538         /// <param name="capabilities">The set of <see cref="MediaControlPlaybackCommand"/> and <see cref="MediaControlCapabilitySupport"/>.</param>
539         /// <exception cref="InvalidOperationException">
540         ///     The server is not running .<br/>
541         ///     -or-<br/>
542         ///     An internal error occurs.
543         /// </exception>
544         /// <exception cref="ArgumentException"><paramref name="capabilities"/> is invalid.</exception>
545         /// <since_tizen> 5 </since_tizen>
546         public static void SetPlaybackCapabilities(Dictionary<MediaControlPlaybackCommand, MediaControlCapabilitySupport> capabilities)
547         {
548             foreach (var pair in capabilities)
549             {
550                 ValidationUtil.ValidateEnum(typeof(MediaControlPlaybackCommand), pair.Key, nameof(pair.Key));
551                 ValidationUtil.ValidateEnum(typeof(MediaControlCapabilitySupport), pair.Value, nameof(pair.Value));
552
553                 SetPlaybackCapability(pair.Key, pair.Value);
554                 Native.SetPlaybackCapability(Handle, pair.Key.ToNative(), pair.Value).
555                     ThrowIfError("Failed to set playback capability.");
556             }
557
558             Native.SaveAndNotifyPlaybackCapabilityUpdated(Handle).ThrowIfError("Failed to update playback capability.");
559         }
560
561         /// <summary>
562         /// Sets the capabilities by <see cref="MediaControlPlaybackCommand"/>.
563         /// </summary>
564         /// <param name="action">A playback command.</param>
565         /// <param name="support">A value indicating whether the <paramref name="action"/> is supported or not.</param>
566         /// <exception cref="InvalidOperationException">
567         ///     The server is not running .<br/>
568         ///     -or-<br/>
569         ///     An internal error occurs.
570         /// </exception>
571         /// <exception cref="ArgumentException"><paramref name="action"/> or <paramref name="support"/> is invalid.</exception>
572         /// <since_tizen> 5 </since_tizen>
573         public static void SetPlaybackCapability(MediaControlPlaybackCommand action, MediaControlCapabilitySupport support)
574         {
575             ValidationUtil.ValidateEnum(typeof(MediaControlPlaybackCommand), action, nameof(action));
576             ValidationUtil.ValidateEnum(typeof(MediaControlCapabilitySupport), support, nameof(support));
577
578             Native.SetPlaybackCapability(Handle, action.ToNative(), support).ThrowIfError("Failed to set playback capability.");
579
580             Native.SaveAndNotifyPlaybackCapabilityUpdated(Handle).ThrowIfError("Failed to update playback capability.");
581         }
582
583         /// <summary>
584         /// Sets the <see cref="MediaControlCapabilitySupport"/> indicating shuffle mode is supported or not.
585         /// </summary>
586         /// <param name="support">A value indicating whether the shuffle mode is supported or not.</param>
587         /// <exception cref="InvalidOperationException">
588         ///     The server is not running .<br/>
589         ///     -or-<br/>
590         ///     An internal error occurs.
591         /// </exception>
592         /// <exception cref="ArgumentException"><paramref name="support"/> is invalid.</exception>
593         /// <since_tizen> 5 </since_tizen>
594         public static void SetShuffleModeCapability(MediaControlCapabilitySupport support)
595         {
596             ValidationUtil.ValidateEnum(typeof(MediaControlCapabilitySupport), support, nameof(support));
597
598             Native.SetShuffleModeCapability(Handle, support).ThrowIfError("Failed to set shuffle mode capability.");
599         }
600
601         /// <summary>
602         /// Sets the content type of latest played media.
603         /// </summary>
604         /// <param name="support">A value indicating whether the <see cref="MediaControlRepeatMode"/> is supported or not.</param>
605         /// <exception cref="InvalidOperationException">
606         ///     The server is not running .<br/>
607         ///     -or-<br/>
608         ///     An internal error occurs.
609         /// </exception>
610         /// <exception cref="ArgumentException"><paramref name="support"/> is invalid.</exception>
611         /// <since_tizen> 5 </since_tizen>
612         public static void SetRepeatModeCapability(MediaControlCapabilitySupport support)
613         {
614             ValidationUtil.ValidateEnum(typeof(MediaControlCapabilitySupport), support, nameof(support));
615
616             Native.SetRepeatModeCapability(Handle, support).ThrowIfError("Failed to set shuffle mode capability.");
617         }
618         #endregion Capabilities
619
620         /// <summary>
621         /// Sets the age rating of latest played media.
622         /// </summary>
623         /// <param name="ageRating">
624         /// The Age rating of latest played media. The valid range is 0 to 19, inclusive.
625         /// Especially, 0 means that media is suitable for all ages.
626         /// </param>
627         /// <exception cref="ArgumentOutOfRangeException">The specified <paramref name="ageRating"/> is not valid.</exception>
628         /// <exception cref="InvalidOperationException">
629         ///     The server is not running .<br/>
630         ///     -or-<br/>
631         ///     An internal error occurs.
632         /// </exception>
633         /// <since_tizen> 5 </since_tizen>
634         public static void SetAgeRating(int ageRating)
635         {
636             if (ageRating < 0 || ageRating > 19)
637             {
638                 throw new ArgumentOutOfRangeException(nameof(ageRating));
639             }
640
641             Native.SetAgeRating(Handle, ageRating).ThrowIfError("Failed to set age rating.");
642
643             Native.UpdatePlayback(Handle).ThrowIfError("Failed to set playback.");
644         }
645     }
646 }