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