Newer
Older
EARS-LINUX / program / AudioOutput.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;

/// Speaker <-> headphone-jack switching through the sound server
/// (PipeWire's pulse layer, or PulseAudio), using the `pactl` command.
///
/// 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 Profile
    {
        public string Name;
        public bool   Available;
        public int    Priority;
        public int    Sinks;
        public Kind   Kind;
    }

    private class Card
    {
        public string Name;
        public string ActiveProfile;
        public List<Profile> Profiles = new List<Profile>();
    }

    public static event Action<string> 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()
    {
        Card c = FindCard();
        if (c != null) return Classify(c.ActiveProfile);

        // 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
    /// short reason when it could not switch.
    public static Kind Toggle(out string problem)
    {
        problem = null;

        int code;
        Run("info", out code);
        if (code != 0) { problem = "pactl not available"; return Kind.Unknown; }

        Card card = FindCard();
        if (card == null)
        {
            problem = "no-jack";
            Emit("no sound card with both speaker and headphone profiles");
            return Current();
        }

        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 parsing ──────────────────────────────────────────────────

    /// The built-in card: the one that has both a speaker and a headphone profile.
    private static Card FindCard()
    {
        int code;
        string list = Run("list cards", out code);
        if (code != 0 || list == null) return null;

        var cards = new List<Card>();
        Card cur = null;
        bool inProfiles = false;

        foreach (string raw in list.Split('\n'))
        {
            string line = raw.TrimEnd();
            string t = line.Trim();

            if (line.StartsWith("Card #")) { cur = new Card(); cards.Add(cur); inProfiles = false; continue; }
            if (cur == null) continue;

            // top-level card fields are indented one tab
            bool oneTab = line.StartsWith("\t") && !line.StartsWith("\t\t");

            if (oneTab)
            {
                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;
            }

            // 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);
            }
        }

        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 text)
    {
        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) 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)
    {
        exitCode = -1;
        try
        {
            var psi = new ProcessStartInfo("pactl", args)
            {
                UseShellExecute        = false,
                RedirectStandardOutput = true,
                RedirectStandardError  = true,
                CreateNoWindow         = true
            };
            psi.EnvironmentVariables["LC_ALL"] = "C";   // English output, whatever the system locale
            psi.EnvironmentVariables["LANG"]   = "C";

            using (var p = Process.Start(psi))
            {
                string output = p.StandardOutput.ReadToEnd();
                string err    = p.StandardError.ReadToEnd();
                if (!p.WaitForExit(3000)) { try { p.Kill(); } catch { } return null; }
                exitCode = p.ExitCode;
                if (exitCode != 0 && err.Length > 0) Emit("pactl " + args + ": " + err.Trim());
                return output;
            }
        }
        catch (Exception ex)
        {
            Emit("pactl not runnable: " + ex.Message);
            return null;
        }
    }

    // ── 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)
    {
        var h = Log;
        if (h != null) h(m); else Console.WriteLine("[output] " + m);
    }
}