1 /*
2     init/start/stop/exit stream functions
3     Copyright (C) 2003-2004  Kevin Thayer <nufan_wfk at yahoo.com>
4     Copyright (C) 2004  Chris Kennedy <c@groovy.org>
5     Copyright (C) 2005-2007  Hans Verkuil <hverkuil@xs4all.nl>
6 
7     This program is free software; you can redistribute it and/or modify
8     it under the terms of the GNU General Public License as published by
9     the Free Software Foundation; either version 2 of the License, or
10     (at your option) any later version.
11 
12     This program is distributed in the hope that it will be useful,
13     but WITHOUT ANY WARRANTY; without even the implied warranty of
14     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20  */
21 
22 /* License: GPL
23  * Author: Kevin Thayer <nufan_wfk at yahoo dot com>
24  *
25  * This file will hold API related functions, both internal (firmware api)
26  * and external (v4l2, etc)
27  *
28  * -----
29  * MPG600/MPG160 support by  T.Adachi <tadachi@tadachi-net.com>
30  *                      and Takeru KOMORIYA<komoriya@paken.org>
31  *
32  * AVerMedia M179 GPIO info by Chris Pinkham <cpinkham@bc2va.org>
33  *                using information provided by Jiun-Kuei Jung @ AVerMedia.
34  */
35 
36 #include "ivtv-driver.h"
37 #include "ivtv-fileops.h"
38 #include "ivtv-queue.h"
39 #include "ivtv-mailbox.h"
40 #include "ivtv-ioctl.h"
41 #include "ivtv-irq.h"
42 #include "ivtv-yuv.h"
43 #include "ivtv-cards.h"
44 #include "ivtv-streams.h"
45 #include "ivtv-firmware.h"
46 #include <media/v4l2-event.h>
47 
48 static const struct v4l2_file_operations ivtv_v4l2_enc_fops = {
49 	.owner = THIS_MODULE,
50 	.read = ivtv_v4l2_read,
51 	.write = ivtv_v4l2_write,
52 	.open = ivtv_v4l2_open,
53 	.unlocked_ioctl = video_ioctl2,
54 	.release = ivtv_v4l2_close,
55 	.poll = ivtv_v4l2_enc_poll,
56 };
57 
58 static const struct v4l2_file_operations ivtv_v4l2_dec_fops = {
59 	.owner = THIS_MODULE,
60 	.read = ivtv_v4l2_read,
61 	.write = ivtv_v4l2_write,
62 	.open = ivtv_v4l2_open,
63 	.unlocked_ioctl = video_ioctl2,
64 	.release = ivtv_v4l2_close,
65 	.poll = ivtv_v4l2_dec_poll,
66 };
67 
68 static const struct v4l2_file_operations ivtv_v4l2_radio_fops = {
69 	.owner = THIS_MODULE,
70 	.open = ivtv_v4l2_open,
71 	.unlocked_ioctl = video_ioctl2,
72 	.release = ivtv_v4l2_close,
73 	.poll = ivtv_v4l2_enc_poll,
74 };
75 
76 #define IVTV_V4L2_DEC_MPG_OFFSET  16	/* offset from 0 to register decoder mpg v4l2 minors on */
77 #define IVTV_V4L2_ENC_PCM_OFFSET  24	/* offset from 0 to register pcm v4l2 minors on */
78 #define IVTV_V4L2_ENC_YUV_OFFSET  32	/* offset from 0 to register yuv v4l2 minors on */
79 #define IVTV_V4L2_DEC_YUV_OFFSET  48	/* offset from 0 to register decoder yuv v4l2 minors on */
80 #define IVTV_V4L2_DEC_VBI_OFFSET   8	/* offset from 0 to register decoder vbi input v4l2 minors on */
81 #define IVTV_V4L2_DEC_VOUT_OFFSET 16	/* offset from 0 to register vbi output v4l2 minors on */
82 
83 static struct {
84 	const char *name;
85 	int vfl_type;
86 	int num_offset;
87 	int dma, pio;
88 	u32 v4l2_caps;
89 	const struct v4l2_file_operations *fops;
90 } ivtv_stream_info[] = {
91 	{	/* IVTV_ENC_STREAM_TYPE_MPG */
92 		"encoder MPG",
93 		VFL_TYPE_GRABBER, 0,
94 		PCI_DMA_FROMDEVICE, 0,
95 		V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_TUNER |
96 			V4L2_CAP_AUDIO | V4L2_CAP_READWRITE,
97 		&ivtv_v4l2_enc_fops
98 	},
99 	{	/* IVTV_ENC_STREAM_TYPE_YUV */
100 		"encoder YUV",
101 		VFL_TYPE_GRABBER, IVTV_V4L2_ENC_YUV_OFFSET,
102 		PCI_DMA_FROMDEVICE, 0,
103 		V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_TUNER |
104 			V4L2_CAP_AUDIO | V4L2_CAP_READWRITE,
105 		&ivtv_v4l2_enc_fops
106 	},
107 	{	/* IVTV_ENC_STREAM_TYPE_VBI */
108 		"encoder VBI",
109 		VFL_TYPE_VBI, 0,
110 		PCI_DMA_FROMDEVICE, 0,
111 		V4L2_CAP_VBI_CAPTURE | V4L2_CAP_SLICED_VBI_CAPTURE | V4L2_CAP_TUNER |
112 			V4L2_CAP_AUDIO | V4L2_CAP_READWRITE,
113 		&ivtv_v4l2_enc_fops
114 	},
115 	{	/* IVTV_ENC_STREAM_TYPE_PCM */
116 		"encoder PCM",
117 		VFL_TYPE_GRABBER, IVTV_V4L2_ENC_PCM_OFFSET,
118 		PCI_DMA_FROMDEVICE, 0,
119 		V4L2_CAP_TUNER | V4L2_CAP_AUDIO | V4L2_CAP_READWRITE,
120 		&ivtv_v4l2_enc_fops
121 	},
122 	{	/* IVTV_ENC_STREAM_TYPE_RAD */
123 		"encoder radio",
124 		VFL_TYPE_RADIO, 0,
125 		PCI_DMA_NONE, 1,
126 		V4L2_CAP_RADIO | V4L2_CAP_TUNER,
127 		&ivtv_v4l2_radio_fops
128 	},
129 	{	/* IVTV_DEC_STREAM_TYPE_MPG */
130 		"decoder MPG",
131 		VFL_TYPE_GRABBER, IVTV_V4L2_DEC_MPG_OFFSET,
132 		PCI_DMA_TODEVICE, 0,
133 		V4L2_CAP_VIDEO_OUTPUT | V4L2_CAP_AUDIO | V4L2_CAP_READWRITE,
134 		&ivtv_v4l2_dec_fops
135 	},
136 	{	/* IVTV_DEC_STREAM_TYPE_VBI */
137 		"decoder VBI",
138 		VFL_TYPE_VBI, IVTV_V4L2_DEC_VBI_OFFSET,
139 		PCI_DMA_NONE, 1,
140 		V4L2_CAP_SLICED_VBI_CAPTURE | V4L2_CAP_READWRITE,
141 		&ivtv_v4l2_enc_fops
142 	},
143 	{	/* IVTV_DEC_STREAM_TYPE_VOUT */
144 		"decoder VOUT",
145 		VFL_TYPE_VBI, IVTV_V4L2_DEC_VOUT_OFFSET,
146 		PCI_DMA_NONE, 1,
147 		V4L2_CAP_SLICED_VBI_OUTPUT | V4L2_CAP_AUDIO | V4L2_CAP_READWRITE,
148 		&ivtv_v4l2_dec_fops
149 	},
150 	{	/* IVTV_DEC_STREAM_TYPE_YUV */
151 		"decoder YUV",
152 		VFL_TYPE_GRABBER, IVTV_V4L2_DEC_YUV_OFFSET,
153 		PCI_DMA_TODEVICE, 0,
154 		V4L2_CAP_VIDEO_OUTPUT | V4L2_CAP_AUDIO | V4L2_CAP_READWRITE,
155 		&ivtv_v4l2_dec_fops
156 	}
157 };
158 
159 static void ivtv_stream_init(struct ivtv *itv, int type)
160 {
161 	struct ivtv_stream *s = &itv->streams[type];
162 	struct video_device *vdev = s->vdev;
163 
164 	/* we need to keep vdev, so restore it afterwards */
165 	memset(s, 0, sizeof(*s));
166 	s->vdev = vdev;
167 
168 	/* initialize ivtv_stream fields */
169 	s->itv = itv;
170 	s->type = type;
171 	s->name = ivtv_stream_info[type].name;
172 	s->caps = ivtv_stream_info[type].v4l2_caps;
173 
174 	if (ivtv_stream_info[type].pio)
175 		s->dma = PCI_DMA_NONE;
176 	else
177 		s->dma = ivtv_stream_info[type].dma;
178 	s->buf_size = itv->stream_buf_size[type];
179 	if (s->buf_size)
180 		s->buffers = (itv->options.kilobytes[type] * 1024 + s->buf_size - 1) / s->buf_size;
181 	spin_lock_init(&s->qlock);
182 	init_waitqueue_head(&s->waitq);
183 	s->sg_handle = IVTV_DMA_UNMAPPED;
184 	ivtv_queue_init(&s->q_free);
185 	ivtv_queue_init(&s->q_full);
186 	ivtv_queue_init(&s->q_dma);
187 	ivtv_queue_init(&s->q_predma);
188 	ivtv_queue_init(&s->q_io);
189 }
190 
191 static int ivtv_prep_dev(struct ivtv *itv, int type)
192 {
193 	struct ivtv_stream *s = &itv->streams[type];
194 	int num_offset = ivtv_stream_info[type].num_offset;
195 	int num = itv->instance + ivtv_first_minor + num_offset;
196 
197 	/* These four fields are always initialized. If vdev == NULL, then
198 	   this stream is not in use. In that case no other fields but these
199 	   four can be used. */
200 	s->vdev = NULL;
201 	s->itv = itv;
202 	s->type = type;
203 	s->name = ivtv_stream_info[type].name;
204 
205 	/* Check whether the radio is supported */
206 	if (type == IVTV_ENC_STREAM_TYPE_RAD && !(itv->v4l2_cap & V4L2_CAP_RADIO))
207 		return 0;
208 	if (type >= IVTV_DEC_STREAM_TYPE_MPG && !(itv->v4l2_cap & V4L2_CAP_VIDEO_OUTPUT))
209 		return 0;
210 
211 	/* User explicitly selected 0 buffers for these streams, so don't
212 	   create them. */
213 	if (ivtv_stream_info[type].dma != PCI_DMA_NONE &&
214 	    itv->options.kilobytes[type] == 0) {
215 		IVTV_INFO("Disabled %s device\n", ivtv_stream_info[type].name);
216 		return 0;
217 	}
218 
219 	ivtv_stream_init(itv, type);
220 
221 	/* allocate and initialize the v4l2 video device structure */
222 	s->vdev = video_device_alloc();
223 	if (s->vdev == NULL) {
224 		IVTV_ERR("Couldn't allocate v4l2 video_device for %s\n", s->name);
225 		return -ENOMEM;
226 	}
227 
228 	snprintf(s->vdev->name, sizeof(s->vdev->name), "%s %s",
229 			itv->v4l2_dev.name, s->name);
230 
231 	s->vdev->num = num;
232 	s->vdev->v4l2_dev = &itv->v4l2_dev;
233 	if (ivtv_stream_info[type].v4l2_caps &
234 			(V4L2_CAP_VIDEO_OUTPUT | V4L2_CAP_SLICED_VBI_OUTPUT))
235 		s->vdev->vfl_dir = VFL_DIR_TX;
236 	s->vdev->fops = ivtv_stream_info[type].fops;
237 	s->vdev->ctrl_handler = itv->v4l2_dev.ctrl_handler;
238 	s->vdev->release = video_device_release;
239 	s->vdev->tvnorms = V4L2_STD_ALL;
240 	s->vdev->lock = &itv->serialize_lock;
241 	if (s->type == IVTV_DEC_STREAM_TYPE_VBI) {
242 		v4l2_disable_ioctl(s->vdev, VIDIOC_S_AUDIO);
243 		v4l2_disable_ioctl(s->vdev, VIDIOC_G_AUDIO);
244 		v4l2_disable_ioctl(s->vdev, VIDIOC_ENUMAUDIO);
245 		v4l2_disable_ioctl(s->vdev, VIDIOC_ENUMINPUT);
246 		v4l2_disable_ioctl(s->vdev, VIDIOC_S_INPUT);
247 		v4l2_disable_ioctl(s->vdev, VIDIOC_G_INPUT);
248 		v4l2_disable_ioctl(s->vdev, VIDIOC_S_FREQUENCY);
249 		v4l2_disable_ioctl(s->vdev, VIDIOC_G_FREQUENCY);
250 		v4l2_disable_ioctl(s->vdev, VIDIOC_S_TUNER);
251 		v4l2_disable_ioctl(s->vdev, VIDIOC_G_TUNER);
252 		v4l2_disable_ioctl(s->vdev, VIDIOC_S_STD);
253 	}
254 	ivtv_set_funcs(s->vdev);
255 	return 0;
256 }
257 
258 /* Initialize v4l2 variables and prepare v4l2 devices */
259 int ivtv_streams_setup(struct ivtv *itv)
260 {
261 	int type;
262 
263 	/* Setup V4L2 Devices */
264 	for (type = 0; type < IVTV_MAX_STREAMS; type++) {
265 		/* Prepare device */
266 		if (ivtv_prep_dev(itv, type))
267 			break;
268 
269 		if (itv->streams[type].vdev == NULL)
270 			continue;
271 
272 		/* Allocate Stream */
273 		if (ivtv_stream_alloc(&itv->streams[type]))
274 			break;
275 	}
276 	if (type == IVTV_MAX_STREAMS)
277 		return 0;
278 
279 	/* One or more streams could not be initialized. Clean 'em all up. */
280 	ivtv_streams_cleanup(itv, 0);
281 	return -ENOMEM;
282 }
283 
284 static int ivtv_reg_dev(struct ivtv *itv, int type)
285 {
286 	struct ivtv_stream *s = &itv->streams[type];
287 	int vfl_type = ivtv_stream_info[type].vfl_type;
288 	const char *name;
289 	int num;
290 
291 	if (s->vdev == NULL)
292 		return 0;
293 
294 	num = s->vdev->num;
295 	/* card number + user defined offset + device offset */
296 	if (type != IVTV_ENC_STREAM_TYPE_MPG) {
297 		struct ivtv_stream *s_mpg = &itv->streams[IVTV_ENC_STREAM_TYPE_MPG];
298 
299 		if (s_mpg->vdev)
300 			num = s_mpg->vdev->num + ivtv_stream_info[type].num_offset;
301 	}
302 	video_set_drvdata(s->vdev, s);
303 
304 	/* Register device. First try the desired minor, then any free one. */
305 	if (video_register_device_no_warn(s->vdev, vfl_type, num)) {
306 		IVTV_ERR("Couldn't register v4l2 device for %s (device node number %d)\n",
307 				s->name, num);
308 		video_device_release(s->vdev);
309 		s->vdev = NULL;
310 		return -ENOMEM;
311 	}
312 	name = video_device_node_name(s->vdev);
313 
314 	switch (vfl_type) {
315 	case VFL_TYPE_GRABBER:
316 		IVTV_INFO("Registered device %s for %s (%d kB)\n",
317 			name, s->name, itv->options.kilobytes[type]);
318 		break;
319 	case VFL_TYPE_RADIO:
320 		IVTV_INFO("Registered device %s for %s\n",
321 			name, s->name);
322 		break;
323 	case VFL_TYPE_VBI:
324 		if (itv->options.kilobytes[type])
325 			IVTV_INFO("Registered device %s for %s (%d kB)\n",
326 				name, s->name, itv->options.kilobytes[type]);
327 		else
328 			IVTV_INFO("Registered device %s for %s\n",
329 				name, s->name);
330 		break;
331 	}
332 	return 0;
333 }
334 
335 /* Register v4l2 devices */
336 int ivtv_streams_register(struct ivtv *itv)
337 {
338 	int type;
339 	int err = 0;
340 
341 	/* Register V4L2 devices */
342 	for (type = 0; type < IVTV_MAX_STREAMS; type++)
343 		err |= ivtv_reg_dev(itv, type);
344 
345 	if (err == 0)
346 		return 0;
347 
348 	/* One or more streams could not be initialized. Clean 'em all up. */
349 	ivtv_streams_cleanup(itv, 1);
350 	return -ENOMEM;
351 }
352 
353 /* Unregister v4l2 devices */
354 void ivtv_streams_cleanup(struct ivtv *itv, int unregister)
355 {
356 	int type;
357 
358 	/* Teardown all streams */
359 	for (type = 0; type < IVTV_MAX_STREAMS; type++) {
360 		struct video_device *vdev = itv->streams[type].vdev;
361 
362 		itv->streams[type].vdev = NULL;
363 		if (vdev == NULL)
364 			continue;
365 
366 		ivtv_stream_free(&itv->streams[type]);
367 		/* Unregister or release device */
368 		if (unregister)
369 			video_unregister_device(vdev);
370 		else
371 			video_device_release(vdev);
372 	}
373 }
374 
375 static void ivtv_vbi_setup(struct ivtv *itv)
376 {
377 	int raw = ivtv_raw_vbi(itv);
378 	u32 data[CX2341X_MBOX_MAX_DATA];
379 	int lines;
380 	int i;
381 
382 	/* Reset VBI */
383 	ivtv_vapi(itv, CX2341X_ENC_SET_VBI_LINE, 5, 0xffff , 0, 0, 0, 0);
384 
385 	/* setup VBI registers */
386 	if (raw)
387 		v4l2_subdev_call(itv->sd_video, vbi, s_raw_fmt, &itv->vbi.in.fmt.vbi);
388 	else
389 		v4l2_subdev_call(itv->sd_video, vbi, s_sliced_fmt, &itv->vbi.in.fmt.sliced);
390 
391 	/* determine number of lines and total number of VBI bytes.
392 	   A raw line takes 1443 bytes: 2 * 720 + 4 byte frame header - 1
393 	   The '- 1' byte is probably an unused U or V byte. Or something...
394 	   A sliced line takes 51 bytes: 4 byte frame header, 4 byte internal
395 	   header, 42 data bytes + checksum (to be confirmed) */
396 	if (raw) {
397 		lines = itv->vbi.count * 2;
398 	} else {
399 		lines = itv->is_60hz ? 24 : 38;
400 		if (itv->is_60hz && (itv->hw_flags & IVTV_HW_CX25840))
401 			lines += 2;
402 	}
403 
404 	itv->vbi.enc_size = lines * (raw ? itv->vbi.raw_size : itv->vbi.sliced_size);
405 
406 	/* Note: sliced vs raw flag doesn't seem to have any effect
407 	   TODO: check mode (0x02) value with older ivtv versions. */
408 	data[0] = raw | 0x02 | (0xbd << 8);
409 
410 	/* Every X number of frames a VBI interrupt arrives (frames as in 25 or 30 fps) */
411 	data[1] = 1;
412 	/* The VBI frames are stored in a ringbuffer with this size (with a VBI frame as unit) */
413 	data[2] = raw ? 4 : 4 * (itv->vbi.raw_size / itv->vbi.enc_size);
414 	/* The start/stop codes determine which VBI lines end up in the raw VBI data area.
415 	   The codes are from table 24 in the saa7115 datasheet. Each raw/sliced/video line
416 	   is framed with codes FF0000XX where XX is the SAV/EAV (Start/End of Active Video)
417 	   code. These values for raw VBI are obtained from a driver disassembly. The sliced
418 	   start/stop codes was deduced from this, but they do not appear in the driver.
419 	   Other code pairs that I found are: 0x250E6249/0x13545454 and 0x25256262/0x38137F54.
420 	   However, I have no idea what these values are for. */
421 	if (itv->hw_flags & IVTV_HW_CX25840) {
422 		/* Setup VBI for the cx25840 digitizer */
423 		if (raw) {
424 			data[3] = 0x20602060;
425 			data[4] = 0x30703070;
426 		} else {
427 			data[3] = 0xB0F0B0F0;
428 			data[4] = 0xA0E0A0E0;
429 		}
430 		/* Lines per frame */
431 		data[5] = lines;
432 		/* bytes per line */
433 		data[6] = (raw ? itv->vbi.raw_size : itv->vbi.sliced_size);
434 	} else {
435 		/* Setup VBI for the saa7115 digitizer */
436 		if (raw) {
437 			data[3] = 0x25256262;
438 			data[4] = 0x387F7F7F;
439 		} else {
440 			data[3] = 0xABABECEC;
441 			data[4] = 0xB6F1F1F1;
442 		}
443 		/* Lines per frame */
444 		data[5] = lines;
445 		/* bytes per line */
446 		data[6] = itv->vbi.enc_size / lines;
447 	}
448 
449 	IVTV_DEBUG_INFO(
450 		"Setup VBI API header 0x%08x pkts %d buffs %d ln %d sz %d\n",
451 			data[0], data[1], data[2], data[5], data[6]);
452 
453 	ivtv_api(itv, CX2341X_ENC_SET_VBI_CONFIG, 7, data);
454 
455 	/* returns the VBI encoder memory area. */
456 	itv->vbi.enc_start = data[2];
457 	itv->vbi.fpi = data[0];
458 	if (!itv->vbi.fpi)
459 		itv->vbi.fpi = 1;
460 
461 	IVTV_DEBUG_INFO("Setup VBI start 0x%08x frames %d fpi %d\n",
462 		itv->vbi.enc_start, data[1], itv->vbi.fpi);
463 
464 	/* select VBI lines.
465 	   Note that the sliced argument seems to have no effect. */
466 	for (i = 2; i <= 24; i++) {
467 		int valid;
468 
469 		if (itv->is_60hz) {
470 			valid = i >= 10 && i < 22;
471 		} else {
472 			valid = i >= 6 && i < 24;
473 		}
474 		ivtv_vapi(itv, CX2341X_ENC_SET_VBI_LINE, 5, i - 1,
475 				valid, 0 , 0, 0);
476 		ivtv_vapi(itv, CX2341X_ENC_SET_VBI_LINE, 5, (i - 1) | 0x80000000,
477 				valid, 0, 0, 0);
478 	}
479 
480 	/* Remaining VBI questions:
481 	   - Is it possible to select particular VBI lines only for inclusion in the MPEG
482 	   stream? Currently you can only get the first X lines.
483 	   - Is mixed raw and sliced VBI possible?
484 	   - What's the meaning of the raw/sliced flag?
485 	   - What's the meaning of params 2, 3 & 4 of the Select VBI command? */
486 }
487 
488 int ivtv_start_v4l2_encode_stream(struct ivtv_stream *s)
489 {
490 	u32 data[CX2341X_MBOX_MAX_DATA];
491 	struct ivtv *itv = s->itv;
492 	int captype = 0, subtype = 0;
493 	int enable_passthrough = 0;
494 
495 	if (s->vdev == NULL)
496 		return -EINVAL;
497 
498 	IVTV_DEBUG_INFO("Start encoder stream %s\n", s->name);
499 
500 	switch (s->type) {
501 	case IVTV_ENC_STREAM_TYPE_MPG:
502 		captype = 0;
503 		subtype = 3;
504 
505 		/* Stop Passthrough */
506 		if (itv->output_mode == OUT_PASSTHROUGH) {
507 			ivtv_passthrough_mode(itv, 0);
508 			enable_passthrough = 1;
509 		}
510 		itv->mpg_data_received = itv->vbi_data_inserted = 0;
511 		itv->dualwatch_jiffies = jiffies;
512 		itv->dualwatch_stereo_mode = v4l2_ctrl_g_ctrl(itv->cxhdl.audio_mode);
513 		itv->search_pack_header = 0;
514 		break;
515 
516 	case IVTV_ENC_STREAM_TYPE_YUV:
517 		if (itv->output_mode == OUT_PASSTHROUGH) {
518 			captype = 2;
519 			subtype = 11;	/* video+audio+decoder */
520 			break;
521 		}
522 		captype = 1;
523 		subtype = 1;
524 		break;
525 	case IVTV_ENC_STREAM_TYPE_PCM:
526 		captype = 1;
527 		subtype = 2;
528 		break;
529 	case IVTV_ENC_STREAM_TYPE_VBI:
530 		captype = 1;
531 		subtype = 4;
532 
533 		itv->vbi.frame = 0;
534 		itv->vbi.inserted_frame = 0;
535 		memset(itv->vbi.sliced_mpeg_size,
536 			0, sizeof(itv->vbi.sliced_mpeg_size));
537 		break;
538 	default:
539 		return -EINVAL;
540 	}
541 	s->subtype = subtype;
542 	s->buffers_stolen = 0;
543 
544 	/* Clear Streamoff flags in case left from last capture */
545 	clear_bit(IVTV_F_S_STREAMOFF, &s->s_flags);
546 
547 	if (atomic_read(&itv->capturing) == 0) {
548 		int digitizer;
549 
550 		/* Always use frame based mode. Experiments have demonstrated that byte
551 		   stream based mode results in dropped frames and corruption. Not often,
552 		   but occasionally. Many thanks go to Leonard Orb who spent a lot of
553 		   effort and time trying to trace the cause of the drop outs. */
554 		/* 1 frame per DMA */
555 		/*ivtv_vapi(itv, CX2341X_ENC_SET_DMA_BLOCK_SIZE, 2, 128, 0); */
556 		ivtv_vapi(itv, CX2341X_ENC_SET_DMA_BLOCK_SIZE, 2, 1, 1);
557 
558 		/* Stuff from Windows, we don't know what it is */
559 		ivtv_vapi(itv, CX2341X_ENC_SET_VERT_CROP_LINE, 1, 0);
560 		/* According to the docs, this should be correct. However, this is
561 		   untested. I don't dare enable this without having tested it.
562 		   Only very few old cards actually have this hardware combination.
563 		ivtv_vapi(itv, CX2341X_ENC_SET_VERT_CROP_LINE, 1,
564 			((itv->hw_flags & IVTV_HW_SAA7114) && itv->is_60hz) ? 10001 : 0);
565 		*/
566 		ivtv_vapi(itv, CX2341X_ENC_MISC, 2, 3, !itv->has_cx23415);
567 		ivtv_vapi(itv, CX2341X_ENC_MISC, 2, 8, 0);
568 		ivtv_vapi(itv, CX2341X_ENC_MISC, 2, 4, 1);
569 		ivtv_vapi(itv, CX2341X_ENC_MISC, 1, 12);
570 
571 		/* assign placeholder */
572 		ivtv_vapi(itv, CX2341X_ENC_SET_PLACEHOLDER, 12,
573 			0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
574 
575 		if (itv->card->hw_all & (IVTV_HW_SAA7115 | IVTV_HW_SAA717X))
576 		    digitizer = 0xF1;
577 		else if (itv->card->hw_all & IVTV_HW_SAA7114)
578 		    digitizer = 0xEF;
579 		else /* cx25840 */
580 		    digitizer = 0x140;
581 
582 		ivtv_vapi(itv, CX2341X_ENC_SET_NUM_VSYNC_LINES, 2, digitizer, digitizer);
583 
584 		/* Setup VBI */
585 		if (itv->v4l2_cap & V4L2_CAP_VBI_CAPTURE) {
586 			ivtv_vbi_setup(itv);
587 		}
588 
589 		/* assign program index info. Mask 7: select I/P/B, Num_req: 400 max */
590 		ivtv_vapi_result(itv, data, CX2341X_ENC_SET_PGM_INDEX_INFO, 2, 7, 400);
591 		itv->pgm_info_offset = data[0];
592 		itv->pgm_info_num = data[1];
593 		itv->pgm_info_write_idx = 0;
594 		itv->pgm_info_read_idx = 0;
595 
596 		IVTV_DEBUG_INFO("PGM Index at 0x%08x with %d elements\n",
597 				itv->pgm_info_offset, itv->pgm_info_num);
598 
599 		/* Setup API for Stream */
600 		cx2341x_handler_setup(&itv->cxhdl);
601 
602 		/* mute if capturing radio */
603 		if (test_bit(IVTV_F_I_RADIO_USER, &itv->i_flags))
604 			ivtv_vapi(itv, CX2341X_ENC_MUTE_VIDEO, 1,
605 				1 | (v4l2_ctrl_g_ctrl(itv->cxhdl.video_mute_yuv) << 8));
606 	}
607 
608 	/* Vsync Setup */
609 	if (itv->has_cx23415 && !test_and_set_bit(IVTV_F_I_DIG_RST, &itv->i_flags)) {
610 		/* event notification (on) */
611 		ivtv_vapi(itv, CX2341X_ENC_SET_EVENT_NOTIFICATION, 4, 0, 1, IVTV_IRQ_ENC_VIM_RST, -1);
612 		ivtv_clear_irq_mask(itv, IVTV_IRQ_ENC_VIM_RST);
613 	}
614 
615 	if (atomic_read(&itv->capturing) == 0) {
616 		/* Clear all Pending Interrupts */
617 		ivtv_set_irq_mask(itv, IVTV_IRQ_MASK_CAPTURE);
618 
619 		clear_bit(IVTV_F_I_EOS, &itv->i_flags);
620 
621 		cx2341x_handler_set_busy(&itv->cxhdl, 1);
622 
623 		/* Initialize Digitizer for Capture */
624 		/* Avoid tinny audio problem - ensure audio clocks are going */
625 		v4l2_subdev_call(itv->sd_audio, audio, s_stream, 1);
626 		/* Avoid unpredictable PCI bus hang - disable video clocks */
627 		v4l2_subdev_call(itv->sd_video, video, s_stream, 0);
628 		ivtv_msleep_timeout(300, 0);
629 		ivtv_vapi(itv, CX2341X_ENC_INITIALIZE_INPUT, 0);
630 		v4l2_subdev_call(itv->sd_video, video, s_stream, 1);
631 	}
632 
633 	/* begin_capture */
634 	if (ivtv_vapi(itv, CX2341X_ENC_START_CAPTURE, 2, captype, subtype))
635 	{
636 		IVTV_DEBUG_WARN( "Error starting capture!\n");
637 		return -EINVAL;
638 	}
639 
640 	/* Start Passthrough */
641 	if (enable_passthrough) {
642 		ivtv_passthrough_mode(itv, 1);
643 	}
644 
645 	if (s->type == IVTV_ENC_STREAM_TYPE_VBI)
646 		ivtv_clear_irq_mask(itv, IVTV_IRQ_ENC_VBI_CAP);
647 	else
648 		ivtv_clear_irq_mask(itv, IVTV_IRQ_MASK_CAPTURE);
649 
650 	/* you're live! sit back and await interrupts :) */
651 	atomic_inc(&itv->capturing);
652 	return 0;
653 }
654 EXPORT_SYMBOL(ivtv_start_v4l2_encode_stream);
655 
656 static int ivtv_setup_v4l2_decode_stream(struct ivtv_stream *s)
657 {
658 	u32 data[CX2341X_MBOX_MAX_DATA];
659 	struct ivtv *itv = s->itv;
660 	int datatype;
661 	u16 width;
662 	u16 height;
663 
664 	if (s->vdev == NULL)
665 		return -EINVAL;
666 
667 	IVTV_DEBUG_INFO("Setting some initial decoder settings\n");
668 
669 	width = itv->cxhdl.width;
670 	height = itv->cxhdl.height;
671 
672 	/* set audio mode to left/stereo  for dual/stereo mode. */
673 	ivtv_vapi(itv, CX2341X_DEC_SET_AUDIO_MODE, 2, itv->audio_bilingual_mode, itv->audio_stereo_mode);
674 
675 	/* set number of internal decoder buffers */
676 	ivtv_vapi(itv, CX2341X_DEC_SET_DISPLAY_BUFFERS, 1, 0);
677 
678 	/* prebuffering */
679 	ivtv_vapi(itv, CX2341X_DEC_SET_PREBUFFERING, 1, 1);
680 
681 	/* extract from user packets */
682 	ivtv_vapi_result(itv, data, CX2341X_DEC_EXTRACT_VBI, 1, 1);
683 	itv->vbi.dec_start = data[0];
684 
685 	IVTV_DEBUG_INFO("Decoder VBI RE-Insert start 0x%08x size 0x%08x\n",
686 		itv->vbi.dec_start, data[1]);
687 
688 	/* set decoder source settings */
689 	/* Data type: 0 = mpeg from host,
690 	   1 = yuv from encoder,
691 	   2 = yuv_from_host */
692 	switch (s->type) {
693 	case IVTV_DEC_STREAM_TYPE_YUV:
694 		if (itv->output_mode == OUT_PASSTHROUGH) {
695 			datatype = 1;
696 		} else {
697 			/* Fake size to avoid switching video standard */
698 			datatype = 2;
699 			width = 720;
700 			height = itv->is_out_50hz ? 576 : 480;
701 		}
702 		IVTV_DEBUG_INFO("Setup DEC YUV Stream data[0] = %d\n", datatype);
703 		break;
704 	case IVTV_DEC_STREAM_TYPE_MPG:
705 	default:
706 		datatype = 0;
707 		break;
708 	}
709 	if (ivtv_vapi(itv, CX2341X_DEC_SET_DECODER_SOURCE, 4, datatype,
710 			width, height, itv->cxhdl.audio_properties)) {
711 		IVTV_DEBUG_WARN("Couldn't initialize decoder source\n");
712 	}
713 
714 	/* Decoder sometimes dies here, so wait a moment */
715 	ivtv_msleep_timeout(10, 0);
716 
717 	/* Known failure point for firmware, so check */
718 	return ivtv_firmware_check(itv, "ivtv_setup_v4l2_decode_stream");
719 }
720 
721 int ivtv_start_v4l2_decode_stream(struct ivtv_stream *s, int gop_offset)
722 {
723 	struct ivtv *itv = s->itv;
724 	int rc;
725 
726 	if (s->vdev == NULL)
727 		return -EINVAL;
728 
729 	if (test_and_set_bit(IVTV_F_S_STREAMING, &s->s_flags))
730 		return 0;	/* already started */
731 
732 	IVTV_DEBUG_INFO("Starting decode stream %s (gop_offset %d)\n", s->name, gop_offset);
733 
734 	rc = ivtv_setup_v4l2_decode_stream(s);
735 	if (rc < 0) {
736 		clear_bit(IVTV_F_S_STREAMING, &s->s_flags);
737 		return rc;
738 	}
739 
740 	/* set dma size to 65536 bytes */
741 	ivtv_vapi(itv, CX2341X_DEC_SET_DMA_BLOCK_SIZE, 1, 65536);
742 
743 	/* Clear Streamoff */
744 	clear_bit(IVTV_F_S_STREAMOFF, &s->s_flags);
745 
746 	/* Zero out decoder counters */
747 	writel(0, &itv->dec_mbox.mbox[IVTV_MBOX_DMA_END].data[0]);
748 	writel(0, &itv->dec_mbox.mbox[IVTV_MBOX_DMA_END].data[1]);
749 	writel(0, &itv->dec_mbox.mbox[IVTV_MBOX_DMA_END].data[2]);
750 	writel(0, &itv->dec_mbox.mbox[IVTV_MBOX_DMA_END].data[3]);
751 	writel(0, &itv->dec_mbox.mbox[IVTV_MBOX_DMA].data[0]);
752 	writel(0, &itv->dec_mbox.mbox[IVTV_MBOX_DMA].data[1]);
753 	writel(0, &itv->dec_mbox.mbox[IVTV_MBOX_DMA].data[2]);
754 	writel(0, &itv->dec_mbox.mbox[IVTV_MBOX_DMA].data[3]);
755 
756 	/* turn on notification of dual/stereo mode change */
757 	ivtv_vapi(itv, CX2341X_DEC_SET_EVENT_NOTIFICATION, 4, 0, 1, IVTV_IRQ_DEC_AUD_MODE_CHG, -1);
758 
759 	/* start playback */
760 	ivtv_vapi(itv, CX2341X_DEC_START_PLAYBACK, 2, gop_offset, 0);
761 
762 	/* Let things settle before we actually start */
763 	ivtv_msleep_timeout(10, 0);
764 
765 	/* Clear the following Interrupt mask bits for decoding */
766 	ivtv_clear_irq_mask(itv, IVTV_IRQ_MASK_DECODE);
767 	IVTV_DEBUG_IRQ("IRQ Mask is now: 0x%08x\n", itv->irqmask);
768 
769 	/* you're live! sit back and await interrupts :) */
770 	atomic_inc(&itv->decoding);
771 	return 0;
772 }
773 
774 void ivtv_stop_all_captures(struct ivtv *itv)
775 {
776 	int i;
777 
778 	for (i = IVTV_MAX_STREAMS - 1; i >= 0; i--) {
779 		struct ivtv_stream *s = &itv->streams[i];
780 
781 		if (s->vdev == NULL)
782 			continue;
783 		if (test_bit(IVTV_F_S_STREAMING, &s->s_flags)) {
784 			ivtv_stop_v4l2_encode_stream(s, 0);
785 		}
786 	}
787 }
788 
789 int ivtv_stop_v4l2_encode_stream(struct ivtv_stream *s, int gop_end)
790 {
791 	struct ivtv *itv = s->itv;
792 	DECLARE_WAITQUEUE(wait, current);
793 	int cap_type;
794 	int stopmode;
795 
796 	if (s->vdev == NULL)
797 		return -EINVAL;
798 
799 	/* This function assumes that you are allowed to stop the capture
800 	   and that we are actually capturing */
801 
802 	IVTV_DEBUG_INFO("Stop Capture\n");
803 
804 	if (s->type == IVTV_DEC_STREAM_TYPE_VOUT)
805 		return 0;
806 	if (atomic_read(&itv->capturing) == 0)
807 		return 0;
808 
809 	switch (s->type) {
810 	case IVTV_ENC_STREAM_TYPE_YUV:
811 		cap_type = 1;
812 		break;
813 	case IVTV_ENC_STREAM_TYPE_PCM:
814 		cap_type = 1;
815 		break;
816 	case IVTV_ENC_STREAM_TYPE_VBI:
817 		cap_type = 1;
818 		break;
819 	case IVTV_ENC_STREAM_TYPE_MPG:
820 	default:
821 		cap_type = 0;
822 		break;
823 	}
824 
825 	/* Stop Capture Mode */
826 	if (s->type == IVTV_ENC_STREAM_TYPE_MPG && gop_end) {
827 		stopmode = 0;
828 	} else {
829 		stopmode = 1;
830 	}
831 
832 	/* end_capture */
833 	/* when: 0 =  end of GOP  1 = NOW!, type: 0 = mpeg, subtype: 3 = video+audio */
834 	ivtv_vapi(itv, CX2341X_ENC_STOP_CAPTURE, 3, stopmode, cap_type, s->subtype);
835 
836 	if (!test_bit(IVTV_F_S_PASSTHROUGH, &s->s_flags)) {
837 		if (s->type == IVTV_ENC_STREAM_TYPE_MPG && gop_end) {
838 			/* only run these if we're shutting down the last cap */
839 			unsigned long duration;
840 			unsigned long then = jiffies;
841 
842 			add_wait_queue(&itv->eos_waitq, &wait);
843 
844 			set_current_state(TASK_INTERRUPTIBLE);
845 
846 			/* wait 2s for EOS interrupt */
847 			while (!test_bit(IVTV_F_I_EOS, &itv->i_flags) &&
848 				time_before(jiffies,
849 					    then + msecs_to_jiffies(2000))) {
850 				schedule_timeout(msecs_to_jiffies(10));
851 			}
852 
853 			/* To convert jiffies to ms, we must multiply by 1000
854 			 * and divide by HZ.  To avoid runtime division, we
855 			 * convert this to multiplication by 1000/HZ.
856 			 * Since integer division truncates, we get the best
857 			 * accuracy if we do a rounding calculation of the constant.
858 			 * Think of the case where HZ is 1024.
859 			 */
860 			duration = ((1000 + HZ / 2) / HZ) * (jiffies - then);
861 
862 			if (!test_bit(IVTV_F_I_EOS, &itv->i_flags)) {
863 				IVTV_DEBUG_WARN("%s: EOS interrupt not received! stopping anyway.\n", s->name);
864 				IVTV_DEBUG_WARN("%s: waited %lu ms.\n", s->name, duration);
865 			} else {
866 				IVTV_DEBUG_INFO("%s: EOS took %lu ms to occur.\n", s->name, duration);
867 			}
868 			set_current_state(TASK_RUNNING);
869 			remove_wait_queue(&itv->eos_waitq, &wait);
870 			set_bit(IVTV_F_S_STREAMOFF, &s->s_flags);
871 		}
872 
873 		/* Handle any pending interrupts */
874 		ivtv_msleep_timeout(100, 0);
875 	}
876 
877 	atomic_dec(&itv->capturing);
878 
879 	/* Clear capture and no-read bits */
880 	clear_bit(IVTV_F_S_STREAMING, &s->s_flags);
881 
882 	if (s->type == IVTV_ENC_STREAM_TYPE_VBI)
883 		ivtv_set_irq_mask(itv, IVTV_IRQ_ENC_VBI_CAP);
884 
885 	if (atomic_read(&itv->capturing) > 0) {
886 		return 0;
887 	}
888 
889 	cx2341x_handler_set_busy(&itv->cxhdl, 0);
890 
891 	/* Set the following Interrupt mask bits for capture */
892 	ivtv_set_irq_mask(itv, IVTV_IRQ_MASK_CAPTURE);
893 	del_timer(&itv->dma_timer);
894 
895 	/* event notification (off) */
896 	if (test_and_clear_bit(IVTV_F_I_DIG_RST, &itv->i_flags)) {
897 		/* type: 0 = refresh */
898 		/* on/off: 0 = off, intr: 0x10000000, mbox_id: -1: none */
899 		ivtv_vapi(itv, CX2341X_ENC_SET_EVENT_NOTIFICATION, 4, 0, 0, IVTV_IRQ_ENC_VIM_RST, -1);
900 		ivtv_set_irq_mask(itv, IVTV_IRQ_ENC_VIM_RST);
901 	}
902 
903 	/* Raw-passthrough is implied on start. Make sure it's stopped so
904 	   the encoder will re-initialize when next started */
905 	ivtv_vapi(itv, CX2341X_ENC_STOP_CAPTURE, 3, 1, 2, 7);
906 
907 	wake_up(&s->waitq);
908 
909 	return 0;
910 }
911 EXPORT_SYMBOL(ivtv_stop_v4l2_encode_stream);
912 
913 int ivtv_stop_v4l2_decode_stream(struct ivtv_stream *s, int flags, u64 pts)
914 {
915 	static const struct v4l2_event ev = {
916 		.type = V4L2_EVENT_EOS,
917 	};
918 	struct ivtv *itv = s->itv;
919 
920 	if (s->vdev == NULL)
921 		return -EINVAL;
922 
923 	if (s->type != IVTV_DEC_STREAM_TYPE_YUV && s->type != IVTV_DEC_STREAM_TYPE_MPG)
924 		return -EINVAL;
925 
926 	if (!test_bit(IVTV_F_S_STREAMING, &s->s_flags))
927 		return 0;
928 
929 	IVTV_DEBUG_INFO("Stop Decode at %llu, flags: %x\n", (unsigned long long)pts, flags);
930 
931 	/* Stop Decoder */
932 	if (!(flags & V4L2_DEC_CMD_STOP_IMMEDIATELY) || pts) {
933 		u32 tmp = 0;
934 
935 		/* Wait until the decoder is no longer running */
936 		if (pts) {
937 			ivtv_vapi(itv, CX2341X_DEC_STOP_PLAYBACK, 3,
938 				0, (u32)(pts & 0xffffffff), (u32)(pts >> 32));
939 		}
940 		while (1) {
941 			u32 data[CX2341X_MBOX_MAX_DATA];
942 			ivtv_vapi_result(itv, data, CX2341X_DEC_GET_XFER_INFO, 0);
943 			if (s->q_full.buffers + s->q_dma.buffers == 0) {
944 				if (tmp == data[3])
945 					break;
946 				tmp = data[3];
947 			}
948 			if (ivtv_msleep_timeout(100, 1))
949 				break;
950 		}
951 	}
952 	ivtv_vapi(itv, CX2341X_DEC_STOP_PLAYBACK, 3, flags & V4L2_DEC_CMD_STOP_TO_BLACK, 0, 0);
953 
954 	/* turn off notification of dual/stereo mode change */
955 	ivtv_vapi(itv, CX2341X_DEC_SET_EVENT_NOTIFICATION, 4, 0, 0, IVTV_IRQ_DEC_AUD_MODE_CHG, -1);
956 
957 	ivtv_set_irq_mask(itv, IVTV_IRQ_MASK_DECODE);
958 	del_timer(&itv->dma_timer);
959 
960 	clear_bit(IVTV_F_S_NEEDS_DATA, &s->s_flags);
961 	clear_bit(IVTV_F_S_STREAMING, &s->s_flags);
962 	ivtv_flush_queues(s);
963 
964 	/* decoder needs time to settle */
965 	ivtv_msleep_timeout(40, 0);
966 
967 	/* decrement decoding */
968 	atomic_dec(&itv->decoding);
969 
970 	set_bit(IVTV_F_I_EV_DEC_STOPPED, &itv->i_flags);
971 	wake_up(&itv->event_waitq);
972 	v4l2_event_queue(s->vdev, &ev);
973 
974 	/* wake up wait queues */
975 	wake_up(&s->waitq);
976 
977 	return 0;
978 }
979 
980 int ivtv_passthrough_mode(struct ivtv *itv, int enable)
981 {
982 	struct ivtv_stream *yuv_stream = &itv->streams[IVTV_ENC_STREAM_TYPE_YUV];
983 	struct ivtv_stream *dec_stream = &itv->streams[IVTV_DEC_STREAM_TYPE_YUV];
984 
985 	if (yuv_stream->vdev == NULL || dec_stream->vdev == NULL)
986 		return -EINVAL;
987 
988 	IVTV_DEBUG_INFO("ivtv ioctl: Select passthrough mode\n");
989 
990 	/* Prevent others from starting/stopping streams while we
991 	   initiate/terminate passthrough mode */
992 	if (enable) {
993 		if (itv->output_mode == OUT_PASSTHROUGH) {
994 			return 0;
995 		}
996 		if (ivtv_set_output_mode(itv, OUT_PASSTHROUGH) != OUT_PASSTHROUGH)
997 			return -EBUSY;
998 
999 		/* Fully initialize stream, and then unflag init */
1000 		set_bit(IVTV_F_S_PASSTHROUGH, &dec_stream->s_flags);
1001 		set_bit(IVTV_F_S_STREAMING, &dec_stream->s_flags);
1002 
1003 		/* Setup YUV Decoder */
1004 		ivtv_setup_v4l2_decode_stream(dec_stream);
1005 
1006 		/* Start Decoder */
1007 		ivtv_vapi(itv, CX2341X_DEC_START_PLAYBACK, 2, 0, 1);
1008 		atomic_inc(&itv->decoding);
1009 
1010 		/* Setup capture if not already done */
1011 		if (atomic_read(&itv->capturing) == 0) {
1012 			cx2341x_handler_setup(&itv->cxhdl);
1013 			cx2341x_handler_set_busy(&itv->cxhdl, 1);
1014 		}
1015 
1016 		/* Start Passthrough Mode */
1017 		ivtv_vapi(itv, CX2341X_ENC_START_CAPTURE, 2, 2, 11);
1018 		atomic_inc(&itv->capturing);
1019 		return 0;
1020 	}
1021 
1022 	if (itv->output_mode != OUT_PASSTHROUGH)
1023 		return 0;
1024 
1025 	/* Stop Passthrough Mode */
1026 	ivtv_vapi(itv, CX2341X_ENC_STOP_CAPTURE, 3, 1, 2, 11);
1027 	ivtv_vapi(itv, CX2341X_DEC_STOP_PLAYBACK, 3, 1, 0, 0);
1028 
1029 	atomic_dec(&itv->capturing);
1030 	atomic_dec(&itv->decoding);
1031 	clear_bit(IVTV_F_S_PASSTHROUGH, &dec_stream->s_flags);
1032 	clear_bit(IVTV_F_S_STREAMING, &dec_stream->s_flags);
1033 	itv->output_mode = OUT_NONE;
1034 	if (atomic_read(&itv->capturing) == 0)
1035 		cx2341x_handler_set_busy(&itv->cxhdl, 0);
1036 
1037 	return 0;
1038 }
1039