uvc-gadget: Use V4L2 helper functions
[uvc-gadget.git] / uvc-gadget.c
1 /*
2  * UVC gadget test application
3  *
4  * Copyright (C) 2010 Ideas on board SPRL <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 <sys/time.h>
21 #include <sys/ioctl.h>
22 #include <sys/mman.h>
23 #include <sys/types.h>
24 #include <sys/stat.h>
25 #include <sys/select.h>
26
27 #include <unistd.h>
28 #include <fcntl.h>
29 #include <signal.h>
30 #include <stdlib.h>
31 #include <stdio.h>
32 #include <stdint.h>
33 #include <string.h>
34 #include <errno.h>
35
36 #include <linux/usb/ch9.h>
37 #include <linux/usb/g_uvc.h>
38 #include <linux/usb/video.h>
39 #include <linux/videodev2.h>
40
41 #include "events.h"
42 #include "v4l2.h"
43 #include "tools.h"
44
45 #define UVC_INTF_CONTROL        0
46 #define UVC_INTF_STREAMING      1
47
48 struct uvc_device
49 {
50         struct v4l2_device *vdev;
51
52         struct uvc_streaming_control probe;
53         struct uvc_streaming_control commit;
54
55         int control;
56
57         unsigned int fcc;
58         unsigned int width;
59         unsigned int height;
60
61         unsigned int bulk;
62         uint8_t color;
63         unsigned int imgsize;
64         void *imgdata;
65
66         struct events events;
67 };
68
69 static struct uvc_device *
70 uvc_open(const char *devname)
71 {
72         struct uvc_device *dev;
73
74         dev = malloc(sizeof *dev);
75         if (dev == NULL)
76                 return NULL;
77
78         memset(dev, 0, sizeof *dev);
79
80         dev->vdev = v4l2_open(devname);
81         if (dev->vdev == NULL) {
82                 free(dev);
83                 return NULL;
84         }
85
86         events_init(&dev->events);
87
88         return dev;
89 }
90
91 static void
92 uvc_close(struct uvc_device *dev)
93 {
94         v4l2_close(dev->vdev);
95         dev->vdev = NULL;
96
97         free(dev->imgdata);
98         free(dev);
99 }
100
101 /* ---------------------------------------------------------------------------
102  * Video streaming
103  */
104
105 static void
106 uvc_video_fill_buffer(struct uvc_device *dev, struct v4l2_video_buffer *buf)
107 {
108         unsigned int bpl;
109         unsigned int i;
110
111         switch (dev->fcc) {
112         case V4L2_PIX_FMT_YUYV:
113                 /* Fill the buffer with video data. */
114                 bpl = dev->width * 2;
115                 for (i = 0; i < dev->height; ++i)
116                         memset(buf->mem + i*bpl, dev->color++, bpl);
117
118                 buf->bytesused = bpl * dev->height;
119                 break;
120
121         case V4L2_PIX_FMT_MJPEG:
122                 memcpy(buf->mem, dev->imgdata, dev->imgsize);
123                 buf->bytesused = dev->imgsize;
124                 break;
125         }
126 }
127
128 static void
129 uvc_video_process(void *d)
130 {
131         struct uvc_device *dev = d;
132         struct v4l2_video_buffer buf;
133         int ret;
134
135         ret = v4l2_dequeue_buffer(dev->vdev, &buf);
136         if (ret < 0)
137                 return;
138
139         uvc_video_fill_buffer(dev, &buf);
140
141         v4l2_queue_buffer(dev->vdev, &buf);
142 }
143
144 static int
145 uvc_video_stream(struct uvc_device *dev, int enable)
146 {
147         unsigned int i;
148         int ret;
149
150         if (!enable) {
151                 printf("Stopping video stream.\n");
152                 events_unwatch_fd(&dev->events, dev->vdev->fd, EVENT_WRITE);
153                 v4l2_stream_off(dev->vdev);
154                 v4l2_free_buffers(dev->vdev);
155                 return 0;
156         }
157
158         printf("Starting video stream.\n");
159
160         ret = v4l2_alloc_buffers(dev->vdev, V4L2_MEMORY_MMAP, 4);
161         if (ret < 0) {
162                 printf("Failed to allocate buffers.\n");
163                 return ret;
164         }
165
166         for (i = 0; i < dev->vdev->nbufs; ++i) {
167                 struct v4l2_video_buffer *buf = &dev->vdev->buffers[i];
168
169                 uvc_video_fill_buffer(dev, buf);
170
171                 ret = v4l2_queue_buffer(dev->vdev, buf);
172                 if (ret < 0)
173                         return ret;
174         }
175
176         v4l2_stream_on(dev->vdev);
177         events_watch_fd(&dev->events, dev->vdev->fd, EVENT_WRITE,
178                         uvc_video_process, dev);
179
180         return ret;
181 }
182
183 static int
184 uvc_video_set_format(struct uvc_device *dev)
185 {
186         struct v4l2_pix_format fmt;
187
188         printf("Setting format to 0x%08x %ux%u\n",
189                 dev->fcc, dev->width, dev->height);
190
191         memset(&fmt, 0, sizeof fmt);
192         fmt.width = dev->width;
193         fmt.height = dev->height;
194         fmt.pixelformat = dev->fcc;
195         fmt.field = V4L2_FIELD_NONE;
196         if (dev->fcc == V4L2_PIX_FMT_MJPEG)
197                 fmt.sizeimage = dev->imgsize * 1.5;
198
199         return v4l2_set_format(dev->vdev, &fmt);
200 }
201
202 static int
203 uvc_video_init(struct uvc_device *dev __attribute__((__unused__)))
204 {
205         return 0;
206 }
207
208 /* ---------------------------------------------------------------------------
209  * Request processing
210  */
211
212 struct uvc_frame_info
213 {
214         unsigned int width;
215         unsigned int height;
216         unsigned int intervals[8];
217 };
218
219 struct uvc_format_info
220 {
221         unsigned int fcc;
222         const struct uvc_frame_info *frames;
223 };
224
225 static const struct uvc_frame_info uvc_frames_yuyv[] = {
226         {  640, 360, { 666666, 10000000, 50000000, 0 }, },
227         { 1280, 720, { 50000000, 0 }, },
228         { 0, 0, { 0, }, },
229 };
230
231 static const struct uvc_frame_info uvc_frames_mjpeg[] = {
232         {  640, 360, { 666666, 10000000, 50000000, 0 }, },
233         { 1280, 720, { 50000000, 0 }, },
234         { 0, 0, { 0, }, },
235 };
236
237 static const struct uvc_format_info uvc_formats[] = {
238         { V4L2_PIX_FMT_YUYV, uvc_frames_yuyv },
239         { V4L2_PIX_FMT_MJPEG, uvc_frames_mjpeg },
240 };
241
242 static void
243 uvc_fill_streaming_control(struct uvc_device *dev,
244                            struct uvc_streaming_control *ctrl,
245                            int iframe, int iformat)
246 {
247         const struct uvc_format_info *format;
248         const struct uvc_frame_info *frame;
249         unsigned int nframes;
250
251         if (iformat < 0)
252                 iformat = ARRAY_SIZE(uvc_formats) + iformat;
253         if (iformat < 0 || iformat >= (int)ARRAY_SIZE(uvc_formats))
254                 return;
255         format = &uvc_formats[iformat];
256
257         nframes = 0;
258         while (format->frames[nframes].width != 0)
259                 ++nframes;
260
261         if (iframe < 0)
262                 iframe = nframes + iframe;
263         if (iframe < 0 || iframe >= (int)nframes)
264                 return;
265         frame = &format->frames[iframe];
266
267         memset(ctrl, 0, sizeof *ctrl);
268
269         ctrl->bmHint = 1;
270         ctrl->bFormatIndex = iformat + 1;
271         ctrl->bFrameIndex = iframe + 1;
272         ctrl->dwFrameInterval = frame->intervals[0];
273         switch (format->fcc) {
274         case V4L2_PIX_FMT_YUYV:
275                 ctrl->dwMaxVideoFrameSize = frame->width * frame->height * 2;
276                 break;
277         case V4L2_PIX_FMT_MJPEG:
278                 ctrl->dwMaxVideoFrameSize = dev->imgsize;
279                 break;
280         }
281         ctrl->dwMaxPayloadTransferSize = 512;   /* TODO this should be filled by the driver. */
282         ctrl->bmFramingInfo = 3;
283         ctrl->bPreferedVersion = 1;
284         ctrl->bMaxVersion = 1;
285 }
286
287 static void
288 uvc_events_process_standard(struct uvc_device *dev, struct usb_ctrlrequest *ctrl,
289                             struct uvc_request_data *resp)
290 {
291         printf("standard request\n");
292         (void)dev;
293         (void)ctrl;
294         (void)resp;
295 }
296
297 static void
298 uvc_events_process_control(struct uvc_device *dev, uint8_t req, uint8_t cs,
299                            struct uvc_request_data *resp)
300 {
301         printf("control request (req %02x cs %02x)\n", req, cs);
302         (void)dev;
303         (void)resp;
304 }
305
306 static void
307 uvc_events_process_streaming(struct uvc_device *dev, uint8_t req, uint8_t cs,
308                              struct uvc_request_data *resp)
309 {
310         struct uvc_streaming_control *ctrl;
311
312         printf("streaming request (req %02x cs %02x)\n", req, cs);
313
314         if (cs != UVC_VS_PROBE_CONTROL && cs != UVC_VS_COMMIT_CONTROL)
315                 return;
316
317         ctrl = (struct uvc_streaming_control *)&resp->data;
318         resp->length = sizeof *ctrl;
319
320         switch (req) {
321         case UVC_SET_CUR:
322                 dev->control = cs;
323                 resp->length = 34;
324                 break;
325
326         case UVC_GET_CUR:
327                 if (cs == UVC_VS_PROBE_CONTROL)
328                         memcpy(ctrl, &dev->probe, sizeof *ctrl);
329                 else
330                         memcpy(ctrl, &dev->commit, sizeof *ctrl);
331                 break;
332
333         case UVC_GET_MIN:
334         case UVC_GET_MAX:
335         case UVC_GET_DEF:
336                 uvc_fill_streaming_control(dev, ctrl, req == UVC_GET_MAX ? -1 : 0,
337                                            req == UVC_GET_MAX ? -1 : 0);
338                 break;
339
340         case UVC_GET_RES:
341                 memset(ctrl, 0, sizeof *ctrl);
342                 break;
343
344         case UVC_GET_LEN:
345                 resp->data[0] = 0x00;
346                 resp->data[1] = 0x22;
347                 resp->length = 2;
348                 break;
349
350         case UVC_GET_INFO:
351                 resp->data[0] = 0x03;
352                 resp->length = 1;
353                 break;
354         }
355 }
356
357 static void
358 uvc_events_process_class(struct uvc_device *dev, struct usb_ctrlrequest *ctrl,
359                          struct uvc_request_data *resp)
360 {
361         if ((ctrl->bRequestType & USB_RECIP_MASK) != USB_RECIP_INTERFACE)
362                 return;
363
364         switch (ctrl->wIndex & 0xff) {
365         case UVC_INTF_CONTROL:
366                 uvc_events_process_control(dev, ctrl->bRequest, ctrl->wValue >> 8, resp);
367                 break;
368
369         case UVC_INTF_STREAMING:
370                 uvc_events_process_streaming(dev, ctrl->bRequest, ctrl->wValue >> 8, resp);
371                 break;
372
373         default:
374                 break;
375         }
376 }
377
378 static void
379 uvc_events_process_setup(struct uvc_device *dev, struct usb_ctrlrequest *ctrl,
380                          struct uvc_request_data *resp)
381 {
382         dev->control = 0;
383
384         printf("bRequestType %02x bRequest %02x wValue %04x wIndex %04x "
385                 "wLength %04x\n", ctrl->bRequestType, ctrl->bRequest,
386                 ctrl->wValue, ctrl->wIndex, ctrl->wLength);
387
388         switch (ctrl->bRequestType & USB_TYPE_MASK) {
389         case USB_TYPE_STANDARD:
390                 uvc_events_process_standard(dev, ctrl, resp);
391                 break;
392
393         case USB_TYPE_CLASS:
394                 uvc_events_process_class(dev, ctrl, resp);
395                 break;
396
397         default:
398                 break;
399         }
400 }
401
402 static void
403 uvc_events_process_data(struct uvc_device *dev, struct uvc_request_data *data)
404 {
405         struct uvc_streaming_control *target;
406         struct uvc_streaming_control *ctrl;
407         const struct uvc_format_info *format;
408         const struct uvc_frame_info *frame;
409         const unsigned int *interval;
410         unsigned int iformat, iframe;
411         unsigned int nframes;
412
413         switch (dev->control) {
414         case UVC_VS_PROBE_CONTROL:
415                 printf("setting probe control, length = %d\n", data->length);
416                 target = &dev->probe;
417                 break;
418
419         case UVC_VS_COMMIT_CONTROL:
420                 printf("setting commit control, length = %d\n", data->length);
421                 target = &dev->commit;
422                 break;
423
424         default:
425                 printf("setting unknown control, length = %d\n", data->length);
426                 return;
427         }
428
429         ctrl = (struct uvc_streaming_control *)&data->data;
430         iformat = clamp((unsigned int)ctrl->bFormatIndex, 1U,
431                         (unsigned int)ARRAY_SIZE(uvc_formats));
432         format = &uvc_formats[iformat-1];
433
434         nframes = 0;
435         while (format->frames[nframes].width != 0)
436                 ++nframes;
437
438         iframe = clamp((unsigned int)ctrl->bFrameIndex, 1U, nframes);
439         frame = &format->frames[iframe-1];
440         interval = frame->intervals;
441
442         while (interval[0] < ctrl->dwFrameInterval && interval[1])
443                 ++interval;
444
445         target->bFormatIndex = iformat;
446         target->bFrameIndex = iframe;
447         switch (format->fcc) {
448         case V4L2_PIX_FMT_YUYV:
449                 target->dwMaxVideoFrameSize = frame->width * frame->height * 2;
450                 break;
451         case V4L2_PIX_FMT_MJPEG:
452                 if (dev->imgsize == 0)
453                         printf("WARNING: MJPEG requested and no image loaded.\n");
454                 target->dwMaxVideoFrameSize = dev->imgsize;
455                 break;
456         }
457         target->dwFrameInterval = *interval;
458
459         if (dev->control == UVC_VS_COMMIT_CONTROL) {
460                 dev->fcc = format->fcc;
461                 dev->width = frame->width;
462                 dev->height = frame->height;
463
464                 uvc_video_set_format(dev);
465                 if (dev->bulk)
466                         uvc_video_stream(dev, 1);
467         }
468 }
469
470 static void
471 uvc_events_process(void *d)
472 {
473         struct uvc_device *dev = d;
474         struct v4l2_event v4l2_event;
475         struct uvc_event *uvc_event = (void *)&v4l2_event.u.data;
476         struct uvc_request_data resp;
477         int ret;
478
479         ret = ioctl(dev->vdev->fd, VIDIOC_DQEVENT, &v4l2_event);
480         if (ret < 0) {
481                 printf("VIDIOC_DQEVENT failed: %s (%d)\n", strerror(errno),
482                         errno);
483                 return;
484         }
485
486         memset(&resp, 0, sizeof resp);
487         resp.length = -EL2HLT;
488
489         switch (v4l2_event.type) {
490         case UVC_EVENT_CONNECT:
491         case UVC_EVENT_DISCONNECT:
492                 return;
493
494         case UVC_EVENT_SETUP:
495                 uvc_events_process_setup(dev, &uvc_event->req, &resp);
496                 break;
497
498         case UVC_EVENT_DATA:
499                 uvc_events_process_data(dev, &uvc_event->data);
500                 return;
501
502         case UVC_EVENT_STREAMON:
503                 uvc_video_stream(dev, 1);
504                 return;
505
506         case UVC_EVENT_STREAMOFF:
507                 uvc_video_stream(dev, 0);
508                 return;
509         }
510
511         ioctl(dev->vdev->fd, UVCIOC_SEND_RESPONSE, &resp);
512         if (ret < 0) {
513                 printf("UVCIOC_S_EVENT failed: %s (%d)\n", strerror(errno),
514                         errno);
515                 return;
516         }
517 }
518
519 static void
520 uvc_events_init(struct uvc_device *dev)
521 {
522         struct v4l2_event_subscription sub;
523
524         uvc_fill_streaming_control(dev, &dev->probe, 0, 0);
525         uvc_fill_streaming_control(dev, &dev->commit, 0, 0);
526
527         if (dev->bulk) {
528                 /* FIXME Crude hack, must be negotiated with the driver. */
529                 dev->probe.dwMaxPayloadTransferSize = 16 * 1024;
530                 dev->commit.dwMaxPayloadTransferSize = 16 * 1024;
531         }
532
533
534         memset(&sub, 0, sizeof sub);
535         sub.type = UVC_EVENT_SETUP;
536         ioctl(dev->vdev->fd, VIDIOC_SUBSCRIBE_EVENT, &sub);
537         sub.type = UVC_EVENT_DATA;
538         ioctl(dev->vdev->fd, VIDIOC_SUBSCRIBE_EVENT, &sub);
539         sub.type = UVC_EVENT_STREAMON;
540         ioctl(dev->vdev->fd, VIDIOC_SUBSCRIBE_EVENT, &sub);
541         sub.type = UVC_EVENT_STREAMOFF;
542         ioctl(dev->vdev->fd, VIDIOC_SUBSCRIBE_EVENT, &sub);
543 }
544
545 /* ---------------------------------------------------------------------------
546  * main
547  */
548
549 static void image_load(struct uvc_device *dev, const char *img)
550 {
551         int fd = -1;
552
553         if (img == NULL)
554                 return;
555
556         fd = open(img, O_RDONLY);
557         if (fd == -1) {
558                 printf("Unable to open MJPEG image '%s'\n", img);
559                 return;
560         }
561
562         dev->imgsize = lseek(fd, 0, SEEK_END);
563         lseek(fd, 0, SEEK_SET);
564         dev->imgdata = malloc(dev->imgsize);
565         if (dev->imgdata == NULL) {
566                 printf("Unable to allocate memory for MJPEG image\n");
567                 dev->imgsize = 0;
568                 return;
569         }
570
571         read(fd, dev->imgdata, dev->imgsize);
572         close(fd);
573 }
574
575 static void usage(const char *argv0)
576 {
577         fprintf(stderr, "Usage: %s [options]\n", argv0);
578         fprintf(stderr, "Available options are\n");
579         fprintf(stderr, " -b            Use bulk mode\n");
580         fprintf(stderr, " -d device     Video device\n");
581         fprintf(stderr, " -h            Print this help screen and exit\n");
582         fprintf(stderr, " -i image      MJPEG image\n");
583 }
584
585 /* Necesssary for and only used by signal handler. */
586 static struct uvc_device *uvc_device;
587
588 static void sigint_handler(int signal __attribute__((__unused__)))
589 {
590         /* Stop the main loop when the user presses CTRL-C */
591         events_stop(&uvc_device->events);
592 }
593
594 int main(int argc, char *argv[])
595 {
596         char *device = "/dev/video0";
597         struct uvc_device *dev;
598         int bulk_mode = 0;
599         char *mjpeg_image = NULL;
600         int opt;
601
602         while ((opt = getopt(argc, argv, "bd:hi:")) != -1) {
603                 switch (opt) {
604                 case 'b':
605                         bulk_mode = 1;
606                         break;
607
608                 case 'd':
609                         device = optarg;
610                         break;
611
612                 case 'h':
613                         usage(argv[0]);
614                         return 0;
615
616                 case 'i':
617                         mjpeg_image = optarg;
618                         break;
619
620                 default:
621                         fprintf(stderr, "Invalid option '-%c'\n", opt);
622                         usage(argv[0]);
623                         return 1;
624                 }
625         }
626
627         dev = uvc_open(device);
628         if (dev == NULL)
629                 return 1;
630
631         image_load(dev, mjpeg_image);
632
633         dev->bulk = bulk_mode;
634
635         uvc_events_init(dev);
636         uvc_video_init(dev);
637
638         /*
639          * Register a signal handler for SIGINT, received when the user presses
640          * CTRL-C. This will allow the main loop to be interrupted, and resources
641          * to be freed cleanly.
642          */
643         uvc_device = dev;
644         signal(SIGINT, sigint_handler);
645
646         events_watch_fd(&dev->events, dev->vdev->fd, EVENT_EXCEPTION,
647                         uvc_events_process, dev);
648
649         /* Main capture loop */
650         events_loop(&dev->events);
651
652         events_cleanup(&dev->events);
653         uvc_close(dev);
654         return 0;
655 }