blob: 2c073321cdcd284f0908735d9bb76b47fc757b91 [file] [log] [blame]
brians343bc112013-02-10 01:53:46 +00001#include <stdio.h>
2#include <stdlib.h>
3#include <string.h>
4#include <fcntl.h>
5#include <unistd.h>
6#include <errno.h>
7#include <malloc.h>
8#include <sys/stat.h>
9#include <sys/types.h>
10#include <sys/time.h>
11#include <sys/mman.h>
12
13#include <string>
14#include <inttypes.h>
15
16#include "aos/aos_core.h"
17#include "aos/atom_code/camera/V4L2.h"
18#include "aos/atom_code/camera/Buffers.h"
19
20#define CLEAR(x) memset(&(x), 0, sizeof(x))
21
22namespace aos {
23namespace camera {
24
25class Reader {
26 static const char *const dev_name;
27
28 // of the camera
29 int fd_;
30 // the bound socket listening for fd requests
31 int server_fd_;
32
33 static const aos_type_sig kRecycleSignature;
34 aos_queue *queue_, *recycle_queue_;
35 // the number of buffers currently queued in v4l2
36 uint32_t queued_;
37 public:
38 Reader() {
39 struct stat st;
40 if (stat(dev_name, &st) == -1) {
41 LOG(FATAL, "Cannot identify '%s' because of %d: %s\n",
42 dev_name, errno, strerror(errno));
43 }
44 if (!S_ISCHR(st.st_mode)) {
45 LOG(FATAL, "%s is no device\n", dev_name);
46 }
47
48 fd_ = open(dev_name, O_RDWR /* required */ | O_NONBLOCK, 0);
49 if (fd_ == -1) {
50 LOG(FATAL, "Cannot open '%s' because of %d: %s\n",
51 dev_name, errno, strerror(errno));
52 }
53
54 queue_ = aos_fetch_queue_recycle(Buffers::kQueueName.c_str(), &Buffers::kSignature,
55 &kRecycleSignature, &recycle_queue_);
56 // read off any existing recycled messages
57 while (aos_queue_read_msg(recycle_queue_, NON_BLOCK) != NULL);
58 queued_ = 0;
59
60 InitServer();
61 Init();
62 }
63 private:
64 void InitServer() {
65 if (unlink(Buffers::kFDServerName.c_str()) == -1 && errno != ENOENT) {
66 LOG(WARNING, "unlink(kFDServerName(='%s')) failed with %d: %s\n",
67 Buffers::kFDServerName.c_str(), errno, strerror(errno));
68 }
69 if ((server_fd_ = Buffers::CreateSocket(bind)) == -1) {
70 LOG(FATAL, "creating the IPC socket failed\n");
71 }
72 if (listen(server_fd_, 10) == -1) {
73 LOG(FATAL, "listen(%d, 10) failed with %d: %s\n",
74 server_fd_, errno, strerror(errno));
75 }
76 }
77 void SendFD(const int sock) {
78 int myfds[Buffers::kNumFDs]; /* Contains the file descriptors to pass. */
79 myfds[0] = fd_;
80 char buf[CMSG_SPACE(sizeof(myfds))]; /* ancillary data buffer */
81
82 iovec data;
83 memset(&data, 0, sizeof(data));
84 char dummy = 'A';
85 data.iov_base = &dummy;
86 data.iov_len = sizeof(dummy);
87 msghdr msg;
88 memset(&msg, 0, sizeof(msg));
89 msg.msg_iov = &data;
90 msg.msg_iovlen = 1;
91 msg.msg_control = buf;
92 msg.msg_controllen = sizeof(buf);
93 cmsghdr *const cmsg = CMSG_FIRSTHDR(&msg);
94 cmsg->cmsg_level = SOL_SOCKET;
95 cmsg->cmsg_type = SCM_RIGHTS;
96 cmsg->cmsg_len = CMSG_LEN(sizeof(myfds));
97 /* Initialize the payload: */
98 memcpy(CMSG_DATA(cmsg), myfds, sizeof(myfds));
99 if (sendmsg(sock, &msg, 0) == -1) {
100 LOG(ERROR, "sendmsg(%d, %p, 0) failed with %d: %s\n",
101 sock, &msg, errno, strerror(errno));
102 }
103 // leave it open so that the other end can tell if this process dies
104 }
105
106#if 0
107 // if we ever do want to do any of these things, this is how
108 void Stop() {
109 const v4l2_buf_type type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
110 if (xioctl(fd_, VIDIOC_STREAMOFF, &type) == -1) {
111 errno_exit("VIDIOC_STREAMOFF");
112 }
113 }
114 void Close() {
115 if (close(fd_) == -1)
116 errno_exit("close");
117 fd_ = -1;
118 }
119#endif
120
121 void QueueBuffer(v4l2_buffer *buf) {
122 if (xioctl(fd_, VIDIOC_QBUF, buf) == -1) {
123 LOG(WARNING, "ioctl VIDIOC_QBUF(%d, %p) failed with %d: %s. losing buf #%"PRIu32"\n",
124 fd_, &buf, errno, strerror(errno), buf->index);
125 } else {
126 LOG(DEBUG, "put buf #%"PRIu32" into driver's queue\n", buf->index);
127 ++queued_;
128 }
129 }
130 void ReadFrame() {
131 v4l2_buffer buf;
132 CLEAR(buf);
133 buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
134 buf.memory = V4L2_MEMORY_MMAP;
135
136 const Buffers::Message *read;
137 do {
138 read = static_cast<const Buffers::Message *>(
139 // we block waiting for one if we can't dequeue one without leaving
140 // the driver <= 2 (to be safe)
141 aos_queue_read_msg(recycle_queue_, (queued_ <= 2) ? BLOCK : NON_BLOCK));
142 if (read != NULL) {
143 buf.index = read->index;
144 aos_queue_free_msg(recycle_queue_, read);
145 QueueBuffer(&buf);
146 }
147 } while (read != NULL);
148
149 if (xioctl(fd_, VIDIOC_DQBUF, &buf) == -1) {
150 if (errno != EAGAIN) {
151 LOG(ERROR, "ioctl VIDIOC_DQBUF(%d, %p) failed with %d: %s\n",
152 fd_, &buf, errno, strerror(errno));
153 }
154 return;
155 }
156 --queued_;
157 if (buf.index >= Buffers::kNumBuffers) {
158 LOG(ERROR, "buf.index (%"PRIu32") is >= kNumBuffers (%u)\n",
159 buf.index, Buffers::kNumBuffers);
160 return;
161 }
162
163 Buffers::Message *const msg = static_cast<Buffers::Message *>(
164 aos_queue_get_msg(queue_));
165 if (msg == NULL) {
166 LOG(WARNING, "couldn't get a message to send buf #%"PRIu32" from queue %p."
167 " re-queueing now\n", buf.index, queue_);
168 QueueBuffer(&buf);
169 return;
170 }
171 msg->index = buf.index;
172 msg->bytesused = buf.bytesused;
173 memcpy(&msg->timestamp, &buf.timestamp, sizeof(msg->timestamp));
174 msg->sequence = buf.sequence;
175 if (aos_queue_write_msg_free(queue_, msg, OVERRIDE) == -1) {
176 LOG(WARNING, "sending message %p with buf #%"PRIu32" to queue %p failed."
177 " re-queueing now\n", msg, buf.index, queue_);
178 QueueBuffer(&buf);
179 return;
180 } else {
181 LOG(DEBUG, "sent message off to queue %p with buffer #%"PRIu32"\n",
182 queue_, buf.index);
183 }
184 }
185
186 void init_mmap() {
187 v4l2_requestbuffers req;
188 CLEAR(req);
189 req.count = Buffers::kNumBuffers;
190 req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
191 req.memory = V4L2_MEMORY_MMAP;
192 if (xioctl(fd_, VIDIOC_REQBUFS, &req) == -1) {
193 if (EINVAL == errno) {
194 LOG(FATAL, "%s does not support memory mapping\n", dev_name);
195 } else {
196 LOG(FATAL, "ioctl VIDIOC_REQBUFS(%d, %p) failed with %d: %s\n",
197 fd_, &req, errno, strerror(errno));
198 }
199 }
200 queued_ = Buffers::kNumBuffers;
201 if (req.count < Buffers::kNumBuffers) {
202 LOG(FATAL, "Insufficient buffer memory on %s\n", dev_name);
203 }
204 }
205
Austin Schuhb3fb8972013-04-04 05:46:09 +0000206 // Sets one of the camera's user-control values.
207 // Prints the old and new values.
208 // Just prints a message if the camera doesn't support this control or value.
209 bool SetCameraControl(int id, const char *name, int value) {
210 struct v4l2_control getArg = {id, 0};
211 int r = xioctl(fd_, VIDIOC_G_CTRL, &getArg);
212 if (r == 0) {
213 if (getArg.value == value) {
214 printf("Camera control %s was already %d\n", name, getArg.value);
215 return true;
216 }
217 } else if (errno == EINVAL) {
218 printf("Camera control %s is invalid\n", name);
219 errno = 0;
220 return false;
221 }
222
223 struct v4l2_control setArg = {id, value};
224 r = xioctl(fd_, VIDIOC_S_CTRL, &setArg);
225 if (r == 0) {
226 printf("Set camera control %s from %d to %d\n", name, getArg.value, value);
227 return true;
228 }
229
230 printf("Couldn't set camera control %s to %d: %s (errno %d)\n",
231 name, value, strerror(errno), errno);
232 errno = 0;
233 return false;
234 }
235
brians343bc112013-02-10 01:53:46 +0000236 void Init() {
237 v4l2_capability cap;
238 if (xioctl(fd_, VIDIOC_QUERYCAP, &cap) == -1) {
239 if (EINVAL == errno) {
240 LOG(FATAL, "%s is no V4L2 device\n",
241 dev_name);
242 } else {
243 LOG(FATAL, "ioctl VIDIOC_QUERYCAP(%d, %p) failed with %d: %s\n",
244 fd_, &cap, errno, strerror(errno));
245 }
246 }
247 if (!(cap.capabilities & V4L2_CAP_VIDEO_CAPTURE)) {
248 LOG(FATAL, "%s is no video capture device\n",
249 dev_name);
250 }
251 if (!(cap.capabilities & V4L2_CAP_STREAMING)) {
252 LOG(FATAL, "%s does not support streaming i/o\n",
253 dev_name);
254 }
255
256 /* Select video input, video standard and tune here. */
257
258 v4l2_cropcap cropcap;
259 CLEAR(cropcap);
260 cropcap.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
261 if (xioctl(fd_, VIDIOC_CROPCAP, &cropcap) == 0) {
262 v4l2_crop crop;
263 crop.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
264 crop.c = cropcap.defrect; /* reset to default */
265
266 if (xioctl(fd_, VIDIOC_S_CROP, &crop) == -1) {
267 switch (errno) {
268 case EINVAL:
269 /* Cropping not supported. */
270 break;
271 default:
272 /* Errors ignored. */
273 break;
274 }
275 }
276 } else {
277 /* Errors ignored. */
278 }
279
280 v4l2_format fmt;
281 CLEAR(fmt);
282 fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
283 fmt.fmt.pix.width = Buffers::kWidth;
284 fmt.fmt.pix.height = Buffers::kHeight;
285 fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_MJPEG;
286 fmt.fmt.pix.field = V4L2_FIELD_ANY;
287 //fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_YUYV;
288 //fmt.fmt.pix.field = V4L2_FIELD_INTERLACED;
289 if (xioctl(fd_, VIDIOC_S_FMT, &fmt) == -1) {
290 LOG(FATAL, "ioctl VIDIC_S_FMT(%d, %p) failed with %d: %s\n",
291 fd_, &fmt, errno, strerror(errno));
292 }
293 /* Note VIDIOC_S_FMT may change width and height. */
294
295 /* Buggy driver paranoia. */
296 unsigned int min = fmt.fmt.pix.width * 2;
297 if (fmt.fmt.pix.bytesperline < min)
298 fmt.fmt.pix.bytesperline = min;
299 min = fmt.fmt.pix.bytesperline * fmt.fmt.pix.height;
300 if (fmt.fmt.pix.sizeimage < min)
301 fmt.fmt.pix.sizeimage = min;
302
Austin Schuhb3fb8972013-04-04 05:46:09 +0000303 if (!SetCameraControl(V4L2_CID_EXPOSURE_AUTO,
304 "V4L2_CID_EXPOSURE_AUTO", V4L2_EXPOSURE_MANUAL)) {
305 LOG(FATAL, "Failed to set exposure\n");
306 }
307
308 if (!SetCameraControl(V4L2_CID_EXPOSURE_ABSOLUTE,
309 "V4L2_CID_EXPOSURE_ABSOLUTE", 65)) {
310 LOG(FATAL, "Failed to set exposure\n");
311 }
312
313 if (!SetCameraControl(V4L2_CID_BRIGHTNESS, "V4L2_CID_BRIGHTNESS", 128)) {
314 LOG(FATAL, "Failed to set up camera\n");
315 }
316
317 if (!SetCameraControl(V4L2_CID_GAIN, "V4L2_CID_GAIN", 0)) {
318 LOG(FATAL, "Failed to set up camera\n");
319 }
320
brians343bc112013-02-10 01:53:46 +0000321#if 0
322 // set framerate
323 struct v4l2_streamparm *setfps;
324 setfps = (struct v4l2_streamparm *) calloc(1, sizeof(struct v4l2_streamparm));
325 memset(setfps, 0, sizeof(struct v4l2_streamparm));
326 setfps->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
327 setfps->parm.capture.timeperframe.numerator = 1;
328 setfps->parm.capture.timeperframe.denominator = 20;
329 if (xioctl(fd_, VIDIOC_S_PARM, setfps) == -1) {
330 LOG(ERROR, "ioctl VIDIOC_S_PARM(%d, %p) failed with %d: %s\n",
331 fd_, setfps, errno, strerror(errno));
332 exit(EXIT_FAILURE);
333 }
334 LOG(INFO, "framerate ended up at %d/%d\n",
335 setfps->parm.capture.timeperframe.numerator,
336 setfps->parm.capture.timeperframe.denominator);
337#endif
338
339 init_mmap();
340 }
341
342 void Start() {
343 LOG(DEBUG, "queueing buffers for the first time\n");
344 v4l2_buffer buf;
345 for (unsigned int i = 0; i < Buffers::kNumBuffers; ++i) {
346 CLEAR(buf);
347 buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
348 buf.memory = V4L2_MEMORY_MMAP;
349 buf.index = i;
350 QueueBuffer(&buf);
351 }
352 LOG(DEBUG, "done with first queue\n");
353
354 v4l2_buf_type type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
355 if (xioctl(fd_, VIDIOC_STREAMON, &type) == -1) {
356 LOG(FATAL, "ioctl VIDIOC_STREAMON(%d, %p) failed with %d: %s\n",
357 fd_, &type, errno, strerror(errno));
358 }
359 }
360
361 public:
362 void Run() {
363 Start();
364
365 fd_set fds;
366 timeval tv;
367 while (true) {
368 // HAVE TO DO THIS EACH TIME THROUGH THE LOOP
369 tv.tv_sec = 2;
370 tv.tv_usec = 0;
371
372 FD_ZERO(&fds);
373 FD_SET(fd_, &fds);
374 FD_SET(server_fd_, &fds);
375 switch (select(std::max(fd_, server_fd_) + 1, &fds, NULL, NULL, &tv)) {
376 case -1:
377 if (errno != EINTR) {
378 LOG(ERROR, "select(%d, %p, NULL, NULL, %p) failed with %d: %s\n",
379 std::max(fd_, server_fd_) + 1, &fds, &tv, errno, strerror(errno));
380 }
381 continue;
382 case 0:
383 LOG(WARNING, "select timed out\n");
384 continue;
385 }
386
387 if (FD_ISSET(fd_, &fds)) {
Austin Schuhb3fb8972013-04-04 05:46:09 +0000388 LOG(INFO, "Got a frame\n");
brians343bc112013-02-10 01:53:46 +0000389 ReadFrame();
390 }
391 if (FD_ISSET(server_fd_, &fds)) {
392 const int sock = accept4(server_fd_, NULL, NULL, SOCK_NONBLOCK);
393 if (sock == -1) {
394 LOG(ERROR, "accept4(%d, NULL, NULL, SOCK_NONBLOCK(=%d) failed with %d: %s\n",
395 server_fd_, SOCK_NONBLOCK, errno, strerror(errno));
396 } else {
397 SendFD(sock);
398 }
399 }
400 }
401 }
402};
403const char *const Reader::dev_name = "/dev/video0";
404const aos_type_sig Reader::kRecycleSignature{
405 sizeof(Buffers::Message), 1, Buffers::kNumBuffers};
406
407} // namespace camera
408} // namespace aos
409
410AOS_RUN_NRT(aos::camera::Reader)
411