blob: 991339bd3d4d44b4b94e3a9fc6c38ccef9e51f23 [file] [log] [blame]
Parker Schuh24ee58d2017-03-11 16:13:23 -08001#include "aos/vision/image/reader.h"
2
3#include <errno.h>
4#include <fcntl.h>
5#include <malloc.h>
6#include <stdio.h>
7#include <stdlib.h>
8#include <string.h>
9#include <sys/mman.h>
10#include <sys/stat.h>
11#include <sys/time.h>
12#include <sys/types.h>
13#include <unistd.h>
Parker Schuh44f86922017-01-03 23:59:50 -080014
John Park33858a32018-09-28 23:05:48 -070015#include "aos/logging/logging.h"
16#include "aos/time/time.h"
Parker Schuh44f86922017-01-03 23:59:50 -080017
18#define CLEAR(x) memset(&(x), 0, sizeof(x))
19
20namespace camera {
21
22struct Reader::Buffer {
23 void *start;
24 size_t length; // for munmap
25};
26
Parker Schuh24ee58d2017-03-11 16:13:23 -080027aos::vision::CameraParams MakeCameraParams(int32_t width, int32_t height,
28 int32_t exposure, int32_t brightness,
29 int32_t gain, int32_t fps) {
30 aos::vision::CameraParams cam;
31 cam.set_width(width);
32 cam.set_height(height);
33 cam.set_exposure(exposure);
34 cam.set_brightness(brightness);
35 cam.set_gain(gain);
36 cam.set_fps(fps);
37 return cam;
38}
39
Parker Schuh44f86922017-01-03 23:59:50 -080040Reader::Reader(const std::string &dev_name, ProcessCb process,
Parker Schuh24ee58d2017-03-11 16:13:23 -080041 aos::vision::CameraParams params)
Parker Schuh44f86922017-01-03 23:59:50 -080042 : dev_name_(dev_name), process_(std::move(process)), params_(params) {
43 struct stat st;
44 if (stat(dev_name.c_str(), &st) == -1) {
45 PLOG(FATAL, "Cannot identify '%s'", dev_name.c_str());
46 }
47 if (!S_ISCHR(st.st_mode)) {
48 PLOG(FATAL, "%s is no device\n", dev_name.c_str());
49 }
50
51 fd_ = open(dev_name.c_str(), O_RDWR /* required */ | O_NONBLOCK, 0);
52 if (fd_ == -1) {
53 PLOG(FATAL, "Cannot open '%s'", dev_name.c_str());
54 }
55
56 Init();
Parker Schuh309dd722017-02-25 11:31:18 -080057
58 InitMMap();
Tyler Chatowfdd7fbf2019-04-13 21:14:05 -070059
60 SetExposure(params.exposure());
Parker Schuh309dd722017-02-25 11:31:18 -080061 LOG(INFO, "Bat Vision Successfully Initialized.\n");
Parker Schuh44f86922017-01-03 23:59:50 -080062}
63
64void Reader::QueueBuffer(v4l2_buffer *buf) {
65 if (xioctl(fd_, VIDIOC_QBUF, buf) == -1) {
66 PLOG(WARNING,
67 "ioctl VIDIOC_QBUF(%d, %p)."
68 " losing buf #%" PRIu32 "\n",
69 fd_, &buf, buf->index);
70 } else {
71 // LOG(DEBUG, "put buf #%" PRIu32 " into driver's queue\n", buf->index);
72 ++queued_;
73 }
74}
75
76void Reader::HandleFrame() {
77 v4l2_buffer buf;
78 CLEAR(buf);
79 buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
80 buf.memory = V4L2_MEMORY_MMAP;
81
82 if (xioctl(fd_, VIDIOC_DQBUF, &buf) == -1) {
83 if (errno != EAGAIN) {
84 PLOG(ERROR, "ioctl VIDIOC_DQBUF(%d, %p)", fd_, &buf);
85 }
86 return;
87 }
88 --queued_;
89
Parker Schuh309dd722017-02-25 11:31:18 -080090 ++tick_id_;
Parker Schuh44f86922017-01-03 23:59:50 -080091 // Get a timestamp now as proxy for when the image was taken
92 // TODO(ben): the image should come with a timestamp, parker
93 // will know how to get it.
94 auto time = aos::monotonic_clock::now();
95
96 process_(aos::vision::DataRef(
97 reinterpret_cast<const char *>(buffers_[buf.index].start),
98 buf.bytesused),
99 time);
Parker Schuh309dd722017-02-25 11:31:18 -0800100
Parker Schuh44f86922017-01-03 23:59:50 -0800101 QueueBuffer(&buf);
102}
103
104void Reader::MMapBuffers() {
105 buffers_ = new Buffer[kNumBuffers];
106 v4l2_buffer buf;
107 for (unsigned int n = 0; n < kNumBuffers; ++n) {
108 memset(&buf, 0, sizeof(buf));
109 buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
110 buf.memory = V4L2_MEMORY_MMAP;
111 buf.index = n;
112 if (xioctl(fd_, VIDIOC_QUERYBUF, &buf) == -1) {
113 PLOG(FATAL, "ioctl VIDIOC_QUERYBUF(%d, %p)", fd_, &buf);
114 }
115 buffers_[n].length = buf.length;
116 buffers_[n].start = mmap(NULL, buf.length, PROT_READ | PROT_WRITE,
117 MAP_SHARED, fd_, buf.m.offset);
118 if (buffers_[n].start == MAP_FAILED) {
119 PLOG(FATAL,
120 "mmap(NULL, %zd, PROT_READ | PROT_WRITE, MAP_SHARED, %d, %jd)",
121 (size_t)buf.length, fd_, static_cast<intmax_t>(buf.m.offset));
122 }
123 }
124}
125
126void Reader::InitMMap() {
127 v4l2_requestbuffers req;
128 CLEAR(req);
129 req.count = kNumBuffers;
130 req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
131 req.memory = V4L2_MEMORY_MMAP;
132 if (xioctl(fd_, VIDIOC_REQBUFS, &req) == -1) {
133 if (EINVAL == errno) {
134 LOG(FATAL, "%s does not support memory mapping\n", dev_name_.c_str());
135 } else {
136 PLOG(FATAL, "ioctl VIDIOC_REQBUFS(%d, %p)\n", fd_, &req);
137 }
138 }
139 queued_ = kNumBuffers;
Parker Schuh309dd722017-02-25 11:31:18 -0800140 if (req.count != kNumBuffers) {
Parker Schuh44f86922017-01-03 23:59:50 -0800141 LOG(FATAL, "Insufficient buffer memory on %s\n", dev_name_.c_str());
142 }
143}
144
145// Sets one of the camera's user-control values.
146// Prints the old and new values.
147// Just prints a message if the camera doesn't support this control or value.
148bool Reader::SetCameraControl(uint32_t id, const char *name, int value) {
149 struct v4l2_control getArg = {id, 0U};
150 int r = xioctl(fd_, VIDIOC_G_CTRL, &getArg);
151 if (r == 0) {
152 if (getArg.value == value) {
153 LOG(DEBUG, "Camera control %s was already %d\n", name, getArg.value);
154 return true;
155 }
156 } else if (errno == EINVAL) {
157 LOG(DEBUG, "Camera control %s is invalid\n", name);
158 errno = 0;
159 return false;
160 }
161
162 struct v4l2_control setArg = {id, value};
163 r = xioctl(fd_, VIDIOC_S_CTRL, &setArg);
164 if (r == 0) {
Parker Schuh44f86922017-01-03 23:59:50 -0800165 return true;
166 }
167
168 LOG(DEBUG, "Couldn't set camera control %s to %d", name, value);
169 errno = 0;
170 return false;
171}
172
Tyler Chatowfdd7fbf2019-04-13 21:14:05 -0700173bool Reader::SetExposure(int abs_exp) {
174 return SetCameraControl(V4L2_CID_EXPOSURE_ABSOLUTE,
175 "V4L2_CID_EXPOSURE_ABSOLUTE", abs_exp);
176}
177
Parker Schuh44f86922017-01-03 23:59:50 -0800178void Reader::Init() {
179 v4l2_capability cap;
180 if (xioctl(fd_, VIDIOC_QUERYCAP, &cap) == -1) {
181 if (EINVAL == errno) {
182 LOG(FATAL, "%s is no V4L2 device\n", dev_name_.c_str());
183 } else {
184 PLOG(FATAL, "ioctl VIDIOC_QUERYCAP(%d, %p)", fd_, &cap);
185 }
186 }
187 if (!(cap.capabilities & V4L2_CAP_VIDEO_CAPTURE)) {
188 LOG(FATAL, "%s is no video capture device\n", dev_name_.c_str());
189 }
190 if (!(cap.capabilities & V4L2_CAP_STREAMING)) {
191 LOG(FATAL, "%s does not support streaming i/o\n", dev_name_.c_str());
192 }
193
194 /* Select video input, video standard and tune here. */
195
196 v4l2_cropcap cropcap;
197 CLEAR(cropcap);
198 cropcap.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
199 if (xioctl(fd_, VIDIOC_CROPCAP, &cropcap) == 0) {
200 v4l2_crop crop;
201 crop.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
202 crop.c = cropcap.defrect; /* reset to default */
203
204 if (xioctl(fd_, VIDIOC_S_CROP, &crop) == -1) {
205 switch (errno) {
206 case EINVAL:
207 /* Cropping not supported. */
208 break;
209 default:
210 /* Errors ignored. */
211 PLOG(WARNING, "xioctl VIDIOC_S_CROP");
212 break;
213 }
214 }
215 } else {
216 PLOG(WARNING, "xioctl VIDIOC_CROPCAP");
217 }
218
219 v4l2_format fmt;
220 CLEAR(fmt);
221 fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
Parker Schuh24ee58d2017-03-11 16:13:23 -0800222 fmt.fmt.pix.width = params_.width();
223 fmt.fmt.pix.height = params_.height();
Parker Schuh44f86922017-01-03 23:59:50 -0800224 fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_MJPEG;
225 fmt.fmt.pix.field = V4L2_FIELD_ANY;
226 // fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_YUYV;
227 // fmt.fmt.pix.field = V4L2_FIELD_INTERLACED;
228 if (xioctl(fd_, VIDIOC_S_FMT, &fmt) == -1) {
229 LOG(FATAL, "ioctl VIDIC_S_FMT(%d, %p) failed with %d: %s\n", fd_, &fmt,
230 errno, strerror(errno));
231 }
232 /* Note VIDIOC_S_FMT may change width and height. */
233
234 /* Buggy driver paranoia. */
235 unsigned int min = fmt.fmt.pix.width * 2;
236 if (fmt.fmt.pix.bytesperline < min) fmt.fmt.pix.bytesperline = min;
237 min = fmt.fmt.pix.bytesperline * fmt.fmt.pix.height;
238 if (fmt.fmt.pix.sizeimage < min) fmt.fmt.pix.sizeimage = min;
239
240 if (!SetCameraControl(V4L2_CID_EXPOSURE_AUTO, "V4L2_CID_EXPOSURE_AUTO",
241 V4L2_EXPOSURE_MANUAL)) {
242 LOG(FATAL, "Failed to set exposure\n");
243 }
244
245 if (!SetCameraControl(V4L2_CID_EXPOSURE_ABSOLUTE,
Parker Schuh24ee58d2017-03-11 16:13:23 -0800246 "V4L2_CID_EXPOSURE_ABSOLUTE", params_.exposure())) {
Parker Schuh44f86922017-01-03 23:59:50 -0800247 LOG(FATAL, "Failed to set exposure\n");
248 }
249
250 if (!SetCameraControl(V4L2_CID_BRIGHTNESS, "V4L2_CID_BRIGHTNESS",
Parker Schuh24ee58d2017-03-11 16:13:23 -0800251 params_.brightness())) {
Parker Schuh44f86922017-01-03 23:59:50 -0800252 LOG(FATAL, "Failed to set up camera\n");
253 }
254
Parker Schuh24ee58d2017-03-11 16:13:23 -0800255 if (!SetCameraControl(V4L2_CID_GAIN, "V4L2_CID_GAIN", params_.gain())) {
Parker Schuh44f86922017-01-03 23:59:50 -0800256 LOG(FATAL, "Failed to set up camera\n");
257 }
258
Parker Schuh44f86922017-01-03 23:59:50 -0800259 // set framerate
260 struct v4l2_streamparm *setfps;
261 setfps = (struct v4l2_streamparm *)calloc(1, sizeof(struct v4l2_streamparm));
262 memset(setfps, 0, sizeof(struct v4l2_streamparm));
263 setfps->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
264 setfps->parm.capture.timeperframe.numerator = 1;
Parker Schuh24ee58d2017-03-11 16:13:23 -0800265 setfps->parm.capture.timeperframe.denominator = params_.fps();
Parker Schuh44f86922017-01-03 23:59:50 -0800266 if (xioctl(fd_, VIDIOC_S_PARM, setfps) == -1) {
267 PLOG(FATAL, "ioctl VIDIOC_S_PARM(%d, %p)\n", fd_, setfps);
268 }
269 LOG(INFO, "framerate ended up at %d/%d\n",
270 setfps->parm.capture.timeperframe.numerator,
271 setfps->parm.capture.timeperframe.denominator);
Parker Schuh44f86922017-01-03 23:59:50 -0800272}
273
274aos::vision::ImageFormat Reader::get_format() {
275 struct v4l2_format fmt;
276 fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
277 if (xioctl(fd_, VIDIOC_G_FMT, &fmt) == -1) {
278 PLOG(FATAL, "ioctl VIDIC_G_FMT(%d, %p)\n", fd_, &fmt);
279 }
280
281 return aos::vision::ImageFormat{(int)fmt.fmt.pix.width,
282 (int)fmt.fmt.pix.height};
283}
284
285void Reader::Start() {
286 LOG(DEBUG, "queueing buffers for the first time\n");
287 v4l2_buffer buf;
288 for (unsigned int i = 0; i < kNumBuffers; ++i) {
289 CLEAR(buf);
290 buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
291 buf.memory = V4L2_MEMORY_MMAP;
292 buf.index = i;
293 QueueBuffer(&buf);
294 }
295 LOG(DEBUG, "done with first queue\n");
296
297 v4l2_buf_type type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
298 if (xioctl(fd_, VIDIOC_STREAMON, &type) == -1) {
299 PLOG(FATAL, "ioctl VIDIOC_STREAMON(%d, %p)\n", fd_, &type);
300 }
301}
302
303} // namespace camera