wrapper.hpp 46.2 KB
Newer Older
G
gineshidalgo99 已提交
1 2 3 4
#ifndef OPENPOSE__WRAPPER__WRAPPER_HPP
#define OPENPOSE__WRAPPER__WRAPPER_HPP

#include "../thread/headers.hpp"
G
gineshidalgo99 已提交
5 6 7 8
#include "wrapperStructPose.hpp"
#include "wrapperStructHands.hpp"
#include "wrapperStructInput.hpp"
#include "wrapperStructOutput.hpp"
G
gineshidalgo99 已提交
9 10 11

namespace op
{
G
gineshidalgo99 已提交
12 13 14 15 16 17 18 19 20 21 22 23 24 25
    /**
     * Wrapper: OpenPose all-in-one wrapper template class.
     * Wrapper allows the user to set up the input (video, webcam, custom input, etc.), pose, face and/or hands estimation and rendering,
     * and output (integrated small GUI, custom output, etc.).
     *
     * This function can be used in 2 ways:
     *     - Synchronous mode: call the full constructor with your desired input and output workers.
     *     - Asynchronous mode: call the empty constructor Wrapper() + use the emplace and pop functions to push the original frames and
     *       retrieve the processed ones.
     *     - Mix of them:
     *         - Synchronous input + asynchronous output: call the constructor Wrapper(ThreadManagerMode::Synchronous, workersInput, {}, true)
     *         - Asynchronous input + synchronous output: call the constructor
     *           Wrapper(ThreadManagerMode::Synchronous, nullptr, workersOutput, irrelevantBoolean, true)
     */
G
gineshidalgo99 已提交
26 27 28 29
    template<typename TDatums, typename TWorker = std::shared_ptr<Worker<std::shared_ptr<TDatums>>>, typename TQueue = Queue<std::shared_ptr<TDatums>>>
    class Wrapper
    {
    public:
G
gineshidalgo99 已提交
30 31 32 33 34 35 36 37 38 39 40 41
        /**
         * Constructor.
         * @param threadManagerMode Thread syncronization mode. If set to ThreadManagerMode::Synchronous, everything will run inside the Wrapper. If
         * ThreadManagerMode::Synchronous(In/Out), then input (frames producer) and/or output (GUI, writing results, etc.) will be controlled
         * outside the Wrapper class by the user. See ThreadManagerMode for a detailed explanation of when to use each one.
         */
        explicit Wrapper(const ThreadManagerMode threadManagerMode = ThreadManagerMode::Synchronous);

        /**
         * Destructor.
         * It automatically frees resources.
         */
G
gineshidalgo99 已提交
42 43
        ~Wrapper();

G
gineshidalgo99 已提交
44 45 46 47 48 49 50 51 52 53 54 55 56
        /**
         * Disable multi-threading.
         * Useful for debugging and logging, all the Workers will run in the same thread.
         * Note that workerOnNewThread (argument for setWorkerInput, setWorkerPostProcessing and setWorkerOutput) will not make any effect.
         */
        void disableMultiThreading();

        /**
         * Add an user-defined extra Worker as frames generator.
         * @param worker TWorker to be added.
         * @param workerOnNewThread Whether to add this TWorker on a new thread (if it is computationally demanding) or simply reuse
         * existing threads (for light functions). Set to true if the performance time is unknown.
         */
G
gineshidalgo99 已提交
57 58
        void setWorkerInput(const TWorker& worker, const bool workerOnNewThread = true);

G
gineshidalgo99 已提交
59 60 61 62 63 64
        /**
         * Add an user-defined extra Worker as frames post-processor.
         * @param worker TWorker to be added.
         * @param workerOnNewThread Whether to add this TWorker on a new thread (if it is computationally demanding) or simply reuse
         * existing threads (for light functions). Set to true if the performance time is unknown.
         */
G
gineshidalgo99 已提交
65 66
        void setWorkerPostProcessing(const TWorker& worker, const bool workerOnNewThread = true);

G
gineshidalgo99 已提交
67 68 69 70 71 72
        /**
         * Add an user-defined extra Worker as frames consumer (custom display and/or saving).
         * @param worker TWorker to be added.
         * @param workerOnNewThread Whether to add this TWorker on a new thread (if it is computationally demanding) or simply reuse
         * existing threads (for light functions). Set to true if the performance time is unknown.
         */
G
gineshidalgo99 已提交
73 74
        void setWorkerOutput(const TWorker& worker, const bool workerOnNewThread = true);

G
gineshidalgo99 已提交
75 76 77 78 79
        // If output is not required, just use this function until the renderOutput argument. Keep the default values for the other parameters
        // in order not to display/save any output.
        void configure(const WrapperStructPose& wrapperStructPose,
                       // Producer (set producerSharedPtr = nullptr or use the default WrapperStructInput{} to disable any input)
                       const WrapperStructInput& wrapperStructInput = WrapperStructInput{},
G
gineshidalgo99 已提交
80
                       // Consumer (keep default values to disable any output)
G
gineshidalgo99 已提交
81
                       const WrapperStructOutput& wrapperStructOutput = WrapperStructOutput{});
G
gineshidalgo99 已提交
82 83

        // Similar to the previos configure, but it includes hand extraction and rendering
G
gineshidalgo99 已提交
84 85 86 87 88
        void configure(const WrapperStructPose& wrapperStructPose = WrapperStructPose{},
                       // Hand (use the default WrapperStructHands{} to disable any hand detector)
                       const experimental::WrapperStructHands& wrapperHandStruct = experimental::WrapperStructHands{},
                       // Producer (set producerSharedPtr = nullptr or use the default WrapperStructInput{} to disable any input)
                       const WrapperStructInput& wrapperStructInput = WrapperStructInput{},
G
gineshidalgo99 已提交
89
                       // Consumer (keep default values to disable any output)
G
gineshidalgo99 已提交
90
                       const WrapperStructOutput& wrapperStructOutput = WrapperStructOutput{});
G
gineshidalgo99 已提交
91

G
gineshidalgo99 已提交
92 93 94 95 96
        /**
         * Function to start multi-threading.
         * Similar to start(), but exec() blocks the thread that calls the function (it saves 1 thread). Use exec() instead of
         * start() if the calling thread will otherwise be waiting for the Wrapper to end.
         */
G
gineshidalgo99 已提交
97 98
        void exec();

G
gineshidalgo99 已提交
99 100 101 102 103
        /**
         * Function to start multi-threading.
         * Similar to exec(), but start() does not block the thread that calls the function. It just opens new threads, so it
         * lets the user perform other tasks meanwhile on the calling thread.
         */
G
gineshidalgo99 已提交
104 105
        void start();

G
gineshidalgo99 已提交
106 107 108 109
        /**
         * Function to stop multi-threading.
         * It can be called internally or externally.
         */
G
gineshidalgo99 已提交
110 111
        void stop();

G
gineshidalgo99 已提交
112 113 114 115 116
        /**
         * Whether the Wrapper is running.
         * It will return true after exec() or start() and before stop(), and false otherwise.
         * @return Boolean specifying whether the Wrapper is running.
         */
G
gineshidalgo99 已提交
117 118
        bool isRunning() const;

G
gineshidalgo99 已提交
119 120 121 122 123 124 125
        /**
         * Emplace (move) an element on the first (input) queue.
         * Only valid if ThreadManagerMode::Asynchronous or ThreadManagerMode::AsynchronousIn.
         * If the input queue is full or the Wrapper was stopped, it will return false and not emplace it.
         * @param tDatums std::shared_ptr<TDatums> element to be emplaced.
         * @return Boolean specifying whether the tDatums could be emplaced.
         */
G
gineshidalgo99 已提交
126 127
        bool tryEmplace(std::shared_ptr<TDatums>& tDatums);

G
gineshidalgo99 已提交
128 129 130 131 132 133 134 135
        /**
         * Emplace (move) an element on the first (input) queue.
         * Similar to tryEmplace.
         * However, if the input queue is full, it will wait until it can emplace it.
         * If the Wrapper class is stopped before adding the element, it will return false and not emplace it.
         * @param tDatums std::shared_ptr<TDatums> element to be emplaced.
         * @return Boolean specifying whether the tDatums could be emplaced.
         */
G
gineshidalgo99 已提交
136 137
        bool waitAndEmplace(std::shared_ptr<TDatums>& tDatums);

G
gineshidalgo99 已提交
138 139 140 141 142 143
        /**
         * Push (copy) an element on the first (input) queue.
         * Same as tryEmplace, but it copies the data instead of moving it.
         * @param tDatums std::shared_ptr<TDatums> element to be pushed.
         * @return Boolean specifying whether the tDatums could be pushed.
         */
G
gineshidalgo99 已提交
144 145
        bool tryPush(const std::shared_ptr<TDatums>& tDatums);

G
gineshidalgo99 已提交
146 147 148 149 150 151
        /**
         * Push (copy) an element on the first (input) queue.
         * Same as waitAndEmplace, but it copies the data instead of moving it.
         * @param tDatums std::shared_ptr<TDatums> element to be pushed.
         * @return Boolean specifying whether the tDatums could be pushed.
         */
G
gineshidalgo99 已提交
152 153
        bool waitAndPush(const std::shared_ptr<TDatums>& tDatums);

G
gineshidalgo99 已提交
154 155 156 157 158 159 160
        /**
         * Pop (retrieve) an element from the last (output) queue.
         * Only valid if ThreadManagerMode::Asynchronous or ThreadManagerMode::AsynchronousOut.
         * If the output queue is empty or the Wrapper was stopped, it will return false and not retrieve it.
         * @param tDatums std::shared_ptr<TDatums> element where the retrieved element will be placed.
         * @return Boolean specifying whether the tDatums could be retrieved.
         */
G
gineshidalgo99 已提交
161 162
        bool tryPop(std::shared_ptr<TDatums>& tDatums);

G
gineshidalgo99 已提交
163 164 165 166 167 168 169 170
        /**
         * Pop (retrieve) an element from the last (output) queue.
         * Similar to tryPop.
         * However, if the output queue is empty, it will wait until it can pop an element.
         * If the Wrapper class is stopped before popping the element, it will return false and not retrieve it.
         * @param tDatums std::shared_ptr<TDatums> element where the retrieved element will be placed.
         * @return Boolean specifying whether the tDatums could be retrieved.
         */
G
gineshidalgo99 已提交
171 172 173
        bool waitAndPop(std::shared_ptr<TDatums>& tDatums);

    private:
G
gineshidalgo99 已提交
174
        const ThreadManagerMode mThreadManagerMode;
G
gineshidalgo99 已提交
175 176 177 178 179 180 181
        const std::shared_ptr<std::pair<std::atomic<bool>, std::atomic<int>>> spVideoSeek;
        ThreadManager<std::shared_ptr<TDatums>> mThreadManager;
        int mGpuNumber;
        bool mUserInputWsOnNewThread;
        bool mUserPostProcessingWsOnNewThread;
        bool mUserOutputWsOnNewThread;
        unsigned int mThreadId;
G
gineshidalgo99 已提交
182
        bool mMultiThreadEnabled;
G
gineshidalgo99 已提交
183 184 185 186 187 188 189 190 191 192 193 194 195
        // Workers
        std::vector<TWorker> mUserInputWs;
        TWorker wDatumProducer;
        TWorker spWIdGenerator;
        TWorker spWCvMatToOpInput;
        TWorker spWCvMatToOpOutput;
        std::vector<std::vector<TWorker>> spWPoses;
        std::vector<TWorker> mPostProcessingWs;
        std::vector<TWorker> mUserPostProcessingWs;
        std::vector<TWorker> mOutputWs;
        TWorker spWGui;
        std::vector<TWorker> mUserOutputWs;

G
gineshidalgo99 已提交
196 197 198 199 200 201 202 203 204 205 206 207
        /**
         * Frees TWorker variables (private internal function).
         * For most cases, this class is non-necessary, since std::shared_ptr are automatically cleaned on destruction of each class.
         * However, it might be useful if the same Wrapper is gonna be started twice (not recommended on most cases).
         */
        void reset();

        /**
         * Set ThreadManager from TWorkers (private internal function).
         * After any configure() has been called, the TWorkers are initialized. This function resets the ThreadManager and adds them. 
         * Common code for start() and exec().
         */
G
gineshidalgo99 已提交
208 209
        void configureThreadManager();

G
gineshidalgo99 已提交
210 211 212 213 214 215 216
        /**
         * Thread ID increase (private internal function).
         * If multi-threading mode, it increases the thread ID.
         * If single-threading mode (for debugging), it does not modify it.
         * Note that mThreadId must be re-initialized to 0 before starting a new Wrapper configuration.
         * @return unsigned int with the next thread id value.
         */
G
gineshidalgo99 已提交
217 218
        unsigned int threadIdPP();

G
gineshidalgo99 已提交
219 220 221 222 223 224 225 226 227
        /**
         * TWorker concatenator (private internal function).
         * Auxiliary function that concatenate std::vectors of TWorker. Since TWorker is some kind of smart pointer (usually
         * std::shared_ptr), its copy still shares the same internal data. It will not work for TWorker classes that do not share
         * the data when moved.
         * @param workersA First std::shared_ptr<TDatums> element to be concatenated.
         * @param workersB Second std::shared_ptr<TDatums> element to be concatenated.
         * @return Concatenated std::vector<TWorker> of both workersA and workersB.
         */
G
gineshidalgo99 已提交
228 229 230 231 232 233 234 235 236 237 238
        std::vector<TWorker> mergeWorkers(const std::vector<TWorker>& workersA, const std::vector<TWorker>& workersB);

        DELETE_COPY(Wrapper);
    };
}





// Implementation
G
gineshidalgo99 已提交
239
#include "../core/headers.hpp"
G
gineshidalgo99 已提交
240
#include "../experimental/headers.hpp"
G
gineshidalgo99 已提交
241
#include "../filestream/headers.hpp"
G
gineshidalgo99 已提交
242
#include "../gui/headers.hpp"
G
gineshidalgo99 已提交
243 244
#include "../pose/headers.hpp"
#include "../producer/headers.hpp"
G
gineshidalgo99 已提交
245 246 247 248 249
#include "../utilities/errorAndLog.hpp"
#include "../utilities/fileSystem.hpp"
namespace op
{
    template<typename TDatums, typename TWorker, typename TQueue>
G
gineshidalgo99 已提交
250 251
    Wrapper<TDatums, TWorker, TQueue>::Wrapper(const ThreadManagerMode threadManagerMode) :
        mThreadManagerMode{threadManagerMode},
G
gineshidalgo99 已提交
252
        spVideoSeek{std::make_shared<std::pair<std::atomic<bool>, std::atomic<int>>>()},
G
gineshidalgo99 已提交
253 254
        mThreadManager{threadManagerMode},
        mMultiThreadEnabled{true}
G
gineshidalgo99 已提交
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
    {
        try
        {
            // It cannot be directly included in the constructor, otherwise compiler error for copying std::atomic
            spVideoSeek->first = false;
            spVideoSeek->second = 0;
        }
        catch (const std::exception& e)
        {
            error(e.what(), __LINE__, __FUNCTION__, __FILE__);
        }
    }

    template<typename TDatums, typename TWorker, typename TQueue>
    Wrapper<TDatums, TWorker, TQueue>::~Wrapper()
    {
        try
        {
            stop();
            reset();
        }
        catch (const std::exception& e)
        {
            error(e.what(), __LINE__, __FUNCTION__, __FILE__);
        }
    }

    template<typename TDatums, typename TWorker, typename TQueue>
G
gineshidalgo99 已提交
283
    void Wrapper<TDatums, TWorker, TQueue>::disableMultiThreading()
G
gineshidalgo99 已提交
284 285 286
    {
        try
        {
G
gineshidalgo99 已提交
287
            mMultiThreadEnabled = false;
G
gineshidalgo99 已提交
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
        }
        catch (const std::exception& e)
        {
            error(e.what(), __LINE__, __FUNCTION__, __FILE__);
        }
    }

    template<typename TDatums, typename TWorker, typename TQueue>
    void Wrapper<TDatums, TWorker, TQueue>::setWorkerInput(const TWorker& worker, const bool workerOnNewThread)
    {
        try
        {
            mUserInputWs.clear();
            if (worker == nullptr)
                error("Your worker is a nullptr.", __LINE__, __FILE__, __FUNCTION__);
            mUserInputWs.emplace_back(worker);
            mUserInputWsOnNewThread = {workerOnNewThread};
        }
        catch (const std::exception& e)
        {
            error(e.what(), __LINE__, __FUNCTION__, __FILE__);
        }
    }

    template<typename TDatums, typename TWorker, typename TQueue>
    void Wrapper<TDatums, TWorker, TQueue>::setWorkerPostProcessing(const TWorker& worker, const bool workerOnNewThread)
    {
        try
        {
            mUserPostProcessingWs.clear();
            if (worker == nullptr)
                error("Your worker is a nullptr.", __LINE__, __FILE__, __FUNCTION__);
            mUserPostProcessingWs.emplace_back(worker);
            mUserPostProcessingWsOnNewThread = {workerOnNewThread};
        }
        catch (const std::exception& e)
        {
            error(e.what(), __LINE__, __FUNCTION__, __FILE__);
        }
    }

    template<typename TDatums, typename TWorker, typename TQueue>
    void Wrapper<TDatums, TWorker, TQueue>::setWorkerOutput(const TWorker& worker, const bool workerOnNewThread)
    {
        try
        {
            mUserOutputWs.clear();
            if (worker == nullptr)
                error("Your worker is a nullptr.", __LINE__, __FILE__, __FUNCTION__);
            mUserOutputWs.emplace_back(worker);
            mUserOutputWsOnNewThread = {workerOnNewThread};
        }
        catch (const std::exception& e)
        {
            error(e.what(), __LINE__, __FUNCTION__, __FILE__);
        }
    }

    template<typename TDatums, typename TWorker, typename TQueue>
G
gineshidalgo99 已提交
347 348
    void Wrapper<TDatums, TWorker, TQueue>::configure(const WrapperStructPose& wrapperStructPose, const WrapperStructInput& wrapperStructInput,
                                                      const WrapperStructOutput& wrapperStructOutput)
G
gineshidalgo99 已提交
349 350 351
    {
        try
        {
G
gineshidalgo99 已提交
352
            configure(wrapperStructPose, experimental::WrapperStructHands{}, wrapperStructInput, wrapperStructOutput);
G
gineshidalgo99 已提交
353 354 355 356 357 358 359 360
        }
        catch (const std::exception& e)
        {
            error(e.what(), __LINE__, __FUNCTION__, __FILE__);
        }
    }

    template<typename TDatums, typename TWorker, typename TQueue>
G
gineshidalgo99 已提交
361 362
    void Wrapper<TDatums, TWorker, TQueue>::configure(const WrapperStructPose& wrapperStructPose, const experimental::WrapperStructHands& wrapperHandStruct,
                                                      const WrapperStructInput& wrapperStructInput, const WrapperStructOutput& wrapperStructOutput)
G
gineshidalgo99 已提交
363 364 365 366 367 368 369 370 371
    {
        try
        {
            log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);

            // Shortcut
            typedef std::shared_ptr<TDatums> TDatumsPtr;

            // Check no contradictory flags enabled
G
gineshidalgo99 已提交
372 373
            if (wrapperStructPose.alphaPose < 0. || wrapperStructPose.alphaPose > 1. || wrapperStructPose.alphaHeatMap < 0.
                || wrapperStructPose.alphaHeatMap > 1.)
G
gineshidalgo99 已提交
374
                error("Alpha value for blending must be in the range [0,1].", __LINE__, __FUNCTION__, __FILE__);
G
gineshidalgo99 已提交
375
            if (wrapperStructPose.scaleGap <= 0.f && wrapperStructPose.scalesNumber > 1)
G
gineshidalgo99 已提交
376
                error("The scale gap must be greater than 0 (it has no effect if the number of scales is 1).", __LINE__, __FUNCTION__, __FILE__);
G
gineshidalgo99 已提交
377 378 379 380 381 382
            if (!wrapperStructPose.renderOutput && (!wrapperStructOutput.writeImages.empty() || !wrapperStructOutput.writeVideo.empty()))
            {
                const auto message = "In order to save the rendered frames (`write_images` or `write_video`), you must set `render_output` to true.";
                error(message, __LINE__, __FUNCTION__, __FILE__);
            }
            if (!wrapperStructOutput.writeHeatMaps.empty() && wrapperStructPose.heatMapTypes.empty())
G
gineshidalgo99 已提交
383 384
            {
                const auto message = "In order to save the heatmaps (`write_heatmaps`), you need to pick which heat maps you want to save: `heatmaps_add_X`"
G
gineshidalgo99 已提交
385
                                     " flags or fill the wrapperStructPose.heatMapTypes.";
G
gineshidalgo99 已提交
386 387
                error(message, __LINE__, __FUNCTION__, __FILE__);
            }
G
gineshidalgo99 已提交
388
            if (!wrapperStructOutput.writeHeatMaps.empty() && wrapperStructPose.heatMapScaleMode != ScaleMode::UnsignedChar)
G
gineshidalgo99 已提交
389
            {
G
gineshidalgo99 已提交
390 391 392 393 394 395 396 397 398 399 400 401
                const auto message = "In order to save the heatmaps, you must set wrapperStructPose.heatMapScaleMode to ScaleMode::UnsignedChar,"
                                     " i.e. range [0, 255].";
                error(message, __LINE__, __FUNCTION__, __FILE__);
            }
            if (mUserOutputWs.empty() && mThreadManagerMode != ThreadManagerMode::Asynchronous && mThreadManagerMode != ThreadManagerMode::AsynchronousOut)
            {
                const std::string additionalMessage = " You could also set mThreadManagerMode = mThreadManagerMode::Asynchronous(Out) and/or add your own output worker"
                                                      " class before calling this function.";
                const auto savingSomething = (!wrapperStructOutput.writeImages.empty() || !wrapperStructOutput.writeVideo.empty()
                                              || !wrapperStructOutput.writePose.empty() || !wrapperStructOutput.writePoseJson.empty()
                                              || !wrapperStructOutput.writeCocoJson.empty() || !wrapperStructOutput.writeHeatMaps.empty());
                if (!wrapperStructOutput.displayGui && !savingSomething)
G
gineshidalgo99 已提交
402
                {
G
gineshidalgo99 已提交
403 404
                    const auto message = "No output is selected (`no_display`) and no results are generated (no `write_X` flags enabled). Thus,"
                                         " no output would be generated." + additionalMessage;
G
gineshidalgo99 已提交
405 406 407
                    error(message, __LINE__, __FUNCTION__, __FILE__);
                }

G
gineshidalgo99 已提交
408
                if ((wrapperStructOutput.displayGui && wrapperStructOutput.guiVerbose) && !wrapperStructPose.renderOutput)
G
gineshidalgo99 已提交
409
                {
G
gineshidalgo99 已提交
410 411
                    const auto message = "No render is enabled (`no_render_output`), so you should also remove the display (set `no_display`"
                                         " or `no_gui_verbose`)." + additionalMessage;
G
gineshidalgo99 已提交
412 413
                    error(message, __LINE__, __FUNCTION__, __FILE__);
                }
G
gineshidalgo99 已提交
414
                if (wrapperStructInput.framesRepeat && savingSomething)
G
gineshidalgo99 已提交
415 416 417 418 419
                {
                    const auto message = "Frames repetition (`frames_repeat`) is enabled as well as some writing function (`write_X`). This program would"
                                         " never stop recording the same frames over and over. Please, disable repetition or remove writing.";
                    error(message, __LINE__, __FUNCTION__, __FILE__);
                }
G
gineshidalgo99 已提交
420
                if (wrapperStructInput.realTimeProcessing && savingSomething)
G
gineshidalgo99 已提交
421
                {
G
gineshidalgo99 已提交
422 423
                    const auto message = "Real time processing is enabled as well as some writing function. Thus, some frames might be skipped. Consider"
                                         " disabling real time processing if you intend to save any results.";
G
gineshidalgo99 已提交
424 425 426
                    log(message, Priority::Max, __LINE__, __FUNCTION__, __FILE__);
                }
            }
G
gineshidalgo99 已提交
427 428
            if (!wrapperStructOutput.writeVideo.empty() && wrapperStructInput.producerSharedPtr == nullptr)
                error("Writting video is only available if the OpenPose producer is used (i.e. wrapperStructInput.producerSharedPtr cannot be a nullptr).");
G
gineshidalgo99 已提交
429 430

            // Proper format
G
gineshidalgo99 已提交
431 432 433 434
            const auto writeImagesCleaned = formatAsDirectory(wrapperStructOutput.writeImages);
            const auto writePoseCleaned = formatAsDirectory(wrapperStructOutput.writePose);
            const auto writePoseJsonCleaned = formatAsDirectory(wrapperStructOutput.writePoseJson);
            const auto writeHeatMapsCleaned = formatAsDirectory(wrapperStructOutput.writeHeatMaps);
G
gineshidalgo99 已提交
435 436

            // Common parameters
G
gineshidalgo99 已提交
437
            auto finalOutputSize = wrapperStructPose.outputSize;
G
gineshidalgo99 已提交
438
            cv::Size producerSize{-1,-1};
G
gineshidalgo99 已提交
439
            if (wrapperStructInput.producerSharedPtr != nullptr)
G
gineshidalgo99 已提交
440 441
            {
                // 1. Set producer properties
G
gineshidalgo99 已提交
442 443 444 445 446
                const auto displayProducerFpsMode = (wrapperStructInput.realTimeProcessing ? ProducerFpsMode::OriginalFps : ProducerFpsMode::RetrievalFps);
                wrapperStructInput.producerSharedPtr->setProducerFpsMode(displayProducerFpsMode);
                wrapperStructInput.producerSharedPtr->set(ProducerProperty::Flip, wrapperStructInput.frameFlip);
                wrapperStructInput.producerSharedPtr->set(ProducerProperty::Rotation, wrapperStructInput.frameRotate);
                wrapperStructInput.producerSharedPtr->set(ProducerProperty::AutoRepeat, wrapperStructInput.framesRepeat);
G
gineshidalgo99 已提交
447
                // 2. Set finalOutputSize
G
gineshidalgo99 已提交
448 449 450
                producerSize = cv::Size{(int)wrapperStructInput.producerSharedPtr->get(CV_CAP_PROP_FRAME_WIDTH),
                                        (int)wrapperStructInput.producerSharedPtr->get(CV_CAP_PROP_FRAME_HEIGHT)};
                if (wrapperStructPose.outputSize.width == -1 || wrapperStructPose.outputSize.height == -1)
G
gineshidalgo99 已提交
451 452 453 454
                {
                    if (producerSize.area() > 0)
                        finalOutputSize = producerSize;
                    else
G
gineshidalgo99 已提交
455 456 457 458
                    {
                        const auto message = "Output resolution = input resolution not valid for image reading (size might change between images).";
                        error(message, __LINE__, __FUNCTION__, __FILE__);
                    }
G
gineshidalgo99 已提交
459 460 461
                }
            }
            else if (finalOutputSize.width == -1 || finalOutputSize.height == -1)
G
gineshidalgo99 已提交
462 463 464 465
            {
                const auto message = "Output resolution cannot be (-1 x -1) unless wrapperStructInput.producerSharedPtr is also set.";
                error(message, __LINE__, __FUNCTION__, __FILE__);
            }
G
gineshidalgo99 已提交
466 467

            // Update global parameter
G
gineshidalgo99 已提交
468
            mGpuNumber = wrapperStructPose.gpuNumber;
G
gineshidalgo99 已提交
469 470

            // Producer
G
gineshidalgo99 已提交
471
            if (wrapperStructInput.producerSharedPtr != nullptr)
G
gineshidalgo99 已提交
472
            {
G
gineshidalgo99 已提交
473 474 475
                const auto datumProducer = std::make_shared<DatumProducer<TDatums>>(
                    wrapperStructInput.producerSharedPtr, wrapperStructInput.frameFirst, wrapperStructInput.frameLast, spVideoSeek
                );
G
gineshidalgo99 已提交
476 477 478 479 480 481
                wDatumProducer = std::make_shared<WDatumProducer<TDatumsPtr, TDatums>>(datumProducer);
            }
            else
                wDatumProducer = nullptr;

            // Pose estimators
G
gineshidalgo99 已提交
482
            const cv::Size& netOutputSize = wrapperStructPose.netInputSize;
G
gineshidalgo99 已提交
483
            std::vector<std::shared_ptr<PoseExtractor>> poseExtractors;
G
gineshidalgo99 已提交
484 485 486 487 488 489
            for (auto gpuId = 0; gpuId < wrapperStructPose.gpuNumber; gpuId++)
                poseExtractors.emplace_back(std::make_shared<PoseExtractorCaffe>(
                    wrapperStructPose.netInputSize, netOutputSize, finalOutputSize, wrapperStructPose.scalesNumber,
                    wrapperStructPose.scaleGap, wrapperStructPose.poseModel, wrapperStructPose.modelFolder,
                    gpuId + wrapperStructPose.gpuNumberStart, wrapperStructPose.heatMapTypes, wrapperStructPose.heatMapScaleMode
                ));
G
gineshidalgo99 已提交
490 491
            // Pose renderers
            std::vector<std::shared_ptr<PoseRenderer>> poseRenderers;
G
gineshidalgo99 已提交
492 493
            if (wrapperStructPose.renderOutput)
            {
G
gineshidalgo99 已提交
494
                for (auto gpuId = 0; gpuId < poseExtractors.size(); gpuId++)
G
gineshidalgo99 已提交
495 496 497 498 499 500 501 502
                {
                    poseRenderers.emplace_back(std::make_shared<PoseRenderer>(
                        netOutputSize, finalOutputSize, wrapperStructPose.poseModel, poseExtractors[gpuId],
                        wrapperStructPose.blendOriginalFrame, wrapperStructPose.alphaPose,
                        wrapperStructPose.alphaHeatMap, wrapperStructPose.defaultPartToRender
                    ));
                }
            }
G
gineshidalgo99 已提交
503 504 505
            log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);

            // Input cvMat to OpenPose format
G
gineshidalgo99 已提交
506 507 508
            const auto cvMatToOpInput = std::make_shared<CvMatToOpInput>(
                wrapperStructPose.netInputSize, wrapperStructPose.scalesNumber, wrapperStructPose.scaleGap
            );
G
gineshidalgo99 已提交
509
            spWCvMatToOpInput = std::make_shared<WCvMatToOpInput<TDatumsPtr>>(cvMatToOpInput);
G
gineshidalgo99 已提交
510
            const auto cvMatToOpOutput = std::make_shared<CvMatToOpOutput>(finalOutputSize, wrapperStructPose.renderOutput);
G
gineshidalgo99 已提交
511 512 513 514 515 516 517 518 519 520 521 522 523
            spWCvMatToOpOutput = std::make_shared<WCvMatToOpOutput<TDatumsPtr>>(cvMatToOpOutput);

            // Pose extractor(s)
            spWPoses.clear();
            spWPoses.resize(poseExtractors.size());
            for (auto i = 0; i < spWPoses.size(); i++)
                spWPoses.at(i) = {std::make_shared<WPoseExtractor<TDatumsPtr>>(poseExtractors.at(i))};

            // Hand extractor(s)
            if (wrapperHandStruct.extractAndRenderHands)
            {
                for (auto gpuId = 0; gpuId < spWPoses.size(); gpuId++)
                {
G
gineshidalgo99 已提交
524 525 526
                    const auto handsExtractor = std::make_shared<experimental::HandsExtractor>(
                        wrapperStructPose.modelFolder, gpuId + wrapperStructPose.gpuNumberStart, wrapperStructPose.poseModel
                    );
G
gineshidalgo99 已提交
527 528 529 530 531 532 533 534 535 536 537 538 539 540 541
                    spWPoses.at(gpuId).emplace_back(std::make_shared<experimental::WHandsExtractor<TDatumsPtr>>(handsExtractor));
                }
            }

            // Pose renderer(s)
            if (!poseRenderers.empty())
                for (auto i = 0; i < spWPoses.size(); i++)
                    spWPoses.at(i).emplace_back(std::make_shared<WPoseRenderer<TDatumsPtr>>(poseRenderers.at(i)));

            // Hands renderer(s)
            if (wrapperHandStruct.extractAndRenderHands)
            {
                for (auto i = 0; i < spWPoses.size(); i++)
                {
                    // Construct hands renderer
G
gineshidalgo99 已提交
542
                    const auto handsRenderer = std::make_shared<experimental::HandsRenderer>(finalOutputSize);
G
gineshidalgo99 已提交
543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559
                    // Performance boost -> share spGpuMemoryPtr for all renderers
                    if (!poseRenderers.empty())
                    {
                        const bool isLastRenderer = true;
                        handsRenderer->setGpuMemoryAndSetIfLast(poseRenderers.at(i)->getGpuMemoryAndSetAsFirst(), isLastRenderer);
                    }
                    // Add worker
                    spWPoses.at(i).emplace_back(std::make_shared<experimental::WHandsRenderer<TDatumsPtr>>(handsRenderer));
                }
            }

            // Itermediate workers (e.g. OpenPose format to cv::Mat, json & frames recorder, ...)
            mPostProcessingWs.clear();
            // Frame buffer and ordering
            if (spWPoses.size() > 1)
                mPostProcessingWs.emplace_back(std::make_shared<WQueueOrderer<TDatumsPtr>>());
            // Frames processor (OpenPose format -> cv::Mat format)
G
gineshidalgo99 已提交
560
            if (wrapperStructPose.renderOutput)
G
gineshidalgo99 已提交
561 562 563 564
            {
                const auto opOutputToCvMat = std::make_shared<OpOutputToCvMat>(finalOutputSize);
                mPostProcessingWs.emplace_back(std::make_shared<WOpOutputToCvMat<TDatumsPtr>>(opOutputToCvMat));
            }
G
gineshidalgo99 已提交
565 566 567 568
            // Re-scale pose if desired
            if (wrapperStructPose.poseScaleMode != ScaleMode::OutputResolution
                && (wrapperStructPose.poseScaleMode != ScaleMode::InputResolution || (finalOutputSize != producerSize))
                && (wrapperStructPose.poseScaleMode != ScaleMode::NetOutputResolution || (finalOutputSize != netOutputSize)))
G
gineshidalgo99 已提交
569
            {
G
gineshidalgo99 已提交
570
                auto arrayScaler = std::make_shared<ArrayScaler>(wrapperStructPose.poseScaleMode);
G
gineshidalgo99 已提交
571 572 573 574 575 576 577
                mPostProcessingWs.emplace_back(std::make_shared<WArrayScaler<TDatumsPtr>>(arrayScaler));
            }

            mOutputWs.clear();
            // Write people pose data on disk (json for OpenCV >= 3, xml, yml...)
            if (!writePoseCleaned.empty())
            {
G
gineshidalgo99 已提交
578
                const auto poseSaver = std::make_shared<PoseSaver>(writePoseCleaned, wrapperStructOutput.writePoseDataFormat);
G
gineshidalgo99 已提交
579 580 581 582 583 584 585 586 587
                mOutputWs.emplace_back(std::make_shared<WPoseSaver<TDatumsPtr>>(poseSaver));
            }
            // Write people pose data on disk (json format)
            if (!writePoseJsonCleaned.empty())
            {
                const auto poseJsonSaver = std::make_shared<PoseJsonSaver>(writePoseJsonCleaned);
                mOutputWs.emplace_back(std::make_shared<WPoseJsonSaver<TDatumsPtr>>(poseJsonSaver));
            }
            // Write people pose data on disk (COCO validation json format)
G
gineshidalgo99 已提交
588
            if (!wrapperStructOutput.writeCocoJson.empty())
G
gineshidalgo99 已提交
589 590
            {
                const auto humanFormat = true; // If true, bigger size (and potentially slower to process), but easier for a human to read it
G
gineshidalgo99 已提交
591
                const auto poseJsonCocoSaver = std::make_shared<PoseJsonCocoSaver>(wrapperStructOutput.writeCocoJson, humanFormat);
G
gineshidalgo99 已提交
592 593 594 595 596
                mOutputWs.emplace_back(std::make_shared<experimental::WPoseJsonCocoSaver<TDatumsPtr>>(poseJsonCocoSaver));
            }
            // Write frames as desired image format on hard disk
            if (!writeImagesCleaned.empty())
            {
G
gineshidalgo99 已提交
597
                const auto imageSaver = std::make_shared<ImageSaver>(writeImagesCleaned, wrapperStructOutput.writeImagesFormat);
G
gineshidalgo99 已提交
598 599 600
                mOutputWs.emplace_back(std::make_shared<WImageSaver<TDatumsPtr>>(imageSaver));
            }
            // Write frames as *.avi video on hard disk
G
gineshidalgo99 已提交
601
            if (!wrapperStructOutput.writeVideo.empty() && wrapperStructInput.producerSharedPtr != nullptr)
G
gineshidalgo99 已提交
602
            {
G
gineshidalgo99 已提交
603 604 605 606 607 608
                const auto originalVideoFps = (wrapperStructInput.producerSharedPtr->getType() != ProducerType::Webcam
                                               && wrapperStructInput.producerSharedPtr->get(CV_CAP_PROP_FPS) > 0.
                                               ? wrapperStructInput.producerSharedPtr->get(CV_CAP_PROP_FPS) : 30.);
                const auto videoSaver = std::make_shared<VideoSaver>(
                    wrapperStructOutput.writeVideo, CV_FOURCC('M','J','P','G'), originalVideoFps, finalOutputSize
                );
G
gineshidalgo99 已提交
609 610 611 612 613
                mOutputWs.emplace_back(std::make_shared<WVideoSaver<TDatumsPtr>>(videoSaver));
            }
            // Write heat maps as desired image format on hard disk
            if (!writeHeatMapsCleaned.empty())
            {
G
gineshidalgo99 已提交
614
                const auto heatMapSaver = std::make_shared<HeatMapSaver>(writeHeatMapsCleaned, wrapperStructOutput.writeHeatMapsFormat);
G
gineshidalgo99 已提交
615 616 617
                mOutputWs.emplace_back(std::make_shared<WHeatMapSaver<TDatumsPtr>>(heatMapSaver));
            }
            // Add frame information for GUI
G
gineshidalgo99 已提交
618 619 620
            // If this WGuiInfoAdder instance is placed before the WImageSaver or WVideoSaver, then the resulting recorded frames will
            // look exactly as the final displayed image by the GUI
            if (wrapperStructOutput.displayGui && wrapperStructOutput.guiVerbose)
G
gineshidalgo99 已提交
621
            {
G
gineshidalgo99 已提交
622
                const auto guiInfoAdder = std::make_shared<GuiInfoAdder>(finalOutputSize, wrapperStructPose.gpuNumber);
G
gineshidalgo99 已提交
623 624 625 626
                mOutputWs.emplace_back(std::make_shared<WGuiInfoAdder<TDatumsPtr>>(guiInfoAdder));
            }
            // Minimal graphical user interface (GUI)
            spWGui = nullptr;
G
gineshidalgo99 已提交
627
            if (wrapperStructOutput.displayGui)
G
gineshidalgo99 已提交
628
            {
G
gineshidalgo99 已提交
629 630 631
                const auto gui = std::make_shared<Gui>(
                    wrapperStructOutput.fullScreen, finalOutputSize, mThreadManager.getIsRunningSharedPtr(), spVideoSeek, poseExtractors, poseRenderers
                );
G
gineshidalgo99 已提交
632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792
                spWGui = {std::make_shared<WGui<TDatumsPtr>>(gui)};
            }
            log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);
        }
        catch (const std::exception& e)
        {
            error(e.what(), __LINE__, __FUNCTION__, __FILE__);
        }
    }

    template<typename TDatums, typename TWorker, typename TQueue>
    void Wrapper<TDatums, TWorker, TQueue>::exec()
    {
        try
        {
            configureThreadManager();
            mThreadManager.exec();
        }
        catch (const std::exception& e)
        {
            error(e.what(), __LINE__, __FUNCTION__, __FILE__);
        }
    }

    template<typename TDatums, typename TWorker, typename TQueue>
    void Wrapper<TDatums, TWorker, TQueue>::start()
    {
        try
        {
            configureThreadManager();
            mThreadManager.start();
        }
        catch (const std::exception& e)
        {
            error(e.what(), __LINE__, __FUNCTION__, __FILE__);
        }
    }

    template<typename TDatums, typename TWorker, typename TQueue>
    void Wrapper<TDatums, TWorker, TQueue>::stop()
    {
        try
        {
            mThreadManager.stop();
        }
        catch (const std::exception& e)
        {
            error(e.what(), __LINE__, __FUNCTION__, __FILE__);
        }
    }

    template<typename TDatums, typename TWorker, typename TQueue>
    bool Wrapper<TDatums, TWorker, TQueue>::isRunning() const
    {
        try
        {
            return mThreadManager.isRunning();
        }
        catch (const std::exception& e)
        {
            error(e.what(), __LINE__, __FUNCTION__, __FILE__);
            return false;
        }
    }

    template<typename TDatums, typename TWorker, typename TQueue>
    bool Wrapper<TDatums, TWorker, TQueue>::tryEmplace(std::shared_ptr<TDatums>& tDatums)
    {
        try
        {
            if (!mUserInputWs.empty())
                error("Emplace cannot be called if an input worker was already selected.", __LINE__, __FUNCTION__, __FILE__);
            return mThreadManager.tryEmplace(tDatums);
        }
        catch (const std::exception& e)
        {
            error(e.what(), __LINE__, __FUNCTION__, __FILE__);
            return false;
        }
    }

    template<typename TDatums, typename TWorker, typename TQueue>
    bool Wrapper<TDatums, TWorker, TQueue>::waitAndEmplace(std::shared_ptr<TDatums>& tDatums)
    {
        try
        {
            if (!mUserInputWs.empty())
                error("Emplace cannot be called if an input worker was already selected.", __LINE__, __FUNCTION__, __FILE__);
            return mThreadManager.waitAndEmplace(tDatums);
        }
        catch (const std::exception& e)
        {
            error(e.what(), __LINE__, __FUNCTION__, __FILE__);
            return false;
        }
    }

    template<typename TDatums, typename TWorker, typename TQueue>
    bool Wrapper<TDatums, TWorker, TQueue>::tryPush(const std::shared_ptr<TDatums>& tDatums)
    {
        try
        {
            if (!mUserInputWs.empty())
                error("Push cannot be called if an input worker was already selected.", __LINE__, __FUNCTION__, __FILE__);
            return mThreadManager.tryPush(tDatums);
        }
        catch (const std::exception& e)
        {
            error(e.what(), __LINE__, __FUNCTION__, __FILE__);
            return false;
        }
    }

    template<typename TDatums, typename TWorker, typename TQueue>
    bool Wrapper<TDatums, TWorker, TQueue>::waitAndPush(const std::shared_ptr<TDatums>& tDatums)
    {
        try
        {
            if (!mUserInputWs.empty())
                error("Push cannot be called if an input worker was already selected.", __LINE__, __FUNCTION__, __FILE__);
            return mThreadManager.waitAndPush(tDatums);
        }
        catch (const std::exception& e)
        {
            error(e.what(), __LINE__, __FUNCTION__, __FILE__);
            return false;
        }
    }

    template<typename TDatums, typename TWorker, typename TQueue>
    bool Wrapper<TDatums, TWorker, TQueue>::tryPop(std::shared_ptr<TDatums>& tDatums)
    {
        try
        {
            if (!mUserOutputWs.empty())
                error("Pop cannot be called if an output worker was already selected.", __LINE__, __FUNCTION__, __FILE__);
            return mThreadManager.tryPop(tDatums);
        }
        catch (const std::exception& e)
        {
            error(e.what(), __LINE__, __FUNCTION__, __FILE__);
            return false;
        }
    }

    template<typename TDatums, typename TWorker, typename TQueue>
    bool Wrapper<TDatums, TWorker, TQueue>::waitAndPop(std::shared_ptr<TDatums>& tDatums)
    {
        try
        {
            if (!mUserOutputWs.empty())
                error("Pop cannot be called if an output worker was already selected.", __LINE__, __FUNCTION__, __FILE__);
            return mThreadManager.waitAndPop(tDatums);
        }
        catch (const std::exception& e)
        {
            error(e.what(), __LINE__, __FUNCTION__, __FILE__);
            return false;
        }
    }

G
gineshidalgo99 已提交
793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817
    template<typename TDatums, typename TWorker, typename TQueue>
    void Wrapper<TDatums, TWorker, TQueue>::reset()
    {
        try
        {
            mThreadManager.reset();
            mThreadId = 0ull;
            // Reset 
            mUserInputWs.clear();
            wDatumProducer = nullptr;
            spWCvMatToOpInput = nullptr;
            spWCvMatToOpOutput = nullptr;
            spWPoses.clear();
            mPostProcessingWs.clear();
            mUserPostProcessingWs.clear();
            mOutputWs.clear();
            spWGui = nullptr;
            mUserOutputWs.clear();
        }
        catch (const std::exception& e)
        {
            error(e.what(), __LINE__, __FUNCTION__, __FILE__);
        }
    }

G
gineshidalgo99 已提交
818 819 820 821 822 823 824 825 826 827
    template<typename TDatums, typename TWorker, typename TQueue>
    void Wrapper<TDatums, TWorker, TQueue>::configureThreadManager()
    {
        try
        {
            // The less number of queues -> the less lag

            // Security checks
            if (spWCvMatToOpInput == nullptr || spWCvMatToOpOutput == nullptr)
                error("Configure the Wrapper class before calling `start()`.", __LINE__, __FUNCTION__, __FILE__);
G
gineshidalgo99 已提交
828 829 830 831 832 833 834 835 836 837 838
            if ((wDatumProducer == nullptr) == (mUserInputWs.empty())
                && mThreadManagerMode != ThreadManagerMode::Asynchronous && mThreadManagerMode != ThreadManagerMode::AsynchronousIn)
            {
                const auto message = "You need to have 1 and only 1 producer selected. You can introduce your own producer by using setWorkerInput() or"
                                     " use the OpenPose default producer by configuring it in the configure function) or use the"
                                     " ThreadManagerMode::Asynchronous(In) mode.";
                error(message, __LINE__, __FUNCTION__, __FILE__);
            }
            if (mOutputWs.empty() && mUserOutputWs.empty() && spWGui == nullptr && mThreadManagerMode != ThreadManagerMode::Asynchronous
                && mThreadManagerMode != ThreadManagerMode::AsynchronousOut)
            {
G
gineshidalgo99 已提交
839
                error("No output selected.", __LINE__, __FUNCTION__, __FILE__);
G
gineshidalgo99 已提交
840
            }
G
gineshidalgo99 已提交
841 842 843 844 845 846 847 848 849 850 851

            // Thread Manager:
            // Clean previous thread manager (avoid configure to crash the program if used more than once)
            mThreadManager.reset();
            mThreadId = 0ull;
            auto queueIn = 0ull;
            auto queueOut = 1ull;
            // If custom user Worker and uses its own thread
            spWIdGenerator = std::make_shared<WIdGenerator<std::shared_ptr<TDatums>>>();
            if (!mUserInputWs.empty() && mUserInputWsOnNewThread)
            {
G
gineshidalgo99 已提交
852
                mThreadManager.add(mThreadId, mUserInputWs, queueIn++, queueOut++);                     // Thread 0, queues 0 -> 1
G
gineshidalgo99 已提交
853
                threadIdPP();
G
gineshidalgo99 已提交
854
                mThreadManager.add(mThreadId, {spWIdGenerator, spWCvMatToOpInput, spWCvMatToOpOutput}, queueIn++, queueOut++); // Thread 1, queues 1 -> 2
G
gineshidalgo99 已提交
855 856 857 858 859 860 861 862 863 864 865 866
            }
            // If custom user Worker in same thread or producer on same thread
            else
            {
                std::vector<TWorker> workersAux;
                // Custom user Worker
                if (!mUserInputWs.empty())
                    workersAux = mergeWorkers(workersAux, mUserInputWs);
                // OpenPose producer
                else if (wDatumProducer != nullptr)       
                    workersAux = mergeWorkers(workersAux, {wDatumProducer});
                // Otherwise
G
gineshidalgo99 已提交
867
                else if (mThreadManagerMode != ThreadManagerMode::Asynchronous && mThreadManagerMode != ThreadManagerMode::AsynchronousIn)
G
gineshidalgo99 已提交
868 869 870
                    error("No input selected.", __LINE__, __FUNCTION__, __FILE__);

                workersAux = mergeWorkers(workersAux, {spWIdGenerator, spWCvMatToOpInput, spWCvMatToOpOutput});
G
gineshidalgo99 已提交
871
                mThreadManager.add(mThreadId, workersAux, queueIn++, queueOut++);                       // Thread 0 or 1, queues 0 -> 1
G
gineshidalgo99 已提交
872 873 874
            }
            threadIdPP();
            // Pose estimation & rendering
G
gineshidalgo99 已提交
875
            if (!spWPoses.empty())                                                                      // Thread 1 or 2...X, queues 1 -> 2, X = 2 + #GPUs
G
gineshidalgo99 已提交
876
            {
G
gineshidalgo99 已提交
877
                if (mMultiThreadEnabled)
G
gineshidalgo99 已提交
878 879 880 881 882 883 884 885
                {
                    for (auto& wPose : spWPoses)
                    {
                        mThreadManager.add(mThreadId, wPose, queueIn, queueOut);
                        threadIdPP();
                    }
                }
                else
G
gineshidalgo99 已提交
886 887
                {
                    log("Debugging activated, only 1 thread running, all spWPoses have been disabled but the first one.");
G
gineshidalgo99 已提交
888
                    mThreadManager.add(mThreadId, spWPoses.at(0), queueIn, queueOut);
G
gineshidalgo99 已提交
889
                }
G
gineshidalgo99 已提交
890 891 892 893 894 895 896 897 898
                queueIn++;
                queueOut++;
            }
            // If custom user Worker and uses its own thread
            if (!mUserPostProcessingWs.empty() && mUserPostProcessingWsOnNewThread)
            {
                // Post processing workers
                if (!mPostProcessingWs.empty())
                {
G
gineshidalgo99 已提交
899
                    mThreadManager.add(mThreadId, mPostProcessingWs, queueIn++, queueOut++);                // Thread 2 or 3, queues 2 -> 3
G
gineshidalgo99 已提交
900 901 902
                    threadIdPP();
                }
                // User processing workers
G
gineshidalgo99 已提交
903
                mThreadManager.add(mThreadId, mUserPostProcessingWs, queueIn++, queueOut++);                // Thread 3 or 4, queues 3 -> 4
G
gineshidalgo99 已提交
904 905 906 907
                threadIdPP();
                // Output workers
                if (!mOutputWs.empty())
                {
G
gineshidalgo99 已提交
908
                    mThreadManager.add(mThreadId, mOutputWs, queueIn++, queueOut++);                        // Thread 4 or 5, queues 4 -> 5
G
gineshidalgo99 已提交
909 910 911 912 913 914 915 916 917 918 919
                    threadIdPP();
                }
            }
            // If custom user Worker in same thread or producer on same thread
            else
            {
                // Post processing workers + User post processing workers + Output workers
                auto workersAux = mergeWorkers(mPostProcessingWs, mUserPostProcessingWs);
                workersAux = mergeWorkers(workersAux, mOutputWs);
                if (!workersAux.empty())
                {
G
gineshidalgo99 已提交
920
                    mThreadManager.add(mThreadId, workersAux, queueIn++, queueOut++);                       // Thread 2 or 3, queues 2 -> 3
G
gineshidalgo99 已提交
921 922 923 924
                    threadIdPP();
                }
            }
            // User output worker
G
gineshidalgo99 已提交
925
            if (!mUserOutputWs.empty())                                                                     // Thread Y, queues Q -> Q+1
G
gineshidalgo99 已提交
926 927 928 929 930 931 932 933 934 935 936 937
            {
                if (mUserOutputWsOnNewThread)
                {
                    mThreadManager.add(mThreadId, mUserOutputWs, queueIn++, queueOut++);
                    threadIdPP();
                }
                else
                    mThreadManager.add(mThreadId-1, mUserOutputWs, queueIn++, queueOut++);
            }
            // OpenPose GUI
            if (spWGui != nullptr)
            {
G
gineshidalgo99 已提交
938
                mThreadManager.add(mThreadId, spWGui, queueIn++, queueOut++);                               // Thread Y+1, queues Q+1 -> Q+2
G
gineshidalgo99 已提交
939 940 941 942 943 944 945 946 947 948 949 950 951 952 953
                threadIdPP();
            }
            log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);
        }
        catch (const std::exception& e)
        {
            error(e.what(), __LINE__, __FUNCTION__, __FILE__);
        }
    }

    template<typename TDatums, typename TWorker, typename TQueue>
    unsigned int Wrapper<TDatums, TWorker, TQueue>::threadIdPP()
    {
        try
        {
G
gineshidalgo99 已提交
954
            if (mMultiThreadEnabled)
G
gineshidalgo99 已提交
955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984
                mThreadId++;
            return mThreadId;
        }
        catch (const std::exception& e)
        {
            error(e.what(), __LINE__, __FUNCTION__, __FILE__);
        }
    }

    template<typename TDatums, typename TWorker, typename TQueue>
    std::vector<TWorker> Wrapper<TDatums, TWorker, TQueue>::mergeWorkers(const std::vector<TWorker>& workersA, const std::vector<TWorker>& workersB)
    {
        try
        {
            auto workersToReturn(workersA);
            for (auto& worker : workersB)
                workersToReturn.emplace_back(worker);
            return workersToReturn;
        }
        catch (const std::exception& e)
        {
            error(e.what(), __LINE__, __FUNCTION__, __FILE__);
            return std::vector<TWorker>{};
        }
    }

    extern template class Wrapper<DATUM_BASE_NO_PTR>;
}

#endif // OPENPOSE__WRAPPER__WRAPPER_HPP