Give better name to Inverse_Table_6_9
[mplayer/glamo.git] / stream / tvi_v4l.c
blob89796917765704650ad7ac9f7b94da92818c9266
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 <sys/ioctl.h>
24 #include <sys/types.h>
25 #include <sys/time.h>
27 /* Necessary to prevent collisions between <linux/time.h> and <sys/time.h> when V4L2 is installed. */
28 #define _LINUX_TIME_H
30 #include <linux/videodev.h>
31 #include <unistd.h>
32 #include <sys/mman.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <pthread.h>
36 #ifdef HAVE_SYS_SYSINFO_H
37 #include <sys/sysinfo.h>
38 #endif
40 #include "mp_msg.h"
41 #include "libaf/af_format.h"
42 #include "libmpcodecs/img_format.h"
43 #include "libvo/fastmemcpy.h"
44 #include "libvo/videodev_mjpeg.h"
46 #include "tv.h"
48 #include "audio_in.h"
50 static tvi_handle_t *tvi_init_v4l(tv_param_t* tv_param);
52 const tvi_info_t tvi_info_v4l = {
53 tvi_init_v4l,
54 "Video 4 Linux input",
55 "v4l",
56 "Alex Beregszaszi",
57 "under development"
60 #define PAL_WIDTH 768
61 #define PAL_HEIGHT 576
62 #define PAL_FPS 25
64 #define NTSC_WIDTH 640
65 #define NTSC_HEIGHT 480
66 #define NTSC_FPS (30000.0/1001.0)
68 #define MAX_AUDIO_CHANNELS 10
70 #define VID_BUF_SIZE_IMMEDIATE 2
71 #define VIDEO_AVG_BUFFER_SIZE 600
73 typedef struct {
74 /* general */
75 char *video_device;
76 int video_fd;
77 struct video_capability capability;
78 struct video_channel *channels;
79 int act_channel;
80 struct video_tuner tuner;
82 /* video */
83 struct video_picture picture;
84 int format; /* output format */
85 int width;
86 int height;
87 int bytesperline;
88 float fps;
90 struct video_mbuf mbuf;
91 unsigned char *mmap;
92 struct video_mmap *buf;
93 int nbuf;
95 /* audio */
96 char *audio_device;
97 audio_in_t audio_in;
99 int audio_id;
100 struct video_audio audio[MAX_AUDIO_CHANNELS];
101 int audio_channels[MAX_AUDIO_CHANNELS];
103 /* buffering stuff */
104 int immediate_mode;
106 int audio_buffer_size;
107 int aud_skew_cnt;
108 unsigned char *audio_ringbuffer;
109 long long *audio_skew_buffer;
110 volatile int audio_head;
111 volatile int audio_tail;
112 volatile int audio_cnt;
113 volatile long long audio_skew;
114 volatile double audio_skew_factor;
115 volatile long long audio_skew_measure_time;
116 volatile int audio_drop;
118 int first;
119 int video_buffer_size_max;
120 volatile int video_buffer_size_current;
121 unsigned char **video_ringbuffer;
122 long long *video_timebuffer;
123 long long *video_avg_buffer;
124 int video_avg_ptr;
125 int video_interval_sum;
126 volatile int video_head;
127 volatile int video_tail;
128 volatile int video_cnt;
130 volatile int shutdown;
132 pthread_t audio_grabber_thread;
133 pthread_t video_grabber_thread;
134 pthread_mutex_t audio_starter;
135 pthread_mutex_t skew_mutex;
136 pthread_mutex_t video_buffer_mutex;
138 long long starttime;
139 double audio_secs_per_block;
140 long long audio_skew_total;
141 long audio_recv_blocks_total;
142 long audio_sent_blocks_total;
143 long mjpeg_bufsize;
144 #ifdef CONFIG_TV_TELETEXT
145 char *vbi_dev;
146 int vbi_fd;
147 int vbi_bufsize;
148 int vbi_shutdown;
149 pthread_t vbi_grabber_thread;
150 void *priv_vbi;
151 #endif
153 tv_param_t *tv_param;
154 } priv_t;
156 #include "tvi_def.h"
158 static const char *device_cap2name[] = {
159 "capture", "tuner", "teletext", "overlay", "chromakey", "clipping",
160 "frameram", "scales", "monochrome", "subcapture", "mpeg-decoder",
161 "mpeg-encoder", "mjpeg-decoder", "mjpeg-encoder", NULL
164 static const char *device_palette2name[] = {
165 "-", "grey", "hi240", "rgb16", "rgb24", "rgb32", "rgb15", "yuv422",
166 "yuyv", "uyvy", "yuv420", "yuv411", "raw", "yuv422p", "yuv411p",
167 "yuv420p", "yuv410p"
169 #define PALETTE(x) ((x < sizeof(device_palette2name)/sizeof(char*)) ? device_palette2name[x] : "UNKNOWN")
171 static const struct {
172 char* name;
173 int normid;
174 int tuner_flags;
175 int tuner_mode;
176 int input_norm;
177 float fps;
178 } supported_norms[]={
179 {"pal", TV_NORM_PAL, VIDEO_TUNER_PAL, VIDEO_MODE_PAL, VIDEO_MODE_PAL, PAL_FPS },
180 {"ntsc", TV_NORM_NTSC, VIDEO_TUNER_NTSC, VIDEO_MODE_NTSC, VIDEO_MODE_NTSC, NTSC_FPS},
181 {"secam", TV_NORM_SECAM, VIDEO_TUNER_SECAM, VIDEO_MODE_SECAM,VIDEO_MODE_SECAM,PAL_FPS },
182 {"palnc", TV_NORM_PALNC, VIDEO_TUNER_PAL, VIDEO_MODE_PAL, 3, PAL_FPS },
183 {"palm", TV_NORM_PALM, VIDEO_TUNER_NTSC, VIDEO_MODE_NTSC, 4, NTSC_FPS},
184 {"paln", TV_NORM_PALN, VIDEO_TUNER_PAL, VIDEO_MODE_PAL, 5, PAL_FPS },
185 {"ntscjp",TV_NORM_NTSCJP, VIDEO_TUNER_NTSC, VIDEO_MODE_NTSC, 6, NTSC_FPS},
186 {"auto", -1, -1, -1, VIDEO_MODE_AUTO, -1 },
187 {NULL, -1, -1, -1, -1 }
190 static const char *norm2name(int mode)
192 int i;
193 for(i=0;supported_norms[i].name; i++)
194 if(supported_norms[i].input_norm==mode)
195 return supported_norms[i].name;
196 return "unknown";
199 static const char *audio_mode2name(int mode)
201 switch (mode) {
202 case VIDEO_SOUND_MONO:
203 return "mono";
204 case VIDEO_SOUND_STEREO:
205 return "stereo";
206 case VIDEO_SOUND_LANG1:
207 return "language1";
208 case VIDEO_SOUND_LANG2:
209 return "language2";
210 default:
211 return "unknown";
215 static void *audio_grabber(void *data);
216 static void *video_grabber(void *data);
218 static int palette2depth(int palette)
220 switch(palette)
222 /* component */
223 case VIDEO_PALETTE_RGB555:
224 return 15;
225 case VIDEO_PALETTE_RGB565:
226 return 16;
227 case VIDEO_PALETTE_RGB24:
228 return 24;
229 case VIDEO_PALETTE_RGB32:
230 return 32;
231 /* planar */
232 case VIDEO_PALETTE_YUV411P:
233 case VIDEO_PALETTE_YUV420P:
234 case VIDEO_PALETTE_YUV410P:
235 return 12;
236 /* packed */
237 case VIDEO_PALETTE_YUV422P:
238 case VIDEO_PALETTE_YUV422:
239 case VIDEO_PALETTE_YUYV:
240 case VIDEO_PALETTE_UYVY:
241 case VIDEO_PALETTE_YUV420:
242 case VIDEO_PALETTE_YUV411:
243 return 16;
245 return -1;
248 static int format2palette(int format)
250 switch(format)
252 case IMGFMT_BGR15:
253 return VIDEO_PALETTE_RGB555;
254 case IMGFMT_BGR16:
255 return VIDEO_PALETTE_RGB565;
256 case IMGFMT_BGR24:
257 return VIDEO_PALETTE_RGB24;
258 case IMGFMT_BGR32:
259 return VIDEO_PALETTE_RGB32;
260 case IMGFMT_YV12:
261 case IMGFMT_I420:
262 return VIDEO_PALETTE_YUV420P;
263 case IMGFMT_YUY2:
264 return VIDEO_PALETTE_YUV422;
265 case IMGFMT_UYVY:
266 return VIDEO_PALETTE_UYVY;
268 return -1;
271 // sets and sanitizes audio buffer/block sizes
272 static void setup_audio_buffer_sizes(priv_t *priv)
274 int bytes_per_sample = priv->audio_in.bytes_per_sample;
276 // make the audio buffer at least 5 seconds long
277 priv->audio_buffer_size = 1 + 5*priv->audio_in.samplerate
278 *priv->audio_in.channels
279 *bytes_per_sample/priv->audio_in.blocksize;
280 if (priv->audio_buffer_size < 256) priv->audio_buffer_size = 256;
282 // make the skew buffer at least 1 second long
283 priv->aud_skew_cnt = 1 + 1*priv->audio_in.samplerate
284 *priv->audio_in.channels
285 *bytes_per_sample/priv->audio_in.blocksize;
286 if (priv->aud_skew_cnt < 16) priv->aud_skew_cnt = 16;
288 mp_msg(MSGT_TV, MSGL_V, "Audio capture - buffer %d blocks of %d bytes, skew average from %d meas.\n",
289 priv->audio_buffer_size, priv->audio_in.blocksize, priv->aud_skew_cnt);
292 static tvi_handle_t *tvi_init_v4l(tv_param_t* tv_param)
294 tvi_handle_t *h;
295 priv_t *priv;
297 h = new_handle();
298 if (!h)
299 return NULL;
301 priv = h->priv;
303 /* set video device name */
304 if (!tv_param->device)
305 priv->video_device = strdup("/dev/video0");
306 else
307 priv->video_device = strdup(tv_param->device);
309 /* set video device name */
310 if (!tv_param->adevice)
311 priv->audio_device = NULL;
312 else {
313 priv->audio_device = strdup(tv_param->adevice);
316 /* allocation failed */
317 if (!priv->video_device) {
318 free_handle(h);
319 return NULL;
322 priv->tv_param=tv_param;
323 return h;
326 /* retrieves info about audio channels from the BTTV */
327 static void init_v4l_audio(priv_t *priv)
329 int i;
330 int reqmode;
332 if (!priv->capability.audios) return;
334 /* audio chanlist */
336 mp_msg(MSGT_TV, MSGL_V, " Audio devices: %d\n", priv->capability.audios);
338 mp_msg(MSGT_TV, MSGL_V, "Video capture card reports the audio setup as follows:\n");
339 for (i = 0; i < priv->capability.audios; i++)
341 if (i >= MAX_AUDIO_CHANNELS)
343 mp_msg(MSGT_TV, MSGL_ERR, "no space for more audio channels (increase in source!) (%d > %d)\n",
344 i, MAX_AUDIO_CHANNELS);
345 i = priv->capability.audios;
346 break;
349 priv->audio[i].audio = i;
350 if (ioctl(priv->video_fd, VIDIOCGAUDIO, &priv->audio[i]) == -1)
352 mp_msg(MSGT_TV, MSGL_ERR, "ioctl get audio failed: %s\n", strerror(errno));
353 break;
356 /* mute all channels */
357 priv->audio[i].flags |= VIDEO_AUDIO_MUTE;
358 reqmode = -1;
359 if (priv->tv_param->amode >= 0) {
360 switch (priv->tv_param->amode) {
361 case 0:
362 reqmode = VIDEO_SOUND_MONO;
363 break;
364 case 1:
365 reqmode = VIDEO_SOUND_STEREO;
366 break;
367 case 2:
368 reqmode = VIDEO_SOUND_LANG1;
369 break;
370 case 3:
371 reqmode = VIDEO_SOUND_LANG2;
372 break;
373 default:
374 mp_msg(MSGT_TV, MSGL_ERR, "Unknown audio mode requested.\n");
375 break;
377 if (reqmode >= 0) priv->audio[i].mode = reqmode;
379 ioctl(priv->video_fd, VIDIOCSAUDIO, &priv->audio[i]);
381 // get the parameters back
382 if (ioctl(priv->video_fd, VIDIOCGAUDIO, &priv->audio[i]) == -1)
384 mp_msg(MSGT_TV, MSGL_ERR, "ioctl get audio failed: %s\n", strerror(errno));
385 break;
388 switch(priv->audio[i].mode)
390 case VIDEO_SOUND_MONO:
391 case VIDEO_SOUND_LANG1:
392 case VIDEO_SOUND_LANG2:
393 priv->audio_channels[i] = 1;
394 break;
395 case VIDEO_SOUND_STEREO:
396 priv->audio_channels[i] = 2;
397 break;
398 default:
399 mp_msg(MSGT_TV, MSGL_ERR, "Card reports an unknown audio mode !\n");
400 mp_msg(MSGT_TV, MSGL_ERR, "Trying two channel audio. Use forcechan to override.\n");
401 priv->audio_channels[i] = 2;
402 break;
405 if (reqmode >= 0 && priv->audio[i].mode != reqmode) {
406 mp_msg(MSGT_TV, MSGL_ERR, "Audio mode setup warning!\n");
407 mp_msg(MSGT_TV, MSGL_ERR, "Requested mode was %s, but v4l still reports %s.\n",
408 audio_mode2name(reqmode), audio_mode2name(priv->audio[i].mode));
409 mp_msg(MSGT_TV, MSGL_ERR, "You may need \"forcechan\" option to force stereo/mono audio recording.\n");
412 /* display stuff */
413 mp_msg(MSGT_TV, MSGL_V, " %d: %s: ", priv->audio[i].audio,
414 priv->audio[i].name);
415 if (priv->audio[i].flags & VIDEO_AUDIO_MUTABLE) {
416 mp_msg(MSGT_TV, MSGL_V, "muted=%s ",
417 (priv->audio[i].flags & VIDEO_AUDIO_MUTE) ? "yes" : "no");
419 mp_msg(MSGT_TV, MSGL_V, "vol=%d bass=%d treble=%d balance=%d mode=%s",
420 priv->audio[i].volume, priv->audio[i].bass, priv->audio[i].treble,
421 priv->audio[i].balance, audio_mode2name(priv->audio[i].mode));
422 mp_msg(MSGT_TV, MSGL_V, " chan=%d\n", priv->audio_channels[i]);
424 if (priv->tv_param->forcechan >= 0)
425 priv->audio_channels[i] = priv->tv_param->forcechan;
427 // we'll call VIDIOCSAUDIO again when starting capture
428 // let's set audio mode to requested mode again for the case
429 // when VIDIOCGAUDIO just cannot report the mode correctly
430 if (reqmode >= 0) priv->audio[i].mode = reqmode;
434 #if !defined(__LINUX_VIDEODEV2_H) && !defined(VIDIOC_QUERYCAP)
435 struct v4l2_capability
437 __u8 driver[16]; /* i.e. "bttv" */
438 __u8 card[32]; /* i.e. "Hauppauge WinTV" */
439 __u8 bus_info[32]; /* "PCI:" + pci_dev->slot_name */
440 __u32 version; /* should use KERNEL_VERSION() */
441 __u32 capabilities; /* Device capabilities */
442 __u32 reserved[4];
445 #define VIDIOC_QUERYCAP _IOR ('V', 0, struct v4l2_capability)
446 #endif
448 static int init(priv_t *priv)
450 int i;
452 if (priv->tv_param->immediate == 1)
453 priv->tv_param->noaudio = 1;
455 priv->video_ringbuffer = NULL;
456 priv->video_timebuffer = NULL;
457 priv->video_avg_buffer = NULL;
458 priv->audio_ringbuffer = NULL;
459 priv->audio_skew_buffer = NULL;
461 priv->video_fd = open(priv->video_device, O_RDWR);
462 mp_msg(MSGT_TV, MSGL_DBG2, "Video fd: %d, %p\n", priv->video_fd,
463 priv->video_device);
464 if (priv->video_fd == -1)
466 mp_msg(MSGT_TV, MSGL_ERR, "unable to open '%s': %s\n",
467 priv->video_device, strerror(errno));
468 goto err;
471 /* check for v4l2 */
472 if (ioctl(priv->video_fd, VIDIOC_QUERYCAP, &priv->capability) == 0) {
473 mp_msg(MSGT_TV, MSGL_ERR, "=================================================================\n");
474 mp_msg(MSGT_TV, MSGL_ERR, " WARNING: YOU ARE USING V4L DEMUXER WITH V4L2 DRIVERS!!!\n");
475 mp_msg(MSGT_TV, MSGL_ERR, " As the V4L1 compatibility layer is broken, this may not work.\n");
476 mp_msg(MSGT_TV, MSGL_ERR, " If you encounter any problems, use driver=v4l2 instead.\n");
477 mp_msg(MSGT_TV, MSGL_ERR, " Bugreports on driver=v4l with v4l2 drivers will be ignored.\n");
478 mp_msg(MSGT_TV, MSGL_ERR, "=================================================================\n");
481 /* get capabilities (priv->capability is needed!) */
482 if (ioctl(priv->video_fd, VIDIOCGCAP, &priv->capability) == -1)
484 mp_msg(MSGT_TV, MSGL_ERR, "ioctl get capabilites failed: %s\n", strerror(errno));
485 goto err;
488 fcntl(priv->video_fd, F_SETFD, FD_CLOEXEC);
490 mp_msg(MSGT_TV, MSGL_INFO, "Selected device: %s\n", priv->capability.name);
491 mp_msg(MSGT_TV, MSGL_INFO, " Capabilites: ");
492 for (i = 0; device_cap2name[i] != NULL; i++)
493 if (priv->capability.type & (1 << i))
494 mp_msg(MSGT_TV, MSGL_INFO, "%s ", device_cap2name[i]);
495 mp_msg(MSGT_TV, MSGL_INFO, "\n");
496 mp_msg(MSGT_TV, MSGL_INFO, " Device type: %d\n", priv->capability.type);
497 mp_msg(MSGT_TV, MSGL_INFO, " Supported sizes: %dx%d => %dx%d\n",
498 priv->capability.minwidth, priv->capability.minheight,
499 priv->capability.maxwidth, priv->capability.maxheight);
500 priv->width = priv->capability.minwidth;
501 priv->height = priv->capability.minheight;
503 /* somewhere here could disable priv->tv_param->mjpeg, if it is not a capability */
505 /* initialize if necessary */
506 if ( priv->tv_param->mjpeg )
508 struct mjpeg_params bparm;
509 struct mjpeg_requestbuffers breq; /* buffer requests */
511 if (ioctl(priv->video_fd, MJPIOC_G_PARAMS, &bparm) < 0)
513 mp_msg(MSGT_TV, MSGL_ERR,
514 " MJP: Error getting video parameters: %s\n", strerror(errno));
515 goto err;
518 mp_msg(MSGT_TV, MSGL_INFO,
519 " MJP: previous params: x: %d, y: %d, w: %d, h: %d, decim: %d, fields: %d,\n",
520 bparm.img_x, bparm.img_y, bparm.img_width, bparm.img_height,
521 bparm.decimation, bparm.field_per_buff);
523 mp_msg(MSGT_TV, MSGL_INFO,
524 " MJP: HorDcm: %d, VerDcm: %d, TmpDcm: %d\n",
525 bparm.HorDcm, bparm.VerDcm, bparm.TmpDcm);
527 bparm.input = priv->tv_param->input; /* tv */
528 if (!strcasecmp(priv->tv_param->norm, "pal"))
529 bparm.norm = 0; /* PAL */
530 else if (!strcasecmp(priv->tv_param->norm, "ntsc"))
531 bparm.norm = 1; /* NTSC */
532 else if (!strcasecmp(priv->tv_param->norm, "secam"))
533 bparm.norm = 2; /* SECAM */
534 bparm.quality = priv->tv_param->quality;
535 bparm.decimation = priv->tv_param->decimation;
537 mp_msg(MSGT_TV, MSGL_INFO, " MJP: setting params to decimation: %d, quality: %d\n",
538 bparm.decimation, bparm.quality);
540 if (ioctl(priv->video_fd, MJPIOC_S_PARAMS, &bparm) < 0)
542 mp_msg(MSGT_TV, MSGL_ERR,
543 " MJP: Error setting video parameters: %s\n", strerror(errno));
544 goto err;
547 if (ioctl(priv->video_fd, MJPIOC_G_PARAMS, &bparm) < 0)
549 mp_msg(MSGT_TV, MSGL_ERR,
550 " MJP: Error getting video parameters: %s\n", strerror(errno));
551 goto err;
554 mp_msg(MSGT_TV, MSGL_INFO,
555 " MJP: current params: x: %d, y: %d, w: %d, h: %d, decim: %d, fields: %d,\n",
556 bparm.img_x, bparm.img_y, bparm.img_width, bparm.img_height,
557 bparm.decimation, bparm.field_per_buff);
559 mp_msg(MSGT_TV, MSGL_INFO,
560 " MJP: HorDcm: %d, VerDcm: %d, TmpDcm: %d\n",
561 bparm.HorDcm, bparm.VerDcm, bparm.TmpDcm);
564 breq.count = 64;
565 priv -> nbuf = breq.count;
566 priv->mbuf.frames = priv -> nbuf;
567 priv->mjpeg_bufsize = 256*1024;
568 if (priv->tv_param->buffer_size >= 0)
569 priv->mjpeg_bufsize = priv->tv_param->buffer_size*1024;
570 breq.size = priv -> mjpeg_bufsize;
571 if (ioctl(priv->video_fd, MJPIOC_REQBUFS,&(breq)) < 0)
573 mp_msg (MSGT_TV, MSGL_ERR,
574 " MJP: Error requesting video buffers: %s\n", strerror(errno));
575 goto err;
577 mp_msg(MSGT_TV, MSGL_INFO,
578 " MJP: Got %ld buffers of size %ld KB\n",
579 breq.count, breq.size/1024);
581 priv -> mmap = mmap(0, breq.count * breq.size,
582 PROT_READ|PROT_WRITE, MAP_SHARED, priv->video_fd, 0);
583 if (priv -> mmap == MAP_FAILED)
585 mp_msg(MSGT_TV, MSGL_INFO,
586 " MJP: Error mapping video buffers: %s\n", strerror(errno));
587 goto err;
591 mp_msg(MSGT_TV, MSGL_INFO, " Inputs: %d\n", priv->capability.channels);
592 priv->channels = calloc(priv->capability.channels, sizeof(struct video_channel));
593 if (!priv->channels)
594 goto malloc_failed;
595 memset(priv->channels, 0, sizeof(struct video_channel)*priv->capability.channels);
596 for (i = 0; i < priv->capability.channels; i++)
598 priv->channels[i].channel = i;
599 if (ioctl(priv->video_fd, VIDIOCGCHAN, &priv->channels[i]) == -1)
601 mp_msg(MSGT_TV, MSGL_ERR, "ioctl get channel failed: %s\n", strerror(errno));
602 break;
604 mp_msg(MSGT_TV, MSGL_INFO, " %d: %s: %s%s%s%s (tuner:%d, norm:%s)\n", i,
605 priv->channels[i].name,
606 (priv->channels[i].flags & VIDEO_VC_TUNER) ? "tuner " : "",
607 (priv->channels[i].flags & VIDEO_VC_AUDIO) ? "audio " : "",
608 (priv->channels[i].flags & VIDEO_TYPE_TV) ? "tv " : "",
609 (priv->channels[i].flags & VIDEO_TYPE_CAMERA) ? "camera " : "",
610 priv->channels[i].tuners,
611 norm2name(priv->channels[i].norm));
613 priv->act_channel = 0;
615 if (!(priv->capability.type & VID_TYPE_CAPTURE))
617 mp_msg(MSGT_TV, MSGL_ERR, "Only grabbing supported (for overlay use another program)\n");
618 goto err;
622 /* init v4l audio even when we don't capture */
623 init_v4l_audio(priv);
625 if (!priv->capability.audios && !priv->tv_param->force_audio) priv->tv_param->noaudio = 1;
627 /* audio init */
628 if (!priv->tv_param->noaudio) {
630 #ifdef CONFIG_ALSA
631 if (priv->tv_param->alsa)
632 audio_in_init(&priv->audio_in, AUDIO_IN_ALSA);
633 else
634 audio_in_init(&priv->audio_in, AUDIO_IN_OSS);
635 #else
636 audio_in_init(&priv->audio_in, AUDIO_IN_OSS);
637 #endif
639 if (priv->audio_device) {
640 audio_in_set_device(&priv->audio_in, priv->audio_device);
643 if (priv->tv_param->audio_id < priv->capability.audios)
644 priv->audio_id = priv->tv_param->audio_id;
645 else
646 priv->audio_id = 0;
647 audio_in_set_samplerate(&priv->audio_in, 44100);
648 if (priv->capability.audios) {
649 audio_in_set_channels(&priv->audio_in, priv->audio_channels[priv->audio_id]);
650 } else {
651 if (priv->tv_param->forcechan >= 0) {
652 audio_in_set_channels(&priv->audio_in, priv->tv_param->forcechan);
653 } else {
654 audio_in_set_channels(&priv->audio_in, 2);
657 if (audio_in_setup(&priv->audio_in) < 0) return 0;
658 setup_audio_buffer_sizes(priv);
661 return 1;
663 malloc_failed:
664 if (priv->channels)
665 free(priv->channels);
666 if (priv->buf)
667 free(priv->buf);
668 err:
669 if (priv->video_fd != -1)
670 close(priv->video_fd);
671 return 0;
674 static int uninit(priv_t *priv)
676 unsigned long num;
678 #ifdef CONFIG_TV_TELETEXT
679 priv->vbi_shutdown=1;
680 if(priv->vbi_grabber_thread)
681 pthread_join(priv->vbi_grabber_thread, NULL);
683 teletext_control(priv->priv_vbi,TV_VBI_CONTROL_STOP,(void*)1);
684 priv->priv_vbi=NULL;
686 if(priv->vbi_fd){
687 close(priv->vbi_fd);
688 priv->vbi_fd=0;
691 if(priv->vbi_dev){
692 free(priv->vbi_dev);
693 priv->vbi_dev=0;
696 #endif
698 priv->shutdown = 1;
700 mp_msg(MSGT_TV, MSGL_V, "Waiting for threads to finish... ");
701 if (!priv->tv_param->noaudio) {
702 pthread_join(priv->audio_grabber_thread, NULL);
703 pthread_mutex_destroy(&priv->audio_starter);
704 pthread_mutex_destroy(&priv->skew_mutex);
706 pthread_mutex_destroy(&priv->video_buffer_mutex);
707 if(priv->video_grabber_thread)
708 pthread_join(priv->video_grabber_thread, NULL);
710 mp_msg(MSGT_TV, MSGL_V, "done\n");
712 if (priv->capability.audios) {
713 priv->audio[priv->audio_id].flags |= VIDEO_AUDIO_MUTE;
714 ioctl(priv->video_fd, VIDIOCSAUDIO, &priv->audio[priv->audio_id]);
717 if ( priv->tv_param->mjpeg )
719 num = -1;
720 if (ioctl(priv->video_fd, MJPIOC_QBUF_CAPT, &num) < 0)
721 mp_msg(MSGT_TV, MSGL_ERR, "\n MJP: ioctl MJPIOC_QBUF_CAPT failed: %s\n", strerror(errno));
723 else
725 // We need to munmap as close don't close mem mappings
726 if(munmap(priv->mmap,priv->mbuf.size))
727 mp_msg(MSGT_TV, MSGL_ERR, "Munmap failed: %s\n",strerror(errno));
730 if(close(priv->video_fd))
731 mp_msg(MSGT_TV, MSGL_ERR, "Close tv failed: %s\n",strerror(errno));
733 audio_in_uninit(&priv->audio_in);
735 if (priv->video_ringbuffer) {
736 int i;
737 for (i = 0; i < priv->video_buffer_size_current; i++) {
738 free(priv->video_ringbuffer[i]);
740 free(priv->video_ringbuffer);
743 if (priv->video_timebuffer)
744 free(priv->video_timebuffer);
745 if (priv->video_avg_buffer)
746 free(priv->video_avg_buffer);
747 if (!priv->tv_param->noaudio) {
748 if (priv->audio_ringbuffer)
749 free(priv->audio_ringbuffer);
750 if (priv->audio_skew_buffer)
751 free(priv->audio_skew_buffer);
754 return 1;
757 static int get_capture_buffer_size(priv_t *priv)
759 int bufsize, cnt;
761 if (priv->tv_param->buffer_size >= 0) {
762 bufsize = priv->tv_param->buffer_size*1024*1024;
763 } else {
764 #ifdef HAVE_SYS_SYSINFO_H
765 struct sysinfo si;
767 sysinfo(&si);
768 if (si.totalram<2*1024*1024) {
769 bufsize = 1024*1024;
770 } else {
771 bufsize = si.totalram/2;
773 #else
774 bufsize = 16*1024*1024;
775 #endif
778 cnt = bufsize/(priv->height*priv->bytesperline);
779 if (cnt < 2) cnt = 2;
781 return cnt;
784 #ifdef CONFIG_TV_TELETEXT
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 capatibilities 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;
900 #endif /* CONFIG_TV_TELETEXT */
902 static int start(priv_t *priv)
904 int i;
905 int bytes_per_sample;
906 struct video_window win;
908 if (ioctl(priv->video_fd, VIDIOCGPICT, &priv->picture) == -1)
910 mp_msg(MSGT_TV, MSGL_ERR, "ioctl get picture failed: %s\n", strerror(errno));
911 return 0;
914 priv->picture.palette = format2palette(priv->format);
915 priv->picture.depth = palette2depth(priv->picture.palette);
917 if (priv->format != IMGFMT_BGR15) {
918 priv->bytesperline = priv->width * priv->picture.depth / 8;
919 } else {
920 priv->bytesperline = priv->width * 2;
923 mp_msg(MSGT_TV, MSGL_V, "Picture values:\n");
924 mp_msg(MSGT_TV, MSGL_V, " Depth: %d, Palette: %s (Format: %s)\n", priv->picture.depth,
925 PALETTE(priv->picture.palette), vo_format_name(priv->format));
926 mp_msg(MSGT_TV, MSGL_V, " Brightness: %d, Hue: %d, Colour: %d, Contrast: %d\n",
927 priv->picture.brightness, priv->picture.hue,
928 priv->picture.colour, priv->picture.contrast);
930 if (ioctl(priv->video_fd, VIDIOCSPICT, &priv->picture) == -1)
932 mp_msg(MSGT_TV, MSGL_ERR, "ioctl set picture failed: %s\n", strerror(errno));
933 mp_msg(MSGT_TV, MSGL_ERR, "The 'outfmt' of '%s' is likely not supported by your card\n",
934 vo_format_name(priv->format));
935 return 0;
938 /* Set capture size */
939 win.x = 0;
940 win.y = 0;
941 win.width = priv->width;
942 win.height = priv->height;
943 win.chromakey = -1;
944 win.flags = 0;
945 win.clipcount = 0;
946 if (ioctl(priv->video_fd, VIDIOCSWIN, &win) == -1)
947 mp_msg(MSGT_TV, MSGL_ERR, "ioctl set window failed: %s\n", strerror(errno));
949 if ( !priv->tv_param->mjpeg )
951 /* map grab buffer */
952 if (ioctl(priv->video_fd, VIDIOCGMBUF, &priv->mbuf) == -1)
954 mp_msg(MSGT_TV, MSGL_ERR, "ioctl get mbuf failed: %s\n", strerror(errno));
955 return 0;
958 mp_msg(MSGT_TV, MSGL_V, "mbuf: size=%d, frames=%d\n",
959 priv->mbuf.size, priv->mbuf.frames);
960 priv->mmap = mmap(0, priv->mbuf.size, PROT_READ|PROT_WRITE,
961 MAP_SHARED, priv->video_fd, 0);
962 if (priv->mmap == (unsigned char *)-1)
964 mp_msg(MSGT_TV, MSGL_ERR, "Unable to map memory for buffers: %s\n", strerror(errno));
965 return 0;
967 mp_msg(MSGT_TV, MSGL_DBG2, "our buffer: %p\n", priv->mmap);
969 /* num of buffers */
970 priv->nbuf = priv->mbuf.frames;
972 /* video buffers */
973 priv->buf = calloc(priv->nbuf, sizeof(struct video_mmap));
974 if (!priv->buf)
975 return 0;
976 memset(priv->buf, 0, priv->nbuf * sizeof(struct video_mmap));
979 if ( !priv->tv_param->mjpeg )
981 priv->nbuf = priv->mbuf.frames;
982 for (i=0; i < priv->nbuf; i++)
984 priv->buf[i].format = priv->picture.palette;
985 priv->buf[i].frame = i;
986 priv->buf[i].width = priv->width;
987 priv->buf[i].height = priv->height;
988 mp_msg(MSGT_TV, MSGL_DBG2, "buffer: %d => %p\n", i, &priv->buf[i]);
992 #if 0
994 struct video_play_mode pmode;
996 pmode.mode = VID_PLAY_NORMAL;
997 pmode.p1 = 1;
998 pmode.p2 = 0;
999 if (ioctl(priv->video_fd, VIDIOCSPLAYMODE, &pmode) == -1)
1001 mp_msg(MSGT_TV, MSGL_ERR, "ioctl set play mode failed: %s\n", strerror(errno));
1002 // return 0;
1005 #endif
1007 #if 0
1008 // initialize video capture
1009 if (ioctl(priv->video_fd, VIDIOCCAPTURE, &one) == -1)
1011 mp_msg(MSGT_TV, MSGL_ERR, "FATAL: ioctl ccapture failed: %s\n", strerror(errno));
1012 return 0;
1014 #endif
1016 /* setup audio parameters */
1017 if (!priv->tv_param->noaudio) {
1018 setup_audio_buffer_sizes(priv);
1019 bytes_per_sample = priv->audio_in.bytes_per_sample;
1020 priv->audio_skew_buffer = calloc(priv->aud_skew_cnt, sizeof(long long));
1021 if (!priv->audio_skew_buffer) {
1022 mp_msg(MSGT_TV, MSGL_ERR, "cannot allocate skew buffer: %s\n", strerror(errno));
1023 return 0;
1026 priv->audio_ringbuffer = calloc(priv->audio_in.blocksize, priv->audio_buffer_size);
1027 if (!priv->audio_ringbuffer) {
1028 mp_msg(MSGT_TV, MSGL_ERR, "cannot allocate audio buffer: %s\n", strerror(errno));
1029 return 0;
1032 priv->audio_secs_per_block = (double)priv->audio_in.blocksize/(priv->audio_in.samplerate
1033 *priv->audio_in.channels
1034 *bytes_per_sample);
1035 priv->audio_head = 0;
1036 priv->audio_tail = 0;
1037 priv->audio_cnt = 0;
1038 priv->audio_drop = 0;
1039 priv->audio_skew = 0;
1040 priv->audio_skew_total = 0;
1041 priv->audio_recv_blocks_total = 0;
1042 priv->audio_sent_blocks_total = 0;
1045 /* setup video parameters */
1046 if (priv->immediate_mode) {
1047 priv->video_buffer_size_max = VID_BUF_SIZE_IMMEDIATE;
1048 } else {
1049 priv->video_buffer_size_max = get_capture_buffer_size(priv);
1051 priv->video_buffer_size_current = 0;
1053 if (!priv->tv_param->noaudio) {
1054 if (priv->video_buffer_size_max < 3.0*priv->fps*priv->audio_secs_per_block) {
1055 mp_msg(MSGT_TV, MSGL_ERR, "Video buffer shorter than 3 times audio frame duration.\n"
1056 "You will probably experience heavy framedrops.\n");
1060 mp_msg(MSGT_TV, MSGL_V, "Using a ring buffer for maximum %d frames, %d MB total size.\n",
1061 priv->video_buffer_size_max,
1062 priv->video_buffer_size_max*priv->height*priv->bytesperline/(1024*1024));
1064 priv->video_ringbuffer = calloc(priv->video_buffer_size_max, sizeof(unsigned char*));
1065 if (!priv->video_ringbuffer) {
1066 mp_msg(MSGT_TV, MSGL_ERR, "cannot allocate video buffer: %s\n", strerror(errno));
1067 return 0;
1069 for (i = 0; i < priv->video_buffer_size_max; i++)
1070 priv->video_ringbuffer[i] = NULL;
1072 priv->video_timebuffer = calloc(priv->video_buffer_size_max, sizeof(long long));
1073 if (!priv->video_timebuffer) {
1074 mp_msg(MSGT_TV, MSGL_ERR, "cannot allocate time buffer: %s\n", strerror(errno));
1075 return 0;
1077 priv->video_avg_buffer = malloc(sizeof(long long) * VIDEO_AVG_BUFFER_SIZE);
1078 if (!priv->video_avg_buffer) {
1079 mp_msg(MSGT_TV, MSGL_ERR, "cannot allocate period buffer: %s\n", strerror(errno));
1080 return 0;
1082 priv->video_interval_sum = (1e6/priv->fps)*VIDEO_AVG_BUFFER_SIZE;
1083 for (i = 0; i < VIDEO_AVG_BUFFER_SIZE; i++) {
1084 priv->video_avg_buffer[i] = 1e6/priv->fps;
1087 priv->video_avg_ptr = 0;
1089 priv->video_head = 0;
1090 priv->video_tail = 0;
1091 priv->video_cnt = 0;
1092 priv->first = 1;
1094 if (priv->capability.audios) {
1095 /* enable audio */
1096 if (priv->tv_param->volume >= 0)
1097 priv->audio[priv->audio_id].volume = priv->tv_param->volume;
1098 if (priv->tv_param->bass >= 0)
1099 priv->audio[priv->audio_id].bass = priv->tv_param->bass;
1100 if (priv->tv_param->treble >= 0)
1101 priv->audio[priv->audio_id].treble = priv->tv_param->treble;
1102 if (priv->tv_param->balance >= 0)
1103 priv->audio[priv->audio_id].balance = priv->tv_param->balance;
1104 priv->audio[priv->audio_id].flags &= ~VIDEO_AUDIO_MUTE;
1105 mp_msg(MSGT_TV, MSGL_V, "Enabling tv audio. Requested setup is:\n");
1106 mp_msg(MSGT_TV, MSGL_V, "id=%d vol=%d bass=%d treble=%d balance=%d mode=%s",
1107 priv->audio_id,
1108 priv->audio[priv->audio_id].volume, priv->audio[priv->audio_id].bass, priv->audio[priv->audio_id].treble,
1109 priv->audio[priv->audio_id].balance, audio_mode2name(priv->audio[priv->audio_id].mode));
1110 mp_msg(MSGT_TV, MSGL_V, " chan=%d\n", priv->audio_channels[priv->audio_id]);
1111 ioctl(priv->video_fd, VIDIOCSAUDIO, &priv->audio[priv->audio_id]);
1114 #ifdef CONFIG_TV_TELETEXT
1115 /* start vbi thread */
1116 if(priv->priv_vbi){
1117 priv->vbi_shutdown = 0;
1118 pthread_create(&priv->vbi_grabber_thread, NULL, vbi_grabber, priv);
1120 #endif
1122 /* launch capture threads */
1123 priv->shutdown = 0;
1124 if (!priv->tv_param->noaudio) {
1125 pthread_mutex_init(&priv->audio_starter, NULL);
1126 pthread_mutex_init(&priv->skew_mutex, NULL);
1127 pthread_mutex_lock(&priv->audio_starter);
1128 pthread_create(&priv->audio_grabber_thread, NULL, audio_grabber, priv);
1130 pthread_mutex_init(&priv->video_buffer_mutex, NULL);
1131 /* we'll launch the video capture later, when a first request for a frame arrives */
1133 return 1;
1137 static int control(priv_t *priv, int cmd, void *arg)
1139 mp_msg(MSGT_TV, MSGL_DBG2, "\ndebug: control(priv=%p, cmd=%d, arg=%p)\n",
1140 priv, cmd, arg);
1141 switch(cmd)
1143 /* ========== GENERIC controls =========== */
1144 case TVI_CONTROL_IS_VIDEO:
1146 if (priv->capability.type & VID_TYPE_CAPTURE)
1147 return TVI_CONTROL_TRUE;
1148 return TVI_CONTROL_FALSE;
1150 case TVI_CONTROL_IS_AUDIO:
1151 if (priv->tv_param->force_audio) return TVI_CONTROL_TRUE;
1152 if (priv->channels[priv->act_channel].flags & VIDEO_VC_AUDIO)
1154 return TVI_CONTROL_TRUE;
1156 return TVI_CONTROL_FALSE;
1157 case TVI_CONTROL_IS_TUNER:
1159 // if (priv->capability.type & VID_TYPE_TUNER)
1160 if (priv->channels[priv->act_channel].flags & VIDEO_VC_TUNER)
1161 return TVI_CONTROL_TRUE;
1162 return TVI_CONTROL_FALSE;
1165 /* ========== VIDEO controls =========== */
1166 case TVI_CONTROL_VID_GET_FORMAT:
1168 int output_fmt = -1;
1170 output_fmt = priv->format;
1171 if ( priv->tv_param->mjpeg )
1173 mp_msg(MSGT_TV, MSGL_INFO, " MJP: setting sh_video->format to mjpg\n");
1174 output_fmt = 0x47504a4d;
1175 output_fmt = 0x67706a6d;
1176 *(int *)arg = output_fmt;
1177 mp_msg(MSGT_TV, MSGL_V, "Output format: %s\n", "mjpg");
1179 else
1181 *(int *)arg = output_fmt;
1182 mp_msg(MSGT_TV, MSGL_V, "Output format: %s\n", vo_format_name(output_fmt));
1184 return TVI_CONTROL_TRUE;
1186 case TVI_CONTROL_VID_SET_FORMAT:
1187 priv->format = *(int *)arg;
1188 // !HACK! v4l uses BGR format instead of RGB
1189 // and we have to correct this. Fortunately,
1190 // tv.c reads later the format back so we
1191 // can persuade it to use what we want.
1192 if (IMGFMT_IS_RGB(priv->format)) {
1193 priv->format &= ~IMGFMT_RGB_MASK;
1194 priv->format |= IMGFMT_BGR;
1196 return TVI_CONTROL_TRUE;
1197 case TVI_CONTROL_VID_GET_PLANES:
1198 *(int *)arg = 1; /* FIXME, also not needed at this time */
1199 return TVI_CONTROL_TRUE;
1200 case TVI_CONTROL_VID_GET_BITS:
1201 *(int *)arg = palette2depth(format2palette(priv->format));
1202 return TVI_CONTROL_TRUE;
1203 case TVI_CONTROL_VID_GET_WIDTH:
1204 *(int *)arg = priv->width;
1205 return TVI_CONTROL_TRUE;
1206 case TVI_CONTROL_VID_CHK_WIDTH:
1208 int req_width = *(int *)arg;
1210 mp_msg(MSGT_TV, MSGL_V, "Requested width: %d\n", req_width);
1211 if ((req_width >= priv->capability.minwidth) &&
1212 (req_width <= priv->capability.maxwidth))
1213 return TVI_CONTROL_TRUE;
1214 return TVI_CONTROL_FALSE;
1216 case TVI_CONTROL_VID_SET_WIDTH:
1217 priv->width = *(int *)arg;
1218 return TVI_CONTROL_TRUE;
1219 case TVI_CONTROL_VID_GET_HEIGHT:
1220 *(int *)arg = priv->height;
1221 return TVI_CONTROL_TRUE;
1222 case TVI_CONTROL_VID_CHK_HEIGHT:
1224 int req_height = *(int *)arg;
1226 mp_msg(MSGT_TV, MSGL_V, "Requested height: %d\n", req_height);
1227 if ((req_height >= priv->capability.minheight) &&
1228 (req_height <= priv->capability.maxheight))
1229 return TVI_CONTROL_TRUE;
1230 return TVI_CONTROL_FALSE;
1232 case TVI_CONTROL_VID_SET_HEIGHT:
1233 priv->height = *(int *)arg;
1234 return TVI_CONTROL_TRUE;
1235 case TVI_CONTROL_VID_GET_PICTURE:
1236 if (ioctl(priv->video_fd, VIDIOCGPICT, &priv->picture) == -1)
1238 mp_msg(MSGT_TV, MSGL_ERR, "ioctl get picture failed: %s\n", strerror(errno));
1239 return TVI_CONTROL_FALSE;
1241 return TVI_CONTROL_TRUE;
1242 case TVI_CONTROL_VID_SET_PICTURE:
1243 if (ioctl(priv->video_fd, VIDIOCSPICT, &priv->picture) == -1)
1245 mp_msg(MSGT_TV, MSGL_ERR, "ioctl set picture failed: %s\n", strerror(errno));
1246 return TVI_CONTROL_FALSE;
1248 return TVI_CONTROL_TRUE;
1249 case TVI_CONTROL_VID_SET_BRIGHTNESS:
1250 priv->picture.brightness = (327*(*(int *)arg+100)) + 68;
1251 return control(priv, TVI_CONTROL_VID_SET_PICTURE, 0);
1252 case TVI_CONTROL_VID_SET_HUE:
1253 priv->picture.hue = (327*(*(int *)arg+100)) + 68;
1254 return control(priv, TVI_CONTROL_VID_SET_PICTURE, 0);
1255 case TVI_CONTROL_VID_SET_SATURATION:
1256 priv->picture.colour = (327*(*(int *)arg+100)) + 68;
1257 return control(priv, TVI_CONTROL_VID_SET_PICTURE, 0);
1258 case TVI_CONTROL_VID_SET_CONTRAST:
1259 priv->picture.contrast = (327*(*(int *)arg+100)) + 68;
1260 return control(priv, TVI_CONTROL_VID_SET_PICTURE, 0);
1261 case TVI_CONTROL_VID_GET_BRIGHTNESS:
1262 if(!control(priv, TVI_CONTROL_VID_GET_PICTURE, 0)) return 0;
1263 *(int*)arg = ((int)priv->picture.brightness-68)/327-100;
1264 return 1;
1265 case TVI_CONTROL_VID_GET_HUE:
1266 if(!control(priv, TVI_CONTROL_VID_GET_PICTURE, 0)) return 0;
1267 *(int*)arg = ((int)priv->picture.hue-68)/327-100;
1268 return 1;
1269 case TVI_CONTROL_VID_GET_SATURATION:
1270 if(!control(priv, TVI_CONTROL_VID_GET_PICTURE, 0)) return 0;
1271 *(int*)arg = ((int)priv->picture.colour-68)/327-100;
1272 return 1;
1273 case TVI_CONTROL_VID_GET_CONTRAST:
1274 if(!control(priv, TVI_CONTROL_VID_GET_PICTURE, 0)) return 0;
1275 *(int*)arg = ((int)priv->picture.contrast-68)/327-100;
1276 return 1;
1277 case TVI_CONTROL_VID_GET_FPS:
1278 *(float *)arg=priv->fps;
1279 return TVI_CONTROL_TRUE;
1281 /* ========== TUNER controls =========== */
1282 case TVI_CONTROL_TUN_GET_FREQ:
1284 unsigned long freq;
1286 if (ioctl(priv->video_fd, VIDIOCGFREQ, &freq) == -1)
1288 mp_msg(MSGT_TV, MSGL_ERR, "ioctl get freq failed: %s\n", strerror(errno));
1289 return TVI_CONTROL_FALSE;
1292 /* tuner uses khz not mhz ! */
1293 // if (priv->tuner.flags & VIDEO_TUNER_LOW)
1294 // freq /= 1000;
1295 *(unsigned long *)arg = freq;
1296 return TVI_CONTROL_TRUE;
1298 case TVI_CONTROL_TUN_SET_FREQ:
1300 /* argument is in MHz ! */
1301 unsigned long freq = *(unsigned long *)arg;
1303 if (priv->capability.audios) {
1304 priv->audio[priv->audio_id].flags |= VIDEO_AUDIO_MUTE;
1305 ioctl(priv->video_fd, VIDIOCSAUDIO, &priv->audio[priv->audio_id]);
1308 mp_msg(MSGT_TV, MSGL_V, "requested frequency: %.3f\n", (float)freq/16);
1310 /* tuner uses khz not mhz ! */
1311 // if (priv->tuner.flags & VIDEO_TUNER_LOW)
1312 // freq *= 1000;
1313 // mp_msg(MSGT_TV, MSGL_V, " requesting from driver: freq=%.3f\n", (float)freq/16);
1314 if (ioctl(priv->video_fd, VIDIOCSFREQ, &freq) == -1)
1316 mp_msg(MSGT_TV, MSGL_ERR, "ioctl set freq failed: %s\n", strerror(errno));
1317 return TVI_CONTROL_FALSE;
1319 usleep(100000); // wait to suppress noise during switching
1321 if (priv->capability.audios) {
1322 priv->audio[priv->audio_id].flags &= ~VIDEO_AUDIO_MUTE;
1323 ioctl(priv->video_fd, VIDIOCSAUDIO, &priv->audio[priv->audio_id]);
1326 return TVI_CONTROL_TRUE;
1328 case TVI_CONTROL_TUN_GET_TUNER:
1330 if (ioctl(priv->video_fd, VIDIOCGTUNER, &priv->tuner) == -1)
1332 mp_msg(MSGT_TV, MSGL_ERR, "ioctl get tuner failed: %s\n", strerror(errno));
1333 return TVI_CONTROL_FALSE;
1336 mp_msg(MSGT_TV, MSGL_V, "Tuner (%s) range: %lu -> %lu\n", priv->tuner.name,
1337 priv->tuner.rangelow, priv->tuner.rangehigh);
1338 return TVI_CONTROL_TRUE;
1340 case TVI_CONTROL_TUN_SET_TUNER:
1342 if (ioctl(priv->video_fd, VIDIOCSTUNER, &priv->tuner) == -1)
1344 mp_msg(MSGT_TV, MSGL_ERR, "ioctl set tuner failed: %s\n", strerror(errno));
1345 return TVI_CONTROL_FALSE;
1347 return TVI_CONTROL_TRUE;
1349 case TVI_CONTROL_TUN_SET_NORM:
1351 int req_mode = *(int *)arg;
1352 int norm_index;
1353 for(norm_index=0;supported_norms[norm_index].name; norm_index++)
1354 if(req_mode==supported_norms[norm_index].normid)
1355 break;
1357 if(!supported_norms[norm_index].name) {
1358 mp_msg(MSGT_TV, MSGL_ERR, "Unknown norm!\n");
1359 return TVI_CONTROL_FALSE;
1362 if (priv->channels[priv->act_channel].flags & VIDEO_VC_TUNER) {
1363 int prev_mode;
1365 control(priv, TVI_CONTROL_TUN_GET_TUNER, 0);
1366 if(!(priv->tuner.flags & supported_norms[norm_index].tuner_flags))
1368 mp_msg(MSGT_TV, MSGL_ERR, "Tuner isn't capable to set norm!\n");
1369 return TVI_CONTROL_FALSE;
1372 prev_mode = priv->tuner.mode;
1374 priv->tuner.mode = supported_norms[norm_index].tuner_mode;
1376 if (control(priv, TVI_CONTROL_TUN_SET_TUNER, &priv->tuner) != TVI_CONTROL_TRUE) {
1377 // norm setting failed, but maybe it's only because it's fixed
1378 if (priv->tuner.mode != prev_mode) return TVI_CONTROL_FALSE; // no it really failed
1383 priv->channels[priv->act_channel].norm = supported_norms[norm_index].input_norm;
1385 if (ioctl(priv->video_fd, VIDIOCSCHAN, &priv->channels[priv->act_channel]) == -1)
1387 mp_msg(MSGT_TV, MSGL_ERR, "ioctl set chan failed: %s\n", strerror(errno));
1388 return TVI_CONTROL_FALSE;
1391 if (ioctl(priv->video_fd, VIDIOCGCAP, &priv->capability) == -1) {
1392 mp_msg(MSGT_TV, MSGL_ERR, "ioctl get capabilites failed: %s\n", strerror(errno));
1393 return TVI_CONTROL_FALSE;
1396 priv->fps = supported_norms[norm_index].fps;
1398 if(priv->height > priv->capability.maxheight) {
1399 priv->height = priv->capability.maxheight;
1402 if(priv->width > priv->capability.maxwidth) {
1403 priv->width = priv->capability.maxwidth;
1406 return TVI_CONTROL_TRUE;
1408 case TVI_CONTROL_TUN_GET_NORM:
1410 *(int *)arg = priv->tuner.mode;
1412 return TVI_CONTROL_TRUE;
1414 case TVI_CONTROL_TUN_GET_SIGNAL:
1416 if (ioctl(priv->video_fd, VIDIOCGTUNER, &priv->tuner) == -1)
1418 mp_msg(MSGT_TV, MSGL_ERR, "ioctl get tuner failed: %s\n", strerror(errno));
1419 return TVI_CONTROL_FALSE;
1421 *(int*)arg=100*(priv->tuner.signal>>8)/255;
1422 return TVI_CONTROL_TRUE;
1425 /* ========== AUDIO controls =========== */
1426 case TVI_CONTROL_AUD_GET_FORMAT:
1428 *(int *)arg = AF_FORMAT_S16_LE;
1429 return TVI_CONTROL_TRUE;
1431 case TVI_CONTROL_AUD_GET_CHANNELS:
1433 *(int *)arg = priv->audio_in.channels;
1434 return TVI_CONTROL_TRUE;
1436 case TVI_CONTROL_AUD_GET_SAMPLERATE:
1438 *(int *)arg = priv->audio_in.samplerate;
1439 return TVI_CONTROL_TRUE;
1441 case TVI_CONTROL_AUD_GET_SAMPLESIZE:
1443 *(int *)arg = priv->audio_in.bytes_per_sample;
1444 return TVI_CONTROL_TRUE;
1446 case TVI_CONTROL_AUD_SET_SAMPLERATE:
1448 if (audio_in_set_samplerate(&priv->audio_in, *(int *)arg) < 0) return TVI_CONTROL_FALSE;
1449 setup_audio_buffer_sizes(priv);
1450 return TVI_CONTROL_TRUE;
1452 /* ========== SPECIFIC controls =========== */
1453 case TVI_CONTROL_SPC_GET_INPUT:
1455 int req_chan = *(int *)arg;
1456 int i;
1458 for (i = 0; i < priv->capability.channels; i++)
1460 if (priv->channels[i].channel == req_chan)
1461 break;
1464 priv->act_channel = i;
1466 if (ioctl(priv->video_fd, VIDIOCGCHAN, &priv->channels[i]) == -1)
1468 mp_msg(MSGT_TV, MSGL_ERR, "ioctl get channel failed: %s\n", strerror(errno));
1469 return TVI_CONTROL_FALSE;
1471 return TVI_CONTROL_TRUE;
1474 case TVI_CONTROL_SPC_SET_INPUT:
1476 struct video_channel chan;
1477 int req_chan = *(int *)arg;
1478 int i;
1480 if (req_chan >= priv->capability.channels)
1482 mp_msg(MSGT_TV, MSGL_ERR, "Invalid input requested: %d, valid: 0-%d\n",
1483 req_chan, priv->capability.channels - 1);
1484 return TVI_CONTROL_FALSE;
1487 for (i = 0; i < priv->capability.channels; i++)
1489 if (priv->channels[i].channel == req_chan)
1490 chan = priv->channels[i];
1493 if (ioctl(priv->video_fd, VIDIOCSCHAN, &chan) == -1)
1495 mp_msg(MSGT_TV, MSGL_ERR, "ioctl set chan failed: %s\n", strerror(errno));
1496 return TVI_CONTROL_FALSE;
1498 mp_msg(MSGT_TV, MSGL_INFO, "Using input '%s'\n", chan.name);
1500 priv->act_channel = i;
1502 /* update tuner state */
1503 // if (priv->capability.type & VID_TYPE_TUNER)
1504 if (priv->channels[priv->act_channel].flags & VIDEO_VC_TUNER)
1505 control(priv, TVI_CONTROL_TUN_GET_TUNER, 0);
1507 /* update local channel list */
1508 control(priv, TVI_CONTROL_SPC_GET_INPUT, &req_chan);
1509 return TVI_CONTROL_TRUE;
1510 case TVI_CONTROL_IMMEDIATE:
1511 priv->immediate_mode = 1;
1512 return TVI_CONTROL_TRUE;
1514 #ifdef CONFIG_TV_TELETEXT
1515 case TVI_CONTROL_VBI_INIT:
1517 void* ptr;
1518 tt_stream_props tsp;
1520 if (vbi_init(priv,*(char**)arg)!=TVI_CONTROL_TRUE)
1521 return TVI_CONTROL_FALSE;
1522 if(vbi_get_props(priv,&tsp)==TVI_CONTROL_TRUE)
1524 ptr=&tsp;
1525 if(teletext_control(NULL,TV_VBI_CONTROL_START,&ptr)==TVI_CONTROL_TRUE)
1526 priv->priv_vbi=ptr;
1527 else
1528 priv->priv_vbi=NULL;
1530 return TVI_CONTROL_TRUE;
1532 default:
1533 return teletext_control(priv->priv_vbi,cmd,arg);
1534 #endif
1537 return TVI_CONTROL_UNKNOWN;
1540 static int set_mute(priv_t* priv,int value)
1542 if (!priv->capability.audios) {
1543 return 0;
1545 if(value)
1546 priv->audio[priv->audio_id].flags |=VIDEO_AUDIO_MUTE;
1547 else
1548 priv->audio[priv->audio_id].flags &= ~VIDEO_AUDIO_MUTE;
1550 if(ioctl(priv->video_fd, VIDIOCSAUDIO, &priv->audio[priv->audio_id])<0)
1551 return 0;
1552 return 1;
1555 // copies a video frame
1556 // for YV12 swaps the 2nd and 3rd plane
1557 static inline void copy_frame(priv_t *priv, unsigned char *dest, unsigned char *source)
1559 if(priv->tv_param->automute>0){
1560 if (ioctl(priv->video_fd, VIDIOCGTUNER, &priv->tuner) >= 0) {
1561 if(priv->tv_param->automute<<8>priv->tuner.signal){
1562 fill_blank_frame(dest,priv->bytesperline * priv->height,priv->format);
1563 set_mute(priv,1);
1564 return;
1567 set_mute(priv,0);
1569 // YV12 uses VIDEO_PALETTE_YUV420P, but the planes are swapped
1570 if (priv->format == IMGFMT_YV12) {
1571 fast_memcpy(dest, source, priv->width * priv->height);
1572 fast_memcpy(dest+priv->width * priv->height*5/4, source+priv->width * priv->height, priv->width * priv->height/4);
1573 fast_memcpy(dest+priv->width * priv->height, source+priv->width * priv->height*5/4, priv->width * priv->height/4);
1574 return;
1577 fast_memcpy(dest, source, priv->bytesperline * priv->height);
1580 // maximum skew change, in frames
1581 #define MAX_SKEW_DELTA 0.6
1582 static void *video_grabber(void *data)
1584 #define MAXTOL (priv->nbuf)
1585 priv_t *priv = (priv_t*)data;
1586 struct timeval curtime;
1587 long long skew, prev_skew, xskew, interval, prev_interval;
1588 int frame;
1589 int i;
1590 int framecount;
1591 int tolerance;
1592 unsigned long num;
1594 /* start the capture process */
1596 if ( priv->tv_param->mjpeg )
1598 mp_msg(MSGT_TV, MSGL_INFO, " MJP: gonna capture ! \n");
1599 for (i=0; i < priv->nbuf; i++) {
1600 num = i;
1601 if (ioctl(priv->video_fd, MJPIOC_QBUF_CAPT, &num) < 0)
1602 mp_msg(MSGT_TV, MSGL_ERR,
1603 "\n MJP: ioctl MJPIOC_QBUF_CAPT b failed: %s\n", strerror(errno));
1606 else
1608 for (i=0; i < priv->nbuf; i++) {
1609 if (ioctl(priv->video_fd, VIDIOCMCAPTURE, &priv->buf[i]) == -1)
1610 mp_msg(MSGT_TV, MSGL_ERR, "\nioctl mcapture failed: %s\n", strerror(errno));
1614 gettimeofday(&curtime, NULL);
1615 priv->starttime = (long long)1e6*curtime.tv_sec + curtime.tv_usec;
1616 priv->audio_skew_measure_time = 0;
1617 pthread_mutex_unlock(&priv->audio_starter);
1618 xskew = 0;
1619 skew = 0;
1620 interval = 0;
1622 prev_interval = 0;
1623 prev_skew = 0;
1625 tolerance = MAXTOL;
1627 for (framecount = 0; !priv->shutdown;)
1629 for (i = 0; i < priv->nbuf && !priv->shutdown; i++, framecount++) {
1631 if (priv->immediate_mode) {
1632 while (priv->video_cnt == priv->video_buffer_size_max) {
1633 usleep(10000);
1634 if (priv->shutdown) {
1635 return NULL;
1640 frame = i;
1642 if ( priv->tv_param->mjpeg )
1644 while (ioctl(priv->video_fd, MJPIOC_SYNC, &priv->buf[frame].frame) < 0 &&
1645 (errno == EAGAIN || errno == EINTR));
1647 else
1649 while (ioctl(priv->video_fd, VIDIOCSYNC, &priv->buf[frame].frame) < 0 &&
1650 (errno == EAGAIN || errno == EINTR));
1652 mp_dbg(MSGT_TV, MSGL_DBG3, "\npicture sync failed\n");
1654 gettimeofday(&curtime, NULL);
1655 if (!priv->immediate_mode) {
1656 interval = (long long)1e6*curtime.tv_sec + curtime.tv_usec - priv->starttime;
1657 } else {
1658 interval = (long long)1e6*framecount/priv->fps;
1661 if (!priv->immediate_mode) {
1662 long long period, orig_interval;
1664 if (tolerance == 0) {
1665 if (interval - prev_interval == 0) {
1666 mp_msg(MSGT_TV, MSGL_V, "\nvideo capture thread: frame delta = 0\n");
1667 } else if ((interval - prev_interval < (long long)0.85e6/priv->fps)
1668 || (interval - prev_interval > (long long)1.15e6/priv->fps) ) {
1669 mp_msg(MSGT_TV, MSGL_V, "\nvideo capture thread: frame delta ~ %.1lf fps\n",
1670 (double)1e6/(interval - prev_interval));
1674 // correct the rate fluctuations on a small scale
1675 orig_interval = interval;
1676 period = priv->video_interval_sum/VIDEO_AVG_BUFFER_SIZE;
1677 if (interval - prev_interval > 105*period/100) {
1678 if (tolerance > 0) {
1679 mp_msg(MSGT_TV, MSGL_DBG3, "correcting timestamp\n");
1680 interval = prev_interval + priv->video_interval_sum/VIDEO_AVG_BUFFER_SIZE;
1681 tolerance--;
1682 } else {
1683 mp_msg(MSGT_TV, MSGL_DBG3, "bad - frames were dropped\n");
1684 tolerance = MAXTOL;
1686 } else {
1687 if (tolerance < MAXTOL) {
1688 mp_msg(MSGT_TV, MSGL_DBG3, "fluctuation overcome\n");
1690 tolerance = MAXTOL;
1693 priv->video_interval_sum -= priv->video_avg_buffer[priv->video_avg_ptr];
1694 priv->video_avg_buffer[priv->video_avg_ptr++] = orig_interval-prev_interval;
1695 priv->video_interval_sum += orig_interval-prev_interval;
1696 if (priv->video_avg_ptr >= VIDEO_AVG_BUFFER_SIZE) priv->video_avg_ptr = 0;
1698 // fprintf(stderr, "fps: %lf\n", (double)1e6*VIDEO_AVG_BUFFER_SIZE/priv->video_interval_sum);
1700 // interpolate the skew in time
1701 pthread_mutex_lock(&priv->skew_mutex);
1702 xskew = priv->audio_skew + (interval - priv->audio_skew_measure_time)*priv->audio_skew_factor;
1703 pthread_mutex_unlock(&priv->skew_mutex);
1704 // correct extreme skew changes to avoid (especially) moving backwards in time
1705 if (xskew - prev_skew > (interval - prev_interval)*MAX_SKEW_DELTA) {
1706 skew = prev_skew + (interval - prev_interval)*MAX_SKEW_DELTA;
1707 } else if (xskew - prev_skew < -(interval - prev_interval)*MAX_SKEW_DELTA) {
1708 skew = prev_skew - (interval - prev_interval)*MAX_SKEW_DELTA;
1709 } else {
1710 skew = xskew;
1714 mp_msg(MSGT_TV, MSGL_DBG3, "\nfps = %lf, interval = %lf, a_skew = %f, corr_skew = %f\n",
1715 (interval != prev_interval) ? (double)1e6/(interval - prev_interval) : -1,
1716 (double)1e-6*interval, (double)1e-6*xskew, (double)1e-6*skew);
1717 mp_msg(MSGT_TV, MSGL_DBG3, "vcnt = %d, acnt = %d\n", priv->video_cnt, priv->audio_cnt);
1719 prev_skew = skew;
1720 prev_interval = interval;
1722 /* allocate a new buffer, if needed */
1723 pthread_mutex_lock(&priv->video_buffer_mutex);
1724 if (priv->video_buffer_size_current < priv->video_buffer_size_max) {
1725 if (priv->video_cnt == priv->video_buffer_size_current) {
1726 unsigned char *newbuf = calloc(priv->bytesperline, priv->height);
1727 if (newbuf) {
1728 memmove(priv->video_ringbuffer+priv->video_tail+1, priv->video_ringbuffer+priv->video_tail,
1729 (priv->video_buffer_size_current-priv->video_tail)*sizeof(unsigned char *));
1730 memmove(priv->video_timebuffer+priv->video_tail+1, priv->video_timebuffer+priv->video_tail,
1731 (priv->video_buffer_size_current-priv->video_tail)*sizeof(long long));
1732 priv->video_ringbuffer[priv->video_tail] = newbuf;
1733 if ((priv->video_head >= priv->video_tail) && (priv->video_cnt > 0)) priv->video_head++;
1734 priv->video_buffer_size_current++;
1738 pthread_mutex_unlock(&priv->video_buffer_mutex);
1740 if (priv->video_cnt == priv->video_buffer_size_current) {
1741 if (!priv->immediate_mode) {
1742 mp_msg(MSGT_TV, MSGL_ERR, "\nvideo buffer full - dropping frame\n");
1744 } else {
1745 if (priv->immediate_mode) {
1746 priv->video_timebuffer[priv->video_tail] = interval;
1747 } else {
1748 // compensate for audio skew
1749 // negative skew => there are more audio samples, increase interval
1750 // positive skew => less samples, shorten the interval
1751 priv->video_timebuffer[priv->video_tail] = interval - skew;
1754 if ( priv->tv_param->mjpeg )
1755 copy_frame(priv, priv->video_ringbuffer[priv->video_tail],
1756 priv->mmap+(priv->mjpeg_bufsize)*i);
1757 else
1758 copy_frame(priv, priv->video_ringbuffer[priv->video_tail],
1759 priv->mmap+priv->mbuf.offsets[frame]);
1760 priv->video_tail = (priv->video_tail+1)%priv->video_buffer_size_current;
1761 priv->video_cnt++;
1764 if ( priv->tv_param->mjpeg )
1766 num = frame;
1767 if (ioctl(priv->video_fd, MJPIOC_QBUF_CAPT, &num) < 0)
1769 mp_msg(MSGT_TV, MSGL_ERR, "\n MJP: ioctl MJPIOC_QBUF_CAPT end failed: %s\n",
1770 strerror(errno));
1771 continue;
1774 else
1776 if (ioctl(priv->video_fd, VIDIOCMCAPTURE, &priv->buf[frame]) == -1)
1778 mp_msg(MSGT_TV, MSGL_ERR, "\nioctl mcapture failed: %s\n", strerror(errno));
1779 continue;
1784 mp_msg(MSGT_TV, MSGL_INFO, " MJP: returning! \n");
1785 return NULL;
1788 static double grab_video_frame(priv_t *priv, char *buffer, int len)
1790 double interval;
1792 if (priv->first) {
1793 pthread_create(&priv->video_grabber_thread, NULL, video_grabber, priv);
1794 priv->first = 0;
1797 while (priv->video_cnt == 0) {
1798 usleep(10000);
1801 pthread_mutex_lock(&priv->video_buffer_mutex);
1802 interval = (double)priv->video_timebuffer[priv->video_head]*1e-6;
1803 fast_memcpy(buffer, priv->video_ringbuffer[priv->video_head], len);
1804 priv->video_cnt--;
1805 priv->video_head = (priv->video_head+1)%priv->video_buffer_size_current;
1806 pthread_mutex_unlock(&priv->video_buffer_mutex);
1808 return interval;
1811 static int get_video_framesize(priv_t *priv)
1813 return priv->bytesperline * priv->height;
1816 static void *audio_grabber(void *data)
1818 priv_t *priv = (priv_t*)data;
1819 struct timeval tv;
1820 int i, audio_skew_ptr = 0;
1821 long long current_time, prev_skew = 0;
1823 pthread_mutex_lock(&priv->audio_starter);
1825 audio_in_start_capture(&priv->audio_in);
1826 for (i = 0; i < priv->aud_skew_cnt; i++)
1827 priv->audio_skew_buffer[i] = 0;
1829 for (; !priv->shutdown;)
1831 if (audio_in_read_chunk(&priv->audio_in, priv->audio_ringbuffer+priv->audio_tail*priv->audio_in.blocksize) < 0)
1832 continue;
1834 gettimeofday(&tv, NULL);
1836 priv->audio_recv_blocks_total++;
1837 current_time = (long long)1e6*tv.tv_sec + tv.tv_usec - priv->starttime;
1839 priv->audio_skew_total -= priv->audio_skew_buffer[audio_skew_ptr];
1840 priv->audio_skew_buffer[audio_skew_ptr] = current_time
1841 - 1e6*priv->audio_secs_per_block*priv->audio_recv_blocks_total;
1842 priv->audio_skew_total += priv->audio_skew_buffer[audio_skew_ptr];
1843 audio_skew_ptr = (audio_skew_ptr+1) % priv->aud_skew_cnt;
1845 pthread_mutex_lock(&priv->skew_mutex);
1846 // linear interpolation - here we interpolate current skew value
1847 // from the moving average, which we expect to be in the middle
1848 // of the interval
1849 if (priv->audio_recv_blocks_total > priv->aud_skew_cnt) {
1850 priv->audio_skew = priv->audio_skew_total/priv->aud_skew_cnt;
1851 priv->audio_skew += (priv->audio_skew*priv->aud_skew_cnt)/(2*priv->audio_recv_blocks_total-priv->aud_skew_cnt);
1852 } else {
1853 // this smoothes the evolution of audio_skew at startup a bit
1854 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);
1856 // current skew factor (assuming linearity)
1857 // used for further interpolation in video_grabber
1858 // probably overkill but seems to be necessary for
1859 // stress testing by dropping half of the audio frames ;)
1860 // especially when using ALSA with large block sizes
1861 // where audio_skew remains a long while behind
1862 if ((priv->audio_skew_measure_time != 0) && (current_time - priv->audio_skew_measure_time != 0)) {
1863 priv->audio_skew_factor = (double)(priv->audio_skew-prev_skew)/(current_time - priv->audio_skew_measure_time);
1864 } else {
1865 priv->audio_skew_factor = 0.0;
1868 priv->audio_skew_measure_time = current_time;
1869 prev_skew = priv->audio_skew;
1870 pthread_mutex_unlock(&priv->skew_mutex);
1872 if ((priv->audio_tail+1) % priv->audio_buffer_size == priv->audio_head) {
1873 mp_msg(MSGT_TV, MSGL_ERR, "\ntoo bad - dropping audio frame !\n");
1874 priv->audio_drop++;
1875 } else {
1876 priv->audio_tail = (priv->audio_tail+1) % priv->audio_buffer_size;
1877 priv->audio_cnt++;
1880 return NULL;
1883 static double grab_audio_frame(priv_t *priv, char *buffer, int len)
1885 mp_dbg(MSGT_TV, MSGL_DBG2, "grab_audio_frame(priv=%p, buffer=%p, len=%d)\n",
1886 priv, buffer, len);
1888 if (priv->first) {
1889 pthread_create(&priv->video_grabber_thread, NULL, video_grabber, priv);
1890 priv->first = 0;
1893 // compensate for dropped audio frames
1894 if (priv->audio_drop && (priv->audio_head == priv->audio_tail)) {
1895 priv->audio_drop--;
1896 priv->audio_sent_blocks_total++;
1897 memset(buffer, 0, len);
1898 return (double)priv->audio_sent_blocks_total*priv->audio_secs_per_block;
1901 while (priv->audio_head == priv->audio_tail) {
1902 usleep(10000);
1904 fast_memcpy(buffer, priv->audio_ringbuffer+priv->audio_head*priv->audio_in.blocksize, len);
1905 priv->audio_head = (priv->audio_head+1) % priv->audio_buffer_size;
1906 priv->audio_cnt--;
1907 priv->audio_sent_blocks_total++;
1908 return (double)priv->audio_sent_blocks_total*priv->audio_secs_per_block;
1911 static int get_audio_framesize(priv_t *priv)
1913 return priv->audio_in.blocksize;