fix: use atomic.Bool for audio source to prevent mutex contention during switching

This commit is contained in:
Alex P 2025-10-29 00:26:48 +02:00
parent 4bc60c3f1b
commit 802166ba23
2 changed files with 11 additions and 14 deletions

View File

@ -22,7 +22,7 @@ var (
audioLogger zerolog.Logger
currentAudioTrack *webrtc.TrackLocalStaticSample
inputTrackHandling atomic.Bool
useUSBForAudioOutput bool
useUSBForAudioOutput atomic.Bool
audioOutputEnabled atomic.Bool
audioInputEnabled atomic.Bool
)
@ -32,7 +32,7 @@ func initAudio() {
// Load audio output source from config
ensureConfigLoaded()
useUSBForAudioOutput = config.AudioOutputSource == "usb"
useUSBForAudioOutput.Store(config.AudioOutputSource == "usb")
// Enable both by default
audioOutputEnabled.Store(true)
@ -57,7 +57,7 @@ func startAudio() error {
// Start output audio if not running and enabled
if outputSource == nil && audioOutputEnabled.Load() {
alsaDevice := "hw:0,0" // HDMI
if useUSBForAudioOutput {
if useUSBForAudioOutput.Load() {
alsaDevice = "hw:1,0" // USB
}
@ -167,17 +167,17 @@ func SetAudioOutputSource(useUSB bool) error {
audioMutex.Lock()
defer audioMutex.Unlock()
if useUSBForAudioOutput == useUSB {
if useUSBForAudioOutput.Load() == useUSB {
return nil
}
audioLogger.Info().
Bool("old_usb", useUSBForAudioOutput).
Bool("old_usb", useUSBForAudioOutput.Load()).
Bool("new_usb", useUSB).
Msg("Switching audio output source")
oldValue := useUSBForAudioOutput
useUSBForAudioOutput = useUSB
oldValue := useUSBForAudioOutput.Load()
useUSBForAudioOutput.Store(useUSB)
ensureConfigLoaded()
if useUSB {
@ -187,7 +187,7 @@ func SetAudioOutputSource(useUSB bool) error {
}
if err := SaveConfig(); err != nil {
audioLogger.Error().Err(err).Msg("Failed to save config")
useUSBForAudioOutput = oldValue
useUSBForAudioOutput.Store(oldValue)
return err
}

View File

@ -899,7 +899,7 @@ func updateUsbRelatedConfig(wasAudioEnabled bool) error {
if config.UsbDevices != nil && !config.UsbDevices.Audio && config.AudioOutputSource == "usb" {
audioMutex.Lock()
config.AudioOutputSource = "hdmi"
useUSBForAudioOutput = false
useUSBForAudioOutput.Store(false)
audioSourceChanged = true
audioMutex.Unlock()
}
@ -908,7 +908,7 @@ func updateUsbRelatedConfig(wasAudioEnabled bool) error {
if config.UsbDevices != nil && config.UsbDevices.Audio && !wasAudioEnabled {
audioMutex.Lock()
config.AudioOutputSource = "usb"
useUSBForAudioOutput = true
useUSBForAudioOutput.Store(true)
audioSourceChanged = true
audioMutex.Unlock()
}
@ -970,10 +970,7 @@ func rpcSetUsbDeviceState(device string, enabled bool) error {
}
func rpcGetAudioOutputSource() (string, error) {
audioMutex.Lock()
defer audioMutex.Unlock()
if useUSBForAudioOutput {
if useUSBForAudioOutput.Load() {
return "usb", nil
}
return "hdmi", nil