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