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>
62 public ScreenMirroring()
64 if (IsSupported() == false)
66 throw new PlatformNotSupportedException($"The feature({Feature}) is not supported on the current device");
69 Native.Create(out _handle).ThrowIfError("Failed to create ScreenMirroring.");
71 _state = new AtomicState();
73 AudioInfo = new ScreenMirroringAudioInfo(this);
74 VideoInfo = new ScreenMirroringVideoInfo(this);
76 RegisterStateChangedEvent();
85 /// Occurs when the state is changed.
87 public event EventHandler<ScreenMirroringStateChangedEventArgs> StateChanged;
90 /// Occurs when an error occurs.
92 public event EventHandler<ScreenMirroringErrorOccurredEventArgs> ErrorOccurred;
94 #region Display support
96 private Display _display;
98 private void DetachDisplay()
100 if (_display != null)
102 _display.SetOwner(null);
107 private void SetDisplay(Display display)
111 throw new ArgumentNullException(nameof(Display));
114 display.SetOwner(this);
115 display.ApplyTo(this).ThrowIfError("Failed to set display.");
120 ScreenMirroringErrorCode IDisplayable<ScreenMirroringErrorCode>.ApplyEvasDisplay(DisplayType type,
121 ElmSharp.EvasObject evasObject)
123 Debug.Assert(Enum.IsDefined(typeof(DisplayType), type));
125 return Native.SetDisplay(Handle, (int)type, evasObject);
128 ScreenMirroringErrorCode IDisplayable<ScreenMirroringErrorCode>.ApplyEcoreWindow(IntPtr windowHandle)
130 throw new NotSupportedException("ScreenMirroring does not support NUI.Window display.");
135 /// Gets the negotiated audio info.
137 public ScreenMirroringAudioInfo AudioInfo { get; }
140 /// Gets the negotiated video info.
142 public ScreenMirroringVideoInfo VideoInfo { get; }
144 private bool IsConnected
148 return _state.IsOneOf(ScreenMirroringState.Connected, ScreenMirroringState.Playing,
149 ScreenMirroringState.Paused);
153 internal void ThrowIfNotConnected()
157 if (IsConnected == false)
159 throw new InvalidOperationException("ScreenMirroring is not connected.");
164 /// Prepares the screen mirroring with the specified display.
167 /// The state must be <see cref="ScreenMirroringState.Idle"/>.\n
169 /// All supported resolutions will be candidates.
171 /// <param name="display">The display where the mirroring will be played on.</param>
172 /// <exception cref="ArgumentException">
173 /// <paramref name="display"/> has already been assigned to another.
175 /// <exception cref="ArgumentNullException"><paramref name="display"/> is null.</exception>
176 /// <exception cref="InvalidOperationException">
177 /// The current state is not in the valid.\n
179 /// An internal error occurs.
181 /// <exception cref="ObjectDisposedException">The <see cref="ScreenMirroring"/> has already been disposed.</exception>
182 public void Prepare(Display display)
184 PrepareCore(display, (ScreenMirroringResolutions)0);
188 /// Prepares the screen mirroring with the specified display and resolutions.
191 /// The state must be <see cref="ScreenMirroringState.Idle"/>.
193 /// <param name="display">The display where the mirroring will be played on.</param>
194 /// <param name="resolutions">The desired resolutions.</param>
195 /// <exception cref="ArgumentException">
196 /// <paramref name="resolutions"/> contain invalid flags.\n
198 /// <paramref name="display"/> has already been assigned to another.
200 /// <exception cref="ArgumentNullException"><paramref name="display"/> is null.</exception>
201 /// <exception cref="InvalidOperationException">
202 /// The current state is not in the valid.\n
204 /// An internal error occurs.
206 /// <exception cref="ObjectDisposedException">The <see cref="ScreenMirroring"/> has already been disposed.</exception>
207 public void Prepare(Display display, ScreenMirroringResolutions resolutions)
209 ValidationUtil.ValidateFlagsEnum(resolutions, (ScreenMirroringResolutions)((1 << 7) - 1), nameof(resolutions));
211 PrepareCore(display, resolutions);
214 private void PrepareCore(Display display, ScreenMirroringResolutions resolutions)
216 ValidateState(ScreenMirroringState.Idle);
218 Native.SetResolution(Handle, resolutions).ThrowIfError("Failed to set resolutions.");
224 Native.Prepare(Handle).ThrowIfError("Failed to prepare.");
234 /// Creates the connection and ready for receiving data from a mirroring source.
236 /// <param name="sourceIp">The source ip address to connect.</param>
238 /// The state must be <see cref="ScreenMirroringState.Prepared"/> state by
239 /// <see cref="Prepare(Display, ScreenMirroringResolutions)"/>.
241 /// <returns>A task that represents the asynchronous operation.</returns>
242 /// <privilege>http://tizen.org/privilege/internet</privilege>
243 /// <exception cref="ArgumentNullException"><paramref name="sourceIp"/> is null.</exception>
244 /// <exception cref="InvalidOperationException">
245 /// The current state is not in the valid.\n
247 /// An internal error occurs.
249 /// <exception cref="ArgumentException"><paramref name="sourceIp"/> is a zero-length string, contains only white space.</exception>
250 /// <exception cref="ObjectDisposedException">The <see cref="ScreenMirroring"/> has already been disposed.</exception>
251 /// <exception cref="UnauthorizedAccessException">Caller does not have required permission.</exception>
252 public Task ConnectAsync(string sourceIp)
254 if (sourceIp == null)
256 throw new ArgumentNullException(nameof(sourceIp));
259 if (string.IsNullOrWhiteSpace(sourceIp))
261 throw new ArgumentException($"{nameof(sourceIp)} is a zero-length string.", nameof(sourceIp));
264 ValidateState(ScreenMirroringState.Prepared);
266 Native.SetIpAndPort(Handle, sourceIp, Port.ToString()).ThrowIfError("Failed to set ip.");
268 var tcs = new TaskCompletionSource<bool>();
270 Task.Factory.StartNew(() =>
272 Native.Connect(Handle).ThrowIfError("Failed to connect");
280 /// Starts mirroring from the source.
283 /// The state must be <see cref="ScreenMirroringState.Connected"/> state by
284 /// <see cref="ConnectAsync(string)"/>.
286 /// <returns>A task that represents the asynchronous operation.</returns>
287 /// <privilege>http://tizen.org/privilege/internet</privilege>
288 /// <exception cref="InvalidOperationException">
289 /// The current state is not in the valid.\n
291 /// An internal error occurs.
293 /// <exception cref="ObjectDisposedException">The <see cref="ScreenMirroring"/> has already been disposed.</exception>
294 /// <exception cref="UnauthorizedAccessException">Caller does not have required permission.</exception>
295 public Task StartAsync()
297 ValidateState(ScreenMirroringState.Connected);
299 var tcs = new TaskCompletionSource<bool>();
301 Task.Factory.StartNew(() =>
303 Native.StartAsync(Handle).ThrowIfError("Failed to start.");
304 tcs.TrySetResult(true);
311 /// Pauses mirroring from the source.
314 /// The state must be <see cref="ScreenMirroringState.Playing"/> state by
315 /// <see cref="StartAsync"/>.
317 /// <returns>A task that represents the asynchronous operation.</returns>
318 /// <privilege>http://tizen.org/privilege/internet</privilege>
319 /// <exception cref="InvalidOperationException">
320 /// The current state is not in the valid.\n
322 /// An internal error occurs.
324 /// <exception cref="ObjectDisposedException">The <see cref="ScreenMirroring"/> has already been disposed.</exception>
325 /// <exception cref="UnauthorizedAccessException">Caller does not have required permission.</exception>
326 public Task PauseAsync()
328 ValidateState(ScreenMirroringState.Playing);
330 var tcs = new TaskCompletionSource<bool>();
332 Task.Factory.StartNew(() =>
334 Native.PauseAsync(Handle).ThrowIfError("Failed to prepare.");
335 tcs.TrySetResult(true);
342 /// Resumes mirroring from the source.
345 /// The state must be <see cref="ScreenMirroringState.Paused"/> state by
346 /// <see cref="PauseAsync"/>.
348 /// <returns>A task that represents the asynchronous operation.</returns>
349 /// <privilege>http://tizen.org/privilege/internet</privilege>
350 /// <exception cref="InvalidOperationException">
351 /// The current state is not in the valid.\n
353 /// An internal error occurs.
355 /// <exception cref="ObjectDisposedException">The <see cref="ScreenMirroring"/> has already been disposed.</exception>
356 /// <exception cref="UnauthorizedAccessException">Caller does not have required permission.</exception>
357 public Task ResumeAsync()
359 ValidateState(ScreenMirroringState.Paused);
361 var tcs = new TaskCompletionSource<bool>();
363 Task.Factory.StartNew(() =>
365 Native.ResumeAsync(Handle).ThrowIfError("Failed to resume.");
366 tcs.TrySetResult(true);
373 /// Disconnects from the source.
376 /// The state must be <see cref="ScreenMirroringState.Connected"/>,
377 /// <see cref="ScreenMirroringState.Playing"/> or <see cref="ScreenMirroringState.Paused"/>.
379 /// <privilege>http://tizen.org/privilege/internet</privilege>
380 /// <exception cref="InvalidOperationException">
381 /// The current state is not in the valid.\n
383 /// An internal error occurs.
385 /// <exception cref="ObjectDisposedException">The <see cref="ScreenMirroring"/> has already been disposed.</exception>
386 /// <exception cref="UnauthorizedAccessException">Caller does not have required permission.</exception>
387 public void Disconnect()
389 ValidateState(ScreenMirroringState.Connected, ScreenMirroringState.Playing,
390 ScreenMirroringState.Paused);
392 Native.Disconnect(Handle).ThrowIfError("Failed to disconnect.");
396 /// Unprepares the screen mirroring.
399 /// The state must be <see cref="ScreenMirroringState.Prepared"/>,
400 /// or <see cref="ScreenMirroringState.Disconnected"/>.
402 /// <exception cref="InvalidOperationException">
403 /// The current state is not in the valid.\n
405 /// An internal error occurs.
407 /// <exception cref="ObjectDisposedException">The <see cref="ScreenMirroring"/> has already been disposed.</exception>
408 public void Unprepare()
410 ValidateState(ScreenMirroringState.Prepared, ScreenMirroringState.Disconnected);
412 Native.Unprepare(Handle).ThrowIfError("Failed to reset.");
417 private void ThrowIfDisposed()
421 throw new ObjectDisposedException(nameof(ScreenMirroring));
426 /// Releases all resource used by the <see cref="ScreenMirroring"/> object.
429 /// Call <see cref="Dispose()"/> when you are finished using the <see cref="ScreenMirroring"/>.
430 /// The <see cref="Dispose()"/> method leaves the <see cref="ScreenMirroring"/> in an unusable
431 /// state. After calling <see cref="Dispose"()/>, you must release all references to the
432 /// <see cref="ScreenMirroring"/> so the garbage collector can reclaim the memory that the
433 /// <see cref="ScreenMirroring"/> was occupying.
435 public void Dispose()
438 GC.SuppressFinalize(this);
442 /// Releases the resources used by the ScreenMirroring.
444 /// <param name="disposing">
445 /// true to release both managed and unmanaged resources; false to release only unmanaged resources.
447 protected virtual void Dispose(bool disposing)
453 if (_handle != IntPtr.Zero)
455 Native.Destroy(_handle);
456 _handle = IntPtr.Zero;
463 private Native.StateChangedCallback _stateChangedCallback;
465 private void RegisterStateChangedEvent()
467 _stateChangedCallback = (error, state, _) =>
469 var prevState = _state.Value;
471 _state.Value = state;
473 if (prevState != state)
475 StateChanged?.Invoke(this, new ScreenMirroringStateChangedEventArgs(state));
479 if (error != ScreenMirroringErrorCode.None)
481 ErrorOccurred?.Invoke(this, new ScreenMirroringErrorOccurredEventArgs(
482 ScreenMirroringError.InvalidOperation));
486 Native.SetStateChangedCb(Handle, _stateChangedCallback).
487 ThrowIfError("Failed to initialize StateChanged event.");
490 private void ValidateState(params ScreenMirroringState[] required)
492 Debug.Assert(required.Length > 0);
496 throw new ObjectDisposedException(nameof(ScreenMirroring));
499 var curState = _state.Value;
500 if (!required.Contains(curState))
502 throw new InvalidOperationException($"The screen mirroring is not in a valid state. " +
503 $"Current State : { curState }, Valid State : { string.Join(", ", required) }.");
509 internal class AtomicState
515 _value = (int)ScreenMirroringState.Idle;
518 public ScreenMirroringState Value
522 return (ScreenMirroringState)Interlocked.CompareExchange(ref _value, 0, 0);
526 Interlocked.Exchange(ref _value, (int)value);
530 public bool IsOneOf(params ScreenMirroringState[] states)
532 return states.Contains(Value);