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

sample_rate

The output’s rate: the Ring’s own (the default) up to twice it.

target

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.

max_ppm

How far the ratio may move from nominal, 0 to 10000.

bandwidth

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 spawn and pull take for status: 272.

audiopump.SERVICE_MORE

there is more to do.

Type:

service result

audiopump.SERVICE_FULL

the output ring has no room for another block.

Type:

service result

audiopump.SERVICE_PARKED

the pump is parked.

Type:

service result

audiopump.SERVICE_DONE

the pump has ended.

Type:

service result

audiopump.C_SINK

Whether spawn takes a C sink as sink. False on CPython.

audiopump.SERVICE_MASK

result & SERVICE_MASK.

Type:

Mask for the reason in a service result

audiopump.SERVICE_SHIFT

Shift for the block count in a service result: result >> SERVICE_SHIFT.

audiopump.PRESS

press a note on a synthio.Synthesizer.

Type:

Events.at operation

audiopump.RELEASE

release a note on a synthio.Synthesizer.

Type:

Events.at operation

audiopump.RELEASE_ALL

release every note on a synthio.Synthesizer.

Type:

Events.at operation

audiopump.PLAY

play a sample on an audiomixer.MixerVoice.

Type:

Events.at operation

audiopump.STOP

stop an audiomixer.MixerVoice.

Type:

Events.at operation

audiopump.LEVEL

set an audiomixer.MixerVoice’s level.

Type:

Events.at operation

audiopump.STRIKE

strike an audiomodal.Bank with a table of modes.

Type:

Events.at operation

audiopump.CHOKE

stop an audiomodal.Bank ringing.

Type:

Events.at operation

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 shutdown before spawning another. A graph made of an audiocore.WaveFile, audiomp3.MP3Decoder or audiovorbis.VorbisDecoder is refused, because those read their files through the interpreter inside the pull: fill a Ring from 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 stop or shutdown.

  • status – A writable buffer of at least STATUS_BYTES bytes that the pump fills with counters, as STATUS_WORDS little-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 with struct.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 drain empties.

  • 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_gain changes 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=True when 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 sink could 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 spawn runs, with the same arguments, so it can be measured on the interpreter thread. Wrap it in micropython.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, where why is one of SERVICE_MORE, SERVICE_FULL, SERVICE_PARKED and SERVICE_DONE. Unpack it with why = r & SERVICE_MASK and blocks = r >> SERVICE_SHIFT. It is one small integer, so a call under micropython.heap_lock() does not allocate. On a threaded port it does nothing and returns SERVICE_MORE with no blocks.

audiopump.drain(out, /)[source]

Copy audio from the ring given to spawn into 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 service has finished the graph.

audiopump.stop()[source]

Ask the pump to stop after the block it is on. Follow with join.

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.running()[source]

Whether a pump is running.

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.unpark()[source]

Let a parked pump carry on.

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 spawn set 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. Without fade, None.

Raises:

ValueError – The graph contains a file-backed source, or the sample was deinitialised.

audiopump.reset(sample, /)[source]

Rewind a graph, as the pump does when a looping tail ends.

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.at takes a wrapped value.

audiopump.events(queue=Ellipsis, /)[source]

Attach or detach the queue the pump applies at block boundaries.

Parameters:

queue – An Events to attach, or None to detach. Leave the argument out to only read.

Returns:

The attached queue, or None.

Raises:

TypeError – queue is not an Events or None.

audiopump.tap(tap=Ellipsis, /)[source]

Attach or detach the Tap that copies what goes out.

Parameters:

tap – A Tap to attach, or None to detach. Leave the argument out to only read.

Returns:

The attached tap, or None.

Raises:

TypeError – tap is not a Tap or None.

audiopump.threaded()[source]

Whether spawn puts the loop on a thread of its own. False in service mode, where service is 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, and service is 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_reset clears 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.

audiopump.lock_reset()[source]

Zero the lock statistics and clear the fault code.

class audiopump.Ring(*, sample_rate=48000, channel_count=2, frames=256, capacity=4)[source]

Bases: object

A 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 write take 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.

space()[source]

How many bytes write will take now, in whole frames.

level()[source]

How many bytes are queued.

stats()[source]

Counters.

Returns:

(wrote, read, starved, underruns, overruns, pulls, in_digest, out_digest, capacity, block_size). The 64-bit values are only reliable once the pump has stopped; level and space are the live questions.

clear()[source]

Drop everything queued.

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.USBDevice streams 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: object

Plays a Ring that something else fills on its own clock.

It steers its resampling ratio so the ring holds target frames, 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 Ring to 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:
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 target again.

reset()[source]

Start over and forget the rate.

deinit()[source]

Release the resampler. Every later use raises ValueError.

class audiopump.Events(*, capacity=64)[source]

Bases: object

A 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.Note or sample stays alive until it is applied. Attach the queue with events.

Parameters:

capacity – How many operations the queue holds, 1 to 4096.

Raises:

ValueError – capacity is 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, as now counts. It is masked to 32 bits, so now() + n is fine across the wrap. Do not schedule more than about 12 hours ahead.

  • op –

    The operation, and what target and arg are for it:

  • target – What the operation acts on.

  • arg – The operation’s argument.

  • loop – Whether PLAY loops.

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 – target or arg is the wrong type for op.

  • ValueError – op is 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.

clear()[source]

Remove everything queued, counting it as cancelled.

Returns:

How many operations were removed.

pending()[source]

How many operations are queued.

stats()[source]

Counters.

Returns:

(scheduled, applied, late, cancelled, dropped, refused, depth, capacity): late operations were applied after their frame, dropped found the queue full and refused found their target gone when due.

class audiopump.Tap(*, frames=2048, channel_count=2)[source]

Bases: object

A 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 stats counts.

stats()[source]

Counters.

Returns:

(bytes_written, blocks, reads, torn, capacity, frame_size).