1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media.Imaging;
using Tango.Core;
using Tango.Core.DI;
using Tango.Core.Threading;
using Tango.FSE.Common.Connection;
using Tango.FSE.Common.Notifications;
using Tango.FSE.Common.RemoteDesktop;
using Tango.PMR;
using Tango.PMR.Integration;
using Tango.RemoteDesktop.Frames;
using Tango.RemoteDesktop.Network;
using Tango.Transport;
using Tango.WebRTC;
namespace Tango.FSE.UI.RemoteDesktop
{
public class DefaultRemoteDesktopProvider : ExtendedObject, IRemoteDesktopProvider
{
private class MouseMovement
{
public Point Location { get; set; }
public Size ViewSize { get; set; }
}
private IMachineProvider _machineProvider;
private RasterFrame _currentFrame;
private MemoryStream _currentStream;
private Size? _frameSize;
private IntervalMessageDispatcher<StartRemoteDesktopSessionResponse> _frameDispatcher;
private Thread _mouseMoveThread;
private ProducerConsumerQueue<MouseMovement> _mouseMovements;
private WebRtcClient _webRtcClient;
private List<IceCandidate> _iceCandidates;
private bool _answerReceived;
#region Events
public event EventHandler<DesktopFrameReceivedEventArgs> FrameReceived;
#endregion
#region Properties
[TangoInject]
private INotificationProvider NotificationProvider { get; set; }
private bool _inSession;
public bool InSession
{
get { return _inSession; }
set { _inSession = value; RaisePropertyChangedAuto(); RaisePropertyChanged(nameof(CanStartSession)); }
}
public bool EnableWebRtc { get; set; }
private bool _isWebRtcActive;
public bool IsWebRtcActive
{
get { return _isWebRtcActive; }
set
{
if (_isWebRtcActive != value)
{
_isWebRtcActive = value;
RaisePropertyChangedAuto();
if (_isWebRtcActive)
{
LogManager.Log("WebRTC is now active.");
}
}
}
}
public TimeSpan MouseMoveInterval { get; set; }
public bool CanStartSession
{
get { return _machineProvider.IsConnected && !InSession; }
}
#endregion
#region Constructors
public DefaultRemoteDesktopProvider()
{
_iceCandidates = new List<IceCandidate>();
MouseMoveInterval = TimeSpan.FromMilliseconds(100);
EnableWebRtc = true;
}
public DefaultRemoteDesktopProvider(IMachineProvider machineProvider) : this()
{
_machineProvider = machineProvider;
_machineProvider.MachineConnected += (_, __) =>
{
InSession = false;
};
_machineProvider.MachineDisconnected += (_, __) =>
{
InSession = false;
OnFrameReceived(null);
};
//_machineProvider.MachineOperator.RequestReceived += MachineOperator_RequestReceived;
_machineProvider.MachineOperator.RegisterRequestHandler<WebRtcIceCandidateRequest>(OnIceCandidateRequestReceived);
}
private async void OnIceCandidateRequestReceived(WebRtcIceCandidateRequest request, string token)
{
LogManager.Log("Ice candidate request received from the remote peer.");
await _machineProvider.MachineOperator.SendGenericResponse(new WebRtcIceCandidateResponse() { }, token);
LogManager.Log("Adding ice candidate...");
_webRtcClient.AddIceCandidate(request.IceCandidate);
LogManager.Log("Ice candidate added.");
}
#endregion
//private async void MachineOperator_RequestReceived(object sender, PMR.Common.MessageContainer container)
//{
// if (container.Type == PMR.Common.MessageType.GenericRequest)
// {
// var message = MessageFactory.ExtractMessageFromContainer(container);
// var type = Type.GetType((message as GenericRequest).Type);
// if (type == typeof(WebRtcIceCandidateRequest))
// {
// }
// }
//}
#region Start/Stop Session
public async Task StartSession()
{
TaskCompletionSource<bool> completionSource = new TaskCompletionSource<bool>();
if (!CanStartSession)
{
throw new InvalidOperationException("Unable to start a remote desktop session at the moment.");
}
if (!InSession)
{
LogManager.Log("Starting remote desktop session...");
_iceCandidates.Clear();
_answerReceived = false;
InSession = true;
var taskItem = NotificationProvider.PushTaskItem("Starting remote desktop session...");
await Task.Delay(2000);
if (_frameDispatcher != null)
{
_frameDispatcher.Dispose();
}
_frameDispatcher = new IntervalMessageDispatcher<StartRemoteDesktopSessionResponse>(OnRemoteDesktopResponse);
_frameDispatcher.Start();
bool taskCompleted = false;
_machineProvider.MachineOperator.SendGenericContinuousRequest<StartRemoteDesktopSessionRequest, StartRemoteDesktopSessionResponse>(new StartRemoteDesktopSessionRequest() { }, new TransportContinuousRequestConfig()
{
Timeout = TimeSpan.FromSeconds(10),
ShouldLog = true
}).Subscribe((response) =>
{
if (!taskCompleted)
{
taskCompleted = true;
taskItem.Dispose();
completionSource.SetResult(true);
if (EnableWebRtc)
{
LogManager.Log("WebRTC enabled. Starting WebRTC...");
StartWebRTC();
}
}
_frameDispatcher.Push(response);
}, (ex) =>
{
if (!taskCompleted)
{
taskCompleted = true;
taskItem.Dispose();
completionSource.SetException(ex);
}
else if (InSession)
{
OnFailed(ex);
}
InSession = false;
}, () =>
{
InSession = false;
OnFrameReceived(null);
});
await completionSource.Task;
}
else
{
await Task.FromResult(true);
}
}
public async Task EndSession()
{
if (InSession)
{
using (NotificationProvider.PushTaskItem("Stopping remote desktop session..."))
{
LogManager.Log("Stopping remote desktop session...");
await Task.Delay(2000);
try
{
await _machineProvider.MachineOperator.SendGenericRequest<StopRemoteDesktopSessionRequest, StopRemoteDesktopSessionResponse>(new StopRemoteDesktopSessionRequest(), new TransportRequestConfig()
{
ShouldLog = true
});
LogManager.Log("Remote desktop session stopped.");
}
catch (Exception ex)
{
LogManager.Log(ex, "Error stopping the remote desktop session.");
}
DisposeWebRtc();
InSession = false;
}
}
}
#endregion
#region Virtual Methods
protected virtual void OnFrameReceived(BitmapSource source, DesktopFrameReceivedEventArgs.FrameOrigin origin = DesktopFrameReceivedEventArgs.FrameOrigin.WebSockets)
{
IsWebRtcActive = origin == DesktopFrameReceivedEventArgs.FrameOrigin.WebRTC;
if (InSession)
{
FrameReceived?.Invoke(this, new DesktopFrameReceivedEventArgs()
{
Source = source,
Origin = origin
});
}
}
#endregion
#region SignalR Response Received
private void OnRemoteDesktopResponse(StartRemoteDesktopSessionResponse response)
{
if (!InSession) return; //To stop frame delivery immediately.
if (response.Packet == null)
{
_frameDispatcher.Interval = 1000 / response.FrameRate;
return; //This is the first message with empty bitmap and only the frame rate.
}
try
{
if (!response.Packet.IsPartial)
{
_currentFrame?.Dispose();
_currentStream?.Dispose();
_currentStream = new MemoryStream(response.Packet.Bitmap);
_currentFrame = new RasterFrame(new System.Drawing.Bitmap(_currentStream));
_frameSize = new Size(_currentFrame.Width, _currentFrame.Height);
}
else
{
using (MemoryStream ms = new MemoryStream(response.Packet.Bitmap))
{
var diffFrame = new RasterFrame(new System.Drawing.Bitmap(ms), response.Packet.PartialRegion.Left, response.Packet.PartialRegion.Top);
diffFrame.Apply(_currentFrame);
diffFrame.Dispose();
}
}
OnFrameReceived(_currentFrame.ToBitmapSource());
}
catch (Exception ex)
{
LogManager.Log(ex, "Error on remote desktop packet received.");
}
}
#endregion
#region Mouse/Keyboard
public async void MouseDown(MouseButton button, Point location, Size viewSize)
{
if (!InSession || _frameSize == null) return;
await _machineProvider.MachineOperator.SendGenericRequest<MouseStateRequest, MouseStateResponse>(new MouseStateRequest()
{
Button = button,
EventType = MouseEventType.Down,
Location = TranslateLocation(location, viewSize)
});
}
public async void MouseUp(MouseButton button, Point location, Size viewSize)
{
if (!InSession || _frameSize == null) return;
await _machineProvider.MachineOperator.SendGenericRequest<MouseStateRequest, MouseStateResponse>(new MouseStateRequest()
{
Button = button,
EventType = MouseEventType.Up,
Location = TranslateLocation(location, viewSize)
});
}
public void MouseMove(Point location, Size viewSize)
{
if (!InSession || _frameSize == null) return;
if (_mouseMoveThread == null)
{
_mouseMovements = new ProducerConsumerQueue<MouseMovement>();
_mouseMoveThread = new Thread(async () =>
{
while (InSession)
{
MouseMovement movement = _mouseMovements.BlockDequeue();
while (_mouseMovements.Count > 0)
{
movement = _mouseMovements.BlockDequeue();
}
try
{
await _machineProvider.MachineOperator.SendGenericRequest<MouseStateRequest, MouseStateResponse>(new MouseStateRequest()
{
Button = MouseButton.Left,
EventType = MouseEventType.Move,
Location = TranslateLocation(movement.Location, movement.ViewSize)
});
}
catch (Exception ex)
{
Debug.WriteLine($"Error on mouse move\n{ex.ToString()}");
}
Thread.Sleep(MouseMoveInterval);
}
_mouseMoveThread = null;
});
_mouseMoveThread.IsBackground = true;
_mouseMoveThread.Start();
}
_mouseMovements.BlockEnqueue(new MouseMovement()
{
Location = location,
ViewSize = viewSize,
});
}
public async void MouseDoubleClick(MouseButton button, Point location, Size viewSize)
{
if (!InSession || _frameSize == null) return;
await _machineProvider.MachineOperator.SendGenericRequest<MouseStateRequest, MouseStateResponse>(new MouseStateRequest()
{
Button = button,
EventType = MouseEventType.DoubleClick,
Location = TranslateLocation(location, viewSize)
});
}
private Point TranslateLocation(Point location, Size viewSize)
{
return new Point(
(location.X / viewSize.Width) * _frameSize.Value.Width,
(location.Y / viewSize.Height) * _frameSize.Value.Height);
}
public async void KeyboardDown(Key key, bool ctrlDown, bool shitDown, bool altDown)
{
if (!InSession || _frameSize == null) return;
await _machineProvider.MachineOperator.SendGenericRequest<KeyboardStateRequest, KeyboardStateResponse>(new KeyboardStateRequest()
{
EventType = KeyboardEventType.Down,
Key = key,
IsCtrlDown = ctrlDown,
IsShiftDown = shitDown,
IsAltDown = altDown,
});
}
public async void KeyboardUp(Key key, bool ctrlDown, bool shitDown, bool altDown)
{
if (!InSession || _frameSize == null) return;
await _machineProvider.MachineOperator.SendGenericRequest<KeyboardStateRequest, KeyboardStateResponse>(new KeyboardStateRequest()
{
EventType = KeyboardEventType.Up,
Key = key,
IsCtrlDown = ctrlDown,
IsShiftDown = shitDown,
IsAltDown = altDown,
});
}
#endregion
#region WebRTC
private async void StartWebRTC()
{
_webRtcClient = new WebRtcClient();
try
{
_webRtcClient.NewIceCandidate += _webRtcClient_NewIceCandidate;
_webRtcClient.FrameReceived += _webRtcClient_FrameReceived;
_webRtcClient.Disconnected += _webRtcClient_Disconnected;
LogManager.Log("Initializing WebRTC client...");
await _webRtcClient.Init();
LogManager.Log("Creating WebRTC offer...");
var offer = await _webRtcClient.CreateOffer();
LogManager.Log("Sending WebRTC offer...");
var response = await _machineProvider.MachineOperator.SendGenericRequest<WebRtcOfferRequest, WebRtcOfferResponse>(new WebRtcOfferRequest() { Offer = offer }, new TransportRequestConfig()
{
Timeout = TimeSpan.FromSeconds(30),
ShouldLog = true
});
LogManager.Log("WebRTC offer sent and responded with an answer. Setting WebRTC answer...");
_webRtcClient.SetAnswer(response.Answer);
_answerReceived = true;
foreach (var ice in _iceCandidates.ToList())
{
LogManager.Log("Sending existing ice candidate...");
await _machineProvider.MachineOperator.SendGenericRequest<WebRtcIceCandidateRequest, WebRtcIceCandidateResponse>(new WebRtcIceCandidateRequest() { IceCandidate = ice }, new TransportRequestConfig()
{
Timeout = TimeSpan.FromSeconds(30),
ShouldLog = true
});
}
}
catch (Exception ex)
{
LogManager.Log(ex, "Error starting WebRTC.");
}
}
private void DisposeWebRtc()
{
if (_webRtcClient != null)
{
LogManager.Log("Disposing WebRTC client...");
_webRtcClient.NewIceCandidate -= _webRtcClient_NewIceCandidate;
_webRtcClient.FrameReceived -= _webRtcClient_FrameReceived;
_webRtcClient.Disconnected -= _webRtcClient_Disconnected;
if (_webRtcClient != null)
{
try
{
_webRtcClient.Dispose();
_webRtcClient = null;
LogManager.Log("WebRTC client disposed.");
}
catch (Exception ex)
{
LogManager.Log(ex, "Error disposing WebRTC client.");
}
}
}
}
private void _webRtcClient_Disconnected(object sender, EventArgs e)
{
LogManager.Log("WebRTC client is now disconnected.");
IsWebRtcActive = false;
}
private async void _webRtcClient_NewIceCandidate(object sender, NewIceCandidateEventArgs e)
{
try
{
if (_answerReceived)
{
LogManager.Log("New WebRTC candidate available. Sending ice to remote peer...");
await _machineProvider.MachineOperator.SendGenericRequest<WebRtcIceCandidateRequest, WebRtcIceCandidateResponse>(new WebRtcIceCandidateRequest() { IceCandidate = e.IceCandidate }, new TransportRequestConfig()
{
Timeout = TimeSpan.FromSeconds(30),
ShouldLog = true
});
}
else
{
LogManager.Log("New WebRTC candidate available. Will be sent after an answer is received...");
_iceCandidates.Add(e.IceCandidate);
}
}
catch (Exception ex)
{
LogManager.Log(ex, "Error sending ice candidate to remote peer.");
}
}
private void _webRtcClient_FrameReceived(object sender, VideoFrameReceivedEventArgs e)
{
try
{
RasterFrame frame = new RasterFrame(e.Bitmap);
OnFrameReceived(frame.ToBitmapSource(), DesktopFrameReceivedEventArgs.FrameOrigin.WebRTC);
frame.Dispose();
}
catch (Exception ex)
{
LogManager.Log(ex, "Error on WebRTC client frame received.");
}
}
#endregion
#region OnFailed
private void OnFailed(Exception exception)
{
LogManager.Log(exception, "Remote desktop session failed.");
InSession = false;
OnFrameReceived(null);
DisposeWebRtc();
if (!(exception is TransporterDisconnectedException))
{
NotificationProvider.PushSnackbarItem(MessageType.Error, "Remote desktop session terminated unexpectedly.", true, null, TimeSpan.FromSeconds(5));
}
}
#endregion
}
}
|