GNU Linux-libre 4.9.337-gnu1
[releases.git] / drivers / media / usb / hdpvr / hdpvr-video.c
1 /*
2  * Hauppauge HD PVR USB driver - video 4 linux 2 interface
3  *
4  * Copyright (C) 2008      Janne Grunau (j@jannau.net)
5  *
6  *      This program is free software; you can redistribute it and/or
7  *      modify it under the terms of the GNU General Public License as
8  *      published by the Free Software Foundation, version 2.
9  *
10  */
11
12 #include <linux/kernel.h>
13 #include <linux/errno.h>
14 #include <linux/init.h>
15 #include <linux/slab.h>
16 #include <linux/module.h>
17 #include <linux/uaccess.h>
18 #include <linux/usb.h>
19 #include <linux/mutex.h>
20 #include <linux/workqueue.h>
21
22 #include <linux/videodev2.h>
23 #include <linux/v4l2-dv-timings.h>
24 #include <media/v4l2-dev.h>
25 #include <media/v4l2-common.h>
26 #include <media/v4l2-dv-timings.h>
27 #include <media/v4l2-ioctl.h>
28 #include <media/v4l2-event.h>
29 #include "hdpvr.h"
30
31 #define BULK_URB_TIMEOUT   90 /* 0.09 seconds */
32
33 #define print_buffer_status() { \
34                 v4l2_dbg(MSG_BUFFER, hdpvr_debug, &dev->v4l2_dev,       \
35                          "%s:%d buffer stat: %d free, %d proc\n",       \
36                          __func__, __LINE__,                            \
37                          list_size(&dev->free_buff_list),               \
38                          list_size(&dev->rec_buff_list)); }
39
40 static const struct v4l2_dv_timings hdpvr_dv_timings[] = {
41         V4L2_DV_BT_CEA_720X480I59_94,
42         V4L2_DV_BT_CEA_720X576I50,
43         V4L2_DV_BT_CEA_720X480P59_94,
44         V4L2_DV_BT_CEA_720X576P50,
45         V4L2_DV_BT_CEA_1280X720P50,
46         V4L2_DV_BT_CEA_1280X720P60,
47         V4L2_DV_BT_CEA_1920X1080I50,
48         V4L2_DV_BT_CEA_1920X1080I60,
49 };
50
51 /* Use 480i59 as the default timings */
52 #define HDPVR_DEF_DV_TIMINGS_IDX (0)
53
54 struct hdpvr_fh {
55         struct v4l2_fh fh;
56         bool legacy_mode;
57 };
58
59 static uint list_size(struct list_head *list)
60 {
61         struct list_head *tmp;
62         uint count = 0;
63
64         list_for_each(tmp, list) {
65                 count++;
66         }
67
68         return count;
69 }
70
71 /*=========================================================================*/
72 /* urb callback */
73 static void hdpvr_read_bulk_callback(struct urb *urb)
74 {
75         struct hdpvr_buffer *buf = (struct hdpvr_buffer *)urb->context;
76         struct hdpvr_device *dev = buf->dev;
77
78         /* marking buffer as received and wake waiting */
79         buf->status = BUFSTAT_READY;
80         wake_up_interruptible(&dev->wait_data);
81 }
82
83 /*=========================================================================*/
84 /* buffer bits */
85
86 /* function expects dev->io_mutex to be hold by caller */
87 int hdpvr_cancel_queue(struct hdpvr_device *dev)
88 {
89         struct hdpvr_buffer *buf;
90
91         list_for_each_entry(buf, &dev->rec_buff_list, buff_list) {
92                 usb_kill_urb(buf->urb);
93                 buf->status = BUFSTAT_AVAILABLE;
94         }
95
96         list_splice_init(&dev->rec_buff_list, dev->free_buff_list.prev);
97
98         return 0;
99 }
100
101 static int hdpvr_free_queue(struct list_head *q)
102 {
103         struct list_head *tmp;
104         struct list_head *p;
105         struct hdpvr_buffer *buf;
106         struct urb *urb;
107
108         for (p = q->next; p != q;) {
109                 buf = list_entry(p, struct hdpvr_buffer, buff_list);
110
111                 urb = buf->urb;
112                 usb_free_coherent(urb->dev, urb->transfer_buffer_length,
113                                   urb->transfer_buffer, urb->transfer_dma);
114                 usb_free_urb(urb);
115                 tmp = p->next;
116                 list_del(p);
117                 kfree(buf);
118                 p = tmp;
119         }
120
121         return 0;
122 }
123
124 /* function expects dev->io_mutex to be hold by caller */
125 int hdpvr_free_buffers(struct hdpvr_device *dev)
126 {
127         hdpvr_cancel_queue(dev);
128
129         hdpvr_free_queue(&dev->free_buff_list);
130         hdpvr_free_queue(&dev->rec_buff_list);
131
132         return 0;
133 }
134
135 /* function expects dev->io_mutex to be hold by caller */
136 int hdpvr_alloc_buffers(struct hdpvr_device *dev, uint count)
137 {
138         uint i;
139         int retval = -ENOMEM;
140         u8 *mem;
141         struct hdpvr_buffer *buf;
142         struct urb *urb;
143
144         v4l2_dbg(MSG_INFO, hdpvr_debug, &dev->v4l2_dev,
145                  "allocating %u buffers\n", count);
146
147         for (i = 0; i < count; i++) {
148
149                 buf = kzalloc(sizeof(struct hdpvr_buffer), GFP_KERNEL);
150                 if (!buf) {
151                         v4l2_err(&dev->v4l2_dev, "cannot allocate buffer\n");
152                         goto exit;
153                 }
154                 buf->dev = dev;
155
156                 urb = usb_alloc_urb(0, GFP_KERNEL);
157                 if (!urb)
158                         goto exit_urb;
159                 buf->urb = urb;
160
161                 mem = usb_alloc_coherent(dev->udev, dev->bulk_in_size, GFP_KERNEL,
162                                          &urb->transfer_dma);
163                 if (!mem) {
164                         v4l2_err(&dev->v4l2_dev,
165                                  "cannot allocate usb transfer buffer\n");
166                         goto exit_urb_buffer;
167                 }
168
169                 usb_fill_bulk_urb(buf->urb, dev->udev,
170                                   usb_rcvbulkpipe(dev->udev,
171                                                   dev->bulk_in_endpointAddr),
172                                   mem, dev->bulk_in_size,
173                                   hdpvr_read_bulk_callback, buf);
174
175                 buf->urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
176                 buf->status = BUFSTAT_AVAILABLE;
177                 list_add_tail(&buf->buff_list, &dev->free_buff_list);
178         }
179         return 0;
180 exit_urb_buffer:
181         usb_free_urb(urb);
182 exit_urb:
183         kfree(buf);
184 exit:
185         hdpvr_free_buffers(dev);
186         return retval;
187 }
188
189 static int hdpvr_submit_buffers(struct hdpvr_device *dev)
190 {
191         struct hdpvr_buffer *buf;
192         struct urb *urb;
193         int ret = 0, err_count = 0;
194
195         mutex_lock(&dev->io_mutex);
196
197         while (dev->status == STATUS_STREAMING &&
198                !list_empty(&dev->free_buff_list)) {
199
200                 buf = list_entry(dev->free_buff_list.next, struct hdpvr_buffer,
201                                  buff_list);
202                 if (buf->status != BUFSTAT_AVAILABLE) {
203                         v4l2_err(&dev->v4l2_dev,
204                                  "buffer not marked as available\n");
205                         ret = -EFAULT;
206                         goto err;
207                 }
208
209                 urb = buf->urb;
210                 urb->status = 0;
211                 urb->actual_length = 0;
212                 ret = usb_submit_urb(urb, GFP_KERNEL);
213                 if (ret) {
214                         v4l2_err(&dev->v4l2_dev,
215                                  "usb_submit_urb in %s returned %d\n",
216                                  __func__, ret);
217                         if (++err_count > 2)
218                                 break;
219                         continue;
220                 }
221                 buf->status = BUFSTAT_INPROGRESS;
222                 list_move_tail(&buf->buff_list, &dev->rec_buff_list);
223         }
224 err:
225         print_buffer_status();
226         mutex_unlock(&dev->io_mutex);
227         return ret;
228 }
229
230 static struct hdpvr_buffer *hdpvr_get_next_buffer(struct hdpvr_device *dev)
231 {
232         struct hdpvr_buffer *buf;
233
234         mutex_lock(&dev->io_mutex);
235
236         if (list_empty(&dev->rec_buff_list)) {
237                 mutex_unlock(&dev->io_mutex);
238                 return NULL;
239         }
240
241         buf = list_entry(dev->rec_buff_list.next, struct hdpvr_buffer,
242                          buff_list);
243         mutex_unlock(&dev->io_mutex);
244
245         return buf;
246 }
247
248 static void hdpvr_transmit_buffers(struct work_struct *work)
249 {
250         struct hdpvr_device *dev = container_of(work, struct hdpvr_device,
251                                                 worker);
252
253         while (dev->status == STATUS_STREAMING) {
254
255                 if (hdpvr_submit_buffers(dev)) {
256                         v4l2_err(&dev->v4l2_dev, "couldn't submit buffers\n");
257                         goto error;
258                 }
259                 if (wait_event_interruptible(dev->wait_buffer,
260                                 !list_empty(&dev->free_buff_list) ||
261                                              dev->status != STATUS_STREAMING))
262                         goto error;
263         }
264
265         v4l2_dbg(MSG_INFO, hdpvr_debug, &dev->v4l2_dev,
266                  "transmit worker exited\n");
267         return;
268 error:
269         v4l2_dbg(MSG_INFO, hdpvr_debug, &dev->v4l2_dev,
270                  "transmit buffers errored\n");
271         dev->status = STATUS_ERROR;
272 }
273
274 /* function expects dev->io_mutex to be hold by caller */
275 static int hdpvr_start_streaming(struct hdpvr_device *dev)
276 {
277         int ret;
278         struct hdpvr_video_info vidinf;
279
280         if (dev->status == STATUS_STREAMING)
281                 return 0;
282         if (dev->status != STATUS_IDLE)
283                 return -EAGAIN;
284
285         ret = get_video_info(dev, &vidinf);
286         if (ret < 0)
287                 return ret;
288
289         if (!vidinf.valid) {
290                 msleep(250);
291                 v4l2_dbg(MSG_INFO, hdpvr_debug, &dev->v4l2_dev,
292                                 "no video signal at input %d\n", dev->options.video_input);
293                 return -EAGAIN;
294         }
295
296         v4l2_dbg(MSG_BUFFER, hdpvr_debug, &dev->v4l2_dev,
297                         "video signal: %dx%d@%dhz\n", vidinf.width,
298                         vidinf.height, vidinf.fps);
299
300         /* start streaming 2 request */
301         ret = usb_control_msg(dev->udev,
302                         usb_sndctrlpipe(dev->udev, 0),
303                         0xb8, 0x38, 0x1, 0, NULL, 0, 8000);
304         v4l2_dbg(MSG_BUFFER, hdpvr_debug, &dev->v4l2_dev,
305                         "encoder start control request returned %d\n", ret);
306         if (ret < 0)
307                 return ret;
308
309         ret = hdpvr_config_call(dev, CTRL_START_STREAMING_VALUE, 0x00);
310         if (ret)
311                 return ret;
312
313         dev->status = STATUS_STREAMING;
314
315         schedule_work(&dev->worker);
316
317         v4l2_dbg(MSG_BUFFER, hdpvr_debug, &dev->v4l2_dev,
318                         "streaming started\n");
319
320         return 0;
321 }
322
323
324 /* function expects dev->io_mutex to be hold by caller */
325 static int hdpvr_stop_streaming(struct hdpvr_device *dev)
326 {
327         int actual_length;
328         uint c = 0;
329         u8 *buf;
330
331         if (dev->status == STATUS_IDLE)
332                 return 0;
333         else if (dev->status != STATUS_STREAMING)
334                 return -EAGAIN;
335
336         buf = kmalloc(dev->bulk_in_size, GFP_KERNEL);
337         if (!buf)
338                 v4l2_err(&dev->v4l2_dev, "failed to allocate temporary buffer "
339                          "for emptying the internal device buffer. "
340                          "Next capture start will be slow\n");
341
342         dev->status = STATUS_SHUTTING_DOWN;
343         hdpvr_config_call(dev, CTRL_STOP_STREAMING_VALUE, 0x00);
344         mutex_unlock(&dev->io_mutex);
345
346         wake_up_interruptible(&dev->wait_buffer);
347         msleep(50);
348
349         flush_work(&dev->worker);
350
351         mutex_lock(&dev->io_mutex);
352         /* kill the still outstanding urbs */
353         hdpvr_cancel_queue(dev);
354
355         /* emptying the device buffer beforeshutting it down */
356         while (buf && ++c < 500 &&
357                !usb_bulk_msg(dev->udev,
358                              usb_rcvbulkpipe(dev->udev,
359                                              dev->bulk_in_endpointAddr),
360                              buf, dev->bulk_in_size, &actual_length,
361                              BULK_URB_TIMEOUT)) {
362                 v4l2_dbg(MSG_BUFFER, hdpvr_debug, &dev->v4l2_dev,
363                          "%2d: got %d bytes\n", c, actual_length);
364         }
365         kfree(buf);
366         v4l2_dbg(MSG_BUFFER, hdpvr_debug, &dev->v4l2_dev,
367                  "used %d urbs to empty device buffers\n", c-1);
368         msleep(10);
369
370         dev->status = STATUS_IDLE;
371
372         return 0;
373 }
374
375
376 /*=======================================================================*/
377 /*
378  * video 4 linux 2 file operations
379  */
380
381 static int hdpvr_open(struct file *file)
382 {
383         struct hdpvr_fh *fh = kzalloc(sizeof(*fh), GFP_KERNEL);
384
385         if (fh == NULL)
386                 return -ENOMEM;
387         fh->legacy_mode = true;
388         v4l2_fh_init(&fh->fh, video_devdata(file));
389         v4l2_fh_add(&fh->fh);
390         file->private_data = fh;
391         return 0;
392 }
393
394 static int hdpvr_release(struct file *file)
395 {
396         struct hdpvr_device *dev = video_drvdata(file);
397
398         mutex_lock(&dev->io_mutex);
399         if (file->private_data == dev->owner) {
400                 hdpvr_stop_streaming(dev);
401                 dev->owner = NULL;
402         }
403         mutex_unlock(&dev->io_mutex);
404
405         return v4l2_fh_release(file);
406 }
407
408 /*
409  * hdpvr_v4l2_read()
410  * will allocate buffers when called for the first time
411  */
412 static ssize_t hdpvr_read(struct file *file, char __user *buffer, size_t count,
413                           loff_t *pos)
414 {
415         struct hdpvr_device *dev = video_drvdata(file);
416         struct hdpvr_buffer *buf = NULL;
417         struct urb *urb;
418         unsigned int ret = 0;
419         int rem, cnt;
420
421         if (*pos)
422                 return -ESPIPE;
423
424         mutex_lock(&dev->io_mutex);
425         if (dev->status == STATUS_IDLE) {
426                 if (hdpvr_start_streaming(dev)) {
427                         v4l2_dbg(MSG_INFO, hdpvr_debug, &dev->v4l2_dev,
428                                  "start_streaming failed\n");
429                         ret = -EIO;
430                         msleep(200);
431                         dev->status = STATUS_IDLE;
432                         mutex_unlock(&dev->io_mutex);
433                         goto err;
434                 }
435                 dev->owner = file->private_data;
436                 print_buffer_status();
437         }
438         mutex_unlock(&dev->io_mutex);
439
440         /* wait for the first buffer */
441         if (!(file->f_flags & O_NONBLOCK)) {
442                 if (wait_event_interruptible(dev->wait_data,
443                                              hdpvr_get_next_buffer(dev)))
444                         return -ERESTARTSYS;
445         }
446
447         buf = hdpvr_get_next_buffer(dev);
448
449         while (count > 0 && buf) {
450
451                 if (buf->status != BUFSTAT_READY &&
452                     dev->status != STATUS_DISCONNECTED) {
453                         /* return nonblocking */
454                         if (file->f_flags & O_NONBLOCK) {
455                                 if (!ret)
456                                         ret = -EAGAIN;
457                                 goto err;
458                         }
459
460                         if (wait_event_interruptible(dev->wait_data,
461                                               buf->status == BUFSTAT_READY))
462                                 return -ERESTARTSYS;
463                 }
464
465                 if (buf->status != BUFSTAT_READY)
466                         break;
467
468                 /* set remaining bytes to copy */
469                 urb = buf->urb;
470                 rem = urb->actual_length - buf->pos;
471                 cnt = rem > count ? count : rem;
472
473                 if (copy_to_user(buffer, urb->transfer_buffer + buf->pos,
474                                  cnt)) {
475                         v4l2_err(&dev->v4l2_dev, "read: copy_to_user failed\n");
476                         if (!ret)
477                                 ret = -EFAULT;
478                         goto err;
479                 }
480
481                 buf->pos += cnt;
482                 count -= cnt;
483                 buffer += cnt;
484                 ret += cnt;
485
486                 /* finished, take next buffer */
487                 if (buf->pos == urb->actual_length) {
488                         mutex_lock(&dev->io_mutex);
489                         buf->pos = 0;
490                         buf->status = BUFSTAT_AVAILABLE;
491
492                         list_move_tail(&buf->buff_list, &dev->free_buff_list);
493
494                         print_buffer_status();
495
496                         mutex_unlock(&dev->io_mutex);
497
498                         wake_up_interruptible(&dev->wait_buffer);
499
500                         buf = hdpvr_get_next_buffer(dev);
501                 }
502         }
503 err:
504         if (!ret && !buf)
505                 ret = -EAGAIN;
506         return ret;
507 }
508
509 static unsigned int hdpvr_poll(struct file *filp, poll_table *wait)
510 {
511         unsigned long req_events = poll_requested_events(wait);
512         struct hdpvr_buffer *buf = NULL;
513         struct hdpvr_device *dev = video_drvdata(filp);
514         unsigned int mask = v4l2_ctrl_poll(filp, wait);
515
516         if (!(req_events & (POLLIN | POLLRDNORM)))
517                 return mask;
518
519         mutex_lock(&dev->io_mutex);
520
521         if (dev->status == STATUS_IDLE) {
522                 if (hdpvr_start_streaming(dev)) {
523                         v4l2_dbg(MSG_BUFFER, hdpvr_debug, &dev->v4l2_dev,
524                                  "start_streaming failed\n");
525                         dev->status = STATUS_IDLE;
526                 } else {
527                         dev->owner = filp->private_data;
528                 }
529
530                 print_buffer_status();
531         }
532         mutex_unlock(&dev->io_mutex);
533
534         buf = hdpvr_get_next_buffer(dev);
535         /* only wait if no data is available */
536         if (!buf || buf->status != BUFSTAT_READY) {
537                 poll_wait(filp, &dev->wait_data, wait);
538                 buf = hdpvr_get_next_buffer(dev);
539         }
540         if (buf && buf->status == BUFSTAT_READY)
541                 mask |= POLLIN | POLLRDNORM;
542
543         return mask;
544 }
545
546
547 static const struct v4l2_file_operations hdpvr_fops = {
548         .owner          = THIS_MODULE,
549         .open           = hdpvr_open,
550         .release        = hdpvr_release,
551         .read           = hdpvr_read,
552         .poll           = hdpvr_poll,
553         .unlocked_ioctl = video_ioctl2,
554 };
555
556 /*=======================================================================*/
557 /*
558  * V4L2 ioctl handling
559  */
560
561 static int vidioc_querycap(struct file *file, void  *priv,
562                            struct v4l2_capability *cap)
563 {
564         struct hdpvr_device *dev = video_drvdata(file);
565
566         strcpy(cap->driver, "hdpvr");
567         strcpy(cap->card, "Hauppauge HD PVR");
568         usb_make_path(dev->udev, cap->bus_info, sizeof(cap->bus_info));
569         cap->device_caps = V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_AUDIO |
570                             V4L2_CAP_READWRITE;
571         cap->capabilities = cap->device_caps | V4L2_CAP_DEVICE_CAPS;
572         return 0;
573 }
574
575 static int vidioc_s_std(struct file *file, void *_fh,
576                         v4l2_std_id std)
577 {
578         struct hdpvr_device *dev = video_drvdata(file);
579         struct hdpvr_fh *fh = _fh;
580         u8 std_type = 1;
581
582         if (!fh->legacy_mode && dev->options.video_input == HDPVR_COMPONENT)
583                 return -ENODATA;
584         if (dev->status != STATUS_IDLE)
585                 return -EBUSY;
586         if (std & V4L2_STD_525_60)
587                 std_type = 0;
588         dev->cur_std = std;
589         dev->width = 720;
590         dev->height = std_type ? 576 : 480;
591
592         return hdpvr_config_call(dev, CTRL_VIDEO_STD_TYPE, std_type);
593 }
594
595 static int vidioc_g_std(struct file *file, void *_fh,
596                         v4l2_std_id *std)
597 {
598         struct hdpvr_device *dev = video_drvdata(file);
599         struct hdpvr_fh *fh = _fh;
600
601         if (!fh->legacy_mode && dev->options.video_input == HDPVR_COMPONENT)
602                 return -ENODATA;
603         *std = dev->cur_std;
604         return 0;
605 }
606
607 static int vidioc_querystd(struct file *file, void *_fh, v4l2_std_id *a)
608 {
609         struct hdpvr_device *dev = video_drvdata(file);
610         struct hdpvr_video_info vid_info;
611         struct hdpvr_fh *fh = _fh;
612         int ret;
613
614         *a = V4L2_STD_UNKNOWN;
615         if (dev->options.video_input == HDPVR_COMPONENT)
616                 return fh->legacy_mode ? 0 : -ENODATA;
617         ret = get_video_info(dev, &vid_info);
618         if (vid_info.valid && vid_info.width == 720 &&
619             (vid_info.height == 480 || vid_info.height == 576)) {
620                 *a = (vid_info.height == 480) ?
621                         V4L2_STD_525_60 : V4L2_STD_625_50;
622         }
623         return ret;
624 }
625
626 static int vidioc_s_dv_timings(struct file *file, void *_fh,
627                                     struct v4l2_dv_timings *timings)
628 {
629         struct hdpvr_device *dev = video_drvdata(file);
630         struct hdpvr_fh *fh = _fh;
631         int i;
632
633         fh->legacy_mode = false;
634         if (dev->options.video_input)
635                 return -ENODATA;
636         if (dev->status != STATUS_IDLE)
637                 return -EBUSY;
638         for (i = 0; i < ARRAY_SIZE(hdpvr_dv_timings); i++)
639                 if (v4l2_match_dv_timings(timings, hdpvr_dv_timings + i, 0, false))
640                         break;
641         if (i == ARRAY_SIZE(hdpvr_dv_timings))
642                 return -EINVAL;
643         dev->cur_dv_timings = hdpvr_dv_timings[i];
644         dev->width = hdpvr_dv_timings[i].bt.width;
645         dev->height = hdpvr_dv_timings[i].bt.height;
646         return 0;
647 }
648
649 static int vidioc_g_dv_timings(struct file *file, void *_fh,
650                                     struct v4l2_dv_timings *timings)
651 {
652         struct hdpvr_device *dev = video_drvdata(file);
653         struct hdpvr_fh *fh = _fh;
654
655         fh->legacy_mode = false;
656         if (dev->options.video_input)
657                 return -ENODATA;
658         *timings = dev->cur_dv_timings;
659         return 0;
660 }
661
662 static int vidioc_query_dv_timings(struct file *file, void *_fh,
663                                     struct v4l2_dv_timings *timings)
664 {
665         struct hdpvr_device *dev = video_drvdata(file);
666         struct hdpvr_fh *fh = _fh;
667         struct hdpvr_video_info vid_info;
668         bool interlaced;
669         int ret = 0;
670         int i;
671
672         fh->legacy_mode = false;
673         if (dev->options.video_input)
674                 return -ENODATA;
675         ret = get_video_info(dev, &vid_info);
676         if (ret)
677                 return ret;
678         if (!vid_info.valid)
679                 return -ENOLCK;
680         interlaced = vid_info.fps <= 30;
681         for (i = 0; i < ARRAY_SIZE(hdpvr_dv_timings); i++) {
682                 const struct v4l2_bt_timings *bt = &hdpvr_dv_timings[i].bt;
683                 unsigned hsize;
684                 unsigned vsize;
685                 unsigned fps;
686
687                 hsize = V4L2_DV_BT_FRAME_WIDTH(bt);
688                 vsize = V4L2_DV_BT_FRAME_HEIGHT(bt);
689                 fps = (unsigned)bt->pixelclock / (hsize * vsize);
690                 if (bt->width != vid_info.width ||
691                     bt->height != vid_info.height ||
692                     bt->interlaced != interlaced ||
693                     (fps != vid_info.fps && fps + 1 != vid_info.fps))
694                         continue;
695                 *timings = hdpvr_dv_timings[i];
696                 break;
697         }
698         if (i == ARRAY_SIZE(hdpvr_dv_timings))
699                 ret = -ERANGE;
700
701         return ret;
702 }
703
704 static int vidioc_enum_dv_timings(struct file *file, void *_fh,
705                                     struct v4l2_enum_dv_timings *timings)
706 {
707         struct hdpvr_device *dev = video_drvdata(file);
708         struct hdpvr_fh *fh = _fh;
709
710         fh->legacy_mode = false;
711         memset(timings->reserved, 0, sizeof(timings->reserved));
712         if (dev->options.video_input)
713                 return -ENODATA;
714         if (timings->index >= ARRAY_SIZE(hdpvr_dv_timings))
715                 return -EINVAL;
716         timings->timings = hdpvr_dv_timings[timings->index];
717         return 0;
718 }
719
720 static int vidioc_dv_timings_cap(struct file *file, void *_fh,
721                                     struct v4l2_dv_timings_cap *cap)
722 {
723         struct hdpvr_device *dev = video_drvdata(file);
724         struct hdpvr_fh *fh = _fh;
725
726         fh->legacy_mode = false;
727         if (dev->options.video_input)
728                 return -ENODATA;
729         cap->type = V4L2_DV_BT_656_1120;
730         cap->bt.min_width = 720;
731         cap->bt.max_width = 1920;
732         cap->bt.min_height = 480;
733         cap->bt.max_height = 1080;
734         cap->bt.min_pixelclock = 27000000;
735         cap->bt.max_pixelclock = 74250000;
736         cap->bt.standards = V4L2_DV_BT_STD_CEA861;
737         cap->bt.capabilities = V4L2_DV_BT_CAP_INTERLACED | V4L2_DV_BT_CAP_PROGRESSIVE;
738         return 0;
739 }
740
741 static const char *iname[] = {
742         [HDPVR_COMPONENT] = "Component",
743         [HDPVR_SVIDEO]    = "S-Video",
744         [HDPVR_COMPOSITE] = "Composite",
745 };
746
747 static int vidioc_enum_input(struct file *file, void *_fh, struct v4l2_input *i)
748 {
749         unsigned int n;
750
751         n = i->index;
752         if (n >= HDPVR_VIDEO_INPUTS)
753                 return -EINVAL;
754
755         i->type = V4L2_INPUT_TYPE_CAMERA;
756
757         strncpy(i->name, iname[n], sizeof(i->name) - 1);
758         i->name[sizeof(i->name) - 1] = '\0';
759
760         i->audioset = 1<<HDPVR_RCA_FRONT | 1<<HDPVR_RCA_BACK | 1<<HDPVR_SPDIF;
761
762         i->capabilities = n ? V4L2_IN_CAP_STD : V4L2_IN_CAP_DV_TIMINGS;
763         i->std = n ? V4L2_STD_ALL : 0;
764
765         return 0;
766 }
767
768 static int vidioc_s_input(struct file *file, void *_fh,
769                           unsigned int index)
770 {
771         struct hdpvr_device *dev = video_drvdata(file);
772         int retval;
773
774         if (index >= HDPVR_VIDEO_INPUTS)
775                 return -EINVAL;
776
777         if (dev->status != STATUS_IDLE)
778                 return -EBUSY;
779
780         retval = hdpvr_config_call(dev, CTRL_VIDEO_INPUT_VALUE, index+1);
781         if (!retval) {
782                 dev->options.video_input = index;
783                 /*
784                  * Unfortunately gstreamer calls ENUMSTD and bails out if it
785                  * won't find any formats, even though component input is
786                  * selected. This means that we have to leave tvnorms at
787                  * V4L2_STD_ALL. We cannot use the 'legacy' trick since
788                  * tvnorms is set at the device node level and not at the
789                  * filehandle level.
790                  *
791                  * Comment this out for now, but if the legacy mode can be
792                  * removed in the future, then this code should be enabled
793                  * again.
794                 dev->video_dev.tvnorms =
795                         (index != HDPVR_COMPONENT) ? V4L2_STD_ALL : 0;
796                  */
797         }
798
799         return retval;
800 }
801
802 static int vidioc_g_input(struct file *file, void *private_data,
803                           unsigned int *index)
804 {
805         struct hdpvr_device *dev = video_drvdata(file);
806
807         *index = dev->options.video_input;
808         return 0;
809 }
810
811
812 static const char *audio_iname[] = {
813         [HDPVR_RCA_FRONT] = "RCA front",
814         [HDPVR_RCA_BACK]  = "RCA back",
815         [HDPVR_SPDIF]     = "SPDIF",
816 };
817
818 static int vidioc_enumaudio(struct file *file, void *priv,
819                                 struct v4l2_audio *audio)
820 {
821         unsigned int n;
822
823         n = audio->index;
824         if (n >= HDPVR_AUDIO_INPUTS)
825                 return -EINVAL;
826
827         audio->capability = V4L2_AUDCAP_STEREO;
828
829         strncpy(audio->name, audio_iname[n], sizeof(audio->name) - 1);
830         audio->name[sizeof(audio->name) - 1] = '\0';
831
832         return 0;
833 }
834
835 static int vidioc_s_audio(struct file *file, void *private_data,
836                           const struct v4l2_audio *audio)
837 {
838         struct hdpvr_device *dev = video_drvdata(file);
839         int retval;
840
841         if (audio->index >= HDPVR_AUDIO_INPUTS)
842                 return -EINVAL;
843
844         if (dev->status != STATUS_IDLE)
845                 return -EBUSY;
846
847         retval = hdpvr_set_audio(dev, audio->index+1, dev->options.audio_codec);
848         if (!retval)
849                 dev->options.audio_input = audio->index;
850
851         return retval;
852 }
853
854 static int vidioc_g_audio(struct file *file, void *private_data,
855                           struct v4l2_audio *audio)
856 {
857         struct hdpvr_device *dev = video_drvdata(file);
858
859         audio->index = dev->options.audio_input;
860         audio->capability = V4L2_AUDCAP_STEREO;
861         strncpy(audio->name, audio_iname[audio->index], sizeof(audio->name));
862         audio->name[sizeof(audio->name) - 1] = '\0';
863         return 0;
864 }
865
866 static int hdpvr_try_ctrl(struct v4l2_ctrl *ctrl)
867 {
868         struct hdpvr_device *dev =
869                 container_of(ctrl->handler, struct hdpvr_device, hdl);
870
871         switch (ctrl->id) {
872         case V4L2_CID_MPEG_VIDEO_BITRATE_MODE:
873                 if (ctrl->val == V4L2_MPEG_VIDEO_BITRATE_MODE_VBR &&
874                     dev->video_bitrate->val >= dev->video_bitrate_peak->val)
875                         dev->video_bitrate_peak->val =
876                                         dev->video_bitrate->val + 100000;
877                 break;
878         }
879         return 0;
880 }
881
882 static int hdpvr_s_ctrl(struct v4l2_ctrl *ctrl)
883 {
884         struct hdpvr_device *dev =
885                 container_of(ctrl->handler, struct hdpvr_device, hdl);
886         struct hdpvr_options *opt = &dev->options;
887         int ret = -EINVAL;
888
889         switch (ctrl->id) {
890         case V4L2_CID_BRIGHTNESS:
891                 ret = hdpvr_config_call(dev, CTRL_BRIGHTNESS, ctrl->val);
892                 if (ret)
893                         break;
894                 dev->options.brightness = ctrl->val;
895                 return 0;
896         case V4L2_CID_CONTRAST:
897                 ret = hdpvr_config_call(dev, CTRL_CONTRAST, ctrl->val);
898                 if (ret)
899                         break;
900                 dev->options.contrast = ctrl->val;
901                 return 0;
902         case V4L2_CID_SATURATION:
903                 ret = hdpvr_config_call(dev, CTRL_SATURATION, ctrl->val);
904                 if (ret)
905                         break;
906                 dev->options.saturation = ctrl->val;
907                 return 0;
908         case V4L2_CID_HUE:
909                 ret = hdpvr_config_call(dev, CTRL_HUE, ctrl->val);
910                 if (ret)
911                         break;
912                 dev->options.hue = ctrl->val;
913                 return 0;
914         case V4L2_CID_SHARPNESS:
915                 ret = hdpvr_config_call(dev, CTRL_SHARPNESS, ctrl->val);
916                 if (ret)
917                         break;
918                 dev->options.sharpness = ctrl->val;
919                 return 0;
920         case V4L2_CID_MPEG_AUDIO_ENCODING:
921                 if (dev->flags & HDPVR_FLAG_AC3_CAP) {
922                         opt->audio_codec = ctrl->val;
923                         return hdpvr_set_audio(dev, opt->audio_input + 1,
924                                               opt->audio_codec);
925                 }
926                 return 0;
927         case V4L2_CID_MPEG_VIDEO_ENCODING:
928                 return 0;
929 /*      case V4L2_CID_MPEG_VIDEO_B_FRAMES: */
930 /*              if (ctrl->value == 0 && !(opt->gop_mode & 0x2)) { */
931 /*                      opt->gop_mode |= 0x2; */
932 /*                      hdpvr_config_call(dev, CTRL_GOP_MODE_VALUE, */
933 /*                                        opt->gop_mode); */
934 /*              } */
935 /*              if (ctrl->value == 128 && opt->gop_mode & 0x2) { */
936 /*                      opt->gop_mode &= ~0x2; */
937 /*                      hdpvr_config_call(dev, CTRL_GOP_MODE_VALUE, */
938 /*                                        opt->gop_mode); */
939 /*              } */
940 /*              break; */
941         case V4L2_CID_MPEG_VIDEO_BITRATE_MODE: {
942                 uint peak_bitrate = dev->video_bitrate_peak->val / 100000;
943                 uint bitrate = dev->video_bitrate->val / 100000;
944
945                 if (ctrl->is_new) {
946                         if (ctrl->val == V4L2_MPEG_VIDEO_BITRATE_MODE_CBR)
947                                 opt->bitrate_mode = HDPVR_CONSTANT;
948                         else
949                                 opt->bitrate_mode = HDPVR_VARIABLE_AVERAGE;
950                         hdpvr_config_call(dev, CTRL_BITRATE_MODE_VALUE,
951                                           opt->bitrate_mode);
952                         v4l2_ctrl_activate(dev->video_bitrate_peak,
953                                 ctrl->val != V4L2_MPEG_VIDEO_BITRATE_MODE_CBR);
954                 }
955
956                 if (dev->video_bitrate_peak->is_new ||
957                     dev->video_bitrate->is_new) {
958                         opt->bitrate = bitrate;
959                         opt->peak_bitrate = peak_bitrate;
960                         hdpvr_set_bitrate(dev);
961                 }
962                 return 0;
963         }
964         case V4L2_CID_MPEG_STREAM_TYPE:
965                 return 0;
966         default:
967                 break;
968         }
969         return ret;
970 }
971
972 static int vidioc_enum_fmt_vid_cap(struct file *file, void *private_data,
973                                     struct v4l2_fmtdesc *f)
974 {
975         if (f->index != 0)
976                 return -EINVAL;
977
978         f->flags = V4L2_FMT_FLAG_COMPRESSED;
979         strncpy(f->description, "MPEG2-TS with AVC/AAC streams", 32);
980         f->pixelformat = V4L2_PIX_FMT_MPEG;
981
982         return 0;
983 }
984
985 static int vidioc_g_fmt_vid_cap(struct file *file, void *_fh,
986                                 struct v4l2_format *f)
987 {
988         struct hdpvr_device *dev = video_drvdata(file);
989         struct hdpvr_fh *fh = _fh;
990         int ret;
991
992         /*
993          * The original driver would always returns the current detected
994          * resolution as the format (and EFAULT if it couldn't be detected).
995          * With the introduction of VIDIOC_QUERY_DV_TIMINGS there is now a
996          * better way of doing this, but to stay compatible with existing
997          * applications we assume legacy mode every time an application opens
998          * the device. Only if one of the new DV_TIMINGS ioctls is called
999          * will the filehandle go into 'normal' mode where g_fmt returns the
1000          * last set format.
1001          */
1002         if (fh->legacy_mode) {
1003                 struct hdpvr_video_info vid_info;
1004
1005                 ret = get_video_info(dev, &vid_info);
1006                 if (ret < 0)
1007                         return ret;
1008                 if (!vid_info.valid)
1009                         return -EFAULT;
1010                 f->fmt.pix.width = vid_info.width;
1011                 f->fmt.pix.height = vid_info.height;
1012         } else {
1013                 f->fmt.pix.width = dev->width;
1014                 f->fmt.pix.height = dev->height;
1015         }
1016         f->fmt.pix.pixelformat  = V4L2_PIX_FMT_MPEG;
1017         f->fmt.pix.sizeimage    = dev->bulk_in_size;
1018         f->fmt.pix.bytesperline = 0;
1019         if (f->fmt.pix.width == 720) {
1020                 /* SDTV formats */
1021                 f->fmt.pix.colorspace = V4L2_COLORSPACE_SMPTE170M;
1022                 f->fmt.pix.field = V4L2_FIELD_INTERLACED;
1023         } else {
1024                 /* HDTV formats */
1025                 f->fmt.pix.colorspace = V4L2_COLORSPACE_REC709;
1026                 f->fmt.pix.field = V4L2_FIELD_NONE;
1027         }
1028         return 0;
1029 }
1030
1031 static int vidioc_encoder_cmd(struct file *filp, void *priv,
1032                                struct v4l2_encoder_cmd *a)
1033 {
1034         struct hdpvr_device *dev = video_drvdata(filp);
1035         int res = 0;
1036
1037         mutex_lock(&dev->io_mutex);
1038         a->flags = 0;
1039
1040         switch (a->cmd) {
1041         case V4L2_ENC_CMD_START:
1042                 if (dev->owner && filp->private_data != dev->owner) {
1043                         res = -EBUSY;
1044                         break;
1045                 }
1046                 if (dev->status == STATUS_STREAMING)
1047                         break;
1048                 res = hdpvr_start_streaming(dev);
1049                 if (!res)
1050                         dev->owner = filp->private_data;
1051                 else
1052                         dev->status = STATUS_IDLE;
1053                 break;
1054         case V4L2_ENC_CMD_STOP:
1055                 if (dev->owner && filp->private_data != dev->owner) {
1056                         res = -EBUSY;
1057                         break;
1058                 }
1059                 if (dev->status == STATUS_IDLE)
1060                         break;
1061                 res = hdpvr_stop_streaming(dev);
1062                 if (!res)
1063                         dev->owner = NULL;
1064                 break;
1065         default:
1066                 v4l2_dbg(MSG_INFO, hdpvr_debug, &dev->v4l2_dev,
1067                          "Unsupported encoder cmd %d\n", a->cmd);
1068                 res = -EINVAL;
1069                 break;
1070         }
1071
1072         mutex_unlock(&dev->io_mutex);
1073         return res;
1074 }
1075
1076 static int vidioc_try_encoder_cmd(struct file *filp, void *priv,
1077                                         struct v4l2_encoder_cmd *a)
1078 {
1079         a->flags = 0;
1080         switch (a->cmd) {
1081         case V4L2_ENC_CMD_START:
1082         case V4L2_ENC_CMD_STOP:
1083                 return 0;
1084         default:
1085                 return -EINVAL;
1086         }
1087 }
1088
1089 static const struct v4l2_ioctl_ops hdpvr_ioctl_ops = {
1090         .vidioc_querycap        = vidioc_querycap,
1091         .vidioc_s_std           = vidioc_s_std,
1092         .vidioc_g_std           = vidioc_g_std,
1093         .vidioc_querystd        = vidioc_querystd,
1094         .vidioc_s_dv_timings    = vidioc_s_dv_timings,
1095         .vidioc_g_dv_timings    = vidioc_g_dv_timings,
1096         .vidioc_query_dv_timings= vidioc_query_dv_timings,
1097         .vidioc_enum_dv_timings = vidioc_enum_dv_timings,
1098         .vidioc_dv_timings_cap  = vidioc_dv_timings_cap,
1099         .vidioc_enum_input      = vidioc_enum_input,
1100         .vidioc_g_input         = vidioc_g_input,
1101         .vidioc_s_input         = vidioc_s_input,
1102         .vidioc_enumaudio       = vidioc_enumaudio,
1103         .vidioc_g_audio         = vidioc_g_audio,
1104         .vidioc_s_audio         = vidioc_s_audio,
1105         .vidioc_enum_fmt_vid_cap= vidioc_enum_fmt_vid_cap,
1106         .vidioc_g_fmt_vid_cap   = vidioc_g_fmt_vid_cap,
1107         .vidioc_s_fmt_vid_cap   = vidioc_g_fmt_vid_cap,
1108         .vidioc_try_fmt_vid_cap = vidioc_g_fmt_vid_cap,
1109         .vidioc_encoder_cmd     = vidioc_encoder_cmd,
1110         .vidioc_try_encoder_cmd = vidioc_try_encoder_cmd,
1111         .vidioc_log_status      = v4l2_ctrl_log_status,
1112         .vidioc_subscribe_event = v4l2_ctrl_subscribe_event,
1113         .vidioc_unsubscribe_event = v4l2_event_unsubscribe,
1114 };
1115
1116 static void hdpvr_device_release(struct video_device *vdev)
1117 {
1118         struct hdpvr_device *dev = video_get_drvdata(vdev);
1119
1120         hdpvr_delete(dev);
1121         mutex_lock(&dev->io_mutex);
1122         flush_work(&dev->worker);
1123         mutex_unlock(&dev->io_mutex);
1124
1125         v4l2_device_unregister(&dev->v4l2_dev);
1126         v4l2_ctrl_handler_free(&dev->hdl);
1127
1128         /* deregister I2C adapter */
1129 #if IS_ENABLED(CONFIG_I2C)
1130         mutex_lock(&dev->i2c_mutex);
1131         i2c_del_adapter(&dev->i2c_adapter);
1132         mutex_unlock(&dev->i2c_mutex);
1133 #endif /* CONFIG_I2C */
1134
1135         kfree(dev->usbc_buf);
1136         kfree(dev);
1137 }
1138
1139 static const struct video_device hdpvr_video_template = {
1140         .fops                   = &hdpvr_fops,
1141         .release                = hdpvr_device_release,
1142         .ioctl_ops              = &hdpvr_ioctl_ops,
1143         .tvnorms                = V4L2_STD_ALL,
1144 };
1145
1146 static const struct v4l2_ctrl_ops hdpvr_ctrl_ops = {
1147         .try_ctrl = hdpvr_try_ctrl,
1148         .s_ctrl = hdpvr_s_ctrl,
1149 };
1150
1151 int hdpvr_register_videodev(struct hdpvr_device *dev, struct device *parent,
1152                             int devnum)
1153 {
1154         struct v4l2_ctrl_handler *hdl = &dev->hdl;
1155         bool ac3 = dev->flags & HDPVR_FLAG_AC3_CAP;
1156         int res;
1157
1158         // initialize dev->worker
1159         INIT_WORK(&dev->worker, hdpvr_transmit_buffers);
1160
1161         dev->cur_std = V4L2_STD_525_60;
1162         dev->width = 720;
1163         dev->height = 480;
1164         dev->cur_dv_timings = hdpvr_dv_timings[HDPVR_DEF_DV_TIMINGS_IDX];
1165         v4l2_ctrl_handler_init(hdl, 11);
1166         if (dev->fw_ver > 0x15) {
1167                 v4l2_ctrl_new_std(hdl, &hdpvr_ctrl_ops,
1168                         V4L2_CID_BRIGHTNESS, 0x0, 0xff, 1, 0x80);
1169                 v4l2_ctrl_new_std(hdl, &hdpvr_ctrl_ops,
1170                         V4L2_CID_CONTRAST, 0x0, 0xff, 1, 0x40);
1171                 v4l2_ctrl_new_std(hdl, &hdpvr_ctrl_ops,
1172                         V4L2_CID_SATURATION, 0x0, 0xff, 1, 0x40);
1173                 v4l2_ctrl_new_std(hdl, &hdpvr_ctrl_ops,
1174                         V4L2_CID_HUE, 0x0, 0x1e, 1, 0xf);
1175                 v4l2_ctrl_new_std(hdl, &hdpvr_ctrl_ops,
1176                         V4L2_CID_SHARPNESS, 0x0, 0xff, 1, 0x80);
1177         } else {
1178                 v4l2_ctrl_new_std(hdl, &hdpvr_ctrl_ops,
1179                         V4L2_CID_BRIGHTNESS, 0x0, 0xff, 1, 0x86);
1180                 v4l2_ctrl_new_std(hdl, &hdpvr_ctrl_ops,
1181                         V4L2_CID_CONTRAST, 0x0, 0xff, 1, 0x80);
1182                 v4l2_ctrl_new_std(hdl, &hdpvr_ctrl_ops,
1183                         V4L2_CID_SATURATION, 0x0, 0xff, 1, 0x80);
1184                 v4l2_ctrl_new_std(hdl, &hdpvr_ctrl_ops,
1185                         V4L2_CID_HUE, 0x0, 0xff, 1, 0x80);
1186                 v4l2_ctrl_new_std(hdl, &hdpvr_ctrl_ops,
1187                         V4L2_CID_SHARPNESS, 0x0, 0xff, 1, 0x80);
1188         }
1189
1190         v4l2_ctrl_new_std_menu(hdl, &hdpvr_ctrl_ops,
1191                 V4L2_CID_MPEG_STREAM_TYPE,
1192                 V4L2_MPEG_STREAM_TYPE_MPEG2_TS,
1193                 0x1, V4L2_MPEG_STREAM_TYPE_MPEG2_TS);
1194         v4l2_ctrl_new_std_menu(hdl, &hdpvr_ctrl_ops,
1195                 V4L2_CID_MPEG_AUDIO_ENCODING,
1196                 ac3 ? V4L2_MPEG_AUDIO_ENCODING_AC3 : V4L2_MPEG_AUDIO_ENCODING_AAC,
1197                 0x7, ac3 ? dev->options.audio_codec : V4L2_MPEG_AUDIO_ENCODING_AAC);
1198         v4l2_ctrl_new_std_menu(hdl, &hdpvr_ctrl_ops,
1199                 V4L2_CID_MPEG_VIDEO_ENCODING,
1200                 V4L2_MPEG_VIDEO_ENCODING_MPEG_4_AVC, 0x3,
1201                 V4L2_MPEG_VIDEO_ENCODING_MPEG_4_AVC);
1202
1203         dev->video_mode = v4l2_ctrl_new_std_menu(hdl, &hdpvr_ctrl_ops,
1204                 V4L2_CID_MPEG_VIDEO_BITRATE_MODE,
1205                 V4L2_MPEG_VIDEO_BITRATE_MODE_CBR, 0,
1206                 V4L2_MPEG_VIDEO_BITRATE_MODE_CBR);
1207
1208         dev->video_bitrate = v4l2_ctrl_new_std(hdl, &hdpvr_ctrl_ops,
1209                 V4L2_CID_MPEG_VIDEO_BITRATE,
1210                 1000000, 13500000, 100000, 6500000);
1211         dev->video_bitrate_peak = v4l2_ctrl_new_std(hdl, &hdpvr_ctrl_ops,
1212                 V4L2_CID_MPEG_VIDEO_BITRATE_PEAK,
1213                 1100000, 20200000, 100000, 9000000);
1214         dev->v4l2_dev.ctrl_handler = hdl;
1215         if (hdl->error) {
1216                 res = hdl->error;
1217                 v4l2_err(&dev->v4l2_dev, "Could not register controls\n");
1218                 goto error;
1219         }
1220         v4l2_ctrl_cluster(3, &dev->video_mode);
1221         res = v4l2_ctrl_handler_setup(hdl);
1222         if (res < 0) {
1223                 v4l2_err(&dev->v4l2_dev, "Could not setup controls\n");
1224                 goto error;
1225         }
1226
1227         /* setup and register video device */
1228         dev->video_dev = hdpvr_video_template;
1229         strcpy(dev->video_dev.name, "Hauppauge HD PVR");
1230         dev->video_dev.v4l2_dev = &dev->v4l2_dev;
1231         video_set_drvdata(&dev->video_dev, dev);
1232
1233         res = video_register_device(&dev->video_dev, VFL_TYPE_GRABBER, devnum);
1234         if (res < 0) {
1235                 v4l2_err(&dev->v4l2_dev, "video_device registration failed\n");
1236                 goto error;
1237         }
1238
1239         return 0;
1240 error:
1241         v4l2_ctrl_handler_free(hdl);
1242         return res;
1243 }