[MPlayer-dev-eng] [PATCH] v4l capture

Jindrich Makovicka makovick at KMLinux.fjfi.cvut.cz
Sun Aug 18 09:38:52 CEST 2002


On Sat, Aug 17, 2002 at 03:49:27PM -0400, D Richard Felker III wrote:
> On Sat, Aug 17, 2002 at 03:45:59PM -0400, D Richard Felker III wrote:
> > On Sat, Aug 17, 2002 at 10:42:59AM +0200, Jindrich Makovicka wrote:
> > > here goes the splitted version.
> > > 
> > > -- 
> > > Jindrich Makovicka
> > 
> > I just tested your patch with my bttv and it's impossible to set the
> > capture size -- it's stuck at 48x32 which is useless. Apparently
> > control is never getting called to set the width/height...
> 
> The problem is that you're skipping setting w/h if there's no tuner.
> The no tuner check belongs AFTER setting w/h. Check tv.c around line
> 158 or so.

Thanks. Here is the fixed patch.

-- 
Jindrich Makovicka
-------------- next part --------------
diff -urN --exclude-from dontdiff vanilla/main/DOCS/mplayer.1 main/DOCS/mplayer.1
--- vanilla/main/DOCS/mplayer.1	Fri Aug 16 18:02:32 2002
+++ main/DOCS/mplayer.1	Sat Aug 17 10:23:24 2002
@@ -306,7 +306,24 @@
     chanlist=<value>  available: europe-east,
                       europe-west, us-bcast,
                       us-cable, etc
+    audiorate=<value> set audio capture bitrate
+    alsa              capture from ALSA
+    mono              force mono audio
+    adevice=<value>   set an audio device
+                      /dev/... for OSS,
+                      hardware ID for ALSA
+    audioid=<value>   choose an audio output
+                      of the capture card, if it
+                      has more of them
+.TP
+.I NOTE:
+Mplayer doesn't accept colons so type commas instead in the device ID,
+eg. hw,0,0 instead of hw:0:0)
 
+Be advised that although you can select any samplerate when using ALSA,
+the LAME audio codec is able to encode only the "standard" samplerates.
+You'll get an .avi file with no sound when you choose an odd
+samplerate and use this codec.
 .TP
 .B \-vcd <track>
 Play video CD track from device instead of plain file.
diff -urN --exclude-from dontdiff vanilla/main/cfg-common.h main/cfg-common.h
--- vanilla/main/cfg-common.h	Tue Aug  6 19:04:55 2002
+++ main/cfg-common.h	Fri Aug 16 19:11:19 2002
@@ -197,6 +197,14 @@
 	{"input", &tv_param_input, CONF_TYPE_INT, 0, 0, 20, NULL},
 	{"outfmt", &tv_param_outfmt, CONF_TYPE_STRING, 0, 0, 0, NULL},
 	{"fps", &tv_param_fps, CONF_TYPE_FLOAT, 0, 0, 100.0, NULL},
+#ifdef HAVE_TV_V4L
+	{"mono", &tv_param_mono, CONF_TYPE_FLAG, 0, 0, 1, NULL},
+#ifdef HAVE_ALSA9
+	{"alsa", &tv_param_alsa, CONF_TYPE_FLAG, 0, 0, 1, NULL},
+#endif
+	{"adevice", &tv_param_adevice, CONF_TYPE_STRING, 0, 0, 0, NULL},
+	{"audioid", &tv_param_audio_id, CONF_TYPE_INT, CONF_RANGE, 0, 9, NULL},
+#endif
 	{NULL, NULL, 0, 0, 0, 0, NULL}
 };
 #endif
diff -urN --exclude-from dontdiff vanilla/main/configure main/configure
--- vanilla/main/configure	Fri Aug 16 18:02:20 2002
+++ main/configure	Fri Aug 16 19:11:19 2002
@@ -1975,6 +1975,25 @@
 fi
 echores "$_vsscanf"
 
+echocheck "sys/sysinfo.h"
+cat > $TMPC << EOF
+#include <sys/sysinfo.h>
+int main(void) {
+  struct sysinfo s_info;
+  sysinfo(&s_info);
+  return 0;
+}
+EOF
+_sys_sysinfo=no
+cc_check && _sys_sysinfo=yes
+if test "$_sys_sysinfo" = yes ; then
+  _def_sys_sysinfo='#define HAVE_SYS_SYSINFO_H 1'
+  _inc_sysinfo='#include <sys/sysinfo.h>'
+else
+  _def_sys_sysinfo='#undef HAVE_SYS_SYSINFO_H'
+fi
+echores "$_sys_sysinfo"
+
 
 #########
 # VIDEO #
@@ -4398,6 +4417,9 @@
 /* Define this if your system has the header file for the OSS sound interface
  * in /usr/include */
 $_def_soundcard
+
+/* Define this if your system has the sysinfo header */
+$_def_sys_sysinfo
 
 /* Define this if your system uses ftello() for off_t seeking */
 
diff -urN --exclude-from dontdiff vanilla/main/libmpdemux/Makefile main/libmpdemux/Makefile
--- vanilla/main/libmpdemux/Makefile	Tue Aug  6 19:06:18 2002
+++ main/libmpdemux/Makefile	Fri Aug 16 19:11:19 2002
@@ -3,7 +3,7 @@
 
 include ../config.mak
 
-SRCS = mp3_hdr.c video.c mpeg_hdr.c cache2.c asfheader.c aviheader.c aviprint.c aviwrite.c demux_asf.c demux_avi.c demux_mov.c parse_mp4.c demux_mpg.c demux_viv.c demuxer.c dvdauth.c dvdnav_stream.c open.c parse_es.c stream.c tv.c tvi_dummy.c tvi_v4l.c tvi_bsdbt848.c frequencies.c demux_fli.c demux_real.c demux_y4m.c yuv4mpeg.c yuv4mpeg_ratio.c demux_nuv.c demux_film.c demux_roq.c mf.c demux_mf.c demux_audio.c demux_demuxers.c opt-reg.c mpdemux.c demux_ogg.c demux_bmp.c cdda.c demux_rawaudio.c cddb.c demux_rawdv.c
+SRCS = mp3_hdr.c video.c mpeg_hdr.c cache2.c asfheader.c aviheader.c aviprint.c aviwrite.c demux_asf.c demux_avi.c demux_mov.c parse_mp4.c demux_mpg.c demux_viv.c demuxer.c dvdauth.c dvdnav_stream.c open.c parse_es.c stream.c tv.c tvi_dummy.c tvi_v4l.c tvi_bsdbt848.c frequencies.c demux_fli.c demux_real.c demux_y4m.c yuv4mpeg.c yuv4mpeg_ratio.c demux_nuv.c demux_film.c demux_roq.c mf.c demux_mf.c demux_audio.c demux_demuxers.c opt-reg.c mpdemux.c demux_ogg.c demux_bmp.c cdda.c demux_rawaudio.c cddb.c demux_rawdv.c ai_alsa.c ai_oss.c audio_in.c
 ifeq ($(STREAMING),yes)
 SRCS += asf_streaming.c url.c http.c network.c asf_mmst_streaming.c
 ifeq ($(STREAMING_LIVE_DOT_COM),yes)
diff -urN --exclude-from dontdiff vanilla/main/libmpdemux/ai_alsa.c main/libmpdemux/ai_alsa.c
--- vanilla/main/libmpdemux/ai_alsa.c	Thu Jan  1 01:00:00 1970
+++ main/libmpdemux/ai_alsa.c	Fri Aug 16 19:43:55 2002
@@ -0,0 +1,123 @@
+#include "config.h"
+
+#ifdef HAVE_ALSA9
+#include <alsa/asoundlib.h>
+#include "audio_in.h"
+#include "mp_msg.h"
+
+int ai_alsa_setup(audio_in_t *ai)
+{
+    snd_pcm_hw_params_t *params;
+    snd_pcm_sw_params_t *swparams;
+    size_t buffer_size;
+    int err;
+    size_t n;
+    unsigned int rate;
+    snd_pcm_uframes_t start_threshold, stop_threshold;
+
+    snd_pcm_hw_params_alloca(&params);
+    snd_pcm_sw_params_alloca(&swparams);
+
+    err = snd_pcm_hw_params_any(ai->alsa.handle, params);
+    if (err < 0) {
+	mp_msg(MSGT_TV, MSGL_ERR, "Broken configuration for this PCM: no configurations available\n");
+	return -1;
+    }
+    err = snd_pcm_hw_params_set_access(ai->alsa.handle, params,
+				       SND_PCM_ACCESS_RW_INTERLEAVED);
+    if (err < 0) {
+	mp_msg(MSGT_TV, MSGL_ERR, "Access type not available\n");
+	return -1;
+    }
+    err = snd_pcm_hw_params_set_format(ai->alsa.handle, params, SND_PCM_FORMAT_S16_LE);
+    if (err < 0) {
+	mp_msg(MSGT_TV, MSGL_ERR, "Sample format not available\n");
+	return -1;
+    }
+    err = snd_pcm_hw_params_set_channels(ai->alsa.handle, params, ai->req_channels);
+    if (err < 0) {
+	ai->channels = snd_pcm_hw_params_get_channels(params);
+	mp_msg(MSGT_TV, MSGL_ERR, "Channel count not available - reverting to default: %d\n",
+	       ai->channels);
+    } else {
+	ai->channels = ai->req_channels;
+    }
+
+    err = snd_pcm_hw_params_set_rate_near(ai->alsa.handle, params, ai->req_samplerate, 0);
+    assert(err >= 0);
+    rate = err;
+    ai->samplerate = rate;
+
+    ai->alsa.buffer_time = 1000000;
+    ai->alsa.buffer_time = snd_pcm_hw_params_set_buffer_time_near(ai->alsa.handle, params,
+							       ai->alsa.buffer_time, 0);
+    assert(ai->alsa.buffer_time >= 0);
+    ai->alsa.period_time = ai->alsa.buffer_time / 4;
+    ai->alsa.period_time = snd_pcm_hw_params_set_period_time_near(ai->alsa.handle, params,
+							       ai->alsa.period_time, 0);
+    assert(ai->alsa.period_time >= 0);
+    err = snd_pcm_hw_params(ai->alsa.handle, params);
+    if (err < 0) {
+	mp_msg(MSGT_TV, MSGL_ERR, "Unable to install hw params:");
+	snd_pcm_hw_params_dump(params, ai->alsa.log);
+	return -1;
+    }
+    ai->alsa.chunk_size = snd_pcm_hw_params_get_period_size(params, 0);
+    buffer_size = snd_pcm_hw_params_get_buffer_size(params);
+    if (ai->alsa.chunk_size == buffer_size) {
+	mp_msg(MSGT_TV, MSGL_ERR, "Can't use period equal to buffer size (%u == %lu)\n", ai->alsa.chunk_size, (long)buffer_size);
+	return -1;
+    }
+    snd_pcm_sw_params_current(ai->alsa.handle, swparams);
+    err = snd_pcm_sw_params_set_sleep_min(ai->alsa.handle, swparams,0);
+    assert(err >= 0);
+    err = snd_pcm_sw_params_set_avail_min(ai->alsa.handle, swparams, ai->alsa.chunk_size);
+    assert(err >= 0);
+
+    err = snd_pcm_sw_params_set_start_threshold(ai->alsa.handle, swparams, 0);
+    assert(err >= 0);
+    err = snd_pcm_sw_params_set_stop_threshold(ai->alsa.handle, swparams, buffer_size);
+    assert(err >= 0);
+
+    assert(err >= 0);
+    if (snd_pcm_sw_params(ai->alsa.handle, swparams) < 0) {
+	mp_msg(MSGT_TV, MSGL_ERR, "unable to install sw params:\n");
+	snd_pcm_sw_params_dump(swparams, ai->alsa.log);
+	return -1;
+    }
+
+    if (mp_msg_test(MSGT_TV, MSGL_V)) {
+	snd_pcm_dump(ai->alsa.handle, ai->alsa.log);
+    }
+
+    ai->alsa.bits_per_sample = snd_pcm_format_physical_width(SND_PCM_FORMAT_S16_LE);
+    ai->alsa.bits_per_frame = ai->alsa.bits_per_sample * ai->channels;
+    ai->blocksize = ai->alsa.chunk_size * ai->alsa.bits_per_frame / 8;
+    ai->samplesize = ai->alsa.bits_per_sample;
+    ai->bytes_per_sample = ai->alsa.bits_per_sample/8;
+
+    return 0;
+}
+
+int ai_alsa_init(audio_in_t *ai)
+{
+    int err;
+    
+    err = snd_pcm_open(&ai->alsa.handle, ai->alsa.device, SND_PCM_STREAM_CAPTURE, 0);
+    if (err < 0) {
+	mp_msg(MSGT_TV, MSGL_ERR, "Error opening audio");
+	return -1;
+    }
+    
+    err = snd_output_stdio_attach(&ai->alsa.log, stderr, 0);
+    
+    if (err < 0) {
+	return -1;
+    }
+    
+    err = ai_alsa_setup(ai);
+
+    return err;
+}
+
+#endif /* HAVE_ALSA9 */
diff -urN --exclude-from dontdiff vanilla/main/libmpdemux/ai_oss.c main/libmpdemux/ai_oss.c
--- vanilla/main/libmpdemux/ai_oss.c	Thu Jan  1 01:00:00 1970
+++ main/libmpdemux/ai_oss.c	Fri Aug 16 19:37:43 2002
@@ -0,0 +1,123 @@
+#include "config.h"
+#include <linux/soundcard.h>
+#include <fcntl.h>
+#include <errno.h>
+
+#include "audio_in.h"
+#include "mp_msg.h"
+
+int ai_oss_set_samplerate(audio_in_t *ai)
+{
+    int tmp = ai->req_samplerate;
+    if (ioctl(ai->oss.audio_fd, SNDCTL_DSP_SPEED, &tmp) == -1) return -1;
+    ai->samplerate = ai->req_samplerate;
+    return 0;
+}
+
+int ai_oss_set_channels(audio_in_t *ai)
+{
+    int err;
+    int ioctl_param;
+
+    if (ai->req_channels > 2)
+    {
+	ioctl_param = ai->req_channels;
+	mp_msg(MSGT_TV, MSGL_V, "ioctl dsp channels: %d\n",
+	       err = ioctl(ai->oss.audio_fd, SNDCTL_DSP_CHANNELS, &ioctl_param));
+	if (err < 0) {
+	    mp_msg(MSGT_TV, MSGL_ERR, "Unable to set channel count: %d\n",
+		   ai->req_channels);
+	    return -1;
+	}
+    }
+    else
+    {
+	ioctl_param = (ai->req_channels == 2);
+	mp_msg(MSGT_TV, MSGL_V, "ioctl dsp stereo: %d (req: %d)\n",
+	       err = ioctl(ai->oss.audio_fd, SNDCTL_DSP_STEREO, &ioctl_param),
+	       ioctl_param);
+	if (err < 0) {
+	    mp_msg(MSGT_TV, MSGL_ERR, "Unable to set stereo: %d\n",
+		   ai->req_channels == 2);
+	    return -1;
+	}
+    }
+    ai->channels = ai->req_channels;
+    return 0;
+}
+
+int ai_oss_init(audio_in_t *ai)
+{
+    int err;
+    int ioctl_param;
+
+    ai->oss.audio_fd = open(ai->oss.device, O_RDONLY);
+    if (ai->oss.audio_fd < 0)
+    {
+	mp_msg(MSGT_TV, MSGL_ERR, "unable to open '%s': %s\n",
+	       ai->oss.device, strerror(errno));
+	return -1;
+    }
+	
+    ioctl_param = 0 ;
+    mp_msg(MSGT_TV, MSGL_V, "ioctl dsp getfmt: %d\n",
+	   ioctl(ai->oss.audio_fd, SNDCTL_DSP_GETFMTS, &ioctl_param));
+	
+    mp_msg(MSGT_TV, MSGL_V, "Supported formats: %x\n", ioctl_param);
+    if (!(ioctl_param & AFMT_S16_LE))
+	mp_msg(MSGT_TV, MSGL_ERR, "notsupported format\n");
+
+    ioctl_param = AFMT_S16_LE;
+    mp_msg(MSGT_TV, MSGL_V, "ioctl dsp setfmt: %d\n",
+	   err = ioctl(ai->oss.audio_fd, SNDCTL_DSP_SETFMT, &ioctl_param));
+    if (err < 0) {
+	mp_msg(MSGT_TV, MSGL_ERR, "Unable to set audio format.");
+	return -1;
+    }
+
+    if (ai_oss_set_channels(ai) < 0) return -1;
+	
+    ioctl_param = ai->req_samplerate;
+    mp_msg(MSGT_TV, MSGL_V, "ioctl dsp speed: %d\n",
+	   err = ioctl(ai->oss.audio_fd, SNDCTL_DSP_SPEED, &ioctl_param));
+    if (err < 0) {
+	mp_msg(MSGT_TV, MSGL_ERR, "Unable to set samplerate: %d\n",
+	       ai->req_samplerate);
+	return -1;
+    }
+    ai->samplerate = ai->req_samplerate;
+
+    mp_msg(MSGT_TV, MSGL_V, "ioctl dsp trigger: %d\n",
+	   ioctl(ai->oss.audio_fd, SNDCTL_DSP_GETTRIGGER, &ioctl_param));
+    mp_msg(MSGT_TV, MSGL_V, "trigger: %x\n", ioctl_param);
+    ioctl_param = PCM_ENABLE_INPUT;
+    mp_msg(MSGT_TV, MSGL_V, "ioctl dsp trigger: %d\n",
+	   err = ioctl(ai->oss.audio_fd, SNDCTL_DSP_SETTRIGGER, &ioctl_param));
+    if (err < 0) {
+	mp_msg(MSGT_TV, MSGL_ERR, "Unable to set trigger: %d\n",
+	       PCM_ENABLE_INPUT);
+	return -1;
+    }
+
+    ai->blocksize = 0;
+    mp_msg(MSGT_TV, MSGL_V, "ioctl dsp getblocksize: %d\n",
+	   err = ioctl(ai->oss.audio_fd, SNDCTL_DSP_GETBLKSIZE, &ai->blocksize));
+    if (err < 0) {
+	mp_msg(MSGT_TV, MSGL_ERR, "Unable to get block size!\n");
+    }
+    mp_msg(MSGT_TV, MSGL_V, "blocksize: %d\n", ai->blocksize);
+
+    // correct the blocksize to a reasonable value
+    if (ai->blocksize <= 0) {
+	ai->blocksize = 4096*ai->channels*2;
+	mp_msg(MSGT_TV, MSGL_ERR, "audio block size is zero, setting to %d!\n", ai->blocksize);
+    } else if (ai->blocksize < 4096*ai->channels*2) {
+	ai->blocksize *= 4096*ai->channels*2/ai->blocksize;
+	mp_msg(MSGT_TV, MSGL_ERR, "audio block size too low, setting to %d!\n", ai->blocksize);
+    }
+
+    ai->samplesize = 16;
+    ai->bytes_per_sample = 2;
+
+    return 0;
+}
diff -urN --exclude-from dontdiff vanilla/main/libmpdemux/audio_in.c main/libmpdemux/audio_in.c
--- vanilla/main/libmpdemux/audio_in.c	Thu Jan  1 01:00:00 1970
+++ main/libmpdemux/audio_in.c	Fri Aug 16 20:43:52 2002
@@ -0,0 +1,192 @@
+#include "config.h"
+#include "audio_in.h"
+#include "mp_msg.h"
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <errno.h>
+
+// sanitizes ai structure before calling other functions
+int audio_in_init(audio_in_t *ai, int type)
+{
+    ai->type = type;
+    ai->setup = 0;
+
+    ai->channels = -1;
+    ai->samplerate = -1;
+    ai->blocksize = -1;
+    ai->bytes_per_sample = -1;
+    ai->samplesize = -1;
+
+    switch (ai->type) {
+#ifdef HAVE_ALSA9	  
+    case AUDIO_IN_ALSA:
+	ai->alsa.handle = NULL;
+	ai->alsa.log = NULL;
+	ai->alsa.device = strdup("default");
+	return 0;
+#endif
+    case AUDIO_IN_OSS:
+	ai->oss.audio_fd = -1;
+	ai->oss.device = strdup("/dev/dsp");
+	return 0;
+    default:
+	return -1;
+    }
+}
+
+int audio_in_setup(audio_in_t *ai)
+{
+    int err;
+    
+    switch (ai->type) {
+#ifdef HAVE_ALSA9	  
+    case AUDIO_IN_ALSA:
+	if (ai_alsa_init(ai) < 0) return -1;
+	ai->setup = 1;
+	return 0;
+#endif
+    case AUDIO_IN_OSS:
+	if (ai_oss_init(ai) < 0) return -1;
+	ai->setup = 1;
+	return 0;
+    default:
+	return -1;
+    }
+}
+
+int audio_in_set_samplerate(audio_in_t *ai, int rate)
+{
+    switch (ai->type) {
+#ifdef HAVE_ALSA9	  
+    case AUDIO_IN_ALSA:
+	ai->req_samplerate = rate;
+	if (!ai->setup) return 0;
+	if (ai_alsa_setup(ai) < 0) return -1;
+	return ai->samplerate;
+#endif
+    case AUDIO_IN_OSS:
+	ai->req_samplerate = rate;
+	if (!ai->setup) return 0;
+	if (ai_oss_set_samplerate(ai) < 0) return -1;
+	return ai->samplerate;
+    default:
+	return -1;
+    }
+}
+
+int audio_in_set_channels(audio_in_t *ai, int channels)
+{
+    switch (ai->type) {
+#ifdef HAVE_ALSA9	  
+    case AUDIO_IN_ALSA:
+	ai->req_channels = channels;
+	if (!ai->setup) return 0;
+	if (ai_alsa_setup(ai) < 0) return -1;
+	return ai->channels;
+#endif
+    case AUDIO_IN_OSS:
+	ai->req_channels = channels;
+	if (!ai->setup) return 0;
+	if (ai_oss_set_channels(ai) < 0) return -1;
+	return ai->channels;
+    default:
+	return -1;
+    }
+}
+
+int audio_in_set_device(audio_in_t *ai, char *device)
+{
+    int i;
+    if (ai->setup) return -1;
+    switch (ai->type) {
+#ifdef HAVE_ALSA9	  
+    case AUDIO_IN_ALSA:
+	if (ai->alsa.device) free(ai->alsa.device);
+	ai->alsa.device = strdup(device);
+	/* mplayer cannot handle colons in arguments */
+	for (i = 0; i < strlen(ai->alsa.device); i++) {
+	    if (ai->alsa.device[i] == ',') ai->alsa.device[i] = ':';
+	}
+	return 0;
+#endif
+    case AUDIO_IN_OSS:
+	if (ai->oss.device) free(ai->oss.device);
+	ai->oss.device = strdup(device);
+	return 0;
+    default:
+	return -1;
+    }
+}
+
+int audio_in_uninit(audio_in_t *ai)
+{
+    if (ai->setup) {
+	switch (ai->type) {
+#ifdef HAVE_ALSA9	  
+	case AUDIO_IN_ALSA:
+	    if (ai->alsa.log)
+		snd_output_close(ai->alsa.log);
+	    if (ai->alsa.handle) {
+		snd_pcm_close(ai->alsa.handle);
+	    }
+	    ai->setup = 0;
+	    return 0;
+#endif
+	case AUDIO_IN_OSS:
+	    close(ai->oss.audio_fd);
+	    ai->setup = 0;
+	    return 0;
+	default:
+	    return -1;
+	}
+    }
+}
+
+int audio_in_start_capture(audio_in_t *ai)
+{
+    switch (ai->type) {
+#ifdef HAVE_ALSA9	  
+    case AUDIO_IN_ALSA:
+	return snd_pcm_start(ai->alsa.handle);
+#endif
+    case AUDIO_IN_OSS:
+	return 0;
+    default:
+	return -1;
+    }
+}
+
+int audio_in_read_chunk(audio_in_t *ai, unsigned char *buffer)
+{
+    int ret;
+    
+    switch (ai->type) {
+#ifdef HAVE_ALSA9	  
+    case AUDIO_IN_ALSA:
+	ret = snd_pcm_readi(ai->alsa.handle, buffer, ai->alsa.chunk_size);
+	if (ret != ai->alsa.chunk_size) {
+	    if (ret < 0) {
+		mp_msg(MSGT_TV, MSGL_ERR, "\nerror reading audio: %s\n", snd_strerror(ret));
+	    } else {
+		mp_msg(MSGT_TV, MSGL_ERR, "\nnot enough audio samples!\n");
+	    }
+	    return -1;
+	}
+	return ret;
+#endif
+    case AUDIO_IN_OSS:
+	ret = read(ai->oss.audio_fd, buffer, ai->blocksize);
+	if (ret != ai->blocksize) {
+	    if (ret < 0) {
+		mp_msg(MSGT_TV, MSGL_ERR, "\nerror reading audio: %s\n", strerror(errno));
+	    } else {
+		mp_msg(MSGT_TV, MSGL_ERR, "\nnot enough audio samples!\n");
+	    }
+	    return -1;
+	}
+	return ret;
+    default:
+	return -1;
+    }
+}
diff -urN --exclude-from dontdiff vanilla/main/libmpdemux/audio_in.h main/libmpdemux/audio_in.h
--- vanilla/main/libmpdemux/audio_in.h	Thu Jan  1 01:00:00 1970
+++ main/libmpdemux/audio_in.h	Fri Aug 16 19:33:32 2002
@@ -0,0 +1,68 @@
+#ifndef _audio_in_h 
+#define _audio_in_h 
+
+#define AUDIO_IN_ALSA 1
+#define AUDIO_IN_OSS 2
+
+#include "config.h"
+
+#ifdef HAVE_ALSA9
+#include <alsa/asoundlib.h>
+
+typedef struct {
+    char *device;
+
+    snd_pcm_t *handle;
+    snd_output_t *log;
+    int buffer_time, period_time, chunk_size;
+    size_t bits_per_sample, bits_per_frame;
+} ai_alsa_t;
+#endif
+
+typedef struct {
+    char *device;
+
+    int audio_fd;
+} ai_oss_t;
+
+typedef struct 
+{
+    int type;
+    int setup;
+    
+    /* requested values */
+    int req_channels;
+    int req_samplerate;
+
+    /* real values read-only */
+    int channels;
+    int samplerate;
+    int blocksize;
+    int bytes_per_sample;
+    int samplesize;
+    
+#ifdef HAVE_ALSA9
+    ai_alsa_t alsa;
+#endif
+    ai_oss_t oss;
+} audio_in_t;
+
+int audio_in_init(audio_in_t *ai, int type);
+int audio_in_setup(audio_in_t *ai);
+int audio_in_set_device(audio_in_t *ai, char *device);
+int audio_in_set_samplerate(audio_in_t *ai, int rate);
+int audio_in_set_channels(audio_in_t *ai, int channels);
+int audio_in_uninit(audio_in_t *ai);
+int audio_in_start_capture(audio_in_t *ai);
+int audio_in_read_chunk(audio_in_t *ai, unsigned char *buffer);
+
+#ifdef HAVE_ALSA9
+int ai_alsa_setup(audio_in_t *ai);
+int ai_alsa_init(audio_in_t *ai);
+#endif
+
+int ai_oss_set_samplerate(audio_in_t *ai);
+int ai_oss_set_channels(audio_in_t *ai);
+int ai_oss_init(audio_in_t *ai);
+
+#endif /* _audio_in_h */
diff -urN --exclude-from dontdiff vanilla/main/libmpdemux/demuxer.c main/libmpdemux/demuxer.c
--- vanilla/main/libmpdemux/demuxer.c	Thu Aug 15 18:53:42 2002
+++ main/libmpdemux/demuxer.c	Fri Aug 16 19:11:19 2002
@@ -155,6 +155,18 @@
 extern void demux_close_avi(demuxer_t *demuxer);
 extern void demux_close_rawdv(demuxer_t* demuxer);
 
+#ifdef USE_TV
+#include "tv.h"
+extern tvi_handle_t *tv_handler;
+extern int tv_param_on;
+
+extern int demux_tv_fill_buffer(demuxer_t *demux, demux_stream_t *ds, tvi_handle_t *tvh);
+extern int demux_open_tv(demuxer_t *demuxer, tvi_handle_t *tvh);
+#if defined(USE_TV) && defined(HAVE_TV_V4L)
+extern void demux_close_tv(demuxer_t *demuxer, tvi_handle_t *tvh);
+#endif
+#endif
+
 void free_demuxer(demuxer_t *demuxer){
     int i;
     mp_msg(MSGT_DEMUXER,MSGL_V,"DEMUXER: freeing demuxer at %p  \n",demuxer);
@@ -177,6 +189,10 @@
       demux_close_fli(demuxer); break;
     case DEMUXER_TYPE_NUV:
       demux_close_nuv(demuxer); break;
+#if defined(USE_TV) && defined(HAVE_TV_V4L)
+    case DEMUXER_TYPE_TV:
+	demux_close_tv(demuxer, tv_handler); break;
+#endif
 #ifdef HAVE_LIBDV095
     case DEMUXER_TYPE_RAWDV:
       demux_close_rawdv(demuxer); break;
@@ -267,15 +283,6 @@
 int demux_nuv_fill_buffer(demuxer_t *demux);
 int demux_rtp_fill_buffer(demuxer_t *demux, demux_stream_t* ds);
 int demux_rawdv_fill_buffer(demuxer_t *demuxer);
-
-#ifdef USE_TV
-#include "tv.h"
-extern tvi_handle_t *tv_handler;
-extern int tv_param_on;
-
-extern int demux_tv_fill_buffer(demuxer_t *demux, demux_stream_t *ds, tvi_handle_t *tvh);
-extern int demux_open_tv(demuxer_t *demuxer, tvi_handle_t *tvh);
-#endif
 int demux_y4m_fill_buffer(demuxer_t *demux);
 int demux_audio_fill_buffer(demux_stream_t *ds);
 extern int demux_demuxers_fill_buffer(demuxer_t *demux,demux_stream_t *ds);
diff -urN --exclude-from dontdiff vanilla/main/libmpdemux/tv.c main/libmpdemux/tv.c
--- vanilla/main/libmpdemux/tv.c	Thu May 23 16:53:11 2002
+++ main/libmpdemux/tv.c	Sun Aug 18 09:30:06 2002
@@ -39,9 +39,7 @@
 /* some default values */
 int tv_param_audiorate = 44100;
 int tv_param_noaudio = 0;
-#ifdef HAVE_TV_BSDBT848
 int tv_param_immediate = 0;
-#endif
 char *tv_param_freq = NULL;
 char *tv_param_channel = NULL;
 char *tv_param_norm = "pal";
@@ -53,6 +51,14 @@
 int tv_param_input = 0; /* used in v4l and bttv */
 char *tv_param_outfmt = "yv12";
 float tv_param_fps = -1.0;
+#ifdef HAVE_TV_V4L
+int tv_param_mono = 0;
+int tv_param_audio_id = 0;
+#ifdef HAVE_ALSA9
+int tv_param_alsa = 0;
+#endif
+char* tv_param_adevice = NULL;
+#endif
 
 /* ================== DEMUX_TV ===================== */
 /*
@@ -135,6 +141,21 @@
     }
     funcs->control(tvh->priv, TVI_CONTROL_VID_SET_FORMAT, &picture_format);
 
+    /* set some params got from cmdline */
+    funcs->control(tvh->priv, TVI_CONTROL_SPC_SET_INPUT, &tv_param_input);
+
+    /* select video norm */
+    if (!strcasecmp(tv_param_norm, "pal"))
+	tvh->norm = TV_NORM_PAL;
+    else if (!strcasecmp(tv_param_norm, "ntsc"))
+	tvh->norm = TV_NORM_NTSC;
+    else if (!strcasecmp(tv_param_norm, "secam"))
+	tvh->norm = TV_NORM_SECAM;
+
+    mp_msg(MSGT_TV, MSGL_INFO, "Selected norm: %s\n", tv_param_norm);
+    funcs->control(tvh->priv, TVI_CONTROL_TUN_SET_NORM, &tvh->norm);
+
+    /* limits on w&h are norm-dependent -- JM */
     /* set width */
     if (tv_param_width != -1)
     {
@@ -159,20 +180,6 @@
 	}    
     }
 
-    /* set some params got from cmdline */
-    funcs->control(tvh->priv, TVI_CONTROL_SPC_SET_INPUT, &tv_param_input);
-
-    /* select video norm */
-    if (!strcasecmp(tv_param_norm, "pal"))
-	tvh->norm = TV_NORM_PAL;
-    else if (!strcasecmp(tv_param_norm, "ntsc"))
-	tvh->norm = TV_NORM_NTSC;
-    else if (!strcasecmp(tv_param_norm, "secam"))
-	tvh->norm = TV_NORM_SECAM;
-
-    mp_msg(MSGT_TV, MSGL_INFO, "Selected norm: %s\n", tv_param_norm);
-    funcs->control(tvh->priv, TVI_CONTROL_TUN_SET_NORM, &tvh->norm);
-
     if (funcs->control(tvh->priv, TVI_CONTROL_IS_TUNER, 0) != TVI_CONTROL_TRUE)
     {
 	mp_msg(MSGT_TV, MSGL_WARN, "Selected input hasn't got a tuner!\n");	
@@ -272,14 +279,12 @@
 
     printf("fps: %f, frametime: %f\n", sh_video->fps, sh_video->frametime);
 
-#ifdef HAVE_TV_BSDBT848
     /* If playback only mode, go to immediate mode, fail silently */
     if(tv_param_immediate == 1)
         {
         funcs->control(tvh->priv, TVI_CONTROL_IMMEDIATE, 0);
         tv_param_noaudio = 1; 
         }
-#endif
 
     /* set width */
     funcs->control(tvh->priv, TVI_CONTROL_VID_GET_WIDTH, &sh_video->disp_w);
@@ -371,9 +376,16 @@
     return(funcs->start(tvh->priv));	
 }
 
+#if defined(USE_TV) && defined(HAVE_TV_V4L)
+int demux_close_tv(demuxer_t *demuxer, tvi_handle_t *tvh)
+{
+    return(tvh->functions->uninit(tvh->priv));
+}
+#endif
+
 /* ================== STREAM_TV ===================== */
 tvi_handle_t *tvi_init_dummy(char *device);
-tvi_handle_t *tvi_init_v4l(char *device);
+tvi_handle_t *tvi_init_v4l(char *device, char *adevice);
 tvi_handle_t *tvi_init_bsdbt848(char *device);
 
 tvi_handle_t *tv_begin(void)
@@ -382,7 +394,7 @@
 	return tvi_init_dummy(tv_param_device);
 #ifdef HAVE_TV_V4L
     if (!strcmp(tv_param_driver, "v4l"))
-	return tvi_init_v4l(tv_param_device);
+	return tvi_init_v4l(tv_param_device, tv_param_adevice);
 #endif
 #ifdef HAVE_TV_BSDBT848
     if (!strcmp(tv_param_driver, "bsdbt848"))
diff -urN --exclude-from dontdiff vanilla/main/libmpdemux/tv.h main/libmpdemux/tv.h
--- vanilla/main/libmpdemux/tv.h	Fri Apr 12 12:40:38 2002
+++ main/libmpdemux/tv.h	Fri Aug 16 19:11:19 2002
@@ -23,6 +23,14 @@
 extern int tv_param_noaudio;
 extern int tv_param_immediate;
 extern int tv_param_audiorate;
+#ifdef HAVE_TV_V4L
+extern int tv_param_mono;
+extern int tv_param_audio_id;
+#ifdef HAVE_ALSA9
+extern int tv_param_alsa;
+#endif
+extern char* tv_param_adevice;
+#endif
 
 typedef struct tvi_info_s
 {
@@ -72,9 +80,7 @@
 #define TVI_CONTROL_IS_AUDIO		0x1
 #define TVI_CONTROL_IS_VIDEO		0x2
 #define TVI_CONTROL_IS_TUNER		0x3
-#ifdef HAVE_TV_BSDBT848
-#define TVI_CONTROL_IMMEDIATE       0x4
-#endif
+#define TVI_CONTROL_IMMEDIATE           0x4
 
 /* VIDEO controls */
 #define TVI_CONTROL_VID_GET_FPS		0x101
diff -urN --exclude-from dontdiff vanilla/main/libmpdemux/tvi_v4l.c main/libmpdemux/tvi_v4l.c
--- vanilla/main/libmpdemux/tvi_v4l.c	Mon Jun 24 18:37:18 2002
+++ main/libmpdemux/tvi_v4l.c	Fri Aug 16 23:14:08 2002
@@ -6,6 +6,9 @@
   Some ideas are based on xawtv/libng's grab-v4l.c written by
     Gerd Knorr <kraxel at bytesex.org>
 
+  Multithreading, a/v sync and native ALSA support by
+    Jindrich Makovicka <makovick at kmlinux.fjfi.cvut.cz>
+
   CODE IS UNDER DEVELOPMENT, NO FEATURE REQUESTS PLEASE!
 */
 
@@ -21,11 +24,14 @@
 #include <sys/types.h>
 #include <sys/time.h>
 #include <linux/videodev.h>
-#include <linux/soundcard.h>
 #include <unistd.h>
 #include <sys/mman.h>
 #include <stdlib.h>
 #include <string.h>
+#include <pthread.h>
+#ifdef HAVE_SYS_SYSINFO_H
+#include <sys/sysinfo.h>
+#endif
 
 #include "mp_msg.h"
 #include "../libao2/afmt.h"
@@ -34,6 +40,8 @@
 
 #include "tv.h"
 
+#include "audio_in.h"
+
 static tvi_info_t info = {
 	"Video 4 Linux input",
 	"v4l",
@@ -41,12 +49,22 @@
 	"under development"
 };
 
+#define PAL_WIDTH  768
+#define PAL_HEIGHT 576
+#define PAL_FPS    25
+
+#define NTSC_WIDTH  640
+#define NTSC_HEIGHT 480
+#define NTSC_FPS    30
+
 #define MAX_AUDIO_CHANNELS	10
 
+#define VID_BUF_SIZE_IMMEDIATE 2
+
 typedef struct {
     /* general */
     char			*video_device;
-    int				video_fd;
+    int                         video_fd;
     struct video_capability	capability;
     struct video_channel	*channels;
     int				act_channel;
@@ -61,24 +79,54 @@
     int				fps;
 
     struct video_mbuf		mbuf;
-    unsigned char		*mmap;
+    unsigned char               *mmap;
     struct video_mmap		*buf;
     int				nbuf;
-    int				queue;
 
     /* audio */
-    int				audio_id;
     char			*audio_device;
+    audio_in_t                  audio_in;
+
+    int				audio_id;
     struct video_audio		audio[MAX_AUDIO_CHANNELS];
-    int				audio_fd;
     int				audio_channels[MAX_AUDIO_CHANNELS];
-    int				audio_format[MAX_AUDIO_CHANNELS];
-    int				audio_samplesize[MAX_AUDIO_CHANNELS];
-    int				audio_samplerate[MAX_AUDIO_CHANNELS];
-    int				audio_blocksize;
 
-    /* other */
-    double			starttime;
+    /* buffering stuff */
+    int                         immediate_mode;
+
+    int                         audio_buffer_size;
+    int                         aud_skew_cnt;
+    unsigned char		*audio_ringbuffer;
+    double			*audio_skew_buffer;
+    volatile int		audio_head;
+    volatile int		audio_tail;
+    volatile int		audio_cnt;
+    volatile double             audio_skew;
+    volatile double             audio_skew_factor;
+    volatile double             audio_skew_measure_time;
+    volatile int                audio_drop;
+
+    int                         first;
+    int                         video_buffer_size;
+    unsigned char		*video_ringbuffer;
+    double			*video_timebuffer;
+    volatile int		video_head;
+    volatile int		video_tail;
+    volatile int		video_cnt;
+
+    volatile int                shutdown;
+
+    pthread_t			audio_grabber_thread;
+    pthread_t			video_grabber_thread;
+    pthread_mutex_t             audio_starter;
+    pthread_mutex_t             skew_mutex;
+
+    double                      starttime;
+    double                      audio_secs_per_block;
+    double                      audio_skew_total;
+    long			audio_recv_blocks_total;
+    long			audio_sent_blocks_total;
+    
 } priv_t;
 
 #include "tvi_def.h"
@@ -100,6 +148,9 @@
     "unknown", "mono", "stereo", "language1", "language2", NULL
 };
 
+static void *audio_grabber(void *data);
+static void *video_grabber(void *data);
+
 static int palette2depth(int palette)
 {
     switch(palette)
@@ -134,28 +185,47 @@
 {
     switch(format)
     {
-	case IMGFMT_RGB15:
+	case IMGFMT_BGR15:
 	    return(VIDEO_PALETTE_RGB555);
-	case IMGFMT_RGB16:
+	case IMGFMT_BGR16:
 	    return(VIDEO_PALETTE_RGB565);
-	case IMGFMT_RGB24:
+	case IMGFMT_BGR24:
 	    return(VIDEO_PALETTE_RGB24);
-	case IMGFMT_RGB32:
+	case IMGFMT_BGR32:
 	    return(VIDEO_PALETTE_RGB32);
 	case IMGFMT_YV12:
 	case IMGFMT_I420:
 	    return(VIDEO_PALETTE_YUV420P);
-	case IMGFMT_UYVY:
-	    return(VIDEO_PALETTE_YUV422);
 	case IMGFMT_YUY2:
-	    return(VIDEO_PALETTE_YUYV);
+	    return(VIDEO_PALETTE_YUV422);
     }
     return(-1);
 }
 
+// sets and sanitizes audio buffer/block sizes
+static void setup_audio_buffer_sizes(priv_t *priv)
+{
+    int bytes_per_sample = priv->audio_in.bytes_per_sample;
+
+    // make the audio buffer at least 5 seconds long
+    priv->audio_buffer_size = 1 + 5*priv->audio_in.samplerate
+	*priv->audio_in.channels
+	*bytes_per_sample/priv->audio_in.blocksize;
+    if (priv->audio_buffer_size < 256) priv->audio_buffer_size = 256;
+
+    // make the skew buffer at least 1 second long
+    priv->aud_skew_cnt = 1 + 1*priv->audio_in.samplerate
+	*priv->audio_in.channels
+	*bytes_per_sample/priv->audio_in.blocksize;
+    if (priv->aud_skew_cnt < 16) priv->aud_skew_cnt = 16;
+
+    mp_msg(MSGT_TV, MSGL_V, "Audio capture - buffer %d blocks of %d bytes, skew average from %d meas.\n",
+	   priv->audio_buffer_size, priv->audio_in.blocksize, priv->aud_skew_cnt);
+}
+
 static int one = 1, zero = 0;
 
-tvi_handle_t *tvi_init_v4l(char *device)
+tvi_handle_t *tvi_init_v4l(char *device, char *adevice)
 {
     tvi_handle_t *h;
     priv_t *priv;
@@ -172,22 +242,114 @@
     else
 	priv->video_device = strdup(device);
 
+    /* set video device name */
+    if (!adevice)
+	priv->audio_device = NULL;
+    else {
+	priv->audio_device = strdup(adevice);
+    }
+    
     /* allocation failed */
     if (!priv->video_device) {
 	free_handle(h);
 	return(NULL);
     }
 
-    /* set audio device name */
-    priv->audio_device = strdup("/dev/dsp");
-
     return(h);
 }
 
+/* retrieves info about audio channels from the BTTV */
+static void init_v4l_audio(priv_t *priv)
+{
+    int i;
+
+    if (!priv->capability.audios) return;
+
+    /* audio chanlist */
+
+    mp_msg(MSGT_TV, MSGL_INFO, " Audio devices: %d\n", priv->capability.audios);
+
+    for (i = 0; i < priv->capability.audios; i++)
+    {
+	if (i >= MAX_AUDIO_CHANNELS)
+	{
+	    mp_msg(MSGT_TV, MSGL_ERR, "no space for more audio channels (increase in source!) (%d > %d)\n",
+		   i, MAX_AUDIO_CHANNELS);
+	    i = priv->capability.audios;
+	    break;
+	}
+
+	priv->audio[i].audio = i;
+	if (ioctl(priv->video_fd, VIDIOCGAUDIO, &priv->audio[i]) == -1)
+	{
+	    mp_msg(MSGT_TV, MSGL_ERR, "ioctl get audio failed: %s\n", strerror(errno));
+	    break;
+	}
+
+	/* mute all channels */
+	priv->audio[i].volume = 0;
+	priv->audio[i].flags |= VIDEO_AUDIO_MUTE;
+	if (tv_param_mono) {
+	    priv->audio[i].mode = VIDEO_SOUND_MONO;
+	    ioctl(priv->video_fd, VIDIOCSAUDIO, &priv->audio[i]);
+	} else {
+	    /* try to set stereo */
+	    priv->audio[i].mode = VIDEO_SOUND_STEREO;
+	    ioctl(priv->video_fd, VIDIOCSAUDIO, &priv->audio[i]);
+	}
+	
+	priv->audio[i].audio = i;
+	if (ioctl(priv->video_fd, VIDIOCGAUDIO, &priv->audio[i]) == -1)
+	{
+	    mp_msg(MSGT_TV, MSGL_ERR, "ioctl get audio failed: %s\n", strerror(errno));
+	    break;
+	}
+	    
+	switch(priv->audio[i].mode)
+	{
+	case VIDEO_SOUND_MONO:
+	case VIDEO_SOUND_LANG1:
+	case VIDEO_SOUND_LANG2:
+	    priv->audio_channels[i] = 1;
+	    break;
+	case VIDEO_SOUND_STEREO:
+	    priv->audio_channels[i] = 2;
+	    break;
+	}
+
+	/* display stuff */
+	mp_msg(MSGT_TV, MSGL_V, "  %d: %s: ", priv->audio[i].audio,
+	       priv->audio[i].name);
+	if (priv->audio[i].flags & VIDEO_AUDIO_MUTABLE) {
+	    mp_msg(MSGT_TV, MSGL_V, "muted=%s ",
+		   (priv->audio[i].flags & VIDEO_AUDIO_MUTE) ? "yes" : "no");
+	}
+	mp_msg(MSGT_TV, MSGL_V, "volume=%d bass=%d treble=%d balance=%d mode=%s\n",
+	       priv->audio[i].volume, priv->audio[i].bass, priv->audio[i].treble,
+	       priv->audio[i].balance, audio_mode2name[priv->audio[i].mode]);
+	mp_msg(MSGT_TV, MSGL_V, " channels: %d\n", priv->audio_channels[i]);
+    }
+}
+
 static int init(priv_t *priv)
 {
     int i;
 
+    if (tv_param_immediate == 1)
+	tv_param_noaudio = 1;
+    
+    if (!tv_param_noaudio) {
+    }
+
+    if (priv->audio_device) {
+	audio_in_set_device(&priv->audio_in, priv->audio_device);
+    }
+
+    priv->video_ringbuffer = NULL;
+    priv->video_timebuffer = NULL;
+    priv->audio_ringbuffer = NULL;
+    priv->audio_skew_buffer = NULL;
+
     priv->video_fd = open(priv->video_device, O_RDWR);
     mp_msg(MSGT_TV, MSGL_DBG2, "Video fd: %d, %x\n", priv->video_fd,
 	priv->video_device);
@@ -198,7 +360,7 @@
 	goto err;
     }
     
-    priv->fps = 25; /* pal */
+    priv->fps = PAL_FPS; /* pal */
     
     /* get capabilities (priv->capability is needed!) */
     if (ioctl(priv->video_fd, VIDIOCGCAP, &priv->capability) == -1)
@@ -207,6 +369,25 @@
 	goto err;
     }
 
+    if (ioctl(priv->video_fd, VIDIOCGTUNER, &priv->tuner) == -1)
+    {
+	mp_msg(MSGT_TV, MSGL_ERR, "ioctl get tuner failed: %s\n", strerror(errno));
+	goto err;
+    }
+
+    switch (priv->tuner.mode) {
+    case VIDEO_MODE_PAL:
+    case VIDEO_MODE_SECAM:
+	priv->fps = PAL_FPS;
+	break;
+    case VIDEO_MODE_NTSC:
+	priv->fps = NTSC_FPS;
+	break;
+    default:
+	mp_msg(MSGT_TV, MSGL_ERR, "get tuner returned an unknown mode: %d\n", priv->tuner.mode);
+	goto err;
+    }
+
     fcntl(priv->video_fd, F_SETFD, FD_CLOEXEC);
 
     mp_msg(MSGT_TV, MSGL_INFO, "Selected device: %s\n", priv->capability.name);
@@ -245,66 +426,6 @@
 	    priv->channels[i].norm);
     }
 
-    /* audio chanlist */
-    if (priv->capability.audios)
-    {
-	mp_msg(MSGT_TV, MSGL_INFO, " Audio devices: %d\n", priv->capability.audios);
-
-	for (i = 0; i < priv->capability.audios; i++)
-	{
-	    if (i >= MAX_AUDIO_CHANNELS)
-	    {
-		mp_msg(MSGT_TV, MSGL_ERR, "no space for more audio channels (incrase in source!) (%d > %d)\n",
-		    i, MAX_AUDIO_CHANNELS);
-		i = priv->capability.audios;
-		break;
-	    }
-
-	    priv->audio[i].audio = i;
-	    if (ioctl(priv->video_fd, VIDIOCGAUDIO, &priv->audio[i]) == -1)
-	    {
-		mp_msg(MSGT_TV, MSGL_ERR, "ioctl get audio failed: %s\n", strerror(errno));
-		break;
-	    }
-	    
-	    if (priv->audio[i].volume <= 0)
-		priv->audio[i].volume = 100;
-	    priv->audio[i].flags &= ~VIDEO_AUDIO_MUTE;
-	    ioctl(priv->video_fd, VIDIOCSAUDIO, &priv->audio[i]);
-	    
-	    switch(priv->audio[i].mode)
-	    {
-		case VIDEO_SOUND_MONO:
-		case VIDEO_SOUND_LANG1:
-		case VIDEO_SOUND_LANG2:
-		    priv->audio_channels[i] = 1;
-		    break;
-		case VIDEO_SOUND_STEREO:
-		    priv->audio_channels[i] = 2;
-		    break;
-	    }
-	    
-	    priv->audio_format[i] = AFMT_S16_LE;
-	    priv->audio_samplerate[i] = 44100;
-	    priv->audio_samplesize[i] =
-		priv->audio_samplerate[i]/8/priv->fps*
-		priv->audio_channels[i];
-
-	    /* display stuff */
-	    mp_msg(MSGT_TV, MSGL_V, "  %d: %s: ", priv->audio[i].audio,
-		priv->audio[i].name);
-	    if (priv->audio[i].flags & VIDEO_AUDIO_MUTABLE)
-		mp_msg(MSGT_TV, MSGL_V, "muted=%s ",
-		    (priv->audio[i].flags & VIDEO_AUDIO_MUTE) ? "yes" : "no");
-	    mp_msg(MSGT_TV, MSGL_V, "volume=%d bass=%d treble=%d balance=%d mode=%s\n",
-		priv->audio[i].volume, priv->audio[i].bass, priv->audio[i].treble,
-		priv->audio[i].balance, audio_mode2name[priv->audio[i].mode]);
-	    mp_msg(MSGT_TV, MSGL_V, " channels: %d, samplerate: %d, samplesize: %d, format: %s\n",
-		priv->audio_channels[i], priv->audio_samplerate[i], priv->audio_samplesize[i],
-		audio_out_format_name(priv->audio_format[i]));
-	}
-    }
-
     if (!(priv->capability.type & VID_TYPE_CAPTURE))
     {
 	mp_msg(MSGT_TV, MSGL_ERR, "Only grabbing supported (for overlay use another program)\n");
@@ -338,88 +459,35 @@
 	goto malloc_failed;
     memset(priv->buf, 0, priv->nbuf * sizeof(struct video_mmap));
     
-    /* audio init */
-#if 1
-    priv->audio_fd = open(priv->audio_device, O_RDONLY);
-    if (priv->audio_fd < 0)
-    {
-	mp_msg(MSGT_TV, MSGL_ERR, "unable to open '%s': %s\n",
-	    priv->audio_device, strerror(errno));
-    }
-    else
-    {
-	int ioctl_param;
-	
-	fcntl(priv->audio_fd, F_SETFL, O_NONBLOCK);
+    /* init v4l audio even when we don't capture */
+    init_v4l_audio(priv);
 
-#if 0
-	ioctl_param = 0x7fff000d; /* 8k */
-	printf("ioctl dsp setfragment: %d\n",
-	    ioctl(priv->audio_fd, SNDCTL_DSP_SETFRAGMENT, &ioctl_param));	
-#endif
+    if (!priv->capability.audios) tv_param_noaudio = 1;
 
-	ioctl_param = 0 ;
-	printf("ioctl dsp getfmt: %d\n",
-	    ioctl(priv->audio_fd, SNDCTL_DSP_GETFMTS, &ioctl_param));
+    /* audio init */
+    if (!tv_param_noaudio) {
+	int err;
 	
-	printf("Supported formats: %x\n", ioctl_param);
-	if (!(ioctl_param & priv->audio_format[priv->audio_id]))
-	    printf("notsupported format\n");
-
-	ioctl_param = priv->audio_format[priv->audio_id];
-	printf("ioctl dsp setfmt: %d\n",
-	    ioctl(priv->audio_fd, SNDCTL_DSP_SETFMT, &ioctl_param));
-
-//	ioctl(priv->audio_fd, SNDCTL_DSP_GETISPACE, &ioctl_param);
-//	printf("getispace: %d\n", ioctl_param);
-
-	if (priv->audio_channels[priv->audio_id] > 2)
-	{
-	    ioctl_param = priv->audio_channels[priv->audio_id];
-	    printf("ioctl dsp channels: %d\n",
-		ioctl(priv->audio_fd, SNDCTL_DSP_CHANNELS, &ioctl_param));
-	}
+#ifdef HAVE_ALSA9
+	if (tv_param_alsa)
+	    audio_in_init(&priv->audio_in, AUDIO_IN_ALSA);
 	else
-	{
-//	    if (priv->audio_channels[priv->audio_id] == 2)
-//		ioctl_param = 1;
-//	    else
-//		ioctl_param = 0;
-	
-	    ioctl_param = (priv->audio_channels[priv->audio_id] == 2);
-	    printf("ioctl dsp stereo: %d (req: %d)\n",
-		ioctl(priv->audio_fd, SNDCTL_DSP_STEREO, &ioctl_param),
-		ioctl_param);
-	}
-	
-	ioctl_param = priv->audio_samplerate[priv->audio_id];
-	printf("ioctl dsp speed: %d\n",
-	    ioctl(priv->audio_fd, SNDCTL_DSP_SPEED, &ioctl_param));
-
-#if 0
-	ioctl_param = 0;
-	ioctl_param = ~PCM_ENABLE_INPUT;
-	printf("ioctl dsp trigger: %d\n",
-	    ioctl(priv->audio_fd, SNDCTL_DSP_SETTRIGGER, &ioctl_param));
-	ioctl_param = PCM_ENABLE_INPUT;
-	printf("ioctl dsp trigger: %d\n",
-	    ioctl(priv->audio_fd, SNDCTL_DSP_SETTRIGGER, &ioctl_param));
+	    audio_in_init(&priv->audio_in, AUDIO_IN_OSS);
+#else
+	audio_in_init(&priv->audio_in, AUDIO_IN_OSS);
 #endif
 
-	printf("ioctl dsp trigger: %d\n",
-	    ioctl(priv->audio_fd, SNDCTL_DSP_GETTRIGGER, &ioctl_param));
-	printf("trigger: %x\n", ioctl_param);
-	ioctl_param = PCM_ENABLE_INPUT;
-	printf("ioctl dsp trigger: %d\n",
-	    ioctl(priv->audio_fd, SNDCTL_DSP_SETTRIGGER, &ioctl_param));
-
-	printf("ioctl dsp getblocksize: %d\n",
-	    ioctl(priv->audio_fd, SNDCTL_DSP_GETBLKSIZE, &priv->audio_blocksize));
-	printf("blocksize: %d\n", priv->audio_blocksize);
+	if (tv_param_audio_id < priv->capability.audios)
+	    priv->audio_id = tv_param_audio_id;
+	else
+	    priv->audio_id = 0;
+	audio_in_set_samplerate(&priv->audio_in, 44100);
+	audio_in_set_channels(&priv->audio_in, priv->audio_channels[priv->audio_id]);
+	if (audio_in_setup(&priv->audio_in) < 0) return 0;
+	setup_audio_buffer_sizes(priv);
     }
-#endif    
-    return(1);
 
+    return(1);
 
 malloc_failed:
     if (priv->channels)
@@ -434,20 +502,68 @@
 
 static int uninit(priv_t *priv)
 {
-    close(priv->video_fd);
+    priv->shutdown = 1;
+
+    mp_msg(MSGT_TV, MSGL_INFO, "Waiting for threads to finish... ");
+    if (!tv_param_noaudio) {
+	pthread_join(priv->audio_grabber_thread, NULL);
+	pthread_mutex_destroy(&priv->audio_starter);
+	pthread_mutex_destroy(&priv->skew_mutex);
+    }
+    pthread_join(priv->video_grabber_thread, NULL);
+    mp_msg(MSGT_TV, MSGL_INFO, "done\n");
 
     priv->audio[priv->audio_id].volume = 0;
     priv->audio[priv->audio_id].flags |= VIDEO_AUDIO_MUTE;
     ioctl(priv->video_fd, VIDIOCSAUDIO, &priv->audio[priv->audio_id]);
-    close(priv->audio_fd);
+
+    close(priv->video_fd);
+
+    audio_in_uninit(&priv->audio_in);
+
+    if (priv->video_ringbuffer)
+	free(priv->video_ringbuffer);
+    if (priv->video_timebuffer)
+	free(priv->video_timebuffer);
+    if (!tv_param_noaudio) {
+	if (priv->audio_ringbuffer)
+	    free(priv->audio_ringbuffer);
+	if (priv->audio_skew_buffer)
+	    free(priv->audio_skew_buffer);
+    }
 
     return(1);
 }
 
+static int get_capture_buffer_size(priv_t *priv)
+{
+    int bufsize, cnt;
+#ifdef HAVE_SYS_SYSINFO_H
+    struct sysinfo si;
+    
+    sysinfo(&si);
+    if (si.totalram<2*1024*1024) {
+	bufsize = 1024*1024;
+    } else {
+	bufsize = si.totalram/2;
+    }
+#else
+    bufsize = 16*1024*1024;
+#endif
+
+    cnt = bufsize/(priv->width*priv->bytesperline);
+    if (cnt < 2) cnt = 2;
+    
+    mp_msg(MSGT_TV, MSGL_INFO, "Allocating a ring buffer for %d frames, %d MB total size.\n",
+	   cnt, cnt*priv->width*priv->bytesperline/(1024*1024));
+
+    return cnt;
+}
+
 static int start(priv_t *priv)
 {
     int i;
-
+    int bytes_per_sample;
     
     if (ioctl(priv->video_fd, VIDIOCGPICT, &priv->picture) == -1)
     {
@@ -457,14 +573,12 @@
 
     priv->picture.palette = format2palette(priv->format);
     priv->picture.depth = palette2depth(priv->picture.palette);
-    priv->bytesperline = priv->width * priv->picture.depth / 8;
-//    if (IMGFMT_IS_BGR(priv->format) || IMGFMT_IS_RGB(priv->format))
-//	priv->bytesperline = priv->width * priv->picture.depth / 8;
-//    if ((priv->format == IMGFMT_YV12) || (priv->format == IMGFMT_I420) || (priv->format == IMGFMT_IYUV))
-//	priv->bytesperline = priv->width * 3 / 2;
 
-    printf("palette: %d, depth: %d, bytesperline: %d\n",
-	priv->picture.palette, priv->picture.depth, priv->bytesperline);
+    if (priv->format != IMGFMT_BGR15) {
+	priv->bytesperline = priv->width * priv->picture.depth / 8;
+    } else {
+	priv->bytesperline = priv->width * 2;
+    }
 
     mp_msg(MSGT_TV, MSGL_INFO, "Picture values:\n");
     mp_msg(MSGT_TV, MSGL_INFO, " Depth: %d, Palette: %d (Format: %s)\n", priv->picture.depth,
@@ -520,26 +634,94 @@
 	ioctl(priv->video_fd, VIDIOCSWIN, &win);
     }
 
-    /* start capture */
+    // initialize video capture
     if (ioctl(priv->video_fd, VIDIOCCAPTURE, &one) == -1)
     {
-	mp_msg(MSGT_TV, MSGL_ERR, "ioctl capture failed: %s\n", strerror(errno));
+	mp_msg(MSGT_TV, MSGL_ERR, "FATAL: ioctl ccapture failed: %s\n", strerror(errno));
 	return(0);
     }
 #endif
 
-    {
-      struct timeval curtime;
-      gettimeofday(&curtime, NULL);
-      priv->starttime=curtime.tv_sec + curtime.tv_usec*.000001;
+    /* setup audio parameters */
+    if (!tv_param_noaudio) {
+	setup_audio_buffer_sizes(priv);
+	bytes_per_sample = priv->audio_in.bytes_per_sample;
+	priv->audio_skew_buffer = (double*)malloc(sizeof(double)*priv->aud_skew_cnt);
+	if (!priv->audio_skew_buffer) {
+	    mp_msg(MSGT_TV, MSGL_ERR, "cannot allocate skew buffer: %s\n", strerror(errno));
+	    return 0;
+	}
+
+	priv->audio_ringbuffer = (unsigned char*)malloc(priv->audio_in.blocksize*priv->audio_buffer_size);
+	if (!priv->audio_ringbuffer) {
+	    mp_msg(MSGT_TV, MSGL_ERR, "cannot allocate audio buffer: %s\n", strerror(errno));
+	    return 0;
+	}
+
+	priv->audio_secs_per_block = (double)priv->audio_in.blocksize/(priv->audio_in.samplerate
+								    *priv->audio_in.channels
+								    *bytes_per_sample);
+	priv->audio_head = 0;
+	priv->audio_tail = 0;
+	priv->audio_cnt = 0;
+	priv->audio_drop = 0;
+	priv->audio_skew = 0.0;
+	priv->audio_skew_total = 0.0;
+	priv->audio_recv_blocks_total = 0;
+	priv->audio_sent_blocks_total = 0;
+    }
+
+    /* setup video parameters */
+    if (priv->immediate_mode) {
+	priv->video_buffer_size = VID_BUF_SIZE_IMMEDIATE;
+    } else {
+	priv->video_buffer_size = get_capture_buffer_size(priv);
+    }
+
+    if (!tv_param_noaudio) {
+	if (priv->video_buffer_size < 3.0*priv->fps*priv->audio_secs_per_block) {
+	    mp_msg(MSGT_TV, MSGL_ERR, "Video buffer shorter than 3 times audio frame duration.\n"
+		   "You will probably experience heavy framedrops.\n");
+	}
+    }
+
+    priv->video_ringbuffer = (unsigned char*)malloc(priv->bytesperline * priv->height * priv->video_buffer_size);
+    if (!priv->video_ringbuffer) {
+	mp_msg(MSGT_TV, MSGL_ERR, "cannot allocate video buffer: %s\n", strerror(errno));
+	return 0;
+    }
+    priv->video_timebuffer = (double*)malloc(sizeof(double) * priv->video_buffer_size);
+    if (!priv->video_timebuffer) {
+	mp_msg(MSGT_TV, MSGL_ERR, "cannot allocate time buffer: %s\n", strerror(errno));
+	return 0;
+    }
+    priv->video_head = 0;
+    priv->video_tail = 0;
+    priv->video_cnt = 0;
+    priv->first = 1;
+
+    /* enable audio */
+    if (priv->audio[priv->audio_id].volume <= 0)
+	priv->audio[priv->audio_id].volume = 100;
+    priv->audio[priv->audio_id].flags &= ~VIDEO_AUDIO_MUTE;
+    ioctl(priv->video_fd, VIDIOCSAUDIO, &priv->audio[priv->audio_id]);
+	    
+    /* launch capture threads */
+    priv->shutdown = 0;
+    if (!tv_param_noaudio) {
+	pthread_mutex_init(&priv->audio_starter, NULL);
+	pthread_mutex_init(&priv->skew_mutex, NULL);
+	pthread_mutex_lock(&priv->audio_starter);
+	pthread_create(&priv->audio_grabber_thread, NULL, audio_grabber, priv);
     }
+    /* we'll launch the video capture later, when a first request for a frame arrives */
 
     return(1);
 }
 
 static int control(priv_t *priv, int cmd, void *arg)
 {
-    mp_msg(MSGT_TV, MSGL_DBG2, "debug: control(priv=%p, cmd=%d, arg=%p)\n",
+    mp_msg(MSGT_TV, MSGL_DBG2, "\ndebug: control(priv=%p, cmd=%d, arg=%p)\n",
 	priv, cmd, arg);
     switch(cmd)
     {
@@ -576,6 +758,14 @@
 	}
 	case TVI_CONTROL_VID_SET_FORMAT:
 	    priv->format = (int)*(void **)arg;
+	    // !HACK! v4l uses BGR format instead of RGB
+	    // and we have to correct this. Fortunately,
+	    // tv.c reads later the format back so we
+	    // can persuade it to use what we want.
+	    if (IMGFMT_IS_RGB(priv->format)) {
+		priv->format &= ~IMGFMT_RGB_MASK;
+		priv->format |= IMGFMT_BGR;
+	    }
 	    return(TVI_CONTROL_TRUE);
 	case TVI_CONTROL_VID_GET_PLANES:
 	    (int)*(void **)arg = 1; /* FIXME, also not needed at this time */
@@ -682,6 +872,7 @@
 		mp_msg(MSGT_TV, MSGL_ERR, "ioctl set freq failed: %s\n", strerror(errno));
 		return(TVI_CONTROL_FALSE);
 	    }
+	    usleep(100000); // wait to supress noise during switching
 	    return(TVI_CONTROL_TRUE);
 	}
 	case TVI_CONTROL_TUN_GET_TUNER:
@@ -700,7 +891,7 @@
 	{
 	    if (ioctl(priv->video_fd, VIDIOCSTUNER, &priv->tuner) == -1)
 	    {
-		mp_msg(MSGT_TV, MSGL_ERR, "ioctl get tuner failed: %s\n", strerror(errno));
+		mp_msg(MSGT_TV, MSGL_ERR, "ioctl set tuner failed: %s\n", strerror(errno));
 		return(TVI_CONTROL_FALSE);
 	    }
 	    return(TVI_CONTROL_TRUE);
@@ -708,20 +899,57 @@
 	case TVI_CONTROL_TUN_SET_NORM:
 	{
 	    int req_mode = (int)*(void **)arg;
-	    
-	    if ((!(priv->tuner.flags & VIDEO_TUNER_NORM)) ||
-		((req_mode == VIDEO_MODE_PAL) && !(priv->tuner.flags & VIDEO_TUNER_PAL)) ||
-		((req_mode == VIDEO_MODE_NTSC) && !(priv->tuner.flags & VIDEO_TUNER_NTSC)) ||
-		((req_mode == VIDEO_MODE_SECAM) && !(priv->tuner.flags & VIDEO_TUNER_SECAM)))
+
+	    if ((req_mode != TV_NORM_PAL) && (req_mode != TV_NORM_NTSC) && (req_mode != TV_NORM_SECAM)) {
+		mp_msg(MSGT_TV, MSGL_ERR, "Unknown norm!\n");
+		return(TVI_CONTROL_FALSE);
+	    }
+
+	    if (((req_mode == TV_NORM_PAL) && !(priv->tuner.flags & VIDEO_TUNER_PAL)) ||
+		((req_mode == TV_NORM_NTSC) && !(priv->tuner.flags & VIDEO_TUNER_NTSC)) ||
+		((req_mode == TV_NORM_SECAM) && !(priv->tuner.flags & VIDEO_TUNER_SECAM)))
 	    {
 		mp_msg(MSGT_TV, MSGL_ERR, "Tuner isn't capable to set norm!\n");
 		return(TVI_CONTROL_FALSE);
 	    }
 
-	    priv->tuner.mode = req_mode;
+	    switch(req_mode) {
+	    case TV_NORM_PAL:
+		priv->tuner.mode = VIDEO_MODE_PAL;
+		break;
+	    case TV_NORM_NTSC:
+		priv->tuner.mode = VIDEO_MODE_NTSC;
+		break;
+	    case TV_NORM_SECAM:
+		priv->tuner.mode = VIDEO_MODE_SECAM;
+		break;
+	    }
 	    
-	    if (control(priv, TVI_CONTROL_TUN_SET_TUNER, &priv->tuner) != TVI_CONTROL_TRUE)
+	    if (control(priv, TVI_CONTROL_TUN_SET_TUNER, &priv->tuner) != TVI_CONTROL_TRUE) {
+		return(TVI_CONTROL_FALSE);
+	    }
+
+	    if (ioctl(priv->video_fd, VIDIOCGCAP, &priv->capability) == -1) {
+		mp_msg(MSGT_TV, MSGL_ERR, "ioctl get capabilites failed: %s\n", strerror(errno));
 		return(TVI_CONTROL_FALSE);
+	    }
+
+	    if(req_mode == TV_NORM_PAL || req_mode == TV_NORM_SECAM) {
+		priv->fps = PAL_FPS;
+            }
+
+	    if(req_mode == TV_NORM_NTSC) {
+		priv->fps = NTSC_FPS;
+            }
+
+	    if(priv->height > priv->capability.maxheight) {
+		priv->height = priv->capability.maxheight;
+	    }
+
+	    if(priv->width > priv->capability.maxwidth) {
+		priv->width = priv->capability.maxwidth;
+	    }
+	    
 	    return(TVI_CONTROL_TRUE);
 	}
 	case TVI_CONTROL_TUN_GET_NORM:
@@ -734,33 +962,28 @@
 	/* ========== AUDIO controls =========== */
 	case TVI_CONTROL_AUD_GET_FORMAT:
 	{
-	    (int)*(void **)arg = priv->audio_format[priv->audio_id];
+	    (int)*(void **)arg = AFMT_S16_LE;
 	    return(TVI_CONTROL_TRUE);
 	}
 	case TVI_CONTROL_AUD_GET_CHANNELS:
 	{
-	    (int)*(void **)arg = priv->audio_channels[priv->audio_id];
+	    (int)*(void **)arg = priv->audio_in.channels;
 	    return(TVI_CONTROL_TRUE);
 	}
 	case TVI_CONTROL_AUD_GET_SAMPLERATE:
 	{
-	    (int)*(void **)arg = priv->audio_samplerate[priv->audio_id];
+	    (int)*(void **)arg = priv->audio_in.samplerate;
 	    return(TVI_CONTROL_TRUE);
 	}
 	case TVI_CONTROL_AUD_GET_SAMPLESIZE:
 	{
-	    (int)*(void **)arg = priv->audio_samplesize[priv->audio_id]/8;
+	    (int)*(void **)arg = priv->audio_in.bytes_per_sample;
 	    return(TVI_CONTROL_TRUE);
 	}
 	case TVI_CONTROL_AUD_SET_SAMPLERATE:
 	{
-	    int tmp = priv->audio_samplerate[priv->audio_id] = (int)*(void **)arg;
-	    
-	    if (ioctl(priv->audio_fd, SNDCTL_DSP_SPEED, &tmp) == -1)
-		return(TVI_CONTROL_FALSE);
-	    priv->audio_samplesize[priv->audio_id] =
-		priv->audio_samplerate[priv->audio_id]/8/priv->fps*
-		priv->audio_channels[priv->audio_id];
+	    if (audio_in_set_samplerate(&priv->audio_in, (int)*(void **)arg) < 0) return TVI_CONTROL_FALSE;
+	    setup_audio_buffer_sizes(priv);
 	    return(TVI_CONTROL_TRUE);
 	}
 	/* ========== SPECIFIC controls =========== */
@@ -821,50 +1044,189 @@
 	    /* update local channel list */	
 	    control(priv, TVI_CONTROL_SPC_GET_INPUT, &req_chan);
 	    return(TVI_CONTROL_TRUE);
+	case TVI_CONTROL_IMMEDIATE:
+	    priv->immediate_mode = 1;
+	    return(TVI_CONTROL_TRUE);
 	}
     }
 
     return(TVI_CONTROL_UNKNOWN);
 }
 
-static double grab_video_frame(priv_t *priv, char *buffer, int len)
+// copies a video frame
+// for RGB (i.e. BGR in mplayer) flips the image upside down
+// for YV12 swaps the 2nd and 3rd plane
+static inline void copy_frame(priv_t *priv, unsigned char *dest, unsigned char *source)
 {
+    int i;
+    unsigned char *sptr;
+
+    // YV12 uses VIDEO_PALETTE_YUV420P, but the planes are swapped
+    if (priv->format == IMGFMT_YV12) {
+	memcpy(dest, source, priv->width * priv->height);
+	memcpy(dest+priv->width * priv->height*5/4, source+priv->width * priv->height, priv->width * priv->height/4);
+	memcpy(dest+priv->width * priv->height, source+priv->width * priv->height*5/4, priv->width * priv->height/4);
+	return;
+    }
+
+    switch (priv->picture.palette) {
+    case VIDEO_PALETTE_RGB24:
+    case VIDEO_PALETTE_RGB32:
+    case VIDEO_PALETTE_RGB555:
+    case VIDEO_PALETTE_RGB565:
+	sptr = source + (priv->height-1)*priv->bytesperline;
+	for (i = 0; i < priv->height; i++) {
+	    memcpy(dest, sptr, priv->bytesperline);
+	    dest += priv->bytesperline;
+	    sptr -= priv->bytesperline;
+	}
+	break;
+    case VIDEO_PALETTE_UYVY:
+    case VIDEO_PALETTE_YUV420P:
+    default:
+	memcpy(dest, source, priv->bytesperline * priv->height);
+    }
+    
+}
+
+// maximum skew change, in frames
+#define MAX_SKEW_DELTA 0.6
+static void *video_grabber(void *data)
+{
+    priv_t *priv = (priv_t*)data;
     struct timeval curtime;
-    double timestamp;
-    int frame = priv->queue % priv->nbuf;
-    int nextframe = (priv->queue+1) % priv->nbuf;
+    double timestamp, skew, prev_skew, xskew, interval, prev_interval;
+    int frame, nextframe;
+    int fsize = priv->bytesperline * priv->height;
+    int i;
+    int first = 1;
 
-    mp_dbg(MSGT_TV, MSGL_DBG2, "grab_video_frame(priv=%p, buffer=%p, len=%d)\n",
-	priv, buffer, len);
+    int dropped = 0;
+    double dropped_time;
+    double drop_delta = 0.0;
 
-    mp_dbg(MSGT_TV, MSGL_DBG3, "buf: %p + frame: %d => %p\n",
-	priv->buf, nextframe, &priv->buf[nextframe]);
-    if (ioctl(priv->video_fd, VIDIOCMCAPTURE, &priv->buf[nextframe]) == -1)
+    /* start the capture process */
+    if (ioctl(priv->video_fd, VIDIOCMCAPTURE, &priv->buf[0]) == -1)
     {
-	mp_msg(MSGT_TV, MSGL_ERR, "ioctl mcapture failed: %s\n", strerror(errno));
-	return(0);
+	mp_msg(MSGT_TV, MSGL_ERR, "\nioctl mcapture failed: %s\n", strerror(errno));
     }
+    while (ioctl(priv->video_fd, VIDIOCSYNC, &priv->buf[1].frame) < 0 &&
+	   (errno == EAGAIN || errno == EINTR));
+    mp_dbg(MSGT_TV, MSGL_DBG3, "\npicture sync failed\n");
 
-    while (ioctl(priv->video_fd, VIDIOCSYNC, &priv->buf[frame].frame) < 0 &&
-	(errno == EAGAIN || errno == EINTR));
-	mp_dbg(MSGT_TV, MSGL_DBG3, "picture sync failed\n");
+    prev_interval = 0.0;
+    prev_skew = priv->audio_skew;
 
-    priv->queue++;
-    
-    gettimeofday(&curtime, NULL);
-    timestamp=curtime.tv_sec + curtime.tv_usec*.000001;
+    for (;!priv->shutdown;)
+    {
+	for (i = 0; i < priv->nbuf && !priv->shutdown; i++) {
+	    frame = i;
+	    nextframe = (i+1)%priv->nbuf;
+	    
+	    if (ioctl(priv->video_fd, VIDIOCMCAPTURE, &priv->buf[nextframe]) == -1)
+	    {
+		mp_msg(MSGT_TV, MSGL_ERR, "\nioctl mcapture failed: %s\n", strerror(errno));
+		continue;
+	    }
+	    
+	    while (ioctl(priv->video_fd, VIDIOCSYNC, &priv->buf[frame].frame) < 0 &&
+		   (errno == EAGAIN || errno == EINTR));
+	    mp_dbg(MSGT_TV, MSGL_DBG3, "\npicture sync failed\n");
+
+	    gettimeofday(&curtime, NULL);
+	    if (first) {
+		// this was a first frame - let's launch the audio capture thread immediately
+		// before that, just initialize some variables
+		priv->starttime = curtime.tv_sec + curtime.tv_usec*.000001;
+		priv->audio_skew_measure_time = 0;
+		pthread_mutex_unlock(&priv->audio_starter);
+		first = 0;
+	    }
+
+	    interval = curtime.tv_sec + curtime.tv_usec*.000001 - priv->starttime;
+
+	    if (!priv->immediate_mode && (
+		    ((interval - prev_interval < 1.0/priv->fps*0.85) && interval > 0.0001)
+		    || (interval - prev_interval > 1.0/priv->fps*1.15) ) ) {
+		mp_msg(MSGT_TV, MSGL_V, "\nvideo capture thread: frame delta ~ %.1lf fps\n",
+		       1.0/(interval - prev_interval));
+	    }
+
+	    // interpolate the skew in time
+	    pthread_mutex_lock(&priv->skew_mutex);
+	    xskew = priv->audio_skew + (interval - priv->audio_skew_measure_time)*priv->audio_skew_factor;
+	    pthread_mutex_unlock(&priv->skew_mutex);
+	    // correct extreme skew changes to avoid (especially) moving backwards in time
+	    if (xskew - prev_skew > (interval - prev_interval)*MAX_SKEW_DELTA) {
+		skew = prev_skew + (interval - prev_interval)*MAX_SKEW_DELTA;
+	    } else if (xskew - prev_skew < -(interval - prev_interval)*MAX_SKEW_DELTA) {
+		skew = prev_skew - (interval - prev_interval)*MAX_SKEW_DELTA;
+	    } else {
+		skew = xskew;
+	    }
+
+	    mp_msg(MSGT_TV, MSGL_DBG3, "\nfps = %lf, v_interval = %lf, a_skew = %f, corr_skew = %f\n",
+		   1.0/(interval - prev_interval), interval/2, xskew, skew);
+	    mp_msg(MSGT_TV, MSGL_DBG3, "vcnt = %d, acnt = %d\n", priv->video_cnt, priv->audio_cnt);
+
+	    prev_skew = skew;
+	    prev_interval = interval;
+	    
+	    if ((priv->video_tail+1) % priv->video_buffer_size == priv->video_head) {
 
-    mp_dbg(MSGT_TV, MSGL_DBG3, "mmap: %p + offset: %d => %p\n",
-	priv->mmap, priv->mbuf.offsets[frame],
-	priv->mmap+priv->mbuf.offsets[frame]);
+		if (!priv->immediate_mode) {
+		    mp_msg(MSGT_TV, MSGL_ERR, "\nvideo buffer full - dropping frame\n");
+		} else {
+		    if (!dropped) {
+			dropped = 1;
+			dropped_time = interval - skew;
+		    }
+		}
+	    } else {
+		if (priv->immediate_mode) {
+		    if (dropped) {
+			drop_delta += interval - skew - dropped_time;
+			dropped = 0;
+		    }
+		    // compensate for audio skew
+		    // negative skew => there are more audio samples, increase interval
+		    // positive skew => less samples, shorten the interval
+		    
+		    // for TV, we pretend that dropped frames never existed
+		    // without this, mplayer gets confused after pressing pause
+		    priv->video_timebuffer[priv->video_tail] = interval - skew - drop_delta;
+		} else {
+		    priv->video_timebuffer[priv->video_tail] = interval - skew;
+		}
+		
+		copy_frame(priv, priv->video_ringbuffer+(priv->video_tail)*fsize, priv->mmap+priv->mbuf.offsets[frame]);
+		priv->video_tail = (priv->video_tail+1)%priv->video_buffer_size;
+		priv->video_cnt++;
+	    }
 
-    /* XXX also directrendering would be nicer! */
-    /* 3 times copying the same picture to other buffer :( */
+	}
 
-    /* copy the actual frame */
-    memcpy(buffer, priv->mmap+priv->mbuf.offsets[frame], len);
+    }
+}
 
-    return(timestamp-priv->starttime);
+static double grab_video_frame(priv_t *priv, char *buffer, int len)
+{
+    double interval;
+
+    if (priv->first) {
+	pthread_create(&priv->video_grabber_thread, NULL, video_grabber, priv);
+	priv->first = 0;
+    }
+
+    while (priv->video_head == priv->video_tail) {
+	usleep(10000);
+    }
+
+    interval = priv->video_timebuffer[priv->video_head];
+    memcpy(buffer, priv->video_ringbuffer+priv->video_head*priv->bytesperline * priv->height, len);
+    priv->video_cnt--;
+    priv->video_head = (++priv->video_head)%priv->video_buffer_size;
+    return interval;
 }
 
 static int get_video_framesize(priv_t *priv)
@@ -872,6 +1234,80 @@
     return(priv->bytesperline * priv->height);
 }
 
+static void *audio_grabber(void *data)
+{
+    priv_t *priv = (priv_t*)data;
+    struct timeval tv;
+    int ret;
+    int i, audio_skew_ptr = 0;
+    double tmp, current_time, current_skew, prev_skew = 0.0;
+
+    pthread_mutex_lock(&priv->audio_starter);
+
+    audio_in_start_capture(&priv->audio_in);
+    for (i = 0; i < priv->aud_skew_cnt; i++)
+	priv->audio_skew_buffer[i] = 0.0;
+
+    for (; !priv->shutdown;)
+    {
+	if (audio_in_read_chunk(&priv->audio_in, priv->audio_ringbuffer+priv->audio_tail*priv->audio_in.blocksize) < 0)
+	    continue;
+
+	gettimeofday(&tv, NULL);
+
+	priv->audio_recv_blocks_total++;
+	current_time = tv.tv_sec + tv.tv_usec*.000001 - priv->starttime;
+
+	// compute the moving sum of the skews
+	if (priv->audio_recv_blocks_total % 1024 == 0) {
+	    // recompute the moving sum to avoid truncation errors
+	    priv->audio_skew_buffer[audio_skew_ptr] = current_time
+		- priv->audio_secs_per_block*priv->audio_recv_blocks_total;
+	    audio_skew_ptr = (audio_skew_ptr+1) % priv->aud_skew_cnt;
+	    for (i = 0, tmp = 0.0; i < priv->aud_skew_cnt; i++)
+		tmp += priv->audio_skew_buffer[i];
+	    priv->audio_skew_total = tmp;
+	} else {
+	    priv->audio_skew_total -= priv->audio_skew_buffer[audio_skew_ptr];
+	    priv->audio_skew_buffer[audio_skew_ptr] = current_time
+		- priv->audio_secs_per_block*priv->audio_recv_blocks_total;
+	    priv->audio_skew_total += priv->audio_skew_buffer[audio_skew_ptr];
+	    audio_skew_ptr = (audio_skew_ptr+1) % priv->aud_skew_cnt;
+	}
+
+	pthread_mutex_lock(&priv->skew_mutex);
+	// linear interpolation - here we interpolate current skew value
+	// from the moving average, which we expect to be in the middle
+	// of the interval
+	if (priv->audio_recv_blocks_total > priv->aud_skew_cnt) {
+	    priv->audio_skew = priv->audio_skew_total/priv->aud_skew_cnt;
+	    priv->audio_skew += (priv->audio_skew*priv->aud_skew_cnt)/(2*priv->audio_recv_blocks_total-priv->aud_skew_cnt);
+	} else {
+//	    priv->audio_skew = 2*priv->audio_skew_total/priv->aud_skew_cnt;
+	    priv->audio_skew = (priv->aud_skew_cnt+priv->audio_recv_blocks_total)/priv->aud_skew_cnt*priv->audio_skew_total/priv->audio_recv_blocks_total;
+//	    priv->audio_skew = current_time - priv->audio_secs_per_block*priv->audio_recv_blocks_total;
+	}
+	// current skew factor (assuming linearity)
+	// used for further interpolation in video_grabber
+	// probably overkill but seems to be necessary for
+	// stress testing by dropping half of the audio frames ;)
+	// especially when using ALSA with large block sizes
+	// where audio_skew remains a long while behind
+	priv->audio_skew_factor = (priv->audio_skew-prev_skew)/(current_time - priv->audio_skew_measure_time);
+	priv->audio_skew_measure_time = current_time;
+	prev_skew = priv->audio_skew;
+	pthread_mutex_unlock(&priv->skew_mutex);
+	
+	if ((priv->audio_tail+1) % priv->audio_buffer_size == priv->audio_head) {
+	    mp_msg(MSGT_TV, MSGL_ERR, "\ntoo bad - dropping audio frame !\n");
+	    priv->audio_drop++;
+	} else {
+	    priv->audio_tail = (++priv->audio_tail) % priv->audio_buffer_size;
+	    priv->audio_cnt++;
+	}
+    }
+}
+
 static double grab_audio_frame(priv_t *priv, char *buffer, int len)
 {
     int in_len = 0;
@@ -879,30 +1315,28 @@
 
     mp_dbg(MSGT_TV, MSGL_DBG2, "grab_audio_frame(priv=%p, buffer=%p, len=%d)\n",
 	priv, buffer, len);
-    
-    while (--max_tries > 0)
-//    for (;;)
-    {
-	in_len = read(priv->audio_fd, buffer, len);
-//	printf("in_len: %d\n", in_len);
-//	fflush(NULL);
-
-	if (in_len > 0)
-	    break;
-	if (!((in_len == 0) || (in_len == -1 && (errno == EAGAIN || errno == EINTR))))
-	{
-	    in_len = 0; /* -EIO */
-	    break;
-	}
-    }
 
-    return 0; //(in_len); // FIXME!
+    // compensate for dropped audio frames
+    if (priv->audio_drop && (priv->audio_head == priv->audio_tail)) {
+	priv->audio_drop--;
+	priv->audio_sent_blocks_total++;
+	memset(buffer, 0, len);
+	return (double)priv->audio_sent_blocks_total*priv->audio_secs_per_block;
+    }
+
+    while (priv->audio_head == priv->audio_tail) {
+	usleep(10000);
+    }
+    memcpy(buffer, priv->audio_ringbuffer+priv->audio_head*priv->audio_in.blocksize, len);
+    priv->audio_head = (++priv->audio_head) % priv->audio_buffer_size;
+    priv->audio_cnt--;
+    priv->audio_sent_blocks_total++;
+    return (double)priv->audio_sent_blocks_total*priv->audio_secs_per_block;
 }
 
 static int get_audio_framesize(priv_t *priv)
 {
-    return(priv->audio_blocksize);
-//    return(priv->audio_samplesize[priv->audio_id]);
+    return(priv->audio_in.blocksize);
 }
 
 #endif /* USE_TV */
diff -urN --exclude-from dontdiff vanilla/main/mencoder.c main/mencoder.c
--- vanilla/main/mencoder.c	Thu Aug  8 18:06:26 2002
+++ main/mencoder.c	Fri Aug 16 19:11:19 2002
@@ -1126,7 +1126,7 @@
 	if(verbose) {
 		mp_msg(MSGT_AVSYNC,MSGL_STATUS,"Pos:%6.1fs %6df (%2d%%) %3dfps Trem:%4dmin %3dmb  A-V:%5.3f [%d:%d] A/Vms %d/%d D/S %d/%d \r",
 	    	mux_v->timer, decoded_frameno, (int)(p*100),
-	    	(t>1) ? (int)(decoded_frameno/t) : 0,
+	    	(t>1) ? (int)(decoded_frameno/t+0.5) : 0,
 	    	(p>0.001) ? (int)((t/p-t)/60) : 0, 
 	    	(p>0.001) ? (int)(ftello(muxer_f)/p/1024/1024) : 0,
 	    	v_pts_corr,
@@ -1138,7 +1138,7 @@
 	} else
 	mp_msg(MSGT_AVSYNC,MSGL_STATUS,"Pos:%6.1fs %6df (%2d%%) %3dfps Trem:%4dmin %3dmb  A-V:%5.3f [%d:%d]\r",
 	    mux_v->timer, decoded_frameno, (int)(p*100),
-	    (t>1) ? (int)(decoded_frameno/t) : 0,
+	    (t>1) ? (int)(decoded_frameno/t+0.5) : 0,
 	    (p>0.001) ? (int)((t/p-t)/60) : 0, 
 	    (p>0.001) ? (int)(ftell(muxer_f)/p/1024/1024) : 0,
 	    v_pts_corr,
@@ -1186,6 +1186,8 @@
  }
 
 } // while(!at_eof)
+
+if (demuxer) free_demuxer(demuxer);
 
 #ifdef HAVE_MP3LAME
 // fixup CBR mp3 audio header:
diff -urN --exclude-from dontdiff vanilla/main/mp_msg.c main/mp_msg.c
--- vanilla/main/mp_msg.c	Wed Jun  5 04:24:35 2002
+++ main/mp_msg.c	Fri Aug 16 19:11:19 2002
@@ -40,6 +40,11 @@
     }
 }
 
+int mp_msg_test(int mod, int lev)
+{
+    return lev <= mp_msg_levels[mod];
+}
+
 void mp_msg_c( int x, const char *format, ... ){
 #if 1
     va_list va;
diff -urN --exclude-from dontdiff vanilla/main/mp_msg.h main/mp_msg.h
--- vanilla/main/mp_msg.h	Tue Jun  4 01:23:02 2002
+++ main/mp_msg.h	Fri Aug 16 19:11:19 2002
@@ -85,6 +85,7 @@
 
 void mp_msg_init();
 void mp_msg_set_level(int verbose);
+int mp_msg_test(int mod, int lev);
 
 #include "config.h"
 
diff -urN --exclude-from dontdiff vanilla/main/mplayer.c main/mplayer.c
--- vanilla/main/mplayer.c	Fri Aug 16 18:02:28 2002
+++ main/mplayer.c	Fri Aug 16 19:11:19 2002
@@ -268,6 +268,8 @@
 
 static stream_t* stream=NULL;
 
+static demuxer_t *demuxer=NULL;
+
 char* current_module=NULL; // for debugging
 
 int vo_gamma_brightness = 1000;
@@ -291,6 +293,7 @@
 #define INITED_STREAM 64
 #define INITED_INPUT    128
 #define INITED_VOBSUB  256
+#define INITED_DEMUXER  512
 #define INITED_ALL 0xFFFF
 
 void uninit_player(unsigned int mask){
@@ -306,6 +309,12 @@
     stream=NULL;
   }
 
+  if(mask&INITED_DEMUXER){
+    current_module="uninit_demuxer";
+    if(demuxer) free_demuxer(demuxer);
+    demuxer=NULL;
+  }
+
   if(mask&INITED_VO){
     inited_flags&=~INITED_VO;
     current_module="uninit_vo";
@@ -489,8 +498,6 @@
 float sub_last_pts = -303;
 #endif
 
-static demuxer_t *demuxer=NULL;
-
 static demux_stream_t *d_audio=NULL;
 static demux_stream_t *d_video=NULL;
 static demux_stream_t *d_dvdsub=NULL;
@@ -565,9 +572,7 @@
 
 #endif
 
-#ifdef HAVE_TV_BSDBT848
   tv_param_immediate = 1;
-#endif
 
   if ( argv[0] )
     if(!strcmp(argv[0],"gmplayer") ||
@@ -1076,6 +1081,8 @@
 
 demuxer=demux_open(stream,file_format,audio_id,video_id,dvdsub_id);
 if(!demuxer) goto goto_next_file; // exit_player(MSGTR_Exit_error); // ERROR
+
+inited_flags|=INITED_DEMUXER;
 
 current_module="demux_open2";
 


More information about the MPlayer-dev-eng mailing list