blob: d46e7b5a25de40f0c3ad55303682527f92dbfc82 [file] [log] [blame]
Jim Ostrowski977850f2022-01-22 21:04:22 -08001#include "frc971/vision/v4l2_reader.h"
Brian Silverman9dd793b2020-01-31 23:52:21 -08002
3#include <fcntl.h>
4#include <linux/videodev2.h>
5#include <sys/ioctl.h>
6#include <sys/stat.h>
7#include <sys/types.h>
8
Jim Ostrowski8565b402020-02-29 20:26:53 -08009DEFINE_bool(ignore_timestamps, false,
10 "Don't require timestamps on images. Used to allow webcams");
11
Brian Silverman9dd793b2020-01-31 23:52:21 -080012namespace frc971 {
13namespace vision {
14
Austin Schuh77d0bbd2022-12-26 14:00:51 -080015V4L2ReaderBase::V4L2ReaderBase(aos::EventLoop *event_loop,
16 const std::string &device_name)
17 : fd_(open(device_name.c_str(), O_RDWR | O_NONBLOCK)),
18 event_loop_(event_loop) {
Jim Ostrowskifec0c332022-02-06 23:28:26 -080019 PCHECK(fd_.get() != -1) << " Failed to open device " << device_name;
Brian Silverman9dd793b2020-01-31 23:52:21 -080020
Austin Schuh77d0bbd2022-12-26 14:00:51 -080021 // Figure out if we are multi-planar or not.
22 {
23 struct v4l2_capability capability;
24 memset(&capability, 0, sizeof(capability));
25 PCHECK(Ioctl(VIDIOC_QUERYCAP, &capability) == 0);
26
27 LOG(INFO) << "Opening " << device_name;
28 LOG(INFO) << " driver " << capability.driver;
29 LOG(INFO) << " card " << capability.card;
30 LOG(INFO) << " bus_info " << capability.bus_info;
31 if (capability.capabilities & V4L2_CAP_VIDEO_CAPTURE_MPLANE) {
32 LOG(INFO) << " Multi-planar";
33 multiplanar_ = true;
34 }
35 }
36
Brian Silverman9dd793b2020-01-31 23:52:21 -080037 // First, clean up after anybody else who left the device streaming.
Brian Silverman8f24adb2020-02-02 17:15:58 -080038 StreamOff();
Austin Schuh77d0bbd2022-12-26 14:00:51 -080039}
Brian Silverman9dd793b2020-01-31 23:52:21 -080040
Austin Schuh77d0bbd2022-12-26 14:00:51 -080041void V4L2ReaderBase::StreamOn() {
Brian Silverman9dd793b2020-01-31 23:52:21 -080042 {
43 struct v4l2_requestbuffers request;
44 memset(&request, 0, sizeof(request));
45 request.count = buffers_.size();
Austin Schuh77d0bbd2022-12-26 14:00:51 -080046 request.type = multiplanar() ? V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE
47 : V4L2_BUF_TYPE_VIDEO_CAPTURE;
Brian Silverman9dd793b2020-01-31 23:52:21 -080048 request.memory = V4L2_MEMORY_USERPTR;
49 PCHECK(Ioctl(VIDIOC_REQBUFS, &request) == 0);
50 CHECK_EQ(request.count, buffers_.size())
51 << ": Kernel refused to give us the number of buffers we asked for";
52 }
53
Austin Schuh77d0bbd2022-12-26 14:00:51 -080054 {
55 struct v4l2_format format;
56 memset(&format, 0, sizeof(format));
57 format.type = multiplanar() ? V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE
58 : V4L2_BUF_TYPE_VIDEO_CAPTURE;
59 PCHECK(Ioctl(VIDIOC_G_FMT, &format) == 0);
60
61 if (multiplanar()) {
62 cols_ = format.fmt.pix_mp.width;
63 rows_ = format.fmt.pix_mp.height;
64 LOG(INFO) << "Format is " << cols_ << ", " << rows_;
65 CHECK_EQ(format.fmt.pix_mp.pixelformat, V4L2_PIX_FMT_YUYV)
66 << ": Invalid pixel format";
67
68 CHECK_EQ(format.fmt.pix_mp.num_planes, 1u);
69
70 CHECK_EQ(static_cast<int>(format.fmt.pix_mp.plane_fmt[0].bytesperline),
71 cols_ * 2 /* bytes per pixel */);
72 CHECK_EQ(format.fmt.pix_mp.plane_fmt[0].sizeimage, ImageSize());
73 } else {
74 cols_ = format.fmt.pix.width;
75 rows_ = format.fmt.pix.height;
76 LOG(INFO) << "Format is " << cols_ << ", " << rows_;
77 CHECK_EQ(format.fmt.pix.pixelformat, V4L2_PIX_FMT_YUYV)
78 << ": Invalid pixel format";
79
80 CHECK_EQ(static_cast<int>(format.fmt.pix.bytesperline),
81 cols_ * 2 /* bytes per pixel */);
82 CHECK_EQ(format.fmt.pix.sizeimage, ImageSize());
83 }
84 }
85
Brian Silverman9dd793b2020-01-31 23:52:21 -080086 for (size_t i = 0; i < buffers_.size(); ++i) {
Austin Schuh77d0bbd2022-12-26 14:00:51 -080087 buffers_[i].sender = event_loop_->MakeSender<CameraImage>("/camera");
Brian Silverman9dd793b2020-01-31 23:52:21 -080088 EnqueueBuffer(i);
89 }
Austin Schuh77d0bbd2022-12-26 14:00:51 -080090 int type = multiplanar() ? V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE
91 : V4L2_BUF_TYPE_VIDEO_CAPTURE;
92 PCHECK(Ioctl(VIDIOC_STREAMON, &type) == 0);
Brian Silverman9dd793b2020-01-31 23:52:21 -080093}
94
Austin Schuh77d0bbd2022-12-26 14:00:51 -080095bool V4L2ReaderBase::ReadLatestImage() {
Jim Ostrowski977850f2022-01-22 21:04:22 -080096 // First, enqueue any old buffer we already have. This is the one which
97 // may have been sent.
Brian Silverman967e5df2020-02-09 16:43:34 -080098 if (saved_buffer_) {
99 EnqueueBuffer(saved_buffer_.index);
100 saved_buffer_.Clear();
Brian Silverman9dd793b2020-01-31 23:52:21 -0800101 }
102 while (true) {
Brian Silverman967e5df2020-02-09 16:43:34 -0800103 const BufferInfo previous_buffer = saved_buffer_;
Brian Silverman9dd793b2020-01-31 23:52:21 -0800104 saved_buffer_ = DequeueBuffer();
Brian Silverman967e5df2020-02-09 16:43:34 -0800105 if (saved_buffer_) {
Brian Silverman9dd793b2020-01-31 23:52:21 -0800106 // We got a new buffer. Return the previous one (if relevant) and keep
107 // going.
Brian Silverman967e5df2020-02-09 16:43:34 -0800108 if (previous_buffer) {
109 EnqueueBuffer(previous_buffer.index);
Brian Silverman9dd793b2020-01-31 23:52:21 -0800110 }
111 continue;
112 }
Brian Silverman967e5df2020-02-09 16:43:34 -0800113 if (!previous_buffer) {
Brian Silverman9dd793b2020-01-31 23:52:21 -0800114 // There were no images to read. Return an indication of that.
Brian Silverman967e5df2020-02-09 16:43:34 -0800115 return false;
Brian Silverman9dd793b2020-01-31 23:52:21 -0800116 }
117 // We didn't get a new one, but we already got one in a previous
118 // iteration, which means we found an image so return it.
119 saved_buffer_ = previous_buffer;
Brian Silverman967e5df2020-02-09 16:43:34 -0800120 buffers_[saved_buffer_.index].PrepareMessage(rows_, cols_, ImageSize(),
121 saved_buffer_.monotonic_eof);
122 return true;
Brian Silverman9dd793b2020-01-31 23:52:21 -0800123 }
124}
125
Austin Schuh77d0bbd2022-12-26 14:00:51 -0800126void V4L2ReaderBase::SendLatestImage() { buffers_[saved_buffer_.index].Send(); }
Brian Silverman967e5df2020-02-09 16:43:34 -0800127
Austin Schuh77d0bbd2022-12-26 14:00:51 -0800128void V4L2ReaderBase::SetExposure(size_t duration) {
milind-udaebe9b2022-01-09 18:25:24 -0800129 v4l2_control manual_control;
130 manual_control.id = V4L2_CID_EXPOSURE_AUTO;
131 manual_control.value = V4L2_EXPOSURE_MANUAL;
132 PCHECK(Ioctl(VIDIOC_S_CTRL, &manual_control) == 0);
133
134 v4l2_control exposure_control;
135 exposure_control.id = V4L2_CID_EXPOSURE_ABSOLUTE;
136 exposure_control.value = static_cast<int>(duration); // 100 micro s units
137 PCHECK(Ioctl(VIDIOC_S_CTRL, &exposure_control) == 0);
138}
139
Austin Schuh77d0bbd2022-12-26 14:00:51 -0800140void V4L2ReaderBase::UseAutoExposure() {
milind-udaebe9b2022-01-09 18:25:24 -0800141 v4l2_control control;
142 control.id = V4L2_CID_EXPOSURE_AUTO;
143 control.value = V4L2_EXPOSURE_AUTO;
144 PCHECK(Ioctl(VIDIOC_S_CTRL, &control) == 0);
145}
146
Austin Schuh77d0bbd2022-12-26 14:00:51 -0800147void V4L2ReaderBase::Buffer::InitializeMessage(size_t max_image_size) {
Brian Silverman967e5df2020-02-09 16:43:34 -0800148 message_offset = flatbuffers::Offset<CameraImage>();
149 builder = aos::Sender<CameraImage>::Builder();
150 builder = sender.MakeBuilder();
151 // The kernel has an undocumented requirement that the buffer is aligned
Austin Schuh77d0bbd2022-12-26 14:00:51 -0800152 // to 128 bytes. If you give it a nonaligned pointer, it will return EINVAL
Brian Silverman967e5df2020-02-09 16:43:34 -0800153 // and only print something in dmesg with the relevant dynamic debug
154 // prints turned on.
Austin Schuh77d0bbd2022-12-26 14:00:51 -0800155 builder.fbb()->StartIndeterminateVector(max_image_size, 1, 128,
156 &data_pointer);
157 CHECK_EQ(reinterpret_cast<uintptr_t>(data_pointer) % 128, 0u)
Brian Silverman967e5df2020-02-09 16:43:34 -0800158 << ": Flatbuffers failed to align things as requested";
159}
160
Austin Schuh77d0bbd2022-12-26 14:00:51 -0800161void V4L2ReaderBase::Buffer::PrepareMessage(
Brian Silverman967e5df2020-02-09 16:43:34 -0800162 int rows, int cols, size_t image_size,
163 aos::monotonic_clock::time_point monotonic_eof) {
164 CHECK(data_pointer != nullptr);
165 data_pointer = nullptr;
166
167 const auto data_offset = builder.fbb()->EndIndeterminateVector(image_size, 1);
168 auto image_builder = builder.MakeBuilder<CameraImage>();
169 image_builder.add_data(data_offset);
170 image_builder.add_rows(rows);
171 image_builder.add_cols(cols);
172 image_builder.add_monotonic_timestamp_ns(
173 std::chrono::nanoseconds(monotonic_eof.time_since_epoch()).count());
174 message_offset = image_builder.Finish();
Brian Silverman9dd793b2020-01-31 23:52:21 -0800175}
176
Austin Schuh77d0bbd2022-12-26 14:00:51 -0800177int V4L2ReaderBase::Ioctl(unsigned long number, void *arg) {
Brian Silverman9dd793b2020-01-31 23:52:21 -0800178 return ioctl(fd_.get(), number, arg);
179}
180
Austin Schuh77d0bbd2022-12-26 14:00:51 -0800181V4L2ReaderBase::BufferInfo V4L2ReaderBase::DequeueBuffer() {
Brian Silverman9dd793b2020-01-31 23:52:21 -0800182 struct v4l2_buffer buffer;
183 memset(&buffer, 0, sizeof(buffer));
Brian Silverman9dd793b2020-01-31 23:52:21 -0800184 buffer.memory = V4L2_MEMORY_USERPTR;
Austin Schuh77d0bbd2022-12-26 14:00:51 -0800185 if (multiplanar()) {
186 buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
187 struct v4l2_plane planes[1];
188 std::memset(planes, 0, sizeof(planes));
189 buffer.m.planes = planes;
190 buffer.length = 1;
191 const int result = Ioctl(VIDIOC_DQBUF, &buffer);
192 if (result == -1 && errno == EAGAIN) {
193 return BufferInfo();
194 }
195 PCHECK(result == 0) << ": VIDIOC_DQBUF failed";
196 CHECK_LT(buffer.index, buffers_.size());
197
198 CHECK_EQ(reinterpret_cast<uintptr_t>(buffers_[buffer.index].data_pointer),
199 planes[0].m.userptr);
200
201 CHECK_EQ(ImageSize(), planes[0].length);
202 } else {
203 buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
204 const int result = Ioctl(VIDIOC_DQBUF, &buffer);
205 if (result == -1 && errno == EAGAIN) {
206 return BufferInfo();
207 }
208 PCHECK(result == 0) << ": VIDIOC_DQBUF failed";
209 CHECK_LT(buffer.index, buffers_.size());
210 CHECK_EQ(reinterpret_cast<uintptr_t>(buffers_[buffer.index].data_pointer),
211 buffer.m.userptr);
212 CHECK_EQ(ImageSize(), buffer.length);
Brian Silverman9dd793b2020-01-31 23:52:21 -0800213 }
Brian Silverman967e5df2020-02-09 16:43:34 -0800214 CHECK(buffer.flags & V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC);
Jim Ostrowski8565b402020-02-29 20:26:53 -0800215 if (!FLAGS_ignore_timestamps) {
216 // Require that we have good timestamp on images
217 CHECK_EQ(buffer.flags & V4L2_BUF_FLAG_TSTAMP_SRC_MASK,
218 static_cast<uint32_t>(V4L2_BUF_FLAG_TSTAMP_SRC_EOF));
219 }
Brian Silverman967e5df2020-02-09 16:43:34 -0800220 return {static_cast<int>(buffer.index),
221 aos::time::from_timeval(buffer.timestamp)};
Brian Silverman9dd793b2020-01-31 23:52:21 -0800222}
223
Austin Schuh77d0bbd2022-12-26 14:00:51 -0800224void V4L2ReaderBase::EnqueueBuffer(int buffer_number) {
225 // TODO(austin): Detect multiplanar and do this all automatically.
226
Brian Silverman9dd793b2020-01-31 23:52:21 -0800227 CHECK_GE(buffer_number, 0);
228 CHECK_LT(buffer_number, static_cast<int>(buffers_.size()));
229 buffers_[buffer_number].InitializeMessage(ImageSize());
230 struct v4l2_buffer buffer;
Austin Schuh77d0bbd2022-12-26 14:00:51 -0800231 struct v4l2_plane planes[1];
Brian Silverman9dd793b2020-01-31 23:52:21 -0800232 memset(&buffer, 0, sizeof(buffer));
Austin Schuh77d0bbd2022-12-26 14:00:51 -0800233 memset(&planes, 0, sizeof(planes));
Brian Silverman9dd793b2020-01-31 23:52:21 -0800234 buffer.memory = V4L2_MEMORY_USERPTR;
235 buffer.index = buffer_number;
Austin Schuh77d0bbd2022-12-26 14:00:51 -0800236 if (multiplanar()) {
237 buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
238 buffer.m.planes = planes;
239 buffer.length = 1;
240 planes[0].m.userptr =
241 reinterpret_cast<uintptr_t>(buffers_[buffer_number].data_pointer);
242 planes[0].length = ImageSize();
243 planes[0].bytesused = planes[0].length;
244 } else {
245 buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
246 buffer.m.userptr =
247 reinterpret_cast<uintptr_t>(buffers_[buffer_number].data_pointer);
248 buffer.length = ImageSize();
249 }
250
Brian Silverman9dd793b2020-01-31 23:52:21 -0800251 PCHECK(Ioctl(VIDIOC_QBUF, &buffer) == 0);
252}
253
Austin Schuh77d0bbd2022-12-26 14:00:51 -0800254void V4L2ReaderBase::StreamOff() {
255 int type = multiplanar() ? V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE
256 : V4L2_BUF_TYPE_VIDEO_CAPTURE;
Brian Silverman8f24adb2020-02-02 17:15:58 -0800257 const int result = Ioctl(VIDIOC_STREAMOFF, &type);
258 if (result == 0) {
259 return;
260 }
Jim Ostrowski977850f2022-01-22 21:04:22 -0800261 // Some devices (like Alex's webcam) return this if streaming isn't
262 // currently on, unlike what the documentations says should happen.
Brian Silverman8f24adb2020-02-02 17:15:58 -0800263 if (errno == EBUSY) {
264 return;
265 }
266 PLOG(FATAL) << "VIDIOC_STREAMOFF failed";
267}
268
Austin Schuh77d0bbd2022-12-26 14:00:51 -0800269V4L2Reader::V4L2Reader(aos::EventLoop *event_loop,
270 const std::string &device_name)
271 : V4L2ReaderBase(event_loop, device_name) {
272 // Don't know why this magic call to SetExposure is required (before the
273 // camera settings are configured) to make things work on boot of the pi, but
274 // it seems to be-- without it, the image exposure is wrong (too dark). Note--
275 // any valid value seems to work-- just choosing 1 for now
276
277 SetExposure(1);
278
279 struct v4l2_format format;
280 memset(&format, 0, sizeof(format));
281 format.type = multiplanar() ? V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE
282 : V4L2_BUF_TYPE_VIDEO_CAPTURE;
283 format.fmt.pix.width = cols_;
284 format.fmt.pix.height = rows_;
285 format.fmt.pix.pixelformat = V4L2_PIX_FMT_YUYV;
286 // This means we want to capture from a progressive (non-interlaced)
287 // source.
288 format.fmt.pix.field = V4L2_FIELD_NONE;
289 PCHECK(Ioctl(VIDIOC_S_FMT, &format) == 0);
290 CHECK_EQ(static_cast<int>(format.fmt.pix.width), cols_);
291 CHECK_EQ(static_cast<int>(format.fmt.pix.height), rows_);
292 CHECK_EQ(static_cast<int>(format.fmt.pix.bytesperline),
293 cols_ * 2 /* bytes per pixel */);
294 CHECK_EQ(format.fmt.pix.sizeimage, ImageSize());
295
296 StreamOn();
297}
298
299RockchipV4L2Reader::RockchipV4L2Reader(aos::EventLoop *event_loop,
300 const std::string &device_name)
301 : V4L2ReaderBase(event_loop, device_name) {
302 StreamOn();
303}
304
Brian Silverman9dd793b2020-01-31 23:52:21 -0800305} // namespace vision
306} // namespace frc971