pw_framebuffer.cpp 34 KB
Newer Older
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
/* This file is part of the KDE project
   Copyright (C) 2018 Oleg Chernovskiy <kanedias@xaker.ru>
   Copyright (C) 2018 Jan Grulich <jgrulich@redhat.com>

   This program 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.
*/

// system
#include <sys/mman.h>
#include <cstring>

// Qt
#include <QX11Info>
#include <QCoreApplication>
#include <QGuiApplication>
#include <QScreen>
#include <QSocketNotifier>
#include <QDebug>
#if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0))
#include <QRandomGenerator>
#endif

// pipewire
#include <pipewire/version.h>

29
30
#if PW_CHECK_VERSION(0, 2, 90)
#include <spa/utils/result.h>
31
#ifdef HAVE_LINUX_DMABUF_H
Aleix Pol Gonzalez's avatar
Aleix Pol Gonzalez committed
32
#include <linux/dma-buf.h>
33
#endif
Aleix Pol Gonzalez's avatar
Aleix Pol Gonzalez committed
34
#include <sys/ioctl.h>
35
#endif
36
37

#include <spa/param/format-utils.h>
38
39
40
41
42
43
44
45
46
47
#include <spa/param/video/format-utils.h>
#include <spa/param/props.h>

#include <pipewire/pipewire.h>

#include <limits.h>

#include "pw_framebuffer.h"
#include "xdp_dbus_screencast_interface.h"
#include "xdp_dbus_remotedesktop_interface.h"
48
#include "krfb_fb_pipewire_debug.h"
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

static const uint MIN_SUPPORTED_XDP_KDE_SC_VERSION = 1;

Q_DECLARE_METATYPE(PWFrameBuffer::Stream);
Q_DECLARE_METATYPE(PWFrameBuffer::Streams);

const QDBusArgument &operator >> (const QDBusArgument &arg, PWFrameBuffer::Stream &stream)
{
    arg.beginStructure();
    arg >> stream.nodeId;

    arg.beginMap();
    while (!arg.atEnd()) {
        QString key;
        QVariant map;
        arg.beginMapEntry();
        arg >> key >> map;
        arg.endMapEntry();
        stream.map.insert(key, map);
    }
    arg.endMap();
    arg.endStructure();

    return arg;
}

75
#if !PW_CHECK_VERSION(0, 2, 90)
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
/**
 * @brief The PwType class - helper class to contain pointers to raw C pipewire media mappings
 */
class PwType {
public:
    spa_type_media_type media_type;
    spa_type_media_subtype media_subtype;
    spa_type_format_video format_video;
    spa_type_video_format video_format;
};
#endif

/**
 * @brief The PWFrameBuffer::Private class - private counterpart of PWFramebuffer class. This is the entity where
 *        whole logic resides, for more info search for "d-pointer pattern" information.
 */
class PWFrameBuffer::Private {
public:
    Private(PWFrameBuffer *q);
    ~Private();

private:
    friend class PWFrameBuffer;

100
101
102
103
#if PW_CHECK_VERSION(0, 2, 90)
    static void onCoreError(void *data, uint32_t id, int seq, int res, const char *message);
    static void onStreamParamChanged(void *data, uint32_t id, const struct spa_pod *format);
#else
104
105
    static void onStateChanged(void *data, pw_remote_state old, pw_remote_state state, const char *error);
    static void onStreamFormatChanged(void *data, const struct spa_pod *format);
106
107
#endif
    static void onStreamStateChanged(void *data, pw_stream_state old, pw_stream_state state, const char *error_message);
108
109
110
111
    static void onStreamProcess(void *data);

    void initDbus();
    void initPw();
112
#if !PW_CHECK_VERSION(0, 2, 90)
113
114
115
116
117
118
119
120
121
122
    void initializePwTypes();
#endif

    // dbus handling
    void handleSessionCreated(quint32 &code, QVariantMap &results);
    void handleDevicesSelected(quint32 &code, QVariantMap &results);
    void handleSourcesSelected(quint32 &code, QVariantMap &results);
    void handleRemoteDesktopStarted(quint32 &code, QVariantMap &results);

    // pw handling
123
    pw_stream *createReceivingStream();
124
125
126
127
128
129
    void handleFrame(pw_buffer *pwBuffer);

    // link to public interface
    PWFrameBuffer *q;

    // pipewire stuff
130
131
#if PW_CHECK_VERSION(0, 2, 90)
    struct pw_context *pwContext = nullptr;
132
133
134
    struct pw_core *pwCore = nullptr;
    struct pw_stream *pwStream = nullptr;
    struct pw_thread_loop *pwMainLoop = nullptr;
135
136
137
138
139
140
141
142
143

    // wayland-like listeners
    // ...of events that happen in pipewire server
    spa_hook coreListener = {};
    spa_hook streamListener = {};

    // event handlers
    pw_core_events pwCoreEvents = {};
    pw_stream_events pwStreamEvents = {};
144
145
146
#else
    pw_core *pwCore = nullptr;
    pw_loop *pwLoop = nullptr;
147
    pw_thread_loop *pwMainLoop = nullptr;
148
149
150
151
152
    pw_stream *pwStream = nullptr;
    pw_remote *pwRemote = nullptr;
    pw_type *pwCoreType = nullptr;
    PwType *pwType = nullptr;

153
154
    spa_hook remoteListener = {};
    spa_hook streamListener = {};
155
156
157
158

    // event handlers
    pw_remote_events pwRemoteEvents = {};
    pw_stream_events pwStreamEvents = {};
159
#endif
160

161
    uint pwStreamNodeId = 0;
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

    // negotiated video format
    spa_video_info_raw *videoFormat = nullptr;

    // requests a session from XDG Desktop Portal
    // auto-generated and compiled from xdp_dbus_interface.xml file
    QScopedPointer<OrgFreedesktopPortalScreenCastInterface> dbusXdpScreenCastService;
    QScopedPointer<OrgFreedesktopPortalRemoteDesktopInterface> dbusXdpRemoteDesktopService;

    // XDP screencast session handle
    QDBusObjectPath sessionPath;
    // Pipewire file descriptor
    QDBusUnixFileDescriptor pipewireFd;

    // screen geometry holder
    struct {
        quint32 width;
        quint32 height;
    } screenGeometry;

    // Allowed devices
    uint devices;

    // sanity indicator
    bool isValid = true;
};

PWFrameBuffer::Private::Private(PWFrameBuffer *q) : q(q)
{
191
192
193
194
195
196
197
198
199
#if PW_CHECK_VERSION(0, 2, 90)
    pwCoreEvents.version = PW_VERSION_CORE_EVENTS;
    pwCoreEvents.error = &onCoreError;

    pwStreamEvents.version = PW_VERSION_STREAM_EVENTS;
    pwStreamEvents.state_changed = &onStreamStateChanged;
    pwStreamEvents.param_changed = &onStreamParamChanged;
    pwStreamEvents.process = &onStreamProcess;
#else
200
201
202
203
204
205
206
207
    // initialize event handlers, remote end and stream-related
    pwRemoteEvents.version = PW_VERSION_REMOTE_EVENTS;
    pwRemoteEvents.state_changed = &onStateChanged;

    pwStreamEvents.version = PW_VERSION_STREAM_EVENTS;
    pwStreamEvents.state_changed = &onStreamStateChanged;
    pwStreamEvents.format_changed = &onStreamFormatChanged;
    pwStreamEvents.process = &onStreamProcess;
208
#endif
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
}

/**
 * @brief PWFrameBuffer::Private::initDbus - initialize D-Bus connectivity with XDG Desktop Portal.
 *        Based on XDG_CURRENT_DESKTOP environment variable it will give us implementation that we need,
 *        in case of KDE it is xdg-desktop-portal-kde binary.
 */
void PWFrameBuffer::Private::initDbus()
{
    qInfo() << "Initializing D-Bus connectivity with XDG Desktop Portal";
    dbusXdpScreenCastService.reset(new OrgFreedesktopPortalScreenCastInterface(QLatin1String("org.freedesktop.portal.Desktop"),
                                                                     QLatin1String("/org/freedesktop/portal/desktop"),
                                                                     QDBusConnection::sessionBus()));
    dbusXdpRemoteDesktopService.reset(new OrgFreedesktopPortalRemoteDesktopInterface(QLatin1String("org.freedesktop.portal.Desktop"),
                                                                     QLatin1String("/org/freedesktop/portal/desktop"),
                                                                     QDBusConnection::sessionBus()));
    auto version = dbusXdpScreenCastService->version();
    if (version < MIN_SUPPORTED_XDP_KDE_SC_VERSION) {
227
        qCWarning(KRFB_FB_PIPEWIRE) << "Unsupported XDG Portal screencast interface version:" << version;
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
        isValid = false;
        return;
    }

    // create session
    auto sessionParameters = QVariantMap {
#if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0))
        { QLatin1String("session_handle_token"), QStringLiteral("krfb%1").arg(QRandomGenerator::global()->generate()) },
        { QLatin1String("handle_token"), QStringLiteral("krfb%1").arg(QRandomGenerator::global()->generate()) }
#else
        { QLatin1String("session_handle_token"), QStringLiteral("krfb%1").arg(qrand()) },
        { QLatin1String("handle_token"), QStringLiteral("krfb%1").arg(qrand()) }
#endif
    };
    auto sessionReply = dbusXdpRemoteDesktopService->CreateSession(sessionParameters);
    sessionReply.waitForFinished();
    if (!sessionReply.isValid()) {
        qWarning("Couldn't initialize XDP-KDE screencast session");
        isValid = false;
        return;
    }

    qInfo() << "DBus session created: " << sessionReply.value().path();
    QDBusConnection::sessionBus().connect(QString(),
                                          sessionReply.value().path(),
                                          QLatin1String("org.freedesktop.portal.Request"),
                                          QLatin1String("Response"),
                                          this->q,
                                          SLOT(handleXdpSessionCreated(uint, QVariantMap)));
}

void PWFrameBuffer::handleXdpSessionCreated(quint32 code, QVariantMap results)
{
    d->handleSessionCreated(code, results);
}

/**
 * @brief PWFrameBuffer::Private::handleSessionCreated - handle creation of ScreenCast session.
 *        XDG Portal answers with session path if it was able to successfully create the screencast.
 *
 * @param code return code for dbus call. Zero is success, non-zero means error
 * @param results map with results of call.
 */
void PWFrameBuffer::Private::handleSessionCreated(quint32 &code, QVariantMap &results)
{
    if (code != 0) {
274
        qCWarning(KRFB_FB_PIPEWIRE) << "Failed to create session: " << code;
275
276
277
278
279
280
281
282
283
        isValid = false;
        return;
    }

    sessionPath = QDBusObjectPath(results.value(QLatin1String("session_handle")).toString());

    // select sources for the session
    auto selectionOptions = QVariantMap {
        // We have to specify it's an uint, otherwise xdg-desktop-portal will not forward it to backend implementation
284
        { QLatin1String("types"), QVariant::fromValue<uint>(7) }, // request all (KeyBoard, Pointer, TouchScreen)
285
286
287
288
289
290
291
292
293
#if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0))
        { QLatin1String("handle_token"), QStringLiteral("krfb%1").arg(QRandomGenerator::global()->generate()) }
#else
        { QLatin1String("handle_token"), QStringLiteral("krfb%1").arg(qrand()) }
#endif
    };
    auto selectorReply = dbusXdpRemoteDesktopService->SelectDevices(sessionPath, selectionOptions);
    selectorReply.waitForFinished();
    if (!selectorReply.isValid()) {
294
        qCWarning(KRFB_FB_PIPEWIRE) << "Couldn't select devices for the remote-desktop session";
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
        isValid = false;
        return;
    }
    QDBusConnection::sessionBus().connect(QString(),
                                          selectorReply.value().path(),
                                          QLatin1String("org.freedesktop.portal.Request"),
                                          QLatin1String("Response"),
                                          this->q,
                                          SLOT(handleXdpDevicesSelected(uint, QVariantMap)));
}

void PWFrameBuffer::handleXdpDevicesSelected(quint32 code, QVariantMap results)
{
    d->handleDevicesSelected(code, results);
}

/**
 * @brief PWFrameBuffer::Private::handleDevicesCreated - handle selection of devices we want to use for remote desktop
 *
 * @param code return code for dbus call. Zero is success, non-zero means error
 * @param results map with results of call.
 */
void PWFrameBuffer::Private::handleDevicesSelected(quint32 &code, QVariantMap &results)
{
Alexey Min's avatar
Alexey Min committed
319
    Q_UNUSED(results)
320
    if (code != 0) {
321
        qCWarning(KRFB_FB_PIPEWIRE) << "Failed to select devices: " << code;
322
323
324
325
326
327
        isValid = false;
        return;
    }

    // select sources for the session
    auto selectionOptions = QVariantMap {
328
        { QLatin1String("types"), QVariant::fromValue<uint>(1) }, // only MONITOR is supported
329
330
331
332
333
334
335
336
337
338
        { QLatin1String("multiple"), false },
#if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0))
        { QLatin1String("handle_token"), QStringLiteral("krfb%1").arg(QRandomGenerator::global()->generate()) }
#else
        { QLatin1String("handle_token"), QStringLiteral("krfb%1").arg(qrand()) }
#endif
    };
    auto selectorReply = dbusXdpScreenCastService->SelectSources(sessionPath, selectionOptions);
    selectorReply.waitForFinished();
    if (!selectorReply.isValid()) {
339
        qCWarning(KRFB_FB_PIPEWIRE) << "Couldn't select sources for the screen-casting session";
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
        isValid = false;
        return;
    }
    QDBusConnection::sessionBus().connect(QString(),
                                          selectorReply.value().path(),
                                          QLatin1String("org.freedesktop.portal.Request"),
                                          QLatin1String("Response"),
                                          this->q,
                                          SLOT(handleXdpSourcesSelected(uint, QVariantMap)));
}

void PWFrameBuffer::handleXdpSourcesSelected(quint32 code, QVariantMap results)
{
    d->handleSourcesSelected(code, results);
}

/**
 * @brief PWFrameBuffer::Private::handleSourcesSelected - handle Screencast sources selection.
 *        XDG Portal shows a dialog at this point which allows you to select monitor from the list.
 *        This function is called after you make a selection.
 *
 * @param code return code for dbus call. Zero is success, non-zero means error
 * @param results map with results of call.
 */
void PWFrameBuffer::Private::handleSourcesSelected(quint32 &code, QVariantMap &)
{
    if (code != 0) {
367
        qCWarning(KRFB_FB_PIPEWIRE) << "Failed to select sources: " << code;
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
        isValid = false;
        return;
    }

    // start session
    auto startParameters = QVariantMap {
#if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0))
        { QLatin1String("handle_token"), QStringLiteral("krfb%1").arg(QRandomGenerator::global()->generate()) }
#else
        { QLatin1String("handle_token"), QStringLiteral("krfb%1").arg(qrand()) }
#endif
    };
    auto startReply = dbusXdpRemoteDesktopService->Start(sessionPath, QString(), startParameters);
    startReply.waitForFinished();
    QDBusConnection::sessionBus().connect(QString(),
                                          startReply.value().path(),
                                          QLatin1String("org.freedesktop.portal.Request"),
                                          QLatin1String("Response"),
                                          this->q,
                                          SLOT(handleXdpRemoteDesktopStarted(uint, QVariantMap)));
}


void PWFrameBuffer::handleXdpRemoteDesktopStarted(quint32 code, QVariantMap results)
{
    d->handleRemoteDesktopStarted(code, results);
}

/**
 * @brief PWFrameBuffer::Private::handleScreencastStarted - handle Screencast start.
 *        At this point there shall be ready pipewire stream to consume.
 *
 * @param code return code for dbus call. Zero is success, non-zero means error
 * @param results map with results of call.
 */
void PWFrameBuffer::Private::handleRemoteDesktopStarted(quint32 &code, QVariantMap &results)
{
    if (code != 0) {
406
        qCWarning(KRFB_FB_PIPEWIRE) << "Failed to start screencast: " << code;
407
408
409
410
411
412
413
414
        isValid = false;
        return;
    }

    // there should be only one stream
    Streams streams = qdbus_cast<Streams>(results.value(QLatin1String("streams")));
    if (streams.isEmpty()) {
        // maybe we should check deeper with qdbus_cast but this suffices for now
415
        qCWarning(KRFB_FB_PIPEWIRE) << "Failed to get screencast streams";
416
417
418
419
420
421
422
        isValid = false;
        return;
    }

    auto streamReply = dbusXdpScreenCastService->OpenPipeWireRemote(sessionPath, QVariantMap());
    streamReply.waitForFinished();
    if (!streamReply.isValid()) {
423
        qCWarning(KRFB_FB_PIPEWIRE) << "Couldn't open pipewire remote for the screen-casting session";
424
425
426
427
428
429
        isValid = false;
        return;
    }

    pipewireFd = streamReply.value();
    if (!pipewireFd.isValid()) {
430
        qCWarning(KRFB_FB_PIPEWIRE) << "Couldn't get pipewire connection file descriptor";
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
        isValid = false;
        return;
    }

    QSize streamResolution = qdbus_cast<QSize>(streams.first().map.value(QLatin1String("size")));
    screenGeometry.width = streamResolution.width();
    screenGeometry.height = streamResolution.height();

    devices = results.value(QLatin1String("types")).toUInt();

    pwStreamNodeId = streams.first().nodeId;

    // Reallocate our buffer with actual needed size
    q->fb = static_cast<char*>(malloc(screenGeometry.width * screenGeometry.height * 4));

    if (!q->fb) {
447
        qCWarning(KRFB_FB_PIPEWIRE) << "Failed to allocate buffer";
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
        isValid = false;
        return;
    }

    Q_EMIT q->frameBufferChanged();

    initPw();
}

/**
 * @brief PWFrameBuffer::Private::initPw - initialize Pipewire socket connectivity.
 *        pipewireFd should be pointing to existing file descriptor that was passed by D-Bus at this point.
 */
void PWFrameBuffer::Private::initPw() {
    qInfo() << "Initializing Pipewire connectivity";

    // init pipewire (required)
    pw_init(nullptr, nullptr); // args are not used anyways

467
468
469
470
#if PW_CHECK_VERSION(0, 2, 90)
    pwMainLoop = pw_thread_loop_new("pipewire-main-loop", nullptr);
    pwContext = pw_context_new(pw_thread_loop_get_loop(pwMainLoop), nullptr, 0);
    if (!pwContext) {
471
        qCWarning(KRFB_FB_PIPEWIRE) << "Failed to create PipeWire context";
472
473
474
475
476
        return;
    }

    pwCore = pw_context_connect(pwContext, nullptr, 0);
    if (!pwCore) {
477
        qCWarning(KRFB_FB_PIPEWIRE) << "Failed to connect PipeWire context";
478
479
480
481
482
483
484
        return;
    }

    pw_core_add_listener(pwCore, &coreListener, &pwCoreEvents, this);

    pwStream = createReceivingStream();
    if (!pwStream) {
485
        qCWarning(KRFB_FB_PIPEWIRE) << "Failed to create PipeWire stream";
486
487
488
        return;
    }
#else
489
490
491
492
493
494
495
496
497
498
499
500
501
502
    // initialize our source
    pwLoop = pw_loop_new(nullptr);
    pwMainLoop = pw_thread_loop_new(pwLoop, "pipewire-main-loop");
    // create PipeWire core object (required)
    pwCore = pw_core_new(pwLoop, nullptr);
    pwCoreType = pw_core_get_type(pwCore);

    initializePwTypes();

    // pw_remote should be initialized before type maps or connection error will happen
    pwRemote = pw_remote_new(pwCore, nullptr, 0);
    // init PipeWire remote, add listener to handle events
    pw_remote_add_listener(pwRemote, &remoteListener, &pwRemoteEvents, this);
    pw_remote_connect_fd(pwRemote, pipewireFd.fileDescriptor());
503
#endif
504
505

    if (pw_thread_loop_start(pwMainLoop) < 0) {
506
        qCWarning(KRFB_FB_PIPEWIRE) << "Failed to start main PipeWire loop";
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
        isValid = false;
    }
}

#if !PW_CHECK_VERSION(0, 2, 9)
/**
 * @brief PWFrameBuffer::Private::initializePwTypes - helper method to initialize and map all needed
 *        Pipewire types from core to type structure.
 */
void PWFrameBuffer::Private::initializePwTypes()
{
    // raw C-like PipeWire type map
    spa_type_map *map = pwCoreType->map;
    pwType = new PwType();

    spa_type_media_type_map(map, &pwType->media_type);
    spa_type_media_subtype_map(map, &pwType->media_subtype);
    spa_type_format_video_map(map, &pwType->format_video);
    spa_type_video_format_map(map, &pwType->video_format);
}
#endif

529
530
531
532
533
534
535
536
537
538
539
540

#if PW_CHECK_VERSION(0, 2, 90)
void PWFrameBuffer::Private::onCoreError(void *data, uint32_t id, int seq, int res, const char *message)
{
    Q_UNUSED(data);
    Q_UNUSED(id);
    Q_UNUSED(seq);
    Q_UNUSED(res);

    qInfo() << "core error: " << message;
}
#else
541
542
543
544
545
546
547
548
549
550
551
552
553
554
/**
 * @brief PWFrameBuffer::Private::onStateChanged - global state tracking for pipewire connection
 * @param data pointer that you have set in pw_remote_add_listener call's last argument
 * @param state new state that connection has changed to
 * @param error optional error message, is set to non-null if state is error
 */
void PWFrameBuffer::Private::onStateChanged(void *data, pw_remote_state /*old*/, pw_remote_state state, const char *error)
{
    qInfo() << "remote state: " << pw_remote_state_as_string(state);

    PWFrameBuffer::Private *d = static_cast<PWFrameBuffer::Private*>(data);

    switch (state) {
    case PW_REMOTE_STATE_ERROR:
555
        qCWarning(KRFB_FB_PIPEWIRE) << "remote error: " << error;
556
557
        break;
    case PW_REMOTE_STATE_CONNECTED:
558
        d->pwStream = d->createReceivingStream();
559
560
561
562
563
564
        break;
    default:
        qInfo() << "remote state: " << pw_remote_state_as_string(state);
        break;
    }
}
565
#endif
566
567
568
569
570
571
572
573
574
575
576
577
578

/**
 * @brief PWFrameBuffer::Private::onStreamStateChanged - called whenever stream state changes on pipewire server
 * @param data pointer that you have set in pw_stream_add_listener call's last argument
 * @param state new state that stream has changed to
 * @param error_message optional error message, is set to non-null if state is error
 */
void PWFrameBuffer::Private::onStreamStateChanged(void *data, pw_stream_state /*old*/, pw_stream_state state, const char *error_message)
{
    qInfo() << "Stream state changed: " << pw_stream_state_as_string(state);

    auto *d = static_cast<PWFrameBuffer::Private *>(data);

579
580
581
#if PW_CHECK_VERSION(0, 2, 90)
    switch (state) {
    case PW_STREAM_STATE_ERROR:
582
        qCWarning(KRFB_FB_PIPEWIRE) << "pipewire stream error: " << error_message;
583
584
585
586
587
588
589
590
591
592
        break;
    case PW_STREAM_STATE_PAUSED:
            pw_stream_set_active(d->pwStream, true);
        break;
    case PW_STREAM_STATE_STREAMING:
    case PW_STREAM_STATE_UNCONNECTED:
    case PW_STREAM_STATE_CONNECTING:
        break;
    }
#else
593
594
    switch (state) {
    case PW_STREAM_STATE_ERROR:
595
        qCWarning(KRFB_FB_PIPEWIRE) << "pipewire stream error: " << error_message;
596
597
598
599
600
601
602
        break;
    case PW_STREAM_STATE_CONFIGURE:
        pw_stream_set_active(d->pwStream, true);
        break;
    default:
        break;
    }
603
#endif
604
605
606
607
608
609
610
611
}

/**
 * @brief PWFrameBuffer::Private::onStreamFormatChanged - being executed after stream is set to active
 *        and after setup has been requested to connect to it. The actual video format is being negotiated here.
 * @param data pointer that you have set in pw_stream_add_listener call's last argument
 * @param format format that's being proposed
 */
612
613
#if PW_CHECK_VERSION(0, 2, 90)
void PWFrameBuffer::Private::onStreamParamChanged(void *data, uint32_t id, const struct spa_pod *format)
614
615
#else
void PWFrameBuffer::Private::onStreamFormatChanged(void *data, const struct spa_pod *format)
616
#endif
617
618
619
620
621
622
{
    qInfo() << "Stream format changed";
    auto *d = static_cast<PWFrameBuffer::Private *>(data);

    const int bpp = 4;

623
624
625
#if PW_CHECK_VERSION(0, 2, 90)
    if (!format || id != SPA_PARAM_Format) {
#else
626
627
    if (!format) {
        pw_stream_finish_format(d->pwStream, 0, nullptr, 0);
628
#endif
629
630
631
632
        return;
    }

    d->videoFormat = new spa_video_info_raw();
633
#if PW_CHECK_VERSION(0, 2, 90)
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
    spa_format_video_raw_parse(format, d->videoFormat);
#else
    spa_format_video_raw_parse(format, d->videoFormat, &d->pwType->format_video);
#endif
    auto width = d->videoFormat->size.width;
    auto height = d->videoFormat->size.height;
    auto stride = SPA_ROUND_UP_N(width * bpp, 4);
    auto size = height * stride;

    uint8_t buffer[1024];
    auto builder = SPA_POD_BUILDER_INIT(buffer, sizeof(buffer));

    // setup buffers and meta header for new format
    const struct spa_pod *params[2];

649
#if PW_CHECK_VERSION(0, 2, 90)
650
651
    params[0] = reinterpret_cast<spa_pod *>(spa_pod_builder_add_object(&builder,
                SPA_TYPE_OBJECT_ParamBuffers, SPA_PARAM_Buffers,
652
653
654
655
656
                SPA_PARAM_BUFFERS_size, SPA_POD_Int(size),
                SPA_PARAM_BUFFERS_stride, SPA_POD_Int(stride),
                SPA_PARAM_BUFFERS_buffers, SPA_POD_CHOICE_RANGE_Int(8, 1, 32),
                SPA_PARAM_BUFFERS_blocks, SPA_POD_Int(1),
                SPA_PARAM_BUFFERS_align, SPA_POD_Int(16)));
657
658
    params[1] = reinterpret_cast<spa_pod *>(spa_pod_builder_add_object(&builder,
                SPA_TYPE_OBJECT_ParamMeta, SPA_PARAM_Meta,
659
660
661
                SPA_PARAM_META_type, SPA_POD_Id(SPA_META_Header),
                SPA_PARAM_META_size, SPA_POD_Int(sizeof(struct spa_meta_header))));
    pw_stream_update_params(d->pwStream, params, 2);
662
663
664
665
666
667
668
669
670
671
672
673
#else
    params[0] = reinterpret_cast<spa_pod *>(spa_pod_builder_object(&builder,
                d->pwCoreType->param.idBuffers, d->pwCoreType->param_buffers.Buffers,
                ":", d->pwCoreType->param_buffers.size, "i", size,
                ":", d->pwCoreType->param_buffers.stride, "i", stride,
                ":", d->pwCoreType->param_buffers.buffers, "iru", 8, SPA_POD_PROP_MIN_MAX(1, 32),
                ":", d->pwCoreType->param_buffers.align, "i", 16));
    params[1] = reinterpret_cast<spa_pod *>(spa_pod_builder_object(&builder,
                d->pwCoreType->param.idMeta, d->pwCoreType->param_meta.Meta,
                ":", d->pwCoreType->param_meta.type, "I", d->pwCoreType->meta.Header,
                ":", d->pwCoreType->param_meta.size, "i", sizeof(struct spa_meta_header)));
    pw_stream_finish_format(d->pwStream, 0, params, 2);
674
#endif
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
}

/**
 * @brief PWFrameBuffer::Private::onNewBuffer - called when new buffer is available in pipewire stream
 * @param data pointer that you have set in pw_stream_add_listener call's last argument
 * @param id
 */
void PWFrameBuffer::Private::onStreamProcess(void *data)
{
    auto *d = static_cast<PWFrameBuffer::Private *>(data);

    pw_buffer *buf;
    if (!(buf = pw_stream_dequeue_buffer(d->pwStream))) {
        return;
    }

    d->handleFrame(buf);

    pw_stream_queue_buffer(d->pwStream, buf);
}

696
#if PW_CHECK_VERSION(0, 2, 90) && defined(HAVE_LINUX_DMABUF_H)
Aleix Pol Gonzalez's avatar
Aleix Pol Gonzalez committed
697
698
699
700
701
702
703
704
705
706
707
static void syncDmaBuf(int fd, uint64_t start_or_end)
{
    struct dma_buf_sync sync = { 0 };
    sync.flags = start_or_end | DMA_BUF_SYNC_READ;

    while(true) {
        int ret;
        ret = ioctl (fd, DMA_BUF_IOCTL_SYNC, &sync);
        if (ret == -1 && errno == EINTR) {
            continue;
        } else if (ret == -1) {
708
            qCWarning(KRFB_FB_PIPEWIRE) << "Failed to synchronize DMA buffer: " << strerror(errno);
Aleix Pol Gonzalez's avatar
Aleix Pol Gonzalez committed
709
710
711
712
713
714
            break;
        } else {
            break;
        }
    }
}
715
#endif
Aleix Pol Gonzalez's avatar
Aleix Pol Gonzalez committed
716

717
718
719
void PWFrameBuffer::Private::handleFrame(pw_buffer *pwBuffer)
{
    auto *spaBuffer = pwBuffer->buffer;
Aleix Pol Gonzalez's avatar
Aleix Pol Gonzalez committed
720
    void *src = spaBuffer->datas[0].data;
721

722
#if PW_CHECK_VERSION(0, 2, 90)
723
724
    if (!src && spaBuffer->datas->type != SPA_DATA_DmaBuf) {
        qCDebug(KRFB_FB_PIPEWIRE)  << "discarding null buffer";
725
726
        return;
    }
727
#endif
728

Aleix Pol Gonzalez's avatar
Aleix Pol Gonzalez committed
729
730
731
732
    const quint32 maxSize = spaBuffer->datas[0].maxsize;

    std::function<void()> cleanup;
#if PW_CHECK_VERSION(0, 2, 90)
733
#ifdef HAVE_LINUX_DMABUF_H
Aleix Pol Gonzalez's avatar
Aleix Pol Gonzalez committed
734
735
736
737
738
739
    if (spaBuffer->datas->type == SPA_DATA_DmaBuf) {
        const int fd = spaBuffer->datas[0].fd;
        auto map = mmap(
            nullptr, spaBuffer->datas[0].maxsize + spaBuffer->datas[0].mapoffset,
            PROT_READ, MAP_PRIVATE, fd, 0);
        if (map == MAP_FAILED) {
740
            qCWarning(KRFB_FB_PIPEWIRE) << "Failed to mmap the dmabuf: " << strerror(errno);
Aleix Pol Gonzalez's avatar
Aleix Pol Gonzalez committed
741
742
743
744
745
746
747
748
749
750
            return;
        }

        syncDmaBuf(fd, DMA_BUF_SYNC_START);
        src = SPA_MEMBER(map, spaBuffer->datas[0].mapoffset, uint8_t);

        cleanup = [map, spaBuffer, fd] {
            syncDmaBuf(fd, DMA_BUF_SYNC_END);
            munmap(map, spaBuffer->datas[0].maxsize + spaBuffer->datas[0].mapoffset);
        };
751
752
753
    } else
#endif
    if (spaBuffer->datas->type == SPA_DATA_MemFd) {
Aleix Pol Gonzalez's avatar
Aleix Pol Gonzalez committed
754
755
756
757
758
        uint8_t *map = static_cast<uint8_t*>(mmap(
            nullptr, spaBuffer->datas->maxsize + spaBuffer->datas->mapoffset,
            PROT_READ, MAP_PRIVATE, spaBuffer->datas->fd, 0));

        if (map == MAP_FAILED) {
759
            qCWarning(KRFB_FB_PIPEWIRE) << "Failed to mmap the memory: " << strerror(errno);
Aleix Pol Gonzalez's avatar
Aleix Pol Gonzalez committed
760
761
762
763
764
765
766
767
768
769
770
            return;
        }
        src = SPA_MEMBER(map, spaBuffer->datas[0].mapoffset, uint8_t);

        cleanup = [map, spaBuffer] {
            munmap(map, spaBuffer->datas->maxsize + spaBuffer->datas->mapoffset);
        };
    }
#endif

    const qint32 srcStride = spaBuffer->datas[0].chunk->stride;
771
    if (srcStride != q->paddedWidth()) {
772
        qCWarning(KRFB_FB_PIPEWIRE) << "Got buffer with stride different from screen stride" << srcStride << "!=" << q->paddedWidth();
773
774
775
776
777
        return;
    }

    q->tiles.append(QRect(0, 0, q->width(), q->height()));
    std::memcpy(q->fb, src, maxSize);
Aleix Pol Gonzalez's avatar
Aleix Pol Gonzalez committed
778
779
780
781
782
783
784
785
786
787
788
789
    cleanup();

#if PW_CHECK_VERSION(0, 2, 90)
    if (videoFormat->format != SPA_VIDEO_FORMAT_RGB) {
        const QImage::Format format = videoFormat->format == SPA_VIDEO_FORMAT_BGR  ? QImage::Format_BGR888
                                    : videoFormat->format == SPA_VIDEO_FORMAT_RGBx ? QImage::Format_RGBX8888
                                                                                   : QImage::Format_RGB32;

        QImage img((uchar*) q->fb, videoFormat->size.width, videoFormat->size.height, spaBuffer->datas->chunk->stride, format);
        img.convertTo(QImage::Format_RGB888);
    }
#endif
790
791
792
793
794
795
796
}

/**
 * @brief PWFrameBuffer::Private::createReceivingStream - create a stream that will consume Pipewire buffers
 *        and copy the framebuffer to the existing image that we track. The state of the stream and configuration
 *        are later handled by the corresponding listener.
 */
797
pw_stream *PWFrameBuffer::Private::createReceivingStream()
798
799
800
801
802
803
804
{
    spa_rectangle pwMinScreenBounds = SPA_RECTANGLE(1, 1);
    spa_rectangle pwMaxScreenBounds = SPA_RECTANGLE(screenGeometry.width, screenGeometry.height);

    spa_fraction pwFramerateMin = SPA_FRACTION(0, 1);
    spa_fraction pwFramerateMax = SPA_FRACTION(60, 1);

805
806
807
808
809
810
811
#if PW_CHECK_VERSION(0, 2, 90)
    auto stream = pw_stream_new_simple(pw_thread_loop_get_loop(pwMainLoop), "krfb-fb-consume-stream",
                                       pw_properties_new(PW_KEY_MEDIA_TYPE, "Video",
                                                         PW_KEY_MEDIA_CATEGORY, "Capture",
                                                         PW_KEY_MEDIA_ROLE, "Screen",
                                                         nullptr),
                                       &pwStreamEvents, this);
812

813
814
815
816
#else
    auto reuseProps = pw_properties_new("pipewire.client.reuse", "1", nullptr); // null marks end of varargs
    auto stream = pw_stream_new(pwRemote, "krfb-fb-consume-stream", reuseProps);
#endif
817
818
819
820
    uint8_t buffer[1024] = {};
    const spa_pod *params[1];
    auto builder = SPA_POD_BUILDER_INIT(buffer, sizeof(buffer));

821
#if PW_CHECK_VERSION(0, 2, 90)
822
823
    params[0] = reinterpret_cast<spa_pod *>(spa_pod_builder_add_object(&builder,
                SPA_TYPE_OBJECT_Format, SPA_PARAM_EnumFormat,
824
825
                SPA_FORMAT_mediaType, SPA_POD_Id(SPA_MEDIA_TYPE_video),
                SPA_FORMAT_mediaSubtype, SPA_POD_Id(SPA_MEDIA_SUBTYPE_raw),
Aleix Pol Gonzalez's avatar
Aleix Pol Gonzalez committed
826
827
828
829
                SPA_FORMAT_VIDEO_format, SPA_POD_CHOICE_ENUM_Id(6,
                                                    SPA_VIDEO_FORMAT_RGBx, SPA_VIDEO_FORMAT_RGBA,
                                                    SPA_VIDEO_FORMAT_BGRx, SPA_VIDEO_FORMAT_BGRA,
                                                    SPA_VIDEO_FORMAT_RGB, SPA_VIDEO_FORMAT_BGR),
830
831
832
                SPA_FORMAT_VIDEO_size, SPA_POD_CHOICE_RANGE_Rectangle(&pwMaxScreenBounds, &pwMinScreenBounds, &pwMaxScreenBounds),
                SPA_FORMAT_VIDEO_framerate, SPA_POD_Fraction(&pwFramerateMin),
                SPA_FORMAT_VIDEO_maxFramerate, SPA_POD_CHOICE_RANGE_Fraction(&pwFramerateMax, &pwFramerateMin, &pwFramerateMax)));
833
834
835
836
837
838
839
840
841
#else
    params[0] = reinterpret_cast<spa_pod *>(spa_pod_builder_object(&builder,
                pwCoreType->param.idEnumFormat, pwCoreType->spa_format,
                "I", pwType->media_type.video,
                "I", pwType->media_subtype.raw,
                ":", pwType->format_video.format, "I", pwType->video_format.RGBx,
                ":", pwType->format_video.size, "Rru", &pwMaxScreenBounds, SPA_POD_PROP_MIN_MAX(&pwMinScreenBounds, &pwMaxScreenBounds),
                ":", pwType->format_video.framerate, "F", &pwFramerateMin,
                ":", pwType->format_video.max_framerate, "Fru", &pwFramerateMax, 2, &pwFramerateMin, &pwFramerateMax));
842
    pw_stream_add_listener(stream, &streamListener, &pwStreamEvents, this);
843
844
845
#endif

    auto flags = static_cast<pw_stream_flags>(PW_STREAM_FLAG_AUTOCONNECT | PW_STREAM_FLAG_INACTIVE | PW_STREAM_FLAG_MAP_BUFFERS);
846
847
#if PW_CHECK_VERSION(0, 2, 90)
    if (pw_stream_connect(stream, PW_DIRECTION_INPUT, PW_ID_ANY, flags, params, 1) != 0) {
848
#else
849
    if (pw_stream_connect(stream, PW_DIRECTION_INPUT, nullptr, flags, params, 1) != 0) {
850
#endif
851
        qCWarning(KRFB_FB_PIPEWIRE) << "Could not connect receiving stream";
852
853
        isValid = false;
    }
854
855

    return stream;
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
}

PWFrameBuffer::Private::~Private()
{
    if (pwMainLoop) {
        pw_thread_loop_stop(pwMainLoop);
    }

#if !PW_CHECK_VERSION(0, 2, 9)
    if (pwType) {
        delete pwType;
    }
#endif

    if (pwStream) {
        pw_stream_destroy(pwStream);
    }

874
#if !PW_CHECK_VERSION(0, 2, 90)
875
876
877
    if (pwRemote) {
        pw_remote_destroy(pwRemote);
    }
878
879
880
881
882
883
#endif

#if PW_CHECK_VERSION(0, 2, 90)
    if (pwCore) {
        pw_core_disconnect(pwCore);
    }
884

885
886
887
888
889
    if (pwContext) {
        pw_context_destroy(pwContext);
    }
#else
    if (pwCore) {
890
        pw_core_destroy(pwCore);
891
892
    }
#endif
893
894
895
896
897

    if (pwMainLoop) {
        pw_thread_loop_destroy(pwMainLoop);
    }

898
#if !PW_CHECK_VERSION(0, 2, 90)
899
    if (pwLoop) {
900
        pw_loop_leave(pwLoop);
901
902
        pw_loop_destroy(pwLoop);
    }
903
#endif
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
}

PWFrameBuffer::PWFrameBuffer(WId winid, QObject *parent)
    : FrameBuffer (winid, parent),
      d(new Private(this))
{
    // D-Bus is most important in init chain, no toys for us if something is wrong with XDP
    // PipeWire connectivity is initialized after D-Bus session is started
    d->initDbus();

    // FIXME: for now use some initial size, later on we will reallocate this with the actual size we get from portal
    d->screenGeometry.width = 800;
    d->screenGeometry.height = 600;
    fb = nullptr;
}

PWFrameBuffer::~PWFrameBuffer()
{
    free(fb);
    fb = nullptr;
}

int PWFrameBuffer::depth()
{
    return 32;
}

int PWFrameBuffer::height()
{
    return static_cast<qint32>(d->screenGeometry.height);
}

int PWFrameBuffer::width()
{
    return static_cast<qint32>(d->screenGeometry.width);
}

int PWFrameBuffer::paddedWidth()
{
    return width() * 4;
}

void PWFrameBuffer::getServerFormat(rfbPixelFormat &format)
{
    format.bitsPerPixel = 32;
    format.depth = 32;
    format.trueColour = true;
    format.bigEndian = false;
}

void PWFrameBuffer::startMonitor()
{

}

void PWFrameBuffer::stopMonitor()
{

}

QVariant PWFrameBuffer::customProperty(const QString &property) const
{
    if (property == QLatin1String("stream_node_id")) {
        return QVariant::fromValue<uint>(d->pwStreamNodeId);
    } if (property == QLatin1String("session_handle")) {
        return QVariant::fromValue<QDBusObjectPath>(d->sessionPath);
    }

    return FrameBuffer::customProperty(property);
}

bool PWFrameBuffer::isValid() const
{
    return d->isValid;
}