10f4d777f92255f8d2fcd5309d84f9af5d423505
[cascardo/linux.git] / drivers / media / pci / saa7164 / saa7164-encoder.c
1 /*
2  *  Driver for the NXP SAA7164 PCIe bridge
3  *
4  *  Copyright (c) 2010-2015 Steven Toth <stoth@kernellabs.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  *
15  *  GNU General Public License for more details.
16  *
17  *  You should have received a copy of the GNU General Public License
18  *  along with this program; if not, write to the Free Software
19  *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20  */
21
22 #include "saa7164.h"
23
24 #define ENCODER_MAX_BITRATE 6500000
25 #define ENCODER_MIN_BITRATE 1000000
26 #define ENCODER_DEF_BITRATE 5000000
27
28 /*
29  * This is a dummy non-zero value for the sizeimage field of v4l2_pix_format.
30  * It is not actually used for anything since this driver does not support
31  * stream I/O, only read(), and because this driver produces an MPEG stream
32  * and not discrete frames. But the V4L2 spec doesn't allow for this value
33  * to be 0, so set it to 0x10000 instead.
34  *
35  * If we ever change this driver to support stream I/O, then this field
36  * will be the size of the streaming buffers.
37  */
38 #define SAA7164_SIZEIMAGE (0x10000)
39
40 static struct saa7164_tvnorm saa7164_tvnorms[] = {
41         {
42                 .name      = "NTSC-M",
43                 .id        = V4L2_STD_NTSC_M,
44         }, {
45                 .name      = "NTSC-JP",
46                 .id        = V4L2_STD_NTSC_M_JP,
47         }
48 };
49
50 /* Take the encoder configuration form the port struct and
51  * flush it to the hardware.
52  */
53 static void saa7164_encoder_configure(struct saa7164_port *port)
54 {
55         struct saa7164_dev *dev = port->dev;
56         dprintk(DBGLVL_ENC, "%s()\n", __func__);
57
58         port->encoder_params.width = port->width;
59         port->encoder_params.height = port->height;
60         port->encoder_params.is_50hz =
61                 (port->encodernorm.id & V4L2_STD_625_50) != 0;
62
63         /* Set up the DIF (enable it) for analog mode by default */
64         saa7164_api_initialize_dif(port);
65
66         /* Configure the correct video standard */
67         saa7164_api_configure_dif(port, port->encodernorm.id);
68
69         /* Ensure the audio decoder is correct configured */
70         saa7164_api_set_audio_std(port);
71 }
72
73 static int saa7164_encoder_buffers_dealloc(struct saa7164_port *port)
74 {
75         struct list_head *c, *n, *p, *q, *l, *v;
76         struct saa7164_dev *dev = port->dev;
77         struct saa7164_buffer *buf;
78         struct saa7164_user_buffer *ubuf;
79
80         /* Remove any allocated buffers */
81         mutex_lock(&port->dmaqueue_lock);
82
83         dprintk(DBGLVL_ENC, "%s(port=%d) dmaqueue\n", __func__, port->nr);
84         list_for_each_safe(c, n, &port->dmaqueue.list) {
85                 buf = list_entry(c, struct saa7164_buffer, list);
86                 list_del(c);
87                 saa7164_buffer_dealloc(buf);
88         }
89
90         dprintk(DBGLVL_ENC, "%s(port=%d) used\n", __func__, port->nr);
91         list_for_each_safe(p, q, &port->list_buf_used.list) {
92                 ubuf = list_entry(p, struct saa7164_user_buffer, list);
93                 list_del(p);
94                 saa7164_buffer_dealloc_user(ubuf);
95         }
96
97         dprintk(DBGLVL_ENC, "%s(port=%d) free\n", __func__, port->nr);
98         list_for_each_safe(l, v, &port->list_buf_free.list) {
99                 ubuf = list_entry(l, struct saa7164_user_buffer, list);
100                 list_del(l);
101                 saa7164_buffer_dealloc_user(ubuf);
102         }
103
104         mutex_unlock(&port->dmaqueue_lock);
105         dprintk(DBGLVL_ENC, "%s(port=%d) done\n", __func__, port->nr);
106
107         return 0;
108 }
109
110 /* Dynamic buffer switch at encoder start time */
111 static int saa7164_encoder_buffers_alloc(struct saa7164_port *port)
112 {
113         struct saa7164_dev *dev = port->dev;
114         struct saa7164_buffer *buf;
115         struct saa7164_user_buffer *ubuf;
116         struct tmHWStreamParameters *params = &port->hw_streamingparams;
117         int result = -ENODEV, i;
118         int len = 0;
119
120         dprintk(DBGLVL_ENC, "%s()\n", __func__);
121
122         if (port->encoder_params.stream_type ==
123                 V4L2_MPEG_STREAM_TYPE_MPEG2_PS) {
124                 dprintk(DBGLVL_ENC,
125                         "%s() type=V4L2_MPEG_STREAM_TYPE_MPEG2_PS\n",
126                         __func__);
127                 params->samplesperline = 128;
128                 params->numberoflines = 256;
129                 params->pitch = 128;
130                 params->numpagetables = 2 +
131                         ((SAA7164_PS_NUMBER_OF_LINES * 128) / PAGE_SIZE);
132         } else
133         if (port->encoder_params.stream_type ==
134                 V4L2_MPEG_STREAM_TYPE_MPEG2_TS) {
135                 dprintk(DBGLVL_ENC,
136                         "%s() type=V4L2_MPEG_STREAM_TYPE_MPEG2_TS\n",
137                         __func__);
138                 params->samplesperline = 188;
139                 params->numberoflines = 312;
140                 params->pitch = 188;
141                 params->numpagetables = 2 +
142                         ((SAA7164_TS_NUMBER_OF_LINES * 188) / PAGE_SIZE);
143         } else
144                 BUG();
145
146         /* Init and establish defaults */
147         params->bitspersample = 8;
148         params->linethreshold = 0;
149         params->pagetablelistvirt = NULL;
150         params->pagetablelistphys = NULL;
151         params->numpagetableentries = port->hwcfg.buffercount;
152
153         /* Allocate the PCI resources, buffers (hard) */
154         for (i = 0; i < port->hwcfg.buffercount; i++) {
155                 buf = saa7164_buffer_alloc(port,
156                         params->numberoflines *
157                         params->pitch);
158
159                 if (!buf) {
160                         printk(KERN_ERR "%s() failed "
161                                "(errno = %d), unable to allocate buffer\n",
162                                 __func__, result);
163                         result = -ENOMEM;
164                         goto failed;
165                 } else {
166
167                         mutex_lock(&port->dmaqueue_lock);
168                         list_add_tail(&buf->list, &port->dmaqueue.list);
169                         mutex_unlock(&port->dmaqueue_lock);
170
171                 }
172         }
173
174         /* Allocate some kernel buffers for copying
175          * to userpsace.
176          */
177         len = params->numberoflines * params->pitch;
178
179         if (encoder_buffers < 16)
180                 encoder_buffers = 16;
181         if (encoder_buffers > 512)
182                 encoder_buffers = 512;
183
184         for (i = 0; i < encoder_buffers; i++) {
185
186                 ubuf = saa7164_buffer_alloc_user(dev, len);
187                 if (ubuf) {
188                         mutex_lock(&port->dmaqueue_lock);
189                         list_add_tail(&ubuf->list, &port->list_buf_free.list);
190                         mutex_unlock(&port->dmaqueue_lock);
191                 }
192
193         }
194
195         result = 0;
196
197 failed:
198         return result;
199 }
200
201 static int saa7164_encoder_initialize(struct saa7164_port *port)
202 {
203         saa7164_encoder_configure(port);
204         return 0;
205 }
206
207 /* -- V4L2 --------------------------------------------------------- */
208 static int vidioc_s_std(struct file *file, void *priv, v4l2_std_id id)
209 {
210         struct saa7164_encoder_fh *fh = file->private_data;
211         struct saa7164_port *port = fh->port;
212         struct saa7164_dev *dev = port->dev;
213         unsigned int i;
214
215         dprintk(DBGLVL_ENC, "%s(id=0x%x)\n", __func__, (u32)id);
216
217         for (i = 0; i < ARRAY_SIZE(saa7164_tvnorms); i++) {
218                 if (id & saa7164_tvnorms[i].id)
219                         break;
220         }
221         if (i == ARRAY_SIZE(saa7164_tvnorms))
222                 return -EINVAL;
223
224         port->encodernorm = saa7164_tvnorms[i];
225         port->std = id;
226
227         /* Update the audio decoder while is not running in
228          * auto detect mode.
229          */
230         saa7164_api_set_audio_std(port);
231
232         dprintk(DBGLVL_ENC, "%s(id=0x%x) OK\n", __func__, (u32)id);
233
234         return 0;
235 }
236
237 static int vidioc_g_std(struct file *file, void *priv, v4l2_std_id *id)
238 {
239         struct saa7164_encoder_fh *fh = file->private_data;
240         struct saa7164_port *port = fh->port;
241
242         *id = port->std;
243         return 0;
244 }
245
246 static int vidioc_enum_input(struct file *file, void *priv,
247         struct v4l2_input *i)
248 {
249         int n;
250
251         char *inputs[] = { "tuner", "composite", "svideo", "aux",
252                 "composite 2", "svideo 2", "aux 2" };
253
254         if (i->index >= 7)
255                 return -EINVAL;
256
257         strcpy(i->name, inputs[i->index]);
258
259         if (i->index == 0)
260                 i->type = V4L2_INPUT_TYPE_TUNER;
261         else
262                 i->type  = V4L2_INPUT_TYPE_CAMERA;
263
264         for (n = 0; n < ARRAY_SIZE(saa7164_tvnorms); n++)
265                 i->std |= saa7164_tvnorms[n].id;
266
267         return 0;
268 }
269
270 static int vidioc_g_input(struct file *file, void *priv, unsigned int *i)
271 {
272         struct saa7164_encoder_fh *fh = file->private_data;
273         struct saa7164_port *port = fh->port;
274         struct saa7164_dev *dev = port->dev;
275
276         if (saa7164_api_get_videomux(port) != SAA_OK)
277                 return -EIO;
278
279         *i = (port->mux_input - 1);
280
281         dprintk(DBGLVL_ENC, "%s() input=%d\n", __func__, *i);
282
283         return 0;
284 }
285
286 static int vidioc_s_input(struct file *file, void *priv, unsigned int i)
287 {
288         struct saa7164_encoder_fh *fh = file->private_data;
289         struct saa7164_port *port = fh->port;
290         struct saa7164_dev *dev = port->dev;
291
292         dprintk(DBGLVL_ENC, "%s() input=%d\n", __func__, i);
293
294         if (i >= 7)
295                 return -EINVAL;
296
297         port->mux_input = i + 1;
298
299         if (saa7164_api_set_videomux(port) != SAA_OK)
300                 return -EIO;
301
302         return 0;
303 }
304
305 static int vidioc_g_tuner(struct file *file, void *priv,
306         struct v4l2_tuner *t)
307 {
308         struct saa7164_encoder_fh *fh = file->private_data;
309         struct saa7164_port *port = fh->port;
310         struct saa7164_dev *dev = port->dev;
311
312         if (0 != t->index)
313                 return -EINVAL;
314
315         strcpy(t->name, "tuner");
316         t->type = V4L2_TUNER_ANALOG_TV;
317         t->capability = V4L2_TUNER_CAP_NORM | V4L2_TUNER_CAP_STEREO;
318
319         dprintk(DBGLVL_ENC, "VIDIOC_G_TUNER: tuner type %d\n", t->type);
320
321         return 0;
322 }
323
324 static int vidioc_s_tuner(struct file *file, void *priv,
325         const struct v4l2_tuner *t)
326 {
327         /* Update the A/V core */
328         return 0;
329 }
330
331 static int vidioc_g_frequency(struct file *file, void *priv,
332         struct v4l2_frequency *f)
333 {
334         struct saa7164_encoder_fh *fh = file->private_data;
335         struct saa7164_port *port = fh->port;
336
337         f->type = V4L2_TUNER_ANALOG_TV;
338         f->frequency = port->freq;
339
340         return 0;
341 }
342
343 static int vidioc_s_frequency(struct file *file, void *priv,
344         const struct v4l2_frequency *f)
345 {
346         struct saa7164_encoder_fh *fh = file->private_data;
347         struct saa7164_port *port = fh->port;
348         struct saa7164_dev *dev = port->dev;
349         struct saa7164_port *tsport;
350         struct dvb_frontend *fe;
351
352         /* TODO: Pull this for the std */
353         struct analog_parameters params = {
354                 .mode      = V4L2_TUNER_ANALOG_TV,
355                 .audmode   = V4L2_TUNER_MODE_STEREO,
356                 .std       = port->encodernorm.id,
357                 .frequency = f->frequency
358         };
359
360         /* Stop the encoder */
361         dprintk(DBGLVL_ENC, "%s() frequency=%d tuner=%d\n", __func__,
362                 f->frequency, f->tuner);
363
364         if (f->tuner != 0)
365                 return -EINVAL;
366
367         if (f->type != V4L2_TUNER_ANALOG_TV)
368                 return -EINVAL;
369
370         port->freq = f->frequency;
371
372         /* Update the hardware */
373         if (port->nr == SAA7164_PORT_ENC1)
374                 tsport = &dev->ports[SAA7164_PORT_TS1];
375         else
376         if (port->nr == SAA7164_PORT_ENC2)
377                 tsport = &dev->ports[SAA7164_PORT_TS2];
378         else
379                 BUG();
380
381         fe = tsport->dvb.frontend;
382
383         if (fe && fe->ops.tuner_ops.set_analog_params)
384                 fe->ops.tuner_ops.set_analog_params(fe, &params);
385         else
386                 printk(KERN_ERR "%s() No analog tuner, aborting\n", __func__);
387
388         saa7164_encoder_initialize(port);
389
390         return 0;
391 }
392
393 static int saa7164_s_ctrl(struct v4l2_ctrl *ctrl)
394 {
395         struct saa7164_port *port =
396                 container_of(ctrl->handler, struct saa7164_port, ctrl_handler);
397         struct saa7164_encoder_params *params = &port->encoder_params;
398         int ret = 0;
399
400         switch (ctrl->id) {
401         case V4L2_CID_BRIGHTNESS:
402                 port->ctl_brightness = ctrl->val;
403                 saa7164_api_set_usercontrol(port, PU_BRIGHTNESS_CONTROL);
404                 break;
405         case V4L2_CID_CONTRAST:
406                 port->ctl_contrast = ctrl->val;
407                 saa7164_api_set_usercontrol(port, PU_CONTRAST_CONTROL);
408                 break;
409         case V4L2_CID_SATURATION:
410                 port->ctl_saturation = ctrl->val;
411                 saa7164_api_set_usercontrol(port, PU_SATURATION_CONTROL);
412                 break;
413         case V4L2_CID_HUE:
414                 port->ctl_hue = ctrl->val;
415                 saa7164_api_set_usercontrol(port, PU_HUE_CONTROL);
416                 break;
417         case V4L2_CID_SHARPNESS:
418                 port->ctl_sharpness = ctrl->val;
419                 saa7164_api_set_usercontrol(port, PU_SHARPNESS_CONTROL);
420                 break;
421         case V4L2_CID_AUDIO_VOLUME:
422                 port->ctl_volume = ctrl->val;
423                 saa7164_api_set_audio_volume(port, port->ctl_volume);
424                 break;
425         case V4L2_CID_MPEG_VIDEO_BITRATE:
426                 params->bitrate = ctrl->val;
427                 break;
428         case V4L2_CID_MPEG_STREAM_TYPE:
429                 params->stream_type = ctrl->val;
430                 break;
431         case V4L2_CID_MPEG_AUDIO_MUTE:
432                 params->ctl_mute = ctrl->val;
433                 ret = saa7164_api_audio_mute(port, params->ctl_mute);
434                 if (ret != SAA_OK) {
435                         printk(KERN_ERR "%s() error, ret = 0x%x\n", __func__,
436                                 ret);
437                         ret = -EIO;
438                 }
439                 break;
440         case V4L2_CID_MPEG_VIDEO_ASPECT:
441                 params->ctl_aspect = ctrl->val;
442                 ret = saa7164_api_set_aspect_ratio(port);
443                 if (ret != SAA_OK) {
444                         printk(KERN_ERR "%s() error, ret = 0x%x\n", __func__,
445                                 ret);
446                         ret = -EIO;
447                 }
448                 break;
449         case V4L2_CID_MPEG_VIDEO_BITRATE_MODE:
450                 params->bitrate_mode = ctrl->val;
451                 break;
452         case V4L2_CID_MPEG_VIDEO_B_FRAMES:
453                 params->refdist = ctrl->val;
454                 break;
455         case V4L2_CID_MPEG_VIDEO_BITRATE_PEAK:
456                 params->bitrate_peak = ctrl->val;
457                 break;
458         case V4L2_CID_MPEG_VIDEO_GOP_SIZE:
459                 params->gop_size = ctrl->val;
460                 break;
461         default:
462                 ret = -EINVAL;
463         }
464
465         return ret;
466 }
467
468 static int vidioc_querycap(struct file *file, void  *priv,
469         struct v4l2_capability *cap)
470 {
471         struct saa7164_encoder_fh *fh = file->private_data;
472         struct saa7164_port *port = fh->port;
473         struct saa7164_dev *dev = port->dev;
474
475         strcpy(cap->driver, dev->name);
476         strlcpy(cap->card, saa7164_boards[dev->board].name,
477                 sizeof(cap->card));
478         sprintf(cap->bus_info, "PCI:%s", pci_name(dev->pci));
479
480         cap->device_caps =
481                 V4L2_CAP_VIDEO_CAPTURE |
482                 V4L2_CAP_READWRITE |
483                 V4L2_CAP_TUNER;
484
485         cap->capabilities = cap->device_caps |
486                 V4L2_CAP_VBI_CAPTURE |
487                 V4L2_CAP_DEVICE_CAPS;
488
489         return 0;
490 }
491
492 static int vidioc_enum_fmt_vid_cap(struct file *file, void  *priv,
493         struct v4l2_fmtdesc *f)
494 {
495         if (f->index != 0)
496                 return -EINVAL;
497
498         strlcpy(f->description, "MPEG", sizeof(f->description));
499         f->pixelformat = V4L2_PIX_FMT_MPEG;
500
501         return 0;
502 }
503
504 static int vidioc_fmt_vid_cap(struct file *file, void *priv,
505                                 struct v4l2_format *f)
506 {
507         struct saa7164_encoder_fh *fh = file->private_data;
508         struct saa7164_port *port = fh->port;
509
510         f->fmt.pix.pixelformat  = V4L2_PIX_FMT_MPEG;
511         f->fmt.pix.bytesperline = 0;
512         f->fmt.pix.sizeimage    = SAA7164_SIZEIMAGE;
513         f->fmt.pix.field        = V4L2_FIELD_INTERLACED;
514         f->fmt.pix.colorspace   = V4L2_COLORSPACE_SMPTE170M;
515         f->fmt.pix.width        = port->width;
516         f->fmt.pix.height       = port->height;
517         return 0;
518 }
519
520 static int saa7164_encoder_stop_port(struct saa7164_port *port)
521 {
522         struct saa7164_dev *dev = port->dev;
523         int ret;
524
525         ret = saa7164_api_transition_port(port, SAA_DMASTATE_STOP);
526         if ((ret != SAA_OK) && (ret != SAA_ERR_ALREADY_STOPPED)) {
527                 printk(KERN_ERR "%s() stop transition failed, ret = 0x%x\n",
528                         __func__, ret);
529                 ret = -EIO;
530         } else {
531                 dprintk(DBGLVL_ENC, "%s()    Stopped\n", __func__);
532                 ret = 0;
533         }
534
535         return ret;
536 }
537
538 static int saa7164_encoder_acquire_port(struct saa7164_port *port)
539 {
540         struct saa7164_dev *dev = port->dev;
541         int ret;
542
543         ret = saa7164_api_transition_port(port, SAA_DMASTATE_ACQUIRE);
544         if ((ret != SAA_OK) && (ret != SAA_ERR_ALREADY_STOPPED)) {
545                 printk(KERN_ERR "%s() acquire transition failed, ret = 0x%x\n",
546                         __func__, ret);
547                 ret = -EIO;
548         } else {
549                 dprintk(DBGLVL_ENC, "%s() Acquired\n", __func__);
550                 ret = 0;
551         }
552
553         return ret;
554 }
555
556 static int saa7164_encoder_pause_port(struct saa7164_port *port)
557 {
558         struct saa7164_dev *dev = port->dev;
559         int ret;
560
561         ret = saa7164_api_transition_port(port, SAA_DMASTATE_PAUSE);
562         if ((ret != SAA_OK) && (ret != SAA_ERR_ALREADY_STOPPED)) {
563                 printk(KERN_ERR "%s() pause transition failed, ret = 0x%x\n",
564                         __func__, ret);
565                 ret = -EIO;
566         } else {
567                 dprintk(DBGLVL_ENC, "%s()   Paused\n", __func__);
568                 ret = 0;
569         }
570
571         return ret;
572 }
573
574 /* Firmware is very windows centric, meaning you have to transition
575  * the part through AVStream / KS Windows stages, forwards or backwards.
576  * States are: stopped, acquired (h/w), paused, started.
577  * We have to leave here will all of the soft buffers on the free list,
578  * else the cfg_post() func won't have soft buffers to correctly configure.
579  */
580 static int saa7164_encoder_stop_streaming(struct saa7164_port *port)
581 {
582         struct saa7164_dev *dev = port->dev;
583         struct saa7164_buffer *buf;
584         struct saa7164_user_buffer *ubuf;
585         struct list_head *c, *n;
586         int ret;
587
588         dprintk(DBGLVL_ENC, "%s(port=%d)\n", __func__, port->nr);
589
590         ret = saa7164_encoder_pause_port(port);
591         ret = saa7164_encoder_acquire_port(port);
592         ret = saa7164_encoder_stop_port(port);
593
594         dprintk(DBGLVL_ENC, "%s(port=%d) Hardware stopped\n", __func__,
595                 port->nr);
596
597         /* Reset the state of any allocated buffer resources */
598         mutex_lock(&port->dmaqueue_lock);
599
600         /* Reset the hard and soft buffer state */
601         list_for_each_safe(c, n, &port->dmaqueue.list) {
602                 buf = list_entry(c, struct saa7164_buffer, list);
603                 buf->flags = SAA7164_BUFFER_FREE;
604                 buf->pos = 0;
605         }
606
607         list_for_each_safe(c, n, &port->list_buf_used.list) {
608                 ubuf = list_entry(c, struct saa7164_user_buffer, list);
609                 ubuf->pos = 0;
610                 list_move_tail(&ubuf->list, &port->list_buf_free.list);
611         }
612
613         mutex_unlock(&port->dmaqueue_lock);
614
615         /* Free any allocated resources */
616         saa7164_encoder_buffers_dealloc(port);
617
618         dprintk(DBGLVL_ENC, "%s(port=%d) Released\n", __func__, port->nr);
619
620         return ret;
621 }
622
623 static int saa7164_encoder_start_streaming(struct saa7164_port *port)
624 {
625         struct saa7164_dev *dev = port->dev;
626         int result, ret = 0;
627
628         dprintk(DBGLVL_ENC, "%s(port=%d)\n", __func__, port->nr);
629
630         port->done_first_interrupt = 0;
631
632         /* allocate all of the PCIe DMA buffer resources on the fly,
633          * allowing switching between TS and PS payloads without
634          * requiring a complete driver reload.
635          */
636         saa7164_encoder_buffers_alloc(port);
637
638         /* Configure the encoder with any cache values */
639         saa7164_api_set_encoder(port);
640         saa7164_api_get_encoder(port);
641
642         /* Place the empty buffers on the hardware */
643         saa7164_buffer_cfg_port(port);
644
645         /* Acquire the hardware */
646         result = saa7164_api_transition_port(port, SAA_DMASTATE_ACQUIRE);
647         if ((result != SAA_OK) && (result != SAA_ERR_ALREADY_STOPPED)) {
648                 printk(KERN_ERR "%s() acquire transition failed, res = 0x%x\n",
649                         __func__, result);
650
651                 /* Stop the hardware, regardless */
652                 result = saa7164_api_transition_port(port, SAA_DMASTATE_STOP);
653                 if ((result != SAA_OK) && (result != SAA_ERR_ALREADY_STOPPED)) {
654                         printk(KERN_ERR "%s() acquire/forced stop transition "
655                                 "failed, res = 0x%x\n", __func__, result);
656                 }
657                 ret = -EIO;
658                 goto out;
659         } else
660                 dprintk(DBGLVL_ENC, "%s()   Acquired\n", __func__);
661
662         /* Pause the hardware */
663         result = saa7164_api_transition_port(port, SAA_DMASTATE_PAUSE);
664         if ((result != SAA_OK) && (result != SAA_ERR_ALREADY_STOPPED)) {
665                 printk(KERN_ERR "%s() pause transition failed, res = 0x%x\n",
666                                 __func__, result);
667
668                 /* Stop the hardware, regardless */
669                 result = saa7164_api_transition_port(port, SAA_DMASTATE_STOP);
670                 if ((result != SAA_OK) && (result != SAA_ERR_ALREADY_STOPPED)) {
671                         printk(KERN_ERR "%s() pause/forced stop transition "
672                                 "failed, res = 0x%x\n", __func__, result);
673                 }
674
675                 ret = -EIO;
676                 goto out;
677         } else
678                 dprintk(DBGLVL_ENC, "%s()   Paused\n", __func__);
679
680         /* Start the hardware */
681         result = saa7164_api_transition_port(port, SAA_DMASTATE_RUN);
682         if ((result != SAA_OK) && (result != SAA_ERR_ALREADY_STOPPED)) {
683                 printk(KERN_ERR "%s() run transition failed, result = 0x%x\n",
684                                 __func__, result);
685
686                 /* Stop the hardware, regardless */
687                 result = saa7164_api_transition_port(port, SAA_DMASTATE_STOP);
688                 if ((result != SAA_OK) && (result != SAA_ERR_ALREADY_STOPPED)) {
689                         printk(KERN_ERR "%s() run/forced stop transition "
690                                 "failed, res = 0x%x\n", __func__, result);
691                 }
692
693                 ret = -EIO;
694         } else
695                 dprintk(DBGLVL_ENC, "%s()   Running\n", __func__);
696
697 out:
698         return ret;
699 }
700
701 static int fops_open(struct file *file)
702 {
703         struct saa7164_dev *dev;
704         struct saa7164_port *port;
705         struct saa7164_encoder_fh *fh;
706
707         port = (struct saa7164_port *)video_get_drvdata(video_devdata(file));
708         if (!port)
709                 return -ENODEV;
710
711         dev = port->dev;
712
713         dprintk(DBGLVL_ENC, "%s()\n", __func__);
714
715         /* allocate + initialize per filehandle data */
716         fh = kzalloc(sizeof(*fh), GFP_KERNEL);
717         if (NULL == fh)
718                 return -ENOMEM;
719
720         fh->port = port;
721         v4l2_fh_init(&fh->fh, video_devdata(file));
722         v4l2_fh_add(&fh->fh);
723         file->private_data = fh;
724
725         return 0;
726 }
727
728 static int fops_release(struct file *file)
729 {
730         struct saa7164_encoder_fh *fh = file->private_data;
731         struct saa7164_port *port = fh->port;
732         struct saa7164_dev *dev = port->dev;
733
734         dprintk(DBGLVL_ENC, "%s()\n", __func__);
735
736         /* Shut device down on last close */
737         if (atomic_cmpxchg(&fh->v4l_reading, 1, 0) == 1) {
738                 if (atomic_dec_return(&port->v4l_reader_count) == 0) {
739                         /* stop mpeg capture then cancel buffers */
740                         saa7164_encoder_stop_streaming(port);
741                 }
742         }
743
744         v4l2_fh_del(&fh->fh);
745         v4l2_fh_exit(&fh->fh);
746         kfree(fh);
747
748         return 0;
749 }
750
751 static struct
752 saa7164_user_buffer *saa7164_enc_next_buf(struct saa7164_port *port)
753 {
754         struct saa7164_user_buffer *ubuf = NULL;
755         struct saa7164_dev *dev = port->dev;
756         u32 crc;
757
758         mutex_lock(&port->dmaqueue_lock);
759         if (!list_empty(&port->list_buf_used.list)) {
760                 ubuf = list_first_entry(&port->list_buf_used.list,
761                         struct saa7164_user_buffer, list);
762
763                 if (crc_checking) {
764                         crc = crc32(0, ubuf->data, ubuf->actual_size);
765                         if (crc != ubuf->crc) {
766                                 printk(KERN_ERR
767                 "%s() ubuf %p crc became invalid, was 0x%x became 0x%x\n",
768                                         __func__,
769                                         ubuf, ubuf->crc, crc);
770                         }
771                 }
772
773         }
774         mutex_unlock(&port->dmaqueue_lock);
775
776         dprintk(DBGLVL_ENC, "%s() returns %p\n", __func__, ubuf);
777
778         return ubuf;
779 }
780
781 static ssize_t fops_read(struct file *file, char __user *buffer,
782         size_t count, loff_t *pos)
783 {
784         struct saa7164_encoder_fh *fh = file->private_data;
785         struct saa7164_port *port = fh->port;
786         struct saa7164_user_buffer *ubuf = NULL;
787         struct saa7164_dev *dev = port->dev;
788         int ret = 0;
789         int rem, cnt;
790         u8 *p;
791
792         port->last_read_msecs_diff = port->last_read_msecs;
793         port->last_read_msecs = jiffies_to_msecs(jiffies);
794         port->last_read_msecs_diff = port->last_read_msecs -
795                 port->last_read_msecs_diff;
796
797         saa7164_histogram_update(&port->read_interval,
798                 port->last_read_msecs_diff);
799
800         if (*pos) {
801                 printk(KERN_ERR "%s() ESPIPE\n", __func__);
802                 return -ESPIPE;
803         }
804
805         if (atomic_cmpxchg(&fh->v4l_reading, 0, 1) == 0) {
806                 if (atomic_inc_return(&port->v4l_reader_count) == 1) {
807
808                         if (saa7164_encoder_initialize(port) < 0) {
809                                 printk(KERN_ERR "%s() EINVAL\n", __func__);
810                                 return -EINVAL;
811                         }
812
813                         saa7164_encoder_start_streaming(port);
814                         msleep(200);
815                 }
816         }
817
818         /* blocking wait for buffer */
819         if ((file->f_flags & O_NONBLOCK) == 0) {
820                 if (wait_event_interruptible(port->wait_read,
821                         saa7164_enc_next_buf(port))) {
822                                 printk(KERN_ERR "%s() ERESTARTSYS\n", __func__);
823                                 return -ERESTARTSYS;
824                 }
825         }
826
827         /* Pull the first buffer from the used list */
828         ubuf = saa7164_enc_next_buf(port);
829
830         while ((count > 0) && ubuf) {
831
832                 /* set remaining bytes to copy */
833                 rem = ubuf->actual_size - ubuf->pos;
834                 cnt = rem > count ? count : rem;
835
836                 p = ubuf->data + ubuf->pos;
837
838                 dprintk(DBGLVL_ENC,
839                         "%s() count=%d cnt=%d rem=%d buf=%p buf->pos=%d\n",
840                         __func__, (int)count, cnt, rem, ubuf, ubuf->pos);
841
842                 if (copy_to_user(buffer, p, cnt)) {
843                         printk(KERN_ERR "%s() copy_to_user failed\n", __func__);
844                         if (!ret) {
845                                 printk(KERN_ERR "%s() EFAULT\n", __func__);
846                                 ret = -EFAULT;
847                         }
848                         goto err;
849                 }
850
851                 ubuf->pos += cnt;
852                 count -= cnt;
853                 buffer += cnt;
854                 ret += cnt;
855
856                 if (ubuf->pos > ubuf->actual_size)
857                         printk(KERN_ERR "read() pos > actual, huh?\n");
858
859                 if (ubuf->pos == ubuf->actual_size) {
860
861                         /* finished with current buffer, take next buffer */
862
863                         /* Requeue the buffer on the free list */
864                         ubuf->pos = 0;
865
866                         mutex_lock(&port->dmaqueue_lock);
867                         list_move_tail(&ubuf->list, &port->list_buf_free.list);
868                         mutex_unlock(&port->dmaqueue_lock);
869
870                         /* Dequeue next */
871                         if ((file->f_flags & O_NONBLOCK) == 0) {
872                                 if (wait_event_interruptible(port->wait_read,
873                                         saa7164_enc_next_buf(port))) {
874                                                 break;
875                                 }
876                         }
877                         ubuf = saa7164_enc_next_buf(port);
878                 }
879         }
880 err:
881         if (!ret && !ubuf)
882                 ret = -EAGAIN;
883
884         return ret;
885 }
886
887 static unsigned int fops_poll(struct file *file, poll_table *wait)
888 {
889         unsigned long req_events = poll_requested_events(wait);
890         struct saa7164_encoder_fh *fh =
891                 (struct saa7164_encoder_fh *)file->private_data;
892         struct saa7164_port *port = fh->port;
893         unsigned int mask = v4l2_ctrl_poll(file, wait);
894
895         port->last_poll_msecs_diff = port->last_poll_msecs;
896         port->last_poll_msecs = jiffies_to_msecs(jiffies);
897         port->last_poll_msecs_diff = port->last_poll_msecs -
898                 port->last_poll_msecs_diff;
899
900         saa7164_histogram_update(&port->poll_interval,
901                 port->last_poll_msecs_diff);
902
903         if (!(req_events & (POLLIN | POLLRDNORM)))
904                 return mask;
905
906         if (atomic_cmpxchg(&fh->v4l_reading, 0, 1) == 0) {
907                 if (atomic_inc_return(&port->v4l_reader_count) == 1) {
908                         if (saa7164_encoder_initialize(port) < 0)
909                                 return mask | POLLERR;
910                         saa7164_encoder_start_streaming(port);
911                         msleep(200);
912                 }
913         }
914
915         /* Pull the first buffer from the used list */
916         if (!list_empty(&port->list_buf_used.list))
917                 mask |= POLLIN | POLLRDNORM;
918
919         return mask;
920 }
921
922 static const struct v4l2_ctrl_ops saa7164_ctrl_ops = {
923         .s_ctrl = saa7164_s_ctrl,
924 };
925
926 static const struct v4l2_file_operations mpeg_fops = {
927         .owner          = THIS_MODULE,
928         .open           = fops_open,
929         .release        = fops_release,
930         .read           = fops_read,
931         .poll           = fops_poll,
932         .unlocked_ioctl = video_ioctl2,
933 };
934
935 static const struct v4l2_ioctl_ops mpeg_ioctl_ops = {
936         .vidioc_s_std            = vidioc_s_std,
937         .vidioc_g_std            = vidioc_g_std,
938         .vidioc_enum_input       = vidioc_enum_input,
939         .vidioc_g_input          = vidioc_g_input,
940         .vidioc_s_input          = vidioc_s_input,
941         .vidioc_g_tuner          = vidioc_g_tuner,
942         .vidioc_s_tuner          = vidioc_s_tuner,
943         .vidioc_g_frequency      = vidioc_g_frequency,
944         .vidioc_s_frequency      = vidioc_s_frequency,
945         .vidioc_querycap         = vidioc_querycap,
946         .vidioc_enum_fmt_vid_cap = vidioc_enum_fmt_vid_cap,
947         .vidioc_g_fmt_vid_cap    = vidioc_fmt_vid_cap,
948         .vidioc_try_fmt_vid_cap  = vidioc_fmt_vid_cap,
949         .vidioc_s_fmt_vid_cap    = vidioc_fmt_vid_cap,
950         .vidioc_log_status       = v4l2_ctrl_log_status,
951         .vidioc_subscribe_event  = v4l2_ctrl_subscribe_event,
952         .vidioc_unsubscribe_event = v4l2_event_unsubscribe,
953 };
954
955 static struct video_device saa7164_mpeg_template = {
956         .name          = "saa7164",
957         .fops          = &mpeg_fops,
958         .ioctl_ops     = &mpeg_ioctl_ops,
959         .minor         = -1,
960         .tvnorms       = SAA7164_NORMS,
961 };
962
963 static struct video_device *saa7164_encoder_alloc(
964         struct saa7164_port *port,
965         struct pci_dev *pci,
966         struct video_device *template,
967         char *type)
968 {
969         struct video_device *vfd;
970         struct saa7164_dev *dev = port->dev;
971
972         dprintk(DBGLVL_ENC, "%s()\n", __func__);
973
974         vfd = video_device_alloc();
975         if (NULL == vfd)
976                 return NULL;
977
978         *vfd = *template;
979         snprintf(vfd->name, sizeof(vfd->name), "%s %s (%s)", dev->name,
980                 type, saa7164_boards[dev->board].name);
981
982         vfd->v4l2_dev  = &dev->v4l2_dev;
983         vfd->release = video_device_release;
984         return vfd;
985 }
986
987 int saa7164_encoder_register(struct saa7164_port *port)
988 {
989         struct saa7164_dev *dev = port->dev;
990         struct v4l2_ctrl_handler *hdl = &port->ctrl_handler;
991         int result = -ENODEV;
992
993         dprintk(DBGLVL_ENC, "%s()\n", __func__);
994
995         if (port->type != SAA7164_MPEG_ENCODER)
996                 BUG();
997
998         /* Sanity check that the PCI configuration space is active */
999         if (port->hwcfg.BARLocation == 0) {
1000                 printk(KERN_ERR "%s() failed "
1001                        "(errno = %d), NO PCI configuration\n",
1002                         __func__, result);
1003                 result = -ENOMEM;
1004                 goto failed;
1005         }
1006
1007         /* Establish encoder defaults here */
1008         /* Set default TV standard */
1009         port->encodernorm = saa7164_tvnorms[0];
1010         port->width = 720;
1011         port->mux_input = 1; /* Composite */
1012         port->video_format = EU_VIDEO_FORMAT_MPEG_2;
1013         port->audio_format = 0;
1014         port->video_resolution = 0;
1015
1016         v4l2_ctrl_handler_init(hdl, 14);
1017         v4l2_ctrl_new_std(hdl, &saa7164_ctrl_ops,
1018                           V4L2_CID_BRIGHTNESS, 0, 255, 1, 127);
1019         v4l2_ctrl_new_std(hdl, &saa7164_ctrl_ops,
1020                           V4L2_CID_CONTRAST, 0, 255, 1, 66);
1021         v4l2_ctrl_new_std(hdl, &saa7164_ctrl_ops,
1022                           V4L2_CID_SATURATION, 0, 255, 1, 62);
1023         v4l2_ctrl_new_std(hdl, &saa7164_ctrl_ops,
1024                           V4L2_CID_HUE, 0, 255, 1, 128);
1025         v4l2_ctrl_new_std(hdl, &saa7164_ctrl_ops,
1026                           V4L2_CID_SHARPNESS, 0x0, 0x0f, 1, 8);
1027         v4l2_ctrl_new_std(hdl, &saa7164_ctrl_ops,
1028                           V4L2_CID_MPEG_AUDIO_MUTE, 0x0, 0x01, 1, 0);
1029         v4l2_ctrl_new_std(hdl, &saa7164_ctrl_ops,
1030                           V4L2_CID_AUDIO_VOLUME, -83, 24, 1, 20);
1031         v4l2_ctrl_new_std(hdl, &saa7164_ctrl_ops,
1032                           V4L2_CID_MPEG_VIDEO_BITRATE,
1033                           ENCODER_MIN_BITRATE, ENCODER_MAX_BITRATE,
1034                           100000, ENCODER_DEF_BITRATE);
1035         v4l2_ctrl_new_std_menu(hdl, &saa7164_ctrl_ops,
1036                                V4L2_CID_MPEG_STREAM_TYPE,
1037                                V4L2_MPEG_STREAM_TYPE_MPEG2_TS, 0,
1038                                V4L2_MPEG_STREAM_TYPE_MPEG2_PS);
1039         v4l2_ctrl_new_std_menu(hdl, &saa7164_ctrl_ops,
1040                                V4L2_CID_MPEG_VIDEO_ASPECT,
1041                                V4L2_MPEG_VIDEO_ASPECT_221x100, 0,
1042                                V4L2_MPEG_VIDEO_ASPECT_4x3);
1043         v4l2_ctrl_new_std(hdl, &saa7164_ctrl_ops,
1044                           V4L2_CID_MPEG_VIDEO_GOP_SIZE, 1, 255, 1, 15);
1045         v4l2_ctrl_new_std_menu(hdl, &saa7164_ctrl_ops,
1046                                V4L2_CID_MPEG_VIDEO_BITRATE_MODE,
1047                                V4L2_MPEG_VIDEO_BITRATE_MODE_CBR, 0,
1048                                V4L2_MPEG_VIDEO_BITRATE_MODE_VBR);
1049         v4l2_ctrl_new_std(hdl, &saa7164_ctrl_ops,
1050                           V4L2_CID_MPEG_VIDEO_B_FRAMES, 1, 3, 1, 1);
1051         v4l2_ctrl_new_std(hdl, &saa7164_ctrl_ops,
1052                           V4L2_CID_MPEG_VIDEO_BITRATE_PEAK,
1053                           ENCODER_MIN_BITRATE, ENCODER_MAX_BITRATE,
1054                           100000, ENCODER_DEF_BITRATE);
1055         if (hdl->error) {
1056                 result = hdl->error;
1057                 goto failed;
1058         }
1059
1060         port->std = V4L2_STD_NTSC_M;
1061
1062         if (port->encodernorm.id & V4L2_STD_525_60)
1063                 port->height = 480;
1064         else
1065                 port->height = 576;
1066
1067         /* Allocate and register the video device node */
1068         port->v4l_device = saa7164_encoder_alloc(port,
1069                 dev->pci, &saa7164_mpeg_template, "mpeg");
1070
1071         if (!port->v4l_device) {
1072                 printk(KERN_INFO "%s: can't allocate mpeg device\n",
1073                         dev->name);
1074                 result = -ENOMEM;
1075                 goto failed;
1076         }
1077
1078         port->v4l_device->ctrl_handler = hdl;
1079         v4l2_ctrl_handler_setup(hdl);
1080         video_set_drvdata(port->v4l_device, port);
1081         result = video_register_device(port->v4l_device,
1082                 VFL_TYPE_GRABBER, -1);
1083         if (result < 0) {
1084                 printk(KERN_INFO "%s: can't register mpeg device\n",
1085                         dev->name);
1086                 /* TODO: We're going to leak here if we don't dealloc
1087                  The buffers above. The unreg function can't deal wit it.
1088                 */
1089                 goto failed;
1090         }
1091
1092         printk(KERN_INFO "%s: registered device video%d [mpeg]\n",
1093                 dev->name, port->v4l_device->num);
1094
1095         /* Configure the hardware defaults */
1096         saa7164_api_set_videomux(port);
1097         saa7164_api_set_usercontrol(port, PU_BRIGHTNESS_CONTROL);
1098         saa7164_api_set_usercontrol(port, PU_CONTRAST_CONTROL);
1099         saa7164_api_set_usercontrol(port, PU_HUE_CONTROL);
1100         saa7164_api_set_usercontrol(port, PU_SATURATION_CONTROL);
1101         saa7164_api_set_usercontrol(port, PU_SHARPNESS_CONTROL);
1102         saa7164_api_audio_mute(port, 0);
1103         saa7164_api_set_audio_volume(port, 20);
1104         saa7164_api_set_aspect_ratio(port);
1105
1106         /* Disable audio standard detection, it's buggy */
1107         saa7164_api_set_audio_detection(port, 0);
1108
1109         saa7164_api_set_encoder(port);
1110         saa7164_api_get_encoder(port);
1111
1112         result = 0;
1113 failed:
1114         return result;
1115 }
1116
1117 void saa7164_encoder_unregister(struct saa7164_port *port)
1118 {
1119         struct saa7164_dev *dev = port->dev;
1120
1121         dprintk(DBGLVL_ENC, "%s(port=%d)\n", __func__, port->nr);
1122
1123         if (port->type != SAA7164_MPEG_ENCODER)
1124                 BUG();
1125
1126         if (port->v4l_device) {
1127                 if (port->v4l_device->minor != -1)
1128                         video_unregister_device(port->v4l_device);
1129                 else
1130                         video_device_release(port->v4l_device);
1131
1132                 port->v4l_device = NULL;
1133         }
1134         v4l2_ctrl_handler_free(&port->ctrl_handler);
1135
1136         dprintk(DBGLVL_ENC, "%s(port=%d) done\n", __func__, port->nr);
1137 }
1138