diff --git a/program/AudioOutput.cs b/program/AudioOutput.cs index 668efd0..1b7b642 100644 --- a/program/AudioOutput.cs +++ b/program/AudioOutput.cs @@ -1,47 +1,63 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using System.Runtime.InteropServices; +using System.Threading; /// Speaker <-> headphone-jack switching through the sound server -/// (PulseAudio, or PipeWire's pulse layer), using the `pactl` command. +/// (PipeWire's pulse layer, or PulseAudio), using the `pactl` command. /// -/// Built-in speaker and the 3.5mm jack are normally two PORTS of the same -/// output (sink), so switching is `pactl set-sink-port`. The OpenAL stream -/// keeps playing, it just comes out of the other port. If the headphones are -/// a separate device (USB / Bluetooth), the default sink is changed instead -/// and every playing stream is moved to it. +/// On the T101HA tablet (sof-bytcht rt5645) the speaker and the 3.5mm jack +/// are NOT two ports of one output. The sound card has separate PROFILES: +/// HiFi (Headphones, Mic) -> sink ...HiFi__Headphones__sink +/// HiFi (Mic, Speaker) -> sink ...HiFi__Speaker__sink +/// Only one exists at a time, so switching = `pactl set-card-profile`. +/// After the switch the new sink is made the default and every playing +/// stream (the OpenAL one included) is moved onto it, so it never falls +/// back to the HDMI output. +/// +/// Public API is unchanged from the previous version: +/// AudioOutput.Current(), AudioOutput.Toggle(out problem), AudioOutput.Log public static class AudioOutput { public enum Kind { Unknown, Speaker, Jack } - private class Port + private class Profile { - public string Name, Desc; - public bool Unplugged; // "not available" = jack empty + public string Name; + public bool Available; + public int Priority; + public int Sinks; public Kind Kind; } - private class Sink + private class Card { public string Name; - public string ActivePort; - public List Ports = new List(); + public string ActiveProfile; + public List Profiles = new List(); } public static event Action Log; + /// Volume set on the output after switching. The app's own volume curve + /// does the rest, so keep this at 100% unless it's too loud. + public const string OutputVolume = "100%"; + /// What is playing sound right now. public static Kind Current() { - List sinks; string def; - if (!Read(out sinks, out def)) return Kind.Unknown; + Card c = FindCard(); + if (c != null) return Classify(c.ActiveProfile); - Sink s = sinks.Find(x => x.Name == def); - if (s == null) return Kind.Unknown; - - Port p = s.Ports.Find(x => x.Name == s.ActivePort); - if (p != null && p.Kind != Kind.Unknown) return p.Kind; - return Classify(s.Name, ""); // e.g. a USB headset sink with no ports + // No speaker/headphone card found: guess from the default sink's name. + int code; + string info = Run("info", out code); + if (code != 0 || info == null) return Kind.Unknown; + foreach (string line in info.Split('\n')) + if (line.StartsWith("Default Sink:")) + return Classify(line.Substring("Default Sink:".Length)); + return Kind.Unknown; } /// Switches to the other output. Returns the output now in use, and a @@ -49,126 +65,200 @@ public static Kind Toggle(out string problem) { problem = null; - List sinks; string def; - if (!Read(out sinks, out def)) { problem = "pactl not available"; return Kind.Unknown; } - Kind now = Current(); - Kind want = now == Kind.Jack ? Kind.Speaker : Kind.Jack; + int code; + Run("info", out code); + if (code != 0) { problem = "pactl not available"; return Kind.Unknown; } - // 1) another port on the same sink (the normal laptop / tablet case) - Sink cur = sinks.Find(x => x.Name == def); - if (cur != null) + Card card = FindCard(); + if (card == null) { - Port target = cur.Ports.Find(p => p.Kind == want); - if (target != null) - { - if (target.Unplugged && want == Kind.Jack) - { - problem = "jack-empty"; - Emit("headphone port '" + target.Name + "' reports nothing plugged in"); - return now; - } - int code; - Run("set-sink-port " + Quote(cur.Name) + " " + Quote(target.Name), out code); - if (code == 0) - { - Emit("port " + cur.ActivePort + " -> " + target.Name); - return Current(); - } - Emit("set-sink-port failed (exit " + code + ")"); - } - } - - // 2) a different sink of the wanted kind (USB / Bluetooth headphones) - foreach (var s in sinks) - { - if (s.Name == def) continue; - bool match = Classify(s.Name, "") == want || s.Ports.Exists(p => p.Kind == want && !p.Unplugged); - if (!match) continue; - - int code; - Run("set-default-sink " + Quote(s.Name), out code); - if (code != 0) continue; - MoveAllStreams(s.Name); - Emit("default sink " + def + " -> " + s.Name); + problem = "no-jack"; + Emit("no sound card with both speaker and headphone profiles"); return Current(); } - problem = want == Kind.Jack ? "no-jack" : "no-speaker"; - Emit("no " + want + " output found"); - return now; + Kind now = Classify(card.ActiveProfile); + Kind want = now == Kind.Jack ? Kind.Speaker : Kind.Jack; + + // Best available profile of the wanted kind (highest priority). + Profile target = null; + foreach (var p in card.Profiles) + { + if (p.Kind != want || p.Sinks < 1 || !p.Available) continue; + if (target == null || p.Priority > target.Priority) target = p; + } + + if (target == null) + { + if (want == Kind.Jack) + { + problem = "jack-empty"; + Emit("no headphone profile available - is anything plugged in?"); + } + else + { + problem = "no-speaker"; + Emit("no speaker profile available"); + } + return now; + } + + Run("set-card-profile " + Quote(card.Name) + " " + Quote(target.Name), out code); + if (code != 0) + { + problem = want == Kind.Jack ? "no-jack" : "no-speaker"; + Emit("set-card-profile failed (exit " + code + ")"); + return now; + } + Emit("profile " + card.ActiveProfile + " -> " + target.Name); + + // The new sink takes a moment to appear. Make it the default and move + // playing streams onto it, otherwise they may land on HDMI. + string sink = WaitForSink(card.Name, want); + if (sink != null) + { + Run("set-default-sink " + Quote(sink), out code); + Run("set-sink-mute " + Quote(sink) + " 0", out code); // new sink may start muted + Run("set-sink-volume " + Quote(sink) + " " + OutputVolume, out code); + MoveAllStreams(sink); + Emit("default sink -> " + sink + " (unmuted, volume " + OutputVolume + ")"); + + // OpenAL is still attached to the output that was just deleted: + // reconnect it to the new default, keeping all loaded sounds. + ReopenOpenAL(); + } + else + { + Emit("profile switched but its output did not appear"); + } + + return Current(); } - // ── pactl ────────────────────────────────────────────────────────── + // ── pactl parsing ────────────────────────────────────────────────── - private static bool Read(out List sinks, out string defaultSink) + /// The built-in card: the one that has both a speaker and a headphone profile. + private static Card FindCard() { - sinks = new List(); - defaultSink = null; - int code; - string info = Run("info", out code); - if (code != 0 || info == null) return false; - foreach (string line in info.Split('\n')) - if (line.StartsWith("Default Sink:")) - defaultSink = line.Substring("Default Sink:".Length).Trim(); + string list = Run("list cards", out code); + if (code != 0 || list == null) return null; - string list = Run("list sinks", out code); - if (code != 0 || list == null) return false; + var cards = new List(); + Card cur = null; + bool inProfiles = false; - Sink cur = null; - bool inPorts = false; foreach (string raw in list.Split('\n')) { string line = raw.TrimEnd(); string t = line.Trim(); - if (line.StartsWith("Sink #")) { cur = new Sink(); sinks.Add(cur); inPorts = false; continue; } + if (line.StartsWith("Card #")) { cur = new Card(); cards.Add(cur); inProfiles = false; continue; } if (cur == null) continue; - if (t.StartsWith("Name:")) { cur.Name = t.Substring(5).Trim(); continue; } - if (t.StartsWith("Active Port:")) { cur.ActivePort = t.Substring(12).Trim(); inPorts = false; continue; } - if (t == "Ports:") { inPorts = true; continue; } + // top-level card fields are indented one tab + bool oneTab = line.StartsWith("\t") && !line.StartsWith("\t\t"); - if (inPorts) + if (oneTab) { - // port lines are indented two tabs: "\t\tname: Description (type: ..., availability ...)" - if (!line.StartsWith("\t\t") || line.StartsWith("\t\t\t")) { if (!line.StartsWith("\t\t")) inPorts = false; continue; } - int colon = t.IndexOf(':'); - if (colon <= 0) continue; + inProfiles = false; + if (t.StartsWith("Name:")) cur.Name = t.Substring(5).Trim(); + else if (t.StartsWith("Active Profile:")) cur.ActiveProfile = t.Substring(15).Trim(); + else if (t == "Profiles:") inProfiles = true; + continue; + } - var p = new Port { Name = t.Substring(0, colon).Trim() }; - string rest = t.Substring(colon + 1).Trim(); - int paren = rest.IndexOf('('); - p.Desc = paren > 0 ? rest.Substring(0, paren).Trim() : rest; - p.Unplugged = rest.Contains("not available"); - p.Kind = Classify(p.Name, rest); - cur.Ports.Add(p); + // profile lines: "\t\tNAME: Description (sinks: 1, sources: 1, priority: 8300, available: yes)" + if (inProfiles && line.StartsWith("\t\t") && !line.StartsWith("\t\t\t")) + { + int sep = t.IndexOf(": "); + if (sep <= 0) continue; + string rest = t.Substring(sep + 2); + var p = new Profile + { + Name = t.Substring(0, sep).Trim(), + Sinks = IntAfter(rest, "sinks:"), + Priority = IntAfter(rest, "priority:"), + Available = !rest.Contains("available: no") + }; + p.Kind = Classify(p.Name); + cur.Profiles.Add(p); } } - return defaultSink != null; + + foreach (var c in cards) + { + if (c.Name == null) continue; + bool hasSpeaker = c.Profiles.Exists(p => p.Kind == Kind.Speaker); + bool hasJack = c.Profiles.Exists(p => p.Kind == Kind.Jack); + if (hasSpeaker && hasJack) return c; + } + return null; } - private static Kind Classify(string name, string desc) + private static Kind Classify(string text) { - string s = (name + " " + desc).ToLowerInvariant(); - if (s.Contains("headphone") || s.Contains("headset") || s.Contains("lineout") || + if (text == null) return Kind.Unknown; + string s = text.ToLowerInvariant(); + if (s.Contains("hdmi")) return Kind.Unknown; // never treat HDMI as the speaker + if (s.Contains("headphone") || s.Contains("lineout") || s.Contains("line-out") || s.Contains("line out")) return Kind.Jack; if (s.Contains("speaker")) return Kind.Speaker; return Kind.Unknown; } + /// Waits up to ~2 s for the card's sink of the given kind to appear. + private static string WaitForSink(string cardName, Kind want) + { + string key = cardName.StartsWith("alsa_card.") ? cardName.Substring(10) : cardName; + + for (int i = 0; i < 20; i++) + { + int code; + string list = Run("list short sinks", out code); + if (code == 0 && list != null) + { + foreach (string line in list.Split('\n')) + { + string[] cols = line.Split('\t'); + if (cols.Length < 2) continue; + string name = cols[1].Trim(); + if (name.Contains(key) && Classify(name) == want) return name; + } + } + Thread.Sleep(100); + } + return null; + } + + private static int IntAfter(string s, string key) + { + int i = s.IndexOf(key); + if (i < 0) return 0; + i += key.Length; + while (i < s.Length && s[i] == ' ') i++; + int start = i; + while (i < s.Length && char.IsDigit(s[i])) i++; + int v; + return int.TryParse(s.Substring(start, i - start), out v) ? v : 0; + } + private static void MoveAllStreams(string sink) { int code; string list = Run("list short sink-inputs", out code); if (code != 0 || list == null) return; + int moved = 0; foreach (string line in list.Split('\n')) { string id = line.Split('\t')[0].Trim(); - if (id.Length > 0) Run("move-sink-input " + id + " " + Quote(sink), out code); + if (id.Length == 0) continue; + Run("move-sink-input " + id + " " + Quote(sink), out code); + if (code == 0) moved++; } + Emit("moved " + moved + " playing stream(s)"); } private static string Run(string args, out int exitCode) @@ -203,6 +293,56 @@ } } + // ── reconnect OpenAL after the switch ────────────────────────────── + // + // Switching profile deletes the old output; OpenAL stays attached to it + // and goes silent. ALC_SOFT_reopen_device (OpenAL Soft 1.22+) moves the + // open device onto the current default output, keeping every loaded + // sound and its playback. Linux only; this file is only used on Linux + // anyway, and the platform check keeps it harmless elsewhere. + + private const string OpenALLib = "libopenal.so.1"; + + [DllImport(OpenALLib)] private static extern IntPtr alcGetCurrentContext(); + [DllImport(OpenALLib)] private static extern IntPtr alcGetContextsDevice(IntPtr context); + [DllImport(OpenALLib)] private static extern byte alcIsExtensionPresent(IntPtr device, string name); + [DllImport(OpenALLib)] private static extern IntPtr alcGetProcAddress(IntPtr device, string name); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private delegate byte ReopenDeviceFn(IntPtr device, IntPtr deviceName, IntPtr attribs); + + private static bool ReopenOpenAL() + { + if (Environment.OSVersion.Platform != PlatformID.Unix) return false; + try + { + IntPtr ctx = alcGetCurrentContext(); + if (ctx == IntPtr.Zero) { Emit("reopen: no OpenAL context"); return false; } + + IntPtr dev = alcGetContextsDevice(ctx); + if (dev == IntPtr.Zero) { Emit("reopen: no OpenAL device"); return false; } + + if (alcIsExtensionPresent(dev, "ALC_SOFT_reopen_device") == 0) + { + Emit("reopen: OpenAL Soft is too old (needs 1.22+)"); + return false; + } + + IntPtr fp = alcGetProcAddress(dev, "alcReopenDeviceSOFT"); + if (fp == IntPtr.Zero) { Emit("reopen: function not found"); return false; } + + var reopen = (ReopenDeviceFn)Marshal.GetDelegateForFunctionPointer(fp, typeof(ReopenDeviceFn)); + bool ok = reopen(dev, IntPtr.Zero, IntPtr.Zero) != 0; // null name = default output + Emit("reopen OpenAL on default output: " + (ok ? "ok" : "FAILED")); + return ok; + } + catch (Exception ex) + { + Emit("reopen failed: " + ex.Message); + return false; + } + } + private static string Quote(string s) { return "\"" + s.Replace("\"", "\\\"") + "\""; } private static void Emit(string m)