mixer: support native audio driver mute
[mplayer.git] / stream / tvi_v4l.c
blob31f767850b6567e84119bd6047e47c1191e1f43c
1 /*
2 * Video 4 Linux input
4 * Copyright (C) 2001 Alex Beregszaszi
6 * Some ideas are based on xawtv/libng's grab-v4l.c written by
7 * Gerd Knorr <kraxel@bytesex.org>
9 * Multithreading, a/v sync and native ALSA support by
10 * Jindrich Makovicka <makovick@gmail.com>
12 * MJPEG hardware encoding support by
13 * Ivan Szanto <szivan@freemail.hu>
15 * CODE IS UNDER DEVELOPMENT, NO FEATURE REQUESTS PLEASE!
17 * This file is part of MPlayer.
19 * MPlayer is free software; you can redistribute it and/or modify
20 * it under the terms of the GNU General Public License as published by
21 * the Free Software Foundation; either version 2 of the License, or
22 * (at your option) any later version.
24 * MPlayer is distributed in the hope that it will be useful,
25 * but WITHOUT ANY WARRANTY; without even the implied warranty of
26 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
27 * GNU General Public License for more details.
29 * You should have received a copy of the GNU General Public License along
30 * with MPlayer; if not, write to the Free Software Foundation, Inc.,
31 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
34 #include "config.h"
36 #include <stdio.h>
37 #include <errno.h>
38 #include <fcntl.h>
39 #include <sys/ioctl.h>
40 #include <sys/types.h>
41 #include <sys/time.h>
43 /* Necessary to prevent collisions between <linux/time.h> and <sys/time.h> when V4L2 is installed. */
44 #define _LINUX_TIME_H
46 #include <linux/videodev.h>
47 #include <unistd.h>
48 #include <sys/mman.h>
49 #include <stdlib.h>
50 #include <string.h>
51 #include <pthread.h>
52 #ifdef HAVE_SYS_SYSINFO_H
53 #include <sys/sysinfo.h>
54 #endif
56 #include "mp_msg.h"
57 #include "libaf/af_format.h"
58 #include "libmpcodecs/img_format.h"
59 #include "libmpcodecs/dec_teletext.h"
60 #include "libvo/fastmemcpy.h"
61 #include "libvo/videodev_mjpeg.h"
63 #include "tv.h"
65 #include "audio_in.h"
67 static tvi_handle_t *tvi_init_v4l(tv_param_t* tv_param);
69 const tvi_info_t tvi_info_v4l = {
70 tvi_init_v4l,
71 "Video 4 Linux input",
72 "v4l",
73 "Alex Beregszaszi",
74 "under development"
77 #define PAL_WIDTH 768
78 #define PAL_HEIGHT 576
79 #define PAL_FPS 25
81 #define NTSC_WIDTH 640
82 #define NTSC_HEIGHT 480
83 #define NTSC_FPS (30000.0/1001.0)
85 #define MAX_AUDIO_CHANNELS 10
87 #define VID_BUF_SIZE_IMMEDIATE 2
88 #define VIDEO_AVG_BUFFER_SIZE 600
90 typedef struct priv {
91 /* general */
92 char *video_device;
93 int video_fd;
94 struct video_capability capability;
95 struct video_channel *channels;
96 int act_channel;
97 struct video_tuner tuner;
99 /* video */
100 struct video_picture picture;
101 int format; /* output format */
102 int width;
103 int height;
104 int bytesperline;
105 float fps;
107 struct video_mbuf mbuf;
108 unsigned char *mmap;
109 struct video_mmap *buf;
110 int nbuf;
112 /* audio */
113 char *audio_device;
114 audio_in_t audio_in;
116 int audio_id;
117 struct video_audio audio[MAX_AUDIO_CHANNELS];
118 int audio_channels[MAX_AUDIO_CHANNELS];
120 /* buffering stuff */
121 int immediate_mode;
123 int audio_buffer_size;
124 int aud_skew_cnt;
125 unsigned char *audio_ringbuffer;
126 long long *audio_skew_buffer;
127 volatile int audio_head;
128 volatile int audio_tail;
129 volatile int audio_cnt;
130 volatile long long audio_skew;
131 volatile double audio_skew_factor;
132 volatile long long audio_skew_measure_time;
133 volatile int audio_drop;
135 int first;
136 int video_buffer_size_max;
137 volatile int video_buffer_size_current;
138 unsigned char **video_ringbuffer;
139 long long *video_timebuffer;
140 long long *video_avg_buffer;
141 int video_avg_ptr;
142 int video_interval_sum;
143 volatile int video_head;
144 volatile int video_tail;
145 volatile int video_cnt;
147 volatile int shutdown;
149 pthread_t audio_grabber_thread;
150 pthread_t video_grabber_thread;
151 pthread_mutex_t audio_starter;
152 pthread_mutex_t skew_mutex;
153 pthread_mutex_t video_buffer_mutex;
155 long long starttime;
156 double audio_secs_per_block;
157 long long audio_skew_total;
158 long audio_recv_blocks_total;
159 long audio_sent_blocks_total;
160 long mjpeg_bufsize;
161 char *vbi_dev;
162 int vbi_fd;
163 int vbi_bufsize;
164 int vbi_shutdown;
165 pthread_t vbi_grabber_thread;
166 void *priv_vbi;
168 tv_param_t *tv_param;
169 } priv_t;
171 #include "tvi_def.h"
173 static const char *device_cap2name[] = {
174 "capture", "tuner", "teletext", "overlay", "chromakey", "clipping",
175 "frameram", "scales", "monochrome", "subcapture", "mpeg-decoder",
176 "mpeg-encoder", "mjpeg-decoder", "mjpeg-encoder", NULL
179 static const char *device_palette2name[] = {
180 "-", "grey", "hi240", "rgb16", "rgb24", "rgb32", "rgb15", "yuv422",
181 "yuyv", "uyvy", "yuv420", "yuv411", "raw", "yuv422p", "yuv411p",
182 "yuv420p", "yuv410p"
184 #define PALETTE(x) ((x < sizeof(device_palette2name)/sizeof(char*)) ? device_palette2name[x] : "UNKNOWN")
186 static const struct {
187 char* name;
188 int normid;
189 int tuner_flags;
190 int tuner_mode;
191 int input_norm;
192 float fps;
193 } supported_norms[]={
194 {"pal", TV_NORM_PAL, VIDEO_TUNER_PAL, VIDEO_MODE_PAL, VIDEO_MODE_PAL, PAL_FPS },
195 {"ntsc", TV_NORM_NTSC, VIDEO_TUNER_NTSC, VIDEO_MODE_NTSC, VIDEO_MODE_NTSC, NTSC_FPS},
196 {"secam", TV_NORM_SECAM, VIDEO_TUNER_SECAM, VIDEO_MODE_SECAM,VIDEO_MODE_SECAM,PAL_FPS },
197 {"palnc", TV_NORM_PALNC, VIDEO_TUNER_PAL, VIDEO_MODE_PAL, 3, PAL_FPS },
198 {"palm", TV_NORM_PALM, VIDEO_TUNER_NTSC, VIDEO_MODE_NTSC, 4, NTSC_FPS},
199 {"paln", TV_NORM_PALN, VIDEO_TUNER_PAL, VIDEO_MODE_PAL, 5, PAL_FPS },
200 {"ntscjp",TV_NORM_NTSCJP, VIDEO_TUNER_NTSC, VIDEO_MODE_NTSC, 6, NTSC_FPS},
201 {"auto", -1, -1, -1, VIDEO_MODE_AUTO, -1 },
202 {NULL, -1, -1, -1, -1 }
205 static const char *norm2name(int mode)
207 int i;
208 for(i=0;supported_norms[i].name; i++)
209 if(supported_norms[i].input_norm==mode)
210 return supported_norms[i].name;
211 return "unknown";
214 static const char *audio_mode2name(int mode)
216 switch (mode) {
217 case VIDEO_SOUND_MONO:
218 return "mono";
219 case VIDEO_SOUND_STEREO:
220 return "stereo";
221 case VIDEO_SOUND_LANG1:
222 return "language1";
223 case VIDEO_SOUND_LANG2:
224 return "language2";
225 default:
226 return "unknown";
230 static void *audio_grabber(void *data);
231 static void *video_grabber(void *data);
233 static int palette2depth(int palette)
235 switch(palette)
237 /* component */
238 case VIDEO_PALETTE_RGB555:
239 return 15;
240 case VIDEO_PALETTE_RGB565:
241 return 16;
242 case VIDEO_PALETTE_RGB24:
243 return 24;
244 case VIDEO_PALETTE_RGB32:
245 return 32;
246 /* planar */
247 case VIDEO_PALETTE_YUV411P:
248 case VIDEO_PALETTE_YUV420P:
249 case VIDEO_PALETTE_YUV410P:
250 return 12;
251 /* packed */
252 case VIDEO_PALETTE_YUV422P:
253 case VIDEO_PALETTE_YUV422:
254 case VIDEO_PALETTE_YUYV:
255 case VIDEO_PALETTE_UYVY:
256 case VIDEO_PALETTE_YUV420:
257 case VIDEO_PALETTE_YUV411:
258 return 16;
260 return -1;
263 static int format2palette(int format)
265 switch(format)
267 case IMGFMT_BGR15:
268 return VIDEO_PALETTE_RGB555;
269 case IMGFMT_BGR16:
270 return VIDEO_PALETTE_RGB565;
271 case IMGFMT_BGR24:
272 return VIDEO_PALETTE_RGB24;
273 case IMGFMT_BGR32:
274 return VIDEO_PALETTE_RGB32;
275 case IMGFMT_YV12:
276 case IMGFMT_I420:
277 return VIDEO_PALETTE_YUV420P;
278 case IMGFMT_YUY2:
279 return VIDEO_PALETTE_YUV422;
280 case IMGFMT_UYVY:
281 return VIDEO_PALETTE_UYVY;
283 return -1;
286 // sets and sanitizes audio buffer/block sizes
287 static void setup_audio_buffer_sizes(priv_t *priv)
289 int bytes_per_sample = priv->audio_in.bytes_per_sample;
291 // make the audio buffer at least 5 seconds long
292 priv->audio_buffer_size = 1 + 5*priv->audio_in.samplerate
293 *priv->audio_in.channels
294 *bytes_per_sample/priv->audio_in.blocksize;
295 if (priv->audio_buffer_size < 256) priv->audio_buffer_size = 256;
297 // make the skew buffer at least 1 second long
298 priv->aud_skew_cnt = 1 + 1*priv->audio_in.samplerate
299 *priv->audio_in.channels
300 *bytes_per_sample/priv->audio_in.blocksize;
301 if (priv->aud_skew_cnt < 16) priv->aud_skew_cnt = 16;
303 mp_msg(MSGT_TV, MSGL_V, "Audio capture - buffer %d blocks of %d bytes, skew average from %d meas.\n",
304 priv->audio_buffer_size, priv->audio_in.blocksize, priv->aud_skew_cnt);
307 static tvi_handle_t *tvi_init_v4l(tv_param_t* tv_param)
309 tvi_handle_t *h;
310 priv_t *priv;
312 h = tv_new_handle(sizeof(priv_t), &functions);
313 if (!h)
314 return NULL;
316 priv = h->priv;
318 /* set video device name */
319 if (!tv_param->device)
320 priv->video_device = strdup("/dev/video0");
321 else
322 priv->video_device = strdup(tv_param->device);
324 /* set video device name */
325 if (!tv_param->adevice)
326 priv->audio_device = NULL;
327 else {
328 priv->audio_device = strdup(tv_param->adevice);
331 /* allocation failed */
332 if (!priv->video_device) {
333 tv_free_handle(h);
334 return NULL;
337 priv->tv_param=tv_param;
338 return h;
341 /* retrieves info about audio channels from the BTTV */
342 static void init_v4l_audio(priv_t *priv)
344 int i;
345 int reqmode;
347 if (!priv->capability.audios) return;
349 /* audio chanlist */
351 mp_msg(MSGT_TV, MSGL_V, " Audio devices: %d\n", priv->capability.audios);
353 mp_msg(MSGT_TV, MSGL_V, "Video capture card reports the audio setup as follows:\n");
354 for (i = 0; i < priv->capability.audios; i++)
356 if (i >= MAX_AUDIO_CHANNELS)
358 mp_msg(MSGT_TV, MSGL_ERR, "no space for more audio channels (increase in source!) (%d > %d)\n",
359 i, MAX_AUDIO_CHANNELS);
360 i = priv->capability.audios;
361 break;
364 priv->audio[i].audio = i;
365 if (ioctl(priv->video_fd, VIDIOCGAUDIO, &priv->audio[i]) == -1)
367 mp_msg(MSGT_TV, MSGL_ERR, "ioctl get audio failed: %s\n", strerror(errno));
368 break;
371 /* mute all channels */
372 priv->audio[i].flags |= VIDEO_AUDIO_MUTE;
373 reqmode = -1;
374 if (priv->tv_param->amode >= 0) {
375 switch (priv->tv_param->amode) {
376 case 0:
377 reqmode = VIDEO_SOUND_MONO;
378 break;
379 case 1:
380 reqmode = VIDEO_SOUND_STEREO;
381 break;
382 case 2:
383 reqmode = VIDEO_SOUND_LANG1;
384 break;
385 case 3:
386 reqmode = VIDEO_SOUND_LANG2;
387 break;
388 default:
389 mp_msg(MSGT_TV, MSGL_ERR, "Unknown audio mode requested.\n");
390 break;
392 if (reqmode >= 0) priv->audio[i].mode = reqmode;
394 ioctl(priv->video_fd, VIDIOCSAUDIO, &priv->audio[i]);
396 // get the parameters back
397 if (ioctl(priv->video_fd, VIDIOCGAUDIO, &priv->audio[i]) == -1)
399 mp_msg(MSGT_TV, MSGL_ERR, "ioctl get audio failed: %s\n", strerror(errno));
400 break;
403 switch(priv->audio[i].mode)
405 case VIDEO_SOUND_MONO:
406 case VIDEO_SOUND_LANG1:
407 case VIDEO_SOUND_LANG2:
408 priv->audio_channels[i] = 1;
409 break;
410 case VIDEO_SOUND_STEREO:
411 priv->audio_channels[i] = 2;
412 break;
413 default:
414 mp_msg(MSGT_TV, MSGL_ERR, "Card reports an unknown audio mode !\n");
415 mp_msg(MSGT_TV, MSGL_ERR, "Trying two channel audio. Use forcechan to override.\n");
416 priv->audio_channels[i] = 2;
417 break;
420 if (reqmode >= 0 && priv->audio[i].mode != reqmode) {
421 mp_msg(MSGT_TV, MSGL_ERR, "Audio mode setup warning!\n");
422 mp_msg(MSGT_TV, MSGL_ERR, "Requested mode was %s, but v4l still reports %s.\n",
423 audio_mode2name(reqmode), audio_mode2name(priv->audio[i].mode));
424 mp_msg(MSGT_TV, MSGL_ERR, "You may need \"forcechan\" option to force stereo/mono audio recording.\n");
427 /* display stuff */
428 mp_msg(MSGT_TV, MSGL_V, " %d: %s: ", priv->audio[i].audio,
429 priv->audio[i].name);
430 if (priv->audio[i].flags & VIDEO_AUDIO_MUTABLE) {
431 mp_msg(MSGT_TV, MSGL_V, "muted=%s ",
432 (priv->audio[i].flags & VIDEO_AUDIO_MUTE) ? "yes" : "no");
434 mp_msg(MSGT_TV, MSGL_V, "vol=%d bass=%d treble=%d balance=%d mode=%s",
435 priv->audio[i].volume, priv->audio[i].bass, priv->audio[i].treble,
436 priv->audio[i].balance, audio_mode2name(priv->audio[i].mode));
437 mp_msg(MSGT_TV, MSGL_V, " chan=%d\n", priv->audio_channels[i]);
439 if (priv->tv_param->forcechan >= 0)
440 priv->audio_channels[i] = priv->tv_param->forcechan;
442 // we'll call VIDIOCSAUDIO again when starting capture
443 // let's set audio mode to requested mode again for the case
444 // when VIDIOCGAUDIO just cannot report the mode correctly
445 if (reqmode >= 0) priv->audio[i].mode = reqmode;
449 #if !defined(__LINUX_VIDEODEV2_H) && !defined(VIDIOC_QUERYCAP)
450 struct v4l2_capability
452 __u8 driver[16]; /* i.e. "bttv" */
453 __u8 card[32]; /* i.e. "Hauppauge WinTV" */
454 __u8 bus_info[32]; /* "PCI:" + pci_dev->slot_name */
455 __u32 version; /* should use KERNEL_VERSION() */
456 __u32 capabilities; /* Device capabilities */
457 __u32 reserved[4];
460 #define VIDIOC_QUERYCAP _IOR ('V', 0, struct v4l2_capability)
461 #endif
463 static int init(priv_t *priv)
465 int i;
467 if (priv->tv_param->immediate == 1)
468 priv->tv_param->noaudio = 1;
470 priv->video_ringbuffer = NULL;
471 priv->video_timebuffer = NULL;
472 priv->video_avg_buffer = NULL;
473 priv->audio_ringbuffer = NULL;
474 priv->audio_skew_buffer = NULL;
476 priv->video_fd = open(priv->video_device, O_RDWR);
477 mp_msg(MSGT_TV, MSGL_DBG2, "Video fd: %d, %p\n", priv->video_fd,
478 priv->video_device);
479 if (priv->video_fd == -1)
481 mp_msg(MSGT_TV, MSGL_ERR, "unable to open '%s': %s\n",
482 priv->video_device, strerror(errno));
483 goto err;
486 /* check for v4l2 */
487 if (ioctl(priv->video_fd, VIDIOC_QUERYCAP, &priv->capability) == 0) {
488 mp_msg(MSGT_TV, MSGL_ERR, "=================================================================\n");
489 mp_msg(MSGT_TV, MSGL_ERR, " WARNING: YOU ARE USING V4L DEMUXER WITH V4L2 DRIVERS!!!\n");
490 mp_msg(MSGT_TV, MSGL_ERR, " As the V4L1 compatibility layer is broken, this may not work.\n");
491 mp_msg(MSGT_TV, MSGL_ERR, " If you encounter any problems, use driver=v4l2 instead.\n");
492 mp_msg(MSGT_TV, MSGL_ERR, " Bugreports on driver=v4l with v4l2 drivers will be ignored.\n");
493 mp_msg(MSGT_TV, MSGL_ERR, "=================================================================\n");
496 /* get capabilities (priv->capability is needed!) */
497 if (ioctl(priv->video_fd, VIDIOCGCAP, &priv->capability) == -1)
499 mp_msg(MSGT_TV, MSGL_ERR, "ioctl get capabilities failed: %s\n", strerror(errno));
500 goto err;
503 fcntl(priv->video_fd, F_SETFD, FD_CLOEXEC);
505 mp_msg(MSGT_TV, MSGL_INFO, "Selected device: %s\n", priv->capability.name);
506 mp_msg(MSGT_TV, MSGL_INFO, " Capabilities: ");
507 for (i = 0; device_cap2name[i] != NULL; i++)
508 if (priv->capability.type & (1 << i))
509 mp_msg(MSGT_TV, MSGL_INFO, "%s ", device_cap2name[i]);
510 mp_msg(MSGT_TV, MSGL_INFO, "\n");
511 mp_msg(MSGT_TV, MSGL_INFO, " Device type: %d\n", priv->capability.type);
512 mp_msg(MSGT_TV, MSGL_INFO, " Supported sizes: %dx%d => %dx%d\n",
513 priv->capability.minwidth, priv->capability.minheight,
514 priv->capability.maxwidth, priv->capability.maxheight);
515 priv->width = priv->capability.minwidth;
516 priv->height = priv->capability.minheight;
518 /* somewhere here could disable priv->tv_param->mjpeg, if it is not a capability */
520 /* initialize if necessary */
521 if ( priv->tv_param->mjpeg )
523 struct mjpeg_params bparm;
524 struct mjpeg_requestbuffers breq; /* buffer requests */
526 if (ioctl(priv->video_fd, MJPIOC_G_PARAMS, &bparm) < 0)
528 mp_msg(MSGT_TV, MSGL_ERR,
529 " MJP: Error getting video parameters: %s\n", strerror(errno));
530 goto err;
533 mp_msg(MSGT_TV, MSGL_INFO,
534 " MJP: previous params: x: %d, y: %d, w: %d, h: %d, decim: %d, fields: %d,\n",
535 bparm.img_x, bparm.img_y, bparm.img_width, bparm.img_height,
536 bparm.decimation, bparm.field_per_buff);
538 mp_msg(MSGT_TV, MSGL_INFO,
539 " MJP: HorDcm: %d, VerDcm: %d, TmpDcm: %d\n",
540 bparm.HorDcm, bparm.VerDcm, bparm.TmpDcm);
542 bparm.input = priv->tv_param->input; /* tv */
543 if (!strcasecmp(priv->tv_param->norm, "pal"))
544 bparm.norm = 0; /* PAL */
545 else if (!strcasecmp(priv->tv_param->norm, "ntsc"))
546 bparm.norm = 1; /* NTSC */
547 else if (!strcasecmp(priv->tv_param->norm, "secam"))
548 bparm.norm = 2; /* SECAM */
549 bparm.quality = priv->tv_param->quality;
550 bparm.decimation = priv->tv_param->decimation;
552 mp_msg(MSGT_TV, MSGL_INFO, " MJP: setting params to decimation: %d, quality: %d\n",
553 bparm.decimation, bparm.quality);
555 if (ioctl(priv->video_fd, MJPIOC_S_PARAMS, &bparm) < 0)
557 mp_msg(MSGT_TV, MSGL_ERR,
558 " MJP: Error setting video parameters: %s\n", strerror(errno));
559 goto err;
562 if (ioctl(priv->video_fd, MJPIOC_G_PARAMS, &bparm) < 0)
564 mp_msg(MSGT_TV, MSGL_ERR,
565 " MJP: Error getting video parameters: %s\n", strerror(errno));
566 goto err;
569 mp_msg(MSGT_TV, MSGL_INFO,
570 " MJP: current params: x: %d, y: %d, w: %d, h: %d, decim: %d, fields: %d,\n",
571 bparm.img_x, bparm.img_y, bparm.img_width, bparm.img_height,
572 bparm.decimation, bparm.field_per_buff);
574 mp_msg(MSGT_TV, MSGL_INFO,
575 " MJP: HorDcm: %d, VerDcm: %d, TmpDcm: %d\n",
576 bparm.HorDcm, bparm.VerDcm, bparm.TmpDcm);
579 breq.count = 64;
580 priv -> nbuf = breq.count;
581 priv->mbuf.frames = priv -> nbuf;
582 priv->mjpeg_bufsize = 256*1024;
583 if (priv->tv_param->buffer_size >= 0)
584 priv->mjpeg_bufsize = priv->tv_param->buffer_size*1024;
585 breq.size = priv -> mjpeg_bufsize;
586 if (ioctl(priv->video_fd, MJPIOC_REQBUFS,&(breq)) < 0)
588 mp_msg (MSGT_TV, MSGL_ERR,
589 " MJP: Error requesting video buffers: %s\n", strerror(errno));
590 goto err;
592 mp_msg(MSGT_TV, MSGL_INFO,
593 " MJP: Got %ld buffers of size %ld KB\n",
594 breq.count, breq.size/1024);
596 priv -> mmap = mmap(0, breq.count * breq.size,
597 PROT_READ|PROT_WRITE, MAP_SHARED, priv->video_fd, 0);
598 if (priv -> mmap == MAP_FAILED)
600 mp_msg(MSGT_TV, MSGL_INFO,
601 " MJP: Error mapping video buffers: %s\n", strerror(errno));
602 goto err;
606 mp_msg(MSGT_TV, MSGL_INFO, " Inputs: %d\n", priv->capability.channels);
607 priv->channels = calloc(priv->capability.channels, sizeof(struct video_channel));
608 if (!priv->channels)
609 goto malloc_failed;
610 memset(priv->channels, 0, sizeof(struct video_channel)*priv->capability.channels);
611 for (i = 0; i < priv->capability.channels; i++)
613 priv->channels[i].channel = i;
614 if (ioctl(priv->video_fd, VIDIOCGCHAN, &priv->channels[i]) == -1)
616 mp_msg(MSGT_TV, MSGL_ERR, "ioctl get channel failed: %s\n", strerror(errno));
617 break;
619 mp_msg(MSGT_TV, MSGL_INFO, " %d: %s: %s%s%s%s (tuner:%d, norm:%s)\n", i,
620 priv->channels[i].name,
621 (priv->channels[i].flags & VIDEO_VC_TUNER) ? "tuner " : "",
622 (priv->channels[i].flags & VIDEO_VC_AUDIO) ? "audio " : "",
623 (priv->channels[i].flags & VIDEO_TYPE_TV) ? "tv " : "",
624 (priv->channels[i].flags & VIDEO_TYPE_CAMERA) ? "camera " : "",
625 priv->channels[i].tuners,
626 norm2name(priv->channels[i].norm));
628 priv->act_channel = 0;
630 if (!(priv->capability.type & VID_TYPE_CAPTURE))
632 mp_msg(MSGT_TV, MSGL_ERR, "Only grabbing supported (for overlay use another program)\n");
633 goto err;
637 /* init v4l audio even when we don't capture */
638 init_v4l_audio(priv);
640 if (!priv->capability.audios && !priv->tv_param->force_audio) priv->tv_param->noaudio = 1;
642 /* audio init */
643 if (!priv->tv_param->noaudio) {
645 #ifdef CONFIG_ALSA
646 if (priv->tv_param->alsa)
647 audio_in_init(&priv->audio_in, AUDIO_IN_ALSA);
648 else
649 audio_in_init(&priv->audio_in, AUDIO_IN_OSS);
650 #else
651 audio_in_init(&priv->audio_in, AUDIO_IN_OSS);
652 #endif
654 if (priv->audio_device) {
655 audio_in_set_device(&priv->audio_in, priv->audio_device);
658 if (priv->tv_param->audio_id < priv->capability.audios)
659 priv->audio_id = priv->tv_param->audio_id;
660 else
661 priv->audio_id = 0;
662 audio_in_set_samplerate(&priv->audio_in, 44100);
663 if (priv->capability.audios) {
664 audio_in_set_channels(&priv->audio_in, priv->audio_channels[priv->audio_id]);
665 } else {
666 if (priv->tv_param->forcechan >= 0) {
667 audio_in_set_channels(&priv->audio_in, priv->tv_param->forcechan);
668 } else {
669 audio_in_set_channels(&priv->audio_in, 2);
672 if (audio_in_setup(&priv->audio_in) < 0) return 0;
673 setup_audio_buffer_sizes(priv);
676 return 1;
678 malloc_failed:
679 free(priv->channels);
680 free(priv->buf);
681 err:
682 if (priv->video_fd != -1)
683 close(priv->video_fd);
684 return 0;
687 static int uninit(priv_t *priv)
689 unsigned long num;
691 priv->vbi_shutdown=1;
692 if(priv->vbi_grabber_thread)
693 pthread_join(priv->vbi_grabber_thread, NULL);
695 teletext_control(priv->priv_vbi,TV_VBI_CONTROL_STOP,(void*)1);
696 priv->priv_vbi=NULL;
698 if(priv->vbi_fd){
699 close(priv->vbi_fd);
700 priv->vbi_fd=0;
703 free(priv->vbi_dev);
704 priv->vbi_dev = NULL;
706 priv->shutdown = 1;
708 mp_msg(MSGT_TV, MSGL_V, "Waiting for threads to finish... ");
709 if (!priv->tv_param->noaudio) {
710 pthread_join(priv->audio_grabber_thread, NULL);
711 pthread_mutex_destroy(&priv->audio_starter);
712 pthread_mutex_destroy(&priv->skew_mutex);
714 pthread_mutex_destroy(&priv->video_buffer_mutex);
715 if(priv->video_grabber_thread)
716 pthread_join(priv->video_grabber_thread, NULL);
718 mp_msg(MSGT_TV, MSGL_V, "done\n");
720 if (priv->capability.audios) {
721 priv->audio[priv->audio_id].flags |= VIDEO_AUDIO_MUTE;
722 ioctl(priv->video_fd, VIDIOCSAUDIO, &priv->audio[priv->audio_id]);
725 if ( priv->tv_param->mjpeg )
727 num = -1;
728 if (ioctl(priv->video_fd, MJPIOC_QBUF_CAPT, &num) < 0)
729 mp_msg(MSGT_TV, MSGL_ERR, "\n MJP: ioctl MJPIOC_QBUF_CAPT failed: %s\n", strerror(errno));
731 else
733 // We need to munmap as close don't close mem mappings
734 if(munmap(priv->mmap,priv->mbuf.size))
735 mp_msg(MSGT_TV, MSGL_ERR, "Munmap failed: %s\n",strerror(errno));
738 if(close(priv->video_fd))
739 mp_msg(MSGT_TV, MSGL_ERR, "Close tv failed: %s\n",strerror(errno));
741 audio_in_uninit(&priv->audio_in);
743 if (priv->video_ringbuffer) {
744 int i;
745 for (i = 0; i < priv->video_buffer_size_current; i++) {
746 free(priv->video_ringbuffer[i]);
748 free(priv->video_ringbuffer);
751 free(priv->video_timebuffer);
752 free(priv->video_avg_buffer);
753 if (!priv->tv_param->noaudio) {
754 free(priv->audio_ringbuffer);
755 free(priv->audio_skew_buffer);
758 return 1;
761 static int get_capture_buffer_size(priv_t *priv)
763 uint64_t bufsize;
764 int cnt;
766 if (priv->tv_param->buffer_size >= 0) {
767 bufsize = priv->tv_param->buffer_size*1024*1024;
768 } else {
769 #ifdef HAVE_SYS_SYSINFO_H
770 struct sysinfo si;
772 sysinfo(&si);
773 bufsize = (si.freeram/2)*si.mem_unit;
774 if (bufsize < 16*1024*1024)
775 #endif
776 bufsize = 16*1024*1024;
779 cnt = bufsize/(priv->height*priv->bytesperline);
780 if (cnt < 2) cnt = 2;
782 return cnt;
785 static int vbi_init(priv_t* priv,char* device)
787 int vbi_fd=0;
788 struct video_capability cap;
790 if(!device)
791 return TVI_CONTROL_FALSE;
793 priv->vbi_dev=strdup(device);
795 vbi_fd=open(priv->vbi_dev,O_RDWR);
796 if(vbi_fd<0){
797 mp_msg(MSGT_TV,MSGL_ERR,"vbi: could not open device %s\n",priv->vbi_dev);
798 return TVI_CONTROL_FALSE;
801 if(ioctl(vbi_fd,VIDIOCGCAP,&cap)<0){
802 mp_msg(MSGT_TV,MSGL_ERR,"vbi: Query capabilities failed for %s\n",priv->vbi_dev);
803 close(vbi_fd);
804 return TVI_CONTROL_FALSE;
806 if(!cap.type & VID_TYPE_CAPTURE){
807 mp_msg(MSGT_TV,MSGL_ERR,"vbi: %s is not capture device\n",priv->vbi_dev);
808 close(vbi_fd);
809 return TVI_CONTROL_FALSE;
812 priv->vbi_fd=vbi_fd;
813 mp_msg(MSGT_TV,MSGL_DBG3,"vbi: init ok\n");
814 return TVI_CONTROL_TRUE;
817 static int vbi_get_props(priv_t* priv,tt_stream_props* ptsp)
819 struct vbi_format fmt;
820 int res;
821 if(!priv || !ptsp)
822 return TVI_CONTROL_FALSE;
824 memset(&fmt,0,sizeof(struct vbi_format));
825 if((res=ioctl(priv->vbi_fd,VIDIOCGVBIFMT,&fmt))<0){
826 mp_msg(MSGT_TV,MSGL_ERR,"vbi_get_props: Query format failed: %x\n",res);
827 return TVI_CONTROL_FALSE;
830 ptsp->interlaced=(fmt.flags& VBI_INTERLACED?1:0);
831 if(fmt.start[1]>0 && fmt.count[1]){
832 if(fmt.start[1]>=286)
833 //625
834 ptsp->offset=10.2e-6*fmt.sampling_rate;
835 else
836 //525
837 ptsp->offset=9.2e-6*fmt.sampling_rate;
838 }else
839 ptsp->offset=9.7e-6*fmt.sampling_rate;
841 ptsp->sampling_rate=fmt.sampling_rate;
842 ptsp->samples_per_line=fmt.samples_per_line,
844 ptsp->count[0]=fmt.count[0];
845 ptsp->count[1]=fmt.count[1];
846 ptsp->bufsize = ptsp->samples_per_line * (ptsp->count[0] + ptsp->count[1]);
848 mp_msg(MSGT_TV,MSGL_V,"vbi_get_props: sampling_rate=%d,offset:%d,samples_per_line: %d\n interlaced:%s, count=[%d,%d]\n",
849 ptsp->sampling_rate,
850 ptsp->offset,
851 ptsp->samples_per_line,
852 ptsp->interlaced?"Yes":"No",
853 ptsp->count[0],
854 ptsp->count[1]);
856 return TVI_CONTROL_TRUE;
859 static void *vbi_grabber(void *data)
861 priv_t *priv = (priv_t *) data;
862 int bytes,seq,prev_seq;
863 unsigned char* buf;
864 tt_stream_props tsp;
866 if(!priv->priv_vbi){
867 mp_msg(MSGT_TV,MSGL_WARN,"vbi: vbi not initialized. stopping thread.\n");
868 return NULL;
871 if(vbi_get_props(priv,&tsp)!=TVI_CONTROL_TRUE)
872 return NULL;
874 buf=malloc(tsp.bufsize);
875 seq=0;
876 prev_seq=0;
877 mp_msg(MSGT_TV,MSGL_V,"vbi: vbi capture thread started.\n");
879 while (!priv->vbi_shutdown){
880 bytes=read(priv->vbi_fd,buf,tsp.bufsize);
881 if(bytes<0 && errno==EINTR)
882 continue;
883 if (bytes!=tsp.bufsize){
884 mp_msg(MSGT_TV,MSGL_WARN,"vbi: expecting bytes: %d, got: %d",tsp.bufsize,bytes);
885 break;
887 seq=*(int*)(buf+bytes-4);
888 if(seq<=1) continue;
889 if (prev_seq && seq!=prev_seq+1){
890 prev_seq=0;
891 seq=0;
893 prev_seq=seq;
894 teletext_control(priv->priv_vbi,TV_VBI_CONTROL_DECODE_PAGE,&buf);
895 mp_msg(MSGT_TV,MSGL_DBG3,"grabber: seq:%d\n",seq);
897 free(buf);
898 return NULL;
901 static int start(priv_t *priv)
903 int i;
904 int bytes_per_sample;
905 struct video_window win;
907 if (ioctl(priv->video_fd, VIDIOCGPICT, &priv->picture) == -1)
909 mp_msg(MSGT_TV, MSGL_ERR, "ioctl get picture failed: %s\n", strerror(errno));
910 return 0;
913 priv->picture.palette = format2palette(priv->format);
914 priv->picture.depth = palette2depth(priv->picture.palette);
916 if (priv->format != IMGFMT_BGR15) {
917 priv->bytesperline = priv->width * priv->picture.depth / 8;
918 } else {
919 priv->bytesperline = priv->width * 2;
922 mp_msg(MSGT_TV, MSGL_V, "Picture values:\n");
923 mp_msg(MSGT_TV, MSGL_V, " Depth: %d, Palette: %s (Format: %s)\n", priv->picture.depth,
924 PALETTE(priv->picture.palette), vo_format_name(priv->format));
925 mp_msg(MSGT_TV, MSGL_V, " Brightness: %d, Hue: %d, Colour: %d, Contrast: %d\n",
926 priv->picture.brightness, priv->picture.hue,
927 priv->picture.colour, priv->picture.contrast);
929 if (ioctl(priv->video_fd, VIDIOCSPICT, &priv->picture) == -1)
931 mp_msg(MSGT_TV, MSGL_ERR, "ioctl set picture failed: %s\n", strerror(errno));
932 mp_msg(MSGT_TV, MSGL_ERR, "The 'outfmt' of '%s' is likely not supported by your card\n",
933 vo_format_name(priv->format));
934 return 0;
937 /* Set capture size */
938 win.x = 0;
939 win.y = 0;
940 win.width = priv->width;
941 win.height = priv->height;
942 win.chromakey = -1;
943 win.flags = 0;
944 win.clipcount = 0;
945 if (ioctl(priv->video_fd, VIDIOCSWIN, &win) == -1)
946 mp_msg(MSGT_TV, MSGL_ERR, "ioctl set window failed: %s\n", strerror(errno));
948 if ( !priv->tv_param->mjpeg )
950 /* map grab buffer */
951 if (ioctl(priv->video_fd, VIDIOCGMBUF, &priv->mbuf) == -1)
953 mp_msg(MSGT_TV, MSGL_ERR, "ioctl get mbuf failed: %s\n", strerror(errno));
954 return 0;
957 mp_msg(MSGT_TV, MSGL_V, "mbuf: size=%d, frames=%d\n",
958 priv->mbuf.size, priv->mbuf.frames);
959 priv->mmap = mmap(0, priv->mbuf.size, PROT_READ|PROT_WRITE,
960 MAP_SHARED, priv->video_fd, 0);
961 if (priv->mmap == (unsigned char *)-1)
963 mp_msg(MSGT_TV, MSGL_ERR, "Unable to map memory for buffers: %s\n", strerror(errno));
964 return 0;
966 mp_msg(MSGT_TV, MSGL_DBG2, "our buffer: %p\n", priv->mmap);
968 /* num of buffers */
969 priv->nbuf = priv->mbuf.frames;
971 /* video buffers */
972 priv->buf = calloc(priv->nbuf, sizeof(struct video_mmap));
973 if (!priv->buf)
974 return 0;
975 memset(priv->buf, 0, priv->nbuf * sizeof(struct video_mmap));
978 if ( !priv->tv_param->mjpeg )
980 priv->nbuf = priv->mbuf.frames;
981 for (i=0; i < priv->nbuf; i++)
983 priv->buf[i].format = priv->picture.palette;
984 priv->buf[i].frame = i;
985 priv->buf[i].width = priv->width;
986 priv->buf[i].height = priv->height;
987 mp_msg(MSGT_TV, MSGL_DBG2, "buffer: %d => %p\n", i, &priv->buf[i]);
991 #if 0
993 struct video_play_mode pmode;
995 pmode.mode = VID_PLAY_NORMAL;
996 pmode.p1 = 1;
997 pmode.p2 = 0;
998 if (ioctl(priv->video_fd, VIDIOCSPLAYMODE, &pmode) == -1)
1000 mp_msg(MSGT_TV, MSGL_ERR, "ioctl set play mode failed: %s\n", strerror(errno));
1001 // return 0;
1004 #endif
1006 #if 0
1007 // initialize video capture
1008 if (ioctl(priv->video_fd, VIDIOCCAPTURE, &one) == -1)
1010 mp_msg(MSGT_TV, MSGL_ERR, "FATAL: ioctl ccapture failed: %s\n", strerror(errno));
1011 return 0;
1013 #endif
1015 /* setup audio parameters */
1016 if (!priv->tv_param->noaudio) {
1017 setup_audio_buffer_sizes(priv);
1018 bytes_per_sample = priv->audio_in.bytes_per_sample;
1019 priv->audio_skew_buffer = calloc(priv->aud_skew_cnt, sizeof(long long));
1020 if (!priv->audio_skew_buffer) {
1021 mp_msg(MSGT_TV, MSGL_ERR, "cannot allocate skew buffer: %s\n", strerror(errno));
1022 return 0;
1025 priv->audio_ringbuffer = calloc(priv->audio_in.blocksize, priv->audio_buffer_size);
1026 if (!priv->audio_ringbuffer) {
1027 mp_msg(MSGT_TV, MSGL_ERR, "cannot allocate audio buffer: %s\n", strerror(errno));
1028 return 0;
1031 priv->audio_secs_per_block = (double)priv->audio_in.blocksize/(priv->audio_in.samplerate
1032 *priv->audio_in.channels
1033 *bytes_per_sample);
1034 priv->audio_head = 0;
1035 priv->audio_tail = 0;
1036 priv->audio_cnt = 0;
1037 priv->audio_drop = 0;
1038 priv->audio_skew = 0;
1039 priv->audio_skew_total = 0;
1040 priv->audio_recv_blocks_total = 0;
1041 priv->audio_sent_blocks_total = 0;
1044 /* setup video parameters */
1045 if (priv->immediate_mode) {
1046 priv->video_buffer_size_max = VID_BUF_SIZE_IMMEDIATE;
1047 } else {
1048 priv->video_buffer_size_max = get_capture_buffer_size(priv);
1050 priv->video_buffer_size_current = 0;
1052 if (!priv->tv_param->noaudio) {
1053 if (priv->video_buffer_size_max < 3.0*priv->fps*priv->audio_secs_per_block) {
1054 mp_msg(MSGT_TV, MSGL_ERR, "Video buffer shorter than 3 times audio frame duration.\n"
1055 "You will probably experience heavy framedrops.\n");
1059 mp_msg(MSGT_TV, MSGL_V, "Using a ring buffer for maximum %d frames, %d MB total size.\n",
1060 priv->video_buffer_size_max,
1061 priv->video_buffer_size_max*priv->height*priv->bytesperline/(1024*1024));
1063 priv->video_ringbuffer = calloc(priv->video_buffer_size_max, sizeof(unsigned char*));
1064 if (!priv->video_ringbuffer) {
1065 mp_msg(MSGT_TV, MSGL_ERR, "cannot allocate video buffer: %s\n", strerror(errno));
1066 return 0;
1068 for (i = 0; i < priv->video_buffer_size_max; i++)
1069 priv->video_ringbuffer[i] = NULL;
1071 priv->video_timebuffer = calloc(priv->video_buffer_size_max, sizeof(long long));
1072 if (!priv->video_timebuffer) {
1073 mp_msg(MSGT_TV, MSGL_ERR, "cannot allocate time buffer: %s\n", strerror(errno));
1074 return 0;
1076 priv->video_avg_buffer = malloc(sizeof(long long) * VIDEO_AVG_BUFFER_SIZE);
1077 if (!priv->video_avg_buffer) {
1078 mp_msg(MSGT_TV, MSGL_ERR, "cannot allocate period buffer: %s\n", strerror(errno));
1079 return 0;
1081 priv->video_interval_sum = (1e6/priv->fps)*VIDEO_AVG_BUFFER_SIZE;
1082 for (i = 0; i < VIDEO_AVG_BUFFER_SIZE; i++) {
1083 priv->video_avg_buffer[i] = 1e6/priv->fps;
1086 priv->video_avg_ptr = 0;
1088 priv->video_head = 0;
1089 priv->video_tail = 0;
1090 priv->video_cnt = 0;
1091 priv->first = 1;
1093 if (priv->capability.audios) {
1094 /* enable audio */
1095 if (priv->tv_param->volume >= 0)
1096 priv->audio[priv->audio_id].volume = priv->tv_param->volume;
1097 if (priv->tv_param->bass >= 0)
1098 priv->audio[priv->audio_id].bass = priv->tv_param->bass;
1099 if (priv->tv_param->treble >= 0)
1100 priv->audio[priv->audio_id].treble = priv->tv_param->treble;
1101 if (priv->tv_param->balance >= 0)
1102 priv->audio[priv->audio_id].balance = priv->tv_param->balance;
1103 priv->audio[priv->audio_id].flags &= ~VIDEO_AUDIO_MUTE;
1104 mp_msg(MSGT_TV, MSGL_V, "Enabling tv audio. Requested setup is:\n");
1105 mp_msg(MSGT_TV, MSGL_V, "id=%d vol=%d bass=%d treble=%d balance=%d mode=%s",
1106 priv->audio_id,
1107 priv->audio[priv->audio_id].volume, priv->audio[priv->audio_id].bass, priv->audio[priv->audio_id].treble,
1108 priv->audio[priv->audio_id].balance, audio_mode2name(priv->audio[priv->audio_id].mode));
1109 mp_msg(MSGT_TV, MSGL_V, " chan=%d\n", priv->audio_channels[priv->audio_id]);
1110 ioctl(priv->video_fd, VIDIOCSAUDIO, &priv->audio[priv->audio_id]);
1113 /* start vbi thread */
1114 if(priv->priv_vbi){
1115 priv->vbi_shutdown = 0;
1116 pthread_create(&priv->vbi_grabber_thread, NULL, vbi_grabber, priv);
1119 /* launch capture threads */
1120 priv->shutdown = 0;
1121 if (!priv->tv_param->noaudio) {
1122 pthread_mutex_init(&priv->audio_starter, NULL);
1123 pthread_mutex_init(&priv->skew_mutex, NULL);
1124 pthread_mutex_lock(&priv->audio_starter);
1125 pthread_create(&priv->audio_grabber_thread, NULL, audio_grabber, priv);
1127 pthread_mutex_init(&priv->video_buffer_mutex, NULL);
1128 /* we'll launch the video capture later, when a first request for a frame arrives */
1130 return 1;
1134 static int control(priv_t *priv, int cmd, void *arg)
1136 mp_msg(MSGT_TV, MSGL_DBG2, "\ndebug: control(priv=%p, cmd=%d, arg=%p)\n",
1137 priv, cmd, arg);
1138 switch(cmd)
1140 /* ========== GENERIC controls =========== */
1141 case TVI_CONTROL_IS_VIDEO:
1143 if (priv->capability.type & VID_TYPE_CAPTURE)
1144 return TVI_CONTROL_TRUE;
1145 return TVI_CONTROL_FALSE;
1147 case TVI_CONTROL_IS_AUDIO:
1148 if (priv->tv_param->force_audio) return TVI_CONTROL_TRUE;
1149 if (priv->channels[priv->act_channel].flags & VIDEO_VC_AUDIO)
1151 return TVI_CONTROL_TRUE;
1153 return TVI_CONTROL_FALSE;
1154 case TVI_CONTROL_IS_TUNER:
1156 // if (priv->capability.type & VID_TYPE_TUNER)
1157 if (priv->channels[priv->act_channel].flags & VIDEO_VC_TUNER)
1158 return TVI_CONTROL_TRUE;
1159 return TVI_CONTROL_FALSE;
1162 /* ========== VIDEO controls =========== */
1163 case TVI_CONTROL_VID_GET_FORMAT:
1165 int output_fmt = -1;
1167 output_fmt = priv->format;
1168 if ( priv->tv_param->mjpeg )
1170 mp_msg(MSGT_TV, MSGL_INFO, " MJP: setting sh_video->format to mjpg\n");
1171 output_fmt = 0x47504a4d;
1172 output_fmt = 0x67706a6d;
1173 *(int *)arg = output_fmt;
1174 mp_msg(MSGT_TV, MSGL_V, "Output format: %s\n", "mjpg");
1176 else
1178 *(int *)arg = output_fmt;
1179 mp_msg(MSGT_TV, MSGL_V, "Output format: %s\n", vo_format_name(output_fmt));
1181 return TVI_CONTROL_TRUE;
1183 case TVI_CONTROL_VID_SET_FORMAT:
1184 priv->format = *(int *)arg;
1185 // !HACK! v4l uses BGR format instead of RGB
1186 // and we have to correct this. Fortunately,
1187 // tv.c reads later the format back so we
1188 // can persuade it to use what we want.
1189 if (IMGFMT_IS_RGB(priv->format)) {
1190 priv->format &= ~IMGFMT_RGB_MASK;
1191 priv->format |= IMGFMT_BGR;
1193 return TVI_CONTROL_TRUE;
1194 case TVI_CONTROL_VID_GET_PLANES:
1195 *(int *)arg = 1; /* FIXME, also not needed at this time */
1196 return TVI_CONTROL_TRUE;
1197 case TVI_CONTROL_VID_GET_BITS:
1198 *(int *)arg = palette2depth(format2palette(priv->format));
1199 return TVI_CONTROL_TRUE;
1200 case TVI_CONTROL_VID_GET_WIDTH:
1201 *(int *)arg = priv->width;
1202 return TVI_CONTROL_TRUE;
1203 case TVI_CONTROL_VID_CHK_WIDTH:
1205 int req_width = *(int *)arg;
1207 mp_msg(MSGT_TV, MSGL_V, "Requested width: %d\n", req_width);
1208 if ((req_width >= priv->capability.minwidth) &&
1209 (req_width <= priv->capability.maxwidth))
1210 return TVI_CONTROL_TRUE;
1211 return TVI_CONTROL_FALSE;
1213 case TVI_CONTROL_VID_SET_WIDTH:
1214 priv->width = *(int *)arg;
1215 return TVI_CONTROL_TRUE;
1216 case TVI_CONTROL_VID_GET_HEIGHT:
1217 *(int *)arg = priv->height;
1218 return TVI_CONTROL_TRUE;
1219 case TVI_CONTROL_VID_CHK_HEIGHT:
1221 int req_height = *(int *)arg;
1223 mp_msg(MSGT_TV, MSGL_V, "Requested height: %d\n", req_height);
1224 if ((req_height >= priv->capability.minheight) &&
1225 (req_height <= priv->capability.maxheight))
1226 return TVI_CONTROL_TRUE;
1227 return TVI_CONTROL_FALSE;
1229 case TVI_CONTROL_VID_SET_HEIGHT:
1230 priv->height = *(int *)arg;
1231 return TVI_CONTROL_TRUE;
1232 case TVI_CONTROL_VID_GET_PICTURE:
1233 if (ioctl(priv->video_fd, VIDIOCGPICT, &priv->picture) == -1)
1235 mp_msg(MSGT_TV, MSGL_ERR, "ioctl get picture failed: %s\n", strerror(errno));
1236 return TVI_CONTROL_FALSE;
1238 return TVI_CONTROL_TRUE;
1239 case TVI_CONTROL_VID_SET_PICTURE:
1240 if (ioctl(priv->video_fd, VIDIOCSPICT, &priv->picture) == -1)
1242 mp_msg(MSGT_TV, MSGL_ERR, "ioctl set picture failed: %s\n", strerror(errno));
1243 return TVI_CONTROL_FALSE;
1245 return TVI_CONTROL_TRUE;
1246 case TVI_CONTROL_VID_SET_BRIGHTNESS:
1247 priv->picture.brightness = (327*(*(int *)arg+100)) + 68;
1248 return control(priv, TVI_CONTROL_VID_SET_PICTURE, 0);
1249 case TVI_CONTROL_VID_SET_HUE:
1250 priv->picture.hue = (327*(*(int *)arg+100)) + 68;
1251 return control(priv, TVI_CONTROL_VID_SET_PICTURE, 0);
1252 case TVI_CONTROL_VID_SET_SATURATION:
1253 priv->picture.colour = (327*(*(int *)arg+100)) + 68;
1254 return control(priv, TVI_CONTROL_VID_SET_PICTURE, 0);
1255 case TVI_CONTROL_VID_SET_CONTRAST:
1256 priv->picture.contrast = (327*(*(int *)arg+100)) + 68;
1257 return control(priv, TVI_CONTROL_VID_SET_PICTURE, 0);
1258 case TVI_CONTROL_VID_GET_BRIGHTNESS:
1259 if(!control(priv, TVI_CONTROL_VID_GET_PICTURE, 0)) return 0;
1260 *(int*)arg = ((int)priv->picture.brightness-68)/327-100;
1261 return 1;
1262 case TVI_CONTROL_VID_GET_HUE:
1263 if(!control(priv, TVI_CONTROL_VID_GET_PICTURE, 0)) return 0;
1264 *(int*)arg = ((int)priv->picture.hue-68)/327-100;
1265 return 1;
1266 case TVI_CONTROL_VID_GET_SATURATION:
1267 if(!control(priv, TVI_CONTROL_VID_GET_PICTURE, 0)) return 0;
1268 *(int*)arg = ((int)priv->picture.colour-68)/327-100;
1269 return 1;
1270 case TVI_CONTROL_VID_GET_CONTRAST:
1271 if(!control(priv, TVI_CONTROL_VID_GET_PICTURE, 0)) return 0;
1272 *(int*)arg = ((int)priv->picture.contrast-68)/327-100;
1273 return 1;
1274 case TVI_CONTROL_VID_GET_FPS:
1275 *(float *)arg=priv->fps;
1276 return TVI_CONTROL_TRUE;
1278 /* ========== TUNER controls =========== */
1279 case TVI_CONTROL_TUN_GET_FREQ:
1281 unsigned long freq;
1283 if (ioctl(priv->video_fd, VIDIOCGFREQ, &freq) == -1)
1285 mp_msg(MSGT_TV, MSGL_ERR, "ioctl get freq failed: %s\n", strerror(errno));
1286 return TVI_CONTROL_FALSE;
1289 /* tuner uses khz not mhz ! */
1290 // if (priv->tuner.flags & VIDEO_TUNER_LOW)
1291 // freq /= 1000;
1292 *(unsigned long *)arg = freq;
1293 return TVI_CONTROL_TRUE;
1295 case TVI_CONTROL_TUN_SET_FREQ:
1297 /* argument is in MHz ! */
1298 unsigned long freq = *(unsigned long *)arg;
1300 if (priv->capability.audios) {
1301 priv->audio[priv->audio_id].flags |= VIDEO_AUDIO_MUTE;
1302 ioctl(priv->video_fd, VIDIOCSAUDIO, &priv->audio[priv->audio_id]);
1305 mp_msg(MSGT_TV, MSGL_V, "requested frequency: %.3f\n", (float)freq/16);
1307 /* tuner uses khz not mhz ! */
1308 // if (priv->tuner.flags & VIDEO_TUNER_LOW)
1309 // freq *= 1000;
1310 // mp_msg(MSGT_TV, MSGL_V, " requesting from driver: freq=%.3f\n", (float)freq/16);
1311 if (ioctl(priv->video_fd, VIDIOCSFREQ, &freq) == -1)
1313 mp_msg(MSGT_TV, MSGL_ERR, "ioctl set freq failed: %s\n", strerror(errno));
1314 return TVI_CONTROL_FALSE;
1316 usleep(100000); // wait to suppress noise during switching
1318 if (priv->capability.audios) {
1319 priv->audio[priv->audio_id].flags &= ~VIDEO_AUDIO_MUTE;
1320 ioctl(priv->video_fd, VIDIOCSAUDIO, &priv->audio[priv->audio_id]);
1323 return TVI_CONTROL_TRUE;
1325 case TVI_CONTROL_TUN_GET_TUNER:
1327 if (ioctl(priv->video_fd, VIDIOCGTUNER, &priv->tuner) == -1)
1329 mp_msg(MSGT_TV, MSGL_ERR, "ioctl get tuner failed: %s\n", strerror(errno));
1330 return TVI_CONTROL_FALSE;
1333 mp_msg(MSGT_TV, MSGL_V, "Tuner (%s) range: %lu -> %lu\n", priv->tuner.name,
1334 priv->tuner.rangelow, priv->tuner.rangehigh);
1335 return TVI_CONTROL_TRUE;
1337 case TVI_CONTROL_TUN_SET_TUNER:
1339 if (ioctl(priv->video_fd, VIDIOCSTUNER, &priv->tuner) == -1)
1341 mp_msg(MSGT_TV, MSGL_ERR, "ioctl set tuner failed: %s\n", strerror(errno));
1342 return TVI_CONTROL_FALSE;
1344 return TVI_CONTROL_TRUE;
1346 case TVI_CONTROL_TUN_SET_NORM:
1348 int req_mode = *(int *)arg;
1349 int norm_index;
1350 for(norm_index=0;supported_norms[norm_index].name; norm_index++)
1351 if(req_mode==supported_norms[norm_index].normid)
1352 break;
1354 if(!supported_norms[norm_index].name) {
1355 mp_msg(MSGT_TV, MSGL_ERR, "Unknown norm!\n");
1356 return TVI_CONTROL_FALSE;
1359 if (priv->channels[priv->act_channel].flags & VIDEO_VC_TUNER) {
1360 int prev_mode;
1362 control(priv, TVI_CONTROL_TUN_GET_TUNER, 0);
1363 if(!(priv->tuner.flags & supported_norms[norm_index].tuner_flags))
1365 mp_msg(MSGT_TV, MSGL_ERR, "Tuner isn't capable to set norm!\n");
1366 return TVI_CONTROL_FALSE;
1369 prev_mode = priv->tuner.mode;
1371 priv->tuner.mode = supported_norms[norm_index].tuner_mode;
1373 if (control(priv, TVI_CONTROL_TUN_SET_TUNER, &priv->tuner) != TVI_CONTROL_TRUE) {
1374 // norm setting failed, but maybe it's only because it's fixed
1375 if (priv->tuner.mode != prev_mode) return TVI_CONTROL_FALSE; // no it really failed
1380 priv->channels[priv->act_channel].norm = supported_norms[norm_index].input_norm;
1382 if (ioctl(priv->video_fd, VIDIOCSCHAN, &priv->channels[priv->act_channel]) == -1)
1384 mp_msg(MSGT_TV, MSGL_ERR, "ioctl set chan failed: %s\n", strerror(errno));
1385 return TVI_CONTROL_FALSE;
1388 if (ioctl(priv->video_fd, VIDIOCGCAP, &priv->capability) == -1) {
1389 mp_msg(MSGT_TV, MSGL_ERR, "ioctl get capabilities failed: %s\n", strerror(errno));
1390 return TVI_CONTROL_FALSE;
1393 priv->fps = supported_norms[norm_index].fps;
1395 if(priv->height > priv->capability.maxheight) {
1396 priv->height = priv->capability.maxheight;
1399 if(priv->width > priv->capability.maxwidth) {
1400 priv->width = priv->capability.maxwidth;
1403 return TVI_CONTROL_TRUE;
1405 case TVI_CONTROL_TUN_GET_NORM:
1407 *(int *)arg = priv->tuner.mode;
1409 return TVI_CONTROL_TRUE;
1411 case TVI_CONTROL_TUN_GET_SIGNAL:
1413 if (ioctl(priv->video_fd, VIDIOCGTUNER, &priv->tuner) == -1)
1415 mp_msg(MSGT_TV, MSGL_ERR, "ioctl get tuner failed: %s\n", strerror(errno));
1416 return TVI_CONTROL_FALSE;
1418 *(int*)arg=100*(priv->tuner.signal>>8)/255;
1419 return TVI_CONTROL_TRUE;
1422 /* ========== AUDIO controls =========== */
1423 case TVI_CONTROL_AUD_GET_FORMAT:
1425 *(int *)arg = AF_FORMAT_S16_LE;
1426 return TVI_CONTROL_TRUE;
1428 case TVI_CONTROL_AUD_GET_CHANNELS:
1430 *(int *)arg = priv->audio_in.channels;
1431 return TVI_CONTROL_TRUE;
1433 case TVI_CONTROL_AUD_GET_SAMPLERATE:
1435 *(int *)arg = priv->audio_in.samplerate;
1436 return TVI_CONTROL_TRUE;
1438 case TVI_CONTROL_AUD_GET_SAMPLESIZE:
1440 *(int *)arg = priv->audio_in.bytes_per_sample;
1441 return TVI_CONTROL_TRUE;
1443 case TVI_CONTROL_AUD_SET_SAMPLERATE:
1445 if (audio_in_set_samplerate(&priv->audio_in, *(int *)arg) < 0) return TVI_CONTROL_FALSE;
1446 setup_audio_buffer_sizes(priv);
1447 return TVI_CONTROL_TRUE;
1449 /* ========== SPECIFIC controls =========== */
1450 case TVI_CONTROL_SPC_GET_INPUT:
1452 int req_chan = *(int *)arg;
1453 int i;
1455 for (i = 0; i < priv->capability.channels; i++)
1457 if (priv->channels[i].channel == req_chan)
1458 break;
1461 priv->act_channel = i;
1463 if (ioctl(priv->video_fd, VIDIOCGCHAN, &priv->channels[i]) == -1)
1465 mp_msg(MSGT_TV, MSGL_ERR, "ioctl get channel failed: %s\n", strerror(errno));
1466 return TVI_CONTROL_FALSE;
1468 return TVI_CONTROL_TRUE;
1471 case TVI_CONTROL_SPC_SET_INPUT:
1473 struct video_channel chan;
1474 int req_chan = *(int *)arg;
1475 int i;
1477 if (req_chan >= priv->capability.channels)
1479 mp_msg(MSGT_TV, MSGL_ERR, "Invalid input requested: %d, valid: 0-%d\n",
1480 req_chan, priv->capability.channels - 1);
1481 return TVI_CONTROL_FALSE;
1484 for (i = 0; i < priv->capability.channels; i++)
1486 if (priv->channels[i].channel == req_chan)
1487 chan = priv->channels[i];
1490 if (ioctl(priv->video_fd, VIDIOCSCHAN, &chan) == -1)
1492 mp_msg(MSGT_TV, MSGL_ERR, "ioctl set chan failed: %s\n", strerror(errno));
1493 return TVI_CONTROL_FALSE;
1495 mp_msg(MSGT_TV, MSGL_INFO, "Using input '%s'\n", chan.name);
1497 priv->act_channel = i;
1499 /* update tuner state */
1500 // if (priv->capability.type & VID_TYPE_TUNER)
1501 if (priv->channels[priv->act_channel].flags & VIDEO_VC_TUNER)
1502 control(priv, TVI_CONTROL_TUN_GET_TUNER, 0);
1504 /* update local channel list */
1505 control(priv, TVI_CONTROL_SPC_GET_INPUT, &req_chan);
1506 return TVI_CONTROL_TRUE;
1507 case TVI_CONTROL_IMMEDIATE:
1508 priv->immediate_mode = 1;
1509 return TVI_CONTROL_TRUE;
1511 case TVI_CONTROL_VBI_INIT:
1513 void* ptr;
1514 tt_stream_props tsp;
1516 if (vbi_init(priv,*(char**)arg)!=TVI_CONTROL_TRUE)
1517 return TVI_CONTROL_FALSE;
1518 if(vbi_get_props(priv,&tsp)==TVI_CONTROL_TRUE)
1520 ptr=&tsp;
1521 if(teletext_control(NULL,TV_VBI_CONTROL_START,&ptr)==VBI_CONTROL_TRUE)
1522 priv->priv_vbi=ptr;
1523 else
1524 priv->priv_vbi=NULL;
1526 return TVI_CONTROL_TRUE;
1528 case TVI_CONTROL_GET_VBI_PTR:
1529 *(void **)arg=priv->priv_vbi;
1530 return TVI_CONTROL_TRUE;
1533 return TVI_CONTROL_UNKNOWN;
1536 static int set_mute(priv_t* priv,int value)
1538 if (!priv->capability.audios) {
1539 return 0;
1541 if(value)
1542 priv->audio[priv->audio_id].flags |=VIDEO_AUDIO_MUTE;
1543 else
1544 priv->audio[priv->audio_id].flags &= ~VIDEO_AUDIO_MUTE;
1546 if(ioctl(priv->video_fd, VIDIOCSAUDIO, &priv->audio[priv->audio_id])<0)
1547 return 0;
1548 return 1;
1551 // copies a video frame
1552 // for YV12 swaps the 2nd and 3rd plane
1553 static inline void copy_frame(priv_t *priv, unsigned char *dest, unsigned char *source)
1555 if(priv->tv_param->automute>0){
1556 if (ioctl(priv->video_fd, VIDIOCGTUNER, &priv->tuner) >= 0) {
1557 if(priv->tv_param->automute<<8>priv->tuner.signal){
1558 fill_blank_frame(dest,priv->bytesperline * priv->height,priv->format);
1559 set_mute(priv,1);
1560 return;
1563 set_mute(priv,0);
1565 // YV12 uses VIDEO_PALETTE_YUV420P, but the planes are swapped
1566 if (priv->format == IMGFMT_YV12) {
1567 fast_memcpy(dest, source, priv->width * priv->height);
1568 fast_memcpy(dest+priv->width * priv->height*5/4, source+priv->width * priv->height, priv->width * priv->height/4);
1569 fast_memcpy(dest+priv->width * priv->height, source+priv->width * priv->height*5/4, priv->width * priv->height/4);
1570 return;
1573 fast_memcpy(dest, source, priv->bytesperline * priv->height);
1576 // maximum skew change, in frames
1577 #define MAX_SKEW_DELTA 0.6
1578 static void *video_grabber(void *data)
1580 #define MAXTOL (priv->nbuf)
1581 priv_t *priv = (priv_t*)data;
1582 struct timeval curtime;
1583 long long skew, prev_skew, xskew, interval, prev_interval;
1584 int frame;
1585 int i;
1586 int framecount;
1587 int tolerance;
1588 unsigned long num;
1590 /* start the capture process */
1592 if ( priv->tv_param->mjpeg )
1594 mp_msg(MSGT_TV, MSGL_INFO, " MJP: gonna capture ! \n");
1595 for (i=0; i < priv->nbuf; i++) {
1596 num = i;
1597 if (ioctl(priv->video_fd, MJPIOC_QBUF_CAPT, &num) < 0)
1598 mp_msg(MSGT_TV, MSGL_ERR,
1599 "\n MJP: ioctl MJPIOC_QBUF_CAPT b failed: %s\n", strerror(errno));
1602 else
1604 for (i=0; i < priv->nbuf; i++) {
1605 if (ioctl(priv->video_fd, VIDIOCMCAPTURE, &priv->buf[i]) == -1)
1606 mp_msg(MSGT_TV, MSGL_ERR, "\nioctl mcapture failed: %s\n", strerror(errno));
1610 gettimeofday(&curtime, NULL);
1611 priv->starttime = (long long)1e6*curtime.tv_sec + curtime.tv_usec;
1612 priv->audio_skew_measure_time = 0;
1613 pthread_mutex_unlock(&priv->audio_starter);
1614 xskew = 0;
1615 skew = 0;
1616 interval = 0;
1618 prev_interval = 0;
1619 prev_skew = 0;
1621 tolerance = MAXTOL;
1623 for (framecount = 0; !priv->shutdown;)
1625 for (i = 0; i < priv->nbuf && !priv->shutdown; i++, framecount++) {
1627 if (priv->immediate_mode) {
1628 while (priv->video_cnt == priv->video_buffer_size_max) {
1629 usleep(10000);
1630 if (priv->shutdown) {
1631 return NULL;
1636 frame = i;
1638 if ( priv->tv_param->mjpeg )
1640 while (ioctl(priv->video_fd, MJPIOC_SYNC, &priv->buf[frame].frame) < 0 &&
1641 (errno == EAGAIN || errno == EINTR));
1643 else
1645 while (ioctl(priv->video_fd, VIDIOCSYNC, &priv->buf[frame].frame) < 0 &&
1646 (errno == EAGAIN || errno == EINTR));
1648 mp_dbg(MSGT_TV, MSGL_DBG3, "\npicture sync failed\n");
1650 gettimeofday(&curtime, NULL);
1651 if (!priv->immediate_mode) {
1652 interval = (long long)1e6*curtime.tv_sec + curtime.tv_usec - priv->starttime;
1653 } else {
1654 interval = (long long)1e6*framecount/priv->fps;
1657 if (!priv->immediate_mode) {
1658 long long period, orig_interval;
1660 if (tolerance == 0) {
1661 if (interval - prev_interval == 0) {
1662 mp_msg(MSGT_TV, MSGL_V, "\nvideo capture thread: frame delta = 0\n");
1663 } else if ((interval - prev_interval < (long long)0.85e6/priv->fps)
1664 || (interval - prev_interval > (long long)1.15e6/priv->fps) ) {
1665 mp_msg(MSGT_TV, MSGL_V, "\nvideo capture thread: frame delta ~ %.1f fps\n",
1666 (double)1e6/(interval - prev_interval));
1670 // correct the rate fluctuations on a small scale
1671 orig_interval = interval;
1672 period = priv->video_interval_sum/VIDEO_AVG_BUFFER_SIZE;
1673 if (interval - prev_interval > 105*period/100) {
1674 if (tolerance > 0) {
1675 mp_msg(MSGT_TV, MSGL_DBG3, "correcting timestamp\n");
1676 interval = prev_interval + priv->video_interval_sum/VIDEO_AVG_BUFFER_SIZE;
1677 tolerance--;
1678 } else {
1679 mp_msg(MSGT_TV, MSGL_DBG3, "bad - frames were dropped\n");
1680 tolerance = MAXTOL;
1682 } else {
1683 if (tolerance < MAXTOL) {
1684 mp_msg(MSGT_TV, MSGL_DBG3, "fluctuation overcome\n");
1686 tolerance = MAXTOL;
1689 priv->video_interval_sum -= priv->video_avg_buffer[priv->video_avg_ptr];
1690 priv->video_avg_buffer[priv->video_avg_ptr++] = orig_interval-prev_interval;
1691 priv->video_interval_sum += orig_interval-prev_interval;
1692 if (priv->video_avg_ptr >= VIDEO_AVG_BUFFER_SIZE) priv->video_avg_ptr = 0;
1694 // fprintf(stderr, "fps: %f\n", (double)1e6*VIDEO_AVG_BUFFER_SIZE/priv->video_interval_sum);
1696 // interpolate the skew in time
1697 pthread_mutex_lock(&priv->skew_mutex);
1698 xskew = priv->audio_skew + (interval - priv->audio_skew_measure_time)*priv->audio_skew_factor;
1699 pthread_mutex_unlock(&priv->skew_mutex);
1700 // correct extreme skew changes to avoid (especially) moving backwards in time
1701 if (xskew - prev_skew > (interval - prev_interval)*MAX_SKEW_DELTA) {
1702 skew = prev_skew + (interval - prev_interval)*MAX_SKEW_DELTA;
1703 } else if (xskew - prev_skew < -(interval - prev_interval)*MAX_SKEW_DELTA) {
1704 skew = prev_skew - (interval - prev_interval)*MAX_SKEW_DELTA;
1705 } else {
1706 skew = xskew;
1710 mp_msg(MSGT_TV, MSGL_DBG3, "\nfps = %f, interval = %f, a_skew = %f, corr_skew = %f\n",
1711 (interval != prev_interval) ? (double)1e6/(interval - prev_interval) : -1,
1712 (double)1e-6*interval, (double)1e-6*xskew, (double)1e-6*skew);
1713 mp_msg(MSGT_TV, MSGL_DBG3, "vcnt = %d, acnt = %d\n", priv->video_cnt, priv->audio_cnt);
1715 prev_skew = skew;
1716 prev_interval = interval;
1718 /* allocate a new buffer, if needed */
1719 pthread_mutex_lock(&priv->video_buffer_mutex);
1720 if (priv->video_buffer_size_current < priv->video_buffer_size_max) {
1721 if (priv->video_cnt == priv->video_buffer_size_current) {
1722 unsigned char *newbuf = calloc(priv->bytesperline, priv->height);
1723 if (newbuf) {
1724 memmove(priv->video_ringbuffer+priv->video_tail+1, priv->video_ringbuffer+priv->video_tail,
1725 (priv->video_buffer_size_current-priv->video_tail)*sizeof(unsigned char *));
1726 memmove(priv->video_timebuffer+priv->video_tail+1, priv->video_timebuffer+priv->video_tail,
1727 (priv->video_buffer_size_current-priv->video_tail)*sizeof(long long));
1728 priv->video_ringbuffer[priv->video_tail] = newbuf;
1729 if ((priv->video_head >= priv->video_tail) && (priv->video_cnt > 0)) priv->video_head++;
1730 priv->video_buffer_size_current++;
1734 pthread_mutex_unlock(&priv->video_buffer_mutex);
1736 if (priv->video_cnt == priv->video_buffer_size_current) {
1737 if (!priv->immediate_mode) {
1738 mp_msg(MSGT_TV, MSGL_ERR, "\nvideo buffer full - dropping frame\n");
1740 } else {
1741 if (priv->immediate_mode) {
1742 priv->video_timebuffer[priv->video_tail] = interval;
1743 } else {
1744 // compensate for audio skew
1745 // negative skew => there are more audio samples, increase interval
1746 // positive skew => less samples, shorten the interval
1747 priv->video_timebuffer[priv->video_tail] = interval - skew;
1750 if ( priv->tv_param->mjpeg )
1751 copy_frame(priv, priv->video_ringbuffer[priv->video_tail],
1752 priv->mmap+(priv->mjpeg_bufsize)*i);
1753 else
1754 copy_frame(priv, priv->video_ringbuffer[priv->video_tail],
1755 priv->mmap+priv->mbuf.offsets[frame]);
1756 priv->video_tail = (priv->video_tail+1)%priv->video_buffer_size_current;
1757 priv->video_cnt++;
1760 if ( priv->tv_param->mjpeg )
1762 num = frame;
1763 if (ioctl(priv->video_fd, MJPIOC_QBUF_CAPT, &num) < 0)
1765 mp_msg(MSGT_TV, MSGL_ERR, "\n MJP: ioctl MJPIOC_QBUF_CAPT end failed: %s\n",
1766 strerror(errno));
1767 continue;
1770 else
1772 if (ioctl(priv->video_fd, VIDIOCMCAPTURE, &priv->buf[frame]) == -1)
1774 mp_msg(MSGT_TV, MSGL_ERR, "\nioctl mcapture failed: %s\n", strerror(errno));
1775 continue;
1780 mp_msg(MSGT_TV, MSGL_INFO, " MJP: returning! \n");
1781 return NULL;
1784 static double grab_video_frame(priv_t *priv, char *buffer, int len)
1786 double interval;
1788 if (priv->first) {
1789 pthread_create(&priv->video_grabber_thread, NULL, video_grabber, priv);
1790 priv->first = 0;
1793 while (priv->video_cnt == 0) {
1794 usleep(10000);
1797 pthread_mutex_lock(&priv->video_buffer_mutex);
1798 interval = (double)priv->video_timebuffer[priv->video_head]*1e-6;
1799 fast_memcpy(buffer, priv->video_ringbuffer[priv->video_head], len);
1800 priv->video_cnt--;
1801 priv->video_head = (priv->video_head+1)%priv->video_buffer_size_current;
1802 pthread_mutex_unlock(&priv->video_buffer_mutex);
1804 return interval;
1807 static int get_video_framesize(priv_t *priv)
1809 return priv->bytesperline * priv->height;
1812 static void *audio_grabber(void *data)
1814 priv_t *priv = (priv_t*)data;
1815 struct timeval tv;
1816 int i, audio_skew_ptr = 0;
1817 long long current_time, prev_skew = 0;
1819 pthread_mutex_lock(&priv->audio_starter);
1821 audio_in_start_capture(&priv->audio_in);
1822 for (i = 0; i < priv->aud_skew_cnt; i++)
1823 priv->audio_skew_buffer[i] = 0;
1825 for (; !priv->shutdown;)
1827 if (audio_in_read_chunk(&priv->audio_in, priv->audio_ringbuffer+priv->audio_tail*priv->audio_in.blocksize) < 0)
1828 continue;
1830 gettimeofday(&tv, NULL);
1832 priv->audio_recv_blocks_total++;
1833 current_time = (long long)1e6*tv.tv_sec + tv.tv_usec - priv->starttime;
1835 priv->audio_skew_total -= priv->audio_skew_buffer[audio_skew_ptr];
1836 priv->audio_skew_buffer[audio_skew_ptr] = current_time
1837 - 1e6*priv->audio_secs_per_block*priv->audio_recv_blocks_total;
1838 priv->audio_skew_total += priv->audio_skew_buffer[audio_skew_ptr];
1839 audio_skew_ptr = (audio_skew_ptr+1) % priv->aud_skew_cnt;
1841 pthread_mutex_lock(&priv->skew_mutex);
1842 // linear interpolation - here we interpolate current skew value
1843 // from the moving average, which we expect to be in the middle
1844 // of the interval
1845 if (priv->audio_recv_blocks_total > priv->aud_skew_cnt) {
1846 priv->audio_skew = priv->audio_skew_total/priv->aud_skew_cnt;
1847 priv->audio_skew += (priv->audio_skew*priv->aud_skew_cnt)/(2*priv->audio_recv_blocks_total-priv->aud_skew_cnt);
1848 } else {
1849 // this smoothes the evolution of audio_skew at startup a bit
1850 priv->audio_skew = ((priv->aud_skew_cnt+priv->audio_recv_blocks_total)*priv->audio_skew_total)/(priv->aud_skew_cnt*priv->audio_recv_blocks_total);
1852 // current skew factor (assuming linearity)
1853 // used for further interpolation in video_grabber
1854 // probably overkill but seems to be necessary for
1855 // stress testing by dropping half of the audio frames ;)
1856 // especially when using ALSA with large block sizes
1857 // where audio_skew remains a long while behind
1858 if ((priv->audio_skew_measure_time != 0) && (current_time - priv->audio_skew_measure_time != 0)) {
1859 priv->audio_skew_factor = (double)(priv->audio_skew-prev_skew)/(current_time - priv->audio_skew_measure_time);
1860 } else {
1861 priv->audio_skew_factor = 0.0;
1864 priv->audio_skew_measure_time = current_time;
1865 prev_skew = priv->audio_skew;
1866 pthread_mutex_unlock(&priv->skew_mutex);
1868 if ((priv->audio_tail+1) % priv->audio_buffer_size == priv->audio_head) {
1869 mp_msg(MSGT_TV, MSGL_ERR, "\ntoo bad - dropping audio frame !\n");
1870 priv->audio_drop++;
1871 } else {
1872 priv->audio_tail = (priv->audio_tail+1) % priv->audio_buffer_size;
1873 priv->audio_cnt++;
1876 return NULL;
1879 static double grab_audio_frame(priv_t *priv, char *buffer, int len)
1881 mp_dbg(MSGT_TV, MSGL_DBG2, "grab_audio_frame(priv=%p, buffer=%p, len=%d)\n",
1882 priv, buffer, len);
1884 if (priv->first) {
1885 pthread_create(&priv->video_grabber_thread, NULL, video_grabber, priv);
1886 priv->first = 0;
1889 // compensate for dropped audio frames
1890 if (priv->audio_drop && (priv->audio_head == priv->audio_tail)) {
1891 priv->audio_drop--;
1892 priv->audio_sent_blocks_total++;
1893 memset(buffer, 0, len);
1894 return (double)priv->audio_sent_blocks_total*priv->audio_secs_per_block;
1897 while (priv->audio_head == priv->audio_tail) {
1898 usleep(10000);
1900 fast_memcpy(buffer, priv->audio_ringbuffer+priv->audio_head*priv->audio_in.blocksize, len);
1901 priv->audio_head = (priv->audio_head+1) % priv->audio_buffer_size;
1902 priv->audio_cnt--;
1903 priv->audio_sent_blocks_total++;
1904 return (double)priv->audio_sent_blocks_total*priv->audio_secs_per_block;
1907 static int get_audio_framesize(priv_t *priv)
1909 return priv->audio_in.blocksize;