File: buffer_snd.cpp

package info (click to toggle)
srt 1.5.4-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 5,804 kB
  • sloc: cpp: 52,175; ansic: 5,746; tcl: 1,183; sh: 318; python: 99; makefile: 38
file content (749 lines) | stat: -rw-r--r-- 25,477 bytes parent folder | download | duplicates (2)
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
/*
 * SRT - Secure, Reliable, Transport
 * Copyright (c) 2018 Haivision Systems Inc.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 */

/*****************************************************************************
Copyright (c) 2001 - 2011, The Board of Trustees of the University of Illinois.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

* Redistributions of source code must retain the above
  copyright notice, this list of conditions and the
  following disclaimer.

* Redistributions in binary form must reproduce the
  above copyright notice, this list of conditions
  and the following disclaimer in the documentation
  and/or other materials provided with the distribution.

* Neither the name of the University of Illinois
  nor the names of its contributors may be used to
  endorse or promote products derived from this
  software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*****************************************************************************/

/*****************************************************************************
written by
   Yunhong Gu, last updated 03/12/2011
modified by
   Haivision Systems Inc.
*****************************************************************************/

#include "platform_sys.h"

#include <cmath>
#include "buffer_snd.h"
#include "packet.h"
#include "core.h" // provides some constants
#include "logging.h"

namespace srt {

using namespace std;
using namespace srt_logging;
using namespace sync;

CSndBuffer::CSndBuffer(int ip_family, int size, int maxpld, int authtag)
    : m_BufLock()
    , m_pBlock(NULL)
    , m_pFirstBlock(NULL)
    , m_pCurrBlock(NULL)
    , m_pLastBlock(NULL)
    , m_pBuffer(NULL)
    , m_iNextMsgNo(1)
    , m_iSize(size)
    , m_iBlockLen(maxpld)
    , m_iAuthTagSize(authtag)
    , m_iCount(0)
    , m_iBytesCount(0)
    , m_rateEstimator(ip_family)
{
    // initial physical buffer of "size"
    m_pBuffer           = new Buffer;
    m_pBuffer->m_pcData = new char[m_iSize * m_iBlockLen];
    m_pBuffer->m_iSize  = m_iSize;
    m_pBuffer->m_pNext  = NULL;

    // circular linked list for out bound packets
    m_pBlock  = new Block;
    Block* pb = m_pBlock;
    char* pc  = m_pBuffer->m_pcData;

    for (int i = 0; i < m_iSize; ++i)
    {
        pb->m_iMsgNoBitset = 0;
        pb->m_pcData       = pc;
        pc                += m_iBlockLen;

        if (i < m_iSize - 1)
        {
            pb->m_pNext        = new Block;
            pb                 = pb->m_pNext;
        }
    }
    pb->m_pNext = m_pBlock;

    m_pFirstBlock = m_pCurrBlock = m_pLastBlock = m_pBlock;

    setupMutex(m_BufLock, "Buf");
}

CSndBuffer::~CSndBuffer()
{
    Block* pb = m_pBlock->m_pNext;
    while (pb != m_pBlock)
    {
        Block* temp = pb;
        pb          = pb->m_pNext;
        delete temp;
    }
    delete m_pBlock;

    while (m_pBuffer != NULL)
    {
        Buffer* temp = m_pBuffer;
        m_pBuffer    = m_pBuffer->m_pNext;
        delete[] temp->m_pcData;
        delete temp;
    }

    releaseMutex(m_BufLock);
}

void CSndBuffer::addBuffer(const char* data, int len, SRT_MSGCTRL& w_mctrl)
{
    int32_t& w_msgno     = w_mctrl.msgno;
    int32_t& w_seqno     = w_mctrl.pktseq;
    int64_t& w_srctime   = w_mctrl.srctime;
    const int& ttl       = w_mctrl.msgttl;
    const int iPktLen    = getMaxPacketLen();
    const int iNumBlocks = countNumPacketsRequired(len, iPktLen);

    HLOGC(bslog.Debug,
          log << "addBuffer: needs=" << iNumBlocks << " buffers for " << len << " bytes. Taken=" << m_iCount << "/" << m_iSize);
    // Retrieve current time before locking the mutex to be closer to packet submission event.
    const steady_clock::time_point tnow = steady_clock::now();

    ScopedLock bufferguard(m_BufLock);
    // Dynamically increase sender buffer if there is not enough room.
    while (iNumBlocks + m_iCount >= m_iSize)
    {
        HLOGC(bslog.Debug, log << "addBuffer: ... still lacking " << (iNumBlocks + m_iCount - m_iSize) << " buffers...");
        increase();
    }

    const int32_t inorder = w_mctrl.inorder ? MSGNO_PACKET_INORDER::mask : 0;
    HLOGC(bslog.Debug,
          log << CONID() << "addBuffer: adding " << iNumBlocks << " packets (" << len << " bytes) to send, msgno="
              << (w_msgno > 0 ? w_msgno : m_iNextMsgNo) << (inorder ? "" : " NOT") << " in order");

    // Calculate origin time (same for all blocks of the message).
    m_tsLastOriginTime = w_srctime ? time_point() + microseconds_from(w_srctime) : tnow;
    // Rewrite back the actual value, even if it stays the same, so that the calling facilities can reuse it.
    // May also be a subject to conversion error, thus the actual value is signalled back.
    w_srctime = count_microseconds(m_tsLastOriginTime.time_since_epoch());

    // The sequence number passed to this function is the sequence number
    // that the very first packet from the packet series should get here.
    // If there's more than one packet, this function must increase it by itself
    // and then return the accordingly modified sequence number in the reference.

    Block* s = m_pLastBlock;

    if (w_msgno == SRT_MSGNO_NONE) // DEFAULT-UNCHANGED msgno supplied
    {
        HLOGC(bslog.Debug, log << "addBuffer: using internally managed msgno=" << m_iNextMsgNo);
        w_msgno = m_iNextMsgNo;
    }
    else
    {
        HLOGC(bslog.Debug, log << "addBuffer: OVERWRITTEN by msgno supplied by caller: msgno=" << w_msgno);
        m_iNextMsgNo = w_msgno;
    }

    for (int i = 0; i < iNumBlocks; ++i)
    {
        int pktlen = len - i * iPktLen;
        if (pktlen > iPktLen)
            pktlen = iPktLen;

        HLOGC(bslog.Debug,
              log << "addBuffer: %" << w_seqno << " #" << w_msgno << " offset=" << (i * iPktLen)
                  << " size=" << pktlen << " TO BUFFER:" << (void*)s->m_pcData);
        memcpy((s->m_pcData), data + i * iPktLen, pktlen);
        s->m_iLength = pktlen;

        s->m_iSeqNo = w_seqno;
        w_seqno     = CSeqNo::incseq(w_seqno);

        s->m_iMsgNoBitset = m_iNextMsgNo | inorder;
        if (i == 0)
            s->m_iMsgNoBitset |= PacketBoundaryBits(PB_FIRST);
        if (i == iNumBlocks - 1)
            s->m_iMsgNoBitset |= PacketBoundaryBits(PB_LAST);
        // NOTE: if i is neither 0 nor size-1, it resuls with PB_SUBSEQUENT.
        //       if i == 0 == size-1, it results with PB_SOLO.
        // Packets assigned to one message can be:
        // [PB_FIRST] [PB_SUBSEQUENT] [PB_SUBSEQUENT] [PB_LAST] - 4 packets per message
        // [PB_FIRST] [PB_LAST] - 2 packets per message
        // [PB_SOLO] - 1 packet per message

        s->m_iTTL = ttl;
        s->m_tsRexmitTime = time_point();
        s->m_tsOriginTime = m_tsLastOriginTime;
        
        // Should never happen, as the call to increase() should ensure enough buffers.
        SRT_ASSERT(s->m_pNext);
        s = s->m_pNext;
    }
    m_pLastBlock = s;

    m_iCount = m_iCount + iNumBlocks;
    m_iBytesCount += len;

    m_rateEstimator.updateInputRate(m_tsLastOriginTime, iNumBlocks, len);
    updAvgBufSize(m_tsLastOriginTime);

    // MSGNO_SEQ::mask has a form: 00000011111111...
    // At least it's known that it's from some index inside til the end (to bit 0).
    // If this value has been reached in a step of incrementation, it means that the
    // maximum value has been reached. Casting to int32_t to ensure the same sign
    // in comparison, although it's far from reaching the sign bit.

    const int nextmsgno = ++MsgNo(m_iNextMsgNo);
    HLOGC(bslog.Debug, log << "CSndBuffer::addBuffer: updating msgno: #" << m_iNextMsgNo << " -> #" << nextmsgno);
    m_iNextMsgNo = nextmsgno;
}

int CSndBuffer::addBufferFromFile(fstream& ifs, int len)
{
    const int iPktLen    = getMaxPacketLen();
    const int iNumBlocks = countNumPacketsRequired(len, iPktLen);

    HLOGC(bslog.Debug,
          log << "addBufferFromFile: size=" << m_iCount << " reserved=" << m_iSize << " needs=" << iPktLen
              << " buffers for " << len << " bytes");

    // dynamically increase sender buffer
    while (iNumBlocks + m_iCount >= m_iSize)
    {
        HLOGC(bslog.Debug,
              log << "addBufferFromFile: ... still lacking " << (iNumBlocks + m_iCount - m_iSize) << " buffers...");
        increase();
    }

    HLOGC(bslog.Debug,
          log << CONID() << "addBufferFromFile: adding " << iPktLen << " packets (" << len
              << " bytes) to send, msgno=" << m_iNextMsgNo);

    Block* s     = m_pLastBlock;
    int    total = 0;
    for (int i = 0; i < iNumBlocks; ++i)
    {
        if (ifs.bad() || ifs.fail() || ifs.eof())
            break;

        int pktlen = len - i * iPktLen;
        if (pktlen > iPktLen)
            pktlen = iPktLen;

        HLOGC(bslog.Debug,
              log << "addBufferFromFile: reading from=" << (i * iPktLen) << " size=" << pktlen
                  << " TO BUFFER:" << (void*)s->m_pcData);
        ifs.read(s->m_pcData, pktlen);
        if ((pktlen = int(ifs.gcount())) <= 0)
            break;

        // currently file transfer is only available in streaming mode, message is always in order, ttl = infinite
        s->m_iMsgNoBitset = m_iNextMsgNo | MSGNO_PACKET_INORDER::mask;
        if (i == 0)
            s->m_iMsgNoBitset |= PacketBoundaryBits(PB_FIRST);
        if (i == iNumBlocks - 1)
            s->m_iMsgNoBitset |= PacketBoundaryBits(PB_LAST);
        // NOTE: PB_FIRST | PB_LAST == PB_SOLO.
        // none of PB_FIRST & PB_LAST == PB_SUBSEQUENT.

        s->m_iLength = pktlen;
        s->m_iTTL    = SRT_MSGTTL_INF;
        s            = s->m_pNext;

        total += pktlen;
    }
    m_pLastBlock = s;

    enterCS(m_BufLock);
    m_iCount = m_iCount + iNumBlocks;
    m_iBytesCount += total;

    leaveCS(m_BufLock);

    m_iNextMsgNo++;
    if (m_iNextMsgNo == int32_t(MSGNO_SEQ::mask))
        m_iNextMsgNo = 1;

    return total;
}

int CSndBuffer::readData(CPacket& w_packet, steady_clock::time_point& w_srctime, int kflgs, int& w_seqnoinc)
{
    int readlen = 0;
    w_seqnoinc = 0;

    ScopedLock bufferguard(m_BufLock);
    while (m_pCurrBlock != m_pLastBlock)
    {
        // Make the packet REFLECT the data stored in the buffer.
        w_packet.m_pcData = m_pCurrBlock->m_pcData;
        readlen = m_pCurrBlock->m_iLength;
        w_packet.setLength(readlen, m_iBlockLen);
        w_packet.set_seqno(m_pCurrBlock->m_iSeqNo);

        // 1. On submission (addBuffer), the KK flag is set to EK_NOENC (0).
        // 2. The readData() is called to get the original (unique) payload not ever sent yet.
        //    The payload must be encrypted for the first time if the encryption
        //    is enabled (arg kflgs != EK_NOENC). The KK encryption flag of the data packet
        //    header must be set and remembered accordingly (see EncryptionKeySpec).
        // 3. The next time this packet is read (only for retransmission), the payload is already
        //    encrypted, and the proper flag value is already stored.
        
        // TODO: Alternatively, encryption could happen before the packet is submitted to the buffer
        // (before the addBuffer() call), and corresponding flags could be set accordingly.
        // This may also put an encryption burden on the application thread, rather than the sending thread,
        // which could be more efficient. Note that packet sequence number must be properly set in that case,
        // as it is used as a counter for the AES encryption.
        if (kflgs == -1)
        {
            HLOGC(bslog.Debug, log << CONID() << " CSndBuffer: ERROR: encryption required and not possible. NOT SENDING.");
            readlen = 0;
        }
        else
        {
            m_pCurrBlock->m_iMsgNoBitset |= MSGNO_ENCKEYSPEC::wrap(kflgs);
        }

        Block* p = m_pCurrBlock;
        w_packet.set_msgflags(m_pCurrBlock->m_iMsgNoBitset);
        w_srctime = m_pCurrBlock->m_tsOriginTime;
        m_pCurrBlock = m_pCurrBlock->m_pNext;

        if ((p->m_iTTL >= 0) && (count_milliseconds(steady_clock::now() - w_srctime) > p->m_iTTL))
        {
            LOGC(bslog.Warn, log << CONID() << "CSndBuffer: skipping packet %" << p->m_iSeqNo << " #" << p->getMsgSeq() << " with TTL=" << p->m_iTTL);
            // Skip this packet due to TTL expiry.
            readlen = 0;
            ++w_seqnoinc;
            continue;
        }

        HLOGC(bslog.Debug, log << CONID() << "CSndBuffer: picked up packet to send: size=" << readlen
                << " #" << w_packet.getMsgSeq()
                << " %" << w_packet.seqno()
                << " !" << BufferStamp(w_packet.m_pcData, w_packet.getLength()));

        break;
    }

    return readlen;
}

CSndBuffer::time_point CSndBuffer::peekNextOriginal() const
{
    ScopedLock bufferguard(m_BufLock);
    if (m_pCurrBlock == m_pLastBlock)
        return time_point();

    return m_pCurrBlock->m_tsOriginTime;
}

int32_t CSndBuffer::getMsgNoAt(const int offset)
{
    ScopedLock bufferguard(m_BufLock);

    Block* p = m_pFirstBlock;

    if (p)
    {
        HLOGC(bslog.Debug,
              log << "CSndBuffer::getMsgNoAt: FIRST MSG: size=" << p->m_iLength << " %" << p->m_iSeqNo << " #"
                  << p->getMsgSeq() << " !" << BufferStamp(p->m_pcData, p->m_iLength));
    }

    if (offset >= m_iCount)
    {
        // Prevent accessing the last "marker" block
        LOGC(bslog.Error,
             log << "CSndBuffer::getMsgNoAt: IPE: offset=" << offset << " not found, max offset=" << m_iCount);
        return SRT_MSGNO_CONTROL;
    }

    // XXX Suboptimal procedure to keep the blocks identifiable
    // by sequence number. Consider using some circular buffer.
    int       i;
    Block* ee SRT_ATR_UNUSED = 0;
    for (i = 0; i < offset && p; ++i)
    {
        ee = p;
        p  = p->m_pNext;
    }

    if (!p)
    {
        LOGC(bslog.Error,
             log << "CSndBuffer::getMsgNoAt: IPE: offset=" << offset << " not found, stopped at " << i << " with #"
                 << (ee ? ee->getMsgSeq() : SRT_MSGNO_NONE));
        return SRT_MSGNO_CONTROL;
    }

    HLOGC(bslog.Debug,
          log << "CSndBuffer::getMsgNoAt: offset=" << offset << " found, size=" << p->m_iLength << " %" << p->m_iSeqNo
              << " #" << p->getMsgSeq() << " !" << BufferStamp(p->m_pcData, p->m_iLength));

    return p->getMsgSeq();
}

int CSndBuffer::readData(const int offset, CPacket& w_packet, steady_clock::time_point& w_srctime, DropRange& w_drop)
{
    // NOTE: w_packet.m_iSeqNo is expected to be set to the value
    // of the sequence number with which this packet should be sent.

    ScopedLock bufferguard(m_BufLock);

    Block* p = m_pFirstBlock;

    // XXX Suboptimal procedure to keep the blocks identifiable
    // by sequence number. Consider using some circular buffer.
    for (int i = 0; i < offset && p != m_pLastBlock; ++i)
    {
        p = p->m_pNext;
    }
    if (p == m_pLastBlock)
    {
        LOGC(qslog.Error, log << "CSndBuffer::readData: offset " << offset << " too large!");
        return READ_NONE;
    }
#if ENABLE_HEAVY_LOGGING
    const int32_t first_seq = p->m_iSeqNo;
    int32_t last_seq = p->m_iSeqNo;
#endif

    // This is rexmit request, so the packet should have the sequence number
    // already set when it was once sent uniquely.
    SRT_ASSERT(p->m_iSeqNo == w_packet.seqno());

    // Check if the block that is the next candidate to send (m_pCurrBlock pointing) is stale.

    // If so, then inform the caller that it should first take care of the whole
    // message (all blocks with that message id). Shift the m_pCurrBlock pointer
    // to the position past the last of them. Then return -1 and set the
    // msgno bitset packet field to the message id that should be dropped as
    // a whole.

    // After taking care of that, the caller should immediately call this function again,
    // this time possibly in order to find the real data to be sent.

    // if found block is stale
    // (This is for messages that have declared TTL - messages that fail to be sent
    // before the TTL defined time comes, will be dropped).

    if ((p->m_iTTL >= 0) && (count_milliseconds(steady_clock::now() - p->m_tsOriginTime) > p->m_iTTL))
    {
        w_drop.msgno = p->getMsgSeq();
        int msglen   = 1;
        p            = p->m_pNext;
        bool move    = false;
        while (p != m_pLastBlock && w_drop.msgno == p->getMsgSeq())
        {
#if ENABLE_HEAVY_LOGGING
            last_seq = p->m_iSeqNo;
#endif
            if (p == m_pCurrBlock)
                move = true;
            p = p->m_pNext;
            if (move)
                m_pCurrBlock = p;
            msglen++;
        }

        HLOGC(qslog.Debug,
              log << "CSndBuffer::readData: due to TTL exceeded, %(" << first_seq << " - " << last_seq << "), "
                  << msglen << " packets to drop with #" << w_drop.msgno);

        // Theoretically as the seq numbers are being tracked, you should be able
        // to simply take the sequence number from the block. But this is a new
        // feature and should be only used after refax for the sender buffer to
        // make it manage the sequence numbers inside, instead of by CUDT::m_iSndLastDataAck.
        w_drop.seqno[DropRange::BEGIN] = w_packet.seqno();
        w_drop.seqno[DropRange::END] = CSeqNo::incseq(w_packet.seqno(), msglen - 1);

        // Note the rules: here `p` is pointing to the first block AFTER the
        // message to be dropped, so the end sequence should be one behind
        // the one for p. Note that the loop rolls until hitting the first
        // packet that doesn't belong to the message or m_pLastBlock, which
        // is past-the-end for the occupied range in the sender buffer.
        SRT_ASSERT(w_drop.seqno[DropRange::END] == CSeqNo::decseq(p->m_iSeqNo));
        return READ_DROP;
    }

    w_packet.m_pcData = p->m_pcData;
    const int readlen = p->m_iLength;
    w_packet.setLength(readlen, m_iBlockLen);

    // XXX Here the value predicted to be applied to PH_MSGNO field is extracted.
    // As this function is predicted to extract the data to send as a rexmited packet,
    // the packet must be in the form ready to send - so, in case of encryption,
    // encrypted, and with all ENC flags already set. So, the first call to send
    // the packet originally (the other overload of this function) must set these
    // flags.
    w_packet.set_msgflags(p->m_iMsgNoBitset);
    w_srctime = p->m_tsOriginTime;

    // This function is called when packet retransmission is triggered.
    // Therefore we are setting the rexmit time.
    p->m_tsRexmitTime = steady_clock::now();

    HLOGC(qslog.Debug,
          log << CONID() << "CSndBuffer: getting packet %" << p->m_iSeqNo << " as per %" << w_packet.seqno()
              << " size=" << readlen << " to send [REXMIT]");

    return readlen;
}

sync::steady_clock::time_point CSndBuffer::getPacketRexmitTime(const int offset)
{
    ScopedLock bufferguard(m_BufLock);
    const Block* p = m_pFirstBlock;

    // XXX Suboptimal procedure to keep the blocks identifiable
    // by sequence number. Consider using some circular buffer.
    for (int i = 0; i < offset; ++i)
    {
        SRT_ASSERT(p);
        p = p->m_pNext;
    }

    SRT_ASSERT(p);
    return p->m_tsRexmitTime;
}

void CSndBuffer::ackData(int offset)
{
    ScopedLock bufferguard(m_BufLock);

    bool move = false;
    for (int i = 0; i < offset; ++i)
    {
        m_iBytesCount -= m_pFirstBlock->m_iLength;
        if (m_pFirstBlock == m_pCurrBlock)
            move = true;
        m_pFirstBlock = m_pFirstBlock->m_pNext;
    }
    if (move)
        m_pCurrBlock = m_pFirstBlock;

    m_iCount = m_iCount - offset;

    updAvgBufSize(steady_clock::now());
}

int CSndBuffer::getCurrBufSize() const
{
    return m_iCount;
}

int CSndBuffer::getMaxPacketLen() const
{
    return m_iBlockLen - m_iAuthTagSize;
}

int CSndBuffer::countNumPacketsRequired(int iPldLen) const
{
    const int iPktLen = getMaxPacketLen();
    return countNumPacketsRequired(iPldLen, iPktLen);
}

int CSndBuffer::countNumPacketsRequired(int iPldLen, int iPktLen) const
{
    return (iPldLen + iPktLen - 1) / iPktLen;
}

namespace {
int round_val(double val)
{
    return static_cast<int>(round(val));
}
}

int CSndBuffer::getAvgBufSize(int& w_bytes, int& w_tsp)
{
    ScopedLock bufferguard(m_BufLock); /* Consistency of pkts vs. bytes vs. spantime */

    /* update stats in case there was no add/ack activity lately */
    updAvgBufSize(steady_clock::now());

    // Average number of packets and timespan could be small,
    // so rounding is beneficial, while for the number of
    // bytes in the buffer is a higher value, so rounding can be omitted,
    // but probably better to round all three values.
    w_bytes = round_val(m_mavg.bytes());
    w_tsp   = round_val(m_mavg.timespan_ms());
    return round_val(m_mavg.pkts());
}

void CSndBuffer::updAvgBufSize(const steady_clock::time_point& now)
{
    if (!m_mavg.isTimeToUpdate(now))
        return;

    int       bytes       = 0;
    int       timespan_ms = 0;
    const int pkts        = getCurrBufSize((bytes), (timespan_ms));
    m_mavg.update(now, pkts, bytes, timespan_ms);
}

int CSndBuffer::getCurrBufSize(int& w_bytes, int& w_timespan) const
{
    w_bytes = m_iBytesCount;
    /*
     * Timespan can be less then 1000 us (1 ms) if few packets.
     * Also, if there is only one pkt in buffer, the time difference will be 0.
     * Therefore, always add 1 ms if not empty.
     */
    w_timespan = 0 < m_iCount ? (int) count_milliseconds(m_tsLastOriginTime - m_pFirstBlock->m_tsOriginTime) + 1 : 0;

    return m_iCount;
}

CSndBuffer::duration CSndBuffer::getBufferingDelay(const time_point& tnow) const
{
    ScopedLock lck(m_BufLock);
    SRT_ASSERT(m_pFirstBlock);
    if (m_iCount == 0)
        return duration(0);

    return tnow - m_pFirstBlock->m_tsOriginTime;
}

int CSndBuffer::dropLateData(int& w_bytes, int32_t& w_first_msgno, const steady_clock::time_point& too_late_time)
{
    int     dpkts  = 0;
    int     dbytes = 0;
    bool    move   = false;
    int32_t msgno  = 0;

    ScopedLock bufferguard(m_BufLock);
    for (int i = 0; i < m_iCount && m_pFirstBlock->m_tsOriginTime < too_late_time; ++i)
    {
        dpkts++;
        dbytes += m_pFirstBlock->m_iLength;
        msgno = m_pFirstBlock->getMsgSeq();

        if (m_pFirstBlock == m_pCurrBlock)
            move = true;
        m_pFirstBlock = m_pFirstBlock->m_pNext;
    }

    if (move)
    {
        m_pCurrBlock = m_pFirstBlock;
    }
    m_iCount = m_iCount - dpkts;

    m_iBytesCount -= dbytes;
    w_bytes = dbytes;

    // We report the increased number towards the last ever seen
    // by the loop, as this last one is the last received. So remained
    // (even if "should remain") is the first after the last removed one.
    w_first_msgno = ++MsgNo(msgno);

    updAvgBufSize(steady_clock::now());

    return (dpkts);
}

void CSndBuffer::increase()
{
    int unitsize = m_pBuffer->m_iSize;

    // new physical buffer
    Buffer* nbuf = NULL;
    try
    {
        nbuf           = new Buffer;
        nbuf->m_pcData = new char[unitsize * m_iBlockLen];
    }
    catch (...)
    {
        delete nbuf;
        throw CUDTException(MJ_SYSTEMRES, MN_MEMORY, 0);
    }
    nbuf->m_iSize = unitsize;
    nbuf->m_pNext = NULL;

    // insert the buffer at the end of the buffer list
    Buffer* p = m_pBuffer;
    while (p->m_pNext != NULL)
        p = p->m_pNext;
    p->m_pNext = nbuf;

    // new packet blocks
    Block* nblk = NULL;
    try
    {
        nblk = new Block;
    }
    catch (...)
    {
        delete nblk;
        throw CUDTException(MJ_SYSTEMRES, MN_MEMORY, 0);
    }
    Block* pb = nblk;
    for (int i = 1; i < unitsize; ++i)
    {
        pb->m_pNext = new Block;
        pb          = pb->m_pNext;
    }

    // insert the new blocks onto the existing one
    pb->m_pNext           = m_pLastBlock->m_pNext;
    m_pLastBlock->m_pNext = nblk;

    pb       = nblk;
    char* pc = nbuf->m_pcData;
    for (int i = 0; i < unitsize; ++i)
    {
        pb->m_pcData = pc;
        pb           = pb->m_pNext;
        pc += m_iBlockLen;
    }

    m_iSize += unitsize;

    HLOGC(bslog.Debug,
          log << "CSndBuffer: BUFFER FULL - adding " << (unitsize * m_iBlockLen) << " bytes spread to " << unitsize
              << " blocks"
              << " (total size: " << m_iSize << " bytes)");
}

} // namespace srt