uvc-gadget: Don't hardcode formats and frame sizes
[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 "configfs.h"
42 #include "events.h"
43 #include "tools.h"
44 #include "v4l2.h"
45
46 struct uvc_device
47 {
48         struct v4l2_device *vdev;
49
50         struct uvc_function_config *fc;
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 static void
255 uvc_fill_streaming_control(struct uvc_device *dev,
256                            struct uvc_streaming_control *ctrl,
257                            int iformat, int iframe, unsigned int ival)
258 {
259         const struct uvc_function_config_format *format;
260         const struct uvc_function_config_frame *frame;
261         unsigned int i;
262
263         /*
264          * Restrict the iformat, iframe and ival to valid values. Negative
265          * values for iformat or iframe will result in the maximum valid value
266          * being selected.
267          */
268         iformat = clamp((unsigned int)iformat, 1U,
269                         dev->fc->streaming.num_formats);
270         format = &dev->fc->streaming.formats[iformat-1];
271
272         iframe = clamp((unsigned int)iframe, 1U, format->num_frames);
273         frame = &format->frames[iframe-1];
274
275         for (i = 0; i < frame->num_intervals; ++i) {
276                 if (ival <= frame->intervals[i]) {
277                         ival = frame->intervals[i];
278                         break;
279                 }
280         }
281
282         if (i == frame->num_intervals)
283                 ival = frame->intervals[frame->num_intervals-1];
284
285         memset(ctrl, 0, sizeof *ctrl);
286
287         ctrl->bmHint = 1;
288         ctrl->bFormatIndex = iformat;
289         ctrl->bFrameIndex = iframe ;
290         ctrl->dwFrameInterval = ival;
291
292         switch (format->fcc) {
293         case V4L2_PIX_FMT_YUYV:
294                 ctrl->dwMaxVideoFrameSize = frame->width * frame->height * 2;
295                 break;
296         case V4L2_PIX_FMT_MJPEG:
297                 ctrl->dwMaxVideoFrameSize = dev->maxsize;
298                 break;
299         }
300
301         ctrl->dwMaxPayloadTransferSize = 512;   /* TODO this should be filled by the driver. */
302         ctrl->bmFramingInfo = 3;
303         ctrl->bPreferedVersion = 1;
304         ctrl->bMaxVersion = 1;
305 }
306
307 static void
308 uvc_events_process_standard(struct uvc_device *dev,
309                             const struct usb_ctrlrequest *ctrl,
310                             struct uvc_request_data *resp)
311 {
312         printf("standard request\n");
313         (void)dev;
314         (void)ctrl;
315         (void)resp;
316 }
317
318 static void
319 uvc_events_process_control(struct uvc_device *dev, uint8_t req, uint8_t cs,
320                            struct uvc_request_data *resp)
321 {
322         printf("control request (req %02x cs %02x)\n", req, cs);
323         (void)dev;
324         (void)resp;
325 }
326
327 static void
328 uvc_events_process_streaming(struct uvc_device *dev, uint8_t req, uint8_t cs,
329                              struct uvc_request_data *resp)
330 {
331         struct uvc_streaming_control *ctrl;
332
333         printf("streaming request (req %02x cs %02x)\n", req, cs);
334
335         if (cs != UVC_VS_PROBE_CONTROL && cs != UVC_VS_COMMIT_CONTROL)
336                 return;
337
338         ctrl = (struct uvc_streaming_control *)&resp->data;
339         resp->length = sizeof *ctrl;
340
341         switch (req) {
342         case UVC_SET_CUR:
343                 dev->control = cs;
344                 resp->length = 34;
345                 break;
346
347         case UVC_GET_CUR:
348                 if (cs == UVC_VS_PROBE_CONTROL)
349                         memcpy(ctrl, &dev->probe, sizeof *ctrl);
350                 else
351                         memcpy(ctrl, &dev->commit, sizeof *ctrl);
352                 break;
353
354         case UVC_GET_MIN:
355         case UVC_GET_MAX:
356         case UVC_GET_DEF:
357                 uvc_fill_streaming_control(dev, ctrl, req == UVC_GET_MAX ? -1 : 1,
358                                            req == UVC_GET_MAX ? -1 : 1, 0);
359                 break;
360
361         case UVC_GET_RES:
362                 memset(ctrl, 0, sizeof *ctrl);
363                 break;
364
365         case UVC_GET_LEN:
366                 resp->data[0] = 0x00;
367                 resp->data[1] = 0x22;
368                 resp->length = 2;
369                 break;
370
371         case UVC_GET_INFO:
372                 resp->data[0] = 0x03;
373                 resp->length = 1;
374                 break;
375         }
376 }
377
378 static void
379 uvc_events_process_class(struct uvc_device *dev,
380                          const struct usb_ctrlrequest *ctrl,
381                          struct uvc_request_data *resp)
382 {
383         unsigned int interface = ctrl->wIndex & 0xff;
384
385         if ((ctrl->bRequestType & USB_RECIP_MASK) != USB_RECIP_INTERFACE)
386                 return;
387
388         if (interface == dev->fc->control.intf.bInterfaceNumber)
389                 uvc_events_process_control(dev, ctrl->bRequest, ctrl->wValue >> 8, resp);
390         else if (interface == dev->fc->streaming.intf.bInterfaceNumber)
391                 uvc_events_process_streaming(dev, ctrl->bRequest, ctrl->wValue >> 8, resp);
392 }
393
394 static void
395 uvc_events_process_setup(struct uvc_device *dev,
396                          const struct usb_ctrlrequest *ctrl,
397                          struct uvc_request_data *resp)
398 {
399         dev->control = 0;
400
401         printf("bRequestType %02x bRequest %02x wValue %04x wIndex %04x "
402                 "wLength %04x\n", ctrl->bRequestType, ctrl->bRequest,
403                 ctrl->wValue, ctrl->wIndex, ctrl->wLength);
404
405         switch (ctrl->bRequestType & USB_TYPE_MASK) {
406         case USB_TYPE_STANDARD:
407                 uvc_events_process_standard(dev, ctrl, resp);
408                 break;
409
410         case USB_TYPE_CLASS:
411                 uvc_events_process_class(dev, ctrl, resp);
412                 break;
413
414         default:
415                 break;
416         }
417 }
418
419 static void
420 uvc_events_process_data(struct uvc_stream *stream,
421                         const struct uvc_request_data *data)
422 {
423         struct uvc_device *dev = stream->uvc;
424         const struct uvc_streaming_control *ctrl =
425                 (const struct uvc_streaming_control *)&data->data;
426         struct uvc_streaming_control *target;
427
428         switch (dev->control) {
429         case UVC_VS_PROBE_CONTROL:
430                 printf("setting probe control, length = %d\n", data->length);
431                 target = &dev->probe;
432                 break;
433
434         case UVC_VS_COMMIT_CONTROL:
435                 printf("setting commit control, length = %d\n", data->length);
436                 target = &dev->commit;
437                 break;
438
439         default:
440                 printf("setting unknown control, length = %d\n", data->length);
441                 return;
442         }
443
444         uvc_fill_streaming_control(dev, target, ctrl->bFormatIndex,
445                                    ctrl->bFrameIndex, ctrl->dwFrameInterval);
446
447         if (dev->control == UVC_VS_COMMIT_CONTROL) {
448                 const struct uvc_function_config_format *format;
449                 const struct uvc_function_config_frame *frame;
450
451                 format = &dev->fc->streaming.formats[target->bFormatIndex-1];
452                 frame = &format->frames[target->bFrameIndex-1];
453
454                 dev->fcc = format->fcc;
455                 dev->width = frame->width;
456                 dev->height = frame->height;
457
458                 uvc_video_set_format(stream);
459         }
460 }
461
462 static void
463 uvc_events_process(void *d)
464 {
465         struct uvc_stream *stream = d;
466         struct uvc_device *dev = stream->uvc;
467         struct v4l2_event v4l2_event;
468         const struct uvc_event *uvc_event = (void *)&v4l2_event.u.data;
469         struct uvc_request_data resp;
470         int ret;
471
472         ret = ioctl(dev->vdev->fd, VIDIOC_DQEVENT, &v4l2_event);
473         if (ret < 0) {
474                 printf("VIDIOC_DQEVENT failed: %s (%d)\n", strerror(errno),
475                         errno);
476                 return;
477         }
478
479         memset(&resp, 0, sizeof resp);
480         resp.length = -EL2HLT;
481
482         switch (v4l2_event.type) {
483         case UVC_EVENT_CONNECT:
484         case UVC_EVENT_DISCONNECT:
485                 return;
486
487         case UVC_EVENT_SETUP:
488                 uvc_events_process_setup(dev, &uvc_event->req, &resp);
489                 break;
490
491         case UVC_EVENT_DATA:
492                 uvc_events_process_data(stream, &uvc_event->data);
493                 return;
494
495         case UVC_EVENT_STREAMON:
496                 capture_video_stream(stream, 1);
497                 uvc_video_stream(stream, 1);
498                 return;
499
500         case UVC_EVENT_STREAMOFF:
501                 uvc_video_stream(stream, 0);
502                 capture_video_stream(stream, 0);
503                 return;
504         }
505
506         ioctl(dev->vdev->fd, UVCIOC_SEND_RESPONSE, &resp);
507         if (ret < 0) {
508                 printf("UVCIOC_S_EVENT failed: %s (%d)\n", strerror(errno),
509                         errno);
510                 return;
511         }
512 }
513
514 static void
515 uvc_events_init(struct uvc_device *dev)
516 {
517         struct v4l2_event_subscription sub;
518
519         /* Default to the minimum values. */
520         uvc_fill_streaming_control(dev, &dev->probe, 1, 1, 0);
521         uvc_fill_streaming_control(dev, &dev->commit, 1, 1, 0);
522
523         memset(&sub, 0, sizeof sub);
524         sub.type = UVC_EVENT_SETUP;
525         ioctl(dev->vdev->fd, VIDIOC_SUBSCRIBE_EVENT, &sub);
526         sub.type = UVC_EVENT_DATA;
527         ioctl(dev->vdev->fd, VIDIOC_SUBSCRIBE_EVENT, &sub);
528         sub.type = UVC_EVENT_STREAMON;
529         ioctl(dev->vdev->fd, VIDIOC_SUBSCRIBE_EVENT, &sub);
530         sub.type = UVC_EVENT_STREAMOFF;
531         ioctl(dev->vdev->fd, VIDIOC_SUBSCRIBE_EVENT, &sub);
532 }
533
534 /* ---------------------------------------------------------------------------
535  * Stream handling
536  */
537
538 static struct uvc_stream *uvc_stream_new(const char *uvc_device,
539                                          const char *cap_device)
540 {
541         struct uvc_stream *stream;
542
543         stream = malloc(sizeof(*stream));
544         if (stream == NULL)
545                 return NULL;
546
547         memset(stream, 0, sizeof(*stream));
548
549         stream->cap = v4l2_open(cap_device);
550         if (stream->cap == NULL)
551                 goto error;
552
553         stream->uvc = uvc_open(uvc_device);
554         if (stream->uvc == NULL)
555                 goto error;
556
557         return stream;
558
559 error:
560         if (stream->cap)
561                 v4l2_close(stream->cap);
562
563         free(stream);
564         return NULL;
565 }
566
567 static void uvc_stream_delete(struct uvc_stream *stream)
568 {
569         if (stream == NULL)
570                 return;
571
572         v4l2_close(stream->cap);
573         uvc_close(stream->uvc);
574
575         free(stream);
576 }
577
578 static void uvc_stream_init_uvc(struct uvc_stream *stream,
579                                 struct uvc_function_config *fc)
580 {
581         /*
582          * FIXME: The maximum size should be specified per format and frame.
583          */
584         stream->uvc->maxsize = 0;
585         stream->uvc->fc = fc;
586
587         uvc_events_init(stream->uvc);
588         uvc_video_init(stream->uvc);
589 }
590
591 static void uvc_stream_set_event_handler(struct uvc_stream *stream,
592                                          struct events *events)
593 {
594         stream->events = events;
595
596         events_watch_fd(stream->events, stream->uvc->vdev->fd, EVENT_EXCEPTION,
597                         uvc_events_process, stream);
598 }
599
600 /* ---------------------------------------------------------------------------
601  * main
602  */
603
604 static void usage(const char *argv0)
605 {
606         fprintf(stderr, "Usage: %s [options] <uvc device>\n", argv0);
607         fprintf(stderr, "Available options are\n");
608         fprintf(stderr, " -c device     V4L2 source device\n");
609         fprintf(stderr, " -h            Print this help screen and exit\n");
610         fprintf(stderr, " -i image      MJPEG image\n");
611         fprintf(stderr, "\n");
612         fprintf(stderr, " <uvc device>  UVC device instance specifier\n");
613         fprintf(stderr, "\n");
614
615         fprintf(stderr, "  For ConfigFS devices the <uvc device> parameter can take the form of a shortened\n");
616         fprintf(stderr, "  function specifier such as: 'uvc.0', or if multiple gadgets are configured, the\n");
617         fprintf(stderr, "  gadget name should be included to prevent ambiguity: 'g1/functions/uvc.0'.\n");
618         fprintf(stderr, "\n");
619         fprintf(stderr, "  For legacy g_webcam UVC instances, this parameter will identify the UDC that the\n");
620         fprintf(stderr, "  UVC function is bound to.\n");
621         fprintf(stderr, "\n");
622         fprintf(stderr, "  The parameter is optional, and if not provided the first UVC function on the first\n");
623         fprintf(stderr, "  gadget identified will be used.\n");
624         fprintf(stderr, "\n");
625         fprintf(stderr, "Example usage:\n");
626         fprintf(stderr, "    uvc-gadget uvc.1\n");
627         fprintf(stderr, "    uvc-gadget g1/functions/uvc.1\n");
628         fprintf(stderr, "\n");
629         fprintf(stderr, "    uvc-gadget musb-hdrc.0.auto\n");
630 }
631
632 /* Necessary for and only used by signal handler. */
633 static struct events *sigint_events;
634
635 static void sigint_handler(int signal __attribute__((__unused__)))
636 {
637         /* Stop the main loop when the user presses CTRL-C */
638         events_stop(sigint_events);
639 }
640
641 int main(int argc, char *argv[])
642 {
643         char *function = NULL;
644         char *cap_device = "/dev/video1";
645         struct uvc_function_config *fc;
646         struct uvc_stream *stream;
647         struct events events;
648         int ret = 0;
649         int opt;
650
651         while ((opt = getopt(argc, argv, "c:h")) != -1) {
652                 switch (opt) {
653                 case 'c':
654                         cap_device = optarg;
655                         break;
656
657                 case 'h':
658                         usage(argv[0]);
659                         return 0;
660
661                 default:
662                         fprintf(stderr, "Invalid option '-%c'\n", opt);
663                         usage(argv[0]);
664                         return 1;
665                 }
666         }
667
668         if (argv[optind] != NULL)
669                 function = argv[optind];
670
671         fc = configfs_parse_uvc_function(function);
672         if (!fc) {
673                 printf("Failed to identify function configuration\n");
674                 return 1;
675         }
676
677         /*
678          * Create the events handler. Register a signal handler for SIGINT,
679          * received when the user presses CTRL-C. This will allow the main loop
680          * to be interrupted, and resources to be freed cleanly.
681          */
682         events_init(&events);
683
684         sigint_events = &events;
685         signal(SIGINT, sigint_handler);
686
687         /* Create and initialise the stream. */
688         stream = uvc_stream_new(fc->video, cap_device);
689         if (stream == NULL) {
690                 ret = 1;
691                 goto done;
692         }
693
694         uvc_stream_init_uvc(stream, fc);
695         uvc_stream_set_event_handler(stream, &events);
696
697         /* Main capture loop */
698         events_loop(&events);
699
700 done:
701         /* Cleanup */
702         uvc_stream_delete(stream);
703         events_cleanup(&events);
704         configfs_free_uvc_function(fc);
705
706         return ret;
707 }