upgrade opencv to 3.3.1, complete patch similarity
[trackerpp.git] / src / Engine.cpp
1 #include <mutex>
2 #include <thread>
3 #include "Engine.h"
4 #include "Logger.h"
5 #include "PredictorWrapper.h"
6
7 using namespace suanzi;
8
9 static const std::string TAG = "Engine";
10
11 static std::mutex g_mutex;
12 static EngineWPtr g_instance;
13
14
15 EnginePtr Engine::create()
16 {
17     LOG_DEBUG(TAG, "create");
18     std::lock_guard<std::mutex> lock(g_mutex);
19     if (g_instance.lock()){
20         LOG_ERROR(TAG, "already exists");
21         return EnginePtr(); // nullptr
22     }
23     EnginePtr instance (new Engine());
24     g_instance = instance;
25     return instance;
26 }
27
28 Engine::Engine()
29 {
30     detector = std::make_shared<Detector>();
31     multiTracker = std::make_shared<MultiTracker>();
32 }
33
34 Engine::~Engine()
35 {    
36     destroy();
37 }
38
39 void Engine::destroy()
40 {
41     LOG_DEBUG(TAG, "destroy");
42     detector.reset();
43     multiTracker.reset();
44     reader.reset();
45     observer_list.clear();
46 }
47
48
49 void Engine::setVideoSrc(VideoSrcType type, const std::string& url)
50 {
51     reader = VideoReaderFactory::createVideoReader(type, url);
52 }
53
54 void Engine::run()
55 {
56     LOG_DEBUG(TAG, "run");
57     cv::Mat frame;
58     Detection detections[128];
59     while (reader->read(frame)){
60         LOG_DEBUG(TAG, "Size: " << frame.cols  <<  "x" << frame.rows);
61         int total = detector->detect(frame, detections);
62         multiTracker->update(total, detections, frame);
63     }
64 }
65
66 void Engine::start()
67 {
68     LOG_DEBUG(TAG, "start");
69     if (!reader){
70         LOG_ERROR(TAG, "reader is null. exit");
71         return;
72     }
73     std::thread t(&Engine::run, this);
74     t.join();
75 }
76
77 void Engine::addObserver(EngineObserver *observer)
78 {
79     observer_list.insert(observer);
80 }