2 * This small demo sends a simple sinusoidal wave to your speakers.
11 #include "../include/asoundlib.h"
15 char *device = "plughw:0,0"; /* playback device */
16 snd_pcm_format_t format = SND_PCM_FORMAT_S16; /* sample format */
17 unsigned int rate = 44100; /* stream rate */
18 unsigned int channels = 1; /* count of channels */
19 unsigned int buffer_time = 500000; /* ring buffer length in us */
20 unsigned int period_time = 100000; /* period time in us */
21 double freq = 440; /* sinusoidal wave frequency in Hz */
22 int verbose = 0; /* verbose flag */
23 int resample = 1; /* enable alsa-lib resampling */
25 snd_pcm_sframes_t buffer_size;
26 snd_pcm_sframes_t period_size;
27 snd_output_t *output = NULL;
29 static void generate_sine(const snd_pcm_channel_area_t *areas,
30 snd_pcm_uframes_t offset,
31 int count, double *_phase)
33 static double max_phase = 2. * M_PI;
34 double phase = *_phase;
35 double step = max_phase*freq/(double)rate;
37 unsigned char *samples[channels], *tmp;
39 unsigned int chn, byte;
41 unsigned int maxval = (1 << (snd_pcm_format_width(format) - 1)) - 1;
42 int bps = snd_pcm_format_width(format) / 8; /* bytes per sample */
44 /* verify and prepare the contents of areas */
45 for (chn = 0; chn < channels; chn++) {
46 if ((areas[chn].first % 8) != 0) {
47 printf("areas[%i].first == %i, aborting...\n", chn, areas[chn].first);
50 samples[chn] = /*(signed short *)*/(((unsigned char *)areas[chn].addr) + (areas[chn].first / 8));
51 if ((areas[chn].step % 16) != 0) {
52 printf("areas[%i].step == %i, aborting...\n", chn, areas[chn].step);
55 steps[chn] = areas[chn].step / 8;
56 samples[chn] += offset * steps[chn];
58 /* fill the channel areas */
60 res = sin(phase) * maxval;
62 tmp = (unsigned char *)(&ires);
63 for (chn = 0; chn < channels; chn++) {
64 for (byte = 0; byte < bps; byte++)
65 *(samples[chn] + byte) = tmp[byte];
66 samples[chn] += steps[chn];
69 if (phase >= max_phase)
75 static int set_hwparams(snd_pcm_t *handle,
76 snd_pcm_hw_params_t *params,
77 snd_pcm_access_t access)
82 /* choose all parameters */
83 err = snd_pcm_hw_params_any(handle, params);
85 printf("Broken configuration for playback: no configurations available: %s\n", snd_strerror(err));
88 /* set hardware resampling */
89 err = snd_pcm_hw_params_set_rate_resample(handle, params, resample);
91 printf("Resampling setup failed for playback: %s\n", snd_strerror(err));
94 /* set the interleaved read/write format */
95 err = snd_pcm_hw_params_set_access(handle, params, access);
97 printf("Access type not available for playback: %s\n", snd_strerror(err));
100 /* set the sample format */
101 err = snd_pcm_hw_params_set_format(handle, params, format);
103 printf("Sample format not available for playback: %s\n", snd_strerror(err));
106 /* set the count of channels */
107 err = snd_pcm_hw_params_set_channels(handle, params, channels);
109 printf("Channels count (%i) not available for playbacks: %s\n", channels, snd_strerror(err));
112 /* set the stream rate */
114 err = snd_pcm_hw_params_set_rate_near(handle, params, &rrate, 0);
116 printf("Rate %iHz not available for playback: %s\n", rate, snd_strerror(err));
120 printf("Rate doesn't match (requested %iHz, get %iHz)\n", rate, err);
123 /* set the buffer time */
124 err = snd_pcm_hw_params_set_buffer_time_near(handle, params, &buffer_time, &dir);
126 printf("Unable to set buffer time %i for playback: %s\n", buffer_time, snd_strerror(err));
129 err = snd_pcm_hw_params_get_buffer_size(params, &buffer_size);
131 printf("Unable to get buffer size for playback: %s\n", snd_strerror(err));
134 /* set the period time */
135 err = snd_pcm_hw_params_set_period_time_near(handle, params, &period_time, &dir);
137 printf("Unable to set period time %i for playback: %s\n", period_time, snd_strerror(err));
140 err = snd_pcm_hw_params_get_period_size(params, &period_size, &dir);
142 printf("Unable to get period size for playback: %s\n", snd_strerror(err));
145 /* write the parameters to device */
146 err = snd_pcm_hw_params(handle, params);
148 printf("Unable to set hw params for playback: %s\n", snd_strerror(err));
154 static int set_swparams(snd_pcm_t *handle, snd_pcm_sw_params_t *swparams)
158 /* get the current swparams */
159 err = snd_pcm_sw_params_current(handle, swparams);
161 printf("Unable to determine current swparams for playback: %s\n", snd_strerror(err));
164 /* start the transfer when the buffer is almost full: */
165 /* (buffer_size / avail_min) * avail_min */
166 err = snd_pcm_sw_params_set_start_threshold(handle, swparams, (buffer_size / period_size) * period_size);
168 printf("Unable to set start threshold mode for playback: %s\n", snd_strerror(err));
171 /* allow the transfer when at least period_size samples can be processed */
172 err = snd_pcm_sw_params_set_avail_min(handle, swparams, period_size);
174 printf("Unable to set avail min for playback: %s\n", snd_strerror(err));
177 /* align all transfers to 1 sample */
178 err = snd_pcm_sw_params_set_xfer_align(handle, swparams, 1);
180 printf("Unable to set transfer align for playback: %s\n", snd_strerror(err));
183 /* write the parameters to the playback device */
184 err = snd_pcm_sw_params(handle, swparams);
186 printf("Unable to set sw params for playback: %s\n", snd_strerror(err));
193 * Underrun and suspend recovery
196 static int xrun_recovery(snd_pcm_t *handle, int err)
198 if (err == -EPIPE) { /* under-run */
199 err = snd_pcm_prepare(handle);
201 printf("Can't recovery from underrun, prepare failed: %s\n", snd_strerror(err));
203 } else if (err == -ESTRPIPE) {
204 while ((err = snd_pcm_resume(handle)) == -EAGAIN)
205 sleep(1); /* wait until the suspend flag is released */
207 err = snd_pcm_prepare(handle);
209 printf("Can't recovery from suspend, prepare failed: %s\n", snd_strerror(err));
217 * Transfer method - write only
220 static int write_loop(snd_pcm_t *handle,
221 signed short *samples,
222 snd_pcm_channel_area_t *areas)
229 generate_sine(areas, 0, period_size, &phase);
233 err = snd_pcm_writei(handle, ptr, cptr);
237 if (xrun_recovery(handle, err) < 0) {
238 printf("Write error: %s\n", snd_strerror(err));
241 break; /* skip one period */
243 ptr += err * channels;
250 * Transfer method - write and wait for room in buffer using poll
253 static int wait_for_poll(snd_pcm_t *handle, struct pollfd *ufds, unsigned int count)
255 unsigned short revents;
258 poll(ufds, count, -1);
259 snd_pcm_poll_descriptors_revents(handle, ufds, count, &revents);
260 if (revents & POLLERR)
262 if (revents & POLLOUT)
267 static int write_and_poll_loop(snd_pcm_t *handle,
268 signed short *samples,
269 snd_pcm_channel_area_t *areas)
274 int err, count, cptr, init;
276 count = snd_pcm_poll_descriptors_count (handle);
278 printf("Invalid poll descriptors count\n");
282 ufds = malloc(sizeof(struct pollfd) * count);
284 printf("No enough memory\n");
287 if ((err = snd_pcm_poll_descriptors(handle, ufds, count)) < 0) {
288 printf("Unable to obtain poll descriptors for playback: %s\n", snd_strerror(err));
295 err = wait_for_poll(handle, ufds, count);
297 if (snd_pcm_state(handle) == SND_PCM_STATE_XRUN ||
298 snd_pcm_state(handle) == SND_PCM_STATE_SUSPENDED) {
299 err = snd_pcm_state(handle) == SND_PCM_STATE_XRUN ? -EPIPE : -ESTRPIPE;
300 if (xrun_recovery(handle, err) < 0) {
301 printf("Write error: %s\n", snd_strerror(err));
306 printf("Wait for poll failed\n");
312 generate_sine(areas, 0, period_size, &phase);
316 err = snd_pcm_writei(handle, ptr, cptr);
318 if (xrun_recovery(handle, err) < 0) {
319 printf("Write error: %s\n", snd_strerror(err));
323 break; /* skip one period */
325 if (snd_pcm_state(handle) == SND_PCM_STATE_RUNNING)
327 ptr += err * channels;
331 /* it is possible, that the initial buffer cannot store */
332 /* all data from the last period, so wait awhile */
333 err = wait_for_poll(handle, ufds, count);
335 if (snd_pcm_state(handle) == SND_PCM_STATE_XRUN ||
336 snd_pcm_state(handle) == SND_PCM_STATE_SUSPENDED) {
337 err = snd_pcm_state(handle) == SND_PCM_STATE_XRUN ? -EPIPE : -ESTRPIPE;
338 if (xrun_recovery(handle, err) < 0) {
339 printf("Write error: %s\n", snd_strerror(err));
344 printf("Wait for poll failed\n");
353 * Transfer method - asynchronous notification
356 struct async_private_data {
357 signed short *samples;
358 snd_pcm_channel_area_t *areas;
362 static void async_callback(snd_async_handler_t *ahandler)
364 snd_pcm_t *handle = snd_async_handler_get_pcm(ahandler);
365 struct async_private_data *data = snd_async_handler_get_callback_private(ahandler);
366 signed short *samples = data->samples;
367 snd_pcm_channel_area_t *areas = data->areas;
368 snd_pcm_sframes_t avail;
371 avail = snd_pcm_avail_update(handle);
372 while (avail >= period_size) {
373 generate_sine(areas, 0, period_size, &data->phase);
374 err = snd_pcm_writei(handle, samples, period_size);
376 printf("Initial write error: %s\n", snd_strerror(err));
379 if (err != period_size) {
380 printf("Initial write error: written %i expected %li\n", err, period_size);
383 avail = snd_pcm_avail_update(handle);
387 static int async_loop(snd_pcm_t *handle,
388 signed short *samples,
389 snd_pcm_channel_area_t *areas)
391 struct async_private_data data;
392 snd_async_handler_t *ahandler;
395 data.samples = samples;
398 err = snd_async_add_pcm_handler(&ahandler, handle, async_callback, &data);
400 printf("Unable to register async handler\n");
403 for (count = 0; count < 2; count++) {
404 generate_sine(areas, 0, period_size, &data.phase);
405 err = snd_pcm_writei(handle, samples, period_size);
407 printf("Initial write error: %s\n", snd_strerror(err));
410 if (err != period_size) {
411 printf("Initial write error: written %i expected %li\n", err, period_size);
415 err = snd_pcm_start(handle);
417 printf("Start error: %s\n", snd_strerror(err));
421 /* because all other work is done in the signal handler,
422 suspend the process */
429 * Transfer method - asynchronous notification + direct write
432 static void async_direct_callback(snd_async_handler_t *ahandler)
434 snd_pcm_t *handle = snd_async_handler_get_pcm(ahandler);
435 struct async_private_data *data = snd_async_handler_get_callback_private(ahandler);
436 const snd_pcm_channel_area_t *my_areas;
437 snd_pcm_uframes_t offset, frames, size;
438 snd_pcm_sframes_t avail, commitres;
439 snd_pcm_state_t state;
443 state = snd_pcm_state(handle);
444 if (state == SND_PCM_STATE_XRUN) {
445 err = xrun_recovery(handle, -EPIPE);
447 printf("XRUN recovery failed: %s\n", snd_strerror(err));
451 } else if (state == SND_PCM_STATE_SUSPENDED) {
452 err = xrun_recovery(handle, -ESTRPIPE);
454 printf("SUSPEND recovery failed: %s\n", snd_strerror(err));
458 avail = snd_pcm_avail_update(handle);
460 err = xrun_recovery(handle, avail);
462 printf("avail update failed: %s\n", snd_strerror(err));
468 if (avail < period_size) {
471 err = snd_pcm_start(handle);
473 printf("Start error: %s\n", snd_strerror(err));
484 err = snd_pcm_mmap_begin(handle, &my_areas, &offset, &frames);
486 if ((err = xrun_recovery(handle, err)) < 0) {
487 printf("MMAP begin avail error: %s\n", snd_strerror(err));
492 generate_sine(my_areas, offset, frames, &data->phase);
493 commitres = snd_pcm_mmap_commit(handle, offset, frames);
494 if (commitres < 0 || (snd_pcm_uframes_t)commitres != frames) {
495 if ((err = xrun_recovery(handle, commitres >= 0 ? -EPIPE : commitres)) < 0) {
496 printf("MMAP commit error: %s\n", snd_strerror(err));
506 static int async_direct_loop(snd_pcm_t *handle,
507 signed short *samples,
508 snd_pcm_channel_area_t *areas)
510 struct async_private_data data;
511 snd_async_handler_t *ahandler;
512 const snd_pcm_channel_area_t *my_areas;
513 snd_pcm_uframes_t offset, frames, size;
514 snd_pcm_sframes_t commitres;
517 data.samples = NULL; /* we do not require the global sample area for direct write */
518 data.areas = NULL; /* we do not require the global areas for direct write */
520 err = snd_async_add_pcm_handler(&ahandler, handle, async_direct_callback, &data);
522 printf("Unable to register async handler\n");
525 for (count = 0; count < 2; count++) {
529 err = snd_pcm_mmap_begin(handle, &my_areas, &offset, &frames);
531 if ((err = xrun_recovery(handle, err)) < 0) {
532 printf("MMAP begin avail error: %s\n", snd_strerror(err));
536 generate_sine(my_areas, offset, frames, &data.phase);
537 commitres = snd_pcm_mmap_commit(handle, offset, frames);
538 if (commitres < 0 || (snd_pcm_uframes_t)commitres != frames) {
539 if ((err = xrun_recovery(handle, commitres >= 0 ? -EPIPE : commitres)) < 0) {
540 printf("MMAP commit error: %s\n", snd_strerror(err));
547 err = snd_pcm_start(handle);
549 printf("Start error: %s\n", snd_strerror(err));
553 /* because all other work is done in the signal handler,
554 suspend the process */
561 * Transfer method - direct write only
564 static int direct_loop(snd_pcm_t *handle,
565 signed short *samples,
566 snd_pcm_channel_area_t *areas)
569 const snd_pcm_channel_area_t *my_areas;
570 snd_pcm_uframes_t offset, frames, size;
571 snd_pcm_sframes_t avail, commitres;
572 snd_pcm_state_t state;
576 state = snd_pcm_state(handle);
577 if (state == SND_PCM_STATE_XRUN) {
578 err = xrun_recovery(handle, -EPIPE);
580 printf("XRUN recovery failed: %s\n", snd_strerror(err));
584 } else if (state == SND_PCM_STATE_SUSPENDED) {
585 err = xrun_recovery(handle, -ESTRPIPE);
587 printf("SUSPEND recovery failed: %s\n", snd_strerror(err));
591 avail = snd_pcm_avail_update(handle);
593 err = xrun_recovery(handle, avail);
595 printf("avail update failed: %s\n", snd_strerror(err));
601 if (avail < period_size) {
604 err = snd_pcm_start(handle);
606 printf("Start error: %s\n", snd_strerror(err));
610 err = snd_pcm_wait(handle, -1);
612 if ((err = xrun_recovery(handle, err)) < 0) {
613 printf("snd_pcm_wait error: %s\n", snd_strerror(err));
624 err = snd_pcm_mmap_begin(handle, &my_areas, &offset, &frames);
626 if ((err = xrun_recovery(handle, err)) < 0) {
627 printf("MMAP begin avail error: %s\n", snd_strerror(err));
632 generate_sine(my_areas, offset, frames, &phase);
633 commitres = snd_pcm_mmap_commit(handle, offset, frames);
634 if (commitres < 0 || (snd_pcm_uframes_t)commitres != frames) {
635 if ((err = xrun_recovery(handle, commitres >= 0 ? -EPIPE : commitres)) < 0) {
636 printf("MMAP commit error: %s\n", snd_strerror(err));
647 * Transfer method - direct write only using mmap_write functions
650 static int direct_write_loop(snd_pcm_t *handle,
651 signed short *samples,
652 snd_pcm_channel_area_t *areas)
659 generate_sine(areas, 0, period_size, &phase);
663 err = snd_pcm_mmap_writei(handle, ptr, cptr);
667 if (xrun_recovery(handle, err) < 0) {
668 printf("Write error: %s\n", snd_strerror(err));
671 break; /* skip one period */
673 ptr += err * channels;
683 struct transfer_method {
685 snd_pcm_access_t access;
686 int (*transfer_loop)(snd_pcm_t *handle,
687 signed short *samples,
688 snd_pcm_channel_area_t *areas);
691 static struct transfer_method transfer_methods[] = {
692 { "write", SND_PCM_ACCESS_RW_INTERLEAVED, write_loop },
693 { "write_and_poll", SND_PCM_ACCESS_RW_INTERLEAVED, write_and_poll_loop },
694 { "async", SND_PCM_ACCESS_RW_INTERLEAVED, async_loop },
695 { "async_direct", SND_PCM_ACCESS_MMAP_INTERLEAVED, async_direct_loop },
696 { "direct_interleaved", SND_PCM_ACCESS_MMAP_INTERLEAVED, direct_loop },
697 { "direct_noninterleaved", SND_PCM_ACCESS_MMAP_NONINTERLEAVED, direct_loop },
698 { "direct_write", SND_PCM_ACCESS_MMAP_INTERLEAVED, direct_write_loop },
699 { NULL, SND_PCM_ACCESS_RW_INTERLEAVED, NULL }
702 static void help(void)
706 "Usage: pcm [OPTION]... [FILE]...\n"
708 "-D,--device playback device\n"
709 "-r,--rate stream rate in Hz\n"
710 "-c,--channels count of channels in stream\n"
711 "-f,--frequency sine wave frequency in Hz\n"
712 "-b,--buffer ring buffer size in us\n"
713 "-p,--period period size in us\n"
714 "-m,--method transfer method\n"
715 "-o,--format sample format\n"
716 "-v,--verbose show the PCM setup parameters\n"
718 printf("Recognized sample formats are:");
719 for (k = 0; k < SND_PCM_FORMAT_LAST; ++(unsigned long) k) {
720 const char *s = snd_pcm_format_name(k);
725 printf("Recognized transfer methods are:");
726 for (k = 0; transfer_methods[k].name; k++)
727 printf(" %s", transfer_methods[k].name);
731 int main(int argc, char *argv[])
733 struct option long_option[] =
735 {"help", 0, NULL, 'h'},
736 {"device", 1, NULL, 'D'},
737 {"rate", 1, NULL, 'r'},
738 {"channels", 1, NULL, 'c'},
739 {"frequency", 1, NULL, 'f'},
740 {"buffer", 1, NULL, 'b'},
741 {"period", 1, NULL, 'p'},
742 {"method", 1, NULL, 'm'},
743 {"format", 1, NULL, 'o'},
744 {"verbose", 1, NULL, 'v'},
745 {"noresample", 1, NULL, 'n'},
750 snd_pcm_hw_params_t *hwparams;
751 snd_pcm_sw_params_t *swparams;
753 signed short *samples;
755 snd_pcm_channel_area_t *areas;
757 snd_pcm_hw_params_alloca(&hwparams);
758 snd_pcm_sw_params_alloca(&swparams);
763 if ((c = getopt_long(argc, argv, "hD:r:c:f:b:p:m:o:vn", long_option, NULL)) < 0)
770 device = strdup(optarg);
774 rate = rate < 4000 ? 4000 : rate;
775 rate = rate > 196000 ? 196000 : rate;
778 channels = atoi(optarg);
779 channels = channels < 1 ? 1 : channels;
780 channels = channels > 1024 ? 1024 : channels;
784 freq = freq < 50 ? 50 : freq;
785 freq = freq > 5000 ? 5000 : freq;
788 buffer_time = atoi(optarg);
789 buffer_time = buffer_time < 1000 ? 1000 : buffer_time;
790 buffer_time = buffer_time > 1000000 ? 1000000 : buffer_time;
793 period_time = atoi(optarg);
794 period_time = period_time < 1000 ? 1000 : period_time;
795 period_time = period_time > 1000000 ? 1000000 : period_time;
798 for (method = 0; transfer_methods[method].name; method++)
799 if (!strcasecmp(transfer_methods[method].name, optarg))
801 if (transfer_methods[method].name == NULL)
805 for (format = 0; format < SND_PCM_FORMAT_LAST; format++) {
806 const char *format_name = snd_pcm_format_name(format);
808 if (!strcasecmp(format_name, optarg))
811 if (format == SND_PCM_FORMAT_LAST)
812 format = SND_PCM_FORMAT_S16;
828 err = snd_output_stdio_attach(&output, stdout, 0);
830 printf("Output failed: %s\n", snd_strerror(err));
834 printf("Playback device is %s\n", device);
835 printf("Stream parameters are %iHz, %s, %i channels\n", rate, snd_pcm_format_name(format), channels);
836 printf("Sine wave rate is %.4fHz\n", freq);
837 printf("Using transfer method: %s\n", transfer_methods[method].name);
839 if ((err = snd_pcm_open(&handle, device, SND_PCM_STREAM_PLAYBACK, 0)) < 0) {
840 printf("Playback open error: %s\n", snd_strerror(err));
844 if ((err = set_hwparams(handle, hwparams, transfer_methods[method].access)) < 0) {
845 printf("Setting of hwparams failed: %s\n", snd_strerror(err));
848 if ((err = set_swparams(handle, swparams)) < 0) {
849 printf("Setting of swparams failed: %s\n", snd_strerror(err));
854 snd_pcm_dump(handle, output);
856 samples = malloc((period_size * channels * snd_pcm_format_width(format)) / 8);
857 if (samples == NULL) {
858 printf("No enough memory\n");
862 areas = calloc(channels, sizeof(snd_pcm_channel_area_t));
864 printf("No enough memory\n");
867 for (chn = 0; chn < channels; chn++) {
868 areas[chn].addr = samples;
869 areas[chn].first = chn * snd_pcm_format_width(format);
870 areas[chn].step = channels * snd_pcm_format_width(format);
873 err = transfer_methods[method].transfer_loop(handle, samples, areas);
875 printf("Transfer failed: %s\n", snd_strerror(err));
879 snd_pcm_close(handle);