Feature request: make backend clock-drift correction continuous instead of whole-block repeat/drop
Nessuno ha ancora preso questa issue.
Valutazione
- Difficoltà
- 5/5
- Tempo stimato
- Più di una settimana
- Idoneità per principianti
- 38/100
Direzione di ricerca
Start by tracing virtual_oss_process() in virtual_oss.c, then read vresample_setup(), vclient_export_read_locked(), vclient_import_write_locked(), and the delay hooks in the backend files. Compare timing through the transmit backend with the -L/-O synchronized-client path; done means continuous correction covers both clock topologies without whole-block repeat/drop events and preserves the existing diagnostics.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Descrizione
Summary
When virtual_oss carries audio between two independently clocked devices — -R plus
-P, or a capture device plus the synchronized master client of an -L / -O setup —
each is driven by its own crystal, so their true sample rates differ by a small but
non-zero amount.
In the -R/-P case virtual_oss already detects and corrects this. The correction in
virtual_oss_process() is to repeat or discard one entire DSP block:
/* Get output delay in bytes */
tx_be->delay(tx_be, &blocks);
/*
* Simple fix for jitter: Repeat data when too
* little. Skip data when too much. This
* should not happen during normal operation.
*/
if (blocks == 0) {
blocks = 2; /* buffer is empty */
voss_jitter_up++;
} else if (blocks >= (3 * buffer_dsp_tx_size_ref)) {
blocks = 0; /* too much data */
voss_jitter_down++;
} else {
blocks = 1; /* normal */
}
The comment says "This should not happen during normal operation." For two free-running
clock domains it happens during all operation, at a predictable rate, forever. Each
event is a duplicated or dropped block — at -s 50ms, a 50 ms discontinuity.
In the -L / -O case it is worse: that path is gated on tx_be->delay(), so when the
transmit backend is /dev/null — which is the normal configuration for a master-loopback
setup — nothing fires at all and the drift simply accumulates in the loopback ring. Point
7 below has the detail.
This request is that the correction be applied continuously as a resampling ratio trim
rather than in one-block quanta, using the libsamplerate instance that is already linked
in, so a long-running bridge between two independent clocks is glitch-free rather than
glitch-periodic.
Motivating use case
Digital room correction for a source device that is not the computer.
I already run virtual_oss as the mixing stage of a room-correction chain for locally
played files, in the -L master-loopback configuration described in point 7 below:
MPD / mpv ──> /dev/dsp.play ─┐
│ virtual_oss -f /dev/null -d dsp.play -L dsp.loop
└─> /dev/dsp.loop ──> BruteFIR ──> /dev/dsp0 ──> USB DAC
One clock governs that whole chain: BruteFIR blocks on its write to the DAC, the
synchronized loopback client paces the virtual_oss engine, and there is no drift
anywhere. It has been solid.
What I want to add is a physical source to the same chain, so that a CD transport passes
through the same correction filters as local files instead of bypassing them:
CD transport ── coax S/PDIF ──> USB capture interface ──USB──> host
│
virtual_oss (-R <capture>)
│
/dev/dsp.loop ──> BruteFIR ──> USB DAC
That is the step which introduces a second clock domain, and the clock topology is the
essential point:
- Capture side: the S/PDIF receiver in the USB interface is slaved to the biphase
clock recovered from the source. The source transport is the master. The host cannot
influence this rate. - Playback side: an asynchronous USB DAC is its own master, running from its own local
oscillator. The host cannot influence this rate either.
There is no word-clock path between the two, and in the general consumer case there cannot
be one — the source has no clock input and the DAC has no clock output.
This is not specific to my hardware. The same topology arises for:
- any S/PDIF, AES3 or ADAT input feeding a different playback device;
- HDMI audio extractors feeding an external DAC;
- USB microphones or capture devices monitored through a separate output device;
- Bluetooth A2DP, where the remote endpoint's clock is entirely outside host control.
The magnitude of the problem
Consumer crystal oscillators are commonly specified at ±50 ppm; ±25 ppm is typical for
better hardware, ±100 ppm for the worst. Two independent oscillators can therefore differ
by up to ~100 ppm relative in the worst case, ~20–50 ppm in practice.
Because the correction quantum is one DSP block, the interval between correction events
reduces to a pleasantly simple expression:
interval = block_duration / fractional_rate_error
independent of sample rate. At -s 50ms:
| relative drift | interval between repeat/drop events |
|---|---|
| 100 ppm | 500 s (~8 min) |
| 50 ppm | 1000 s (~17 min) |
| 20 ppm | 2500 s (~42 min) |
The failure is guaranteed rather than probabilistic. The bridge cannot run for the length
of an album, let alone as a permanently configured system service, without discontinuities.
Note that -s does not help in either direction: a smaller block makes the events more
frequent but shorter, a larger block makes them rarer but longer and more audible, and adds
latency. The product is invariant.
The corrective action actually needed is tiny — a steady-state ratio trim of a few tens of
ppm, far below audibility for any reasonable resampler — but it must be applied
continuously, and it must be derived from a measurement rather than from configuration.
Current behaviour
I have read virtual_oss.8, main.c, virtual_oss.c, eq.c, ctl.c, command.c and the
backend_oss, backend_bt, backend_sndio and backend_null backends. I run the FreeBSD
base copy rather than this repository (see the version note at the end), but every fragment
quoted below is from the files here. My reading, which I would be glad to have corrected:
1. The routing is already fully expressible. -R, -P and -O are independent, and
-M i,src_ch,dst_ch,pol,mute,log2_gain feeds a mix input channel into a mix output
channel. So
virtual_oss -B -C 2 -c 2 -b 32 -r 44100 -s 50ms \
-R /dev/dsp<capture> -P /dev/dsp<playback> \
-M i,0,0,0,0,0 -M i,1,1,0,0,0 \
-t vdsp.ctl
does describe the desired signal routing: step (5) of virtual_oss_process() adds
buffer_monitor (the copy of the captured input) into buffer_temp (the output mix).
Nothing is missing at the routing level.
2. -S is orthogonal to this. The resampler is instantiated per cuse client in
vresample_setup() via src_new(voss_libsamplerate_quality, pvc->channels, &code), and
the ratio is assigned on every block as:
/* vclient_export_read_locked() */
pvr->data.src_ratio = (float)pvc->sample_rate / (float)voss_dsp_sample_rate;
/* vclient_import_write_locked() */
pvr->data.src_ratio = (float)voss_dsp_sample_rate / (float)pvc->sample_rate;
Two consequences:
- The ratio is a function of declared nominal rates. It contains no term derived from
actual data flow, so it cannot represent a rate that differs from its nominal value by
20 ppm. - It sits on the client path — between a cuse client and the internal mix domain — not
between the two backend devices. Both physical devices are opened at
voss_dsp_sample_rateand are never resampled with respect to each other. In the routing
above there is no cuse client in the path at all, so no resampler is instantiated on the
audio path whatsoever.
So -S correctly serves its actual purpose and is simply a different mechanism.
3. A drift measurement and a correction loop already exist — at block granularity.
This is the block quoted in the summary. Two details seem worth drawing out:
- The "too little" branch triggers on
blocks == 0, i.e. only once
SNDCTL_DSP_GETODELAYreports the playback buffer completely empty. By then the
device has already underrun. The up-correction is therefore reactive to a fault rather
than preventive. - The deadband spans 0 to
3 * buffer_dsp_tx_size_ref, so the steady-state loop rides
between empty and three blocks of output delay. At-s 50msthat is a 150 ms swing in
end-to-end latency in addition to the discontinuities.
4. The counters are already exported. voss_jitter_up and voss_jitter_down reach
userland through struct virtual_oss_system_info and
VIRTUAL_OSS_GET_SYSTEM_INFO, and virtual_oss_cmd prints them:
printf(... "Output jitter: %u / %u\n" ..., info.tx_jitter_down, info.tx_jitter_up, ...);
So the diagnostic hook I was going to ask for largely exists. What it reports is an event
count, not a rate; the request below is only to also express it as ppm.
5. Only the OSS backend measures anything. oss_play_delay() uses
SNDCTL_DSP_GETODELAY, but:
static void
oss_play_delay(struct voss_backend *pbe, int *pdelay)
{
if (voss_has_synchronization != 0 ||
ioctl(pbe->fd, SNDCTL_DSP_GETODELAY, pdelay) != 0)
*pdelay = -1;
}
-1 falls into the else branch above, so blocks is always 1 and the compensation is
disabled entirely whenever -O or a synchronized client is in use. And in the other
backends the hook is a stub:
static void
bt_play_delay(struct voss_backend *pbe __unused, int *pdelay)
{
/* TODO */
*pdelay = -1;
}
The sndio and null backends do the same. So on the Bluetooth path — where the remote
endpoint's clock drifts by orders of magnitude more than crystal tolerance — there is
currently no compensation of any kind, and the TODO suggests that is known.
6. The receive side is never measured. oss_rec_delay() exists and does the right
thing (FIONREAD), but ->delay is only ever invoked on tx_be. The input-side
measurement primitive is present in the backend interface and unused.
7. In a -L / -O topology the timing master is a client, not a backend. Worth
spelling out separately, because it is the configuration I actually run: with
-f /dev/null -d dsp.play -L dsp.loop, virtual_oss has no physical backend at all. It
mixes into a master loopback device that an external convolver reads, and that convolver
owns the real DAC. null_rec_transfer() then deliberately skips its own pacing:
if (voss_has_synchronization == 0)
virtual_oss_wait();
so the engine is throttled by the synchronized client's reads, which are in turn throttled
by the DAC that the convolver writes to. One clock governs the whole chain and it works
well.
But it means that in such a chain the drift-relevant elastic buffer is the loopback
client's ring, not any backend, and tx_be is /dev/null, whose delay hook returns -1
unconditionally. Adding a capture backend to a configuration like this therefore gets no
compensation and no diagnostic: blocks is always 1 and both jitter counters stay at
zero forever. Any correction that keys exclusively off tx_be->delay() would miss this
case, which is why the proposal below is phrased in terms of the timing master rather than
the transmit backend.
Proposed feature
An option — name entirely at your discretion, e.g. -Y or -A — that replaces the
block-granular repeat/drop with a continuous resampling ratio trim on the capture path,
whenever the capture backend sits in a different clock domain from whatever is pacing the
engine.
Behaviour
- One clock is the rate reference and the capture backend is resampled to follow it.
The reference is whatever already paces the engine: the transmit backend in an-R/-P
bridge, or the synchronized client in an-L/-Oconfiguration. Keying off "the
timing master" rather than "the tx backend" is what makes this cover both; a correction
driven only bytx_be->delay()would do nothing in the second case, wheretx_beis
frequently/dev/null. Making the choice explicit would be useful, but the default
ought to follow whatever is already master. - The instantaneous ratio is
1 + e, whereeis a small correction produced by a
controller acting on the difference between measured buffer fill and a target fill. eclamped to a configurable maximum deviation (±500 ppm would be generous; beyond that
indicates a genuine rate mismatch or a stalled device rather than drift, and should be
reported rather than silently tracked). The existing repeat/drop logic remains as the
backstop for that case, which is what its comment already implies it was meant for.- The controller time constant should be long — seconds to tens of seconds. The disturbance
being rejected is a slowly varying DC offset; fast correction would only inject audible
pitch modulation in response to scheduling jitter.
Implementation sketch
I have not written the backend loop, so please read this as a description of intent rather
than a proposed patch. The pieces do appear to exist:
libsamplerateis already a dependency and already used.src_process()is designed for
exactly this: assigning a slightly differentdata.src_ratioon each call interpolates
the ratio smoothly across the block, which is the intended mechanism for varying-ratio
operation. No new dependency and no discontinuity at block boundaries.- The occupancy measurement is the
tx_be->delay()call that is already there — the same
number currently thresholded into three cases would instead be an error term. Enabling
oss_rec_delay()on therx_beside would give the input-side equivalent. For the
synchronized-client case of point 7 the corresponding quantity is the master client's
ring occupancy, whichvring_total_read_len()already returns and
vclient_output_delay()already computes. virtual_oss_timestamp()already provides a monotonic reference, and
vclient_bufsize_consumed()already shows the pattern of correcting block-granular
accounting against the system clock — the same technique would give a jitter-suppressed
occupancy estimate.
A minimal PI controller is on the order of a few tens of lines:
/* per bridge, evaluated once per backend block */
err = (double)current_fill - (double)target_fill; /* in frames */
integ += err * dt;
e = -(kp * err + ki * integ) / (double)target_fill;
e = clamp(e, -max_dev, +max_dev);
ratio = 1.0 + e;
with kp and ki chosen for a closed-loop time constant of ~10 s and no overshoot, and
anti-windup on integ while e is clamped.
Diagnostics
Independently of whether the controller itself is accepted, it would be valuable to express
the drift the daemon already observes as a rate:
- add the applied correction in ppm, plus current and target fill, to
struct virtual_oss_system_infoand thevirtual_oss_cmdoutput alongside the existing
jitter counters; - optionally the same over the HTTP server.
Even without the controller this would turn "why does it click every eight minutes" into a
number. Today the counters exist but a user has to poll them and differentiate by hand to
learn anything.
Alternatives I considered, and why they fall short
Use an alsaloop -A equivalent. I am not aware of a FreeBSD counterpart. On Linux this
is the standard answer, which is itself an argument that the capability belongs in the audio
bridging daemon.
Resample offline / pick matching hardware. Not possible: the capture rate is dictated by
an external transport that the host cannot address.
Use the DAC's own S/PDIF input and bypass the host. This works, and I use it as an A/B
reference, but it defeats the purpose — the signal then receives no correction.
Slave both devices to a common word clock. Correct in a studio; unavailable in consumer
topologies, where neither the source nor the DAC exposes a clock port.
Run the bridge at a large buffer and restart periodically. As shown above, -s trades
event frequency against event length at constant product, and adds latency.
Do it outside virtual_oss with two cuse clients and an external resampler. I already
accept one external process in the chain for convolution, so I am not objecting to this on
principle. But a resampler stage is a third process and another pair of ring buffers, and
it would still need the same occupancy measurement that virtual_oss is making internally
and is best placed to make — it would be reconstructing from outside what the daemon
already knows.
A related gap: there is no DSP stage on the backend-to-backend path
This does not block me — I use BruteFIR as the convolver, downstream of the loopback
device — so it is a separate request and I am not asking for it here. But it seems
dishonest to describe the -R/-P routing as sufficient without recording what it does
not do.
vclient_tx_equalizer() and vclient_rx_equalizer() are called only from
vclient_read_linear() and vclient_write_linear(), i.e. on the per-client ring paths, and
they read pvc->profile->{rx,tx}_filter_size. -F and -G set those sizes on the profile
for the next -d / -l / -L device to be created. Consistently, the FIR ioctls take a
profile index (vprofile_by_index() on the client or loopback head), and
virtual_equalizer -w selects among rx_dev, tx_dev, rx_loop, tx_loop — all
per-device, none of them the physical backend.
So in the -R/-P bridge above, which has no cuse client in the path, no filtering is
applied at all. Getting an external source through the FIR currently requires a client
process to read one device and write another, which reintroduces exactly the extra process
and extra buffering that the bridge avoids.
A device-level (master) FIR applied to the mix domain — or the ability to attach a filter to
the -M i monitor path — would close this. I am happy to open it as a separate issue.
There is a second, smaller point in the same area. virtual_equalizer takes
frequency amplification control points, linearly interpolated and Hann-windowed, which
yields a linear-phase, magnitude-only filter; minimum-phase correction and all-pass sections
for low-frequency phase alignment cannot be expressed that way. But
struct virtual_oss_fir_filter already carries double *filter_data and
VIRTUAL_OSS_SET_TX_DEV_FIR_FILTER already copies raw coefficients in, so the core API
needs nothing: this is only a matter of virtual_equalizer (or a sibling tool) growing an
option to load an impulse response from a WAV or raw float file, subject to the existing
constraint that filter_size must match the size fixed by -F/-G. That would let
existing DRC toolchains target virtual_oss directly.
Willingness to help, and where I actually stand
To be straightforward about it: I do not own the S/PDIF capture interface yet, so every
number above is derived from the code and from datasheet oscillator tolerances, not
measured. I am raising this before buying the hardware precisely because the answer bears
on whether buying it makes sense — if this is something you would not want in
virtual_oss, or if I have misread the backend loop and there is already a way to do it,
I would rather know now.
If the direction is workable, I will buy the interface and report measured results on
FreeBSD with it and an asynchronous USB DAC — i.e. exactly the two-free-running-clocks
case: observed drift in ppm, voss_jitter_up / voss_jitter_down rates over multi-hour
runs, and sample-accurate offset accounting. Those counters already give a usable
measurement without any code change, which is one reason I think exposing the same
information as a rate would be worth doing on its own.
If a prototype patch would be more useful than a description, I am willing to attempt one,
given a steer on where in the backend loop you would prefer the correction to sit.
Version note
I am running the copy in the FreeBSD base system, imported by christos@ in
5a31c623143f ("virtual_oss: Port to base", review D52308) and shipping since 15.0;
audio/virtual_oss now carries IGNORE_FreeBSD_15 / IGNORE_FreeBSD_16 = "included in
base system". That copy is restructured relative to this repository — the programs are
split, backends are dlopen'd shared objects under /usr/lib/virtual_oss rather than the
in-tree backend_*/ directories, libsamplerate is a base private library rather than
contrib/libsamplerate, and the pieces with third-party dependencies (virtual_equalizer,
the sndio and Bluetooth backends) are separate ports. None of that touches the logic quoted
above, which is identical in the two trees — I checked every fragment quoted here against
the files in this repository before quoting it.
I am filing here rather than on FreeBSD Bugzilla because this is a design change to the
audio engine rather than something specific to the base build. Happy to mirror it there if
you would prefer the FreeBSD side tracked separately.
- Lingua principale
- C
- Stelle
- 10
- Fork
- 5
- Metriche di merge delle PR
- Nessuna PR unita negli ultimi 30g
Preparare l'ambiente
Questo progetto non fornisce container di sviluppo, Dockerfile né guida per i contributori, quindi l'ambiente è a tuo carico: parti dal suo README e consulta la nostra guida al primo contributo per i passaggi generali.
Come iniziare
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Issue simili
-
Difficoltà 2/5 1-3 ore Idoneità per principianti 78/100
I maintainer di solito rispondono entro 13 giorni
-
DBMS_UTILITY.FORMAT_ERROR_STACK exceeds the 2000-byte limitForse già presa @coder999o l’ha presa oggi. Aperta
Difficoltà 2/5 1-3 ore Idoneità per principianti 76/100
I maintainer di solito rispondono entro 1 giorno
-
Difficoltà 2/5 1-3 ore Idoneità per principianti 66/100
zephyrproject-rtos/zephyr#127560 · 1 commento ·
I maintainer di solito rispondono entro 2 giorni
-
area-VM-meta-mono untriaged
Difficoltà 2/5 1-3 ore Idoneità per principianti 75/100
I maintainer di solito rispondono entro 1 giorno
-
tetragon-info.json btf_fname doesn't record the BTF file the agent usesForse già presa @bar234 l’ha presa oggi. Aperta
Difficoltà 2/5 1-3 ore Idoneità per principianti 68/100
I maintainer di solito rispondono entro 1 giorno