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