diff --git a/program/AudioEngine.cs b/program/AudioEngine.cs index 0995efb..b5ba11c 100644 --- a/program/AudioEngine.cs +++ b/program/AudioEngine.cs @@ -39,6 +39,7 @@ { _context = new AudioContext(); // opens default device + context _context.MakeCurrent(); + AudioOutput.RegisterCurrentDevice(); Emit("OpenAL ready: " + AudioContext.CurrentContext.CurrentDevice); return true; } @@ -54,6 +55,7 @@ public Voice Warm(string wavPath, string key) { + wavPath = AudioOutput.SoundFor(wavPath); // ← add: speaker copy in legacy speaker mode if (string.IsNullOrEmpty(wavPath) || !File.Exists(wavPath)) { Emit("Sound file not found: " + wavPath); diff --git a/program/AudioOutput.cs b/program/AudioOutput.cs index 1b7b642..fc189a7 100644 --- a/program/AudioOutput.cs +++ b/program/AudioOutput.cs @@ -40,9 +40,51 @@ 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%"; + /// 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 -> /speaker/.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() @@ -78,40 +120,77 @@ return Current(); } - Kind now = Classify(card.ActiveProfile); - Kind want = now == Kind.Jack ? Kind.Speaker : Kind.Jack; + Kind want = Classify(card.ActiveProfile) == Kind.Jack ? Kind.Speaker : Kind.Jack; + return SwitchTo(card, want, true, out problem); + } - // Best available profile of the wanted kind (highest priority). - Profile target = null; - foreach (var p in card.Profiles) + /// 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) { - if (p.Kind != want || p.Sinks < 1 || !p.Available) continue; - if (target == null || p.Priority > target.Priority) target = p; + 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; + } - if (target == null) + /// 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) { - if (want == Kind.Jack) + // Best available profile of the wanted kind (highest priority). + Profile target = null; + foreach (var p in card.Profiles) { - problem = "jack-empty"; - Emit("no headphone profile available - is anything plugged in?"); + if (p.Kind != want || p.Sinks < 1 || !p.Available) continue; + if (target == null || p.Priority > target.Priority) target = p; } - 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; + 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); } - 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. @@ -120,13 +199,17 @@ { 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); + string vol = want == Kind.Speaker ? SpeakerVolume : JackVolume; + Run("set-sink-volume " + Quote(sink) + " " + vol, out code); MoveAllStreams(sink); - Emit("default sink -> " + sink + " (unmuted, volume " + OutputVolume + ")"); + 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. - ReopenOpenAL(); + if (reopen) ReopenOpenAL(); + SetSpeakerMode(want == Kind.Speaker); + var changed = OutputChanged; + if (changed != null) changed(); } else { @@ -311,30 +394,99 @@ [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 _devices = new List(); + private static readonly List _contexts = new List(); + + /// 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(); + 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(); + lock (_devices) list.AddRange(_devices); 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) + if (ctx != IntPtr.Zero) { - Emit("reopen: OpenAL Soft is too old (needs 1.22+)"); - return false; + 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; } - IntPtr fp = alcGetProcAddress(dev, "alcReopenDeviceSOFT"); - if (fp == IntPtr.Zero) { Emit("reopen: function not found"); 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 on default output: " + (ok ? "ok" : "FAILED")); - return ok; + 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) { @@ -347,7 +499,8 @@ private static void Emit(string m) { + Console.WriteLine("[output] " + m); var h = Log; - if (h != null) h(m); else Console.WriteLine("[output] " + m); + if (h != null) h(m); } } \ No newline at end of file diff --git a/program/MapWindow.cs b/program/MapWindow.cs index f28a876..3a545c4 100644 --- a/program/MapWindow.cs +++ b/program/MapWindow.cs @@ -325,6 +325,7 @@ // former 再生テスト — now switches output: speaker <-> headphone jack AudioOutput.Log += m => Logger.Write("output", m); + AudioOutput.OutputChanged += OnOutputChanged; if (SoundTestButton != null) { SoundTestButton.Clicked += (s, e) => ToggleOutput(); @@ -2523,4 +2524,14 @@ foreach (var r in _regions) r.Enabled = shown; if (!shown) MuteRegions(); } + private void OnOutputChanged() + { + if (!AppMode.Legacy || _case == null) return; + LoadRegions(_case); // re-warms with the right files + var group = new List(); + foreach (var r in _regions) group.Add(r.Voice); + _sound.RestartTogether(group); + _playClock.Restart(); + UpdateAudioFromPosition(); + } } \ No newline at end of file