diff --git a/CHANGELOG.md b/CHANGELOG.md index bb3b746..a7ed2f0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,13 @@ releasing. is said out loud; nothing is lost. At most one quiz a minute (adjustable), never during an item challenge. Works on any server. - New settings: "Quizzes while playing" and "Time between quizzes". +- **Linux: the microphone chosen in PipeWire or PulseAudio** is the one that listens. With + "Microphone" left empty, the mod follows the system's default input, and `/langmod mics` and the + settings list the inputs by the names your desktop shows (accents don't matter when typing one). + Before, the mod only saw the raw sound cards and often listened to an input with nothing plugged + in. A "Microphone" saved from the old list (such as `PCH`) now falls back to the default: pick it + again. Names said out loud would go the same way, to the output chosen in Minecraft's sound + settings (no voices on Linux for the moment). Windows and macOS are unchanged. ## 0.2.0 diff --git a/README.md b/README.md index bc3c9ec..0a16ed4 100644 --- a/README.md +++ b/README.md @@ -232,6 +232,9 @@ also work on servers without the mod. - Windows x64, Linux x64 or macOS. On Windows: a CPU with AVX2 (Intel Core from 2013 on, any AMD Ryzen; some budget Pentium/Celeron chips lack it) and the Microsoft Visual C++ 2015-2022 runtime, which almost every gaming PC already has (otherwise: ) +- On Linux: PipeWire (with pipewire-pulse or on its own) or PulseAudio, which nearly every desktop + runs. The mod reaches them through OpenAL, the sound library that comes with Minecraft. Without + either, it falls back to the raw ALSA sound cards. - About 0.5 GB of disk space for the Whisper model (downloaded separately, see below) - For hearing names said out loud: Windows 10 or 11 with a voice for the language (see [Hearing the name](#hearing-the-name)) @@ -296,8 +299,10 @@ the `.en` ones are English only. In a world, run `/langmod test`, then say something in the language you are learning (Mandarin until you choose another one). Chat shows what Whisper heard, its pinyin or romanization and how -long it took. If nothing is detected, `/langmod mics` lists the microphones Java can -see; pick one in the settings ("Microphone"). +long it took. If nothing is detected, `/langmod mics` lists the microphones the mod can use; pick one +in the settings ("Microphone"). Left empty, it uses the system's default microphone: on Linux, the +default input chosen in PipeWire or PulseAudio (your desktop's sound settings, `pavucontrol` or +`wpctl set-default`), listed under the names they show there. ### Using it in your normal Minecraft @@ -312,7 +317,7 @@ default launcher: `%APPDATA%\.minecraft\config\langmod\models`). | Command | What it does | |---|---| | `/langmod test` | Records one utterance and prints what Whisper heard (text, pinyin or romanization, timing). | -| `/langmod mics` | Lists the microphones. | +| `/langmod mics` | Lists the microphones (on Linux, the PipeWire or PulseAudio inputs). | | `/langmod language` | Opens the menu for choosing the language to learn (also **Practice Language** in the game menu). | | `/langmod items` | Opens the items list, where items can be turned off (also **Items** in the game menu). | | `/langmod voices` | Looks for the voices installed in Windows again and lists the one that says each language's names. | @@ -360,7 +365,7 @@ screen. The file can also be edited by hand (then run `/langmod reload`). | Use GPU (`useGpu`) | on | Only used by the `server` engine. | | Whisper window (`audioContext`) | 512 = 10 s | Audio Whisper processes per answer, in 20 ms frames: `0` = its full 30 s window, `-1` = just the clip (fastest, much less accurate). See the measurements below. | | CPU threads (`whisperThreads`) | 0 = auto | Auto uses half your cores (at most 8), so the game keeps running smoothly. | -| Microphone (`micDevice`) | system default | Part of a device name from `/langmod mics`. | +| Microphone (`micDevice`) | system default | Part of a device name from `/langmod mics` (any case, accents don't matter). Empty: the system's default microphone, on Linux the default input in PipeWire or PulseAudio. | | Speech threshold (`vadThresholdDb`) | 12 | How much louder than background noise (dB) counts as speech. | | Tone colors (`toneColors`) | red, green, blue, purple, grey | Mandarin tones 1-4 and neutral, as `#RRGGBB` (shown in the settings when learning Mandarin). | | Name size (`hanziScale`) | 3 | Size of the name in the popup; long names are shrunk to fit. | @@ -507,6 +512,15 @@ popup shows when it is. Audio is recorded as 16 kHz mono and split into utteranc voice activity detector (it adapts to background noise; 0.8 s of silence ends a recording, 5 s maximum). +On Windows and macOS the microphone is opened with Java Sound. On Linux, Java Sound only sees the raw +ALSA sound cards: not PipeWire or PulseAudio, not the default input chosen there, and not a card +they are using. So on Linux the mod records through OpenAL Soft, the sound library Minecraft +already uses, which talks to PipeWire or PulseAudio. Their "Monitor of ..." inputs (which record +what is playing) are left out of the list. If OpenAL can't open a microphone, Java Sound is tried. +The log says which one was used: `Microphone open: @ 16000 Hz (OpenAL)` or `(Java Sound)`. +A voice saying a name would play the same way, on the output device chosen in Minecraft's sound +settings, in its own OpenAL context that never touches the game's sound. + Whisper gets these hints by default, chosen from the measurements below: - A **10 second window** instead of Whisper's usual 30 seconds (it always processes a fixed window, @@ -767,6 +781,12 @@ the WAV files; the runner only has English voices, and others cannot be added to "Speech threshold" if you speak quietly, raise it if background noise starts recordings. Windows must allow desktop apps to use the microphone (Settings > Privacy (& security) > Microphone > "Let desktop apps access your microphone"). +- **Linux: the wrong microphone, or none**: `/langmod mics` lists the PipeWire or PulseAudio inputs. + Leave "Microphone" empty to use the default input (change it in your desktop's sound settings, + `pavucontrol` or with `wpctl set-default`), or pick one. A "Microphone" saved by an older version + (a sound card name such as `PCH`) no longer matches: the log says so and the default is used, so + pick it again. If the log says `Microphone open: ... (Java Sound)`, OpenAL could not reach the + sound server: check that PipeWire or PulseAudio is running. - **Recordings start but are cut off**: raise `vadSilenceMs`. - **"Transcription took longer than 10 s"** (not counted as an attempt): use a smaller model (`base`), give Whisper more threads, use the `server` engine with a GPU, or as a last resort set diff --git a/src/client/java/io/github/dylantopic/langmod/client/audio/JavaSoundSource.java b/src/client/java/io/github/dylantopic/langmod/client/audio/JavaSoundSource.java new file mode 100644 index 0000000..6aedda9 --- /dev/null +++ b/src/client/java/io/github/dylantopic/langmod/client/audio/JavaSoundSource.java @@ -0,0 +1,144 @@ +package io.github.dylantopic.langmod.client.audio; + +import java.util.ArrayList; +import java.util.List; + +import javax.sound.sampled.AudioFormat; +import javax.sound.sampled.AudioSystem; +import javax.sound.sampled.DataLine; +import javax.sound.sampled.Line; +import javax.sound.sampled.LineUnavailableException; +import javax.sound.sampled.Mixer; +import javax.sound.sampled.TargetDataLine; + +import io.github.dylantopic.langmod.LangMod; +import io.github.dylantopic.langmod.core.audio.AudioDevices; + +/** A microphone through Java Sound: the system's devices on Windows and macOS, raw ALSA cards on Linux. */ +final class JavaSoundSource implements MicSource { + private static final AudioFormat[] FORMATS = { + new AudioFormat(16_000f, 16, 1, true, false), + new AudioFormat(48_000f, 16, 1, true, false), + new AudioFormat(44_100f, 16, 1, true, false), + new AudioFormat(48_000f, 16, 2, true, false), + new AudioFormat(44_100f, 16, 2, true, false), + }; + + private final TargetDataLine line; + private final String name; + + private JavaSoundSource(TargetDataLine line, String name) { + this.line = line; + this.name = name; + } + + /** @param preferred part of a device name, or empty for the system default */ + static JavaSoundSource open(String preferred) throws LineUnavailableException { + LineUnavailableException last = null; + + for (Mixer.Info mixer : candidateMixers(preferred)) { + for (AudioFormat format : FORMATS) { + DataLine.Info info = new DataLine.Info(TargetDataLine.class, format); + + try { + TargetDataLine line; + String name; + + if (mixer == null) { + if (!AudioSystem.isLineSupported(info)) { + continue; + } + + line = (TargetDataLine) AudioSystem.getLine(info); + name = "system default"; + } else { + Mixer m = AudioSystem.getMixer(mixer); + + if (!m.isLineSupported(info)) { + continue; + } + + line = (TargetDataLine) m.getLine(info); + name = mixer.getName(); + } + + // About 100 ms of buffer; we read in 20 ms chunks. + int frameBytes = format.getFrameSize(); + line.open(format, Math.max(frameBytes * (int) (format.getSampleRate() / 10), 4096)); + line.start(); + return new JavaSoundSource(line, name); + } catch (LineUnavailableException | IllegalArgumentException | SecurityException e) { + last = e instanceof LineUnavailableException lue ? lue : new LineUnavailableException(e.getMessage()); + } + } + } + + throw last != null ? last : new LineUnavailableException("No microphone found"); + } + + /** Names of all devices Java Sound can record from. */ + static List deviceNames() { + List names = new ArrayList<>(); + + for (Mixer.Info info : AudioSystem.getMixerInfo()) { + if (supportsCapture(info)) { + names.add(info.getName()); + } + } + + return names; + } + + @Override + public String name() { + return name; + } + + @Override + public int sampleRate() { + return (int) line.getFormat().getSampleRate(); + } + + @Override + public int channels() { + return line.getFormat().getChannels(); + } + + @Override + public int read(byte[] buffer) { + return line.isOpen() ? line.read(buffer, 0, buffer.length) : -1; + } + + @Override + public void close() { + line.stop(); + line.close(); + } + + private static List candidateMixers(String preferred) { + List result = new ArrayList<>(); + + if (preferred != null && !preferred.isBlank()) { + for (Mixer.Info info : AudioSystem.getMixerInfo()) { + if (AudioDevices.matches(preferred, info.getName() + " " + info.getDescription()) && supportsCapture(info)) { + result.add(info); + } + } + + if (result.isEmpty()) { + LangMod.LOGGER.warn("No microphone matching '{}' (have: {}); using the default", preferred, deviceNames()); + } + } + + result.add(null); // system default + return result; + } + + private static boolean supportsCapture(Mixer.Info info) { + try { + return AudioSystem.getMixer(info).isLineSupported(new Line.Info(TargetDataLine.class)); + } catch (RuntimeException e) { + return false; + } + } +} diff --git a/src/client/java/io/github/dylantopic/langmod/client/audio/MicCapture.java b/src/client/java/io/github/dylantopic/langmod/client/audio/MicCapture.java index db552c0..8357e6f 100644 --- a/src/client/java/io/github/dylantopic/langmod/client/audio/MicCapture.java +++ b/src/client/java/io/github/dylantopic/langmod/client/audio/MicCapture.java @@ -1,18 +1,11 @@ package io.github.dylantopic.langmod.client.audio; -import java.util.ArrayList; import java.util.List; -import java.util.Locale; -import javax.sound.sampled.AudioFormat; -import javax.sound.sampled.AudioSystem; -import javax.sound.sampled.DataLine; -import javax.sound.sampled.Line; import javax.sound.sampled.LineUnavailableException; -import javax.sound.sampled.Mixer; -import javax.sound.sampled.TargetDataLine; import io.github.dylantopic.langmod.LangMod; +import io.github.dylantopic.langmod.core.audio.AudioBackend; import io.github.dylantopic.langmod.core.audio.Resampler; import io.github.dylantopic.langmod.core.audio.Vad; @@ -39,15 +32,7 @@ default void onDiscarded() { void onError(String message); } - private static final AudioFormat[] FORMATS = { - new AudioFormat(16_000f, 16, 1, true, false), - new AudioFormat(48_000f, 16, 1, true, false), - new AudioFormat(44_100f, 16, 1, true, false), - new AudioFormat(48_000f, 16, 2, true, false), - new AudioFormat(44_100f, 16, 2, true, false), - }; - - private final TargetDataLine line; + private final MicSource source; private final String deviceName; private final Vad vad; private final Listener listener; @@ -58,9 +43,9 @@ default void onDiscarded() { private volatile float thresholdDb = -50f; private volatile boolean inSpeech; - private MicCapture(TargetDataLine line, String deviceName, Vad.Config vadConfig, Listener listener) { - this.line = line; - this.deviceName = deviceName; + private MicCapture(MicSource source, Vad.Config vadConfig, Listener listener) { + this.source = source; + this.deviceName = source.name() + " @ " + source.sampleRate() + " Hz"; this.vad = new Vad(vadConfig); this.listener = listener; this.thread = new Thread(this::run, "LangMod-Mic"); @@ -68,70 +53,56 @@ private MicCapture(TargetDataLine line, String deviceName, Vad.Config vadConfig, } /** - * Opens the microphone and starts listening. + * Opens the microphone and starts listening. On Linux this goes through OpenAL (PipeWire or + * PulseAudio) and falls back to Java Sound if that can't open anything; elsewhere it is Java + * Sound. See {@link AudioBackend}. * * @param preferredDevice part of a device name, or empty for the system default */ public static MicCapture open(String preferredDevice, Vad.Config vadConfig, Listener listener) throws LineUnavailableException { - LineUnavailableException last = null; - - for (Mixer.Info mixer : candidateMixers(preferredDevice)) { - for (AudioFormat format : FORMATS) { - DataLine.Info info = new DataLine.Info(TargetDataLine.class, format); - - try { - TargetDataLine line; - String name; - - if (mixer == null) { - if (!AudioSystem.isLineSupported(info)) { - continue; - } + AudioBackend.Opened opened; - line = (TargetDataLine) AudioSystem.getLine(info); - name = "system default"; - } else { - Mixer m = AudioSystem.getMixer(mixer); - - if (!m.isLineSupported(info)) { - continue; - } - - line = (TargetDataLine) m.getLine(info); - name = mixer.getName(); - } - - // About 100 ms of buffer; we read in 20 ms chunks. - int frameBytes = format.getFrameSize(); - line.open(format, Math.max(frameBytes * (int) (format.getSampleRate() / 10), 4096)); - line.start(); - MicCapture capture = new MicCapture(line, name + " @ " + (int) format.getSampleRate() + " Hz", vadConfig, listener); - capture.thread.start(); - LangMod.LOGGER.info("Microphone open: {}", capture.deviceName); - return capture; - } catch (LineUnavailableException | IllegalArgumentException | SecurityException e) { - last = e instanceof LineUnavailableException lue ? lue : new LineUnavailableException(e.getMessage()); - } - } + try { + opened = AudioBackend.openFirst(AudioBackend.order(), backend -> switch (backend) { + case OPENAL -> OpenAlSource.open(preferredDevice); + case JAVA_SOUND -> JavaSoundSource.open(preferredDevice); + }, (backend, e) -> LangMod.LOGGER.warn("{} could not open a microphone ({}); trying the next way", backend.label(), e.getMessage())); + } catch (LineUnavailableException e) { + throw e; + } catch (Exception e) { + throw new LineUnavailableException(e.getMessage() == null ? e.toString() : e.getMessage()); } - throw last != null ? last : new LineUnavailableException("No microphone found"); + MicCapture capture = new MicCapture(opened.value(), vadConfig, listener); + capture.thread.start(); + LangMod.LOGGER.info("Microphone open: {} ({})", capture.deviceName, opened.backend().label()); + return capture; } - /** Names of all devices Java can record from. */ + /** + * Names of the devices that can be recorded from, for /langmod mics and the settings: the sound + * server's sources on Linux (Java Sound's list if OpenAL has none), Java Sound's list elsewhere. + */ public static List deviceNames() { - List names = new ArrayList<>(); - - for (Mixer.Info info : AudioSystem.getMixerInfo()) { - if (supportsCapture(info)) { - names.add(info.getName()); + for (AudioBackend backend : AudioBackend.order()) { + try { + List names = switch (backend) { + case OPENAL -> OpenAlSource.deviceNames(); + case JAVA_SOUND -> JavaSoundSource.deviceNames(); + }; + + if (!names.isEmpty()) { + return names; + } + } catch (RuntimeException | LinkageError e) { + LangMod.LOGGER.debug("{} can't list microphones: {}", backend.label(), e.toString()); } } - return names; + return List.of(); } - /** While paused, audio is read and thrown away (the line stays open, nothing is recorded). */ + /** While paused, audio is read and thrown away (the device stays open, nothing is recorded). */ public void setPaused(boolean paused) { this.paused = paused; } @@ -157,24 +128,27 @@ public boolean inSpeech() { @Override public void close() { running = false; - line.stop(); - line.close(); + source.close(); LangMod.LOGGER.info("Microphone closed"); } private void run() { - AudioFormat format = line.getFormat(); - Resampler resampler = new Resampler((int) format.getSampleRate(), format.getChannels(), Vad.SAMPLE_RATE); - byte[] buffer = new byte[format.getFrameSize() * (int) (format.getSampleRate() / 50)]; + Resampler resampler = new Resampler(source.sampleRate(), source.channels(), Vad.SAMPLE_RATE); + // 20 ms of 16-bit audio. + byte[] buffer = new byte[2 * source.channels() * (source.sampleRate() / 50)]; float[] frame = new float[Vad.FRAME_SAMPLES]; int filled = 0; boolean wasPaused = false; try { while (running) { - int read = line.read(buffer, 0, buffer.length); + int read = source.read(buffer); - if (read <= 0) { + if (read < 0) { + break; // closed + } + + if (read == 0) { continue; } @@ -216,39 +190,9 @@ private void run() { if (running) { LangMod.LOGGER.error("Microphone failed", e); running = false; - line.close(); + source.close(); listener.onError(e.getMessage() == null ? e.toString() : e.getMessage()); } } } - - private static List candidateMixers(String preferred) { - List result = new ArrayList<>(); - String wanted = preferred == null ? "" : preferred.trim().toLowerCase(Locale.ROOT); - - if (!wanted.isEmpty()) { - for (Mixer.Info info : AudioSystem.getMixerInfo()) { - String name = (info.getName() + " " + info.getDescription()).toLowerCase(Locale.ROOT); - - if (name.contains(wanted) && supportsCapture(info)) { - result.add(info); - } - } - - if (result.isEmpty()) { - LangMod.LOGGER.warn("No microphone matching '{}' (have: {}); using the default", preferred, deviceNames()); - } - } - - result.add(null); // system default - return result; - } - - private static boolean supportsCapture(Mixer.Info info) { - try { - return AudioSystem.getMixer(info).isLineSupported(new Line.Info(TargetDataLine.class)); - } catch (RuntimeException e) { - return false; - } - } } diff --git a/src/client/java/io/github/dylantopic/langmod/client/audio/MicSource.java b/src/client/java/io/github/dylantopic/langmod/client/audio/MicSource.java new file mode 100644 index 0000000..493f327 --- /dev/null +++ b/src/client/java/io/github/dylantopic/langmod/client/audio/MicSource.java @@ -0,0 +1,25 @@ +package io.github.dylantopic.langmod.client.audio; + +/** + * An open microphone that gives 16-bit signed little-endian PCM, mono or interleaved stereo. + * {@link MicCapture} reads it on its own thread and does the rest (resampling, voice detection), so + * each way of reaching the hardware only has to open, read and close. + */ +interface MicSource { + /** The device's name, as the player would recognise it. */ + String name(); + + int sampleRate(); + + int channels(); + + /** + * Reads up to {@code buffer.length} bytes (whole frames). Waits for audio rather than spinning; + * may return 0 when nothing came, and returns -1 once closed. Throws a + * {@link RuntimeException} when the device fails (unplugged, say). + */ + int read(byte[] buffer); + + /** Releases the device. Safe to call from another thread while {@link #read} waits, and more than once. */ + void close(); +} diff --git a/src/client/java/io/github/dylantopic/langmod/client/audio/OpenAlSource.java b/src/client/java/io/github/dylantopic/langmod/client/audio/OpenAlSource.java new file mode 100644 index 0000000..536615c --- /dev/null +++ b/src/client/java/io/github/dylantopic/langmod/client/audio/OpenAlSource.java @@ -0,0 +1,171 @@ +package io.github.dylantopic.langmod.client.audio; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import javax.sound.sampled.LineUnavailableException; + +import org.lwjgl.openal.AL10; +import org.lwjgl.openal.ALC10; +import org.lwjgl.openal.ALC11; +import org.lwjgl.openal.ALUtil; +import org.lwjgl.openal.EXTDisconnect; + +import io.github.dylantopic.langmod.LangMod; +import io.github.dylantopic.langmod.core.audio.AudioDevices; +import io.github.dylantopic.langmod.core.audio.Vad; + +/** + * A microphone through OpenAL Soft, the library Minecraft already uses for its own sound. On Linux + * it goes through PipeWire or PulseAudio, so it lists the sound server's sources by the names + * the player knows and, with no name given, records from the default source chosen there. + * + *

Capture devices are separate from Minecraft's playback device and need no OpenAL context, + * so this never touches the game's sound. OpenAL Soft resamples and mixes down to 16 kHz mono + * itself, which is what the speech recogniser wants. + */ +final class OpenAlSource implements MicSource { + private static final int RATE = Vad.SAMPLE_RATE; + /** One second of audio buffered by OpenAL, far more than the capture thread ever falls behind. */ + private static final int BUFFER_SAMPLES = RATE; + /** How long to wait when less than a read's worth has arrived. */ + private static final long POLL_MILLIS = 10; + + private final Object lock = new Object(); + private final String name; + /** Whether OpenAL can tell us the microphone was unplugged (it then just stops sending audio). */ + private final boolean canTellDisconnect; + private ByteBuffer samples = ByteBuffer.allocateDirect(0); + /** 0 once closed. Only used while holding {@link #lock}, so closing can't race a read. */ + private long device; + + private OpenAlSource(long device, String name) { + this.device = device; + this.name = name; + this.canTellDisconnect = ALC10.alcIsExtensionPresent(device, "ALC_EXT_disconnect"); + } + + /** @param preferred part of a device name, or empty for the sound server's default source */ + static OpenAlSource open(String preferred) throws LineUnavailableException { + List names = allDeviceNames(); + Optional wanted = AudioDevices.find(preferred, names); + + if (preferred != null && !preferred.isBlank() && wanted.isEmpty()) { + LangMod.LOGGER.warn("No microphone matching '{}' (have: {}); using the default", preferred, AudioDevices.microphones(names)); + } + + List tries = new ArrayList<>(); + wanted.ifPresent(tries::add); + tries.add(null); // the default source + + for (String name : tries) { + long device = ALC11.alcCaptureOpenDevice(name, RATE, AL10.AL_FORMAT_MONO16, BUFFER_SAMPLES); + + if (device == 0) { + LangMod.LOGGER.debug("OpenAL could not open {}", name == null ? "the default microphone" : name); + continue; + } + + ALC11.alcCaptureStart(device); + int error = ALC10.alcGetError(device); + + if (error != ALC10.ALC_NO_ERROR) { + ALC11.alcCaptureCloseDevice(device); + LangMod.LOGGER.debug("OpenAL could not start {} (error {})", name == null ? "the default microphone" : name, error); + continue; + } + + String opened = ALC10.alcGetString(device, ALC11.ALC_CAPTURE_DEVICE_SPECIFIER); + return new OpenAlSource(device, opened == null || opened.isEmpty() ? (name == null ? "default" : name) : opened); + } + + throw new LineUnavailableException("No microphone found"); + } + + /** The microphones OpenAL can record from, without the sound server's "Monitor of ..." sources. */ + static List deviceNames() { + return AudioDevices.microphones(allDeviceNames()); + } + + private static List allDeviceNames() { + List names = ALUtil.getStringList(0, ALC11.ALC_CAPTURE_DEVICE_SPECIFIER); + return names == null ? List.of() : names; + } + + @Override + public String name() { + return name; + } + + @Override + public int sampleRate() { + return RATE; + } + + @Override + public int channels() { + return 1; + } + + @Override + public int read(byte[] buffer) { + int wanted = buffer.length / 2; + + while (true) { + synchronized (lock) { + if (device == 0) { + return -1; + } + + if (ALC10.alcGetInteger(device, ALC11.ALC_CAPTURE_SAMPLES) >= wanted) { + if (samples.capacity() < wanted * 2) { + samples = ByteBuffer.allocateDirect(wanted * 2); + } + + ALC11.alcCaptureSamples(device, samples, wanted); + samples.get(0, buffer, 0, wanted * 2); + + if (ByteOrder.nativeOrder() == ByteOrder.BIG_ENDIAN) { + swapBytes(buffer, wanted * 2); + } + + return wanted * 2; + } + + if (canTellDisconnect && ALC10.alcGetInteger(device, EXTDisconnect.ALC_CONNECTED) == 0) { + throw new IllegalStateException("The microphone was disconnected"); + } + } + + try { + Thread.sleep(POLL_MILLIS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return 0; + } + } + } + + @Override + public void close() { + synchronized (lock) { + if (device != 0) { + ALC11.alcCaptureStop(device); + ALC11.alcCaptureCloseDevice(device); + device = 0; + } + } + } + + /** OpenAL gives samples in the machine's byte order; the rest of the mod reads little endian. */ + private static void swapBytes(byte[] data, int length) { + for (int i = 0; i + 1 < length; i += 2) { + byte b = data[i]; + data[i] = data[i + 1]; + data[i + 1] = b; + } + } +} diff --git a/src/client/java/io/github/dylantopic/langmod/client/voice/JavaSoundOutput.java b/src/client/java/io/github/dylantopic/langmod/client/voice/JavaSoundOutput.java new file mode 100644 index 0000000..0bd3c95 --- /dev/null +++ b/src/client/java/io/github/dylantopic/langmod/client/voice/JavaSoundOutput.java @@ -0,0 +1,78 @@ +package io.github.dylantopic.langmod.client.voice; + +import javax.sound.sampled.AudioFormat; +import javax.sound.sampled.AudioSystem; +import javax.sound.sampled.Clip; +import javax.sound.sampled.LineEvent; +import javax.sound.sampled.LineUnavailableException; + +import io.github.dylantopic.langmod.core.audio.Wav; + +/** + * The voice through Java Sound's default output: the only way on Windows and macOS, and the + * fallback on Linux (where it reaches a raw ALSA card, not PipeWire or PulseAudio). + */ +final class JavaSoundOutput implements VoiceOutput { + private Clip clip; + + @Override + public String name() { + return "default output"; + } + + @Override + public void play(Wav.Audio audio, float volume) throws LineUnavailableException { + stop(); + AudioFormat.Encoding encoding = audio.floating() ? AudioFormat.Encoding.PCM_FLOAT + : audio.bitsPerSample() == 8 ? AudioFormat.Encoding.PCM_UNSIGNED : AudioFormat.Encoding.PCM_SIGNED; + int frameSize = audio.channels() * audio.bitsPerSample() / 8; + AudioFormat format = new AudioFormat(encoding, audio.sampleRate(), audio.bitsPerSample(), audio.channels(), frameSize, + audio.sampleRate(), false); + byte[] data = audio.bitsPerSample() == 16 && !audio.floating() ? scaled(audio.data(), volume) : audio.data(); + Clip opened = AudioSystem.getClip(); + opened.open(format, data, 0, data.length); + opened.addLineListener(event -> { + if (event.getType() == LineEvent.Type.STOP) { + event.getLine().close(); + } + }); + opened.start(); + clip = opened; + } + + @Override + public void stop() { + if (clip != null) { + clip.stop(); + clip.close(); + clip = null; + } + } + + @Override + public boolean playing() { + return clip != null && clip.isOpen() && clip.isRunning(); + } + + @Override + public void close() { + stop(); + } + + /** 16-bit little-endian samples at a lower volume. */ + private static byte[] scaled(byte[] data, float volume) { + if (volume >= 0.999f) { + return data; + } + + byte[] out = new byte[data.length]; + + for (int i = 0; i + 1 < data.length; i += 2) { + int sample = Math.round((short) ((data[i] & 0xFF) | (data[i + 1] << 8)) * volume); + out[i] = (byte) sample; + out[i + 1] = (byte) (sample >> 8); + } + + return out; + } +} diff --git a/src/client/java/io/github/dylantopic/langmod/client/voice/OpenAlOutput.java b/src/client/java/io/github/dylantopic/langmod/client/voice/OpenAlOutput.java new file mode 100644 index 0000000..791136a --- /dev/null +++ b/src/client/java/io/github/dylantopic/langmod/client/voice/OpenAlOutput.java @@ -0,0 +1,159 @@ +package io.github.dylantopic.langmod.client.voice; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.IntBuffer; +import java.nio.ShortBuffer; + +import org.lwjgl.openal.AL; +import org.lwjgl.openal.AL10; +import org.lwjgl.openal.ALC; +import org.lwjgl.openal.ALC10; +import org.lwjgl.openal.ALCCapabilities; +import org.lwjgl.openal.EXTThreadLocalContext; +import org.lwjgl.openal.EnumerateAllExt; +import org.lwjgl.system.MemoryUtil; + +import io.github.dylantopic.langmod.core.audio.Wav; + +/** + * The voice through OpenAL Soft, on Linux through PipeWire or PulseAudio, so it follows the output + * device and volume routing chosen there. + * + *

It opens its own device and context and never touches Minecraft's. Minecraft makes its + * context current for the whole process ({@code alcMakeContextCurrent}) and calls OpenAL from its + * sound thread; switching that from here would move the game's sound onto our context. So this + * context is made current only on the calling thread with {@code ALC_EXT_thread_local_context}, + * and the AL capabilities are registered for that thread only ({@code AL.createCapabilities} + * does that when a thread context is set; other threads still find Minecraft's). Every method + * must therefore be called on the thread that opened it: {@link Pronouncer}'s voice thread. + */ +final class OpenAlOutput implements VoiceOutput { + private final long device; + private final long context; + private final String name; + private final Thread owner = Thread.currentThread(); + private int source; + private int buffer; + + private OpenAlOutput(long device, long context, String name) { + this.device = device; + this.context = context; + this.name = name; + } + + /** + * Opens the output on this thread. + * + * @param preferred Minecraft's output device, or null for the system default; when it can't + * be opened the default is used + */ + static OpenAlOutput open(String preferred) throws IOException { + long device = preferred == null ? 0 : ALC10.alcOpenDevice(preferred); + + if (device == 0) { + device = ALC10.alcOpenDevice((CharSequence) null); + } + + if (device == 0) { + throw new IOException("OpenAL found no sound output"); + } + + ALCCapabilities caps = ALC.createCapabilities(device); + + if (!caps.ALC_EXT_thread_local_context) { + ALC10.alcCloseDevice(device); + throw new IOException("OpenAL can't keep a context to one thread (no ALC_EXT_thread_local_context)"); + } + + long context = ALC10.alcCreateContext(device, (IntBuffer) null); + + if (context == 0 || !EXTThreadLocalContext.alcSetThreadContext(context)) { + if (context != 0) { + ALC10.alcDestroyContext(context); + } + + ALC10.alcCloseDevice(device); + throw new IOException("OpenAL could not make a context for the voice"); + } + + AL.createCapabilities(caps); + String name = caps.ALC_ENUMERATE_ALL_EXT ? ALC10.alcGetString(device, EnumerateAllExt.ALC_ALL_DEVICES_SPECIFIER) + : ALC10.alcGetString(device, ALC10.ALC_DEVICE_SPECIFIER); + return new OpenAlOutput(device, context, name == null || name.isEmpty() ? "default output" : name); + } + + @Override + public String name() { + return name; + } + + @Override + public void play(Wav.Audio audio, float volume) throws IOException { + checkThread(); + stop(); + Wav.Audio pcm = Wav.toPcm16(audio); + // AL wants samples in the machine's byte order; the WAV is little endian. + ShortBuffer file = ByteBuffer.wrap(pcm.data()).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer(); + ShortBuffer samples = MemoryUtil.memAllocShort(file.remaining()); + + try { + samples.put(file).flip(); + buffer = AL10.alGenBuffers(); + AL10.alBufferData(buffer, pcm.channels() == 1 ? AL10.AL_FORMAT_MONO16 : AL10.AL_FORMAT_STEREO16, samples, pcm.sampleRate()); + } finally { + MemoryUtil.memFree(samples); + } + + source = AL10.alGenSources(); + AL10.alSourcei(source, AL10.AL_BUFFER, buffer); + // Right at the listener, so a mono voice comes from straight ahead. + AL10.alSourcei(source, AL10.AL_SOURCE_RELATIVE, AL10.AL_TRUE); + AL10.alSourcef(source, AL10.AL_GAIN, volume); + AL10.alSourcePlay(source); + int error = AL10.alGetError(); + + if (error != AL10.AL_NO_ERROR) { + stop(); + throw new IOException("OpenAL could not play the voice (error " + error + ")"); + } + } + + @Override + public void stop() { + checkThread(); + + if (source != 0) { + AL10.alSourceStop(source); + AL10.alDeleteSources(source); + source = 0; + } + + if (buffer != 0) { + AL10.alDeleteBuffers(buffer); + buffer = 0; + } + } + + @Override + public boolean playing() { + checkThread(); + return source != 0 && AL10.alGetSourcei(source, AL10.AL_SOURCE_STATE) == AL10.AL_PLAYING; + } + + @Override + public void close() { + stop(); + EXTThreadLocalContext.alcSetThreadContext(0); + AL.setCurrentThread(null); + ALC10.alcDestroyContext(context); + ALC10.alcCloseDevice(device); + } + + private void checkThread() { + if (Thread.currentThread() != owner) { + throw new IllegalStateException("OpenAL voice used from " + Thread.currentThread().getName() + ", opened on " + owner.getName()); + } + } +} diff --git a/src/client/java/io/github/dylantopic/langmod/client/voice/Pronouncer.java b/src/client/java/io/github/dylantopic/langmod/client/voice/Pronouncer.java index 59fba0b..aec0b5f 100644 --- a/src/client/java/io/github/dylantopic/langmod/client/voice/Pronouncer.java +++ b/src/client/java/io/github/dylantopic/langmod/client/voice/Pronouncer.java @@ -7,21 +7,17 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; -import javax.sound.sampled.AudioFormat; -import javax.sound.sampled.AudioSystem; -import javax.sound.sampled.Clip; -import javax.sound.sampled.LineEvent; -import javax.sound.sampled.LineUnavailableException; - import net.minecraft.client.Minecraft; import net.minecraft.client.Options; import net.minecraft.sounds.SoundSource; @@ -30,6 +26,7 @@ import io.github.dylantopic.langmod.LangModConfig; import io.github.dylantopic.langmod.LanguagePacks; import io.github.dylantopic.langmod.client.ClientMessages; +import io.github.dylantopic.langmod.core.audio.AudioBackend; import io.github.dylantopic.langmod.core.audio.Wav; import io.github.dylantopic.langmod.core.lang.Language; import io.github.dylantopic.langmod.core.lang.NameEntry; @@ -41,7 +38,8 @@ /** * Says item names out loud with a voice installed on the computer: after a wrong answer, when an * item is lost, on the "hear it again" key and as a preview in the settings. The sound is made and - * played on a background thread at Minecraft's Voice/Speech volume. {@link #busy()} stays true from + * played on a background thread at Minecraft's Voice/Speech volume, on the output device chosen in + * Minecraft (through OpenAL on Linux, Java Sound elsewhere; see {@link AudioBackend}). {@link #busy()} stays true from * the request until shortly after the voice stops; meanwhile the microphone is paused (so it does * not hear the voice) and the countdown waits. */ @@ -50,6 +48,8 @@ public final class Pronouncer { /** After the voice stops, the speakers' delay and the room can still carry it into the microphone. */ private static final long ECHO_MILLIS = 600; private static final int CACHE_SIZE = 64; + /** How long the output device stays open after the voice stops, so a few names in a row don't reopen it. */ + private static final long IDLE_MILLIS = 15_000; public enum Status { /** Not asked for yet. */ @@ -61,7 +61,7 @@ public enum Status { UNAVAILABLE } - private final ExecutorService worker = Executors.newSingleThreadExecutor(runnable -> { + private final ScheduledExecutorService worker = Executors.newSingleThreadScheduledExecutor(runnable -> { Thread thread = new Thread(runnable, "LangMod voice"); thread.setDaemon(true); return thread; @@ -88,7 +88,12 @@ protected boolean removeEldestEntry(Map.Entry eldest) { private TextToSpeech engine; private TextToSpeech testEngine; private boolean silent; - private Clip clip; + private VoiceOutput output; + /** The Minecraft device {@link #output} was opened for (null: the system default). */ + private String outputDevice; + /** Counts what was played, so a pending release knows whether something newer came. */ + private int plays; + private boolean loggedOutput; private boolean warnedNoSound; private Pronouncer() { @@ -182,10 +187,11 @@ public void sayText(Language language, String text) { double speed = config.voiceSpeed; String preferred = config.voiceName(language); float volume = volume(); + String device = soundDevice(); waiting.incrementAndGet(); boolean queued = run(() -> { try { - play(sound(language, text, speed, preferred), volume); + play(sound(language, text, speed, preferred), volume, device); lastSaid = text; said.incrementAndGet(); } catch (NoVoice e) { @@ -214,12 +220,12 @@ public void preview(Language language) { /** Stops the voice (leaving a world). */ public void stop() { busyUntil = System.nanoTime(); - run(this::stopClip); + run(this::stopOutput); } public void shutdown() { run(() -> { - stopClip(); + closeOutput(); if (engine != null) { engine.close(); @@ -326,9 +332,9 @@ private byte[] sound(Language language, String text, double speed, String prefer return wav; } - private void play(byte[] wav, float volume) { + private void play(byte[] wav, float volume, String device) { Wav.Audio audio = Wav.decode(wav); - stopClip(); + stopOutput(); if (volume <= 0 && !silent) { return; // Voice/Speech is turned all the way down: nothing to wait for @@ -341,22 +347,16 @@ private void play(byte[] wav, float volume) { } try { - AudioFormat.Encoding encoding = audio.floating() ? AudioFormat.Encoding.PCM_FLOAT - : audio.bitsPerSample() == 8 ? AudioFormat.Encoding.PCM_UNSIGNED : AudioFormat.Encoding.PCM_SIGNED; - int frameSize = audio.channels() * audio.bitsPerSample() / 8; - AudioFormat format = new AudioFormat(encoding, audio.sampleRate(), audio.bitsPerSample(), audio.channels(), frameSize, - audio.sampleRate(), false); - byte[] data = audio.bitsPerSample() == 16 && !audio.floating() ? scaled(audio.data(), volume) : audio.data(); - Clip opened = AudioSystem.getClip(); - opened.open(format, data, 0, data.length); - opened.addLineListener(event -> { - if (event.getType() == LineEvent.Type.STOP) { - event.getLine().close(); + openOutput(device).play(audio, volume); + int played = ++plays; + worker.schedule(() -> { + if (plays == played) { + releaseIdleOutput(); } - }); - opened.start(); - clip = opened; - } catch (LineUnavailableException | IllegalArgumentException | SecurityException e) { + }, audio.millis() + IDLE_MILLIS, TimeUnit.MILLISECONDS); + } catch (Exception e) { + closeOutput(); // opened again next time, maybe on a device that works by then + if (!warnedNoSound) { warnedNoSound = true; LangMod.LOGGER.warn("Can't play the voice: {}", e.toString()); @@ -364,29 +364,60 @@ private void play(byte[] wav, float volume) { } } - private void stopClip() { - if (clip != null) { - clip.stop(); - clip.close(); - clip = null; + /** The output for Minecraft's {@code device}, opened when first needed or when the device changed. */ + private VoiceOutput openOutput(String device) throws Exception { + if (output != null && !Objects.equals(device, outputDevice)) { + closeOutput(); } + + if (output == null) { + AudioBackend.Opened opened = AudioBackend.openFirst(AudioBackend.order(), backend -> switch (backend) { + case OPENAL -> OpenAlOutput.open(device); + case JAVA_SOUND -> new JavaSoundOutput(); + }, (backend, e) -> LangMod.LOGGER.warn("{} can't play the voice ({}); trying the next way", backend.label(), e.getMessage())); + output = opened.value(); + outputDevice = device; + + if (loggedOutput) { + LangMod.LOGGER.debug("Voice output: {} ({})", output.name(), opened.backend().label()); + } else { + loggedOutput = true; + LangMod.LOGGER.info("Voice output: {} ({})", output.name(), opened.backend().label()); + } + } + + return output; } - /** 16-bit little-endian samples at a lower volume. */ - private static byte[] scaled(byte[] data, float volume) { - if (volume >= 0.999f) { - return data; + private void stopOutput() { + if (output != null) { + output.stop(); } + } - byte[] out = new byte[data.length]; + /** Lets the device go once nothing has played for a while: the sound server then shows no LangMod stream. */ + private void releaseIdleOutput() { + if (output != null && !output.playing()) { + closeOutput(); + } + } + + private void closeOutput() { + if (output != null) { + try { + output.close(); + } catch (RuntimeException e) { + LangMod.LOGGER.debug("Closing the voice output: {}", e.toString()); + } - for (int i = 0; i + 1 < data.length; i += 2) { - int sample = Math.round((short) ((data[i] & 0xFF) | (data[i + 1] << 8)) * volume); - out[i] = (byte) sample; - out[i + 1] = (byte) (sample >> 8); + output = null; } + } - return out; + /** Minecraft's output device (Music & Sounds > Device), or null for the system default. */ + private static String soundDevice() { + String device = Minecraft.getInstance().options.soundDevice().get(); + return Options.isSoundDeviceDefault(device) ? null : device; } /** Minecraft's Master times Voice/Speech volume. */ diff --git a/src/client/java/io/github/dylantopic/langmod/client/voice/VoiceOutput.java b/src/client/java/io/github/dylantopic/langmod/client/voice/VoiceOutput.java new file mode 100644 index 0000000..f93cb3d --- /dev/null +++ b/src/client/java/io/github/dylantopic/langmod/client/voice/VoiceOutput.java @@ -0,0 +1,23 @@ +package io.github.dylantopic.langmod.client.voice; + +import io.github.dylantopic.langmod.core.audio.Wav; + +/** + * Where the voice is played. {@link Pronouncer} calls every method on its one voice thread, so an + * output may keep state tied to that thread (the OpenAL one does). + */ +interface VoiceOutput { + /** The device's name, for the log. */ + String name(); + + /** Plays the sound at {@code volume} (0 to 1), replacing whatever was playing. */ + void play(Wav.Audio audio, float volume) throws Exception; + + /** Stops the sound; the device stays open. */ + void stop(); + + boolean playing(); + + /** Releases the device. */ + void close(); +} diff --git a/src/main/java/io/github/dylantopic/langmod/core/audio/AudioBackend.java b/src/main/java/io/github/dylantopic/langmod/core/audio/AudioBackend.java new file mode 100644 index 0000000..5104bac --- /dev/null +++ b/src/main/java/io/github/dylantopic/langmod/core/audio/AudioBackend.java @@ -0,0 +1,79 @@ +package io.github.dylantopic.langmod.core.audio; + +import java.util.List; +import java.util.Locale; +import java.util.function.BiConsumer; + +/** + * How the mod reaches the sound hardware. + * + *

On Linux, Java Sound only talks to raw ALSA cards: it does not see PipeWire or PulseAudio, + * so it ignores the default microphone chosen there and can only open a card the sound server is + * not using at that moment (then holding it so nothing else can). OpenAL Soft, which Minecraft + * ships for its own sound, goes through PipeWire or PulseAudio, so it is tried first there. On + * Windows and macOS Java Sound already uses the system's devices and stays the only path. + */ +public enum AudioBackend { + OPENAL("OpenAL"), + JAVA_SOUND("Java Sound"); + + private final String label; + + AudioBackend(String label) { + this.label = label; + } + + /** The name used in the log. */ + public String label() { + return label; + } + + /** The backends to try, in order, on the system called {@code osName} (as in {@code os.name}). */ + public static List order(String osName) { + boolean linux = osName != null && osName.toLowerCase(Locale.ROOT).startsWith("linux"); + return linux ? List.of(OPENAL, JAVA_SOUND) : List.of(JAVA_SOUND); + } + + /** The backends to try on this computer. */ + public static List order() { + return order(System.getProperty("os.name")); + } + + /** Opens a device with one backend. */ + public interface Opener { + T open(AudioBackend backend) throws Exception; + } + + /** What {@link #openFirst} opened, and with which backend. */ + public record Opened(AudioBackend backend, T value) { + } + + /** + * Opens with the first backend in {@code order} that works. A backend whose native library is + * missing counts as one that failed. {@code onFailure} hears about each failure that has another + * backend after it; when they all fail, the last failure is thrown, so the player sees the + * reason the last resort gave (with one backend, the same message as before there was a choice). + */ + public static Opened openFirst(List order, Opener opener, BiConsumer onFailure) + throws Exception { + Exception last = new IllegalStateException("No sound backend to try"); + + for (int i = 0; i < order.size(); i++) { + AudioBackend backend = order.get(i); + + try { + return new Opened<>(backend, opener.open(backend)); + } catch (Exception e) { + last = e; + } catch (LinkageError e) { + last = new IllegalStateException(backend.label() + " is not available: " + e, e); + } + + if (i + 1 < order.size()) { + onFailure.accept(backend, last); + } + } + + throw last; + } +} diff --git a/src/main/java/io/github/dylantopic/langmod/core/audio/AudioDevices.java b/src/main/java/io/github/dylantopic/langmod/core/audio/AudioDevices.java new file mode 100644 index 0000000..0a7ca1e --- /dev/null +++ b/src/main/java/io/github/dylantopic/langmod/core/audio/AudioDevices.java @@ -0,0 +1,94 @@ +package io.github.dylantopic.langmod.core.audio; + +import java.text.Normalizer; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.Optional; + +/** + * Picking a sound device by the name the player typed or chose. The rule has always been "part of + * the name, any case"; accents are ignored too, so "bjorn" finds "Bjørn Studio Mic Mono". + */ +public final class AudioDevices { + private AudioDevices() { + } + + /** + * Whether a capture device only records what another device plays. PipeWire and PulseAudio + * offer one "Monitor of ..." source per output; they are no use as a microphone and would let + * the game hear itself. The name is the sound server's description, which can be translated, + * so on some systems a monitor still shows up: an extra entry, nothing worse. + */ + public static boolean isMonitor(String name) { + return name.regionMatches(true, 0, "Monitor of ", 0, "Monitor of ".length()); + } + + /** The names worth offering as a microphone, in the order given. */ + public static List microphones(List names) { + List result = new ArrayList<>(); + + for (String name : names) { + if (!isMonitor(name)) { + result.add(name); + } + } + + return result; + } + + /** Whether {@code text} contains {@code wanted}, ignoring case and accents. */ + public static boolean matches(String wanted, String text) { + String key = fold(wanted); + return !key.isEmpty() && fold(text).contains(key); + } + + /** + * The device {@code preferred} names, from {@code names}. Empty when nothing is asked for (use + * the default) or nothing matches. Microphones win over monitors, so "Bjørn" means the + * microphone, not "Monitor of Bjørn Studio Mic Analog Stereo"; a monitor is only chosen when + * nothing else matches. + */ + public static Optional find(String preferred, List names) { + if (preferred == null || fold(preferred).isEmpty()) { + return Optional.empty(); + } + + String monitor = null; + + for (String name : names) { + if (matches(preferred, name)) { + if (!isMonitor(name)) { + return Optional.of(name); + } + + if (monitor == null) { + monitor = name; + } + } + } + + return Optional.ofNullable(monitor); + } + + /** Lower case without accents; letters that don't decompose (ø, æ, ß, ł, đ) are spelled out. */ + static String fold(String text) { + String plain = Normalizer.normalize(text.trim(), Normalizer.Form.NFD).replaceAll("\\p{M}+", "").toLowerCase(Locale.ROOT); + StringBuilder out = new StringBuilder(plain.length()); + + for (int i = 0; i < plain.length(); i++) { + char c = plain.charAt(i); + + switch (c) { + case 'ø' -> out.append('o'); + case 'æ' -> out.append("ae"); + case 'ß' -> out.append("ss"); + case 'ł' -> out.append('l'); + case 'đ' -> out.append('d'); + default -> out.append(c); + } + } + + return out.toString(); + } +} diff --git a/src/main/java/io/github/dylantopic/langmod/core/audio/Wav.java b/src/main/java/io/github/dylantopic/langmod/core/audio/Wav.java index 5c3dffd..7ff7834 100644 --- a/src/main/java/io/github/dylantopic/langmod/core/audio/Wav.java +++ b/src/main/java/io/github/dylantopic/langmod/core/audio/Wav.java @@ -29,6 +29,62 @@ public long millis() { private Wav() { } + /** + * The same sound as 16-bit signed samples in one or two channels: what every OpenAL can play + * without extensions. 8-, 24- and 32-bit and float samples are converted; more than two channels + * are mixed down to mono. Returns {@code audio} itself when it already fits. + */ + public static Audio toPcm16(Audio audio) { + int inChannels = audio.channels(); + + if (audio.bitsPerSample() == 16 && !audio.floating() && inChannels <= 2) { + return audio; + } + + int bytes = audio.bitsPerSample() / 8; + int outChannels = inChannels <= 2 ? inChannels : 1; + int frames = bytes <= 0 || inChannels <= 0 ? 0 : audio.data().length / (bytes * inChannels); + ByteBuffer in = ByteBuffer.wrap(audio.data()).order(ByteOrder.LITTLE_ENDIAN); + byte[] out = new byte[frames * outChannels * 2]; + + for (int f = 0; f < frames; f++) { + for (int c = 0; c < outChannels; c++) { + float value; + + if (outChannels == inChannels) { + value = sample(in, (f * inChannels + c) * bytes, audio); + } else { + value = 0; + + for (int k = 0; k < inChannels; k++) { + value += sample(in, (f * inChannels + k) * bytes, audio); + } + + value /= inChannels; + } + + int scaled = Math.round(Math.max(-1f, Math.min(1f, value)) * 32767f); + int at = (f * outChannels + c) * 2; + out[at] = (byte) scaled; + out[at + 1] = (byte) (scaled >> 8); + } + } + + return new Audio(audio.sampleRate(), outChannels, 16, false, out); + } + + /** One sample in [-1, 1]. */ + private static float sample(ByteBuffer in, int at, Audio audio) { + return switch (audio.bitsPerSample()) { + case 8 -> ((in.get(at) & 0xFF) - 128) / 128f; + case 16 -> in.getShort(at) / 32768f; + case 24 -> ((in.get(at) & 0xFF) | (in.get(at + 1) & 0xFF) << 8 | in.get(at + 2) << 16) / 8_388_608f; + case 32 -> audio.floating() ? in.getFloat(at) : in.getInt(at) / 2_147_483_648f; + case 64 -> audio.floating() ? (float) in.getDouble(at) : (float) (in.getLong(at) / 9.223372036854775807E18); + default -> throw new IllegalArgumentException("unsupported sample size: " + audio.bitsPerSample() + " bits"); + }; + } + /** Reads a RIFF/WAVE file with PCM samples (plain, float or WAVE_FORMAT_EXTENSIBLE). */ public static Audio decode(byte[] file) { ByteBuffer buffer = ByteBuffer.wrap(file).order(ByteOrder.LITTLE_ENDIAN); diff --git a/src/test/java/io/github/dylantopic/langmod/core/audio/AudioDevicesTest.java b/src/test/java/io/github/dylantopic/langmod/core/audio/AudioDevicesTest.java new file mode 100644 index 0000000..54e3ee2 --- /dev/null +++ b/src/test/java/io/github/dylantopic/langmod/core/audio/AudioDevicesTest.java @@ -0,0 +1,115 @@ +package io.github.dylantopic.langmod.core.audio; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import org.junit.jupiter.api.Test; + +class AudioDevicesTest { + /** What OpenAL lists on a PipeWire system with a USB microphone, USB headphones and onboard sound. */ + private static final List PIPEWIRE = List.of( + "Monitor of Bjørn Studio Mic Analog Stereo", + "Bjørn Studio Mic Mono", + "Monitor of USB Headphones Analog Stereo", + "Built-in Audio Analog Stereo", + "Monitor of Built-in Audio Digital Stereo (IEC958)"); + + @Test + void hidesMonitors() { + assertEquals(List.of("Bjørn Studio Mic Mono", "Built-in Audio Analog Stereo"), AudioDevices.microphones(PIPEWIRE)); + assertTrue(AudioDevices.isMonitor("monitor of something")); + assertFalse(AudioDevices.isMonitor("Studio Monitor Mic")); + } + + @Test + void emptyMeansTheDefault() { + assertEquals(Optional.empty(), AudioDevices.find("", PIPEWIRE)); + assertEquals(Optional.empty(), AudioDevices.find(" ", PIPEWIRE)); + assertEquals(Optional.empty(), AudioDevices.find(null, PIPEWIRE)); + } + + @Test + void partOfTheNameInAnyCaseOrAccent() { + assertEquals(Optional.of("Bjørn Studio Mic Mono"), AudioDevices.find("Bjørn", PIPEWIRE)); + assertEquals(Optional.of("Bjørn Studio Mic Mono"), AudioDevices.find("bjørn", PIPEWIRE)); + assertEquals(Optional.of("Bjørn Studio Mic Mono"), AudioDevices.find("bjorn studio", PIPEWIRE)); + assertEquals(Optional.of("Built-in Audio Analog Stereo"), AudioDevices.find(" built-in ", PIPEWIRE)); + assertTrue(AudioDevices.matches("Mikrofon", "Mikrofón (USB)")); + } + + @Test + void aMicrophoneWinsOverAMonitorButAMonitorCanBeAsked() { + // "Monitor of Bjørn ..." comes first in the list, but the microphone is meant. + assertEquals(Optional.of("Bjørn Studio Mic Mono"), AudioDevices.find("Studio Mic", PIPEWIRE)); + assertEquals(Optional.of("Monitor of USB Headphones Analog Stereo"), AudioDevices.find("Headphones", PIPEWIRE)); + } + + @Test + void noMatchFallsBackToTheDefault() { + // Names saved from Java Sound's ALSA list ("PCH", "plughw:1,0") don't name a PipeWire source. + assertEquals(Optional.empty(), AudioDevices.find("PCH", PIPEWIRE)); + assertEquals(Optional.empty(), AudioDevices.find("plughw:1,0", PIPEWIRE)); + assertEquals(Optional.empty(), AudioDevices.find("Bjørn", List.of())); + } + + @Test + void backendOrder() { + assertEquals(List.of(AudioBackend.OPENAL, AudioBackend.JAVA_SOUND), AudioBackend.order("Linux")); + assertEquals(List.of(AudioBackend.JAVA_SOUND), AudioBackend.order("Windows 11")); + assertEquals(List.of(AudioBackend.JAVA_SOUND), AudioBackend.order("Mac OS X")); + assertEquals(List.of(AudioBackend.JAVA_SOUND), AudioBackend.order("FreeBSD")); + assertEquals(List.of(AudioBackend.JAVA_SOUND), AudioBackend.order(null)); + } + + @Test + void theFirstBackendThatOpensIsUsed() throws Exception { + List failed = new ArrayList<>(); + AudioBackend.Opened opened = AudioBackend.openFirst(AudioBackend.order("Linux"), backend -> backend.label() + " mic", + (backend, e) -> failed.add(backend)); + assertEquals(AudioBackend.OPENAL, opened.backend()); + assertEquals("OpenAL mic", opened.value()); + assertEquals(List.of(), failed); + } + + @Test + void fallsBackWhenOpenAlFailsOrIsMissing() throws Exception { + for (RuntimeException problem : List.of(new IllegalStateException("no device"), new RuntimeException(new UnsatisfiedLinkError("libopenal.so")))) { + List failed = new ArrayList<>(); + AudioBackend.Opened opened = AudioBackend.openFirst(AudioBackend.order("Linux"), backend -> { + if (backend == AudioBackend.OPENAL) { + throw problem; + } + + return "line"; + }, (backend, e) -> failed.add(backend)); + assertEquals(AudioBackend.JAVA_SOUND, opened.backend()); + assertEquals(List.of(AudioBackend.OPENAL), failed); + } + + // A missing native library is a LinkageError, not an Exception. + AudioBackend.Opened opened = AudioBackend.openFirst(AudioBackend.order("Linux"), backend -> { + if (backend == AudioBackend.OPENAL) { + throw new UnsatisfiedLinkError("libopenal.so"); + } + + return "line"; + }, (backend, e) -> assertTrue(e.getMessage().contains("OpenAL is not available"), e.getMessage())); + assertEquals(AudioBackend.JAVA_SOUND, opened.backend()); + } + + @Test + void whenEverythingFailsTheLastReasonIsThrown() { + List failed = new ArrayList<>(); + Exception thrown = assertThrows(Exception.class, () -> AudioBackend.openFirst(AudioBackend.order("Linux"), backend -> { + throw new Exception(backend.label() + ": no microphone"); + }, (backend, e) -> failed.add(backend))); + assertEquals("Java Sound: no microphone", thrown.getMessage()); + assertEquals(List.of(AudioBackend.OPENAL), failed); // the last one isn't reported twice + } +} diff --git a/src/test/java/io/github/dylantopic/langmod/core/audio/WavConversionTest.java b/src/test/java/io/github/dylantopic/langmod/core/audio/WavConversionTest.java new file mode 100644 index 0000000..818d9bc --- /dev/null +++ b/src/test/java/io/github/dylantopic/langmod/core/audio/WavConversionTest.java @@ -0,0 +1,75 @@ +package io.github.dylantopic.langmod.core.audio; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +import org.junit.jupiter.api.Test; + +class WavConversionTest { + @Test + void sixteenBitMonoAndStereoAreKept() { + Wav.Audio mono = new Wav.Audio(22_050, 1, 16, false, new byte[] { 1, 2, 3, 4 }); + Wav.Audio stereo = new Wav.Audio(22_050, 2, 16, false, new byte[] { 1, 2, 3, 4 }); + assertSame(mono, Wav.toPcm16(mono)); + assertSame(stereo, Wav.toPcm16(stereo)); + } + + @Test + void eightBitUnsigned() { + // 128 is silence, 0 the bottom, 255 nearly the top. + Wav.Audio audio = Wav.toPcm16(new Wav.Audio(8_000, 1, 8, false, new byte[] { (byte) 128, 0, (byte) 255 })); + assertEquals(16, audio.bitsPerSample()); + assertArrayEquals(new short[] { 0, -32767, 32511 }, samples(audio)); + } + + @Test + void twentyFourAndThirtyTwoBit() { + ByteBuffer pcm24 = ByteBuffer.allocate(6).order(ByteOrder.LITTLE_ENDIAN); + pcm24.put(new byte[] { 0, 0, 0x40 }); // +0.5 + pcm24.put(new byte[] { 0, 0, (byte) 0xC0 }); // -0.5 + assertArrayEquals(new short[] { 16384, -16383 }, samples(Wav.toPcm16(new Wav.Audio(16_000, 1, 24, false, pcm24.array())))); + + ByteBuffer pcm32 = ByteBuffer.allocate(8).order(ByteOrder.LITTLE_ENDIAN).putInt(Integer.MAX_VALUE).putInt(Integer.MIN_VALUE); + assertArrayEquals(new short[] { 32767, -32767 }, samples(Wav.toPcm16(new Wav.Audio(16_000, 1, 32, false, pcm32.array())))); + } + + @Test + void floatIsClipped() { + ByteBuffer data = ByteBuffer.allocate(12).order(ByteOrder.LITTLE_ENDIAN).putFloat(0.25f).putFloat(1.5f).putFloat(-2f); + Wav.Audio audio = Wav.toPcm16(new Wav.Audio(24_000, 1, 32, true, data.array())); + assertEquals(24_000, audio.sampleRate()); + assertArrayEquals(new short[] { 8192, 32767, -32767 }, samples(audio)); + } + + @Test + void moreThanTwoChannelsAreMixedToMono() { + // Two frames of four channels. + Wav.Audio audio = Wav.toPcm16(new Wav.Audio(48_000, 4, 32, true, ByteBuffer.allocate(32).order(ByteOrder.LITTLE_ENDIAN) + .putFloat(0.5f).putFloat(0.5f).putFloat(0f).putFloat(0f) + .putFloat(1f).putFloat(1f).putFloat(1f).putFloat(1f).array())); + assertEquals(1, audio.channels()); + assertArrayEquals(new short[] { 8192, 32767 }, samples(audio)); + assertEquals(audio.millis(), new Wav.Audio(48_000, 4, 32, true, new byte[32]).millis()); + } + + @Test + void oddSampleSizesAreRefused() { + assertThrows(IllegalArgumentException.class, () -> Wav.toPcm16(new Wav.Audio(16_000, 1, 40, false, new byte[10]))); + } + + private static short[] samples(Wav.Audio audio) { + ByteBuffer data = ByteBuffer.wrap(audio.data()).order(ByteOrder.LITTLE_ENDIAN); + short[] out = new short[audio.data().length / 2]; + + for (int i = 0; i < out.length; i++) { + out[i] = data.getShort(i * 2); + } + + return out; + } +}