gst-plugin.cpp 16.2 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
/* Plugin implementation for gstreamer encoder
 *
 * \copyright
 * Copyright 2018 Red Hat Inc. All rights reserved.
 */

#include <config.h>
#include <cstring>
#include <exception>
#include <stdexcept>
#include <memory>
#include <syslog.h>
#include <unistd.h>
#include <gst/gst.h>
#include <gst/app/gstappsink.h>

#define XLIB_CAPTURE 1
#if XLIB_CAPTURE
#include <gst/app/gstappsrc.h>
#endif

#include <spice-streaming-agent/plugin.hpp>
#include <spice-streaming-agent/frame-capture.hpp>
24 25
#include <spice-streaming-agent/x11-display-info.hpp>

26 27 28 29 30 31 32 33 34 35 36 37

#define gst_syslog(priority, str, ...) syslog(priority, "Gstreamer plugin: " str, ## __VA_ARGS__);

namespace spice {
namespace streaming_agent {
namespace gstreamer_plugin {

struct GstreamerEncoderSettings
{
    int fps = 25;
    SpiceVideoCodecType codec = SPICE_VIDEO_CODEC_TYPE_H264;
    std::string encoder;
38
    std::vector<std::pair<std::string, std::string>> prop_pairs;
39 40
};

41 42 43 44 45 46 47 48 49 50 51 52 53
#define DECLARE_UPTR(type, func) \
    struct type##Deleter {       \
        void operator()(type* p) \
        {                        \
            func(p);             \
        }                        \
    };                           \
    using type##UPtr = std::unique_ptr<type, type##Deleter>;

DECLARE_UPTR(GstBuffer, gst_buffer_unref)
DECLARE_UPTR(GstCaps, gst_caps_unref)
DECLARE_UPTR(GstSample, gst_sample_unref)
DECLARE_UPTR(GstElement, gst_object_unref)
54

55 56 57 58 59 60 61 62 63 64
class GstreamerFrameCapture final : public FrameCapture
{
public:
    GstreamerFrameCapture(const GstreamerEncoderSettings &settings);
    ~GstreamerFrameCapture();
    FrameInfo CaptureFrame() override;
    void Reset() override;
    SpiceVideoCodecType VideoCodecType() const override {
        return settings.codec;
    }
65
    std::vector<DeviceDisplayInfo> get_device_display_info() const override;
66 67 68 69 70
private:
    void free_sample();
    GstElement *get_encoder_plugin(const GstreamerEncoderSettings &settings, GstCapsUPtr &sink_caps);
    GstElement *get_capture_plugin(const GstreamerEncoderSettings &settings);
    void pipeline_init(const GstreamerEncoderSettings &settings);
71
    Display *const dpy;
72 73 74
#if XLIB_CAPTURE
    void xlib_capture();
#endif
75
    GstElementUPtr pipeline, capture, sink;
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
    GstSampleUPtr sample;
    GstMapInfo map = {};
    uint32_t last_width = ~0u, last_height = ~0u;
    uint32_t cur_width = 0, cur_height = 0;
    bool is_first = true;
    GstreamerEncoderSettings settings; // will be set by plugin settings
};

class GstreamerPlugin final: public Plugin
{
public:
    FrameCapture *CreateCapture() override;
    unsigned Rank() override;
    void ParseOptions(const ConfigureOption *options);
    SpiceVideoCodecType VideoCodecType() const override {
        return settings.codec;
    }
private:
    GstreamerEncoderSettings settings;
};

GstElement *GstreamerFrameCapture::get_capture_plugin(const GstreamerEncoderSettings &settings)
{
    GstElement *capture = nullptr;

#if XLIB_CAPTURE
    capture = gst_element_factory_make("appsrc", "capture");
#else
    capture = gst_element_factory_make("ximagesrc", "capture");
    g_object_set(capture,
                "use-damage", 0,
                 nullptr);
#endif
    return capture;
}

GstElement *GstreamerFrameCapture::get_encoder_plugin(const GstreamerEncoderSettings &settings,
                                                      GstCapsUPtr &sink_caps)
{
    GList *encoders;
    GList *filtered;
    GstElement *encoder;
    GstElementFactory *factory = nullptr;

    switch (settings.codec) {
    case SPICE_VIDEO_CODEC_TYPE_H264:
122 123 124
        sink_caps.reset(gst_caps_new_simple("video/x-h264",
                                            "stream-format", G_TYPE_STRING, "byte-stream",
                                            nullptr));
125 126
        break;
    case SPICE_VIDEO_CODEC_TYPE_MJPEG:
127
        sink_caps.reset(gst_caps_new_empty_simple("image/jpeg"));
128 129
        break;
    case SPICE_VIDEO_CODEC_TYPE_VP8:
130
        sink_caps.reset(gst_caps_new_empty_simple("video/x-vp8"));
131 132
        break;
    case SPICE_VIDEO_CODEC_TYPE_VP9:
133
        sink_caps.reset(gst_caps_new_empty_simple("video/x-vp9"));
134 135
        break;
    case SPICE_VIDEO_CODEC_TYPE_H265:
136
        sink_caps.reset(gst_caps_new_empty_simple("video/x-h265"));
137 138 139 140
        break;
    default : /* Should not happen - just to avoid compiler's complaint */
        throw std::logic_error("Unknown codec");
    }
141 142
    gst_caps_set_simple(sink_caps.get(), "framerate", GST_TYPE_FRACTION, settings.fps, 1, nullptr);
    std::unique_ptr<gchar, decltype(&g_free)> caps_str(gst_caps_to_string(sink_caps.get()), g_free);
143 144 145 146

    encoders = gst_element_factory_list_get_elements(GST_ELEMENT_FACTORY_TYPE_VIDEO_ENCODER, GST_RANK_NONE);
    filtered = gst_element_factory_list_filter(encoders, sink_caps.get(), GST_PAD_SRC, false);
    if (filtered) {
147
        gst_syslog(LOG_NOTICE, "Looking for encoder plugins which can produce a '%s' stream", caps_str.get());
148 149 150 151 152 153 154 155 156
        for (GList *l = filtered; l != nullptr; l = l->next) {
            if (!factory && !settings.encoder.compare(GST_ELEMENT_NAME(l->data))) {
                factory = (GstElementFactory*)l->data;
            }
            gst_syslog(LOG_NOTICE, "'%s' plugin is available", GST_ELEMENT_NAME(l->data));
        }
        if (!factory && !settings.encoder.empty()) {
            gst_syslog(LOG_WARNING,
                       "Specified encoder named '%s' cannot produce '%s' stream, make sure matching gst.codec is specified and plugin's availability",
157
                       settings.encoder.c_str(), caps_str.get());
158 159 160 161 162
        }
        factory = factory ? factory : (GstElementFactory*)filtered->data;
        gst_syslog(LOG_NOTICE, "'%s' encoder plugin is used", GST_ELEMENT_NAME(factory));

    } else {
163
        gst_syslog(LOG_ERR, "No suitable encoder was found for '%s'", caps_str.get());
164 165 166
    }

    encoder = factory ? gst_element_factory_create(factory, "encoder") : nullptr;
167 168 169 170 171 172 173 174 175 176 177 178 179 180
    if (encoder) { // Set encoder properties
        for (const auto &prop : settings.prop_pairs) {
            const auto &name = prop.first;
            const auto &value = prop.second;
            if (!g_object_class_find_property(G_OBJECT_GET_CLASS(encoder), name.c_str())) {
                gst_syslog(LOG_WARNING, "'%s' property was not found for this encoder",
                           name.c_str());
                continue;
            }
            gst_syslog(LOG_NOTICE, "Trying to set encoder property: '%s = %s'",
                       name.c_str(), value.c_str());
            /* Invalid properties will be ignored silently */
            gst_util_set_object_arg(G_OBJECT(encoder), name.c_str(), value.c_str());
        }
181 182 183 184 185 186 187 188
    }
    gst_plugin_feature_list_free(filtered);
    gst_plugin_feature_list_free(encoders);
    return encoder;
}

// Utility to add an element to a GstBin
// This checks return value and update reference correctly
189
void gst_bin_add(GstBin *bin, const GstElementUPtr &elem)
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
{
    if (::gst_bin_add(bin, elem.get())) {
        // ::gst_bin_add take ownership using floating references but
        // we still hold a reference in elem so update the reference
        // accordingly
        g_object_ref(elem.get());
    } else {
        throw std::runtime_error("Gstreamer's element cannot be added to pipeline");
    }
}

void GstreamerFrameCapture::pipeline_init(const GstreamerEncoderSettings &settings)
{
    gboolean link;

205
    GstElementUPtr pipeline(gst_pipeline_new("pipeline"));
206 207 208
    if (!pipeline) {
        throw std::runtime_error("Gstreamer's pipeline element cannot be created");
    }
209
    GstElementUPtr capture(get_capture_plugin(settings));
210 211 212
    if (!capture) {
        throw std::runtime_error("Gstreamer's capture element cannot be created");
    }
213
    GstElementUPtr convert(gst_element_factory_make("autovideoconvert", "convert"));
214
    if (!convert) {
215
        throw std::runtime_error("Gstreamer's 'autovideoconvert' element cannot be created");
216 217
    }
    GstCapsUPtr sink_caps;
218
    GstElementUPtr encoder(get_encoder_plugin(settings, sink_caps));
219 220 221
    if (!encoder) {
        throw std::runtime_error("Gstreamer's encoder element cannot be created");
    }
222
    GstElementUPtr sink(gst_element_factory_make("appsink", "sink"));
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
    if (!sink) {
        throw std::runtime_error("Gstreamer's appsink element cannot be created");
    }

    g_object_set(sink.get(),
                 "sync", FALSE,
                 "drop", TRUE,
                 "max-buffers", 1,
                 nullptr);

    GstBin *bin = GST_BIN(pipeline.get());
    gst_bin_add(bin, capture);
    gst_bin_add(bin, convert);
    gst_bin_add(bin, encoder);
    gst_bin_add(bin, sink);

239
    GstCapsUPtr caps(gst_caps_from_string("video/x-raw(ANY)"));
240 241 242 243
    GstCapsUPtr convert_caps(gst_caps_new_simple("video/x-raw",
                                                 "framerate", GST_TYPE_FRACTION, settings.fps, 1,
                                                 nullptr));
    link = gst_element_link_filtered(capture.get(), convert.get(), convert_caps.get()) &&
244 245 246 247 248 249 250
           gst_element_link_filtered(convert.get(), encoder.get(), caps.get()) &&
           gst_element_link_filtered(encoder.get(), sink.get(), sink_caps.get());
    if (!link) {
        throw std::runtime_error("Linking gstreamer's elements failed");
    }

    gst_element_set_state(pipeline.get(), GST_STATE_PLAYING);
251
    GST_DEBUG_BIN_TO_DOT_FILE(bin, GST_DEBUG_GRAPH_SHOW_VERBOSE, "gst-plugin-pipeline-debug");
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
#if !XLIB_CAPTURE
    int sx, sy, ex, ey;
    g_object_get(capture.get(),
                 "endx", &ex,
                 "endy", &ey,
                 "startx", &sx,
                 "starty", &sy,
                 nullptr);
    cur_width = ex - sx;
    cur_height = ey - sy;
    if (cur_width < 16 || cur_height < 16) {
         throw std::runtime_error("Invalid screen size");
    }
    g_object_set(capture.get(),
    /* Some encoders cannot handle odd resolution make sure it's even number of pixels
     * pixel counting starts from zero here!
     */
                 "endx", cur_width - !(cur_width % 2),
                 "endy", cur_height - !(cur_height % 2),
                 "startx", 0,
                 "starty", 0,
                 nullptr);
#endif

    this->sink.swap(sink);
    this->capture.swap(capture);
    this->pipeline.swap(pipeline);
}

GstreamerFrameCapture::GstreamerFrameCapture(const GstreamerEncoderSettings &settings):
282
    dpy(XOpenDisplay(nullptr)),settings(settings)
283
{
284 285 286
    if (!dpy) {
        throw std::runtime_error("Unable to initialize X11");
    }
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
    pipeline_init(settings);
}

void GstreamerFrameCapture::free_sample()
{
    if (sample) {
        gst_buffer_unmap(gst_sample_get_buffer(sample.get()), &map);
        sample.reset();
    }
}

GstreamerFrameCapture::~GstreamerFrameCapture()
{
    free_sample();
    gst_element_set_state(pipeline.get(), GST_STATE_NULL);
    XCloseDisplay(dpy);
}

void GstreamerFrameCapture::Reset()
{
    //TODO
}

#if XLIB_CAPTURE
311 312 313 314 315 316
void free_ximage(gpointer data)
{
    XImage *image = (XImage*)data;
    image->f.destroy_image(image);
}

317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
void GstreamerFrameCapture::xlib_capture()
{
    int screen = XDefaultScreen(dpy);

    Window win = RootWindow(dpy, screen);
    XWindowAttributes win_info;
    XGetWindowAttributes(dpy, win, &win_info);

    /* Some encoders cannot handle odd resolution make sure it's even number of pixels */
    cur_width = win_info.width - win_info.width % 2;
    cur_height =  win_info.height - win_info.height % 2;

    if (cur_width != last_width || cur_height != last_height) {
        last_width = cur_width;
        last_height = cur_height;
        is_first = true;

        gst_app_src_end_of_stream(GST_APP_SRC(capture.get()));
        gst_element_set_state(pipeline.get(), GST_STATE_NULL);//maybe ximagesrc needs eos as well
        gst_element_set_state(pipeline.get(), GST_STATE_PLAYING);
    }

339 340
    XImage *image = XGetImage(dpy, win, 0, 0,
                              cur_width, cur_height, AllPlanes, ZPixmap);
341 342 343 344
    if (!image) {
        throw std::runtime_error("Cannot capture from X");
    }

345 346 347 348
    GstBufferUPtr buf(gst_buffer_new_wrapped_full(GST_MEMORY_FLAG_PHYSICALLY_CONTIGUOUS, image->data,
                                                  image->height * image->bytes_per_line, 0,
                                                  image->height * image->bytes_per_line, image,
                                                  free_ximage));
349 350 351 352
    if (!buf) {
        throw std::runtime_error("Failed to wrap image in gstreamer buffer");
    }

353 354 355 356 357 358
    GstCapsUPtr caps(gst_caps_new_simple("video/x-raw",
                                         "format", G_TYPE_STRING, "BGRx",
                                         "width", G_TYPE_INT, image->width,
                                         "height", G_TYPE_INT, image->height,
                                         "framerate", GST_TYPE_FRACTION, settings.fps, 1,
                                         nullptr));
359

360 361
    // Push sample (gst_app_src_push_sample does not take buffer ownership)
    GstSampleUPtr appsrc_sample(gst_sample_new(buf.get(), caps.get(), nullptr, nullptr));
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
    if (gst_app_src_push_sample(GST_APP_SRC(capture.get()), appsrc_sample.get()) != GST_FLOW_OK) {
        throw std::runtime_error("gstramer appsrc element cannot push sample");
    }
}
#endif

FrameInfo GstreamerFrameCapture::CaptureFrame()
{
    FrameInfo info;

    free_sample(); // free prev if exist

#if XLIB_CAPTURE
    xlib_capture();
#endif
    info.size.width = cur_width;
    info.size.height = cur_height;
    info.stream_start = is_first;
    if (is_first) {
        is_first = false;
    }

    // Pull sample
    sample.reset(gst_app_sink_pull_sample(GST_APP_SINK(sink.get()))); // blocking

    if (sample) { // map after pipeline
        if (!gst_buffer_map(gst_sample_get_buffer(sample.get()), &map, GST_MAP_READ)) {
            free_sample();
            throw std::runtime_error("Buffer mapping failed");
        }

        info.buffer = map.data;
        info.buffer_size = map.size;
    } else {
        throw std::runtime_error("No sample- EOS or state change");
    }

    return info;
}

402 403 404 405 406 407 408 409 410 411 412
std::vector<DeviceDisplayInfo> GstreamerFrameCapture::get_device_display_info() const
{
    try {
        return get_device_display_info_drm(dpy);
    } catch (const std::exception &e) {
        syslog(LOG_WARNING, "Failed to get device info using DRM: %s. Using no-DRM fallback.",
               e.what());
        return get_device_display_info_no_drm(dpy);
    }
}

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
FrameCapture *GstreamerPlugin::CreateCapture()
{
    return new GstreamerFrameCapture(settings);
}

unsigned GstreamerPlugin::Rank()
{
    return SoftwareMin;
}

void GstreamerPlugin::ParseOptions(const ConfigureOption *options)
{
    for (; options->name; ++options) {
        const std::string name = options->name;
        const std::string value = options->value;

        if (name == "framerate") {
            try {
                settings.fps = std::stoi(value);
            } catch (const std::exception &e) {
                throw std::runtime_error("Invalid value '" + value + "' for option 'framerate'.");
            }
        } else if (name == "gst.codec") {
            if (value == "h264") {
                settings.codec = SPICE_VIDEO_CODEC_TYPE_H264;
            } else if (value == "vp9") {
                settings.codec = SPICE_VIDEO_CODEC_TYPE_VP9;
            } else if (value == "vp8") {
                settings.codec = SPICE_VIDEO_CODEC_TYPE_VP8;
            } else if (value == "mjpeg") {
                settings.codec = SPICE_VIDEO_CODEC_TYPE_MJPEG;
            } else if (value == "h265") {
                settings.codec = SPICE_VIDEO_CODEC_TYPE_H265;
            } else {
                throw std::runtime_error("Invalid value '" + value + "' for option 'gst.codec'.");
            }
        } else if (name == "gst.encoder") {
            settings.encoder = value;
451 452 453 454 455 456 457
        } else if (name == "gst.prop") {
            size_t pos = value.find('=');
            if (pos == 0 || pos >= value.size() - 1) {
                gst_syslog(LOG_WARNING, "Property input is invalid ('%s' Ignored)", value.c_str());
                continue;
            }
            settings.prop_pairs.push_back(make_pair(value.substr(0, pos), value.substr(pos + 1)));
458 459 460 461 462 463 464 465 466 467 468 469
        }
    }
}

}}} //namespace spice::streaming_agent::gstreamer_plugin

using namespace spice::streaming_agent::gstreamer_plugin;

SPICE_STREAMING_AGENT_PLUGIN(agent)
{
    gst_init(nullptr, nullptr);

470
    auto plugin = std::make_shared<GstreamerPlugin>();
471 472 473

    plugin->ParseOptions(agent->Options());

474
    agent->Register(plugin);
475 476 477

    return true;
}