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 int Port = 2022;
34 private IntPtr _handle;
36 private AtomicState _state;
38 private bool _disposed = false;
40 internal IntPtr Handle
51 /// Initializes a new instance of the ScreenMirroring class.
53 /// <feature>http://tizen.org/feature/network.wifi.direct.display</feature>
54 /// <exception cref="NotSupportedException">The feature is not supported.</exception>
55 public ScreenMirroring()
57 Native.Create(out _handle).ThrowIfError("Failed to create ScreenMirroring.");
59 _state = new AtomicState();
61 AudioInfo = new ScreenMirroringAudioInfo(this);
62 VideoInfo = new ScreenMirroringVideoInfo(this);
64 RegisterStateChangedEvent();
73 /// Occurs when the state is changed.
75 public event EventHandler<ScreenMirroringStateChangedEventArgs> StateChanged;
78 /// Occurs when an error occurs.
80 public event EventHandler<ScreenMirroringErrorOccurredEventArgs> ErrorOccurred;
82 #region Display support
84 private Display _display;
86 private void DetachDisplay()
90 _display.SetOwner(null);
95 private void SetDisplay(Display display)
99 throw new ArgumentNullException(nameof(Display));
102 display.SetOwner(this);
103 display.ApplyTo(this).ThrowIfError("Failed to set display.");
108 ScreenMirroringErrorCode IDisplayable<ScreenMirroringErrorCode>.ApplyEvasDisplay(DisplayType type,
109 ElmSharp.EvasObject evasObject)
111 Debug.Assert(Enum.IsDefined(typeof(DisplayType), type));
113 return Native.SetDisplay(Handle, (int)type, evasObject);
118 /// Gets the negotiated audio info.
120 public ScreenMirroringAudioInfo AudioInfo { get; }
123 /// Gets the negotiated video info.
125 public ScreenMirroringVideoInfo VideoInfo { get; }
127 private bool IsConnected
131 return _state.IsOneOf(ScreenMirroringState.Connected, ScreenMirroringState.Playing,
132 ScreenMirroringState.Paused);
136 internal void ThrowIfNotConnected()
140 if (IsConnected == false)
142 throw new InvalidOperationException("ScreenMirroring is not connected.");
147 /// Prepares the screen mirroring with the specified display.
150 /// The state must be <see cref="ScreenMirroringState.Idle"/>.\n
152 /// All supported resolutions will be candidates.
154 /// <param name="display">The display where the mirroring will be played on.</param>
155 /// <exception cref="ArgumentException">
156 /// <paramref name="display"/> has already been assigned to another.
158 /// <exception cref="ArgumentNullException"><paramref name="display"/> is null.</exception>
159 /// <exception cref="InvalidOperationException">
160 /// The current state is not in the valid.\n
162 /// An internal error occurs.
164 /// <exception cref="ObjectDisposedException">The <see cref="ScreenMirroring"/> has already been disposed.</exception>
165 public void Prepare(Display display)
167 PrepareCore(display, (ScreenMirroringResolutions)0);
171 /// Prepares the screen mirroring with the specified display and resolutions.
174 /// The state must be <see cref="ScreenMirroringState.Idle"/>.
176 /// <param name="display">The display where the mirroring will be played on.</param>
177 /// <param name="resolutions">The desired resolutions.</param>
178 /// <exception cref="ArgumentException">
179 /// <paramref name="resolutions"/> contain invalid flags.\n
181 /// <paramref name="display"/> has already been assigned to another.
183 /// <exception cref="ArgumentNullException"><paramref name="display"/> is null.</exception>
184 /// <exception cref="InvalidOperationException">
185 /// The current state is not in the valid.\n
187 /// An internal error occurs.
189 /// <exception cref="ObjectDisposedException">The <see cref="ScreenMirroring"/> has already been disposed.</exception>
190 public void Prepare(Display display, ScreenMirroringResolutions resolutions)
192 ValidationUtil.ValidateFlagsEnum(resolutions, (ScreenMirroringResolutions)((1 << 7) - 1), nameof(resolutions));
194 PrepareCore(display, resolutions);
197 private void PrepareCore(Display display, ScreenMirroringResolutions resolutions)
199 ValidateState(ScreenMirroringState.Idle);
201 Native.SetResolution(Handle, resolutions).ThrowIfError("Failed to set resolutions.");
207 Native.Prepare(Handle).ThrowIfError("Failed to prepare.");
217 /// Creates the connection and ready for receiving data from a mirroring source.
219 /// <param name="sourceIp">The source ip address to connect.</param>
221 /// The state must be <see cref="ScreenMirroringState.Prepared"/> state by
222 /// <see cref="Prepare(Display, ScreenMirroringResolutions)"/>.
224 /// <returns>A task that represents the asynchronous operation.</returns>
225 /// <privilege>http://tizen.org/privilege/internet</privilege>
226 /// <exception cref="ArgumentNullException"><paramref name="sourceIp"/> is null.</exception>
227 /// <exception cref="InvalidOperationException">
228 /// The current state is not in the valid.\n
230 /// An internal error occurs.
232 /// <exception cref="ArgumentException"><paramref name="sourceIp"/> is a zero-length string, contains only white space.</exception>
233 /// <exception cref="ObjectDisposedException">The <see cref="ScreenMirroring"/> has already been disposed.</exception>
234 /// <exception cref="UnauthorizedAccessException">Caller does not have required permission.</exception>
235 public Task ConnectAsync(string sourceIp)
237 if (sourceIp == null)
239 throw new ArgumentNullException(nameof(sourceIp));
242 if (string.IsNullOrWhiteSpace(sourceIp))
244 throw new ArgumentException($"{nameof(sourceIp)} is a zero-length string.", nameof(sourceIp));
247 ValidateState(ScreenMirroringState.Prepared);
249 Native.SetIpAndPort(Handle, sourceIp, Port.ToString()).ThrowIfError("Failed to set ip.");
251 var tcs = new TaskCompletionSource<bool>();
253 Task.Factory.StartNew(() =>
255 Native.Connect(Handle).ThrowIfError("Failed to connect");
263 /// Starts mirroring from the source.
266 /// The state must be <see cref="ScreenMirroringState.Connected"/> state by
267 /// <see cref="ConnectAsync(string)"/>.
269 /// <returns>A task that represents the asynchronous operation.</returns>
270 /// <privilege>http://tizen.org/privilege/internet</privilege>
271 /// <exception cref="InvalidOperationException">
272 /// The current state is not in the valid.\n
274 /// An internal error occurs.
276 /// <exception cref="ObjectDisposedException">The <see cref="ScreenMirroring"/> has already been disposed.</exception>
277 /// <exception cref="UnauthorizedAccessException">Caller does not have required permission.</exception>
278 public Task StartAsync()
280 ValidateState(ScreenMirroringState.Connected);
282 var tcs = new TaskCompletionSource<bool>();
284 Task.Factory.StartNew(() =>
286 Native.StartAsync(Handle).ThrowIfError("Failed to start.");
287 tcs.TrySetResult(true);
294 /// Pauses mirroring from the source.
297 /// The state must be <see cref="ScreenMirroringState.Playing"/> state by
298 /// <see cref="StartAsync"/>.
300 /// <returns>A task that represents the asynchronous operation.</returns>
301 /// <privilege>http://tizen.org/privilege/internet</privilege>
302 /// <exception cref="InvalidOperationException">
303 /// The current state is not in the valid.\n
305 /// An internal error occurs.
307 /// <exception cref="ObjectDisposedException">The <see cref="ScreenMirroring"/> has already been disposed.</exception>
308 /// <exception cref="UnauthorizedAccessException">Caller does not have required permission.</exception>
309 public Task PauseAsync()
311 ValidateState(ScreenMirroringState.Playing);
313 var tcs = new TaskCompletionSource<bool>();
315 Task.Factory.StartNew(() =>
317 Native.PauseAsync(Handle).ThrowIfError("Failed to prepare.");
318 tcs.TrySetResult(true);
325 /// Resumes mirroring from the source.
328 /// The state must be <see cref="ScreenMirroringState.Paused"/> state by
329 /// <see cref="PauseAsync"/>.
331 /// <returns>A task that represents the asynchronous operation.</returns>
332 /// <privilege>http://tizen.org/privilege/internet</privilege>
333 /// <exception cref="InvalidOperationException">
334 /// The current state is not in the valid.\n
336 /// An internal error occurs.
338 /// <exception cref="ObjectDisposedException">The <see cref="ScreenMirroring"/> has already been disposed.</exception>
339 /// <exception cref="UnauthorizedAccessException">Caller does not have required permission.</exception>
340 public Task ResumeAsync()
342 ValidateState(ScreenMirroringState.Paused);
344 var tcs = new TaskCompletionSource<bool>();
346 Task.Factory.StartNew(() =>
348 Native.ResumeAsync(Handle).ThrowIfError("Failed to resume.");
349 tcs.TrySetResult(true);
356 /// Disconnects from the source.
359 /// The state must be <see cref="ScreenMirroringState.Connected"/>,
360 /// <see cref="ScreenMirroringState.Playing"/> or <see cref="ScreenMirroringState.Paused"/>.
362 /// <privilege>http://tizen.org/privilege/internet</privilege>
363 /// <exception cref="InvalidOperationException">
364 /// The current state is not in the valid.\n
366 /// An internal error occurs.
368 /// <exception cref="ObjectDisposedException">The <see cref="ScreenMirroring"/> has already been disposed.</exception>
369 /// <exception cref="UnauthorizedAccessException">Caller does not have required permission.</exception>
370 public void Disconnect()
372 ValidateState(ScreenMirroringState.Connected, ScreenMirroringState.Playing,
373 ScreenMirroringState.Paused);
375 Native.Disconnect(Handle).ThrowIfError("Failed to disconnect.");
379 /// Unprepares the screen mirroring.
382 /// The state must be <see cref="ScreenMirroringState.Prepared"/>,
383 /// or <see cref="ScreenMirroringState.Disconnected"/>.
385 /// <exception cref="InvalidOperationException">
386 /// The current state is not in the valid.\n
388 /// An internal error occurs.
390 /// <exception cref="ObjectDisposedException">The <see cref="ScreenMirroring"/> has already been disposed.</exception>
391 public void Unprepare()
393 ValidateState(ScreenMirroringState.Prepared, ScreenMirroringState.Disconnected);
395 Native.Unprepare(Handle).ThrowIfError("Failed to reset.");
400 private void ThrowIfDisposed()
404 throw new ObjectDisposedException(nameof(ScreenMirroring));
409 /// Releases all resource used by the <see cref="ScreenMirroring"/> object.
412 /// Call <see cref="Dispose()"/> when you are finished using the <see cref="ScreenMirroring"/>.
413 /// The <see cref="Dispose()"/> method leaves the <see cref="ScreenMirroring"/> in an unusable
414 /// state. After calling <see cref="Dispose"()/>, you must release all references to the
415 /// <see cref="ScreenMirroring"/> so the garbage collector can reclaim the memory that the
416 /// <see cref="ScreenMirroring"/> was occupying.
418 public void Dispose()
421 GC.SuppressFinalize(this);
425 /// Releases the resources used by the ScreenMirroring.
427 /// <param name="disposing">
428 /// true to release both managed and unmanaged resources; false to release only unmanaged resources.
430 protected virtual void Dispose(bool disposing)
436 if (_handle != IntPtr.Zero)
438 Native.Destroy(_handle);
439 _handle = IntPtr.Zero;
446 private Native.StateChangedCallback _stateChangedCallback;
448 private void RegisterStateChangedEvent()
450 _stateChangedCallback = (_, state, error) =>
452 var prevState = _state.Value;
454 _state.Value = state;
456 if (prevState != state)
458 StateChanged?.Invoke(this, new ScreenMirroringStateChangedEventArgs(state));
462 if (error != ScreenMirroringErrorCode.None)
464 ErrorOccurred?.Invoke(this, new ScreenMirroringErrorOccurredEventArgs(
465 ScreenMirroringError.InvalidOperation));
469 Native.SetStateChangedCb(Handle, _stateChangedCallback).
470 ThrowIfError("Failed to initialize StateChanged event.");
473 private void ValidateState(params ScreenMirroringState[] required)
475 Debug.Assert(required.Length > 0);
479 throw new ObjectDisposedException(nameof(ScreenMirroring));
482 var curState = _state.Value;
483 if (!required.Contains(curState))
485 throw new InvalidOperationException($"The screen mirroring is not in a valid state. " +
486 $"Current State : { curState }, Valid State : { string.Join(", ", required) }.");
492 internal class AtomicState
498 _value = (int)ScreenMirroringState.Idle;
501 public ScreenMirroringState Value
505 return (ScreenMirroringState)Interlocked.CompareExchange(ref _value, 0, 0);
509 Interlocked.Exchange(ref _value, (int)value);
513 public bool IsOneOf(params ScreenMirroringState[] states)
515 return states.Contains(Value);