-
Notifications
You must be signed in to change notification settings - Fork 2
/
camera_thread.cc
95 lines (73 loc) · 1.6 KB
/
camera_thread.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
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
//
// Created by YongGyu Lee on 2021/09/16.
//
#include "camera_thread.h"
#include <iostream>
#include <thread>
#include <utility>
namespace sample {
CameraThread::CameraThread() {
thread_ = std::thread([this](){
run_impl();
});
}
CameraThread::~CameraThread() {
join();
}
bool CameraThread::run(int camera_index) {
if (camera_index == camera_index_) {
resume();
}
auto lck = pause_wait();
camera_index_ = camera_index;
if (!check_status())
return false;
lck.unlock();
pause_ = false;
cv_.notify_all();
return true;
}
void CameraThread::pause() {
pause_ = true;
cv_.notify_all();
}
std::unique_lock<std::mutex> CameraThread::pause_wait() {
pause_ = true;
cv_.notify_all();
std::unique_lock<std::mutex> lck(mutex_);
return lck;
}
void CameraThread::resume() {
pause_ = false;
cv_.notify_all();
}
void CameraThread::run_impl() {
std::unique_lock<std::mutex> lck(mutex_);
while (true) {
cv_.wait(lck, [this]() -> bool {
return !pause_ || stop_;
});
if (stop_)
break;
video_ >> frame_;
on_frame_(std::move(frame_));
}
}
void CameraThread::join() {
stop_.store(true, std::memory_order_release);
cv_.notify_all();
if (thread_.joinable())
thread_.join();
}
bool CameraThread::check_status() {
video_.open(camera_index_);
if (!video_.isOpened()) {
std::cerr << "Failed to open camera\n";
return false;
} else if ((video_ >> frame_, frame_.empty())) {
std::cerr << "Camera is opened, but failed to get a frame. Try changing the camera_index\n";
return false;
}
return true;
}
} // namespace sample