File: GStreamerDataChannelHandler.cpp

package info (click to toggle)
webkit2gtk 2.48.5-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 429,764 kB
  • sloc: cpp: 3,697,587; javascript: 194,444; ansic: 169,997; python: 46,499; asm: 19,295; ruby: 18,528; perl: 16,602; xml: 4,650; yacc: 2,360; sh: 2,098; java: 1,993; lex: 1,327; pascal: 366; makefile: 298
file content (443 lines) | stat: -rw-r--r-- 15,850 bytes parent folder | download | duplicates (7)
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
/*
 *  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 "GStreamerDataChannelHandler.h"

#if USE(GSTREAMER_WEBRTC)

#include "EventNames.h"
#include "GStreamerWebRTCUtils.h"
#include "RTCDataChannel.h"
#include "RTCDataChannelEvent.h"
#include "RTCError.h"
#include "RTCPriorityType.h"

#include <wtf/MainThread.h>
#include <wtf/TZoneMallocInlines.h>

GST_DEBUG_CATEGORY(webkit_webrtc_data_channel_debug);
#define GST_CAT_DEFAULT webkit_webrtc_data_channel_debug

#if GST_CHECK_VERSION(1, 22, 0)
#define DC_DEBUG(...) GST_DEBUG_ID(m_channelId.ascii().data(), __VA_ARGS__)
#define DC_TRACE(...) GST_TRACE_ID(m_channelId.ascii().data(), __VA_ARGS__)
#define DC_WARNING(...) GST_WARNING_ID(m_channelId.ascii().data(), __VA_ARGS__)
#define DC_MEMDUMP(...) GST_MEMDUMP_ID(m_channelId.ascii().data(), __VA_ARGS__)
#else
#define DC_DEBUG(...) GST_DEBUG(__VA_ARGS__)
#define DC_TRACE(...) GST_TRACE(__VA_ARGS__)
#define DC_WARNING(...) GST_WARNING(__VA_ARGS__)
#define DC_MEMDUMP(...) GST_MEMDUMP(__VA_ARGS__)
#endif

namespace WebCore {

WTF_MAKE_TZONE_ALLOCATED_IMPL(GStreamerDataChannelHandler);

GUniquePtr<GstStructure> GStreamerDataChannelHandler::fromRTCDataChannelInit(const RTCDataChannelInit& options)
{
    GUniquePtr<GstStructure> init(gst_structure_new("options", "protocol", G_TYPE_STRING, options.protocol.utf8().data(), nullptr));

    if (options.ordered)
        gst_structure_set(init.get(), "ordered", G_TYPE_BOOLEAN, *options.ordered, nullptr);
    if (options.maxPacketLifeTime)
        gst_structure_set(init.get(), "max-packet-lifetime", G_TYPE_INT, *options.maxPacketLifeTime, nullptr);
    if (options.maxRetransmits)
        gst_structure_set(init.get(), "max-retransmits", G_TYPE_INT, *options.maxRetransmits, nullptr);
    if (options.negotiated)
        gst_structure_set(init.get(), "negotiated", G_TYPE_BOOLEAN, *options.negotiated, nullptr);
    if (options.id)
        gst_structure_set(init.get(), "id", G_TYPE_INT, *options.id, nullptr);

    GstWebRTCPriorityType priorityType;
    switch (options.priority) {
    case RTCPriorityType::VeryLow:
        priorityType = GST_WEBRTC_PRIORITY_TYPE_VERY_LOW;
        break;
    case RTCPriorityType::Low:
        priorityType = GST_WEBRTC_PRIORITY_TYPE_LOW;
        break;
    case RTCPriorityType::Medium:
        priorityType = GST_WEBRTC_PRIORITY_TYPE_MEDIUM;
        break;
    case RTCPriorityType::High:
        priorityType = GST_WEBRTC_PRIORITY_TYPE_HIGH;
        break;
    }
    gst_structure_set(init.get(), "priority", GST_TYPE_WEBRTC_PRIORITY_TYPE, priorityType, nullptr);

    return init;
}

GStreamerDataChannelHandler::GStreamerDataChannelHandler(GRefPtr<GstWebRTCDataChannel>&& channel)
    : m_channel(WTFMove(channel))
{
    static Atomic<uint64_t> nChannel = 0;
    m_channelId = makeString("webkit-webrtc-data-channel-"_s, nChannel.exchangeAdd(1));

    ASSERT(m_channel);
    static std::once_flag debugRegisteredFlag;
    std::call_once(debugRegisteredFlag, [] {
        GST_DEBUG_CATEGORY_INIT(webkit_webrtc_data_channel_debug, "webkitwebrtcdatachannel", 0, "WebKit WebRTC data-channel");
    });
    DC_DEBUG("New GStreamerDataChannelHandler for channel %p", m_channel.get());

    {
        Locker locker { m_clientLock };
        checkState();
    }

    g_signal_connect_swapped(m_channel.get(), "notify::ready-state", G_CALLBACK(+[](GStreamerDataChannelHandler* handler) {
        handler->readyStateChanged();
    }), this);
    g_signal_connect_swapped(m_channel.get(), "notify::buffered-amount", G_CALLBACK(+[](GStreamerDataChannelHandler* handler) {
        handler->bufferedAmountChanged();
    }), this);
    g_signal_connect_swapped(m_channel.get(), "on-message-data", G_CALLBACK(+[](GStreamerDataChannelHandler* handler, GBytes* bytes) {
        handler->onMessageData(bytes);
    }), this);
    g_signal_connect_swapped(m_channel.get(), "on-message-string", G_CALLBACK(+[](GStreamerDataChannelHandler* handler, const char* message) {
        handler->onMessageString(message);
    }), this);
    g_signal_connect_swapped(m_channel.get(), "on-error", G_CALLBACK(+[](GStreamerDataChannelHandler* handler, GError* error) {
        handler->onError(error);
    }), this);
    g_signal_connect_swapped(m_channel.get(), "on-close", G_CALLBACK(+[](GStreamerDataChannelHandler* handler) {
        handler->onClose();
    }), this);
}

GStreamerDataChannelHandler::~GStreamerDataChannelHandler()
{
    DC_DEBUG("Deleting GStreamerDataChannelHandler for channel %p", m_channel.get());
    if (m_channel)
        g_signal_handlers_disconnect_by_data(m_channel.get(), this);
}

RTCDataChannelInit GStreamerDataChannelHandler::dataChannelInit() const
{
    GUniqueOutPtr<char> protocol;
    gboolean ordered, negotiated;
    gint maxPacketLifeTime, maxRetransmits, id;
    g_object_get(m_channel.get(), "ordered", &ordered, "max-packet-lifetime", &maxPacketLifeTime, "max-retransmits", &maxRetransmits,
        "protocol", &protocol.outPtr(), "negotiated", &negotiated, "id", &id, nullptr);

    RTCDataChannelInit init;
    init.ordered = ordered;
    init.maxPacketLifeTime = maxPacketLifeTime;
    init.maxRetransmits = maxRetransmits;
    init.protocol = String::fromLatin1(protocol.get());
    init.negotiated = negotiated;
    init.id = id;
    return init;
}

String GStreamerDataChannelHandler::label() const
{
    GUniqueOutPtr<char> label;
    g_object_get(m_channel.get(), "label", &label.outPtr(), nullptr);
    return String::fromUTF8(label.get());
}

void GStreamerDataChannelHandler::setClient(RTCDataChannelHandlerClient& client, std::optional<ScriptExecutionContextIdentifier> contextIdentifier)
{
    Locker locker { m_clientLock };
    ASSERT(!m_client);
    DC_DEBUG("Setting client on channel %p", m_channel.get());
    m_client = client;
    m_contextIdentifier = contextIdentifier;

    auto readyStateDispatched = checkState();

    auto messages = WTFMove(m_pendingMessages);
    for (auto& message : messages) {
        switchOn(message, [&](Ref<FragmentedSharedBuffer>& data) {
            DC_DEBUG("Notifying queued raw data (size: %zu)", data->size());
            Ref contiguousData = data->makeContiguous();
            auto span = contiguousData->span();
            DC_MEMDUMP("Notifying raw data", span.data(), span.size());
            client.didReceiveRawData(span);
        }, [&](String& text) {
            DC_DEBUG("Notifying queued string of size %d", text.sizeInBytes());
            DC_TRACE("Notifying queued string %s", text.ascii().data());
            client.didReceiveStringData(text);
        }, [&](StateChange stateChange) {
            if (stateChange.error) {
                if (auto rtcError = toRTCError(*stateChange.error))
                    client.didDetectError(rtcError.releaseNonNull());
                return;
            }
            if (!readyStateDispatched) {
                DC_DEBUG("Dispatching state change to %d on channel %p", static_cast<int>(stateChange.state), m_channel.get());
                client.didChangeReadyState(stateChange.state);
            }
        });
    }
}

bool GStreamerDataChannelHandler::sendStringData(const CString& text)
{
    DC_DEBUG("Sending string of length: %zu", text.length());
    DC_TRACE("Sending string %s", text.data());
#if GST_CHECK_VERSION(1, 22, 0)
    GUniqueOutPtr<GError> error;
    // https://gitlab.freedesktop.org/gstreamer/gstreamer/-/merge_requests/1958
    gst_webrtc_data_channel_send_string_full(GST_WEBRTC_DATA_CHANNEL(m_channel.get()), text.data(), &error.outPtr());
    if (error)
        DC_WARNING("Unable to send string, error: %s", error->message);
    return !error;
#else
    g_signal_emit_by_name(m_channel.get(), "send-string", text.data());
    return true;
#endif
}

bool GStreamerDataChannelHandler::sendRawData(std::span<const uint8_t> data)
{
    DC_DEBUG("Sending raw data of length: %zu", data.size());
    DC_MEMDUMP("Sending raw data", data.data(), data.size());
    auto bytes = adoptGRef(g_bytes_new(data.data(), data.size()));
#if GST_CHECK_VERSION(1, 22, 0)
    GUniqueOutPtr<GError> error;
    // https://gitlab.freedesktop.org/gstreamer/gstreamer/-/merge_requests/1958
    gst_webrtc_data_channel_send_data_full(GST_WEBRTC_DATA_CHANNEL(m_channel.get()), bytes.get(), &error.outPtr());
    if (error)
        DC_WARNING("Unable to send raw data, error: %s", error->message);
    return !error;
#else
    g_signal_emit_by_name(m_channel.get(), "send-data", bytes.get());
    return true;
#endif
}

void GStreamerDataChannelHandler::close()
{
    DC_DEBUG("Closing channel %p", m_channel.get());
    m_closing = true;

    GstWebRTCDataChannelState channelState;
    g_object_get(m_channel.get(), "ready-state", &channelState, nullptr);

    if (channelState == GST_WEBRTC_DATA_CHANNEL_STATE_OPEN)
        g_signal_emit_by_name(m_channel.get(), "close");
}

std::optional<unsigned short> GStreamerDataChannelHandler::id() const
{
    int id;
    g_object_get(m_channel.get(), "id", &id, nullptr);
    return id != -1 ? std::make_optional(id) : std::nullopt;
}

bool GStreamerDataChannelHandler::checkState()
{
    ASSERT(m_clientLock.isHeld());

    DC_DEBUG("Checking state.");
    if (!m_channel) {
        DC_DEBUG("No channel.");
        return false;
    }

    GstWebRTCDataChannelState channelState;
    g_object_get(m_channel.get(), "ready-state", &channelState, nullptr);
    if (!channelState) {
        DC_DEBUG("Data-channel ready-state hasn't been set yet.");
        return false;
    }

    RTCDataChannelState state;
    switch (channelState) {
#if !GST_CHECK_VERSION(1, 22, 0)
    // Removed in https://gitlab.freedesktop.org/gstreamer/gstreamer/-/merge_requests/2099. In
    // GStreamer < 1.22 GST_WEBRTC_DATA_CHANNEL_STATE_NEW had the 0 value. We keep this case only to
    // avoid adding a default case.
    case GST_WEBRTC_DATA_CHANNEL_STATE_NEW:
        break;
#endif
    case GST_WEBRTC_DATA_CHANNEL_STATE_CONNECTING:
        state = RTCDataChannelState::Connecting;
        break;
    case GST_WEBRTC_DATA_CHANNEL_STATE_OPEN:
        state = RTCDataChannelState::Open;
        break;
    case GST_WEBRTC_DATA_CHANNEL_STATE_CLOSING:
        state = RTCDataChannelState::Closing;
        break;
    case GST_WEBRTC_DATA_CHANNEL_STATE_CLOSED:
        state = RTCDataChannelState::Closed;
        break;
    }

    if (!m_client) {
        DC_DEBUG("No client yet on channel %p, queueing state", m_channel.get());
        m_pendingMessages.append(StateChange { state, { } });
        return false;
    }

    if (channelState == GST_WEBRTC_DATA_CHANNEL_STATE_OPEN && m_closing) {
        DC_DEBUG("Ignoring open state notification on channel %p because it was pending to be closed", m_channel.get());
        return false;
    }

    if (!*m_client) {
        DC_DEBUG("Client is empty.");
        return false;
    }

#ifndef GST_DISABLE_GST_DEBUG
    GUniquePtr<char> stateString(g_enum_to_string(GST_TYPE_WEBRTC_DATA_CHANNEL_STATE, channelState));
    DC_DEBUG("Dispatching state change to %s on channel %p", stateString.get(), m_channel.get());
#endif
    postTask([client = m_client, state] {
        if (!*client) {
            GST_DEBUG("No client");
            return;
        }
        client.value()->didChangeReadyState(state);
    });
    return true;
}

void GStreamerDataChannelHandler::readyStateChanged()
{
    Locker locker { m_clientLock };
    checkState();
}

void GStreamerDataChannelHandler::bufferedAmountChanged()
{
    Locker locker { m_clientLock };

    uint64_t currentBufferedAmount;
    g_object_get(m_channel.get(), "buffered-amount", &currentBufferedAmount, nullptr);

    auto bufferedAmount = static_cast<size_t>(currentBufferedAmount);
    DC_DEBUG("New buffered amount on channel %p: %" G_GSIZE_FORMAT " old: %" G_GSIZE_FORMAT, m_channel.get(), bufferedAmount, m_cachedBufferedAmount ? *m_cachedBufferedAmount : -1);

    if (m_cachedBufferedAmount && (*m_cachedBufferedAmount >= bufferedAmount)) {
        DC_DEBUG("Buffered amount getting low on channel %p", m_channel.get());
        if (!m_client) {
            DC_DEBUG("No client yet on channel %p", m_channel.get());
            return;
        }

        postTask([client = m_client, amount = *m_cachedBufferedAmount - bufferedAmount] {
            if (!client)
                return;

            size_t clientAmount = client.value()->bufferedAmount();
            size_t clampedAmount = amount > clientAmount ? clientAmount : amount;
            client.value()->bufferedAmountIsDecreasing(clampedAmount);
        });
    }

    m_cachedBufferedAmount = bufferedAmount;
}

void GStreamerDataChannelHandler::onMessageData(GBytes* bytes)
{
    DC_DEBUG("Incoming data of size: %zu", g_bytes_get_size(bytes));
    Locker locker { m_clientLock };

    auto buffer = SharedBuffer::create(bytes);
    if (!m_client) {
        m_pendingMessages.append(WTFMove(buffer));
        return;
    }

    if (!*m_client)
        return;

    postTask([this, client = m_client, buffer = WTFMove(buffer)] {
        UNUSED_VARIABLE(this); // Conditionally used in DC_MEMDUMP.
        if (!*client)
            return;
        auto span = buffer->span();
        DC_MEMDUMP("Incoming raw data", span.data(), span.size());
        client.value()->didReceiveRawData(span);
    });
}

void GStreamerDataChannelHandler::onMessageString(const char* message)
{
    Locker locker { m_clientLock };

    DC_TRACE("Incoming string: %s", message);
    if (!m_client) {
        DC_DEBUG("No client yet, keeping as buffered message");
        m_pendingMessages.append(String::fromUTF8(message));
        return;
    }

    if (!*m_client)
        return;

    DC_DEBUG("Dispatching string of size %zu", strlen(message));
    postTask([client = m_client, string = String::fromUTF8(message)] {
        if (!*client)
            return;

        client.value()->didReceiveStringData(string);
    });
}

void GStreamerDataChannelHandler::onError(GError* error)
{
    Locker locker { m_clientLock };
    if (!m_client)
        return;

    DC_WARNING("Got data-channel error %s", error->message);
    GUniquePtr<GError> errorCopy(g_error_copy(error));
    postTask([client = m_client, error = WTFMove(errorCopy)] {
        if (!client || !error)
            return;

        auto rtcError = toRTCError(error.get());
        if (!rtcError)
            rtcError = RTCError::create(RTCError::Init { RTCErrorDetailType::DataChannelFailure, { }, { }, { }, { } }, { });
        client.value()->didDetectError(rtcError.releaseNonNull());
    });
}

void GStreamerDataChannelHandler::onClose()
{
    Locker locker { m_clientLock };
    DC_DEBUG("Channel %p closed!", m_channel.get());
    checkState();
}

void GStreamerDataChannelHandler::postTask(Function<void()>&& function)
{
    ASSERT(m_clientLock.isHeld());

    if (!m_contextIdentifier) {
        callOnMainThread(WTFMove(function));
        return;
    }
    ScriptExecutionContext::postTaskTo(*m_contextIdentifier, WTFMove(function));
}

#undef GST_CAT_DEFAULT

} // namespace WebCore

#endif // USE(GSTREAMER_WEBRTC)