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