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
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
// This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.
//
// Copyright (C) 2021 Intel Corporation

#include "gstreamer_buffer_utils.hpp"

#include "gstreamer_media_adapter.hpp"

#include "gstreamersource_priv.hpp"
#include <opencv2/gapi/streaming/gstreamer/gstreamersource.hpp>

#include <opencv2/gapi/streaming/meta.hpp>

#include <logger.hpp>

#include <opencv2/imgproc.hpp>

#ifdef HAVE_GSTREAMER
#include <gst/app/gstappsink.h>
#include <gst/gstbuffer.h>
#include <gst/video/video-frame.h>
#endif // HAVE_GSTREAMER

namespace cv {
namespace gapi {
namespace wip {
namespace gst {

#ifdef HAVE_GSTREAMER

constexpr char ALLOWED_CAPS_STRING[] =
    "video/x-raw,format=(string){NV12, GRAY8};video/x-raw(memory:DMABuf),format=(string){NV12, GRAY8}";


namespace {
GstPadProbeReturn appsinkQueryCallback(GstPad*, GstPadProbeInfo* info, gpointer)

{
    GstQuery *query = GST_PAD_PROBE_INFO_QUERY(info);

    if (GST_QUERY_TYPE(query) != GST_QUERY_ALLOCATION)
        return GST_PAD_PROBE_OK;

    gst_query_add_allocation_meta(query, GST_VIDEO_META_API_TYPE, NULL);

    return GST_PAD_PROBE_HANDLED;
}
} // anonymous namespace

GStreamerSource::Priv::Priv(const std::string& pipelineDesc,
                            const GStreamerSource::OutputType outputType) :
    m_pipeline(std::make_shared<GStreamerPipelineFacade>(pipelineDesc)),
    m_outputType(outputType)
{
    GAPI_Assert((m_outputType == GStreamerSource::OutputType::FRAME ||
                 m_outputType == GStreamerSource::OutputType::MAT)
                && "Unsupported output type for GStreamerSource!");

    auto appsinks = m_pipeline->getElementsByFactoryName("appsink");
    GAPI_Assert(1ul == appsinks.size() &&
        "GStreamerSource can accept pipeline with only 1 appsink element inside!\n"
        "Please, note, that amount of sink elements of other than appsink type is not limited.\n");

    m_appsink = GST_ELEMENT(gst_object_ref(appsinks[0]));

    configureAppsink();
}

GStreamerSource::Priv::Priv(std::shared_ptr<GStreamerPipelineFacade> pipeline,
                            const std::string& appsinkName,
                            const GStreamerSource::OutputType outputType) :
    m_pipeline(pipeline),
    m_outputType(outputType)
{
    GAPI_Assert((m_outputType == GStreamerSource::OutputType::FRAME ||
                 m_outputType == GStreamerSource::OutputType::MAT)
                && "Unsupported output type for GStreamerSource!");

    m_appsink = (GST_ELEMENT(gst_object_ref(m_pipeline->getElementByName(appsinkName))));
    configureAppsink();
}

bool GStreamerSource::Priv::pull(cv::gapi::wip::Data& data)
{
    bool result = false;
    switch(m_outputType) {
        case GStreamerSource::OutputType::FRAME: {
            cv::MediaFrame frame;
            result = retrieveFrame(frame);
            if (result) {
                data = frame;
            }
            break;
        }
        case GStreamerSource::OutputType::MAT: {
            cv::Mat mat;
            result = retrieveFrame(mat);
            if (result) {
                data = mat;
            }
            break;
        }
    }

    if (result) {
        data.meta[cv::gapi::streaming::meta_tag::timestamp] = computeTimestamp();
        data.meta[cv::gapi::streaming::meta_tag::seq_id]    = m_frameId++;
    }

    return result;
}

GMetaArg GStreamerSource::Priv::descr_of() noexcept
{
    // Prepare frame metadata if it wasn't prepared yet.
    prepareVideoMeta();

    switch(m_outputType) {
        case GStreamerSource::OutputType::FRAME: {
            return GMetaArg { m_mediaFrameMeta };
        }
        case GStreamerSource::OutputType::MAT: {
            return GMetaArg { m_matMeta };
        }
    }

    return GMetaArg { };
}

void GStreamerSource::Priv::configureAppsink() {
    // NOTE: appsink element should be configured before pipeline launch.
    GAPI_Assert(!m_pipeline->isPlaying());

    // TODO: is 1 single buffer really high enough?
    gst_app_sink_set_max_buffers(GST_APP_SINK(m_appsink.get()), 1);

    // Do not emit signals: all calls will be synchronous and blocking.
    gst_app_sink_set_emit_signals(GST_APP_SINK(m_appsink.get()), FALSE);

    GStreamerPtr<GstCaps> gstCaps(gst_caps_from_string(ALLOWED_CAPS_STRING));

    GStreamerPtr<GstPad> appsinkPad(gst_element_get_static_pad(m_appsink, "sink"));
    GStreamerPtr<GstCaps> peerCaps(gst_pad_peer_query_caps(appsinkPad, NULL));
    if (!gst_caps_can_intersect(peerCaps, gstCaps)) {
        cv::util::throw_error(
            std::logic_error("appsink element can only consume video-frame in NV12 or GRAY8 format in "
                             "GStreamerSource"));
    }

    gst_app_sink_set_caps(GST_APP_SINK(m_appsink.get()), gstCaps);

    gst_pad_add_probe(appsinkPad, GST_PAD_PROBE_TYPE_QUERY_DOWNSTREAM, appsinkQueryCallback,
                      NULL, NULL);
}

void GStreamerSource::Priv::prepareVideoMeta()
{
    if (!m_isMetaPrepared) {
        m_pipeline->completePreroll();

        GStreamerPtr<GstSample> prerollSample(

#if GST_VERSION_MINOR >= 10

            gst_app_sink_try_pull_preroll(GST_APP_SINK(m_appsink.get()), 5 * GST_SECOND));
#else // GST_VERSION_MINOR < 10
            // TODO: This function may cause hang with some pipelines, need to check whether these
            // pipelines are really wrong or not?
            gst_app_sink_pull_preroll(GST_APP_SINK(m_appsink.get())));
#endif // GST_VERSION_MINOR >= 10
        GAPI_Assert(prerollSample != nullptr);

        GstCaps* prerollCaps(gst_sample_get_caps(prerollSample));
        GAPI_Assert(prerollCaps != nullptr);

        const GstStructure* structure = gst_caps_get_structure(prerollCaps, 0);

        // Width and height held in GstCaps structure are format-independent width and height
        // of the frame. So the actual height of the output buffer in NV12 format will be
        // height * 3/2.
        int width = 0;
        int height = 0;
        if (!gst_structure_get_int(structure, "width", &width) ||
            !gst_structure_get_int(structure, "height", &height))
        {
            cv::util::throw_error(std::logic_error("Cannot query video width/height."));
        }

        // Fill GstVideoInfo structure to work further with GstVideoFrame class.
        if (!gst_video_info_from_caps(&m_videoInfo, prerollCaps)) {
            cv::util::throw_error(std::logic_error("preroll sample has invalid caps."));
        }
        m_type = GST_VIDEO_INFO_FORMAT(&m_videoInfo);
        switch(m_outputType) {
            case GStreamerSource::OutputType::FRAME: {
                // Construct metadata for media frame.
                switch (m_type) {
                    case GST_VIDEO_FORMAT_NV12: {
                        m_mediaFrameMeta = GFrameDesc{ cv::MediaFormat::NV12, cv::Size(width, height) };
                        GAPI_Assert(GST_VIDEO_INFO_N_PLANES(&m_videoInfo) == 2);
                        break;
                    }
                    case GST_VIDEO_FORMAT_GRAY8: {
                        m_mediaFrameMeta = GFrameDesc{ cv::MediaFormat::GRAY, cv::Size(width, height) };
                        GAPI_Assert(GST_VIDEO_INFO_N_PLANES(&m_videoInfo) == 1);
                        break;
                    }
                    default: {
                        GAPI_Error("Unsupported GStreamerSource FRAME type.");
                    }
                }
                break;
            }
            case GStreamerSource::OutputType::MAT: {
                // Construct metadata for BGR mat.
                m_matMeta = GMatDesc { CV_8U, 3, cv::Size(width, height), false };
                break;
            }
        }

        m_isMetaPrepared = true;
    }
}

int64_t GStreamerSource::Priv::computeTimestamp()
{
    GAPI_Assert(m_buffer && "Pulled buffer is nullptr!");

    int64_t timestamp { };

    GstClockTime pts = GST_BUFFER_PTS(m_buffer);
    if (GST_CLOCK_TIME_IS_VALID(pts)) {
        timestamp = GST_TIME_AS_USECONDS(pts);
    } else {
        const auto now = std::chrono::system_clock::now();
        const auto dur = std::chrono::duration_cast<std::chrono::microseconds>
            (now.time_since_epoch());
        timestamp = int64_t{dur.count()};
    }

    return timestamp;
}

bool GStreamerSource::Priv::pullBuffer()
{
    // Start the pipeline if it is not in the playing state yet
    if (!m_isPipelinePlaying) {
        m_pipeline->play();
        m_isPipelinePlaying = true;
    }

    // Bail out if EOS
    if (gst_app_sink_is_eos(GST_APP_SINK(m_appsink.get())))
    {
        return false;
    }

    m_sample = gst_app_sink_pull_sample(GST_APP_SINK(m_appsink.get()));

    // TODO: GAPI_Assert because of already existed check for EOS?
    if (m_sample == nullptr)
    {
        return false;
    }

    m_buffer = gst_sample_get_buffer(m_sample);
    GAPI_Assert(m_buffer && "Grabbed sample has no buffer!");

    return true;
}

bool GStreamerSource::Priv::retrieveFrame(cv::Mat& data)
{
    // Prepare metadata if it isn't prepared yet.
    prepareVideoMeta();

    bool result = pullBuffer();
    if (!result)
    {
        return false;
    }

    // TODO: Use RAII for map/unmap
    GstVideoFrame videoFrame;
    gstreamer_utils::mapBufferToFrame(*m_buffer, m_videoInfo, videoFrame, GST_MAP_READ);

    try
    {
        switch (m_type) {
            case GST_VIDEO_FORMAT_NV12: {
                // m_matMeta holds width and height for 8U BGR frame, but actual
                // frame m_buffer we request from GStreamer pipeline has 8U NV12 format.
                // Constructing y and uv cv::Mat-s from such a m_buffer:
                GAPI_Assert((uint8_t*)GST_VIDEO_FRAME_PLANE_DATA(&videoFrame, 1) ==
                    (uint8_t*)GST_VIDEO_FRAME_PLANE_DATA(&videoFrame, 0) +
                    GST_VIDEO_FRAME_PLANE_OFFSET(&videoFrame, 1));
                GAPI_Assert(GST_VIDEO_INFO_N_PLANES(&m_videoInfo) == 2);

                cv::Mat y(m_matMeta.size, CV_8UC1,

                    (uint8_t*)GST_VIDEO_FRAME_PLANE_DATA(&videoFrame, 0) +

                    GST_VIDEO_FRAME_PLANE_OFFSET(&videoFrame, 0),

                    GST_VIDEO_FRAME_PLANE_STRIDE(&videoFrame, 0));
                cv::Mat uv(m_matMeta.size / 2, CV_8UC2,

                    (uint8_t*)GST_VIDEO_FRAME_PLANE_DATA(&videoFrame, 0) +

                    GST_VIDEO_FRAME_PLANE_OFFSET(&videoFrame, 1),

                    GST_VIDEO_FRAME_PLANE_STRIDE(&videoFrame, 1));

                cv::cvtColorTwoPlane(y, uv, data, cv::COLOR_YUV2BGR_NV12);
                break;
            }
            case GST_VIDEO_FORMAT_GRAY8: {
                GAPI_Assert(GST_VIDEO_INFO_N_PLANES(&m_videoInfo) == 1);
                cv::Mat y(m_matMeta.size, CV_8UC1,

                    (uint8_t*)GST_VIDEO_FRAME_PLANE_DATA(&videoFrame, 0) +

                    GST_VIDEO_FRAME_PLANE_OFFSET(&videoFrame, 0),

                    GST_VIDEO_FRAME_PLANE_STRIDE(&videoFrame, 0));
                cv::cvtColor(y, data, cv::COLOR_GRAY2BGR);
                break;
            }
            default: {
                GAPI_Error("retrieveFrame - unsupported GStreamerSource FRAME type.");
            }
        }
    }
    catch (...)
    {
        gst_video_frame_unmap(&videoFrame);
        cv::util::throw_error(std::runtime_error("NV12 or GRAY8 buffer conversion to BGR is failed!"));
    }
    gst_video_frame_unmap(&videoFrame);

    return true;
}

bool GStreamerSource::Priv::retrieveFrame(cv::MediaFrame& data)
{
    // Prepare metadata if it isn't prepared yet.
    prepareVideoMeta();

    bool result = pullBuffer();
    if (!result)
    {
        return false;
    }

    data = cv::MediaFrame::Create<GStreamerMediaAdapter>(m_mediaFrameMeta, &m_videoInfo,
                                                         m_buffer);

    return true;
}

GStreamerSource::Priv::~Priv() { }

#else // HAVE_GSTREAMER

GStreamerSource::Priv::Priv(const std::string&, const GStreamerSource::OutputType)
{
    GAPI_Error("Built without GStreamer support!");
}

GStreamerSource::Priv::Priv(std::shared_ptr<GStreamerPipelineFacade>, const std::string&,
                            const GStreamerSource::OutputType)
{
    GAPI_Error("Built without GStreamer support!");
}

bool GStreamerSource::Priv::pull(cv::gapi::wip::Data&)
{
    // No need an assert here. Constructor have already got assert.
    return false;
}

GMetaArg GStreamerSource::Priv::descr_of() const noexcept
{
    // No need an assert here. The assert raise C4702 warning. Constructor have already got assert.
    return GMetaArg{};
}

GStreamerSource::Priv::~Priv()
{
    // No need an assert here. The assert raise C4722 warning. Constructor have already got assert.
}

#endif // HAVE_GSTREAMER

GStreamerSource::GStreamerSource(const std::string& pipeline,
                                 const GStreamerSource::OutputType outputType):
    m_priv(new Priv(pipeline, outputType)) { }

GStreamerSource::GStreamerSource(std::shared_ptr<GStreamerPipelineFacade> pipeline,
                                 const std::string& appsinkName,
                                 const GStreamerSource::OutputType outputType):
    m_priv(new Priv(pipeline, appsinkName, outputType)) { }

bool GStreamerSource::pull(cv::gapi::wip::Data& data)

{
    return m_priv->pull(data);
}

GMetaArg GStreamerSource::descr_of() const

{
    return m_priv->descr_of();
}

GStreamerSource::~GStreamerSource()
{ }

GStreamerSource::GStreamerSource(std::unique_ptr<Priv> priv):
    m_priv(std::move(priv))
{ }

} // namespace gst
} // namespace wip
} // namespace gapi
} // namespace cv