shithub: qk1

Download patch

ref: 08ea19ee8b2e15ade2ba7f2408a14b89225b05b5
parent: d40a186cc44a69a1e138e3347298e477b6f8d81f
author: Sigrid Solveig Haflínudóttir <sigrid@ftrv.se>
date: Tue Nov 7 14:03:18 EST 2023

audio: completely stop audio when needed, resume on next write

--- a/fns.h
+++ b/fns.h
@@ -59,6 +59,7 @@
 char *lerr(void);
 int	sys_mkdir(char *path);
 
+void sndstop(void);
 void sndwrite(uchar *buf, long sz);
 void sndclose(void);
 int sndopen(void);
--- a/snd.c
+++ b/snd.c
@@ -33,8 +33,7 @@
 static Chan *chans, *che;
 
 static int ainit, mixbufi;
-static uchar *mixbufs[2], *mixbuf;
-static int mixbufsz[2];
+static uchar mixbufs[2][Ssamp*Sblk], *mixbuf;
 static vlong sndt, sampt;
 static int nsamp;
 static int sampbuf[Ssamp*2];
@@ -531,10 +530,6 @@
 	if(nsamp > Ssamp)
 		nsamp = Ssamp;
 	ns = nsamp * Sblk;
-	if(ns > mixbufsz[mixbufi]){
-		mixbufsz[mixbufi] = ns;
-		mixbufs[mixbufi] = realloc(mixbufs[mixbufi], mixbufsz[mixbufi]);
-	}
 	mixbuf = mixbufs[mixbufi];
 	samplesfx();
 	sampt += nsamp;
@@ -541,7 +536,6 @@
 	if(ns != 0){
 		sndwrite(mixbuf, ns);
 		mixbufi = (mixbufi + 1) % nelem(mixbufs);
-		mixbuf = mixbufs[mixbufi];
 	}
 	sndt = nanosec();
 }
@@ -553,6 +547,7 @@
 		return;
 	memset(chans, 0, sizeof(*chans)*Nchan);
 	che = chans + Sstat;
+	sndstop();
 }
 
 void
--- a/snd_plan9.c
+++ b/snd_plan9.c
@@ -26,11 +26,18 @@
 }
 
 void
+sndstop(void)
+{
+	close(afd);
+	afd = -1;
+}
+
+void
 sndwrite(uchar *buf, long sz)
 {
 	static Channel *ach;
 
-	if(afd < 0)
+	if(afd < 0 && sndopen() < 0)
 		return;
 	if(ach == nil){
 		ach = chancreate(sizeof(ulong), 0);
--- a/unix/snd_sdl.c
+++ b/unix/snd_sdl.c
@@ -4,9 +4,22 @@
 static SDL_AudioDeviceID adev;
 
 void
+sndstop(void)
+{
+	if(adev == 0)
+		return;
+	SDL_ClearQueuedAudio(adev);
+	SDL_PauseAudioDevice(adev, 1);
+}
+
+void
 sndwrite(uchar *buf, long sz)
 {
-	if(adev != 0 && SDL_QueueAudio(adev, buf, sz) != 0){
+	if(adev == 0)
+		return;
+	if(SDL_QueueAudio(adev, buf, sz) == 0)
+		SDL_PauseAudioDevice(adev, 0);
+	else{
 		Con_Printf("sndwrite: %s\n", SDL_GetError());
 		sndclose();
 	}
@@ -15,11 +28,11 @@
 void
 sndclose(void)
 {
-	if(adev != 0){
-		SDL_CloseAudioDevice(adev);
-		SDL_QuitSubSystem(SDL_INIT_AUDIO);
-		adev = 0;
-	}
+	if(adev == 0)
+		return;
+	SDL_CloseAudioDevice(adev);
+	SDL_QuitSubSystem(SDL_INIT_AUDIO);
+	adev = 0;
 }
 
 int
@@ -42,6 +55,5 @@
 		SDL_QuitSubSystem(SDL_INIT_AUDIO);
 		goto err;
 	}
-	SDL_PauseAudioDevice(adev, 0);
 	return 0;
 }