audiopump
What spawn() takes, what status holds, which builds carry the pump and
what can feed it. To start one, see
Run audio off the interpreter thread.
retarget and loop=
retarget’s loop= travels with the swap rather than being stored when
you call it: the old tail is pulled until the next block boundary, so setting
the flag early ends the pump one block before the new tail ever runs. Leave it
out and the flag stays as spawn() set it, which is what every caller before
the argument existed wanted. Get it wrong the other way and a looping client
left alone on a live pump stops at the end of its lap.
backpressure()
>>> audiopump.backpressure()
True
True where a full output ring makes the pump wait for room instead of
dropping the block; False where a free-running pump would lose audio. It is
the question a driver asks before it decides whether to park the pump between
ticks, and it is True in two different ways: on a threaded port whose driver
fills in park_spin, where a wake ends the wait, and in service mode, where
the loop hands the thread back on a full ring and the caller’s next
service() is the wake. It is False only on a threaded build with no
park_spin — a driver that is not finished, which now says so rather than
quietly losing blocks.
DriftResampler
drift = audiopump.DriftResampler(ring, *, sample_rate=None, target=None,
max_ppm=1000, bandwidth=0.01)
Plays ring, which something else fills on its own clock, and steers its
ratio so the Ring holds target frames. Play the DriftResampler, not the
Ring: it is the Ring’s only reader. On every runtime, CircuitPython included.
Argument |
Meaning |
|---|---|
|
The output’s rate: the Ring’s own (the default) up to twice it. |
|
The fill to hold, in frames. Half the Ring by default; at least a block, and at most the Ring less 16 frames, the filter’s look-ahead. Settable while playing; the fill moves there at the loop’s pace. |
|
How far the ratio may move from nominal, 0 to 10000. |
|
How fast the loop follows the clocks once locked, 0.001 to 0.1 Hz. It starts eight times faster and narrows over about a minute. |
The Ring’s block must be 16 to 1024 frames. ppm (the ratio’s offset from
nominal), fill (the smoothed fill it is holding) and rate (Ring frames per
output frame) say what the loop is doing; underruns counts blocks of
silence played because the Ring ran dry, after which it waits for target
again. reset() starts over and forgets the rate. Why it is built this way,
and what it measured: the drift resampler.
What feeds the pump
Three kinds of source feed it and they are all the same kind of thing to it:
a graph; audiopump.Ring, an audiosample node Python writes PCM into, so a
pushed stream can sit behind a Mixer with effects on it like anything else;
and audiopump.Events, a queue of frame-stamped presses, plays and levels
the pump applies at block boundaries, which is what puts a sequenced bar on
the audio’s clock instead of the interpreter’s. audiopump.Tap reads what is
going out, for a meter or a scope, without being in the path.
Which builds carry it. Every MicroPython port: unix, Windows,
WebAssembly and esp32. The CPython wheel does too, in the shape a port
with no thread has: driver() is 'none', threaded() is False, spawn()
returns −2 and adopts the graph, and nothing is pulled until you call
service(), which fills the ring you passed to spawn() and returns when it
is full. The names, the status block, Ring, Events and Tap are the same,
and so are the bytes: drained from the ring, a graph is byte-identical to the
same graph on the MicroPython unix build.
status = bytearray(audiopump.STATUS_BYTES)
ring = bytearray(16384)
audiopump.spawn(mixer, 0x7FFFFFFF, status, ring=ring)
buf = bytearray(4096)
while playing: # from your app's timer, say every 20 ms
audiopump.service()
n = audiopump.drain(buf)
sink.write(memoryview(buf)[:n])
audiodev does this for you: on CPython its players drive the pump from
their own tick. What CPython does not have is pull() under a heap lock,
because it has no heap lock, and audiocore’s pull-depth cap: a graph that
leads back into itself is caught at Python’s recursion limit instead, and
reported as the same fault. CircuitPython carries only Ring and
DriftResampler: its playback layer already pulls natively from its own
audio thread, and a second pull loop would be a second owner of the same
graph, so there a board’s audio output pulls the Ring itself. It still takes the lock and the
hook table, on default hooks, which cost a load and a branch.
The hardware — the channel a board writes into, and a live microphone as a
source — is not here. It arrives as a separate module, _audioif, from a
platform driver, and audiopump.driver() tells you which one bound:
>>> audiopump.driver()
'esp32' # or 'pthread', 'win32', 'none'
'none' is a real answer rather than a failure: the default hook table is
all NULLs, which means one thread and no hardware, and that is exactly how
the WebAssembly build runs. Writing a driver for a platform that has none yet
is the pump-port guide.
Names and signatures
Generated from audiopump.pyi; the file reads on its own.
Run an audio graph off the interpreter thread.
spawn pulls a graph of audio samples (a audiomixer.Mixer, a
synthio.Synthesizer, effects) on a thread the interpreter is not on, so the
audio keeps an exact clock while a screen redraws or Python does anything
else. A platform driver supplies the thread and the output; driver says
which one bound. Where there is no thread, the pump runs in service mode:
spawn adopts the graph and nothing is pulled until you call service.
Ring lets Python push PCM into the graph, DriftResampler plays a ring that
something else fills on its own clock, Events schedules notes on the audio
clock, and Tap reads what is going out.
The CPython wheel and every MicroPython port carry this whole module.
CircuitPython carries only Ring and DriftResampler, because its playback
layer already pulls from its own audio thread.
- audiopump.STATUS_WORDS
- Type:
How many 64-bit words the status block holds
- audiopump.STATUS_BYTES
How many bytes the status block holds, which is the size of the buffer
spawnandpulltake forstatus: 272.
- audiopump.PRESS
press a note on a
synthio.Synthesizer.- Type:
Events.atoperation
- audiopump.RELEASE
release a note on a
synthio.Synthesizer.- Type:
Events.atoperation
- audiopump.RELEASE_ALL
release every note on a
synthio.Synthesizer.- Type:
Events.atoperation
- audiopump.STRIKE
strike an
audiomodal.Bankwith a table of modes.- Type:
Events.atoperation
- audiopump.CHOKE
stop an
audiomodal.Bankringing.- Type:
Events.atoperation
- audiopump.spawn(sample, blocks, status, sink=None, ring=None, core=-1, prio=21, stack=16384, psram=False, timeout_ms=200, pace=False, loop=False, sink_room=0, sink_gain=None)[source]
Start pulling a graph on a thread of its own.
Only one pump can run at a time; call
shutdownbefore spawning another. A graph made of anaudiocore.WaveFile,audiomp3.MP3Decoderoraudiovorbis.VorbisDecoderis refused, because those read their files through the interpreter inside the pull: fill aRingfrom the interpreter instead.- Parameters:
sample – The tail of the graph to pull.
blocks – How many blocks to pull before stopping. A large number such as 0x7FFFFFFF plays until
stoporshutdown.status – A writable buffer of at least
STATUS_BYTESbytes that the pump fills with counters, asSTATUS_WORDSlittle-endian 64-bit words. Word 0 is blocks pulled, 1 bytes seen, 2 an FNV-1a digest of every byte, 3 the last pull’s result, 4 whether the loop is running, 5 the error (0 none, 1 buffer, 2 null, 3 done, 6 the C sink closed), 14 sink timeouts and 24 the fault code. Read it withstruct.unpack.sink – Where the audio goes. True sends it to the board’s I2S output when the driver has opened one; a path writes it to a file on a desktop. Bytes holding a C sink that another native module published, such as a USB speaker’s
c_sink(), send it there from the pump’s own thread: the graph must be signed 16-bit at the sink’s rate and channel count, and the pump ends with error 6 when the sink closes. None sends it nowhere.ring – A writable buffer of at least 64 bytes to write the audio into instead, which
drainempties.core – The CPU core to run on, on ports that have cores. -1 lets the driver choose.
prio – The thread’s priority, on ports that have one.
stack – The thread’s stack in bytes, on ports that need one.
psram – Whether the thread’s stack goes in PSRAM, where the port has it.
timeout_ms – How long the pump waits on a full sink before counting a timeout.
pace – On a desktop, pull at the graph’s own sample rate in real time.
loop – Rewind the tail and carry on when it reports it is done, as
audiobusio.I2SOut.play(sample, loop=True)does.sink_room – For a C sink, the bytes of room it must have before the pump writes a block. The pump then keeps the sink’s capacity less this much queued, which is the delay it adds, however large the sink’s own buffer is. 0 writes whenever anything fits.
sink_gain – For a C sink, the level the audio goes to it at, 0.0 to 1.0. None is 1.0.
sink_gainchanges it while the pump plays.
- Returns:
The core the thread runs on, or -1 when it has no core affinity, or -2 in service mode, where no thread was made.
- Raises:
ValueError – A pump is already spawned, the status or ring buffer is too small, the graph contains a file-backed source,
sink=Truewhen the driver has no output open, or a C sink whose format is not the graph’s.OSError – The thread could not be made, or a file
sinkcould not be opened.
- audiopump.pull(sample, blocks, status, sink=None, ring=None, /)[source]
Run the pump’s loop on the calling thread until it ends.
It is the same loop
spawnruns, with the same arguments, so it can be measured on the interpreter thread. Wrap it inmicropython.heap_lock()to check that a pull does not allocate.
- audiopump.sink_gain(level, /)[source]
Set the level a C sink’s audio goes out at, 0.0 to 1.0.
It takes effect within a few milliseconds and steps to the new level, so move it in small steps to fade. It does nothing to audio going to the board’s own output, a file or a ring.
- Parameters:
level – 0.0 for silence to 1.0 for the graph’s samples as they are. None is 1.0.
- audiopump.service(max_blocks=0, /)[source]
Advance the pump where there is no thread to do it.
- Parameters:
max_blocks – The most blocks to produce. 0 means as many as the output ring has room for.
- Returns:
blocks << SERVICE_SHIFT | why, wherewhyis one ofSERVICE_MORE,SERVICE_FULL,SERVICE_PARKEDandSERVICE_DONE. Unpack it withwhy = r & SERVICE_MASKandblocks = r >> SERVICE_SHIFT. It is one small integer, so a call undermicropython.heap_lock()does not allocate. On a threaded port it does nothing and returnsSERVICE_MOREwith no blocks.
- audiopump.drain(out, /)[source]
Copy audio from the ring given to
spawninto a buffer.- Parameters:
out – A writable buffer.
- Returns:
How many bytes were copied. 0 when there is no ring or it is empty.
- audiopump.join(timeout_ms=30000, /)[source]
Wait for the pump to end, and release its thread and sink.
- Returns:
True when the pump had ended or was never running; False when it was still running at the deadline. In service mode it does not pull anything itself, so it reports False until
servicehas finished the graph.
- audiopump.shutdown()[source]
Stop the pump, release the graph and close the sink. It is safe to call twice, and a soft reset does it for you.
- audiopump.park(timeout_us=100000, *, fade=False)[source]
Hold the pump at a block boundary so the graph can be rewired.
The pump does not touch the graph again until
unpark.- Parameters:
timeout_us – How long to wait for the pump to reach a boundary, in microseconds.
fade – True makes the park a hold with a deadline: the block the pump holds goes out faded, and the pump feeds silence until
unpark.
- Returns:
True once the pump is parked, or has ended.
- audiopump.retarget(sample, *, loop=None, fade=False, timeout_us=100000)[source]
Point the pump at a different tail while it runs.
Everything that can raise happens first, on the calling thread; then the pump either sees the whole new tail or the whole old one.
- Parameters:
sample – The new tail.
loop – Whether the new tail loops. It takes effect with the swap, so it is right for the tail that plays. None leaves the flag as
spawnset it.fade – True fades the old tail’s next block to silence, swaps, and fades the new tail’s first block in, a dip of one block each way, instead of a cut that clicks.
timeout_us – With
fade, how long to wait for the swap.
- Returns:
With
fade, True once the pump has stopped pulling the old tail so it can be released, or False if the swap will happen at the next block instead. Withoutfade, None.- Raises:
ValueError – The graph contains a file-backed source, or the sample was deinitialised.
- audiopump.info(sample, /)[source]
Describe a graph’s output, so a sink can be opened to match it.
- Returns:
(sample_rate, channel_count, bits_per_sample, max_buffer_length, samples_signed, single_buffer).
- audiopump.now()[source]
Frames the pump has pulled since
spawn.This is what an event’s frame is compared against, so schedule with it. It wraps at 2**32 frames, which is 24.9 hours at 48 kHz, and
Events.attakes a wrapped value.
- audiopump.events(queue=Ellipsis, /)[source]
Attach or detach the queue the pump applies at block boundaries.
- audiopump.threaded()[source]
Whether
spawnputs the loop on a thread of its own. False in service mode, whereserviceis the driver.
- audiopump.backpressure()[source]
Whether a full output ring makes the pump wait for room instead of dropping the block.
This is True on a threaded port whose driver can end the wait with a wake, and in service mode, where the loop hands the thread back on a full ring. It is False only on a threaded build whose driver has no way to wake the pump, where a free-running pump would lose audio.
- audiopump.driver()[source]
Which platform driver bound:
"esp32","pthread","win32"or"none"."none"is a real answer, not a failure: one thread, no hardware, andserviceis the driver.
- audiopump.fades()[source]
What fading has done since
spawn.- Returns:
(fades, clean_holds, silence_bytes)– blocks that went out faded, fading parks that ended in time and were never heard, and the bytes of silence a held park fed the output.
- audiopump.fault()[source]
Why the last pull gave up: 0 when it has not. The pull never raises, because there is no interpreter on its thread, so it publishes a code and stops.
lock_resetclears it.
- audiopump.lock_stats()[source]
What the pump lock has cost since
spawn.- Returns:
(pump_takes, pump_wait_us, pump_wait_us_max, ctrl_takes, ctrl_wait_us, ctrl_wait_us_max, ctrl_held_us_max): how often and how long the pump thread and the control calls waited for the lock.
- class audiopump.Ring(*, sample_rate=48000, channel_count=2, frames=256, capacity=4)[source]
Bases:
objectA ring buffer Python writes PCM into, which is an audio sample.
The pump pulls blocks out of it through the same protocol as any other node, so a pushed stream can be the tail by itself or sit behind a mixer with effects on it. One producer writes and one consumer pulls, and neither takes a lock to do it.
An underrun plays a whole block of silence and counts it, leaving the audio in the ring to refill. An overrun makes
writetake what fits and count it. Neither raises or blocks.The audio is signed 16-bit.
- Parameters:
sample_rate – Frames per second.
channel_count – 1 or 2.
frames – Frames in one block, the amount the pump pulls at a time.
capacity – How many blocks deep the ring is, at least 2. Depth is latency.
- Raises:
ValueError – An argument is out of range, or the ring would be over 16 MB.
- sample_rate
Frames per second. Writable, to 1 or more.
- property bits_per_sample
Size of one sample in bits: always 16.
- property channel_count
Number of channels: 1 or 2.
- write(buffer, /)[source]
Push PCM into the ring.
- Parameters:
buffer – Signed 16-bit samples, interleaved.
- Returns:
How many bytes were taken, in whole frames. It is less than the buffer’s length when the ring is full, and the caller keeps the rest.
- from_usb(endpoint, packet, /)[source]
Make a USB sound card’s isochronous OUT endpoint write straight into this ring from the USB interrupt, so the pump plays it. Only on ports whose
machine.USBDevicestreams isochronous endpoints.While it runs the interrupt is the ring’s one producer, so do not also
write.- Parameters:
endpoint – The endpoint number.
packet – The packet size in bytes, or None to stop.
- deinit()[source]
Release the ring. Every later use raises
ValueError.
- class audiopump.DriftResampler(ring, *, sample_rate=None, target=None, max_ppm=1000, bandwidth=None)[source]
Bases:
objectPlays a
Ringthat something else fills on its own clock.It steers its resampling ratio so the ring holds
targetframes, which keeps the producer’s clock and the output’s clock from drifting apart. Play the resampler, not the ring: it is the ring’s only reader. The ring’s block must be 16 to 1024 frames.It is an audio sample, signed 16-bit, with the ring’s channel count.
- Parameters:
ring – The
Ringto play.sample_rate – The output rate, from the ring’s own rate (the default) up to twice it.
target – The fill to hold, in frames. It must cover a block and fit in the ring less the filter’s look-ahead of 16 frames. The default is half the ring.
max_ppm – How far the ratio may move from nominal, in parts per million, 0 to 10000.
bandwidth – How fast the loop follows the clocks once locked, in Hz, 0.001 to 0.1. It starts eight times faster and narrows over about a minute. The default is 0.01.
- Raises:
ValueError – An argument is out of range.
- sample_rate
Frames per second of the output. Writable, to 1 or more.
- target
The fill to hold, in frames. It can be set while playing; the fill moves there at the loop’s pace. Setting it out of range raises
ValueError.
- property bits_per_sample
Size of one sample in bits: always 16.
- property channel_count
Number of channels: 1 or 2.
- property ppm
The ratio’s offset from nominal, in parts per million.
- property fill
The smoothed fill it is holding, in frames.
- property rate
Ring frames consumed per output frame.
- property underruns
Blocks of silence played because the ring ran dry, after which it waits for
targetagain.
- deinit()[source]
Release the resampler. Every later use raises
ValueError.
- class audiopump.Events(*, capacity=64)[source]
Bases:
objectA queue of frame-stamped operations the pump applies at block boundaries, so a sequenced bar keeps time on the audio clock instead of the interpreter’s.
Scheduling is a call on the interpreter thread and does every type and range check there; applying is a handful of stores on the pump’s thread. A scheduled
synthio.Noteor sample stays alive until it is applied. Attach the queue withevents.- Parameters:
capacity – How many operations the queue holds, 1 to 4096.
- Raises:
ValueError –
capacityis out of range.
- at(frame, op, target, arg=None, loop=False, /)[source]
Schedule an operation.
- Parameters:
frame – When to apply it, in frames since
spawn, asnowcounts. It is masked to 32 bits, sonow() + nis fine across the wrap. Do not schedule more than about 12 hours ahead.op –
The operation, and what
targetandargare for it:PRESSandRELEASE:targetis asynthio.Synthesizer,argasynthio.Noteor a MIDI note number from 0 to 127.RELEASE_ALL:targetis asynthio.Synthesizer.PLAY:targetis anaudiomixer.MixerVoice,arga sample whose format matches the mixer’s.loopsays whether it loops.STOP:targetis anaudiomixer.MixerVoice.LEVEL:targetis anaudiomixer.MixerVoice,argthe level.STRIKE:targetis anaudiomodal.Bank,arganarray('f')offrequency, decay, gainfor each mode.CHOKE:targetis anaudiomodal.Bank.
target – What the operation acts on.
arg – The operation’s argument.
loop – Whether
PLAYloops.
- Returns:
A token for
cancel, or 0 when the queue was full and the operation was dropped, which is counted rather than raised.- Raises:
TypeError –
targetorargis the wrong type forop.ValueError –
opis unknown, a MIDI note is out of range, the voice is not in a mixer, or a strike’s table is the wrong shape.
- cancel(token, /)[source]
Remove a scheduled operation that has not been applied.
- Returns:
Whether the token was still queued.
- class audiopump.Tap(*, frames=2048, channel_count=2)[source]
Bases:
objectA copy of the audio going out, for a meter or a scope, without being in the path.
The pump writes each block it sends into the tap’s ring, and a reader takes the latest audio. Attach it with
tap. The audio is signed 16-bit.- Parameters:
frames – How many frames to keep, at least 16. The size is rounded up to a power of two in bytes, to at most 4 MB.
channel_count – 1 or 2.
- Raises:
ValueError – An argument is out of range.
- readinto(buffer, /)[source]
Copy the newest audio into a buffer.
- Parameters:
buffer – A writable buffer. It is filled with whole frames, up to the tap’s size.
- Returns:
How many bytes were written. 0 when nothing has gone out since the last read, or when the pump kept overwriting the audio while it was copied, which
statscounts.