-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathtcrelay.cpp
1569 lines (1340 loc) · 45 KB
/
tcrelay.cpp
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
// Copyright © 2021 Michael Thornburgh
// SPDX-License-Identifier: MIT
// TODO:
// * don't relay setPeerInfo
// * happy eyeballs for RTMP (handle multiple addresses from getaddrinfo))
// * use URIs for dest
// - rewrite connect tcUrl
// * RTMPS (at least output)
#include <cassert>
#include <cerrno>
#include <csignal>
#include <cstdio>
#include <cstdlib>
#include <cstring>
extern "C" {
#include <fcntl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <unistd.h>
}
#include "rtmfp/rtmfp.hpp"
#include "rtmfp/RunLoops.hpp"
#include "rtmfp/FlashCryptoAdapter_OpenSSL.hpp"
#include "rtmfp/PerformerPosixPlatformAdapter.hpp"
#include "rtmfp/TCMessage.hpp"
#include "rtmfp/FlowSyncManager.hpp"
#include "rtmfp/ReorderBuffer.hpp"
#include "rtmfp/RedirectorClient.hpp"
#include "rtmfp/Hex.hpp"
#include "RTMP.hpp"
#include "PosixStreamPlatformAdapter.hpp"
#include "redirectorspec.hpp"
#include "RTWebSocket.hpp"
#include "SimpleWebSocket.hpp"
#include "SimpleWebSocketMessagePlatformAdapter.hpp"
using namespace com::zenomt;
using namespace com::zenomt::rtmfp;
using namespace com::zenomt::rtmp;
using namespace com::zenomt::websock;
// need to keep rtws:: qualifier to avoid collisions with RTMFP SendFlow/RecvFlow.
namespace {
class Connection; class Client;
enum Protocol { PROTO_UNSPEC, PROTO_RTMP, PROTO_RTMP_SIMPLE, PROTO_RTWS, PROTO_RTMFP };
enum {
TC_VIDEO_COMMAND_RANDOM_ACCESS_CHECKPOINT = 3
};
int verbose = 0;
int port = 1935;
bool requireHMAC = true;
bool requireSSEQ = true;
bool interleave = false;
bool sendVideoCheckpoint = false;
bool replayCheckpointFrame = true;
bool collapseAudioGaps = false;
Time videoLifetime = 2.0;
Time audioLifetime = 2.2;
Time finishByMargin = 0.1;
Time previousGopStartByMargin = 0.1;
Time checkpointLifetime = 4.5;
Time reorderWindowPeriod = 1.0;
Time delaycc_delay = INFINITY;
ReceiveOrder mediaReceiveIntent = RO_SEQUENCE;
bool expirePreviousGop = true;
bool interrupted = false;
bool stopping = false;
Protocol inputProtocol = PROTO_UNSPEC;
Protocol outputProtocol = PROTO_UNSPEC;
const char *desthostname = nullptr;
const char *destservname = "1935";
const char *overrideRtmfpUri = nullptr;
const char *backupRtmfpUri = "rtmfp:";
int dscp = 0;
PreferredRunLoop mainRL;
Performer mainPerformer(&mainRL);
PreferredRunLoop workerRL;
Performer workerPerformer(&workerRL);
PreferredRunLoop lookupRL;
Performer lookupPerformer(&lookupRL);
std::set<std::shared_ptr<Client>> clients;
void lookup(const std::function<void(const std::vector<Address> &results)> &onresult)
{
lookupPerformer.perform([onresult] {
int error = 0;
auto results = Address::lookup(desthostname, destservname, &error);
if(error)
printf("address lookup: %s\n", gai_strerror(error));
mainPerformer.perform([onresult, results] { onresult(results); });
});
}
class Connection : public Object {
public:
~Connection()
{
if(verbose > 1) printf("~Connection %p\n", (void *)this);
}
virtual void close()
{
if(m_open)
{
if(verbose and (m_videoMessages or m_audioMessages or m_videoMessagesLate or m_audioMessagesLate))
printf("Connection %p video abn %lu/%lu (%lu late) audio abn %lu/%lu (%lu late)\n", (void *)this, (unsigned long)m_videoMessagesAbandoned, (unsigned long)m_videoMessages, (unsigned long)m_videoMessagesLate, (unsigned long)m_audioMessagesAbandoned, (unsigned long)m_audioMessages, (unsigned long)m_audioMessagesLate);
}
m_open = false;
}
virtual void shutdown() = 0;
bool isFinished() const { return m_finished; }
std::shared_ptr<WriteReceipt> write(uint32_t streamID, uint8_t messageType, uint32_t timestamp, const void *payload, size_t len)
{
const uint8_t *data = (const uint8_t *)payload;
Time startWithin = INFINITY;
bool isVideoCodingLayer = false;
auto &streamState = m_streamStates[streamID];
if(collapseAudioGaps)
{
uint32_t adjustedTimestamp = timestamp ? timestamp - streamState.m_timestampShift : 0;
if(TCMSG_AUDIO == messageType)
{
uint32_t lastTS = streamState.m_lastAudioTimestamp;
if(adjustedTimestamp and lastTS and Message::timestamp_gt(adjustedTimestamp, lastTS + 1536/48)) // XXX 48kHz AAC only
{
streamState.m_timestampShift = (timestamp - lastTS) - 1024/48; // XXX need real audio frame duration
adjustedTimestamp = timestamp - streamState.m_timestampShift;
if(verbose) printf("Connection %p stream %lu new timestamp shift %lu at %lu\n", (void *)this, (unsigned long)streamID, (unsigned long)(streamState.m_timestampShift), (unsigned long)adjustedTimestamp);
}
}
timestamp = adjustedTimestamp;
}
switch(messageType)
{
case TCMSG_VIDEO:
if(collapseAudioGaps and Message::timestamp_lt(timestamp, streamState.m_lastVideoTimestamp))
timestamp = streamState.m_lastVideoTimestamp + 5;
streamState.m_lastVideoTimestamp = timestamp;
if(isVideoCheckpointCommand(data, len))
{
if(replayCheckpointFrame)
{
if(Message::timestamp_gt(timestamp, streamState.m_lastKeyframeTimestamp) and streamState.m_lastKeyframe.size())
{
write(streamID, TCMSG_VIDEO, timestamp, streamState.m_lastKeyframe.data(), streamState.m_lastKeyframe.size());
if(verbose) printf("Connection %p stream %lu replay keyframe at %lu\n", (void *)this, (unsigned long)streamID, (unsigned long)timestamp);
}
return nullptr;
}
else
startWithin = checkpointLifetime; // forward (or delete if checkpointLifetime < 0)
}
else if(not isVideoSequenceSpecial(data, len))
{
startWithin = videoLifetime;
isVideoCodingLayer = true;
}
break;
case TCMSG_AUDIO:
streamState.m_lastAudioTimestamp = timestamp;
if(not isAudioSequenceSpecial(data, len))
startWithin = audioLifetime;
break;
}
Time finishWithin = startWithin + finishByMargin;
auto rv = basicWrite(streamID, messageType, timestamp, data, len, startWithin, finishWithin);
if(rv and isVideoCodingLayer)
{
if(Message::isVideoKeyframe(data, len))
{
streamState.m_chain.expire(
expirePreviousGop ? mainRL.getCurrentTime() + previousGopStartByMargin : INFINITY,
expirePreviousGop ? mainRL.getCurrentTime() + finishByMargin : INFINITY);
if(replayCheckpointFrame)
{
streamState.m_lastKeyframe = Bytes(data, data + len);
streamState.m_lastKeyframeTimestamp = timestamp;
}
if(sendVideoCheckpoint)
{
uint8_t command[] = { TC_VIDEO_FRAMETYPE_COMMAND | TC_VIDEO_CODEC_NONE, TC_VIDEO_COMMAND_RANDOM_ACCESS_CHECKPOINT };
basicWrite(streamID, TCMSG_VIDEO, timestamp, command, sizeof(command), checkpointLifetime, checkpointLifetime);
}
}
if(startWithin < INFINITY)
streamState.m_chain.append(rv);
}
if(rv and verbose)
rv->onFinished = [messageType, this] (bool abandoned) {
if(abandoned)
{
printf("-");
fflush(stdout);
}
switch(messageType)
{
case TCMSG_VIDEO:
m_videoMessages++;
if(abandoned)
m_videoMessagesAbandoned++;
break;
case TCMSG_AUDIO:
m_audioMessages++;
if(abandoned)
m_audioMessagesAbandoned++;
break;
default:
break;
}
};
return rv;
}
std::function<void(uint32_t streamID, uint8_t messageType, uint32_t timestamp, const uint8_t *payload, size_t len)> onmessage;
Task onerror;
Task onShutdownCompleteCallback;
protected:
virtual std::shared_ptr<WriteReceipt> basicWrite(uint32_t streamID, uint8_t messageType, uint32_t timestamp, const uint8_t *payload, size_t len, Time startWithin, Time finishWithin) = 0;
void callOnError()
{
onmessage = nullptr;
Task cb;
swap(cb, onerror);
if(cb)
cb();
}
void callOnShutdownComplete()
{
callOnError();
Task cb;
m_finished = true;
swap(cb, onShutdownCompleteCallback);
if(cb)
cb();
}
bool isVideoSequenceSpecial(const uint8_t *payload, size_t len) const
{
if(isVideoCheckpointCommand(payload, len))
return false;
return Message::isVideoSequenceSpecial(payload, len);
}
bool isVideoCheckpointCommand(const uint8_t *payload, size_t len) const
{
if(len < 2)
return false;
if(TC_VIDEO_FRAMETYPE_COMMAND != (payload[0] & TC_VIDEO_FRAMETYPE_MASK))
return false;
if(Message::isVideoEnhanced(payload, len) or (TC_VIDEO_CODEC_AVC == Message::getVideoCodec(payload, len)))
{
if(len < 6)
return false;
return TC_VIDEO_COMMAND_RANDOM_ACCESS_CHECKPOINT == payload[5];
}
else
return TC_VIDEO_COMMAND_RANDOM_ACCESS_CHECKPOINT == payload[1];
}
bool isAudioSequenceSpecial(const uint8_t *payload, size_t len) const
{
if(0 == len)
return true;
if(len < 2)
return false;
return (TC_AUDIO_CODEC_AAC == (payload[0] & TC_AUDIO_CODEC_MASK)) and (TC_AUDIO_AACPACKET_AUDIO_SPECIFIC_CONFIG == payload[1]);
}
struct StreamState {
WriteReceiptChain m_chain;
Bytes m_lastKeyframe;
uint32_t m_lastKeyframeTimestamp { 0 };
uint32_t m_lastVideoTimestamp { 0 };
uint32_t m_lastAudioTimestamp { 0 };
uint32_t m_timestampShift { 0 };
};
std::map<uint32_t, StreamState> m_streamStates;
bool m_open = { true };
bool m_finished = { false };
size_t m_videoMessages { 0 };
size_t m_videoMessagesAbandoned { 0 };
size_t m_videoMessagesLate { 0 };
size_t m_audioMessages { 0 };
size_t m_audioMessagesAbandoned { 0 };
size_t m_audioMessagesLate { 0 };
};
class RTMPConnection : public Connection {
public:
static std::shared_ptr<RTMPConnection> newRTMPConnection(bool isServer) {
auto conn = share_ref(new RTMPConnection(isServer), false);
conn->m_rtmp->onmessage = [conn] (uint32_t streamID, uint8_t messageType, uint32_t timestamp, const uint8_t *payload, size_t len) {
if((TCMSG_USER_CONTROL == messageType) and (len >= 2) and (((TC_USERCONTROL_FLOW_SYNC >> 8) & 0xff) == payload[0]) and ((TC_USERCONTROL_FLOW_SYNC & 0xff) == payload[1]))
{
if(verbose)
printf("ignoring TC_USERCONTROL_FLOW_SYNC from RTMP\n");
return;
}
if(conn->onmessage)
conn->onmessage(streamID, messageType, timestamp, payload, len);
};
conn->m_rtmp->onerror = [conn] { conn->callOnError(); };
conn->m_adapter->onShutdownCompleteCallback = [conn] { conn->callOnShutdownComplete(); };
return conn;
}
RTMPConnection(bool isServer) : m_connectionOpen(false)
{
m_adapter = share_ref(new PosixStreamPlatformAdapter(&mainRL), false);
m_rtmp = share_ref(new RTMP(m_adapter), false);
m_rtmp->init(isServer);
m_rtmp->minOutstandingThresh = 16 * 1024; // default 64KB probably too big
m_rtmp->maxAdditionalDelay = (delaycc_delay < INFINITY) ? delaycc_delay : 120.0;
if(PROTO_RTMP_SIMPLE == (isServer ? inputProtocol : outputProtocol))
{
m_rtmp->setSimpleMode(true);
m_rtmp->setChunkSize(1<<24); // maximum message size
m_rtmp->minOutstandingThresh = m_rtmp->outstandingThresh = SIZE_MAX;
}
}
bool setFd(int fd)
{
int tos = dscp << 2;
setsockopt(fd, IPPROTO_IP, IP_TOS, &tos, sizeof(tos));
setsockopt(fd, IPPROTO_IPV6, IPV6_TCLASS, &tos, sizeof(tos));
if(not m_adapter->setSocketFd(fd))
{
::close(fd);
return false;
}
m_connectionOpen = true;
return true;
}
void openConnection()
{
auto myself = share_ref(this);
lookup([this, myself] (const std::vector<Address> &results) {
if(m_open)
{
if(results.empty())
goto error;
auto addr = results.front();
if(verbose) printf("connecting to %s\n", addr.toPresentation().c_str());
int fd = socket(addr.getFamily(), SOCK_STREAM, IPPROTO_TCP);
if(fd < 0)
{
::perror("socket");
goto error;
}
{
int flags = fcntl(fd, F_GETFL);
flags |= O_NONBLOCK;
fcntl(fd, F_SETFL, flags); // just so connect() won't block
}
if((connect(fd, addr.getSockaddr(), addr.getSockaddrLen()) < 0) and (EINPROGRESS != errno))
{
::perror("connect");
::close(fd);
goto error;
}
if(not setFd(fd))
goto error;
}
return;
error:
callOnError();
(void) myself;
});
m_connectionOpen = true;
}
void close() override
{
Connection::close();
m_rtmp->close();
}
void shutdown() override
{
retain();
close();
m_adapter->close();
release();
}
protected:
std::shared_ptr<WriteReceipt> basicWrite(uint32_t streamID, uint8_t messageType, uint32_t timestamp, const uint8_t *payload, size_t len, Time startWithin, Time finishWithin) override
{
if(not m_connectionOpen)
openConnection(); // lazy open outgoing connections so we know client is talking RTMP
Priority pri = PRI_ROUTINE;
switch(messageType)
{
case TCMSG_COMMAND:
case TCMSG_COMMAND_EX:
pri = PRI_IMMEDIATE;
break;
case TCMSG_AUDIO:
case TCMSG_DATA:
case TCMSG_DATA_EX:
pri = interleave ? PRI_PRIORITY : PRI_IMMEDIATE;
break;
case TCMSG_VIDEO:
pri = PRI_PRIORITY;
break;
}
return m_rtmp->write(pri, streamID, messageType, timestamp, payload, len, startWithin, finishWithin);
}
std::shared_ptr<PosixStreamPlatformAdapter> m_adapter;
std::shared_ptr<RTMP> m_rtmp;
bool m_connectionOpen;
};
class RTMFPConnection : public Connection {
public:
void close() override
{
Connection::close();
if(m_controlSend)
m_controlSend->close();
if(m_controlRecv)
m_controlRecv->close(); // needed for AIR compatibility; this is not good, clean close should be on all RecvFlows closing.
m_netStreams.clear(); // closes all NetStream SendFlows
checkFinishedLater();
}
void shutdown() override
{
auto recvFlows = m_recvFlows;
for(auto it = recvFlows.begin(); it != recvFlows.end(); it++)
(*it)->close();
m_recvFlows.clear();
close();
}
bool acceptControl(const std::shared_ptr<RecvFlow> &controlRecv)
{
assert(not m_controlRecv);
uint32_t streamID = 0;
if((not TCMetadata::parse(controlRecv->getMetadata(), &streamID, nullptr)) or (0 != streamID))
return false;
if(not m_controlSend)
{
m_controlSend = controlRecv->openReturnFlow(TCMetadata::encode(0, RO_SEQUENCE), PRI_IMMEDIATE);
if(not m_controlSend)
return false;
wireControlSend();
}
controlRecv->onComplete = [this] (bool error) { callOnError(); };
if(verbose)
controlRecv->onFarAddressDidChange = [this, controlRecv] { printf("RTMFPConnection %p address changed %s\n", (void *)this, controlRecv->getFarAddress().toPresentation().c_str()); };
controlRecv->accept();
m_controlRecv = controlRecv;
setOnMessage(controlRecv, 0, nullptr);
controlRecv->setSessionCongestionDelay(delaycc_delay);
controlRecv->setSessionTrafficClass(dscp << 2);
return true;
}
protected:
struct NetStream {
~NetStream()
{
if(m_video) m_video->close();
if(m_audio) m_audio->close();
if(m_data) m_data->close();
}
SendFlow * openFlowForType(const std::shared_ptr<RecvFlow> &control, uint32_t streamID, uint8_t messageType)
{
Priority pri = PRI_IMMEDIATE;
ReceiveOrder rxIntent = RO_SEQUENCE;
std::shared_ptr<SendFlow> *flowRef = &m_data;
if(TCMSG_VIDEO == messageType)
{
flowRef = &m_video;
if(not interleave)
pri = PRI_PRIORITY; // lower than audio/data but still time-critical
rxIntent = mediaReceiveIntent;
}
else if(TCMSG_AUDIO == messageType)
{
flowRef = &m_audio;
rxIntent = mediaReceiveIntent;
}
if(not *flowRef)
{
*flowRef = control->openReturnFlow(TCMetadata::encode(streamID, rxIntent), pri);
if(interleave)
m_video = m_audio = m_data = *flowRef;
}
return flowRef->get();
}
std::shared_ptr<WriteReceipt> write(const std::shared_ptr<RecvFlow> &control, uint32_t streamID, uint8_t messageType, uint32_t timestamp, const uint8_t *payload, size_t len, Time startWithin, Time finishWithin)
{
if(not control)
return nullptr; // connection must be open before we can write to NetStream flows
auto flow = openFlowForType(control, streamID, messageType);
if(not flow)
return nullptr;
return flow->write(TCMessage::message(messageType, timestamp, payload, len), startWithin, finishWithin);
}
std::shared_ptr<SendFlow> m_video;
std::shared_ptr<SendFlow> m_audio;
std::shared_ptr<SendFlow> m_data;
};
std::shared_ptr<WriteReceipt> basicWrite(uint32_t streamID, uint8_t messageType, uint32_t timestamp, const uint8_t *payload, size_t len, Time startWithin, Time finishWithin) override
{
if(0 == streamID)
return m_controlSend->write(TCMessage::message(messageType, timestamp, payload, len), startWithin, finishWithin);
auto &stream = m_netStreams[streamID];
return stream.write(m_controlRecv, streamID, messageType, timestamp, payload, len, startWithin, finishWithin);
}
void wireControlSend()
{
m_controlSend->onException = [this] (uintmax_t reason) { callOnError(); };
m_controlSend->onRecvFlow = [this] (std::shared_ptr<RecvFlow> flow) { acceptOther(flow); };
}
void deliverMessage(uint32_t streamID, const uint8_t *bytes, size_t len)
{
uint8_t messageType = 0;
uint32_t timestamp = 0;
size_t rv = TCMessage::parseHeader(bytes, bytes + len, &messageType, ×tamp);
if(rv and onmessage)
onmessage(streamID, messageType, timestamp, bytes + rv, len - rv);
}
bool shouldAlwaysDeliver(const uint8_t *bytes, size_t len)
{
uint8_t messageType = 0;
size_t rv = TCMessage::parseHeader(bytes, bytes + len, &messageType, nullptr);
if(not rv)
return false;
switch(messageType)
{
case TCMSG_VIDEO: return isVideoSequenceSpecial(bytes + rv, len - rv);
case TCMSG_AUDIO: return isAudioSequenceSpecial(bytes + rv, len - rv);
default: return true;
}
}
void onLateMessage(const uint8_t *bytes, size_t len)
{
uint8_t messageType = 0;
if(not TCMessage::parseHeader(bytes, bytes + len, &messageType, nullptr))
return;
switch(messageType)
{
case TCMSG_VIDEO: m_videoMessagesLate++; break;
case TCMSG_AUDIO: m_audioMessagesLate++; break;
default: break;
}
}
void setOnMessage(const std::shared_ptr<RecvFlow> &flow, uint32_t streamID, const std::shared_ptr<ReorderBuffer> &reorderBuffer)
{
if(reorderBuffer)
{
reorderBuffer->onMessage = [this, streamID] (const uint8_t *bytes, size_t len, uintmax_t sequenceNumber, size_t fragmentCount, bool isLate) {
if((not isLate) or shouldAlwaysDeliver(bytes, len))
deliverMessage(streamID, bytes, len);
else
onLateMessage(bytes, len);
if(isLate and (verbose > 1))
printf("message %lu late, %s\n", (unsigned long)sequenceNumber, shouldAlwaysDeliver(bytes, len) ? "relayed anyway" : "dropped");
};
flow->onCumulativeAckDidMerge = [flow, reorderBuffer] {
reorderBuffer->deliverThrough(flow->getCumulativeAckSequenceNumber());
};
}
flow->onMessage = [this, streamID, flow, reorderBuffer] (const uint8_t *bytes, size_t len, uintmax_t sequenceNumber, size_t fragmentCount) {
uint32_t syncID = 0;
size_t count = 0;
if(FlowSyncManager::parse(bytes, len, syncID, count))
{
m_syncManager.sync(syncID, count, flow);
len = 0; // allow accounting for sequence numbers in reorderBuffer; deliverMessage will drop empty messages
}
if(reorderBuffer)
{
reorderBuffer->insert(bytes, len, sequenceNumber, fragmentCount);
reorderBuffer->deliverThrough(flow->getCumulativeAckSequenceNumber());
}
else
deliverMessage(streamID, bytes, len);
};
}
void acceptOther(const std::shared_ptr<RecvFlow> flow)
{
if(not m_controlRecv)
{
if(not acceptControl(flow))
callOnError();
return;
}
uint32_t streamID = 0;
ReceiveOrder rxOrder = RO_SEQUENCE;
if(not TCMetadata::parse(flow->getMetadata(), &streamID, &rxOrder))
return;
flow->setReceiveOrder(rxOrder);
flow->setBufferCapacity((1<<24) - 1024); // 16MB, big enough for largest TCMessage
std::shared_ptr<ReorderBuffer> reorderBuffer;
if(RO_NETWORK == rxOrder)
reorderBuffer = share_ref(new RunLoopReorderBuffer(&mainRL, reorderWindowPeriod), false);
flow->onComplete = [this, flow, reorderBuffer] (bool error) {
if(reorderBuffer)
reorderBuffer->flush();
m_recvFlows.erase(flow);
checkFinishedLater();
};
setOnMessage(flow, streamID, reorderBuffer);
flow->accept();
m_recvFlows.insert(flow);
}
virtual void checkFinished()
{
if(m_recvFlows.empty() and (not m_open) and (not isFinished()))
callOnShutdownComplete();
}
void checkFinishedLater()
{
auto myself = share_ref(this);
mainRL.doLater([this, myself] { checkFinished(); });
}
FlowSyncManager m_syncManager;
std::shared_ptr<SendFlow> m_controlSend;
std::shared_ptr<RecvFlow> m_controlRecv;
std::set<std::shared_ptr<RecvFlow>> m_recvFlows;
std::map<uint32_t, NetStream> m_netStreams;
};
class RTMFPOutgoingConnection : public RTMFPConnection {
public:
RTMFPOutgoingConnection() : m_platform(&mainRL, &mainPerformer, &workerPerformer)
{
m_platform.onShutdownCompleteCallback = [this] { m_rtmfpShutdownComplete = true; checkFinishedLater(); };
m_crypto.init(false, nullptr);
m_crypto.setHMACSendAlways(requireHMAC);
m_crypto.setHMACRecvRequired(requireHMAC);
m_crypto.setSSeqSendAlways(requireSSEQ);
m_crypto.setSSeqRecvRequired(requireSSEQ);
m_rtmfp = share_ref(new RTMFP(&m_platform, &m_crypto), false);
m_platform.setRtmfp(m_rtmfp.get());
m_rtmfp->setDefaultSessionKeepalivePeriod(10);
m_rtmfp->setDefaultSessionRetransmitLimit(20);
m_rtmfp->setDefaultSessionIdleLimit(120);
}
void shutdown() override
{
RTMFPConnection::shutdown();
m_rtmfp->shutdown(true);
}
protected:
void checkFinished() override
{
if(m_recvFlows.empty() and not m_open)
m_rtmfp->shutdown(false);
if(m_rtmfpShutdownComplete)
RTMFPConnection::checkFinished();
}
std::string findConnectUri(uint32_t streamID, uint8_t messageType, const uint8_t *payload, size_t len)
{
if(overrideRtmfpUri)
return overrideRtmfpUri;
if(len and (0 == streamID) and ((TCMSG_COMMAND == messageType) or (TCMSG_COMMAND_EX == messageType)))
{
const uint8_t *cursor = payload;
const uint8_t *limit = cursor + len;
if((TCMSG_COMMAND_EX == messageType) and (0 != *cursor++)) // COMMAND_EX has a format id, and only format id=0 is defined
goto notfound;
std::vector<std::shared_ptr<AMF0>> args;
if( (not AMF0::decode(cursor, limit, args))
or (args.size() < 3)
or (not args[0]->isString())
or (not args[2]->isObject())
or (0 != strcmp(args[0]->stringValue(), "connect"))
)
goto notfound;
auto tcUrl = args[2]->getValueAtKey("tcUrl");
if(tcUrl and tcUrl->isString())
return tcUrl->stringValue();
}
notfound:
return backupRtmfpUri;
}
void openConnection(const std::string &uri)
{
m_controlSend = m_rtmfp->openFlow(m_crypto.makeEPD(nullptr, uri.c_str(), nullptr), TCMetadata::encode(0, RO_SEQUENCE), PRI_IMMEDIATE);
wireControlSend();
m_platform.addUdpInterface(0, AF_INET);
m_platform.addUdpInterface(0, AF_INET6);
auto myself = share_ref(this);
lookup([this, myself] (const std::vector<Address> &results) {
if(m_open)
{
for(auto it = results.begin(); it != results.end(); it++)
m_controlSend->addCandidateAddress(*it);
}
});
}
std::shared_ptr<WriteReceipt> basicWrite(uint32_t streamID, uint8_t messageType, uint32_t timestamp, const uint8_t *payload, size_t len, Time startWithin, Time finishWithin) override
{
if(not m_controlSend)
openConnection(findConnectUri(streamID, messageType, payload, len));
return RTMFPConnection::basicWrite(streamID, messageType, timestamp, payload, len, startWithin, finishWithin);
}
FlashCryptoAdapter_OpenSSL m_crypto;
PerformerPosixPlatformAdapter m_platform;
std::shared_ptr<RTMFP> m_rtmfp;
bool m_rtmfpShutdownComplete { false };
};
class RTWebSocketConnection : public Connection {
public:
RTWebSocketConnection()
{}
bool setFd(int fd)
{
if(m_platformStream)
return false;
m_platformStream = share_ref(new PosixStreamPlatformAdapter(&mainRL), false);
m_wsMessageAdapter = share_ref(new rtws::SimpleWebSocketMessagePlatformAdapter(m_platformStream), false);
int tos = dscp << 2;
setsockopt(fd, IPPROTO_IP, IP_TOS, &tos, sizeof(tos));
setsockopt(fd, IPPROTO_IPV6, IPV6_TCLASS, &tos, sizeof(tos));
if(not m_platformStream->setSocketFd(fd))
{
::close(fd);
return false;
}
auto myself = share_ref(this);
m_platformStream->onShutdownCompleteCallback = [this, myself] { callOnShutdownComplete(); };
m_websock = share_ref(new SimpleWebSocket_OpenSSL(m_platformStream), false);
m_wsMessageAdapter->init(m_websock);
m_rtws = share_ref(new rtws::RTWebSocket(m_wsMessageAdapter), false);
m_wsMessageAdapter->onOpen = [this, myself] {
if(verbose) printf("RTWebSocketConnection %p WebSocket message adapter: onOpen\n", (void *)this);
m_rtws->init();
};
m_rtws->onRecvFlow = [this] (std::shared_ptr<rtws::RecvFlow> flow) { acceptControl(flow); };
m_rtws->onError = [this, myself] { callOnError(); };
m_rtws->minOutstandingThresh = 1024 * 16; // default 64KB probably too big
m_rtws->maxAdditionalDelay = (delaycc_delay < INFINITY) ? delaycc_delay : 120.0;
return true;
}
void acceptControl(std::shared_ptr<rtws::RecvFlow> flow)
{
uint32_t streamID = 0;
if(m_controlRecv or (not TCMetadata::parse(flow->getMetadata(), &streamID, nullptr)) or (0 != streamID))
return;
m_controlRecv = flow;
flow->onComplete = [this] { callOnError(); };
flow->accept();
setOnMessage(flow, streamID);
m_controlSend = flow->openReturnFlow(TCMetadata::encode(0, RO_SEQUENCE), PRI_IMMEDIATE);
m_controlSend->onException = [this] (uintmax_t reason, const std::string &description) { callOnError(); };
m_controlSend->onRecvFlow = [this] (std::shared_ptr<rtws::RecvFlow> flow) { acceptOther(flow); };
if(verbose) printf("RTWebSocketConnection %p accept control flow\n", (void *)this);
}
void close() override
{
Connection::close();
if(m_controlSend)
m_controlSend->close();
m_netStreams.clear();
if(m_rtws)
m_rtws->close();
if(m_platformStream)
m_platformStream->close();
}
void shutdown() override
{
close();
}
protected:
struct NetStream {
~NetStream()
{
if(m_video) m_video->close();
if(m_audio) m_audio->close();
if(m_data) m_data->close();
}
rtws::SendFlow * openFlowForType(const std::shared_ptr<rtws::RecvFlow> &control, uint32_t streamID, uint8_t messageType)
{
Priority pri = PRI_IMMEDIATE;
std::shared_ptr<rtws::SendFlow> *flowRef = &m_data;
if(TCMSG_VIDEO == messageType)
{
flowRef = &m_video;
if(not interleave)
pri = PRI_PRIORITY;
}
else if(TCMSG_AUDIO == messageType)
flowRef = &m_audio;
if(not *flowRef)
{
*flowRef = control->openReturnFlow(TCMetadata::encode(streamID, RO_SEQUENCE), pri);
if(interleave)
m_video = m_audio = m_data = *flowRef;
}
return flowRef->get();
}
std::shared_ptr<WriteReceipt> write(const std::shared_ptr<rtws::RecvFlow> &control, uint32_t streamID, uint8_t messageType, uint32_t timestamp, const uint8_t *payload, size_t len, Time startWithin, Time finishWithin)
{
auto flow = openFlowForType(control, streamID, messageType);
if(not flow)
return nullptr;
return flow->write(TCMessage::message(messageType, timestamp, payload, len), startWithin, finishWithin);
}
std::shared_ptr<rtws::SendFlow> m_video;
std::shared_ptr<rtws::SendFlow> m_audio;
std::shared_ptr<rtws::SendFlow> m_data;
};
std::shared_ptr<WriteReceipt> basicWrite(uint32_t streamID, uint8_t messageType, uint32_t timestamp, const uint8_t *payload, size_t len, Time startWithin, Time finishWithin) override
{
if(0 == streamID)
return m_controlSend->write(TCMessage::message(messageType, timestamp, payload, len), startWithin, finishWithin);
auto &stream = m_netStreams[streamID];
return stream.write(m_controlRecv, streamID, messageType, timestamp, payload, len, startWithin, finishWithin);
}
void setOnMessage(std::shared_ptr<rtws::RecvFlow> flow, uint32_t streamID)
{
flow->onMessage = [this, streamID] (const uint8_t *bytes, size_t len, uintmax_t messageNumber) {
uint32_t syncID = 0;
size_t count = 0;
if(FlowSyncManager::parse(bytes, len, syncID, count))
return; // TODO make a FlowSyncManager for RTWS. don't relay flow sync messages.
uint8_t messageType = 0;
uint32_t timestamp = 0;
size_t rv = TCMessage::parseHeader(bytes, bytes + len, &messageType, ×tamp);
if(rv and onmessage)
onmessage(streamID, messageType, timestamp, bytes + rv, len - rv);
};
}
void acceptOther(std::shared_ptr<rtws::RecvFlow> flow)
{
if(not m_open)
return;
uint32_t streamID = 0;
if(not TCMetadata::parse(flow->getMetadata(), &streamID, nullptr))
return;
flow->setBufferCapacity((1<<24) - 1);
flow->onComplete = [this, flow] {
m_recvFlows.erase(flow);
};
setOnMessage(flow, streamID);
flow->accept();
m_recvFlows.insert(flow);
}
std::shared_ptr<rtws::SendFlow> m_controlSend;
std::shared_ptr<rtws::RecvFlow> m_controlRecv;
std::set<std::shared_ptr<rtws::RecvFlow>> m_recvFlows;
std::map<uint32_t, NetStream> m_netStreams;
std::shared_ptr<rtws::RTWebSocket> m_rtws;
std::shared_ptr<SimpleWebSocket> m_websock;
std::shared_ptr<rtws::SimpleWebSocketMessagePlatformAdapter> m_wsMessageAdapter;
std::shared_ptr<PosixStreamPlatformAdapter> m_platformStream;
};
class Client : public Object {
public:
~Client()
{
if(verbose > 1) printf("~Client %p\n", (void *)this);
}