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.Diagnostics;
20 using System.Threading;
21 using System.Threading.Tasks;
22 using Native = Interop.ScreenMirroring;
24 namespace Tizen.Multimedia.Remoting
27 /// Provides the ability to connect to and disconnect from a screen mirroring source,
28 /// start, pause, and resume the screen mirroring as a sink.
30 public class ScreenMirroring : IDisposable, IDisplayable<ScreenMirroringErrorCode>
32 private const string Feature = "http://tizen.org/feature/network.wifi.direct.display";
33 private const int Port = 2022;
35 private IntPtr _handle;
37 private AtomicState _state;
39 private bool _disposed = false;
41 internal IntPtr Handle
51 private static bool IsSupported()
53 return System.Information.TryGetValue(Feature, out bool isSupported) ? isSupported : false;
57 /// Initializes a new instance of the ScreenMirroring class.
59 /// <feature>http://tizen.org/feature/network.wifi.direct.display</feature>
60 /// <exception cref="NotSupportedException">The feature is not supported.</exception>
61 public ScreenMirroring()
63 if (IsSupported() == false)
65 throw new PlatformNotSupportedException($"The feature({Feature}) is not supported on the current device");
68 Native.Create(out _handle).ThrowIfError("Failed to create ScreenMirroring.");
70 _state = new AtomicState();
72 AudioInfo = new ScreenMirroringAudioInfo(this);
73 VideoInfo = new ScreenMirroringVideoInfo(this);
75 RegisterStateChangedEvent();
84 /// Occurs when the state is changed.
86 public event EventHandler<ScreenMirroringStateChangedEventArgs> StateChanged;
89 /// Occurs when an error occurs.
91 public event EventHandler<ScreenMirroringErrorOccurredEventArgs> ErrorOccurred;
93 #region Display support
95 private Display _display;
97 private void DetachDisplay()
101 _display.SetOwner(null);
106 private void SetDisplay(Display display)
110 throw new ArgumentNullException(nameof(Display));
113 display.SetOwner(this);
114 display.ApplyTo(this).ThrowIfError("Failed to set display.");
119 ScreenMirroringErrorCode IDisplayable<ScreenMirroringErrorCode>.ApplyEvasDisplay(DisplayType type,
120 ElmSharp.EvasObject evasObject)
122 Debug.Assert(Enum.IsDefined(typeof(DisplayType), type));
124 return Native.SetDisplay(Handle, (int)type, evasObject);
127 ScreenMirroringErrorCode IDisplayable<ScreenMirroringErrorCode>.ApplyEcoreWindow(IntPtr windowHandle)
129 throw new NotSupportedException("ScreenMirroring does not support NUI.Window display.");
134 /// Gets the negotiated audio info.
136 public ScreenMirroringAudioInfo AudioInfo { get; }
139 /// Gets the negotiated video info.
141 public ScreenMirroringVideoInfo VideoInfo { get; }
143 private bool IsConnected
147 return _state.IsOneOf(ScreenMirroringState.Connected, ScreenMirroringState.Playing,
148 ScreenMirroringState.Paused);
152 internal void ThrowIfNotConnected()
156 if (IsConnected == false)
158 throw new InvalidOperationException("ScreenMirroring is not connected.");
163 /// Prepares the screen mirroring with the specified display.
166 /// The state must be <see cref="ScreenMirroringState.Idle"/>.\n
168 /// All supported resolutions will be candidates.
170 /// <param name="display">The display where the mirroring will be played on.</param>
171 /// <exception cref="ArgumentException">
172 /// <paramref name="display"/> has already been assigned to another.
174 /// <exception cref="ArgumentNullException"><paramref name="display"/> is null.</exception>
175 /// <exception cref="InvalidOperationException">
176 /// The current state is not in the valid.\n
178 /// An internal error occurs.
180 /// <exception cref="ObjectDisposedException">The <see cref="ScreenMirroring"/> has already been disposed.</exception>
181 public void Prepare(Display display)
183 PrepareCore(display, (ScreenMirroringResolutions)0);
187 /// Prepares the screen mirroring with the specified display and resolutions.
190 /// The state must be <see cref="ScreenMirroringState.Idle"/>.
192 /// <param name="display">The display where the mirroring will be played on.</param>
193 /// <param name="resolutions">The desired resolutions.</param>
194 /// <exception cref="ArgumentException">
195 /// <paramref name="resolutions"/> contain invalid flags.\n
197 /// <paramref name="display"/> has already been assigned to another.
199 /// <exception cref="ArgumentNullException"><paramref name="display"/> is null.</exception>
200 /// <exception cref="InvalidOperationException">
201 /// The current state is not in the valid.\n
203 /// An internal error occurs.
205 /// <exception cref="ObjectDisposedException">The <see cref="ScreenMirroring"/> has already been disposed.</exception>
206 public void Prepare(Display display, ScreenMirroringResolutions resolutions)
208 ValidationUtil.ValidateFlagsEnum(resolutions, (ScreenMirroringResolutions)((1 << 7) - 1), nameof(resolutions));
210 PrepareCore(display, resolutions);
213 private void PrepareCore(Display display, ScreenMirroringResolutions resolutions)
215 ValidateState(ScreenMirroringState.Idle);
217 Native.SetResolution(Handle, resolutions).ThrowIfError("Failed to set resolutions.");
223 Native.Prepare(Handle).ThrowIfError("Failed to prepare.");
233 /// Creates the connection and ready for receiving data from a mirroring source.
235 /// <param name="sourceIp">The source ip address to connect.</param>
237 /// The state must be <see cref="ScreenMirroringState.Prepared"/> state by
238 /// <see cref="Prepare(Display, ScreenMirroringResolutions)"/>.
240 /// <returns>A task that represents the asynchronous operation.</returns>
241 /// <privilege>http://tizen.org/privilege/internet</privilege>
242 /// <exception cref="ArgumentNullException"><paramref name="sourceIp"/> is null.</exception>
243 /// <exception cref="InvalidOperationException">
244 /// The current state is not in the valid.\n
246 /// An internal error occurs.
248 /// <exception cref="ArgumentException"><paramref name="sourceIp"/> is a zero-length string, contains only white space.</exception>
249 /// <exception cref="ObjectDisposedException">The <see cref="ScreenMirroring"/> has already been disposed.</exception>
250 /// <exception cref="UnauthorizedAccessException">Caller does not have required permission.</exception>
251 public Task ConnectAsync(string sourceIp)
253 if (sourceIp == null)
255 throw new ArgumentNullException(nameof(sourceIp));
258 if (string.IsNullOrWhiteSpace(sourceIp))
260 throw new ArgumentException($"{nameof(sourceIp)} is a zero-length string.", nameof(sourceIp));
263 ValidateState(ScreenMirroringState.Prepared);
265 Native.SetIpAndPort(Handle, sourceIp, Port.ToString()).ThrowIfError("Failed to set ip.");
267 var tcs = new TaskCompletionSource<bool>();
269 Task.Factory.StartNew(() =>
271 Native.Connect(Handle).ThrowIfError("Failed to connect");
279 /// Starts mirroring from the source.
282 /// The state must be <see cref="ScreenMirroringState.Connected"/> state by
283 /// <see cref="ConnectAsync(string)"/>.
285 /// <returns>A task that represents the asynchronous operation.</returns>
286 /// <privilege>http://tizen.org/privilege/internet</privilege>
287 /// <exception cref="InvalidOperationException">
288 /// The current state is not in the valid.\n
290 /// An internal error occurs.
292 /// <exception cref="ObjectDisposedException">The <see cref="ScreenMirroring"/> has already been disposed.</exception>
293 /// <exception cref="UnauthorizedAccessException">Caller does not have required permission.</exception>
294 public Task StartAsync()
296 ValidateState(ScreenMirroringState.Connected);
298 var tcs = new TaskCompletionSource<bool>();
300 Task.Factory.StartNew(() =>
302 Native.StartAsync(Handle).ThrowIfError("Failed to start.");
303 tcs.TrySetResult(true);
310 /// Pauses mirroring from the source.
313 /// The state must be <see cref="ScreenMirroringState.Playing"/> state by
314 /// <see cref="StartAsync"/>.
316 /// <returns>A task that represents the asynchronous operation.</returns>
317 /// <privilege>http://tizen.org/privilege/internet</privilege>
318 /// <exception cref="InvalidOperationException">
319 /// The current state is not in the valid.\n
321 /// An internal error occurs.
323 /// <exception cref="ObjectDisposedException">The <see cref="ScreenMirroring"/> has already been disposed.</exception>
324 /// <exception cref="UnauthorizedAccessException">Caller does not have required permission.</exception>
325 public Task PauseAsync()
327 ValidateState(ScreenMirroringState.Playing);
329 var tcs = new TaskCompletionSource<bool>();
331 Task.Factory.StartNew(() =>
333 Native.PauseAsync(Handle).ThrowIfError("Failed to prepare.");
334 tcs.TrySetResult(true);
341 /// Resumes mirroring from the source.
344 /// The state must be <see cref="ScreenMirroringState.Paused"/> state by
345 /// <see cref="PauseAsync"/>.
347 /// <returns>A task that represents the asynchronous operation.</returns>
348 /// <privilege>http://tizen.org/privilege/internet</privilege>
349 /// <exception cref="InvalidOperationException">
350 /// The current state is not in the valid.\n
352 /// An internal error occurs.
354 /// <exception cref="ObjectDisposedException">The <see cref="ScreenMirroring"/> has already been disposed.</exception>
355 /// <exception cref="UnauthorizedAccessException">Caller does not have required permission.</exception>
356 public Task ResumeAsync()
358 ValidateState(ScreenMirroringState.Paused);
360 var tcs = new TaskCompletionSource<bool>();
362 Task.Factory.StartNew(() =>
364 Native.ResumeAsync(Handle).ThrowIfError("Failed to resume.");
365 tcs.TrySetResult(true);
372 /// Disconnects from the source.
375 /// The state must be <see cref="ScreenMirroringState.Connected"/>,
376 /// <see cref="ScreenMirroringState.Playing"/> or <see cref="ScreenMirroringState.Paused"/>.
378 /// <privilege>http://tizen.org/privilege/internet</privilege>
379 /// <exception cref="InvalidOperationException">
380 /// The current state is not in the valid.\n
382 /// An internal error occurs.
384 /// <exception cref="ObjectDisposedException">The <see cref="ScreenMirroring"/> has already been disposed.</exception>
385 /// <exception cref="UnauthorizedAccessException">Caller does not have required permission.</exception>
386 public void Disconnect()
388 ValidateState(ScreenMirroringState.Connected, ScreenMirroringState.Playing,
389 ScreenMirroringState.Paused);
391 Native.Disconnect(Handle).ThrowIfError("Failed to disconnect.");
395 /// Unprepares the screen mirroring.
398 /// The state must be <see cref="ScreenMirroringState.Prepared"/>,
399 /// or <see cref="ScreenMirroringState.Disconnected"/>.
401 /// <exception cref="InvalidOperationException">
402 /// The current state is not in the valid.\n
404 /// An internal error occurs.
406 /// <exception cref="ObjectDisposedException">The <see cref="ScreenMirroring"/> has already been disposed.</exception>
407 public void Unprepare()
409 ValidateState(ScreenMirroringState.Prepared, ScreenMirroringState.Disconnected);
411 Native.Unprepare(Handle).ThrowIfError("Failed to reset.");
416 private void ThrowIfDisposed()
420 throw new ObjectDisposedException(nameof(ScreenMirroring));
425 /// Releases all resource used by the <see cref="ScreenMirroring"/> object.
428 /// Call <see cref="Dispose()"/> when you are finished using the <see cref="ScreenMirroring"/>.
429 /// The <see cref="Dispose()"/> method leaves the <see cref="ScreenMirroring"/> in an unusable
430 /// state. After calling <see cref="Dispose"()/>, you must release all references to the
431 /// <see cref="ScreenMirroring"/> so the garbage collector can reclaim the memory that the
432 /// <see cref="ScreenMirroring"/> was occupying.
434 public void Dispose()
437 GC.SuppressFinalize(this);
441 /// Releases the resources used by the ScreenMirroring.
443 /// <param name="disposing">
444 /// true to release both managed and unmanaged resources; false to release only unmanaged resources.
446 protected virtual void Dispose(bool disposing)
452 if (_handle != IntPtr.Zero)
454 Native.Destroy(_handle);
455 _handle = IntPtr.Zero;
462 private Native.StateChangedCallback _stateChangedCallback;
464 private void RegisterStateChangedEvent()
466 _stateChangedCallback = (error, state, _) =>
468 var prevState = _state.Value;
470 _state.Value = state;
472 if (prevState != state)
474 StateChanged?.Invoke(this, new ScreenMirroringStateChangedEventArgs(state));
478 if (error != ScreenMirroringErrorCode.None)
480 ErrorOccurred?.Invoke(this, new ScreenMirroringErrorOccurredEventArgs(
481 ScreenMirroringError.InvalidOperation));
485 Native.SetStateChangedCb(Handle, _stateChangedCallback).
486 ThrowIfError("Failed to initialize StateChanged event.");
489 private void ValidateState(params ScreenMirroringState[] required)
491 Debug.Assert(required.Length > 0);
495 throw new ObjectDisposedException(nameof(ScreenMirroring));
498 var curState = _state.Value;
499 if (!required.Contains(curState))
501 throw new InvalidOperationException($"The screen mirroring is not in a valid state. " +
502 $"Current State : { curState }, Valid State : { string.Join(", ", required) }.");
508 internal class AtomicState
514 _value = (int)ScreenMirroringState.Idle;
517 public ScreenMirroringState Value
521 return (ScreenMirroringState)Interlocked.CompareExchange(ref _value, 0, 0);
525 Interlocked.Exchange(ref _value, (int)value);
529 public bool IsOneOf(params ScreenMirroringState[] states)
531 return states.Contains(Value);