Skip to contentSkip to conversation

Improve audio output quality

PATCH Superseded Martin Schrodt 1 participant 3 messages Oct 15, 2017

v2 of 4 Superseded Latest is v4 →

lore
Share & tools
lore
#0 lore raw

v2 cover Improve audio output quality

After being annoyed for too long with the crackling QEMU produces, I decided to dive in and try to fix this.

This has already been tested by several people, please see the corresponding Reddit-thread:

https://www.reddit.com/r/VFIO/comments/74vokw/improved_pulse_audio_driver_for_qemu/

I presented this to the list a few days ago, but it was in too rough a state, so I cleaned it up and wrote better commit messages.

This is still missing proper handling for VMState-migration, which I will need a bit of assistance with.

Martin Schrodt (2):
audio/paaudio: remove separate PA feeder threads audio/hda: create millisecond timers that handle IO

 audio/audio.c        |   5 +
 audio/audio_int.h    |   2 +
 audio/paaudio.c      | 862 ++++++++++++++++++++++-----------------------------
 hw/audio/hda-codec.c | 193 +++++++++---
 hw/audio/intel-hda.c |   7 -
 5 files changed, 531 insertions(+), 538 deletions(-)
Signature · 1 line
2.14.2
#1 lore raw

PATCH v2 1/2 audio/paaudio: remove separate PA feeder threads

Reduce latency when playing back via Pulse Audio, by removing the separate threads that feed PA. These are not needed, since feeding can be done in a non blocking way directly from the audio timer.

This also exposes several new configuration settings that make it easier for the user to tune the behaviour:

QEMU_PA_BUFFER_SIZE_OUT: integer, default = 0
"internal buffer size in frames for playback device" This equals the previous QEMU_PA_SAMPLES, but is only for the playback device.When no value is given, this will be calculated as 2.5 times the audio timer interval.

QEMU_PA_BUFFER_SIZE_IN: integer, default = 0
"internal buffer size in frames for recording device" This equals the previous QEMU_PA_SAMPLES, but is only for the recording device. When no value is given, this will be calculated as 2.5 times the audio timer interval.

QEMU_PA_TLENGTH: integer, default = 0
"playback buffer target length in frames"
The server tries to assure that at least tlength bytes are always available in the per-stream server-side playback buffer. When no value is given, this will be calculated as 2.5 times the audio timer interval.

QEMU_PA_FRAGSIZE: integer, default = 0
"fragment length of recording device in frames"
When recording, the server sends data in blocks of fragsize bytes size. Large values diminish interactivity with other operations on the connection context but decrease control overhead. When no value is given, this will be calculated as 0.25 times the audio timer interval.

QEMU_PA_MAXLENGTH_IN: integer, default = 0
"maximum length of PA recording buffer in frames" Maximum length of the server side buffer in bytes. When no value is given, this will be calculated as 4 times the audio timer interval.

QEMU_PA_ADJUST_LATENCY_OUT: boolean, default = 0
"instruct PA to adjust latency for playback device"
When this is enabled, PA will try to set the overall latency of the sink to the value given by TLENGTH.

QEMU_PA_ADJUST_LATENCY_IN: boolean, default = 1
"instruct PA to adjust latency for recording device" When this is enabled, PA will try to set the overall latency of the source to the value given by FRAGSIZE.

---
 audio/audio.c     |   5 +
 audio/audio_int.h |   2 +
 audio/paaudio.c   | 862 +++++++++++++++++++++++-------------------------------
 3 files changed, 377 insertions(+), 492 deletions(-)
audio/audio.c +5 -0
index beafed209b..6f42a019b0 100644
@@ -2066,3 +2066,8 @@ void AUD_set_volume_in (SWVoiceIn *sw, int mute, uint8_t lvol, uint8_t rvol)
         }
     }
 }
+
+int64_t audio_get_timer_ticks(void)
+{
+    return conf.period.ticks;
+}
audio/audio_int.h +2 -0
index 5bcb1c60e1..2f7fc4f8ac 100644
@@ -214,6 +214,8 @@ extern struct audio_driver pa_audio_driver;
 extern struct audio_driver spice_audio_driver;
 extern const struct mixeng_volume nominal_volume;
 
+int64_t audio_get_timer_ticks(void);
+
 void audio_pcm_init_info (struct audio_pcm_info *info, struct audsettings *as);
 void audio_pcm_info_clear_buf (struct audio_pcm_info *info, void *buf, int len);
 
audio/paaudio.c +370 -492

1,094 lines not on this page · raw message

Signature · 1 line
2.14.2
#2 lore raw

PATCH v2 2/2 audio/hda: create millisecond timers that handle IO

In reply to Martin Schrodt

Currently, the HDA device tries to sync itself with the QEMU audio backend by waiting for the guest driver to handle buffer completion interrupts. This causes the backend to often read too much data from the device, as well as running out of data whenever the guest takes too long to handle the interrupt.

According to the HDA specification, the guest is also not required to use interrupts, but can also sync itself by polling the LPIB registers.

This patch will introduce high frequency (1000Hz) timers that interface with the device and allow for much smoother emulation of the LPIB registers. Since the timing is now provided by these timers, the need to wait for buffer completion interrupts also ceases.

Together with change of the Pulse Audio Driver, this allows for crackle free, clean playback using the HDA device. I have not yet tested this, but this should also improve the output with other backends (for example Alsa).

---
 hw/audio/hda-codec.c | 193 ++++++++++++++++++++++++++++++++++++++++-----------
 hw/audio/intel-hda.c |   7 --
 2 files changed, 154 insertions(+), 46 deletions(-)
hw/audio/hda-codec.c +154 -39
index 5402cd196c..ab89158bfc 100644
@@ -18,6 +18,7 @@
  */
 
 #include "qemu/osdep.h"
+#include "qemu/atomic.h"
 #include "hw/hw.h"
 #include "hw/pci/pci.h"
 #include "intel-hda.h"
@@ -126,6 +127,11 @@ static void hda_codec_parse_fmt(uint32_t format, struct audsettings *as)
 #define   PARAM nomixemu
 #include  "hda-codec-common.h"
 
+#define HDA_TIMER_TICKS (SCALE_MS)
+#define MAX_CORR (SCALE_US * 100)
+#define B_SIZE sizeof(st->buf)
+#define B_MASK (sizeof(st->buf) - 1)
+
 /* -------------------------------------------------------------------------- */
 
 static const char *fmt2name[] = {
@@ -154,8 +160,13 @@ struct HDAAudioStream {
         SWVoiceIn *in;
         SWVoiceOut *out;
     } voice;
-    uint8_t buf[HDA_BUFFER_SIZE];
-    uint32_t bpos;
+    uint8_t compat_buf[HDA_BUFFER_SIZE];
+    uint32_t compat_bpos;
+    uint8_t buf[8192]; /* size must be power of two */
+    int64_t rpos;
+    int64_t wpos;
+    QEMUTimer *buft;
+    int64_t buft_start;
 };
 
 #define TYPE_HDA_AUDIO "hda-audio"
@@ -176,53 +187,146 @@ struct HDAAudioState {
     bool     mixer;
 };
 
+static inline int64_t hda_bytes_per_second(HDAAudioStream *st)
+{
+    return 2 * st->as.nchannels * st->as.freq;
+}
+
+static inline void hda_timer_sync_adjust(HDAAudioStream *st, int64_t target_pos)
+{
+    int64_t corr =
+        NANOSECONDS_PER_SECOND * target_pos / hda_bytes_per_second(st);
+    if (corr > MAX_CORR) {
+        corr = MAX_CORR;
+    } else if (corr < -MAX_CORR) {
+        corr = -MAX_CORR;
+    }
+    atomic_fetch_add(&st->buft_start, corr);
+}
+
+static void hda_audio_input_timer(void *opaque)
+{
+    HDAAudioStream *st = opaque;
+
+    int64_t now = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
+
+    int64_t buft_start = atomic_fetch_add(&st->buft_start, 0);
+    int64_t wpos = atomic_fetch_add(&st->wpos, 0);
+    int64_t rpos = atomic_fetch_add(&st->rpos, 0);
+
+    int64_t wanted_rpos = hda_bytes_per_second(st) * (now - buft_start)
+                          / NANOSECONDS_PER_SECOND;
+    wanted_rpos &= -4; /* IMPORTANT! clip to frames */
+
+    if (wanted_rpos <= rpos) {
+        /* we already transmitted the data */
+        goto out_timer;
+    }
+
+    int64_t to_transfer = audio_MIN(wpos - rpos, wanted_rpos - rpos);
+    while (to_transfer) {
+        uint32_t start = (rpos & B_MASK);
+        uint32_t chunk = audio_MIN(B_SIZE - start, to_transfer);
+        int rc = hda_codec_xfer(
+                &st->state->hda, st->stream, false, st->buf + start, chunk);
+        if (!rc) {
+            break;
+        }
+        rpos += chunk;
+        to_transfer -= chunk;
+        atomic_fetch_add(&st->rpos, chunk);
+    }
+
+out_timer:
+
+    if (st->running) {
+        timer_mod_anticipate_ns(st->buft, now + HDA_TIMER_TICKS);
+    }
+}
+
 static void hda_audio_input_cb(void *opaque, int avail)
 {
     HDAAudioStream *st = opaque;
-    int recv = 0;
-    int len;
-    bool rc;
-
-    while (avail - recv >= sizeof(st->buf)) {
-        if (st->bpos != sizeof(st->buf)) {
-            len = AUD_read(st->voice.in, st->buf + st->bpos,
-                           sizeof(st->buf) - st->bpos);
-            st->bpos += len;
-            recv += len;
-            if (st->bpos != sizeof(st->buf)) {
-                break;
-            }
+
+    int64_t wpos = atomic_fetch_add(&st->wpos, 0);
+    int64_t rpos = atomic_fetch_add(&st->rpos, 0);
+
+    int64_t to_transfer = audio_MIN(B_SIZE - (wpos - rpos), avail);
+
+    hda_timer_sync_adjust(st, -((wpos - rpos) + to_transfer - (B_SIZE >> 1)));
+
+    while (to_transfer) {
+        uint32_t start = (uint32_t) (wpos & B_MASK);
+        uint32_t chunk = (uint32_t) audio_MIN(B_SIZE - start, to_transfer);
+        uint32_t read = AUD_read(st->voice.in, st->buf + start, chunk);
+        wpos += read;
+        to_transfer -= read;
+        atomic_fetch_add(&st->wpos, read);
+        if (chunk != read) {
+            break;
         }
-        rc = hda_codec_xfer(&st->state->hda, st->stream, false,
-                            st->buf, sizeof(st->buf));
+    }
+}
+
+static void hda_audio_output_timer(void *opaque)
+{
+    HDAAudioStream *st = opaque;
+
+    int64_t now = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
+
+    int64_t buft_start = atomic_fetch_add(&st->buft_start, 0);
+    int64_t wpos = atomic_fetch_add(&st->wpos, 0);
+    int64_t rpos = atomic_fetch_add(&st->rpos, 0);
+
+    int64_t wanted_wpos = hda_bytes_per_second(st) * (now - buft_start)
+                          / NANOSECONDS_PER_SECOND;
+    wanted_wpos &= -4; /* IMPORTANT! clip to frames */
+
+    if (wanted_wpos <= wpos) {
+        /* we already received the data */
+        goto out_timer;
+    }
+
+    int64_t to_transfer = audio_MIN(B_SIZE - (wpos - rpos), wanted_wpos - wpos);
+    while (to_transfer) {
+        uint32_t start = (wpos & B_MASK);
+        uint32_t chunk = audio_MIN(B_SIZE - start, to_transfer);
+        int rc = hda_codec_xfer(
+                &st->state->hda, st->stream, true, st->buf + start, chunk);
         if (!rc) {
             break;
         }
-        st->bpos = 0;
+        wpos += chunk;
+        to_transfer -= chunk;
+        atomic_fetch_add(&st->wpos, chunk);
+    }
+
+out_timer:
+
+    if (st->running) {
+        timer_mod_anticipate_ns(st->buft, now + HDA_TIMER_TICKS);
     }
 }
 
 static void hda_audio_output_cb(void *opaque, int avail)
 {
     HDAAudioStream *st = opaque;
-    int sent = 0;
-    int len;
-    bool rc;
-
-    while (avail - sent >= sizeof(st->buf)) {
-        if (st->bpos == sizeof(st->buf)) {
-            rc = hda_codec_xfer(&st->state->hda, st->stream, true,
-                                st->buf, sizeof(st->buf));
-            if (!rc) {
-                break;
-            }
-            st->bpos = 0;
-        }
-        len = AUD_write(st->voice.out, st->buf + st->bpos,
-                        sizeof(st->buf) - st->bpos);
-        st->bpos += len;
-        sent += len;
-        if (st->bpos != sizeof(st->buf)) {
+
+    int64_t wpos = atomic_fetch_add(&st->wpos, 0);
+    int64_t rpos = atomic_fetch_add(&st->rpos, 0);
+
+    int64_t to_transfer = audio_MIN(wpos - rpos, avail);
+
+    hda_timer_sync_adjust(st, (wpos - rpos) - to_transfer - (B_SIZE >> 1));
+
+    while (to_transfer) {
+        uint32_t start = (uint32_t) (rpos & B_MASK);
+        uint32_t chunk = (uint32_t) audio_MIN(B_SIZE - start, to_transfer);
+        uint32_t written = AUD_write(st->voice.out, st->buf + start, chunk);
+        rpos += written;
+        to_transfer -= written;
+        atomic_fetch_add(&st->rpos, written);
+        if (chunk != written) {
             break;
         }
     }
@@ -239,6 +343,15 @@ static void hda_audio_set_running(HDAAudioStream *st, bool running)
     st->running = running;
     dprint(st->state, 1, "%s: %s (stream %d)\n", st->node->name,
            st->running ? "on" : "off", st->stream);
+    if (running) {
+        int64_t now = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
+        st->rpos = 0;
+        st->wpos = 0;
+        st->buft_start = now;
+        timer_mod_anticipate_ns(st->buft, now + HDA_TIMER_TICKS);
+    } else {
+        timer_del(st->buft);
+    }
     if (st->output) {
         AUD_set_active_out(st->voice.out, st->running);
     } else {
@@ -286,10 +399,12 @@ static void hda_audio_setup(HDAAudioStream *st)
         st->voice.out = AUD_open_out(&st->state->card, st->voice.out,
                                      st->node->name, st,
                                      hda_audio_output_cb, &st->as);
+        st->buft = timer_new_ns(QEMU_CLOCK_VIRTUAL, hda_audio_output_timer, st);
     } else {
         st->voice.in = AUD_open_in(&st->state->card, st->voice.in,
                                    st->node->name, st,
                                    hda_audio_input_cb, &st->as);
+        st->buft = timer_new_ns(QEMU_CLOCK_VIRTUAL, hda_audio_input_timer, st);
     }
 }
 
@@ -505,7 +620,6 @@ static int hda_audio_init(HDACodecDevice *hda, const struct desc_codec *desc)
                 /* unmute output by default */
                 st->gain_left = QEMU_HDA_AMP_STEPS;
                 st->gain_right = QEMU_HDA_AMP_STEPS;
-                st->bpos = sizeof(st->buf);
                 st->output = true;
             } else {
                 st->output = false;
@@ -532,6 +646,7 @@ static void hda_audio_exit(HDACodecDevice *hda)
         if (st->node == NULL) {
             continue;
         }
+        timer_del(st->buft);
         if (st->output) {
             AUD_close_out(&a->card, st->voice.out);
         } else {
@@ -592,8 +707,8 @@ static const VMStateDescription vmstate_hda_audio_stream = {
         VMSTATE_UINT32(gain_right, HDAAudioStream),
         VMSTATE_BOOL(mute_left, HDAAudioStream),
         VMSTATE_BOOL(mute_right, HDAAudioStream),
-        VMSTATE_UINT32(bpos, HDAAudioStream),
-        VMSTATE_BUFFER(buf, HDAAudioStream),
+        VMSTATE_UINT32(compat_bpos, HDAAudioStream),
+        VMSTATE_BUFFER(compat_buf, HDAAudioStream),
         VMSTATE_END_OF_LIST()
     }
 };
hw/audio/intel-hda.c +0 -7
index 18a50a8f83..721eba792d 100644
@@ -407,13 +407,6 @@ static bool intel_hda_xfer(HDACodecDevice *dev, uint32_t stnr, bool output,
     if (st->bpl == NULL) {
         return false;
     }
-    if (st->ctl & (1 << 26)) {
-        /*
-         * Wait with the next DMA xfer until the guest
-         * has acked the buffer completion interrupt
-         */
-        return false;
-    }
 
     left = len;
     s = st->bentries;
Signature · 1 line
2.14.2