From df2e3038b2bbd14f88ef37cba1fe5e0a27156e2e Mon Sep 17 00:00:00 2001 From: qiyinxi Date: Tue, 17 Nov 2026 15:16:23 +0100 Subject: [PATCH 1/2] emu: optional sound and the screenshot folder - Instance setting "sound" (mas-avd.json instances..sound, off by default). Off boots exactly as before; on leaves out -audio none and -feature -VirtioSndCard, windowed and headless, and writes hw.audioInput / hw.audioOutput yes (no when off). Settable from the settings page, `modavd set --sound on|off`, the API (PATCH sound) and MCP update_instance; shown as config.sound and in `info`. - Every boot passes -save-path \ModAVD (FOLDERID_Pictures on Windows, ~/Pictures elsewhere), created first; left out when the folder is unknown or cannot be made. Refs ModAVD/ModAVD#226 Refs ModAVD/ModAVD#231 --- README.en.md | 2 +- README.md | 2 +- changelog.d/226-sound.feat.md | 1 + internal/avd/avd.go | 42 ++++++++++++++++++-- internal/avd/avd_test.go | 58 +++++++++++++++++++++++++++ internal/cli/commands.go | 18 +++++++-- internal/cli/format.go | 12 ++++++ internal/cli/sound_test.go | 55 ++++++++++++++++++++++++++ internal/emu/crud.go | 8 ++-- internal/emu/launch.go | 45 ++++++++++++++++----- internal/emu/launch_test.go | 59 ++++++++++++++++++++++++++-- internal/emu/portplan_test.go | 67 ++++++++++++++++++++++++++++++++ internal/emu/savepath.go | 31 +++++++++++++++ internal/emu/savepath_other.go | 22 +++++++++++ internal/emu/savepath_test.go | 62 +++++++++++++++++++++++++++++ internal/emu/savepath_windows.go | 38 ++++++++++++++++++ internal/emu/status.go | 1 + internal/emu/syncio_test.go | 4 +- internal/emu/types.go | 4 ++ internal/mcp/mcp_test.go | 15 +++++++ internal/mcp/tools.go | 11 ++++-- internal/ui/API.en.md | 2 +- internal/ui/API.md | 2 +- internal/ui/handlers.go | 7 ++-- internal/ui/web/dev/mock.js | 4 +- internal/ui/web/js/forms.js | 7 +++- scripts/test_create_cancel.mjs | 18 ++++++++- 27 files changed, 555 insertions(+), 42 deletions(-) create mode 100644 changelog.d/226-sound.feat.md create mode 100644 internal/cli/sound_test.go create mode 100644 internal/emu/savepath.go create mode 100644 internal/emu/savepath_other.go create mode 100644 internal/emu/savepath_test.go create mode 100644 internal/emu/savepath_windows.go diff --git a/README.en.md b/README.en.md index c57c6bb2..e97d6b7c 100644 --- a/README.en.md +++ b/README.en.md @@ -63,7 +63,7 @@ modavd [--root ] [--json] [--quiet] [--verbose] [args] | `list` | All instances and their status | | `info ` / `status ` | Details of one instance / its status | | `create [--index N] [--title T] [--memory 6G] [--cpu N] [--data-gb auto\|N] [--fps 1-60] [--resolution 1080\|720] [--no-bridge] [--timeout 1200]`, `create --resume N` | Create an instance (automatic data disk by default, see below), then start it once in the background, headless, to finish initialization, and shut it down (see below). The arm64 execution bridge is included by default; `--no-bridge` records that this instance does not want the bridge, so it is not installed on later starts either. New instances never get the Google Play Store; add it afterwards with `playstore install`. `--resume N` redoes the initialization of an instance whose creation failed | -| `set [--title T] [--memory M] [--cpu N] [--fps F] [--resolution 1080\|720] [--data-gb auto\|N] [--diagnostics on\|off] [--boss-key combination\|none]` | Change settings. Diagnostics and the boss key apply immediately; other settings take effect at the next start. `--data-gb auto` makes the data disk automatic, `--data-gb N` gives it a fixed size (see below); the size can only be increased, and game data is untouched: the emulator (from 0.36) grows the disk image at start and grows the file system online after boot. A disk created before 0.36 at 16 GB or smaller can only be grown to just below the next backup group (a 16 GB disk to about 30 GB). `--boss-key` is this instance's boss key (see the ModAVD.exe manager section), for example `Ctrl+Alt+Shift+1`; `none` means no boss key; Windows only. | +| `set [--title T] [--memory M] [--cpu N] [--fps F] [--resolution 1080\|720] [--data-gb auto\|N] [--diagnostics on\|off] [--sound on\|off] [--boss-key combination\|none]` | Change settings. Diagnostics and the boss key apply immediately; other settings take effect at the next start. `--data-gb auto` makes the data disk automatic, `--data-gb N` gives it a fixed size (see below); the size can only be increased, and game data is untouched: the emulator (from 0.36) grows the disk image at start and grows the file system online after boot. A disk created before 0.36 at 16 GB or smaller can only be grown to just below the next backup group (a 16 GB disk to about 30 GB). `--sound on` gives this instance sound from its next start (windowed and headless, at some extra CPU); the default `off` boots without a sound card; stored as `instances..sound` in `mas-avd.json`. `--boss-key` is this instance's boss key (see the ModAVD.exe manager section), for example `Ctrl+Alt+Shift+1`; `none` means no boss key; Windows only. | | `proxy [on\|off\|test] [--server URL\|auto] [--add PKG] [--remove PKG] [--apps PKG]` | Per-app proxy: the listed apps go through a proxy, the others direct (see below) | | `delete --yes` | Delete a stopped instance, together with its game data | | `start [--window \| --headless] [--timeout 300] [--no-bridge]` | Start (headless by default, with the window for `--window`), wait until boot finishes and the post-boot setup is done, and before returning confirm that files can be written to `/sdcard` (normally it is ready long before this; it waits up to 60 more seconds and only warns at the deadline). If the instance is shutting down (for example, right after a click on the emulator window's ×), it first waits for the shutdown to finish (up to 30 seconds) and then starts it. If the instance has no execution bridge yet, install it afterward; `--no-bridge` skips that this time. The install takes a cold boot or two: with `--window`, the boots that only prepare it are headless, and after a normal shutdown the last boot has the window (when the instance has no boot marker yet, so the bridge is surely to be installed, the first boot is headless too; with the marker there, whether the bridge is installed is only known once it runs, so the first boot has the window). No switch while it runs: if the instance is already running and `--window` / `--headless` asks for the other way, it fails (exit code 5) without taking it over or restarting it; to switch, `stop` and then `start`. With neither, it is taken over as it runs | diff --git a/README.md b/README.md index 2b328fc1..859d57ec 100644 --- a/README.md +++ b/README.md @@ -63,7 +63,7 @@ modavd [--root <目录>] [--json] [--quiet] [--verbose] <命令> [参数] | `list` | 全部实例和状态 | | `info ` / `status ` | 一台实例的详细信息 / 状态 | | `create [--index N] [--title T] [--memory 6G] [--cpu N] [--data-gb auto\|N] [--fps 1-60] [--resolution 1080\|720] [--no-bridge] [--timeout 1200]`、`create --resume N` | 新建(数据盘默认自动扩盘,见下),并在后台无头开机一次把初始化做完再关机(见下)。默认带 arm64 执行桥;`--no-bridge` 记下这台不要桥,以后开机也不装。新建的实例不带 Google Play 商店,要的话建好后用 `playstore install`。`--resume N` 重做新建失败的那台的初始化 | -| `set [--title T] [--memory M] [--cpu N] [--fps F] [--resolution 1080\|720] [--data-gb auto\|N] [--diagnostics on\|off] [--boss-key 组合\|none]` | 修改;诊断模式和老板键立即生效,其余设置下次开机生效。`--data-gb auto` 改成自动扩盘,`--data-gb N` 改成指定大小(见下);大小只能改大,游戏数据不动:模拟器(0.36 起)开机时扩磁盘镜像,开机后在线扩文件系统。0.36 之前按 16 GB 及以下建的盘只能扩到下一个备份组之前(16 GB 约到 30 GB)。`--boss-key` 是这台的老板键(见「管理器 ModAVD.exe」一节),比如 `Ctrl+Alt+Shift+1`,`none` 是不要,只有 Windows。 | +| `set [--title T] [--memory M] [--cpu N] [--fps F] [--resolution 1080\|720] [--data-gb auto\|N] [--diagnostics on\|off] [--sound on\|off] [--boss-key 组合\|none]` | 修改;诊断模式和老板键立即生效,其余设置下次开机生效。`--data-gb auto` 改成自动扩盘,`--data-gb N` 改成指定大小(见下);大小只能改大,游戏数据不动:模拟器(0.36 起)开机时扩磁盘镜像,开机后在线扩文件系统。0.36 之前按 16 GB 及以下建的盘只能扩到下一个备份组之前(16 GB 约到 30 GB)。`--sound on` 让这台下次开机起有声音(带窗口和无头都是,会多占一些 CPU),默认 `off` 不带声卡;记在 `mas-avd.json` 的 `instances..sound`。`--boss-key` 是这台的老板键(见「管理器 ModAVD.exe」一节),比如 `Ctrl+Alt+Shift+1`,`none` 是不要,只有 Windows。 | | `proxy [on\|off\|test] [--server URL\|auto] [--add 包名] [--remove 包名] [--apps 包名]` | 按应用走代理:名单里的应用走代理,其余直连(见下) | | `delete --yes` | 删除已关机的实例,连同游戏数据 | | `start [--window \| --headless] [--timeout 300] [--no-bridge]` | 开机(默认无头,`--window` 带窗口),等开完并做完开机后的设置,返回前确认 `/sdcard` 能写进文件(一般这时早已就绪;最多再等 60 秒,到点只警告);实例正在关机时(比如刚点了模拟器窗口的 ×)先等它关完(最多 30 秒)再开机;实例还没有执行桥时接着装上,`--no-bridge` 这次不装;装桥要冷启动一两次,带 `--window` 时这几次准备用的开机都无头,装好后正常关机,最后一次才带窗口开机(实例还没有开机标记、一定要装桥时,第一次开机就无头;有标记的要开起来才知道装没装,第一次照样带窗口)。运行中不换方式:实例已经在运行时,给了 `--window` / `--headless` 而它不是这种方式,就报错(退出码 5),不接管也不重启,要换先 `stop` 再 `start`;两个都不给就照原样接管 | diff --git a/changelog.d/226-sound.feat.md b/changelog.d/226-sound.feat.md new file mode 100644 index 00000000..58e8c3f7 --- /dev/null +++ b/changelog.d/226-sound.feat.md @@ -0,0 +1 @@ +实例设置里可以打开声音,开了以后模拟器有声音 (ModAVD/ModAVD#226) diff --git a/internal/avd/avd.go b/internal/avd/avd.go index 6efccb95..fca57364 100644 --- a/internal/avd/avd.go +++ b/internal/avd/avd.go @@ -51,6 +51,10 @@ const ( DataDiskModeKey = "dataDiskMode" DataDiskAuto = "auto" DataDiskManual = "manual" + // SoundKey is instances..sound in mas-avd.json: true gives the instance a sound card from its next boot + // (ModAVD/ModAVD#226); anything else (absent: every instance before it) keeps it without one, the default. The + // boot reads only this key; config.ini's hw.audioInput / hw.audioOutput are written along with it (SoundConfig). + SoundKey = "sound" // New instances default to 1080p. Existing instances are identified by their dimensions. DefaultResolution = 1080 TargetAPI = "android-34" @@ -61,7 +65,8 @@ const ( // ConfigTemplate is config.ini of a new instance before the per-instance keys (AUTO-MAS _CONFIG_TEMPLATE, same // order). Taken from the tuned mas_p0: landscape, host GPU, no device frame, no sound card keys (the real switch is -// -feature -VirtioSndCard), hw.mainKeys=yes (no on-screen navigation bar; ModAVD #1). +// -feature -VirtioSndCard; the instance's sound switch, SoundKey, writes them yes), hw.mainKeys=yes (no on-screen +// navigation bar; ModAVD #1). var ConfigTemplate = [][2]string{ {"PlayStore.enabled", "no"}, {"abi.type", "x86_64"}, @@ -331,6 +336,22 @@ func DataDiskAutoMeta(meta *jsonord.Obj) bool { return s != DataDiskManual } +// SoundMeta: the instance with metadata meta boots with a sound card (SoundKey is true; nil metadata, a missing key or +// any other value is off). +func SoundMeta(meta *jsonord.Obj) bool { + on, ok := meta.Get(SoundKey).BoolVal() + return ok && on +} + +// SoundConfig is config.ini's sound keys for the switch: hw.audioInput and hw.audioOutput, both yes or both no. +func SoundConfig(on bool) [][2]string { + v := "no" + if on { + v = "yes" + } + return [][2]string{{"hw.audioInput", v}, {"hw.audioOutput", v}} +} + // Display returns the size and density the instance will boot with (after DisplayChanges). func (in *Instance) Display() (width, height, dpi int) { ch := DisplayChanges(in.Config) @@ -777,13 +798,17 @@ type UpdateOptions struct { // DataDiskAuto makes the data disk automatic (dataDiskMode auto) and raises it to AutoDataPartitionGB unless it is // larger already. Not together with DataPartitionGB. DataDiskAuto bool + // Sound turns the instance's sound card on or off from its next boot: instances..sound (SoundKey) and + // config.ini's hw.audioInput / hw.audioOutput (SoundConfig). + Sound *bool } // Update writes the changed keys like AUTO-MAS write_instance_settings: hw.ramSize=M and hw.cpu.ncore always // (current values when not changed), hw.lcd.vsync only when FPS is given, avd.ini.displayname when Title is given, -// disk.dataPartition.size when DataPartitionGB is given, and instances..memoryMb always. Validates first -// (memory / cpu / fps steps). Returns the applied changes by option name ("title", "memory_mb", "cpu", "fps", -// "data_partition_gb"). Takes effect at the next boot. +// disk.dataPartition.size when DataPartitionGB is given, hw.audioInput / hw.audioOutput and instances..sound when +// Sound is given, and instances..memoryMb always. Validates first (memory / cpu / fps steps). Returns the applied +// changes by option name ("title", "memory_mb", "cpu", "fps", "data_partition_gb", "sound"). Takes effect at the next +// boot. // // As in AUTO-MAS the unchanged values are validated too: memory is MemoryFor (old instances get 6144 written), cores // hw.cpu.ncore (DefaultCPU when unreadable), and the instance's data partition must still be within range unless a @@ -874,6 +899,9 @@ func Update(r *root.Root, i int, opt UpdateOptions) (map[string]any, error) { if opt.DataPartitionGB != nil || opt.DataDiskAuto { changes = append(changes, [2]string{"disk.dataPartition.size", strconv.Itoa(data) + "G"}) } + if opt.Sound != nil { + changes = append(changes, SoundConfig(*opt.Sound)...) + } title := "" if opt.Title != nil { title = *opt.Title @@ -893,6 +921,9 @@ func Update(r *root.Root, i int, opt UpdateOptions) (map[string]any, error) { case opt.DataPartitionGB != nil: metaChanges[DataDiskModeKey] = jsonord.NewString(DataDiskManual) } + if opt.Sound != nil { + metaChanges[SoundKey] = jsonord.NewBool(*opt.Sound) + } if err := r.UpdateInstanceMeta(i, metaChanges); err != nil { return nil, err } @@ -919,6 +950,9 @@ func Update(r *root.Root, i int, opt UpdateOptions) (map[string]any, error) { applied["data_disk_mode"] = DataDiskAuto } } + if opt.Sound != nil { + applied["sound"] = *opt.Sound + } return applied, nil } diff --git a/internal/avd/avd_test.go b/internal/avd/avd_test.go index 2d976694..e9afb4b1 100644 --- a/internal/avd/avd_test.go +++ b/internal/avd/avd_test.go @@ -18,6 +18,7 @@ import ( "testing" "modavd/internal/errs" + "modavd/internal/jsonord" "modavd/internal/root" "modavd/internal/testutil" ) @@ -994,6 +995,63 @@ func TestUpdateTitleAndApplied(t *testing.T) { } } +// TestUpdateSound: the sound switch (ModAVD/ModAVD#226) is off for a new instance, and Update writes it to +// instances..sound and config.ini's hw.audioInput / hw.audioOutput in place, nothing else of config.ini changing. +func TestUpdateSound(t *testing.T) { + r := newRoot(t) + if _, err := Create(r, 0, CreateOptions{MemoryMB: 4096, CPU: 4, DataPartitionGB: 64, FPS: 60}); err != nil { + t.Fatal(err) + } + if SoundMeta(r.InstanceMeta(0)) { + t.Fatal("a new instance has sound") + } + before := string(readFile(t, ConfigPath(r, 0))) + if !strings.Contains(before, "hw.audioInput=no\r\n") || !strings.Contains(before, "hw.audioOutput=no\r\n") { + t.Fatalf("new config.ini: %q", before) + } + for _, on := range []bool{true, false} { + applied, err := Update(r, 0, UpdateOptions{Sound: &on}) + if err != nil { + t.Fatal(err) + } + if applied["sound"] != on || len(applied) != 1 { + t.Errorf("sound %v: applied %v", on, applied) + } + if SoundMeta(r.InstanceMeta(0)) != on { + t.Errorf("sound %v: instances.0.sound = %v", on, SoundMeta(r.InstanceMeta(0))) + } + want := before + if on { + want = strings.NewReplacer("hw.audioInput=no\r\n", "hw.audioInput=yes\r\n", + "hw.audioOutput=no\r\n", "hw.audioOutput=yes\r\n").Replace(before) + } + if got := string(readFile(t, ConfigPath(r, 0))); got != want { + t.Errorf("sound %v: config\n got %q\nwant %q", on, got, want) + } + } +} + +// TestSoundMeta: only a JSON true turns sound on. +func TestSoundMeta(t *testing.T) { + if SoundMeta(nil) { + t.Error("nil metadata") + } + for text, want := range map[string]bool{`{}`: false, `{"sound":true}`: true, `{"sound":false}`: false, + `{"sound":"true"}`: false, `{"sound":1}`: false} { + v, err := jsonord.Parse([]byte(text)) + if err != nil { + t.Fatal(err) + } + if got := SoundMeta(v.Obj()); got != want { + t.Errorf("%s: SoundMeta = %v, want %v", text, got, want) + } + } + if fmt.Sprint(SoundConfig(true)) != "[[hw.audioInput yes] [hw.audioOutput yes]]" || + fmt.Sprint(SoundConfig(false)) != "[[hw.audioInput no] [hw.audioOutput no]]" { + t.Errorf("SoundConfig: %v %v", SoundConfig(true), SoundConfig(false)) + } +} + func TestUpdateDataPartition(t *testing.T) { r := newRoot(t) if _, err := Create(r, 0, CreateOptions{MemoryMB: 4096, CPU: 4, DataPartitionGB: 64, FPS: 60}); err != nil { diff --git a/internal/cli/commands.go b/internal/cli/commands.go index 66ceb8d2..6981f003 100644 --- a/internal/cli/commands.go +++ b/internal/cli/commands.go @@ -94,6 +94,7 @@ var ( optLanguage = flagSpec{"language", kindString, "host|preserve|语言", "Windows:host 按宿主界面语言设置一次,preserve 保持安卓语言,或指定 zh-CN、en-US 等语言"} optTimeZone = flagSpec{"timezone", kindString, "host|preserve|IANA", "Windows:host 每次冷启动跟随宿主,preserve 沿用原行为,或指定 Asia/Shanghai、Etc/UTC 等 IANA 时区"} optDiagnostics = flagSpec{"diagnostics", kindString, "on|off", "诊断模式:即时增加日志保留;off 立即删回平常规则"} + optSound = flagSpec{"sound", kindString, "on|off", "声音:on 下次开机起带声卡、电脑出声(会多占一些 CPU),off 照旧不带(默认)"} optBossKey = flagSpec{"boss-key", kindString, "组合", "老板键,比如 Ctrl+Alt+Shift+1(Ctrl、Alt、Shift 至少带一个,不收 Win);none 是不要(只有 Windows)"} optYes = flagSpec{"yes", kindBool, "", "确认删除(连同游戏数据)"} optWindow = flagSpec{"window", kindBool, "", "带窗口开机(默认无头);实例已经无头运行时报错,不接管"} @@ -211,13 +212,14 @@ func init() { run: runCreate, human: humanOf(formatCreate), }, { - name: "set", args: " [--title T] [--memory M] [--cpu N] [--fps F] [--resolution 1080|720] [--data-gb auto|N] [--language host|preserve|语言] [--timezone host|preserve|IANA] [--diagnostics on|off] [--boss-key 组合|none]", + name: "set", args: " [--title T] [--memory M] [--cpu N] [--fps F] [--resolution 1080|720] [--data-gb auto|N] [--language host|preserve|语言] [--timezone host|preserve|IANA] [--diagnostics on|off] [--sound on|off] [--boss-key 组合|none]", summary: "修改实例设置、诊断模式和老板键", details: "至少给一个选项。诊断模式和老板键立即生效;其它改动下次开机生效。诊断模式最多多用约 4 GiB 磁盘和 48 MiB 客体内存,日志可能含账号信息,只存本机;关闭立即删回平常保留规则。" + dataDiskHelp + "数据盘只能改大,游戏数据不动:下次开机时模拟器(0.36 起)扩大磁盘镜像,开机后再在线扩大文件系统。" + + "--sound on 让这台下次开机起有声音(带窗口和无头都是),会多占一些 CPU;默认 off。" + "--boss-key 是这台的老板键:管理器开着时(窗口关了、留在托盘也算),按一下藏起这台带窗口运行的模拟器窗口,再按一下叫回来;" + "几台设成同一个键就一起藏、一起显示。没设过时编号 0–9 默认 Ctrl+Alt+Shift+编号,超过 9 没有;none 是不要。立即生效,只有 Windows。", - flags: []flagSpec{optTitle, optMemory, optCPU, optFPS, optResolution, optDataGB, optLanguage, optTimeZone, optDiagnostics, optBossKey}, + flags: []flagSpec{optTitle, optMemory, optCPU, optFPS, optResolution, optDataGB, optLanguage, optTimeZone, optDiagnostics, optSound, optBossKey}, posNames: []string{"实例编号"}, minPos: 1, maxPos: 1, final: true, run: runSet, human: humanOf(formatUpdate), @@ -658,13 +660,21 @@ func buildUpdateRequest(inv *invocation) (emu.UpdateRequest, error) { enabled := value == "on" req.Diagnostics = &enabled } + if inv.isSet("sound") { + value := strings.ToLower(inv.strOpt("sound")) + if value != "on" && value != "off" { + return req, errs.New(errs.InvalidArgument, "--sound 只能是 on 或 off") + } + on := value == "on" + req.Sound = &on + } if inv.isSet("boss-key") { k := inv.strOpt("boss-key") req.BossKey = &k } if req.Title == nil && req.MemoryMB == nil && req.CPU == nil && req.FPS == nil && req.Resolution == nil && req.DataPartitionGB == nil && - !req.DataDiskAuto && req.Diagnostics == nil && req.BossKey == nil && req.Language == nil && req.TimeZone == nil { - return req, errs.New(errs.Usage, "没有要改的内容:至少给 --title、--memory、--cpu、--fps、--resolution、--data-gb、--language、--timezone、--diagnostics、--boss-key 中的一个"). + !req.DataDiskAuto && req.Diagnostics == nil && req.Sound == nil && req.BossKey == nil && req.Language == nil && req.TimeZone == nil { + return req, errs.New(errs.Usage, "没有要改的内容:至少给 --title、--memory、--cpu、--fps、--resolution、--data-gb、--language、--timezone、--diagnostics、--sound、--boss-key 中的一个"). WithAdvice(findCommand("set").usageAdvice()) } return req, nil diff --git a/internal/cli/format.go b/internal/cli/format.go index 85809acf..c69089dd 100644 --- a/internal/cli/format.go +++ b/internal/cli/format.go @@ -270,6 +270,7 @@ func formatInfo(w io.Writer, in *emu.InstanceInfo) { kv("内存", fmtMemory(cfg.MemoryMB)) kv("核数", intOrDash(cfg.CPU)) kv("帧率", intOrDash(cfg.FPS)) + kv("声音", onOff(cfg.Sound)) kv("数据盘", dataDiskText(cfg)+","+dataSpaceSummary(in.DataSpace)) if in.DataSpace.Message != "" { kv("数据盘提示", dataSpaceNote(in.DataSpace)) @@ -308,6 +309,14 @@ func formatInfo(w io.Writer, in *emu.InstanceInfo) { kv("路径", in.Path) } +// onOff is a switch for people: "开" / "关". +func onOff(on bool) string { + if on { + return "开" + } + return "关" +} + // bossKeyText is a boss key for people: "无" when there is none. func bossKeyText(key string) string { if key == "" { @@ -415,6 +424,9 @@ func appliedParts(applied map[string]any) []string { } else { parts = append(parts, "诊断模式 关") } + case "sound": + on, _ := v.(bool) + parts = append(parts, "声音 "+onOff(on)) case "boss_key": key, _ := v.(string) parts = append(parts, "老板键 "+bossKeyText(key)) diff --git a/internal/cli/sound_test.go b/internal/cli/sound_test.go new file mode 100644 index 00000000..4d4d99b1 --- /dev/null +++ b/internal/cli/sound_test.go @@ -0,0 +1,55 @@ +//go:build windows + +package cli + +import ( + "strings" + "testing" + + "modavd/internal/emu" +) + +// TestSoundSet: set --sound on|off reaches the manager as Sound alone and comes back in JSON and for people +// (ModAVD/ModAVD#226); info shows the switch. +func TestSoundSet(t *testing.T) { + for _, value := range []string{"on", "off", "ON"} { + h := newHarness() + on := strings.EqualFold(value, "on") + h.fake.update = func(i int, req emu.UpdateRequest) (*emu.UpdateResult, error) { + if i != 3 || req.Sound == nil || *req.Sound != on || req.MemoryMB != nil || req.CPU != nil || req.Diagnostics != nil { + t.Fatalf("request = %d/%+v", i, req) + } + in := sampleInstance(i) + in.Config.Sound = on + return &emu.UpdateResult{Instance: in, Applied: map[string]any{"sound": on}}, nil + } + result := h.run(t, nil, "set", "3", "--sound", value, "--json") + if result.code != 0 { + t.Fatalf("%s: CLI = %d/%s", value, result.code, result.stdout) + } + data := envelope(t, result.stdout)["data"].(map[string]any) + if data["instance"].(map[string]any)["config"].(map[string]any)["sound"] != on || data["applied"].(map[string]any)["sound"] != on { + t.Fatalf("%s: JSON = %s", value, result.stdout) + } + want := "声音 关" + if on { + want = "声音 开" + } + if human := h.run(t, nil, "set", "3", "--sound", value); human.code != 0 || !strings.Contains(human.stdout, want) { + t.Fatalf("%s: human = %+v", value, human) + } + } + for _, value := range []string{"true", "1", "maybe", ""} { + h := newHarness() + if result := h.run(t, nil, "set", "3", "--sound", value, "--json"); result.code != 2 || len(h.fake.callList()) != 0 { + t.Fatalf("%q = %+v / %q", value, result, h.fake.callList()) + } + } + h := newHarness() + in := sampleInstance(3) + in.Config.Sound = true + h.fake.info = func(int) (*emu.InstanceInfo, error) { return &in, nil } + if result := h.run(t, nil, "info", "3"); !strings.Contains(result.stdout, "声音:开") { + t.Fatalf("info: %s", result.stdout) + } +} diff --git a/internal/emu/crud.go b/internal/emu/crud.go index 8856cbd4..e7255b4c 100644 --- a/internal/emu/crud.go +++ b/internal/emu/crud.go @@ -208,8 +208,8 @@ func (m *Manager) resumeCreate(ctx context.Context, req CreateRequest) (*Instanc return m.setupNew(ctx, i, in.Config, req, lock) } -// Update changes title / memory / cpu / fps / data partition size (next boot), the data partition's automatic growth -// and diagnostics (at once). +// Update changes title / memory / cpu / fps / data partition size / sound (next boot), the data partition's automatic +// growth and diagnostics (at once). func (m *Manager) Update(ctx context.Context, i int, req UpdateRequest) (*UpdateResult, error) { if err := requireLifecycle(); err != nil { return nil, err @@ -238,10 +238,10 @@ func (m *Manager) Update(ctx context.Context, i int, req UpdateRequest) (*Update } } if req.Title != nil || req.MemoryMB != nil || req.CPU != nil || req.FPS != nil || req.Resolution != nil || req.DataPartitionGB != nil || - req.DataDiskAuto { + req.DataDiskAuto || req.Sound != nil { applied, err = avd.Update(m.Root, i, avd.UpdateOptions{ Title: req.Title, MemoryMB: req.MemoryMB, CPU: req.CPU, FPS: req.FPS, Resolution: req.Resolution, DataPartitionGB: req.DataPartitionGB, - DataDiskAuto: req.DataDiskAuto, + DataDiskAuto: req.DataDiskAuto, Sound: req.Sound, }) if err != nil { return nil, err diff --git a/internal/emu/launch.go b/internal/emu/launch.go index 9479290a..caeede5f 100644 --- a/internal/emu/launch.go +++ b/internal/emu/launch.go @@ -27,7 +27,11 @@ const adbServerStartTimeout = 20 * time.Second // - cold boot (-no-snapshot), like MAS does with LDPlayer / MuMu every round; // - the boot animation is turned off only when headless: a window has something to show meanwhile; // - -audio none and -feature -VirtioSndCard: no host sound and no guest sound card (the image's virtio-snd ignores -// hw.audio*); qemu CPU on the 1999 main screen 147% -> 104%; +// hw.audio*); qemu CPU on the 1999 main screen 147% -> 104%. Both are left out only for an instance whose sound +// switch is on (o.sound, avd.SoundMeta; ModAVD/ModAVD#226), headless or not; the emulator shows its volume button +// exactly when it was not started with -audio none; +// - -save-path: the folder the emulator's screenshot button saves to (o.savePath, screenshotSavePath; +// ModAVD/ModAVD#231); left out when empty, and the emulator keeps its own default; // - -memory: the instance's own setting (avd.MemoryFor), hw.ramSize is left alone; // - the Windows balloon (free page reporting) is on; QuickbootFileBacked has to be off for it, or the guest RAM is // a file mapping whose pages qemu cannot drop; @@ -45,7 +49,7 @@ const adbServerStartTimeout = 20 * time.Second // On Windows the guest kernel also gets tsc=nowatchdog (tscNoWatchdogArgs). // // The window is not an instance option: it is decided at boot by whoever starts it. -func buildLaunchArgs(avdName string, console, memoryMB int, headless bool, qemuExtra ...string) []string { +func buildLaunchArgs(avdName string, console, memoryMB int, o launchOptions, qemuExtra ...string) []string { args := []string{ "-avd", avdName, "-no-snapshot", @@ -53,10 +57,15 @@ func buildLaunchArgs(avdName string, console, memoryMB int, headless bool, qemuE "-ports", fmt.Sprintf("%d,%d", console, console+1), "-grpc", strconv.Itoa(console + 2), "-grpc-use-token", - "-audio", "none", - "-memory", strconv.Itoa(memoryMB), } - if headless { + if !o.sound { + args = append(args, "-audio", "none") + } + args = append(args, "-memory", strconv.Itoa(memoryMB)) + if o.savePath != "" { + args = append(args, "-save-path", o.savePath) + } + if o.headless { args = append(args, "-no-window", "-no-boot-anim") } if p := root.CurrentPlatform(); p.MirrorOS == "macos" && p.GuestABI == "arm64-v8a" { @@ -64,9 +73,11 @@ func buildLaunchArgs(avdName string, console, memoryMB int, headless bool, qemuE // Silicon. -gpu host alone selects the older host GLES translation path. args = append(args, "-feature", "GuestAngle,Vulkan") } + args = append(args, "-feature", "-QuickbootFileBacked") + if !o.sound { + args = append(args, "-feature", "-VirtioSndCard") + } args = append(args, - "-feature", "-QuickbootFileBacked", - "-feature", "-VirtioSndCard", "-feature", "VulkanBatchedDescriptorSetUpdate", "-feature", "-WiFiPacketStream", "-feature", "-BluetoothEmulation", @@ -86,6 +97,14 @@ func buildLaunchArgs(avdName string, console, memoryMB int, headless bool, qemuE return append(args, qemuExtra...) } +// launchOptions are the per-boot choices of buildLaunchArgs. The zero value is a windowed boot without sound or +// screenshot folder. +type launchOptions struct { + headless bool // no window, no boot animation + sound bool // the instance's sound switch (avd.SoundMeta): host sound and a guest sound card + savePath string // -save-path; "" leaves it out +} + // tscNoWatchdogArgs keeps the guest on the TSC clocksource for the whole run (ModAVD/ModAVD#110). WHPX gives the // guest no kvm-clock, so when the kernel's clocksource watchdog drops the TSC the only clock left is the HPET, which // QEMU emulates: every clock read exits to the host. The watchdog compares the TSC against that HPET and gives up on @@ -178,7 +197,9 @@ func (m *Manager) launchPlanFor(ctx context.Context, inst *avd.Instance, memoryM } headless := !window - args := buildLaunchArgs(inst.Name, port, memoryMB, headless, m.syncIOQemuArgs(inst)...) + sound := avd.SoundMeta(m.Root.InstanceMeta(i)) + args := buildLaunchArgs(inst.Name, port, memoryMB, + launchOptions{headless: headless, sound: sound, savePath: m.screenshotSavePath()}, m.syncIOQemuArgs(inst)...) regionalArgs, err := m.regionalLaunch(i) if err != nil { return nil, err @@ -202,8 +223,12 @@ func (m *Manager) launchPlanFor(ctx context.Context, inst *avd.Instance, memoryM if root.CurrentPlatform().MirrorOS == "macos" { balloon = "" } - m.Log.Infof("启动 ModAVD 实例 %d(%s,%dp %d Hz,%d MB / %s 核,%s不带声卡,ANDROID_EMU_VK_HIDE_REBAR=%s): emulator %s", - i, mode, inst.Resolution(), inst.FPS(), memoryMB, cpu, balloon, hideRebar, strings.Join(args, " ")) + card := "不带声卡" + if sound { + card = "带声卡" + } + m.Log.Infof("启动 ModAVD 实例 %d(%s,%dp %d Hz,%d MB / %s 核,%s%s,ANDROID_EMU_VK_HIDE_REBAR=%s): emulator %s", + i, mode, inst.Resolution(), inst.FPS(), memoryMB, cpu, balloon, card, hideRebar, strings.Join(args, " ")) return &launchPlan{args: args, logPath: logPath, memoryMB: memoryMB}, nil } diff --git a/internal/emu/launch_test.go b/internal/emu/launch_test.go index 7bd8b467..e949ddaa 100644 --- a/internal/emu/launch_test.go +++ b/internal/emu/launch_test.go @@ -6,6 +6,7 @@ import ( "os" "path/filepath" "reflect" + "slices" "strconv" "strings" "testing" @@ -37,19 +38,71 @@ var ( ) func TestBuildLaunchArgs(t *testing.T) { - if got := buildLaunchArgs("mas_3", 20030, 4096, true); !reflect.DeepEqual(got, masArgsHeadless) { + if got := buildLaunchArgs("mas_3", 20030, 4096, launchOptions{headless: true}); !reflect.DeepEqual(got, masArgsHeadless) { t.Errorf("headless:\n got %q\nwant %q", got, masArgsHeadless) } - if got := buildLaunchArgs("mas_3", 20030, 4096, false); !reflect.DeepEqual(got, masArgsWindow) { + if got := buildLaunchArgs("mas_3", 20030, 4096, launchOptions{}); !reflect.DeepEqual(got, masArgsWindow) { t.Errorf("window:\n got %q\nwant %q", got, masArgsWindow) } // another instance: only the name, ports and memory move - got := buildLaunchArgs("mas_0", 20000, 6144, true) + got := buildLaunchArgs("mas_0", 20000, 6144, launchOptions{headless: true}) if got[1] != "mas_0" || got[6] != "20000,20001" || got[8] != "20002" || got[13] != "6144" { t.Errorf("mas_0: %q", got) } } +// without drops every item of the pairs from args, each pair once. +func without(args []string, pairs ...[2]string) []string { + out := append([]string(nil), args...) + for _, p := range pairs { + for k := 0; k+1 < len(out); k++ { + if out[k] == p[0] && out[k+1] == p[1] { + out = append(out[:k], out[k+2:]...) + break + } + } + } + return out +} + +// TestBuildLaunchArgsSound: the sound switch (ModAVD/ModAVD#226) takes out exactly -audio none and +// -feature -VirtioSndCard, windowed and headless; everything else stays as it is. +func TestBuildLaunchArgsSound(t *testing.T) { + soundless := [][2]string{{"-audio", "none"}, {"-feature", "-VirtioSndCard"}} + for _, c := range []struct { + name string + o launchOptions + base []string + }{ + {"headless", launchOptions{headless: true, sound: true}, masArgsHeadless}, + {"window", launchOptions{sound: true}, masArgsWindow}, + } { + got := buildLaunchArgs("mas_3", 20030, 4096, c.o) + if want := without(c.base, soundless...); !reflect.DeepEqual(got, want) { + t.Errorf("%s with sound:\n got %q\nwant %q", c.name, got, want) + } + for _, a := range got { + if a == "none" || a == "-VirtioSndCard" { + t.Errorf("%s with sound still has %q: %q", c.name, a, got) + } + } + } +} + +// TestBuildLaunchArgsSavePath: -save-path right after -memory (ModAVD/ModAVD#231); nothing when "". +func TestBuildLaunchArgsSavePath(t *testing.T) { + dir := `X:\Pictures\ModAVD` + got := buildLaunchArgs("mas_3", 20030, 4096, launchOptions{headless: true, savePath: dir}) + want := append(append(append([]string(nil), masArgsHeadless[:14]...), "-save-path", dir), masArgsHeadless[14:]...) + if !reflect.DeepEqual(got, want) { + t.Errorf("save path:\n got %q\nwant %q", got, want) + } + got = buildLaunchArgs("mas_3", 20030, 4096, launchOptions{sound: true, savePath: dir}) + if k := slices.Index(got, "-save-path"); k < 0 || got[k+1] != dir { + t.Errorf("save path with sound: %q", got) + } +} + // lastEnv is the value the child sees for key: the last entry of that name, compared case-insensitively (what // win.StartOrphan / StartDetached hand to the child). func lastEnv(env []string, key string) (string, bool) { diff --git a/internal/emu/portplan_test.go b/internal/emu/portplan_test.go index 782a44a6..b94f80ed 100644 --- a/internal/emu/portplan_test.go +++ b/internal/emu/portplan_test.go @@ -558,6 +558,73 @@ func TestLaunchPlanPorts(t *testing.T) { } } +// TestLaunchPlanSound: a boot follows the instance's sound switch (ModAVD/ModAVD#226) as set through Update, which +// also writes config.ini's hw.audio* and shows it in the instance's info; every boot gets -save-path +// \ModAVD, made first (ModAVD/ModAVD#231). +func TestLaunchPlanSound(t *testing.T) { + r, _ := portPlanRoot(t) + m := New(r, logx.Nop()) + six := 6 + if _, err := m.Create(context.Background(), CreateRequest{filesOnly: true, Index: &six}); err != nil { + t.Fatal(err) + } + pictures := testutil.TempDir(t) + usePictures(t, pictures) + shots := filepath.Join(pictures, "ModAVD") + boot := func(want bool) { + t.Helper() + inst, err := m.instance(6) + if err != nil { + t.Fatal(err) + } + plan, err := m.launchPlanFor(context.Background(), inst, 3072, true) + if errs.CodeOf(err) == errs.Busy { + t.Skipf("ports of instance 6 in use on this machine: %v", err) + } + if err != nil { + t.Fatal(err) + } + args := " " + strings.Join(plan.args, " ") + " " + muted := strings.Contains(args, " -audio none ") + card := !strings.Contains(args, " -feature -VirtioSndCard ") + if muted == want || card != want { + t.Errorf("sound %v: emulator arguments %s", want, args) + } + if !strings.Contains(args, " -save-path "+shots+" ") { + t.Errorf("no -save-path %s: %s", shots, args) + } + if st, err := os.Stat(shots); err != nil || !st.IsDir() { + t.Errorf("%s not made before the boot: %v", shots, err) + } + in, err := m.instance(6) + if err != nil { + t.Fatal(err) + } + v := "no" + if want { + v = "yes" + } + if in.Config.Value("hw.audioInput") != v || in.Config.Value("hw.audioOutput") != v { + t.Errorf("sound %v: config.ini hw.audioInput=%q hw.audioOutput=%q", want, in.Config.Value("hw.audioInput"), + in.Config.Value("hw.audioOutput")) + } + if got := m.mustInfo(t, 6).Config.Sound; got != want { + t.Errorf("info config.sound = %v, want %v", got, want) + } + } + boot(false) // a new instance: no sound, exactly as before + for _, on := range []bool{true, false} { + res, err := m.Update(context.Background(), 6, UpdateRequest{Sound: &on}) + if err != nil { + t.Fatal(err) + } + if res.Applied["sound"] != on || res.Instance.Config.Sound != on { + t.Errorf("Update sound %v: applied %v, info %v", on, res.Applied, res.Instance.Config.Sound) + } + boot(on) + } +} + // TestQemuMatchedByPortPlan: on a root with portBase 21000, this root's qemu of instance 6 is the one on -ports 21060 // (and listening on 21061), not one of mas_6 on the default plan's 20060; a qemu of another root's mas_7 on 21070 is // that other root's instance on our ports; the host tuning counts our qemu's vCPUs from our instance. diff --git a/internal/emu/savepath.go b/internal/emu/savepath.go new file mode 100644 index 00000000..5f6b1acc --- /dev/null +++ b/internal/emu/savepath.go @@ -0,0 +1,31 @@ +package emu + +import ( + "os" + "path/filepath" +) + +// screenshotFolder is the folder under the user's Pictures that the emulator's screenshot button saves to +// (ModAVD/ModAVD#231). +const screenshotFolder = "ModAVD" + +// picturesDir is the current user's Pictures folder ("" and the reason when there is none): hostPicturesDir, a +// variable so tests point it at a temporary directory instead of the real one. +var picturesDir = hostPicturesDir + +// screenshotSavePath is the -save-path of a boot: \ModAVD, created first. "" when the Pictures folder is +// unknown or the folder cannot be made; the emulator then saves where it always did. Never stops a start. -save-path +// is the emulator's own option (stock emulators have it too), and it is not remembered past that run. +func (m *Manager) screenshotSavePath() string { + base, why := picturesDir() + if base == "" { + m.Log.Warnf("找不到当前用户的「图片」文件夹(%s),截图照模拟器默认的位置保存", why) + return "" + } + dir := filepath.Join(base, screenshotFolder) + if err := os.MkdirAll(dir, 0o755); err != nil { + m.Log.Warnf("建截图文件夹 %s 失败(%v),截图照模拟器默认的位置保存", dir, err) + return "" + } + return dir +} diff --git a/internal/emu/savepath_other.go b/internal/emu/savepath_other.go new file mode 100644 index 00000000..f6f86455 --- /dev/null +++ b/internal/emu/savepath_other.go @@ -0,0 +1,22 @@ +//go:build !windows + +package emu + +import ( + "os" + "path/filepath" +) + +// hostPicturesDir is ~/Pictures (macOS keeps the user's pictures there; Linux desktops too unless XDG says +// otherwise, which this does not read). An existing folder only, never created here. +func hostPicturesDir() (string, string) { + home, err := os.UserHomeDir() + if err != nil { + return "", err.Error() + } + dir := filepath.Join(home, "Pictures") + if st, err := os.Stat(dir); err != nil || !st.IsDir() { + return "", dir + " 不存在" + } + return dir, "" +} diff --git a/internal/emu/savepath_test.go b/internal/emu/savepath_test.go new file mode 100644 index 00000000..475e2a2d --- /dev/null +++ b/internal/emu/savepath_test.go @@ -0,0 +1,62 @@ +package emu + +import ( + "os" + "path/filepath" + "testing" + + "modavd/internal/logx" + "modavd/internal/testutil" +) + +// No test creates ModAVD in the real Pictures folder: boots in tests have none, unless a test gives one. +func init() { + picturesDir = func() (string, string) { return "", "tests have no Pictures folder" } +} + +// usePictures points picturesDir at dir for the test. +func usePictures(t *testing.T, dir string) { + t.Helper() + old := picturesDir + picturesDir = func() (string, string) { return dir, "" } + t.Cleanup(func() { picturesDir = old }) +} + +// TestScreenshotSavePath: \ModAVD, made when missing and kept when there; "" without a Pictures folder or +// when the folder cannot be made (a file in its place). +func TestScreenshotSavePath(t *testing.T) { + m := &Manager{Log: logx.Nop()} + if got := m.screenshotSavePath(); got != "" { + t.Errorf("no Pictures folder: %q", got) + } + pictures := testutil.TempDir(t) + usePictures(t, pictures) + want := filepath.Join(pictures, "ModAVD") + for range 2 { + if got := m.screenshotSavePath(); got != want { + t.Errorf("screenshotSavePath = %q, want %q", got, want) + } + if st, err := os.Stat(want); err != nil || !st.IsDir() { + t.Errorf("%s not made: %v", want, err) + } + } + blocked := testutil.TempDir(t) + if err := os.WriteFile(filepath.Join(blocked, "ModAVD"), []byte("x"), 0o644); err != nil { + t.Fatal(err) + } + usePictures(t, blocked) + if got := m.screenshotSavePath(); got != "" { + t.Errorf("ModAVD is a file: %q", got) + } +} + +// TestHostPicturesDir: the real lookup answers with an existing folder (or says why not); it is only read. +func TestHostPicturesDir(t *testing.T) { + dir, why := hostPicturesDir() + if dir == "" { + t.Skipf("no Pictures folder here: %s", why) + } + if st, err := os.Stat(dir); err != nil || !st.IsDir() || !filepath.IsAbs(dir) { + t.Errorf("hostPicturesDir = %q: %v", dir, err) + } +} diff --git a/internal/emu/savepath_windows.go b/internal/emu/savepath_windows.go new file mode 100644 index 00000000..048218be --- /dev/null +++ b/internal/emu/savepath_windows.go @@ -0,0 +1,38 @@ +package emu + +import ( + "fmt" + "syscall" + "unsafe" +) + +var ( + procSHGetKnownFolderPath = syscall.NewLazyDLL("shell32.dll").NewProc("SHGetKnownFolderPath") + procCoTaskMemFree = syscall.NewLazyDLL("ole32.dll").NewProc("CoTaskMemFree") +) + +// folderIDPictures is FOLDERID_Pictures {33E28130-4E1E-4676-835A-98395C3BC3BB}. +var folderIDPictures = syscall.GUID{Data1: 0x33E28130, Data2: 0x4E1E, Data3: 0x4676, + Data4: [8]byte{0x83, 0x5A, 0x98, 0x39, 0x5C, 0x3B, 0xC3, 0xBB}} + +// hostPicturesDir is the known folder FOLDERID_Pictures of the current user: where Windows keeps it, also when the +// user moved it (to another drive, into OneDrive), which %USERPROFILE%\Pictures would miss. KF_FLAG_DEFAULT: an +// existing folder only, never created here. +func hostPicturesDir() (string, string) { + if err := procSHGetKnownFolderPath.Find(); err != nil { + return "", err.Error() + } + var p *uint16 + hr, _, _ := procSHGetKnownFolderPath.Call(uintptr(unsafe.Pointer(&folderIDPictures)), 0, 0, + uintptr(unsafe.Pointer(&p))) + if p != nil { + defer procCoTaskMemFree.Call(uintptr(unsafe.Pointer(p))) + } + if int32(hr) < 0 || p == nil { + return "", fmt.Sprintf("SHGetKnownFolderPath(FOLDERID_Pictures) 返回 0x%08X", uint32(hr)) + } + n := 0 + for ptr := unsafe.Pointer(p); *(*uint16)(unsafe.Add(ptr, 2*n)) != 0; n++ { + } + return syscall.UTF16ToString(unsafe.Slice(p, n)), "" +} diff --git a/internal/emu/status.go b/internal/emu/status.go index 0035e920..b311d370 100644 --- a/internal/emu/status.go +++ b/internal/emu/status.go @@ -224,6 +224,7 @@ func (m *Manager) instanceInfo(ctx context.Context, in *avd.Instance, p *host.Pr if avd.DataDiskAutoMeta(meta) { cfg.DataDiskMode = avd.DataDiskAuto } + cfg.Sound = avd.SoundMeta(meta) info.Config = cfg if meta != nil { diff --git a/internal/emu/syncio_test.go b/internal/emu/syncio_test.go index 0c620a2b..02119227 100644 --- a/internal/emu/syncio_test.go +++ b/internal/emu/syncio_test.go @@ -180,7 +180,7 @@ func TestSyncIOQemuArgs(t *testing.T) { t.Errorf("table for the instance's 4 CPUs: %d bytes, err %v", len(b), err) } // they end up after the manager's other QEMU arguments - args := buildLaunchArgs("mas_3", 20030, 4096, true, m.syncIOQemuArgs(inst)...) + args := buildLaunchArgs("mas_3", 20030, 4096, launchOptions{headless: true}, m.syncIOQemuArgs(inst)...) if n := len(masArgsHeadless); !reflect.DeepEqual(args[:n], masArgsHeadless) || !reflect.DeepEqual(args[n:], want) { t.Errorf("launch arguments: %q", args) } @@ -219,7 +219,7 @@ func TestSyncIOOff(t *testing.T) { if got := m.syncIOQemuArgs(inst); got != nil { t.Errorf("%s=%q: got %q", envSyncIO, v, got) } - if got := buildLaunchArgs("mas_3", 20030, 4096, true, m.syncIOQemuArgs(inst)...); !reflect.DeepEqual(got, masArgsHeadless) { + if got := buildLaunchArgs("mas_3", 20030, 4096, launchOptions{headless: true}, m.syncIOQemuArgs(inst)...); !reflect.DeepEqual(got, masArgsHeadless) { t.Errorf("%s=%q: launch arguments %q", envSyncIO, v, got) } } diff --git a/internal/emu/types.go b/internal/emu/types.go index 1d3ea177..1c703965 100644 --- a/internal/emu/types.go +++ b/internal/emu/types.go @@ -44,6 +44,8 @@ type InstanceConfig struct { Width int `json:"width"` Height int `json:"height"` DPI int `json:"dpi"` + // Sound: the next boot has host sound and a guest sound card (mas-avd.json instances..sound; off by default). + Sound bool `json:"sound"` } type InstanceInfo struct { @@ -185,6 +187,8 @@ type UpdateRequest struct { // DataDiskAuto switches the data disk to 自动扩盘 (raised to avd.AutoDataPartitionGB at the next boot); not together // with DataPartitionGB. DataDiskAuto bool + // Sound turns the sound card on or off from the next boot (avd.SoundKey; ModAVD/ModAVD#226). + Sound *bool } type UpdateResult struct { diff --git a/internal/mcp/mcp_test.go b/internal/mcp/mcp_test.go index d8095530..9fc74994 100644 --- a/internal/mcp/mcp_test.go +++ b/internal/mcp/mcp_test.go @@ -1003,6 +1003,21 @@ func TestIntegralFloatArgument(t *testing.T) { } } +// TestUpdateSound: update_instance takes sound alone (ModAVD/ModAVD#226), true and false both reaching the manager. +func TestUpdateSound(t *testing.T) { + h := newHarness(t, nil, nil) + h.initialize("2025-11-25") + for k, on := range []bool{true, false} { + h.send(fmt.Sprintf(`{"jsonrpc":"2.0","id":%d,"method":"tools/call","params":{"name":"update_instance","arguments":{"index":1,"sound":%v}}}`, k+2, on)) + if text, isErr, _ := toolText(t, h.recv()); isErr { + t.Fatalf("sound %v: %s", on, text) + } + if u := h.f.updates[k]; u.Sound == nil || *u.Sound != on || u.MemoryMB != nil { + t.Fatalf("sound %v: update %+v", on, u) + } + } +} + func TestServeNeedsManager(t *testing.T) { err := Serve(context.Background(), strings.NewReader(""), io.Discard, Options{}) if errs.CodeOf(err) != errs.Internal { diff --git a/internal/mcp/tools.go b/internal/mcp/tools.go index 9a34f57f..89f4893b 100644 --- a/internal/mcp/tools.go +++ b/internal/mcp/tools.go @@ -243,7 +243,7 @@ func toolDefs() []*toolDef { })), finishing(newTool("update_instance", "Update instance", - "Change the title, memory, CPU cores, frame rate, resolution or data disk (a fixed size or automatic) of an instance. The changes take "+ + "Change the title, memory, CPU cores, frame rate, resolution, data disk (a fixed size or automatic) or sound of an instance. The changes take "+ "effect at its next boot (applies_next_boot=true when it is running now).", mutating(true, true), reflect.TypeFor[emu.UpdateResult](), []prop{ indexProp(true), @@ -259,6 +259,8 @@ func toolDefs() []*toolDef { {"data_disk_auto", false, map[string]any{"type": "boolean", "description": fmt.Sprintf("true: make the data "+ "disk automatic (%d GB from the next boot, the host only pays for what is written). Not together with "+ "data_partition_gb.", avd.AutoDataPartitionGB)}}, + {"sound", false, map[string]any{"type": "boolean", "description": "true: host sound and a guest sound " + + "card from the next boot, windowed or headless (costs some CPU); false: no sound (the default)."}}, }, func(ctx context.Context, b backend, a args, _ func(emu.Progress)) (any, error) { i, err := a.reqInt("index") @@ -289,9 +291,12 @@ func toolDefs() []*toolDef { return nil, err } req.DataDiskAuto = auto != nil && *auto + if req.Sound, err = a.optBool("sound"); err != nil { + return nil, err + } if req.Title == nil && req.MemoryMB == nil && req.CPU == nil && req.FPS == nil && req.Resolution == nil && req.DataPartitionGB == nil && - !req.DataDiskAuto { - return nil, errs.New(errs.Usage, "没有要改的选项:title、memory_mb、cpu、fps、resolution、data_partition_gb、data_disk_auto 至少给一项") + !req.DataDiskAuto && req.Sound == nil { + return nil, errs.New(errs.Usage, "没有要改的选项:title、memory_mb、cpu、fps、resolution、data_partition_gb、data_disk_auto、sound 至少给一项") } return b.Update(ctx, i, req) })), diff --git a/internal/ui/API.en.md b/internal/ui/API.en.md index 8f367e10..5d741f8f 100644 --- a/internal/ui/API.en.md +++ b/internal/ui/API.en.md @@ -41,7 +41,7 @@ HTTP 4xx / 5xx with the body `{"error":{"code":"…","message":"…","advice":" | GET | `/api/instances/{i}` | | `InstanceInfo` | | GET | `/api/instances/{i}/regional` | | `RegionalResult` | | POST | `/api/instances` | `{title?, index?, memory_mb?, cpu?, data_partition_gb?, fps?, resolution?, language?: string, time_zone?: string}` | 202 `Job` (`kind` is `create`: without `data_partition_gb` the data disk is automatic (256 GB), with it a fixed size; it boots in the background, finishes the initial setup and shuts down again, which takes a few minutes. When `index` is not given, the server picks the number first, and `Job.index` is the new instance's; the result is an `InstanceInfo`). A new instance comes without the Google Play store (there is no `play_store` field; sending one returns 400). If you want it, use `playstore-install` below after the instance is created | -| PATCH | `/api/instances/{i}` | `{title?, memory_mb?, cpu?, fps?, resolution?, data_partition_gb?, data_disk_auto?: bool, diagnostics?: bool, boss_key?: string, language?: string, time_zone?: string}` | `UpdateResult`; the diagnostics setting and the boss key take effect immediately, ordinary configuration at the next boot. `data_partition_gb` gives the data disk a fixed size (only larger), `data_disk_auto: true` makes it automatic; not both. When `boss_key` is given, the result has one more field `boss_key_taken` (bool): the new key was tried at once, and `true` means another program holds it (see "Boss keys and the tray" below) | +| PATCH | `/api/instances/{i}` | `{title?, memory_mb?, cpu?, fps?, resolution?, data_partition_gb?, data_disk_auto?: bool, diagnostics?: bool, sound?: bool, boss_key?: string, language?: string, time_zone?: string}` | `UpdateResult`; the diagnostics setting and the boss key take effect immediately, ordinary configuration (`sound` too) at the next boot. `data_partition_gb` gives the data disk a fixed size (only larger), `data_disk_auto: true` makes it automatic; not both. When `boss_key` is given, the result has one more field `boss_key_taken` (bool): the new key was tried at once, and `true` means another program holds it (see "Boss keys and the tray" below) | | GET | `/api/instances/{i}/diagnostics/preview` | | `{"index","files","bytes"}`: the number of files and bytes that would be cleaned up when diagnostics is turned off; it changes no configuration and deletes no files | | DELETE | `/api/instances/{i}?confirm=1` | without `confirm=1` the server returns 400 `usage` | `DeleteResult` | | POST | `/api/instances/{i}/start` | `{}` | 202 `Job`: always boots with a window (the manager never boots headless; headless boot is command line only). If the instance is already running headless, the job fails with code `busy` (no switching while running) | diff --git a/internal/ui/API.md b/internal/ui/API.md index 841f5d70..975dd84f 100644 --- a/internal/ui/API.md +++ b/internal/ui/API.md @@ -41,7 +41,7 @@ HTTP 4xx / 5xx,体为 `{"error":{"code":"…","message":"…","advice":"…"," | GET | `/api/instances/{i}` | | `InstanceInfo` | | GET | `/api/instances/{i}/regional` | | `RegionalResult` | | POST | `/api/instances` | `{title?, index?, memory_mb?, cpu?, data_partition_gb?, fps?, resolution?, language?: string, time_zone?: string}` | 202 `Job`(`kind` 是 `create`:不给 `data_partition_gb` 是自动扩盘(256 GB),给了是指定大小;后台开机做完初始化再关机,要几分钟;没给 `index` 时服务端先选好编号,`Job.index` 就是新实例的;结果是 `InstanceInfo`)。新建的实例不带 Google Play 商店(没有 `play_store` 字段,给了回 400),要的话建好后用下面的 `playstore-install` | -| PATCH | `/api/instances/{i}` | `{title?, memory_mb?, cpu?, fps?, resolution?, data_partition_gb?, data_disk_auto?: bool, diagnostics?: bool, boss_key?: string, language?: string, time_zone?: string}` | `UpdateResult`;诊断和老板键立即生效,普通配置下次开机生效。`data_partition_gb` 把数据盘改成指定大小(只能改大),`data_disk_auto: true` 改成自动扩盘,两个不能同时给。给了 `boss_key` 时多一个 `boss_key_taken`(bool):新键当场试注册过,被别的程序占着是 `true`(见下「老板键和托盘」) | +| PATCH | `/api/instances/{i}` | `{title?, memory_mb?, cpu?, fps?, resolution?, data_partition_gb?, data_disk_auto?: bool, diagnostics?: bool, sound?: bool, boss_key?: string, language?: string, time_zone?: string}` | `UpdateResult`;诊断和老板键立即生效,普通配置(声音 `sound` 也是)下次开机生效。`data_partition_gb` 把数据盘改成指定大小(只能改大),`data_disk_auto: true` 改成自动扩盘,两个不能同时给。给了 `boss_key` 时多一个 `boss_key_taken`(bool):新键当场试注册过,被别的程序占着是 `true`(见下「老板键和托盘」) | | GET | `/api/instances/{i}/diagnostics/preview` | | `{"index","files","bytes"}`:关闭诊断时预计清理的份数、字节,不改配置、不删文件 | | DELETE | `/api/instances/{i}?confirm=1` | 不带 `confirm=1` 回 400 `usage` | `DeleteResult` | | POST | `/api/instances/{i}/start` | `{}` | 202 `Job`:一律带窗口开机(管理器不开无头的,无头开机只走命令行);实例要先装执行桥时,装桥这几次准备用的开机都无头,装好后正常关机,最后一次带窗口开机(同 `modavd start --window`);实例已经以无头方式在运行时,任务失败,code 是 `busy`(运行中不切换) | diff --git a/internal/ui/handlers.go b/internal/ui/handlers.go index 4f8c5ae5..ad518484 100644 --- a/internal/ui/handlers.go +++ b/internal/ui/handlers.go @@ -130,13 +130,14 @@ func (s *server) handleUpdate(w http.ResponseWriter, r *http.Request) { DataPartitionGB *int `json:"data_partition_gb"` DataDiskAuto bool `json:"data_disk_auto"` BossKey *string `json:"boss_key"` + Sound *bool `json:"sound"` } if !decode(w, r, &body) { return } if body.Title == nil && body.MemoryMB == nil && body.CPU == nil && body.FPS == nil && body.Resolution == nil && body.DataPartitionGB == nil && - !body.DataDiskAuto && body.Diagnostics == nil && body.BossKey == nil && body.Language == nil && body.TimeZone == nil { - writeError(w, errs.New(errs.Usage, "没有要改的设置").WithAdvice("至少给出 title、memory_mb、cpu、fps、resolution、data_partition_gb、data_disk_auto、language、time_zone、diagnostics、boss_key 中的一项")) + !body.DataDiskAuto && body.Diagnostics == nil && body.Sound == nil && body.BossKey == nil && body.Language == nil && body.TimeZone == nil { + writeError(w, errs.New(errs.Usage, "没有要改的设置").WithAdvice("至少给出 title、memory_mb、cpu、fps、resolution、data_partition_gb、data_disk_auto、language、time_zone、diagnostics、sound、boss_key 中的一项")) return } release, err := s.beginInstanceAction(kindSettings, i) @@ -148,7 +149,7 @@ func (s *server) handleUpdate(w http.ResponseWriter, r *http.Request) { res, err := s.mgr.Update(detached(r), i, emu.UpdateRequest{Title: body.Title, MemoryMB: body.MemoryMB, CPU: body.CPU, Language: body.Language, TimeZone: body.TimeZone, FPS: body.FPS, Resolution: body.Resolution, DataPartitionGB: body.DataPartitionGB, DataDiskAuto: body.DataDiskAuto, - Diagnostics: body.Diagnostics, BossKey: body.BossKey}) + Diagnostics: body.Diagnostics, BossKey: body.BossKey, Sound: body.Sound}) if err != nil { writeError(w, err) return diff --git a/internal/ui/web/dev/mock.js b/internal/ui/web/dev/mock.js index 5b5edf39..e292f189 100644 --- a/internal/ui/web/dev/mock.js +++ b/internal/ui/web/dev/mock.js @@ -50,7 +50,7 @@ function mk(i, title, o = {}) { ports: { console, adb: console + 1, grpc: console + 2 }, screencap: { shm: 'SHM_videmulator' + console, shm_ready: st === 'online' }, // o.disk: a size the user set (manual); without it 自动扩盘 (256 GB) - config: { memory_mb: o.mem || 6144, cpu: o.cpu || 6, fps: o.fps || 60, data_partition_gb: o.disk || 256, data_disk_mode: o.disk ? 'manual' : 'auto', resolution: o.resolution || 720, width: o.resolution === 1080 ? 1920 : 1280, height: o.resolution === 1080 ? 1080 : 720, dpi: o.resolution === 1080 ? 280 : 240 }, + config: { memory_mb: o.mem || 6144, cpu: o.cpu || 6, fps: o.fps || 60, data_partition_gb: o.disk || 256, data_disk_mode: o.disk ? 'manual' : 'auto', resolution: o.resolution || 720, width: o.resolution === 1080 ? 1920 : 1280, height: o.resolution === 1080 ? 1080 : 720, dpi: o.resolution === 1080 ? 280 : 240, sound: !!o.sound }, initialized, launcher: initialized ? 'µLauncher' : '', renderer: initialized ? (o.sw ? SWIFT : GPU) : '', software_renderer: !!o.sw, path: `${ROOT}\\avd\\mas_${i}.avd`, @@ -997,7 +997,7 @@ async function handle(url, init) { Object.assign(inst.config, { resolution: body.resolution, width: portrait ? h : w, height: portrait ? w : h, dpi: body.resolution === 1080 ? 280 : 240 }); applied.resolution = body.resolution; } - for (const k of ['memory_mb', 'cpu', 'fps']) if (body[k] != null) { inst.config[k] = body[k]; applied[k] = body[k]; } + for (const k of ['memory_mb', 'cpu', 'fps', 'sound']) if (body[k] != null) { inst.config[k] = body[k]; applied[k] = body[k]; } // the data disk: 自动扩盘, or a size that can only grow if (body.data_disk_auto && body.data_partition_gb != null) return errResp('invalid_argument', '数据盘只能二选一:自动扩盘,或者指定大小'); if (body.data_disk_auto) { diff --git a/internal/ui/web/js/forms.js b/internal/ui/web/js/forms.js index 2bc04ff6..6b194de5 100644 --- a/internal/ui/web/js/forms.js +++ b/internal/ui/web/js/forms.js @@ -209,8 +209,10 @@ export function openSettings(i, field) { const initDiagnostics = inst0.diagnostics === true; const title = h('input', { class: 'input', id: 's-title', maxlength: '40', autocomplete: 'off', value: initTitle, placeholder: defaultName(i) }); const diagnostics = h('input', { type: 'checkbox', id: 's-diagnostics', checked: initDiagnostics, 'aria-describedby': 's-diagnostics-h' }); + const initSound = cfg.sound === true; + const sound = h('input', { type: 'checkbox', id: 's-sound', checked: initSound, 'aria-describedby': 's-sound-h' }); const boss = bossKeyField(inst0.boss_key || '', () => dirty()); - const runNote = h('div', { class: 'note-box tone-warn', role: 'status' }, icon('info'), h('span', { text: '实例运行中,内存、CPU、帧率、分辨率和数据盘在下次开机生效。诊断设置立即生效。' })); + const runNote = h('div', { class: 'note-box tone-warn', role: 'status' }, icon('info'), h('span', { text: '实例运行中,内存、CPU、帧率、分辨率、数据盘和声音在下次开机生效。诊断设置立即生效。' })); const kv = h('dl', { class: 'kv' }); const fps = fpsField('s', cfg.fps); const diskAuto0 = cfg.data_disk_mode !== 'manual'; @@ -235,6 +237,8 @@ export function openSettings(i, field) { fps.rows, segRow('分辨率', 'resolution', RESOLUTION, cfg.resolution, hint('下次开机生效,自动化工具里的分辨率也要跟着改')), disk.rows, + inputRow('声音', h('span', { class: 'checkbox p-switch' }, sound), + hint('下次开机生效,带窗口和无头都有声音。开了会多占一些 CPU。', 's-sound-h')), inputRow('诊断模式', h('span', { class: 'checkbox p-switch' }, diagnostics), hint('立即生效。历史日志上限 4 GiB、客体内存最多增加 48 MiB;日志可能包含账号信息,仅保存在本机。', 's-diagnostics-h')), boss.row, @@ -252,6 +256,7 @@ export function openSettings(i, field) { const out = {}; if (title.value.trim() !== initTitle) out.title = title.value.trim(); if (diagnostics.checked !== initDiagnostics) out.diagnostics = diagnostics.checked; + if (sound.checked !== initSound) out.sound = sound.checked; if (boss.changed()) out.boss_key = boss.value(); if (regional) Object.assign(out, regional.changes()); for (const [k, key] of [['memory', 'memory_mb'], ['cpu', 'cpu'], ['fps', 'fps'], ['resolution', 'resolution']]) { diff --git a/scripts/test_create_cancel.mjs b/scripts/test_create_cancel.mjs index e3ba6f57..5994590f 100644 --- a/scripts/test_create_cancel.mjs +++ b/scripts/test_create_cancel.mjs @@ -237,9 +237,10 @@ async function settingsHarness({ diagnostics = true, running = true, get, patch, const turn = () => new Promise(resolve => setImmediate(resolve)); -test('settings has one diagnostic checkbox with limits, privacy and immediate application', async () => { +test('settings has a diagnostic checkbox with limits, privacy and immediate application', async () => { const h = await settingsHarness(); - assert.equal(descendants(h.settings.form).filter(x => x.type === 'checkbox').length, 1); + // the diagnostics switch and the sound switch + assert.deepEqual(descendants(h.settings.form).filter(x => x.type === 'checkbox').map(x => x.attrs.get('id')), ['s-sound', 's-diagnostics']); assert.equal(h.control('s-diagnostics').checked, true); const text = h.settings.options.body.textContent; for (const expected of ['历史日志上限 4 GiB', '客体内存最多增加 48 MiB', '账号信息', '仅保存在本机', '诊断设置立即生效']) assert.ok(text.includes(expected), text); @@ -255,6 +256,19 @@ test('enabling diagnostics patches a boolean immediately without a deletion prev assert.doesNotMatch(h.toasts[0].title + h.toasts[0].text, /下次开机/); }); +// ModAVD/ModAVD#226: off unless config.sound is true; turning it on patches sound alone, for the next boot. +test('the sound switch is off by default and patches a boolean', async () => { + const h = await settingsHarness(); + const sound = h.control('s-sound'); + assert.equal(sound.checked, false); + const text = h.settings.options.body.textContent; + for (const expected of ['声音', '下次开机生效', '多占一些 CPU']) assert.ok(text.includes(expected), text); + sound.checked = true; + h.settings.form.dispatch('change'); + await h.submit(); + assert.deepEqual(h.requests, [{ method: 'PATCH', path: '/api/instances/3', body: { sound: true } }]); +}); + test('diagnostic save displays the external capture warning from its result', async () => { const h = await settingsHarness({ diagnostics: false, patch: async () => ({ instance: { index: 3, diagnostics: true }, warnings: ['已有其它程序采集 logcat,诊断模式未接管宿主采集'], From c6b941c3c26c58730cebbc94538aab77ba297640 Mon Sep 17 00:00:00 2001 From: qiyinxi Date: Tue, 17 Nov 2026 15:25:43 +0100 Subject: [PATCH 2/2] avd: sound alone writes only the sound keys Changing only the sound switch no longer validates or rewrites memory, cores or the data disk (like the diagnostics switch), so an old 8 GB instance can turn sound on and AUTO-MAS's automatic memory stays. Refs ModAVD/ModAVD#226 --- internal/avd/avd.go | 24 ++++++++++++++++++--- internal/avd/avd_test.go | 45 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 66 insertions(+), 3 deletions(-) diff --git a/internal/avd/avd.go b/internal/avd/avd.go index fca57364..7a305374 100644 --- a/internal/avd/avd.go +++ b/internal/avd/avd.go @@ -64,8 +64,9 @@ const ( ) // ConfigTemplate is config.ini of a new instance before the per-instance keys (AUTO-MAS _CONFIG_TEMPLATE, same -// order). Taken from the tuned mas_p0: landscape, host GPU, no device frame, no sound card keys (the real switch is -// -feature -VirtioSndCard; the instance's sound switch, SoundKey, writes them yes), hw.mainKeys=yes (no on-screen +// order). Taken from the tuned mas_p0: landscape, host GPU, no device frame, sound keys hw.audioInput / hw.audioOutput +// set to no (the real switch is -feature -VirtioSndCard; the instance's sound switch, SoundKey, writes them yes), +// hw.mainKeys=yes (no on-screen // navigation bar; ModAVD #1). var ConfigTemplate = [][2]string{ {"PlayStore.enabled", "no"}, @@ -810,7 +811,9 @@ type UpdateOptions struct { // changes by option name ("title", "memory_mb", "cpu", "fps", "data_partition_gb", "sound"). Takes effect at the next // boot. // -// As in AUTO-MAS the unchanged values are validated too: memory is MemoryFor (old instances get 6144 written), cores +// Sound on its own only writes the sound keys and instances..sound: nothing is validated or rewritten then. +// +// Otherwise, as in AUTO-MAS, the unchanged values are validated too: memory is MemoryFor (old instances get 6144 written), cores // hw.cpu.ncore (DefaultCPU when unreadable), and the instance's data partition must still be within range unless a // new DataPartitionGB is given (an old 8 GB instance can be raised that way). A given empty Title means the AVD name, // like Create. @@ -830,6 +833,21 @@ func Update(r *root.Root, i int, opt UpdateOptions) (map[string]any, error) { if err != nil { return nil, err } + // Sound alone is not an AUTO-MAS hardware edit: like the diagnostics switch it neither validates nor rewrites the + // unrelated values (an old out-of-range data disk, AUTO-MAS's automatic memory), only the sound keys. + if opt.Sound != nil && opt.Title == nil && opt.MemoryMB == nil && opt.CPU == nil && opt.FPS == nil && + opt.Resolution == nil && opt.DataPartitionGB == nil && !opt.DataDiskAuto { + if _, err := r.ReadMetadata(); err != nil { + return nil, err + } + if err := writeInstanceConfig(r, i, SoundConfig(*opt.Sound)); err != nil { + return nil, err + } + if err := r.UpdateInstanceMeta(i, map[string]*jsonord.Value{SoundKey: jsonord.NewBool(*opt.Sound)}); err != nil { + return nil, err + } + return map[string]any{"sound": *opt.Sound}, nil + } if opt.Title != nil { if err := validateTitle(*opt.Title); err != nil { return nil, err diff --git a/internal/avd/avd_test.go b/internal/avd/avd_test.go index e9afb4b1..a3186183 100644 --- a/internal/avd/avd_test.go +++ b/internal/avd/avd_test.go @@ -1029,6 +1029,51 @@ func TestUpdateSound(t *testing.T) { t.Errorf("sound %v: config\n got %q\nwant %q", on, got, want) } } + + // Sound alone neither validates nor rewrites unrelated values: an old 8 GB data disk is not refused, AUTO-MAS's + // automatic memory (no memoryMb) stays automatic, hw.ramSize stays as it was. + cfg := strings.NewReplacer("disk.dataPartition.size=64G", "disk.dataPartition.size=8G", + "hw.ramSize=4096M", "hw.ramSize=3000M").Replace(before) + if strings.Count(cfg, "=8G\r\n")+strings.Count(cfg, "=3000M\r\n") != 2 { + t.Fatalf("old config: %q", cfg) + } + writeFile(t, ConfigPath(r, 0), []byte(cfg)) + if err := r.EditInstanceMeta(0, func(meta *jsonord.Obj) error { meta.Delete("memoryMb"); return nil }); err != nil { + t.Fatal(err) + } + on := true + if applied, err := Update(r, 0, UpdateOptions{Sound: &on}); err != nil || fmt.Sprint(applied) != "map[sound:true]" { + t.Fatalf("sound on an old instance: %v %v", applied, err) + } + want := strings.NewReplacer("hw.audioInput=no\r\n", "hw.audioInput=yes\r\n", + "hw.audioOutput=no\r\n", "hw.audioOutput=yes\r\n").Replace(cfg) + if got := string(readFile(t, ConfigPath(r, 0))); got != want { + t.Errorf("sound on an old instance: config\n got %q\nwant %q", got, want) + } + if r.InstanceMeta(0).Has("memoryMb") || !SoundMeta(r.InstanceMeta(0)) { + t.Errorf("sound on an old instance: metadata %v", r.InstanceMeta(0)) + } + + // Together with a hardware setting it goes the whole way, sound keys included. + writeFile(t, ConfigPath(r, 0), []byte(before)) + off := false + if applied, err := Update(r, 0, UpdateOptions{Sound: &off, CPU: ip(6)}); err != nil || + fmt.Sprint(applied) != "map[cpu:6 sound:false]" { + t.Fatalf("sound with cpu: %v %v", applied, err) + } + got := string(readFile(t, ConfigPath(r, 0))) + if !strings.Contains(got, "hw.cpu.ncore=6\r\n") || !strings.Contains(got, "hw.audioInput=no\r\n") || + !strings.Contains(got, "hw.audioOutput=no\r\n") || SoundMeta(r.InstanceMeta(0)) { + t.Errorf("sound with cpu: sound %v, config %q", SoundMeta(r.InstanceMeta(0)), got) + } + writeFile(t, ConfigPath(r, 0), []byte(before)) + if _, err := Update(r, 0, UpdateOptions{Sound: &on, CPU: ip(4)}); err != nil { + t.Fatal(err) + } + if got := string(readFile(t, ConfigPath(r, 0))); !strings.Contains(got, "hw.audioOutput=yes\r\n") || + !SoundMeta(r.InstanceMeta(0)) { + t.Errorf("sound on with cpu: sound %v, config %q", SoundMeta(r.InstanceMeta(0)), got) + } } // TestSoundMeta: only a JSON true turns sound on.