Search code examples
clinuxalsa

Paul Davis' 2002 "Interrupt Driven" ALSA Example Code Still Valid Today?


I'm learning how to poll/wait to fill the sound card buffer using the ALSA API. I wanted to know if Paul Davis' (author of JACK) 2002 example code titled "A Minimal Interrupt-Driven Program" is still valid today:

http://equalarea.com/paul/alsa-audio.html

I've also read that snd_pcm_wait() uses the poll() system call, so that should be fine. Will snd_pcm_avail_update(), which does not use system calls, return the correct number of frames because it was called after snd_pcm_wait() (which would presumably updates the status of the buffer)?

    while (1) {

        /* wait till the interface is ready for data, or 1 second
           has elapsed.
        */

        if ((err = snd_pcm_wait (playback_handle, 1000)) < 0) {
                fprintf (stderr, "poll failed (%s)\n", strerror (errno));
                break;
        }              

        /* find out how much space is available for playback data */

        if ((frames_to_deliver = snd_pcm_avail_update (playback_handle)) < 0) {
            if (frames_to_deliver == -EPIPE) {
                fprintf (stderr, "an xrun occured\n");
                break;
            } else {
                fprintf (stderr, "unknown ALSA avail update return value (%d)\n", 
                     frames_to_deliver);
                break;
            }
        }

        frames_to_deliver = frames_to_deliver > 4096 ? 4096 : frames_to_deliver;

        /* deliver the data */

        if (playback_callback (frames_to_deliver) != frames_to_deliver) {
                fprintf (stderr, "playback callback failed\n");
            break;
        }
    }

    snd_pcm_close (playback_handle);
    exit (0);
}

Solution

  • The various buffer pointers are automatically updated at every period boundary, where interrupts are delivered.

    snd_pcm_wait() is woken up by such interrupts, so directly after a call, the status as read by snd_pcm_avail_update() is correct.