Add explanatory comments to the #endif part of multiple inclusion guards.
[mplayer/greg.git] / stream / tvi_v4l.c
blob25d439ab45194a1923f3f1afb1bea3df45ac377d
1 /*
2 Video 4 Linux input
4 (C) 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!
18 #include "config.h"
20 #include <stdio.h>
21 #include <errno.h>
22 #include <fcntl.h>
23 #include <signal.h>
24 #include <sys/ioctl.h>
25 #include <sys/types.h>
26 #include <sys/time.h>
28 /* Necessary to prevent collisions between <linux/time.h> and <sys/time.h> when V4L2 is installed. */
29 #define _LINUX_TIME_H
31 #include <linux/videodev.h>
32 #include <unistd.h>
33 #include <sys/mman.h>
34 #include <stdlib.h>
35 #include <string.h>
36 #include <pthread.h>
37 #ifdef HAVE_SYS_SYSINFO_H
38 #include <sys/sysinfo.h>
39 #endif
41 #include "mp_msg.h"
42 #include "libaf/af_format.h"
43 #include "libmpcodecs/img_format.h"
44 #include "libvo/fastmemcpy.h"
45 #include "libvo/videodev_mjpeg.h"
47 #include "tv.h"
49 #include "audio_in.h"
51 static tvi_handle_t *tvi_init_v4l(tv_param_t* tv_param);
53 tvi_info_t tvi_info_v4l = {
54 tvi_init_v4l,
55 "Video 4 Linux input",
56 "v4l",
57 "Alex Beregszaszi",
58 "under development"
61 #define PAL_WIDTH 768
62 #define PAL_HEIGHT 576
63 #define PAL_FPS 25
65 #define NTSC_WIDTH 640
66 #define NTSC_HEIGHT 480
67 #define NTSC_FPS (30000.0/1001.0)
69 #define MAX_AUDIO_CHANNELS 10
71 #define VID_BUF_SIZE_IMMEDIATE 2
72 #define VIDEO_AVG_BUFFER_SIZE 600
74 typedef struct {
75 /* general */
76 char *video_device;
77 int video_fd;
78 struct video_capability capability;
79 struct video_channel *channels;
80 int act_channel;
81 struct video_tuner tuner;
83 /* video */
84 struct video_picture picture;
85 int format; /* output format */
86 int width;
87 int height;
88 int bytesperline;
89 float fps;
91 struct video_mbuf mbuf;
92 unsigned char *mmap;
93 struct video_mmap *buf;
94 int nbuf;
96 /* audio */
97 char *audio_device;
98 audio_in_t audio_in;
100 int audio_id;
101 struct video_audio audio[MAX_AUDIO_CHANNELS];
102 int audio_channels[MAX_AUDIO_CHANNELS];
104 /* buffering stuff */
105 int immediate_mode;
107 int audio_buffer_size;
108 int aud_skew_cnt;
109 unsigned char *audio_ringbuffer;
110 long long *audio_skew_buffer;
111 volatile int audio_head;
112 volatile int audio_tail;
113 volatile int audio_cnt;
114 volatile long long audio_skew;
115 volatile double audio_skew_factor;
116 volatile long long audio_skew_measure_time;
117 volatile int audio_drop;
119 int first;
120 int video_buffer_size_max;
121 volatile int video_buffer_size_current;
122 unsigned char **video_ringbuffer;
123 long long *video_timebuffer;
124 long long *video_avg_buffer;
125 int video_avg_ptr;
126 int video_interval_sum;
127 volatile int video_head;
128 volatile int video_tail;
129 volatile int video_cnt;
131 volatile int shutdown;
133 pthread_t audio_grabber_thread;
134 pthread_t video_grabber_thread;
135 pthread_mutex_t audio_starter;
136 pthread_mutex_t skew_mutex;
137 pthread_mutex_t video_buffer_mutex;
139 long long starttime;
140 double audio_secs_per_block;
141 long long audio_skew_total;
142 long audio_recv_blocks_total;
143 long audio_sent_blocks_total;
144 long mjpeg_bufsize;
145 #ifdef HAVE_TV_TELETEXT
146 char *vbi_dev;
147 int vbi_fd;
148 int vbi_bufsize;
149 int vbi_shutdown;
150 pthread_t vbi_grabber_thread;
151 void *priv_vbi;
152 #endif
154 tv_param_t *tv_param;
155 } priv_t;
157 #include "tvi_def.h"
159 static const char *device_cap2name[] = {
160 "capture", "tuner", "teletext", "overlay", "chromakey", "clipping",
161 "frameram", "scales", "monochrome", "subcapture", "mpeg-decoder",
162 "mpeg-encoder", "mjpeg-decoder", "mjpeg-encoder", NULL
165 static const char *device_palette2name[] = {
166 "-", "grey", "hi240", "rgb16", "rgb24", "rgb32", "rgb15", "yuv422",
167 "yuyv", "uyvy", "yuv420", "yuv411", "raw", "yuv422p", "yuv411p",
168 "yuv420p", "yuv410p"
170 #define PALETTE(x) ((x < sizeof(device_palette2name)/sizeof(char*)) ? device_palette2name[x] : "UNKNOWN")
172 static const struct {
173 char* name;
174 int normid;
175 int tuner_flags;
176 int tuner_mode;
177 int input_norm;
178 float fps;
179 } supported_norms[]={
180 {"pal", TV_NORM_PAL, VIDEO_TUNER_PAL, VIDEO_MODE_PAL, VIDEO_MODE_PAL, PAL_FPS },
181 {"ntsc", TV_NORM_NTSC, VIDEO_TUNER_NTSC, VIDEO_MODE_NTSC, VIDEO_MODE_NTSC, NTSC_FPS},
182 {"secam", TV_NORM_SECAM, VIDEO_TUNER_SECAM, VIDEO_MODE_SECAM,VIDEO_MODE_SECAM,PAL_FPS },
183 {"palnc", TV_NORM_PALNC, VIDEO_TUNER_PAL, VIDEO_MODE_PAL, 3, PAL_FPS },
184 {"palm", TV_NORM_PALM, VIDEO_TUNER_NTSC, VIDEO_MODE_NTSC, 4, NTSC_FPS},
185 {"paln", TV_NORM_PALN, VIDEO_TUNER_PAL, VIDEO_MODE_PAL, 5, PAL_FPS },
186 {"ntscjp",TV_NORM_NTSCJP, VIDEO_TUNER_NTSC, VIDEO_MODE_NTSC, 6, NTSC_FPS},
187 {"auto", -1, -1, -1, VIDEO_MODE_AUTO, -1 },
188 {NULL, -1, -1, -1, -1 }
191 static const char *norm2name(int mode)
193 int i;
194 for(i=0;supported_norms[i].name; i++)
195 if(supported_norms[i].input_norm==mode)
196 return supported_norms[i].name;
197 return "unknown";
200 static const char *audio_mode2name(int mode)
202 switch (mode) {
203 case VIDEO_SOUND_MONO:
204 return "mono";
205 case VIDEO_SOUND_STEREO:
206 return "stereo";
207 case VIDEO_SOUND_LANG1:
208 return "language1";
209 case VIDEO_SOUND_LANG2:
210 return "language2";
211 default:
212 return "unknown";
216 static void *audio_grabber(void *data);
217 static void *video_grabber(void *data);
219 static int palette2depth(int palette)
221 switch(palette)
223 /* component */
224 case VIDEO_PALETTE_RGB555:
225 return(15);
226 case VIDEO_PALETTE_RGB565:
227 return(16);
228 case VIDEO_PALETTE_RGB24:
229 return(24);
230 case VIDEO_PALETTE_RGB32:
231 return(32);
232 /* planar */
233 case VIDEO_PALETTE_YUV411P:
234 case VIDEO_PALETTE_YUV420P:
235 case VIDEO_PALETTE_YUV410P:
236 return(12);
237 /* packed */
238 case VIDEO_PALETTE_YUV422P:
239 case VIDEO_PALETTE_YUV422:
240 case VIDEO_PALETTE_YUYV:
241 case VIDEO_PALETTE_UYVY:
242 case VIDEO_PALETTE_YUV420:
243 case VIDEO_PALETTE_YUV411:
244 return(16);
246 return(-1);
249 static int format2palette(int format)
251 switch(format)
253 case IMGFMT_BGR15:
254 return(VIDEO_PALETTE_RGB555);
255 case IMGFMT_BGR16:
256 return(VIDEO_PALETTE_RGB565);
257 case IMGFMT_BGR24:
258 return(VIDEO_PALETTE_RGB24);
259 case IMGFMT_BGR32:
260 return(VIDEO_PALETTE_RGB32);
261 case IMGFMT_YV12:
262 case IMGFMT_I420:
263 return(VIDEO_PALETTE_YUV420P);
264 case IMGFMT_YUY2:
265 return(VIDEO_PALETTE_YUV422);
266 case IMGFMT_UYVY:
267 return(VIDEO_PALETTE_UYVY);
269 return(-1);
272 // sets and sanitizes audio buffer/block sizes
273 static void setup_audio_buffer_sizes(priv_t *priv)
275 int bytes_per_sample = priv->audio_in.bytes_per_sample;
277 // make the audio buffer at least 5 seconds long
278 priv->audio_buffer_size = 1 + 5*priv->audio_in.samplerate
279 *priv->audio_in.channels
280 *bytes_per_sample/priv->audio_in.blocksize;
281 if (priv->audio_buffer_size < 256) priv->audio_buffer_size = 256;
283 // make the skew buffer at least 1 second long
284 priv->aud_skew_cnt = 1 + 1*priv->audio_in.samplerate
285 *priv->audio_in.channels
286 *bytes_per_sample/priv->audio_in.blocksize;
287 if (priv->aud_skew_cnt < 16) priv->aud_skew_cnt = 16;
289 mp_msg(MSGT_TV, MSGL_V, "Audio capture - buffer %d blocks of %d bytes, skew average from %d meas.\n",
290 priv->audio_buffer_size, priv->audio_in.blocksize, priv->aud_skew_cnt);
293 static tvi_handle_t *tvi_init_v4l(tv_param_t* tv_param)
295 tvi_handle_t *h;
296 priv_t *priv;
298 h = new_handle();
299 if (!h)
300 return(NULL);
302 priv = h->priv;
304 /* set video device name */
305 if (!tv_param->device)
306 priv->video_device = strdup("/dev/video0");
307 else
308 priv->video_device = strdup(tv_param->device);
310 /* set video device name */
311 if (!tv_param->adevice)
312 priv->audio_device = NULL;
313 else {
314 priv->audio_device = strdup(tv_param->adevice);
317 /* allocation failed */
318 if (!priv->video_device) {
319 free_handle(h);
320 return(NULL);
323 priv->tv_param=tv_param;
324 return(h);
327 /* retrieves info about audio channels from the BTTV */
328 static void init_v4l_audio(priv_t *priv)
330 int i;
331 int reqmode;
333 if (!priv->capability.audios) return;
335 /* audio chanlist */
337 mp_msg(MSGT_TV, MSGL_V, " Audio devices: %d\n", priv->capability.audios);
339 mp_msg(MSGT_TV, MSGL_V, "Video capture card reports the audio setup as follows:\n");
340 for (i = 0; i < priv->capability.audios; i++)
342 if (i >= MAX_AUDIO_CHANNELS)
344 mp_msg(MSGT_TV, MSGL_ERR, "no space for more audio channels (increase in source!) (%d > %d)\n",
345 i, MAX_AUDIO_CHANNELS);
346 i = priv->capability.audios;
347 break;
350 priv->audio[i].audio = i;
351 if (ioctl(priv->video_fd, VIDIOCGAUDIO, &priv->audio[i]) == -1)
353 mp_msg(MSGT_TV, MSGL_ERR, "ioctl get audio failed: %s\n", strerror(errno));
354 break;
357 /* mute all channels */
358 priv->audio[i].flags |= VIDEO_AUDIO_MUTE;
359 reqmode = -1;
360 if (priv->tv_param->amode >= 0) {
361 switch (priv->tv_param->amode) {
362 case 0:
363 reqmode = VIDEO_SOUND_MONO;
364 break;
365 case 1:
366 reqmode = VIDEO_SOUND_STEREO;
367 break;
368 case 2:
369 reqmode = VIDEO_SOUND_LANG1;
370 break;
371 case 3:
372 reqmode = VIDEO_SOUND_LANG2;
373 break;
374 default:
375 mp_msg(MSGT_TV, MSGL_ERR, "Unknown audio mode requested.\n");
376 break;
378 if (reqmode >= 0) priv->audio[i].mode = reqmode;
380 ioctl(priv->video_fd, VIDIOCSAUDIO, &priv->audio[i]);
382 // get the parameters back
383 if (ioctl(priv->video_fd, VIDIOCGAUDIO, &priv->audio[i]) == -1)
385 mp_msg(MSGT_TV, MSGL_ERR, "ioctl get audio failed: %s\n", strerror(errno));
386 break;
389 switch(priv->audio[i].mode)
391 case VIDEO_SOUND_MONO:
392 case VIDEO_SOUND_LANG1:
393 case VIDEO_SOUND_LANG2:
394 priv->audio_channels[i] = 1;
395 break;
396 case VIDEO_SOUND_STEREO:
397 priv->audio_channels[i] = 2;
398 break;
399 default:
400 mp_msg(MSGT_TV, MSGL_ERR, "Card reports an unknown audio mode !\n");
401 mp_msg(MSGT_TV, MSGL_ERR, "Trying two channel audio. Use forcechan to override.\n");
402 priv->audio_channels[i] = 2;
403 break;
406 if (reqmode >= 0 && priv->audio[i].mode != reqmode) {
407 mp_msg(MSGT_TV, MSGL_ERR, "Audio mode setup warning!\n");
408 mp_msg(MSGT_TV, MSGL_ERR, "Requested mode was %s, but v4l still reports %s.\n",
409 audio_mode2name(reqmode), audio_mode2name(priv->audio[i].mode));
410 mp_msg(MSGT_TV, MSGL_ERR, "You may need \"forcechan\" option to force stereo/mono audio recording.\n");
413 /* display stuff */
414 mp_msg(MSGT_TV, MSGL_V, " %d: %s: ", priv->audio[i].audio,
415 priv->audio[i].name);
416 if (priv->audio[i].flags & VIDEO_AUDIO_MUTABLE) {
417 mp_msg(MSGT_TV, MSGL_V, "muted=%s ",
418 (priv->audio[i].flags & VIDEO_AUDIO_MUTE) ? "yes" : "no");
420 mp_msg(MSGT_TV, MSGL_V, "vol=%d bass=%d treble=%d balance=%d mode=%s",
421 priv->audio[i].volume, priv->audio[i].bass, priv->audio[i].treble,
422 priv->audio[i].balance, audio_mode2name(priv->audio[i].mode));
423 mp_msg(MSGT_TV, MSGL_V, " chan=%d\n", priv->audio_channels[i]);
425 if (priv->tv_param->forcechan >= 0)
426 priv->audio_channels[i] = priv->tv_param->forcechan;
428 // we'll call VIDIOCSAUDIO again when starting capture
429 // let's set audio mode to requested mode again for the case
430 // when VIDIOCGAUDIO just cannot report the mode correctly
431 if (reqmode >= 0) priv->audio[i].mode = reqmode;
435 #if !defined(__LINUX_VIDEODEV2_H) && !defined(VIDIOC_QUERYCAP)
436 struct v4l2_capability
438 __u8 driver[16]; /* i.e. "bttv" */
439 __u8 card[32]; /* i.e. "Hauppauge WinTV" */
440 __u8 bus_info[32]; /* "PCI:" + pci_dev->slot_name */
441 __u32 version; /* should use KERNEL_VERSION() */
442 __u32 capabilities; /* Device capabilities */
443 __u32 reserved[4];
446 #define VIDIOC_QUERYCAP _IOR ('V', 0, struct v4l2_capability)
447 #endif
449 static int init(priv_t *priv)
451 int i;
453 if (priv->tv_param->immediate == 1)
454 priv->tv_param->noaudio = 1;
456 priv->video_ringbuffer = NULL;
457 priv->video_timebuffer = NULL;
458 priv->video_avg_buffer = NULL;
459 priv->audio_ringbuffer = NULL;
460 priv->audio_skew_buffer = NULL;
462 priv->video_fd = open(priv->video_device, O_RDWR);
463 mp_msg(MSGT_TV, MSGL_DBG2, "Video fd: %d, %p\n", priv->video_fd,
464 priv->video_device);
465 if (priv->video_fd == -1)
467 mp_msg(MSGT_TV, MSGL_ERR, "unable to open '%s': %s\n",
468 priv->video_device, strerror(errno));
469 goto err;
472 /* check for v4l2 */
473 if (ioctl(priv->video_fd, VIDIOC_QUERYCAP, &priv->capability) == 0) {
474 mp_msg(MSGT_TV, MSGL_ERR, "=================================================================\n");
475 mp_msg(MSGT_TV, MSGL_ERR, " WARNING: YOU ARE USING V4L DEMUXER WITH V4L2 DRIVERS!!!\n");
476 mp_msg(MSGT_TV, MSGL_ERR, " As the V4L1 compatibility layer is broken, this may not work.\n");
477 mp_msg(MSGT_TV, MSGL_ERR, " If you encounter any problems, use driver=v4l2 instead.\n");
478 mp_msg(MSGT_TV, MSGL_ERR, " Bugreports on driver=v4l with v4l2 drivers will be ignored.\n");
479 mp_msg(MSGT_TV, MSGL_ERR, "=================================================================\n");
482 /* get capabilities (priv->capability is needed!) */
483 if (ioctl(priv->video_fd, VIDIOCGCAP, &priv->capability) == -1)
485 mp_msg(MSGT_TV, MSGL_ERR, "ioctl get capabilites failed: %s\n", strerror(errno));
486 goto err;
489 fcntl(priv->video_fd, F_SETFD, FD_CLOEXEC);
491 mp_msg(MSGT_TV, MSGL_INFO, "Selected device: %s\n", priv->capability.name);
492 mp_msg(MSGT_TV, MSGL_INFO, " Capabilites: ");
493 for (i = 0; device_cap2name[i] != NULL; i++)
494 if (priv->capability.type & (1 << i))
495 mp_msg(MSGT_TV, MSGL_INFO, "%s ", device_cap2name[i]);
496 mp_msg(MSGT_TV, MSGL_INFO, "\n");
497 mp_msg(MSGT_TV, MSGL_INFO, " Device type: %d\n", priv->capability.type);
498 mp_msg(MSGT_TV, MSGL_INFO, " Supported sizes: %dx%d => %dx%d\n",
499 priv->capability.minwidth, priv->capability.minheight,
500 priv->capability.maxwidth, priv->capability.maxheight);
501 priv->width = priv->capability.minwidth;
502 priv->height = priv->capability.minheight;
504 /* somewhere here could disable priv->tv_param->mjpeg, if it is not a capability */
506 /* initialize if necessary */
507 if ( priv->tv_param->mjpeg )
509 struct mjpeg_params bparm;
510 struct mjpeg_requestbuffers breq; /* buffer requests */
512 if (ioctl(priv->video_fd, MJPIOC_G_PARAMS, &bparm) < 0)
514 mp_msg(MSGT_TV, MSGL_ERR,
515 " MJP: Error getting video parameters: %s\n", strerror(errno));
516 goto err;
519 mp_msg(MSGT_TV, MSGL_INFO,
520 " MJP: previous params: x: %d, y: %d, w: %d, h: %d, decim: %d, fields: %d,\n",
521 bparm.img_x, bparm.img_y, bparm.img_width, bparm.img_height,
522 bparm.decimation, bparm.field_per_buff);
524 mp_msg(MSGT_TV, MSGL_INFO,
525 " MJP: HorDcm: %d, VerDcm: %d, TmpDcm: %d\n",
526 bparm.HorDcm, bparm.VerDcm, bparm.TmpDcm);
528 bparm.input = priv->tv_param->input; /* tv */
529 if (!strcasecmp(priv->tv_param->norm, "pal"))
530 bparm.norm = 0; /* PAL */
531 else if (!strcasecmp(priv->tv_param->norm, "ntsc"))
532 bparm.norm = 1; /* NTSC */
533 else if (!strcasecmp(priv->tv_param->norm, "secam"))
534 bparm.norm = 2; /* SECAM */
535 bparm.quality = priv->tv_param->quality;
536 bparm.decimation = priv->tv_param->decimation;
538 mp_msg(MSGT_TV, MSGL_INFO, " MJP: setting params to decimation: %d, quality: %d\n",
539 bparm.decimation, bparm.quality);
541 if (ioctl(priv->video_fd, MJPIOC_S_PARAMS, &bparm) < 0)
543 mp_msg(MSGT_TV, MSGL_ERR,
544 " MJP: Error setting video parameters: %s\n", strerror(errno));
545 goto err;
548 if (ioctl(priv->video_fd, MJPIOC_G_PARAMS, &bparm) < 0)
550 mp_msg(MSGT_TV, MSGL_ERR,
551 " MJP: Error getting video parameters: %s\n", strerror(errno));
552 goto err;
555 mp_msg(MSGT_TV, MSGL_INFO,
556 " MJP: current params: x: %d, y: %d, w: %d, h: %d, decim: %d, fields: %d,\n",
557 bparm.img_x, bparm.img_y, bparm.img_width, bparm.img_height,
558 bparm.decimation, bparm.field_per_buff);
560 mp_msg(MSGT_TV, MSGL_INFO,
561 " MJP: HorDcm: %d, VerDcm: %d, TmpDcm: %d\n",
562 bparm.HorDcm, bparm.VerDcm, bparm.TmpDcm);
565 breq.count = 64;
566 priv -> nbuf = breq.count;
567 priv->mbuf.frames = priv -> nbuf;
568 priv->mjpeg_bufsize = 256*1024;
569 if (priv->tv_param->buffer_size >= 0)
570 priv->mjpeg_bufsize = priv->tv_param->buffer_size*1024;
571 breq.size = priv -> mjpeg_bufsize;
572 if (ioctl(priv->video_fd, MJPIOC_REQBUFS,&(breq)) < 0)
574 mp_msg (MSGT_TV, MSGL_ERR,
575 " MJP: Error requesting video buffers: %s\n", strerror(errno));
576 goto err;
578 mp_msg(MSGT_TV, MSGL_INFO,
579 " MJP: Got %ld buffers of size %ld KB\n",
580 breq.count, breq.size/1024);
582 priv -> mmap = mmap(0, breq.count * breq.size,
583 PROT_READ|PROT_WRITE, MAP_SHARED, priv->video_fd, 0);
584 if (priv -> mmap == MAP_FAILED)
586 mp_msg(MSGT_TV, MSGL_INFO,
587 " MJP: Error mapping video buffers: %s\n", strerror(errno));
588 goto err;
592 mp_msg(MSGT_TV, MSGL_INFO, " Inputs: %d\n", priv->capability.channels);
593 priv->channels = calloc(priv->capability.channels, sizeof(struct video_channel));
594 if (!priv->channels)
595 goto malloc_failed;
596 memset(priv->channels, 0, sizeof(struct video_channel)*priv->capability.channels);
597 for (i = 0; i < priv->capability.channels; i++)
599 priv->channels[i].channel = i;
600 if (ioctl(priv->video_fd, VIDIOCGCHAN, &priv->channels[i]) == -1)
602 mp_msg(MSGT_TV, MSGL_ERR, "ioctl get channel failed: %s\n", strerror(errno));
603 break;
605 mp_msg(MSGT_TV, MSGL_INFO, " %d: %s: %s%s%s%s (tuner:%d, norm:%s)\n", i,
606 priv->channels[i].name,
607 (priv->channels[i].flags & VIDEO_VC_TUNER) ? "tuner " : "",
608 (priv->channels[i].flags & VIDEO_VC_AUDIO) ? "audio " : "",
609 (priv->channels[i].flags & VIDEO_TYPE_TV) ? "tv " : "",
610 (priv->channels[i].flags & VIDEO_TYPE_CAMERA) ? "camera " : "",
611 priv->channels[i].tuners,
612 norm2name(priv->channels[i].norm));
614 priv->act_channel = 0;
616 if (!(priv->capability.type & VID_TYPE_CAPTURE))
618 mp_msg(MSGT_TV, MSGL_ERR, "Only grabbing supported (for overlay use another program)\n");
619 goto err;
623 /* init v4l audio even when we don't capture */
624 init_v4l_audio(priv);
626 if (!priv->capability.audios && !priv->tv_param->force_audio) priv->tv_param->noaudio = 1;
628 /* audio init */
629 if (!priv->tv_param->noaudio) {
631 #if defined(HAVE_ALSA9) || defined(HAVE_ALSA1X)
632 if (priv->tv_param->alsa)
633 audio_in_init(&priv->audio_in, AUDIO_IN_ALSA);
634 else
635 audio_in_init(&priv->audio_in, AUDIO_IN_OSS);
636 #else
637 audio_in_init(&priv->audio_in, AUDIO_IN_OSS);
638 #endif
640 if (priv->audio_device) {
641 audio_in_set_device(&priv->audio_in, priv->audio_device);
644 if (priv->tv_param->audio_id < priv->capability.audios)
645 priv->audio_id = priv->tv_param->audio_id;
646 else
647 priv->audio_id = 0;
648 audio_in_set_samplerate(&priv->audio_in, 44100);
649 if (priv->capability.audios) {
650 audio_in_set_channels(&priv->audio_in, priv->audio_channels[priv->audio_id]);
651 } else {
652 if (priv->tv_param->forcechan >= 0) {
653 audio_in_set_channels(&priv->audio_in, priv->tv_param->forcechan);
654 } else {
655 audio_in_set_channels(&priv->audio_in, 2);
658 if (audio_in_setup(&priv->audio_in) < 0) return 0;
659 setup_audio_buffer_sizes(priv);
662 return(1);
664 malloc_failed:
665 if (priv->channels)
666 free(priv->channels);
667 if (priv->buf)
668 free(priv->buf);
669 err:
670 if (priv->video_fd != -1)
671 close(priv->video_fd);
672 return(0);
675 static int uninit(priv_t *priv)
677 unsigned long num;
679 #ifdef HAVE_TV_TELETEXT
680 priv->vbi_shutdown=1;
681 if(priv->vbi_grabber_thread)
682 pthread_join(priv->vbi_grabber_thread, NULL);
684 teletext_control(priv->priv_vbi,TV_VBI_CONTROL_STOP,(void*)1);
685 priv->priv_vbi=NULL;
687 if(priv->vbi_fd){
688 close(priv->vbi_fd);
689 priv->vbi_fd=0;
692 if(priv->vbi_dev){
693 free(priv->vbi_dev);
694 priv->vbi_dev=0;
697 #endif
699 priv->shutdown = 1;
701 mp_msg(MSGT_TV, MSGL_V, "Waiting for threads to finish... ");
702 if (!priv->tv_param->noaudio) {
703 pthread_join(priv->audio_grabber_thread, NULL);
704 pthread_mutex_destroy(&priv->audio_starter);
705 pthread_mutex_destroy(&priv->skew_mutex);
707 pthread_mutex_destroy(&priv->video_buffer_mutex);
708 if(priv->video_grabber_thread)
709 pthread_join(priv->video_grabber_thread, NULL);
711 mp_msg(MSGT_TV, MSGL_V, "done\n");
713 if (priv->capability.audios) {
714 priv->audio[priv->audio_id].flags |= VIDEO_AUDIO_MUTE;
715 ioctl(priv->video_fd, VIDIOCSAUDIO, &priv->audio[priv->audio_id]);
718 if ( priv->tv_param->mjpeg )
720 num = -1;
721 if (ioctl(priv->video_fd, MJPIOC_QBUF_CAPT, &num) < 0)
722 mp_msg(MSGT_TV, MSGL_ERR, "\n MJP: ioctl MJPIOC_QBUF_CAPT failed: %s\n", strerror(errno));
724 else
726 // We need to munmap as close don't close mem mappings
727 if(munmap(priv->mmap,priv->mbuf.size))
728 mp_msg(MSGT_TV, MSGL_ERR, "Munmap failed: %s\n",strerror(errno));
731 if(close(priv->video_fd))
732 mp_msg(MSGT_TV, MSGL_ERR, "Close tv failed: %s\n",strerror(errno));
734 audio_in_uninit(&priv->audio_in);
736 if (priv->video_ringbuffer) {
737 int i;
738 for (i = 0; i < priv->video_buffer_size_current; i++) {
739 free(priv->video_ringbuffer[i]);
741 free(priv->video_ringbuffer);
744 if (priv->video_timebuffer)
745 free(priv->video_timebuffer);
746 if (priv->video_avg_buffer)
747 free(priv->video_avg_buffer);
748 if (!priv->tv_param->noaudio) {
749 if (priv->audio_ringbuffer)
750 free(priv->audio_ringbuffer);
751 if (priv->audio_skew_buffer)
752 free(priv->audio_skew_buffer);
755 return(1);
758 static int get_capture_buffer_size(priv_t *priv)
760 int bufsize, cnt;
762 if (priv->tv_param->buffer_size >= 0) {
763 bufsize = priv->tv_param->buffer_size*1024*1024;
764 } else {
765 #ifdef HAVE_SYS_SYSINFO_H
766 struct sysinfo si;
768 sysinfo(&si);
769 if (si.totalram<2*1024*1024) {
770 bufsize = 1024*1024;
771 } else {
772 bufsize = si.totalram/2;
774 #else
775 bufsize = 16*1024*1024;
776 #endif
779 cnt = bufsize/(priv->height*priv->bytesperline);
780 if (cnt < 2) cnt = 2;
782 return cnt;
785 #ifdef HAVE_TV_TELETEXT
786 static int vbi_init(priv_t* priv,char* device)
788 int vbi_fd=0;
789 struct video_capability cap;
791 if(!device)
792 return TVI_CONTROL_FALSE;
794 priv->vbi_dev=strdup(device);
796 vbi_fd=open(priv->vbi_dev,O_RDWR);
797 if(vbi_fd<0){
798 mp_msg(MSGT_TV,MSGL_ERR,"vbi: could not open device %s\n",priv->vbi_dev);
799 return TVI_CONTROL_FALSE;
802 if(ioctl(vbi_fd,VIDIOCGCAP,&cap)<0){
803 mp_msg(MSGT_TV,MSGL_ERR,"vbi: Query capatibilities failed for %s\n",priv->vbi_dev);
804 close(vbi_fd);
805 return TVI_CONTROL_FALSE;
807 if(!cap.type & VID_TYPE_CAPTURE){
808 mp_msg(MSGT_TV,MSGL_ERR,"vbi: %s is not capture device\n",priv->vbi_dev);
809 close(vbi_fd);
810 return TVI_CONTROL_FALSE;
813 priv->vbi_fd=vbi_fd;
814 mp_msg(MSGT_TV,MSGL_DBG3,"vbi: init ok\n");
815 return TVI_CONTROL_TRUE;
818 static int vbi_get_props(priv_t* priv,tt_stream_props* ptsp)
820 struct vbi_format fmt;
821 int res;
822 if(!priv || !ptsp)
823 return TVI_CONTROL_FALSE;
825 memset(&fmt,0,sizeof(struct vbi_format));
826 if((res=ioctl(priv->vbi_fd,VIDIOCGVBIFMT,&fmt))<0){
827 mp_msg(MSGT_TV,MSGL_ERR,"vbi_get_props: Query format failed: %x\n",res);
828 return TVI_CONTROL_FALSE;
831 ptsp->interlaced=(fmt.flags& VBI_INTERLACED?1:0);
832 if(fmt.start[1]>0 && fmt.count[1]){
833 if(fmt.start[1]>=286)
834 //625
835 ptsp->offset=10.2e-6*fmt.sampling_rate;
836 else
837 //525
838 ptsp->offset=9.2e-6*fmt.sampling_rate;
839 }else
840 ptsp->offset=9.7e-6*fmt.sampling_rate;
842 ptsp->sampling_rate=fmt.sampling_rate;
843 ptsp->samples_per_line=fmt.samples_per_line,
845 ptsp->count[0]=fmt.count[0];
846 ptsp->count[1]=fmt.count[1];
847 ptsp->bufsize = ptsp->samples_per_line * (ptsp->count[0] + ptsp->count[1]);
849 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",
850 ptsp->sampling_rate,
851 ptsp->offset,
852 ptsp->samples_per_line,
853 ptsp->interlaced?"Yes":"No",
854 ptsp->count[0],
855 ptsp->count[1]);
857 return TVI_CONTROL_TRUE;
860 static void *vbi_grabber(void *data)
862 priv_t *priv = (priv_t *) data;
863 int bytes,seq,prev_seq;
864 unsigned char* buf;
865 tt_stream_props tsp;
867 if(!priv->priv_vbi){
868 mp_msg(MSGT_TV,MSGL_WARN,"vbi: vbi not initialized. stopping thread.\n");
869 return NULL;
872 if(vbi_get_props(priv,&tsp)!=TVI_CONTROL_TRUE)
873 return NULL;
875 buf=malloc(tsp.bufsize);
876 seq=0;
877 prev_seq=0;
878 mp_msg(MSGT_TV,MSGL_V,"vbi: vbi capture thread started.\n");
880 while (!priv->vbi_shutdown){
881 bytes=read(priv->vbi_fd,buf,tsp.bufsize);
882 if(bytes<0 && errno==EINTR)
883 continue;
884 if (bytes!=tsp.bufsize){
885 mp_msg(MSGT_TV,MSGL_WARN,"vbi: expecting bytes: %d, got: %d",tsp.bufsize,bytes);
886 break;
888 seq=*(int*)(buf+bytes-4);
889 if(seq<=1) continue;
890 if (prev_seq && seq!=prev_seq+1){
891 prev_seq=0;
892 seq=0;
894 prev_seq=seq;
895 teletext_control(priv->priv_vbi,TV_VBI_CONTROL_DECODE_PAGE,&buf);
896 mp_msg(MSGT_TV,MSGL_DBG3,"grabber: seq:%d\n",seq);
898 free(buf);
899 return NULL;
901 #endif //HAVE_TV_TELETEXT
903 static int start(priv_t *priv)
905 int i;
906 int bytes_per_sample;
907 struct video_window win;
909 if (ioctl(priv->video_fd, VIDIOCGPICT, &priv->picture) == -1)
911 mp_msg(MSGT_TV, MSGL_ERR, "ioctl get picture failed: %s\n", strerror(errno));
912 return(0);
915 priv->picture.palette = format2palette(priv->format);
916 priv->picture.depth = palette2depth(priv->picture.palette);
918 if (priv->format != IMGFMT_BGR15) {
919 priv->bytesperline = priv->width * priv->picture.depth / 8;
920 } else {
921 priv->bytesperline = priv->width * 2;
924 mp_msg(MSGT_TV, MSGL_V, "Picture values:\n");
925 mp_msg(MSGT_TV, MSGL_V, " Depth: %d, Palette: %s (Format: %s)\n", priv->picture.depth,
926 PALETTE(priv->picture.palette), vo_format_name(priv->format));
927 mp_msg(MSGT_TV, MSGL_V, " Brightness: %d, Hue: %d, Colour: %d, Contrast: %d\n",
928 priv->picture.brightness, priv->picture.hue,
929 priv->picture.colour, priv->picture.contrast);
931 if (ioctl(priv->video_fd, VIDIOCSPICT, &priv->picture) == -1)
933 mp_msg(MSGT_TV, MSGL_ERR, "ioctl set picture failed: %s\n", strerror(errno));
934 mp_msg(MSGT_TV, MSGL_ERR, "The 'outfmt' of '%s' is likely not supported by your card\n",
935 vo_format_name(priv->format));
936 return 0;
939 /* Set capture size */
940 win.x = 0;
941 win.y = 0;
942 win.width = priv->width;
943 win.height = priv->height;
944 win.chromakey = -1;
945 win.flags = 0;
946 win.clipcount = 0;
947 if (ioctl(priv->video_fd, VIDIOCSWIN, &win) == -1)
948 mp_msg(MSGT_TV, MSGL_ERR, "ioctl set window failed: %s\n", strerror(errno));
950 if ( !priv->tv_param->mjpeg )
952 /* map grab buffer */
953 if (ioctl(priv->video_fd, VIDIOCGMBUF, &priv->mbuf) == -1)
955 mp_msg(MSGT_TV, MSGL_ERR, "ioctl get mbuf failed: %s\n", strerror(errno));
956 return 0;
959 mp_msg(MSGT_TV, MSGL_V, "mbuf: size=%d, frames=%d\n",
960 priv->mbuf.size, priv->mbuf.frames);
961 priv->mmap = mmap(0, priv->mbuf.size, PROT_READ|PROT_WRITE,
962 MAP_SHARED, priv->video_fd, 0);
963 if (priv->mmap == (unsigned char *)-1)
965 mp_msg(MSGT_TV, MSGL_ERR, "Unable to map memory for buffers: %s\n", strerror(errno));
966 return 0;
968 mp_msg(MSGT_TV, MSGL_DBG2, "our buffer: %p\n", priv->mmap);
970 /* num of buffers */
971 priv->nbuf = priv->mbuf.frames;
973 /* video buffers */
974 priv->buf = calloc(priv->nbuf, sizeof(struct video_mmap));
975 if (!priv->buf)
976 return 0;
977 memset(priv->buf, 0, priv->nbuf * sizeof(struct video_mmap));
980 if ( !priv->tv_param->mjpeg )
982 priv->nbuf = priv->mbuf.frames;
983 for (i=0; i < priv->nbuf; i++)
985 priv->buf[i].format = priv->picture.palette;
986 priv->buf[i].frame = i;
987 priv->buf[i].width = priv->width;
988 priv->buf[i].height = priv->height;
989 mp_msg(MSGT_TV, MSGL_DBG2, "buffer: %d => %p\n", i, &priv->buf[i]);
993 #if 0
995 struct video_play_mode pmode;
997 pmode.mode = VID_PLAY_NORMAL;
998 pmode.p1 = 1;
999 pmode.p2 = 0;
1000 if (ioctl(priv->video_fd, VIDIOCSPLAYMODE, &pmode) == -1)
1002 mp_msg(MSGT_TV, MSGL_ERR, "ioctl set play mode failed: %s\n", strerror(errno));
1003 // return(0);
1006 #endif
1008 #if 0
1009 // initialize video capture
1010 if (ioctl(priv->video_fd, VIDIOCCAPTURE, &one) == -1)
1012 mp_msg(MSGT_TV, MSGL_ERR, "FATAL: ioctl ccapture failed: %s\n", strerror(errno));
1013 return(0);
1015 #endif
1017 /* setup audio parameters */
1018 if (!priv->tv_param->noaudio) {
1019 setup_audio_buffer_sizes(priv);
1020 bytes_per_sample = priv->audio_in.bytes_per_sample;
1021 priv->audio_skew_buffer = calloc(priv->aud_skew_cnt, sizeof(long long));
1022 if (!priv->audio_skew_buffer) {
1023 mp_msg(MSGT_TV, MSGL_ERR, "cannot allocate skew buffer: %s\n", strerror(errno));
1024 return 0;
1027 priv->audio_ringbuffer = calloc(priv->audio_in.blocksize, priv->audio_buffer_size);
1028 if (!priv->audio_ringbuffer) {
1029 mp_msg(MSGT_TV, MSGL_ERR, "cannot allocate audio buffer: %s\n", strerror(errno));
1030 return 0;
1033 priv->audio_secs_per_block = (double)priv->audio_in.blocksize/(priv->audio_in.samplerate
1034 *priv->audio_in.channels
1035 *bytes_per_sample);
1036 priv->audio_head = 0;
1037 priv->audio_tail = 0;
1038 priv->audio_cnt = 0;
1039 priv->audio_drop = 0;
1040 priv->audio_skew = 0;
1041 priv->audio_skew_total = 0;
1042 priv->audio_recv_blocks_total = 0;
1043 priv->audio_sent_blocks_total = 0;
1046 /* setup video parameters */
1047 if (priv->immediate_mode) {
1048 priv->video_buffer_size_max = VID_BUF_SIZE_IMMEDIATE;
1049 } else {
1050 priv->video_buffer_size_max = get_capture_buffer_size(priv);
1052 priv->video_buffer_size_current = 0;
1054 if (!priv->tv_param->noaudio) {
1055 if (priv->video_buffer_size_max < 3.0*priv->fps*priv->audio_secs_per_block) {
1056 mp_msg(MSGT_TV, MSGL_ERR, "Video buffer shorter than 3 times audio frame duration.\n"
1057 "You will probably experience heavy framedrops.\n");
1061 mp_msg(MSGT_TV, MSGL_V, "Using a ring buffer for maximum %d frames, %d MB total size.\n",
1062 priv->video_buffer_size_max,
1063 priv->video_buffer_size_max*priv->height*priv->bytesperline/(1024*1024));
1065 priv->video_ringbuffer = calloc(priv->video_buffer_size_max, sizeof(unsigned char*));
1066 if (!priv->video_ringbuffer) {
1067 mp_msg(MSGT_TV, MSGL_ERR, "cannot allocate video buffer: %s\n", strerror(errno));
1068 return 0;
1070 for (i = 0; i < priv->video_buffer_size_max; i++)
1071 priv->video_ringbuffer[i] = NULL;
1073 priv->video_timebuffer = calloc(priv->video_buffer_size_max, sizeof(long long));
1074 if (!priv->video_timebuffer) {
1075 mp_msg(MSGT_TV, MSGL_ERR, "cannot allocate time buffer: %s\n", strerror(errno));
1076 return 0;
1078 priv->video_avg_buffer = malloc(sizeof(long long) * VIDEO_AVG_BUFFER_SIZE);
1079 if (!priv->video_avg_buffer) {
1080 mp_msg(MSGT_TV, MSGL_ERR, "cannot allocate period buffer: %s\n", strerror(errno));
1081 return 0;
1083 priv->video_interval_sum = (1e6/priv->fps)*VIDEO_AVG_BUFFER_SIZE;
1084 for (i = 0; i < VIDEO_AVG_BUFFER_SIZE; i++) {
1085 priv->video_avg_buffer[i] = 1e6/priv->fps;
1088 priv->video_avg_ptr = 0;
1090 priv->video_head = 0;
1091 priv->video_tail = 0;
1092 priv->video_cnt = 0;
1093 priv->first = 1;
1095 if (priv->capability.audios) {
1096 /* enable audio */
1097 if (priv->tv_param->volume >= 0)
1098 priv->audio[priv->audio_id].volume = priv->tv_param->volume;
1099 if (priv->tv_param->bass >= 0)
1100 priv->audio[priv->audio_id].bass = priv->tv_param->bass;
1101 if (priv->tv_param->treble >= 0)
1102 priv->audio[priv->audio_id].treble = priv->tv_param->treble;
1103 if (priv->tv_param->balance >= 0)
1104 priv->audio[priv->audio_id].balance = priv->tv_param->balance;
1105 priv->audio[priv->audio_id].flags &= ~VIDEO_AUDIO_MUTE;
1106 mp_msg(MSGT_TV, MSGL_V, "Enabling tv audio. Requested setup is:\n");
1107 mp_msg(MSGT_TV, MSGL_V, "id=%d vol=%d bass=%d treble=%d balance=%d mode=%s",
1108 priv->audio_id,
1109 priv->audio[priv->audio_id].volume, priv->audio[priv->audio_id].bass, priv->audio[priv->audio_id].treble,
1110 priv->audio[priv->audio_id].balance, audio_mode2name(priv->audio[priv->audio_id].mode));
1111 mp_msg(MSGT_TV, MSGL_V, " chan=%d\n", priv->audio_channels[priv->audio_id]);
1112 ioctl(priv->video_fd, VIDIOCSAUDIO, &priv->audio[priv->audio_id]);
1115 #ifdef HAVE_TV_TELETEXT
1116 /* start vbi thread */
1117 if(priv->priv_vbi){
1118 priv->vbi_shutdown = 0;
1119 pthread_create(&priv->vbi_grabber_thread, NULL, vbi_grabber, priv);
1121 #endif
1123 /* launch capture threads */
1124 priv->shutdown = 0;
1125 if (!priv->tv_param->noaudio) {
1126 pthread_mutex_init(&priv->audio_starter, NULL);
1127 pthread_mutex_init(&priv->skew_mutex, NULL);
1128 pthread_mutex_lock(&priv->audio_starter);
1129 pthread_create(&priv->audio_grabber_thread, NULL, audio_grabber, priv);
1131 pthread_mutex_init(&priv->video_buffer_mutex, NULL);
1132 /* we'll launch the video capture later, when a first request for a frame arrives */
1134 return(1);
1138 static int control(priv_t *priv, int cmd, void *arg)
1140 mp_msg(MSGT_TV, MSGL_DBG2, "\ndebug: control(priv=%p, cmd=%d, arg=%p)\n",
1141 priv, cmd, arg);
1142 switch(cmd)
1144 /* ========== GENERIC controls =========== */
1145 case TVI_CONTROL_IS_VIDEO:
1147 if (priv->capability.type & VID_TYPE_CAPTURE)
1148 return(TVI_CONTROL_TRUE);
1149 return(TVI_CONTROL_FALSE);
1151 case TVI_CONTROL_IS_AUDIO:
1152 if (priv->tv_param->force_audio) return(TVI_CONTROL_TRUE);
1153 if (priv->channels[priv->act_channel].flags & VIDEO_VC_AUDIO)
1155 return(TVI_CONTROL_TRUE);
1157 return(TVI_CONTROL_FALSE);
1158 case TVI_CONTROL_IS_TUNER:
1160 // if (priv->capability.type & VID_TYPE_TUNER)
1161 if (priv->channels[priv->act_channel].flags & VIDEO_VC_TUNER)
1162 return(TVI_CONTROL_TRUE);
1163 return(TVI_CONTROL_FALSE);
1166 /* ========== VIDEO controls =========== */
1167 case TVI_CONTROL_VID_GET_FORMAT:
1169 int output_fmt = -1;
1171 output_fmt = priv->format;
1172 if ( priv->tv_param->mjpeg )
1174 mp_msg(MSGT_TV, MSGL_INFO, " MJP: setting sh_video->format to mjpg\n");
1175 output_fmt = 0x47504a4d;
1176 output_fmt = 0x67706a6d;
1177 *(int *)arg = output_fmt;
1178 mp_msg(MSGT_TV, MSGL_V, "Output format: %s\n", "mjpg");
1180 else
1182 *(int *)arg = output_fmt;
1183 mp_msg(MSGT_TV, MSGL_V, "Output format: %s\n", vo_format_name(output_fmt));
1185 return(TVI_CONTROL_TRUE);
1187 case TVI_CONTROL_VID_SET_FORMAT:
1188 priv->format = *(int *)arg;
1189 // !HACK! v4l uses BGR format instead of RGB
1190 // and we have to correct this. Fortunately,
1191 // tv.c reads later the format back so we
1192 // can persuade it to use what we want.
1193 if (IMGFMT_IS_RGB(priv->format)) {
1194 priv->format &= ~IMGFMT_RGB_MASK;
1195 priv->format |= IMGFMT_BGR;
1197 return(TVI_CONTROL_TRUE);
1198 case TVI_CONTROL_VID_GET_PLANES:
1199 *(int *)arg = 1; /* FIXME, also not needed at this time */
1200 return(TVI_CONTROL_TRUE);
1201 case TVI_CONTROL_VID_GET_BITS:
1202 *(int *)arg = palette2depth(format2palette(priv->format));
1203 return(TVI_CONTROL_TRUE);
1204 case TVI_CONTROL_VID_GET_WIDTH:
1205 *(int *)arg = priv->width;
1206 return(TVI_CONTROL_TRUE);
1207 case TVI_CONTROL_VID_CHK_WIDTH:
1209 int req_width = *(int *)arg;
1211 mp_msg(MSGT_TV, MSGL_V, "Requested width: %d\n", req_width);
1212 if ((req_width >= priv->capability.minwidth) &&
1213 (req_width <= priv->capability.maxwidth))
1214 return(TVI_CONTROL_TRUE);
1215 return(TVI_CONTROL_FALSE);
1217 case TVI_CONTROL_VID_SET_WIDTH:
1218 priv->width = *(int *)arg;
1219 return(TVI_CONTROL_TRUE);
1220 case TVI_CONTROL_VID_GET_HEIGHT:
1221 *(int *)arg = priv->height;
1222 return(TVI_CONTROL_TRUE);
1223 case TVI_CONTROL_VID_CHK_HEIGHT:
1225 int req_height = *(int *)arg;
1227 mp_msg(MSGT_TV, MSGL_V, "Requested height: %d\n", req_height);
1228 if ((req_height >= priv->capability.minheight) &&
1229 (req_height <= priv->capability.maxheight))
1230 return(TVI_CONTROL_TRUE);
1231 return(TVI_CONTROL_FALSE);
1233 case TVI_CONTROL_VID_SET_HEIGHT:
1234 priv->height = *(int *)arg;
1235 return(TVI_CONTROL_TRUE);
1236 case TVI_CONTROL_VID_GET_PICTURE:
1237 if (ioctl(priv->video_fd, VIDIOCGPICT, &priv->picture) == -1)
1239 mp_msg(MSGT_TV, MSGL_ERR, "ioctl get picture failed: %s\n", strerror(errno));
1240 return(TVI_CONTROL_FALSE);
1242 return(TVI_CONTROL_TRUE);
1243 case TVI_CONTROL_VID_SET_PICTURE:
1244 if (ioctl(priv->video_fd, VIDIOCSPICT, &priv->picture) == -1)
1246 mp_msg(MSGT_TV, MSGL_ERR, "ioctl set picture failed: %s\n", strerror(errno));
1247 return(TVI_CONTROL_FALSE);
1249 return(TVI_CONTROL_TRUE);
1250 case TVI_CONTROL_VID_SET_BRIGHTNESS:
1251 priv->picture.brightness = (327*(*(int *)arg+100)) + 68;
1252 return control(priv, TVI_CONTROL_VID_SET_PICTURE, 0);
1253 case TVI_CONTROL_VID_SET_HUE:
1254 priv->picture.hue = (327*(*(int *)arg+100)) + 68;
1255 return control(priv, TVI_CONTROL_VID_SET_PICTURE, 0);
1256 case TVI_CONTROL_VID_SET_SATURATION:
1257 priv->picture.colour = (327*(*(int *)arg+100)) + 68;
1258 return control(priv, TVI_CONTROL_VID_SET_PICTURE, 0);
1259 case TVI_CONTROL_VID_SET_CONTRAST:
1260 priv->picture.contrast = (327*(*(int *)arg+100)) + 68;
1261 return control(priv, TVI_CONTROL_VID_SET_PICTURE, 0);
1262 case TVI_CONTROL_VID_GET_BRIGHTNESS:
1263 if(!control(priv, TVI_CONTROL_VID_GET_PICTURE, 0)) return 0;
1264 *(int*)arg = ((int)priv->picture.brightness-68)/327-100;
1265 return 1;
1266 case TVI_CONTROL_VID_GET_HUE:
1267 if(!control(priv, TVI_CONTROL_VID_GET_PICTURE, 0)) return 0;
1268 *(int*)arg = ((int)priv->picture.hue-68)/327-100;
1269 return 1;
1270 case TVI_CONTROL_VID_GET_SATURATION:
1271 if(!control(priv, TVI_CONTROL_VID_GET_PICTURE, 0)) return 0;
1272 *(int*)arg = ((int)priv->picture.colour-68)/327-100;
1273 return 1;
1274 case TVI_CONTROL_VID_GET_CONTRAST:
1275 if(!control(priv, TVI_CONTROL_VID_GET_PICTURE, 0)) return 0;
1276 *(int*)arg = ((int)priv->picture.contrast-68)/327-100;
1277 return 1;
1278 case TVI_CONTROL_VID_GET_FPS:
1279 *(float *)arg=priv->fps;
1280 return(TVI_CONTROL_TRUE);
1282 /* ========== TUNER controls =========== */
1283 case TVI_CONTROL_TUN_GET_FREQ:
1285 unsigned long freq;
1287 if (ioctl(priv->video_fd, VIDIOCGFREQ, &freq) == -1)
1289 mp_msg(MSGT_TV, MSGL_ERR, "ioctl get freq failed: %s\n", strerror(errno));
1290 return(TVI_CONTROL_FALSE);
1293 /* tuner uses khz not mhz ! */
1294 // if (priv->tuner.flags & VIDEO_TUNER_LOW)
1295 // freq /= 1000;
1296 *(unsigned long *)arg = freq;
1297 return(TVI_CONTROL_TRUE);
1299 case TVI_CONTROL_TUN_SET_FREQ:
1301 /* argument is in MHz ! */
1302 unsigned long freq = *(unsigned long *)arg;
1304 if (priv->capability.audios) {
1305 priv->audio[priv->audio_id].flags |= VIDEO_AUDIO_MUTE;
1306 ioctl(priv->video_fd, VIDIOCSAUDIO, &priv->audio[priv->audio_id]);
1309 mp_msg(MSGT_TV, MSGL_V, "requested frequency: %.3f\n", (float)freq/16);
1311 /* tuner uses khz not mhz ! */
1312 // if (priv->tuner.flags & VIDEO_TUNER_LOW)
1313 // freq *= 1000;
1314 // mp_msg(MSGT_TV, MSGL_V, " requesting from driver: freq=%.3f\n", (float)freq/16);
1315 if (ioctl(priv->video_fd, VIDIOCSFREQ, &freq) == -1)
1317 mp_msg(MSGT_TV, MSGL_ERR, "ioctl set freq failed: %s\n", strerror(errno));
1318 return(TVI_CONTROL_FALSE);
1320 usleep(100000); // wait to suppress noise during switching
1322 if (priv->capability.audios) {
1323 priv->audio[priv->audio_id].flags &= ~VIDEO_AUDIO_MUTE;
1324 ioctl(priv->video_fd, VIDIOCSAUDIO, &priv->audio[priv->audio_id]);
1327 return(TVI_CONTROL_TRUE);
1329 case TVI_CONTROL_TUN_GET_TUNER:
1331 if (ioctl(priv->video_fd, VIDIOCGTUNER, &priv->tuner) == -1)
1333 mp_msg(MSGT_TV, MSGL_ERR, "ioctl get tuner failed: %s\n", strerror(errno));
1334 return(TVI_CONTROL_FALSE);
1337 mp_msg(MSGT_TV, MSGL_V, "Tuner (%s) range: %lu -> %lu\n", priv->tuner.name,
1338 priv->tuner.rangelow, priv->tuner.rangehigh);
1339 return(TVI_CONTROL_TRUE);
1341 case TVI_CONTROL_TUN_SET_TUNER:
1343 if (ioctl(priv->video_fd, VIDIOCSTUNER, &priv->tuner) == -1)
1345 mp_msg(MSGT_TV, MSGL_ERR, "ioctl set tuner failed: %s\n", strerror(errno));
1346 return(TVI_CONTROL_FALSE);
1348 return(TVI_CONTROL_TRUE);
1350 case TVI_CONTROL_TUN_SET_NORM:
1352 int req_mode = *(int *)arg;
1353 int norm_index;
1354 for(norm_index=0;supported_norms[norm_index].name; norm_index++)
1355 if(req_mode==supported_norms[norm_index].normid)
1356 break;
1358 if(!supported_norms[norm_index].name) {
1359 mp_msg(MSGT_TV, MSGL_ERR, "Unknown norm!\n");
1360 return(TVI_CONTROL_FALSE);
1363 if (priv->channels[priv->act_channel].flags & VIDEO_VC_TUNER) {
1364 int prev_mode;
1366 control(priv, TVI_CONTROL_TUN_GET_TUNER, 0);
1367 if(!(priv->tuner.flags & supported_norms[norm_index].tuner_flags))
1369 mp_msg(MSGT_TV, MSGL_ERR, "Tuner isn't capable to set norm!\n");
1370 return(TVI_CONTROL_FALSE);
1373 prev_mode = priv->tuner.mode;
1375 priv->tuner.mode = supported_norms[norm_index].tuner_mode;
1377 if (control(priv, TVI_CONTROL_TUN_SET_TUNER, &priv->tuner) != TVI_CONTROL_TRUE) {
1378 // norm setting failed, but maybe it's only because it's fixed
1379 if (priv->tuner.mode != prev_mode) return(TVI_CONTROL_FALSE); // no it really failed
1384 priv->channels[priv->act_channel].norm = supported_norms[norm_index].input_norm;
1386 if (ioctl(priv->video_fd, VIDIOCSCHAN, &priv->channels[priv->act_channel]) == -1)
1388 mp_msg(MSGT_TV, MSGL_ERR, "ioctl set chan failed: %s\n", strerror(errno));
1389 return(TVI_CONTROL_FALSE);
1392 if (ioctl(priv->video_fd, VIDIOCGCAP, &priv->capability) == -1) {
1393 mp_msg(MSGT_TV, MSGL_ERR, "ioctl get capabilites failed: %s\n", strerror(errno));
1394 return(TVI_CONTROL_FALSE);
1397 priv->fps = supported_norms[norm_index].fps;
1399 if(priv->height > priv->capability.maxheight) {
1400 priv->height = priv->capability.maxheight;
1403 if(priv->width > priv->capability.maxwidth) {
1404 priv->width = priv->capability.maxwidth;
1407 return(TVI_CONTROL_TRUE);
1409 case TVI_CONTROL_TUN_GET_NORM:
1411 *(int *)arg = priv->tuner.mode;
1413 return(TVI_CONTROL_TRUE);
1415 case TVI_CONTROL_TUN_GET_SIGNAL:
1417 if (ioctl(priv->video_fd, VIDIOCGTUNER, &priv->tuner) == -1)
1419 mp_msg(MSGT_TV, MSGL_ERR, "ioctl get tuner failed: %s\n", strerror(errno));
1420 return(TVI_CONTROL_FALSE);
1422 *(int*)arg=100*(priv->tuner.signal>>8)/255;
1423 return(TVI_CONTROL_TRUE);
1426 /* ========== AUDIO controls =========== */
1427 case TVI_CONTROL_AUD_GET_FORMAT:
1429 *(int *)arg = AF_FORMAT_S16_LE;
1430 return(TVI_CONTROL_TRUE);
1432 case TVI_CONTROL_AUD_GET_CHANNELS:
1434 *(int *)arg = priv->audio_in.channels;
1435 return(TVI_CONTROL_TRUE);
1437 case TVI_CONTROL_AUD_GET_SAMPLERATE:
1439 *(int *)arg = priv->audio_in.samplerate;
1440 return(TVI_CONTROL_TRUE);
1442 case TVI_CONTROL_AUD_GET_SAMPLESIZE:
1444 *(int *)arg = priv->audio_in.bytes_per_sample;
1445 return(TVI_CONTROL_TRUE);
1447 case TVI_CONTROL_AUD_SET_SAMPLERATE:
1449 if (audio_in_set_samplerate(&priv->audio_in, *(int *)arg) < 0) return TVI_CONTROL_FALSE;
1450 setup_audio_buffer_sizes(priv);
1451 return(TVI_CONTROL_TRUE);
1453 /* ========== SPECIFIC controls =========== */
1454 case TVI_CONTROL_SPC_GET_INPUT:
1456 int req_chan = *(int *)arg;
1457 int i;
1459 for (i = 0; i < priv->capability.channels; i++)
1461 if (priv->channels[i].channel == req_chan)
1462 break;
1465 priv->act_channel = i;
1467 if (ioctl(priv->video_fd, VIDIOCGCHAN, &priv->channels[i]) == -1)
1469 mp_msg(MSGT_TV, MSGL_ERR, "ioctl get channel failed: %s\n", strerror(errno));
1470 return(TVI_CONTROL_FALSE);
1472 return(TVI_CONTROL_TRUE);
1475 case TVI_CONTROL_SPC_SET_INPUT:
1477 struct video_channel chan;
1478 int req_chan = *(int *)arg;
1479 int i;
1481 if (req_chan >= priv->capability.channels)
1483 mp_msg(MSGT_TV, MSGL_ERR, "Invalid input requested: %d, valid: 0-%d\n",
1484 req_chan, priv->capability.channels - 1);
1485 return(TVI_CONTROL_FALSE);
1488 for (i = 0; i < priv->capability.channels; i++)
1490 if (priv->channels[i].channel == req_chan)
1491 chan = priv->channels[i];
1494 if (ioctl(priv->video_fd, VIDIOCSCHAN, &chan) == -1)
1496 mp_msg(MSGT_TV, MSGL_ERR, "ioctl set chan failed: %s\n", strerror(errno));
1497 return(TVI_CONTROL_FALSE);
1499 mp_msg(MSGT_TV, MSGL_INFO, "Using input '%s'\n", chan.name);
1501 priv->act_channel = i;
1503 /* update tuner state */
1504 // if (priv->capability.type & VID_TYPE_TUNER)
1505 if (priv->channels[priv->act_channel].flags & VIDEO_VC_TUNER)
1506 control(priv, TVI_CONTROL_TUN_GET_TUNER, 0);
1508 /* update local channel list */
1509 control(priv, TVI_CONTROL_SPC_GET_INPUT, &req_chan);
1510 return(TVI_CONTROL_TRUE);
1511 case TVI_CONTROL_IMMEDIATE:
1512 priv->immediate_mode = 1;
1513 return(TVI_CONTROL_TRUE);
1515 #ifdef HAVE_TV_TELETEXT
1516 case TVI_CONTROL_VBI_INIT:
1518 void* ptr;
1519 tt_stream_props tsp;
1521 if (vbi_init(priv,*(char**)arg)!=TVI_CONTROL_TRUE)
1522 return TVI_CONTROL_FALSE;
1523 if(vbi_get_props(priv,&tsp)==TVI_CONTROL_TRUE)
1525 ptr=&tsp;
1526 if(teletext_control(NULL,TV_VBI_CONTROL_START,&ptr)==TVI_CONTROL_TRUE)
1527 priv->priv_vbi=ptr;
1528 else
1529 priv->priv_vbi=NULL;
1531 return TVI_CONTROL_TRUE;
1533 default:
1534 return teletext_control(priv->priv_vbi,cmd,arg);
1535 #endif
1538 return(TVI_CONTROL_UNKNOWN);
1541 static int set_mute(priv_t* priv,int value)
1543 if (!priv->capability.audios) {
1544 return 0;
1546 if(value)
1547 priv->audio[priv->audio_id].flags |=VIDEO_AUDIO_MUTE;
1548 else
1549 priv->audio[priv->audio_id].flags &= ~VIDEO_AUDIO_MUTE;
1551 if(ioctl(priv->video_fd, VIDIOCSAUDIO, &priv->audio[priv->audio_id])<0)
1552 return 0;
1553 return 1;
1556 // copies a video frame
1557 // for YV12 swaps the 2nd and 3rd plane
1558 static inline void copy_frame(priv_t *priv, unsigned char *dest, unsigned char *source)
1560 if(priv->tv_param->automute>0){
1561 if (ioctl(priv->video_fd, VIDIOCGTUNER, &priv->tuner) >= 0) {
1562 if(priv->tv_param->automute<<8>priv->tuner.signal){
1563 fill_blank_frame(dest,priv->bytesperline * priv->height,priv->format);
1564 set_mute(priv,1);
1565 return;
1568 set_mute(priv,0);
1570 // YV12 uses VIDEO_PALETTE_YUV420P, but the planes are swapped
1571 if (priv->format == IMGFMT_YV12) {
1572 fast_memcpy(dest, source, priv->width * priv->height);
1573 fast_memcpy(dest+priv->width * priv->height*5/4, source+priv->width * priv->height, priv->width * priv->height/4);
1574 fast_memcpy(dest+priv->width * priv->height, source+priv->width * priv->height*5/4, priv->width * priv->height/4);
1575 return;
1578 fast_memcpy(dest, source, priv->bytesperline * priv->height);
1581 // maximum skew change, in frames
1582 #define MAX_SKEW_DELTA 0.6
1583 static void *video_grabber(void *data)
1585 #define MAXTOL (priv->nbuf)
1586 priv_t *priv = (priv_t*)data;
1587 struct timeval curtime;
1588 long long skew, prev_skew, xskew, interval, prev_interval;
1589 int frame;
1590 int i;
1591 int framecount;
1592 int tolerance;
1593 unsigned long num;
1595 /* start the capture process */
1597 if ( priv->tv_param->mjpeg )
1599 mp_msg(MSGT_TV, MSGL_INFO, " MJP: gonna capture ! \n");
1600 for (i=0; i < priv->nbuf; i++) {
1601 num = i;
1602 if (ioctl(priv->video_fd, MJPIOC_QBUF_CAPT, &num) < 0)
1603 mp_msg(MSGT_TV, MSGL_ERR,
1604 "\n MJP: ioctl MJPIOC_QBUF_CAPT b failed: %s\n", strerror(errno));
1607 else
1609 for (i=0; i < priv->nbuf; i++) {
1610 if (ioctl(priv->video_fd, VIDIOCMCAPTURE, &priv->buf[i]) == -1)
1611 mp_msg(MSGT_TV, MSGL_ERR, "\nioctl mcapture failed: %s\n", strerror(errno));
1615 gettimeofday(&curtime, NULL);
1616 priv->starttime = (long long)1e6*curtime.tv_sec + curtime.tv_usec;
1617 priv->audio_skew_measure_time = 0;
1618 pthread_mutex_unlock(&priv->audio_starter);
1619 xskew = 0;
1620 skew = 0;
1621 interval = 0;
1623 prev_interval = 0;
1624 prev_skew = 0;
1626 tolerance = MAXTOL;
1628 for (framecount = 0; !priv->shutdown;)
1630 for (i = 0; i < priv->nbuf && !priv->shutdown; i++, framecount++) {
1632 if (priv->immediate_mode) {
1633 while (priv->video_cnt == priv->video_buffer_size_max) {
1634 usleep(10000);
1635 if (priv->shutdown) {
1636 return NULL;
1641 frame = i;
1643 if ( priv->tv_param->mjpeg )
1645 while (ioctl(priv->video_fd, MJPIOC_SYNC, &priv->buf[frame].frame) < 0 &&
1646 (errno == EAGAIN || errno == EINTR));
1648 else
1650 while (ioctl(priv->video_fd, VIDIOCSYNC, &priv->buf[frame].frame) < 0 &&
1651 (errno == EAGAIN || errno == EINTR));
1653 mp_dbg(MSGT_TV, MSGL_DBG3, "\npicture sync failed\n");
1655 gettimeofday(&curtime, NULL);
1656 if (!priv->immediate_mode) {
1657 interval = (long long)1e6*curtime.tv_sec + curtime.tv_usec - priv->starttime;
1658 } else {
1659 interval = (long long)1e6*framecount/priv->fps;
1662 if (!priv->immediate_mode) {
1663 long long period, orig_interval;
1665 if (tolerance == 0) {
1666 if (interval - prev_interval == 0) {
1667 mp_msg(MSGT_TV, MSGL_V, "\nvideo capture thread: frame delta = 0\n");
1668 } else if ((interval - prev_interval < (long long)0.85e6/priv->fps)
1669 || (interval - prev_interval > (long long)1.15e6/priv->fps) ) {
1670 mp_msg(MSGT_TV, MSGL_V, "\nvideo capture thread: frame delta ~ %.1lf fps\n",
1671 (double)1e6/(interval - prev_interval));
1675 // correct the rate fluctuations on a small scale
1676 orig_interval = interval;
1677 period = priv->video_interval_sum/VIDEO_AVG_BUFFER_SIZE;
1678 if (interval - prev_interval > 105*period/100) {
1679 if (tolerance > 0) {
1680 mp_msg(MSGT_TV, MSGL_DBG3, "correcting timestamp\n");
1681 interval = prev_interval + priv->video_interval_sum/VIDEO_AVG_BUFFER_SIZE;
1682 tolerance--;
1683 } else {
1684 mp_msg(MSGT_TV, MSGL_DBG3, "bad - frames were dropped\n");
1685 tolerance = MAXTOL;
1687 } else {
1688 if (tolerance < MAXTOL) {
1689 mp_msg(MSGT_TV, MSGL_DBG3, "fluctuation overcome\n");
1691 tolerance = MAXTOL;
1694 priv->video_interval_sum -= priv->video_avg_buffer[priv->video_avg_ptr];
1695 priv->video_avg_buffer[priv->video_avg_ptr++] = orig_interval-prev_interval;
1696 priv->video_interval_sum += orig_interval-prev_interval;
1697 if (priv->video_avg_ptr >= VIDEO_AVG_BUFFER_SIZE) priv->video_avg_ptr = 0;
1699 // fprintf(stderr, "fps: %lf\n", (double)1e6*VIDEO_AVG_BUFFER_SIZE/priv->video_interval_sum);
1701 // interpolate the skew in time
1702 pthread_mutex_lock(&priv->skew_mutex);
1703 xskew = priv->audio_skew + (interval - priv->audio_skew_measure_time)*priv->audio_skew_factor;
1704 pthread_mutex_unlock(&priv->skew_mutex);
1705 // correct extreme skew changes to avoid (especially) moving backwards in time
1706 if (xskew - prev_skew > (interval - prev_interval)*MAX_SKEW_DELTA) {
1707 skew = prev_skew + (interval - prev_interval)*MAX_SKEW_DELTA;
1708 } else if (xskew - prev_skew < -(interval - prev_interval)*MAX_SKEW_DELTA) {
1709 skew = prev_skew - (interval - prev_interval)*MAX_SKEW_DELTA;
1710 } else {
1711 skew = xskew;
1715 mp_msg(MSGT_TV, MSGL_DBG3, "\nfps = %lf, interval = %lf, a_skew = %f, corr_skew = %f\n",
1716 (interval != prev_interval) ? (double)1e6/(interval - prev_interval) : -1,
1717 (double)1e-6*interval, (double)1e-6*xskew, (double)1e-6*skew);
1718 mp_msg(MSGT_TV, MSGL_DBG3, "vcnt = %d, acnt = %d\n", priv->video_cnt, priv->audio_cnt);
1720 prev_skew = skew;
1721 prev_interval = interval;
1723 /* allocate a new buffer, if needed */
1724 pthread_mutex_lock(&priv->video_buffer_mutex);
1725 if (priv->video_buffer_size_current < priv->video_buffer_size_max) {
1726 if (priv->video_cnt == priv->video_buffer_size_current) {
1727 unsigned char *newbuf = calloc(priv->bytesperline, priv->height);
1728 if (newbuf) {
1729 memmove(priv->video_ringbuffer+priv->video_tail+1, priv->video_ringbuffer+priv->video_tail,
1730 (priv->video_buffer_size_current-priv->video_tail)*sizeof(unsigned char *));
1731 memmove(priv->video_timebuffer+priv->video_tail+1, priv->video_timebuffer+priv->video_tail,
1732 (priv->video_buffer_size_current-priv->video_tail)*sizeof(long long));
1733 priv->video_ringbuffer[priv->video_tail] = newbuf;
1734 if ((priv->video_head >= priv->video_tail) && (priv->video_cnt > 0)) priv->video_head++;
1735 priv->video_buffer_size_current++;
1739 pthread_mutex_unlock(&priv->video_buffer_mutex);
1741 if (priv->video_cnt == priv->video_buffer_size_current) {
1742 if (!priv->immediate_mode) {
1743 mp_msg(MSGT_TV, MSGL_ERR, "\nvideo buffer full - dropping frame\n");
1745 } else {
1746 if (priv->immediate_mode) {
1747 priv->video_timebuffer[priv->video_tail] = interval;
1748 } else {
1749 // compensate for audio skew
1750 // negative skew => there are more audio samples, increase interval
1751 // positive skew => less samples, shorten the interval
1752 priv->video_timebuffer[priv->video_tail] = interval - skew;
1755 if ( priv->tv_param->mjpeg )
1756 copy_frame(priv, priv->video_ringbuffer[priv->video_tail],
1757 priv->mmap+(priv->mjpeg_bufsize)*i);
1758 else
1759 copy_frame(priv, priv->video_ringbuffer[priv->video_tail],
1760 priv->mmap+priv->mbuf.offsets[frame]);
1761 priv->video_tail = (priv->video_tail+1)%priv->video_buffer_size_current;
1762 priv->video_cnt++;
1765 if ( priv->tv_param->mjpeg )
1767 num = frame;
1768 if (ioctl(priv->video_fd, MJPIOC_QBUF_CAPT, &num) < 0)
1770 mp_msg(MSGT_TV, MSGL_ERR, "\n MJP: ioctl MJPIOC_QBUF_CAPT end failed: %s\n",
1771 strerror(errno));
1772 continue;
1775 else
1777 if (ioctl(priv->video_fd, VIDIOCMCAPTURE, &priv->buf[frame]) == -1)
1779 mp_msg(MSGT_TV, MSGL_ERR, "\nioctl mcapture failed: %s\n", strerror(errno));
1780 continue;
1785 mp_msg(MSGT_TV, MSGL_INFO, " MJP: returning! \n");
1786 return NULL;
1789 static double grab_video_frame(priv_t *priv, char *buffer, int len)
1791 double interval;
1793 if (priv->first) {
1794 pthread_create(&priv->video_grabber_thread, NULL, video_grabber, priv);
1795 priv->first = 0;
1798 while (priv->video_cnt == 0) {
1799 usleep(10000);
1802 pthread_mutex_lock(&priv->video_buffer_mutex);
1803 interval = (double)priv->video_timebuffer[priv->video_head]*1e-6;
1804 fast_memcpy(buffer, priv->video_ringbuffer[priv->video_head], len);
1805 priv->video_cnt--;
1806 priv->video_head = (priv->video_head+1)%priv->video_buffer_size_current;
1807 pthread_mutex_unlock(&priv->video_buffer_mutex);
1809 return interval;
1812 static int get_video_framesize(priv_t *priv)
1814 return(priv->bytesperline * priv->height);
1817 static void *audio_grabber(void *data)
1819 priv_t *priv = (priv_t*)data;
1820 struct timeval tv;
1821 int i, audio_skew_ptr = 0;
1822 long long current_time, prev_skew = 0;
1824 pthread_mutex_lock(&priv->audio_starter);
1826 audio_in_start_capture(&priv->audio_in);
1827 for (i = 0; i < priv->aud_skew_cnt; i++)
1828 priv->audio_skew_buffer[i] = 0;
1830 for (; !priv->shutdown;)
1832 if (audio_in_read_chunk(&priv->audio_in, priv->audio_ringbuffer+priv->audio_tail*priv->audio_in.blocksize) < 0)
1833 continue;
1835 gettimeofday(&tv, NULL);
1837 priv->audio_recv_blocks_total++;
1838 current_time = (long long)1e6*tv.tv_sec + tv.tv_usec - priv->starttime;
1840 priv->audio_skew_total -= priv->audio_skew_buffer[audio_skew_ptr];
1841 priv->audio_skew_buffer[audio_skew_ptr] = current_time
1842 - 1e6*priv->audio_secs_per_block*priv->audio_recv_blocks_total;
1843 priv->audio_skew_total += priv->audio_skew_buffer[audio_skew_ptr];
1844 audio_skew_ptr = (audio_skew_ptr+1) % priv->aud_skew_cnt;
1846 pthread_mutex_lock(&priv->skew_mutex);
1847 // linear interpolation - here we interpolate current skew value
1848 // from the moving average, which we expect to be in the middle
1849 // of the interval
1850 if (priv->audio_recv_blocks_total > priv->aud_skew_cnt) {
1851 priv->audio_skew = priv->audio_skew_total/priv->aud_skew_cnt;
1852 priv->audio_skew += (priv->audio_skew*priv->aud_skew_cnt)/(2*priv->audio_recv_blocks_total-priv->aud_skew_cnt);
1853 } else {
1854 // this smoothes the evolution of audio_skew at startup a bit
1855 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);
1857 // current skew factor (assuming linearity)
1858 // used for further interpolation in video_grabber
1859 // probably overkill but seems to be necessary for
1860 // stress testing by dropping half of the audio frames ;)
1861 // especially when using ALSA with large block sizes
1862 // where audio_skew remains a long while behind
1863 if ((priv->audio_skew_measure_time != 0) && (current_time - priv->audio_skew_measure_time != 0)) {
1864 priv->audio_skew_factor = (double)(priv->audio_skew-prev_skew)/(current_time - priv->audio_skew_measure_time);
1865 } else {
1866 priv->audio_skew_factor = 0.0;
1869 priv->audio_skew_measure_time = current_time;
1870 prev_skew = priv->audio_skew;
1871 pthread_mutex_unlock(&priv->skew_mutex);
1873 if ((priv->audio_tail+1) % priv->audio_buffer_size == priv->audio_head) {
1874 mp_msg(MSGT_TV, MSGL_ERR, "\ntoo bad - dropping audio frame !\n");
1875 priv->audio_drop++;
1876 } else {
1877 priv->audio_tail = (priv->audio_tail+1) % priv->audio_buffer_size;
1878 priv->audio_cnt++;
1881 return NULL;
1884 static double grab_audio_frame(priv_t *priv, char *buffer, int len)
1886 mp_dbg(MSGT_TV, MSGL_DBG2, "grab_audio_frame(priv=%p, buffer=%p, len=%d)\n",
1887 priv, buffer, len);
1889 if (priv->first) {
1890 pthread_create(&priv->video_grabber_thread, NULL, video_grabber, priv);
1891 priv->first = 0;
1894 // compensate for dropped audio frames
1895 if (priv->audio_drop && (priv->audio_head == priv->audio_tail)) {
1896 priv->audio_drop--;
1897 priv->audio_sent_blocks_total++;
1898 memset(buffer, 0, len);
1899 return (double)priv->audio_sent_blocks_total*priv->audio_secs_per_block;
1902 while (priv->audio_head == priv->audio_tail) {
1903 usleep(10000);
1905 fast_memcpy(buffer, priv->audio_ringbuffer+priv->audio_head*priv->audio_in.blocksize, len);
1906 priv->audio_head = (priv->audio_head+1) % priv->audio_buffer_size;
1907 priv->audio_cnt--;
1908 priv->audio_sent_blocks_total++;
1909 return (double)priv->audio_sent_blocks_total*priv->audio_secs_per_block;
1912 static int get_audio_framesize(priv_t *priv)
1914 return(priv->audio_in.blocksize);