Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
284 changes: 283 additions & 1 deletion audio1/audio.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,10 @@ import (
"fmt"
"math"
"os"
"os/exec"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"time"
Expand Down Expand Up @@ -63,6 +65,9 @@ const (
dsgKeyBluezModeDefault = "bluezModeDefault"
dsgKeyMonoEnabled = "monoEnabled"
dsgKeyReduceNoiseEnabled = "reduceNoiseEnabled" // 降噪配置,保存用户数据
dsgKeyAiReduceNoiseEnabled = "aiReduceNoiseEnabled"
dsgKeyAiNoiseSourceName = "aiNoisePhysicalSourceName" // 开启AI降噪时持久化的物理麦克风名
rnnoiseSourceName = "effect_output.rnnoise"

dsgKeyFirstRun = "firstRun"
dsgKeyInputVolume = "inputVolume"
Expand Down Expand Up @@ -95,7 +100,7 @@ const (
AudioStateChanging = false
)

//go:generate dbusutil-gen -type Audio,Sink,SinkInput,Source,Meter -import github.com/godbus/dbus audio.go sink.go sinkinput.go source.go meter.go
//go:generate dbusutil-gen -type Audio,Sink,SinkInput,Source,Meter -import github.com/godbus/dbus/v5 audio.go sink.go sinkinput.go source.go meter.go
//go:generate dbusutil-gen em -type Audio,Sink,SinkInput,Source,Meter

func objectPathSliceEqual(v1, v2 []dbus.ObjectPath) bool {
Expand Down Expand Up @@ -151,6 +156,12 @@ type Audio struct {

ReduceNoise bool `prop:"access:rw"`

AiReduceNoise bool `prop:"access:rw"`

AiNoiseSourcePath dbus.ObjectPath

aiNoiseSourceName string

defaultPaCfg defaultPaConfig

// 最大音量
Expand Down Expand Up @@ -240,6 +251,10 @@ func newAudio(service *dbusutil.Service) *Audio {
a.PausePlayer = false
a.ReduceNoise = false
a.emitPropChangedReduceNoise(a.ReduceNoise)
a.AiReduceNoise = false
a.emitPropChangedAiReduceNoise(a.AiReduceNoise)
a.AiNoiseSourcePath = "/"
a.emitPropChangedAiNoiseSourcePath(a.AiNoiseSourcePath)
a.CurrentAudioServer = a.getCurrentAudioServer()
a.headphoneUnplugAutoPause, err = a.audioDConfig.GetValueBool(dsgKeyHeadphoneUnplugAutoPause)
if err != nil {
Expand Down Expand Up @@ -804,6 +819,10 @@ func (a *Audio) init() error {

// 更新本地数据
a.refresh()

// After refresh, run AI noise-reduction init with both DConfig and
// source list available.
a.initAiReduceNoise()
logger.Debug("init cards")
a.PropsMu.Lock()
a.setPropCards(a.cards.string())
Expand Down Expand Up @@ -941,6 +960,29 @@ func (a *Audio) findSource(cardId uint32, activePortName string) *Source {
return nil
}

// getSourcePathByName returns the D-Bus object path of the source whose Name
// matches, or "/" if not found. Used to expose the physical mic's Source path
// to control center while AI noise reduction is enabled.
func (a *Audio) getSourcePathByName(name string) dbus.ObjectPath {
if name == "" {
return "/"
}
a.mu.Lock()
defer a.mu.Unlock()
for _, source := range a.sources {
if source.Name == name {
return source.getPath()
}
}
return "/"
}

// updateAiNoiseSourcePath refreshes the AiNoiseSourcePath D-Bus property from
// aiNoiseSourceName. Call under PropsMu.
func (a *Audio) updateAiNoiseSourcePath() {
a.setPropAiNoiseSourcePath(a.getSourcePathByName(a.aiNoiseSourceName))
}

func (a *Audio) SetPortEnabled(cardId uint32, portName string, enabled bool) *dbus.Error {
logger.Infof("dbus call SetPortEnabled with cardId %d, portName %s and enabled %t", cardId, portName, enabled)

Expand Down Expand Up @@ -1868,6 +1910,19 @@ func (a *Audio) initDsgProp() error {
}
getReduceNoiseEnabled()

getAiReduceNoiseEnabled := func() {
aiReduceNoiseEnabled, err := a.audioDConfig.GetValueBool(dsgKeyAiReduceNoiseEnabled)
if err != nil {
logger.Warningf("aiReduceNoise DConfig: GetValueBool failed: %v", err)
return
}
logger.Infof("aiReduceNoise: DConfig=%v, calling setAiReduceNoise", aiReduceNoiseEnabled)
a.setAiReduceNoise(aiReduceNoiseEnabled)
}
// NOTE: do NOT call getAiReduceNoiseEnabled() during initDsgProp — it runs
// before refresh() and would get an empty default-source name. The actual
// init is done in initAiReduceNoise() after refresh().

a.audioDConfig.ConnectValueChanged(func(key string) {
switch key {
case dsgKeyAutoSwitchPort:
Expand All @@ -1884,6 +1939,8 @@ func (a *Audio) initDsgProp() error {
getMonoEnabled()
case dsgKeyVolumeIncrease:
a.handleVolumeIncrease()
case dsgKeyAiReduceNoiseEnabled:
getAiReduceNoiseEnabled()
}
})

Expand Down Expand Up @@ -2009,3 +2066,228 @@ func (a *Audio) isModuleExist(name string) bool {
}
return false
}

func (a *Audio) paDefaultSourceIs(target string) bool {
out, err := exec.Command("pactl", "get-default-source").Output()
if err != nil {
return false
}
return strings.TrimSpace(string(out)) == target
}

func (a *Audio) recoverPhysicalSourceName() string {
runtimeDir := os.Getenv("XDG_RUNTIME_DIR")
if runtimeDir == "" {
runtimeDir = "/run/user/" + strconv.Itoa(os.Getuid())
}

// 1) rnnoise-toggle's saved original source (tmpfs, may be gone after reboot).
stateFile := runtimeDir + "/rnnoise-toggle-original-source"
if data, err := os.ReadFile(stateFile); err == nil {
name := strings.TrimSpace(string(data))
if name != "" && name != rnnoiseSourceName {
return name
}
}

// 2) ConfigKeeper: find the source whose ActivePort matches the user's
// saved DefaultInputPort. This is the most reliable source across reboots
// because it records the port the user manually selected.
defaultPort := GetConfigKeeper().GetDefaultInputPortAnyCard()
if defaultPort != "" {
a.mu.Lock()
for _, s := range a.sources {
if s.ActivePort.Name == defaultPort && s.Name != rnnoiseSourceName {
name := s.Name
a.mu.Unlock()
return name
}
}
a.mu.Unlock()
}

// 3) DConfig — survives reboot but can be stale/wrong on multi-mic systems.
if name, err := a.audioDConfig.GetValueString(dsgKeyAiNoiseSourceName); err == nil {
name = strings.TrimSpace(name)
if name != "" && name != rnnoiseSourceName {
return name
}
}

// 4) Fallback: scan pactl source list for a non-rnnoise, non-monitor source.
out, err := exec.Command("pactl", "list", "sources", "short").Output()
if err != nil {
return ""
}
for _, line := range strings.Split(string(out), "\n") {
fields := strings.Fields(line)
if len(fields) >= 2 {
name := fields[1]
if name != rnnoiseSourceName && !strings.Contains(name, ".monitor") {
return name
}
}
}
return ""
}

func (a *Audio) setAiReduceNoise(enable bool) error {
a.PropsMu.Lock()
sameAsCurrent := a.AiReduceNoise == enable
if sameAsCurrent {
// Already in the requested state.
a.PropsMu.Unlock()
return nil
}

// Compute aiNoiseSourceName under lock before rnnoise-toggle changes
// the PA default source (which would trigger updateDefaultSource on
// the PA goroutine and race on aiNoiseSourceName).
var micName string
var micNameRecovered bool // true if micName came from recoverPhysicalSourceName()
if enable {
if defaultPort := GetConfigKeeper().GetDefaultInputPortAnyCard(); defaultPort != "" {
a.mu.Lock()
for _, s := range a.sources {
if s.ActivePort.Name == defaultPort && s.Name != rnnoiseSourceName {
micName = s.Name
break
}
}
a.mu.Unlock()
}
if micName == "" {
micName = a.getDefaultSourceName()
if micName == rnnoiseSourceName || micName == "" {
micName = a.recoverPhysicalSourceName()
micNameRecovered = true
}
}
a.aiNoiseSourceName = micName
} else {
micName = a.aiNoiseSourceName
}
a.PropsMu.Unlock()

// Phase 2: Execute PA operations (outside PropsMu to avoid blocking
// PA event handlers like updateDefaultSource).
if enable {
// Enable rnnoise: rnnoise-toggle saves the current default source
// (the physical mic) and sets effect_output.rnnoise as default.
cmd := exec.Command("rnnoise-toggle", "-q", "on")
err := cmd.Run()
if err != nil {
// rnnoise-toggle -q on exits 1 when default source is already
// effect_output.rnnoise (save_original_source rejects its own).
if a.paDefaultSourceIs(rnnoiseSourceName) {
logger.Warningf("rnnoise-toggle -q on reported failure "+
"but default source is already %s; continuing", rnnoiseSourceName)
} else {
logger.Warning("failed to enable ai reduce noise:", err)
return err
}
}
} else {
args := []string{"-q", "off"}
if micName != "" {
args = append(args, micName)
}
cmd := exec.Command("rnnoise-toggle", args...)
err := cmd.Run()
if err != nil {
if !a.paDefaultSourceIs(rnnoiseSourceName) {
logger.Warningf("rnnoise-toggle -q off reported failure "+
"but default source is no longer %s; continuing", rnnoiseSourceName)
} else {
logger.Warning("failed to disable ai reduce noise:", err)
return err
}
}
}

// Phase 3: Update property and persist DConfig (only on success).
a.PropsMu.Lock()
a.setPropAiReduceNoise(enable)
if enable {
// AiNoiseSourceName was computed in Phase 1; refresh the path so
// control center can bind the volume slider to the physical mic.
a.updateAiNoiseSourcePath()
} else {
// Clear the path — DefaultSource is the physical mic again.
if a.AiNoiseSourcePath != "/" {
a.AiNoiseSourcePath = "/"
a.emitPropChangedAiNoiseSourcePath(a.AiNoiseSourcePath)
}
}
a.PropsMu.Unlock()
if err := a.audioDConfig.SetValue(dsgKeyAiReduceNoiseEnabled, enable); err != nil {
logger.Warning("failed to persist aiReduceNoiseEnabled to dconfig:", err)
}
if enable && !micNameRecovered {
if err := a.audioDConfig.SetValue(dsgKeyAiNoiseSourceName, micName); err != nil {
logger.Warning("failed to persist aiNoisePhysicalSourceName to dconfig:", err)
}
} else if !enable {
if err := a.audioDConfig.SetValue(dsgKeyAiNoiseSourceName, ""); err != nil {
logger.Warning("failed to clear aiNoisePhysicalSourceName in dconfig:", err)
}
}
return nil
}

func (a *Audio) initAiReduceNoise() {
logger.Debug("initAiReduceNoise")

// 1. Check if rnnoise source already exists in the source list.
a.mu.Lock()
rnnoiseFound := false
for _, src := range a.sources {
if src.Name == rnnoiseSourceName {
rnnoiseFound = true
break
}
}
a.mu.Unlock()

// 2. Check DConfig value.
aiReduceNoiseEnabled, err := a.audioDConfig.GetValueBool(dsgKeyAiReduceNoiseEnabled)
if err != nil {
logger.Warningf("initAiReduceNoise: DConfig GetValueBool failed: %v", err)
}

shouldEnable := aiReduceNoiseEnabled
if err != nil && rnnoiseFound {
shouldEnable = true
}
if !shouldEnable {
logger.Infof("initAiReduceNoise: DConfig=%v (err=%v), rnnoiseFound=%v, nothing to do",
aiReduceNoiseEnabled, err != nil, rnnoiseFound)
return
}

logger.Infof("initAiReduceNoise: DConfig=%v, rnnoiseFound=%v, calling setAiReduceNoise(true)",
aiReduceNoiseEnabled, rnnoiseFound)
if err := a.setAiReduceNoise(true); err != nil {
logger.Warning("initAiReduceNoise: setAiReduceNoise(true) failed:", err)
return
}

a.PropsMu.RLock()
micName := a.aiNoiseSourceName
a.PropsMu.RUnlock()
if micName != "" {
a.mu.Lock()
var micSource *Source
for _, s := range a.sources {
if s.Name == micName {
micSource = s
break
}
}
a.mu.Unlock()
if micSource != nil {
logger.Infof("initAiReduceNoise: resumeSourceConfig for %s", micName)
a.resumeSourceConfig(micSource)
}
}
}
28 changes: 27 additions & 1 deletion audio1/audio_dbusutil.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading