1 /* -*- c-basic-offset: 8 -*-
2    rdesktop: A Remote Desktop Protocol client.
3    Sound Channel Process Functions - alsa-driver
4    Copyright (C) Matthew Chapman <matthewc.unsw.edu.au> 2003-2008
5    Copyright (C) GuoJunBo <guojunbo@ict.ac.cn> 2003
6    Copyright (C) Michael Gernoth <mike@zerfleddert.de> 2006-2008
7    Copyright 2006-2008 Pierre Ossman <ossman@cendio.se> for Cendio AB
8 
9    This program is free software: you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation, either version 3 of the License, or
12    (at your option) any later version.
13 
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18 
19    You should have received a copy of the GNU General Public License
20    along with this program.  If not, see <http://www.gnu.org/licenses/>.
21 */
22 
23 #include "rdesktop.h"
24 #include "rdpsnd.h"
25 #include "rdpsnd_dsp.h"
26 #include <unistd.h>
27 #include <fcntl.h>
28 #include <errno.h>
29 #include <alsa/asoundlib.h>
30 #include <sys/time.h>
31 
32 #define DEFAULTDEVICE	"default"
33 #define MAX_FRAMES	32
34 
35 static struct pollfd pfds_out[32];
36 static size_t num_fds_out;
37 
38 static struct pollfd pfds_in[32];
39 static size_t num_fds_in;
40 
41 static snd_pcm_t *out_handle = NULL;
42 static snd_pcm_t *in_handle = NULL;
43 
44 static RD_BOOL reopened;
45 
46 static short samplewidth_out;
47 static int audiochannels_out;
48 static unsigned int rate_out;
49 
50 static short samplewidth_in;
51 static int audiochannels_in;
52 static unsigned int rate_in;
53 
54 static char *pcm_name;
55 
56 void alsa_play(void);
57 void alsa_record(void);
58 
59 void
alsa_add_fds(int * n,fd_set * rfds,fd_set * wfds,struct timeval * tv)60 alsa_add_fds(int *n, fd_set * rfds, fd_set * wfds, struct timeval *tv)
61 {
62 	UNUSED(tv);
63 	int err;
64 	struct pollfd *f;
65 
66 	if (out_handle && !rdpsnd_queue_empty())
67 	{
68 		num_fds_out = snd_pcm_poll_descriptors_count(out_handle);
69 
70 		if (num_fds_out > sizeof(pfds_out) / sizeof(*pfds_out))
71 			return;
72 
73 		err = snd_pcm_poll_descriptors(out_handle, pfds_out, num_fds_out);
74 		if (err < 0)
75 			return;
76 
77 		for (f = pfds_out; f < &pfds_out[num_fds_out]; f++)
78 		{
79 			if (f->events & POLLIN)
80 				FD_SET(f->fd, rfds);
81 			if (f->events & POLLOUT)
82 				FD_SET(f->fd, wfds);
83 			if (f->fd > *n && (f->events & (POLLIN | POLLOUT)))
84 				*n = f->fd;
85 		}
86 	}
87 
88 	if (in_handle)
89 	{
90 		num_fds_in = snd_pcm_poll_descriptors_count(in_handle);
91 
92 		if (num_fds_in > sizeof(pfds_in) / sizeof(*pfds_in))
93 			return;
94 
95 		err = snd_pcm_poll_descriptors(in_handle, pfds_in, num_fds_in);
96 		if (err < 0)
97 			return;
98 
99 		for (f = pfds_in; f < &pfds_in[num_fds_in]; f++)
100 		{
101 			if (f->events & POLLIN)
102 				FD_SET(f->fd, rfds);
103 			if (f->events & POLLOUT)
104 				FD_SET(f->fd, wfds);
105 			if (f->fd > *n && (f->events & (POLLIN | POLLOUT)))
106 				*n = f->fd;
107 		}
108 	}
109 }
110 
111 void
alsa_check_fds(fd_set * rfds,fd_set * wfds)112 alsa_check_fds(fd_set * rfds, fd_set * wfds)
113 {
114 	struct pollfd *f;
115 	int err;
116 	unsigned short revents;
117 
118 	if (out_handle && !rdpsnd_queue_empty())
119 	{
120 		for (f = pfds_out; f < &pfds_out[num_fds_out]; f++)
121 		{
122 			f->revents = 0;
123 			if (f->fd != -1)
124 			{
125 				/* Fixme: This doesn't properly deal with things like POLLHUP */
126 				if (FD_ISSET(f->fd, rfds))
127 					f->revents |= POLLIN;
128 				if (FD_ISSET(f->fd, wfds))
129 					f->revents |= POLLOUT;
130 			}
131 		}
132 
133 		err = snd_pcm_poll_descriptors_revents(out_handle, pfds_out, num_fds_out, &revents);
134 		if (err < 0)
135 			return;
136 
137 		if (revents & POLLOUT)
138 			alsa_play();
139 	}
140 
141 
142 	if (in_handle)
143 	{
144 		for (f = pfds_in; f < &pfds_in[num_fds_in]; f++)
145 		{
146 			f->revents = 0;
147 			if (f->fd != -1)
148 			{
149 				/* Fixme: This doesn't properly deal with things like POLLHUP */
150 				if (FD_ISSET(f->fd, rfds))
151 					f->revents |= POLLIN;
152 				if (FD_ISSET(f->fd, wfds))
153 					f->revents |= POLLOUT;
154 			}
155 		}
156 
157 		err = snd_pcm_poll_descriptors_revents(in_handle, pfds_in, num_fds_in, &revents);
158 		if (err < 0)
159 			return;
160 
161 		if (revents & POLLIN)
162 			alsa_record();
163 	}
164 }
165 
166 static RD_BOOL
alsa_set_format(snd_pcm_t * pcm,RD_WAVEFORMATEX * pwfx)167 alsa_set_format(snd_pcm_t * pcm, RD_WAVEFORMATEX * pwfx)
168 {
169 	snd_pcm_hw_params_t *hwparams = NULL;
170 	int err;
171 	unsigned int buffertime;
172 	unsigned int rate;
173 
174 	if ((err = snd_pcm_hw_params_malloc(&hwparams)) < 0)
175 	{
176 		logger(Sound, Error, "alsa_set_format(), snd_pcm_hw_params_malloc() failed: %s",
177 		       snd_strerror(err));
178 		return False;
179 	}
180 
181 	if ((err = snd_pcm_hw_params_any(pcm, hwparams)) < 0)
182 	{
183 		logger(Sound, Error, "alsa_set_format(), snd_pcm_hw_params_any() failed: %s",
184 		       snd_strerror(err));
185 		return False;
186 	}
187 
188 	if ((err = snd_pcm_hw_params_set_access(pcm, hwparams, SND_PCM_ACCESS_RW_INTERLEAVED)) < 0)
189 	{
190 		logger(Sound, Error, "alsa_set_format(), snd_pcm_hw_params_set_access() failed: %s",
191 		       snd_strerror(err));
192 		return False;
193 	}
194 
195 	if (pwfx->wBitsPerSample == 16)
196 	{
197 		if ((err = snd_pcm_hw_params_set_format(pcm, hwparams, SND_PCM_FORMAT_S16_LE)) < 0)
198 		{
199 			logger(Sound, Error,
200 			       "alsa_set_format(), snd_pcm_hw_params_set_format() failed: %s",
201 			       snd_strerror(err));
202 			return False;
203 		}
204 	}
205 	else
206 	{
207 		if ((err = snd_pcm_hw_params_set_format(pcm, hwparams, SND_PCM_FORMAT_S8)) < 0)
208 		{
209 			logger(Sound, Error,
210 			       "alsa_set_format(), snd_pcm_hw_params_set_format() failed: %s",
211 			       snd_strerror(err));
212 			return False;
213 		}
214 	}
215 
216 #if 0
217 	if ((err = snd_pcm_hw_params_set_rate_resample(pcm, hwparams, 1)) < 0)
218 	{
219 		logger(Sound, Error,
220 		       "alsa_set_format(), snd_pcm_hw_params_set_rate_resample() failed: %s",
221 		       snd_strerror(err));
222 		return False;
223 	}
224 #endif
225 
226 	rate = pwfx->nSamplesPerSec;
227 	if ((err = snd_pcm_hw_params_set_rate_near(pcm, hwparams, &rate, 0)) < 0)
228 	{
229 		logger(Sound, Error,
230 		       "alsa_set_format(), snd_pcm_hw_params_set_rate_near() failed: %s",
231 		       snd_strerror(err));
232 		return False;
233 	}
234 
235 	if ((err = snd_pcm_hw_params_set_channels(pcm, hwparams, pwfx->nChannels)) < 0)
236 	{
237 		logger(Sound, Error,
238 		       "alsa_set_format(), snd_pcm_hw_params_set_channels() failed: %s",
239 		       snd_strerror(err));
240 		return False;
241 	}
242 
243 
244 	buffertime = 500000;	/* microseconds */
245 	if ((err = snd_pcm_hw_params_set_buffer_time_near(pcm, hwparams, &buffertime, 0)) < 0)
246 	{
247 		logger(Sound, Error,
248 		       "alsa_set_format(), snd_pcm_hw_params_set_buffer_time_near() failed: %s",
249 		       snd_strerror(err));
250 		return False;
251 	}
252 
253 	if ((err = snd_pcm_hw_params(pcm, hwparams)) < 0)
254 	{
255 		logger(Sound, Error, "alsa_set_format(), snd_pcm_hw_params(): %s",
256 		       snd_strerror(err));
257 		return False;
258 	}
259 
260 	snd_pcm_hw_params_free(hwparams);
261 
262 	if ((err = snd_pcm_prepare(pcm)) < 0)
263 	{
264 		logger(Sound, Error, "alsa_set_format(), snd_pcm_prepare() failed: %s\n",
265 		       snd_strerror(err));
266 		return False;
267 	}
268 
269 	reopened = True;
270 
271 	return True;
272 }
273 
274 RD_BOOL
alsa_open_out(void)275 alsa_open_out(void)
276 {
277 	int err;
278 
279 	if ((err = snd_pcm_open(&out_handle, pcm_name, SND_PCM_STREAM_PLAYBACK, 0)) < 0)
280 	{
281 		logger(Sound, Error, "alsa_open_out(), snd_pcm_open() failed: %s",
282 		       snd_strerror(err));
283 		return False;
284 	}
285 
286 	reopened = True;
287 
288 	return True;
289 }
290 
291 void
alsa_close_out(void)292 alsa_close_out(void)
293 {
294 	/* Ack all remaining packets */
295 	while (!rdpsnd_queue_empty())
296 		rdpsnd_queue_next(0);
297 
298 	if (out_handle)
299 	{
300 		snd_pcm_close(out_handle);
301 		out_handle = NULL;
302 	}
303 }
304 
305 RD_BOOL
alsa_format_supported(RD_WAVEFORMATEX * pwfx)306 alsa_format_supported(RD_WAVEFORMATEX * pwfx)
307 {
308 #if 0
309 	int err;
310 	snd_pcm_hw_params_t *hwparams = NULL;
311 
312 	if ((err = snd_pcm_hw_params_malloc(&hwparams)) < 0)
313 	{
314 		logger(Sound, Error,
315 		       "alsa_format_supported(), snd_pcm_hw_params_malloc() failed: %s",
316 		       snd_strerror(err));
317 		return False;
318 	}
319 
320 	if ((err = snd_pcm_hw_params_any(pcm_handle, hwparams)) < 0)
321 	{
322 		logger(Sound, Error,
323 		       "alsa_format_supported(), snd_pcm_hw_params_any() failed: %s\n",
324 		       snd_strerror(err));
325 		return False;
326 	}
327 	snd_pcm_hw_params_free(hwparams);
328 #endif
329 
330 	if (pwfx->wFormatTag != WAVE_FORMAT_PCM)
331 		return False;
332 	if ((pwfx->nChannels != 1) && (pwfx->nChannels != 2))
333 		return False;
334 	if ((pwfx->wBitsPerSample != 8) && (pwfx->wBitsPerSample != 16))
335 		return False;
336 	if ((pwfx->nSamplesPerSec != 44100) && (pwfx->nSamplesPerSec != 22050))
337 		return False;
338 
339 	return True;
340 }
341 
342 RD_BOOL
alsa_set_format_out(RD_WAVEFORMATEX * pwfx)343 alsa_set_format_out(RD_WAVEFORMATEX * pwfx)
344 {
345 	if (!alsa_set_format(out_handle, pwfx))
346 		return False;
347 
348 	samplewidth_out = pwfx->wBitsPerSample / 8;
349 	audiochannels_out = pwfx->nChannels;
350 	rate_out = pwfx->nSamplesPerSec;
351 
352 	return True;
353 }
354 
355 void
alsa_play(void)356 alsa_play(void)
357 {
358 	struct audio_packet *packet;
359 	STREAM out;
360 	int len;
361 	const unsigned char *data;
362 	size_t before;
363 	static long prev_s, prev_us;
364 	int duration;
365 	struct timeval tv;
366 	int next_tick;
367 
368 	if (reopened)
369 	{
370 		reopened = False;
371 		gettimeofday(&tv, NULL);
372 		prev_s = tv.tv_sec;
373 		prev_us = tv.tv_usec;
374 	}
375 
376 	/* We shouldn't be called if the queue is empty, but still */
377 	if (rdpsnd_queue_empty())
378 		return;
379 
380 	packet = rdpsnd_queue_current_packet();
381 	out = packet->s;
382 
383 	next_tick = rdpsnd_queue_next_tick();
384 
385 	before = s_tell(out);
386 
387 	len = s_remaining(out) / (samplewidth_out * audiochannels_out);
388 	len = MIN(len, MAX_FRAMES);
389 	in_uint8p(out, data, len);
390 
391 	len = snd_pcm_writei(out_handle, data, len);
392 	if (len < 0)
393 	{
394 		snd_pcm_prepare(out_handle);
395 		len = 0;
396 	}
397 
398 	/* We might not have written everything */
399 	s_seek(out, before + len * samplewidth_out * audiochannels_out);
400 
401 	gettimeofday(&tv, NULL);
402 
403 	duration = ((tv.tv_sec - prev_s) * 1000000 + (tv.tv_usec - prev_us)) / 1000;
404 
405 	if (packet->tick > next_tick)
406 		next_tick += 65536;
407 
408 	if (s_check_end(out) || duration > next_tick - packet->tick + 500)
409 	{
410 		snd_pcm_sframes_t delay_frames;
411 		unsigned long delay_us;
412 
413 		prev_s = tv.tv_sec;
414 		prev_us = tv.tv_usec;
415 
416 		if (abs((next_tick - packet->tick) - duration) > 20)
417 		{
418 			logger(Sound, Debug,
419 			       "alsa_play(), duration=%d, calc=%d, last=%d, is=%d, should=%d",
420 			       duration, next_tick - packet->tick, packet->tick,
421 			       (packet->tick + duration) % 65536, next_tick % 65536);
422 		}
423 
424 		if (snd_pcm_delay(out_handle, &delay_frames) < 0)
425 			delay_frames = out->size / (samplewidth_out * audiochannels_out);
426 		if (delay_frames < 0)
427 			delay_frames = 0;
428 
429 		delay_us = delay_frames * (1000000 / rate_out);
430 
431 		rdpsnd_queue_next(delay_us);
432 	}
433 }
434 
435 RD_BOOL
alsa_open_in(void)436 alsa_open_in(void)
437 {
438 	int err;
439 
440 	if ((err =
441 	     snd_pcm_open(&in_handle, pcm_name, SND_PCM_STREAM_CAPTURE, SND_PCM_NONBLOCK)) < 0)
442 	{
443 		logger(Sound, Error, "alsa_open_in(), snd_pcm_open() failed: %s",
444 		       snd_strerror(err));
445 		return False;
446 	}
447 
448 	return True;
449 }
450 
451 void
alsa_close_in(void)452 alsa_close_in(void)
453 {
454 	if (in_handle)
455 	{
456 		snd_pcm_close(in_handle);
457 		in_handle = NULL;
458 	}
459 }
460 
461 RD_BOOL
alsa_set_format_in(RD_WAVEFORMATEX * pwfx)462 alsa_set_format_in(RD_WAVEFORMATEX * pwfx)
463 {
464 	int err;
465 
466 	if (!alsa_set_format(in_handle, pwfx))
467 		return False;
468 
469 	if ((err = snd_pcm_start(in_handle)) < 0)
470 	{
471 		logger(Sound, Error, "alsa_open_in(), snd_pcm_start() failed: %s",
472 		       snd_strerror(err));
473 		return False;
474 	}
475 
476 	samplewidth_in = pwfx->wBitsPerSample / 8;
477 	audiochannels_in = pwfx->nChannels;
478 	rate_in = pwfx->nSamplesPerSec;
479 
480 	return True;
481 }
482 
483 void
alsa_record(void)484 alsa_record(void)
485 {
486 	int len;
487 	char buffer[32768];
488 
489 	len = snd_pcm_readi(in_handle, buffer,
490 			    sizeof(buffer) / (samplewidth_in * audiochannels_in));
491 	if (len < 0)
492 	{
493 		snd_pcm_prepare(in_handle);
494 		len = 0;
495 	}
496 
497 	rdpsnd_record(buffer, len * samplewidth_in * audiochannels_in);
498 }
499 
500 struct audio_driver *
alsa_register(char * options)501 alsa_register(char *options)
502 {
503 	static struct audio_driver alsa_driver;
504 
505 	memset(&alsa_driver, 0, sizeof(alsa_driver));
506 
507 	alsa_driver.name = "alsa";
508 	alsa_driver.description = "ALSA output driver, default device: " DEFAULTDEVICE;
509 
510 	alsa_driver.add_fds = alsa_add_fds;
511 	alsa_driver.check_fds = alsa_check_fds;
512 
513 	alsa_driver.wave_out_open = alsa_open_out;
514 	alsa_driver.wave_out_close = alsa_close_out;
515 	alsa_driver.wave_out_format_supported = alsa_format_supported;
516 	alsa_driver.wave_out_set_format = alsa_set_format_out;
517 	alsa_driver.wave_out_volume = rdpsnd_dsp_softvol_set;
518 
519 	alsa_driver.wave_in_open = alsa_open_in;
520 	alsa_driver.wave_in_close = alsa_close_in;
521 	alsa_driver.wave_in_format_supported = alsa_format_supported;
522 	alsa_driver.wave_in_set_format = alsa_set_format_in;
523 	alsa_driver.wave_in_volume = NULL;	/* FIXME */
524 
525 	alsa_driver.need_byteswap_on_be = 0;
526 	alsa_driver.need_resampling = 0;
527 
528 	if (options)
529 	{
530 		pcm_name = xstrdup(options);
531 	}
532 	else
533 	{
534 		pcm_name = DEFAULTDEVICE;
535 	}
536 
537 	return &alsa_driver;
538 }
539