forked from PhotonVision/photon-libcamera-gl-driver
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcamera_runner.cpp
More file actions
240 lines (186 loc) · 7.53 KB
/
camera_runner.cpp
File metadata and controls
240 lines (186 loc) · 7.53 KB
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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
#include "camera_runner.h"
#include <chrono>
#include <cstring>
#include <iostream>
#include <thread>
#ifdef __cpp_lib_latch
#include <latch>
using latch = std::latch;
#else
#include "latch.hpp"
using latch = Latch;
#endif
#include <sys/mman.h>
#include <unistd.h>
#include <libcamera/property_ids.h>
#include <libcamera/control_ids.h>
using namespace std::chrono;
using namespace std::chrono_literals;
static double approxRollingAverage(double avg, double new_sample) {
avg -= avg / 50;
avg += new_sample / 50;
return avg;
}
CameraRunner::CameraRunner(int width, int height, int rotation,
std::shared_ptr<libcamera::Camera> cam)
: m_camera(std::move(cam)), m_width(width), m_height(height),
grabber(m_camera, m_width, m_height, rotation), m_thresholder(m_width, m_height),
allocer("/dev/dma_heap/linux,cma") {
grabber.setOnData(
[&](libcamera::Request *request) { camera_queue.push(request); });
fds = {allocer.alloc_buf_fd(m_width * m_height * 4),
allocer.alloc_buf_fd(m_width * m_height * 4),
allocer.alloc_buf_fd(m_width * m_height * 4)};
}
CameraRunner::~CameraRunner() {
for (auto i : fds) {
close(i);
}
}
void CameraRunner::requestShaderIdx(int idx) {
m_shaderIdx = idx;
}
void CameraRunner::setCopyOptions(bool copyIn, bool copyOut) {
m_copyInput = copyIn;
m_copyOutput = copyOut;
}
void CameraRunner::start() {
unsigned int stride = grabber.streamConfiguration().stride;
latch start_frame_grabber{2};
threshold = std::thread([&, stride]() {
m_thresholder.start(fds);
auto colorspace = grabber.streamConfiguration().colorSpace.value();
double gpuTimeAvgMs = 0;
start_frame_grabber.count_down();
while (true) {
// printf("Threshold thread!\n");
auto request = camera_queue.pop();
if (!request) {
break;
}
auto planes = request->buffers()
.at(grabber.streamConfiguration().stream())
->planes();
for (int i = 0; i < 3; i++) {
// std::cout << "Plane " << (i + 1) << " has fd " << planes[i].fd.get() << " with offset " << planes[i].offset << std::endl;
// std::cout << "Plane " << (i + 1) << " has fd " << planes[i].fd.get() << " with offset " << planes[i].offset << " and pitch " << static_cast<EGLint>(stride / 2) << std::endl;
}
std::array<GlHsvThresholder::DmaBufPlaneData, 3> yuv_data{{
{planes[0].fd.get(), static_cast<EGLint>(planes[0].offset),
static_cast<EGLint>(stride)},
{planes[1].fd.get(), static_cast<EGLint>(planes[1].offset),
static_cast<EGLint>(stride / 2)},
{planes[2].fd.get(), static_cast<EGLint>(planes[2].offset),
static_cast<EGLint>(stride / 2)},
}};
auto begintime = steady_clock::now();
auto type = static_cast<ProcessType>(m_shaderIdx.load());
int out = m_thresholder.testFrame(yuv_data,
encodingFromColorspace(colorspace),
rangeFromColorspace(colorspace),
type);
if (out != 0) {
/*
From libcamera docs:
The timestamp, expressed in nanoseconds, represents a monotonically
increasing counter since the system boot time, as defined by the
Linux-specific CLOCK_BOOTTIME clock id.
*/
uint64_t sensorTimestamp = static_cast<uint64_t>(request->metadata()
.get(libcamera::controls::SensorTimestamp)
.value_or(0));
gpu_queue.push({out, type, sensorTimestamp});
}
std::chrono::duration<double, std::milli> elapsedMillis =
steady_clock::now() - begintime;
if (elapsedMillis > 0.9ms) {
// gpuTimeAvgMs =
// approxRollingAverage(gpuTimeAvgMs, elapsedMillis.count());
// std::cout << "GLProcess: " << elapsedMillis.count() << std::endl;
}
{
std::lock_guard<std::mutex> lock{camera_stop_mutex};
grabber.requeueRequest(request);
}
}
m_thresholder.release();
});
display = std::thread([&]() {
std::unordered_map<int, unsigned char *> mmaped;
for (auto fd : fds) {
auto mmap_ptr = mmap(nullptr, m_width * m_height * 4, PROT_READ,
MAP_SHARED, fd, 0);
if (mmap_ptr == MAP_FAILED) {
throw std::runtime_error("failed to mmap pointer");
}
mmaped.emplace(fd, static_cast<unsigned char *>(mmap_ptr));
}
double copyTimeAvgMs = 0;
double fpsTimeAvgMs = 0;
start_frame_grabber.count_down();
auto lastTime = steady_clock::now();
while (true) {
// printf("Display thread!\n");
auto data = gpu_queue.pop();
if (data.fd == -1) {
break;
}
auto mat_pair = MatPair(m_width, m_height);
// Save the current shader idx
mat_pair.frameProcessingType = static_cast<int32_t>(data.type);
mat_pair.captureTimestamp = data.captureTimestamp;
uint8_t *processed_out_buf = mat_pair.processed.data;
uint8_t *color_out_buf = mat_pair.color.data;
// auto begin_time = steady_clock::now();
auto input_ptr = mmaped.at(data.fd);
int bound = m_width * m_height;
if (m_copyInput) {
for (int i = 0; i < bound; i++) {
std::memcpy(color_out_buf + i * 3, input_ptr + i * 4, 3);
}
}
if (m_copyOutput) {
for (int i = 0; i < bound; i++) {
processed_out_buf[i] = input_ptr[i * 4 + 3];
}
}
m_thresholder.returnBuffer(data.fd);
outgoing.set(std::move(mat_pair));
// std::chrono::duration<double, std::milli> elapsedMillis =
// steady_clock::now() - begin_time;
// copyTimeAvgMs =
// approxRollingAverage(copyTimeAvgMs, elapsedMillis.count());
// std::cout << "Copy: " << copyTimeAvgMs << std::endl;
// auto now = steady_clock::now();
// std::chrono::duration<double, std::milli> elapsed =
// (now - lastTime);
// fpsTimeAvgMs = approxRollingAverage(fpsTimeAvgMs, elapsed.count());
// printf("Delta %.2f FPS: %.2f\n", fpsTimeAvgMs,
// 1000.0 / fpsTimeAvgMs);
// lastTime = now;
}
for (const auto &[fd, pointer] : mmaped) {
munmap(pointer, m_width * m_height * 4);
}
});
start_frame_grabber.wait();
{
std::lock_guard<std::mutex> lock{camera_stop_mutex};
grabber.startAndQueue();
}
}
void CameraRunner::stop() {
printf("stopping all\n");
// stop the camera
{
std::lock_guard<std::mutex> lock{camera_stop_mutex};
grabber.stop();
}
// push sentinel value to stop threshold thread
camera_queue.push(nullptr);
threshold.join();
// push sentinel value to stop display thread
gpu_queue.push({-1, ProcessType::None});
display.join();
printf("stopped all\n");
}