-
Notifications
You must be signed in to change notification settings - Fork 333
/
Copy pathPeerConnection.c
2011 lines (1666 loc) · 82.4 KB
/
PeerConnection.c
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
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#define LOG_CLASS "PeerConnection"
#include "../Include_i.h"
static volatile ATOMIC_BOOL gKvsWebRtcInitialized = (SIZE_T) FALSE;
// Function to get access to the Singleton instance
PWebRtcClientContext getWebRtcClientInstance()
{
ENTERS();
static WebRtcClientContext w = {.pStunIpAddrCtx = NULL, .stunCtxlock = INVALID_MUTEX_VALUE, .contextRefCnt = 0, .isContextInitialized = FALSE};
ATOMIC_INCREMENT(&w.contextRefCnt);
LEAVES();
return &w;
}
VOID releaseHoldOnInstance(PWebRtcClientContext pWebRtcClientContext)
{
ENTERS();
ATOMIC_DECREMENT(&pWebRtcClientContext->contextRefCnt);
LEAVES();
}
STATUS createWebRtcClientInstance()
{
ENTERS();
PWebRtcClientContext pWebRtcClientContext = getWebRtcClientInstance();
STATUS retStatus = STATUS_SUCCESS;
BOOL locked = FALSE;
CHK_WARN(!ATOMIC_LOAD_BOOL(&pWebRtcClientContext->isContextInitialized), retStatus, "WebRtc client context already initialized, nothing to do");
CHK_ERR(!IS_VALID_MUTEX_VALUE(pWebRtcClientContext->stunCtxlock), retStatus, "Mutex seems to have been created already");
pWebRtcClientContext->stunCtxlock = MUTEX_CREATE(TRUE);
CHK_ERR(IS_VALID_MUTEX_VALUE(pWebRtcClientContext->stunCtxlock), STATUS_NULL_ARG, "Mutex creation failed");
MUTEX_LOCK(pWebRtcClientContext->stunCtxlock);
locked = TRUE;
CHK_WARN(pWebRtcClientContext->pStunIpAddrCtx == NULL, STATUS_INVALID_OPERATION, "STUN object already allocated");
pWebRtcClientContext->pStunIpAddrCtx = (PStunIpAddrContext) MEMCALLOC(1, SIZEOF(StunIpAddrContext));
CHK_ERR(pWebRtcClientContext->pStunIpAddrCtx != NULL, STATUS_NULL_ARG, "Memory allocation for WebRtc client object failed");
pWebRtcClientContext->pStunIpAddrCtx->expirationDuration = 2 * HUNDREDS_OF_NANOS_IN_AN_HOUR;
ATOMIC_STORE_BOOL(&pWebRtcClientContext->isContextInitialized, TRUE);
DLOGI("Initialized WebRTC Client instance");
CleanUp:
if (locked) {
MUTEX_UNLOCK(pWebRtcClientContext->stunCtxlock);
}
releaseHoldOnInstance(pWebRtcClientContext);
CHK_LOG_ERR(retStatus);
LEAVES();
return retStatus;
}
STATUS allocateSrtp(PKvsPeerConnection pKvsPeerConnection)
{
ENTERS();
DtlsKeyingMaterial dtlsKeyingMaterial;
STATUS retStatus = STATUS_SUCCESS;
BOOL locked = FALSE;
MEMSET(&dtlsKeyingMaterial, 0, SIZEOF(DtlsKeyingMaterial));
CHK(pKvsPeerConnection != NULL, STATUS_SUCCESS);
CHK_STATUS(dtlsSessionVerifyRemoteCertificateFingerprint(pKvsPeerConnection->pDtlsSession, pKvsPeerConnection->remoteCertificateFingerprint));
CHK_STATUS(dtlsSessionPopulateKeyingMaterial(pKvsPeerConnection->pDtlsSession, &dtlsKeyingMaterial));
MUTEX_LOCK(pKvsPeerConnection->pSrtpSessionLock);
locked = TRUE;
CHK_STATUS(initSrtpSession(pKvsPeerConnection->dtlsIsServer ? dtlsKeyingMaterial.clientWriteKey : dtlsKeyingMaterial.serverWriteKey,
pKvsPeerConnection->dtlsIsServer ? dtlsKeyingMaterial.serverWriteKey : dtlsKeyingMaterial.clientWriteKey,
dtlsKeyingMaterial.srtpProfile, &(pKvsPeerConnection->pSrtpSession)));
CleanUp:
if (locked) {
MUTEX_UNLOCK(pKvsPeerConnection->pSrtpSessionLock);
}
CHK_LOG_ERR(retStatus);
LEAVES();
return retStatus;
}
#ifdef ENABLE_DATA_CHANNEL
STATUS allocateSctpSortDataChannelsDataCallback(UINT64 customData, PHashEntry pHashEntry)
{
ENTERS();
STATUS retStatus = STATUS_SUCCESS;
PAllocateSctpSortDataChannelsData data = (PAllocateSctpSortDataChannelsData) customData;
PKvsDataChannel pKvsDataChannel = (PKvsDataChannel) pHashEntry->value;
CHK(customData != 0, STATUS_NULL_ARG);
pKvsDataChannel->channelId = data->currentDataChannelId;
CHK_STATUS(hashTablePut(data->pKvsPeerConnection->pDataChannels, pKvsDataChannel->channelId, (UINT64) pKvsDataChannel));
data->currentDataChannelId += 2;
CleanUp:
CHK_LOG_ERR(retStatus);
LEAVES();
return retStatus;
}
STATUS allocateSctp(PKvsPeerConnection pKvsPeerConnection)
{
ENTERS();
STATUS retStatus = STATUS_SUCCESS;
SctpSessionCallbacks sctpSessionCallbacks;
AllocateSctpSortDataChannelsData data;
UINT32 currentDataChannelId = 0;
UINT64 hashValue = 0;
PKvsDataChannel pKvsDataChannel = NULL;
CHK(pKvsPeerConnection != NULL, STATUS_NULL_ARG);
currentDataChannelId = (pKvsPeerConnection->dtlsIsServer) ? 1 : 0;
// Re-sort DataChannel hashmap using proper streamIds if we are offerer or answerer
data.currentDataChannelId = currentDataChannelId;
data.pKvsPeerConnection = pKvsPeerConnection;
data.unkeyedDataChannels = pKvsPeerConnection->pDataChannels;
CHK_STATUS(hashTableCreateWithParams(CODEC_HASH_TABLE_BUCKET_COUNT, CODEC_HASH_TABLE_BUCKET_LENGTH, &pKvsPeerConnection->pDataChannels));
CHK_STATUS(hashTableIterateEntries(data.unkeyedDataChannels, (UINT64) &data, allocateSctpSortDataChannelsDataCallback));
// Free unkeyed DataChannels
CHK_LOG_ERR(hashTableClear(data.unkeyedDataChannels));
CHK_LOG_ERR(hashTableFree(data.unkeyedDataChannels));
// Create the SCTP Session
sctpSessionCallbacks.outboundPacketFunc = onSctpSessionOutboundPacket;
sctpSessionCallbacks.dataChannelMessageFunc = onSctpSessionDataChannelMessage;
sctpSessionCallbacks.dataChannelOpenFunc = onSctpSessionDataChannelOpen;
sctpSessionCallbacks.customData = (UINT64) pKvsPeerConnection;
CHK_STATUS(createSctpSession(&sctpSessionCallbacks, &(pKvsPeerConnection->pSctpSession)));
for (; currentDataChannelId < data.currentDataChannelId; currentDataChannelId += 2) {
pKvsDataChannel = NULL;
retStatus = hashTableGet(pKvsPeerConnection->pDataChannels, currentDataChannelId, &hashValue);
pKvsDataChannel = (PKvsDataChannel) hashValue;
if (retStatus == STATUS_SUCCESS || retStatus == STATUS_HASH_KEY_NOT_PRESENT) {
retStatus = STATUS_SUCCESS;
} else {
CHK(FALSE, retStatus);
}
CHK(pKvsDataChannel != NULL, STATUS_INTERNAL_ERROR);
CHK_STATUS(sctpSessionWriteDcep(pKvsPeerConnection->pSctpSession, currentDataChannelId, pKvsDataChannel->dataChannel.name,
STRLEN(pKvsDataChannel->dataChannel.name), &pKvsDataChannel->rtcDataChannelInit));
pKvsDataChannel->rtcDataChannelDiagnostics.state = RTC_DATA_CHANNEL_STATE_OPEN;
if (STATUS_FAILED(hashTableUpsert(pKvsPeerConnection->pDataChannels, currentDataChannelId, (UINT64) pKvsDataChannel))) {
DLOGW("Failed to update entry in hash table with recent changes to data channel");
}
if (pKvsDataChannel->onOpen != NULL) {
pKvsDataChannel->onOpen(pKvsDataChannel->onOpenCustomData, &pKvsDataChannel->dataChannel);
}
}
CleanUp:
CHK_LOG_ERR(retStatus);
LEAVES();
return retStatus;
}
#endif
VOID onInboundPacket(UINT64 customData, PBYTE buff, UINT32 buffLen)
{
ENTERS();
STATUS retStatus = STATUS_SUCCESS;
PKvsPeerConnection pKvsPeerConnection = (PKvsPeerConnection) customData;
BOOL isDtlsConnected = FALSE;
INT32 signedBuffLen = buffLen;
CHK(signedBuffLen > 2 && pKvsPeerConnection != NULL, STATUS_SUCCESS);
/*
demux each packet off of its first byte
https://tools.ietf.org/html/rfc5764#section-5.1.2
+----------------+
| 127 < B < 192 -+--> forward to RTP
| |
packet --> | 19 < B < 64 -+--> forward to DTLS
| |
| B < 2 -+--> forward to STUN
+----------------+
*/
if (buff[0] > 19 && buff[0] < 64) {
dtlsSessionProcessPacket(pKvsPeerConnection->pDtlsSession, buff, &signedBuffLen);
#ifdef ENABLE_DATA_CHANNEL
if (ATOMIC_LOAD_BOOL(&pKvsPeerConnection->sctpIsEnabled) && signedBuffLen > 0) {
CHK_STATUS(putSctpPacket(pKvsPeerConnection->pSctpSession, buff, signedBuffLen));
}
#endif
CHK_STATUS(dtlsSessionIsInitFinished(pKvsPeerConnection->pDtlsSession, &isDtlsConnected));
if (isDtlsConnected) {
if (pKvsPeerConnection->pSrtpSession == NULL) {
CHK_STATUS(allocateSrtp(pKvsPeerConnection));
}
#ifdef ENABLE_DATA_CHANNEL
if (ATOMIC_LOAD_BOOL(&pKvsPeerConnection->sctpIsEnabled)) {
if (pKvsPeerConnection->pSctpSession == NULL) {
CHK_STATUS(allocateSctp(pKvsPeerConnection));
}
if (signedBuffLen > 0) {
CHK_STATUS(putSctpPacket(pKvsPeerConnection->pSctpSession, buff, signedBuffLen));
}
}
#endif
changePeerConnectionState(pKvsPeerConnection, RTC_PEER_CONNECTION_STATE_CONNECTED);
}
} else if ((buff[0] > 127 && buff[0] < 192) && (pKvsPeerConnection->pSrtpSession != NULL)) {
if (buff[1] >= 192 && buff[1] <= 223) {
if (STATUS_FAILED(retStatus = decryptSrtcpPacket(pKvsPeerConnection->pSrtpSession, buff, &signedBuffLen))) {
DLOGW("decryptSrtcpPacket failed with 0x%08x", retStatus);
CHK(FALSE, STATUS_SUCCESS);
}
CHK_STATUS(onRtcpPacket(pKvsPeerConnection, buff, signedBuffLen));
} else {
CHK_STATUS(sendPacketToRtpReceiver(pKvsPeerConnection, buff, signedBuffLen));
}
}
CleanUp:
CHK_LOG_ERR(retStatus);
LEAVES();
}
STATUS sendPacketToRtpReceiver(PKvsPeerConnection pKvsPeerConnection, PBYTE pBuffer, UINT32 bufferLen)
{
ENTERS();
STATUS retStatus = STATUS_SUCCESS;
PDoubleListNode pCurNode = NULL;
PKvsRtpTransceiver pTransceiver;
UINT64 item, now;
UINT32 ssrc;
PRtpPacket pRtpPacket = NULL;
PBYTE pPayload = NULL;
BOOL ownedByJitterBuffer = FALSE, discarded = FALSE;
UINT64 packetsReceived = 0, packetsFailedDecryption = 0, lastPacketReceivedTimestamp = 0, headerBytesReceived = 0, bytesReceived = 0,
packetsDiscarded = 0;
INT64 arrival, r_ts, transit, delta;
CHK(pKvsPeerConnection != NULL && pBuffer != NULL, STATUS_NULL_ARG);
CHK(bufferLen >= MIN_HEADER_LENGTH, STATUS_INVALID_ARG);
ssrc = getInt32(*(PUINT32) (pBuffer + SSRC_OFFSET));
CHK_STATUS(doubleListGetHeadNode(pKvsPeerConnection->pTransceivers, &pCurNode));
while (pCurNode != NULL) {
CHK_STATUS(doubleListGetNodeData(pCurNode, &item));
pTransceiver = (PKvsRtpTransceiver) item;
if (pTransceiver->jitterBufferSsrc == ssrc) {
packetsReceived++;
if (STATUS_FAILED(retStatus = decryptSrtpPacket(pKvsPeerConnection->pSrtpSession, pBuffer, (PINT32) &bufferLen))) {
DLOGW("decryptSrtpPacket failed with 0x%08x", retStatus);
packetsFailedDecryption++;
CHK(FALSE, STATUS_SUCCESS);
}
now = GETTIME();
CHK(NULL != (pPayload = (PBYTE) MEMALLOC(bufferLen)), STATUS_NOT_ENOUGH_MEMORY);
MEMCPY(pPayload, pBuffer, bufferLen);
CHK_STATUS(createRtpPacketFromBytes(pPayload, bufferLen, &pRtpPacket));
// pRtpPacket took ownership of pPayload. Set pPayload to NULL to
// avoid possible double-free.
pPayload = NULL;
pRtpPacket->receivedTime = now;
// https://tools.ietf.org/html/rfc3550#section-6.4.1
// https://tools.ietf.org/html/rfc3550#appendix-A.8
// interarrival jitter
// arrival, the current time in the same units.
// r_ts, the timestamp from the incoming packet
arrival = KVS_CONVERT_TIMESCALE(now, HUNDREDS_OF_NANOS_IN_A_SECOND, pTransceiver->pJitterBuffer->clockRate);
r_ts = pRtpPacket->header.timestamp;
transit = arrival - r_ts;
delta = transit - pTransceiver->pJitterBuffer->transit;
pTransceiver->pJitterBuffer->transit = transit;
pTransceiver->pJitterBuffer->jitter += (1. / 16.) * ((DOUBLE) ABS(delta) - pTransceiver->pJitterBuffer->jitter);
headerBytesReceived += RTP_HEADER_LEN(pRtpPacket);
bytesReceived += pRtpPacket->rawPacketLength - RTP_HEADER_LEN(pRtpPacket);
CHK_STATUS(jitterBufferPush(pTransceiver->pJitterBuffer, pRtpPacket, &discarded));
if (discarded) {
packetsDiscarded++;
}
lastPacketReceivedTimestamp = KVS_CONVERT_TIMESCALE(now, HUNDREDS_OF_NANOS_IN_A_SECOND, 1000);
ownedByJitterBuffer = TRUE;
CHK(FALSE, STATUS_SUCCESS);
}
pCurNode = pCurNode->pNext;
}
DLOGW("No transceiver to handle inbound ssrc %u", ssrc);
CleanUp:
if (packetsReceived > 0) {
MUTEX_LOCK(pTransceiver->statsLock);
pTransceiver->inboundStats.received.packetsReceived += packetsReceived;
pTransceiver->inboundStats.packetsFailedDecryption += packetsFailedDecryption;
pTransceiver->inboundStats.lastPacketReceivedTimestamp = lastPacketReceivedTimestamp;
pTransceiver->inboundStats.headerBytesReceived += headerBytesReceived;
pTransceiver->inboundStats.bytesReceived += bytesReceived;
pTransceiver->inboundStats.received.jitter = pTransceiver->pJitterBuffer->jitter / pTransceiver->pJitterBuffer->clockRate;
pTransceiver->inboundStats.received.packetsDiscarded += packetsDiscarded;
MUTEX_UNLOCK(pTransceiver->statsLock);
}
if (!ownedByJitterBuffer) {
SAFE_MEMFREE(pPayload);
freeRtpPacket(&pRtpPacket);
CHK_LOG_ERR(retStatus);
}
CHK_LOG_ERR(retStatus);
LEAVES();
return retStatus;
}
STATUS changePeerConnectionState(PKvsPeerConnection pKvsPeerConnection, RTC_PEER_CONNECTION_STATE newState)
{
ENTERS();
STATUS retStatus = STATUS_SUCCESS;
BOOL locked = FALSE;
RtcOnConnectionStateChange onConnectionStateChange = NULL;
UINT64 customData = 0;
CHK(pKvsPeerConnection != NULL, STATUS_NULL_ARG);
MUTEX_LOCK(pKvsPeerConnection->peerConnectionObjLock);
locked = TRUE;
switch (newState) {
case RTC_PEER_CONNECTION_STATE_CONNECTING:
if (pKvsPeerConnection->iceConnectingStartTime == 0) {
pKvsPeerConnection->iceConnectingStartTime = GETTIME();
}
break;
case RTC_PEER_CONNECTION_STATE_CONNECTED:
if (pKvsPeerConnection->iceConnectingStartTime != 0) {
PROFILE_WITH_START_TIME_OBJ(pKvsPeerConnection->iceConnectingStartTime,
pKvsPeerConnection->peerConnectionDiagnostics.iceHolePunchingTime, "ICE Hole Punching Time");
pKvsPeerConnection->iceConnectingStartTime = 0;
}
break;
default:
break;
}
/* new and closed state are terminal*/
CHK(pKvsPeerConnection->connectionState != newState && pKvsPeerConnection->connectionState != RTC_PEER_CONNECTION_STATE_FAILED &&
pKvsPeerConnection->connectionState != RTC_PEER_CONNECTION_STATE_CLOSED,
retStatus);
pKvsPeerConnection->connectionState = newState;
onConnectionStateChange = pKvsPeerConnection->onConnectionStateChange;
customData = pKvsPeerConnection->onConnectionStateChangeCustomData;
MUTEX_UNLOCK(pKvsPeerConnection->peerConnectionObjLock);
locked = FALSE;
if (onConnectionStateChange != NULL) {
onConnectionStateChange(customData, newState);
}
CleanUp:
if (locked) {
MUTEX_UNLOCK(pKvsPeerConnection->peerConnectionObjLock);
}
CHK_LOG_ERR(retStatus);
LEAVES();
return retStatus;
}
STATUS onFrameReadyFunc(UINT64 customData, UINT16 startIndex, UINT16 endIndex, UINT32 frameSize)
{
ENTERS();
STATUS retStatus = STATUS_SUCCESS;
PKvsRtpTransceiver pTransceiver = (PKvsRtpTransceiver) customData;
PRtpPacket pPacket = NULL;
Frame frame;
UINT64 hashValue;
UINT32 filledSize = 0, index;
CHK(pTransceiver != NULL, STATUS_NULL_ARG);
// TODO: handle multi-packet frames
retStatus = hashTableGet(pTransceiver->pJitterBuffer->pPkgBufferHashTable, startIndex, &hashValue);
pPacket = (PRtpPacket) hashValue;
if (retStatus == STATUS_SUCCESS || retStatus == STATUS_HASH_KEY_NOT_PRESENT) {
retStatus = STATUS_SUCCESS;
} else {
CHK(FALSE, retStatus);
}
CHK(pPacket != NULL, STATUS_NULL_ARG);
MUTEX_LOCK(pTransceiver->statsLock);
// https://www.w3.org/TR/webrtc-stats/#dom-rtcinboundrtpstreamstats-jitterbufferdelay
pTransceiver->inboundStats.jitterBufferDelay += (DOUBLE) (GETTIME() - pPacket->receivedTime) / HUNDREDS_OF_NANOS_IN_A_SECOND;
index = pTransceiver->inboundStats.jitterBufferEmittedCount;
pTransceiver->inboundStats.jitterBufferEmittedCount++;
if (MEDIA_STREAM_TRACK_KIND_VIDEO == pTransceiver->transceiver.receiver.track.kind) {
pTransceiver->inboundStats.framesReceived++;
}
MUTEX_UNLOCK(pTransceiver->statsLock);
if (frameSize > pTransceiver->peerFrameBufferSize) {
MEMFREE(pTransceiver->peerFrameBuffer);
pTransceiver->peerFrameBufferSize = (UINT32) (frameSize * PEER_FRAME_BUFFER_SIZE_INCREMENT_FACTOR);
pTransceiver->peerFrameBuffer = (PBYTE) MEMALLOC(pTransceiver->peerFrameBufferSize);
CHK(pTransceiver->peerFrameBuffer != NULL, STATUS_NOT_ENOUGH_MEMORY);
}
CHK_STATUS(jitterBufferFillFrameData(pTransceiver->pJitterBuffer, pTransceiver->peerFrameBuffer, frameSize, &filledSize, startIndex, endIndex));
CHK(frameSize == filledSize, STATUS_INVALID_ARG_LEN);
frame.version = FRAME_CURRENT_VERSION;
frame.decodingTs = pPacket->header.timestamp * HUNDREDS_OF_NANOS_IN_A_MILLISECOND;
frame.presentationTs = frame.decodingTs;
frame.frameData = pTransceiver->peerFrameBuffer;
frame.size = frameSize;
frame.duration = 0;
frame.index = index;
// TODO: Fill frame flag and track id and index if we need to, currently those are not used by RtcRtpTransceiver
if (pTransceiver->onFrame != NULL) {
pTransceiver->onFrame(pTransceiver->onFrameCustomData, &frame);
}
CleanUp:
CHK_LOG_ERR(retStatus);
LEAVES();
return retStatus;
}
STATUS onFrameDroppedFunc(UINT64 customData, UINT16 startIndex, UINT16 endIndex, UINT32 timestamp)
{
ENTERS();
UNUSED_PARAM(endIndex);
STATUS retStatus = STATUS_SUCCESS;
UINT64 hashValue = 0;
PRtpPacket pPacket = NULL;
PKvsRtpTransceiver pTransceiver = (PKvsRtpTransceiver) customData;
DLOGW("Frame with timestamp %ld is dropped!", timestamp);
CHK(pTransceiver != NULL, STATUS_NULL_ARG);
retStatus = hashTableGet(pTransceiver->pJitterBuffer->pPkgBufferHashTable, startIndex, &hashValue);
pPacket = (PRtpPacket) hashValue;
if (retStatus == STATUS_SUCCESS || retStatus == STATUS_HASH_KEY_NOT_PRESENT) {
retStatus = STATUS_SUCCESS;
} else {
CHK(FALSE, retStatus);
}
CHK(pPacket != NULL, STATUS_NULL_ARG);
MUTEX_LOCK(pTransceiver->statsLock);
// https://www.w3.org/TR/webrtc-stats/#dom-rtcinboundrtpstreamstats-jitterbufferdelay
pTransceiver->inboundStats.jitterBufferDelay += (DOUBLE) (GETTIME() - pPacket->receivedTime) / HUNDREDS_OF_NANOS_IN_A_SECOND;
pTransceiver->inboundStats.jitterBufferEmittedCount++;
pTransceiver->inboundStats.received.framesDropped++;
pTransceiver->inboundStats.received.fullFramesLost++;
MUTEX_UNLOCK(pTransceiver->statsLock);
CleanUp:
CHK_LOG_ERR(retStatus);
LEAVES();
return retStatus;
}
PVOID dtlsSessionStartThread(PVOID args)
{
ENTERS();
PKvsPeerConnection pKvsPeerConnection = (PKvsPeerConnection) args;
if (pKvsPeerConnection != NULL) {
dtlsSessionHandshakeInThread(pKvsPeerConnection->pDtlsSession, pKvsPeerConnection->dtlsIsServer);
} else {
DLOGE("Peer connection object NULL, cannot start DTLS handshake");
}
LEAVES();
return NULL;
}
VOID onIceConnectionStateChange(UINT64 customData, UINT64 connectionState)
{
ENTERS();
STATUS retStatus = STATUS_SUCCESS;
PKvsPeerConnection pKvsPeerConnection = (PKvsPeerConnection) customData;
RTC_PEER_CONNECTION_STATE newConnectionState = RTC_PEER_CONNECTION_STATE_NEW;
BOOL startDtlsSession = FALSE, dtlsConnected;
CHK(pKvsPeerConnection != NULL, STATUS_NULL_ARG);
switch (connectionState) {
case ICE_AGENT_STATE_NEW:
newConnectionState = RTC_PEER_CONNECTION_STATE_NEW;
break;
case ICE_AGENT_STATE_CHECK_CONNECTION:
newConnectionState = RTC_PEER_CONNECTION_STATE_CONNECTING;
break;
case ICE_AGENT_STATE_CONNECTED:
/* explicit fall-through */
case ICE_AGENT_STATE_NOMINATING:
newConnectionState = RTC_PEER_CONNECTION_STATE_CONNECTING;
break;
case ICE_AGENT_STATE_READY:
/* start dtlsSession as soon as ice is connected */
newConnectionState = RTC_PEER_CONNECTION_STATE_CONNECTING;
startDtlsSession = TRUE;
break;
case ICE_AGENT_STATE_DISCONNECTED:
DLOGD("ice agent disconnected");
newConnectionState = RTC_PEER_CONNECTION_STATE_DISCONNECTED;
break;
case ICE_AGENT_STATE_FAILED:
newConnectionState = RTC_PEER_CONNECTION_STATE_FAILED;
break;
default:
DLOGW("Unknown ice agent state %" PRIu64, connectionState);
break;
}
if (startDtlsSession) {
CHK_STATUS(dtlsSessionIsInitFinished(pKvsPeerConnection->pDtlsSession, &dtlsConnected));
if (dtlsConnected) {
// In ICE restart scenario, DTLS handshake is not going to be reset. Therefore, we need to check
// if the DTLS state has been connected.
newConnectionState = RTC_PEER_CONNECTION_STATE_CONNECTED;
} else {
// PeerConnection's state changes to CONNECTED only when DTLS state is also connected. So, we need
// wait until DTLS state changes to CONNECTED.
//
// Reference: https://w3c.github.io/webrtc-pc/#rtcpeerconnectionstate-enum
#if defined(ENABLE_KVS_THREADPOOL) && defined(KVS_USE_OPENSSL)
CHK_STATUS(threadpoolContextPush(dtlsSessionStartThread, (PVOID) pKvsPeerConnection));
#else
CHK_STATUS(dtlsSessionStart(pKvsPeerConnection->pDtlsSession, pKvsPeerConnection->dtlsIsServer));
#endif
}
}
CHK_STATUS(changePeerConnectionState(pKvsPeerConnection, newConnectionState));
CleanUp:
CHK_LOG_ERR(retStatus);
LEAVES();
}
VOID onNewIceLocalCandidate(UINT64 customData, PCHAR candidateSdpStr)
{
ENTERS();
STATUS retStatus = STATUS_SUCCESS;
PKvsPeerConnection pKvsPeerConnection = (PKvsPeerConnection) customData;
BOOL locked = FALSE;
CHAR jsonStrBuffer[MAX_ICE_CANDIDATE_JSON_LEN];
INT32 strCompleteLen = 0;
PCHAR pIceCandidateStr = NULL;
CHK(pKvsPeerConnection != NULL, STATUS_NULL_ARG);
CHK(candidateSdpStr == NULL || STRLEN(candidateSdpStr) < MAX_SDP_ATTRIBUTE_VALUE_LENGTH, STATUS_INVALID_ARG);
CHK(pKvsPeerConnection->onIceCandidate != NULL, retStatus); // do nothing if onIceCandidate is not implemented
MUTEX_LOCK(pKvsPeerConnection->peerConnectionObjLock);
locked = TRUE;
if (candidateSdpStr != NULL) {
strCompleteLen = SNPRINTF(jsonStrBuffer, ARRAY_SIZE(jsonStrBuffer), ICE_CANDIDATE_JSON_TEMPLATE, candidateSdpStr);
CHK(strCompleteLen > 0, STATUS_INTERNAL_ERROR);
CHK(strCompleteLen < (INT32) ARRAY_SIZE(jsonStrBuffer), STATUS_BUFFER_TOO_SMALL);
pIceCandidateStr = jsonStrBuffer;
}
pKvsPeerConnection->onIceCandidate(pKvsPeerConnection->onIceCandidateCustomData, pIceCandidateStr);
CleanUp:
CHK_LOG_ERR(retStatus);
if (locked) {
MUTEX_UNLOCK(pKvsPeerConnection->peerConnectionObjLock);
}
LEAVES();
}
VOID onSctpSessionOutboundPacket(UINT64 customData, PBYTE pPacket, UINT32 packetLen)
{
ENTERS();
STATUS retStatus = STATUS_SUCCESS;
PKvsPeerConnection pKvsPeerConnection = NULL;
if (customData == 0) {
return;
}
pKvsPeerConnection = (PKvsPeerConnection) customData;
CHK_STATUS(dtlsSessionPutApplicationData(pKvsPeerConnection->pDtlsSession, pPacket, packetLen));
CleanUp:
CHK_LOG_ERR(retStatus);
LEAVES();
}
VOID onSctpSessionDataChannelMessage(UINT64 customData, UINT32 channelId, BOOL isBinary, PBYTE pMessage, UINT32 pMessageLen)
{
ENTERS();
STATUS retStatus = STATUS_SUCCESS;
PKvsPeerConnection pKvsPeerConnection = (PKvsPeerConnection) customData;
PKvsDataChannel pKvsDataChannel = NULL;
UINT64 hashValue = 0;
CHK(pKvsPeerConnection != NULL, STATUS_INTERNAL_ERROR);
retStatus = hashTableGet(pKvsPeerConnection->pDataChannels, channelId, &hashValue);
pKvsDataChannel = (PKvsDataChannel) hashValue;
if (retStatus == STATUS_SUCCESS || retStatus == STATUS_HASH_KEY_NOT_PRESENT) {
retStatus = STATUS_SUCCESS;
} else {
CHK(FALSE, retStatus);
}
CHK(pKvsDataChannel != NULL && pKvsDataChannel->onMessage != NULL, STATUS_INTERNAL_ERROR);
pKvsDataChannel->rtcDataChannelDiagnostics.messagesReceived++;
pKvsDataChannel->rtcDataChannelDiagnostics.bytesReceived += pMessageLen;
if (STATUS_FAILED(hashTableUpsert(pKvsPeerConnection->pDataChannels, channelId, (UINT64) pKvsDataChannel))) {
DLOGW("Failed to update entry in hash table with recent changes to data channel");
}
pKvsDataChannel->onMessage(pKvsDataChannel->onMessageCustomData, &pKvsDataChannel->dataChannel, isBinary, pMessage, pMessageLen);
CleanUp:
CHK_LOG_ERR(retStatus);
LEAVES();
}
VOID onSctpSessionDataChannelOpen(UINT64 customData, UINT32 channelId, PBYTE pName, UINT32 nameLen)
{
ENTERS();
STATUS retStatus = STATUS_SUCCESS;
PKvsPeerConnection pKvsPeerConnection = (PKvsPeerConnection) customData;
PKvsDataChannel pKvsDataChannel = NULL;
CHK(pKvsPeerConnection != NULL && pKvsPeerConnection->onDataChannel != NULL, STATUS_NULL_ARG);
pKvsDataChannel = (PKvsDataChannel) MEMCALLOC(1, SIZEOF(KvsDataChannel));
CHK(pKvsDataChannel != NULL, STATUS_NOT_ENOUGH_MEMORY);
STRNCPY(pKvsDataChannel->dataChannel.name, (PCHAR) pName, nameLen);
pKvsDataChannel->dataChannel.id = channelId;
pKvsDataChannel->pRtcPeerConnection = (PRtcPeerConnection) pKvsPeerConnection;
pKvsDataChannel->channelId = channelId;
// Set the data channel parameters when data channel is created by peer
pKvsDataChannel->rtcDataChannelDiagnostics.dataChannelIdentifier = channelId;
pKvsDataChannel->rtcDataChannelDiagnostics.state = RTC_DATA_CHANNEL_STATE_OPEN;
STRNCPY(pKvsDataChannel->rtcDataChannelDiagnostics.label, (PCHAR) pName, nameLen);
CHK_STATUS(hashTablePut(pKvsPeerConnection->pDataChannels, channelId, (UINT64) pKvsDataChannel));
pKvsPeerConnection->onDataChannel(pKvsPeerConnection->onDataChannelCustomData, &(pKvsDataChannel->dataChannel));
CleanUp:
CHK_LOG_ERR(retStatus);
LEAVES();
}
VOID onDtlsOutboundPacket(UINT64 customData, PBYTE pBuffer, UINT32 bufferLen)
{
ENTERS();
PKvsPeerConnection pKvsPeerConnection = NULL;
if (customData == 0) {
return;
}
pKvsPeerConnection = (PKvsPeerConnection) customData;
iceAgentSendPacket(pKvsPeerConnection->pIceAgent, pBuffer, bufferLen);
LEAVES();
}
VOID onDtlsStateChange(UINT64 customData, RTC_DTLS_TRANSPORT_STATE newDtlsState)
{
ENTERS();
PKvsPeerConnection pKvsPeerConnection = NULL;
if (customData == 0) {
return;
}
pKvsPeerConnection = (PKvsPeerConnection) customData;
switch (newDtlsState) {
case RTC_DTLS_TRANSPORT_STATE_CONNECTED:
pKvsPeerConnection->peerConnectionDiagnostics.dtlsSessionSetupTime = pKvsPeerConnection->pDtlsSession->dtlsSessionSetupTime;
break;
case RTC_DTLS_TRANSPORT_STATE_CLOSED:
changePeerConnectionState(pKvsPeerConnection, RTC_PEER_CONNECTION_STATE_CLOSED);
break;
default:
/* explicit ignore */
break;
}
LEAVES();
}
/* Generate a printable string that does not
* need to be escaped when encoding in JSON
*/
STATUS generateJSONSafeString(PCHAR pDst, UINT32 len)
{
ENTERS();
STATUS retStatus = STATUS_SUCCESS;
UINT32 i = 0;
CHK(pDst != NULL, STATUS_NULL_ARG);
for (i = 0; i < len; i++) {
pDst[i] = VALID_CHAR_SET_FOR_JSON[RAND() % (ARRAY_SIZE(VALID_CHAR_SET_FOR_JSON) - 1)];
}
CleanUp:
CHK_LOG_ERR(retStatus);
LEAVES();
return retStatus;
}
STATUS rtcpReportsCallback(UINT32 timerId, UINT64 currentTime, UINT64 customData)
{
ENTERS();
UNUSED_PARAM(timerId);
STATUS retStatus = STATUS_SUCCESS;
BOOL ready = FALSE;
UINT64 ntpTime, rtpTime, delay;
UINT32 packetCount, octetCount, packetLen, allocSize, ssrc;
PBYTE rawPacket = NULL;
PKvsPeerConnection pKvsPeerConnection = NULL;
PKvsRtpTransceiver pKvsRtpTransceiver = (PKvsRtpTransceiver) customData;
CHK(pKvsRtpTransceiver != NULL && pKvsRtpTransceiver->pJitterBuffer != NULL && pKvsRtpTransceiver->pKvsPeerConnection != NULL, STATUS_NULL_ARG);
pKvsPeerConnection = pKvsRtpTransceiver->pKvsPeerConnection;
ssrc = pKvsRtpTransceiver->sender.ssrc;
DLOGS("rtcpReportsCallback %" PRIu64 " ssrc: %u rtxssrc: %u", currentTime, ssrc, pKvsRtpTransceiver->sender.rtxSsrc);
// check if ice agent is connected, reschedule in 200msec if not
ready = pKvsPeerConnection->pSrtpSession != NULL &&
currentTime - pKvsRtpTransceiver->sender.firstFrameWallClockTime >= 2500 * HUNDREDS_OF_NANOS_IN_A_MILLISECOND;
if (!ready) {
DLOGV("sender report no frames sent %u", ssrc);
} else {
// create rtcp sender report packet
// https://tools.ietf.org/html/rfc3550#section-6.4.1
ntpTime = convertTimestampToNTP(currentTime);
rtpTime = pKvsRtpTransceiver->sender.rtpTimeOffset +
CONVERT_TIMESTAMP_TO_RTP(pKvsRtpTransceiver->pJitterBuffer->clockRate, currentTime - pKvsRtpTransceiver->sender.firstFrameWallClockTime);
MUTEX_LOCK(pKvsRtpTransceiver->statsLock);
packetCount = pKvsRtpTransceiver->outboundStats.sent.packetsSent;
octetCount = pKvsRtpTransceiver->outboundStats.sent.bytesSent;
MUTEX_UNLOCK(pKvsRtpTransceiver->statsLock);
DLOGV("sender report %u %" PRIu64 " %" PRIu64 " : %u packets %u bytes", ssrc, ntpTime, rtpTime, packetCount, octetCount);
packetLen = RTCP_PACKET_HEADER_LEN + 24;
// srtp_protect_rtcp() in encryptRtcpPacket() assumes memory availability to write 10 bytes of authentication tag and
// SRTP_MAX_TRAILER_LEN + 4 following the actual rtcp Packet payload
allocSize = packetLen + SRTP_AUTH_TAG_OVERHEAD + SRTP_MAX_TRAILER_LEN + 4;
CHK(NULL != (rawPacket = (PBYTE) MEMALLOC(allocSize)), STATUS_NOT_ENOUGH_MEMORY);
rawPacket[0] = RTCP_PACKET_VERSION_VAL << 6;
rawPacket[RTCP_PACKET_TYPE_OFFSET] = RTCP_PACKET_TYPE_SENDER_REPORT;
putUnalignedInt16BigEndian(rawPacket + RTCP_PACKET_LEN_OFFSET,
(packetLen / RTCP_PACKET_LEN_WORD_SIZE) - 1); // The length of this RTCP packet in 32-bit words minus one
putUnalignedInt32BigEndian(rawPacket + 4, ssrc);
putUnalignedInt64BigEndian(rawPacket + 8, ntpTime);
putUnalignedInt32BigEndian(rawPacket + 16, rtpTime);
putUnalignedInt32BigEndian(rawPacket + 20, packetCount);
putUnalignedInt32BigEndian(rawPacket + 24, octetCount);
CHK_STATUS(encryptRtcpPacket(pKvsPeerConnection->pSrtpSession, rawPacket, (PINT32) &packetLen));
CHK_STATUS(iceAgentSendPacket(pKvsPeerConnection->pIceAgent, rawPacket, packetLen));
}
delay = 100 + (RAND() % 200);
DLOGS("next sender report %u in %" PRIu64 " msec", ssrc, delay);
// reschedule timer with 200msec +- 100ms
CHK_STATUS(timerQueueAddTimer(pKvsPeerConnection->timerQueueHandle, delay * HUNDREDS_OF_NANOS_IN_A_MILLISECOND,
TIMER_QUEUE_SINGLE_INVOCATION_PERIOD, rtcpReportsCallback, (UINT64) pKvsRtpTransceiver,
&pKvsRtpTransceiver->rtcpReportsTimerId));
CleanUp:
CHK_LOG_ERR(retStatus);
SAFE_MEMFREE(rawPacket);
LEAVES();
return retStatus;
}
// Not thread safe
STATUS getStunAddr(PStunIpAddrContext pStunIpAddrCtx)
{
ENTERS();
INT32 errCode;
STATUS retStatus = STATUS_SUCCESS;
struct addrinfo *rp, *res;
struct sockaddr_in* ipv4Addr;
BOOL resolved = FALSE;
errCode = getaddrinfo(pStunIpAddrCtx->hostname, NULL, NULL, &res);
if (errCode != 0) {
DLOGI("Failed to resolve hostname with errcode: %d", errCode);
retStatus = STATUS_RESOLVE_HOSTNAME_FAILED;
} else {
for (rp = res; rp != NULL && !resolved; rp = rp->ai_next) {
if (rp->ai_family == AF_INET) {
ipv4Addr = (struct sockaddr_in*) rp->ai_addr;
pStunIpAddrCtx->kvsIpAddr.family = KVS_IP_FAMILY_TYPE_IPV4;
pStunIpAddrCtx->kvsIpAddr.port = 0;
MEMCPY(pStunIpAddrCtx->kvsIpAddr.address, &ipv4Addr->sin_addr, IPV4_ADDRESS_LENGTH);
resolved = TRUE;
}
}
freeaddrinfo(res);
}
if (!resolved) {
retStatus = STATUS_RESOLVE_HOSTNAME_FAILED;
}
CHK_LOG_ERR(retStatus);
LEAVES();
return retStatus;
}
STATUS onSetStunServerIp(UINT64 customData, PCHAR url, PKvsIpAddress pIpAddr)
{
ENTERS();
UNUSED_PARAM(customData);
STATUS retStatus = STATUS_SUCCESS;
BOOL locked = FALSE;
PWebRtcClientContext pWebRtcClientContext = getWebRtcClientInstance();
CHK_WARN(ATOMIC_LOAD_BOOL(&pWebRtcClientContext->isContextInitialized), STATUS_NULL_ARG, "WebRTC Client object Object not initialized");
UINT64 currentTime = GETTIME();
MUTEX_LOCK(pWebRtcClientContext->stunCtxlock);
locked = TRUE;
// This covers a situation where say we receive a URL that is not the default STUN or the hostname is not populated
// pWebRtcClientContext->pStunIpAddrCtx->status needs to be set to ensure we do not go ahead with resolution on thread
// in case we receive the request early on
if (STRCMP(url, pWebRtcClientContext->pStunIpAddrCtx->hostname) != 0) {
retStatus = STATUS_PEERCONNECTION_EARLY_DNS_RESOLUTION_FAILED;
// This is to ensure we do not go ahead with STUN resolution if this call is already made
pWebRtcClientContext->pStunIpAddrCtx->status = STATUS_PEERCONNECTION_EARLY_DNS_RESOLUTION_FAILED;
} else {
if (pWebRtcClientContext->pStunIpAddrCtx->isIpInitialized) {
DLOGI("Initialized successfully");
if (currentTime > (pWebRtcClientContext->pStunIpAddrCtx->startTime + pWebRtcClientContext->pStunIpAddrCtx->expirationDuration)) {
DLOGI("Expired...need to refresh STUN address");
// Reset start time
pWebRtcClientContext->pStunIpAddrCtx->startTime = 0;
CHK_ERR(getStunAddr(pWebRtcClientContext->pStunIpAddrCtx) == STATUS_SUCCESS, retStatus, "Failed to resolve after cache expiry");
}
MEMCPY(pIpAddr, &pWebRtcClientContext->pStunIpAddrCtx->kvsIpAddr, SIZEOF(pWebRtcClientContext->pStunIpAddrCtx->kvsIpAddr));
} else {
DLOGE("Initialization failed");
}
}
CleanUp:
if (locked) {
MUTEX_UNLOCK(pWebRtcClientContext->stunCtxlock);
}
DLOGD("Exiting from stun server IP callback");
releaseHoldOnInstance(pWebRtcClientContext);
CHK_LOG_ERR(retStatus);
LEAVES();
return retStatus;
}
PVOID resolveStunIceServerIp(PVOID args)
{
ENTERS();
UNUSED_PARAM(args);
PWebRtcClientContext pWebRtcClientContext = getWebRtcClientInstance();
BOOL locked = FALSE;
CHAR addressResolved[KVS_IP_ADDRESS_STRING_BUFFER_LEN + 1] = {'\0'};
PCHAR pRegion;
PCHAR pHostnamePostfix;
UINT64 stunDnsResolutionStartTime = 0;
if (ATOMIC_LOAD_BOOL(&pWebRtcClientContext->isContextInitialized)) {
MUTEX_LOCK(pWebRtcClientContext->stunCtxlock);
locked = TRUE;
if (pWebRtcClientContext->pStunIpAddrCtx == NULL) {
DLOGE("Failed to resolve STUN IP address because webrtc client instance was not created");
} else {
if (pWebRtcClientContext->pStunIpAddrCtx->status != STATUS_PEERCONNECTION_EARLY_DNS_RESOLUTION_FAILED) {
if ((pRegion = GETENV(DEFAULT_REGION_ENV_VAR)) == NULL) {
pRegion = DEFAULT_AWS_REGION;
}
pHostnamePostfix = KINESIS_VIDEO_STUN_URL_POSTFIX;
// If region is in CN, add CN region uri postfix
if (STRSTR(pRegion, "cn-")) {
pHostnamePostfix = KINESIS_VIDEO_STUN_URL_POSTFIX_CN;
}
SNPRINTF(pWebRtcClientContext->pStunIpAddrCtx->hostname, SIZEOF(pWebRtcClientContext->pStunIpAddrCtx->hostname),
KINESIS_VIDEO_STUN_URL_WITHOUT_PORT, pRegion, pHostnamePostfix);
stunDnsResolutionStartTime = GETTIME();
if (getStunAddr(pWebRtcClientContext->pStunIpAddrCtx) == STATUS_SUCCESS) {
getIpAddrStr(&pWebRtcClientContext->pStunIpAddrCtx->kvsIpAddr, addressResolved, ARRAY_SIZE(addressResolved));
DLOGI("ICE Server address for %s with getaddrinfo: %s", pWebRtcClientContext->pStunIpAddrCtx->hostname, addressResolved);
pWebRtcClientContext->pStunIpAddrCtx->isIpInitialized = TRUE;
} else {
DLOGE("Failed to resolve %s", pWebRtcClientContext->pStunIpAddrCtx->hostname);
}
pWebRtcClientContext->pStunIpAddrCtx->startTime = GETTIME();
} else {
DLOGW("Request already received to get the URL before resolution could even start...allowing higher layers to handle resolution");
}
PROFILE_WITH_START_TIME_OBJ(stunDnsResolutionStartTime, pWebRtcClientContext->pStunIpAddrCtx->stunDnsResolutionTime,
"STUN DNS resolution time taken");
}
if (locked) {
MUTEX_UNLOCK(pWebRtcClientContext->stunCtxlock);
}
} else {
DLOGW("STUN DNS thread invoked without context being initialized");
}
releaseHoldOnInstance(pWebRtcClientContext);
DLOGD("Exiting from stun server IP resolution thread");
LEAVES();
return NULL;
}
STATUS createPeerConnection(PRtcConfiguration pConfiguration, PRtcPeerConnection* ppPeerConnection)
{
ENTERS();
STATUS retStatus = STATUS_SUCCESS;
PKvsPeerConnection pKvsPeerConnection = NULL;
IceAgentCallbacks iceAgentCallbacks;
DtlsSessionCallbacks dtlsSessionCallbacks;
PConnectionListener pConnectionListener = NULL;
UINT64 startTime = 0;
UINT64 startTimeInMacro = 0;
CHK(pConfiguration != NULL && ppPeerConnection != NULL, STATUS_NULL_ARG);
startTime = GETTIME();
MEMSET(&iceAgentCallbacks, 0, SIZEOF(IceAgentCallbacks));
MEMSET(&dtlsSessionCallbacks, 0, SIZEOF(DtlsSessionCallbacks));
pKvsPeerConnection = (PKvsPeerConnection) MEMCALLOC(1, SIZEOF(KvsPeerConnection));
CHK(pKvsPeerConnection != NULL, STATUS_NOT_ENOUGH_MEMORY);
CHK_STATUS(timerQueueCreate(&pKvsPeerConnection->timerQueueHandle));
pKvsPeerConnection->peerConnection.version = PEER_CONNECTION_CURRENT_VERSION;
CHK_STATUS(generateJSONSafeString(pKvsPeerConnection->localIceUfrag, LOCAL_ICE_UFRAG_LEN));
CHK_STATUS(generateJSONSafeString(pKvsPeerConnection->localIcePwd, LOCAL_ICE_PWD_LEN));
CHK_STATUS(generateJSONSafeString(pKvsPeerConnection->localCNAME, LOCAL_CNAME_LEN));
PROFILE_CALL(CHK_STATUS(createDtlsSession(
&dtlsSessionCallbacks, pKvsPeerConnection->timerQueueHandle, pConfiguration->kvsRtcConfiguration.generatedCertificateBits,
pConfiguration->kvsRtcConfiguration.generateRSACertificate, pConfiguration->certificates, &pKvsPeerConnection->pDtlsSession)),
"Create DTLS Session object");
CHK_STATUS(dtlsSessionOnOutBoundData(pKvsPeerConnection->pDtlsSession, (UINT64) pKvsPeerConnection, onDtlsOutboundPacket));
CHK_STATUS(dtlsSessionOnStateChange(pKvsPeerConnection->pDtlsSession, (UINT64) pKvsPeerConnection, onDtlsStateChange));
CHK_STATUS(hashTableCreateWithParams(CODEC_HASH_TABLE_BUCKET_COUNT, CODEC_HASH_TABLE_BUCKET_LENGTH, &pKvsPeerConnection->pCodecTable));
CHK_STATUS(hashTableCreateWithParams(CODEC_HASH_TABLE_BUCKET_COUNT, CODEC_HASH_TABLE_BUCKET_LENGTH, &pKvsPeerConnection->pDataChannels));
CHK_STATUS(hashTableCreateWithParams(RTX_HASH_TABLE_BUCKET_COUNT, RTX_HASH_TABLE_BUCKET_LENGTH, &pKvsPeerConnection->pRtxTable));
CHK_STATUS(doubleListCreate(&(pKvsPeerConnection->pTransceivers)));
CHK_STATUS(doubleListCreate(&(pKvsPeerConnection->pFakeTransceivers)));
CHK_STATUS(doubleListCreate(&(pKvsPeerConnection->pAnswerTransceivers)));
pKvsPeerConnection->pSrtpSessionLock = MUTEX_CREATE(TRUE);
pKvsPeerConnection->peerConnectionObjLock = MUTEX_CREATE(FALSE);
pKvsPeerConnection->connectionState = RTC_PEER_CONNECTION_STATE_NONE;
pKvsPeerConnection->MTU = pConfiguration->kvsRtcConfiguration.maximumTransmissionUnit == 0
? DEFAULT_MTU_SIZE_BYTES
: pConfiguration->kvsRtcConfiguration.maximumTransmissionUnit;
ATOMIC_STORE_BOOL(&pKvsPeerConnection->sctpIsEnabled, FALSE);
iceAgentCallbacks.customData = (UINT64) pKvsPeerConnection;
iceAgentCallbacks.inboundPacketFn = onInboundPacket;
iceAgentCallbacks.connectionStateChangedFn = onIceConnectionStateChange;
iceAgentCallbacks.newLocalCandidateFn = onNewIceLocalCandidate;
iceAgentCallbacks.setStunServerIpFn = onSetStunServerIp;
PROFILE_CALL(CHK_STATUS(createConnectionListener(&pConnectionListener)), "Create connection listener");
// IceAgent will own the lifecycle of pConnectionListener;
PROFILE_CALL(CHK_STATUS(createIceAgent(pKvsPeerConnection->localIceUfrag, pKvsPeerConnection->localIcePwd, &iceAgentCallbacks, pConfiguration,
pKvsPeerConnection->timerQueueHandle, pConnectionListener, &pKvsPeerConnection->pIceAgent)),