giebackend.cpp 87.5 KB
Newer Older
1 2 3 4
// 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.
//
5
// Copyright (C) 2018-2022 Intel Corporation
6 7 8

#include "precomp.hpp"

9 10 11 12
// needs to be included regardless if IE is present or not
// (cv::gapi::ie::backend() is still there and is defined always)
#include "backends/ie/giebackend.hpp"

13 14
#ifdef HAVE_INF_ENGINE

15
#if INF_ENGINE_RELEASE <= 2019010000
16 17 18 19 20
#   error G-API IE module supports only OpenVINO IE >= 2019 R1
#endif

#include <functional>
#include <unordered_set>
21
#include <atomic>
22 23
#include <tuple>

24 25 26 27 28 29 30 31

#include <ade/util/algorithm.hpp>

#include <ade/util/range.hpp>
#include <ade/util/zip_range.hpp>
#include <ade/util/chain_range.hpp>
#include <ade/typed_graph.hpp>

32 33 34
#include <opencv2/core/utility.hpp>
#include <opencv2/core/utils/logger.hpp>

35 36
#include <opencv2/gapi/gcommon.hpp>
#include <opencv2/gapi/garray.hpp>
37
#include <opencv2/gapi/gopaque.hpp>
38 39 40
#include <opencv2/gapi/util/any.hpp>
#include <opencv2/gapi/gtype_traits.hpp>
#include <opencv2/gapi/infer.hpp>
41
#include <opencv2/gapi/own/convert.hpp>
42
#include <opencv2/gapi/gframe.hpp>
43 44 45 46

#include "compiler/gobjref.hpp"
#include "compiler/gmodel.hpp"

47
#include "backends/ie/util.hpp"
48
#include "backends/ie/giebackend/giewrapper.hpp"
49 50

#include "api/gbackend_priv.hpp" // FIXME: Make it part of Backend SDK!
51
#include "logger.hpp"
52

53 54 55 56
#if INF_ENGINE_RELEASE < 2021010000
#include "ie_compound_blob.h"
#endif

57 58 59 60 61 62 63 64
#if defined(HAVE_TBB)
#  include <tbb/concurrent_queue.h> // FIXME: drop it from here!
template<typename T> using QueueClass = tbb::concurrent_bounded_queue<T>;
#else
#  include "executor/conc_queue.hpp"
template<typename T> using QueueClass = cv::gapi::own::concurrent_bounded_queue<T>;
#endif // TBB

65 66
#include "utils/itt.hpp"

67 68 69
#include "streaming/onevpl/engine/preproc_engine_interface.hpp"
#include "streaming/onevpl/engine/preproc/preproc_dispatcher.hpp"

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
namespace IE = InferenceEngine;

namespace {

inline IE::ROI toIE(const cv::Rect &rc) {
    return IE::ROI
        { 0u
        , static_cast<std::size_t>(rc.x)
        , static_cast<std::size_t>(rc.y)
        , static_cast<std::size_t>(rc.width)
        , static_cast<std::size_t>(rc.height)
        };
}

inline IE::SizeVector toIE(const cv::MatSize &sz) {
    return cv::to_own<IE::SizeVector::value_type>(sz);
}
inline std::vector<int> toCV(const IE::SizeVector &vsz) {
    std::vector<int> result;
    result.reserve(vsz.size());
    for (auto sz : vsz) {
        result.push_back(ade::util::checked_cast<int>(sz));
    }
    return result;
}

96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
inline IE::Layout toIELayout(const std::size_t ndims) {
    static const IE::Layout lts[] = {
        IE::Layout::SCALAR,
        IE::Layout::C,
        IE::Layout::NC,
        IE::Layout::CHW,
        IE::Layout::NCHW,
        IE::Layout::NCDHW,
    };
    // FIXME: This is not really a good conversion,
    // since it may also stand for NHWC/HW/CN/NDHWC data
    CV_Assert(ndims < sizeof(lts) / sizeof(lts[0]));
    return lts[ndims];
}

111 112 113
inline IE::Precision toIE(int depth) {
    switch (depth) {
    case CV_8U:  return IE::Precision::U8;
114
    case CV_32S: return IE::Precision::I32;
115
    case CV_32F: return IE::Precision::FP32;
116
    case CV_16F: return IE::Precision::FP16;
117
    default:     GAPI_Error("IE. Unsupported data type");
118 119 120 121 122 123 124
    }
    return IE::Precision::UNSPECIFIED;
}
inline int toCV(IE::Precision prec) {
    switch (prec) {
    case IE::Precision::U8:   return CV_8U;
    case IE::Precision::FP32: return CV_32F;
125
    case IE::Precision::I32:  return CV_32S;
126
    case IE::Precision::I64:  return CV_32S;
127
    case IE::Precision::FP16: return CV_16F;
128
    default:     GAPI_Error("IE. Unsupported data type");
129 130 131 132
    }
    return -1;
}

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
// NB: In short: Tensor - ND or 2D + precision != U8.
cv::gapi::ie::TraitAs clarifyTrait(const cv::GMatDesc   &mat_desc,
                                   const IE::TensorDesc &tensor_desc) {
    // NB: This check does not include 2D matrices like {32, 16},
    // which also falls under the category of tensors.
    // The reason for this is that RGB images are also considered 2D
    // as the channel component is not taken into account in this case.
    if (mat_desc.isND() || mat_desc.planar) {
        return cv::gapi::ie::TraitAs::TENSOR;
    }
    // NB: If user provided 2D data in U8 precision
    // and network expects NHWC/NCHW layout - data is image (most likely).
    const auto layout = tensor_desc.getLayout();
    if (layout == IE::Layout::NCHW || layout == IE::Layout::NHWC) {
        if (mat_desc.depth == CV_8U) {
            return cv::gapi::ie::TraitAs::IMAGE;
        }
        // NB: 2D data with precision != U8 provided for 4D layout.
        std::stringstream ss;
        ss << "IE Backend: An inconsistency has been detected between"
              " the provided data: " << mat_desc <<
              " and the network layout: " << layout;
        cv::util::throw_error(std::logic_error(ss.str()));
    }
    // NB: Otherwise trait is TENSOR.
    // If there is an inconsistency between the data dimensions
    // and the network layout, the "setBlob" will fail.
    return cv::gapi::ie::TraitAs::TENSOR;
}

cv::gapi::ie::TraitAs clarifyTrait(const cv::GMetaArg   &meta,
                                   const IE::TensorDesc &tensor_desc) {
    // NB: All media formats: BGR, NV12, Gray
    // are traited as image.
    if (cv::util::holds_alternative<cv::GFrameDesc>(meta)) {
        return cv::gapi::ie::TraitAs::IMAGE;
    }
    GAPI_Assert(cv::util::holds_alternative<cv::GMatDesc>(meta));
    return clarifyTrait(cv::util::get<cv::GMatDesc>(meta), tensor_desc);
}

174
inline IE::TensorDesc toIE(const cv::Mat &mat, cv::gapi::ie::TraitAs hint) {
175 176 177
    const auto &sz = mat.size;
    // NB: For some reason RGB image is 2D image
    // (since channel component is not counted here).
178 179 180
    // Note: regular 2D vectors also fall into this category
    if (sz.dims() == 2 && hint == cv::gapi::ie::TraitAs::IMAGE)
    {
181 182 183 184 185
        // NB: This logic is mainly taken from IE samples
        const size_t channels = mat.channels();
        const size_t height   = mat.size().height;
        const size_t width    = mat.size().width;

A
Anatoliy Talamanov 已提交
186
        const size_t strideH  = mat.step1();
A
Anatoliy Talamanov 已提交
187
        IE::BlockingDesc bdesc({1, height, width, channels} /* blocking dims */,
A
Anatoliy Talamanov 已提交
188 189
                               {0, 2, 3, 1} /* order for NHWC   */,
                               0            /* offset           */,
A
Anastasiya Pronina 已提交
190 191
                               {0, 0, 0, 0} /* offsets for dims */,
                               {strideH * height, strideH, channels, 1} /* strides for dims */);
192 193

        return IE::TensorDesc(toIE(mat.depth()),
A
Anastasiya Pronina 已提交
194
                              IE::SizeVector{1, channels, height, width}, bdesc);
195
    }
196
    return IE::TensorDesc(toIE(mat.depth()), toIE(sz), toIELayout(sz.dims()));
197 198
}

199 200
inline IE::Blob::Ptr wrapIE(const cv::Mat &mat, cv::gapi::ie::TraitAs hint) {
    const auto tDesc = toIE(mat, hint);
201 202 203 204 205 206 207
    switch (mat.depth()) {
        // NB: Seems there's no way to create an untyped (T-less) Blob::Ptr
        // in IE given only precision via TensorDesc. So we have to do this:
#define HANDLE(E,T) \
        case CV_##E: return IE::make_shared_blob<T>(tDesc, const_cast<T*>(mat.ptr<T>()))
        HANDLE(8U, uint8_t);
        HANDLE(32F, float);
208
        HANDLE(32S, int);
209
        HANDLE(16F, int16_t);
210
#undef HANDLE
211
    default: GAPI_Error("IE. Unsupported data type");
212 213 214 215
    }
    return IE::Blob::Ptr{};
}

216 217 218 219 220 221 222 223 224 225 226 227 228
inline IE::Blob::Ptr wrapIE(const cv::MediaFrame::View& view,
                            const cv::GFrameDesc& desc) {

    switch (desc.fmt) {
        case cv::MediaFormat::BGR: {
            auto bgr = cv::Mat(desc.size, CV_8UC3, view.ptr[0], view.stride[0]);
            return wrapIE(bgr, cv::gapi::ie::TraitAs::IMAGE);
        }
        case cv::MediaFormat::NV12: {
            auto y_plane  = cv::Mat(desc.size, CV_8UC1, view.ptr[0], view.stride[0]);
            auto uv_plane = cv::Mat(desc.size / 2, CV_8UC2, view.ptr[1], view.stride[1]);
            return cv::gapi::ie::util::to_ie(y_plane, uv_plane);
        }
229 230 231 232
        case cv::MediaFormat::GRAY: {
            auto gray = cv::Mat(desc.size, CV_8UC1, view.ptr[0], view.stride[0]);
            return wrapIE(gray, cv::gapi::ie::TraitAs::IMAGE);
        }
233
        default:
234
            GAPI_Error("Unsupported media format for IE backend");
235
    }
236
    GAPI_Error("InternalError");
237 238
}

239 240
template<class MatType>
inline void copyFromIE(const IE::Blob::Ptr &blob, MatType &mat) {
T
TolyaTalamanov 已提交
241 242 243 244
    const auto& desc = blob->getTensorDesc();
    const auto ie_type = toCV(desc.getPrecision());
    if (ie_type != mat.type()) {
        std::stringstream ss;
T
TolyaTalamanov 已提交
245 246 247 248
        ss << "Failed to copy blob from IE to OCV: "
           << "Blobs have different data types "
           << "(IE type: " << ie_type
           << " vs OCV type: " << mat.type() << ")." << std::endl;
T
TolyaTalamanov 已提交
249 250
        throw std::logic_error(ss.str());
    }
251 252 253 254 255 256 257 258
    switch (blob->getTensorDesc().getPrecision()) {
#define HANDLE(E,T)                                                 \
        case IE::Precision::E: std::copy_n(blob->buffer().as<T*>(), \
                                           mat.total(),             \
                                           reinterpret_cast<T*>(mat.data)); \
            break;
        HANDLE(U8, uint8_t);
        HANDLE(FP32, float);
259
        HANDLE(I32, int);
260
        HANDLE(FP16, cv::float16_t);
261
#undef HANDLE
262 263 264 265 266 267 268
        case IE::Precision::I64: {
            GAPI_LOG_WARNING(NULL, "INT64 isn't supported for cv::Mat. Conversion to INT32 is used.");
            cv::gimpl::convertInt64ToInt32(blob->buffer().as<int64_t*>(),
                                           reinterpret_cast<int*>(mat.data),
                                           mat.total());
            break;
        }
269
    default: GAPI_Error("IE. Unsupported data type");
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
template <typename MapT>
void checkLayerNames(const MapT&                     network_map,
                     const std::vector<std::string>& layer_names,
                     const std::string&              layer_type) {
    for (const auto& layer_name : layer_names) {
        const auto it = network_map.find(layer_name);
        if (it == network_map.end()) {
            std::stringstream ss;
            ss << "Failed to find " << layer_type << " layer with name: "
               << "\"" << layer_name << "\"" << std::endl;
            ss << "Network " << layer_type << " layers: " << std::endl;
            for (const auto& p : network_map) {
                const auto& desc = p.second->getTensorDesc();
                ss << p.first << " : " << desc.getPrecision()
                   << " / " << desc.getLayout() << std::endl;
            }
            throw std::logic_error(ss.str());
        }
    }
}

template <typename MapT>
void checkInputLayerNames(const MapT&                     network_map,
                          const std::vector<std::string>& layer_names) {
    checkLayerNames(network_map, layer_names, "input");
}

template <typename MapT>
void checkOutputLayerNames(const MapT&                     network_map,
                          const std::vector<std::string>& layer_names) {
    checkLayerNames(network_map, layer_names, "output");
}

306 307 308 309 310 311 312
// IE-specific metadata, represents a network with its parameters
struct IEUnit {
    static const char *name() { return "IEModelConfig"; }

    cv::gapi::ie::detail::ParamDesc params;
    IE::CNNNetwork net;

313 314 315
    IE::ExecutableNetwork this_network;
    cv::gimpl::ie::wrap::Plugin this_plugin;

316 317
    InferenceEngine::RemoteContext::Ptr rctx = nullptr;

318 319
    std::shared_ptr<cv::gapi::wip::IPreprocEngine> preproc_engine_impl;

320 321 322 323 324 325
    // FIXME: Unlike loadNetwork case, importNetwork requires that preprocessing
    // should be passed as ExecutableNetwork::SetBlob method, so need to collect
    // and store this information at the graph compilation stage (outMeta) and use in runtime.
    using PreProcMap = std::unordered_map<std::string, IE::PreProcessInfo>;
    PreProcMap preproc_map;

326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
    // NEW FIXME: Need to aggregate getInputInfo & GetInputInfo from network
    // into generic wrapper and invoke it at once in single place instead of
    // analyzing ParamDesc::Kind::Load/Import every time when we need to get access
    // for network info.
    // In term of introducing custom VPP/VPL preprocessing functionality
    // It was decided to use GFrameDesc as such aggregated network info with limitation
    // that VPP/VPL produces cv::MediaFrame only. But it should be not considered as
    // final solution
    class InputFramesDesc {
        using input_name_type = std::string;
        using description_type = cv::GFrameDesc;
        std::map<input_name_type, description_type> map;
    public:
        static bool is_applicable(const cv::GMetaArg &mm);
        const description_type &get_param(const input_name_type &input) const;

        void set_param(const input_name_type &input,
                       const IE::TensorDesc& desc);
    };

    InputFramesDesc net_input_params;

348 349
    explicit IEUnit(const cv::gapi::ie::detail::ParamDesc &pp)
        : params(pp) {
350 351 352 353
        InferenceEngine::ParamMap* ctx_params =
                            cv::util::any_cast<InferenceEngine::ParamMap>(&params.context_config);
        if (ctx_params != nullptr) {
            auto ie_core = cv::gimpl::ie::wrap::getCore();
354
            GAPI_LOG_DEBUG(nullptr, "create IE remote ctx for device id: " << params.device_id);
355 356 357
            rctx = ie_core.CreateContext(params.device_id, *ctx_params);
        }

358 359
        if (params.kind == cv::gapi::ie::detail::ParamDesc::Kind::Load) {
            net = cv::gimpl::ie::wrap::readNetwork(params);
360 361 362 363
            // NB: Set batch size only if user asked. (don't set by default)
            if (params.batch_size.has_value())  {
                net.setBatchSize(params.batch_size.value());
            }
364
        } else if (params.kind == cv::gapi::ie::detail::ParamDesc::Kind::Import) {
365
            this_plugin = cv::gimpl::ie::wrap::getPlugin(params);
366
            this_network = cv::gimpl::ie::wrap::importNetwork(this_plugin, params, rctx);
367 368 369
            if (!params.reshape_table.empty() || !params.layer_names_to_reshape.empty()) {
                GAPI_LOG_WARNING(NULL, "Reshape isn't supported for imported network");
            }
370 371 372 373
        } else {
            cv::util::throw_error(std::logic_error("Unsupported ParamDesc::Kind"));
        }

374 375 376
        // The practice shows that not all inputs and not all outputs
        // are mandatory to specify in IE model.
        // So what we're concerned here about is:
B
Brian Wignall 已提交
377
        // if operation's (not topology's) input/output number is
378 379 380 381 382 383 384 385 386 387 388 389
        // greater than 1, then we do care about input/output layer
        // names. Otherwise, names are picked up automatically.
        // TODO: Probably this check could be done at the API entry point? (gnet)
        if (params.num_in > 1u && params.num_in != params.input_names.size()) {
            cv::util::throw_error(std::logic_error("Please specify input layer names for "
                                                   + params.model_path));
        }
        if (params.num_out > 1u && params.num_out != params.output_names.size()) {
            cv::util::throw_error(std::logic_error("Please specify output layer names for "
                                                   + params.model_path));
        }
        if (params.num_in == 1u && params.input_names.empty()) {
390
            if (params.kind == cv::gapi::ie::detail::ParamDesc::Kind::Load) {
391
                params.input_names = { net.getInputsInfo().begin()->first };
392 393 394
            } else {
                params.input_names = { this_network.GetInputsInfo().begin()->first };
            }
395 396
        }
        if (params.num_out == 1u && params.output_names.empty()) {
397
            if (params.kind == cv::gapi::ie::detail::ParamDesc::Kind::Load) {
398
                params.output_names = { net.getOutputsInfo().begin()->first };
399 400 401
            } else {
                params.output_names = { this_network.GetOutputsInfo().begin()->first };
            }
402
        }
403 404 405 406 407
        if (!params.reshape_table.empty()) {
            GAPI_Assert((params.reshape_table.size() + params.layer_names_to_reshape.size()) <=
                         params.num_in &&
                        "Number of layers to reshape must be less than or equal to number of inputs");
        }
408 409 410 411 412 413 414 415 416 417

        if (params.kind == cv::gapi::ie::detail::ParamDesc::Kind::Load) {
            checkInputLayerNames(net.getInputsInfo(), params.input_names);
            checkOutputLayerNames(net.getOutputsInfo(), params.output_names);
        } else if (params.kind == cv::gapi::ie::detail::ParamDesc::Kind::Import) {
            checkInputLayerNames(this_network.GetInputsInfo(), params.input_names);
            checkOutputLayerNames(this_network.GetOutputsInfo(), params.output_names);
        } else {
            cv::util::throw_error(std::logic_error("Unsupported ParamDesc::Kind"));
        }
418

T
TolyaTalamanov 已提交
419 420 421 422 423 424 425
        if (params.kind == cv::gapi::ie::detail::ParamDesc::Kind::Import &&
            !cv::util::holds_alternative<cv::util::monostate>(params.output_precision)) {
            cv::util::throw_error(
                    std::logic_error("Setting output precision isn't supported for imported network"));
        }


426 427 428 429 430 431 432 433 434 435
        using namespace cv::gapi::wip::onevpl;
        if (params.vpl_preproc_device.has_value() && params.vpl_preproc_ctx.has_value()) {
            using namespace cv::gapi::wip;
            GAPI_LOG_INFO(nullptr, "VPP preproc creation requested");
            preproc_engine_impl =
                IPreprocEngine::create_preproc_engine<onevpl::VPPPreprocDispatcher>(
                                    params.vpl_preproc_device.value(),
                                    params.vpl_preproc_ctx.value());
            GAPI_LOG_INFO(nullptr, "VPP preproc created successfuly");
        }
436

T
TolyaTalamanov 已提交
437
        if (params.mode == cv::gapi::ie::InferMode::Sync &&
438 439
            params.nireq != 1u) {
            throw std::logic_error(
T
TolyaTalamanov 已提交
440
                    "Failed: cv::gapi::ie::InferMode::Sync works only with nireq equal to 1.");
441
        }
442 443 444 445
    }

    // This method is [supposed to be] called at Island compilation stage
    cv::gimpl::ie::IECompiled compile() const {
446
        IEUnit* non_const_this = const_cast<IEUnit*>(this);
447 448 449
        // FIXME: LoadNetwork must be called only after all necessary model
        // inputs information is set, since it's done in outMeta and compile called after that,
        // this place seems to be suitable, but consider another place not to break const agreements.
450 451
        if (params.kind == cv::gapi::ie::detail::ParamDesc::Kind::Load) {
            non_const_this->this_plugin  = cv::gimpl::ie::wrap::getPlugin(params);
452 453
            non_const_this->this_network = cv::gimpl::ie::wrap::loadNetwork(non_const_this->this_plugin,
                                                                            net, params, rctx);
454
        }
455

456
        return {params, this_plugin, this_network};
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
bool IEUnit::InputFramesDesc::is_applicable(const cv::GMetaArg &mm) {
    return cv::util::holds_alternative<cv::GFrameDesc>(mm);
}

const IEUnit::InputFramesDesc::description_type &
IEUnit::InputFramesDesc::get_param(const input_name_type &input) const {
    auto it = map.find(input);
    GAPI_Assert(it != map.end() && "No appropriate input is found in InputFramesDesc");
    return it->second;
}

void IEUnit::InputFramesDesc::set_param(const input_name_type &input,
                                        const IE::TensorDesc& desc) {
    description_type ret;
    ret.fmt = cv::MediaFormat::NV12;
    const InferenceEngine::SizeVector& inDims = desc.getDims();
    auto layout = desc.getLayout();
    GAPI_LOG_DEBUG(nullptr, "network input: " << input <<
                            ", tensor dims: " << inDims[0] << ", " << inDims[1] <<
                             ", " << inDims[2] << ", " << inDims[3]);
    if (layout != InferenceEngine::NHWC && layout != InferenceEngine::NCHW) {
        GAPI_LOG_WARNING(nullptr, "Unsupported layout for VPP preproc: " << layout <<
                                  ", input name: " << input);
483
        GAPI_Error("Unsupported layout for VPP preproc");
484 485 486 487 488 489 490 491 492
    }
    GAPI_Assert(inDims.size() == 4u);
    ret.size.width = static_cast<int>(inDims[3]);
    ret.size.height = static_cast<int>(inDims[2]);

    auto res = map.emplace(input, ret);
    GAPI_Assert(res.second && "Duplicated input info in InputFramesDesc are not allowable");
}

493
class IECallContext
494
{
495 496 497 498 499
public:
    IECallContext(const IEUnit                                      &  unit,
                  cv::gimpl::GIslandExecutable::IOutput             &  output,
                  const cv::GArgs                                   &  args,
                  const std::vector<cv::gimpl::RcDesc>              &  outs,
500
                  cv::GRunArg::Meta                                 && meta,
501 502
                  std::vector<cv::gimpl::GIslandExecutable::InObj>  && input_objs,
                  std::vector<cv::gimpl::GIslandExecutable::OutObj> && output_objs);
503

504
    const cv::GArgs& inArgs() const;
505 506 507

    // Generic accessor API
    template<typename T>
508 509 510
    const T& inArg(std::size_t input) const {
        return m_args.at(input).get<T>();
    }
511

512
    template<typename T>
513
    std::vector<T>& outVecR(std::size_t output) {
514
        return outVecRef(output).wref<T>();
515 516
    }

517
    // Syntax sugar
518 519
          cv::GShape      inShape(std::size_t input) const;
    const cv::Mat&        inMat  (std::size_t input) const;
520
    const cv::MediaFrame& inFrame(std::size_t input) const;
521

522 523
    cv::GRunArgP output (std::size_t idx);
    cv::Mat&     outMatR(std::size_t idx);
524 525 526 527

    const IEUnit                          &uu;
    cv::gimpl::GIslandExecutable::IOutput &out;

528
    // NB: Need to guarantee that MediaFrame::View doesn't die until request is over.
529 530 531
    using Views = std::vector<std::unique_ptr<cv::MediaFrame::View>>;
    Views views;

532 533 534
    // To store exception appeared in callback.
    std::exception_ptr eptr;

535 536
    const cv::GRunArg::Meta& getMeta() { return m_meta; };

537 538 539
    using req_key_t = void*;
    cv::MediaFrame* prepareKeepAliveFrameSlot(req_key_t key);
    size_t releaseKeepAliveFrame(req_key_t key);
540 541 542 543 544
private:
    cv::detail::VectorRef& outVecRef(std::size_t idx);

    cv::GArg packArg(const cv::GArg &arg);

545 546 547
    // To propagate accumulated meta from all inputs to output.
    cv::GRunArg::Meta m_meta;

548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563
    // To store input/output data from frames
    std::vector<cv::gimpl::GIslandExecutable::InObj>  m_input_objs;
    std::vector<cv::gimpl::GIslandExecutable::OutObj> m_output_objs;

    // To simplify access to cv::Mat inside cv::RMat
    cv::gimpl::Mag m_res;

    // FIXME: avoid conversion of arguments from internal representation to OpenCV one on each call
    //to OCV kernel. (This can be achieved by a two single time conversions in GCPUExecutable::run,
    //once on enter for input and output arguments, and once before return for output arguments only
    // FIXME: check if the above applies to this backend (taken from CPU)
    std::unordered_map<std::size_t, cv::GRunArgP> m_results;

    // Input parameters passed to an inference operation.
    cv::GArgs m_args;
    cv::GShapes m_in_shapes;
564 565 566 567

    // keep alive preprocessed frames
    std::mutex keep_alive_frames_mutex;
    std::unordered_map<req_key_t, cv::MediaFrame> keep_alive_pp_frames;
568 569 570 571 572 573
};

IECallContext::IECallContext(const IEUnit                                      &  unit,
                             cv::gimpl::GIslandExecutable::IOutput             &  output,
                             const cv::GArgs                                   &  args,
                             const std::vector<cv::gimpl::RcDesc>              &  outs,
574
                             cv::GRunArg::Meta                                 && meta,
575 576
                             std::vector<cv::gimpl::GIslandExecutable::InObj>  && input_objs,
                             std::vector<cv::gimpl::GIslandExecutable::OutObj> && output_objs)
577 578
: uu(unit), out(output), m_meta(std::move(meta)),
  m_input_objs(std::move(input_objs)), m_output_objs(std::move(output_objs))
579 580 581 582 583 584 585 586 587 588 589 590 591 592 593
{
    for (auto& it : m_input_objs)  cv::gimpl::magazine::bindInArg (m_res, it.first, it.second);
    for (auto& it : m_output_objs) cv::gimpl::magazine::bindOutArg(m_res, it.first, it.second);

    m_args.reserve(args.size());
    using namespace std::placeholders;
    ade::util::transform(args,
                         std::back_inserter(m_args),
                         std::bind(&IECallContext::packArg, this, _1));

    ade::util::transform(args, std::back_inserter(m_in_shapes),
            [](const cv::GArg& arg) {
                return arg.get<cv::gimpl::RcDesc>().shape;
            });

594 595 596 597 598 599
    for (const auto out_it : ade::util::indexed(outs)) {
        // FIXME: Can the same GArg type resolution mechanism be reused here?
        const auto port  = ade::util::index(out_it);
        const auto desc  = ade::util::value(out_it);
        m_results[port] = cv::gimpl::magazine::getObjPtr(m_res, desc);
    }
600 601 602 603 604 605
}

const cv::GArgs& IECallContext::inArgs() const {
    return m_args;
}

606
cv::GShape IECallContext::inShape(std::size_t i) const {
607 608 609 610 611 612 613 614 615 616 617 618 619 620 621
    return m_in_shapes[i];
}

const cv::Mat& IECallContext::inMat(std::size_t input) const {
    return inArg<cv::Mat>(input);
}

const cv::MediaFrame& IECallContext::inFrame(std::size_t input) const {
    return inArg<cv::MediaFrame>(input);
}

cv::Mat& IECallContext::outMatR(std::size_t idx) {
    return *cv::util::get<cv::Mat*>(m_results.at(idx));
}

622
cv::GRunArgP IECallContext::output(std::size_t idx) {
623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638
    return m_output_objs[idx].second;
};

cv::detail::VectorRef& IECallContext::outVecRef(std::size_t idx) {
    return cv::util::get<cv::detail::VectorRef>(m_results.at(idx));
}

cv::GArg IECallContext::packArg(const cv::GArg &arg) {
    // No API placeholders allowed at this point
    // FIXME: this check has to be done somewhere in compilation stage.
    GAPI_Assert(   arg.kind != cv::detail::ArgKind::GMAT
                && arg.kind != cv::detail::ArgKind::GSCALAR
                && arg.kind != cv::detail::ArgKind::GARRAY);

    if (arg.kind != cv::detail::ArgKind::GOBJREF) {
        cv::util::throw_error(std::logic_error("Inference supports G-types ONLY!"));
639
    }
640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661
    GAPI_Assert(arg.kind == cv::detail::ArgKind::GOBJREF);

    // Wrap associated CPU object (either host or an internal one)
    // FIXME: object can be moved out!!! GExecutor faced that.
    const cv::gimpl::RcDesc &ref = arg.get<cv::gimpl::RcDesc>();
    switch (ref.shape)
    {
    case cv::GShape::GMAT: return cv::GArg(m_res.slot<cv::Mat>()[ref.id]);

    // Note: .at() is intentional for GArray as object MUST be already there
    //   (and constructed by either bindIn/Out or resetInternal)
    case cv::GShape::GARRAY:  return cv::GArg(m_res.slot<cv::detail::VectorRef>().at(ref.id));

    // Note: .at() is intentional for GOpaque as object MUST be already there
    //   (and constructed by either bindIn/Out or resetInternal)
    case cv::GShape::GOPAQUE:  return cv::GArg(m_res.slot<cv::detail::OpaqueRef>().at(ref.id));

    case cv::GShape::GFRAME:  return cv::GArg(m_res.slot<cv::MediaFrame>().at(ref.id));

    default:
        cv::util::throw_error(std::logic_error("Unsupported GShape type"));
        break;
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
cv::MediaFrame* IECallContext::prepareKeepAliveFrameSlot(req_key_t key) {
    std::lock_guard<std::mutex> lock(keep_alive_frames_mutex);
    return &keep_alive_pp_frames[key];
}

size_t IECallContext::releaseKeepAliveFrame(req_key_t key) {
    size_t elapsed_count = 0;
    void *prev_slot = nullptr;
    // NB: release MediaFrame previously captured by prepareKeepAliveFrameSlot
    // We must capture it to keep a reference counter on inner media adapter
    // to ensure that frame resource would be locked until inference done.
    // Otherwise decoder could seized this frame resource as free/unlocked resource
    // from resource pool
    // Current  function just take a unique frame `key` and overwrite stored
    // actual frame by empty frame
    {
        std::lock_guard<std::mutex> lock(keep_alive_frames_mutex);
        auto ka_frame_it = keep_alive_pp_frames.find(key);
        if (ka_frame_it != keep_alive_pp_frames.end()) {
            prev_slot = &ka_frame_it->second;
            ka_frame_it->second = cv::MediaFrame();
        }
        elapsed_count = keep_alive_pp_frames.size();
    }
S
sivanov-work 已提交
689
    cv::util::suppress_unused_warning(prev_slot);
690 691 692 693 694
    GAPI_LOG_DEBUG(nullptr, "Release keep alive frame, slot: " << prev_slot <<
                            ", reserved frames count: " << elapsed_count);
    return elapsed_count;
}

695 696
struct IECallable {
    static const char *name() { return "IERequestCallable"; }
697
    using Run = std::function<void(std::shared_ptr<IECallContext>, cv::gimpl::ie::RequestPool&)>;
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
    Run run;
};

struct KImpl {
    cv::gimpl::CustomMetaFunction::CM customMetaFunc;
    IECallable::Run run;
};

// FIXME: Is there a way to take a typed graph (our GModel),
// and create a new typed graph _ATOP_ of that (by extending with a couple of
// new types?).
// Alternatively, is there a way to compose types graphs?
//
// If not, we need to introduce that!
using GIEModel = ade::TypedGraph
    < cv::gimpl::Protocol
    , cv::gimpl::Op
    , cv::gimpl::NetworkParams
    , cv::gimpl::CustomMetaFunction
    , IEUnit
    , IECallable
    >;

// FIXME: Same issue with Typed and ConstTyped
using GConstGIEModel = ade::ConstTypedGraph
    < cv::gimpl::Protocol
    , cv::gimpl::Op
    , cv::gimpl::NetworkParams
    , cv::gimpl::CustomMetaFunction
    , IEUnit
    , IECallable
    >;
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
cv::MediaFrame preprocess_frame_impl(cv::MediaFrame &&in_frame, const std::string &layer_name,
                                    IECallContext& ctx,
                                    const cv::util::optional<cv::Rect> &opt_roi,
                                    cv::MediaFrame* out_keep_alive_frame,
                                    bool* out_is_preprocessed) {
    cv::util::optional<cv::gapi::wip::pp_params> param =
                        ctx.uu.preproc_engine_impl->is_applicable(in_frame);
    if (param.has_value()) {
        GAPI_LOG_DEBUG(nullptr, "VPP preprocessing for decoded remote frame will be used");
        cv::GFrameDesc expected_net_input_descr =
                    ctx.uu.net_input_params.get_param(layer_name);

        // TODO: Find a better place to configure media format for GPU
        // adjust color conversion to NV12 according to OV GPU limitation
        if(ctx.uu.params.device_id.find("GPU") != std::string::npos &&
           ctx.uu.rctx) {
            auto it = ctx.uu.params.config.find(std::string("GPU_NV12_TWO_INPUTS"));
            if (it != ctx.uu.params.config.end()) {
                if (it->second == "YES") {
                    GAPI_LOG_DEBUG(nullptr, "Adjust preprocessing GPU media format to NV12");
                    expected_net_input_descr.fmt = cv::MediaFormat::NV12;
                }
            }
        }

        cv::gapi::wip::pp_session pp_sess =
                    ctx.uu.preproc_engine_impl->initialize_preproc(param.value(),
                                                                   expected_net_input_descr);

        in_frame = ctx.uu.preproc_engine_impl->run_sync(pp_sess, in_frame, opt_roi);

        if (out_keep_alive_frame != nullptr) {
            GAPI_LOG_DEBUG(nullptr, "remember preprocessed remote frame to keep it busy from reuse, slot: " <<
                                    out_keep_alive_frame);
            *out_keep_alive_frame = in_frame;
        }
        if (out_is_preprocessed) {
            *out_is_preprocessed = true;
        }
    } // otherwise it is not suitable frame, then check on other preproc backend or rely on IE plugin
    return std::move(in_frame);
}

774 775
inline IE::Blob::Ptr extractBlob(IECallContext& ctx,
                                 std::size_t i,
776 777 778 779 780
                                 cv::gapi::ie::TraitAs hint,
                                 const std::string& layer_name,
                                 const cv::util::optional<cv::Rect> &opt_roi,
                                 cv::MediaFrame* out_keep_alive_frame = nullptr,
                                 bool* out_is_preprocessed = nullptr) {
781
    switch (ctx.inShape(i)) {
782
        case cv::GShape::GFRAME: {
783 784 785 786 787 788
            auto frame = ctx.inFrame(i);
            if (ctx.uu.preproc_engine_impl) {
                GAPI_LOG_DEBUG(nullptr, "Try to use preprocessing for decoded frame in local ctx");
                frame = preprocess_frame_impl(std::move(frame), layer_name, ctx, opt_roi,
                                              out_keep_alive_frame, out_is_preprocessed);
            }
789 790 791 792 793 794 795 796 797 798 799 800

            // NB: check OV remote device context availability.
            // if it exist and MediaFrame shares the same device context
            // then we create a remote blob without memory copy
            if (ctx.uu.rctx != nullptr) {
                // Request params for result frame whatever it got preprocessed or not
                cv::util::any any_blob_params = frame.blobParams();
                using ParamType = std::pair<InferenceEngine::TensorDesc, InferenceEngine::ParamMap>;
                using NV12ParamType = std::pair<ParamType, ParamType>;

                NV12ParamType* blob_params = cv::util::any_cast<NV12ParamType>(&any_blob_params);
                if (blob_params == nullptr) {
801
                    GAPI_Error("Incorrect type of blobParams:"
802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819
                                         "expected std::pair<ParamType, ParamType>,"
                                         "with ParamType std::pair<InferenceEngine::TensorDesc,"
                                         "InferenceEngine::ParamMap >>");
                }

                //The parameters are TensorDesc and ParamMap for both y and uv blobs
                auto y_blob = ctx.uu.rctx->CreateBlob(blob_params->first.first, blob_params->first.second);
                auto uv_blob = ctx.uu.rctx->CreateBlob(blob_params->second.first, blob_params->second.second);

#if INF_ENGINE_RELEASE >= 2021010000
                return IE::make_shared_blob<IE::NV12Blob>(y_blob, uv_blob);
#else
                return IE::make_shared_blob<InferenceEngine::NV12Blob>(y_blob, uv_blob);
#endif
            }

            // NB: If no OV remote context created then use default MediaFrame accessor approach:
            // it invokes memory copying operation If GPU MediaFrame come
820 821
            ctx.views.emplace_back(new cv::MediaFrame::View(frame.access(cv::MediaFrame::Access::R)));
            return wrapIE(*(ctx.views.back()), frame.desc());
822 823
        }
        case cv::GShape::GMAT: {
824
            return wrapIE(ctx.inMat(i), hint);
825 826 827 828
        }
        default:
            GAPI_Assert("Unsupported input shape for IE backend");
    }
829
    GAPI_Error("InternalError");
830
}
831 832


833 834 835 836
static void setBlob(InferenceEngine::InferRequest& req,
                    const std::string&             layer_name,
                    const IE::Blob::Ptr&           blob,
                    const IECallContext&           ctx) {
837 838 839
    // TODO: Ideally we shouldn't do SetBlob() but GetBlob() instead,
    // and redirect our data producers to this memory
    // (A memory dialog comes to the picture again)
840 841
    using namespace cv::gapi::ie::detail;
    if (ctx.uu.params.kind == ParamDesc::Kind::Load) {
842 843
        req.SetBlob(layer_name, blob);
    } else {
844 845
        GAPI_Assert(ctx.uu.params.kind == ParamDesc::Kind::Import);
        req.SetBlob(layer_name, blob, ctx.uu.preproc_map.at(layer_name));
846 847 848
    }
}

849 850 851
static void setROIBlob(InferenceEngine::InferRequest& req,
                       const std::string&             layer_name,
                       const IE::Blob::Ptr&           blob,
852
                       const cv::Rect                 &roi,
853
                       const IECallContext&           ctx) {
854 855
    if (ctx.uu.params.device_id.find("GPU") != std::string::npos &&
        ctx.uu.rctx) {
856 857 858 859 860 861 862 863 864 865 866 867 868 869
        try {
            // NB: make_shared_blob() cannot work with GPU NV12 & ROI at the moment.
            // OpenVINO produces exception with unsupported status.
            // To do not encounter with silent crash situation we should catch OV exception
            // and suggest to avoid this problem by using inner preprocessing feature.
            // VPP/VPL proprocessing are supported at the moment
            setBlob(req, layer_name, IE::make_shared_blob(blob, toIE(roi)), ctx);
        } catch (const std::exception &ex) {
            GAPI_LOG_WARNING(nullptr, "cannot set ROI blob for layer: " << layer_name <<
                                      ", reason:\n" << ex.what() <<
                                      "\nTry using self GAPI preprocessing feature: "
                                      " Check method `cfgPreprocessingParams` in `cv::gapi::ie::Params`");
            throw;
        }
870 871 872 873
    } else {
        setBlob(req, layer_name, IE::make_shared_blob(blob, toIE(roi)), ctx);
    }
}
874 875
} // anonymous namespace

876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895
std::vector<InferenceEngine::InferRequest> cv::gimpl::ie::IECompiled::createInferRequests() {
    std::vector<InferenceEngine::InferRequest> requests;
    requests.reserve(params.nireq);

    for (size_t i = 0; i < params.nireq; ++i) {
        requests.push_back(this_network.CreateInferRequest());
        auto& request = requests.back();
        // Bind const data to infer request
        for (auto &&p : params.const_inputs) {
            // FIXME: SetBlob is known to be inefficient,
            // it is worth to make a customizable "initializer" and pass the
            // cv::Mat-wrapped blob there to support IE's optimal "GetBlob idiom"
            // Still, constant data is to set only once.
            request.SetBlob(p.first, wrapIE(p.second.first, p.second.second));
        }
    }

    return requests;
}

896
class IInferExecutor {
897
public:
898 899
    using Ptr             = std::shared_ptr<IInferExecutor>;
    using NotifyCallbackF = std::function<void()>;
T
TolyaTalamanov 已提交
900 901
    using SetInputDataF   = std::function<void(InferenceEngine::InferRequest&)>;
    using ReadOutputDataF = std::function<void(InferenceEngine::InferRequest&, InferenceEngine::StatusCode)>;
902 903

    // NB: The task is represented by:
T
TolyaTalamanov 已提交
904 905
    // SetInputDataF - function which set input data.
    // ReadOutputDataF - function which read output data.
906
    struct Task {
907
        SetInputDataF   set_input_data;
T
TolyaTalamanov 已提交
908
        ReadOutputDataF read_output_data;
909 910
    };

911 912 913 914
    IInferExecutor(IE::InferRequest request, NotifyCallbackF notify)
        : m_request(std::move(request)),
          m_notify(std::move(notify)) {
    };
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
    virtual void execute(const Task& task) = 0;
    virtual ~IInferExecutor() = default;

protected:
    IE::InferRequest m_request;
    NotifyCallbackF  m_notify;
};

class SyncInferExecutor : public IInferExecutor {
    using IInferExecutor::IInferExecutor;
    virtual void execute(const IInferExecutor::Task& task) override;
};

void SyncInferExecutor::execute(const IInferExecutor::Task& task) {
    try {
        task.set_input_data(m_request);
        m_request.Infer();
        task.read_output_data(m_request, IE::StatusCode::OK);
    } catch (...) {
        m_notify();
        throw;
    }
    // NB: Notify pool that executor has finished.
    m_notify();
}

class AsyncInferExecutor : public IInferExecutor {
public:
    using IInferExecutor::IInferExecutor;
    virtual void execute(const IInferExecutor::Task& task) override;
946 947

private:
948 949
    void callback(Task task,
                  IE::InferRequest request,
950
                  IE::StatusCode code) noexcept;
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
};

void AsyncInferExecutor::execute(const IInferExecutor::Task& task) {
    using namespace std::placeholders;
    using callback_t = std::function<void(IE::InferRequest, IE::StatusCode)>;
    m_request.SetCompletionCallback(
            static_cast<callback_t>(
                std::bind(&AsyncInferExecutor::callback, this, task, _1, _2)));
    try {
        task.set_input_data(m_request);
        m_request.StartAsync();
    } catch (...) {
        m_request.SetCompletionCallback([](){});
        m_notify();
        throw;
    }
}

void AsyncInferExecutor::callback(IInferExecutor::Task task,
                                  IE::InferRequest     request,
                                  IE::StatusCode       code) noexcept {
    task.read_output_data(request, code);
    request.SetCompletionCallback([](){});
    // NB: Notify pool that executor has finished.
    m_notify();
}

class cv::gimpl::ie::RequestPool {
public:

T
TolyaTalamanov 已提交
981
    explicit RequestPool(cv::gapi::ie::InferMode                      mode,
982
                         std::vector<InferenceEngine::InferRequest>&& requests);
983 984 985 986 987

    IInferExecutor::Ptr getIdleRequest();
    void waitAll();

private:
A
Anatoliy Talamanov 已提交
988
    void setup();
T
TolyaTalamanov 已提交
989
    void release(const size_t id);
990

991 992
    QueueClass<size_t>               m_idle_ids;
    std::vector<IInferExecutor::Ptr> m_requests;
993 994
};

T
TolyaTalamanov 已提交
995
void cv::gimpl::ie::RequestPool::release(const size_t id) {
T
TolyaTalamanov 已提交
996 997 998
    m_idle_ids.push(id);
}

999
// RequestPool implementation //////////////////////////////////////////////
T
TolyaTalamanov 已提交
1000
cv::gimpl::ie::RequestPool::RequestPool(cv::gapi::ie::InferMode                      mode,
1001
                                        std::vector<InferenceEngine::InferRequest>&& requests) {
1002
    for (size_t i = 0; i < requests.size(); ++i) {
1003 1004
        IInferExecutor::Ptr iexec = nullptr;
        switch (mode) {
T
TolyaTalamanov 已提交
1005
            case cv::gapi::ie::InferMode::Async:
1006 1007 1008
                iexec = std::make_shared<AsyncInferExecutor>(std::move(requests[i]),
                                                             std::bind(&RequestPool::release, this, i));
                break;
T
TolyaTalamanov 已提交
1009
            case cv::gapi::ie::InferMode::Sync:
1010 1011 1012 1013
                iexec = std::make_shared<SyncInferExecutor>(std::move(requests[i]),
                                                             std::bind(&RequestPool::release, this, i));
                break;
            default:
1014
                GAPI_Error("Unsupported cv::gapi::ie::InferMode");
1015 1016
        }
        m_requests.emplace_back(std::move(iexec));
1017
    }
1018 1019
    setup();
}
1020

A
Anatoliy Talamanov 已提交
1021 1022 1023 1024 1025 1026
void cv::gimpl::ie::RequestPool::setup() {
    for (size_t i = 0; i < m_requests.size(); ++i) {
        m_idle_ids.push(i);
    }
}

1027
IInferExecutor::Ptr cv::gimpl::ie::RequestPool::getIdleRequest() {
1028 1029
    size_t id = 0u;
    m_idle_ids.pop(id);
1030
    return m_requests[id];
1031 1032 1033
}

// NB: Not thread-safe.
A
Anatoliy Talamanov 已提交
1034
void cv::gimpl::ie::RequestPool::waitAll() {
1035 1036 1037 1038 1039
    // NB: It will be blocked if at least one request is busy.
    for (size_t i = 0; i < m_requests.size(); ++i) {
        size_t id = 0u;
        m_idle_ids.pop(id);
    }
A
Anatoliy Talamanov 已提交
1040
    setup();
1041 1042
}

1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056
// GCPUExcecutable implementation //////////////////////////////////////////////
cv::gimpl::ie::GIEExecutable::GIEExecutable(const ade::Graph &g,
                                            const std::vector<ade::NodeHandle> &nodes)
    : m_g(g), m_gm(m_g) {
    // FIXME: Currently this backend is capable to run a single inference node only.
    // Need to extend our island fusion with merge/not-to-merge decision making parametrization
    GConstGIEModel iem(g);

    for (auto &nh : nodes) {
        switch (m_gm.metadata(nh).get<NodeType>().t) {
        case NodeType::OP:
            if (this_nh == nullptr) {
                this_nh = nh;
                this_iec = iem.metadata(this_nh).get<IEUnit>().compile();
1057
                m_reqPool.reset(new RequestPool(this_iec.params.mode, this_iec.createInferRequests()));
1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078
            }
            else
                util::throw_error(std::logic_error("Multi-node inference is not supported!"));
            break;

        case NodeType::DATA: {
            m_dataNodes.push_back(nh);
            const auto &desc = m_gm.metadata(nh).get<Data>();
            if (desc.storage == Data::Storage::CONST_VAL) {
                util::throw_error(std::logic_error("No const data please!"));
            }
            if (desc.storage == Data::Storage::INTERNAL) {
                util::throw_error(std::logic_error("No internal data please!"));
            }
            break;
        }
        default: util::throw_error(std::logic_error("Unsupported NodeType type"));
        }
    }
}

1079 1080
void cv::gimpl::ie::GIEExecutable::run(cv::gimpl::GIslandExecutable::IInput  &in,
                                       cv::gimpl::GIslandExecutable::IOutput &out) {
1081
    // General algorithm:
1082 1083 1084
    //     1. Collect island inputs/outputs.
    //     2. Create kernel context. (Every kernel has his own context).
    //     3. If the EndOfStream message is recieved, wait until all passed task are done.
1085 1086
    //     4. If the Exception message is revieved, propagate it further.
    //     5.
1087 1088 1089
    //        5.1 Run the kernel.
    //        5.2 Kernel wait for all nececcary infer requests and start asynchronous execution.
    //        5.3 After the kernel is finished continue processing next frame.
1090
    //
1091
    //     6. If graph is compiled in non-streaming mode, wait until all tasks are done.
1092 1093 1094 1095

    std::vector<InObj>  input_objs;
    std::vector<OutObj> output_objs;

1096 1097
    const auto &in_desc = in.desc();
          auto  in_msg  = in.get();
1098 1099

    if (cv::util::holds_alternative<cv::gimpl::EndOfStream>(in_msg))
1100
    {
1101
        // (3) Wait until all passed task are done.
A
Anatoliy Talamanov 已提交
1102
        m_reqPool->waitAll();
1103 1104 1105
        out.post(cv::gimpl::EndOfStream{});
        return;
    }
1106

1107 1108
    GAPI_Assert(cv::util::holds_alternative<cv::GRunArgs>(in_msg));
    const auto in_vector = cv::util::get<cv::GRunArgs>(in_msg);
1109 1110 1111 1112 1113 1114
    // NB: Collect meta from all inputs.
    cv::GRunArg::Meta stub_meta;
    for (auto &&in_arg : in_vector)
    {
        stub_meta.insert(in_arg.meta.begin(), in_arg.meta.end());
    }
1115

1116
    // (1) Collect island inputs/outputs
1117 1118
    input_objs.reserve(in_desc.size());
    for (auto &&it: ade::util::zip(ade::util::toRange(in_desc),
1119
                    ade::util::toRange(in_vector)))
1120 1121 1122
    {
        input_objs.emplace_back(std::get<0>(it), std::get<1>(it));
    }
1123 1124 1125

    const auto &out_desc = out.desc();
    output_objs.reserve(out_desc.size());
1126 1127 1128
    for (auto &&it: ade::util::indexed(ade::util::toRange(out_desc)))
    {
        output_objs.emplace_back(ade::util::value(it),
1129
                out.get(ade::util::checked_cast<int>(ade::util::index(it))));
1130 1131
    }

1132 1133 1134
    GConstGIEModel giem(m_g);
    const auto &uu = giem.metadata(this_nh).get<IEUnit>();
    const auto &op = m_gm.metadata(this_nh).get<Op>();
1135 1136
    // (2) Create kernel context
    auto ctx = std::make_shared<IECallContext>(uu, out, op.args, op.outs,
1137
            std::move(stub_meta), std::move(input_objs), std::move(output_objs));
1138

1139
    const auto &kk = giem.metadata(this_nh).get<IECallable>();
1140

1141 1142 1143 1144 1145 1146 1147 1148
    // (5) Run the kernel.
    try {
        kk.run(ctx, *m_reqPool);
    } catch (...) {
        auto eptr = std::current_exception();
        for (auto i : ade::util::iota(ctx->uu.params.num_out))
        {
            auto output = ctx->output(i);
1149
            ctx->out.meta(output, ctx->getMeta());
1150 1151 1152 1153
            ctx->out.post(std::move(output), eptr);
        }
        return;
    }
1154

1155
    // (6) In non-streaming mode need to wait until the all tasks are done
1156 1157
    // FIXME: Is there more graceful way to handle this case ?
    if (!m_gm.metadata().contains<Streaming>()) {
A
Anatoliy Talamanov 已提交
1158
        m_reqPool->waitAll();
1159 1160 1161 1162 1163 1164
    }
}

namespace cv {
namespace gimpl {
namespace ie {
1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197
static void configureInputReshapeByImage(const IE::InputInfo::Ptr& ii,
                                         const cv::GMetaArg mm,
                                         IE::ICNNNetwork::InputShapes& input_reshape_table) {
    const auto& layer_name = ii->name();
    // Finding name in reshape table
    const auto name_pos_in_table = input_reshape_table.find(layer_name);
    // If contains then reshape for this layer already configured by shapes
    // otherwise create a new element of reshape table with name and dimension
    // which based on input image size.
    if (name_pos_in_table != input_reshape_table.end()) {
        GAPI_Assert(false &&
                    "Names of layers for reshape with specified dimensions shouldn't intersect with names for reshape by image");
    }
    cv::Size image_sz;
    switch (mm.index()) {
        case cv::GMetaArg::index_of<cv::GMatDesc>():
            {
                const auto &meta = util::get<cv::GMatDesc>(mm);
                image_sz = meta.size;
                break;
            }
        case cv::GMetaArg::index_of<cv::GFrameDesc>():
            {
                const auto &meta = util::get<cv::GFrameDesc>(mm);
                image_sz = meta.size;
                break;
            }
        default:
            util::throw_error(std::runtime_error("Unsupported input meta for IE backend"));
    }
    auto input_dims = ii->getTensorDesc().getDims();
    const auto size = input_dims.size();
    if (size <= 1) {
1198
        GAPI_Error("Unsupported number of dimensions for reshape by image");
1199 1200 1201 1202 1203 1204
    }
    input_dims.at(size - 2) = static_cast<size_t>(image_sz.height);
    input_dims.at(size - 1) = static_cast<size_t>(image_sz.width);
    // Adding new element to reshape table
    input_reshape_table.emplace(layer_name, input_dims);
}
1205

1206 1207
// NB: This function is used in order to configure
// preprocessing for "Load" case networks.
1208 1209 1210
static void configureInputInfo(const IE::InputInfo::Ptr& ii, const cv::GMetaArg mm) {
    switch (mm.index()) {
        case cv::GMetaArg::index_of<cv::GMatDesc>():
1211
        {
1212 1213 1214 1215 1216 1217 1218
            const auto &desc = util::get<cv::GMatDesc>(mm);
            ii->setPrecision(toIE(desc.depth));
            // NB: Configure resize only for images.
            const auto trait = clarifyTrait(desc, ii->getTensorDesc());
            if (trait == cv::gapi::ie::TraitAs::IMAGE) {
                ii->getPreProcess().setResizeAlgorithm(IE::RESIZE_BILINEAR);
            }
1219 1220
            break;
        }
1221
        case cv::GMetaArg::index_of<cv::GFrameDesc>():
1222 1223 1224 1225 1226 1227 1228 1229 1230
        {
            const auto &meta = util::get<cv::GFrameDesc>(mm);
            switch (meta.fmt) {
                case cv::MediaFormat::NV12:
                    ii->getPreProcess().setColorFormat(IE::ColorFormat::NV12);
                    break;
                case cv::MediaFormat::BGR:
                    // NB: Do nothing
                    break;
1231 1232 1233
                case cv::MediaFormat::GRAY:
                    // NB: Do nothing
                    break;
1234
                default:
1235
                    GAPI_Error("Unsupported media format for IE backend");
1236
            }
1237
            ii->setPrecision(toIE(CV_8U));
1238 1239
            // NB: Always configure resize because media formats are images.
            ii->getPreProcess().setResizeAlgorithm(IE::RESIZE_BILINEAR);
1240 1241
            break;
        }
1242 1243 1244 1245 1246
        default:
            util::throw_error(std::runtime_error("Unsupported input meta for IE backend"));
    }
}

1247 1248
// NB: This function is used in order to configure
// preprocessing for "Import" case networks.
1249 1250 1251
static IE::PreProcessInfo configurePreProcInfo(const IE::InputInfo::CPtr& ii,
                                               const cv::GMetaArg&        mm) {
    IE::PreProcessInfo info;
1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262
    switch (mm.index()) {
        // NB: Note that it doesn't specify precision.
        case cv::GMetaArg::index_of<cv::GMatDesc>():
        {
            // NB: Configure resize only for images.
            const auto &desc = cv::util::get<cv::GMatDesc>(mm);
            const auto trait = clarifyTrait(desc, ii->getTensorDesc());
            if (trait == cv::gapi::ie::TraitAs::IMAGE) {
                info.setResizeAlgorithm(IE::RESIZE_BILINEAR);
            }
            break;
1263
        }
1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276
        // NB: Note that it doesn't specify precision.
        case cv::GMetaArg::index_of<cv::GFrameDesc>():
        {
            const auto &desc = cv::util::get<cv::GFrameDesc>(mm);
            if (desc.fmt == cv::MediaFormat::NV12) {
                info.setColorFormat(IE::ColorFormat::NV12);
            }
            // NB: Always configure resize because media formats are images.
            info.setResizeAlgorithm(IE::RESIZE_BILINEAR);
            break;
        }
        default:
            util::throw_error(std::runtime_error("Unsupported input meta for IE backend"));
1277
    }
1278

1279 1280 1281
    return info;
}

T
TolyaTalamanov 已提交
1282
using namespace cv::gapi::ie::detail;
T
TolyaTalamanov 已提交
1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298
static void configureOutputPrecision(const IE::OutputsDataMap           &outputs_info,
                                     const ParamDesc::PrecisionVariantT &output_precision) {
    cv::util::visit(cv::util::overload_lambdas(
            [&outputs_info](ParamDesc::PrecisionT cvdepth) {
                auto precision = toIE(cvdepth);
                for (auto it : outputs_info) {
                    it.second->setPrecision(precision);
                }
            },
            [&outputs_info](const ParamDesc::PrecisionMapT& precision_map) {
                for (auto it : precision_map) {
                    outputs_info.at(it.first)->setPrecision(toIE(it.second));
                }
            },
            [&outputs_info](cv::util::monostate) {
                // Do nothing.
T
TolyaTalamanov 已提交
1299
            }
T
TolyaTalamanov 已提交
1300 1301
        ), output_precision
    );
T
TolyaTalamanov 已提交
1302 1303
}

1304 1305
// NB: This is a callback used by async infer
// to post outputs blobs (cv::GMat's).
1306 1307 1308
static void PostOutputs(InferenceEngine::InferRequest &request,
                        InferenceEngine::StatusCode    code,
                        std::shared_ptr<IECallContext> ctx) {
1309 1310 1311
    GAPI_ITT_STATIC_LOCAL_HANDLE(ie_cb_post_outputs_hndl, "IE_async_callback_PostOutputs");
    GAPI_ITT_AUTO_TRACE_GUARD(ie_cb_post_outputs_hndl);

1312 1313 1314 1315 1316 1317 1318 1319
    if (code != IE::StatusCode::OK) {
        std::stringstream ss;
        ss << "InferRequest for model: " << ctx->uu.params.model_path
           << " finished with InferenceEngine::StatusCode: " << static_cast<int>(code);
        ctx->eptr = std::make_exception_ptr(std::logic_error(ss.str()));
    }

    for (auto i : ade::util::iota(ctx->uu.params.num_out)) {
1320 1321 1322
        auto& out_mat = ctx->outMatR(i);
        IE::Blob::Ptr this_blob = request.GetBlob(ctx->uu.params.output_names[i]);
        copyFromIE(this_blob, out_mat);
1323
        auto output = ctx->output(i);
1324
        ctx->out.meta(output, ctx->getMeta());
1325
        ctx->out.post(std::move(output), ctx->eptr);
1326
    }
1327

1328
    ctx->views.clear();
1329
    ctx->releaseKeepAliveFrame(&request);
1330
}
1331

1332 1333 1334 1335 1336 1337
class PostOutputsList {
public:
    PostOutputsList(size_t size,
                    std::shared_ptr<IECallContext> ctx,
                    std::vector<std::vector<int>>&& cached_dims);

1338 1339 1340
    void operator()(InferenceEngine::InferRequest &request,
                    InferenceEngine::StatusCode    code,
                    size_t                         pos) const;
1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360

private:
    struct Priv {
        size_t              size;
        std::atomic<size_t> finished{0u};
        std::shared_ptr<IECallContext> ctx;
        std::vector<std::vector<int>> cached_dims;
    };
    std::shared_ptr<Priv> m_priv;
};

PostOutputsList::PostOutputsList(size_t size,
                                 std::shared_ptr<IECallContext> ctx,
                                 std::vector<std::vector<int>>&& cached_dims)
    : m_priv(new Priv()) {
    m_priv->size = size;
    m_priv->ctx = ctx;
    m_priv->cached_dims = std::move(cached_dims);
}

1361 1362 1363
void PostOutputsList::operator()(InferenceEngine::InferRequest &req,
                                 InferenceEngine::StatusCode    code,
                                 size_t                         pos) const {
1364 1365 1366 1367 1368
    auto&& ctx         = m_priv->ctx;
    auto&& cached_dims = m_priv->cached_dims;
    auto&& finished    = m_priv->finished;
    auto&& size        = m_priv->size;

1369 1370 1371 1372 1373 1374 1375 1376
    if (code != IE::StatusCode::OK) {
        ctx->eptr = std::make_exception_ptr(
               std::logic_error("IE::InferRequest finished with not OK status"));
    }

    if (!ctx->eptr) {
        for (auto i : ade::util::iota(ctx->uu.params.num_out)) {
            std::vector<cv::Mat> &out_vec = ctx->outVecR<cv::Mat>(i);
1377

1378 1379 1380 1381 1382 1383 1384
            IE::Blob::Ptr out_blob = req.GetBlob(ctx->uu.params.output_names[i]);
            GAPI_Assert(out_blob);

            // FIXME: Avoid data copy. Not sure if it is possible though
            out_vec[pos].create(cached_dims[i], toCV(out_blob->getTensorDesc().getPrecision()));
            copyFromIE(out_blob, out_vec[pos]);
        }
1385 1386 1387 1388 1389 1390
    }
    ++finished;

    if (finished == size) {
        for (auto i : ade::util::iota(ctx->uu.params.num_out)) {
            auto output = ctx->output(i);
1391
            ctx->out.meta(output, ctx->getMeta());
1392
            ctx->out.post(std::move(output), ctx->eptr);
1393 1394 1395 1396
        }
    }
}

1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414
struct Infer: public cv::detail::KernelTag {
    using API = cv::GInferBase;
    static cv::gapi::GBackend backend()  { return cv::gapi::ie::backend(); }
    static KImpl kernel()                { return KImpl{outMeta, run}; }

    static cv::GMetaArgs outMeta(const ade::Graph      &gr,
                                 const ade::NodeHandle &nh,
                                 const cv::GMetaArgs   &in_metas,
                                 const cv::GArgs       &/*in_args*/) {
        // Specify network's output layer metadata to the framework
        // Also specify the input information to the IE from the framework
        // NB: Have no clue if network's input [dimensions] may ever define
        // its output dimensions. It seems possible with OpenCV DNN APIs

        cv::GMetaArgs result;

        GConstGIEModel gm(gr);
        const auto &uu = gm.metadata(nh).get<IEUnit>();
1415
        IE::ICNNNetwork::InputShapes input_reshape_table = uu.params.reshape_table;
1416 1417 1418 1419 1420 1421 1422

        // Initialize input information
        // Note our input layers list order matches the API order and so
        // meta order.
        GAPI_Assert(uu.params.input_names.size() == in_metas.size()
                    && "Known input layers count doesn't match input meta count");

T
TolyaTalamanov 已提交
1423
        // NB: Configuring input/output precision and network reshape must be done
1424
        // only in the loadNetwork case.
1425 1426 1427
        using namespace cv::gapi::ie::detail;
        if (uu.params.kind == ParamDesc::Kind::Load) {
            auto inputs = uu.net.getInputsInfo();
1428 1429 1430
            for (auto &&it : ade::util::zip(ade::util::toRange(uu.params.input_names),
                                            ade::util::toRange(in_metas))) {
                    const auto &input_name = std::get<0>(it);
1431
                    auto ii = inputs.at(input_name);
1432 1433 1434 1435 1436 1437 1438
                    const auto & mm = std::get<1>(it);

                    configureInputInfo(ii, mm);
                    if (uu.params.layer_names_to_reshape.find(input_name) !=
                        uu.params.layer_names_to_reshape.end()) {
                        configureInputReshapeByImage(ii, mm, input_reshape_table);
                    }
1439

1440 1441 1442 1443 1444
                    // NB: configure input param for further preproc
                    if (uu.net_input_params.is_applicable(mm)) {
                        const_cast<IEUnit::InputFramesDesc &>(uu.net_input_params)
                                .set_param(input_name, ii->getTensorDesc());
                    }
1445
            }
1446

1447 1448 1449 1450 1451
            for (auto &&p : uu.params.const_inputs) {
                const auto ii = inputs.at(p.first);
                ii->setPrecision(toIE(p.second.first.depth()));
            }

1452 1453 1454 1455 1456 1457
            // FIXME: This isn't the best place to call reshape function.
            // Сorrect solution would be to do this in compile() method of network,
            // but now input meta isn't passed to compile() method.
            if (!input_reshape_table.empty()) {
                const_cast<IE::CNNNetwork *>(&uu.net)->reshape(input_reshape_table);
            }
T
TolyaTalamanov 已提交
1458
            configureOutputPrecision(uu.net.getOutputsInfo(), uu.params.output_precision);
1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469
        } else {
            GAPI_Assert(uu.params.kind == ParamDesc::Kind::Import);
            auto inputs = uu.this_network.GetInputsInfo();
            // FIXME: This isn't the best place to collect PreProcMap.
            auto* non_const_prepm = const_cast<IEUnit::PreProcMap*>(&uu.preproc_map);
            for (auto &&it : ade::util::zip(ade::util::toRange(uu.params.input_names),
                                            ade::util::toRange(in_metas))) {
                const auto &input_name = std::get<0>(it);
                auto ii = inputs.at(input_name);
                const auto & mm = std::get<1>(it);
                non_const_prepm->emplace(input_name, configurePreProcInfo(ii, mm));
1470 1471 1472 1473 1474 1475

                // NB: configure input param for further preproc
                if (uu.net_input_params.is_applicable(mm)) {
                    const_cast<IEUnit::InputFramesDesc &>(uu.net_input_params)
                                .set_param(input_name, ii->getTensorDesc());
                }
1476
            }
1477 1478
        }

1479 1480 1481 1482 1483 1484
        // FIXME: It would be nice here to have an exact number of network's
        // input/output parameters. Probably GCall should store it here for us.
        // It doesn't, as far as I know..
        for (const auto &out_name : uu.params.output_names) {
            // NOTE: our output_names vector follows the API order
            // of this operation's outputs
1485 1486 1487 1488
            const auto& desc =
                uu.params.kind == cv::gapi::ie::detail::ParamDesc::Kind::Load
                    ? uu.net.getOutputsInfo().at(out_name)->getTensorDesc()
                    : uu.this_network.GetOutputsInfo().at(out_name)->getTensorDesc();
1489

1490 1491
            cv::GMatDesc outm(toCV(desc.getPrecision()),
                              toCV(desc.getDims()));
1492 1493 1494 1495 1496
            result.emplace_back(outm);
        }
        return result;
    }

1497 1498 1499
    static void run(std::shared_ptr<IECallContext>  ctx,
                    cv::gimpl::ie::RequestPool     &reqPool) {
        using namespace std::placeholders;
1500 1501
        reqPool.getIdleRequest()->execute(
                IInferExecutor::Task {
1502 1503 1504 1505
                    [ctx](InferenceEngine::InferRequest &req) {
                        // non-generic version for now:
                        // - assumes all inputs/outputs are always Mats
                        for (auto i : ade::util::iota(ctx->uu.params.num_in)) {
1506 1507 1508 1509 1510 1511 1512 1513
                            const auto& layer_name = ctx->uu.params.input_names[i];
                            auto layout =
                                ctx->uu.this_network.GetInputsInfo().
                                    at(layer_name)->getTensorDesc().getLayout();
                            auto hint =
                                (layout == IE::Layout::NCHW || layout == IE::Layout::NHWC)
                                ? cv::gapi::ie::TraitAs::IMAGE : cv::gapi::ie::TraitAs::TENSOR;

1514 1515 1516
                            IE::Blob::Ptr this_blob = extractBlob(*ctx, i, hint,
                                                                  layer_name,
                                                                  cv::util::optional<cv::Rect>{});
1517
                            setBlob(req, layer_name, this_blob, *ctx);
1518 1519
                        }
                    },
1520
                    std::bind(PostOutputs, _1, _2, ctx)
1521 1522
                }
        );
1523 1524 1525
    }
};

1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538
struct InferROI: public cv::detail::KernelTag {
    using API = cv::GInferROIBase;
    static cv::gapi::GBackend backend()  { return cv::gapi::ie::backend(); }
    static KImpl kernel()                { return KImpl{outMeta, run}; }

    static cv::GMetaArgs outMeta(const ade::Graph      &gr,
                                 const ade::NodeHandle &nh,
                                 const cv::GMetaArgs   &in_metas,
                                 const cv::GArgs       &/*in_args*/) {
        cv::GMetaArgs result;

        GConstGIEModel gm(gr);
        const auto &uu = gm.metadata(nh).get<IEUnit>();
1539
        IE::ICNNNetwork::InputShapes input_reshape_table = uu.params.reshape_table;
1540 1541 1542 1543 1544 1545

        // Initialize input information
        // FIXME: So far it is pretty limited
        GAPI_Assert(1u == uu.params.input_names.size());
        GAPI_Assert(2u == in_metas.size());

1546 1547
        const auto &input_name = uu.params.input_names.at(0);
        auto &&mm = in_metas.at(1u);
1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566
        const auto &tensor_desc =
            (uu.params.kind == cv::gapi::ie::detail::ParamDesc::Kind::Load)
             ? uu.net.getInputsInfo().at(input_name)->getTensorDesc()
             : uu.this_network.GetInputsInfo().at(input_name)->getTensorDesc();

        if (cv::util::holds_alternative<cv::GMatDesc>(mm) ||
            cv::util::holds_alternative<cv::GFrameDesc>(mm)) {
            const auto trait = clarifyTrait(mm, tensor_desc);
            if (trait != cv::gapi::ie::TraitAs::IMAGE) {
                util::throw_error(std::runtime_error(
                            "IE Backend: Only image is supported"
                            " as the 1th argument for InferROI"));
            }
        } else {
            util::throw_error(std::runtime_error(
                        "IE Backend: Unsupported input meta for"
                        " 1th argument for InferROI"));
        }

1567 1568 1569 1570
        // NB: Configuring input precision and network reshape must be done
        // only in the loadNetwork case.
        if (uu.params.kind == cv::gapi::ie::detail::ParamDesc::Kind::Load) {
            // 0th is ROI, 1st is input image
T
TolyaTalamanov 已提交
1571 1572
            auto inputs = uu.net.getInputsInfo();
            auto ii = inputs.at(input_name);
1573

1574 1575 1576 1577 1578
            configureInputInfo(ii, mm);
            if (uu.params.layer_names_to_reshape.find(input_name) !=
                uu.params.layer_names_to_reshape.end()) {
                configureInputReshapeByImage(ii, mm, input_reshape_table);
            }
1579

1580 1581 1582 1583 1584 1585
            // FIXME: This isn't the best place to call reshape function.
            // Сorrect solution would be to do this in compile() method of network,
            // but now input meta isn't passed to compile() method.
            if (!input_reshape_table.empty()) {
                const_cast<IE::CNNNetwork *>(&uu.net)->reshape(input_reshape_table);
            }
1586 1587 1588 1589 1590 1591

            // NB: configure input param for further preproc
            if (uu.net_input_params.is_applicable(mm)) {
                const_cast<IEUnit::InputFramesDesc &>(uu.net_input_params)
                            .set_param(input_name, ii->getTensorDesc());
            }
1592 1593

            for (auto &&p : uu.params.const_inputs) {
T
TolyaTalamanov 已提交
1594
                inputs.at(p.first)->setPrecision(toIE(p.second.first.depth()));
1595 1596
            }

T
TolyaTalamanov 已提交
1597
            configureOutputPrecision(uu.net.getOutputsInfo(), uu.params.output_precision);
1598 1599 1600 1601 1602 1603
        } else {
            GAPI_Assert(uu.params.kind == cv::gapi::ie::detail::ParamDesc::Kind::Import);
            auto inputs = uu.this_network.GetInputsInfo();
            // FIXME: This isn't the best place to collect PreProcMap.
            auto* non_const_prepm = const_cast<IEUnit::PreProcMap*>(&uu.preproc_map);
            auto ii = inputs.at(input_name);
1604

1605
            non_const_prepm->emplace(input_name, configurePreProcInfo(ii, mm));
1606 1607 1608 1609 1610 1611

            // NB: configure intput param for further preproc
            if (uu.net_input_params.is_applicable(mm)) {
                const_cast<IEUnit::InputFramesDesc &>(uu.net_input_params)
                            .set_param(input_name, ii->getTensorDesc());
            }
1612 1613
        }

1614 1615 1616 1617 1618 1619
        // FIXME: It would be nice here to have an exact number of network's
        // input/output parameters. Probably GCall should store it here for us.
        // It doesn't, as far as I know..
        for (const auto &out_name : uu.params.output_names) {
            // NOTE: our output_names vector follows the API order
            // of this operation's outputs
1620 1621 1622 1623
            const auto& desc =
                uu.params.kind == cv::gapi::ie::detail::ParamDesc::Kind::Load
                    ? uu.net.getOutputsInfo().at(out_name)->getTensorDesc()
                    : uu.this_network.GetOutputsInfo().at(out_name)->getTensorDesc();
1624

1625 1626
            cv::GMatDesc outm(toCV(desc.getPrecision()),
                              toCV(desc.getDims()));
1627 1628 1629 1630 1631
            result.emplace_back(outm);
        }
        return result;
    }

1632 1633 1634
    static void run(std::shared_ptr<IECallContext>  ctx,
                    cv::gimpl::ie::RequestPool     &reqPool) {
        using namespace std::placeholders;
1635 1636
        reqPool.getIdleRequest()->execute(
                IInferExecutor::Task {
1637 1638 1639 1640
                    [ctx](InferenceEngine::InferRequest &req) {
                        GAPI_Assert(ctx->uu.params.num_in == 1);
                        auto&& this_roi = ctx->inArg<cv::detail::OpaqueRef>(0).rref<cv::Rect>();

1641 1642 1643
                        // reserve unique slot for keep alive preprocessed frame
                        cv::MediaFrame* slot_ptr = ctx->prepareKeepAliveFrameSlot(&req);

1644 1645
                        // NB: This blob will be used to make roi from its, so
                        // it should be treated as image
1646
                        bool preprocessed = false;
1647
                        IE::Blob::Ptr this_blob =
1648 1649 1650 1651 1652 1653
                            extractBlob(*ctx, 1, cv::gapi::ie::TraitAs::IMAGE,
                                        *(ctx->uu.params.input_names.begin()),
                                        cv::util::make_optional(this_roi),
                                        slot_ptr, &preprocessed);
                        if (!preprocessed) {
                            setROIBlob(req,
1654 1655
                                   *(ctx->uu.params.input_names.begin()),
                                   this_blob, this_roi, *ctx);
1656 1657 1658 1659 1660
                        } else {
                            setBlob(req,
                                   *(ctx->uu.params.input_names.begin()),
                                   this_blob, *ctx);
                        }
1661
                    },
1662
                    std::bind(PostOutputs, _1, _2, ctx)
1663 1664
                }
        );
1665 1666 1667 1668
    }
};


1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683
struct InferList: public cv::detail::KernelTag {
    using API = cv::GInferListBase;
    static cv::gapi::GBackend backend()  { return cv::gapi::ie::backend(); }
    static KImpl kernel()                { return KImpl{outMeta, run}; }

    static cv::GMetaArgs outMeta(const ade::Graph      &gr,
                                 const ade::NodeHandle &nh,
                                 const cv::GMetaArgs   &in_metas,
                                 const cv::GArgs       &/*in_args*/) {
        // Specify the input information to the IE from the framework
        // NB: Have no clue if network's input [dimensions] may ever define
        // its output dimensions. It seems possible with OpenCV DNN APIs

        GConstGIEModel gm(gr);
        const auto &uu = gm.metadata(nh).get<IEUnit>();
1684
        IE::ICNNNetwork::InputShapes input_reshape_table = uu.params.reshape_table;
1685 1686 1687 1688 1689 1690 1691

        // Initialize input information
        // Note our input layers list order matches the API order and so
        // meta order.
        GAPI_Assert(uu.params.input_names.size() == (in_metas.size() - 1u)
                    && "Known input layers count doesn't match input meta count");

1692 1693 1694 1695
        // NB: Configuring input precision and network reshape must be done
        // only in the loadNetwork case.
        if (uu.params.kind == cv::gapi::ie::detail::ParamDesc::Kind::Load) {
            std::size_t idx = 1u;
1696
            auto inputs = uu.net.getInputsInfo();
1697
            for (auto &&input_name : uu.params.input_names) {
1698
                auto ii = inputs.at(input_name);
1699
                const auto & mm = in_metas[idx++];
1700 1701 1702 1703 1704 1705 1706 1707 1708

                // NB: InferList expects the input starts with index 1 wil be the images.
                const auto input_trait = clarifyTrait(mm, ii->getTensorDesc());
                if (input_trait != cv::gapi::ie::TraitAs::IMAGE) {
                    util::throw_error(std::runtime_error(
                                "IE Backend: Only image is supported"
                                " as the " + std::to_string(idx) + "th argument for InferList"));
                }

1709 1710 1711 1712 1713
                configureInputInfo(ii, mm);
                if (uu.params.layer_names_to_reshape.find(input_name) !=
                    uu.params.layer_names_to_reshape.end()) {
                    configureInputReshapeByImage(ii, mm, input_reshape_table);
                }
1714 1715


1716
            }
1717

1718 1719 1720 1721 1722 1723
            // FIXME: This isn't the best place to call reshape function.
            // Сorrect solution would be to do this in compile() method of network,
            // but now input meta isn't passed to compile() method.
            if (!input_reshape_table.empty()) {
                const_cast<IE::CNNNetwork *>(&uu.net)->reshape(input_reshape_table);
            }
1724 1725 1726 1727 1728 1729

            for (auto &&p : uu.params.const_inputs) {
                const auto ii = inputs.at(p.first);
                ii->setPrecision(toIE(p.second.first.depth()));
            }

T
TolyaTalamanov 已提交
1730
            configureOutputPrecision(uu.net.getOutputsInfo(), uu.params.output_precision);
1731 1732 1733 1734 1735 1736 1737 1738
        } else {
            GAPI_Assert(uu.params.kind == cv::gapi::ie::detail::ParamDesc::Kind::Import);
            std::size_t idx = 1u;
            auto inputs = uu.this_network.GetInputsInfo();
            auto* non_const_prepm = const_cast<IEUnit::PreProcMap*>(&uu.preproc_map);
            for (auto &&input_name : uu.params.input_names) {
                auto ii = inputs.at(input_name);
                const auto & mm = in_metas[idx++];
1739 1740 1741 1742 1743 1744 1745 1746 1747

                // NB: InferList expects the input starts with index 1 wil be the images.
                const auto input_trait = clarifyTrait(mm, ii->getTensorDesc());
                if (input_trait != cv::gapi::ie::TraitAs::IMAGE) {
                    util::throw_error(std::runtime_error(
                                "IE Backend: Only image is supported"
                                " as the " + std::to_string(idx) + "th argument for InferList"));
                }

1748 1749
                non_const_prepm->emplace(input_name, configurePreProcInfo(ii, mm));
            }
1750 1751
        }

1752 1753 1754 1755 1756 1757 1758 1759
        // roi-list version is much easier at the moment.
        // All our outputs are vectors which don't have
        // metadata at the moment - so just create a vector of
        // "empty" array metadatas of the required size.
        return cv::GMetaArgs(uu.params.output_names.size(),
                             cv::GMetaArg{cv::empty_array_desc()});
    }

1760 1761
    static void run(std::shared_ptr<IECallContext>  ctx,
                    cv::gimpl::ie::RequestPool     &reqPool) {
1762 1763 1764 1765 1766
        const auto& in_roi_vec = ctx->inArg<cv::detail::VectorRef>(0u).rref<cv::Rect>();
        // NB: In case there is no input data need to post output anyway
        if (in_roi_vec.empty()) {
            for (auto i : ade::util::iota(ctx->uu.params.num_out)) {
                auto output = ctx->output(i);
1767
                ctx->out.meta(output, ctx->getMeta());
1768 1769 1770 1771
                ctx->out.post(std::move(output));
            }
            return;
        }
1772

1773 1774
        // NB: This blob will be used to make roi from its, so
        // it should be treated as image
1775 1776 1777
        IE::Blob::Ptr this_blob = extractBlob(*ctx, 1, cv::gapi::ie::TraitAs::IMAGE,
                                              ctx->uu.params.input_names[0u],
                                              cv::util::optional<cv::Rect>{});
1778

1779 1780
        std::vector<std::vector<int>> cached_dims(ctx->uu.params.num_out);
        for (auto i : ade::util::iota(ctx->uu.params.num_out)) {
1781 1782 1783 1784 1785 1786
            const auto& out_name = ctx->uu.params.output_names[i];
            const auto& desc =
                ctx->uu.params.kind == cv::gapi::ie::detail::ParamDesc::Kind::Load
                    ? ctx->uu.net.getOutputsInfo().at(out_name)->getTensorDesc()
                    : ctx->uu.this_network.GetOutputsInfo().at(out_name)->getTensorDesc();
            cached_dims[i] = toCV(desc.getDims());
1787 1788 1789 1790 1791 1792
            // FIXME: Isn't this should be done automatically
            // by some resetInternalData(), etc? (Probably at the GExecutor level)
            auto& out_vec = ctx->outVecR<cv::Mat>(i);
            out_vec.clear();
            out_vec.resize(in_roi_vec.size());
        }
1793

1794 1795 1796 1797
        PostOutputsList callback(in_roi_vec.size(), ctx, std::move(cached_dims));
        for (auto&& it : ade::util::indexed(in_roi_vec)) {
                  auto  pos = ade::util::index(it);
            const auto& rc  = ade::util::value(it);
1798 1799
            reqPool.getIdleRequest()->execute(
                IInferExecutor::Task {
1800
                    [ctx, rc, this_blob](InferenceEngine::InferRequest &req) {
1801
                        setROIBlob(req, ctx->uu.params.input_names[0u], this_blob, rc, *ctx);
1802
                    },
1803
                    std::bind(callback, std::placeholders::_1, std::placeholders::_2, pos)
1804 1805 1806
                }
            );
        }
1807 1808 1809
    }
};

1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824
struct InferList2: public cv::detail::KernelTag {
    using API = cv::GInferList2Base;
    static cv::gapi::GBackend backend()  { return cv::gapi::ie::backend(); }
    static KImpl kernel()                { return KImpl{outMeta, run}; }

    static cv::GMetaArgs outMeta(const ade::Graph      &gr,
                                 const ade::NodeHandle &nh,
                                 const cv::GMetaArgs   &in_metas,
                                 const cv::GArgs       &/*in_args*/) {
        // Specify the input information to the IE from the framework
        // NB: Have no clue if network's input [dimensions] may ever define
        // its output dimensions. It seems possible with OpenCV DNN APIs

        GConstGIEModel gm(gr);
        const auto &uu = gm.metadata(nh).get<IEUnit>();
1825
        IE::ICNNNetwork::InputShapes input_reshape_table = uu.params.reshape_table;
1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841

        // Initialize input information
        // Note our input layers list order matches the API order and so
        // meta order.
        GAPI_Assert(uu.params.input_names.size() == (in_metas.size() - 1u)
                    && "Known input layers count doesn't match input meta count");

        const auto &op = gm.metadata(nh).get<Op>();

        // In contrast to InferList, the InferList2 has only one
        // "full-frame" image argument, and all the rest are arrays of
        // ether ROI or blobs. So here we set the 0th arg image format
        // to all inputs which are ROI-based (skipping the
        // "blob"-based ones)
        // FIXME: this is filtering not done, actually! GArrayDesc has
        // no hint for its underlying type!
1842 1843

        const auto &input_name_0 = uu.params.input_names.front();
1844
        const auto &mm_0 = in_metas[0u];
1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856
        const auto &tensor_desc_0 =
            (uu.params.kind == cv::gapi::ie::detail::ParamDesc::Kind::Load)
             ? uu.net.getInputsInfo().at(input_name_0)->getTensorDesc()
             : uu.this_network.GetInputsInfo().at(input_name_0)->getTensorDesc();

        if (cv::util::holds_alternative<cv::GMatDesc>(mm_0) ||
            cv::util::holds_alternative<cv::GFrameDesc>(mm_0)) {
            const auto trait = clarifyTrait(mm_0, tensor_desc_0);
            if (trait != cv::gapi::ie::TraitAs::IMAGE) {
                util::throw_error(std::runtime_error(
                            "IE Backend: Only images is"
                            " supported as the 0th argument"));
1857
            }
1858 1859 1860 1861
        } else {
            util::throw_error(std::runtime_error(
                        "IE Backend: Unsupported input meta"
                        " for 0th argument in IE backend"));
1862 1863
        }

1864 1865 1866 1867 1868 1869
        std::size_t idx = 1u;
        for (auto &&input_name : uu.params.input_names) {
            const auto &mm = in_metas[idx];
            GAPI_Assert(util::holds_alternative<cv::GArrayDesc>(mm)
                        && "Non-array inputs are not supported");

1870
            if (op.k.inKinds[idx] == cv::detail::OpaqueKind::CV_RECT) {
1871 1872 1873
                // NB: Configuring input precision and network reshape must be done
                // only in the loadNetwork case.
                if (uu.params.kind == cv::gapi::ie::detail::ParamDesc::Kind::Load) {
T
TolyaTalamanov 已提交
1874
                    auto inputs = uu.net.getInputsInfo();
1875
                    // This is a cv::Rect -- configure the IE preprocessing
T
TolyaTalamanov 已提交
1876
                    auto ii = inputs.at(input_name);
1877 1878 1879 1880 1881 1882
                    configureInputInfo(ii, mm_0);
                    if (uu.params.layer_names_to_reshape.find(input_name) !=
                        uu.params.layer_names_to_reshape.end()) {
                        configureInputReshapeByImage(ii, mm_0, input_reshape_table);
                    }

1883
                    for (auto &&p : uu.params.const_inputs) {
T
TolyaTalamanov 已提交
1884
                        inputs.at(p.first)->setPrecision(toIE(p.second.first.depth()));
1885 1886
                    }

1887 1888 1889 1890 1891 1892
                    // FIXME: This isn't the best place to call reshape function.
                    // Сorrect solution would be to do this in compile() method of network,
                    // but now input meta isn't passed to compile() method.
                    if (!input_reshape_table.empty()) {
                        const_cast<IE::CNNNetwork *>(&uu.net)->reshape(input_reshape_table);
                    }
T
TolyaTalamanov 已提交
1893
                    configureOutputPrecision(uu.net.getOutputsInfo(), uu.params.output_precision);
1894 1895 1896 1897 1898 1899
                } else {
                    GAPI_Assert(uu.params.kind == cv::gapi::ie::detail::ParamDesc::Kind::Import);
                    auto inputs = uu.this_network.GetInputsInfo();
                    auto* non_const_prepm = const_cast<IEUnit::PreProcMap*>(&uu.preproc_map);
                    auto ii = inputs.at(input_name);
                    non_const_prepm->emplace(input_name, configurePreProcInfo(ii, mm_0));
1900
                }
1901 1902 1903 1904
            } else {
                // This is a cv::GMat (equals to: cv::Mat)
                // Just validate that it is really the type
                // (other types are prohibited here)
1905
                GAPI_Assert(op.k.inKinds[idx] == cv::detail::OpaqueKind::CV_MAT);
1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917
            }
            idx++; // NB: Never forget to increment the counter
        }

        // roi-list version is much easier at the moment.
        // All our outputs are vectors which don't have
        // metadata at the moment - so just create a vector of
        // "empty" array metadatas of the required size.
        return cv::GMetaArgs(uu.params.output_names.size(),
                             cv::GMetaArg{cv::empty_array_desc()});
    }

1918 1919
    static void run(std::shared_ptr<IECallContext> ctx,
                    cv::gimpl::ie::RequestPool    &reqPool) {
1920 1921
        GAPI_Assert(ctx->inArgs().size() > 1u
                && "This operation must have at least two arguments");
1922 1923
        // NB: This blob will be used to make roi from its, so
        // it should be treated as image
1924 1925 1926
        IE::Blob::Ptr blob_0 = extractBlob(*ctx, 0, cv::gapi::ie::TraitAs::IMAGE,
                                           ctx->uu.params.input_names[0u],
                                           cv::util::optional<cv::Rect>{});
1927 1928 1929 1930
        const auto list_size = ctx->inArg<cv::detail::VectorRef>(1u).size();
        if (list_size == 0u) {
            for (auto i : ade::util::iota(ctx->uu.params.num_out)) {
                auto output = ctx->output(i);
1931
                ctx->out.meta(output, ctx->getMeta());
1932 1933 1934 1935 1936 1937 1938
                ctx->out.post(std::move(output));
            }
            return;
        }
        // FIXME: This could be done ONCE at graph compile stage!
        std::vector< std::vector<int> > cached_dims(ctx->uu.params.num_out);
        for (auto i : ade::util::iota(ctx->uu.params.num_out)) {
1939 1940 1941 1942 1943 1944
            const auto& out_name = ctx->uu.params.output_names[i];
            const auto& desc =
                ctx->uu.params.kind == cv::gapi::ie::detail::ParamDesc::Kind::Load
                    ? ctx->uu.net.getOutputsInfo().at(out_name)->getTensorDesc()
                    : ctx->uu.this_network.GetOutputsInfo().at(out_name)->getTensorDesc();
            cached_dims[i] = toCV(desc.getDims());
1945 1946 1947 1948 1949 1950
            // FIXME: Isn't this should be done automatically
            // by some resetInternalData(), etc? (Probably at the GExecutor level)
            auto& out_vec = ctx->outVecR<cv::Mat>(i);
            out_vec.clear();
            out_vec.resize(list_size);
        }
1951

1952 1953
        PostOutputsList callback(list_size, ctx, std::move(cached_dims));
        for (const auto &list_idx : ade::util::iota(list_size)) {
1954 1955
            reqPool.getIdleRequest()->execute(
                IInferExecutor::Task {
1956 1957 1958 1959 1960 1961
                    [ctx, list_idx, list_size, blob_0](InferenceEngine::InferRequest &req) {
                        for (auto in_idx : ade::util::iota(ctx->uu.params.num_in)) {
                            const auto &this_vec = ctx->inArg<cv::detail::VectorRef>(in_idx+1u);
                            GAPI_Assert(this_vec.size() == list_size);
                            if (this_vec.getKind() == cv::detail::OpaqueKind::CV_RECT) {
                                const auto &vec = this_vec.rref<cv::Rect>();
1962 1963
                                setROIBlob(req, ctx->uu.params.input_names[in_idx],
                                           blob_0, vec[list_idx], *ctx);
1964 1965 1966
                            } else if (this_vec.getKind() == cv::detail::OpaqueKind::CV_MAT) {
                                const auto &vec = this_vec.rref<cv::Mat>();
                                const auto &mat = vec[list_idx];
1967 1968 1969
                                setBlob(req, ctx->uu.params.input_names[in_idx],
                                        wrapIE(mat, cv::gapi::ie::TraitAs::TENSOR),
                                        *ctx);
1970 1971 1972
                            } else {
                                GAPI_Assert(false &&
                                        "Only Rect and Mat types are supported for infer list 2!");
1973
                            }
1974
                        }
1975
                    },
1976
                    std::bind(callback, std::placeholders::_1, std::placeholders::_2, list_idx)
1977
                } // task
1978
            );
1979
        } // for
1980 1981 1982
    }
};

1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997
} // namespace ie
} // namespace gapi
} // namespace cv


// IE backend implementation of GBackend::Priv ///////////////////////
namespace {
    class GIEBackendImpl final: public cv::gapi::GBackend::Priv {
        virtual void unpackKernel(ade::Graph            &gr,
                                  const ade::NodeHandle &nh,
                                  const cv::GKernelImpl &ii) override {
            using namespace cv::gimpl;
            // FIXME: Introduce a DNNBackend interface which'd specify
            // the framework for this???
            GIEModel gm(gr);
1998 1999
            auto &np = gm.metadata(nh).get<NetworkParams>();
            auto &pp = cv::util::any_cast<cv::gapi::ie::detail::ParamDesc>(np.opaque);
2000
            const auto &ki = cv::util::any_cast<KImpl>(ii.opaque);
2001 2002 2003 2004 2005 2006 2007

            GModel::Graph model(gr);
            auto& op = model.metadata(nh).get<Op>();

            // NB: In case generic infer, info about in/out names is stored in operation (op.params)
            if (pp.is_generic)
            {
2008
                auto& info      = cv::util::any_cast<cv::detail::InOutInfo>(op.params);
2009 2010 2011 2012 2013 2014
                pp.input_names  = info.in_names;
                pp.output_names = info.out_names;
                pp.num_in       = info.in_names.size();
                pp.num_out      = info.out_names.size();
            }

2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025
            gm.metadata(nh).set(IEUnit{pp});
            gm.metadata(nh).set(IECallable{ki.run});
            gm.metadata(nh).set(CustomMetaFunction{ki.customMetaFunc});
        }

        virtual EPtr compile(const ade::Graph &graph,
                             const cv::GCompileArgs &,
                             const std::vector<ade::NodeHandle> &nodes) const override {
            return EPtr{new cv::gimpl::ie::GIEExecutable(graph, nodes)};
        }

2026
        virtual cv::GKernelPackage auxiliaryKernels() const override {
2027
            return cv::gapi::kernels< cv::gimpl::ie::Infer
2028
                                    , cv::gimpl::ie::InferROI
2029
                                    , cv::gimpl::ie::InferList
2030
                                    , cv::gimpl::ie::InferList2
2031 2032
                                    >();
        }
2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043

        virtual bool controlsMerge() const override {
            return true;
        }

        virtual bool allowsMerge(const cv::gimpl::GIslandModel::Graph &,
                                 const ade::NodeHandle &,
                                 const ade::NodeHandle &,
                                 const ade::NodeHandle &) const override {
            return false;
        }
2044 2045 2046 2047 2048 2049 2050 2051
    };
}

cv::gapi::GBackend cv::gapi::ie::backend() {
    static cv::gapi::GBackend this_backend(std::make_shared<GIEBackendImpl>());
    return this_backend;
}

2052
cv::Mat cv::gapi::ie::util::to_ocv(IE::Blob::Ptr blob) {
2053 2054 2055 2056 2057 2058
    const auto& tdesc = blob->getTensorDesc();
    return cv::Mat(toCV(tdesc.getDims()),
                   toCV(tdesc.getPrecision()),
                   blob->buffer().as<uint8_t*>());
}

2059
std::vector<int> cv::gapi::ie::util::to_ocv(const IE::SizeVector &dims) {
2060 2061 2062
    return toCV(dims);
}

2063
IE::Blob::Ptr cv::gapi::ie::util::to_ie(const cv::Mat &blob) {
2064
    return wrapIE(blob, cv::gapi::ie::TraitAs::IMAGE);
2065 2066
}

2067
IE::Blob::Ptr cv::gapi::ie::util::to_ie(const cv::Mat &y_plane, const cv::Mat &uv_plane) {
2068 2069 2070 2071 2072 2073 2074 2075 2076
    auto y_blob   = wrapIE(y_plane,  cv::gapi::ie::TraitAs::IMAGE);
    auto uv_blob  = wrapIE(uv_plane, cv::gapi::ie::TraitAs::IMAGE);
#if INF_ENGINE_RELEASE >= 2021010000
    return IE::make_shared_blob<IE::NV12Blob>(y_blob, uv_blob);
#else
    return IE::make_shared_blob<InferenceEngine::NV12Blob>(y_blob, uv_blob);
#endif
}

2077 2078
#else // HAVE_INF_ENGINE

2079 2080 2081 2082
cv::gapi::GBackend cv::gapi::ie::backend() {
    // Still provide this symbol to avoid linking issues
    util::throw_error(std::runtime_error("G-API has been compiled without OpenVINO IE support"));
}
2083
#endif // HAVE_INF_ENGINE