Skip to content

New Feature: Buffer size and sample rate callback functions - #454

Open
faressc wants to merge 4 commits into
thestk:masterfrom
faressc:master
Open

faressc wants to merge 4 commits into
thestk:masterfrom
faressc:master

Conversation

@faressc

@faressc faressc commented Feb 20, 2025

Copy link
Copy Markdown

Some native APIs allow for dynamic buffer size and sample rate changes (i.e. JACK/Pipewire-JACK). This PR adds the ability to set callback functions for buffer size and sample rate changes that occur during stream operation. The callback functions are specified in the RtAudio::StreamOptions struct and are called when the buffer size or sample rate changes. The callback functions are backend agnostic and are implemented for the JACK backend in this PR.

Internally the RtApiStream gets two new members, bufferSizeCallbackInfo and sampleRateCallbackInfo similar to the existing callbackInfo member. The BufferSizeCallbackInfo and SampleRateCallbackInfo structs are populated when the RtAudio::openStream function is called. The user can specify the respective callback functions pointers (RtAudioBufferSizeCallback or/and an RtAudioSampleRateCallback) and user data pointers (void*) in the RtAudio::StreamOptions struct. The RtAudio::StreamOptions are therefore extended with the following members:

  • bufferSizeCallback of type RtAudioBufferSizeCallback
  • bufferSizeCallbackUserData of type void*
  • sampleRateCallback of type RtAudioSampleRateCallback
  • sampleRateCallbackUserData of type void*

When specified, the respective callback functions are called, when the buffer size or sample rate changes. Additionally, the following internal RtApiStream members are updated when the buffer size changes:

  • bufferSize
  • userBuffer is reallocated with the new buffer size
  • deviceBuffer is reallocated with the new buffer size

When the sample rate changes, only the sampleRate member is updated.

This is all implemented with the JACK backend, but the changes are designed to be backend agnostic, so that other backends can be extended in the future.

I would appreciate feedback and would be happy to make any necessary changes to get this PR merged.

Cheers,
Fares

PS: I have also added the ability for the JACK backend to force a buffer size on the JACK server with jack_set_buffer_size() when the stream is opened and the requested buffer size from the stream is different from the current JACK server buffer size. This happens automatically, but a warning is printed to the console. To me this seems better than the current behavior where the buffer size of the JACK server is queried and the stream is simply opened with the JACK server buffer size.

@faressc

faressc commented Apr 19, 2025 •

Copy link
Copy Markdown
Author

Hello there,

Any feedback would be highly appreciated. I am very open to change the code in order to better fit your guidelines.

Best
Fares

@garyscavone

Copy link
Copy Markdown
Contributor

Would you consider writing a small test program for the tests directory to test this functionality? The added functionality seems great but could be challenging to test if added incrementally in other APIs.

@faressc

faressc commented Apr 23, 2025 •

Copy link
Copy Markdown
Author

Thanks for the answer! I'd be happy to provide some test cases for the feature! It will take me a few days as I'm on vacation this week.

@mattbeghin

Copy link
Copy Markdown

This would be interesting in CoreAudio (macOS) since when another app opens the same audio device, it might change sample rate and buffer size

@faressc

faressc commented Dec 16, 2025

Copy link
Copy Markdown
Author

Oh, this has completely escaped my scope! Sorry! Unfortunately, I'm too involved these days to implement the tests. But if you need a more detailed explanation of the suggestion, let me know! I'd also be happy to help with the CoreAudio implementation.

@kinggs

kinggs commented Dec 2, 2026

Copy link
Copy Markdown

A test case for this, from a real fault, and one bug found while running it.

The fault. With PipeWire's JACK, an application can be told one buffer size and then be driven at another. VCV Rack 2.6.6 on Linux goes silent this way and cannot start playing: its bundled RtAudio returns from every callback at "the JACK buffer size has changed ... cannot process!". #286 reported the same message in 2021.

How to get there. PipeWire 1.6.9 with pipewire-jack, an audio interface on the Pro Audio profile (a Focusrite Scarlett 4i4 here), 48 kHz, JACK clients configured with node.latency = 256/48000. Start a stream at 1024 frames first, then the JACK client. In Pro Audio mode PipeWire does not change the period of a running device, so the graph stays at 1024, while jack_get_buffer_size() answers 256 before activation. PipeWire does deliver the buffer-size callback.

Results with a small silent program (below): it opens a JACK output stream at 256 frames, counts the callbacks the application receives for 3 s, then times stopStream().

Application callbacks in 3 s "cannot process!" messages stopStream()
master f028430, nothing else playing (control) 557, 256 frames 0 16 ms
master f028430, 1024 stream playing first 0 140 never returns
this branch be0b2d5, with a bufferSizeCallback set 140, 1024 frames 0 48 ms

On this branch the callback reported "now 1024 frames" once, the stream ran, and it stopped cleanly. So for this case it is the fix. (#497 separately bounds the stopStream() wait.)

One bug: openStream() crashes when options is null, which is the default argument. RtApi::openStream reads options->bufferSizeCallback (and the three lines after it) before the existing if ( options ) check:

Thread 1 "probe" received signal SIGSEGV, Segmentation fault.
#0  RtApi::openStream(...)
#1  RtAudio::openStream(...)
#2  main ()

Guarding those four assignments with if ( options ) should be enough. I have not checked what the JACK backend then does on a size change when no callback is set; without one, an application that never asked for the feature would still go silent as on master.

The maintainer asked for a test program for tests/. The one below could be a start: it needs no audible output, and its pass condition is a non-zero callback count after the size changes. I can run any revision of this branch on the same machine.

The test program (builds with g++ -std=c++17 -D__UNIX_JACK__ probe.cpp RtAudio.cpp $(pkg-config --cflags --libs jack) -lpthread)
// Silent probe: opens a JACK output stream at 256 frames, writes zeros,
// counts the callbacks the application receives, then times stopStream().
#include "RtAudio.h"
#include <atomic>
#include <chrono>
#include <cstdio>
#include <cstring>
#include <thread>
#include <unistd.h>
static std::atomic<long> calls{0};
static std::atomic<unsigned> lastFrames{0};
static std::atomic<long> errors{0};
static int cb(void *out, void *, unsigned int n, double, RtAudioStreamStatus, void *) {
  std::memset(out, 0, n * 2 * sizeof(float));
  calls++; lastFrames = n; return 0;
}
static int onSize(unsigned int *n, void *) { std::printf("  buffer-size callback: now %u frames\n", *n); return 0; }
static void onError(RtAudioErrorType, const std::string &text) {
  if (errors++ < 2) std::printf("  rtaudio says: %s\n", text.c_str());
}
int main() {
  RtAudio dac(RtAudio::UNIX_JACK, &onError);
  RtAudio::StreamParameters p; p.deviceId = dac.getDefaultOutputDevice(); p.nChannels = 2;
  unsigned int frames = 256;
  RtAudio::StreamOptions o; o.bufferSizeCallback = &onSize; o.bufferSizeCallbackUserData = nullptr;
  if (dac.openStream(&p, nullptr, RTAUDIO_FLOAT32, 48000, &frames, &cb, nullptr, &o)) { std::puts("  open failed"); return 2; }
  std::printf("  opened: bufferSize the library settled on = %u\n", frames);
  if (dac.startStream()) { std::puts("  start failed"); return 2; }
  std::this_thread::sleep_for(std::chrono::seconds(3));
  std::printf("  after 3 s: callbacks delivered to the application = %ld (last nframes %u), error messages = %ld\n",
              calls.load(), lastFrames.load(), errors.load());
  std::thread watchdog([] { std::this_thread::sleep_for(std::chrono::seconds(6));
    std::puts("  stopStream(): STILL WAITING after 6 s (hung); exiting"); std::fflush(stdout); _exit(3); });
  watchdog.detach();
  auto t0 = std::chrono::steady_clock::now();
  dac.stopStream();
  double ms = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count();
  std::printf("  stopStream(): returned after %.0f ms\n", ms);
  if (dac.isStreamOpen()) dac.closeStream();
  return 0;
}

The competing stream: pw-cat -p --raw --format s16 --rate 48000 --channels 2 -P '{ node.latency = 1024/48000 }' --target <the interface's output node> /dev/zero, started after the device was restarted and before the program.

(Written with a coding agent, Claude Code. The runs are from my own machine.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants