Merge branch 'upstream-jgarzik' of git://git.kernel.org/pub/scm/linux/kernel/git...
[linux-2.6] / drivers / media / video / ivtv / ivtv-fileops.c
1 /*
2     file operation 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 #include "ivtv-driver.h"
23 #include "ivtv-fileops.h"
24 #include "ivtv-i2c.h"
25 #include "ivtv-queue.h"
26 #include "ivtv-udma.h"
27 #include "ivtv-irq.h"
28 #include "ivtv-vbi.h"
29 #include "ivtv-mailbox.h"
30 #include "ivtv-audio.h"
31 #include "ivtv-streams.h"
32 #include "ivtv-yuv.h"
33 #include "ivtv-controls.h"
34 #include "ivtv-ioctl.h"
35 #include "ivtv-cards.h"
36 #include <media/saa7115.h>
37
38 /* This function tries to claim the stream for a specific file descriptor.
39    If no one else is using this stream then the stream is claimed and
40    associated VBI streams are also automatically claimed.
41    Possible error returns: -EBUSY if someone else has claimed
42    the stream or 0 on success. */
43 int ivtv_claim_stream(struct ivtv_open_id *id, int type)
44 {
45         struct ivtv *itv = id->itv;
46         struct ivtv_stream *s = &itv->streams[type];
47         struct ivtv_stream *s_vbi;
48         int vbi_type;
49
50         if (test_and_set_bit(IVTV_F_S_CLAIMED, &s->s_flags)) {
51                 /* someone already claimed this stream */
52                 if (s->id == id->open_id) {
53                         /* yes, this file descriptor did. So that's OK. */
54                         return 0;
55                 }
56                 if (s->id == -1 && (type == IVTV_DEC_STREAM_TYPE_VBI ||
57                                          type == IVTV_ENC_STREAM_TYPE_VBI)) {
58                         /* VBI is handled already internally, now also assign
59                            the file descriptor to this stream for external
60                            reading of the stream. */
61                         s->id = id->open_id;
62                         IVTV_DEBUG_INFO("Start Read VBI\n");
63                         return 0;
64                 }
65                 /* someone else is using this stream already */
66                 IVTV_DEBUG_INFO("Stream %d is busy\n", type);
67                 return -EBUSY;
68         }
69         s->id = id->open_id;
70         if (type == IVTV_DEC_STREAM_TYPE_VBI) {
71                 /* Enable reinsertion interrupt */
72                 ivtv_clear_irq_mask(itv, IVTV_IRQ_DEC_VBI_RE_INSERT);
73         }
74
75         /* IVTV_DEC_STREAM_TYPE_MPG needs to claim IVTV_DEC_STREAM_TYPE_VBI,
76            IVTV_ENC_STREAM_TYPE_MPG needs to claim IVTV_ENC_STREAM_TYPE_VBI
77            (provided VBI insertion is on and sliced VBI is selected), for all
78            other streams we're done */
79         if (type == IVTV_DEC_STREAM_TYPE_MPG) {
80                 vbi_type = IVTV_DEC_STREAM_TYPE_VBI;
81         } else if (type == IVTV_ENC_STREAM_TYPE_MPG &&
82                    itv->vbi.insert_mpeg && itv->vbi.sliced_in->service_set) {
83                 vbi_type = IVTV_ENC_STREAM_TYPE_VBI;
84         } else {
85                 return 0;
86         }
87         s_vbi = &itv->streams[vbi_type];
88
89         if (!test_and_set_bit(IVTV_F_S_CLAIMED, &s_vbi->s_flags)) {
90                 /* Enable reinsertion interrupt */
91                 if (vbi_type == IVTV_DEC_STREAM_TYPE_VBI)
92                         ivtv_clear_irq_mask(itv, IVTV_IRQ_DEC_VBI_RE_INSERT);
93         }
94         /* mark that it is used internally */
95         set_bit(IVTV_F_S_INTERNAL_USE, &s_vbi->s_flags);
96         return 0;
97 }
98
99 /* This function releases a previously claimed stream. It will take into
100    account associated VBI streams. */
101 void ivtv_release_stream(struct ivtv_stream *s)
102 {
103         struct ivtv *itv = s->itv;
104         struct ivtv_stream *s_vbi;
105
106         s->id = -1;
107         if ((s->type == IVTV_DEC_STREAM_TYPE_VBI || s->type == IVTV_ENC_STREAM_TYPE_VBI) &&
108                 test_bit(IVTV_F_S_INTERNAL_USE, &s->s_flags)) {
109                 /* this stream is still in use internally */
110                 return;
111         }
112         if (!test_and_clear_bit(IVTV_F_S_CLAIMED, &s->s_flags)) {
113                 IVTV_DEBUG_WARN("Release stream %s not in use!\n", s->name);
114                 return;
115         }
116
117         ivtv_flush_queues(s);
118
119         /* disable reinsertion interrupt */
120         if (s->type == IVTV_DEC_STREAM_TYPE_VBI)
121                 ivtv_set_irq_mask(itv, IVTV_IRQ_DEC_VBI_RE_INSERT);
122
123         /* IVTV_DEC_STREAM_TYPE_MPG needs to release IVTV_DEC_STREAM_TYPE_VBI,
124            IVTV_ENC_STREAM_TYPE_MPG needs to release IVTV_ENC_STREAM_TYPE_VBI,
125            for all other streams we're done */
126         if (s->type == IVTV_DEC_STREAM_TYPE_MPG)
127                 s_vbi = &itv->streams[IVTV_DEC_STREAM_TYPE_VBI];
128         else if (s->type == IVTV_ENC_STREAM_TYPE_MPG)
129                 s_vbi = &itv->streams[IVTV_ENC_STREAM_TYPE_VBI];
130         else
131                 return;
132
133         /* clear internal use flag */
134         if (!test_and_clear_bit(IVTV_F_S_INTERNAL_USE, &s_vbi->s_flags)) {
135                 /* was already cleared */
136                 return;
137         }
138         if (s_vbi->id != -1) {
139                 /* VBI stream still claimed by a file descriptor */
140                 return;
141         }
142         /* disable reinsertion interrupt */
143         if (s_vbi->type == IVTV_DEC_STREAM_TYPE_VBI)
144                 ivtv_set_irq_mask(itv, IVTV_IRQ_DEC_VBI_RE_INSERT);
145         clear_bit(IVTV_F_S_CLAIMED, &s_vbi->s_flags);
146         ivtv_flush_queues(s_vbi);
147 }
148
149 static void ivtv_dualwatch(struct ivtv *itv)
150 {
151         struct v4l2_tuner vt;
152         u16 new_bitmap;
153         u16 new_stereo_mode;
154         const u16 stereo_mask = 0x0300;
155         const u16 dual = 0x0200;
156
157         new_stereo_mode = itv->params.audio_properties & stereo_mask;
158         memset(&vt, 0, sizeof(vt));
159         ivtv_call_i2c_clients(itv, VIDIOC_G_TUNER, &vt);
160         if (vt.audmode == V4L2_TUNER_MODE_LANG1_LANG2 && (vt.rxsubchans & V4L2_TUNER_SUB_LANG2))
161                 new_stereo_mode = dual;
162
163         if (new_stereo_mode == itv->dualwatch_stereo_mode)
164                 return;
165
166         new_bitmap = new_stereo_mode | (itv->params.audio_properties & ~stereo_mask);
167
168         IVTV_DEBUG_INFO("dualwatch: change stereo flag from 0x%x to 0x%x. new audio_bitmask=0x%ux\n",
169                            itv->dualwatch_stereo_mode, new_stereo_mode, new_bitmap);
170
171         if (ivtv_vapi(itv, CX2341X_ENC_SET_AUDIO_PROPERTIES, 1, new_bitmap) == 0) {
172                 itv->dualwatch_stereo_mode = new_stereo_mode;
173                 return;
174         }
175         IVTV_DEBUG_INFO("dualwatch: changing stereo flag failed\n");
176 }
177
178 static void ivtv_update_pgm_info(struct ivtv *itv)
179 {
180         u32 wr_idx = (read_enc(itv->pgm_info_offset) - itv->pgm_info_offset - 4) / 24;
181         int cnt;
182         int i = 0;
183
184         if (wr_idx >= itv->pgm_info_num) {
185                 IVTV_DEBUG_WARN("Invalid PGM index %d (>= %d)\n", wr_idx, itv->pgm_info_num);
186                 return;
187         }
188         cnt = (wr_idx + itv->pgm_info_num - itv->pgm_info_write_idx) % itv->pgm_info_num;
189         while (i < cnt) {
190                 int idx = (itv->pgm_info_write_idx + i) % itv->pgm_info_num;
191                 struct v4l2_enc_idx_entry *e = itv->pgm_info + idx;
192                 u32 addr = itv->pgm_info_offset + 4 + idx * 24;
193                 const int mapping[] = { V4L2_ENC_IDX_FRAME_P, V4L2_ENC_IDX_FRAME_I, V4L2_ENC_IDX_FRAME_B, 0 };
194
195                 e->offset = read_enc(addr + 4) + ((u64)read_enc(addr + 8) << 32);
196                 if (e->offset > itv->mpg_data_received) {
197                         break;
198                 }
199                 e->offset += itv->vbi_data_inserted;
200                 e->length = read_enc(addr);
201                 e->pts = read_enc(addr + 16) + ((u64)(read_enc(addr + 20) & 1) << 32);
202                 e->flags = mapping[read_enc(addr + 12) & 3];
203                 i++;
204         }
205         itv->pgm_info_write_idx = (itv->pgm_info_write_idx + i) % itv->pgm_info_num;
206 }
207
208 static struct ivtv_buffer *ivtv_get_buffer(struct ivtv_stream *s, int non_block, int *err)
209 {
210         struct ivtv *itv = s->itv;
211         struct ivtv_stream *s_vbi = &itv->streams[IVTV_ENC_STREAM_TYPE_VBI];
212         struct ivtv_buffer *buf;
213         DEFINE_WAIT(wait);
214
215         *err = 0;
216         while (1) {
217                 if (s->type == IVTV_ENC_STREAM_TYPE_MPG) {
218                         /* Process pending program info updates and pending VBI data */
219                         ivtv_update_pgm_info(itv);
220
221                         if (jiffies - itv->dualwatch_jiffies > HZ) {
222                                 itv->dualwatch_jiffies = jiffies;
223                                 ivtv_dualwatch(itv);
224                         }
225
226                         if (test_bit(IVTV_F_S_INTERNAL_USE, &s_vbi->s_flags) &&
227                             !test_bit(IVTV_F_S_APPL_IO, &s_vbi->s_flags)) {
228                                 while ((buf = ivtv_dequeue(s_vbi, &s_vbi->q_full))) {
229                                         /* byteswap and process VBI data */
230                                         ivtv_process_vbi_data(itv, buf, s_vbi->dma_pts, s_vbi->type);
231                                         ivtv_enqueue(s_vbi, buf, &s_vbi->q_free);
232                                 }
233                         }
234                         buf = &itv->vbi.sliced_mpeg_buf;
235                         if (buf->readpos != buf->bytesused) {
236                                 return buf;
237                         }
238                 }
239
240                 /* do we have leftover data? */
241                 buf = ivtv_dequeue(s, &s->q_io);
242                 if (buf)
243                         return buf;
244
245                 /* do we have new data? */
246                 buf = ivtv_dequeue(s, &s->q_full);
247                 if (buf) {
248                         if (!test_and_clear_bit(IVTV_F_B_NEED_BUF_SWAP, &buf->b_flags))
249                                 return buf;
250                         if (s->type == IVTV_ENC_STREAM_TYPE_MPG)
251                                 /* byteswap MPG data */
252                                 ivtv_buf_swap(buf);
253                         else if (s->type != IVTV_DEC_STREAM_TYPE_VBI) {
254                                 /* byteswap and process VBI data */
255                                 ivtv_process_vbi_data(itv, buf, s->dma_pts, s->type);
256                         }
257                         return buf;
258                 }
259                 /* return if file was opened with O_NONBLOCK */
260                 if (non_block) {
261                         *err = -EAGAIN;
262                         return NULL;
263                 }
264
265                 /* return if end of stream */
266                 if (s->type != IVTV_DEC_STREAM_TYPE_VBI && !test_bit(IVTV_F_S_STREAMING, &s->s_flags)) {
267                         clear_bit(IVTV_F_S_STREAMOFF, &s->s_flags);
268                         IVTV_DEBUG_INFO("EOS %s\n", s->name);
269                         return NULL;
270                 }
271
272                 /* wait for more data to arrive */
273                 prepare_to_wait(&s->waitq, &wait, TASK_INTERRUPTIBLE);
274                 /* New buffers might have become available before we were added to the waitqueue */
275                 if (!s->q_full.buffers)
276                         schedule();
277                 finish_wait(&s->waitq, &wait);
278                 if (signal_pending(current)) {
279                         /* return if a signal was received */
280                         IVTV_DEBUG_INFO("User stopped %s\n", s->name);
281                         *err = -EINTR;
282                         return NULL;
283                 }
284         }
285 }
286
287 static void ivtv_setup_sliced_vbi_buf(struct ivtv *itv)
288 {
289         int idx = itv->vbi.inserted_frame % IVTV_VBI_FRAMES;
290
291         itv->vbi.sliced_mpeg_buf.buf = itv->vbi.sliced_mpeg_data[idx];
292         itv->vbi.sliced_mpeg_buf.bytesused = itv->vbi.sliced_mpeg_size[idx];
293         itv->vbi.sliced_mpeg_buf.readpos = 0;
294 }
295
296 static size_t ivtv_copy_buf_to_user(struct ivtv_stream *s, struct ivtv_buffer *buf,
297                 char __user *ubuf, size_t ucount)
298 {
299         struct ivtv *itv = s->itv;
300         size_t len = buf->bytesused - buf->readpos;
301
302         if (len > ucount) len = ucount;
303         if (itv->vbi.insert_mpeg && s->type == IVTV_ENC_STREAM_TYPE_MPG &&
304             itv->vbi.sliced_in->service_set && buf != &itv->vbi.sliced_mpeg_buf) {
305                 const char *start = buf->buf + buf->readpos;
306                 const char *p = start + 1;
307                 const u8 *q;
308                 u8 ch = itv->search_pack_header ? 0xba : 0xe0;
309                 int stuffing, i;
310
311                 while (start + len > p && (q = memchr(p, 0, start + len - p))) {
312                         p = q + 1;
313                         if ((char *)q + 15 >= buf->buf + buf->bytesused ||
314                             q[1] != 0 || q[2] != 1 || q[3] != ch) {
315                                 continue;
316                         }
317                         if (!itv->search_pack_header) {
318                                 if ((q[6] & 0xc0) != 0x80)
319                                         continue;
320                                 if (((q[7] & 0xc0) == 0x80 && (q[9] & 0xf0) == 0x20) ||
321                                     ((q[7] & 0xc0) == 0xc0 && (q[9] & 0xf0) == 0x30)) {
322                                         ch = 0xba;
323                                         itv->search_pack_header = 1;
324                                         p = q + 9;
325                                 }
326                                 continue;
327                         }
328                         stuffing = q[13] & 7;
329                         /* all stuffing bytes must be 0xff */
330                         for (i = 0; i < stuffing; i++)
331                                 if (q[14 + i] != 0xff)
332                                         break;
333                         if (i == stuffing && (q[4] & 0xc4) == 0x44 && (q[12] & 3) == 3 &&
334                                         q[14 + stuffing] == 0 && q[15 + stuffing] == 0 &&
335                                         q[16 + stuffing] == 1) {
336                                 itv->search_pack_header = 0;
337                                 len = (char *)q - start;
338                                 ivtv_setup_sliced_vbi_buf(itv);
339                                 break;
340                         }
341                 }
342         }
343         if (copy_to_user(ubuf, (u8 *)buf->buf + buf->readpos, len)) {
344                 IVTV_DEBUG_WARN("copy %zd bytes to user failed for %s\n", len, s->name);
345                 return -EFAULT;
346         }
347         /*IVTV_INFO("copied %lld %d %d %d %d %d vbi %d\n", itv->mpg_data_received, len, ucount,
348                         buf->readpos, buf->bytesused, buf->bytesused - buf->readpos - len,
349                         buf == &itv->vbi.sliced_mpeg_buf); */
350         buf->readpos += len;
351         if (s->type == IVTV_ENC_STREAM_TYPE_MPG && buf != &itv->vbi.sliced_mpeg_buf)
352                 itv->mpg_data_received += len;
353         return len;
354 }
355
356 static ssize_t ivtv_read(struct ivtv_stream *s, char __user *ubuf, size_t tot_count, int non_block)
357 {
358         struct ivtv *itv = s->itv;
359         size_t tot_written = 0;
360         int single_frame = 0;
361
362         if (atomic_read(&itv->capturing) == 0 && s->id == -1) {
363                 /* shouldn't happen */
364                 IVTV_DEBUG_WARN("Stream %s not initialized before read\n", s->name);
365                 return -EIO;
366         }
367
368         /* Each VBI buffer is one frame, the v4l2 API says that for VBI the frames should
369            arrive one-by-one, so make sure we never output more than one VBI frame at a time */
370         if (s->type == IVTV_DEC_STREAM_TYPE_VBI ||
371                         (s->type == IVTV_ENC_STREAM_TYPE_VBI && itv->vbi.sliced_in->service_set))
372                 single_frame = 1;
373
374         for (;;) {
375                 struct ivtv_buffer *buf;
376                 int rc;
377
378                 buf = ivtv_get_buffer(s, non_block, &rc);
379                 if (buf == NULL && rc == -EAGAIN && tot_written)
380                         break;
381                 if (buf == NULL)
382                         return rc;
383                 rc = ivtv_copy_buf_to_user(s, buf, ubuf + tot_written, tot_count - tot_written);
384                 if (buf != &itv->vbi.sliced_mpeg_buf) {
385                         ivtv_enqueue(s, buf, (buf->readpos == buf->bytesused) ? &s->q_free : &s->q_io);
386                 }
387                 else if (buf->readpos == buf->bytesused) {
388                         int idx = itv->vbi.inserted_frame % IVTV_VBI_FRAMES;
389                         itv->vbi.sliced_mpeg_size[idx] = 0;
390                         itv->vbi.inserted_frame++;
391                         itv->vbi_data_inserted += buf->bytesused;
392                 }
393                 if (rc < 0)
394                         return rc;
395                 tot_written += rc;
396
397                 if (tot_written == tot_count || single_frame)
398                         break;
399         }
400         return tot_written;
401 }
402
403 static ssize_t ivtv_read_pos(struct ivtv_stream *s, char __user *ubuf, size_t count,
404                         loff_t *pos, int non_block)
405 {
406         ssize_t rc = count ? ivtv_read(s, ubuf, count, non_block) : 0;
407         struct ivtv *itv = s->itv;
408
409         IVTV_DEBUG_HI_INFO("read %zd from %s, got %zd\n", count, s->name, rc);
410         if (rc > 0)
411                 pos += rc;
412         return rc;
413 }
414
415 int ivtv_start_capture(struct ivtv_open_id *id)
416 {
417         struct ivtv *itv = id->itv;
418         struct ivtv_stream *s = &itv->streams[id->type];
419         struct ivtv_stream *s_vbi;
420
421         if (s->type == IVTV_ENC_STREAM_TYPE_RAD ||
422             s->type == IVTV_DEC_STREAM_TYPE_MPG ||
423             s->type == IVTV_DEC_STREAM_TYPE_YUV ||
424             s->type == IVTV_DEC_STREAM_TYPE_VOUT) {
425                 /* you cannot read from these stream types. */
426                 return -EPERM;
427         }
428
429         /* Try to claim this stream. */
430         if (ivtv_claim_stream(id, s->type))
431                 return -EBUSY;
432
433         /* This stream does not need to start capturing */
434         if (s->type == IVTV_DEC_STREAM_TYPE_VBI) {
435                 set_bit(IVTV_F_S_APPL_IO, &s->s_flags);
436                 return 0;
437         }
438
439         /* If capture is already in progress, then we also have to
440            do nothing extra. */
441         if (test_bit(IVTV_F_S_STREAMOFF, &s->s_flags) || test_and_set_bit(IVTV_F_S_STREAMING, &s->s_flags)) {
442                 set_bit(IVTV_F_S_APPL_IO, &s->s_flags);
443                 return 0;
444         }
445
446         /* Start VBI capture if required */
447         s_vbi = &itv->streams[IVTV_ENC_STREAM_TYPE_VBI];
448         if (s->type == IVTV_ENC_STREAM_TYPE_MPG &&
449             test_bit(IVTV_F_S_INTERNAL_USE, &s_vbi->s_flags) &&
450             !test_and_set_bit(IVTV_F_S_STREAMING, &s_vbi->s_flags)) {
451                 /* Note: the IVTV_ENC_STREAM_TYPE_VBI is claimed
452                    automatically when the MPG stream is claimed.
453                    We only need to start the VBI capturing. */
454                 if (ivtv_start_v4l2_encode_stream(s_vbi)) {
455                         IVTV_DEBUG_WARN("VBI capture start failed\n");
456
457                         /* Failure, clean up and return an error */
458                         clear_bit(IVTV_F_S_STREAMING, &s_vbi->s_flags);
459                         clear_bit(IVTV_F_S_STREAMING, &s->s_flags);
460                         /* also releases the associated VBI stream */
461                         ivtv_release_stream(s);
462                         return -EIO;
463                 }
464                 IVTV_DEBUG_INFO("VBI insertion started\n");
465         }
466
467         /* Tell the card to start capturing */
468         if (!ivtv_start_v4l2_encode_stream(s)) {
469                 /* We're done */
470                 set_bit(IVTV_F_S_APPL_IO, &s->s_flags);
471                 /* Resume a possibly paused encoder */
472                 if (test_and_clear_bit(IVTV_F_I_ENC_PAUSED, &itv->i_flags))
473                         ivtv_vapi(itv, CX2341X_ENC_PAUSE_ENCODER, 1, 1);
474                 return 0;
475         }
476
477         /* failure, clean up */
478         IVTV_DEBUG_WARN("Failed to start capturing for stream %s\n", s->name);
479
480         /* Note: the IVTV_ENC_STREAM_TYPE_VBI is released
481            automatically when the MPG stream is released.
482            We only need to stop the VBI capturing. */
483         if (s->type == IVTV_ENC_STREAM_TYPE_MPG &&
484             test_bit(IVTV_F_S_STREAMING, &s_vbi->s_flags)) {
485                 ivtv_stop_v4l2_encode_stream(s_vbi, 0);
486                 clear_bit(IVTV_F_S_STREAMING, &s_vbi->s_flags);
487         }
488         clear_bit(IVTV_F_S_STREAMING, &s->s_flags);
489         ivtv_release_stream(s);
490         return -EIO;
491 }
492
493 ssize_t ivtv_v4l2_read(struct file * filp, char __user *buf, size_t count, loff_t * pos)
494 {
495         struct ivtv_open_id *id = filp->private_data;
496         struct ivtv *itv = id->itv;
497         struct ivtv_stream *s = &itv->streams[id->type];
498         int rc;
499
500         IVTV_DEBUG_HI_IOCTL("read %zd bytes from %s\n", count, s->name);
501
502         rc = ivtv_start_capture(id);
503         if (rc)
504                 return rc;
505         return ivtv_read_pos(s, buf, count, pos, filp->f_flags & O_NONBLOCK);
506 }
507
508 int ivtv_start_decoding(struct ivtv_open_id *id, int speed)
509 {
510         struct ivtv *itv = id->itv;
511         struct ivtv_stream *s = &itv->streams[id->type];
512
513         if (atomic_read(&itv->decoding) == 0) {
514                 if (ivtv_claim_stream(id, s->type)) {
515                         /* someone else is using this stream already */
516                         IVTV_DEBUG_WARN("start decode, stream already claimed\n");
517                         return -EBUSY;
518                 }
519                 ivtv_start_v4l2_decode_stream(s, 0);
520         }
521         if (s->type == IVTV_DEC_STREAM_TYPE_MPG)
522                 return ivtv_set_speed(itv, speed);
523         return 0;
524 }
525
526 ssize_t ivtv_v4l2_write(struct file *filp, const char __user *user_buf, size_t count, loff_t *pos)
527 {
528         struct ivtv_open_id *id = filp->private_data;
529         struct ivtv *itv = id->itv;
530         struct ivtv_stream *s = &itv->streams[id->type];
531         struct ivtv_buffer *buf;
532         struct ivtv_queue q;
533         int bytes_written = 0;
534         int mode;
535         int rc;
536         DEFINE_WAIT(wait);
537
538         IVTV_DEBUG_HI_IOCTL("write %zd bytes to %s\n", count, s->name);
539
540         if (s->type != IVTV_DEC_STREAM_TYPE_MPG &&
541             s->type != IVTV_DEC_STREAM_TYPE_YUV &&
542             s->type != IVTV_DEC_STREAM_TYPE_VOUT)
543                 /* not decoder streams */
544                 return -EPERM;
545
546         /* Try to claim this stream */
547         if (ivtv_claim_stream(id, s->type))
548                 return -EBUSY;
549
550         /* This stream does not need to start any decoding */
551         if (s->type == IVTV_DEC_STREAM_TYPE_VOUT) {
552                 set_bit(IVTV_F_S_APPL_IO, &s->s_flags);
553                 return ivtv_write_vbi(itv, user_buf, count);
554         }
555
556         mode = s->type == IVTV_DEC_STREAM_TYPE_MPG ? OUT_MPG : OUT_YUV;
557
558         if (ivtv_set_output_mode(itv, mode) != mode) {
559             ivtv_release_stream(s);
560             return -EBUSY;
561         }
562         ivtv_queue_init(&q);
563         set_bit(IVTV_F_S_APPL_IO, &s->s_flags);
564
565 retry:
566         for (;;) {
567                 /* Gather buffers */
568                 while (q.length - q.bytesused < count && (buf = ivtv_dequeue(s, &s->q_io)))
569                         ivtv_enqueue(s, buf, &q);
570                 while (q.length - q.bytesused < count && (buf = ivtv_dequeue(s, &s->q_free))) {
571                         ivtv_enqueue(s, buf, &q);
572                 }
573                 if (q.buffers)
574                         break;
575                 if (filp->f_flags & O_NONBLOCK)
576                         return -EAGAIN;
577                 prepare_to_wait(&s->waitq, &wait, TASK_INTERRUPTIBLE);
578                 /* New buffers might have become free before we were added to the waitqueue */
579                 if (!s->q_free.buffers)
580                         schedule();
581                 finish_wait(&s->waitq, &wait);
582                 if (signal_pending(current)) {
583                         IVTV_DEBUG_INFO("User stopped %s\n", s->name);
584                         return -EINTR;
585                 }
586         }
587
588         /* copy user data into buffers */
589         while ((buf = ivtv_dequeue(s, &q))) {
590                 /* Make sure we really got all the user data */
591                 rc = ivtv_buf_copy_from_user(s, buf, user_buf, count);
592
593                 if (rc < 0) {
594                         ivtv_queue_move(s, &q, NULL, &s->q_free, 0);
595                         return rc;
596                 }
597                 user_buf += rc;
598                 count -= rc;
599                 bytes_written += rc;
600
601                 if (buf->bytesused != s->buf_size) {
602                         /* incomplete, leave in q_io for next time */
603                         ivtv_enqueue(s, buf, &s->q_io);
604                         break;
605                 }
606                 /* Byteswap MPEG buffer */
607                 if (s->type == IVTV_DEC_STREAM_TYPE_MPG)
608                         ivtv_buf_swap(buf);
609                 ivtv_enqueue(s, buf, &s->q_full);
610         }
611
612         /* Start decoder (returns 0 if already started) */
613         rc = ivtv_start_decoding(id, itv->speed);
614         if (rc) {
615                 IVTV_DEBUG_WARN("Failed start decode stream %s\n", s->name);
616
617                 /* failure, clean up */
618                 clear_bit(IVTV_F_S_STREAMING, &s->s_flags);
619                 clear_bit(IVTV_F_S_APPL_IO, &s->s_flags);
620                 return rc;
621         }
622         if (test_bit(IVTV_F_S_NEEDS_DATA, &s->s_flags)) {
623                 if (s->q_full.length >= itv->dma_data_req_size) {
624                         int got_sig;
625
626                         prepare_to_wait(&itv->dma_waitq, &wait, TASK_INTERRUPTIBLE);
627                         while (!(got_sig = signal_pending(current)) &&
628                                         test_bit(IVTV_F_S_DMA_PENDING, &s->s_flags)) {
629                                 schedule();
630                         }
631                         finish_wait(&itv->dma_waitq, &wait);
632                         if (got_sig) {
633                                 IVTV_DEBUG_INFO("User interrupted %s\n", s->name);
634                                 return -EINTR;
635                         }
636
637                         clear_bit(IVTV_F_S_NEEDS_DATA, &s->s_flags);
638                         ivtv_queue_move(s, &s->q_full, NULL, &s->q_predma, itv->dma_data_req_size);
639                         ivtv_dma_stream_dec_prepare(s, itv->dma_data_req_offset + IVTV_DECODER_OFFSET, 1);
640                 }
641         }
642         /* more user data is available, wait until buffers become free
643            to transfer the rest. */
644         if (count && !(filp->f_flags & O_NONBLOCK))
645                 goto retry;
646         IVTV_DEBUG_HI_INFO("Wrote %d bytes to %s (%d)\n", bytes_written, s->name, s->q_full.bytesused);
647         return bytes_written;
648 }
649
650 unsigned int ivtv_v4l2_dec_poll(struct file *filp, poll_table *wait)
651 {
652         struct ivtv_open_id *id = filp->private_data;
653         struct ivtv *itv = id->itv;
654         struct ivtv_stream *s = &itv->streams[id->type];
655         int res = 0;
656
657         /* add stream's waitq to the poll list */
658         poll_wait(filp, &s->waitq, wait);
659
660         set_bit(IVTV_F_I_EV_VSYNC_ENABLED, &itv->i_flags);
661         if (test_bit(IVTV_F_I_EV_VSYNC, &itv->i_flags) ||
662             test_bit(IVTV_F_I_EV_DEC_STOPPED, &itv->i_flags))
663                 res = POLLPRI;
664
665         /* Allow write if buffers are available for writing */
666         if (s->q_free.buffers)
667                 res |= POLLOUT | POLLWRNORM;
668         return res;
669 }
670
671 unsigned int ivtv_v4l2_enc_poll(struct file *filp, poll_table * wait)
672 {
673         struct ivtv_open_id *id = filp->private_data;
674         struct ivtv *itv = id->itv;
675         struct ivtv_stream *s = &itv->streams[id->type];
676         int eof = test_bit(IVTV_F_S_STREAMOFF, &s->s_flags);
677
678         /* Start a capture if there is none */
679         if (!eof && !test_bit(IVTV_F_S_STREAMING, &s->s_flags)) {
680                 int rc = ivtv_start_capture(id);
681
682                 if (rc) {
683                         IVTV_DEBUG_INFO("Could not start capture for %s (%d)\n",
684                                         s->name, rc);
685                         return POLLERR;
686                 }
687         }
688
689         /* add stream's waitq to the poll list */
690         poll_wait(filp, &s->waitq, wait);
691
692         if (eof || s->q_full.length)
693                 return POLLIN | POLLRDNORM;
694         return 0;
695 }
696
697 void ivtv_stop_capture(struct ivtv_open_id *id, int gop_end)
698 {
699         struct ivtv *itv = id->itv;
700         struct ivtv_stream *s = &itv->streams[id->type];
701
702         IVTV_DEBUG_IOCTL("close() of %s\n", s->name);
703
704         /* 'Unclaim' this stream */
705
706         /* Stop capturing */
707         if (test_bit(IVTV_F_S_STREAMING, &s->s_flags)) {
708                 struct ivtv_stream *s_vbi = &itv->streams[IVTV_ENC_STREAM_TYPE_VBI];
709
710                 IVTV_DEBUG_INFO("close stopping capture\n");
711                 /* Special case: a running VBI capture for VBI insertion
712                    in the mpeg stream. Need to stop that too. */
713                 if (id->type == IVTV_ENC_STREAM_TYPE_MPG &&
714                     test_bit(IVTV_F_S_STREAMING, &s_vbi->s_flags) &&
715                     !test_bit(IVTV_F_S_APPL_IO, &s_vbi->s_flags)) {
716                         IVTV_DEBUG_INFO("close stopping embedded VBI capture\n");
717                         ivtv_stop_v4l2_encode_stream(s_vbi, 0);
718                 }
719                 if ((id->type == IVTV_DEC_STREAM_TYPE_VBI ||
720                      id->type == IVTV_ENC_STREAM_TYPE_VBI) &&
721                     test_bit(IVTV_F_S_INTERNAL_USE, &s->s_flags)) {
722                         /* Also used internally, don't stop capturing */
723                         s->id = -1;
724                 }
725                 else {
726                         ivtv_stop_v4l2_encode_stream(s, gop_end);
727                 }
728         }
729         clear_bit(IVTV_F_S_APPL_IO, &s->s_flags);
730         clear_bit(IVTV_F_S_STREAMOFF, &s->s_flags);
731
732         ivtv_release_stream(s);
733 }
734
735 static void ivtv_stop_decoding(struct ivtv_open_id *id, int flags, u64 pts)
736 {
737         struct ivtv *itv = id->itv;
738         struct ivtv_stream *s = &itv->streams[id->type];
739
740         IVTV_DEBUG_IOCTL("close() of %s\n", s->name);
741
742         /* Stop decoding */
743         if (test_bit(IVTV_F_S_STREAMING, &s->s_flags)) {
744                 IVTV_DEBUG_INFO("close stopping decode\n");
745
746                 ivtv_stop_v4l2_decode_stream(s, flags, pts);
747         }
748         clear_bit(IVTV_F_S_APPL_IO, &s->s_flags);
749         clear_bit(IVTV_F_S_STREAMOFF, &s->s_flags);
750         if (id->type == IVTV_DEC_STREAM_TYPE_YUV && test_bit(IVTV_F_I_DECODING_YUV, &itv->i_flags)) {
751                 /* Restore registers we've changed & clean up any mess we've made */
752                 ivtv_yuv_close(itv);
753         }
754         if (s->type == IVTV_DEC_STREAM_TYPE_YUV && itv->output_mode == OUT_YUV)
755             itv->output_mode = OUT_NONE;
756         else if (s->type == IVTV_DEC_STREAM_TYPE_MPG && itv->output_mode == OUT_MPG)
757             itv->output_mode = OUT_NONE;
758
759         itv->speed = 0;
760         ivtv_release_stream(s);
761 }
762
763 int ivtv_v4l2_close(struct inode *inode, struct file *filp)
764 {
765         struct ivtv_open_id *id = filp->private_data;
766         struct ivtv *itv = id->itv;
767         struct ivtv_stream *s = &itv->streams[id->type];
768
769         IVTV_DEBUG_IOCTL("close() of %s\n", s->name);
770
771         v4l2_prio_close(&itv->prio, &id->prio);
772
773         /* Easy case first: this stream was never claimed by us */
774         if (s->id != id->open_id) {
775                 kfree(id);
776                 return 0;
777         }
778
779         /* 'Unclaim' this stream */
780
781         /* Stop radio */
782         if (id->type == IVTV_ENC_STREAM_TYPE_RAD) {
783                 /* Closing radio device, return to TV mode */
784                 ivtv_mute(itv);
785                 /* Mark that the radio is no longer in use */
786                 clear_bit(IVTV_F_I_RADIO_USER, &itv->i_flags);
787                 /* Switch tuner to TV */
788                 ivtv_call_i2c_clients(itv, VIDIOC_S_STD, &itv->std);
789                 /* Select correct audio input (i.e. TV tuner or Line in) */
790                 ivtv_audio_set_io(itv);
791                 if (itv->hw_flags & IVTV_HW_SAA711X)
792                 {
793                         struct v4l2_crystal_freq crystal_freq;
794                         crystal_freq.freq = SAA7115_FREQ_32_11_MHZ;
795                         crystal_freq.flags = 0;
796                         ivtv_saa7115(itv, VIDIOC_INT_S_CRYSTAL_FREQ, &crystal_freq);
797                 }
798                 /* Done! Unmute and continue. */
799                 ivtv_unmute(itv);
800                 ivtv_release_stream(s);
801         } else if (s->type >= IVTV_DEC_STREAM_TYPE_MPG) {
802                 ivtv_stop_decoding(id, VIDEO_CMD_STOP_TO_BLACK | VIDEO_CMD_STOP_IMMEDIATELY, 0);
803         } else {
804                 ivtv_stop_capture(id, 0);
805         }
806         kfree(id);
807         return 0;
808 }
809
810 int ivtv_v4l2_open(struct inode *inode, struct file *filp)
811 {
812         int x, y = 0;
813         struct ivtv_open_id *item;
814         struct ivtv *itv = NULL;
815         struct ivtv_stream *s = NULL;
816         int minor = iminor(inode);
817
818         /* Find which card this open was on */
819         spin_lock(&ivtv_cards_lock);
820         for (x = 0; itv == NULL && x < ivtv_cards_active; x++) {
821                 /* find out which stream this open was on */
822                 for (y = 0; y < IVTV_MAX_STREAMS; y++) {
823                         s = &ivtv_cards[x]->streams[y];
824                         if (s->v4l2dev && s->v4l2dev->minor == minor) {
825                                 itv = ivtv_cards[x];
826                                 break;
827                         }
828                 }
829         }
830         spin_unlock(&ivtv_cards_lock);
831
832         if (itv == NULL) {
833                 /* Couldn't find a device registered
834                    on that minor, shouldn't happen! */
835                 printk(KERN_WARNING "ivtv: no ivtv device found on minor %d\n", minor);
836                 return -ENXIO;
837         }
838
839         if (y == IVTV_DEC_STREAM_TYPE_MPG &&
840                 test_bit(IVTV_F_S_CLAIMED, &itv->streams[IVTV_DEC_STREAM_TYPE_YUV].s_flags))
841                 return -EBUSY;
842
843         if (y == IVTV_DEC_STREAM_TYPE_YUV &&
844                 test_bit(IVTV_F_S_CLAIMED, &itv->streams[IVTV_DEC_STREAM_TYPE_MPG].s_flags))
845                 return -EBUSY;
846
847         if (y == IVTV_DEC_STREAM_TYPE_YUV) {
848                 if (read_reg(0x82c) == 0) {
849                         IVTV_ERR("Tried to open YUV output device but need to send data to mpeg decoder before it can be used\n");
850                         /* return -ENODEV; */
851                 }
852                 ivtv_udma_alloc(itv);
853         }
854
855         /* Allocate memory */
856         item = kmalloc(sizeof(struct ivtv_open_id), GFP_KERNEL);
857         if (NULL == item) {
858                 IVTV_DEBUG_WARN("nomem on v4l2 open\n");
859                 return -ENOMEM;
860         }
861         item->itv = itv;
862         item->type = y;
863         v4l2_prio_open(&itv->prio, &item->prio);
864
865         item->open_id = itv->open_id++;
866         filp->private_data = item;
867
868         if (item->type == IVTV_ENC_STREAM_TYPE_RAD) {
869                 /* Try to claim this stream */
870                 if (ivtv_claim_stream(item, item->type)) {
871                         /* No, it's already in use */
872                         kfree(item);
873                         return -EBUSY;
874                 }
875
876                 /* We have the radio */
877                 ivtv_mute(itv);
878                 /* Switch tuner to radio */
879                 ivtv_call_i2c_clients(itv, AUDC_SET_RADIO, NULL);
880                 /* Mark that the radio is being used. */
881                 set_bit(IVTV_F_I_RADIO_USER, &itv->i_flags);
882                 /* Select the correct audio input (i.e. radio tuner) */
883                 ivtv_audio_set_io(itv);
884                 if (itv->hw_flags & IVTV_HW_SAA711X)
885                 {
886                         struct v4l2_crystal_freq crystal_freq;
887                         crystal_freq.freq = SAA7115_FREQ_32_11_MHZ;
888                         crystal_freq.flags = SAA7115_FREQ_FL_APLL;
889                         ivtv_saa7115(itv, VIDIOC_INT_S_CRYSTAL_FREQ, &crystal_freq);
890                 }
891                 /* Done! Unmute and continue. */
892                 ivtv_unmute(itv);
893         }
894
895         /* YUV or MPG Decoding Mode? */
896         if (y == IVTV_DEC_STREAM_TYPE_MPG)
897                 clear_bit(IVTV_F_I_DEC_YUV, &itv->i_flags);
898         else if (y == IVTV_DEC_STREAM_TYPE_YUV)
899         {
900                 set_bit(IVTV_F_I_DEC_YUV, &itv->i_flags);
901         }
902
903         return 0;
904 }
905
906 void ivtv_mute(struct ivtv *itv)
907 {
908         struct v4l2_control ctrl = { V4L2_CID_AUDIO_MUTE, 1 };
909
910         /* Mute sound to avoid pop */
911         ivtv_control_ioctls(itv, VIDIOC_S_CTRL, &ctrl);
912
913         if (atomic_read(&itv->capturing))
914                 ivtv_vapi(itv, CX2341X_ENC_MUTE_AUDIO, 1, 1);
915
916         IVTV_DEBUG_INFO("Mute\n");
917 }
918
919 void ivtv_unmute(struct ivtv *itv)
920 {
921         struct v4l2_control ctrl = { V4L2_CID_AUDIO_MUTE, 0 };
922
923         /* initialize or refresh input */
924         if (atomic_read(&itv->capturing) == 0)
925                 ivtv_vapi(itv, CX2341X_ENC_INITIALIZE_INPUT, 0);
926
927         ivtv_sleep_timeout(HZ / 10, 0);
928
929         if (atomic_read(&itv->capturing)) {
930                 ivtv_vapi(itv, CX2341X_ENC_MISC, 1, 12);
931                 ivtv_vapi(itv, CX2341X_ENC_MUTE_AUDIO, 1, 0);
932         }
933
934         /* Unmute */
935         ivtv_control_ioctls(itv, VIDIOC_S_CTRL, &ctrl);
936         IVTV_DEBUG_INFO("Unmute\n");
937 }