-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebcam_thread.cxx
110 lines (89 loc) · 2.63 KB
/
webcam_thread.cxx
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
#include "webcam.h"
#include "webcam_thread.h"
#include "frame.h"
#include "threadsafe_queue.h"
#include <chrono>
#include <string>
#include <atomic>
#include <system_error>
#include <stdexcept>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/select.h>
#include <spdlog/spdlog.h>
void webcam_thread(WebcamSetup ws, ThreadsafeQueue<FramePtr>& queue,
std::atomic_bool& exit_flag) {
auto logger = spdlog::get("console");
// FPS measurement and some metrics
int frame_count = 0;
int dropped_frames = 0;
const int fps_div_sb = 3; // divide by shifting 3 bit pos (/8)
auto fps_log_seconds = std::chrono::seconds{1 << fps_div_sb};
std::chrono::time_point<std::chrono::steady_clock> start_time = \
std::chrono::steady_clock::now(), now_time;
zxwebcam::Webcam v(ws.device_, ws.res_y_, ws.res_x_, ws.fps_, ws.fps_);
logger->info("Initialising webcam {} with res {}x{} @ {} fps",
ws.device_, ws.res_x_, ws.res_y_, ws.fps_);
try {
v.init();
} catch (const std::runtime_error& e) {
logger->error("Could not initialise webcam device: <{}>",
e.what());
exit_flag = true;
return;
}
try {
v.start_capture();
} catch (const std::runtime_error& e) {
logger->error("Could not start capture: <{}>",
e.what());
exit_flag = true;
return;
}
while (!exit_flag) {
fd_set fds;
FD_ZERO(&fds);
FD_SET(v.fd(), &fds);
timeval timeout = {1, 0}; // 1 sec timeout
int ret = select(v.fd()+1, &fds, NULL, NULL, &timeout);
switch(ret) {
case -1:
logger->error("select() call error with errno {}", errno);
return;
case 0:
logger->warn("timeout waiting for frame from webcam.");
continue;
default:
break;
}
FramePtr f = v.grab_frame();
if (f == nullptr)
continue;
//TODO: put the hardcoded magic num somewhere sensible
if (queue.size() > (int)(ws.fps_)) {
logger->warn("Frame queue full, discarding frame.");
dropped_frames++;
} else {
queue.push(f);
frame_count++;
}
now_time = std::chrono::steady_clock::now();
if (now_time - start_time >= fps_log_seconds) {
// log fps
logger->info("frames {}, dropped {} frames, avg fps {}",
frame_count,
dropped_frames,
(frame_count >> fps_div_sb));
frame_count = 0;
start_time = now_time;
}
}
try {
v.end_capture();
v.close();
} catch (const std::runtime_error& e) {
logger->error("Could not shutdown webcam device: {}",
e.what());
exit_flag = true;
}
}