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;

    /// Output volume set after switching (both outputs at full level).
    public const string SpeakerVolume = "100%";
    public const string JackVolume    = "100%";

    /// Extra loudness for LEGACY mode on the tablet SPEAKER only.
    /// 1.0 = no boost, 2.0 = about +6 dB, 3.0 = about +9.5 dB, 4.0 = +12 dB.
    /// Earphones, normal mode and the PC always stay at 1.0.
    /// Raise it if legacy is still too quiet on the speaker; lower it if
    /// loud spots sound distorted.
    public const float LegacySpeakerBoost = 1.5f;

    /// True in legacy mode while the TABLET speaker is in use. Then sounds are
    /// loaded from the speaker-optimised copies (made by make_speaker_sounds.sh).
    public static bool UseSpeakerSounds { get; private set; }

    /// Raised after the output changed (button or startup), on the caller's
    /// thread. Legacy mode reloads its region sounds when this fires.
    public static event Action OutputChanged;

    /// The file to actually load for a sound:
    ///   legacy + tablet speaker  ->  <folder>/speaker/<name>.wav, if it exists
    ///   anything else            ->  the original path, unchanged
    public static string SoundFor(string wavPath)
    {
        if (!UseSpeakerSounds || string.IsNullOrEmpty(wavPath)) return wavPath;
        try
        {
            string dir  = System.IO.Path.GetDirectoryName(wavPath);
            string name = System.IO.Path.GetFileName(wavPath);
            if (dir != null && System.IO.Path.GetFileName(dir) == "speaker") return wavPath;
            string alt = System.IO.Path.Combine(dir ?? "", "speaker", name);
            return System.IO.File.Exists(alt) ? alt : wavPath;
        }
        catch { return wavPath; }
    }

    /// Records whether legacy speaker mode is on, and sets the boost to match.
    private static void SetSpeakerMode(bool onTabletSpeaker)
    {
        bool use = onTabletSpeaker && AppMode.Legacy;
        if (use != UseSpeakerSounds)
            Emit("speaker-optimised sounds: " + (use ? "ON" : "off"));
        UseSpeakerSounds = use;
        ApplyBoost(onTabletSpeaker);
    }

    /// 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 want = Classify(card.ActiveProfile) == Kind.Jack ? Kind.Speaker : Kind.Jack;
        return SwitchTo(card, want, true, out problem);
    }

    /// Call once at program start, BEFORE the audio engine is created.
    /// Uses the earphones when something is plugged in, otherwise the
    /// speaker, so OpenAL opens on the right output from the beginning.
    public static Kind SelectAtStartup()
    {
        int code;
        Run("info", out code);
        if (code != 0) return Kind.Unknown;

        Card card = FindCard();
        if (card == null) return Current();

        string problem;
        Kind got = SwitchTo(card, Kind.Jack, false, out problem);
        if (got != Kind.Jack)
        {
            Emit("startup: earphones not available, using the speaker");
            card = FindCard();
            if (card != null) got = SwitchTo(card, Kind.Speaker, false, out problem);
        }
        UseSpeakerSounds = got == Kind.Speaker && AppMode.Legacy;
        Emit("startup output: " + got + (UseSpeakerSounds ? " (speaker-optimised sounds)" : ""));
        return got;
    }

    /// Activates the profile of the wanted kind and makes its output the
    /// default (unmuted, full volume). reopen = also reconnect a running OpenAL.
    private static Kind SwitchTo(Card card, Kind want, bool reopen, out string problem)
    {
        problem = null;
        int code;
        Kind now = Classify(card.ActiveProfile);

        if (now != want)
        {
            // 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
            string vol = want == Kind.Speaker ? SpeakerVolume : JackVolume;
            Run("set-sink-volume " + Quote(sink) + " " + vol, out code);
            MoveAllStreams(sink);
            Emit("default sink -> " + sink + " (unmuted, volume " + vol + ")");

            // OpenAL is still attached to the output that was just deleted:
            // reconnect it to the new default, keeping all loaded sounds.
            if (reopen) ReopenOpenAL();
            SetSpeakerMode(want == Kind.Speaker);
            var changed = OutputChanged;
            if (changed != null) changed();
        }
        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);

    // Every OpenAL device/context the app opened. The app can have more than
    // one (the log showed two); each must be reconnected and boosted.
    private static readonly List<IntPtr> _devices  = new List<IntPtr>();
    private static readonly List<IntPtr> _contexts = new List<IntPtr>();

    /// Call right after an OpenAL context is created and made current
    /// (in AudioEngine.Init, after _context.MakeCurrent()).
    public static void RegisterCurrentDevice()
    {
        if (Environment.OSVersion.Platform != PlatformID.Unix) return;
        try
        {
            IntPtr ctx = alcGetCurrentContext();
            if (ctx == IntPtr.Zero) return;
            IntPtr dev = alcGetContextsDevice(ctx);
            if (dev == IntPtr.Zero) return;
            lock (_devices)
            {
                if (!_devices.Contains(dev))  _devices.Add(dev);
                if (!_contexts.Contains(ctx)) _contexts.Add(ctx);
            }
            Emit("registered OpenAL device #" + _devices.Count);

            // start-up: boost straight away if we are already on the speaker
            Card card = FindCard();
            SetSpeakerMode(card != null && Classify(card.ActiveProfile) == Kind.Speaker);
        }
        catch (Exception ex) { Emit("register failed: " + ex.Message); }
    }

    private const int AL_GAIN = 0x100A;
    [DllImport(OpenALLib)] private static extern byte alcMakeContextCurrent(IntPtr context);
    [DllImport(OpenALLib)] private static extern void alListenerf(int param, float value);

    /// Sets the overall (listener) gain of every registered OpenAL context.
    /// Boost only for legacy mode on the tablet speaker; 1.0 otherwise.
    /// OpenAL Soft's output limiter keeps the boosted peaks from clipping harshly.
    private static void ApplyBoost(bool onTabletSpeaker)
    {
        if (Environment.OSVersion.Platform != PlatformID.Unix) return;
        float gain = (onTabletSpeaker && AppMode.Legacy) ? LegacySpeakerBoost : 1.0f;
        try
        {
            var list = new List<IntPtr>();
            lock (_devices) list.AddRange(_contexts);
            if (list.Count == 0) return;

            IntPtr prev = alcGetCurrentContext();
            foreach (IntPtr ctx in list)
            {
                alcMakeContextCurrent(ctx);
                alListenerf(AL_GAIN, gain);
            }
            alcMakeContextCurrent(prev);           // put the app's context back
            Emit("volume boost: x" + gain + (gain > 1f ? " (legacy, speaker)" : ""));
        }
        catch (Exception ex) { Emit("boost failed: " + ex.Message); }
    }

    private static bool ReopenOpenAL()
    {
        if (Environment.OSVersion.Platform != PlatformID.Unix) return false;
        try
        {
            // registered devices, plus the current one in case nothing registered
            var list = new List<IntPtr>();
            lock (_devices) list.AddRange(_devices);
            IntPtr ctx = alcGetCurrentContext();
            if (ctx != IntPtr.Zero)
            {
                IntPtr cur = alcGetContextsDevice(ctx);
                if (cur != IntPtr.Zero && !list.Contains(cur)) list.Add(cur);
            }
            if (list.Count == 0) { Emit("reopen: no OpenAL device"); return false; }

            bool all = true;
            for (int i = 0; i < list.Count; i++)
            {
                IntPtr dev = list[i];
                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 device " + (i + 1) + "/" + list.Count + ": " + (ok ? "ok" : "FAILED"));
                all &= ok;
            }
            return all;
        }
        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)
    {
        Console.WriteLine("[output] " + m);
        var h = Log;
        if (h != null) h(m);
    }
}