Skip to content

Add AlsaSettings for opening an ALSA PCM by address - #644

Open
whatisyourname0 wants to merge 7 commits into
spatialaudio:masterfrom
whatisyourname0:feat/alsa-direct-device
Open

whatisyourname0 wants to merge 7 commits into
spatialaudio:masterfrom
whatisyourname0:feat/alsa-direct-device

Conversation

@whatisyourname0

@whatisyourname0 whatisyourname0 commented Oct 17, 2026 •

Copy link
Copy Markdown

This adds AlsaSettings(device_string) so an application can open an ALSA PCM address through PortAudio's PaAlsaStreamInfo.deviceString. Select it explicitly with device=sd.DEVICE_FROM_EXTRA_SETTINGS, corresponding to paUseHostApiSpecificDeviceSpecification.

This implements the ALSA device-string part of #4 through the existing platform-specific settings interface. It does not resolve all of #4; #85 proposes a broader host-API interface.

import sounddevice as sd

# ALSA's null PCM requires no physical audio device.
with sd.RawInputStream(
    device=sd.DEVICE_FROM_EXTRA_SETTINGS,
    samplerate=48000,
    channels=2,
    dtype='int16',
    blocksize=1024,
    latency=4096 / 48000,
    extra_settings=sd.AlsaSettings('null'),
) as stream:
    data, overflowed = stream.read(1024)
    print(len(data), overflowed)

Replace 'null' with a hardware PCM address or a named ALSA configuration. A PCM address is not a persistent hardware identifier.

Behavior

  • AlsaSettings alone does not override device selection. Set the sentinel in the call or in sd.default.device. PortAudio rejects these settings with a regular ALSA device index.
  • Shared parameter handling queries device information only when channels, sample rate or symbolic latency require it. It has no AlsaSettings type checks. If lookup fails, it raises TypeError naming the first unresolved parameter and chains the original PortAudioError.
  • For direct streams, pass channels and sample rate or configure sd.default.channels and sd.default.samplerate. Latency must be numeric; 'low' and 'high' need device information unavailable for the sentinel. Format checks do not use latency.
  • Input, output, duplex and mixed direct/indexed duplex are covered. A directly specified direction reports -2 in stream.device.
  • Settings and their C buffers remain alive during the native open/format-check call. PortAudio's ALSA backend does not retain deviceString afterward, so streams do not keep the settings alive until close.
  • A small guard rejects non-positive channel counts for the sentinel to work around a PortAudio C assertion that can abort the process. Its comment links to the reviewer's reproduction. Embedded NUL characters are rejected to prevent address truncation.
  • Direct output with mapping=[1] in play(), or output_mapping=[1] in playrec(), needs enumerated device information for automatic stereo detection. Use OutputStream or Stream, respectively, with the channel count specified.

Compatibility and validation

Feature revision: e9a9f0d.

The separate regression branch at adfdf2b differs from that feature revision only by six files under tests/. The feature PR adds no test dependencies, CI steps or lockfile changes.

All 204 tests passed, without skips, on Linux ARM64 and CPython 3.14.7 against each of:

  • Installed PortAudio 19.6.0.
  • PortAudio built with ALSA from 1ca0eee, which reports 19.7.0-devel.

The suite includes 125 identical public API calls against base 626fcb0 and the candidate in separate processes using the same synthetic ALSA configuration. It covers index/name/default selection, blocking and callback input/output/duplex, configured and device-derived defaults, format checks and play()/rec()/playrec().

114 outcomes match exactly. Eleven cases assert three intentional differences:

  1. An invalid numeric device with fully specified parameters now fails during stream opening, rather than during device lookup.
  2. Format checks ignore invalid default latency.
  3. Nine cases with unavailable device information and missing channels and/or sample rate now raise TypeError, with the original PortAudioError as the cause. Code catching only PortAudioError needs to account for this changed failure path.

The remaining 79 cases cover direct-device behavior, errors, exact captured bytes, reopen/recovery and settings lifetime. Lifetime tests check ownership during native calls and exercise blocking/callback I/O after collection. Pyright, warning-as-error Sphinx HTML build, focused Ruff checks and git diff --check also passed.

See the test README for reproduction commands. Set SOUNDDEVICE_BASELINE_PATH to the built base source to include the 125 differential cases; without it those cases are explicitly skipped.

Limits

These runs use isolated ALSA plug/null/file PCMs. They do not establish physical-device behavior, hotplug, real-time performance, negotiated hardware buffer sizes, or native Windows/macOS compatibility. The final revision has not been rerun across the earlier Python-version matrix. PortAudio initialization may still enumerate devices; no performance improvement or automatic hardware-identity resolution is claimed.

@mgeier

mgeier commented Oct 18, 2026

Copy link
Copy Markdown
Member

Thanks for this PR!

It seems to add two (or more?) different things, though: a new ALSA setting and a whole new testing framework.

I think both are valuable, but they should be discussed separately.

Regarding tests, there are already some discussions in #14 and #131, and there has been a very recent PR that also comes with its own test framework: #645.

@whatisyourname0

Copy link
Copy Markdown
Author

Thanks for the review! I agree that adding AlsaSettings and introducing test infrastructure should be discussed separately.

I'll update this PR to focus on the ALSA PCM-address support and its documentation, removing the new test suite, test dependencies, and test-related CI changes from the diff. I'll preserve the regression tests on a separate branch and keep the validation results and reproduction instructions available for reviewing the feature.

Thanks also for pointing me to #14, #131, and #645. I'll follow up on testing separately, building on those discussions before proposing a shared approach.

@whatisyourname0

Copy link
Copy Markdown
Author

Done in 8e0aeba: this PR now contains only the ALSA PCM-address support and its documentation. The tests and reproduction instructions are preserved on test/alsa-direct-device-regressions, with links and validation details in the updated PR description.

@mgeier

mgeier commented Oct 22, 2026

Copy link
Copy Markdown
Member

Thanks for the update!

I like the AlsaSettings class, but I don't like its special handling in code that should ideally be platform-independent.

Would overriding default.device when AlsaSettings is supplied fit the existing API, or should direct selection require an explicit sentinel?

I think an explicit sentinel would be better, as it would make the implementation more straightforward and it would be closer to PortAudio's C API.

Maybe something like

DEVICE_FROM_EXTRA_SETTINGS = _lib.paUseHostApiSpecificDeviceSpecification

Maybe you can come up with a better name?

Your example would then look something like this:

with sd.RawInputStream(
    device=sd.DEVICE_FROM_EXTRA_SETTINGS,
    samplerate=48000,
    channels=2,
    dtype='int16',
    blocksize=1024,
    latency=4096 / 48000,
    extra_settings=sd.AlsaSettings(device_string='null'),
) as stream:
    data, overflowed = stream.read(1024)
    print(len(data), overflowed)

Is requiring numeric latency acceptable for this path?

It is kinda annoying, but I guess we don't really have a choice, right?

However, I would also prefer the handling of this to be less host-API-specific.

Whenever 'low' or 'high' is given and query_devices(device) is not successful, we could raise an error. There is no need to make any of this specific to ALSA or any other host API.

@whatisyourname0

Copy link
Copy Markdown
Author

Thanks for the review, and that makes sense. Your proposed name communicates the intent clearly than mine.

I'll also rework the shared parameter handling around whether device information is available, removing the AlsaSettings type checks from that path. If 'low' or 'high' latency requires device information that cannot be queried, it should produce an error. I'll apply the same principle to channel-count, and sample-rate defaults.

I'll update the examples and the separately maintained regression tests to cover the changed behavior.

@whatisyourname0

whatisyourname0 commented Oct 23, 2026 •

Copy link
Copy Markdown
Author

Updated and pushed in ffcda44: device selection now uses DEVICE_FROM_EXTRA_SETTINGS, and shared parameter handling no longer checks for AlsaSettings. The examples and PR description are updated too.

@mgeier mgeier left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here's a first round of review ... I must postpone the rest because I couldn't manage to run this yet, I always get a sounddevice.PortAudioError: Error querying device -2. Is there anything special I need to do for this to work?

Comment thread src/sounddevice.py Resolved
Comment thread doc/api/platform-specific-settings.rst Resolved
Comment thread src/sounddevice.py Resolved
Comment thread src/sounddevice.py Resolved
Comment thread src/sounddevice.py Resolved
Comment thread src/sounddevice.py Resolved
Comment thread src/sounddevice.py Resolved
Comment thread src/sounddevice.py Resolved
Comment thread src/sounddevice.py Resolved
@whatisyourname0

Copy link
Copy Markdown
Author

Thanks for trying this. I reproduced the same error when channels, samplerate, or numeric latency is omitted. In particular, omitting latency leaves the default 'high', which requires device information that isn't available for the sentinel. The current error doesn't explain that clearly.

This minimal example works locally on Linux with the current PR head:

import sounddevice as sd

with sd.RawInputStream(
    device=sd.DEVICE_FROM_EXTRA_SETTINGS,
    extra_settings=sd.AlsaSettings('null'),
    samplerate=48000,
    channels=2,
    dtype='int16',
    blocksize=1024,
    latency=4096 / 48000,
) as stream:
    data, overflowed = stream.read(1024)
    print(len(data), overflowed)

If this exact example also fails on your setup, could you share the full traceback and your PortAudio version? That should help identify which device-information lookup is being reached.

Thanks also for the inline review comments. I'll address those separately.

@mgeier

mgeier commented Oct 24, 2026

Copy link
Copy Markdown
Member

Thanks, that was it!

As I mentioned in #644 (comment), you should check for failure (namely for a PortAudioError) when calling query_devices() and then, depending on what was given by the user, raise a different error (maybe wrapping the original exception?) explaining the problem.

This way, we would get meaningful error messages for missing channels, samplerate and latency.

@whatisyourname0

Copy link
Copy Markdown
Author

Thanks for confirming! I misunderstood that part of your earlier suggestion and only propagated the original error. I'll make a change that catches PortAudioError from query_devices() and report which parameters need explicit values, while preserving the original exception as the cause. This change will make it stay host-API-independent.

@mgeier mgeier left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here's the rest of my review, let me know if anything is unclear!

Comment thread src/sounddevice.py Resolved
Comment thread src/sounddevice.py Resolved
Comment thread src/sounddevice.py Resolved
Comment thread src/sounddevice.py Outdated
Comment on lines +2844 to +2846
if (isinstance(channels, bool) or
not isinstance(channels, numbers.Integral) or channels < 1):
raise ValueError('A positive channel count is required')

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why would you check this?

We are nowhere else checking for positivity or non-bool-ness. I think the behavior is reasonable enough without this check.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I removed the type and boolean checks, but found a problem when removing the positivity check: with PortAudio 19.6.0 on Linux ARM64, opening the direct 'null' PCM with channels=0 aborts the Python process inside PortAudio.

I therefore retained a minimal non-positive channel-count check for DEVICE_FROM_EXTRA_SETTINGS, after the normal CFFI conversion. The regression tests run these cases in subprocesses so a native abort is reported as a test failure.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this CPU-specific?
I can reproduce it on x86_64.

This seems to be a bug in PortAudio. Would you like to check if that has already been reported?

@whatisyourname0 whatisyourname0 Oct 25, 2026 •

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ARM64 was my test environment (Macbook M4 Pro). Thanks for checking x86_64 too.

Besides, I couldn’t find an existing PortAudio issue for this validation. Maybe I should check it out at the PortAudio.

Comment thread src/sounddevice.py Resolved
Comment thread src/sounddevice.py Resolved
Comment thread src/sounddevice.py Resolved
@whatisyourname0

Copy link
Copy Markdown
Author

Thanks for the detailed review! I’ve pushed the changes in 7641867 and replied to the individual comments. I kept two small checks for the native abort and address-truncation cases described above.

I also updated the separate regression-test branch. All 133 tests pass on Linux ARM64 with Python 3.14.7 and PortAudio 19.6.0, including 74 baseline comparisons. Type checking and the documentation build pass too. These tests use ALSA null/file PCMs; they don’t establish physical-device or other-platform compatibility.

Comment thread src/sounddevice.py Resolved
Comment thread src/sounddevice.py Outdated
device, channels, sampleformat, latency,
extra_settings._streaminfo if extra_settings else _ffi.NULL))
return parameters, dtype, samplesize, samplerate
# PortAudio's ALSA direct-device path asserts on non-positive channels.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This comment is hard to understand, because "assert" has very different behavior in C and Python.

Also, it would be good to mention that this works around a bug in PortAudio, and ideally an issue link should be provided.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for pointing it out, as I'm pretty confused how they behaveonf those both language) I clarified that tihs works around a PortAudio C assertion that can abort the process, and linked to your reproduction.

Comment thread src/sounddevice.py Resolved
@whatisyourname0

Copy link
Copy Markdown
Author

explicitly or through defaults
Where does this formulation come from? LLM?
I find it hard to understand.

Yes to be honest, that wording came from LLM-assisted slop drafting, because of usage of my LLM to convert & double check my English expression. My apologies for the slops :-(

Anyway, I replaced it with direct instructions like “Set channels to an integer.” from the following commit.

Comment thread src/sounddevice.py
extra_settings._streaminfo if extra_settings else _ffi.NULL))
# Work around a PortAudio bug: direct ALSA streams with channels <= 0
# can abort the process in a C assertion instead of returning an error.
# https://github.com/spatialaudio/python-sounddevice/pull/644#discussion_r4370395754

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It would be great if you could report this to PortAudio, and then link to that issue instead.

Comment thread src/sounddevice.py
Comment on lines +2339 to +2340
Use with ``device=sd.DEVICE_FROM_EXTRA_SETTINGS``. Supplying
these settings alone does not override `default.device`.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The second sentence is unclear to me, what is it supposed to mean? I have the feeling is has something to do with the following sentences?

If a user supplies device here, default.device will not be considered, right?
If that's right, that sentence must be wrong.

Comment thread src/sounddevice.py
Comment on lines +2341 to +2342
Pass *channels* and *samplerate* when creating the stream,
or set `default.channels` and `default.samplerate` beforehand.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This instruction sounds strange, because people can do that anyway.

I guess the important part here is that they can always do it optionally, in this case it is required, right?

Comment thread src/sounddevice.py
these settings alone does not override `default.device`.
Pass *channels* and *samplerate* when creating the stream,
or set `default.channels` and `default.samplerate` beforehand.
Set *latency* to a number of seconds.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is even harder to understand. I guess it is meant to say to not use the special values 'high' and 'low', but we should not assume that readers know that those even exist when they read this.

If they don't know, they will wonder why you even mention seconds.
As a minor additional point: "number of seconds" kinda sounds like an integer, which is not a limitation we have.

Comment thread src/sounddevice.py
Pass *channels* and *samplerate* when creating the stream,
or set `default.channels` and `default.samplerate` beforehand.
Set *latency* to a number of seconds.
Format checks do not require latency.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This sounds even more outlandish ... what are format checks, why would or wouldn't they require latency? For what?

This simple sentence raises so many more questions than it answers.

I guess you should add a link to the functions you mean by "format checks", then it might become easier to understand that those function don't have any latency parameters.

Comment thread src/sounddevice.py
Comment on lines +2350 to +2352
ALSA device index. For direct output with ``mapping=[1]`` in
`play()` or ``output_mapping=[1]`` in `playrec()`, automatic
stereo detection needs enumerated device information.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think I understand after reviewing this PR, but I don't think an average reader will understand this sentence. What is "enumerated device information"? Why should a user care? What is "stereo detection"?

Comment thread src/sounddevice.py
>>> with sd.RawInputStream(
... device=sd.DEVICE_FROM_EXTRA_SETTINGS,
... samplerate=48000, channels=2, dtype='int16',
... blocksize=1024, latency=4096 / 48000,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why are you specifying both blocksize and latency here?

Wouldn't you normally only want to specify one of them? And maybe set the other to zero?

Comment thread src/sounddevice.py
>>> import sounddevice as sd
>>> with sd.RawInputStream(
... device=sd.DEVICE_FROM_EXTRA_SETTINGS,
... samplerate=48000, channels=2, dtype='int16',

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is the usage of dtype illustrating anything specific here?

Comment thread src/sounddevice.py
... samplerate=48000, channels=2, dtype='int16',
... blocksize=1024, latency=4096 / 48000,
... extra_settings=sd.AlsaSettings('null')) as stream:
... data, overflowed = stream.read(1024)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This example is a bit strange because it reads only 1024 frames and then it is over.

Of course this doesn't have to be a complete and production-ready script, but feel free to add some hints with comments or ... or some pseudo-code that illustrates what would be done in this example.

Also, it looks a bit strange to put complicated code like this into an interactive prompt, but maybe that's fine.

Comment thread src/sounddevice.py
if error is not None:
raise TypeError(
'Cannot query device information. '
'Set latency to a number of seconds.'

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This error message might have the problem that a user might not ever have set latency to anything (or even thought about latency). As in the docs above, this might also raise the question why we mention a number of seconds, what else would latency be (since a user might not be aware of the 'high'/'low' shorthands)?

To a lesser extent, the errors for channels and samplerate may have similar problems.

I think my suggestions didn't have any of those problems, but maybe you find an even better way to phrase the error.

This branch has not been deployed

No deployments
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.

2 participants