alsa.c 33.5 KB
Newer Older
aymeric's avatar
aymeric committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/*
mediastreamer2 library - modular sound and video processing and streaming
Copyright (C) 2006  Simon MORLAT (simon.morlat@linphone.org)

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
17
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
aymeric's avatar
aymeric committed
18 19
*/

Simon Morlat's avatar
Simon Morlat committed
20 21 22
#if defined(HAVE_CONFIG_H)
#include "mediastreamer-config.h"
#endif
aymeric's avatar
aymeric committed
23 24 25 26 27

#include <alsa/asoundlib.h>


#include "mediastreamer2/msfilter.h"
28
#include "mediastreamer2/msticker.h"
aymeric's avatar
aymeric committed
29 30
#include "mediastreamer2/mssndcard.h"

31 32 33 34 35 36 37 38 39 40
static int forced_rate=-1;

void ms_alsa_card_set_forced_sample_rate(int samplerate){
	if (samplerate==0 || samplerate<-1) {
		ms_warning("ms_alsa_card_set_forced_sample_rate(): bad value %i",samplerate);
		return;
	}
	forced_rate=samplerate;
}

aymeric's avatar
aymeric committed
41 42 43 44 45 46 47 48 49 50 51 52
//#define THREADED_VERSION

/*in case of troubles with a particular driver, try incrementing ALSA_PERIOD_SIZE
to 512, 1024, 2048, 4096...
then try incrementing the number of periods*/
#define ALSA_PERIODS 8
#define ALSA_PERIOD_SIZE 256

/*uncomment the following line if you have problems with an alsa driver
having sound quality trouble:*/
/*#define EPIPE_BUGFIX 1*/

53
static MSSndCard * alsa_card_new(const char *id, const char *pcmbasename);
aymeric's avatar
aymeric committed
54
static MSSndCard *alsa_card_duplicate(MSSndCard *obj);
55 56
static MSFilter * ms_alsa_read_new(MSFactory *factory, const char *dev);
static MSFilter * ms_alsa_write_new(MSFactory *factory, const char *dev);
aymeric's avatar
aymeric committed
57 58 59 60 61 62 63 64 65 66


struct _AlsaData{
	char *pcmdev;
	char *mixdev;
};

typedef struct _AlsaData AlsaData;


Simon Morlat's avatar
Simon Morlat committed
67 68 69 70 71
static void alsa_resume(snd_pcm_t *handle){
	int err;
	snd_pcm_status_t *status=NULL;

	snd_pcm_status_alloca(&status);
72

Simon Morlat's avatar
Simon Morlat committed
73 74 75 76 77 78 79 80 81 82 83 84 85
	if ((err=snd_pcm_status(handle,status))!=0){
		ms_warning("snd_pcm_status() failed: %s",snd_strerror(err));
		return;
	}

	if (snd_pcm_status_get_state(status)==SND_PCM_STATE_SUSPENDED){
		ms_warning("Maybe suspended, trying resume");
		if ((err=snd_pcm_resume(handle))!=0){
			if (err!=EWOULDBLOCK) ms_warning("snd_pcm_resume() failed: %s",snd_strerror(err));
		}
	}
}

aymeric's avatar
aymeric committed
86 87 88 89 90 91 92 93 94 95
static int alsa_set_params(snd_pcm_t *pcm_handle, int rw, int bits, int stereo, int rate)
{
	snd_pcm_hw_params_t *hwparams=NULL;
	snd_pcm_sw_params_t *swparams=NULL;
	int dir;
	uint exact_uvalue;
	unsigned long exact_ulvalue;
	int channels;
	int periods=ALSA_PERIODS;
	int periodsize=ALSA_PERIOD_SIZE;
96
	snd_pcm_uframes_t buffersize;
aymeric's avatar
aymeric committed
97 98
	int err;
	int format;
99

aymeric's avatar
aymeric committed
100 101
	/* Allocate the snd_pcm_hw_params_t structure on the stack. */
	snd_pcm_hw_params_alloca(&hwparams);
102

aymeric's avatar
aymeric committed
103 104 105 106 107
	/* Init hwparams with full configuration space */
	if (snd_pcm_hw_params_any(pcm_handle, hwparams) < 0) {
		ms_warning("alsa_set_params: Cannot configure this PCM device.");
		return -1;
	}
108

aymeric's avatar
aymeric committed
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
	if (snd_pcm_hw_params_set_access(pcm_handle, hwparams, SND_PCM_ACCESS_RW_INTERLEAVED) < 0) {
		ms_warning("alsa_set_params: Error setting access.");
		return -1;
	}
	/* Set sample format */
	format=SND_PCM_FORMAT_S16;
	if (snd_pcm_hw_params_set_format(pcm_handle, hwparams, format) < 0) {
		ms_warning("alsa_set_params: Error setting format.");
		return -1;
	}
	/* Set number of channels */
	if (stereo) channels=2;
	else channels=1;
	if (snd_pcm_hw_params_set_channels(pcm_handle, hwparams, channels) < 0) {
		ms_warning("alsa_set_params: Error setting channels.");
		return -1;
	}
	/* Set sample rate. If the exact rate is not supported */
127
	/* by the hardware, use nearest possible rate.         */
aymeric's avatar
aymeric committed
128 129 130 131 132 133 134 135 136 137 138
	exact_uvalue=rate;
	dir=0;
	if ((err=snd_pcm_hw_params_set_rate_near(pcm_handle, hwparams, &exact_uvalue, &dir))<0){
		ms_warning("alsa_set_params: Error setting rate to %i:%s",rate,snd_strerror(err));
		return -1;
	}
	if (dir != 0) {
		ms_warning("alsa_set_params: The rate %d Hz is not supported by your hardware.\n "
		"==> Using %d Hz instead.", rate, exact_uvalue);
	}
	/* choose greater period size when rate is high */
139 140
	periodsize=periodsize*(rate/8000);

aymeric's avatar
aymeric committed
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
	/* Set buffer size (in frames). The resulting latency is given by */
	/* latency = periodsize * periods / (rate * bytes_per_frame)     */
	/* set period size */
	exact_ulvalue=periodsize;
	dir=0;
	if (snd_pcm_hw_params_set_period_size_near(pcm_handle, hwparams, &exact_ulvalue, &dir) < 0) {
		ms_warning("alsa_set_params: Error setting period size.");
		return -1;
	}
	if (dir != 0) {
		ms_warning("alsa_set_params: The period size %d is not supported by your hardware.\n "
		"==> Using %d instead.", periodsize, (int)exact_ulvalue);
	}
	ms_warning("alsa_set_params: periodsize:%d Using %d", periodsize, (int)exact_ulvalue);
	periodsize=exact_ulvalue;
156
	/* Set number of periods. Periods used to be called fragments. */
aymeric's avatar
aymeric committed
157 158 159 160 161 162 163 164 165 166 167
	exact_uvalue=periods;
	dir=0;
	if (snd_pcm_hw_params_set_periods_near(pcm_handle, hwparams, &exact_uvalue, &dir) < 0) {
		ms_warning("alsa_set_params: Error setting periods.");
		return -1;
	}
	ms_warning("alsa_set_params: period:%d Using %d", periods, exact_uvalue);
	if (dir != 0) {
		ms_warning("alsa_set_params: The number of periods %d is not supported by your hardware.\n "
		"==> Using %d instead.", periods, exact_uvalue);
	}
Simon Morlat's avatar
Simon Morlat committed
168
	periods=exact_uvalue;
169 170 171 172 173

	if (snd_pcm_hw_params_get_buffer_size(hwparams, &buffersize)<0){
		buffersize=0;
		ms_warning("alsa_set_params: could not obtain hw buffer size.");
	}
174

aymeric's avatar
aymeric committed
175 176 177 178 179 180 181 182 183 184
	/* Apply HW parameter settings to */
	/* PCM device and prepare device  */
	if ((err=snd_pcm_hw_params(pcm_handle, hwparams)) < 0) {
		ms_warning("alsa_set_params: Error setting HW params:%s",snd_strerror(err));
		return -1;
	}
	/*prepare sw params */
	if (rw){
		snd_pcm_sw_params_alloca(&swparams);
		snd_pcm_sw_params_current(pcm_handle, swparams);
185
		//ms_message("periodsize=%i, buffersize=%i",(int) periodsize, (int)buffersize);
aymeric's avatar
aymeric committed
186 187 188
		if ((err=snd_pcm_sw_params_set_start_threshold(pcm_handle, swparams,periodsize*2 ))<0){
			ms_warning("alsa_set_params: Error setting start threshold:%s",snd_strerror(err));
		}
189
		if ((err=snd_pcm_sw_params_set_stop_threshold(pcm_handle, swparams,periodsize*periods))<0){
aymeric's avatar
aymeric committed
190 191 192 193 194 195 196
			ms_warning("alsa_set_params: Error setting stop threshold:%s",snd_strerror(err));
		}
		if ((err=snd_pcm_sw_params(pcm_handle, swparams))<0){
			ms_warning("alsa_set_params: Error setting SW params:%s",snd_strerror(err));
			return -1;
		}
	}
197
	return 0;
aymeric's avatar
aymeric committed
198 199 200 201 202 203 204
}

#ifdef EPIPE_BUGFIX
static void alsa_fill_w (snd_pcm_t *pcm_handle)
{
	snd_pcm_hw_params_t *hwparams=NULL;
	int channels;
205
		snd_pcm_uframes_t buffer_size;
aymeric's avatar
aymeric committed
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
	int buffer_size_bytes;
	void *buffer;

	/* Allocate the snd_pcm_hw_params_t structure on the stack. */
	snd_pcm_hw_params_alloca(&hwparams);
	snd_pcm_hw_params_current(pcm_handle, hwparams);

	/* get channels */
	snd_pcm_hw_params_get_channels (hwparams, &channels);

	/* get buffer size */
	snd_pcm_hw_params_get_buffer_size (hwparams, &buffer_size);

	/* fill half */
	buffer_size /= 2;

	/* allocate buffer assuming 2 bytes per sample */
	buffer_size_bytes = buffer_size * channels * 2;
	buffer = alloca (buffer_size_bytes);
	memset (buffer, 0, buffer_size_bytes);

	/* write data */
	snd_pcm_writei(pcm_handle, buffer, buffer_size);
}
#endif

static snd_pcm_t * alsa_open_r(const char *pcmdev,int bits,int stereo,int rate)
{
	snd_pcm_t *pcm_handle;
	int err;

	ms_message("alsa_open_r: opening %s at %iHz, bits=%i, stereo=%i",pcmdev,rate,bits,stereo);


#ifndef THREADED_VERSION
	if (snd_pcm_open(&pcm_handle, pcmdev,SND_PCM_STREAM_CAPTURE,SND_PCM_NONBLOCK) < 0) {
		ms_warning("alsa_open_r: Error opening PCM device %s",pcmdev );
		return NULL;
	}
#else
	/* want blocking mode for threaded version */
	if (snd_pcm_open(&pcm_handle, pcmdev,SND_PCM_STREAM_CAPTURE,0) < 0) {
		ms_warning("alsa_open_r: Error opening PCM device %s",pcmdev );
		return NULL;
	}
#endif
aymeric's avatar
aymeric committed
252 253 254 255 256 257
	{
	struct timeval tv1;
	struct timeval tv2;
	struct timezone tz;
	int diff = 0;
	err = gettimeofday(&tv1, &tz);
258
	while (1) {
aymeric's avatar
aymeric committed
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
		if (!(alsa_set_params(pcm_handle,0,bits,stereo,rate)<0)){
			ms_message("alsa_open_r: Audio params set");
			break;
		}
		if (!gettimeofday(&tv2, &tz) && !err) {
			diff = ((tv2.tv_sec - tv1.tv_sec) * 1000000) + (tv2.tv_usec - tv1.tv_usec);
		} else {
			diff = -1;
		}
		if ((diff < 0) || (diff > 3000000)) { /* 3 secondes */
			ms_error("alsa_open_r: Error setting params for more than 3 seconds");
			snd_pcm_close(pcm_handle);
			return NULL;
		}
		ms_warning("alsa_open_r: Error setting params (for %d micros)", diff);
		usleep(200000);
	}
aymeric's avatar
aymeric committed
276
	}
aymeric's avatar
aymeric committed
277

aymeric's avatar
aymeric committed
278 279 280 281 282 283 284 285 286 287
	err=snd_pcm_start(pcm_handle);
	if (err<0){
		ms_warning("snd_pcm_start() failed: %s", snd_strerror(err));
	}
	return pcm_handle;
}

static snd_pcm_t * alsa_open_w(const char *pcmdev,int bits,int stereo,int rate)
{
	snd_pcm_t *pcm_handle;
Simon Morlat's avatar
Simon Morlat committed
288

289
	ms_message("alsa_open_w: opening %s at %iHz, bits=%i, stereo=%i",pcmdev,rate,bits,stereo);
290

aymeric's avatar
aymeric committed
291 292 293 294
	if (snd_pcm_open(&pcm_handle, pcmdev,SND_PCM_STREAM_PLAYBACK,SND_PCM_NONBLOCK) < 0) {
		ms_warning("alsa_open_w: Error opening PCM device %s",pcmdev );
		return NULL;
	}
Simon Morlat's avatar
Simon Morlat committed
295
	alsa_resume(pcm_handle);
aymeric's avatar
aymeric committed
296 297 298 299 300 301 302
	{
	struct timeval tv1;
	struct timeval tv2;
	struct timezone tz;
	int diff = 0;
	int err;
	err = gettimeofday(&tv1, &tz);
303
	while (1) {
aymeric's avatar
aymeric committed
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
		if (!(alsa_set_params(pcm_handle,1,bits,stereo,rate)<0)){
			ms_message("alsa_open_w: Audio params set");
			break;
		}
		if (!gettimeofday(&tv2, &tz) && !err) {
			diff = ((tv2.tv_sec - tv1.tv_sec) * 1000000) + (tv2.tv_usec - tv1.tv_usec);
		} else {
			diff = -1;
		}
		if ((diff < 0) || (diff > 3000000)) { /* 3 secondes */
			ms_error("alsa_open_w: Error setting params for more than 3 seconds");
			snd_pcm_close(pcm_handle);
			return NULL;
		}
		ms_warning("alsa_open_w: Error setting params (for %d micros)", diff);
		usleep(200000);
	}
aymeric's avatar
aymeric committed
321
	}
aymeric's avatar
aymeric committed
322

aymeric's avatar
aymeric committed
323 324 325
	return pcm_handle;
}

326
static int alsa_can_read(snd_pcm_t *dev)
aymeric's avatar
aymeric committed
327 328 329 330
{
	snd_pcm_sframes_t avail;
	int err;

Simon Morlat's avatar
Simon Morlat committed
331
	alsa_resume(dev);
aymeric's avatar
aymeric committed
332
	avail = snd_pcm_avail_update(dev);
aymeric's avatar
aymeric committed
333 334
	/* A buggy driver does not return an error while being in Xrun */
	if (avail >= 0 && snd_pcm_state(dev) == SND_PCM_STATE_XRUN) avail=-EPIPE;
aymeric's avatar
aymeric committed
335 336 337 338 339 340 341
	if (avail < 0) {
		ms_error("snd_pcm_avail_update: %s", snd_strerror(avail));	// most probably -EPIPE
		/* overrun occured, snd_pcm_state() would return SND_PCM_STATE_XRUN
		 FIXME: handle other error conditions*/
		ms_error("*** alsa_can_read fixup, trying to recover");
		snd_pcm_drain(dev); /* Ignore possible error, at least -EAGAIN.*/
		err = snd_pcm_recover(dev, avail, 0);
342
		if (err){
aymeric's avatar
aymeric committed
343 344 345 346
			ms_error("snd_pcm_recover() failed with err %d: %s", err, snd_strerror(err));
			return -1;
		}
		err = snd_pcm_start(dev);
347 348 349
		if (err){
			ms_error("snd_pcm_start() failed with err %d: %s", err, snd_strerror(err));
			return -1;
aymeric's avatar
aymeric committed
350 351 352 353 354 355
		}
		ms_message("Recovery done");
	}
	return avail;
}

356

aymeric's avatar
aymeric committed
357 358 359 360 361 362 363 364 365 366
static int alsa_read(snd_pcm_t *handle,unsigned char *buf,int nsamples)
{
	int err;
	err=snd_pcm_readi(handle,buf,nsamples);
	if (err<0) {
		ms_warning("alsa_read: snd_pcm_readi() returned %i",err);
		if (err==-EPIPE){
			snd_pcm_prepare(handle);
			err=snd_pcm_readi(handle,buf,nsamples);
			if (err<0) ms_warning("alsa_read: snd_pcm_readi() failed:%s.",snd_strerror(err));
367 368
		}else if (err==-ESTRPIPE){
			alsa_resume(handle);
aymeric's avatar
aymeric committed
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389
		}else if (err!=-EWOULDBLOCK){
			ms_warning("alsa_read: snd_pcm_readi() failed:%s.",snd_strerror(err));
		}
	}else if (err==0){
		ms_warning("alsa_read: snd_pcm_readi() returned 0");
	}
	return err;
}


static int alsa_write(snd_pcm_t *handle,unsigned char *buf,int nsamples)
{
	int err;
	if ((err=snd_pcm_writei(handle,buf,nsamples))<0){
		if (err==-EPIPE){
			snd_pcm_prepare(handle);
#ifdef EPIPE_BUGFIX
			alsa_fill_w (handle);
#endif
			err=snd_pcm_writei(handle,buf,nsamples);
			if (err<0) ms_warning("alsa_card_write: Error writing sound buffer (nsamples=%i):%s",nsamples,snd_strerror(err));
390 391
		}else if (err==-ESTRPIPE){
			alsa_resume(handle);
aymeric's avatar
aymeric committed
392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470
		}else if (err!=-EWOULDBLOCK){
			ms_warning("alsa_card_write: snd_pcm_writei() failed:%s.",snd_strerror(err));
		}
	}else if (err!=nsamples) {
		ms_debug("Only %i samples written instead of %i",err,nsamples);
	}
	return err;
}


static snd_mixer_t *alsa_mixer_open(const char *mixdev){
	snd_mixer_t *mixer=NULL;
	int err;
	err=snd_mixer_open(&mixer,0);
	if (err<0){
		ms_warning("Could not open alsa mixer: %s",snd_strerror(err));
		return NULL;
	}
	if ((err = snd_mixer_attach (mixer, mixdev)) < 0){
		ms_warning("Could not attach mixer to card: %s",snd_strerror(err));
		snd_mixer_close(mixer);
		return NULL;
	}
	if ((err = snd_mixer_selem_register (mixer, NULL, NULL)) < 0){
		ms_warning("snd_mixer_selem_register: %s",snd_strerror(err));
		snd_mixer_close(mixer);
		return NULL;
	}
	if ((err = snd_mixer_load (mixer)) < 0){
		ms_warning("snd_mixer_load: %s",snd_strerror(err));
		snd_mixer_close(mixer);
		return NULL;
	}
	return mixer;
}

static void alsa_mixer_close(snd_mixer_t *mix){
	snd_mixer_close(mix);
}

typedef enum {CAPTURE, PLAYBACK, CAPTURE_SWITCH, PLAYBACK_SWITCH} MixerAction;

static int get_mixer_element(snd_mixer_t *mixer,const char *name, MixerAction action){
	long value=0;
	const char *elemname;
	snd_mixer_elem_t *elem;
	int err;
	long sndMixerPMin=0;
	long sndMixerPMax=0;
	long newvol=0;
	elem=snd_mixer_first_elem(mixer);
	while (elem!=NULL){
		elemname=snd_mixer_selem_get_name(elem);
		//ms_message("Found alsa mixer element %s.",elemname);
		if (strcmp(elemname,name)==0){
			switch (action){
				case CAPTURE:
				if (snd_mixer_selem_has_capture_volume(elem)){
					snd_mixer_selem_get_capture_volume_range(elem, &sndMixerPMin, &sndMixerPMax);
					err=snd_mixer_selem_get_capture_volume(elem,SND_MIXER_SCHN_UNKNOWN,&newvol);
					newvol-=sndMixerPMin;
					value=(100*newvol)/(sndMixerPMax-sndMixerPMin);
					if (err<0) ms_warning("Could not get capture volume for %s:%s",name,snd_strerror(err));
					//else ms_message("Successfully get capture level for %s.",elemname);
					break;
				}
				break;
				case PLAYBACK:
				if (snd_mixer_selem_has_playback_volume(elem)){
					snd_mixer_selem_get_playback_volume_range(elem, &sndMixerPMin, &sndMixerPMax);
					err=snd_mixer_selem_get_playback_volume(elem,SND_MIXER_SCHN_FRONT_LEFT,&newvol);
					newvol-=sndMixerPMin;
					value=(100*newvol)/(sndMixerPMax-sndMixerPMin);
					if (err<0) ms_warning("Could not get playback volume for %s:%s",name,snd_strerror(err));
					//else ms_message("Successfully get playback level for %s.",elemname);
					break;
				}
				break;
				case CAPTURE_SWITCH:
471

aymeric's avatar
aymeric committed
472 473 474 475 476 477 478 479
				break;
				case PLAYBACK_SWITCH:

				break;
			}
		}
		elem=snd_mixer_elem_next(elem);
	}
480

aymeric's avatar
aymeric committed
481 482 483 484 485 486 487 488 489 490
	return value;
}


static void set_mixer_element(snd_mixer_t *mixer,const char *name, int level,MixerAction action){
	const char *elemname;
	snd_mixer_elem_t *elem;
	long sndMixerPMin=0;
	long sndMixerPMax=0;
	long newvol=0;
491

aymeric's avatar
aymeric committed
492
	elem=snd_mixer_first_elem(mixer);
493

aymeric's avatar
aymeric committed
494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539
	while (elem!=NULL){
		elemname=snd_mixer_selem_get_name(elem);
		//ms_message("Found alsa mixer element %s.",elemname);
		if (strcmp(elemname,name)==0){
			switch(action){
				case CAPTURE:
				if (snd_mixer_selem_has_capture_volume(elem)){
					snd_mixer_selem_get_capture_volume_range(elem, &sndMixerPMin, &sndMixerPMax);
					newvol=(((sndMixerPMax-sndMixerPMin)*level)/100)+sndMixerPMin;
					snd_mixer_selem_set_capture_volume_all(elem,newvol);
					//ms_message("Successfully set capture level for %s.",elemname);
					return;
				}
				break;
				case PLAYBACK:
				if (snd_mixer_selem_has_playback_volume(elem)){
					snd_mixer_selem_get_playback_volume_range(elem, &sndMixerPMin, &sndMixerPMax);
					newvol=(((sndMixerPMax-sndMixerPMin)*level)/100)+sndMixerPMin;
					snd_mixer_selem_set_playback_volume_all(elem,newvol);
					//ms_message("Successfully set playback level for %s.",elemname);
					return;
				}
				break;
				case CAPTURE_SWITCH:
				if (snd_mixer_selem_has_capture_switch(elem)){
					snd_mixer_selem_set_capture_switch_all(elem,level);
					//ms_message("Successfully set capture switch for %s.",elemname);
				}
				break;
				case PLAYBACK_SWITCH:
				if (snd_mixer_selem_has_playback_switch(elem)){
					snd_mixer_selem_set_playback_switch_all(elem,level);
					//ms_message("Successfully set capture switch for %s.",elemname);
				}
				break;

			}
		}
		elem=snd_mixer_elem_next(elem);
	}

	return ;
}


static void alsa_card_set_level(MSSndCard *obj,MSSndCardMixerElem e,int a)
540
{
aymeric's avatar
aymeric committed
541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606
	snd_mixer_t *mixer;
	AlsaData *ad=(AlsaData*)obj->data;
	mixer=alsa_mixer_open(ad->mixdev);
	if (mixer==NULL) return ;
	switch(e){
		case MS_SND_CARD_MASTER:
			set_mixer_element(mixer,"Master",a,PLAYBACK);
		break;
		case MS_SND_CARD_CAPTURE:
			set_mixer_element(mixer,"Capture",a,CAPTURE);
		break;
		case MS_SND_CARD_PLAYBACK:
			set_mixer_element(mixer,"PCM",a,PLAYBACK);
		break;
		default:
			ms_warning("alsa_card_set_level: unsupported command.");
	}
	alsa_mixer_close(mixer);
}

static int alsa_card_get_level(MSSndCard *obj, MSSndCardMixerElem e)
{
	snd_mixer_t *mixer;
	AlsaData *ad=(AlsaData*)obj->data;
	int value = -1;
	mixer=alsa_mixer_open(ad->mixdev);
	if (mixer==NULL) return 0;
	switch(e){
		case MS_SND_CARD_MASTER:
			value=get_mixer_element(mixer,"Master",PLAYBACK);
			break;
		case MS_SND_CARD_CAPTURE:
			value=get_mixer_element(mixer,"Capture",CAPTURE);
			break;
		case MS_SND_CARD_PLAYBACK:
			value=get_mixer_element(mixer,"PCM",PLAYBACK);
			break;
		default:
			ms_warning("alsa_card_set_level: unsupported command.");
	}
	alsa_mixer_close(mixer);
	return value;
}

static void alsa_card_set_source(MSSndCard *obj,MSSndCardCapture source)
{
	snd_mixer_t *mixer;
	AlsaData *ad=(AlsaData*)obj->data;
	mixer=alsa_mixer_open(ad->mixdev);
	if (mixer==NULL) return;
	switch (source){
		case MS_SND_CARD_MIC:
			set_mixer_element(mixer,"Mic",1,CAPTURE_SWITCH);
			set_mixer_element(mixer,"Capture",1,CAPTURE_SWITCH);
			break;
		case MS_SND_CARD_LINE:
			set_mixer_element(mixer,"Line",1,CAPTURE_SWITCH);
			set_mixer_element(mixer,"Capture",1,CAPTURE_SWITCH);
			break;
	}
	alsa_mixer_close(mixer);
}

static MSFilter *alsa_card_create_reader(MSSndCard *card)
{
	AlsaData *ad=(AlsaData*)card->data;
607
	MSFilter *f=ms_alsa_read_new(ms_snd_card_get_factory(card), ad->pcmdev);
aymeric's avatar
aymeric committed
608 609 610 611 612 613
	return f;
}

static MSFilter *alsa_card_create_writer(MSSndCard *card)
{
	AlsaData *ad=(AlsaData*)card->data;
614
	MSFilter *f=ms_alsa_write_new(ms_snd_card_get_factory(card), ad->pcmdev);
aymeric's avatar
aymeric committed
615 616 617 618
	return f;
}


619
void alsa_error_log_handler(const char *file, int line, const char *function, int err, const char *fmt, ...) {
620
	char * format = ms_strdup_printf("alsa error in %s:%d - %s", file, line, fmt);
621 622
	va_list args;
	va_start (args, fmt);
623
	bctbx_logv(BCTBX_LOG_DOMAIN, BCTBX_LOG_MESSAGE, format, args);
624
	va_end (args);
625
	ms_free(format);
626 627
}

aymeric's avatar
aymeric committed
628 629 630
static void alsa_card_init(MSSndCard *obj){
	AlsaData *ad=ms_new0(AlsaData,1);
	obj->data=ad;
631 632
	snd_lib_error_set_handler(alsa_error_log_handler);

aymeric's avatar
aymeric committed
633 634 635 636 637 638 639 640 641 642
}

static void alsa_card_uninit(MSSndCard *obj){
	AlsaData *ad=(AlsaData*)obj->data;
	if (ad->pcmdev!=NULL) ms_free(ad->pcmdev);
	if (ad->mixdev!=NULL) ms_free(ad->mixdev);
	ms_free(ad);
}

static void alsa_card_detect(MSSndCardManager *m){
643
	int i,j,k;
644
	void **hints=NULL;
645
	int hint_device_count=0;
646
	int device_count=0;
647
	const char *pcm_base_name = "plug";
648 649
	bool_t found_duplicate;
	const int MAX_NUM_DEVICE_ID = 100;
650
	const int MAX_PLUG_NAME_CHARS = 50;
651
	char *plug_names[MAX_NUM_DEVICE_ID];
652 653
	char *card_names[MAX_NUM_DEVICE_ID], *device_names[MAX_NUM_DEVICE_ID];
	char *unique_card_names[MAX_NUM_DEVICE_ID], *unique_device_names[MAX_NUM_DEVICE_ID];
654

655
	memset(plug_names, 0, sizeof(plug_names));
656

657
	/* Get list of devices from alsa device hints */
658 659
	if (snd_device_name_hint(-1, "pcm", &hints)==0){
		for(i=0; hints[i]!=NULL; ++i){
660
			char *hint = snd_device_name_get_hint(hints[i],"NAME");
Ghislain MARY's avatar
Ghislain MARY committed
661 662 663 664 665 666 667 668
			char *hint_ptr = hint;
			if (hint != NULL) {
				char *device_name = strsep(&hint, ":");
				if (device_name){
					char *card_hint = strsep(&hint, ",");
					if (card_hint){
						if (strcmp(strsep(&card_hint, "="), "CARD")==0){
							char *card_name = card_hint;
669 670
							card_names[hint_device_count] = ms_strdup(card_name);
							device_names[hint_device_count] = ms_strdup(device_name);
Ghislain MARY's avatar
Ghislain MARY committed
671 672
							hint_device_count++;
						}
673 674
					}
				}
Ghislain MARY's avatar
Ghislain MARY committed
675
				free(hint_ptr);
676
			}
677 678 679
		}
		snd_device_name_free_hint(hints);
	}
680 681 682

	/* Produce unique device_names[] */

683
	for (j=0; j<hint_device_count; j++){
684 685
		found_duplicate = FALSE;
		if (j == 0){
686 687 688 689
			unique_card_names[0] = card_names[0];
			unique_device_names[0] = device_names[0];
			plug_names[device_count] = (char*) ms_new(char, MAX_PLUG_NAME_CHARS);
                        sprintf(plug_names[0],"%s:%s", device_names[0], card_names[0]);
690 691 692 693 694 695

			device_count++;
			continue;
		}
		for (k=0; k<device_count; k++){

696
			if ( (strcmp(card_names[j], unique_card_names[k])==0) && (strcmp(device_names[j], unique_device_names[k])==0) ){
697 698 699 700 701
				found_duplicate = TRUE;
				break;
			}
		}
		if ( !found_duplicate ){
702 703
			unique_card_names[device_count] = card_names[j];
			unique_device_names[device_count] = device_names[j];
704

705 706
			plug_names[device_count] = (char*) ms_new(char,MAX_PLUG_NAME_CHARS);
			sprintf(plug_names[device_count],"%s:%s", device_names[j], card_names[j]);
707

708 709
			device_count++;
		}
710
	}
711 712 713

	/* Add unique devices to card manager */

714
	for (i=-1;i<device_count;i++){
715 716
		MSSndCard *card=NULL;
		if (i==-1){
717
			card=alsa_card_new("default", pcm_base_name);
718 719
		}
		else {
720 721 722 723
			// Currently, only 'default' devices are supported.
			if (strcmp(unique_device_names[i], "default")==0) {
				card=alsa_card_new(plug_names[i], pcm_base_name);
			}
724 725
		}

aymeric's avatar
aymeric committed
726
		if (card!=NULL)
727
		{
aymeric's avatar
aymeric committed
728
			ms_snd_card_manager_add_card(m,card);
729
		}
aymeric's avatar
aymeric committed
730
	}
731

Yann Diorcet's avatar
Yann Diorcet committed
732
	atexit((void(*)(void))snd_config_update_free_global);
733

734
	for (i=0; i<hint_device_count; i++) {
735
		if (plug_names[i]) ms_free(plug_names[i]);
736 737 738
		ms_free(device_names[i]);
		ms_free(card_names[i]);
	}
aymeric's avatar
aymeric committed
739 740 741 742 743 744 745 746 747
}

MSSndCardDesc alsa_card_desc={
	.driver_type="ALSA",
	.detect=alsa_card_detect,
	.init=alsa_card_init,
	.set_level=alsa_card_set_level,
	.get_level=alsa_card_get_level,
	.set_capture=alsa_card_set_source,
748 749
	.set_control=NULL,
	.get_control=NULL,
aymeric's avatar
aymeric committed
750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777
	.create_reader=alsa_card_create_reader,
	.create_writer=alsa_card_create_writer,
	.uninit=alsa_card_uninit,
	.duplicate=alsa_card_duplicate
};

static MSSndCard *alsa_card_duplicate(MSSndCard *obj){
	MSSndCard *card=ms_snd_card_new(&alsa_card_desc);
	AlsaData* dcard=(AlsaData*)card->data;
	AlsaData* dobj=(AlsaData*)obj->data;
	card->name=ms_strdup(obj->name);
	card->id=ms_strdup(obj->id);
	dcard->pcmdev=ms_strdup(dobj->pcmdev);
	dcard->mixdev=ms_strdup(dobj->mixdev);
	return card;
}

MSSndCard * ms_alsa_card_new_custom(const char *pcmdev, const char *mixdev){
	MSSndCard * obj;
	AlsaData *ad;
	obj=ms_snd_card_new(&alsa_card_desc);
	ad=(AlsaData*)obj->data;
	obj->name=ms_strdup(pcmdev);
	ad->pcmdev=ms_strdup(pcmdev);
	ad->mixdev=ms_strdup(mixdev);
	return obj;
}

778 779 780 781
static char *get_card_name(snd_pcm_t *handle, unsigned int *card_index_ret){
	snd_pcm_info_t *info=NULL;
	unsigned int card_index=-1;
	char *ret = NULL;
782

783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805
	snd_pcm_info_malloc(&info);
	if (snd_pcm_info(handle, info)==0){
		card_index = snd_pcm_info_get_card(info);
	}
	snd_pcm_info_free(info);
	if (card_index != (unsigned int) -1){
		char *name=NULL;
		*card_index_ret = card_index;
		snd_card_get_name(card_index, &name);
		if (name){
			/* remove trailing spaces from card name */
			char *pos2;
			ret =ms_strdup(name);
			pos2 = ret + strlen(ret) - 1;
			for (; pos2>name && *pos2==' '; pos2--) *pos2='\0';
			free(name);
		}
	}
	if (!ret) ret = ms_strdup("default");
	return ret;
}

static unsigned int get_card_capabilities(const char *devname, char **card_name, unsigned int *card_index){
smorlat's avatar
smorlat committed
806
	snd_pcm_t *pcm_handle;
807
	unsigned int ret = 0;
808

809
	*card_name = NULL;
smorlat's avatar
smorlat committed
810
	if (snd_pcm_open(&pcm_handle,devname,SND_PCM_STREAM_CAPTURE,SND_PCM_NONBLOCK)==0) {
811
		*card_name = get_card_name(pcm_handle, card_index);
smorlat's avatar
smorlat committed
812 813 814 815
		ret|=MS_SND_CARD_CAP_CAPTURE;
		snd_pcm_close(pcm_handle);
	}
	if (snd_pcm_open(&pcm_handle,devname,SND_PCM_STREAM_PLAYBACK,SND_PCM_NONBLOCK)==0) {
816
		if (*card_name == NULL) *card_name = get_card_name(pcm_handle, card_index);
smorlat's avatar
smorlat committed
817 818 819 820 821 822
		ret|=MS_SND_CARD_CAP_PLAYBACK;
		snd_pcm_close(pcm_handle);
	}
	return ret;
}

823
static MSSndCard * alsa_card_new(const char *id, const char *pcmbasename){
aymeric's avatar
aymeric committed
824 825
	MSSndCard * obj;
	AlsaData *ad;
826
	unsigned int hw_index=0;
827

aymeric's avatar
aymeric committed
828 829
	obj=ms_snd_card_new(&alsa_card_desc);
	ad=(AlsaData*)obj->data;
830
	if (strcmp(id,"default")==0) {
aymeric's avatar
aymeric committed
831 832 833 834 835
		/* the default pcm device */
		obj->name=ms_strdup("default device");
		ad->pcmdev=ms_strdup("default");
		ad->mixdev=ms_strdup("default");
	}else{
836
		snd_mixer_t *mixer;
837
		ad->pcmdev=ms_strdup_printf("%s:%s",pcmbasename, id);
838 839 840 841
		obj->capabilities = get_card_capabilities(ad->pcmdev, &obj->name, &hw_index);
		if (obj->capabilities == 0){
			ms_snd_card_destroy(obj);
			return NULL;
smorlat's avatar
smorlat committed
842
		}
843 844 845 846
		ad->mixdev=ms_strdup_printf("hw:%i",hw_index);
		mixer = alsa_mixer_open(ad->mixdev);
		if (!mixer) ms_warning("Fail to get a mixer for device %s", ad->mixdev);
		else alsa_mixer_close(mixer);
smorlat's avatar
smorlat committed
847
	}
aymeric's avatar
aymeric committed
848 849 850 851 852 853 854 855
	return obj;
}

struct _AlsaReadData{
	char *pcmdev;
	snd_pcm_t *handle;
	int rate;
	int nchannels;
856
	uint64_t read_samples;
857
	MSTickerSynchronizer *ticker_synchronizer;
858 859
	bool_t read_started;
	bool_t write_started;
860

aymeric's avatar
aymeric committed
861 862 863 864 865 866 867 868 869 870
#ifdef THREADED_VERSION
	ms_thread_t thread;
	ms_mutex_t mutex;
	MSBufferizer * bufferizer;
#endif
};

typedef struct _AlsaReadData AlsaReadData;

void alsa_read_init(MSFilter *obj){
871
	AlsaReadData *ad=ms_new0(AlsaReadData,1);
aymeric's avatar
aymeric committed
872 873
	ad->pcmdev=NULL;
	ad->handle=NULL;
874
	ad->rate=forced_rate!=-1 ? forced_rate : 8000;
aymeric's avatar
aymeric committed
875
	ad->nchannels=1;
876
	ad->ticker_synchronizer = ms_ticker_synchronizer_new();
aymeric's avatar
aymeric committed
877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903
	obj->data=ad;

#ifdef THREADED_VERSION
	ad->read_started=FALSE;
	ad->write_started=FALSE;
	ad->bufferizer=ms_bufferizer_new();
	ms_mutex_init(&ad->mutex,NULL);
	ad->thread=0;
#endif
}

#ifdef THREADED_VERSION

static void * alsa_write_thread(void *p){
	AlsaReadData *ad=(AlsaReadData*)p;
	int samples=(160*ad->rate)/8000;
	int err;
	int count=0;
	mblk_t *om=NULL;
	struct timeval timeout;
	if (ad->handle==NULL && ad->pcmdev!=NULL){
		ad->handle=alsa_open_r(ad->pcmdev,16,ad->nchannels==2,ad->rate);
	}
	if (ad->handle==NULL) return NULL;

	while (ad->read_started)
	  {
904 905 906 907 908
		count = alsa_can_read(ad->handle,samples);
		if (count==24)
		  { /* keep this value for this driver */ }
		else if (count<=0)
		  {
aymeric's avatar
aymeric committed
909
		count = samples;
910 911 912
		  }
		else if (count>0)
		  {
aymeric's avatar
aymeric committed
913 914
		//ms_warning("%i count", count);
		//count = samples;
915
		  }
aymeric's avatar
aymeric committed
916

917 918
		int size=count*2;
		om=allocb(size,0);
aymeric's avatar
aymeric committed
919

920 921
		if ((err=alsa_read(ad->handle,om->b_wptr,count))<=0)
		  {
aymeric's avatar
aymeric committed
922 923
		ms_warning("nothing to read");
		//ms_warning("Fail to read samples %i", count);
aymeric's avatar
aymeric committed
924
		freemsg(om); /* leak fixed */
aymeric's avatar
aymeric committed
925
		continue;
926 927
		  }
		//ms_warning(" read %i", err);
928

929 930
		size=err*2;
		om->b_wptr+=size;
aymeric's avatar
aymeric committed
931

932 933 934
		ms_mutex_lock(&ad->mutex);
		ms_bufferizer_put(ad->bufferizer,om);
		ms_mutex_unlock(&ad->mutex);
aymeric's avatar
aymeric committed
935

936 937
		if (count==24)
		  {
aymeric's avatar
aymeric committed
938 939 940
		timeout.tv_sec = 0;
		timeout.tv_usec = 2000;
		select(0, 0, NULL, NULL, &timeout );
941 942 943
		  }
		else
		  {
aymeric's avatar
aymeric committed
944 945 946 947
		/* select will be less active than locking on "read" */
		timeout.tv_sec = 0;
		timeout.tv_usec = 5000;
		select(0, 0, NULL, NULL, &timeout );
948
		  }
aymeric's avatar
aymeric committed
949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966
	  }

	if (ad->handle!=NULL) snd_pcm_close(ad->handle);
	ad->handle=NULL;
	return NULL;
}

static void alsa_start_r(AlsaReadData *d){
	if (d->read_started==FALSE){
		d->read_started=TRUE;
		ms_thread_create(&d->thread,NULL,alsa_write_thread,d);
	}else d->read_started=TRUE;
}

static void alsa_stop_r(AlsaReadData *d){
	d->read_started=FALSE;
	if (d->thread!=0)
	  {
967 968
		ms_thread_join(d->thread,NULL);
		d->thread=0;
aymeric's avatar
aymeric committed
969 970 971 972 973
	  }
}
#endif

void alsa_read_preprocess(MSFilter *obj){
974
#ifdef THREADED_VERSION
aymeric's avatar
aymeric committed
975 976 977
	AlsaReadData *ad=(AlsaReadData*)obj->data;
	alsa_start_r(ad);
#endif
978 979
}

aymeric's avatar
aymeric committed
980 981 982 983 984 985

void alsa_read_postprocess(MSFilter *obj){
	AlsaReadData *ad=(AlsaReadData*)obj->data;
#ifdef THREADED_VERSION
	alsa_stop_r(ad);
#endif
986
	ms_ticker_set_synchronizer(obj->ticker, NULL);
aymeric's avatar
aymeric committed
987
	if (ad->handle!=NULL) snd_pcm_close(ad->handle);
988
	ad->read_started=FALSE;
aymeric's avatar
aymeric committed
989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002
	ad->handle=NULL;
}

void alsa_read_uninit(MSFilter *obj){
	AlsaReadData *ad=(AlsaReadData*)obj->data;
#ifdef THREADED_VERSION
	alsa_stop_r(ad);
#endif
	if (ad->pcmdev!=NULL) ms_free(ad->pcmdev);
	if (ad->handle!=NULL) snd_pcm_close(ad->handle);
#ifdef THREADED_VERSION
	ms_bufferizer_destroy(ad->bufferizer);
	ms_mutex_destroy(&ad->mutex);
#endif
1003
	ms_ticker_synchronizer_destroy(ad->ticker_synchronizer);
aymeric's avatar
aymeric committed
1004 1005 1006 1007 1008 1009 1010 1011 1012
	ms_free(ad);
}

#ifndef THREADED_VERSION
void alsa_read_process(MSFilter *obj){
	AlsaReadData *ad=(AlsaReadData*)obj->data;
	int samples=(128*ad->rate)/8000;
	int err;
	mblk_t *om=NULL;
1013 1014
	if (ad->handle==NULL && ad->pcmdev!=NULL && !ad->read_started){
		ad->read_started=TRUE;
aymeric's avatar
aymeric committed
1015
		ad->handle=alsa_open_r(ad->pcmdev,16,ad->nchannels==2,ad->rate);
1016 1017
		if (ad->handle){
			ad->read_samples=0;
1018
			ms_ticker_set_synchronizer(obj->ticker, ad->ticker_synchronizer);
1019
		}
aymeric's avatar
aymeric committed
1020 1021
	}
	if (ad->handle==NULL) return;
1022
	while (alsa_can_read(ad->handle)>=samples){
1023

Simon Morlat's avatar
Simon Morlat committed
1024
		int size=samples*2*ad->nchannels;
aymeric's avatar
aymeric committed
1025 1026 1027 1028 1029 1030
		om=allocb(size,0);
		if ((err=alsa_read(ad->handle,om->b_wptr,samples))<=0) {
			ms_warning("Fail to read samples");
			freemsg(om);
			return;
		}
1031
		ad->read_samples+=err;
Simon Morlat's avatar
Simon Morlat committed
1032
		size=err*2*ad->nchannels;
aymeric's avatar
aymeric committed
1033
		om->b_wptr+=size;
1034
		ms_ticker_synchronizer_update(ad->ticker_synchronizer, ad->read_samples, (unsigned int)ad->rate);
1035

aymeric's avatar
aymeric committed
1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046
		/*ms_message("alsa_read_process: Outputing %i bytes",size);*/
		ms_queue_put(obj->outputs[0],om);
	}
}
#endif

#ifdef THREADED_VERSION
void alsa_read_process(MSFilter *obj){
	AlsaReadData *ad=(AlsaReadData*)obj->data;
	mblk_t *om=NULL;
	int samples=(160*ad->rate)/8000;
Simon Morlat's avatar
Simon Morlat committed
1047
	int size=samples*2*ad->nchannels;
1048

aymeric's avatar
aymeric committed
1049
	ms_mutex_lock(&ad->mutex);
Simon Morlat's avatar
Simon Morlat committed
1050
	while (ms_bufferizer_get_avail(ad->bufferizer)>=size){
1051

Simon Morlat's avatar
Simon Morlat committed
1052
	  om=allocb(size,0);
1053
	  ms_bufferizer_read(ad->bufferizer,om->b_wptr,size);
Simon Morlat's avatar
Simon Morlat committed
1054
	  om->b_wptr+=size;
aymeric's avatar
aymeric committed
1055 1056 1057 1058 1059 1060 1061
	  /*ms_message("alsa_read_process: Outputing %i bytes",size);*/
	  ms_queue_put(obj->outputs[0],om);
	}
	ms_mutex_unlock(&ad->mutex);
}
#endif

1062 1063 1064 1065 1066 1067
static int alsa_read_get_sample_rate(MSFilter *obj, void *param){
	AlsaReadData *ad=(AlsaReadData*)obj->data;
	*((int*)param)=ad->rate;
	return 0;
}

aymeric's avatar
aymeric committed
1068 1069
static int alsa_read_set_sample_rate(MSFilter *obj, void *param){
	AlsaReadData *ad=(AlsaReadData*)obj->data;
1070
	if (forced_rate!=-1) return -1;
aymeric's avatar
aymeric committed
1071 1072 1073 1074
	ad->rate=*((int*)param);
	return 0;
}

1075 1076 1077 1078 1079 1080
static int alsa_read_get_nchannels(MSFilter *obj, void *param) {
	AlsaReadData *ad = (AlsaReadData *)obj->data;
	*((int *)param) = ad->nchannels;
	return 0;
}

aymeric's avatar
aymeric committed
1081 1082 1083 1084 1085 1086 1087
static int alsa_read_set_nchannels(MSFilter *obj, void *param){
	AlsaReadData *ad=(AlsaReadData*)obj->data;
	ad->nchannels=*((int*)param);
	return 0;
}

MSFilterMethod alsa_read_methods[]={
1088
	{MS_FILTER_GET_SAMPLE_RATE,	alsa_read_get_sample_rate},
aymeric's avatar
aymeric committed
1089
	{MS_FILTER_SET_SAMPLE_RATE, alsa_read_set_sample_rate},
1090
	{MS_FILTER_GET_NCHANNELS, alsa_read_get_nchannels},
1091
	{MS_FILTER_SET_NCHANNELS, alsa_read_set_nchannels},
aymeric's avatar
aymeric committed
1092 1093 1094 1095 1096 1097
	{0,NULL}
};

MSFilterDesc alsa_read_desc={
	.id=MS_ALSA_READ_ID,
	.name="MSAlsaRead",
1098
	.text=N_("Alsa sound source"),
aymeric's avatar
aymeric committed
1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109
	.category=MS_FILTER_OTHER,
	.ninputs=0,
	.noutputs=1,
	.init=alsa_read_init,
	.preprocess=alsa_read_preprocess,
	.process=alsa_read_process,
	.postprocess=alsa_read_postprocess,
	.uninit=alsa_read_uninit,
	.methods=alsa_read_methods
};

1110 1111
static MSFilter * ms_alsa_read_new(MSFactory *factory, const char *dev){
	MSFilter *f=ms_factory_create_filter_from_desc(factory, &alsa_read_desc);
aymeric's avatar
aymeric committed
1112 1113 1114 1115 1116 1117 1118 1119
	AlsaReadData *ad=(AlsaReadData*)f->data;
	ad->pcmdev=ms_strdup(dev);
	return f;
}

typedef struct _AlsaReadData AlsaWriteData;

void alsa_write_init(MSFilter *obj){
1120
	AlsaWriteData *ad=ms_new0(AlsaWriteData,1);
aymeric's avatar
aymeric committed
1121 1122
	ad->pcmdev=NULL;
	ad->handle=NULL;
1123
	ad->rate=forced_rate!=-1 ? forced_rate : 8000;
aymeric's avatar
aymeric committed
1124 1125 1126 1127 1128 1129 1130
	ad->nchannels=1;
	obj->data=ad;
}

void alsa_write_postprocess(MSFilter *obj){
	AlsaReadData *ad=(AlsaReadData*)obj->data;
	if (ad->handle!=NULL) snd_pcm_close(ad->handle);
1131
	ad->write_started=FALSE;
aymeric's avatar
aymeric committed
1132 1133 1134 1135 1136 1137 1138 1139 1140 1141
	ad->handle=NULL;
}

void alsa_write_uninit(MSFilter *obj){
	AlsaWriteData *ad=(AlsaWriteData*)obj->data;
	if (ad->pcmdev!=NULL) ms_free(ad->pcmdev);
	if (ad->handle!=NULL) snd_pcm_close(ad->handle);
	ms_free(ad);
}

1142 1143 1144 1145 1146 1147
static int alsa_write_get_sample_rate(MSFilter *obj, void *data){
	AlsaWriteData *ad=(AlsaWriteData*)obj->data;
	*((int*)data)=ad->rate;
	return 0;
}

aymeric's avatar
aymeric committed
1148 1149 1150
int alsa_write_set_sample_rate(MSFilter *obj, void *data){
	int *rate=(int*)data;
	AlsaWriteData *ad=(AlsaWriteData*)obj->data;
1151
	if (forced_rate!=-1) return -1;
aymeric's avatar
aymeric committed
1152 1153 1154 1155
	ad->rate=*rate;
	return 0;
}

1156 1157 1158 1159 1160 1161
int alsa_write_get_nchannels(MSFilter *obj, void *data) {
	AlsaWriteData *ad = (AlsaWriteData *)obj->data;
	*((int *)data) = ad->nchannels;
	return 0;
}

aymeric's avatar
aymeric committed
1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174
int alsa_write_set_nchannels(MSFilter *obj, void *data){
	int *n=(int*)data;
	AlsaWriteData *ad=(AlsaWriteData*)obj->data;
	ad->nchannels=*n;
	return 0;
}

void alsa_write_process(MSFilter *obj){
	AlsaWriteData *ad=(AlsaWriteData*)obj->data;
	mblk_t *im=NULL;
	int size;
	int samples;
	int err;
1175 1176
	if (ad->handle==NULL && ad->pcmdev!=NULL && !ad->write_started){
		ad->write_started=TRUE;
aymeric's avatar
aymeric committed
1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199
		ad->handle=alsa_open_w(ad->pcmdev,16,ad->nchannels==2,ad->rate);
#ifdef EPIPE_BUGFIX
		alsa_fill_w (ad->pcmdev);
#endif
	}
	if (ad->handle==NULL) {
		ms_queue_flush(obj->inputs[0]);
		return;
	}
	while ((im=ms_queue_get(obj->inputs[0]))!=NULL){
		while((size=im->b_wptr-im->b_rptr)>0){
			samples=size/(2*ad->nchannels);
			err=alsa_write(ad->handle,im->b_rptr,samples);
			if (err>0) {
				im->b_rptr+=err*(2*ad->nchannels);
			}
			else break;
		}
		freemsg(im);
	}
}

MSFilterMethod alsa_write_methods[]={
1200
	{MS_FILTER_GET_SAMPLE_RATE,	alsa_write_get_sample_rate},
aymeric's avatar
aymeric committed
1201
	{MS_FILTER_SET_SAMPLE_RATE, alsa_write_set_sample_rate},
1202
	{MS_FILTER_GET_NCHANNELS, alsa_write_get_nchannels},
aymeric's avatar
aymeric committed
1203 1204 1205 1206 1207 1208 1209
	{MS_FILTER_SET_NCHANNELS, alsa_write_set_nchannels},
	{0,NULL}
};

MSFilterDesc alsa_write_desc={
	.id=MS_ALSA_WRITE_ID,
	.name="MSAlsaWrite",
1210
	.text=N_("Alsa sound output"),
aymeric's avatar
aymeric committed
1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221
	.category=MS_FILTER_OTHER,
	.ninputs=1,
	.noutputs=0,
	.init=alsa_write_init,
	.process=alsa_write_process,
	.postprocess=alsa_write_postprocess,
	.uninit=alsa_write_uninit,
	.methods=alsa_write_methods
};


1222 1223
static MSFilter * ms_alsa_write_new(MSFactory *factory, const char *dev){
	MSFilter *f = ms_factory_create_filter_from_desc(factory, &alsa_write_desc);
aymeric's avatar
aymeric committed
1224 1225 1226 1227 1228 1229 1230 1231 1232 1233
	AlsaWriteData *ad=(AlsaWriteData*)f->data;
	ad->pcmdev=ms_strdup(dev);
	return f;
}


MS_FILTER_DESC_EXPORT(alsa_write_desc)

MS_FILTER_DESC_EXPORT(alsa_read_desc)