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