The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
Fix Discord ffmpeg discovery on Windows
LauraGPT9b89da23fb8d
diff --git a/plugins/platforms/discord/adapter.py b/plugins/platforms/discord/adapter.pyindex 0e613408527..8fcbcf3b8ce 100644--- a/plugins/platforms/discord/adapter.py+++ b/plugins/platforms/discord/adapter.py@@ -114,6 +114,11 @@ import sysfrom pathlib import Path as _Pathsys.path.insert(0, str(_Path(__file__).resolve().parents[3]))+try:+ from .ffmpeg_utils import resolve_ffmpeg_executable+except ImportError:+ from ffmpeg_utils import resolve_ffmpeg_executable+from gateway.config import Platform, PlatformConfigfrom gateway.platforms.helpers import MessageDeduplicator, ThreadParticipationTracker, convert_table_to_bullets@@ -780,7 +785,7 @@ class VoiceReceiver:subprocess.run([- "ffmpeg", "-y", "-loglevel", "error",+ resolve_ffmpeg_executable(), "-y", "-loglevel", "error","-f", "s16le","-ar", str(src_rate),"-ac", str(src_channels),@@ -4153,7 +4158,11 @@ class DiscordAdapter(BasePlatformAdapter):lead_ms = 0if lead_ms > 0:ffmpeg_opts["options"] = f"-af adelay={lead_ms}:all=1"- source = discord.FFmpegPCMAudio(audio_path, **ffmpeg_opts)+ source = discord.FFmpegPCMAudio(+ audio_path,+ executable=resolve_ffmpeg_executable(),+ **ffmpeg_opts,+ )source = discord.PCMVolumeTransformer(source, volume=1.0)vc.play(source, after=_after)try:diff --git a/plugins/platforms/discord/ffmpeg_utils.py b/plugins/platforms/discord/ffmpeg_utils.pynew file mode 100644index 00000000000..6e5ef844540--- /dev/null+++ b/plugins/platforms/discord/ffmpeg_utils.py@@ -0,0 +1,27 @@+"""Shared ffmpeg executable discovery for Discord voice paths."""++from __future__ import annotations++import os+import shutil+from pathlib import Path+++def resolve_ffmpeg_executable() -> str:+ """Return an ffmpeg command that also covers common Windows installs."""+ explicit = os.getenv("FFMPEG_PATH")+ if explicit and explicit.strip():+ return os.path.expandvars(os.path.expanduser(explicit.strip()))++ discovered = shutil.which("ffmpeg")+ if discovered:+ return discovered++ local_appdata = os.getenv("LOCALAPPDATA")+ if local_appdata:+ packages_dir = Path(local_appdata) / "Microsoft" / "WinGet" / "Packages"+ candidates = sorted(packages_dir.glob("Gyan.FFmpeg_*/*/bin/ffmpeg.exe"))+ if candidates:+ return str(candidates[-1])++ return "ffmpeg"diff --git a/plugins/platforms/discord/voice_mixer.py b/plugins/platforms/discord/voice_mixer.pyindex 254380a9064..f498eb6ef17 100644--- a/plugins/platforms/discord/voice_mixer.py+++ b/plugins/platforms/discord/voice_mixer.py@@ -48,6 +48,11 @@ from typing import TYPE_CHECKING, List, Optionalimport discord+try:+ from .ffmpeg_utils import resolve_ffmpeg_executable+except ImportError:+ from ffmpeg_utils import resolve_ffmpeg_executable+if TYPE_CHECKING: # numpy is an optional ("voice" extra) dep — never import at runtime top-levelimport numpy as np@@ -314,7 +319,7 @@ def decode_to_pcm(path: str, *, timeout: float = 30.0) -> Optional[bytes]:try:proc = subprocess.run([- "ffmpeg", "-y", "-loglevel", "error",+ resolve_ffmpeg_executable(), "-y", "-loglevel", "error","-i", path,"-f", "s16le","-ar", str(SAMPLE_RATE),diff --git a/tests/gateway/test_discord_voice_mixer.py b/tests/gateway/test_discord_voice_mixer.pyindex 9991785a9a3..f3db3a07737 100644--- a/tests/gateway/test_discord_voice_mixer.py+++ b/tests/gateway/test_discord_voice_mixer.py@@ -207,6 +207,45 @@ class TestPlayInVoiceChannelMixerPath:# Legacy path must NOT have been used.vc.play.assert_not_called()+ @pytest.mark.asyncio+ async def test_mixer_decode_uses_resolved_ffmpeg_executable(self, monkeypatch):+ adapter = _make_adapter()+ vc = MagicMock()+ vc.is_connected.return_value = True+ adapter._voice_clients[111] = vc++ class _Mixer:+ def __init__(self):+ self._polls = 0+ self.play_speech = MagicMock()++ @property+ def speech_active(self):+ self._polls += 1+ return self._polls <= 1++ mixer = _Mixer()+ adapter._voice_mixers[111] = mixer+ adapter._reset_voice_timeout = MagicMock()++ resolved = r"C:\tools\ffmpeg.exe"+ fake_pcm = b"\x00" * vm.FRAME_SIZE+ completed = MagicMock(returncode=0, stdout=fake_pcm, stderr=b"")+ monkeypatch.setattr(+ vm,+ "resolve_ffmpeg_executable",+ lambda: resolved,+ raising=False,+ )++ with patch("subprocess.run", return_value=completed) as run:+ ok = await adapter.play_in_voice_channel(111, "/tmp/x.mp3")++ assert ok is True+ assert run.call_args.args[0][0] == resolved+ mixer.play_speech.assert_called_once()+ vc.play.assert_not_called()+@pytest.mark.asyncioasync def test_falls_back_when_decode_fails(self):adapter = _make_adapter()diff --git a/tests/gateway/test_voice_command.py b/tests/gateway/test_voice_command.pyindex ef49c811926..cf27b238553 100644--- a/tests/gateway/test_voice_command.py+++ b/tests/gateway/test_voice_command.py@@ -1,5 +1,6 @@"""Tests for the /voice command and auto voice reply in the gateway."""+import asyncioimport importlib.utilimport jsonimport os@@ -737,6 +738,47 @@ class TestVoiceReceiver:completed = receiver.check_silence()assert len(completed) == 0+ def test_ffmpeg_resolver_finds_winget_install_when_not_on_path(self, monkeypatch, tmp_path):+ """Windows winget installs ffmpeg outside PATH; Discord voice should still find it."""+ from plugins.platforms.discord import ffmpeg_utils++ ffmpeg = (+ tmp_path+ / "Microsoft"+ / "WinGet"+ / "Packages"+ / "Gyan.FFmpeg_Microsoft.Winget.Source_8wekyb3d8bbwe"+ / "ffmpeg-7.1-full_build"+ / "bin"+ / "ffmpeg.exe"+ )+ ffmpeg.parent.mkdir(parents=True)+ ffmpeg.write_text("", encoding="utf-8")++ monkeypatch.delenv("FFMPEG_PATH", raising=False)+ monkeypatch.setenv("LOCALAPPDATA", str(tmp_path))+ monkeypatch.setattr(ffmpeg_utils.shutil, "which", lambda _cmd: None)++ assert ffmpeg_utils.resolve_ffmpeg_executable() == str(ffmpeg)++ def test_pcm_to_wav_uses_resolved_ffmpeg_executable(self, monkeypatch, tmp_path):+ """Receiver conversion should use the same resolved executable as playback."""+ from plugins.platforms.discord import adapter as discord_adapter+ from plugins.platforms.discord.adapter import VoiceReceiver++ calls = []+ monkeypatch.setattr(discord_adapter, "resolve_ffmpeg_executable", lambda: r"C:\tools\ffmpeg.exe")++ def fake_run(args, **kwargs):+ calls.append((args, kwargs))++ monkeypatch.setattr(discord_adapter.subprocess, "run", fake_run)++ VoiceReceiver.pcm_to_wav(b"\x00\x00" * 100, str(tmp_path / "out.wav"))++ assert calls+ assert calls[0][0][0] == r"C:\tools\ffmpeg.exe"+def test_stale_buffer_discarded(self):receiver = self._make_receiver()# Buffer with no user mapping and very old timestamp@@ -2210,6 +2252,28 @@ class TestPlaybackTimeout:assert hasattr(DiscordAdapter, "PLAYBACK_TIMEOUT")assert DiscordAdapter.PLAYBACK_TIMEOUT > 0+ def test_voice_playback_passes_resolved_ffmpeg_executable(self, monkeypatch):+ """discord.py playback should receive the resolved ffmpeg path via executable=."""+ from plugins.platforms.discord import adapter as discord_adapter++ adapter = self._make_discord_adapter()++ mock_vc = MagicMock()+ mock_vc.is_connected.return_value = True+ mock_vc.is_playing.return_value = False+ mock_vc.play.side_effect = lambda _source, after=None: after and after(None)+ adapter._voice_clients[111] = mock_vc+ adapter._voice_timeout_tasks[111] = MagicMock()++ monkeypatch.setattr(discord_adapter, "resolve_ffmpeg_executable", lambda: r"C:\tools\ffmpeg.exe")++ with patch("discord.FFmpegPCMAudio") as ffmpeg_audio, \+ patch("discord.PCMVolumeTransformer", side_effect=lambda source, **_kw: source):+ result = asyncio.run(adapter.play_in_voice_channel(111, "/tmp/test.mp3"))++ assert result is True+ ffmpeg_audio.assert_called_once_with("/tmp/test.mp3", executable=r"C:\tools\ffmpeg.exe")+@pytest.mark.asyncioasync def test_playback_timeout_fires(self):"""When done event is never set, playback times out gracefully."""