forked from UnigramDev/Unigram
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVoipGroupManager.cpp
More file actions
523 lines (432 loc) · 19 KB
/
Copy pathVoipGroupManager.cpp
File metadata and controls
523 lines (432 loc) · 19 KB
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
#include "pch.h"
#include "VoipGroupManager.h"
#if __has_include("VoipGroupManager.g.cpp")
#include "VoipGroupManager.g.cpp"
#endif
#include "VoipVideoCapture.h"
#include "VoipScreenCapture.h"
#include "VoipVideoOutputSink.h"
#include "GroupNetworkStateChangedEventArgs.h"
#include "BroadcastPartRequestedEventArgs.h"
#include "BroadcastTimeRequestedEventArgs.h"
#include "MediaChannelDescriptionsRequestedEventArgs.h"
#include "StaticThreads.h"
namespace winrt::Telegram::Native::Calls::implementation
{
VoipGroupManager::VoipGroupManager(VoipGroupDescriptor descriptor)
{
// Sharing a screen runs a second manager alongside the main one, and both would
// otherwise interleave into the same file.
auto logPath = Windows::Storage::ApplicationData::Current().LocalFolder().Path()
+ (VoipVideoContentType::Screencast == descriptor.VideoContentType()
? hstring(L"\\tgcalls_screencast.txt")
: hstring(L"\\tgcalls_group.txt"));
tgcalls::GroupConfig config = tgcalls::GroupConfig{
true,
logPath.data()
};
tgcalls::GroupInstanceDescriptor impl = tgcalls::GroupInstanceDescriptor
{
.threads = tgcalls::StaticThreads::getThreads(),
.config = config,
.networkStateUpdated = [weakThis{ get_weak() }](tgcalls::GroupNetworkState state) {
if (auto strongThis = weakThis.get())
{
return strongThis->OnNetworkStateUpdated(state);
}
},
.audioLevelsUpdated = [weakThis{ get_weak() }](tgcalls::GroupLevelsUpdate const& levels) {
if (auto strongThis = weakThis.get())
{
return strongThis->OnAudioLevelsUpdated(levels);
}
},
.initialInputDeviceId = winrt::to_string(descriptor.AudioInputId()),
.initialOutputDeviceId = winrt::to_string(descriptor.AudioOutputId()),
.requestCurrentTime = [weakThis{ get_weak() }](std::function<void(int64_t)> done) {
if (auto strongThis = weakThis.get())
{
return strongThis->OnRequestCurrentTime(done);
}
},
.requestAudioBroadcastPart = [weakThis{ get_weak() }](int64_t time, int64_t period, std::function<void(tgcalls::BroadcastPart&&)> done) {
if (auto strongThis = weakThis.get())
{
return strongThis->OnRequestAudioBroadcastPart(time, period, done);
}
},
.requestVideoBroadcastPart = [weakThis{ get_weak() }](int64_t time, int64_t period, int32_t channel, tgcalls::VideoChannelDescription::Quality quality, std::function<void(tgcalls::BroadcastPart&&)> done) {
if (auto strongThis = weakThis.get())
{
return strongThis->OnRequestVideoBroadcastPart(time, period, channel, quality, done);
}
},
.videoContentType = (tgcalls::VideoContentType)descriptor.VideoContentType(),
.initialEnableNoiseSuppression = m_isNoiseSuppressionEnabled = descriptor.IsNoiseSuppressionEnabled(),
};
if (descriptor.IsConference())
{
impl.isConference = true;
impl.e2eEncryptDecrypt = [weakThis{ get_weak() }](std::vector<uint8_t> const& message, int64_t userId, bool encrypt, int32_t channelId) {
if (auto strongThis = weakThis.get())
{
return strongThis->OnE2EEncryptDecrypt(message, userId, encrypt, channelId);
}
};
impl.requestMediaChannelDescriptions = [weakThis{ get_weak() }](std::vector<uint32_t> const& ssrcs, std::function<void(std::vector<tgcalls::MediaChannelDescription>&&)> done) {
if (auto strongThis = weakThis.get())
{
return strongThis->OnRequestMediaChannelDescriptions(ssrcs, done);
}
};
}
impl.videoCapture = GetVideoCaptureImpl(descriptor.VideoCapture());
m_impl = std::make_unique<tgcalls::GroupInstanceCustomImpl>(std::move(impl));
if (VoipVideoContentType::Screencast == descriptor.VideoContentType())
{
m_isScreencast = true;
auto audioProcessId = descriptor.AudioProcessId();
if (audioProcessId == 0)
{
return;
}
m_loopback = winrt::make_self<VoipLoopbackCapture>([weakThis{ get_weak() }](std::vector<uint8_t>&& samples) {
if (auto strongThis = weakThis.get())
{
strongThis->AddExternalAudioSamples(std::move(samples));
}
});
// -1 means everything this process is not rendering, i.e. the whole system
// minus ourselves; anything else is that process and its children.
auto result = audioProcessId == -1
? m_loopback->Start(GetCurrentProcessId(), false)
: m_loopback->Start(static_cast<uint32_t>(audioProcessId), true);
if (FAILED(result))
{
// Process loopback is unavailable on older builds; share the screen
// without its audio rather than failing the whole capture.
m_loopback = nullptr;
return;
}
IsMuted(false);
}
}
VoipGroupManager::~VoipGroupManager()
{
Stop();
}
void VoipGroupManager::Stop()
{
if (m_loopback)
{
m_loopback->Stop();
m_loopback = nullptr;
}
if (m_impl)
{
m_impl->stop([]() {});
m_impl.reset();
}
}
void VoipGroupManager::SetConnectionMode(VoipGroupConnectionMode connectionMode, bool keepBroadcastIfWasEnabled, bool isUnifiedBroadcast)
{
if (m_impl)
{
m_impl->setConnectionMode((tgcalls::GroupConnectionMode)connectionMode, keepBroadcastIfWasEnabled, isUnifiedBroadcast);
}
}
void VoipGroupManager::EmitJoinPayload(EmitJsonPayloadDelegate completion)
{
if (m_impl)
{
m_impl->emitJoinPayload([completion](auto const& payload) {
completion(payload.audioSsrc, winrt::to_hstring(payload.json));
});
}
// Nothing to join with once the instance is gone. Completing with an empty
// payload only got the caller as far as a join the server would reject, and it
// did it on this thread rather than the one the success path answers on.
}
void VoipGroupManager::SetJoinResponsePayload(hstring payload)
{
if (m_impl)
{
m_impl->setJoinResponsePayload(winrt::to_string(payload));
}
}
void VoipGroupManager::RemoveSsrcs(IVector<int32_t> ssrcs)
{
if (m_impl)
{
m_impl->removeSsrcs(std::vector<uint32_t>(ssrcs.begin(), ssrcs.end()));
}
}
void VoipGroupManager::AddIncomingVideoOutput(hstring endpointId, winrt::Telegram::Native::Calls::VoipVideoOutputSink sink)
{
if (m_impl && sink)
{
auto implementation = winrt::get_self<VoipVideoOutputSink>(sink);
m_impl->addIncomingVideoOutput(winrt::to_string(endpointId), implementation->Sink());
}
}
bool VoipGroupManager::IsMuted()
{
return m_isMuted;
}
void VoipGroupManager::IsMuted(bool value)
{
if (m_impl)
{
m_impl->setIsMuted(m_isMuted = value);
}
}
bool VoipGroupManager::IsNoiseSuppressionEnabled()
{
return m_isNoiseSuppressionEnabled;
}
void VoipGroupManager::IsNoiseSuppressionEnabled(bool value)
{
if (m_impl)
{
m_impl->setIsNoiseSuppressionEnabled(m_isNoiseSuppressionEnabled = value);
}
}
void VoipGroupManager::SetAudioOutputDevice(hstring id)
{
if (m_impl)
{
m_impl->setAudioOutputDevice(winrt::to_string(id));
}
}
void VoipGroupManager::SetAudioInputDevice(hstring id)
{
if (m_impl)
{
m_impl->setAudioInputDevice(winrt::to_string(id));
}
}
void VoipGroupManager::SetVideoCapture(Telegram::Native::Calls::VoipCaptureBase videoCapture)
{
if (m_impl)
{
m_impl->setVideoCapture(GetVideoCaptureImpl(videoCapture));
}
}
void VoipGroupManager::AddExternalAudioSamples(std::vector<uint8_t>&& samples)
{
if (m_impl)
{
m_impl->addExternalAudioSamples(std::move(samples));
}
}
void VoipGroupManager::SetVolume(int32_t ssrc, double volume)
{
if (m_impl && ssrc)
{
m_impl->setVolume(ssrc, volume);
}
}
void VoipGroupManager::SetRequestedVideoChannels(IVector<VoipVideoChannelInfo> descriptions)
{
if (m_impl == nullptr)
{
return;
}
auto impl = std::vector<tgcalls::VideoChannelDescription>();
impl.reserve(descriptions.Size());
for (const VoipVideoChannelInfo& x : descriptions)
{
tgcalls::VideoChannelDescription item;
item.audioSsrc = x.AudioSource();
item.endpointId = winrt::to_string(x.EndpointId());
item.userId = x.ParticipantId();
item.minQuality = (tgcalls::VideoChannelDescription::Quality)x.MinQuality();
item.maxQuality = (tgcalls::VideoChannelDescription::Quality)x.MaxQuality();
for (const VoipVideoSourceGroup& group : x.SourceGroups())
{
tgcalls::MediaSsrcGroup groupImpl;
groupImpl.semantics = winrt::to_string(group.Semantics());
groupImpl.ssrcs = vector_to_unmanaged<uint32_t, int32_t>(group.SourceIds());
item.ssrcGroups.push_back(std::move(groupImpl));
}
impl.push_back(std::move(item));
}
m_impl->setRequestedVideoChannels(std::move(impl));
}
void VoipGroupManager::OnNetworkStateUpdated(tgcalls::GroupNetworkState state)
{
auto args = winrt::make_self<GroupNetworkStateChangedEventArgs>(state.isConnected, state.isTransitioningFromBroadcastToRtc);
m_networkStateUpdated(*this, *args);
}
void VoipGroupManager::OnAudioLevelsUpdated(tgcalls::GroupLevelsUpdate const& levels)
{
// Filled first and handed over whole: appending to the IVector would be a COM
// call per participant, and this arrives about ten times a second for the whole
// length of the call.
auto participants = std::vector<winrt::Telegram::Native::Calls::VoipGroupParticipant>();
participants.reserve(levels.updates.size());
for (const tgcalls::GroupLevelUpdate& x : levels.updates)
{
participants.push_back(winrt::Telegram::Native::Calls::VoipGroupParticipant{
.AudioSource = static_cast<int32_t>(x.ssrc),
.Level = x.value.level,
.IsSpeaking = x.value.voice,
.IsMuted = x.value.isMuted
});
}
m_audioLevelsUpdated(*this, winrt::single_threaded_vector(std::move(participants)));
}
std::shared_ptr<tgcalls::BroadcastPartTask> VoipGroupManager::OnRequestCurrentTime(std::function<void(int64_t)> done)
{
auto task = std::make_shared<BroadcastTimeTaskImpl>(std::move(done));
auto args = winrt::make_self<BroadcastTimeRequestedEventArgs>([task](int64_t time) { task->done(time); });
m_broadcastTimeRequested(*this, *args);
return task;
}
std::shared_ptr<tgcalls::BroadcastPartTask> VoipGroupManager::OnRequestVideoBroadcastPart(int64_t time, int64_t period, int32_t channel, tgcalls::VideoChannelDescription::Quality quality, std::function<void(tgcalls::BroadcastPart&&)> done)
{
int scale = 0;
switch (period)
{
case 1000: scale = 0; break;
case 500: scale = 1; break;
case 250: scale = 2; break;
case 125: scale = 3; break;
}
VoipVideoChannelQuality qualityImpl = VoipVideoChannelQuality::Thumbnail;
switch (quality)
{
case tgcalls::VideoChannelDescription::Quality::Thumbnail:
qualityImpl = VoipVideoChannelQuality::Thumbnail;
break;
case tgcalls::VideoChannelDescription::Quality::Medium:
qualityImpl = VoipVideoChannelQuality::Medium;
break;
case tgcalls::VideoChannelDescription::Quality::Full:
qualityImpl = VoipVideoChannelQuality::Full;
break;
}
auto task = std::make_shared<BroadcastPartTaskImpl>(std::move(done));
auto args = winrt::make_self<VideoBroadcastPartRequestedEventArgs>(scale, time, channel, qualityImpl,
[task](int64_t time, int64_t response, IVector<uint8_t> data) { task->done(time, response, data); });
m_videoBroadcastPartRequested(*this, *args);
return task;
}
std::shared_ptr<tgcalls::BroadcastPartTask> VoipGroupManager::OnRequestAudioBroadcastPart(int64_t time, int64_t period, std::function<void(tgcalls::BroadcastPart&&)> done)
{
int scale = 0;
switch (period)
{
case 1000: scale = 0; break;
case 500: scale = 1; break;
case 250: scale = 2; break;
case 125: scale = 3; break;
}
auto task = std::make_shared<BroadcastPartTaskImpl>(std::move(done));
auto args = winrt::make_self<AudioBroadcastPartRequestedEventArgs>(scale, time,
[task](int64_t time, int64_t response, IVector<uint8_t> data) { task->done(time, response, data); });
m_audioBroadcastPartRequested(*this, *args);
return task;
}
std::shared_ptr<tgcalls::RequestMediaChannelDescriptionTask> VoipGroupManager::OnRequestMediaChannelDescriptions(const std::vector<uint32_t>& ssrcs, std::function<void(std::vector<tgcalls::MediaChannelDescription>&&)> done)
{
auto audioSourceIds = winrt::single_threaded_vector<uint32_t>(std::vector<uint32_t>(ssrcs));
auto task = std::make_shared<RequestMediaChannelDescriptionTaskImpl>(std::move(done));
auto args = winrt::make_self<MediaChannelDescriptionsRequestedEventArgs>(audioSourceIds,
[task](IVector<VoipMediaChannelDescription> participants) { task->done(participants); });
m_mediaChannelDescriptionsRequested(*this, *args);
return task;
}
std::vector<uint8_t> VoipGroupManager::OnE2EEncryptDecrypt(std::vector<uint8_t> const& message, int64_t userId, bool encrypt, int32_t unencryptedPrefixSize)
{
// Taken by copy rather than held: this runs per frame on a media thread, and the
// managed delegates block on a TDLib round trip. The lock covers only the read.
EncryptGroupCallDataDelegate encryptData{ nullptr };
DecryptGroupCallDataDelegate decryptData{ nullptr };
{
std::lock_guard const guard(m_encryptLock);
encryptData = m_encryptData;
decryptData = m_decryptData;
}
// An empty result is how tgcalls is told the frame failed and must be dropped.
// Returning the input untouched would put plaintext on the wire when encrypting,
// and hand ciphertext to the decoder as if it were plaintext when decrypting.
if (encrypt ? encryptData == nullptr : decryptData == nullptr)
{
return {};
}
// A view over the caller's buffer, so nothing is copied on this side: the
// projection marshals it straight into the managed array.
auto view = array_view<uint8_t const>(message.data(), message.data() + message.size());
auto data = encrypt
? encryptData(m_isScreencast ? VoipDataChannel::ScreenSharing : VoipDataChannel::Main, view, unencryptedPrefixSize)
: decryptData(userId, view);
return std::vector<uint8_t>(data.begin(), data.end());
}
void VoipGroupManager::SetEncryptDecrypt(EncryptGroupCallDataDelegate encryptData, DecryptGroupCallDataDelegate decryptData)
{
std::lock_guard const guard(m_encryptLock);
m_encryptData = encryptData;
m_decryptData = decryptData;
}
winrt::event_token VoipGroupManager::NetworkStateUpdated(Windows::Foundation::TypedEventHandler<
winrt::Telegram::Native::Calls::VoipGroupManager,
winrt::Telegram::Native::Calls::GroupNetworkStateChangedEventArgs> const& value)
{
return m_networkStateUpdated.add(value);
}
void VoipGroupManager::NetworkStateUpdated(winrt::event_token const& token)
{
m_networkStateUpdated.remove(token);
}
winrt::event_token VoipGroupManager::AudioLevelsUpdated(Windows::Foundation::TypedEventHandler<
winrt::Telegram::Native::Calls::VoipGroupManager,
IVector<winrt::Telegram::Native::Calls::VoipGroupParticipant>> const& value)
{
return m_audioLevelsUpdated.add(value);
}
void VoipGroupManager::AudioLevelsUpdated(winrt::event_token const& token)
{
m_audioLevelsUpdated.remove(token);
}
winrt::event_token VoipGroupManager::AudioBroadcastPartRequested(Windows::Foundation::TypedEventHandler<
winrt::Telegram::Native::Calls::VoipGroupManager,
winrt::Telegram::Native::Calls::AudioBroadcastPartRequestedEventArgs> const& value)
{
return m_audioBroadcastPartRequested.add(value);
}
void VoipGroupManager::AudioBroadcastPartRequested(winrt::event_token const& token)
{
m_audioBroadcastPartRequested.remove(token);
}
winrt::event_token VoipGroupManager::VideoBroadcastPartRequested(Windows::Foundation::TypedEventHandler<
winrt::Telegram::Native::Calls::VoipGroupManager,
winrt::Telegram::Native::Calls::VideoBroadcastPartRequestedEventArgs> const& value)
{
return m_videoBroadcastPartRequested.add(value);
}
void VoipGroupManager::VideoBroadcastPartRequested(winrt::event_token const& token)
{
m_videoBroadcastPartRequested.remove(token);
}
winrt::event_token VoipGroupManager::BroadcastTimeRequested(Windows::Foundation::TypedEventHandler<
winrt::Telegram::Native::Calls::VoipGroupManager,
winrt::Telegram::Native::Calls::BroadcastTimeRequestedEventArgs> const& value)
{
return m_broadcastTimeRequested.add(value);
}
void VoipGroupManager::BroadcastTimeRequested(winrt::event_token const& token)
{
m_broadcastTimeRequested.remove(token);
}
winrt::event_token VoipGroupManager::MediaChannelDescriptionsRequested(Windows::Foundation::TypedEventHandler<
winrt::Telegram::Native::Calls::VoipGroupManager,
winrt::Telegram::Native::Calls::MediaChannelDescriptionsRequestedEventArgs> const& value)
{
return m_mediaChannelDescriptionsRequested.add(value);
}
void VoipGroupManager::MediaChannelDescriptionsRequested(winrt::event_token const& token)
{
m_mediaChannelDescriptionsRequested.remove(token);
}
}