Close

True hotplug, buffer overruns

A project log for Piano signal processor

Add metronome, reverb, compression, recording in an outboard box.

lion mclionheadlion mclionhead 04/06/2021 at 06:050 Comments

To run it as a daemon, it needed to truly detect when the soundcard & the instrument were unplugged, then stop the signal processing when the instrument was unplugged.  Detecting when ALSA is unplugged requires a complicated polling routine.

snd_pcm_status_t *status;
snd_pcm_status_malloc(&status);
snd_pcm_status(dsp_out, status);
int state = snd_pcm_status_get_state(status);
snd_pcm_status_free(status);

if(state == 0)
{

// disconnected

}

Detecting a USB disconnect requires testing for a LIBUSB_TRANSFER_STALL.

The next problem was buffer overruns when recording, despite using O_DIRECT.  The activity LED tended to get stuck on.  

The raspberry pi uses a swap space on the SD card which must be disabled.  

root@piano:/root% swapon --show

NAME      TYPE SIZE USED PRIO
/var/swap file 100M   0B   -2

The easiest solution is renaming /usr/sbin/swapon to /usr/sbin/swapon.bak

The raspberry pi has enough RAM to record 3 hours of audio in RAM, but to simplify the pointer math, the FIFO can be expanded to just 30 minutes.  The worst case would be to record to RAM & write it after the user stops, but it wouldn't be resistant to power outages.  

After recording for 51 minutes,

F   UID   PID  PPID PRI  NI    VSZ   RSS WCHAN  STAT TTY        TIME COMMAND

4     0  1790     1  -2   - 772096 469844 hrtime Sl  ?         30:29 ./piano

It filled the entire allocated buffer because it's a ring buffer, but it didn't have a single overrun.  It could be optimized by capturing the longest fill size, but that would be wasting the raspberry pi's 4GB of RAM.  The LED only seemed to stay on for 1 minute at most.

Discussions