Debian Codegraph @

srtcore/group.h

raw
1 /*
2 * SRT - Secure, Reliable, Transport
3 * Copyright (c) 2020 Haivision Systems Inc.
4 *
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
8 *
9 */
10
11 /*****************************************************************************
12 Written by
13 Haivision Systems Inc.
14 *****************************************************************************/
15
16 #ifndef INC_SRT_GROUP_H
17 #define INC_SRT_GROUP_H
18
19 #include "srt.h"
20 #include "common.h"
21 #include "packet.h"
22 #include "group_common.h"
23 #include "group_backup.h"
24
25 namespace srt
26 {
27
28 #if ENABLE_HEAVY_LOGGING
29 const char* const srt_log_grp_state[] = {"PENDING", "IDLE", "RUNNING", "BROKEN"};
30 #endif
31
32
33 class CUDTGroup
34 {
35 friend class CUDTUnited;
36
37 typedef sync::steady_clock::time_point time_point;
38 typedef sync::steady_clock::duration duration;
39 typedef sync::steady_clock steady_clock;
40 typedef groups::SocketData SocketData;
41 typedef groups::SendBackupCtx SendBackupCtx;
42 typedef groups::BackupMemberState BackupMemberState;
43
44 public:
45 typedef SRT_MEMBERSTATUS GroupState;
46
47 // Note that the use of states may differ in particular group types:
48 //
49 // Broadcast: links that are freshly connected become PENDING and then IDLE only
50 // for a short moment to be activated immediately at the nearest sending operation.
51 //
52 // Balancing: like with broadcast, just that the link activation gets its shared percentage
53 // of traffic balancing
54 //
55 // Multicast: The link is never idle. The data are always sent over the UDP multicast link
56 // and the receiver simply gets subscribed and reads packets once it's ready.
57 //
58 // Backup: The link stays idle until it's activated, and the activation can only happen
59 // at the moment when the currently active link is "suspected of being likely broken"
60 // (the current active link fails to receive ACK in a time when two ACKs should already
61 // be received). After a while when the current active link is confirmed broken, it turns
62 // into broken state.
63
64 static const char* StateStr(GroupState);
65
66 static int32_t s_tokenGen;
67 static int32_t genToken() { ++s_tokenGen; if (s_tokenGen < 0) s_tokenGen = 0; return s_tokenGen;}
68
69 struct ConfigItem
70 {
71 SRT_SOCKOPT so;
72 std::vector<unsigned char> value;
73
74 template <class T>
75 bool get(T& refr)
76 {
77 if (sizeof(T) > value.size())
78 return false;
79 refr = *(T*)&value[0];
80 return true;
81 }
82
83 ConfigItem(SRT_SOCKOPT o, const void* val, int size)
84 : so(o)
85 {
86 value.resize(size);
87 unsigned char* begin = (unsigned char*)val;
88 std::copy(begin, begin + size, value.begin());
89 }
90
91 struct OfType
92 {
93 SRT_SOCKOPT so;
94 OfType(SRT_SOCKOPT soso)
95 : so(soso)
96 {
97 }
98 bool operator()(ConfigItem& ci) { return ci.so == so; }
99 };
100 };
101
102 typedef std::list<SocketData> group_t;
103 typedef group_t::iterator gli_t;
104 typedef std::vector< std::pair<SRTSOCKET, srt::CUDTSocket*> > sendable_t;
105
106 struct Sendstate
107 {
108 SRTSOCKET id;
109 SocketData* mb;
110 int stat;
111 int code;
112 };
113
114 CUDTGroup(SRT_GROUP_TYPE);
115 ~CUDTGroup();
116
117 SocketData* add(SocketData data);
118
119 struct HaveID
120 {
121 SRTSOCKET id;
122 HaveID(SRTSOCKET sid)
123 : id(sid)
124 {
125 }
126 bool operator()(const SocketData& s) { return s.id == id; }
127 };
128
129 bool contains(SRTSOCKET id, SocketData*& w_f)
130 {
131 srt::sync::ScopedLock g(m_GroupLock);
132 gli_t f = std::find_if(m_Group.begin(), m_Group.end(), HaveID(id));
133 if (f == m_Group.end())
134 {
135 w_f = NULL;
136 return false;
137 }
138 w_f = &*f;
139 return true;
140 }
141
142 // NEED LOCKING
143 gli_t begin() { return m_Group.begin(); }
144 gli_t end() { return m_Group.end(); }
145
146 /// Remove the socket from the group container.
147 /// REMEMBER: the group spec should be taken from the socket
148 /// (set m_GroupOf and m_GroupMemberData to NULL
149 /// PRIOR TO calling this function.
150 /// @param id Socket ID to look for in the container to remove
151 /// @return true if the container still contains any sockets after the operation
152 bool remove(SRTSOCKET id)
153 {
154 using srt_logging::gmlog;
155 srt::sync::ScopedLock g(m_GroupLock);
156
157 bool empty = false;
158 LOGC(gmlog.Note, log << "group/remove: removing member @" << id << " from group $" << m_GroupID);
159
160 gli_t f = std::find_if(m_Group.begin(), m_Group.end(), HaveID(id));
161 if (f != m_Group.end())
162 {
163 m_Group.erase(f);
164
165 // Reset sequence numbers on a dead group so that they are
166 // initialized anew with the new alive connection within
167 // the group.
168 // XXX The problem is that this should be done after the
169 // socket is considered DISCONNECTED, not when it's being
170 // closed. After being disconnected, the sequence numbers
171 // are no longer valid, and will be reinitialized when the
172 // socket is connected again. This may stay as is for now
173 // as in SRT it's not predicted to do anything with the socket
174 // that was disconnected other than immediately closing it.
175 if (m_Group.empty())
176 {
177 // When the group is empty, there's no danger that this
178 // number will collide with any ISN provided by a socket.
179 // Also since now every socket will derive this ISN.
180 m_iLastSchedSeqNo = generateISN();
181 resetInitialRxSequence();
182 empty = true;
183 }
184 }
185 else
186 {
187 HLOGC(gmlog.Debug, log << "group/remove: IPE: id @" << id << " NOT FOUND");
188 empty = true; // not exactly true, but this is to cause error on group in the APP
189 }
190
191 if (m_Group.empty())
192 {
193 m_bOpened = false;
194 m_bConnected = false;
195 }
196
197 return !empty;
198 }
199
200 bool groupEmpty()
201 {
202 srt::sync::ScopedLock g(m_GroupLock);
203 return m_Group.empty();
204 }
205
206 void setGroupConnected();
207
208 int send(const char* buf, int len, SRT_MSGCTRL& w_mc);
209 int sendBroadcast(const char* buf, int len, SRT_MSGCTRL& w_mc);
210 int sendBackup(const char* buf, int len, SRT_MSGCTRL& w_mc);
211 static int32_t generateISN();
212
213 private:
214 // For Backup, sending all previous packet
215 int sendBackupRexmit(srt::CUDT& core, SRT_MSGCTRL& w_mc);
216
217 // Support functions for sendBackup and sendBroadcast
218 /// Check if group member is idle.
219 /// @param d group member
220 /// @param[in,out] w_wipeme array of sockets to remove from group
221 /// @param[in,out] w_pendingLinks array of sockets pending for connection
222 /// @returns true if d is idle (standby), false otherwise
223 bool send_CheckIdle(const gli_t d, std::vector<SRTSOCKET>& w_wipeme, std::vector<SRTSOCKET>& w_pendingLinks);
224
225
226 /// This function checks if the member has just become idle (check if sender buffer is empty) to send a KEEPALIVE immediately.
227 /// @todo Check it is some abandoned logic.
228 void sendBackup_CheckIdleTime(gli_t w_d);
229
230 /// Qualify states of member links.
231 /// [[using locked(this->m_GroupLock, m_pGlobal->m_GlobControlLock)]]
232 /// @param[out] w_sendBackupCtx the context will be updated with state qualifications
233 /// @param[in] currtime current timestamp
234 void sendBackup_QualifyMemberStates(SendBackupCtx& w_sendBackupCtx, const steady_clock::time_point& currtime);
235
236 void sendBackup_AssignBackupState(srt::CUDT& socket, BackupMemberState state, const steady_clock::time_point& currtime);
237
238 /// Qualify the state of the active link: fresh, stable, unstable, wary.
239 /// @retval active backup member state: fresh, stable, unstable, wary.
240 BackupMemberState sendBackup_QualifyActiveState(const gli_t d, const time_point currtime);
241
242 BackupMemberState sendBackup_QualifyIfStandBy(const gli_t d);
243
244 /// Sends the same payload over all active members.
245 /// @param[in] buf payload
246 /// @param[in] len payload length in bytes
247 /// @param[in,out] w_mc message control
248 /// @param[in] currtime current time
249 /// @param[in] currseq current packet sequence number
250 /// @param[out] w_nsuccessful number of members with successful sending.
251 /// @param[in,out] maxActiveWeight
252 /// @param[in,out] sendBackupCtx context
253 /// @param[in,out] w_cx error
254 /// @return group send result: -1 if sending over all members has failed; number of bytes sent otherwise.
255 int sendBackup_SendOverActive(const char* buf, int len, SRT_MSGCTRL& w_mc, const steady_clock::time_point& currtime, int32_t& w_curseq,
256 size_t& w_nsuccessful, uint16_t& w_maxActiveWeight, SendBackupCtx& w_sendBackupCtx, CUDTException& w_cx);
257
258 /// Check link sending status
259 /// @param[in] currtime Current time (logging only)
260 /// @param[in] send_status Result of sending over the socket
261 /// @param[in] lastseq Last sent sequence number before the current sending operation
262 /// @param[in] pktseq Packet sequence number currently tried to be sent
263 /// @param[out] w_u CUDT unit of the current member (to allow calling overrideSndSeqNo)
264 /// @param[out] w_curseq Group's current sequence number (either -1 or the value used already for other links)
265 /// @param[out] w_final_stat w_final_stat = send_status if sending succeeded.
266 ///
267 /// @returns true if the sending operation result (submitted in stat) is a success, false otherwise.
268 bool sendBackup_CheckSendStatus(const time_point& currtime,
269 const int send_status,
270 const int32_t lastseq,
271 const int32_t pktseq,
272 CUDT& w_u,
273 int32_t& w_curseq,
274 int& w_final_stat);
275 void sendBackup_Buffering(const char* buf, const int len, int32_t& curseq, SRT_MSGCTRL& w_mc);
276
277 size_t sendBackup_TryActivateStandbyIfNeeded(
278 const char* buf,
279 const int len,
280 bool& w_none_succeeded,
281 SRT_MSGCTRL& w_mc,
282 int32_t& w_curseq,
283 int32_t& w_final_stat,
284 SendBackupCtx& w_sendBackupCtx,
285 CUDTException& w_cx,
286 const steady_clock::time_point& currtime);
287
288 /// Check if pending sockets are to be qualified as broken.
289 /// This qualification later results in removing the socket from a group and closing it.
290 /// @param[in,out] a context with a list of member sockets, some pending might qualified broken
291 void sendBackup_CheckPendingSockets(SendBackupCtx& w_sendBackupCtx, const steady_clock::time_point& currtime);
292
293 /// Check if unstable sockets are to be qualified as broken.
294 /// The main reason for such qualification is if a socket is unstable for too long.
295 /// This qualification later results in removing the socket from a group and closing it.
296 /// @param[in,out] a context with a list of member sockets, some pending might qualified broken
297 void sendBackup_CheckUnstableSockets(SendBackupCtx& w_sendBackupCtx, const steady_clock::time_point& currtime);
298
299 /// @brief Marks broken sockets as closed. Used in broadcast sending.
300 /// @param w_wipeme a list of sockets to close
301 void send_CloseBrokenSockets(std::vector<SRTSOCKET>& w_wipeme);
302
303 /// @brief Marks broken sockets as closed. Used in backup sending.
304 /// @param w_sendBackupCtx the context with a list of broken sockets
305 void sendBackup_CloseBrokenSockets(SendBackupCtx& w_sendBackupCtx);
306
307 void sendBackup_RetryWaitBlocked(SendBackupCtx& w_sendBackupCtx,
308 int& w_final_stat,
309 bool& w_none_succeeded,
310 SRT_MSGCTRL& w_mc,
311 CUDTException& w_cx);
312 void sendBackup_SilenceRedundantLinks(SendBackupCtx& w_sendBackupCtx, const steady_clock::time_point& currtime);
313
314 void send_CheckValidSockets();
315
316 SRT_KM_STATE getGroupEncryptionState();
317
318 public:
319 int recv(char* buf, int len, SRT_MSGCTRL& w_mc);
320
321 void close();
322
323 void setOpt(SRT_SOCKOPT optname, const void* optval, int optlen);
324 void getOpt(SRT_SOCKOPT optName, void* optval, int& w_optlen);
325 void deriveSettings(srt::CUDT* source);
326 bool applyFlags(uint32_t flags, HandshakeSide);
327
328 SRT_SOCKSTATUS getStatus();
329
330 void debugMasterData(SRTSOCKET slave);
331
332 bool isGroupReceiver()
333 {
334 // XXX add here also other group types, which
335 // predict group receiving.
336 return m_type == SRT_GTYPE_BROADCAST;
337 }
338
339 sync::Mutex* exp_groupLock() { return &m_GroupLock; }
340 void addEPoll(int eid);
341 void removeEPollEvents(const int eid);
342 void removeEPollID(const int eid);
343
344 /// @brief Update read-ready state.
345 /// @param sock member socket ID (unused)
346 /// @param sequence the latest packet sequence number available for reading.
347 void updateReadState(SRTSOCKET sock, int32_t sequence);
348
349 void updateWriteState();
350 void updateFailedLink();
351 void activateUpdateEvent(bool still_have_items);
352 int32_t getRcvBaseSeqNo();
353
354 /// Update the in-group array of packet providers per sequence number.
355 /// Also basing on the information already provided by possibly other sockets,
356 /// report the real status of packet loss, including packets maybe lost
357 /// by the caller provider, but already received from elsewhere. Note that
358 /// these packets are not ready for extraction until ACK-ed.
359 ///
360 /// @param exp_sequence The previously received sequence at this socket
361 /// @param sequence The sequence of this packet
362 /// @param provider The core of the socket for which the packet was dispatched
363 /// @param time TSBPD time of this packet
364 /// @return The bitmap that marks by 'false' packets lost since next to exp_sequence
365 std::vector<bool> providePacket(int32_t exp_sequence, int32_t sequence, srt::CUDT* provider, uint64_t time);
366
367 /// This is called from the ACK action by particular socket, which
368 /// actually signs off the packet for extraction.
369 ///
370 /// @param core The socket core for which the ACK was sent
371 /// @param ack The past-the-last-received ACK sequence number
372 void readyPackets(srt::CUDT* core, int32_t ack);
373
374 void syncWithSocket(const srt::CUDT& core, const HandshakeSide side);
375 int getGroupData(SRT_SOCKGROUPDATA* pdata, size_t* psize);
376 int getGroupData_LOCKED(SRT_SOCKGROUPDATA* pdata, size_t* psize);
377
378 /// Predicted to be called from the reading function to fill
379 /// the group data array as requested.
380 void fillGroupData(SRT_MSGCTRL& w_out, //< MSGCTRL to be written
381 const SRT_MSGCTRL& in //< MSGCTRL read from the data-providing socket
382 );
383
384 void copyGroupData(const CUDTGroup::SocketData& source, SRT_SOCKGROUPDATA& w_target);
385
386 #if ENABLE_HEAVY_LOGGING
387 void debugGroup();
388 #else
389 void debugGroup() {}
390 #endif
391
392 void ackMessage(int32_t msgno);
393 void processKeepalive(SocketData*);
394 void internalKeepalive(SocketData*);
395
396 private:
397 // Check if there's at least one connected socket.
398 // If so, grab the status of all member sockets.
399 void getGroupCount(size_t& w_size, bool& w_still_alive);
400
401 srt::CUDTUnited& m_Global;
402 srt::sync::Mutex m_GroupLock;
403
404 SRTSOCKET m_GroupID;
405 SRTSOCKET m_PeerGroupID;
406 struct GroupContainer
407 {
408 private:
409 std::list<SocketData> m_List;
410 sync::atomic<size_t> m_SizeCache;
411
412 /// This field is used only by some types of groups that need
413 /// to keep track as to which link was lately used. Note that
414 /// by removal of a node from the m_List container, this link
415 /// must be appropriately reset.
416 gli_t m_LastActiveLink;
417
418 public:
419
420 GroupContainer()
421 : m_SizeCache(0)
422 , m_LastActiveLink(m_List.end())
423 {
424 }
425
426 // Property<gli_t> active = { m_LastActiveLink; }
427 SRTU_PROPERTY_RW(gli_t, active, m_LastActiveLink);
428
429 gli_t begin() { return m_List.begin(); }
430 gli_t end() { return m_List.end(); }
431 bool empty() { return m_List.empty(); }
432 void push_back(const SocketData& data) { m_List.push_back(data); ++m_SizeCache; }
433 void clear()
434 {
435 m_LastActiveLink = end();
436 m_List.clear();
437 m_SizeCache = 0;
438 }
439 size_t size() { return m_SizeCache; }
440
441 void erase(gli_t it);
442 };
443 GroupContainer m_Group;
444 SRT_GROUP_TYPE m_type;
445 CUDTSocket* m_listener; // A "group" can only have one listener.
446 srt::sync::atomic<int> m_iBusy;
447 CallbackHolder<srt_connect_callback_fn> m_cbConnectHook;
448 void installConnectHook(srt_connect_callback_fn* hook, void* opaq)
449 {
450 m_cbConnectHook.set(opaq, hook);
451 }
452
453 public:
454 void apiAcquire() { ++m_iBusy; }
455 void apiRelease() { --m_iBusy; }
456
457 // A normal cycle of the send/recv functions is the following:
458 // - [Initial API call for a group]
459 // - GroupKeeper - ctor
460 // - LOCK: GlobControlLock
461 // - Find the group ID in the group container (break if not found)
462 // - LOCK: GroupLock of that group
463 // - Set BUSY flag
464 // - UNLOCK GroupLock
465 // - UNLOCK GlobControlLock
466 // - [Call the sending function (sendBroadcast/sendBackup)]
467 // - LOCK GroupLock
468 // - Preparation activities
469 // - Loop over group members
470 // - Send over a single socket
471 // - Check send status and conditions
472 // - Exit, if nothing else to be done
473 // - Check links to send extra
474 // - UNLOCK GroupLock
475 // - Wait for first ready link
476 // - LOCK GroupLock
477 // - Check status and find sendable link
478 // - Send over a single socket
479 // - Check status and update data
480 // - UNLOCK GroupLock, Exit
481 // - GroupKeeper - dtor
482 // - LOCK GroupLock
483 // - Clear BUSY flag
484 // - UNLOCK GroupLock
485 // END.
486 //
487 // The possibility for isStillBusy to go on is only the following:
488 // 1. Before calling the API function. As GlobControlLock is locked,
489 // the nearest lock on GlobControlLock by GroupKeeper can happen:
490 // - before the group is moved to ClosedGroups (this allows it to be found)
491 // - after the group is moved to ClosedGroups (this makes the group not found)
492 // - NOT after the group was deleted, as it could not be found and occupied.
493 //
494 // 2. Before release of GlobControlLock (acquired by GC), but before the
495 // API function locks GroupLock:
496 // - the GC call to isStillBusy locks GroupLock, but BUSY flag is already set
497 // - GC then avoids deletion of the group
498 //
499 // 3. In any further place up to the exit of the API implementation function,
500 // the BUSY flag is still set.
501 //
502 // 4. After exit of GroupKeeper destructor and unlock of GroupLock
503 // - the group is no longer being accessed and can be freely deleted.
504 // - the group also can no longer be found by ID.
505
506 bool isStillBusy()
507 {
508 sync::ScopedLock glk(m_GroupLock);
509 return m_iBusy || !m_Group.empty();
510 }
511
512 struct BufferedMessageStorage
513 {
514 size_t blocksize;
515 size_t maxstorage;
516 std::vector<char*> storage;
517
518 BufferedMessageStorage(size_t blk, size_t max = 0)
519 : blocksize(blk)
520 , maxstorage(max)
521 , storage()
522 {
523 }
524
525 char* get()
526 {
527 if (storage.empty())
528 return new char[blocksize];
529
530 // Get the element from the end
531 char* block = storage.back();
532 storage.pop_back();
533 return block;
534 }
535
536 void put(char* block)
537 {
538 if (storage.size() >= maxstorage)
539 {
540 // Simply delete
541 delete[] block;
542 return;
543 }
544
545 // Put the block into the spare buffer
546 storage.push_back(block);
547 }
548
549 ~BufferedMessageStorage()
550 {
551 for (size_t i = 0; i < storage.size(); ++i)
552 delete[] storage[i];
553 }
554 };
555
556 struct BufferedMessage
557 {
558 static BufferedMessageStorage storage;
559
560 SRT_MSGCTRL mc;
561 mutable char* data;
562 size_t size;
563
564 BufferedMessage()
565 : data()
566 , size()
567 {
568 }
569 ~BufferedMessage()
570 {
571 if (data)
572 storage.put(data);
573 }
574
575 // NOTE: size 's' must be checked against SRT_LIVE_MAX_PLSIZE
576 // before calling
577 void copy(const char* buf, size_t s)
578 {
579 size = s;
580 data = storage.get();
581 memcpy(data, buf, s);
582 }
583
584 BufferedMessage(const BufferedMessage& foreign)
585 : mc(foreign.mc)
586 , data(foreign.data)
587 , size(foreign.size)
588 {
589 foreign.data = 0;
590 }
591
592 BufferedMessage& operator=(const BufferedMessage& foreign)
593 {
594 data = foreign.data;
595 size = foreign.size;
596 mc = foreign.mc;
597
598 foreign.data = 0;
599 return *this;
600 }
601
602 private:
603 void swap_with(BufferedMessage& b)
604 {
605 std::swap(this->mc, b.mc);
606 std::swap(this->data, b.data);
607 std::swap(this->size, b.size);
608 }
609 };
610
611 typedef std::deque<BufferedMessage> senderBuffer_t;
612 // typedef StaticBuffer<BufferedMessage, 1000> senderBuffer_t;
613
614 private:
615 // Fields required for SRT_GTYPE_BACKUP groups.
616 senderBuffer_t m_SenderBuffer; // This mechanism is to be removed on group-common sndbuf
617 int32_t m_iSndOldestMsgNo; // oldest position in the sender buffer
618 sync::atomic<int32_t> m_iSndAckedMsgNo;
619 uint32_t m_uOPT_MinStabilityTimeout_us;
620
621 // THIS function must be called only in a function for a group type
622 // that does use sender buffer.
623 int32_t addMessageToBuffer(const char* buf, size_t len, SRT_MSGCTRL& w_mc);
624
625 std::set<int> m_sPollID; // set of epoll ID to trigger
626 int m_iMaxPayloadSize;
627 int m_iAvgPayloadSize;
628 bool m_bSynRecving;
629 bool m_bSynSending;
630 bool m_bTsbPd;
631 bool m_bTLPktDrop;
632 int64_t m_iTsbPdDelay_us;
633 int m_RcvEID;
634 class CEPollDesc* m_RcvEpolld;
635 int m_SndEID;
636 class CEPollDesc* m_SndEpolld;
637
638 int m_iSndTimeOut; // sending timeout in milliseconds
639 int m_iRcvTimeOut; // receiving timeout in milliseconds
640
641 // Start times for TsbPd. These times shall be synchronized
642 // between all sockets in the group. The first connected one
643 // defines it, others shall derive it. The value 0 decides if
644 // this has been already set.
645 time_point m_tsStartTime;
646 time_point m_tsRcvPeerStartTime;
647
648 void recv_CollectAliveAndBroken(std::vector<srt::CUDTSocket*>& w_alive, std::set<srt::CUDTSocket*>& w_broken);
649
650 /// The function polls alive member sockets and retrieves a list of read-ready.
651 /// [acquires lock for CUDT::uglobal()->m_GlobControlLock]
652 /// [[using locked(m_GroupLock)]] temporally unlocks-locks internally
653 ///
654 /// @returns list of read-ready sockets
655 /// @throws CUDTException(MJ_CONNECTION, MN_NOCONN, 0)
656 /// @throws CUDTException(MJ_AGAIN, MN_RDAVAIL, 0)
657 std::vector<srt::CUDTSocket*> recv_WaitForReadReady(const std::vector<srt::CUDTSocket*>& aliveMembers, std::set<srt::CUDTSocket*>& w_broken);
658
659 // This is the sequence number of a packet that has been previously
660 // delivered. Initially it should be set to SRT_SEQNO_NONE so that the sequence read
661 // from the first delivering socket will be taken as a good deal.
662 sync::atomic<int32_t> m_RcvBaseSeqNo;
663
664 bool m_bOpened; // Set to true when at least one link is at least pending
665 bool m_bConnected; // Set to true on first link confirmed connected
666 bool m_bClosing;
667
668 // There's no simple way of transforming config
669 // items that are predicted to be used on socket.
670 // Use some options for yourself, store the others
671 // for setting later on a socket.
672 std::vector<ConfigItem> m_config;
673
674 // Signal for the blocking user thread that the packet
675 // is ready to deliver.
676 sync::Condition m_RcvDataCond;
677 sync::Mutex m_RcvDataLock;
678 sync::atomic<int32_t> m_iLastSchedSeqNo; // represetnts the value of CUDT::m_iSndNextSeqNo for each running socket
679 sync::atomic<int32_t> m_iLastSchedMsgNo;
680 // Statistics
681
682 struct Stats
683 {
684 // Stats state
685 time_point tsActivateTime; // Time when this group sent or received the first data packet
686 time_point tsLastSampleTime; // Time reset when clearing stats
687
688 stats::Metric<stats::BytesPackets> sent; // number of packets sent from the application
689 stats::Metric<stats::BytesPackets> recv; // number of packets delivered from the group to the application
690 stats::Metric<stats::BytesPackets> recvDrop; // number of packets dropped by the group receiver (not received from any member)
691 stats::Metric<stats::BytesPackets> recvDiscard; // number of packets discarded as already delivered
692
693 void init()
694 {
695 tsActivateTime = srt::sync::steady_clock::time_point();
696 tsLastSampleTime = srt::sync::steady_clock::now();
697 sent.reset();
698 recv.reset();
699 recvDrop.reset();
700 recvDiscard.reset();
701 }
702
703 void reset()
704 {
705 tsLastSampleTime = srt::sync::steady_clock::now();
706
707 sent.resetTrace();
708 recv.resetTrace();
709 recvDrop.resetTrace();
710 recvDiscard.resetTrace();
711 }
712 } m_stats;
713
714 void updateAvgPayloadSize(int size)
715 {
716 if (m_iAvgPayloadSize == -1)
717 m_iAvgPayloadSize = size;
718 else
719 m_iAvgPayloadSize = avg_iir<4>(m_iAvgPayloadSize, size);
720 }
721
722 int avgRcvPacketSize()
723 {
724 // In case when no packet has been received yet, but already notified
725 // a dropped packet, its size will be SRT_LIVE_DEF_PLSIZE. It will be
726 // the value most matching in the typical uses, although no matter what
727 // value would be used here, each one would be wrong from some points
728 // of view. This one is simply the best choice for typical uses of groups
729 // provided that they are to be ued only for live mode.
730 return m_iAvgPayloadSize == -1 ? SRT_LIVE_DEF_PLSIZE : m_iAvgPayloadSize;
731 }
732
733 public:
734 void bstatsSocket(CBytePerfMon* perf, bool clear);
735
736 // Required after the call on newGroup on the listener side.
737 // On the listener side the group is lazily created just before
738 // accepting a new socket and therefore always open.
739 void setOpen() { m_bOpened = true; }
740
741 std::string CONID() const
742 {
743 #if ENABLE_LOGGING
744 std::ostringstream os;
745 os << "@" << m_GroupID << ":";
746 return os.str();
747 #else
748 return "";
749 #endif
750 }
751
752 void resetInitialRxSequence()
753 {
754 // The app-reader doesn't care about the real sequence number.
755 // The first provided one will be taken as a good deal; even if
756 // this is going to be past the ISN, at worst it will be caused
757 // by TLPKTDROP.
758 m_RcvBaseSeqNo = SRT_SEQNO_NONE;
759 }
760
761 bool applyGroupTime(time_point& w_start_time, time_point& w_peer_start_time)
762 {
763 using srt::sync::is_zero;
764 using srt_logging::gmlog;
765
766 if (is_zero(m_tsStartTime))
767 {
768 // The first socket, defines the group time for the whole group.
769 m_tsStartTime = w_start_time;
770 m_tsRcvPeerStartTime = w_peer_start_time;
771 return true;
772 }
773
774 // Sanity check. This should never happen, fix the bug if found!
775 if (is_zero(m_tsRcvPeerStartTime))
776 {
777 LOGC(gmlog.Error, log << "IPE: only StartTime is set, RcvPeerStartTime still 0!");
778 // Kinda fallback, but that's not too safe.
779 m_tsRcvPeerStartTime = w_peer_start_time;
780 }
781
782 // The redundant connection, derive the times
783 w_start_time = m_tsStartTime;
784 w_peer_start_time = m_tsRcvPeerStartTime;
785
786 return false;
787 }
788
789 // Live state synchronization
790 bool getBufferTimeBase(srt::CUDT* forthesakeof, time_point& w_tb, bool& w_wp, duration& w_dr);
791 bool applyGroupSequences(SRTSOCKET, int32_t& w_snd_isn, int32_t& w_rcv_isn);
792
793 /// @brief Synchronize TSBPD base time and clock drift among members using the @a srcMember as a reference.
794 /// @param srcMember a reference for synchronization.
795 void synchronizeDrift(const srt::CUDT* srcMember);
796
797 void updateLatestRcv(srt::CUDTSocket*);
798
799 // Property accessors
800 SRTU_PROPERTY_RW_CHAIN(CUDTGroup, SRTSOCKET, id, m_GroupID);
801 SRTU_PROPERTY_RW_CHAIN(CUDTGroup, SRTSOCKET, peerid, m_PeerGroupID);
802 SRTU_PROPERTY_RW_CHAIN(CUDTGroup, SRT_GROUP_TYPE, type, m_type);
803 SRTU_PROPERTY_RW_CHAIN(CUDTGroup, int32_t, currentSchedSequence, m_iLastSchedSeqNo);
804 SRTU_PROPERTY_RRW(std::set<int>&, epollset, m_sPollID);
805 SRTU_PROPERTY_RW_CHAIN(CUDTGroup, int64_t, latency_us, m_iTsbPdDelay_us);
806 SRTU_PROPERTY_RO(bool, closing, m_bClosing);
807 };
808
809 } // namespace srt
810
811 #endif // INC_SRT_GROUP_H