Add raw bayer to bitmap conversion tool
[omap4-v4l2-camera:takashi-suzukis-yavta.git] / yavta.c
1 /*
2  * yavta --  Yet Another V4L2 Test Application
3  *
4  * Copyright (C) 2005-2010 Laurent Pinchart <laurent.pinchart@ideasonboard.com>
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License along
17  * with this program; if not, write to the Free Software Foundation, Inc.,
18  */
19
20 #include <stdio.h>
21 #include <string.h>
22 #include <fcntl.h>
23 #include <unistd.h>
24 #include <stdint.h>
25 #include <stdlib.h>
26 #include <errno.h>
27 #include <getopt.h>
28 #include <sched.h>
29 #include <sys/ioctl.h>
30 #include <sys/mman.h>
31 #include <sys/select.h>
32 #include <sys/time.h>
33
34 #include <linux/videodev2.h>
35
36 #ifndef V4L2_BUF_FLAG_ERROR
37 #define V4L2_BUF_FLAG_ERROR     0x0040
38 #endif
39
40 #define ARRAY_SIZE(a)   (sizeof(a)/sizeof((a)[0]))
41
42 struct buffer
43 {
44         unsigned int size;
45         void *mem;
46 };
47
48 struct device
49 {
50         int fd;
51
52         enum v4l2_buf_type type;
53         enum v4l2_memory memtype;
54         unsigned int nbufs;
55         struct buffer *buffers;
56
57         unsigned int width;
58         unsigned int height;
59         unsigned int bytesperline;
60         unsigned int imagesize;
61
62         void *pattern;
63         unsigned int patternsize;
64 };
65
66 static const char *v4l2_buf_type_name(enum v4l2_buf_type type)
67 {
68         static struct {
69                 enum v4l2_buf_type type;
70                 const char *name;
71         } names[] = {
72                 { V4L2_BUF_TYPE_VIDEO_CAPTURE, "Video capture" },
73                 { V4L2_BUF_TYPE_VIDEO_OUTPUT, "Video output" },
74                 { V4L2_BUF_TYPE_VIDEO_OVERLAY, "Video overlay" },
75         };
76
77         unsigned int i;
78
79         for (i = 0; i < ARRAY_SIZE(names); ++i) {
80                 if (names[i].type == type)
81                         return names[i].name;
82         }
83
84         if (type & V4L2_BUF_TYPE_PRIVATE)
85                 return "Private";
86         else
87                 return "Unknown";
88 }
89
90 #ifndef V4L2_PIX_FMT_SGRBG8     /* 2.6.31 */
91 #define V4L2_PIX_FMT_SGRBG8     v4l2_fourcc('G', 'R', 'B', 'G')
92 #endif
93 #ifndef V4L2_PIX_FMT_SRGGB8     /* 2.6.33 */
94 #define V4L2_PIX_FMT_SRGGB8     v4l2_fourcc('R', 'G', 'G', 'B')
95 #define V4L2_PIX_FMT_SBGGR10    v4l2_fourcc('B', 'G', '1', '0')
96 #define V4L2_PIX_FMT_SGBRG10    v4l2_fourcc('G', 'B', '1', '0')
97 #define V4L2_PIX_FMT_SRGGB10    v4l2_fourcc('R', 'G', '1', '0')
98 #endif
99 #ifndef V4L2_PIX_FMT_SBGGR12    /* 2.6.39 */
100 #define V4L2_PIX_FMT_SBGGR12    v4l2_fourcc('B', 'G', '1', '2')
101 #define V4L2_PIX_FMT_SGBRG12    v4l2_fourcc('G', 'B', '1', '2')
102 #define V4L2_PIX_FMT_SGRBG12    v4l2_fourcc('B', 'A', '1', '2')
103 #define V4L2_PIX_FMT_SRGGB12    v4l2_fourcc('R', 'G', '1', '2')
104 #endif
105
106 static struct {
107         const char *name;
108         unsigned int fourcc;
109 } pixel_formats[] = {
110         { "Y8", V4L2_PIX_FMT_GREY },
111         { "Y16", V4L2_PIX_FMT_Y16 },
112         { "YUYV", V4L2_PIX_FMT_YUYV },
113         { "UYVY", V4L2_PIX_FMT_UYVY },
114         { "SBGGR8", V4L2_PIX_FMT_SBGGR8 },
115         { "SGBRG8", V4L2_PIX_FMT_SGBRG8 },
116         { "SGRBG8", V4L2_PIX_FMT_SGRBG8 },
117         { "SRGGB8", V4L2_PIX_FMT_SRGGB8 },
118         { "SGRBG10_DPCM8", V4L2_PIX_FMT_SGRBG10DPCM8 },
119         { "SBGGR10", V4L2_PIX_FMT_SBGGR10 },
120         { "SGBRG10", V4L2_PIX_FMT_SGBRG10 },
121         { "SGRBG10", V4L2_PIX_FMT_SGRBG10 },
122         { "SRGGB10", V4L2_PIX_FMT_SRGGB10 },
123         { "SBGGR12", V4L2_PIX_FMT_SBGGR12 },
124         { "SGBRG12", V4L2_PIX_FMT_SGBRG12 },
125         { "SGRBG12", V4L2_PIX_FMT_SGRBG12 },
126         { "SRGGB12", V4L2_PIX_FMT_SRGGB12 },
127         { "DV", V4L2_PIX_FMT_DV },
128         { "MJPEG", V4L2_PIX_FMT_MJPEG },
129 };
130
131 static const char *v4l2_format_name(unsigned int fourcc)
132 {
133         static char name[5];
134         unsigned int i;
135
136         for (i = 0; i < ARRAY_SIZE(pixel_formats); ++i) {
137                 if (pixel_formats[i].fourcc == fourcc)
138                         return pixel_formats[i].name;
139         }
140
141         for (i = 0; i < 4; ++i) {
142                 name[i] = fourcc & 0xff;
143                 fourcc >>= 8;
144         }
145
146         name[4] = '\0';
147         return name;
148 }
149
150 static unsigned int v4l2_format_code(const char *name)
151 {
152         unsigned int i;
153
154         for (i = 0; i < ARRAY_SIZE(pixel_formats); ++i) {
155                 if (strcasecmp(pixel_formats[i].name, name) == 0)
156                         return pixel_formats[i].fourcc;
157         }
158
159         return 0;
160 }
161
162 static int video_open(struct device *dev, const char *devname, int no_query)
163 {
164         struct v4l2_capability cap;
165         int ret;
166
167         memset(dev, 0, sizeof *dev);
168         dev->fd = -1;
169         dev->memtype = V4L2_MEMORY_MMAP;
170         dev->buffers = NULL;
171         dev->type = (enum v4l2_buf_type)-1;
172
173         dev->fd = open(devname, O_RDWR);
174         if (dev->fd < 0) {
175                 printf("Error opening device %s: %d.\n", devname, errno);
176                 return dev->fd;
177         }
178
179         printf("Device %s opened.\n", devname);
180
181         if (no_query) {
182                 /* Assume capture device. */
183                 dev->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
184                 return 0;
185         }
186
187         memset(&cap, 0, sizeof cap);
188         ret = ioctl(dev->fd, VIDIOC_QUERYCAP, &cap);
189         if (ret < 0)
190                 return 0;
191
192         if (cap.capabilities & V4L2_CAP_VIDEO_CAPTURE)
193                 dev->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
194         else if (cap.capabilities & V4L2_CAP_VIDEO_OUTPUT)
195                 dev->type = V4L2_BUF_TYPE_VIDEO_OUTPUT;
196         else {
197                 printf("Error opening device %s: neither video capture "
198                         "nor video output supported.\n", devname);
199                 close(dev->fd);
200                 return -EINVAL;
201         }
202
203         printf("Device `%s' on `%s' is a video %s device.\n",
204                 cap.card, cap.bus_info,
205                 dev->type == V4L2_BUF_TYPE_VIDEO_CAPTURE ? "capture" : "output");
206         return 0;
207 }
208
209 static void video_close(struct device *dev)
210 {
211         free(dev->pattern);
212         free(dev->buffers);
213         close(dev->fd);
214 }
215
216 static void uvc_get_control(struct device *dev, unsigned int id)
217 {
218         struct v4l2_control ctrl;
219         int ret;
220
221         ctrl.id = id;
222
223         ret = ioctl(dev->fd, VIDIOC_G_CTRL, &ctrl);
224         if (ret < 0) {
225                 printf("unable to get control: %s (%d).\n",
226                         strerror(errno), errno);
227                 return;
228         }
229
230         printf("Control 0x%08x value %u\n", id, ctrl.value);
231 }
232
233 static void uvc_set_control(struct device *dev, unsigned int id, int value)
234 {
235         struct v4l2_control ctrl;
236         int ret;
237
238         ctrl.id = id;
239         ctrl.value = value;
240
241         ret = ioctl(dev->fd, VIDIOC_S_CTRL, &ctrl);
242         if (ret < 0) {
243                 printf("unable to set control: %s (%d).\n",
244                         strerror(errno), errno);
245                 return;
246         }
247
248         printf("Control 0x%08x set to %u, is %u\n", id, value,
249                 ctrl.value);
250 }
251
252 static int video_get_format(struct device *dev)
253 {
254         struct v4l2_format fmt;
255         int ret;
256
257         memset(&fmt, 0, sizeof fmt);
258         fmt.type = dev->type;
259
260         ret = ioctl(dev->fd, VIDIOC_G_FMT, &fmt);
261         if (ret < 0) {
262                 printf("Unable to get format: %s (%d).\n", strerror(errno),
263                         errno);
264                 return ret;
265         }
266
267         dev->width = fmt.fmt.pix.width;
268         dev->height = fmt.fmt.pix.height;
269         dev->bytesperline = fmt.fmt.pix.bytesperline;
270         dev->imagesize = fmt.fmt.pix.bytesperline ? fmt.fmt.pix.sizeimage : 0;
271
272         printf("Video format: %s (%08x) %ux%u buffer size %u\n",
273                 v4l2_format_name(fmt.fmt.pix.pixelformat), fmt.fmt.pix.pixelformat,
274                 fmt.fmt.pix.width, fmt.fmt.pix.height, fmt.fmt.pix.sizeimage);
275         return 0;
276 }
277
278 static int video_set_format(struct device *dev, unsigned int w, unsigned int h, unsigned int format)
279 {
280         struct v4l2_format fmt;
281         int ret;
282
283         memset(&fmt, 0, sizeof fmt);
284         fmt.type = dev->type;
285         fmt.fmt.pix.width = w;
286         fmt.fmt.pix.height = h;
287         fmt.fmt.pix.pixelformat = format;
288         fmt.fmt.pix.field = V4L2_FIELD_ANY;
289
290         ret = ioctl(dev->fd, VIDIOC_S_FMT, &fmt);
291         if (ret < 0) {
292                 printf("Unable to set format: %s (%d).\n", strerror(errno),
293                         errno);
294                 return ret;
295         }
296
297         printf("Video format set: %s (%08x) %ux%u buffer size %u\n",
298                 v4l2_format_name(fmt.fmt.pix.pixelformat), fmt.fmt.pix.pixelformat,
299                 fmt.fmt.pix.width, fmt.fmt.pix.height, fmt.fmt.pix.sizeimage);
300         return 0;
301 }
302
303 static int video_set_framerate(struct device *dev, struct v4l2_fract *time_per_frame)
304 {
305         struct v4l2_streamparm parm;
306         int ret;
307
308         memset(&parm, 0, sizeof parm);
309         parm.type = dev->type;
310
311         ret = ioctl(dev->fd, VIDIOC_G_PARM, &parm);
312         if (ret < 0) {
313                 printf("Unable to get frame rate: %d.\n", errno);
314                 return ret;
315         }
316
317         printf("Current frame rate: %u/%u\n",
318                 parm.parm.capture.timeperframe.numerator,
319                 parm.parm.capture.timeperframe.denominator);
320
321         printf("Setting frame rate to: %u/%u\n",
322                 time_per_frame->numerator,
323                 time_per_frame->denominator);
324
325         parm.parm.capture.timeperframe.numerator = time_per_frame->numerator;
326         parm.parm.capture.timeperframe.denominator = time_per_frame->denominator;
327
328         ret = ioctl(dev->fd, VIDIOC_S_PARM, &parm);
329         if (ret < 0) {
330                 printf("Unable to set frame rate: %d.\n", errno);
331                 return ret;
332         }
333
334         ret = ioctl(dev->fd, VIDIOC_G_PARM, &parm);
335         if (ret < 0) {
336                 printf("Unable to get frame rate: %d.\n", errno);
337                 return ret;
338         }
339
340         printf("Frame rate set: %u/%u\n",
341                 parm.parm.capture.timeperframe.numerator,
342                 parm.parm.capture.timeperframe.denominator);
343         return 0;
344 }
345
346 static int video_alloc_buffers(struct device *dev, int nbufs, unsigned int offset)
347 {
348         struct v4l2_requestbuffers rb;
349         struct v4l2_buffer buf;
350         int page_size;
351         struct buffer *buffers;
352         unsigned int i;
353         int ret;
354
355         memset(&rb, 0, sizeof rb);
356         rb.count = nbufs;
357         rb.type = dev->type;
358         rb.memory = dev->memtype;
359
360         ret = ioctl(dev->fd, VIDIOC_REQBUFS, &rb);
361         if (ret < 0) {
362                 printf("Unable to request buffers: %d.\n", errno);
363                 return ret;
364         }
365
366         printf("%u buffers requested.\n", rb.count);
367
368         buffers = malloc(rb.count * sizeof buffers[0]);
369         if (buffers == NULL)
370                 return -ENOMEM;
371
372         page_size = getpagesize();
373
374         /* Map the buffers. */
375         for (i = 0; i < rb.count; ++i) {
376                 memset(&buf, 0, sizeof buf);
377                 buf.index = i;
378                 buf.type = dev->type;
379                 buf.memory = dev->memtype;
380                 ret = ioctl(dev->fd, VIDIOC_QUERYBUF, &buf);
381                 if (ret < 0) {
382                         printf("Unable to query buffer %u (%d).\n", i, errno);
383                         return ret;
384                 }
385                 printf("length: %u offset: %u\n", buf.length, buf.m.offset);
386
387                 switch (dev->memtype) {
388                 case V4L2_MEMORY_MMAP:
389                         buffers[i].mem = mmap(0, buf.length, PROT_READ | PROT_WRITE, MAP_SHARED, dev->fd, buf.m.offset);
390                         if (buffers[i].mem == MAP_FAILED) {
391                                 printf("Unable to map buffer %u (%d)\n", i, errno);
392                                 return ret;
393                         }
394                         buffers[i].size = buf.length;
395                         printf("Buffer %u mapped at address %p.\n", i, buffers[i].mem);
396                         break;
397
398                 case V4L2_MEMORY_USERPTR:
399                         ret = posix_memalign(&buffers[i].mem, page_size, buf.length + offset);
400                         if (ret < 0) {
401                                 printf("Unable to allocate buffer %u (%d)\n", i, ret);
402                                 return -ENOMEM;
403                         }
404                         buffers[i].mem += offset;
405                         buffers[i].size = buf.length;
406                         printf("Buffer %u allocated at address %p.\n", i, buffers[i].mem);
407                         break;
408
409                 default:
410                         break;
411                 }
412         }
413
414         dev->buffers = buffers;
415         dev->nbufs = rb.count;
416         return 0;
417 }
418
419 static int video_free_buffers(struct device *dev)
420 {
421         struct v4l2_requestbuffers rb;
422         unsigned int i;
423         int ret;
424
425         if (dev->nbufs == 0)
426                 return 0;
427
428         for (i = 0; i < dev->nbufs; ++i) {
429                 switch (dev->memtype) {
430                 case V4L2_MEMORY_MMAP:
431                         ret = munmap(dev->buffers[i].mem, dev->buffers[i].size);
432                         if (ret < 0) {
433                                 printf("Unable to unmap buffer %u (%d)\n", i, errno);
434                                 return ret;
435                         }
436                         break;
437
438                 case V4L2_MEMORY_USERPTR:
439                         free(dev->buffers[i].mem);
440                         break;
441
442                 default:
443                         break;
444                 }
445
446                 dev->buffers[i].mem = NULL;
447         }
448
449         memset(&rb, 0, sizeof rb);
450         rb.count = 0;
451         rb.type = dev->type;
452         rb.memory = dev->memtype;
453
454         ret = ioctl(dev->fd, VIDIOC_REQBUFS, &rb);
455         if (ret < 0) {
456                 printf("Unable to release buffers: %d.\n", errno);
457                 return ret;
458         }
459
460         printf("%u buffers released.\n", dev->nbufs);
461
462         free(dev->buffers);
463         dev->nbufs = 0;
464         dev->buffers = NULL;
465
466         return 0;
467 }
468
469 static int video_queue_buffer(struct device *dev, int index)
470 {
471         struct v4l2_buffer buf;
472         int ret;
473
474         memset(&buf, 0, sizeof buf);
475         buf.index = index;
476         buf.type = dev->type;
477         buf.memory = dev->memtype;
478         buf.length = dev->buffers[index].size;
479         if (dev->memtype == V4L2_MEMORY_USERPTR)
480                 buf.m.userptr = (unsigned long)dev->buffers[index].mem;
481
482         if (dev->type == V4L2_BUF_TYPE_VIDEO_OUTPUT) {
483                 buf.bytesused = dev->patternsize;
484                 memcpy(dev->buffers[buf.index].mem, dev->pattern, dev->patternsize);
485         } else
486                 memset(dev->buffers[buf.index].mem, 0x55, buf.length);
487
488         ret = ioctl(dev->fd, VIDIOC_QBUF, &buf);
489         if (ret < 0)
490                 printf("Unable to queue buffer (%d).\n", errno);
491
492         return ret;
493 }
494
495 static int video_enable(struct device *dev, int enable)
496 {
497         int type = dev->type;
498         int ret;
499
500         ret = ioctl(dev->fd, enable ? VIDIOC_STREAMON : VIDIOC_STREAMOFF, &type);
501         if (ret < 0) {
502                 printf("Unable to %s streaming: %d.\n", enable ? "start" : "stop",
503                         errno);
504                 return ret;
505         }
506
507         return 0;
508 }
509
510 static void video_query_menu(struct device *dev, unsigned int id,
511                              unsigned int min, unsigned int max)
512 {
513         struct v4l2_querymenu menu;
514         int ret;
515
516         for (menu.index = min; menu.index <= max; menu.index++) {
517                 menu.id = id;
518                 ret = ioctl(dev->fd, VIDIOC_QUERYMENU, &menu);
519                 if (ret < 0)
520                         continue;
521
522                 printf("  %u: %.32s\n", menu.index, menu.name);
523         };
524 }
525
526 static void video_list_controls(struct device *dev)
527 {
528         struct v4l2_queryctrl query;
529         struct v4l2_control ctrl;
530         unsigned int nctrls = 0;
531         char value[12];
532         int ret;
533
534 #ifndef V4L2_CTRL_FLAG_NEXT_CTRL
535         unsigned int i;
536
537         for (i = V4L2_CID_BASE; i <= V4L2_CID_LASTP1; ++i) {
538                 query.id = i;
539 #else
540         query.id = 0;
541         while (1) {
542                 query.id |= V4L2_CTRL_FLAG_NEXT_CTRL;
543 #endif
544                 ret = ioctl(dev->fd, VIDIOC_QUERYCTRL, &query);
545                 if (ret < 0)
546                         break;
547
548                 if (query.flags & V4L2_CTRL_FLAG_DISABLED)
549                         continue;
550
551                 ctrl.id = query.id;
552                 ret = ioctl(dev->fd, VIDIOC_G_CTRL, &ctrl);
553                 if (ret < 0)
554                         strcpy(value, "n/a");
555                 else
556                         sprintf(value, "%d", ctrl.value);
557
558                 if (query.type == V4L2_CTRL_TYPE_CTRL_CLASS) {
559                         printf("--- %s (class 0x%08x) ---\n", query.name, query.id);
560                         continue;
561                 }
562
563                 printf("control 0x%08x `%s' min %d max %d step %d default %d current %s.\n",
564                         query.id, query.name, query.minimum, query.maximum,
565                         query.step, query.default_value, value);
566
567                 if (query.type == V4L2_CTRL_TYPE_MENU)
568                         video_query_menu(dev, query.id, query.minimum, query.maximum);
569
570                 nctrls++;
571         }
572
573         if (nctrls)
574                 printf("%u control%s found.\n", nctrls, nctrls > 1 ? "s" : "");
575         else
576                 printf("No control found.\n");
577 }
578
579 static void video_enum_frame_intervals(struct device *dev, __u32 pixelformat,
580         unsigned int width, unsigned int height)
581 {
582         struct v4l2_frmivalenum ival;
583         unsigned int i;
584         int ret;
585
586         for (i = 0; ; ++i) {
587                 memset(&ival, 0, sizeof ival);
588                 ival.index = i;
589                 ival.pixel_format = pixelformat;
590                 ival.width = width;
591                 ival.height = height;
592                 ret = ioctl(dev->fd, VIDIOC_ENUM_FRAMEINTERVALS, &ival);
593                 if (ret < 0)
594                         break;
595
596                 if (i != ival.index)
597                         printf("Warning: driver returned wrong ival index "
598                                 "%u.\n", ival.index);
599                 if (pixelformat != ival.pixel_format)
600                         printf("Warning: driver returned wrong ival pixel "
601                                 "format %08x.\n", ival.pixel_format);
602                 if (width != ival.width)
603                         printf("Warning: driver returned wrong ival width "
604                                 "%u.\n", ival.width);
605                 if (height != ival.height)
606                         printf("Warning: driver returned wrong ival height "
607                                 "%u.\n", ival.height);
608
609                 if (i != 0)
610                         printf(", ");
611
612                 switch (ival.type) {
613                 case V4L2_FRMIVAL_TYPE_DISCRETE:
614                         printf("%u/%u",
615                                 ival.discrete.numerator,
616                                 ival.discrete.denominator);
617                         break;
618
619                 case V4L2_FRMIVAL_TYPE_CONTINUOUS:
620                         printf("%u/%u - %u/%u",
621                                 ival.stepwise.min.numerator,
622                                 ival.stepwise.min.denominator,
623                                 ival.stepwise.max.numerator,
624                                 ival.stepwise.max.denominator);
625                         return;
626
627                 case V4L2_FRMIVAL_TYPE_STEPWISE:
628                         printf("%u/%u - %u/%u (by %u/%u)",
629                                 ival.stepwise.min.numerator,
630                                 ival.stepwise.min.denominator,
631                                 ival.stepwise.max.numerator,
632                                 ival.stepwise.max.denominator,
633                                 ival.stepwise.step.numerator,
634                                 ival.stepwise.step.denominator);
635                         return;
636
637                 default:
638                         break;
639                 }
640         }
641 }
642
643 static void video_enum_frame_sizes(struct device *dev, __u32 pixelformat)
644 {
645         struct v4l2_frmsizeenum frame;
646         unsigned int i;
647         int ret;
648
649         for (i = 0; ; ++i) {
650                 memset(&frame, 0, sizeof frame);
651                 frame.index = i;
652                 frame.pixel_format = pixelformat;
653                 ret = ioctl(dev->fd, VIDIOC_ENUM_FRAMESIZES, &frame);
654                 if (ret < 0)
655                         break;
656
657                 if (i != frame.index)
658                         printf("Warning: driver returned wrong frame index "
659                                 "%u.\n", frame.index);
660                 if (pixelformat != frame.pixel_format)
661                         printf("Warning: driver returned wrong frame pixel "
662                                 "format %08x.\n", frame.pixel_format);
663
664                 switch (frame.type) {
665                 case V4L2_FRMSIZE_TYPE_DISCRETE:
666                         printf("\tFrame size: %ux%u (", frame.discrete.width,
667                                 frame.discrete.height);
668                         video_enum_frame_intervals(dev, frame.pixel_format,
669                                 frame.discrete.width, frame.discrete.height);
670                         printf(")\n");
671                         break;
672
673                 case V4L2_FRMSIZE_TYPE_CONTINUOUS:
674                         printf("\tFrame size: %ux%u - %ux%u (",
675                                 frame.stepwise.min_width,
676                                 frame.stepwise.min_height,
677                                 frame.stepwise.max_width,
678                                 frame.stepwise.max_height);
679                         video_enum_frame_intervals(dev, frame.pixel_format,
680                                 frame.stepwise.max_width,
681                                 frame.stepwise.max_height);
682                         printf(")\n");
683                         break;
684
685                 case V4L2_FRMSIZE_TYPE_STEPWISE:
686                         printf("\tFrame size: %ux%u - %ux%u (by %ux%u) (\n",
687                                 frame.stepwise.min_width,
688                                 frame.stepwise.min_height,
689                                 frame.stepwise.max_width,
690                                 frame.stepwise.max_height,
691                                 frame.stepwise.step_width,
692                                 frame.stepwise.step_height);
693                         video_enum_frame_intervals(dev, frame.pixel_format,
694                                 frame.stepwise.max_width,
695                                 frame.stepwise.max_height);
696                         printf(")\n");
697                         break;
698
699                 default:
700                         break;
701                 }
702         }
703 }
704
705 static void video_enum_formats(struct device *dev, enum v4l2_buf_type type)
706 {
707         struct v4l2_fmtdesc fmt;
708         unsigned int i;
709         int ret;
710
711         for (i = 0; ; ++i) {
712                 memset(&fmt, 0, sizeof fmt);
713                 fmt.index = i;
714                 fmt.type = type;
715                 ret = ioctl(dev->fd, VIDIOC_ENUM_FMT, &fmt);
716                 if (ret < 0)
717                         break;
718
719                 if (i != fmt.index)
720                         printf("Warning: driver returned wrong format index "
721                                 "%u.\n", fmt.index);
722                 if (type != fmt.type)
723                         printf("Warning: driver returned wrong format type "
724                                 "%u.\n", fmt.type);
725
726                 printf("\tFormat %u: %s (%08x)\n", i,
727                         v4l2_format_name(fmt.pixelformat), fmt.pixelformat);
728                 printf("\tType: %s (%u)\n", v4l2_buf_type_name(fmt.type),
729                         fmt.type);
730                 printf("\tName: %.32s\n", fmt.description);
731                 video_enum_frame_sizes(dev, fmt.pixelformat);
732                 printf("\n");
733         }
734 }
735
736 static void video_enum_inputs(struct device *dev)
737 {
738         struct v4l2_input input;
739         unsigned int i;
740         int ret;
741
742         for (i = 0; ; ++i) {
743                 memset(&input, 0, sizeof input);
744                 input.index = i;
745                 ret = ioctl(dev->fd, VIDIOC_ENUMINPUT, &input);
746                 if (ret < 0)
747                         break;
748
749                 if (i != input.index)
750                         printf("Warning: driver returned wrong input index "
751                                 "%u.\n", input.index);
752
753                 printf("\tInput %u: %s.\n", i, input.name);
754         }
755
756         printf("\n");
757 }
758
759 static int video_get_input(struct device *dev)
760 {
761         __u32 input;
762         int ret;
763
764         ret = ioctl(dev->fd, VIDIOC_G_INPUT, &input);
765         if (ret < 0) {
766                 printf("Unable to get current input: %s.\n", strerror(errno));
767                 return ret;
768         }
769
770         return input;
771 }
772
773 static int video_set_input(struct device *dev, unsigned int input)
774 {
775         __u32 _input = input;
776         int ret;
777
778         ret = ioctl(dev->fd, VIDIOC_S_INPUT, &_input);
779         if (ret < 0)
780                 printf("Unable to select input %u: %s.\n", input,
781                         strerror(errno));
782
783         return ret;
784 }
785
786 static int video_set_quality(struct device *dev, unsigned int quality)
787 {
788         struct v4l2_jpegcompression jpeg;
789         int ret;
790
791         if (quality == (unsigned int)-1)
792                 return 0;
793
794         memset(&jpeg, 0, sizeof jpeg);
795         jpeg.quality = quality;
796
797         ret = ioctl(dev->fd, VIDIOC_S_JPEGCOMP, &jpeg);
798         if (ret < 0) {
799                 printf("Unable to set quality to %u: %s.\n", quality,
800                         strerror(errno));
801                 return ret;
802         }
803
804         ret = ioctl(dev->fd, VIDIOC_G_JPEGCOMP, &jpeg);
805         if (ret >= 0)
806                 printf("Quality set to %u\n", jpeg.quality);
807
808         return 0;
809 }
810
811 static int video_load_test_pattern(struct device *dev, const char *filename)
812 {
813         unsigned int size = dev->buffers[0].size;
814         unsigned int x, y;
815         uint8_t *data;
816         int ret;
817         int fd;
818
819         /* Load or generate the test pattern */
820         dev->pattern = malloc(size);
821         if (dev->pattern == NULL)
822                 return -ENOMEM;
823
824         if (filename == NULL) {
825                 if (dev->bytesperline == 0) {
826                         printf("Compressed format detect and no test pattern filename given.\n"
827                                 "The test pattern can't be generated automatically.\n");
828                         return -EINVAL;
829                 }
830
831                 data = dev->pattern;
832
833                 for (y = 0; y < dev->height; ++y) {
834                         for (x = 0; x < dev->bytesperline; ++x)
835                                 *data++ = x + y;
836                 }
837
838                 return 0;
839         }
840
841         fd = open(filename, O_RDONLY);
842         if (fd == -1) {
843                 printf("Unable to open test pattern file '%s': %s.\n", filename,
844                         strerror(errno));
845                 return -errno;
846         }
847
848         ret = read(fd, dev->pattern, size);
849         close(fd);
850
851         if (ret != (int)size && dev->bytesperline != 0) {
852                 printf("Test pattern file size %u doesn't match image size %u\n",
853                         ret, size);
854                 return -EINVAL;
855         }
856
857         dev->patternsize = ret;
858         return 0;
859 }
860
861 static int video_prepare_capture(struct device *dev, int nbufs, unsigned int offset,
862                                  const char *filename)
863 {
864         unsigned int i;
865         int ret;
866
867         /* Allocate and map buffers. */
868         if ((ret = video_alloc_buffers(dev, nbufs, offset)) < 0)
869                 return ret;
870
871         if (dev->type == V4L2_BUF_TYPE_VIDEO_OUTPUT) {
872                 ret = video_load_test_pattern(dev, filename);
873                 if (ret < 0)
874                         return ret;
875         }
876
877         /* Queue the buffers. */
878         for (i = 0; i < dev->nbufs; ++i) {
879                 ret = video_queue_buffer(dev, i);
880                 if (ret < 0)
881                         return ret;
882         }
883
884         return 0;
885 }
886
887 static int video_do_capture(struct device *dev, unsigned int nframes,
888         unsigned int skip, unsigned int delay, const char *filename_prefix,
889         int do_requeue_last)
890 {
891         char *filename = NULL;
892         struct timeval start;
893         struct timeval last;
894         struct timeval ts;
895         struct v4l2_buffer buf;
896         unsigned int size;
897         unsigned int i;
898         FILE *file;
899         double bps;
900         double fps;
901         int ret;
902
903         if (filename_prefix != NULL) {
904                 filename = malloc(strlen(filename_prefix) + 12);
905                 if (filename == NULL)
906                         return -ENOMEM;
907         }
908
909         /* Start streaming. */
910         video_enable(dev, 1);
911
912         size = 0;
913         gettimeofday(&start, NULL);
914         last = start;
915
916         for (i = 0; i < nframes; ++i) {
917                 /* Dequeue a buffer. */
918                 memset(&buf, 0, sizeof buf);
919                 buf.type = dev->type;
920                 buf.memory = dev->memtype;
921                 ret = ioctl(dev->fd, VIDIOC_DQBUF, &buf);
922                 if (ret < 0) {
923                         if (errno != EIO) {
924                                 printf("Unable to dequeue buffer (%d).\n", errno);
925                                 goto done;
926                         }
927                         buf.type = dev->type;
928                         buf.memory = dev->memtype;
929                         if (dev->memtype == V4L2_MEMORY_USERPTR)
930                                 buf.m.userptr = (unsigned long)dev->buffers[i].mem;
931                 }
932
933                 if (dev->type == V4L2_BUF_TYPE_VIDEO_CAPTURE &&
934                     dev->imagesize != 0 && buf.bytesused != dev->imagesize)
935                         printf("Warning: bytes used %u != image size %u\n",
936                                buf.bytesused, dev->imagesize);
937
938                 size += buf.bytesused;
939
940                 fps = (buf.timestamp.tv_sec - last.tv_sec) * 1000000
941                     + buf.timestamp.tv_usec - last.tv_usec;
942                 fps = fps ? 1000000.0 / fps : 0.0;
943
944                 gettimeofday(&ts, NULL);
945                 printf("%u (%u) [%c] %u %u bytes %ld.%06ld %ld.%06ld %.3f fps\n", i, buf.index,
946                         (buf.flags & V4L2_BUF_FLAG_ERROR) ? 'E' : '-',
947                         buf.sequence, buf.bytesused, buf.timestamp.tv_sec,
948                         buf.timestamp.tv_usec, ts.tv_sec, ts.tv_usec, fps);
949
950                 last = buf.timestamp;
951
952                 /* Save the image. */
953                 if (dev->type == V4L2_BUF_TYPE_VIDEO_CAPTURE && filename_prefix && !skip) {
954                         sprintf(filename, "%s-%06u.bin", filename_prefix, i);
955                         file = fopen(filename, "wb");
956                         if (file != NULL) {
957                                 ret = fwrite(dev->buffers[buf.index].mem, buf.bytesused, 1, file);
958                                 fclose(file);
959                         }
960                 }
961                 if (skip)
962                         --skip;
963
964                 /* Requeue the buffer. */
965                 if (delay > 0)
966                         usleep(delay * 1000);
967
968                 fflush(stdout);
969
970                 if (i == nframes - dev->nbufs && !do_requeue_last)
971                         continue;
972
973                 ret = video_queue_buffer(dev, buf.index);
974                 if (ret < 0) {
975                         printf("Unable to requeue buffer (%d).\n", errno);
976                         goto done;
977                 }
978         }
979
980         /* Stop streaming. */
981         video_enable(dev, 0);
982
983         if (nframes == 0) {
984                 printf("No frames captured.\n");
985                 goto done;
986         }
987
988         if (ts.tv_sec == start.tv_sec && ts.tv_usec == start.tv_usec)
989                 goto done;
990
991         ts.tv_sec -= start.tv_sec;
992         ts.tv_usec -= start.tv_usec;
993         if (ts.tv_usec < 0) {
994                 ts.tv_sec--;
995                 ts.tv_usec += 1000000;
996         }
997
998         bps = size/(ts.tv_usec+1000000.0*ts.tv_sec)*1000000.0;
999         fps = i/(ts.tv_usec+1000000.0*ts.tv_sec)*1000000.0;
1000
1001         printf("Captured %u frames in %lu.%06lu seconds (%f fps, %f B/s).\n",
1002                 i, ts.tv_sec, ts.tv_usec, fps, bps);
1003
1004 done:
1005         free(filename);
1006         return video_free_buffers(dev);
1007 }
1008
1009 #define V4L_BUFFERS_DEFAULT     8
1010 #define V4L_BUFFERS_MAX         32
1011
1012 static void usage(const char *argv0)
1013 {
1014         printf("Usage: %s [options] device\n", argv0);
1015         printf("Supported options:\n");
1016         printf("-c, --capture[=nframes]         Capture frames\n");
1017         printf("-d, --delay                     Delay (in ms) before requeuing buffers\n");
1018         printf("-f, --format format             Set the video format\n");
1019         printf("-F, --file[=prefix]             Read/write frames from/to disk\n");
1020         printf("-h, --help                      Show this help screen\n");
1021         printf("-i, --input input               Select the video input\n");
1022         printf("-l, --list-controls             List available controls\n");
1023         printf("-n, --nbufs n                   Set the number of video buffers\n");
1024         printf("-p, --pause                     Pause before starting the video stream\n");
1025         printf("-q, --quality n                 MJPEG quality (0-100)\n");
1026         printf("-r, --get-control ctrl          Get control 'ctrl'\n");
1027         printf("-R, --realtime=[priority]       Enable realtime RR scheduling\n");
1028         printf("-s, --size WxH                  Set the frame size\n");
1029         printf("-t, --time-per-frame num/denom  Set the time per frame (eg. 1/25 = 25 fps)\n");
1030         printf("-u, --userptr                   Use the user pointers streaming method\n");
1031         printf("-w, --set-control 'ctrl value'  Set control 'ctrl' to 'value'\n");
1032         printf("    --enum-formats              Enumerate formats\n");
1033         printf("    --enum-inputs               Enumerate inputs\n");
1034         printf("    --no-query                  Don't query capabilities on open\n");
1035         printf("    --offset                    User pointer buffer offset from page start\n");
1036         printf("    --requeue-last              Requeue the last buffers before streamoff\n");
1037         printf("    --skip n                    Skip the first n frames\n");
1038         printf("    --sleep-forever             Sleep forever after configuring the device\n");
1039 }
1040
1041 #define OPT_ENUM_FORMATS        256
1042 #define OPT_ENUM_INPUTS         257
1043 #define OPT_SKIP_FRAMES         258
1044 #define OPT_NO_QUERY            259
1045 #define OPT_SLEEP_FOREVER       260
1046 #define OPT_USERPTR_OFFSET      261
1047 #define OPT_REQUEUE_LAST        262
1048
1049 static struct option opts[] = {
1050         {"capture", 2, 0, 'c'},
1051         {"delay", 1, 0, 'd'},
1052         {"enum-formats", 0, 0, OPT_ENUM_FORMATS},
1053         {"enum-inputs", 0, 0, OPT_ENUM_INPUTS},
1054         {"file", 2, 0, 'F'},
1055         {"format", 1, 0, 'f'},
1056         {"help", 0, 0, 'h'},
1057         {"input", 1, 0, 'i'},
1058         {"list-controls", 0, 0, 'l'},
1059         {"nbufs", 1, 0, 'n'},
1060         {"no-query", 0, 0, OPT_NO_QUERY},
1061         {"offset", 1, 0, OPT_USERPTR_OFFSET},
1062         {"pause", 0, 0, 'p'},
1063         {"quality", 1, 0, 'q'},
1064         {"get-control", 1, 0, 'r'},
1065         {"requeue-last", 0, 0, OPT_REQUEUE_LAST},
1066         {"realtime", 2, 0, 'R'},
1067         {"size", 1, 0, 's'},
1068         {"set-control", 1, 0, 'w'},
1069         {"skip", 1, 0, OPT_SKIP_FRAMES},
1070         {"sleep-forever", 0, 0, OPT_SLEEP_FOREVER},
1071         {"time-per-frame", 1, 0, 't'},
1072         {"userptr", 0, 0, 'u'},
1073         {0, 0, 0, 0}
1074 };
1075
1076 int main(int argc, char *argv[])
1077 {
1078         struct sched_param sched;
1079         struct device dev;
1080         int ret;
1081
1082         /* Options parsings */
1083         int do_file = 0, do_capture = 0, do_pause = 0;
1084         int do_set_time_per_frame = 0;
1085         int do_enum_formats = 0, do_set_format = 0;
1086         int do_enum_inputs = 0, do_set_input = 0;
1087         int do_list_controls = 0, do_get_control = 0, do_set_control = 0;
1088         int do_sleep_forever = 0, do_requeue_last = 0;
1089         int do_rt = 0;
1090         int no_query = 0;
1091         char *endptr;
1092         int c;
1093
1094         /* Controls */
1095         int ctrl_name = 0;
1096         int ctrl_value = 0;
1097
1098         /* Video buffers */
1099         enum v4l2_memory memtype = V4L2_MEMORY_MMAP;
1100         unsigned int pixelformat = V4L2_PIX_FMT_YUYV;
1101         unsigned int width = 640;
1102         unsigned int height = 480;
1103         unsigned int nbufs = V4L_BUFFERS_DEFAULT;
1104         unsigned int input = 0;
1105         unsigned int skip = 0;
1106         unsigned int quality = (unsigned int)-1;
1107         unsigned int userptr_offset = 0;
1108         struct v4l2_fract time_per_frame = {1, 25};
1109
1110         /* Capture loop */
1111         unsigned int delay = 0, nframes = (unsigned int)-1;
1112         const char *filename = "frame";
1113
1114         unsigned int rt_priority = 1;
1115
1116         opterr = 0;
1117         while ((c = getopt_long(argc, argv, "c::d:f:F::hi:ln:pq:r:R::s:t:uw:", opts, NULL)) != -1) {
1118
1119                 switch (c) {
1120                 case 'c':
1121                         do_capture = 1;
1122                         if (optarg)
1123                                 nframes = atoi(optarg);
1124                         break;
1125                 case 'd':
1126                         delay = atoi(optarg);
1127                         break;
1128                 case 'f':
1129                         do_set_format = 1;
1130                         pixelformat = v4l2_format_code(optarg);
1131                         if (pixelformat == 0) {
1132                                 printf("Unsupported video format '%s'\n", optarg);
1133                                 return 1;
1134                         }
1135                         break;
1136                 case 'F':
1137                         do_file = 1;
1138                         if (optarg)
1139                                 filename = optarg;
1140                         break;
1141                 case 'h':
1142                         usage(argv[0]);
1143                         return 0;
1144                 case 'i':
1145                         do_set_input = 1;
1146                         input = atoi(optarg);
1147                         break;
1148                 case 'l':
1149                         do_list_controls = 1;
1150                         break;
1151                 case 'n':
1152                         nbufs = atoi(optarg);
1153                         if (nbufs > V4L_BUFFERS_MAX)
1154                                 nbufs = V4L_BUFFERS_MAX;
1155                         break;
1156                 case 'p':
1157                         do_pause = 1;
1158                         break;
1159                 case 'q':
1160                         quality = atoi(optarg);
1161                         break;
1162                 case 'r':
1163                         ctrl_name = strtol(optarg, &endptr, 0);
1164                         if (*endptr != 0) {
1165                                 printf("Invalid control name '%s'\n", optarg);
1166                                 return 1;
1167                         }
1168                         do_get_control = 1;
1169                         break;
1170                 case 'R':
1171                         do_rt = 1;
1172                         if (optarg)
1173                                 rt_priority = atoi(optarg);
1174                         break;
1175                 case 's':
1176                         do_set_format = 1;
1177                         width = strtol(optarg, &endptr, 10);
1178                         if (*endptr != 'x' || endptr == optarg) {
1179                                 printf("Invalid size '%s'\n", optarg);
1180                                 return 1;
1181                         }
1182                         height = strtol(endptr + 1, &endptr, 10);
1183                         if (*endptr != 0) {
1184                                 printf("Invalid size '%s'\n", optarg);
1185                                 return 1;
1186                         }
1187                         break;
1188                 case 't':
1189                         do_set_time_per_frame = 1;
1190                         time_per_frame.numerator = strtol(optarg, &endptr, 10);
1191                         if (*endptr != '/' || endptr == optarg) {
1192                                 printf("Invalid time per frame '%s'\n", optarg);
1193                                 return 1;
1194                         }
1195                         time_per_frame.denominator = strtol(endptr + 1, &endptr, 10);
1196                         if (*endptr != 0) {
1197                                 printf("Invalid time per frame '%s'\n", optarg);
1198                                 return 1;
1199                         }
1200                         break;
1201                 case 'u':
1202                         memtype = V4L2_MEMORY_USERPTR;
1203                         break;
1204                 case 'w':
1205                         ctrl_name = strtol(optarg, &endptr, 0);
1206                         if (*endptr != ' ' || endptr == optarg) {
1207                                 printf("Invalid control name '%s'\n", optarg);
1208                                 return 1;
1209                         }
1210                         ctrl_value = strtol(endptr + 1, &endptr, 0);
1211                         if (*endptr != 0) {
1212                                 printf("Invalid control value '%s'\n", optarg);
1213                                 return 1;
1214                         }
1215                         do_set_control = 1;
1216                         break;
1217                 case OPT_ENUM_FORMATS:
1218                         do_enum_formats = 1;
1219                         break;
1220                 case OPT_ENUM_INPUTS:
1221                         do_enum_inputs = 1;
1222                         break;
1223                 case OPT_NO_QUERY:
1224                         no_query = 1;
1225                         break;
1226                 case OPT_REQUEUE_LAST:
1227                         do_requeue_last = 1;
1228                         break;
1229                 case OPT_SKIP_FRAMES:
1230                         skip = atoi(optarg);
1231                         break;
1232                 case OPT_SLEEP_FOREVER:
1233                         do_sleep_forever = 1;
1234                         break;
1235                 case OPT_USERPTR_OFFSET:
1236                         userptr_offset = atoi(optarg);
1237                         break;
1238                 default:
1239                         printf("Invalid option -%c\n", c);
1240                         printf("Run %s -h for help.\n", argv[0]);
1241                         return 1;
1242                 }
1243         }
1244
1245         if (optind >= argc) {
1246                 usage(argv[0]);
1247                 return 1;
1248         }
1249
1250         if (!do_file)
1251                 filename = NULL;
1252
1253         /* Open the video device. If the device type isn't recognized, set the
1254          * --no-query option to avoid querying V4L2 subdevs.
1255          */
1256         ret = video_open(&dev, argv[optind], no_query);
1257         if (ret < 0)
1258                 return 1;
1259
1260         if (dev.type == (enum v4l2_buf_type)-1)
1261                 no_query = 1;
1262
1263         dev.memtype = memtype;
1264
1265         if (do_get_control)
1266                 uvc_get_control(&dev, ctrl_name);
1267         if (do_set_control)
1268                 uvc_set_control(&dev, ctrl_name, ctrl_value);
1269
1270         if (do_list_controls)
1271                 video_list_controls(&dev);
1272
1273         if (do_enum_formats) {
1274                 printf("- Available formats:\n");
1275                 video_enum_formats(&dev, V4L2_BUF_TYPE_VIDEO_CAPTURE);
1276                 video_enum_formats(&dev, V4L2_BUF_TYPE_VIDEO_OUTPUT);
1277                 video_enum_formats(&dev, V4L2_BUF_TYPE_VIDEO_OVERLAY);
1278         }
1279
1280         if (do_enum_inputs) {
1281                 printf("- Available inputs:\n");
1282                 video_enum_inputs(&dev);
1283         }
1284
1285         if (do_set_input) {
1286                 video_set_input(&dev, input);
1287                 ret = video_get_input(&dev);
1288                 printf("Input %d selected\n", ret);
1289         }
1290
1291         /* Set the video format. */
1292         if (do_set_format) {
1293                 if (video_set_format(&dev, width, height, pixelformat) < 0) {
1294                         video_close(&dev);
1295                         return 1;
1296                 }
1297         }
1298
1299         if (!no_query || do_capture)
1300                 video_get_format(&dev);
1301
1302         /* Set the frame rate. */
1303         if (do_set_time_per_frame) {
1304                 if (video_set_framerate(&dev, &time_per_frame) < 0) {
1305                         video_close(&dev);
1306                         return 1;
1307                 }
1308         }
1309
1310         while (do_sleep_forever)
1311                 sleep(1000);
1312
1313         if (!do_capture) {
1314                 video_close(&dev);
1315                 return 0;
1316         }
1317
1318         /* Set the compression quality. */
1319         if (video_set_quality(&dev, quality) < 0) {
1320                 video_close(&dev);
1321                 return 1;
1322         }
1323
1324         if (video_prepare_capture(&dev, nbufs, userptr_offset, filename)) {
1325                 video_close(&dev);
1326                 return 1;
1327         }
1328
1329         if (do_pause) {
1330                 printf("Press enter to start capture\n");
1331                 getchar();
1332         }
1333
1334         if (do_rt) {
1335                 memset(&sched, 0, sizeof sched);
1336                 sched.sched_priority = rt_priority;
1337                 ret = sched_setscheduler(0, SCHED_RR, &sched);
1338                 if (ret < 0)
1339                         printf("Failed to select RR scheduler (%d)\n", errno);
1340         }
1341
1342         if (video_do_capture(&dev, nframes, skip, delay, filename, do_requeue_last) < 0) {
1343                 video_close(&dev);
1344                 return 1;
1345         }
1346
1347         video_close(&dev);
1348         return 0;
1349 }
1350