Repository navigation
Add AlsaSettings for opening an ALSA PCM by address - #644
whatisyourname0 wants to merge 7 commits into
Conversation
|
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. |
|
Thanks for the review! I agree that adding 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. |
|
Done in 8e0aeba: this PR now contains only the ALSA PCM-address support and its documentation. The tests and reproduction instructions are preserved on |
|
Thanks for the update! I like the
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.paUseHostApiSpecificDeviceSpecificationMaybe 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)
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 |
|
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 I'll update the examples and the separately maintained regression tests to cover the changed behavior. |
|
Updated and pushed in ffcda44: device selection now uses |
mgeier
left a comment
There was a problem hiding this comment.
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?
|
Thanks for trying this. I reproduced the same error when 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. |
|
Thanks, that was it! As I mentioned in #644 (comment), you should check for failure (namely for a This way, we would get meaningful error messages for missing |
|
Thanks for confirming! I misunderstood that part of your earlier suggestion and only propagated the original error. I'll make a change that catches |
mgeier
left a comment
There was a problem hiding this comment.
Here's the rest of my review, let me know if anything is unclear!
| if (isinstance(channels, bool) or | ||
| not isinstance(channels, numbers.Integral) or channels < 1): | ||
| raise ValueError('A positive channel count is required') |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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.
|
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. |
| 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. |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
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. |
| 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 |
There was a problem hiding this comment.
It would be great if you could report this to PortAudio, and then link to that issue instead.
| Use with ``device=sd.DEVICE_FROM_EXTRA_SETTINGS``. Supplying | ||
| these settings alone does not override `default.device`. |
There was a problem hiding this comment.
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.
| Pass *channels* and *samplerate* when creating the stream, | ||
| or set `default.channels` and `default.samplerate` beforehand. |
There was a problem hiding this comment.
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?
| 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. |
There was a problem hiding this comment.
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.
| 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. |
There was a problem hiding this comment.
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.
| ALSA device index. For direct output with ``mapping=[1]`` in | ||
| `play()` or ``output_mapping=[1]`` in `playrec()`, automatic | ||
| stereo detection needs enumerated device information. |
There was a problem hiding this comment.
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"?
| >>> with sd.RawInputStream( | ||
| ... device=sd.DEVICE_FROM_EXTRA_SETTINGS, | ||
| ... samplerate=48000, channels=2, dtype='int16', | ||
| ... blocksize=1024, latency=4096 / 48000, |
There was a problem hiding this comment.
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?
| >>> import sounddevice as sd | ||
| >>> with sd.RawInputStream( | ||
| ... device=sd.DEVICE_FROM_EXTRA_SETTINGS, | ||
| ... samplerate=48000, channels=2, dtype='int16', |
There was a problem hiding this comment.
Is the usage of dtype illustrating anything specific here?
| ... samplerate=48000, channels=2, dtype='int16', | ||
| ... blocksize=1024, latency=4096 / 48000, | ||
| ... extra_settings=sd.AlsaSettings('null')) as stream: | ||
| ... data, overflowed = stream.read(1024) |
There was a problem hiding this comment.
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.
| if error is not None: | ||
| raise TypeError( | ||
| 'Cannot query device information. ' | ||
| 'Set latency to a number of seconds.' |
There was a problem hiding this comment.
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 adds
AlsaSettings(device_string)so an application can open an ALSA PCM address through PortAudio'sPaAlsaStreamInfo.deviceString. Select it explicitly withdevice=sd.DEVICE_FROM_EXTRA_SETTINGS, corresponding topaUseHostApiSpecificDeviceSpecification.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.
Replace
'null'with a hardware PCM address or a named ALSA configuration. A PCM address is not a persistent hardware identifier.Behavior
AlsaSettingsalone does not override device selection. Set the sentinel in the call or insd.default.device. PortAudio rejects these settings with a regular ALSA device index.AlsaSettingstype checks. If lookup fails, it raisesTypeErrornaming the first unresolved parameter and chains the originalPortAudioError.sd.default.channelsandsd.default.samplerate. Latency must be numeric;'low'and'high'need device information unavailable for the sentinel. Format checks do not use latency.-2instream.device.deviceStringafterward, so streams do not keep the settings alive until close.mapping=[1]inplay(), oroutput_mapping=[1]inplayrec(), needs enumerated device information for automatic stereo detection. UseOutputStreamorStream, respectively, with the channel count specified.Compatibility and validation
Feature revision:
e9a9f0d.The separate regression branch at
adfdf2bdiffers from that feature revision only by six files undertests/. 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:
1ca0eee, which reports 19.7.0-devel.The suite includes 125 identical public API calls against base
626fcb0and 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 andplay()/rec()/playrec().114 outcomes match exactly. Eleven cases assert three intentional differences:
TypeError, with the originalPortAudioErroras the cause. Code catching onlyPortAudioErrorneeds 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 --checkalso passed.See the test README for reproduction commands. Set
SOUNDDEVICE_BASELINE_PATHto 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.