uvc-gadget: Use uvc_fill_streaming_control in uvc_events_process_data
[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         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         ret = v4l2_mmap_buffers(dev->vdev);
167         if (ret < 0) {
168                 printf("Failed to mmap buffers.\n");
169                 goto error;
170         }
171
172         for (i = 0; i < dev->vdev->nbufs; ++i) {
173                 struct v4l2_video_buffer *buf = &dev->vdev->buffers[i];
174
175                 uvc_video_fill_buffer(dev, buf);
176
177                 ret = v4l2_queue_buffer(dev->vdev, buf);
178                 if (ret < 0)
179                         goto error;
180         }
181
182         v4l2_stream_on(dev->vdev);
183         events_watch_fd(&dev->events, dev->vdev->fd, EVENT_WRITE,
184                         uvc_video_process, dev);
185
186         return 0;
187
188 error:
189         v4l2_free_buffers(dev->vdev);
190         return ret;
191 }
192
193 static int
194 uvc_video_set_format(struct uvc_device *dev)
195 {
196         struct v4l2_pix_format fmt;
197
198         printf("Setting format to 0x%08x %ux%u\n",
199                 dev->fcc, dev->width, dev->height);
200
201         memset(&fmt, 0, sizeof fmt);
202         fmt.width = dev->width;
203         fmt.height = dev->height;
204         fmt.pixelformat = dev->fcc;
205         fmt.field = V4L2_FIELD_NONE;
206         if (dev->fcc == V4L2_PIX_FMT_MJPEG)
207                 fmt.sizeimage = dev->imgsize * 1.5;
208
209         return v4l2_set_format(dev->vdev, &fmt);
210 }
211
212 static int
213 uvc_video_init(struct uvc_device *dev __attribute__((__unused__)))
214 {
215         return 0;
216 }
217
218 /* ---------------------------------------------------------------------------
219  * Request processing
220  */
221
222 struct uvc_frame_info
223 {
224         unsigned int width;
225         unsigned int height;
226         unsigned int intervals[8];
227 };
228
229 struct uvc_format_info
230 {
231         unsigned int fcc;
232         const struct uvc_frame_info *frames;
233 };
234
235 static const struct uvc_frame_info uvc_frames_yuyv[] = {
236         {  640, 360, { 666666, 10000000, 50000000, 0 }, },
237         { 1280, 720, { 50000000, 0 }, },
238         { 0, 0, { 0, }, },
239 };
240
241 static const struct uvc_frame_info uvc_frames_mjpeg[] = {
242         {  640, 360, { 666666, 10000000, 50000000, 0 }, },
243         { 1280, 720, { 50000000, 0 }, },
244         { 0, 0, { 0, }, },
245 };
246
247 static const struct uvc_format_info uvc_formats[] = {
248         { V4L2_PIX_FMT_YUYV, uvc_frames_yuyv },
249         { V4L2_PIX_FMT_MJPEG, uvc_frames_mjpeg },
250 };
251
252 static void
253 uvc_fill_streaming_control(struct uvc_device *dev,
254                            struct uvc_streaming_control *ctrl,
255                            int iformat, int iframe, unsigned int ival)
256 {
257         const struct uvc_format_info *format;
258         const struct uvc_frame_info *frame;
259         const unsigned int *interval;
260         unsigned int nframes;
261
262         /*
263          * Restrict the iformat, iframe and ival to valid values. Negative
264          * values for iformat or iframe will result in the maximum valid value
265          * being selected.
266          */
267         iformat = clamp((unsigned int)iformat, 1U,
268                         (unsigned int)ARRAY_SIZE(uvc_formats));
269         format = &uvc_formats[iformat-1];
270
271         nframes = 0;
272         while (format->frames[nframes].width != 0)
273                 ++nframes;
274
275         iframe = clamp((unsigned int)iframe, 1U, nframes);
276         frame = &format->frames[iframe-1];
277
278         interval = frame->intervals;
279         while (interval[0] < ival && interval[1])
280                 ++interval;
281
282         memset(ctrl, 0, sizeof *ctrl);
283
284         ctrl->bmHint = 1;
285         ctrl->bFormatIndex = iformat;
286         ctrl->bFrameIndex = iframe ;
287         ctrl->dwFrameInterval = *interval;
288
289         switch (format->fcc) {
290         case V4L2_PIX_FMT_YUYV:
291                 ctrl->dwMaxVideoFrameSize = frame->width * frame->height * 2;
292                 break;
293         case V4L2_PIX_FMT_MJPEG:
294                 ctrl->dwMaxVideoFrameSize = dev->imgsize;
295                 break;
296         }
297
298         ctrl->dwMaxPayloadTransferSize = 512;   /* TODO this should be filled by the driver. */
299         ctrl->bmFramingInfo = 3;
300         ctrl->bPreferedVersion = 1;
301         ctrl->bMaxVersion = 1;
302 }
303
304 static void
305 uvc_events_process_standard(struct uvc_device *dev, 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, struct usb_ctrlrequest *ctrl,
376                          struct uvc_request_data *resp)
377 {
378         if ((ctrl->bRequestType & USB_RECIP_MASK) != USB_RECIP_INTERFACE)
379                 return;
380
381         switch (ctrl->wIndex & 0xff) {
382         case UVC_INTF_CONTROL:
383                 uvc_events_process_control(dev, ctrl->bRequest, ctrl->wValue >> 8, resp);
384                 break;
385
386         case UVC_INTF_STREAMING:
387                 uvc_events_process_streaming(dev, ctrl->bRequest, ctrl->wValue >> 8, resp);
388                 break;
389
390         default:
391                 break;
392         }
393 }
394
395 static void
396 uvc_events_process_setup(struct uvc_device *dev, 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_device *dev, struct uvc_request_data *data)
421 {
422         struct uvc_streaming_control *target;
423         struct uvc_streaming_control *ctrl;
424
425         switch (dev->control) {
426         case UVC_VS_PROBE_CONTROL:
427                 printf("setting probe control, length = %d\n", data->length);
428                 target = &dev->probe;
429                 break;
430
431         case UVC_VS_COMMIT_CONTROL:
432                 printf("setting commit control, length = %d\n", data->length);
433                 target = &dev->commit;
434                 break;
435
436         default:
437                 printf("setting unknown control, length = %d\n", data->length);
438                 return;
439         }
440
441         ctrl = (struct uvc_streaming_control *)&data->data;
442
443         uvc_fill_streaming_control(dev, target, ctrl->bFormatIndex,
444                                    ctrl->bFrameIndex, ctrl->dwFrameInterval);
445
446         if (dev->control == UVC_VS_COMMIT_CONTROL) {
447                 const struct uvc_format_info *format;
448                 const struct uvc_frame_info *frame;
449
450                 format = &uvc_formats[target->bFormatIndex-1];
451                 frame = &format->frames[target->bFrameIndex-1];
452
453                 dev->fcc = format->fcc;
454                 dev->width = frame->width;
455                 dev->height = frame->height;
456
457                 uvc_video_set_format(dev);
458                 if (dev->bulk)
459                         uvc_video_stream(dev, 1);
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         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         if (dev->bulk) {
522                 /* FIXME Crude hack, must be negotiated with the driver. */
523                 dev->probe.dwMaxPayloadTransferSize = 16 * 1024;
524                 dev->commit.dwMaxPayloadTransferSize = 16 * 1024;
525         }
526
527
528         memset(&sub, 0, sizeof sub);
529         sub.type = UVC_EVENT_SETUP;
530         ioctl(dev->vdev->fd, VIDIOC_SUBSCRIBE_EVENT, &sub);
531         sub.type = UVC_EVENT_DATA;
532         ioctl(dev->vdev->fd, VIDIOC_SUBSCRIBE_EVENT, &sub);
533         sub.type = UVC_EVENT_STREAMON;
534         ioctl(dev->vdev->fd, VIDIOC_SUBSCRIBE_EVENT, &sub);
535         sub.type = UVC_EVENT_STREAMOFF;
536         ioctl(dev->vdev->fd, VIDIOC_SUBSCRIBE_EVENT, &sub);
537 }
538
539 /* ---------------------------------------------------------------------------
540  * main
541  */
542
543 static void image_load(struct uvc_device *dev, const char *img)
544 {
545         int fd = -1;
546
547         if (img == NULL)
548                 return;
549
550         fd = open(img, O_RDONLY);
551         if (fd == -1) {
552                 printf("Unable to open MJPEG image '%s'\n", img);
553                 return;
554         }
555
556         dev->imgsize = lseek(fd, 0, SEEK_END);
557         lseek(fd, 0, SEEK_SET);
558         dev->imgdata = malloc(dev->imgsize);
559         if (dev->imgdata == NULL) {
560                 printf("Unable to allocate memory for MJPEG image\n");
561                 dev->imgsize = 0;
562                 return;
563         }
564
565         read(fd, dev->imgdata, dev->imgsize);
566         close(fd);
567 }
568
569 static void usage(const char *argv0)
570 {
571         fprintf(stderr, "Usage: %s [options]\n", argv0);
572         fprintf(stderr, "Available options are\n");
573         fprintf(stderr, " -b            Use bulk mode\n");
574         fprintf(stderr, " -d device     Video device\n");
575         fprintf(stderr, " -h            Print this help screen and exit\n");
576         fprintf(stderr, " -i image      MJPEG image\n");
577 }
578
579 /* Necessary for and only used by signal handler. */
580 static struct uvc_device *uvc_device;
581
582 static void sigint_handler(int signal __attribute__((__unused__)))
583 {
584         /* Stop the main loop when the user presses CTRL-C */
585         events_stop(&uvc_device->events);
586 }
587
588 int main(int argc, char *argv[])
589 {
590         char *device = "/dev/video0";
591         struct uvc_device *dev;
592         int bulk_mode = 0;
593         char *mjpeg_image = NULL;
594         int opt;
595
596         while ((opt = getopt(argc, argv, "bd:hi:")) != -1) {
597                 switch (opt) {
598                 case 'b':
599                         bulk_mode = 1;
600                         break;
601
602                 case 'd':
603                         device = optarg;
604                         break;
605
606                 case 'h':
607                         usage(argv[0]);
608                         return 0;
609
610                 case 'i':
611                         mjpeg_image = optarg;
612                         break;
613
614                 default:
615                         fprintf(stderr, "Invalid option '-%c'\n", opt);
616                         usage(argv[0]);
617                         return 1;
618                 }
619         }
620
621         dev = uvc_open(device);
622         if (dev == NULL)
623                 return 1;
624
625         image_load(dev, mjpeg_image);
626
627         dev->bulk = bulk_mode;
628
629         uvc_events_init(dev);
630         uvc_video_init(dev);
631
632         /*
633          * Register a signal handler for SIGINT, received when the user presses
634          * CTRL-C. This will allow the main loop to be interrupted, and resources
635          * to be freed cleanly.
636          */
637         uvc_device = dev;
638         signal(SIGINT, sigint_handler);
639
640         events_watch_fd(&dev->events, dev->vdev->fd, EVENT_EXCEPTION,
641                         uvc_events_process, dev);
642
643         /* Main capture loop */
644         events_loop(&dev->events);
645
646         events_cleanup(&dev->events);
647         uvc_close(dev);
648         return 0;
649 }