File: streamtiming.cpp

package info (click to toggle)
ostinato 1.3.0-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 4,840 kB
  • sloc: cpp: 46,226; makefile: 8
file content (213 lines) | stat: -rw-r--r-- 6,720 bytes parent folder | download
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
/*
Copyright (C) 2023 Srivats P.

This file is part of "Ostinato"

This is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>
*/

#include "streamtiming.h"

#include "timestamp.h"

#include <QCoreApplication>

StreamTiming::StreamTiming(QObject *parent)
    : QObject(parent)
{
    // This class MUST be part of the main thread so that timers can work
    Q_ASSERT(this->thread() == QCoreApplication::instance()->thread());

    timer_ = new QTimer(this);
    connect(timer_, &QTimer::timeout, this, &StreamTiming::processRecords);
    timer_->setInterval(3000);

    gcTimer_ = new QTimer(this);
    connect(gcTimer_, &QTimer::timeout, this, &StreamTiming::deleteStaleRecords);
    gcTimer_->setInterval(30000);
}

void StreamTiming::start(uint portId)
{
    if (activePortSet_.isEmpty()) { // First port?
        timer_->start();
        gcTimer_->start();
        qDebug("Stream Latency tracking started");
    }
    activePortSet_.insert(portId);
    qDebug("Stream Latency tracking started for port %u", portId);
}

void StreamTiming::stop(uint portId)
{
    activePortSet_.remove(portId);
    qDebug("Stream Latency tracking stopped for port %u", portId);
    if (activePortSet_.isEmpty()) { // Last port?
        processRecords();
        deleteStaleRecords();
        timer_->stop();
        gcTimer_->stop();
        qDebug("Stream Latency tracking stopped");
    }
}

StreamTiming::Stats StreamTiming::stats(uint portId, uint guid)
{
    Stats stats = {0, 0};

    Q_ASSERT(guid <= SignProtocol::kMaxGuid);

    // Process anything pending first
    processRecords();

    QMutexLocker locker(&timingLock_);

    if (!timing_.contains(portId))
        return stats;

    Timing t = timing_.value(portId)->value(guid);
    if (t.countDelays == 0)
        return stats;

    stats.latency = timespecToNsecs(t.sumDelays)/t.countDelays;
    if (t.countDelays > 1)
        stats.jitter = t.sumJitter/(t.countDelays-1);

    return stats;
}

void StreamTiming::clear(uint portId, uint guid)
{
    // XXX: We need to clear only the final timing hash; rx/tx hashes
    // are cleared by StreamTiming itself as part of processRecords and
    // deleteStaleRecords respectively
    QMutexLocker locker(&timingLock_);

    if (!timing_.contains(portId))
        return;

    PortTiming *portTiming = timing_.value(portId);
    if (!portTiming)
        return;

    if (guid >= SignProtocol::kInvalidGuid)
        portTiming->clear();      // remove ALL guids
    else
        portTiming->remove(guid);
}

int StreamTiming::processRecords()
{
    // TODO: yield after a certain count of records or time when called in
    // timer context; when called from delay(), process ALL

    int count = 0;
    QMutexLocker txLocker(&txHashLock_);
    QMutexLocker rxLocker(&rxHashLock_);
    QMutexLocker timingLocker(&timingLock_);

    auto i = rxHash_.begin();
    while (i != rxHash_.end()) {
        if (txHash_.contains(i.key())) {
            struct timespec txTime = txHash_.take(i.key()).timeStamp;
            struct timespec rxTime = i.value().timeStamp;
            struct timespec diff;
            timespecsub(&rxTime, &txTime, &diff);

            uint guid = guidFromKey(i.key());
            uint portId = i.value().portId;

            if (!timing_.contains(portId))
                timing_.insert(portId, new PortTiming);
            PortTiming *portTiming = timing_.value(portId);
            Timing &guidTiming = (*portTiming)[guid];
            timespecadd(&guidTiming.sumDelays, &diff, &guidTiming.sumDelays);
            if (guidTiming.countDelays)
                guidTiming.sumJitter += abs(
                        diff.tv_sec*long(1e9) + diff.tv_nsec
                        - guidTiming.lastDelay.tv_sec*long(1e9)
                        - guidTiming.lastDelay.tv_nsec);
            guidTiming.lastDelay = diff;
            guidTiming.countDelays++;

            count++;

            timingDebug("[%u/%u/%u] diff %ld.%09ld (%ld.%09ld - %ld.%09ld)",
                i.value().portId, guid, ttagIdFromKey(i.key()),
                diff.tv_sec, diff.tv_nsec,
                rxTime.tv_sec, rxTime.tv_nsec,
                txTime.tv_sec, txTime.tv_nsec);
            timingDebug("[%u/%u](%d) total %ld.%09ld count %u jittersum %09llu",
                i.value().portId, guid, count,
                guidTiming.sumDelays.tv_sec, guidTiming.sumDelays.tv_nsec,
                guidTiming.countDelays, guidTiming.sumJitter);
        }
        i = rxHash_.erase(i);
    }

    Q_ASSERT(rxHash_.isEmpty());

    return count;
}

int StreamTiming::deleteStaleRecords()
{
    // TODO: yield after a certain count of records or time unless we are
    // idle when we process all; how do we determine we are "idle"?

    // XXX: We assume the Tx packet timestamps are based on CLOCK_REALTIME
    // (or a similar and comparable source). Since garbage collection timer
    // is not a short interval, it need not be the exact same source as long
    // as the values are comparable
    int count = 0;
    struct timespec now;
    clock_gettime(CLOCK_REALTIME, &now);

    // XXX: processRecords() iterates and deletes all rx records irrespective
    // of whether it found a matching tx record. So for garbage collection we
    // only need to look at (and delete) tx records
    QMutexLocker locker(&txHashLock_);

    auto i = txHash_.begin();
    while (i != txHash_.end()) {
        struct timespec txTime = i.value().timeStamp;
        struct timespec diff;
        timespecsub(&now, &txTime, &diff);
        timingDebug("gc diff %ld", diff.tv_sec);
        if (diff.tv_sec > 30) {
            i = txHash_.erase(i);
            count++;
        } else {
            i++;
        }

    }

    if (count)
        qDebug("Latency garbage collected %d stale tx timing records", count);
    return count;
}

StreamTiming* StreamTiming::instance()
{
    static StreamTiming *instance{nullptr};

    // XXX: As of this writing, AbstractPort constructor is the first one
    // to call this - hence this singleton is created when the first port
    // is created
    if (!instance)
        instance = new StreamTiming(QCoreApplication::instance());

    return instance;
}