]> git.alsa-project.org Git - alsa-lib.git/commitdiff
pcm: add a loop to snd_pcm_avail_delay() to avoid bogus delay values
authorKai Vehmanen <kai.vehmanen@linux.intel.com>
Thu, 31 Jul 2025 12:37:33 +0000 (15:37 +0300)
committerJaroslav Kysela <perex@perex.cz>
Thu, 31 Jul 2025 13:25:18 +0000 (15:25 +0200)
snd_pcm_avail_delay() is expected to report avail and delay values
in atomic fashion. However the function does two separate syscalls
and it cannot guarantee the avail value is the same as was used
to calculate the delay. This is a problem as the reported delay is
always relative to avail frames value.

If application (like e.g. alsa_conformance_test) uses snd_pcm_avail_delay()
to estimate the effective play position, it can observe bogus delay
values (and effective play position going backwards) if
snd_pcm_avail_delay() is called during a DMA burst where hw_ptr
moves quickly.

This commit adds a loop similar to that used in snd_pcm_hw_htimestamp()
to wait until we get a stable avail reading, and only then extract
the delay. This will avoid bogus values if function is called during
DMA bursts.

Closes: https://github.com/alsa-project/alsa-lib/pull/469
Closes: https://github.com/alsa-project/alsa-lib/issues/468
Signed-off-by: Kai Vehmanen <kai.vehmanen@linux.intel.com>
Signed-off-by: Jaroslav Kysela <perex@perex.cz>
src/pcm/pcm.c

index da339ace1529ce2f48728cfa9cfa202315e58cc3..c59ea3b686b22bc81b5fa6d9266e0c631bf1cb1d 100644 (file)
@@ -3107,7 +3107,7 @@ int snd_pcm_avail_delay(snd_pcm_t *pcm,
                        snd_pcm_sframes_t *delayp)
 {
        snd_pcm_sframes_t sf;
-       int err;
+       int err, ok = 0;
 
        assert(pcm && availp && delayp);
        if (CHECK_SANITY(! pcm->setup)) {
@@ -3118,15 +3118,25 @@ int snd_pcm_avail_delay(snd_pcm_t *pcm,
        err = __snd_pcm_hwsync(pcm);
        if (err < 0)
                goto unlock;
-       sf = __snd_pcm_avail_update(pcm);
-       if (sf < 0) {
-               err = (int)sf;
-               goto unlock;
+
+       /*
+        * Delay value is relative to avail, so we have to
+        * loop to avoid reporting stale delay data.
+        */
+       while (1) {
+               sf = __snd_pcm_avail_update(pcm);
+               if (sf < 0) {
+                       err = (int)sf;
+                       goto unlock;
+               }
+               if (ok && sf == *availp)
+                       break;
+               *availp = sf;
+               err = __snd_pcm_delay(pcm, delayp);
+               if (err < 0)
+                       goto unlock;
+               ok = 1;
        }
-       err = __snd_pcm_delay(pcm, delayp);
-       if (err < 0)
-               goto unlock;
-       *availp = sf;
        err = 0;
  unlock:
        snd_pcm_unlock(pcm->fast_op_arg);