using System;
using System.Collections.Generic;
using System.Diagnostics;
/// Speaker <-> headphone-jack switching through the sound server
/// (PulseAudio, or PipeWire's pulse layer), 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.
public static class AudioOutput
{
public enum Kind { Unknown, Speaker, Jack }
private class Port
{
public string Name, Desc;
public bool Unplugged; // "not available" = jack empty
public Kind Kind;
}
private class Sink
{
public string Name;
public string ActivePort;
public List<Port> Ports = new List<Port>();
}
public static event Action<string> Log;
/// What is playing sound right now.
public static Kind Current()
{
List<Sink> sinks; string def;
if (!Read(out sinks, out def)) return Kind.Unknown;
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
}
/// 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;
List<Sink> 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;
// 1) another port on the same sink (the normal laptop / tablet case)
Sink cur = sinks.Find(x => x.Name == def);
if (cur != 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);
return Current();
}
problem = want == Kind.Jack ? "no-jack" : "no-speaker";
Emit("no " + want + " output found");
return now;
}
// ── pactl ──────────────────────────────────────────────────────────
private static bool Read(out List<Sink> sinks, out string defaultSink)
{
sinks = new List<Sink>();
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 sinks", out code);
if (code != 0 || list == null) return 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 (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; }
if (inPorts)
{
// 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;
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);
}
}
return defaultSink != null;
}
private static Kind Classify(string name, string desc)
{
string s = (name + " " + desc).ToLowerInvariant();
if (s.Contains("headphone") || s.Contains("headset") || s.Contains("lineout") ||
s.Contains("line-out") || s.Contains("line out"))
return Kind.Jack;
if (s.Contains("speaker")) return Kind.Speaker;
return Kind.Unknown;
}
private static void MoveAllStreams(string sink)
{
int code;
string list = Run("list short sink-inputs", out code);
if (code != 0 || list == null) return;
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);
}
}
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;
}
}
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);
}
}