From 86488a7fc209ac08dd92c9d50a77e3330e7aedd9 Mon Sep 17 00:00:00 2001
From: Patrick Zacharias <1475802+Fighter19@users.noreply.github.com>
Date: Thu, 7 Nov 2024 14:03:29 +0100
Subject: [PATCH] Determine audio buffer size for a time of 500ms

On some hardware like the SGTL5000, not specifying a buffer size
results to EINVAL being returned.

This code sets the buffer time to 500ms and the period time to a fourth of that,
or whatever is nearest to that.

Upstream-Status: Pending
---
 src/alsa.c | 15 +++++++++++++++
 1 file changed, 15 insertions(+)

diff --git a/src/alsa.c b/src/alsa.c
index bebcc4a..ac26578 100644
--- a/src/alsa.c
+++ b/src/alsa.c
@@ -258,6 +258,21 @@ static int open_alsa(ca_context *c, struct outstanding *out) {
         if ((ret = snd_pcm_hw_params_set_channels(out->pcm, hwparams, ca_sound_file_get_nchannels(out->file))) < 0)
                 goto finish;
 
+        unsigned int buffer_time = 0;
+        if ((ret = snd_pcm_hw_params_get_buffer_time_max(hwparams, &buffer_time, 0)) < 0)
+                goto finish;
+
+        // Cap the buffer time to 500ms
+        if (buffer_time > 500000)
+                buffer_time = 500000;
+
+        unsigned int period_time = buffer_time / 4;
+        if ((ret = snd_pcm_hw_params_set_period_time_near(out->pcm, hwparams, &period_time, 0)) < 0)
+                goto finish;
+
+        if ((ret = snd_pcm_hw_params_set_buffer_time_near(out->pcm, hwparams, &buffer_time, 0)) < 0)
+                goto finish;
+
         if ((ret = snd_pcm_hw_params(out->pcm, hwparams)) < 0)
                 goto finish;
 
