Debian Codegraph @

srtcore/buffer_snd.cpp

raw
1 /*
2 * SRT - Secure, Reliable, Transport
3 * Copyright (c) 2018 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 Copyright (c) 2001 - 2011, The Board of Trustees of the University of Illinois.
13 All rights reserved.
14
15 Redistribution and use in source and binary forms, with or without
16 modification, are permitted provided that the following conditions are
17 met:
18
19 * Redistributions of source code must retain the above
20 copyright notice, this list of conditions and the
21 following disclaimer.
22
23 * Redistributions in binary form must reproduce the
24 above copyright notice, this list of conditions
25 and the following disclaimer in the documentation
26 and/or other materials provided with the distribution.
27
28 * Neither the name of the University of Illinois
29 nor the names of its contributors may be used to
30 endorse or promote products derived from this
31 software without specific prior written permission.
32
33 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
34 IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
35 THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
36 PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
37 CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
38 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
39 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
40 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
41 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
42 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
43 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
44 *****************************************************************************/
45
46 /*****************************************************************************
47 written by
48 Yunhong Gu, last updated 03/12/2011
49 modified by
50 Haivision Systems Inc.
51 *****************************************************************************/
52
53 #include "platform_sys.h"
54
55 #include <cmath>
56 #include "buffer_snd.h"
57 #include "packet.h"
58 #include "core.h" // provides some constants
59 #include "logging.h"
60
61 namespace srt {
62
63 using namespace std;
64 using namespace srt_logging;
65 using namespace sync;
66
67 CSndBuffer::CSndBuffer(int ip_family, int size, int maxpld, int authtag)
68 : m_BufLock()
69 , m_pBlock(NULL)
70 , m_pFirstBlock(NULL)
71 , m_pCurrBlock(NULL)
72 , m_pLastBlock(NULL)
73 , m_pBuffer(NULL)
74 , m_iNextMsgNo(1)
75 , m_iSize(size)
76 , m_iBlockLen(maxpld)
77 , m_iAuthTagSize(authtag)
78 , m_iCount(0)
79 , m_iBytesCount(0)
80 , m_rateEstimator(ip_family)
81 {
82 // initial physical buffer of "size"
83 m_pBuffer = new Buffer;
84 m_pBuffer->m_pcData = new char[m_iSize * m_iBlockLen];
85 m_pBuffer->m_iSize = m_iSize;
86 m_pBuffer->m_pNext = NULL;
87
88 // circular linked list for out bound packets
89 m_pBlock = new Block;
90 Block* pb = m_pBlock;
91 char* pc = m_pBuffer->m_pcData;
92
93 for (int i = 0; i < m_iSize; ++i)
94 {
95 pb->m_iMsgNoBitset = 0;
96 pb->m_pcData = pc;
97 pc += m_iBlockLen;
98
99 if (i < m_iSize - 1)
100 {
101 pb->m_pNext = new Block;
102 pb = pb->m_pNext;
103 }
104 }
105 pb->m_pNext = m_pBlock;
106
107 m_pFirstBlock = m_pCurrBlock = m_pLastBlock = m_pBlock;
108
109 setupMutex(m_BufLock, "Buf");
110 }
111
112 CSndBuffer::~CSndBuffer()
113 {
114 Block* pb = m_pBlock->m_pNext;
115 while (pb != m_pBlock)
116 {
117 Block* temp = pb;
118 pb = pb->m_pNext;
119 delete temp;
120 }
121 delete m_pBlock;
122
123 while (m_pBuffer != NULL)
124 {
125 Buffer* temp = m_pBuffer;
126 m_pBuffer = m_pBuffer->m_pNext;
127 delete[] temp->m_pcData;
128 delete temp;
129 }
130
131 releaseMutex(m_BufLock);
132 }
133
134 void CSndBuffer::addBuffer(const char* data, int len, SRT_MSGCTRL& w_mctrl)
135 {
136 int32_t& w_msgno = w_mctrl.msgno;
137 int32_t& w_seqno = w_mctrl.pktseq;
138 int64_t& w_srctime = w_mctrl.srctime;
139 const int& ttl = w_mctrl.msgttl;
140 const int iPktLen = getMaxPacketLen();
141 const int iNumBlocks = countNumPacketsRequired(len, iPktLen);
142
143 HLOGC(bslog.Debug,
144 log << "addBuffer: needs=" << iNumBlocks << " buffers for " << len << " bytes. Taken=" << m_iCount << "/" << m_iSize);
145 // Retrieve current time before locking the mutex to be closer to packet submission event.
146 const steady_clock::time_point tnow = steady_clock::now();
147
148 ScopedLock bufferguard(m_BufLock);
149 // Dynamically increase sender buffer if there is not enough room.
150 while (iNumBlocks + m_iCount >= m_iSize)
151 {
152 HLOGC(bslog.Debug, log << "addBuffer: ... still lacking " << (iNumBlocks + m_iCount - m_iSize) << " buffers...");
153 increase();
154 }
155
156 const int32_t inorder = w_mctrl.inorder ? MSGNO_PACKET_INORDER::mask : 0;
157 HLOGC(bslog.Debug,
158 log << CONID() << "addBuffer: adding " << iNumBlocks << " packets (" << len << " bytes) to send, msgno="
159 << (w_msgno > 0 ? w_msgno : m_iNextMsgNo) << (inorder ? "" : " NOT") << " in order");
160
161 // Calculate origin time (same for all blocks of the message).
162 m_tsLastOriginTime = w_srctime ? time_point() + microseconds_from(w_srctime) : tnow;
163 // Rewrite back the actual value, even if it stays the same, so that the calling facilities can reuse it.
164 // May also be a subject to conversion error, thus the actual value is signalled back.
165 w_srctime = count_microseconds(m_tsLastOriginTime.time_since_epoch());
166
167 // The sequence number passed to this function is the sequence number
168 // that the very first packet from the packet series should get here.
169 // If there's more than one packet, this function must increase it by itself
170 // and then return the accordingly modified sequence number in the reference.
171
172 Block* s = m_pLastBlock;
173
174 if (w_msgno == SRT_MSGNO_NONE) // DEFAULT-UNCHANGED msgno supplied
175 {
176 HLOGC(bslog.Debug, log << "addBuffer: using internally managed msgno=" << m_iNextMsgNo);
177 w_msgno = m_iNextMsgNo;
178 }
179 else
180 {
181 HLOGC(bslog.Debug, log << "addBuffer: OVERWRITTEN by msgno supplied by caller: msgno=" << w_msgno);
182 m_iNextMsgNo = w_msgno;
183 }
184
185 for (int i = 0; i < iNumBlocks; ++i)
186 {
187 int pktlen = len - i * iPktLen;
188 if (pktlen > iPktLen)
189 pktlen = iPktLen;
190
191 HLOGC(bslog.Debug,
192 log << "addBuffer: %" << w_seqno << " #" << w_msgno << " offset=" << (i * iPktLen)
193 << " size=" << pktlen << " TO BUFFER:" << (void*)s->m_pcData);
194 memcpy((s->m_pcData), data + i * iPktLen, pktlen);
195 s->m_iLength = pktlen;
196
197 s->m_iSeqNo = w_seqno;
198 w_seqno = CSeqNo::incseq(w_seqno);
199
200 s->m_iMsgNoBitset = m_iNextMsgNo | inorder;
201 if (i == 0)
202 s->m_iMsgNoBitset |= PacketBoundaryBits(PB_FIRST);
203 if (i == iNumBlocks - 1)
204 s->m_iMsgNoBitset |= PacketBoundaryBits(PB_LAST);
205 // NOTE: if i is neither 0 nor size-1, it results with PB_SUBSEQUENT.
206 // if i == 0 == size-1, it results with PB_SOLO.
207 // Packets assigned to one message can be:
208 // [PB_FIRST] [PB_SUBSEQUENT] [PB_SUBSEQUENT] [PB_LAST] - 4 packets per message
209 // [PB_FIRST] [PB_LAST] - 2 packets per message
210 // [PB_SOLO] - 1 packet per message
211
212 s->m_iTTL = ttl;
213 s->m_tsRexmitTime = time_point();
214 s->m_tsOriginTime = m_tsLastOriginTime;
215
216 // Should never happen, as the call to increase() should ensure enough buffers.
217 SRT_ASSERT(s->m_pNext);
218 s = s->m_pNext;
219 }
220 m_pLastBlock = s;
221
222 m_iCount = m_iCount + iNumBlocks;
223 m_iBytesCount += len;
224
225 m_rateEstimator.updateInputRate(m_tsLastOriginTime, iNumBlocks, len);
226 updAvgBufSize(m_tsLastOriginTime);
227
228 // MSGNO_SEQ::mask has a form: 00000011111111...
229 // At least it's known that it's from some index inside til the end (to bit 0).
230 // If this value has been reached in a step of incrementation, it means that the
231 // maximum value has been reached. Casting to int32_t to ensure the same sign
232 // in comparison, although it's far from reaching the sign bit.
233
234 const int nextmsgno = ++MsgNo(m_iNextMsgNo);
235 HLOGC(bslog.Debug, log << "CSndBuffer::addBuffer: updating msgno: #" << m_iNextMsgNo << " -> #" << nextmsgno);
236 m_iNextMsgNo = nextmsgno;
237 }
238
239 int CSndBuffer::addBufferFromFile(fstream& ifs, int len)
240 {
241 const int iPktLen = getMaxPacketLen();
242 const int iNumBlocks = countNumPacketsRequired(len, iPktLen);
243
244 HLOGC(bslog.Debug,
245 log << "addBufferFromFile: size=" << m_iCount << " reserved=" << m_iSize << " needs=" << iPktLen
246 << " buffers for " << len << " bytes");
247
248 // dynamically increase sender buffer
249 while (iNumBlocks + m_iCount >= m_iSize)
250 {
251 HLOGC(bslog.Debug,
252 log << "addBufferFromFile: ... still lacking " << (iNumBlocks + m_iCount - m_iSize) << " buffers...");
253 increase();
254 }
255
256 HLOGC(bslog.Debug,
257 log << CONID() << "addBufferFromFile: adding " << iPktLen << " packets (" << len
258 << " bytes) to send, msgno=" << m_iNextMsgNo);
259
260 Block* s = m_pLastBlock;
261 int total = 0;
262 for (int i = 0; i < iNumBlocks; ++i)
263 {
264 if (ifs.bad() || ifs.fail() || ifs.eof())
265 break;
266
267 int pktlen = len - i * iPktLen;
268 if (pktlen > iPktLen)
269 pktlen = iPktLen;
270
271 HLOGC(bslog.Debug,
272 log << "addBufferFromFile: reading from=" << (i * iPktLen) << " size=" << pktlen
273 << " TO BUFFER:" << (void*)s->m_pcData);
274 ifs.read(s->m_pcData, pktlen);
275 if ((pktlen = int(ifs.gcount())) <= 0)
276 break;
277
278 // currently file transfer is only available in streaming mode, message is always in order, ttl = infinite
279 s->m_iMsgNoBitset = m_iNextMsgNo | MSGNO_PACKET_INORDER::mask;
280 if (i == 0)
281 s->m_iMsgNoBitset |= PacketBoundaryBits(PB_FIRST);
282 if (i == iNumBlocks - 1)
283 s->m_iMsgNoBitset |= PacketBoundaryBits(PB_LAST);
284 // NOTE: PB_FIRST | PB_LAST == PB_SOLO.
285 // none of PB_FIRST & PB_LAST == PB_SUBSEQUENT.
286
287 s->m_iLength = pktlen;
288 s->m_iTTL = SRT_MSGTTL_INF;
289 s = s->m_pNext;
290
291 total += pktlen;
292 }
293 m_pLastBlock = s;
294
295 enterCS(m_BufLock);
296 m_iCount = m_iCount + iNumBlocks;
297 m_iBytesCount += total;
298
299 leaveCS(m_BufLock);
300
301 m_iNextMsgNo++;
302 if (m_iNextMsgNo == int32_t(MSGNO_SEQ::mask))
303 m_iNextMsgNo = 1;
304
305 return total;
306 }
307
308 int CSndBuffer::readData(CPacket& w_packet, steady_clock::time_point& w_srctime, int kflgs, int& w_seqnoinc)
309 {
310 int readlen = 0;
311 w_seqnoinc = 0;
312
313 ScopedLock bufferguard(m_BufLock);
314 while (m_pCurrBlock != m_pLastBlock)
315 {
316 // Make the packet REFLECT the data stored in the buffer.
317 w_packet.m_pcData = m_pCurrBlock->m_pcData;
318 readlen = m_pCurrBlock->m_iLength;
319 w_packet.setLength(readlen, m_iBlockLen);
320 w_packet.set_seqno(m_pCurrBlock->m_iSeqNo);
321
322 // 1. On submission (addBuffer), the KK flag is set to EK_NOENC (0).
323 // 2. The readData() is called to get the original (unique) payload not ever sent yet.
324 // The payload must be encrypted for the first time if the encryption
325 // is enabled (arg kflgs != EK_NOENC). The KK encryption flag of the data packet
326 // header must be set and remembered accordingly (see EncryptionKeySpec).
327 // 3. The next time this packet is read (only for retransmission), the payload is already
328 // encrypted, and the proper flag value is already stored.
329
330 // TODO: Alternatively, encryption could happen before the packet is submitted to the buffer
331 // (before the addBuffer() call), and corresponding flags could be set accordingly.
332 // This may also put an encryption burden on the application thread, rather than the sending thread,
333 // which could be more efficient. Note that packet sequence number must be properly set in that case,
334 // as it is used as a counter for the AES encryption.
335 if (kflgs == -1)
336 {
337 HLOGC(bslog.Debug, log << CONID() << " CSndBuffer: ERROR: encryption required and not possible. NOT SENDING.");
338 readlen = 0;
339 }
340 else
341 {
342 m_pCurrBlock->m_iMsgNoBitset |= MSGNO_ENCKEYSPEC::wrap(kflgs);
343 }
344
345 Block* p = m_pCurrBlock;
346 w_packet.set_msgflags(m_pCurrBlock->m_iMsgNoBitset);
347 w_srctime = m_pCurrBlock->m_tsOriginTime;
348 m_pCurrBlock = m_pCurrBlock->m_pNext;
349
350 if ((p->m_iTTL >= 0) && (count_milliseconds(steady_clock::now() - w_srctime) > p->m_iTTL))
351 {
352 LOGC(bslog.Warn, log << CONID() << "CSndBuffer: skipping packet %" << p->m_iSeqNo << " #" << p->getMsgSeq() << " with TTL=" << p->m_iTTL);
353 // Skip this packet due to TTL expiry.
354 readlen = 0;
355 ++w_seqnoinc;
356 continue;
357 }
358
359 HLOGC(bslog.Debug, log << CONID() << "CSndBuffer: picked up packet to send: size=" << readlen
360 << " #" << w_packet.getMsgSeq()
361 << " %" << w_packet.seqno()
362 << " !" << BufferStamp(w_packet.m_pcData, w_packet.getLength()));
363
364 break;
365 }
366
367 return readlen;
368 }
369
370 CSndBuffer::time_point CSndBuffer::peekNextOriginal() const
371 {
372 ScopedLock bufferguard(m_BufLock);
373 if (m_pCurrBlock == m_pLastBlock)
374 return time_point();
375
376 return m_pCurrBlock->m_tsOriginTime;
377 }
378
379 int32_t CSndBuffer::getMsgNoAt(const int offset)
380 {
381 ScopedLock bufferguard(m_BufLock);
382
383 Block* p = m_pFirstBlock;
384
385 if (p)
386 {
387 HLOGC(bslog.Debug,
388 log << "CSndBuffer::getMsgNoAt: FIRST MSG: size=" << p->m_iLength << " %" << p->m_iSeqNo << " #"
389 << p->getMsgSeq() << " !" << BufferStamp(p->m_pcData, p->m_iLength));
390 }
391
392 if (offset >= m_iCount)
393 {
394 // Prevent accessing the last "marker" block
395 LOGC(bslog.Error,
396 log << "CSndBuffer::getMsgNoAt: IPE: offset=" << offset << " not found, max offset=" << m_iCount);
397 return SRT_MSGNO_CONTROL;
398 }
399
400 // XXX Suboptimal procedure to keep the blocks identifiable
401 // by sequence number. Consider using some circular buffer.
402 int i;
403 Block* ee SRT_ATR_UNUSED = 0;
404 for (i = 0; i < offset && p; ++i)
405 {
406 ee = p;
407 p = p->m_pNext;
408 }
409
410 if (!p)
411 {
412 LOGC(bslog.Error,
413 log << "CSndBuffer::getMsgNoAt: IPE: offset=" << offset << " not found, stopped at " << i << " with #"
414 << (ee ? ee->getMsgSeq() : SRT_MSGNO_NONE));
415 return SRT_MSGNO_CONTROL;
416 }
417
418 HLOGC(bslog.Debug,
419 log << "CSndBuffer::getMsgNoAt: offset=" << offset << " found, size=" << p->m_iLength << " %" << p->m_iSeqNo
420 << " #" << p->getMsgSeq() << " !" << BufferStamp(p->m_pcData, p->m_iLength));
421
422 return p->getMsgSeq();
423 }
424
425 int CSndBuffer::readData(const int offset, CPacket& w_packet, steady_clock::time_point& w_srctime, DropRange& w_drop)
426 {
427 // NOTE: w_packet.m_iSeqNo is expected to be set to the value
428 // of the sequence number with which this packet should be sent.
429
430 ScopedLock bufferguard(m_BufLock);
431
432 Block* p = m_pFirstBlock;
433
434 // XXX Suboptimal procedure to keep the blocks identifiable
435 // by sequence number. Consider using some circular buffer.
436 for (int i = 0; i < offset && p != m_pLastBlock; ++i)
437 {
438 p = p->m_pNext;
439 }
440 if (p == m_pLastBlock)
441 {
442 LOGC(qslog.Error, log << "CSndBuffer::readData: offset " << offset << " too large!");
443 return READ_NONE;
444 }
445 #if ENABLE_HEAVY_LOGGING
446 const int32_t first_seq = p->m_iSeqNo;
447 int32_t last_seq = p->m_iSeqNo;
448 #endif
449
450 // This is rexmit request, so the packet should have the sequence number
451 // already set when it was once sent uniquely.
452 SRT_ASSERT(p->m_iSeqNo == w_packet.seqno());
453
454 // Check if the block that is the next candidate to send (m_pCurrBlock pointing) is stale.
455
456 // If so, then inform the caller that it should first take care of the whole
457 // message (all blocks with that message id). Shift the m_pCurrBlock pointer
458 // to the position past the last of them. Then return -1 and set the
459 // msgno bitset packet field to the message id that should be dropped as
460 // a whole.
461
462 // After taking care of that, the caller should immediately call this function again,
463 // this time possibly in order to find the real data to be sent.
464
465 // if found block is stale
466 // (This is for messages that have declared TTL - messages that fail to be sent
467 // before the TTL defined time comes, will be dropped).
468
469 if ((p->m_iTTL >= 0) && (count_milliseconds(steady_clock::now() - p->m_tsOriginTime) > p->m_iTTL))
470 {
471 w_drop.msgno = p->getMsgSeq();
472 int msglen = 1;
473 p = p->m_pNext;
474 bool move = false;
475 while (p != m_pLastBlock && w_drop.msgno == p->getMsgSeq())
476 {
477 #if ENABLE_HEAVY_LOGGING
478 last_seq = p->m_iSeqNo;
479 #endif
480 if (p == m_pCurrBlock)
481 move = true;
482 p = p->m_pNext;
483 if (move)
484 m_pCurrBlock = p;
485 msglen++;
486 }
487
488 HLOGC(qslog.Debug,
489 log << "CSndBuffer::readData: due to TTL exceeded, %(" << first_seq << " - " << last_seq << "), "
490 << msglen << " packets to drop with #" << w_drop.msgno);
491
492 // Theoretically as the seq numbers are being tracked, you should be able
493 // to simply take the sequence number from the block. But this is a new
494 // feature and should be only used after refax for the sender buffer to
495 // make it manage the sequence numbers inside, instead of by CUDT::m_iSndLastDataAck.
496 w_drop.seqno[DropRange::BEGIN] = w_packet.seqno();
497 w_drop.seqno[DropRange::END] = CSeqNo::incseq(w_packet.seqno(), msglen - 1);
498
499 // Note the rules: here `p` is pointing to the first block AFTER the
500 // message to be dropped, so the end sequence should be one behind
501 // the one for p. Note that the loop rolls until hitting the first
502 // packet that doesn't belong to the message or m_pLastBlock, which
503 // is past-the-end for the occupied range in the sender buffer.
504 SRT_ASSERT(w_drop.seqno[DropRange::END] == CSeqNo::decseq(p->m_iSeqNo));
505 return READ_DROP;
506 }
507
508 w_packet.m_pcData = p->m_pcData;
509 const int readlen = p->m_iLength;
510 w_packet.setLength(readlen, m_iBlockLen);
511
512 // XXX Here the value predicted to be applied to PH_MSGNO field is extracted.
513 // As this function is predicted to extract the data to send as a rexmited packet,
514 // the packet must be in the form ready to send - so, in case of encryption,
515 // encrypted, and with all ENC flags already set. So, the first call to send
516 // the packet originally (the other overload of this function) must set these
517 // flags.
518 w_packet.set_msgflags(p->m_iMsgNoBitset);
519 w_srctime = p->m_tsOriginTime;
520
521 // This function is called when packet retransmission is triggered.
522 // Therefore we are setting the rexmit time.
523 p->m_tsRexmitTime = steady_clock::now();
524
525 HLOGC(qslog.Debug,
526 log << CONID() << "CSndBuffer: getting packet %" << p->m_iSeqNo << " as per %" << w_packet.seqno()
527 << " size=" << readlen << " to send [REXMIT]");
528
529 return readlen;
530 }
531
532 sync::steady_clock::time_point CSndBuffer::getPacketRexmitTime(const int offset)
533 {
534 ScopedLock bufferguard(m_BufLock);
535 const Block* p = m_pFirstBlock;
536
537 // XXX Suboptimal procedure to keep the blocks identifiable
538 // by sequence number. Consider using some circular buffer.
539 for (int i = 0; i < offset; ++i)
540 {
541 SRT_ASSERT(p);
542 p = p->m_pNext;
543 }
544
545 SRT_ASSERT(p);
546 return p->m_tsRexmitTime;
547 }
548
549 void CSndBuffer::ackData(int offset)
550 {
551 ScopedLock bufferguard(m_BufLock);
552
553 bool move = false;
554 for (int i = 0; i < offset; ++i)
555 {
556 m_iBytesCount -= m_pFirstBlock->m_iLength;
557 if (m_pFirstBlock == m_pCurrBlock)
558 move = true;
559 m_pFirstBlock = m_pFirstBlock->m_pNext;
560 }
561 if (move)
562 m_pCurrBlock = m_pFirstBlock;
563
564 m_iCount = m_iCount - offset;
565
566 updAvgBufSize(steady_clock::now());
567 }
568
569 int CSndBuffer::getCurrBufSize() const
570 {
571 return m_iCount;
572 }
573
574 int CSndBuffer::getMaxPacketLen() const
575 {
576 return m_iBlockLen - m_iAuthTagSize;
577 }
578
579 int CSndBuffer::countNumPacketsRequired(int iPldLen) const
580 {
581 const int iPktLen = getMaxPacketLen();
582 return countNumPacketsRequired(iPldLen, iPktLen);
583 }
584
585 int CSndBuffer::countNumPacketsRequired(int iPldLen, int iPktLen) const
586 {
587 return (iPldLen + iPktLen - 1) / iPktLen;
588 }
589
590 namespace {
591 int round_val(double val)
592 {
593 return static_cast<int>(round(val));
594 }
595 }
596
597 int CSndBuffer::getAvgBufSize(int& w_bytes, int& w_tsp)
598 {
599 ScopedLock bufferguard(m_BufLock); /* Consistency of pkts vs. bytes vs. spantime */
600
601 /* update stats in case there was no add/ack activity lately */
602 updAvgBufSize(steady_clock::now());
603
604 // Average number of packets and timespan could be small,
605 // so rounding is beneficial, while for the number of
606 // bytes in the buffer is a higher value, so rounding can be omitted,
607 // but probably better to round all three values.
608 w_bytes = round_val(m_mavg.bytes());
609 w_tsp = round_val(m_mavg.timespan_ms());
610 return round_val(m_mavg.pkts());
611 }
612
613 void CSndBuffer::updAvgBufSize(const steady_clock::time_point& now)
614 {
615 if (!m_mavg.isTimeToUpdate(now))
616 return;
617
618 int bytes = 0;
619 int timespan_ms = 0;
620 const int pkts = getCurrBufSize((bytes), (timespan_ms));
621 m_mavg.update(now, pkts, bytes, timespan_ms);
622 }
623
624 int CSndBuffer::getCurrBufSize(int& w_bytes, int& w_timespan) const
625 {
626 w_bytes = m_iBytesCount;
627 /*
628 * Timespan can be less then 1000 us (1 ms) if few packets.
629 * Also, if there is only one pkt in buffer, the time difference will be 0.
630 * Therefore, always add 1 ms if not empty.
631 */
632 w_timespan = 0 < m_iCount ? (int) count_milliseconds(m_tsLastOriginTime - m_pFirstBlock->m_tsOriginTime) + 1 : 0;
633
634 return m_iCount;
635 }
636
637 CSndBuffer::duration CSndBuffer::getBufferingDelay(const time_point& tnow) const
638 {
639 ScopedLock lck(m_BufLock);
640 SRT_ASSERT(m_pFirstBlock);
641 if (m_iCount == 0)
642 return duration(0);
643
644 return tnow - m_pFirstBlock->m_tsOriginTime;
645 }
646
647 int CSndBuffer::dropLateData(int& w_bytes, int32_t& w_first_msgno, const steady_clock::time_point& too_late_time)
648 {
649 int dpkts = 0;
650 int dbytes = 0;
651 bool move = false;
652 int32_t msgno = 0;
653
654 ScopedLock bufferguard(m_BufLock);
655 for (int i = 0; i < m_iCount && m_pFirstBlock->m_tsOriginTime < too_late_time; ++i)
656 {
657 dpkts++;
658 dbytes += m_pFirstBlock->m_iLength;
659 msgno = m_pFirstBlock->getMsgSeq();
660
661 if (m_pFirstBlock == m_pCurrBlock)
662 move = true;
663 m_pFirstBlock = m_pFirstBlock->m_pNext;
664 }
665
666 if (move)
667 {
668 m_pCurrBlock = m_pFirstBlock;
669 }
670 m_iCount = m_iCount - dpkts;
671
672 m_iBytesCount -= dbytes;
673 w_bytes = dbytes;
674
675 // We report the increased number towards the last ever seen
676 // by the loop, as this last one is the last received. So remained
677 // (even if "should remain") is the first after the last removed one.
678 w_first_msgno = ++MsgNo(msgno);
679
680 updAvgBufSize(steady_clock::now());
681
682 return (dpkts);
683 }
684
685 void CSndBuffer::increase()
686 {
687 int unitsize = m_pBuffer->m_iSize;
688
689 // new physical buffer
690 Buffer* nbuf = NULL;
691 try
692 {
693 nbuf = new Buffer;
694 nbuf->m_pcData = new char[unitsize * m_iBlockLen];
695 }
696 catch (...)
697 {
698 delete nbuf;
699 throw CUDTException(MJ_SYSTEMRES, MN_MEMORY, 0);
700 }
701 nbuf->m_iSize = unitsize;
702 nbuf->m_pNext = NULL;
703
704 // insert the buffer at the end of the buffer list
705 Buffer* p = m_pBuffer;
706 while (p->m_pNext != NULL)
707 p = p->m_pNext;
708 p->m_pNext = nbuf;
709
710 // new packet blocks
711 Block* nblk = NULL;
712 try
713 {
714 nblk = new Block;
715 }
716 catch (...)
717 {
718 delete nblk;
719 throw CUDTException(MJ_SYSTEMRES, MN_MEMORY, 0);
720 }
721 Block* pb = nblk;
722 for (int i = 1; i < unitsize; ++i)
723 {
724 pb->m_pNext = new Block;
725 pb = pb->m_pNext;
726 }
727
728 // insert the new blocks onto the existing one
729 pb->m_pNext = m_pLastBlock->m_pNext;
730 m_pLastBlock->m_pNext = nblk;
731
732 pb = nblk;
733 char* pc = nbuf->m_pcData;
734 for (int i = 0; i < unitsize; ++i)
735 {
736 pb->m_pcData = pc;
737 pb = pb->m_pNext;
738 pc += m_iBlockLen;
739 }
740
741 m_iSize += unitsize;
742
743 HLOGC(bslog.Debug,
744 log << "CSndBuffer: BUFFER FULL - adding " << (unitsize * m_iBlockLen) << " bytes spread to " << unitsize
745 << " blocks"
746 << " (total size: " << m_iSize << " bytes)");
747 }
748
749 } // namespace srt