-
-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Expand file tree
/
Copy pathpipewire.cpp
More file actions
1341 lines (1181 loc) · 54.3 KB
/
Copy pathpipewire.cpp
File metadata and controls
1341 lines (1181 loc) · 54.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
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
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @file src/platform/linux/pipewire.cpp
* @brief Shared classes for pipewire-based capture methods.
*/
// standard includes
#include <fstream>
#include <utility>
// lib includes
#include <gio/gio.h>
#include <gio/gunixfdlist.h>
#include <libdrm/drm_fourcc.h>
#include <pipewire/pipewire.h>
#include <spa/param/video/format-utils.h>
#include <spa/param/video/type-info.h>
#include <spa/pod/builder.h>
// local includes
#include "cuda.h"
#include "graphics.h"
#include "src/main.h"
#include "src/platform/common.h"
#include "src/video.h"
#include "vaapi.h"
#include "vulkan_encode.h"
#include "wayland.h"
#if !PW_CHECK_VERSION(1, 6, 0)
constexpr int SPA_VIDEO_TRANSFER_SMPTE2084 = 14; ///< Protocol or platform constant for spa video transfer smpte2084.
#endif
#if PW_CHECK_VERSION(0, 3, 75)
// Runtime linked library version checks are available. Check for pipewire 0.3.64 which documented object serial support and deprecated node id.
const bool SUNSHINE_USE_PIPEWIRE_OBJECT_SERIAL = pw_check_library_version(0, 3, 64);
#elifdef PW_KEY_TARGET_OBJECT
// Runtime linked library version checks are UNAVAILABLE but necessary PW_KEY_TARGET_OBJECT for object serial support is available.
constexpr bool SUNSHINE_USE_PIPEWIRE_OBJECT_SERIAL = true;
#else
// Pipewire object serials are unsupported without PW_KEY_TARGET_OBJECT (we define it here so compilation won't break but don't use it).
constexpr bool SUNSHINE_USE_PIPEWIRE_OBJECT_SERIAL = false; ///< Whether PipeWire object serials should be used for matching.
/**
* @def PW_KEY_TARGET_OBJECT
* @brief Macro for PW KEY TARGET OBJECT.
*/
#define PW_KEY_TARGET_OBJECT "target.object"
#endif
namespace {
// Buffer and limit constants
constexpr int SPA_POD_BUFFER_SIZE = 4096;
constexpr int MAX_PARAMS = 200;
constexpr int MAX_DMABUF_FORMATS = 200;
constexpr int MAX_DMABUF_MODIFIERS = 200;
} // namespace
using namespace std::literals;
namespace pipewire {
/**
* @brief PipeWire SPA format mapped to Sunshine pixel format.
*/
struct format_map_t {
uint64_t fourcc; ///< DRM fourcc pixel format.
int32_t pw_format; ///< Matching PipeWire SPA video format.
};
static constexpr std::array<format_map_t, 7> format_map = {{
{DRM_FORMAT_XBGR2101010, SPA_VIDEO_FORMAT_xBGR_210LE},
{DRM_FORMAT_BGRA1010102, SPA_VIDEO_FORMAT_ARGB_210LE},
{DRM_FORMAT_RGBA1010102, SPA_VIDEO_FORMAT_ABGR_210LE},
{DRM_FORMAT_ABGR2101010, SPA_VIDEO_FORMAT_RGBA_102LE},
{DRM_FORMAT_ARGB2101010, SPA_VIDEO_FORMAT_BGRA_102LE},
{DRM_FORMAT_ARGB8888, SPA_VIDEO_FORMAT_BGRA},
{DRM_FORMAT_XRGB8888, SPA_VIDEO_FORMAT_BGRx},
}};
/**
* @brief PipeWire capture state shared with callback threads.
*/
struct shared_state_t {
std::atomic<int> negotiated_width {0}; ///< Width negotiated with PipeWire for the stream.
std::atomic<int> negotiated_height {0}; ///< Height negotiated with PipeWire for the stream.
std::atomic<int> color_primaries {0}; ///< PipeWire color-primaries metadata for the stream.
std::atomic<int> transfer_function {0}; ///< PipeWire transfer-function metadata for the stream.
std::atomic<bool> stream_dead {false}; ///< Whether the PipeWire stream has been destroyed.
pw_stream_state previous_state; ///< Previous PipeWire stream state reported by callbacks.
pw_stream_state current_state; ///< Current PipeWire stream state reported by callbacks.
std::string err_msg; ///< Last PipeWire error message reported by the stream.
};
/**
* @brief Safely returns retained PipeWire buffers from Sunshine's conversion
* thread while preventing use after stream teardown.
*/
struct buffer_release_state_t {
/**
* @brief Make buffer releases target the active PipeWire stream.
*
* @param new_loop PipeWire thread loop that owns the stream.
* @param new_stream PipeWire stream that owns captured buffers.
*/
void activate(struct pw_thread_loop *new_loop, struct pw_stream *new_stream) {
std::scoped_lock lock(mutex);
loop = new_loop;
stream = new_stream;
}
/**
* @brief Ignore future buffer releases before stream teardown.
*/
void deactivate() {
std::scoped_lock lock(mutex);
loop = nullptr;
stream = nullptr;
}
/**
* @brief Return a retained buffer to the active PipeWire stream.
*
* @param buffer PipeWire buffer whose capture contents are no longer used.
*/
void release(struct pw_buffer *buffer) {
std::scoped_lock lock(mutex);
if (!loop || !stream || !buffer) {
return;
}
pw_thread_loop_lock(loop);
pw_stream_queue_buffer(stream, buffer);
pw_thread_loop_unlock(loop);
}
std::mutex mutex; ///< Protects stream lifetime and serialized buffer release.
struct pw_thread_loop *loop = nullptr; ///< Thread loop that owns `stream`.
struct pw_stream *stream = nullptr; ///< Active stream that owns retained buffers.
};
/**
* @brief PipeWire stream handle, format, and shared state pointer.
*/
struct stream_data_t {
struct pw_stream *stream; ///< PipeWire stream handle used for screencast frames.
struct spa_hook stream_listener; ///< Hook registering callbacks on the PipeWire stream.
struct spa_video_info format; ///< Negotiated PipeWire video format.
struct pw_buffer *current_buffer; ///< PipeWire buffer currently exposed to the capture thread.
uint64_t drm_format; ///< DRM format.
std::shared_ptr<shared_state_t> shared; ///< State shared between PipeWire callbacks and the capture backend.
std::mutex frame_mutex; ///< Synchronizes access to the current PipeWire frame.
std::condition_variable frame_cv; ///< Signals arrival or release of a PipeWire frame.
size_t local_stride = 0; ///< Local stride.
bool frame_ready = false; ///< Whether a PipeWire frame is ready to consume.
// Two distinct memory pools
std::vector<uint8_t> buffer_a; ///< First staging buffer used for CPU-copy PipeWire frames.
std::vector<uint8_t> buffer_b; ///< Second staging buffer used for CPU-copy PipeWire frames.
// Points to the buffer currently owned by fill_img
std::vector<uint8_t> *front_buffer; ///< Staging buffer currently readable by `fill_img`.
// Points to the buffer currently being written by on_process
std::vector<uint8_t> *back_buffer; ///< Staging buffer currently writable by PipeWire callbacks.
stream_data_t():
front_buffer(&buffer_a),
back_buffer(&buffer_b) {}
};
/**
* @brief DMA-BUF format and modifier list advertised by PipeWire.
*/
struct dmabuf_format_info_t {
int32_t format; ///< PipeWire SPA video format being advertised.
uint64_t *modifiers; ///< DRM format modifiers supported for the format.
int n_modifiers; ///< Number of entries in `modifiers`.
};
/**
* @brief Pipewire image assembled for encoding.
*/
struct img_descriptor_t: public egl::img_descriptor_t {
~img_descriptor_t() override {
if (data) {
delete[] data;
data = nullptr;
}
}
};
/**
* @brief PipeWire core, context, and stream setup used for screencast capture.
*/
class pipewire_t {
public:
pipewire_t():
loop(pw_thread_loop_new("Pipewire thread", nullptr)) {
BOOST_LOG(debug) << "[pipewire] Start PW thread loop"sv;
pw_thread_loop_start(loop);
}
~pipewire_t() {
BOOST_LOG(debug) << "[pipewire] Destroying pipewire_t"sv;
buffer_release_state->deactivate();
pw_thread_loop_lock(loop);
// Lock the frame mutex to stop fill_img
BOOST_LOG(debug) << "[pipewire] Stop fill_img"sv;
{
std::scoped_lock lock(stream_data.frame_mutex);
stream_data.frame_ready = false;
stream_data.current_buffer = nullptr;
}
// Release pipewire stream
if (stream_data.stream) {
BOOST_LOG(debug) << "[pipewire] Disconnect stream"sv;
pw_stream_disconnect(stream_data.stream);
BOOST_LOG(debug) << "[pipewire] Destroy stream"sv;
pw_stream_destroy(stream_data.stream);
stream_data.stream = nullptr;
}
// Release pipewire core
if (core) {
BOOST_LOG(debug) << "[pipewire] Disconnect PW core"sv;
pw_core_disconnect(core);
core = nullptr;
}
// Release pipewire context
if (context) {
BOOST_LOG(debug) << "[pipewire] Destroy PW context"sv;
pw_context_destroy(context);
context = nullptr;
}
// Release pipewire file descriptor
if (fd >= 0) {
BOOST_LOG(debug) << "[pipewire] Close pipewire_fd"sv;
close(fd);
}
// Release pipewire thread loop
BOOST_LOG(debug) << "[pipewire] Stop PW thread loop"sv;
pw_thread_loop_unlock(loop);
pw_thread_loop_stop(loop);
BOOST_LOG(debug) << "[pipewire] Destroy PW thread loop"sv;
pw_thread_loop_destroy(loop);
}
/**
* @brief Return the mutex protecting PipeWire frame state.
*
* @return Mutex used by producer and capture threads.
*/
std::mutex &frame_mutex() {
return stream_data.frame_mutex;
}
/**
* @brief Return the condition variable signaled when frame state changes.
*
* @return Condition variable used to wait for frames or shutdown.
*/
std::condition_variable &frame_cv() {
return stream_data.frame_cv;
}
/**
* @brief Check whether frame ready.
*
* @return True when PipeWire has delivered a frame ready for capture.
*/
bool is_frame_ready() const {
return stream_data.frame_ready;
}
/**
* @brief Set frame ready.
*
* @param ready Whether the PipeWire frame is ready for capture.
*/
void set_frame_ready(bool ready) {
stream_data.frame_ready = ready;
}
/**
* @brief Initialize PipeWire core objects and optional stream negotiation.
*
* @param stream_fd Stream fd.
* @param stream_node Stream node.
* @param stream_object_serial Stream object serial.
* @param shared_state Shared state.
* @return 0 on success; nonzero or negative platform status on failure.
*/
int init(const int stream_fd, const uint32_t stream_node, const uint64_t stream_object_serial, std::shared_ptr<shared_state_t> shared_state) {
fd = stream_fd;
node = stream_node;
object_serial = stream_object_serial;
stream_data.shared = std::move(shared_state);
pw_thread_loop_lock(loop);
BOOST_LOG(debug) << "[pipewire] Setup PW context"sv;
context = pw_context_new(pw_thread_loop_get_loop(loop), nullptr, 0);
if (context) {
BOOST_LOG(debug) << "[pipewire] Connect PW context to fd"sv;
if (fd >= 0) {
core = pw_context_connect_fd(context, fd, nullptr, 0);
} else {
core = pw_context_connect(context, nullptr, 0);
}
if (core) {
pw_core_add_listener(core, &core_listener, &core_events, nullptr);
} else {
BOOST_LOG(debug) << "[pipewire] Failed to connect to PW core. Error: "sv << errno << "(" << strerror(errno) << ")"sv;
return -1;
}
} else {
BOOST_LOG(debug) << "[pipewire] Failed to setup PW context. Error: "sv << errno << "(" << strerror(errno) << ")"sv;
return -1;
}
pw_thread_loop_unlock(loop);
return 0;
}
/**
* @brief Create the PipeWire stream if it is not already active.
*
* @param mem_type Mem type.
* @param width Frame or display width in pixels.
* @param height Frame or display height in pixels.
* @param refresh_rate Refresh rate.
* @param dmabuf_infos Dmabuf infos.
* @param n_dmabuf_infos N dmabuf infos.
* @param display_is_nvidia Display is nvidia.
* @return 0 when the PipeWire stream is configured; nonzero on negotiation failure.
*/
int ensure_stream(const platf::mem_type_e mem_type, const uint32_t width, const uint32_t height, const uint32_t refresh_rate, const struct dmabuf_format_info_t *dmabuf_infos, const int n_dmabuf_infos, const bool display_is_nvidia) {
pw_thread_loop_lock(loop);
int result = 0;
if (!stream_data.stream) {
if (!core) {
BOOST_LOG(debug) << "[pipewire] PW core not available. Cannot ensure stream."sv;
pw_thread_loop_unlock(loop);
return -1;
}
struct pw_properties *props = pw_properties_new(PW_KEY_MEDIA_TYPE, "Video", PW_KEY_MEDIA_CATEGORY, "Capture", PW_KEY_MEDIA_ROLE, "Screen", nullptr);
BOOST_LOG(debug) << "[pipewire] Create PW stream"sv;
stream_data.stream = pw_stream_new(core, "Sunshine Video Capture", props);
buffer_release_state->activate(loop, stream_data.stream);
pw_stream_add_listener(stream_data.stream, &stream_data.stream_listener, &stream_events, &stream_data);
std::array<uint8_t, SPA_POD_BUFFER_SIZE> buffer;
struct spa_pod_builder pod_builder = SPA_POD_BUILDER_INIT(buffer.data(), buffer.size());
int n_params = 0;
std::array<const struct spa_pod *, MAX_PARAMS> params;
// Add preferred parameters for DMA-BUF with modifiers
// Use DMA-BUF for VAAPI, or for CUDA when the display GPU is NVIDIA (pure NVIDIA system).
// On hybrid GPU systems (Intel+NVIDIA), DMA-BUFs come from the Intel GPU and cannot
// be imported into CUDA, so we fall back to memory buffers in that case.
bool use_dmabuf = n_dmabuf_infos > 0 && (mem_type == platf::mem_type_e::vaapi ||
mem_type == platf::mem_type_e::vulkan ||
(mem_type == platf::mem_type_e::cuda && display_is_nvidia));
retain_dmabuf_for_cuda_ = use_dmabuf && mem_type == platf::mem_type_e::cuda;
if (use_dmabuf) {
for (int i = 0; i < n_dmabuf_infos; i++) {
auto format_param = build_format_parameter(&pod_builder, width, height, refresh_rate, dmabuf_infos[i].format, dmabuf_infos[i].modifiers, dmabuf_infos[i].n_modifiers);
params[n_params] = format_param;
n_params++;
}
}
// Add fallback for memptr
for (const auto &fmt : format_map) {
auto format_param = build_format_parameter(&pod_builder, width, height, refresh_rate, fmt.pw_format, nullptr, 0);
params[n_params] = format_param;
n_params++;
}
// Connection via pipewire object serial if it is supported and the serial is valid (lower 32-bits != SPA_ID_INVALID, see also PW_KEY_OBJECT_SERIAL docs)
if (SUNSHINE_USE_PIPEWIRE_OBJECT_SERIAL && (object_serial & SPA_ID_INVALID) != SPA_ID_INVALID) {
pw_properties_setf(props, PW_KEY_TARGET_OBJECT, "%" PRIu64, object_serial);
BOOST_LOG(debug) << "[pipewire] Connect PW stream - fd: "sv << fd << " object serial: "sv << object_serial;
result = pw_stream_connect(stream_data.stream, PW_DIRECTION_INPUT, PW_ID_ANY, (enum pw_stream_flags)(PW_STREAM_FLAG_AUTOCONNECT | PW_STREAM_FLAG_MAP_BUFFERS), params.data(), n_params);
if (result < 0) {
// Unset object serial for retry with node id
pw_properties_set(props, PW_KEY_TARGET_OBJECT, nullptr);
}
} else {
result = -1; // Mark failed so we try to connect via node id
}
// Connection via legacy (and deprecated) pipewire node id
if (result < 0) {
BOOST_LOG(debug) << "[pipewire] Connect PW stream - fd: "sv << fd << " node: "sv << node;
result = pw_stream_connect(stream_data.stream, PW_DIRECTION_INPUT, node, (enum pw_stream_flags)(PW_STREAM_FLAG_AUTOCONNECT | PW_STREAM_FLAG_MAP_BUFFERS), params.data(), n_params);
}
}
pw_thread_loop_unlock(loop);
return result;
}
/**
* @brief Close img fds.
*
* @param img_descriptor Image descriptor whose duplicated DMA-BUF fds are closed.
*/
static void close_img_fds(egl::img_descriptor_t *img_descriptor) {
for (int &fd : img_descriptor->sd.fds) {
if (fd >= 0) {
close(fd);
fd = -1;
}
}
}
/**
* @brief Copy PipeWire metadata into the Sunshine image descriptor.
*
* @param img_descriptor Image descriptor receiving timestamps, sequence, and damage flags.
* @param buf Raw byte buffer used for serialization.
*/
static void fill_img_metadata(egl::img_descriptor_t *img_descriptor, struct spa_buffer *buf) {
img_descriptor->frame_timestamp = std::chrono::steady_clock::now();
struct spa_meta_header *h = static_cast<struct spa_meta_header *>(
spa_buffer_find_meta_data(buf, SPA_META_Header, sizeof(*h))
);
if (h) {
img_descriptor->seq = h->seq;
img_descriptor->pts = h->pts;
}
if (buf->n_datas > 0) {
img_descriptor->pw_flags = buf->datas[0].chunk->flags;
}
struct spa_meta_region *damage = static_cast<struct spa_meta_region *>(
spa_buffer_find_meta_data(buf, SPA_META_VideoDamage, sizeof(*damage))
);
img_descriptor->pw_damage = (damage && damage->region.size.width > 0 && damage->region.size.height > 0) ? std::optional<bool>(true) : std::nullopt;
}
/**
* @brief Populate a Sunshine image descriptor from PipeWire DMA-BUF planes.
*
* @param img_descriptor Image descriptor receiving duplicated fds and plane layout.
* @param buf Raw byte buffer used for serialization.
* @param d PipeWire listener data passed to the callback.
*/
static void fill_img_dmabuf(egl::img_descriptor_t *img_descriptor, struct spa_buffer *buf, const stream_data_t &d) {
img_descriptor->sd.width = d.format.info.raw.size.width;
img_descriptor->sd.height = d.format.info.raw.size.height;
img_descriptor->sd.modifier = d.format.info.raw.modifier;
img_descriptor->sd.fourcc = d.drm_format;
for (int i = 0; i < MIN(buf->n_datas, 4); i++) {
img_descriptor->sd.fds[i] = dup(buf->datas[i].fd);
img_descriptor->sd.pitches[i] = buf->datas[i].chunk->stride;
img_descriptor->sd.offsets[i] = buf->datas[i].chunk->offset;
}
}
/**
* @brief Copy the latest PipeWire frame into Sunshine's image buffer.
*
* @param img Image or frame object to read from or populate.
*/
void fill_img(platf::img_t *img) {
pw_thread_loop_lock(loop);
std::scoped_lock lock(stream_data.frame_mutex);
if (stream_data.shared && stream_data.shared->stream_dead.load()) {
img->data = nullptr;
close_img_fds(static_cast<egl::img_descriptor_t *>(img));
pw_thread_loop_unlock(loop);
return;
}
if (!stream_data.current_buffer) {
img->data = nullptr;
pw_thread_loop_unlock(loop);
return;
}
struct spa_buffer *buf = stream_data.current_buffer->buffer;
if (buf->datas[0].chunk->size != 0) {
auto *img_descriptor = static_cast<egl::img_descriptor_t *>(img);
fill_img_metadata(img_descriptor, buf);
if (buf->datas[0].type == SPA_DATA_DmaBuf) {
fill_img_dmabuf(img_descriptor, buf, stream_data);
if (retain_dmabuf_for_cuda_) {
retain_current_buffer_until_conversion(img_descriptor);
}
} else {
img->data = stream_data.front_buffer->data();
img->row_pitch = stream_data.local_stride;
}
}
pw_thread_loop_unlock(loop);
}
/**
* @brief Set negotiate maxframerate.
*
* @param negotiate_maxframerate Negotiate maxframerate.
*/
void set_negotiate_maxframerate(bool negotiate_maxframerate) {
negotiate_maxframerate_ = negotiate_maxframerate;
}
private:
/**
* @brief Transfer the current PipeWire buffer to an image until conversion completes.
*
* @param img_descriptor Captured image that will release the buffer after conversion.
*/
void retain_current_buffer_until_conversion(egl::img_descriptor_t *img_descriptor) {
const auto retained_buffer = std::exchange(stream_data.current_buffer, nullptr);
const std::weak_ptr<buffer_release_state_t> weak_release_state = buffer_release_state;
img_descriptor->capture_buffer_consumed_cb = [weak_release_state, retained_buffer]() {
const auto release_state = weak_release_state.lock();
if (!release_state) {
return;
}
release_state->release(retained_buffer);
};
}
struct pw_thread_loop *loop;
struct pw_context *context;
struct pw_core *core;
struct spa_hook core_listener;
struct stream_data_t stream_data;
std::shared_ptr<buffer_release_state_t> buffer_release_state = std::make_shared<buffer_release_state_t>();
int fd;
uint32_t node;
uint64_t object_serial;
bool negotiate_maxframerate_ = true;
bool retain_dmabuf_for_cuda_ = false; ///< Retain producer buffers until GL/CUDA conversion consumes them.
struct spa_pod *build_format_parameter(struct spa_pod_builder *b, uint32_t width, uint32_t height, uint32_t refresh_rate, int32_t format, uint64_t *modifiers, int n_modifiers) {
struct spa_pod_frame object_frame;
struct spa_pod_frame modifier_frame;
std::array<struct spa_rectangle, 3> sizes;
std::array<struct spa_fraction, 3> framerates;
sizes[0] = SPA_RECTANGLE(width, height); // Preferred
sizes[1] = SPA_RECTANGLE(1, 1);
sizes[2] = SPA_RECTANGLE(8192, 4096);
framerates[0] = SPA_FRACTION(0, 1); // default; we only want variable rate, thus bypassing compositor pacing
framerates[1] = SPA_FRACTION(0, 1); // min
framerates[2] = SPA_FRACTION(0, 1); // max
spa_pod_builder_push_object(b, &object_frame, SPA_TYPE_OBJECT_Format, SPA_PARAM_EnumFormat);
spa_pod_builder_add(b, SPA_FORMAT_mediaType, SPA_POD_Id(SPA_MEDIA_TYPE_video), 0);
spa_pod_builder_add(b, SPA_FORMAT_mediaSubtype, SPA_POD_Id(SPA_MEDIA_SUBTYPE_raw), 0);
spa_pod_builder_add(b, SPA_FORMAT_VIDEO_format, SPA_POD_Id(format), 0);
spa_pod_builder_add(b, SPA_FORMAT_VIDEO_size, SPA_POD_CHOICE_RANGE_Rectangle(&sizes[0], &sizes[1], &sizes[2]), 0);
spa_pod_builder_add(b, SPA_FORMAT_VIDEO_framerate, SPA_POD_Fraction(&framerates[0]), 0);
if (negotiate_maxframerate_) {
spa_pod_builder_add(b, SPA_FORMAT_VIDEO_maxFramerate, SPA_POD_CHOICE_RANGE_Fraction(&framerates[0], &framerates[1], &framerates[2]), 0);
}
if (format == SPA_VIDEO_FORMAT_xBGR_210LE) {
spa_pod_builder_add(b, SPA_FORMAT_VIDEO_colorPrimaries, SPA_POD_Id(SPA_VIDEO_COLOR_PRIMARIES_BT2020), 0);
spa_pod_builder_add(b, SPA_FORMAT_VIDEO_transferFunction, SPA_POD_Id(SPA_VIDEO_TRANSFER_SMPTE2084), 0);
}
if (n_modifiers) {
spa_pod_builder_prop(b, SPA_FORMAT_VIDEO_modifier, SPA_POD_PROP_FLAG_MANDATORY | SPA_POD_PROP_FLAG_DONT_FIXATE);
spa_pod_builder_push_choice(b, &modifier_frame, SPA_CHOICE_Enum, 0);
// Preferred value, we pick the first modifier be the preferred one
spa_pod_builder_long(b, modifiers[0]);
for (uint32_t i = 0; i < n_modifiers; i++) {
spa_pod_builder_long(b, modifiers[i]);
}
spa_pod_builder_pop(b, &modifier_frame);
}
return static_cast<struct spa_pod *>(spa_pod_builder_pop(b, &object_frame));
}
static void on_core_info_cb([[maybe_unused]] void *user_data, const struct pw_core_info *pw_info) {
BOOST_LOG(info) << "[pipewire] Connected to pipewire version "sv << pw_info->version;
}
static void on_core_error_cb([[maybe_unused]] void *user_data, const uint32_t id, const int seq, [[maybe_unused]] int res, const char *message) {
BOOST_LOG(info) << "[pipewire] Pipewire Error, id:"sv << id << " seq:"sv << seq << " message: "sv << message;
}
constexpr static const struct pw_core_events core_events = {
.version = PW_VERSION_CORE_EVENTS,
.info = on_core_info_cb,
.error = on_core_error_cb,
};
static void on_stream_state_changed(void *user_data, enum pw_stream_state old, enum pw_stream_state state, const char *err_msg) {
if (err_msg != nullptr) {
BOOST_LOG(info) << "[pipewire] PipeWire stream error '" << err_msg << "' on state: " << pw_stream_state_as_string(old)
<< " -> " << pw_stream_state_as_string(state);
} else {
BOOST_LOG(info) << "[pipewire] PipeWire stream state: " << pw_stream_state_as_string(old)
<< " -> " << pw_stream_state_as_string(state);
}
auto *d = static_cast<stream_data_t *>(user_data);
switch (state) {
case PW_STREAM_STATE_PAUSED:
if (d->shared && old == PW_STREAM_STATE_STREAMING) {
{
std::scoped_lock lock(d->frame_mutex);
d->frame_ready = false;
d->current_buffer = nullptr;
d->shared->stream_dead.store(true);
d->shared->current_state = state;
d->shared->previous_state = old;
d->shared->err_msg = "";
}
d->frame_cv.notify_all();
}
break;
case PW_STREAM_STATE_ERROR:
{
std::scoped_lock lock(d->frame_mutex);
d->shared->current_state = state;
d->shared->previous_state = old;
d->shared->err_msg = std::string(err_msg);
}
[[fallthrough]];
case PW_STREAM_STATE_UNCONNECTED:
if (d->shared) {
d->shared->stream_dead.store(true);
d->frame_cv.notify_all();
}
break;
default:
break;
}
}
static void on_process(void *user_data) {
const auto d = static_cast<struct stream_data_t *>(user_data);
struct pw_buffer *b = nullptr;
// 1. Drain the queue: Always grab the most recent buffer
while (struct pw_buffer *aux = pw_stream_dequeue_buffer(d->stream)) {
if (b) {
pw_stream_queue_buffer(d->stream, b); // Return the older, unused buffer
}
b = aux;
}
if (!b) {
return;
}
// 2. Fast Path: DMA-BUF
if (b->buffer->datas[0].type == SPA_DATA_DmaBuf) {
std::scoped_lock lock(d->frame_mutex);
if (d->current_buffer) {
pw_stream_queue_buffer(d->stream, d->current_buffer);
}
d->current_buffer = b;
d->frame_ready = true;
}
// 3. Optimized Path: Software/MemPtr
else if (b->buffer->datas[0].data != nullptr) {
size_t size = b->buffer->datas[0].chunk->size;
// Perform the copy to the BACK buffer while NOT holding the lock
if (d->back_buffer->size() < size) {
d->back_buffer->resize(size);
}
std::memcpy(d->back_buffer->data(), b->buffer->datas[0].data, size);
{
// Lock only for the pointer swap and state update
std::scoped_lock lock(d->frame_mutex);
std::swap(d->front_buffer, d->back_buffer);
d->local_stride = b->buffer->datas[0].chunk->stride;
d->frame_ready = true;
d->current_buffer = b;
}
// Release the PW buffer immediately after copy
pw_stream_queue_buffer(d->stream, b);
}
d->frame_cv.notify_one();
}
static void on_param_changed(void *user_data, uint32_t id, const struct spa_pod *param) {
const auto d = static_cast<struct stream_data_t *>(user_data);
d->current_buffer = nullptr;
if (param == nullptr || id != SPA_PARAM_Format) {
return;
}
if (spa_format_parse(param, &d->format.media_type, &d->format.media_subtype) < 0) {
return;
}
if (d->format.media_type != SPA_MEDIA_TYPE_video || d->format.media_subtype != SPA_MEDIA_SUBTYPE_raw) {
return;
}
if (spa_format_video_raw_parse(param, &d->format.info.raw) < 0) {
return;
}
BOOST_LOG(info) << "[pipewire] Video format: "sv << d->format.info.raw.format;
BOOST_LOG(info) << "[pipewire] Size: "sv << d->format.info.raw.size.width << "x"sv << d->format.info.raw.size.height;
BOOST_LOG(info) << "[pipewire] Color primaries: "sv << d->format.info.raw.color_primaries;
BOOST_LOG(info) << "[pipewire] Transfer function: "sv << d->format.info.raw.transfer_function;
if (d->format.info.raw.max_framerate.num == 0 && d->format.info.raw.max_framerate.denom == 1) {
BOOST_LOG(info) << "[pipewire] Framerate (from compositor): 0/1 (variable rate capture)";
} else {
BOOST_LOG(info) << "[pipewire] Framerate (from compositor): "sv << d->format.info.raw.framerate.num << "/"sv << d->format.info.raw.framerate.denom;
BOOST_LOG(info) << "[pipewire] Framerate (from compositor, max): "sv << d->format.info.raw.max_framerate.num << "/"sv << d->format.info.raw.max_framerate.denom;
}
int physical_w = d->format.info.raw.size.width;
int physical_h = d->format.info.raw.size.height;
if (d->shared) {
int old_w = d->shared->negotiated_width.load();
int old_h = d->shared->negotiated_height.load();
int old_color_primaries = d->shared->color_primaries.load();
int old_transfer_function = d->shared->transfer_function.load();
if (physical_w != old_w || physical_h != old_h) {
d->shared->negotiated_width.store(physical_w);
d->shared->negotiated_height.store(physical_h);
}
if (d->format.info.raw.color_primaries != old_color_primaries || d->format.info.raw.transfer_function != old_transfer_function) {
d->shared->color_primaries.store(d->format.info.raw.color_primaries);
d->shared->transfer_function.store(d->format.info.raw.transfer_function);
}
}
uint64_t drm_format = 0;
for (const auto &fmt : format_map) {
if (fmt.pw_format == d->format.info.raw.format) {
drm_format = fmt.fourcc;
}
}
d->drm_format = drm_format;
uint32_t buffer_types = 0;
if (spa_pod_find_prop(param, nullptr, SPA_FORMAT_VIDEO_modifier) != nullptr && d->drm_format) {
BOOST_LOG(info) << "[pipewire] using DMA-BUF buffers"sv;
buffer_types |= 1 << SPA_DATA_DmaBuf;
} else {
BOOST_LOG(info) << "[pipewire] using memory buffers"sv;
buffer_types |= 1 << SPA_DATA_MemPtr;
}
// Ack the buffer type and metadata
std::array<uint8_t, SPA_POD_BUFFER_SIZE> buffer;
std::array<const struct spa_pod *, 3> params;
int n_params = 0;
struct spa_pod_builder pod_builder = SPA_POD_BUILDER_INIT(buffer.data(), buffer.size());
auto buffer_param = static_cast<const struct spa_pod *>(spa_pod_builder_add_object(&pod_builder, SPA_TYPE_OBJECT_ParamBuffers, SPA_PARAM_Buffers, SPA_PARAM_BUFFERS_dataType, SPA_POD_Int(buffer_types)));
params[n_params] = buffer_param;
n_params++;
auto meta_param = static_cast<const struct spa_pod *>(spa_pod_builder_add_object(&pod_builder, SPA_TYPE_OBJECT_ParamMeta, SPA_PARAM_Meta, SPA_PARAM_META_type, SPA_POD_Id(SPA_META_Header), SPA_PARAM_META_size, SPA_POD_Int(sizeof(struct spa_meta_header))));
params[n_params] = meta_param;
n_params++;
int videoDamageRegionCount = 16;
auto damage_param = static_cast<const struct spa_pod *>(spa_pod_builder_add_object(&pod_builder, SPA_TYPE_OBJECT_ParamMeta, SPA_PARAM_Meta, SPA_PARAM_META_type, SPA_POD_Id(SPA_META_VideoDamage), SPA_PARAM_META_size, SPA_POD_CHOICE_RANGE_Int(sizeof(struct spa_meta_region) * videoDamageRegionCount, sizeof(struct spa_meta_region) * 1, sizeof(struct spa_meta_region) * videoDamageRegionCount)));
params[n_params] = damage_param;
n_params++;
pw_stream_update_params(d->stream, params.data(), n_params);
}
constexpr static const struct pw_stream_events stream_events = {
.version = PW_VERSION_STREAM_EVENTS,
.state_changed = on_stream_state_changed,
.param_changed = on_param_changed,
.process = on_process,
};
};
/**
* @brief Display capture backend that consumes frames from a PipeWire stream.
*/
class pipewire_display_t: public platf::display_t {
public:
/**
* @brief Initialize pipewire and check hwdevice type.
*
* @param hwdevice_type Hardware device type requested for capture or encode.
* @return True when PipeWire is initialized and the hardware device type is supported.
*/
static bool init_pipewire_and_check_hwdevice_type(platf::mem_type_e hwdevice_type) {
// Initialize pipewire to load necessary modules
pw_init(nullptr, nullptr);
// Check if we have a matching hwdevice_type
switch (hwdevice_type) {
using enum platf::mem_type_e;
case system:
case vaapi:
case cuda:
case vulkan:
return true;
default:
return false;
}
}
/**
* @brief Configure the pipewire stream
* @param display_name provide a stream for this display_name
* @param out_pipewire_fd set to the pipewire fd for the stream during function call (or -1 for using the local context)
* @param out_pipewire_node set to the pipewire node of the stream during function call (or PW_ID_ANY to refer to object_serial)
* @param out_pipewire_objectserial set the pipewire object serial of the stream during function call
* @returns 0 if the stream successfully configured
*/
virtual int configure_stream(const std::string &display_name, int &out_pipewire_fd, uint32_t &out_pipewire_node, uint64_t &out_pipewire_objectserial) = 0;
/**
* @brief Verify and update display parameters for logical dimensions, desktop dimensions and logical desktop dimensions (default is adapted from wlgrab)
*/
virtual void verify_and_update_display_parameters() {
// Query outputs directly using wayland wl::monitors()
if (logical_height <= 0 || logical_width <= 0 || env_logical_height <= 0 || env_logical_width <= 0 || env_height <= 0 || env_width <= 0) {
int desktop_width = 0;
int desktop_height = 0;
int desktop_logical_width = 0;
int desktop_logical_height = 0;
for (const auto &monitor : wl::monitors()) {
BOOST_LOG(debug) << "[pipewire] Found output: '"sv << monitor->name << "' offset: "sv << monitor->viewport.offset_x << 'x' << monitor->viewport.offset_y << " resolution: "sv << monitor->viewport.width << 'x' << monitor->viewport.height << " logical resolution: "sv << monitor->viewport.logical_width << 'x' << monitor->viewport.logical_height;
// If logical_width and logical_height are not valid try to update them to correct values by matching to monitor
// position/dimension or position/logical dimensions here since we're iterating for maximum environment size anyway
if ((logical_width <= 0 || logical_height <= 0) && monitor->viewport.offset_x == offset_x && monitor->viewport.offset_y == offset_y && ((monitor->viewport.width == width && monitor->viewport.height == height) || (monitor->viewport.logical_width == width && monitor->viewport.logical_height == height))) {
this->logical_width = monitor->viewport.logical_width;
this->logical_height = monitor->viewport.logical_height;
BOOST_LOG(debug) << "[pipewire] Set logical resolution: "sv << logical_width << 'x' << logical_height;
}
// Update desktop dimensions to setup maximum environment size over all screens
desktop_width = std::max(desktop_width, monitor->viewport.offset_x + monitor->viewport.width);
desktop_height = std::max(desktop_height, monitor->viewport.offset_y + monitor->viewport.height);
// Update desktop logical dimensions to setup maximum logical environment size over all screens
desktop_logical_width = std::max(desktop_logical_width, monitor->viewport.offset_x + monitor->viewport.logical_width);
desktop_logical_height = std::max(desktop_logical_height, monitor->viewport.offset_y + monitor->viewport.logical_height);
}
if (env_height <= 0 || env_width <= 0) {
this->env_width = desktop_width;
this->env_height = desktop_height;
BOOST_LOG(debug) << "[pipewire] Set desktop resolution: "sv << env_width << 'x' << env_height;
}
if (env_logical_height <= 0 || env_logical_width <= 0) {
this->env_logical_width = desktop_logical_width;
this->env_logical_height = desktop_logical_height;
BOOST_LOG(debug) << "[pipewire] Set desktop logical resolution: "sv << env_logical_width << 'x' << env_logical_height;
}
}
}
/**
* @brief Initialize the PipeWire display backend for a selected stream.
*
* @param hwdevice_type Hardware device type requested for capture or encode.
* @param display_name Display name.
* @param config Configuration values to apply.
* @return 0 on success; nonzero or negative platform status on failure.
*/
int init(platf::mem_type_e hwdevice_type, const std::string &display_name, const ::video::config_t &config) {
// calculate frame interval we should capture at
framerate = config.framerate;
delay = ::video::capture_frame_interval(config);
const AVRational fps = ::video::framerate_to_rational(config);
if (fps.den != 1) {
BOOST_LOG(info) << "[pipewire] Requested frame rate [" << fps.num << "/" << fps.den << ", approx. " << av_q2d(fps) << " fps]";
} else {
BOOST_LOG(info) << "[pipewire] Requested frame rate [" << fps.num << "fps]";
}
mem_type = hwdevice_type;
if (get_dmabuf_modifiers() < 0) {
return -1;
}
int pipewire_fd = -1;
auto pipewire_node = PW_ID_ANY; // Default for invalid stream from pipewire docs
uint64_t pipewire_object_serial = SPA_ID_INVALID; // Default for invalid stream from pipewire docs for PW_KEY_OBJECT_SERIAL
// Fetch stream info
if (configure_stream(display_name, pipewire_fd, pipewire_node, pipewire_object_serial) < 0 || (pipewire_node == PW_ID_ANY && (pipewire_object_serial & SPA_ID_INVALID) == SPA_ID_INVALID)) {
BOOST_LOG(error) << "[pipewire] Could not find display with name: '"sv << display_name << "'";
return -1;
}
BOOST_LOG(info) << "[pipewire] Streaming display '"sv << display_name << "' offset: "sv << offset_x << "x"sv << offset_y << " resolution: "sv << width << "x"sv << height;
// Verify or update display parameters for streaming to ensure absolute touch inputs work as expected
verify_and_update_display_parameters();
framerate = config.framerate;
if (!shared_state) {
shared_state = std::make_shared<shared_state_t>();
} else {
shared_state->stream_dead.store(false);
shared_state->negotiated_width.store(0);
shared_state->negotiated_height.store(0);
shared_state->color_primaries.store(0);
shared_state->transfer_function.store(0);
}
if (pipewire.init(pipewire_fd, pipewire_node, pipewire_object_serial, shared_state) < 0) {
BOOST_LOG(error) << "[pipewire] Failed to init pipewire. pipewire_t::init() failed.";
return -1;
}
// Start PipeWire now so format negotiation can proceed before capture start
if (pipewire.ensure_stream(mem_type, width, height, framerate, dmabuf_infos.data(), n_dmabuf_infos, display_is_nvidia) < 0) {
BOOST_LOG(error) << "[pipewire] Failed to ensure pipewire stream. pipewire_t::init() failed.";
return -1;
}
// Wait for pipewire negotiation to finish so we have the proper negotiated dimensions
int timeout_ms = 1500;
int negotiated_w = 0;
int negotiated_h = 0;
while (timeout_ms > 0) {
negotiated_w = shared_state->negotiated_width.load();
negotiated_h = shared_state->negotiated_height.load();
if (negotiated_w > 0 && negotiated_h > 0) {
break;
}
std::this_thread::sleep_for(std::chrono::milliseconds(10));
timeout_ms -= 10;
}
// Set width and height to the values negotiated by pipewire
if (negotiated_w > 0 && negotiated_h > 0 && (negotiated_w != width || negotiated_h != height)) {
width = negotiated_w;
height = negotiated_h;
BOOST_LOG(info) << "[pipewire] Using negotiated Resolution: "sv << width << "x" << height;
// Reset and update display parameters for negotiated resolution
env_width = 0;
env_height = 0;
logical_height = 0;
logical_width = 0;
env_logical_height = 0;
env_logical_width = 0;
verify_and_update_display_parameters();
}
return 0;
}
/**
* @brief Capture a display frame into the provided image object.
*
* @param pull_free_image_cb Callback that provides an available image buffer.
* @param img_out Captured PipeWire image returned to the streaming pipeline.
* @param timeout Maximum time to wait for the operation.
* @param show_cursor Show cursor.
* @return Capture status reported to the streaming pipeline.
*/
platf::capture_e snapshot(const pull_free_image_cb_t &pull_free_image_cb, std::shared_ptr<platf::img_t> &img_out, std::chrono::milliseconds timeout, bool show_cursor) {
// FIXME: show_cursor is ignored
auto deadline = std::chrono::steady_clock::now() + timeout;
int retries = 0;
while (std::chrono::steady_clock::now() < deadline) {
if (!wait_for_frame(deadline)) {
return platf::capture_e::timeout;
}
if (!pull_free_image_cb(img_out)) {
return platf::capture_e::interrupted;
}
auto *img_egl = static_cast<egl::img_descriptor_t *>(img_out.get());
img_egl->reset();
pipewire.fill_img(img_egl);
// Check if we got valid data (either DMA-BUF fd or memory pointer), then filter duplicates
if ((img_egl->sd.fds[0] >= 0 || img_egl->data != nullptr) && !is_buffer_redundant(img_egl)) {
// Update frame metadata
update_metadata(img_egl, retries);
return platf::capture_e::ok;
}
// No valid frame yet, or it was a duplicate
retries++;
}
return platf::capture_e::timeout;
}
/**
* @brief Allocate an image buffer compatible with this display backend.