2 * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
4 * Licensed under the Apache License, Version 2.0 (the License);
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an AS IS BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
18 using System.Collections.Generic;
19 using System.Threading.Tasks;
20 using Tizen.Applications;
21 using Native = Interop.MediaControllerServer;
23 namespace Tizen.Multimedia.Remoting
26 /// Provides a means to set playback information and metadata and receive commands from clients.
28 /// <seealso cref="MediaControllerManager"/>
29 /// <seealso cref="MediaController"/>
30 /// <since_tizen> 4 </since_tizen>
31 public static partial class MediaControlServer
33 private static IntPtr _handle = IntPtr.Zero;
34 private static bool? _isRunning;
37 /// Gets a value indicating whether the server is running.
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
47 if (_isRunning.HasValue == false)
49 _isRunning = GetRunningState();
52 return _isRunning.Value;
56 private static bool GetRunningState()
58 IntPtr handle = IntPtr.Zero;
61 Native.ConnectDb(out handle).ThrowIfError("Failed to retrieve the running state.");
63 Native.CheckServerExist(handle, Applications.Application.Current.ApplicationInfo.ApplicationId,
64 out var value).ThrowIfError("Failed to retrieve the running state.");
70 if (handle != IntPtr.Zero)
72 Native.DisconnectDb(handle);
77 private static void EnsureInitializedIfRunning()
79 if (_handle != IntPtr.Zero)
84 if (IsRunning == false)
86 throw new InvalidOperationException("The server is not running.");
92 private static IntPtr Handle
96 EnsureInitializedIfRunning();
102 private static void Initialize()
104 Native.Create(out _handle).ThrowIfError("Failed to create media controller server.");
108 RegisterPlaybackCommandReceivedEvent();
109 RegisterPlaybackActionCommandReceivedEvent();
110 RegisterPlaybackPositionCommandReceivedEvent();
111 RegisterPlaylistCommandReceivedEvent();
112 RegisterShuffleModeCommandReceivedEvent();
113 RegisterRepeatModeCommandReceivedEvent();
114 RegisterCustomCommandReceivedEvent();
115 RegisterCommandCompletedEvent();
116 RegisterSearchCommandReceivedEvent();
122 Native.Destroy(_handle);
123 _playbackCommandCallback = null;
124 _handle = IntPtr.Zero;
130 /// Starts the media control server.
133 /// When the server starts, <see cref="MediaControllerManager.ServerStarted"/> will be raised.
135 /// <privilege>http://tizen.org/privilege/mediacontroller.server</privilege>
136 /// <exception cref="InvalidOperationException">An internal error occurs.</exception>
137 /// <exception cref="UnauthorizedAccessException">Caller does not have required privilege.</exception>
138 /// <seealso cref="MediaControllerManager.ServerStarted"/>
139 /// <since_tizen> 4 </since_tizen>
140 public static void Start()
146 /// Stops the media control server.
149 /// When the server stops, <see cref="MediaControllerManager.ServerStopped"/> will be raised.
151 /// <exception cref="InvalidOperationException">
152 /// The server is not running .<br/>
154 /// An internal error occurs.
156 /// <seealso cref="MediaControllerManager.ServerStopped"/>
157 /// <since_tizen> 4 </since_tizen>
158 public static void Stop()
160 EnsureInitializedIfRunning();
162 Native.Destroy(_handle).ThrowIfError("Failed to stop the server.");
164 _handle = IntPtr.Zero;
165 _playbackCommandCallback = null;
170 /// Updates playback state and playback position.</summary>
171 /// <param name="state">The playback state.</param>
172 /// <param name="position">The playback position in milliseconds.</param>
173 /// <exception cref="ArgumentException"><paramref name="state"/> is not valid.</exception>
174 /// <exception cref="ArgumentOutOfRangeException"><paramref name="position"/> is less than zero.</exception>
175 /// <exception cref="InvalidOperationException">
176 /// The server is not running .<br/>
178 /// An internal error occurs.
180 /// <since_tizen> 4 </since_tizen>
181 public static void SetPlaybackState(MediaControlPlaybackState state, long position)
183 ValidationUtil.ValidateEnum(typeof(MediaControlPlaybackState), state, nameof(state));
187 throw new ArgumentOutOfRangeException(nameof(position), position, "position can't be less than zero.");
190 Native.SetPlaybackState(Handle, state.ToNative()).ThrowIfError("Failed to set playback state.");
192 Native.SetPlaybackPosition(Handle, (ulong)position).ThrowIfError("Failed to set playback position.");
194 Native.UpdatePlayback(Handle).ThrowIfError("Failed to set playback.");
197 private static void SetMetadata(MediaControllerNativeAttribute attribute, string value)
199 Native.SetMetadata(Handle, attribute, value).ThrowIfError($"Failed to set metadata({attribute}).");
203 /// Updates metadata information.
205 /// <param name="metadata">The metadata to update.</param>
206 /// <exception cref="ArgumentNullException"><paramref name="metadata"/> is null.</exception>
207 /// <exception cref="InvalidOperationException">
208 /// The server is not running .<br/>
210 /// An internal error occurs.
212 /// <since_tizen> 4 </since_tizen>
213 public static void SetMetadata(MediaControlMetadata metadata)
215 if (metadata == null)
217 throw new ArgumentNullException(nameof(metadata));
220 SetMetadata(MediaControllerNativeAttribute.Title, metadata.Title);
221 SetMetadata(MediaControllerNativeAttribute.Artist, metadata.Artist);
222 SetMetadata(MediaControllerNativeAttribute.Album, metadata.Album);
223 SetMetadata(MediaControllerNativeAttribute.Author, metadata.Author);
224 SetMetadata(MediaControllerNativeAttribute.Genre, metadata.Genre);
225 SetMetadata(MediaControllerNativeAttribute.Duration, metadata.Duration);
226 SetMetadata(MediaControllerNativeAttribute.Date, metadata.Date);
227 SetMetadata(MediaControllerNativeAttribute.Copyright, metadata.Copyright);
228 SetMetadata(MediaControllerNativeAttribute.Description, metadata.Description);
229 SetMetadata(MediaControllerNativeAttribute.TrackNumber, metadata.TrackNumber);
230 SetMetadata(MediaControllerNativeAttribute.Picture, metadata.AlbumArtPath);
232 Native.UpdateMetadata(Handle).ThrowIfError("Failed to set metadata.");
236 /// Updates the shuffle mode.
238 /// <param name="enabled">A value indicating whether the shuffle mode is enabled.</param>
239 /// <exception cref="InvalidOperationException">
240 /// The server is not running .<br/>
242 /// An internal error occurs.
244 /// <since_tizen> 4 </since_tizen>
245 public static void SetShuffleModeEnabled(bool enabled)
247 Native.UpdateShuffleMode(Handle, enabled ? MediaControllerNativeShuffleMode.On : MediaControllerNativeShuffleMode.Off).
248 ThrowIfError("Failed to set shuffle mode.");
252 /// Updates the repeat mode.
254 /// <param name="mode">A value indicating the repeat mode.</param>
255 /// <exception cref="InvalidOperationException">
256 /// The server is not running .<br/>
258 /// An internal error occurs.
260 /// <exception cref="ArgumentException"><paramref name="mode"/> is invalid.</exception>
261 /// <since_tizen> 4 </since_tizen>
262 public static void SetRepeatMode(MediaControlRepeatMode mode)
264 ValidationUtil.ValidateEnum(typeof(MediaControlRepeatMode), mode, nameof(mode));
266 Native.UpdateRepeatMode(Handle, mode.ToNative()).ThrowIfError("Failed to set repeat mode.");
270 /// Sets the index of current playing media.
272 /// <param name="index">The index of current playing media.</param>
273 /// <exception cref="ArgumentNullException"><paramref name="index"/> is null.</exception>
274 /// <exception cref="InvalidOperationException">
275 /// The server is not running .<br/>
277 /// An internal error occurs.
279 /// <since_tizen> 5 </since_tizen>
280 [Obsolete("Please do not use! This will be deprecated. Please use SetInfoOfCurrentPlayingMedia instead.")]
281 public static void SetIndexOfCurrentPlayingMedia(string index)
285 throw new ArgumentNullException(nameof(index));
288 Native.SetIndexOfCurrentPlayingMedia(Handle, index)
289 .ThrowIfError("Failed to set the index of current playing media");
291 Native.UpdatePlayback(Handle).ThrowIfError("Failed to set playback.");
295 /// Sets the playlist name and index of current playing media.
297 /// <param name="playlistName">The playlist name of current playing media.</param>
298 /// <param name="index">The index of current playing media.</param>
299 /// <exception cref="ArgumentNullException">
300 /// <paramref name="playlistName"/> or <paramref name="index"/> is null.
302 /// <exception cref="InvalidOperationException">
303 /// The server is not running .<br/>
305 /// An internal error occurs.
307 /// <since_tizen> 5 </since_tizen>
308 public static void SetInfoOfCurrentPlayingMedia(string playlistName, string index)
310 if (playlistName == null)
312 throw new ArgumentNullException(nameof(playlistName));
316 throw new ArgumentNullException(nameof(index));
319 Native.SetInfoOfCurrentPlayingMedia(Handle, playlistName, index)
320 .ThrowIfError("Failed to set the playlist name and index of current playing media");
322 Native.UpdatePlayback(Handle).ThrowIfError("Failed to set playback.");
328 /// <param name="playlist">The name of playlist.</param>
329 /// <exception cref="InvalidOperationException">
330 /// The server is not running .<br/>
332 /// An internal error occurs.
334 /// <since_tizen> 5 </since_tizen>
335 public static void RemovePlaylist(MediaControlPlaylist playlist)
337 Native.DeletePlaylist(Handle, playlist.Handle);
341 // Saves the playlist to the persistent storage.
342 internal static void SavePlaylist(IntPtr playlistHandle)
344 Native.SavePlaylist(Handle, playlistHandle).ThrowIfError("Failed to save playlist");
347 // Gets the playlist handle by name.
348 internal static IntPtr GetPlaylistHandle(string name)
350 Native.GetPlaylistHandle(Handle, name, out IntPtr playlistHandle)
351 .ThrowIfError("Failed to get playlist handle by name");
353 return playlistHandle;
357 /// Gets the active clients.
359 /// <exception cref="InvalidOperationException">
360 /// The server is not running .<br/>
362 /// An internal error occurs.
364 /// <returns>the activated client ids.</returns>
365 /// <since_tizen> 5 </since_tizen>
366 public static IEnumerable<string> GetActivatedClients()
368 var clientIds = new List<string>();
370 Native.ActivatedClientCallback activatedClientCallback = (name, _) =>
376 Native.ForeachActivatedClient(Handle, activatedClientCallback).
377 ThrowIfError("Failed to get activated client.");
379 return clientIds.AsReadOnly();
383 /// Requests commands to the client.
386 /// The client can request the command to execute <see cref="Command"/>, <br/>
387 /// and then, the server receive the result of each request(command).
389 /// <param name="command">A <see cref="Command"/> class.</param>
390 /// <param name="clientId">The client Id to send command.</param>
391 /// <returns><see cref="Bundle"/> represents the extra data from client and it can be null.</returns>
392 /// <exception cref="InvalidOperationException">
393 /// The server has already been stopped.<br/>
395 /// An internal error occurs.
397 /// <since_tizen> 5 </since_tizen>
398 public static async Task<Bundle> RequestAsync(Command command, string clientId)
400 command.SetRequestInformation(clientId);
402 var tcs = new TaskCompletionSource<MediaControllerError>();
403 string reqeustId = null;
404 Bundle bundle = null;
406 EventHandler<CommandCompletedEventArgs> eventHandler = (s, e) =>
408 if (e.RequestId == reqeustId)
411 tcs.TrySetResult(e.Result);
417 CommandCompleted += eventHandler;
419 reqeustId = command.Request(Handle);
421 (await tcs.Task).ThrowIfError("Failed to request event.");
427 CommandCompleted -= eventHandler;
432 /// Sends the result of each command.
434 /// <param name="command">The command that return to client.</param>
435 /// <param name="result">The result of <paramref name="command"/>.</param>
436 /// <param name="bundle">The extra data.</param>
437 /// <exception cref="InvalidOperationException">
438 /// The server is not running .<br/>
440 /// An internal error occurs.
442 /// <since_tizen> 5 </since_tizen>
443 public static void Response(Command command, int result, Bundle bundle)
445 command.Response(Handle, result, bundle);
449 /// Sends the result of each command.
451 /// <param name="command">The command that return to client.</param>
452 /// <param name="result">The result of <paramref name="command"/>.</param>
453 /// <exception cref="InvalidOperationException">
454 /// The server is not running .<br/>
456 /// An internal error occurs.
458 /// <since_tizen> 5 </since_tizen>
459 public static void Response(Command command, int result)
461 command.Response(Handle, result, null);
466 /// Sets the content type of latest played media.
468 /// <param name="type">A value indicating the content type of the latest played media.</param>
469 /// <exception cref="InvalidOperationException">
470 /// The server is not running .<br/>
472 /// An internal error occurs.
474 /// <exception cref="ArgumentException"><paramref name="type"/> is invalid.</exception>
475 /// <since_tizen> 5 </since_tizen>
476 public static void SetPlaybackContentType(MediaControlContentType type)
478 ValidationUtil.ValidateEnum(typeof(MediaControlContentType), type, nameof(type));
480 Native.SetPlaybackContentType(Handle, type).ThrowIfError("Failed to set playback content type.");
482 Native.UpdatePlayback(Handle).ThrowIfError("Failed to set playback.");
486 /// Sets the path of icon.
488 /// <param name="path">The path of icon.</param>
489 /// <exception cref="InvalidOperationException">
490 /// The server is not running .<br/>
492 /// An internal error occurs.
494 /// <exception cref="ArgumentNullException"><paramref name="path"/> is invalid.</exception>
495 /// <since_tizen> 5 </since_tizen>
496 public static void SetIconPath(string path)
500 throw new ArgumentNullException(nameof(path));
503 Native.SetIconPath(Handle, path).ThrowIfError("Failed to set uri path.");
507 /// Sets the capabilities by <see cref="MediaControlPlaybackCommand"/>.
509 /// <param name="capabilities">The set of <see cref="MediaControlPlaybackCommand"/> and <see cref="MediaControlCapabilitySupport"/>.</param>
510 /// <exception cref="InvalidOperationException">
511 /// The server is not running .<br/>
513 /// An internal error occurs.
515 /// <exception cref="ArgumentException"><paramref name="capabilities"/> is invalid.</exception>
516 /// <since_tizen> 5 </since_tizen>
517 public static void SetPlaybackCapabilities(Dictionary<MediaControlPlaybackCommand, MediaControlCapabilitySupport> capabilities)
519 foreach (var pair in capabilities)
521 ValidationUtil.ValidateEnum(typeof(MediaControlPlaybackCommand), pair.Key, nameof(pair.Key));
522 ValidationUtil.ValidateEnum(typeof(MediaControlCapabilitySupport), pair.Value, nameof(pair.Value));
524 SetPlaybackCapability(pair.Key, pair.Value);
525 Native.SetPlaybackCapability(Handle, pair.Key.ToNative(), pair.Value).
526 ThrowIfError("Failed to set playback capability.");
529 Native.SaveAndNotifyPlaybackCapabilityUpdated(Handle).ThrowIfError("Failed to update playback capability.");
533 /// Sets the capabilities by <see cref="MediaControlPlaybackCommand"/>.
535 /// <param name="action">A playback command.</param>
536 /// <param name="support">A value indicating whether the <paramref name="action"/> is supported or not.</param>
537 /// <exception cref="InvalidOperationException">
538 /// The server is not running .<br/>
540 /// An internal error occurs.
542 /// <exception cref="ArgumentException"><paramref name="action"/> or <paramref name="support"/> is invalid.</exception>
543 /// <since_tizen> 5 </since_tizen>
544 public static void SetPlaybackCapability(MediaControlPlaybackCommand action, MediaControlCapabilitySupport support)
546 ValidationUtil.ValidateEnum(typeof(MediaControlPlaybackCommand), action, nameof(action));
547 ValidationUtil.ValidateEnum(typeof(MediaControlCapabilitySupport), support, nameof(support));
549 Native.SetPlaybackCapability(Handle, action.ToNative(), support).ThrowIfError("Failed to set playback capability.");
551 Native.SaveAndNotifyPlaybackCapabilityUpdated(Handle).ThrowIfError("Failed to update playback capability.");
555 /// Sets the <see cref="MediaControlCapabilitySupport"/> indicating shuffle mode is supported or not.
557 /// <param name="support">A value indicating whether the shuffle mode is supported or not.</param>
558 /// <exception cref="InvalidOperationException">
559 /// The server is not running .<br/>
561 /// An internal error occurs.
563 /// <exception cref="ArgumentException"><paramref name="support"/> is invalid.</exception>
564 /// <since_tizen> 5 </since_tizen>
565 public static void SetShuffleModeCapability(MediaControlCapabilitySupport support)
567 ValidationUtil.ValidateEnum(typeof(MediaControlCapabilitySupport), support, nameof(support));
569 Native.SetShuffleModeCapability(Handle, support).ThrowIfError("Failed to set shuffle mode capability.");
573 /// Sets the content type of latest played media.
575 /// <param name="support">A value indicating whether the <see cref="MediaControlRepeatMode"/> is supported or not.</param>
576 /// <exception cref="InvalidOperationException">
577 /// The server is not running .<br/>
579 /// An internal error occurs.
581 /// <exception cref="ArgumentException"><paramref name="support"/> is invalid.</exception>
582 /// <since_tizen> 5 </since_tizen>
583 public static void SetRepeatModeCapability(MediaControlCapabilitySupport support)
585 ValidationUtil.ValidateEnum(typeof(MediaControlCapabilitySupport), support, nameof(support));
587 Native.SetRepeatModeCapability(Handle, support).ThrowIfError("Failed to set shuffle mode capability.");
589 #endregion Capabilities
592 /// Sets the age rating of latest played media.
594 /// <param name="ageRating">
595 /// The Age rating of latest played media. The valid range is 0 to 19, inclusive.
596 /// Especially, 0 means that media is suitable for all ages.
598 /// <exception cref="ArgumentOutOfRangeException">The specified <paramref name="ageRating"/> is not valid.</exception>
599 /// <exception cref="InvalidOperationException">
600 /// The server is not running .<br/>
602 /// An internal error occurs.
604 /// <since_tizen> 5 </since_tizen>
605 public static void SetAgeRating(int ageRating)
607 if (ageRating < 0 || ageRating > 19)
609 throw new ArgumentOutOfRangeException(nameof(ageRating));
612 Native.SetAgeRating(Handle, ageRating).ThrowIfError("Failed to set age rating.");
614 Native.UpdatePlayback(Handle).ThrowIfError("Failed to set playback.");