fix(linux): select PipeWire converters from negotiated buffers (#6118)

This commit is contained in:
Dave Lane authored and GitHub committed 2026-11-27 18:15:07 -05:00
1 parent d00a82f1e8
commit aa5df84f12
2 files changed
+524 -86

No files matched your search

+213 -85
View File
@@ -78,6 +78,7 @@ namespace pipewire {
* @brief PipeWire capture state shared with callback threads.
*/
struct shared_state_t {
std::atomic<uint32_t> buffer_type {SPA_ID_INVALID}; ///< Negotiated buffer type, or unknown until format negotiation finishes.
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.
@@ -93,10 +94,10 @@ namespace pipewire {
* @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 pw_stream *stream = nullptr; ///< 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.
struct spa_video_info format {}; ///< Negotiated PipeWire video format.
struct pw_buffer *current_buffer = nullptr; ///< 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.
@@ -273,6 +274,7 @@ namespace pipewire {
object_serial = stream_object_serial;
stream_data.shared = std::move(shared_state);
stream_data.shared->has_streamed.store(false);
stream_data.shared->buffer_type.store(SPA_ID_INVALID);
pw_thread_loop_lock(loop);
BOOST_LOG(debug) << "[pipewire] Setup PW context"sv;
@@ -661,8 +663,10 @@ namespace pipewire {
* @brief Copy the latest PipeWire frame into Sunshine's image buffer.
*
* @param img Image or frame object to read from or populate.
* @param buffer_type Buffer type selected for this display and its encoder.
* @return Capture status, including reinit if the buffer storage changed.
*/
void fill_img(platf::img_t *img) {
platf::capture_e fill_img(platf::img_t *img, uint32_t buffer_type) {
pw_thread_loop_lock(loop);
std::scoped_lock lock(stream_data.frame_mutex);
@@ -670,32 +674,55 @@ namespace pipewire {
img->data = nullptr;
close_img_fds(static_cast<egl::img_descriptor_t *>(img));
pw_thread_loop_unlock(loop);
return;
return platf::capture_e::timeout;
}
if (!stream_data.current_buffer) {
img->data = nullptr;
pw_thread_loop_unlock(loop);
return;
return platf::capture_e::timeout;
}
struct spa_buffer *buf = stream_data.current_buffer->buffer;
if (buf->datas[0].chunk->size != 0) {
auto status = copy_frame(img, stream_data, buffer_type);
pw_thread_loop_unlock(loop);
return status;
}
/**
* @brief Copy a frame only if its storage matches the encoder's selected path.
* @param img Destination image, reset by the caller before copying.
* @param d Frame state, protected by the PipeWire loop and frame locks in production.
* @param buffer_type Buffer type selected before encoder creation.
* @return Reinit on a storage change, otherwise the frame's capture status.
*/
static platf::capture_e copy_frame(platf::img_t *img, const stream_data_t &d, uint32_t buffer_type) {
struct spa_buffer *buf = d.current_buffer->buffer;
if (buf->n_datas == 0 || buf->datas[0].chunk->size == 0) {
return platf::capture_e::timeout;
}
const auto actual_type = buf->datas[0].type;
if (actual_type != SPA_DATA_DmaBuf && actual_type != SPA_DATA_MemPtr && actual_type != SPA_DATA_MemFd) {
return platf::capture_e::capture_error;
}
if ((actual_type == SPA_DATA_DmaBuf) != (buffer_type == SPA_DATA_DmaBuf)) {
return platf::capture_e::reinit;
}
{
auto *img_descriptor = static_cast<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);
fill_img_dmabuf(img_descriptor, buf, d);
} else {
img->data = stream_data.front_buffer->data();
img->data = d.front_buffer->data();
img_descriptor->data_owned = false;
img->row_pitch = stream_data.local_stride;
img->row_pitch = d.local_stride;
// NV12 is the only 1-byte-per-pixel format delivered on the memory
// path; every other negotiated format is packed 4 bytes per pixel.
img->pixel_pitch = (stream_data.format.info.raw.format == SPA_VIDEO_FORMAT_NV12) ? 1 : 4;
img->pixel_pitch = (d.format.info.raw.format == SPA_VIDEO_FORMAT_NV12) ? 1 : 4;
}
}
pw_thread_loop_unlock(loop);
return platf::capture_e::ok;
}
/**
@@ -710,10 +737,23 @@ namespace pipewire {
inline static std::atomic prefer_pipewire_pts {false}; ///< Whether the session should directly passthrough Pipewire pts metadata for client pacing.
inline static std::atomic negotiate_variable_rate {true}; ///< Whether the session should request variable rate (maxFrameRate = 0/1) capture.
/**
* @brief Determine the buffer storage requested by the negotiated format.
* @param param Negotiated SPA format, or null while negotiation is pending.
* @param drm_format DRM format corresponding to the negotiated SPA format.
* @return DMA-BUF with a modifier and known DRM format, memory otherwise; unknown for null.
*/
static uint32_t negotiated_buffer_type(const spa_pod *param, uint64_t drm_format) {
if (!param) {
return SPA_ID_INVALID;
}
return drm_format && spa_pod_find_prop(param, nullptr, SPA_FORMAT_VIDEO_modifier) ? SPA_DATA_DmaBuf : SPA_DATA_MemPtr;
}
private:
struct pw_thread_loop *loop;
struct pw_context *context;
struct pw_core *core;
struct pw_context *context = nullptr; ///< PipeWire context, if initialized.
struct pw_core *core = nullptr; ///< PipeWire core, if connected.
struct spa_hook core_listener;
struct stream_data_t stream_data;
uint32_t node;
@@ -898,9 +938,28 @@ namespace pipewire {
static void on_param_changed(void *user_data, uint32_t id, const struct spa_pod *param) { // NOSONAR(cpp:S5008): PipeWire event callbacks require a void pointer for user data.
const auto d = static_cast<struct stream_data_t *>(user_data);
apply_format(*d, id, param, pw_stream_update_params);
}
public:
/**
* @brief Apply a negotiated format and publish its storage after acknowledging the parameters.
* @param data PipeWire stream and callback state.
* @param id PipeWire parameter identifier.
* @param param Negotiated SPA format, or null when withdrawn.
* @param update_params Function used to acknowledge the negotiated parameters.
*/
static void apply_format(stream_data_t &data, uint32_t id, const spa_pod *param, decltype(&pw_stream_update_params) update_params) {
auto *d = &data;
d->current_buffer = nullptr;
if (param == nullptr || id != SPA_PARAM_Format) {
if (id != SPA_PARAM_Format) {
return;
}
if (d->shared) {
d->shared->buffer_type.store(SPA_ID_INVALID);
}
if (param == nullptr) {
return;
}
if (spa_format_parse(param, &d->format.media_type, &d->format.media_subtype) < 0) {
@@ -954,7 +1013,8 @@ namespace pipewire {
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) {
const auto buffer_type = negotiated_buffer_type(param, d->drm_format);
if (buffer_type == SPA_DATA_DmaBuf) {
BOOST_LOG(info) << "[pipewire] using DMA-BUF buffers"sv;
buffer_types |= 1 << SPA_DATA_DmaBuf;
} else {
@@ -978,9 +1038,14 @@ namespace pipewire {
params[n_params] = damage_param;
n_params++;
pw_stream_update_params(d->stream, params.data(), n_params);
update_params(d->stream, params.data(), n_params);
if (d->shared) {
// Publish last: dimensions alone do not mean buffer negotiation is complete.
d->shared->buffer_type.store(buffer_type);
}
}
private:
constexpr static const struct pw_stream_events stream_events = {
.version = PW_VERSION_STREAM_EVENTS,
.state_changed = on_stream_state_changed,
@@ -1118,34 +1183,7 @@ namespace pipewire {
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();
}
wait_for_negotiation(1500ms);
return 0;
}
@@ -1153,13 +1191,15 @@ namespace pipewire {
/**
* @brief Capture a display frame into the provided image object.
*
* @tparam PullFreeImageCb Type of the image buffer callback.
* @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.
* @param show_cursor Whether to include the cursor, currently ignored.
* @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) {
template<typename PullFreeImageCb>
platf::capture_e snapshot(const PullFreeImageCb &pull_free_image_cb, std::shared_ptr<platf::img_t> &img_out, std::chrono::milliseconds timeout, [[maybe_unused]] bool show_cursor) {
// FIXME: show_cursor is ignored
auto deadline = std::chrono::steady_clock::now() + timeout;
int retries = 0;
@@ -1175,10 +1215,13 @@ namespace pipewire {
auto *img_egl = static_cast<egl::img_descriptor_t *>(img_out.get());
img_egl->reset();
pipewire.fill_img(img_egl);
const auto status = fill_capture_frame(img_egl, capture_buffer_type());
if (status == platf::capture_e::reinit || status == platf::capture_e::capture_error) {
return status;
}
// 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)) {
if (status == platf::capture_e::ok && (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;
@@ -1245,15 +1288,8 @@ namespace pipewire {
bool pacing_required = pipewire.is_pacing_required(target_framerate, delay);
while (true) {
// Check if PipeWire signaled a dead stream
if (shared_state->stream_dead.exchange(false)) {
// Additional custom error-handling for subclasses on stream dead event
if (platf::capture_e status; check_stream_dead(status)) {
return status;
}
// Re-init the capture if the stream is dead for any other reason
BOOST_LOG(warning) << "[pipewire] PipeWire stream disconnected. Forcing session reset."sv;
return reinit;
if (const auto status = dead_stream_status()) {
return *status;
}
// Use unpaced event driven capture when possible
@@ -1302,32 +1338,14 @@ namespace pipewire {
* @return Constructed AVCodec encode device object.
*/
std::unique_ptr<platf::avcodec_encode_device_t> make_avcodec_encode_device(platf::pix_fmt_e pix_fmt) override {
#ifdef SUNSHINE_BUILD_VAAPI
if (mem_type == platf::mem_type_e::vaapi) {
return va::make_avcodec_encode_device(width, height, n_dmabuf_infos > 0);
}
#endif
const bool dmabuf = capture_buffer_type() == SPA_DATA_DmaBuf;
#ifdef SUNSHINE_BUILD_VULKAN
if (mem_type == platf::mem_type_e::vulkan && n_dmabuf_infos > 0) {
return vk::make_avcodec_encode_device_vram(width, height, 0, 0);
if (mem_type == platf::mem_type_e::vulkan && !dmabuf) {
return nullptr;
}
#endif
#ifdef SUNSHINE_BUILD_CUDA
if (mem_type == platf::mem_type_e::cuda) {
if (display_is_nvidia && n_dmabuf_infos > 0) {
// Display GPU is NVIDIA - can use DMA-BUF directly
return cuda::make_avcodec_gl_encode_device(width, height, 0, 0);
} else {
// Hybrid system (Intel display + NVIDIA encode) - use memory buffer path
// DMA-BUFs from Intel GPU cannot be imported into CUDA
return cuda::make_avcodec_encode_device(width, height, false);
}
}
#endif
return std::make_unique<platf::avcodec_encode_device_t>();
return make_converter(mem_type, dmabuf);
}
/**
@@ -1536,19 +1554,129 @@ namespace pipewire {
return 0;
}
platf::mem_type_e mem_type;
wl::display_t wl_display;
std::array<struct dmabuf_format_info_t, MAX_DMABUF_FORMATS> dmabuf_infos;
int n_dmabuf_infos;
bool display_is_nvidia = false; // Track if display GPU is NVIDIA
uint32_t buffer_type = SPA_ID_INVALID; ///< Negotiated storage at startup; remains unknown when the wait expires.
std::chrono::nanoseconds delay;
std::optional<std::uint64_t> last_pts {};
std::optional<std::uint64_t> last_seq {};
std::uint64_t sequence {};
AVRational target_framerate;
/**
* @brief Return the storage expected by this display's converter.
* @return Negotiated storage, or the provisional storage while negotiation is pending.
*/
uint32_t capture_buffer_type() const {
if (mem_type == platf::mem_type_e::cuda && !display_is_nvidia) {
return SPA_DATA_MemPtr;
}
if (buffer_type != SPA_ID_INVALID) {
return buffer_type;
}
// Keep Vulkan's dummy-frame probe and portal retry reachable. Snapshot
// still rejects a real memory frame before it can reach the VRAM converter.
if (mem_type == platf::mem_type_e::vulkan && n_dmabuf_infos > 0) {
return SPA_DATA_DmaBuf;
}
return SPA_DATA_MemPtr;
}
protected:
// Allow subclasses to access for pipewire requirements setup and stream dead checks
/**
* @brief Wait for format negotiation, without substituting a format if it is still pending.
* @param timeout Maximum time to wait for dimensions and a buffer type.
*/
void wait_for_negotiation(std::chrono::milliseconds timeout) {
const auto deadline = std::chrono::steady_clock::now() + timeout;
int negotiated_w;
int negotiated_h;
while (true) {
buffer_type = shared_state->buffer_type.load();
negotiated_w = shared_state->negotiated_width.load();
negotiated_h = shared_state->negotiated_height.load();
if ((negotiated_w > 0 && negotiated_h > 0 && buffer_type != SPA_ID_INVALID) || shared_state->stream_dead.load() || std::chrono::steady_clock::now() >= deadline) {
break;
}
std::this_thread::sleep_for(10ms);
}
if (buffer_type == SPA_ID_INVALID) {
BOOST_LOG(warning) << "[pipewire] Buffer negotiation still pending; using provisional converter selection"sv;
}
// 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();
}
}
/**
* @brief Consume a dead-stream notification and run the backend's recovery hook.
* @return No status for a live stream; a capture status for a dead stream.
*/
std::optional<platf::capture_e> dead_stream_status() {
if (!shared_state->stream_dead.exchange(false)) {
return std::nullopt;
}
if (platf::capture_e status; check_stream_dead(status)) {
return status;
}
BOOST_LOG(warning) << "[pipewire] PipeWire stream disconnected. Forcing session reset."sv;
return platf::capture_e::reinit;
}
/**
* @brief Copy the available frame using the storage expected by the converter.
* @param img Destination image.
* @param expected_type Storage expected by the selected converter.
* @return Status of the copy, including reinit on a storage change.
*/
virtual platf::capture_e fill_capture_frame(platf::img_t *img, uint32_t expected_type) {
return pipewire.fill_img(img, expected_type);
}
/**
* @brief Construct the platform converter for the selected encoder and buffer path.
* @param type Encoder memory type.
* @param vram Whether to use a DMA-BUF converter rather than the memory path.
* @return The encode device that will consume captured frames.
*/
virtual std::unique_ptr<platf::avcodec_encode_device_t> make_converter(platf::mem_type_e type, bool vram) {
#ifdef SUNSHINE_BUILD_VAAPI
if (type == platf::mem_type_e::vaapi) {
return va::make_avcodec_encode_device(width, height, vram);
}
#endif
#ifdef SUNSHINE_BUILD_VULKAN
if (type == platf::mem_type_e::vulkan) {
return vk::make_avcodec_encode_device_vram(width, height, 0, 0);
}
#endif
#ifdef SUNSHINE_BUILD_CUDA
if (type == platf::mem_type_e::cuda) {
if (vram) {
return cuda::make_avcodec_gl_encode_device(width, height, 0, 0);
}
return cuda::make_avcodec_encode_device(width, height, false);
}
#endif
return std::make_unique<platf::avcodec_encode_device_t>();
}
platf::mem_type_e mem_type = platf::mem_type_e::system; ///< Requested encoder memory type.
int n_dmabuf_infos = 0; ///< Number of locally importable DMA-BUF formats advertised at startup.
bool display_is_nvidia = false; ///< Whether CUDA can import DMA-BUFs from the display GPU.
pipewire_t pipewire; ///< Pipewire.
std::shared_ptr<shared_state_t> shared_state; ///< Shared state.
};
+311 -1
View File
@@ -1,6 +1,6 @@
/**
* @file tests/unit/platform/linux/test_pipewire.cpp
* @brief Test PipeWire stream lifecycle handling and capture display teardown.
* @brief Test PipeWire buffer negotiation, stream lifecycle handling, and capture display teardown.
*/
#if defined(SUNSHINE_BUILD_KWIN) || defined(SUNSHINE_BUILD_PORTAL)
// test includes
@@ -62,6 +62,148 @@ namespace {
}
};
/**
* @brief Drive display startup and capture with synthetic formats and recording converter factories.
*/
class negotiation_display_t: public test_display_t {
public:
/**
* @brief Set up a display with local import capabilities but no negotiated format.
* @param type Encoder memory type.
* @param dma_formats Number of DMA-BUF formats available locally.
* @param nvidia Whether the display GPU is NVIDIA.
*/
negotiation_display_t(platf::mem_type_e type, int dma_formats, bool nvidia = false) {
mem_type = type;
n_dmabuf_infos = dma_formats;
display_is_nvidia = nvidia;
width = 640;
height = 480;
shared_state = std::make_shared<pipewire::shared_state_t>();
data.shared = shared_state;
}
/**
* @brief Deliver a valid raw format with or without its DMA-BUF modifier.
* @param dma Whether the compositor supplies a DMA-BUF modifier.
*/
void negotiate(bool dma) {
std::array<uint8_t, 256> storage {};
spa_pod_builder builder = SPA_POD_BUILDER_INIT(storage.data(), storage.size());
spa_pod_frame frame {};
const spa_rectangle size {640, 480};
const spa_fraction framerate {60, 1}; // Required by PipeWire 0.3's raw format parser.
spa_pod_builder_push_object(&builder, &frame, SPA_TYPE_OBJECT_Format, SPA_PARAM_Format);
spa_pod_builder_add(
&builder,
SPA_FORMAT_mediaType,
SPA_POD_Id(SPA_MEDIA_TYPE_video),
SPA_FORMAT_mediaSubtype,
SPA_POD_Id(SPA_MEDIA_SUBTYPE_raw),
SPA_FORMAT_VIDEO_format,
SPA_POD_Id(SPA_VIDEO_FORMAT_BGRx),
SPA_FORMAT_VIDEO_size,
SPA_POD_Rectangle(&size),
SPA_FORMAT_VIDEO_framerate,
SPA_POD_Fraction(&framerate),
0
);
if (dma) {
spa_pod_builder_add(&builder, SPA_FORMAT_VIDEO_modifier, SPA_POD_Long(DRM_FORMAT_MOD_LINEAR), 0);
}
auto *format = static_cast<const spa_pod *>(spa_pod_builder_pop(&builder, &frame));
ASSERT_NE(format, nullptr);
pipewire::pipewire_t::apply_format(data, SPA_PARAM_Format, format, [](pw_stream *, const spa_pod **params, uint32_t n_params) {
EXPECT_GT(n_params, 0U);
EXPECT_NE(spa_pod_find_prop(params[0], nullptr, SPA_PARAM_BUFFERS_dataType), nullptr);
return 0;
});
EXPECT_EQ(shared_state->buffer_type.load(), dma ? SPA_DATA_DmaBuf : SPA_DATA_MemPtr);
}
/**
* @brief Complete the same negotiation wait used by initialization, with an immediate deadline.
*/
void finish_startup() {
wait_for_negotiation(0ms);
}
/**
* @brief Wake the snapshot with a synthetic buffer and run the real frame-storage guard.
* @param type Buffer type for the frame.
* @param fd File descriptor for a synthetic DMA-BUF plane.
* @param size Number of bytes present in the frame.
* @return Status reported to the capture loop.
*/
platf::capture_e capture_frame(uint32_t type, int fd = -1, uint32_t size = 16) {
spa_chunk chunk {};
chunk.size = size;
chunk.stride = 8;
spa_data plane {};
plane.chunk = &chunk;
plane.type = type;
plane.fd = fd;
spa_buffer buffer {};
buffer.n_datas = 1;
buffer.datas = &plane;
pw_buffer current {};
current.buffer = &buffer;
data.current_buffer = &current;
data.buffer_a.resize(16);
data.local_stride = 8;
pipewire.set_frame_ready(true);
std::shared_ptr<platf::img_t> img;
const auto status = snapshot(
[&](auto &out) {
out = alloc_img();
return true;
},
img,
100ms,
false
);
data.current_buffer = nullptr;
if (img) {
pipewire::pipewire_t::close_img_fds(static_cast<egl::img_descriptor_t *>(img.get()));
}
return status;
}
#ifdef SUNSHINE_BUILD_PORTAL
/**
* @brief Simulate a startup error and consume the real capture loop's recovery status.
* @return The capture loop's selected status.
*/
std::optional<platf::capture_e> fail_startup() {
pipewire::pipewire_t::on_stream_state_changed(&data, PW_STREAM_STATE_PAUSED, PW_STREAM_STATE_ERROR, "no more input formats");
return dead_stream_status();
}
bool negotiate_maxframerate = true; ///< Whether portal startup should still request maxFramerate.
#endif
std::optional<std::pair<platf::mem_type_e, bool>> selected_factory; ///< Type and VRAM argument passed to the converter factory.
protected:
std::unique_ptr<platf::avcodec_encode_device_t> make_converter(platf::mem_type_e type, bool vram) override {
selected_factory.emplace(type, vram);
return std::make_unique<platf::avcodec_encode_device_t>();
}
platf::capture_e fill_capture_frame(platf::img_t *img, uint32_t expected_type) override {
return pipewire::pipewire_t::copy_frame(img, data, expected_type);
}
#ifdef SUNSHINE_BUILD_PORTAL
bool check_stream_dead(platf::capture_e &status) override {
return portal::check_stream_dead_for_testing(shared_state, negotiate_maxframerate, status);
}
#endif
private:
pipewire::stream_data_t data {}; ///< Data populated by the format callback and synthetic frame delivery.
};
/**
* @brief Check whether a file descriptor is open.
*
@@ -215,6 +357,172 @@ namespace {
};
} // namespace
TEST(PipeWireBufferTest, NegotiationDistinguishesPendingMemoryAndDmabuf) {
EXPECT_EQ(pipewire::pipewire_t::negotiated_buffer_type(nullptr, DRM_FORMAT_XRGB8888), SPA_ID_INVALID);
pipewire::shared_state_t shared;
EXPECT_EQ(shared.buffer_type.load(), SPA_ID_INVALID);
std::array<uint8_t, 256> storage {};
spa_pod_builder builder = SPA_POD_BUILDER_INIT(storage.data(), storage.size());
auto *memory = static_cast<spa_pod *>(spa_pod_builder_add_object(
&builder,
SPA_TYPE_OBJECT_Format,
SPA_PARAM_Format,
SPA_FORMAT_VIDEO_format,
SPA_POD_Id(SPA_VIDEO_FORMAT_BGRx)
));
// A locally importable format is not evidence that the compositor supplied DMA-BUF.
EXPECT_EQ(pipewire::pipewire_t::negotiated_buffer_type(memory, DRM_FORMAT_XRGB8888), SPA_DATA_MemPtr);
builder = SPA_POD_BUILDER_INIT(storage.data(), storage.size());
auto *dmabuf = static_cast<spa_pod *>(spa_pod_builder_add_object(
&builder,
SPA_TYPE_OBJECT_Format,
SPA_PARAM_Format,
SPA_FORMAT_VIDEO_modifier,
SPA_POD_Long(DRM_FORMAT_MOD_LINEAR)
));
EXPECT_EQ(pipewire::pipewire_t::negotiated_buffer_type(dmabuf, DRM_FORMAT_XRGB8888), SPA_DATA_DmaBuf);
EXPECT_EQ(pipewire::pipewire_t::negotiated_buffer_type(dmabuf, 0), SPA_DATA_MemPtr);
}
TEST(PipeWireBufferTest, StorageChangesAreRejectedBeforeCopyingFrame) {
pipewire::stream_data_t data {};
spa_chunk chunk {};
chunk.size = 16;
chunk.stride = 8;
spa_data plane {};
plane.chunk = &chunk;
plane.fd = -1;
spa_buffer buffer {};
buffer.n_datas = 1;
buffer.datas = &plane;
pw_buffer current {};
current.buffer = &buffer;
data.current_buffer = &current;
data.buffer_a.resize(16, 42);
data.local_stride = 8;
data.format.info.raw.format = SPA_VIDEO_FORMAT_BGRx;
for (auto type : {SPA_DATA_MemPtr, SPA_DATA_MemFd}) {
plane.type = type;
pipewire::img_descriptor_t img {};
img.sd.fds.fill(-1);
EXPECT_EQ(pipewire::pipewire_t::copy_frame(&img, data, SPA_DATA_DmaBuf), platf::capture_e::reinit);
EXPECT_EQ(img.data, nullptr);
EXPECT_EQ(img.sd.fds[0], -1);
EXPECT_EQ(pipewire::pipewire_t::copy_frame(&img, data, SPA_DATA_MemPtr), platf::capture_e::ok);
EXPECT_EQ(img.data, data.buffer_a.data());
EXPECT_EQ(img.row_pitch, 8);
EXPECT_EQ(img.pixel_pitch, 4);
EXPECT_FALSE(img.data_owned);
}
plane.type = SPA_DATA_DmaBuf;
pipewire::img_descriptor_t img {};
img.sd.fds.fill(-1);
EXPECT_EQ(pipewire::pipewire_t::copy_frame(&img, data, SPA_DATA_MemPtr), platf::capture_e::reinit);
EXPECT_EQ(img.data, nullptr);
EXPECT_EQ(img.sd.fds[0], -1);
// A new display may use DMA-BUF again; no process-wide fallback is latched.
plane.fd = open("/dev/null", O_RDONLY | O_CLOEXEC);
ASSERT_GE(plane.fd, 0);
EXPECT_EQ(pipewire::pipewire_t::copy_frame(&img, data, SPA_DATA_DmaBuf), platf::capture_e::ok);
EXPECT_GE(img.sd.fds[0], 0);
EXPECT_NE(img.sd.fds[0], plane.fd);
pipewire::pipewire_t::close_img_fds(&img);
close(plane.fd);
plane.type = SPA_DATA_Invalid;
EXPECT_EQ(pipewire::pipewire_t::copy_frame(&img, data, SPA_DATA_MemPtr), platf::capture_e::capture_error);
chunk.size = 0;
EXPECT_EQ(pipewire::pipewire_t::copy_frame(&img, data, SPA_DATA_MemPtr), platf::capture_e::timeout);
buffer.n_datas = 0;
EXPECT_EQ(pipewire::pipewire_t::copy_frame(&img, data, SPA_DATA_MemPtr), platf::capture_e::timeout);
}
TEST_F(PipeWireDisplayTest, VaapiFactoryUsesNegotiatedStorageRatherThanLocalDmaFormats) {
for (bool dma : {false, true}) {
SCOPED_TRACE(dma);
negotiation_display_t display {platf::mem_type_e::vaapi, 1};
display.negotiate(dma);
display.finish_startup();
EXPECT_NE(display.make_avcodec_encode_device(platf::pix_fmt_e {}), nullptr);
ASSERT_TRUE(display.selected_factory);
EXPECT_EQ(display.selected_factory->first, platf::mem_type_e::vaapi);
EXPECT_EQ(display.selected_factory->second, dma);
}
}
TEST_F(PipeWireDisplayTest, CudaFactoryUsesDmaBufOnlyForNegotiatedDmaBufOnNvidia) {
for (bool nvidia : {false, true}) {
for (bool dma : {false, true}) {
SCOPED_TRACE(::testing::Message() << "nvidia=" << nvidia << " dma=" << dma);
negotiation_display_t display {platf::mem_type_e::cuda, 1, nvidia};
display.negotiate(dma);
display.finish_startup();
EXPECT_NE(display.make_avcodec_encode_device(platf::pix_fmt_e {}), nullptr);
ASSERT_TRUE(display.selected_factory);
EXPECT_EQ(display.selected_factory->first, platf::mem_type_e::cuda);
EXPECT_EQ(display.selected_factory->second, nvidia && dma);
}
}
}
TEST_F(PipeWireDisplayTest, PendingMemoryConverterRequestsReinitOnLateDmaBuf) {
negotiation_display_t display {platf::mem_type_e::vaapi, 1};
display.finish_startup();
EXPECT_NE(display.make_avcodec_encode_device(platf::pix_fmt_e {}), nullptr);
ASSERT_TRUE(display.selected_factory);
EXPECT_FALSE(display.selected_factory->second);
display.negotiate(true);
EXPECT_EQ(display.capture_frame(SPA_DATA_DmaBuf), platf::capture_e::reinit);
EXPECT_EQ(display.capture_frame(SPA_DATA_Invalid), platf::capture_e::capture_error);
EXPECT_EQ(display.capture_frame(SPA_DATA_MemPtr, -1, 0), platf::capture_e::timeout);
}
#ifdef SUNSHINE_BUILD_VULKAN
TEST_F(PipeWireDisplayTest, PendingVulkanProbeAcceptsLateDmaBufButRejectsRealMemoryFrames) {
negotiation_display_t display {platf::mem_type_e::vulkan, 1};
display.finish_startup();
ASSERT_NE(display.make_avcodec_encode_device(platf::pix_fmt_e {}), nullptr);
ASSERT_TRUE(display.selected_factory);
EXPECT_TRUE(display.selected_factory->second);
display.negotiate(true);
const auto fd = open("/dev/null", O_RDONLY | O_CLOEXEC);
ASSERT_GE(fd, 0);
EXPECT_EQ(display.capture_frame(SPA_DATA_DmaBuf, fd), platf::capture_e::ok);
close(fd);
display.negotiate(false);
EXPECT_EQ(display.capture_frame(SPA_DATA_MemPtr), platf::capture_e::reinit);
}
TEST_F(PipeWireDisplayTest, VulkanFactoryRejectsConfirmedMemoryAndPendingWithoutDmaFormats) {
negotiation_display_t memory {platf::mem_type_e::vulkan, 1};
memory.negotiate(false);
memory.finish_startup();
EXPECT_EQ(memory.make_avcodec_encode_device(platf::pix_fmt_e {}), nullptr);
EXPECT_FALSE(memory.selected_factory);
negotiation_display_t unavailable {platf::mem_type_e::vulkan, 0};
unavailable.finish_startup();
EXPECT_EQ(unavailable.make_avcodec_encode_device(platf::pix_fmt_e {}), nullptr);
EXPECT_FALSE(unavailable.selected_factory);
}
#ifdef SUNSHINE_BUILD_PORTAL
TEST_F(PipeWireDisplayTest, PendingVulkanProbeKeepsPortalStartupRetryReachable) {
negotiation_display_t display {platf::mem_type_e::vulkan, 1};
display.finish_startup();
ASSERT_NE(display.make_avcodec_encode_device(platf::pix_fmt_e {}), nullptr);
EXPECT_EQ(display.fail_startup(), platf::capture_e::reinit);
EXPECT_FALSE(display.negotiate_maxframerate);
}
#endif
#endif
TEST(PipeWireStreamStateTest, RecordsStartupUntilTheStreamIsReplaced) {
pipewire::stream_data_t data {};
data.shared = std::make_shared<pipewire::shared_state_t>();
@@ -302,9 +610,11 @@ TEST_F(PipeWireDisplayTest, NewConnectionResetsStartupHistory) {
ASSERT_EQ(socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0, sockets.data()), 0);
auto state = std::make_shared<pipewire::shared_state_t>();
state->has_streamed.store(true);
state->buffer_type.store(SPA_DATA_DmaBuf);
auto display = std::make_shared<test_display_t>();
display->connect(sockets[0], state);
EXPECT_FALSE(state->has_streamed.load());
EXPECT_EQ(state->buffer_type.load(), SPA_ID_INVALID);
display.reset();
close(sockets[1]);
}