Skip to content

Commit 07f9935

Browse files
feat: add ALSA PCM address settings and regression tests
1 parent 626fcb0 commit 07f9935

9 files changed

Lines changed: 827 additions & 122 deletions

File tree

‎.github/workflows/python-versions.yml‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,3 +35,10 @@ jobs:
3535
python -m sounddevice
3636
python -c "import sounddevice as sd; print(sd._libname)"
3737
python -c "import sounddevice as sd; print(sd.get_portaudio_version())"
38+
- name: Install optional NumPy for convenience API tests
39+
if: ${{ !startsWith(matrix.python-version, 'pypy-') }}
40+
run: python -m pip install numpy
41+
- name: Run synthetic ALSA regressions
42+
timeout-minutes: 2
43+
working-directory: git-repo
44+
run: python -m pytest -q tests

‎doc/api/platform-specific-settings.rst‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,13 @@ Platform-specific Settings
88
.. autosummary::
99
:nosignatures:
1010

11+
AlsaSettings
1112
AsioSettings
1213
CoreAudioSettings
1314
WasapiSettings
1415

16+
.. autoclass:: AlsaSettings
17+
1518
.. autoclass:: AsioSettings
1619

1720
.. autoclass:: CoreAudioSettings

‎pyproject.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ numpy = ["numpy"]
2424

2525
[dependency-groups]
2626
dev = [{ include-group = "test" }, { include-group = "doc" }]
27-
test = []
27+
test = ["pytest"]
2828
doc = [
2929
"insipid-sphinx-theme",
3030
"sphinx-last-updated-by-git",

‎sounddevice_build.py‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -233,6 +233,15 @@
233233
234234
typedef unsigned long PaWinWaveFormatChannelMask;
235235
236+
/* pa_linux_alsa.h */
237+
typedef struct PaAlsaStreamInfo {
238+
unsigned long size;
239+
PaHostApiTypeId hostApiType;
240+
unsigned long version;
241+
const char *deviceString;
242+
} PaAlsaStreamInfo;
243+
void PaAlsa_InitializeStreamInfo(PaAlsaStreamInfo *info);
244+
236245
/* pa_asio.h */
237246
238247
#define paAsioUseChannelSelectors 0x01

‎src/sounddevice.py‎

Lines changed: 97 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -173,7 +173,8 @@ def play(data, samplerate=None, mapping=None, blocking=False, loop=False,
173173
174174
"""
175175
ctx = _CallbackContext(loop=loop)
176-
ctx.frames = ctx.check_data(data, mapping, kwargs.get('device'))
176+
ctx.frames = ctx.check_data(
177+
data, mapping, kwargs.get('device'), kwargs.get('extra_settings'))
177178

178179
def callback(outdata, frames, time, status):
179180
assert len(outdata) == frames
@@ -359,7 +360,8 @@ def playrec(data, samplerate=None, channels=None, dtype=None,
359360
360361
"""
361362
ctx = _CallbackContext()
362-
output_frames = ctx.check_data(data, output_mapping, kwargs.get('device'))
363+
output_frames = ctx.check_data(
364+
data, output_mapping, kwargs.get('device'), kwargs.get('extra_settings'))
363365
if dtype is None:
364366
dtype = ctx.data.dtype # ignore module defaults
365367
out, input_frames = ctx.check_out(out, output_frames, channels, dtype,
@@ -690,7 +692,7 @@ def check_input_settings(device=None, channels=None, dtype=None,
690692
"""
691693
parameters, dtype, samplesize, samplerate = _get_stream_parameters(
692694
'input', device=device, channels=channels, dtype=dtype, latency=None,
693-
extra_settings=extra_settings, samplerate=samplerate)
695+
extra_settings=extra_settings, samplerate=samplerate, for_check=True)
694696
_check(_lib.Pa_IsFormatSupported(parameters, _ffi.NULL, samplerate))
695697

696698

@@ -704,7 +706,7 @@ def check_output_settings(device=None, channels=None, dtype=None,
704706
"""
705707
parameters, dtype, samplesize, samplerate = _get_stream_parameters(
706708
'output', device=device, channels=channels, dtype=dtype, latency=None,
707-
extra_settings=extra_settings, samplerate=samplerate)
709+
extra_settings=extra_settings, samplerate=samplerate, for_check=True)
708710
_check(_lib.Pa_IsFormatSupported(_ffi.NULL, parameters, samplerate))
709711

710712

@@ -808,6 +810,12 @@ def __init__(self, kind, samplerate=None, blocksize=None, device=None,
808810
if prime_output_buffers_using_stream_callback:
809811
stream_flags |= _lib.paPrimeOutputBuffersUsingStreamCallback
810812

813+
# Retain effective settings, including their C buffers, through close.
814+
if extra_settings is None:
815+
extra_settings = tuple(default.extra_settings)
816+
self._extra_settings = (tuple(_split(extra_settings)),
817+
tuple(default.extra_settings))
818+
811819
if kind == 'duplex':
812820
idevice, odevice = _split(device)
813821
ichannels, ochannels = _split(channels)
@@ -2167,7 +2175,7 @@ class default:
21672175
21682176
See Also
21692177
--------
2170-
AsioSettings, CoreAudioSettings, WasapiSettings
2178+
AlsaSettings, AsioSettings, CoreAudioSettings, WasapiSettings
21712179
21722180
"""
21732181
samplerate: ... = None
@@ -2316,6 +2324,44 @@ class CallbackAbort(Exception):
23162324
"""
23172325

23182326

2327+
class AlsaSettings:
2328+
2329+
def __init__(self, device_string):
2330+
"""ALSA-specific settings for opening a PCM by address.
2331+
2332+
Use as ``extra_settings`` with ``device=None`` (or ``-2``).
2333+
The address overrides `default.device`. Channels and sample rate
2334+
must be supplied explicitly or through defaults. Streams also
2335+
require a numeric latency in seconds.
2336+
2337+
Parameters
2338+
----------
2339+
device_string : str
2340+
ALSA PCM address, such as ``'hw:2,0'`` or a named PCM from the
2341+
ALSA configuration. It must be nonempty and contain no NUL.
2342+
An ALSA address is not a persistent hardware identifier.
2343+
2344+
Notes
2345+
-----
2346+
The stream's device attribute reports PortAudio's special value
2347+
``-2``. Passing an explicit device index or name is an error.
2348+
For direct output with ``mapping=[1]`` in `play()` or `playrec()`,
2349+
use `OutputStream` with explicit channels instead; automatic
2350+
stereo detection requires enumerated device information.
2351+
2352+
"""
2353+
if not isinstance(device_string, str):
2354+
raise TypeError('device_string must be a string')
2355+
if not device_string or '\0' in device_string:
2356+
raise ValueError('device_string must be nonempty and contain no NUL')
2357+
_check(_lib.Pa_HostApiTypeIdToHostApiIndex(_lib.paALSA),
2358+
'ALSA host API is unavailable')
2359+
self._device_string = _ffi.new('char[]', device_string.encode('utf-8'))
2360+
self._streaminfo: ... = _ffi.new('PaAlsaStreamInfo*')
2361+
_lib.PaAlsa_InitializeStreamInfo(self._streaminfo)
2362+
self._streaminfo.deviceString = self._device_string
2363+
2364+
23192365
class AsioSettings:
23202366

23212367
def __init__(self, channel_selectors):
@@ -2541,7 +2587,7 @@ def __init__(self, loop=False):
25412587
self.event = threading.Event()
25422588
self.status = CallbackFlags()
25432589

2544-
def check_data(self, data, mapping, device):
2590+
def check_data(self, data, mapping, device, extra_settings=None):
25452591
"""Check data and output mapping."""
25462592
import numpy as np
25472593
data = np.asarray(data)
@@ -2563,6 +2609,13 @@ def check_data(self, data, mapping, device):
25632609
# first two channels, which is unexpected when specifying mapping=[1].
25642610
# In this case, we play silence on the second channel, but only if the
25652611
# device actually supports a second channel:
2612+
effective_settings = (default.extra_settings if extra_settings is None
2613+
else extra_settings)
2614+
if (mapping_is_explicit and np.array_equal(mapping, [0]) and
2615+
isinstance(_select_input_or_output(effective_settings, 'output'),
2616+
AlsaSettings)):
2617+
raise ValueError('For ALSA direct output mapping=[1], use '
2618+
'OutputStream with explicit channels')
25662619
if (mapping_is_explicit and np.array_equal(mapping, [0]) and
25672620
query_devices(device, 'output')['max_output_channels'] >= 2):
25682621
channels = 2
@@ -2730,12 +2783,22 @@ def _check_dtype(dtype):
27302783

27312784

27322785
def _get_stream_parameters(kind, device, channels, dtype, latency,
2733-
extra_settings: ..., samplerate):
2786+
extra_settings: ..., samplerate, *, for_check=False):
27342787
"""Get parameters for one direction (input or output) of a stream."""
27352788
assert kind in ('input', 'output')
2736-
if device is None:
2737-
device = default.device
2738-
device = _get_device_id(device, kind, raise_on_error=True)
2789+
if extra_settings is None:
2790+
extra_settings = default.extra_settings
2791+
extra_settings = _select_input_or_output(extra_settings, kind)
2792+
direct_alsa = isinstance(extra_settings, AlsaSettings)
2793+
if direct_alsa:
2794+
device = _select_input_or_output(device, kind)
2795+
if device is not None and device != -2:
2796+
raise ValueError('AlsaSettings conflicts with an explicit device')
2797+
device = _lib.paUseHostApiSpecificDeviceSpecification
2798+
else:
2799+
if device is None:
2800+
device = default.device
2801+
device = _get_device_id(device, kind, raise_on_error=True)
27392802
if channels is None:
27402803
channels = default.channels
27412804
channels = _select_input_or_output(channels, kind)
@@ -2745,15 +2808,33 @@ def _get_stream_parameters(kind, device, channels, dtype, latency,
27452808
if latency is None:
27462809
latency = default.latency
27472810
latency = _select_input_or_output(latency, kind)
2748-
if extra_settings is None:
2749-
extra_settings = default.extra_settings
2750-
extra_settings = _select_input_or_output(extra_settings, kind)
27512811
if samplerate is None:
27522812
samplerate = default.samplerate
27532813

2754-
info = query_devices(device)
2755-
if channels is None:
2756-
channels = info['max_' + kind + '_channels']
2814+
if direct_alsa:
2815+
import math
2816+
import numbers
2817+
if (isinstance(channels, bool) or
2818+
not isinstance(channels, numbers.Integral) or channels < 1):
2819+
raise ValueError('AlsaSettings requires a positive channel count')
2820+
if (isinstance(samplerate, bool) or
2821+
not isinstance(samplerate, numbers.Real) or
2822+
not math.isfinite(samplerate) or samplerate <= 0):
2823+
raise ValueError('AlsaSettings requires a positive finite sample rate')
2824+
if for_check:
2825+
latency = 0.0 # Pa_IsFormatSupported ignores suggested latency.
2826+
elif (isinstance(latency, bool) or
2827+
not isinstance(latency, numbers.Real) or
2828+
not math.isfinite(latency) or latency < 0):
2829+
raise ValueError('AlsaSettings requires finite numeric latency >= 0')
2830+
else:
2831+
info = query_devices(device)
2832+
if channels is None:
2833+
channels = info['max_' + kind + '_channels']
2834+
if latency in ('low', 'high'):
2835+
latency = info['default_' + latency + '_' + kind + '_latency']
2836+
if samplerate is None:
2837+
samplerate = info['default_samplerate']
27572838
try:
27582839
# If NumPy is available, get canonical dtype name
27592840
dtype = _sys.modules['numpy'].dtype(dtype).name
@@ -2764,10 +2845,6 @@ def _get_stream_parameters(kind, device, channels, dtype, latency,
27642845
except KeyError as e:
27652846
raise ValueError('Invalid ' + kind + ' sample format') from e
27662847
samplesize = _check(_lib.Pa_GetSampleSize(sampleformat))
2767-
if latency in ('low', 'high'):
2768-
latency = info['default_' + latency + '_' + kind + '_latency']
2769-
if samplerate is None:
2770-
samplerate = info['default_samplerate']
27712848
parameters: ... = _ffi.new('PaStreamParameters*', (
27722849
device, channels, sampleformat, latency,
27732850
extra_settings._streaminfo if extra_settings else _ffi.NULL))

‎tests/README.rst‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
Synthetic ALSA tests
2+
===================
3+
4+
These Linux tests exercise sounddevice and the real PortAudio ALSA backend
5+
using null and file PCMs. No microphone or sound card is needed.
6+
Run them in a fresh Python process so the isolated ALSA configuration is set
7+
before PortAudio initialization. The fixture does not include system or user
8+
ALSA configuration and restores the environment when the test session ends.
9+
10+
Install PortAudio and ALSA plugins (Debian/Ubuntu)::
11+
12+
sudo apt-get install libportaudio2
13+
python -m pip install . pytest numpy
14+
python -m pytest -q tests
15+
16+
The temporary directory contains a deterministic input file and ALSA config.
17+
It is removed at the end of the session. Non-Linux runs skip these tests;
18+
missing ALSA support on Linux fails rather than silently skipping coverage.
19+
20+
The tests cover direct input/output/duplex, exact input bytes, close/reopen,
21+
invalid parameters, settings lifetime, default overrides and existing indexed
22+
and named selection. They do not validate hardware identity, physical capture,
23+
hotplug, real-time scheduling or a negotiated hardware buffer size.
24+
25+
The raw-stream tests require only pytest and sounddevice. The convenience API
26+
test uses NumPy and reports a skip when NumPy is unavailable (including the
27+
PyPy CI jobs). CPython CI installs NumPy and exercises that test too.
28+
29+
ALSA_CONFIG_PATH cannot represent spaces or colons in its configuration path.
30+
If the process temporary directory contains either, the fixture uses /tmp.

‎tests/conftest.py‎

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
"""Configure synthetic ALSA PCMs before sounddevice initializes PortAudio."""
2+
3+
import json
4+
import random
5+
import os
6+
from pathlib import Path
7+
import sys
8+
import tempfile
9+
10+
import pytest
11+
12+
13+
def pytest_configure(config):
14+
if sys.platform != 'linux':
15+
return
16+
if 'sounddevice' in sys.modules:
17+
raise pytest.UsageError('Run ALSA tests in a fresh Python process')
18+
# ALSA_CONFIG_PATH splits on spaces/colons without an escaping syntax.
19+
temp_root = tempfile.gettempdir()
20+
if ':' in temp_root or ' ' in temp_root:
21+
temp_root = '/tmp'
22+
directory = tempfile.TemporaryDirectory(
23+
prefix='sounddevice-alsa-', dir=temp_root)
24+
root = Path(directory.name)
25+
rng = random.Random(0)
26+
data = bytes(rng.getrandbits(8) for _ in range(192000))
27+
(root / 'input.raw').write_bytes(data)
28+
# This standalone configuration has no hardware PCMs or user includes.
29+
alsa_config = root / 'alsa.conf'
30+
alsa_config.write_text(
31+
"""
32+
pcm.null { type null }
33+
# PortAudio 19.6 expects a deferred default/dmix entry during enumeration.
34+
pcm.default { type null }
35+
pcm.test_named {
36+
type null
37+
hint { show on description "Synthetic PCM" }
38+
}
39+
pcm.portaudio_file_capture {
40+
type file
41+
slave.pcm "null"
42+
infile %s
43+
file %s
44+
format "raw"
45+
}
46+
"""
47+
% (json.dumps(str(root / 'input.raw'), ensure_ascii=False),
48+
json.dumps(str(root / 'output.raw'), ensure_ascii=False))
49+
)
50+
previous = os.environ.get('ALSA_CONFIG_PATH')
51+
os.environ['ALSA_CONFIG_PATH'] = str(alsa_config)
52+
53+
def cleanup():
54+
if previous is None:
55+
os.environ.pop('ALSA_CONFIG_PATH', None)
56+
else:
57+
os.environ['ALSA_CONFIG_PATH'] = previous
58+
directory.cleanup()
59+
60+
config.add_cleanup(cleanup)
61+
config._alsa_capture_bytes = data
62+
63+
64+
@pytest.fixture
65+
def alsa_capture_bytes(pytestconfig):
66+
return pytestconfig._alsa_capture_bytes

0 commit comments

Comments
 (0)