File: GStreamerStatsCollector.cpp

package info (click to toggle)
webkit2gtk 2.51.91-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 484,084 kB
  • sloc: cpp: 3,931,583; javascript: 197,713; ansic: 167,619; python: 53,160; asm: 21,857; ruby: 18,114; perl: 17,149; xml: 4,631; sh: 2,462; yacc: 2,394; java: 2,032; lex: 1,358; pascal: 372; makefile: 215
file content (608 lines) | stat: -rw-r--r-- 24,402 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
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
/*
 *  Copyright (C) 2019-2022 Igalia S.L. All rights reserved.
 *  Copyright (C) 2022 Metrological Group B.V.
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2 of the License, or (at your option) any later version.
 *
 *  This library 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
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "config.h"
#include "GStreamerStatsCollector.h"

#if ENABLE(WEB_RTC) && USE(GSTREAMER_WEBRTC)

#include "GStreamerCommon.h"
#include "GStreamerWebRTCUtils.h"
#include "JSDOMMapLike.h"
#include "JSRTCStatsReport.h"

#define GST_USE_UNSTABLE_API
#include <gst/webrtc/webrtc.h>
#undef GST_USE_UNSTABLE_API

#include <wtf/MainThread.h>
#include <wtf/TZoneMallocInlines.h>
#include <wtf/glib/WTFGType.h>
#include <wtf/text/StringToIntegerConversion.h>

GST_DEBUG_CATEGORY(webkit_webrtc_stats_debug);
#define GST_CAT_DEFAULT webkit_webrtc_stats_debug

namespace WebCore {

GStreamerStatsCollector::GStreamerStatsCollector()
{
    static std::once_flag debugRegisteredFlag;
    std::call_once(debugRegisteredFlag, [] {
        GST_DEBUG_CATEGORY_INIT(webkit_webrtc_stats_debug, "webkitwebrtcstats", 0, "WebKit WebRTC Stats");
    });
}

RTCStatsReport::Stats::Stats(Type type, const GstStructure* structure)
    : type(type)
    , id(gstStructureGetString(structure, "id"_s).span())
{
    if (auto value = gstStructureGet<double>(structure, "timestamp"_s))
        timestamp = Seconds::fromMicroseconds(*value).milliseconds();
}

RTCStatsReport::RtpStreamStats::RtpStreamStats(Type type, const GstStructure* structure)
    : Stats(type, structure)
    , kind(gstStructureGetString(structure, "kind"_s).span())
    , transportId(gstStructureGetString(structure, "transport-id"_s).span())
    , codecId(gstStructureGetString(structure, "codec-id"_s).span())
{
    if (auto value = gstStructureGet<unsigned>(structure, "ssrc"_s))
        ssrc = *value;
}

RTCStatsReport::SentRtpStreamStats::SentRtpStreamStats(Type type, const GstStructure* structure)
    : RtpStreamStats(type, structure)
{
    packetsSent = gstStructureGet<uint64_t>(structure, "packets-sent"_s);
    bytesSent = gstStructureGet<uint64_t>(structure, "bytes-sent"_s);
}

RTCStatsReport::CodecStats::CodecStats(const GstStructure* structure)
    : Stats(Type::Codec, structure)
    , mimeType(gstStructureGetString(structure, "mime-type"_s).span())
    , sdpFmtpLine(gstStructureGetString(structure, "sdp-fmtp-line"_s).span())
{
    clockRate = gstStructureGet<unsigned>(structure, "clock-rate"_s);
    channels = gstStructureGet<unsigned>(structure, "channels"_s);

    if (auto value = gstStructureGet<unsigned>(structure, "payload-type"_s))
        payloadType = *value;

    // FIXME:
    // stats.implementation =
}

RTCStatsReport::ReceivedRtpStreamStats::ReceivedRtpStreamStats(Type type, const GstStructure* structure)
    : RtpStreamStats(type, structure)
{
    GUniqueOutPtr<GstStructure> rtpSourceStats;
    gst_structure_get(structure, "gst-rtpsource-stats", GST_TYPE_STRUCTURE, &rtpSourceStats.outPtr(), nullptr);

    if (rtpSourceStats)
        packetsReceived = gstStructureGet<uint64_t>(rtpSourceStats.get(), "packets-received"_s);

#if GST_CHECK_VERSION(1, 22, 0)
    packetsLost = gstStructureGet<int64_t>(structure, "packets-lost"_s);
#else
    packetsLost = gstStructureGet<unsigned>(structure, "packets-lost"_s);
#endif

    jitter = gstStructureGet<double>(structure, "jitter"_s);
}

RTCStatsReport::RemoteInboundRtpStreamStats::RemoteInboundRtpStreamStats(const GstStructure* structure)
    : ReceivedRtpStreamStats(Type::RemoteInboundRtp, structure)
    , localId(gstStructureGetString(structure, "local-id"_s).span())
{
    roundTripTime = gstStructureGet<double>(structure, "round-trip-time"_s);
    fractionLost = gstStructureGet<double>(structure, "fraction-lost"_s);

    // FIXME:
    // stats.reportsReceived
    // stats.roundTripTimeMeasurements
}

RTCStatsReport::RemoteOutboundRtpStreamStats::RemoteOutboundRtpStreamStats(const GstStructure* structure)
    : SentRtpStreamStats(Type::RemoteOutboundRtp, structure)
    , localId(gstStructureGetString(structure, "local-id"_s).span())
{
    remoteTimestamp = gstStructureGet<double>(structure, "remote-timestamp"_s);

    // FIXME:
    // stats.roundTripTime
    // stats.reportsSent
    // stats.totalRoundTripTime
    // stats.roundTripTimeMeasurements
}

RTCStatsReport::InboundRtpStreamStats::InboundRtpStreamStats(const GstStructure* structure)
    : ReceivedRtpStreamStats(Type::InboundRtp, structure)
{
    bytesReceived = gstStructureGet<uint64_t>(structure, "bytes-received"_s);
    packetsDiscarded = gstStructureGet<uint64_t>(structure, "packets-discarded"_s);
    packetsDuplicated = gstStructureGet<uint64_t>(structure, "packets-duplicated"_s);
    firCount = gstStructureGet<unsigned>(structure, "fir-count"_s);
    pliCount = gstStructureGet<unsigned>(structure, "pli-count"_s);
    nackCount = gstStructureGet<unsigned>(structure, "nack-count"_s);

    // This should be exposed only if allowed (due to fingerprinting).
    // if (kind == "video"_s)
    //     decoderImplementation = gstStructureGetString(structure, "decoder-implementation"_s).span();

    framesPerSecond = gstStructureGet<double>(structure, "frames-per-second"_s);
    totalDecodeTime = gstStructureGet<double>(structure, "total-decode-time"_s);
    framesDecoded = gstStructureGet<uint64_t>(structure, "frames-decoded"_s);
    framesDropped = gstStructureGet<uint64_t>(structure, "frames-dropped"_s);
    frameWidth = gstStructureGet<unsigned>(structure, "frame-width"_s);
    frameHeight = gstStructureGet<unsigned>(structure, "frame-height"_s);
    framesReceived = gstStructureGet<uint64_t>(structure, "frames-received"_s);
    keyFramesDecoded = gstStructureGet<uint64_t>(structure, "key-frames-decoded"_s);

    if (auto identifier = gstStructureGetString(structure, "track-identifier"_s))
        trackIdentifier = identifier.span();

    // FIXME:
    // stats.fractionLost =
    // stats.burstPacketsLost =
    // stats.burstPacketsDiscarded =
    // stats.burstLossCount =
    // stats.burstDiscardCount =
    // stats.burstLossRate =
    // stats.burstDiscardRate =
    // stats.gapLossRate =
    // stats.gapDiscardRate =
}

RTCStatsReport::OutboundRtpStreamStats::OutboundRtpStreamStats(const GstStructure* structure)
    : SentRtpStreamStats(Type::OutboundRtp, structure)
    , remoteId(gstStructureGetString(structure, "remote-id"_s).span())
{
    firCount = gstStructureGet<unsigned>(structure, "fir-count"_s);
    pliCount = gstStructureGet<unsigned>(structure, "pli-count"_s);
    nackCount = gstStructureGet<unsigned>(structure, "nack-count"_s);

    framesSent = gstStructureGet<uint64_t>(structure, "frames-sent"_s);
    framesEncoded = gstStructureGet<uint64_t>(structure, "frames-encoded"_s);
    targetBitrate = gstStructureGet<double>(structure, "target-bitrate"_s);
    frameWidth = gstStructureGet<unsigned>(structure, "frame-width"_s);
    frameHeight = gstStructureGet<unsigned>(structure, "frame-height"_s);
    framesPerSecond = gstStructureGet<double>(structure, "frames-per-second"_s);

    if (auto midValue = gstStructureGetString(structure, "mid"_s))
        mid = midValue.span();
    if (auto ridValue = gstStructureGetString(structure, "rid"_s))
        rid = ridValue.span();
}

RTCStatsReport::PeerConnectionStats::PeerConnectionStats(const GstStructure* structure)
    : Stats(Type::PeerConnection, structure)
{
    dataChannelsOpened = gstStructureGet<int>(structure, "data-channels-opened"_s);
    dataChannelsClosed = gstStructureGet<int>(structure, "data-channels-closed"_s);
}

RTCStatsReport::TransportStats::TransportStats(const GstStructure* structure)
    : Stats(Type::Transport, structure)
    , selectedCandidatePairId(gstStructureGetString(structure, "selected-candidate-pair-id"_s).span())
{
    // https://gitlab.freedesktop.org/gstreamer/gstreamer/-/commit/9e38ee7526ecbb12320d1aef29a0c74b815eb4ef
    if (gst_structure_has_field_typed(structure, "dtls-state", GST_TYPE_WEBRTC_DTLS_TRANSPORT_STATE)) {
        GstWebRTCDTLSTransportState state;
        gst_structure_get(structure, "dtls-state", GST_TYPE_WEBRTC_DTLS_TRANSPORT_STATE, &state, nullptr);
        dtlsState = toRTCDtlsTransportState(state);
    } else {
        // Our GStreamer version is likely too old, but this field being required, hard-code it to Connected.
        dtlsState = RTCDtlsTransportState::Connected;
    }

    // https://gitlab.freedesktop.org/gstreamer/gstreamer/-/commit/9e38ee7526ecbb12320d1aef29a0c74b815eb4ef
#if GST_CHECK_VERSION(1, 27, 0)
    if (gst_structure_has_field_typed(structure, "dtls-role", GST_TYPE_WEBRTC_DTLS_ROLE)) {
        GstWebRTCDTLSRole role;
        gst_structure_get(structure, "dtls-role", GST_TYPE_WEBRTC_DTLS_ROLE, &role, nullptr);
        switch (role) {
        case GST_WEBRTC_DTLS_ROLE_CLIENT:
            dtlsRole = DtlsRole::Client;
            break;
        case GST_WEBRTC_DTLS_ROLE_SERVER:
            dtlsRole = DtlsRole::Server;
            break;
        case GST_WEBRTC_DTLS_ROLE_UNKNOWN:
            dtlsRole = DtlsRole::Unknown;
            break;
        }
    }
#endif
    // FIXME
    // stats.bytesSent =
    // stats.bytesReceived =
    // stats.rtcpTransportStatsId =
    // stats.localCertificateId =
    // stats.remoteCertificateId =
    // stats.tlsVersion =
    // stats.dtlsCipher =
    // stats.srtpCipher =
}

RTCStatsReport::IceCandidateStats::IceCandidateStats(GstWebRTCStatsType statsType, const GstStructure* structure)
    : Stats(statsType == GST_WEBRTC_STATS_REMOTE_CANDIDATE ? Type::RemoteCandidate : Type::LocalCandidate, structure)
    , transportId(gstStructureGetString(structure, "transport-id"_s).span())
    , protocol(gstStructureGetString(structure, "protocol"_s).span())
    , url(gstStructureGetString(structure, "url"_s).span())
    , foundation(gstStructureGetString(structure, "foundation"_s).span())
    , usernameFragment(gstStructureGetString(structure, "username-fragment"_s).span())
{
    // NOTE: We have the address field in the structure but we don't expose it for privacy reasons.
    // Covered by test: webrtc/candidate-stats.html
    port = gstStructureGet<unsigned>(structure, "port"_s);
    priority = gstStructureGet<unsigned>(structure, "priority"_s);

#if GST_CHECK_VERSION(1, 27, 0)
    GstWebRTCICETcpCandidateType gstTcpType;
    if (gst_structure_get(structure, "tcp-type", &gstTcpType, nullptr)) {
        switch (gstTcpType) {
        case GST_WEBRTC_ICE_TCP_CANDIDATE_TYPE_ACTIVE:
            tcpType = RTCIceTcpCandidateType::Active;
            break;
        case GST_WEBRTC_ICE_TCP_CANDIDATE_TYPE_PASSIVE:
            tcpType = RTCIceTcpCandidateType::Passive;
            break;
        case GST_WEBRTC_ICE_TCP_CANDIDATE_TYPE_SO:
            tcpType = RTCIceTcpCandidateType::So;
            break;
        case GST_WEBRTC_ICE_TCP_CANDIDATE_TYPE_NONE:
            break;
        };
    }
#endif

    candidateType = RTCIceCandidateType::Host;

    auto value = gstStructureGetString(structure, "candidate-type"_s);
    if (!value) [[unlikely]]
        return;

    if (auto iceCandidateType = toRTCIceCandidateType(StringView::fromLatin1(value.utf8())))
        candidateType = *iceCandidateType;
}

RTCStatsReport::IceCandidatePairStats::IceCandidatePairStats(const GstStructure* structure)
    : Stats(Type::CandidatePair, structure)
    , localCandidateId(gstStructureGetString(structure, "local-candidate-id"_s).span())
    , remoteCandidateId(gstStructureGetString(structure, "remote-candidate-id"_s).span())
{
    // FIXME
    // stats.transportId =
    state = RTCStatsReport::IceCandidatePairState::Succeeded;
    // stats.priority =
    // stats.nominated =
    // stats.writable =
    // stats.readable =
    // stats.bytesSent =
    // stats.bytesReceived =
    // stats.totalRoundTripTime =
    // stats.currentRoundTripTime =
    // stats.availableOutgoingBitrate =
    // stats.availableIncomingBitrate =
    // stats.requestsReceived =
    // stats.requestsSent =
    // stats.responsesReceived =
    // stats.responsesSent =
    // stats.retransmissionsReceived =
    // stats.retransmissionsSent =
    // stats.consentRequestsReceived =
    // stats.consentRequestsSent =
    // stats.consentResponsesReceived =
    // stats.consentResponsesSent =
}

RTCStatsReport::CertificateStats::CertificateStats(const GstStructure* structure)
    : Stats(Type::Certificate, structure)
    , fingerprint(gstStructureGetString(structure, "fingerprint"_s).span())
    , fingerprintAlgorithm(gstStructureGetString(structure, "fingerprint-algorithm"_s).span())
    , base64Certificate(gstStructureGetString(structure, "base64-certificate"_s).span())

{
    // FIXME: Fill issuerCertificateId if present.
}

RTCStatsReport::MediaSourceStats::MediaSourceStats(Type type, const GstStructure* structure)
    : Stats(type, structure)
    , trackIdentifier(gstStructureGetString(structure, "track-identifier"_s).span())
    , kind(gstStructureGetString(structure, "kind"_s).span())
{
}

RTCStatsReport::AudioSourceStats::AudioSourceStats(const GstStructure* structure)
    : MediaSourceStats(Type::MediaSource, structure)
    , audioLevel(gstStructureGet<double>(structure, "audio-level"_s))
    , totalAudioEnergy(gstStructureGet<double>(structure, "total-audio-energy"_s))
    , totalSamplesDuration(gstStructureGet<double>(structure, "total-samples-duration"_s))
{
    /* FIXME:
        std::optional<double> echoReturnLoss;
        std::optional<double> echoReturnLossEnhancement;
     */
}

RTCStatsReport::VideoSourceStats::VideoSourceStats(const GstStructure* structure)
    : MediaSourceStats(Type::MediaSource, structure)
    , width(gstStructureGet<unsigned>(structure, "width"_s))
    , height(gstStructureGet<unsigned>(structure, "height"_s))
    , frames(gstStructureGet<unsigned>(structure, "frames"_s))
    , framesPerSecond(gstStructureGet<double>(structure, "frames-per-second"_s))
{
}

struct ReportHolder : public ThreadSafeRefCounted<ReportHolder> {
    WTF_MAKE_TZONE_ALLOCATED_INLINE(ReportHolder);
    WTF_MAKE_NONCOPYABLE(ReportHolder);
public:
    ReportHolder(DOMMapAdapter* adapter)
        : adapter(adapter) { }

    DOMMapAdapter* adapter;
};

static gboolean fillReportCallback(const GValue* value, Ref<ReportHolder>& reportHolder)
{
    if (!GST_VALUE_HOLDS_STRUCTURE(value))
        return TRUE;

    const GstStructure* structure = gst_value_get_structure(value);

    if (!reportHolder->adapter) [[unlikely]]
        return TRUE;

    auto& report = *reportHolder->adapter;

    if (auto webkitStatsType = gstStructureGetString(structure, "webkit-stats-type"_s)) {
        if (webkitStatsType == "audio-source-stats"_s) {
            RTCStatsReport::AudioSourceStats stats(structure);
            report.set<IDLDOMString, IDLDictionary<RTCStatsReport::AudioSourceStats>>(stats.id, WTF::move(stats));
            return TRUE;
        }
        if (webkitStatsType == "video-source-stats"_s) {
            RTCStatsReport::VideoSourceStats stats(structure);
            report.set<IDLDOMString, IDLDictionary<RTCStatsReport::VideoSourceStats>>(stats.id, WTF::move(stats));
            return TRUE;
        }
    }

    GstWebRTCStatsType statsType;
    if (!gst_structure_get(structure, "type", GST_TYPE_WEBRTC_STATS_TYPE, &statsType, nullptr))
        return TRUE;

    switch (statsType) {
    case GST_WEBRTC_STATS_CODEC: {
        RTCStatsReport::CodecStats stats(structure);
        report.set<IDLDOMString, IDLDictionary<RTCStatsReport::CodecStats>>(stats.id, WTF::move(stats));
        break;
    }
    case GST_WEBRTC_STATS_INBOUND_RTP: {
        RTCStatsReport::InboundRtpStreamStats stats(structure);
        report.set<IDLDOMString, IDLDictionary<RTCStatsReport::InboundRtpStreamStats>>(stats.id, WTF::move(stats));
        break;
    }
    case GST_WEBRTC_STATS_OUTBOUND_RTP: {
        RTCStatsReport::OutboundRtpStreamStats stats(structure);
        report.set<IDLDOMString, IDLDictionary<RTCStatsReport::OutboundRtpStreamStats>>(stats.id, WTF::move(stats));
        break;
    }
    case GST_WEBRTC_STATS_REMOTE_INBOUND_RTP: {
        RTCStatsReport::RemoteInboundRtpStreamStats stats(structure);
        report.set<IDLDOMString, IDLDictionary<RTCStatsReport::RemoteInboundRtpStreamStats>>(stats.id, WTF::move(stats));
        break;
    }
    case GST_WEBRTC_STATS_REMOTE_OUTBOUND_RTP: {
        RTCStatsReport::RemoteOutboundRtpStreamStats stats(structure);
        report.set<IDLDOMString, IDLDictionary<RTCStatsReport::RemoteOutboundRtpStreamStats>>(stats.id, WTF::move(stats));
        break;
    }
    case GST_WEBRTC_STATS_CSRC:
        // Deprecated stats: csrc.
        break;
    case GST_WEBRTC_STATS_PEER_CONNECTION: {
        RTCStatsReport::PeerConnectionStats stats(structure);
        report.set<IDLDOMString, IDLDictionary<RTCStatsReport::PeerConnectionStats>>(stats.id, WTF::move(stats));
        break;
    }
    case GST_WEBRTC_STATS_TRANSPORT: {
        RTCStatsReport::TransportStats stats(structure);
        report.set<IDLDOMString, IDLDictionary<RTCStatsReport::TransportStats>>(stats.id, WTF::move(stats));
        break;
    }
    case GST_WEBRTC_STATS_STREAM:
        // Deprecated stats: stream.
        break;
    case GST_WEBRTC_STATS_DATA_CHANNEL:
        // FIXME: Missing data-channel stats support.
        break;
    case GST_WEBRTC_STATS_LOCAL_CANDIDATE:
    case GST_WEBRTC_STATS_REMOTE_CANDIDATE:
        if (gst_check_version(1, 22, 0)) {
            RTCStatsReport::IceCandidateStats stats(statsType, structure);
            report.set<IDLDOMString, IDLDictionary<RTCStatsReport::IceCandidateStats>>(stats.id, WTF::move(stats));
        }
        break;
    case GST_WEBRTC_STATS_CANDIDATE_PAIR:
        if (gst_check_version(1, 22, 0)) {
            RTCStatsReport::IceCandidatePairStats stats(structure);
            report.set<IDLDOMString, IDLDictionary<RTCStatsReport::IceCandidatePairStats>>(stats.id, WTF::move(stats));
        }
        break;
    case GST_WEBRTC_STATS_CERTIFICATE: {
        // https://gitlab.freedesktop.org/gstreamer/gstreamer/-/merge_requests/10313
        RTCStatsReport::CertificateStats stats(structure);
        report.set<IDLDOMString, IDLDictionary<RTCStatsReport::CertificateStats>>(stats.id, WTF::move(stats));
        break;
    }
    }

    return TRUE;
}

struct CallbackHolder {
    GStreamerStatsCollector::StatsCallback callback;
    GStreamerStatsCollector::PreprocessCallback preprocessCallback;
    GRefPtr<GstPad> pad;
};

WEBKIT_DEFINE_ASYNC_DATA_STRUCT(CallbackHolder)

void GStreamerStatsCollector::gatherStats(StatsCallback&& callback, const GRefPtr<GstPad>& pad, PreprocessCallback&& preprocessCallback)
{
    auto webrtcBin = m_webrtcBin.get();
    if (!webrtcBin) {
        callback(nullptr);
        return;
    }

    auto* holder = createCallbackHolder();
    holder->callback = WTF::move(callback);
    holder->preprocessCallback = WTF::move(preprocessCallback);
    holder->pad = pad;
    g_signal_emit_by_name(webrtcBin.get(), "get-stats", pad.get(), gst_promise_new_with_change_func([](GstPromise* rawPromise, gpointer userData) mutable {
        auto promise = adoptGRef(rawPromise);
        auto* holder = static_cast<CallbackHolder*>(userData);
        if (gst_promise_wait(promise.get()) != GST_PROMISE_RESULT_REPLIED) {
            holder->callback(nullptr);
            return;
        }

        const auto* stats = gst_promise_get_reply(promise.get());
        if (!stats) {
            holder->callback(nullptr);
            return;
        }

        if (gst_structure_has_field(stats, "error")) {
            GUniqueOutPtr<GError> error;
            gst_structure_get(stats, "error", G_TYPE_ERROR, &error.outPtr(), nullptr);
            GST_WARNING("Unable to get stats, error: %s", error->message);
            holder->callback(nullptr);
            return;
        }

        callOnMainThreadAndWait([holder, stats] {
            holder->callback(holder->preprocessCallback(holder->pad, stats));
        });
    }, holder, reinterpret_cast<GDestroyNotify>(destroyCallbackHolder)));
}

void GStreamerStatsCollector::getStats(CollectorCallback&& callback, const GRefPtr<GstPad>& pad, PreprocessCallback&& preprocessCallback)
{
    static auto s_maximumReportAge = 300_ms;
    static std::once_flag onceFlag;
    std::call_once(onceFlag, [] {
        auto expirationTime = StringView::fromLatin1(std::getenv("WEBKIT_GST_WEBRTC_STATS_CACHE_EXPIRATION_TIME_MS"));
        if (expirationTime.isEmpty())
            return;

        if (auto milliseconds = WTF::parseInteger<int>(expirationTime))
            s_maximumReportAge = Seconds::fromMilliseconds(*milliseconds);
    });

    auto webrtcBin = m_webrtcBin.get();
    if (!webrtcBin) {
        callback(nullptr);
        return;
    }

    auto now = MonotonicTime::now();
    if (!pad) {
        if (m_cachedGlobalReport && (now - m_cachedGlobalReport->generationTime < s_maximumReportAge)) {
            GST_TRACE_OBJECT(webrtcBin.get(), "Returning cached global stats report");
            callback(m_cachedGlobalReport->report.get());
            return;
        }
    } else if (auto report = m_cachedReportsPerPad.getOptional(pad)) {
        if (now - report->generationTime < s_maximumReportAge) {
            GST_TRACE_OBJECT(webrtcBin.get(), "Returning cached stats report for pad %" GST_PTR_FORMAT, pad.get());
            callback(report->report.get());
            return;
        }
    }

    gatherStats([this, pad = GRefPtr(pad), callback = WTF::move(callback)](auto&& stats) mutable {
        if (!stats) {
            callback(nullptr);
            return;
        }
        auto report = RTCStatsReport::create([stats = WTF::move(stats)](auto& mapAdapter) mutable {
            auto holder = adoptRef(*new ReportHolder(&mapAdapter));
            gstStructureForeach(stats.get(), [&](auto, const auto value) -> bool {
                return fillReportCallback(value, holder);
            });
        });
        CachedReport cachedReport;
        cachedReport.generationTime = MonotonicTime::now();
        cachedReport.report = report.ptr();
        if (pad)
            m_cachedReportsPerPad.set(pad, WTF::move(cachedReport));
        else
            m_cachedGlobalReport = WTF::move(cachedReport);
        callback(WTF::move(report));
    }, pad, WTF::move(preprocessCallback));
}

void GStreamerStatsCollector::invalidateCache()
{
    ASSERT(isMainThread());
    m_cachedGlobalReport = std::nullopt;
    m_cachedReportsPerPad.clear();
}

void GStreamerStatsCollector::gatherDecoderImplementationName(const GRefPtr<GstPad>& pad, PreprocessCallback&& preprocessCallback, Function<void(String&&)>&& callback)
{
    gatherStats([callback = WTF::move(callback)](auto&& stats) mutable {
        if (!stats) {
            callback({ });
            return;
        }
        auto decoderImplementation = emptyString();
        gstStructureForeach(stats.get(), [&](auto, const auto value) -> bool {
            if (!GST_VALUE_HOLDS_STRUCTURE(value)) [[unlikely]]
                return true;

            const GstStructure* structure = gst_value_get_structure(value);
            GstWebRTCStatsType statsType;
            if (!gst_structure_get(structure, "type", GST_TYPE_WEBRTC_STATS_TYPE, &statsType, nullptr)) [[unlikely]]
                return true;

            if (statsType != GST_WEBRTC_STATS_INBOUND_RTP)
                return true;

            auto kind = gstStructureGetString(structure, "kind"_s);
            if (kind != "video"_s)
                return true;

            decoderImplementation = gstStructureGetString(structure, "decoder-implementation"_s).span();
            return false;
        });
        callback(WTF::move(decoderImplementation));
    }, pad, WTF::move(preprocessCallback));
}

#undef GST_CAT_DEFAULT

} // namespace WebCore

#endif // ENABLE(WEB_RTC) && USE(GSTREAMER_WEBRTC)