Minimizing TTM for Embedded Applications with GNU Guix
Extreme programming art (a SuperCollider application on a ARM64 device)
Programming novel ideas is great: feel inspired, sit down, hack it out, press enter (or some arcane combination on the keyboard) and watch it go. Sadly, in the real world this usually does not go right from the first try. We are used to trial and error, working our ways through the stack of abstractions, fixing all the issues until it finally works. Often, the fun part (hacking out your idea) takes much less time than making it work in the target environment.
Maintainability, reproducibility, hackability and development speed are often thought of as contradictions or mutual exclusives. With GNU Guix this is not the case, and can even be fun!
the issue with toolchains, environments and (embedded) operating systems
or: Optimizing TTM vs. reproducing and hacking maintainable toolchains
It is be clear that bringing products to the market is essential, should, for example, an employer want to get some of the money they invest in salaries to return. Research and Development is expensive, markets are chaotic. How can one know if a product will return a profit or mostly be ignored by potential customers?
Therefor, enterprises optimize time-to-market (TTM). The faster a product can land on a market the faster the company can evaluate who they reach, which parts customers like, what they should adjust or alter on the product, etc. Short development times imply reduced development cost (for equally sized teams, that is).
In the context of embedded software development this boils down to buying boards with widely used SoCs, downloading a huge container or disk image containing a toolchain (which usually is just some configuration of readily available Free Software tools) and having a go at it. This certainly saves a bunch of time (after all, disk space is still regarded as practically free) and provides with a readily available environment for development.
But this is far from optimal: Not only need we blindly trust the creators, vendors or distributors of these GiB of binary data, we are often unable to inspect or fix them—or can only do that with an infeasible amount of work. This is one of the many areas where GNU Guix excels in: with Guix we build binary artifacts in a reproducible, understandable and thus maintainable manner. But can we use that outside of packaging and distributing software or (desktop) operating systems? Of course!
the project
the idea
I got the chance to contribute to an arts exhibition with a sound installation. The show would take place in a small white cube setting: a single room with white walls where paintings are hung. The exhibition is open for the public on several days for several hours.
constraints
I will surely need some speakers and means of amplicifation, but also a sound source. I neither:
- want to record hours of audio that is exactly the same whenever it is turned on, nor do I
- want to leave my laptop or other expensive computer (or other device) unattended in the gallery just to play some audio.
So, I will create a minimalist, supplementary sound installation that procedurally generates audio as long as it runs! I want the installation to start as soon as the device is powered on—minimizing potential user (in this case: the person turning the device on in the exhibition) error.
This should just be doable as a holiday side project in two or three afternoons—which is exactly the amount of time I have at hands… What an awesome coincidence!
the stack
I own a single-board computer that I know runs Linux and has an audio output: a Rock64 LTS. I've created Guix system images for that device, flashed them to some microSD card and booted those before, so I know this works.
I write the application in SuperCollider, because it enables to do whatever you want in audio. You should know what you want to do, though, otherwise it will just be overwhelming, far too very complicated and probably taking more than a couple of afternoons time.
the program
The SuperCollider program is rather simple: a bunch of SynthDefs
(these constitute the basic sound-generating abstraction that gets
sent to the server scsynth), some Pattern
bindings (which trigger the server to play the previously defined
sounds according to some rules) and we're good to go. It's supposed
to be minimalist, after all.
s.waitForBoot{
SynthDef.new(\wind, {
| t_trig=0, amp=0.001, freq=11000, reso=6, pan=0, atk=4, len=20, dcy=4 |
var vol = (-0.5*reso).dbamp.neg*amp;
var env = Env.linen(atk, len, dcy, curve: \cub);
var snd = WhiteNoise.ar;
env = EnvGen.kr(env, t_trig, doneAction: Done.freeSelf());
snd = BPF.ar(snd, freq, reso.reciprocal);
snd = Pan2.ar(snd, pan);
snd = snd*env;
Out.ar(0, vol*snd);
}).add;
SynthDef(\birds, {
| b, rate=1 |
var total_dur = BufDur.kr(b);
var fade_time = 0.3;
var env = EnvGen.kr(Env([0,1,1,0], [fade_time,total_dur-(2*fade_time),fade_time], \sin), doneAction: Done.freeSelf);
var snd = PlayBuf.ar(2, b, rate*BufRateScale.kr(b), 1, Line.kr(total_dur*rate), doneAction: Done.freeSelf);
snd = HPF.ar(snd, 160);
Out.ar(0, snd*env);
}).add;
thisProcess.nowExecutingPath.dirname.standardizePath.postln;
~buffer = Buffer.read(Server.default, thisProcess.nowExecutingPath.dirname +/+ "alpendohlen_short.wav".standardizePath);
1.sleep;
Ppar([
Pbind(
\instrument, \wind,
\freq, Pexprand(200, 14000),
\t_trig, 1,
\reso, Pwhite(0.3, 15),
\pan, Pwhite(0,1)-0.5,
\dur, Pwhite(40,120),
\atk, Pgauss(10, 1).abs,
\dcy, Pgauss(15, 1).abs,
\len, Pkey(\dur)-Pkey(\atk)-Pkey(\dcy),
),
Pbind(
// we play it at beginning then alternate between play and break
\instrument, \birds,
\b, ~buffer,
\degree, Pseq([1, Pseq([0,1], inf)]),
\rate, Pwhite(0.2,1.1),
\dur, Pseq([~buffer.duration, Pwhite(360, 900)], inf))
]).play;
}
Note: Usually SuperCollider is developed and executed from its very own IDE, where you open and edit your files, boot the audio server and execute your code (and consequently play your sound via the server).
But you can as well start your sketch from command-line by wrapping your whole script into a
s.waitForBoot{}block (as seen above) and executing it through an invocation like:sclang path/to/sript.scd.
All we need now is to write a small, minimalistic operating system by copying Guix' bare-bones template. Then we create an image:
guix system image --image-type=pine64-raw path-to-os.scm
dd it to an SD card and boot the target
device.
At this point I make sure I am able to run stuff (literally anything that could be of potential interest; read and write files, play audio, etc.) on the target device before I continue. Hacking my brains out for the most excellent audio installation only to find out last minute that it won't work on the device would be a huge bummer.
bridge the gap to the real world
Now, what is still missing? Yes, we need to optimize that TTM! We have a sketch that runs in the development environment, we have a system that boots the embedded device. Now we need the device to start our code and play the audio without user interaction.
vm driven embedded development
I do not want to create an image, flash it, shove the SD card into the
board, boot that board and wait every time I change my code to make
sure it still is fine. There's no reason anymore why this were the
way to go. Because in the world of the GNU system (GNU Guix, that
is), we can test our operating system definitions in a container or a
VM—at the cost of one simple command-line invocation. Finally, once
we flash a Guix System onto the target device, we can alter our system
definition on our host machine and guix deploy our changes to the live device. Rebooting through
ssh is all it takes to test the new
system—no haptic interaction necessary.
audio testing in qemu
Tools like speaker-test and
aplay are our friends for audio debugging,
so we start qemu with audio passing through
to our development machine. guix system vm path-to-os.scm spits out the path to a nice little shell script that
invokes qemu for us, which we can just pass some options to.
/gnu/store/<hash>-foo.sh -device virtio-sound-pci,audiodev=my_audiodev \
-audiodev alsa,id=my_audiodev \
-nograhic
starts a CLI in the VM with audio enabled for us. In there we can
make sure we're able to launch SuperCollider
and make it sound by adding all the necessary packages and realtime
properties through Guix' pam-limits-service-type.
(service pam-limits-service-type
(list
(pam-limits-entry "@audio" 'both 'rtprio 99)
(pam-limits-entry "@audio" 'both 'memlock 'unlimited)
(pam-limits-entry "@audio" 'both 'nice -12)))
linux and real-time audio
During project realization I encounter a brief period where I fear having to go down the ALSA+jack route to get audio working. SuperCollider depends on jack for low-latency real-time audio. With my hands dirty from all the hands-on I instantly got a headache trying to remember just how we used to do this, back in the day (I had this working at some point in the past!).
Fortunately we (the Free Software community as a whole) improve over
time and now just installing the awesome pipewire does the trick. So starting pipewire and wireplumber
and then invoking our audio programs with pw-jack prefixed is enough to get the power of low-latency
audio! Without the headache! Without installing the right
configuration files in the right places or having the right tools
start in the correct order (except for the two I just mentioned, that
is)! This is almost suspiciously easy!
running stuff at startup
The proper Guix way to do this is to write a service, of course. But
is this necessary? Turns out that it is not! We can hack away by
logging in a user automatically through Guix' agetty-service-type.
(modify-services
%base-services
(agetty-service-type
config => (agetty-configuration
(inherit config)
(auto-login "root")
(extra-options '("-L")) ;; no carrier detect
(baud-rate "1500000")
(term "vt100")
(tty "ttyS0"))))
Installing the necessary WAV audio and .bashprofile files ensures the code is automatically executed upon boot.
(skeletons `(("alpendohlen_short.wav"
,(local-file "alpendohlen_short.wav"))
(".bash_profile"
,(mixed-text-file "collider-profile"
"export USERPROFILE=/tmp QT_QPA_PLATFORM=offscreen
echo STARTING THE WIND MACHINE NOW
pipewire &
wireplumber &
DISPLAY=:0 pw-jack sclang " (local-file "what-remains-alpine-audio.scd")))))
A quick, not-too-dirty and almost too easy fix!
Note: The expression
(local-file "some/path")in this context results in: Guix looking up the file under "some/path", storing that file immutably in its store (the one that lives under gnu) and replacing the expression with the absolute path of that now immutable object in the store.When guix creates a system image from the above declaration, store paths referenced will in the declaration above will make it into that image.
Note: In this example,
guix(the command-line tool) expects the filesalpendohlen_short.wav(an uncompressed audio file in the WAV format, as it is used in the SuperCollider script) andwhat-remains-alpine-audio.scd(the SuperCollider script) to be present in the current working directory, where theguix system imagecommand is executed from.
delivery
Now we have code we like, a VM that does what we want, we only need to tame the device to our needs. Of course just writing the image to SD card will not work. Not because it were impossible, per se. But because we're working with the real, embedded world, and if anything just worked™ people would get suspicous to the point where they started questioning their mental sanity. But since I am experienced enough to know this is the biggest hurdle, I planned enough time: this is the gist of this whole article, after all. So I flash the image and start debugging. It helps having a serial debugger hooked up to the target device, just in case the screen wouldn't work.
All in all, there's no black magic involved. We need to unmute some
audio channels and set the right volume for some others and that's it.
We figure out what to do with alsamixer and
how we achieve that with amixer, transfer
our findings to our startup script:
(skeletons `(("alpendohlen_short.wav"
,(local-file "alpendohlen_short.wav"))
(".bash_profile"
,(mixed-text-file "collider-profile"
"export USERPROFILE=/tmp QT_QPA_PLATFORM=offscreen
echo STARTING THE WIND MACHINE NOW
pipewire &
wireplumber &
amixer set \"AIF1 DA0\" 160
amixer set \"DAC\" 160
amixer set \"AIF1 Slot 0 Digital DAC\" unmute
DISPLAY=:0 pw-jack sclang " (local-file "what-remains-alpine-audio.scd")))))
recreate and flash the image again and … IT WORKS™.
Well, of course this is a drastic simplification for brevity's sake. But you get the idea. Being an artist often seems to be about tweaking details until the very last minute, but once the whole stack works (from SuperCollider script to the device's audio output) these adjustments come at the cost of pressing some buttons on your keyboard.
Note: I highly recommend to configure
openssh-service-type, install a networking cable between the development machine and the target device and use the handyguix deployinstead of generating multible ~5GiB images in sequence.Note 2: if you already created a bunch of 5GiB images and your drive is full to the point where you need to
guix gc, you should understand Guix' garbage collection before you use it or you may have to wait until guix recompiles all the artifacts (possibly including the complete Linux kernel for aarch64, which may or may not take several hours) once again (→add garbage collector roots to avoid that).
takeaways
GNU Guix is not just a great tool to develop and prototype, but also
to continuously integrate and deliver. Once an abstraction exists
(like the pine64-raw image type), any system
configuration for any device that can use that image type will run
that system.
GNU Guix is a reasonably sane abstraction layer that is intuitively understandable for engineers. With merely two files (one SuperCollider script and one device file) we define the operating system of the devices (including audio real-time configuration, ALSA mixer setup and auto-start mechanism) and the program that the system will be run. The whole project totals to ~118 easily understandable lines of code.
Guix allowed me to create a piece of art that I could leave unattended in a gallery for less than €100 in material cost (excluding audio gear)—delivering a continuous, ad-hoc generated stream of audio in a reproducible, maintainable and relatively quick way. To sum the TTM optimization thing up: should I ever do anything similar, getting my toolchain up and ready to deliver another audio installation will be a matter of mere minutes, giving me more time to work on the audio.