Skip to content
Merged
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
2 changes: 2 additions & 0 deletions changelog.d/280-notification-sound.change.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
实例默认关掉通知提示音,通知照常显示 (ModAVD/ModAVD#280)
Instances now have the notification sound off by default; notifications still show (ModAVD/ModAVD#280)
4 changes: 4 additions & 0 deletions internal/emu/afterboot.go
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,10 @@ func (m *Manager) afterBoot(ctx context.Context, inst *avd.Instance, mode bootSe
}

steps := []func(){
// 0) the notification tone off, once per instance and not in the first boot of a new one (notifysound.go,
// ModAVD/ModAVD#280): first of all, before the guest posts a notification the sound would play for (the
// Safety Center's, about 18 s after the boot)
func() { m.setupNotificationSound(ctx, i) },
func() {
// 0a) the guest library fixes (Vulkan driver, ARM translation layer). A launched boot of an initialized
// instance has mounted them during the boot animation already (earlyGuestFixes): this only finds them
Expand Down
99 changes: 99 additions & 0 deletions internal/emu/notifysound.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
package emu

// The guest's notification sound off by default (ModAVD/ModAVD#280): with sound on, the system plays the default
// notification tone for every notification, e.g. the Safety Center's "no screen lock" one about 18 s after a boot, and
// nobody is at an unattended instance to want it.
//
// What the default tone is: the channels' sound is the URI content://settings/system/notification_sound, which the
// player resolves through the system setting of that name. The setting unset (`settings delete`, `settings get` then
// prints "null") resolves to nothing, so no track is played at all. `settings put system notification_sound ''` does
// not do it (the empty value is ignored and the old one stays). This needs no sound card and leaves the media volume,
// the touch sounds and the ringtone alone; the notifications themselves still show.
//
// Once per instance, recorded in mas-avd.json: an instance set up before this existed gets it at its next boot too,
// and a tone the user chose afterwards is not overwritten at every boot. Not during the first boot of a new instance
// (before the first-boot setup has recorded initialized): the system sets its default tones when its first media scan
// finishes, which can be after this step and then puts the default back (measured 11-27: a create that muted at its
// first boot read the default again at the next start). The next boot is the first one nobody can have heard the tone
// at: the Safety Center posts its notification only 12 hours after it first saw the issue.

import (
"context"
"errors"
"fmt"
"strings"
"time"

"modavd/internal/adb"
"modavd/internal/jsonord"
)

// notificationSoundMutedKey is instances.<i>.notificationSoundMuted in mas-avd.json: true once the notification sound
// was turned off.
const notificationSoundMutedKey = "notificationSoundMuted"

const notificationSoundTimeout = 15 * time.Second

// muteNotificationSoundCommand unsets the setting and reads it back (an unset one reads "null").
const muteNotificationSoundCommand = "settings delete system notification_sound && settings get system notification_sound"

// notificationSoundUnset judges the output of muteNotificationSoundCommand: the read-back (its last line) is "null".
func notificationSoundUnset(out string) bool {
return lastNonEmptyLine(out) == "null"
}

// setupNotificationSound is the first step of afterBoot: it runs before the guest can post anything the user would
// hear. Only warnings: a failure leaves the marker unset and the next boot tries again.
func (m *Manager) setupNotificationSound(ctx context.Context, i int) {
m.muteNotificationSound(ctx, i, func(ctx context.Context, command string) adb.Result { return m.shell(ctx, i, command, 0) })
}

// muteNotificationSound bounds the whole step, including adb cleanup and metadata I/O.
func (m *Manager) muteNotificationSound(ctx context.Context, i int, run func(context.Context, string) adb.Result) {
ctx, cancel := context.WithTimeout(ctx, notificationSoundTimeout)
defer cancel()
type result struct {
muted bool
err error
}
done := make(chan result, 1)
go func() {
muted, err := m.tryMuteNotificationSound(ctx, i, run)
done <- result{muted, err}
}()
select {
case res := <-done:
switch {
case res.err != nil && res.muted:
m.Log.Warnf("实例 %d 通知提示音已关,但结果没写进 mas-avd.json,下次开机再关一次: %v", i, res.err)
case res.err != nil:
m.Log.Warnf("实例 %d 没关掉通知提示音(下次开机重试): %s", i, res.err.Error())
case res.muted:
m.Log.Infof("实例 %d 已关掉通知提示音(通知照常显示)", i)
}
case <-ctx.Done():
m.Log.Warnf("实例 %d 没关掉通知提示音(下次开机重试): %s", i, ctx.Err().Error())
}
}

func (m *Manager) tryMuteNotificationSound(ctx context.Context, i int, run func(context.Context, string) adb.Result) (bool, error) {
meta, err := m.Root.ReadInstanceMeta(i)
if err != nil {
return false, err
}
if !jsonTruthy(meta.Get("initialized")) || jsonTruthy(meta.Get(notificationSoundMutedKey)) {
return false, nil
}
if err := ctx.Err(); err != nil {
return false, err
}
res := run(ctx, muteNotificationSoundCommand)
if res.Code != 0 || !notificationSoundUnset(res.Out) {
return false, errors.New(orText(tail(strings.Join(strings.Fields(res.Out), " "), 200), fmt.Sprintf("退出码 %d", res.Code)))
}
err = m.Root.EditInstanceMetaContext(ctx, i, func(meta *jsonord.Obj) error {
meta.Set(notificationSoundMutedKey, jsonord.NewBool(true))
return nil
})
return true, err
}
260 changes: 260 additions & 0 deletions internal/emu/notifysound_windows_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,260 @@
//go:build windows

package emu

import (
"context"
"os"
"strings"
"sync"
"testing"
"time"

"modavd/internal/adb"
"modavd/internal/jsonord"
"modavd/internal/logx"
"modavd/internal/win"
)

func TestNotificationSoundUnset(t *testing.T) {
for out, want := range map[string]bool{
"Deleted 1 rows\nnull\n": true,
"Deleted 0 rows\r\nnull\r\n": true,
"null": true,
"Deleted 1 rows\ncontent://media/internal/audio/media/184?title=Pixie%20Dust&canonical=1\n": false,
"": false,
"Error: Unknown command: delete\n": false,
"null\nsomething\n": false,
} {
if got := notificationSoundUnset(out); got != want {
t.Errorf("notificationSoundUnset(%q) = %v, want %v", out, got, want)
}
}
}

// fakeSoundGuest is the guest shell of the tests: it answers the mute command with out / code and counts the calls.
type fakeSoundGuest struct {
mu sync.Mutex
out string
code int
commands []string
}

func (f *fakeSoundGuest) run(_ context.Context, command string) adb.Result {
f.mu.Lock()
defer f.mu.Unlock()
f.commands = append(f.commands, command)
return adb.Result{Code: f.code, Out: f.out}
}

func (f *fakeSoundGuest) calls() int {
f.mu.Lock()
defer f.mu.Unlock()
return len(f.commands)
}

func newSoundTestManager(t *testing.T) (*Manager, *[]string) {
t.Helper()
var mu sync.Mutex
var warnings []string
m := New(managerTestRoot(t, 1), logx.New(func(level logx.Level, message string) {
if level == logx.Warn {
mu.Lock()
warnings = append(warnings, message)
mu.Unlock()
}
}))
setInitialized(t, m, 1, true)
return m, &warnings
}

func setInitialized(t *testing.T, m *Manager, i int, on bool) {
t.Helper()
if err := m.Root.EditInstanceMeta(i, func(meta *jsonord.Obj) error {
meta.Set("initialized", jsonord.NewBool(on))
return nil
}); err != nil {
t.Fatal(err)
}
}

func (m *Manager) notificationSoundDone(i int) bool {
return jsonTruthy(m.Root.InstanceMeta(i).Get(notificationSoundMutedKey))
}

// The first boot of a new instance (not initialized yet) leaves the setting alone: the system sets its default tones
// when its first media scan ends, which may put the default back. The next boot does it.
func TestMuteNotificationSoundWaitsForFirstBoot(t *testing.T) {
m, _ := newSoundTestManager(t)
setInitialized(t, m, 1, false)
guest := &fakeSoundGuest{out: "Deleted 1 rows\nnull\n"}
m.muteNotificationSound(context.Background(), 1, guest.run)
if guest.calls() != 0 || m.notificationSoundDone(1) {
t.Fatalf("first boot: commands %q, marker %v", guest.commands, m.notificationSoundDone(1))
}
setInitialized(t, m, 1, true)
m.muteNotificationSound(context.Background(), 1, guest.run)
if guest.calls() != 1 || !m.notificationSoundDone(1) {
t.Fatalf("next boot: commands %q, marker %v", guest.commands, m.notificationSoundDone(1))
}
}

// The sound is turned off once: the marker is written, and a later boot does not touch the setting again (a tone the
// user chose meanwhile stays).
func TestMuteNotificationSoundOnce(t *testing.T) {
m, warnings := newSoundTestManager(t)
ctx := context.Background()
guest := &fakeSoundGuest{out: "Deleted 1 rows\nnull\n"}
if m.notificationSoundDone(1) {
t.Fatal("a new instance is marked as done")
}
m.muteNotificationSound(ctx, 1, func(ctx context.Context, command string) adb.Result {
if deadline, ok := ctx.Deadline(); !ok || time.Until(deadline) > notificationSoundTimeout {
t.Errorf("adb has no short deadline: %v", deadline)
}
return guest.run(ctx, command)
})
if guest.calls() != 1 || guest.commands[0] != muteNotificationSoundCommand {
t.Fatalf("first boot: commands %q", guest.commands)
}
if !m.notificationSoundDone(1) {
t.Fatal("no marker after success")
}
m.muteNotificationSound(ctx, 1, guest.run)
m.muteNotificationSound(ctx, 1, guest.run)
if guest.calls() != 1 {
t.Fatalf("later boots ran the guest command again: %q", guest.commands)
}
if m.notificationSoundDone(0) || len(*warnings) != 0 {
t.Fatalf("other instance done %v, warnings %q", m.notificationSoundDone(0), *warnings)
}
}

// An instance whose setting is already unset is only marked; a failed attempt (the setting is still there, a non-zero
// exit, a cancelled start) leaves no marker, so the next boot tries again.
func TestMuteNotificationSoundRetries(t *testing.T) {
ctx := context.Background()
still := "Deleted 0 rows\ncontent://media/internal/audio/media/184?title=Pixie%20Dust&canonical=1\n"
for name, c := range map[string]struct {
out string
code int
cancel bool
done bool
warn string
}{
"already unset": {out: "Deleted 0 rows\nnull\n", done: true},
"setting still set": {out: still, warn: "没关掉通知提示音"},
"adb failed": {out: "adb: device offline", code: 1, warn: "device offline"},
"no output": {code: 255, warn: "退出码 255"},
"canceled": {out: "Deleted 1 rows\nnull\n", cancel: true, warn: context.Canceled.Error()},
} {
t.Run(name, func(t *testing.T) {
m, warnings := newSoundTestManager(t)
guest := &fakeSoundGuest{out: c.out, code: c.code}
runCtx, cancel := context.WithCancel(ctx)
defer cancel()
if c.cancel {
cancel()
}
m.muteNotificationSound(runCtx, 1, guest.run)
if got := m.notificationSoundDone(1); got != c.done {
t.Fatalf("marker = %v, want %v", got, c.done)
}
if c.warn == "" && len(*warnings) != 0 ||
c.warn != "" && (len(*warnings) != 1 || !strings.Contains((*warnings)[0], c.warn)) {
t.Fatalf("warnings %q, want one with %q", *warnings, c.warn)
}
if !c.done {
before := guest.calls()
guest.out, guest.code = "Deleted 1 rows\nnull\n", 0
m.muteNotificationSound(ctx, 1, guest.run)
if !m.notificationSoundDone(1) || guest.calls() != before+1 {
t.Fatalf("the next boot did not mute: done %v, calls %d", m.notificationSoundDone(1), guest.calls())
}
}
})
}
}

func TestMuteNotificationSoundDeadline(t *testing.T) {
t.Run("adb", func(t *testing.T) {
m, warnings := newSoundTestManager(t)
started := make(chan struct{})
release := make(chan struct{})
defer close(release)
ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)
defer cancel()
done := make(chan struct{})
go func() {
defer close(done)
m.muteNotificationSound(ctx, 1, func(_ context.Context, _ string) adb.Result {
close(started)
// Simulate adb cleanup still waiting on its pipes when the deadline expires.
<-release
return adb.Result{Out: "null"}
})
}()
select {
case <-started:
case <-done:
t.Fatal("returned before calling adb")
}
select {
case <-done:
case <-time.After(2 * time.Second):
t.Fatal("waited for adb cleanup past the deadline")
}
if m.notificationSoundDone(1) || len(*warnings) != 1 || !strings.Contains((*warnings)[0], context.DeadlineExceeded.Error()) {
t.Fatalf("after timeout: marker %v, warnings %q", m.notificationSoundDone(1), *warnings)
}
})

t.Run("metadata lock", func(t *testing.T) {
m, _ := newSoundTestManager(t)
lock, ok, err := win.TryLock(m.Root.MetadataPath() + ".lock")
if err != nil || !ok {
t.Fatalf("lock metadata: held %v, error %v", ok, err)
}
defer lock.Unlock()
guest := &fakeSoundGuest{out: "null"}
ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)
defer cancel()
start := time.Now()
muted, err := m.tryMuteNotificationSound(ctx, 1, guest.run)
if elapsed := time.Since(start); elapsed > 2*time.Second {
t.Fatalf("metadata lock blocked the step for %s", elapsed)
}
if guest.calls() != 1 || !muted || m.notificationSoundDone(1) || err != context.DeadlineExceeded {
t.Fatalf("after timeout: commands %d, marker %v, error %v", guest.calls(), m.notificationSoundDone(1), err)
}
})
}

func TestMuteNotificationSoundSkipsUnreadableMetadata(t *testing.T) {
m, warnings := newSoundTestManager(t)
guest := &fakeSoundGuest{out: "null"}
path := m.Root.MetadataPath()
partial := `{"instances":{"1":{"initialized":true,`
if err := os.WriteFile(path, []byte(partial), 0o644); err != nil {
t.Fatal(err)
}
m.muteNotificationSound(context.Background(), 1, guest.run)
got, err := os.ReadFile(path)
if err != nil || string(got) != partial || guest.calls() != 0 || len(*warnings) != 1 {
t.Fatalf("after read failure: file %q, error %v, commands %d, warnings %q", got, err, guest.calls(), *warnings)
}
}

func TestMuteNotificationSoundDeleteFailure(t *testing.T) {
m, warnings := newSoundTestManager(t)
m.muteNotificationSound(context.Background(), 1, func(_ context.Context, command string) adb.Result {
// Model a failed delete when get alone would return "null" and exit successfully.
if command == "settings delete system notification_sound && settings get system notification_sound" {
return adb.Result{Code: 1, Out: "delete failed"}
}
return adb.Result{Out: "null"}
})
if m.notificationSoundDone(1) || len(*warnings) != 1 || !strings.Contains((*warnings)[0], "delete failed") {
t.Fatalf("after delete failure: marker %v, warnings %q", m.notificationSoundDone(1), *warnings)
}
}
3 changes: 3 additions & 0 deletions internal/i18n/locales/en/emu.json
Original file line number Diff line number Diff line change
Expand Up @@ -330,6 +330,7 @@
"实例 %d 密集读写加速: 守护已起(pid %s,数据盘 %s,忙等上限 %s)": "Instance %d intensive I/O acceleration: daemon started (pid %s, data disk %s, busy-wait limit %s)",
"实例 %d 密集读写加速: 客体等读写时自己忙等(acpi_idle),不起忙等守护": "Instance %d intensive I/O acceleration: the guest busy-waits for I/O itself (acpi_idle); not starting the busy-wait daemon",
"实例 %d 密集读写加速没起来: %s": "Instance %d: intensive I/O acceleration did not start: %s",
"实例 %d 已关掉通知提示音(通知照常显示)": "Instance %d: notification sound turned off (notifications still show)",
"实例 %d 已在本机生成%s补丁版(sha256 %s): %s": "Instance %d: generated the patched %s locally (sha256 %s): %s",
"实例 %d 已在运行(pid %d),不重新开机": "Instance %d is already running (pid %d); not starting again",
"实例 %d 已就绪(共 %.1f 秒)": "Instance %d is ready (%.1f s in total)",
Expand Down Expand Up @@ -405,6 +406,7 @@
"实例 %d 正在挂驱动补丁,稍后再装": "Instance %d is mounting the driver patch; install later",
"实例 %d 正由另一次启动开机或做开机后设置": "Instance %d is being started or finishing post-boot setup by another start",
"实例 %d 没%s好 Google Play 商店(%s)": "Instance %d: Google Play Store %s did not finish (%s)",
"实例 %d 没关掉通知提示音(下次开机重试): %s": "Instance %d: could not turn off the notification sound (will retry at the next boot): %s",
"实例 %d 没取到 GSF ID(%s)": "Instance %d: could not get the GSF ID (%s)",
"实例 %d 没开机": "Instance %d is not started",
"实例 %d 没放上执行桥的开机标记: %v": "Instance %d: could not place the execution bridge boot marker: %v",
Expand Down Expand Up @@ -493,6 +495,7 @@
"实例 %d 这次开机后的设置做完了": "Instance %d: post-boot setup of this start is done",
"实例 %d 这次开机后的设置还没做完(拉起它的那次启动被取消或超时了),这次接着做完": "Instance %d: post-boot setup of this start was not finished (the start that began it was cancelled or timed out); finishing it now",
"实例 %d 这次开机的客体库补丁还没做,前台是 %s、没有应用在用,也没有安装在进行,接着挂(会重启 zygote)": "Instance %d: the guest library patch of this start is not done yet; the foreground is %s, no app is in use and no install is in progress, so mounting now (zygote will restart)",
"实例 %d 通知提示音已关,但结果没写进 mas-avd.json,下次开机再关一次: %v": "Instance %d: notification sound is off, but the result was not written to mas-avd.json; turning it off once more at the next boot: %v",
"实例 %d 里建不了 %s:%s": "Instance %d: cannot create %s: %s",
"实例 %d 里没有按应用走代理的客体程序": "Instance %d has no guest program for per-app proxy",
"实例 %d 里的 %s 和这个 modavd 带的不一样,不以 root 运行它": "Instance %d: %s differs from the one this modavd carries; not running it as root",
Expand Down
Loading