Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
55 commits
Select commit Hold shift + click to select a range
5a95f98
fix(voice): implement DAVE E2E decryption for voice reception
vito1317 Mar 17, 2026
c9e40d9
feat: Fixes and typesafe discord/voice
Paillat-dev Mar 19, 2026
58518f0
fix: TypeVar ParamSpec
Paillat-dev Mar 19, 2026
fee38b7
chore: Move BytesIO import to the top
Paillat-dev Mar 19, 2026
6caf18f
fix: Better exception catch
Paillat-dev Mar 19, 2026
203a691
fix: Stage channels don't have DAVE
Paillat-dev Mar 19, 2026
fd339e6
fix: Problem
Paillat-dev Mar 19, 2026
884cdc9
chore: Better logging and comments
Paillat-dev Mar 23, 2026
63b6d6a
chore: Minimize WaveSink changes
Paillat-dev Mar 23, 2026
9bb2930
Merge branch 'master' into fix/voice-rec-2
Paillat-dev Mar 23, 2026
e0130cb
style(pre-commit): auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Mar 23, 2026
ce9fbdc
Merge branch 'master' into fix/voice-rec-2
Paillat-dev Mar 24, 2026
923cd8a
Update discord/voice/client.py
Paillat-dev Mar 24, 2026
ec08647
fix(voice): fall back to OPUS_SILENCE when DAVE brute-force uid looku…
orarange Mar 24, 2026
28f404b
fix: Change `HAS_NACL` to `has_nacl` in voice client imports
Paillat-dev Mar 24, 2026
9bf8826
Merge branch 'master' into fix/voice-rec-2
Paillat-dev Mar 24, 2026
757c5ce
docs: CHANGELOG.md
Paillat-dev Mar 24, 2026
7889ca3
Merge branch 'master' into fix/voice-rec-2
Paillat-dev Mar 27, 2026
8dff186
fix: Actually mb that doesn't exist
Paillat-dev Apr 7, 2026
7b2cbea
fix: use client._ssrc_to_id for ssrc_user_map retrieval
Paillat-dev Apr 7, 2026
c48341e
fix: Use PLC instead of silence when buggy packets arrive
Paillat-dev Apr 7, 2026
bdba6a4
feat: Gracefully handle OpusError s
Paillat-dev Apr 7, 2026
1a4e767
fix: Set passthrough 120 bc that's what davey usage docs suggest
Paillat-dev Apr 7, 2026
dda3098
style(pre-commit): auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Apr 7, 2026
374e7f2
fix: Undo VoiceClient Deprecations
Paillat-dev Apr 7, 2026
42cd1b4
Merge branch 'master' into fix/voice-rec-2
Paillat-dev Apr 7, 2026
a61fdc9
fix: Bunch of small fixes and misc stuff
Paillat-dev May 10, 2026
4faa417
Merge branch 'master' into fix/voice-rec-2
Paillat-dev May 22, 2026
fa9282f
fix: Michael fixes and stuff
Paillat-dev May 22, 2026
13a7e16
chore: Tests
Paillat-dev May 22, 2026
54f60aa
Update examples/audio_recording.py
Paillat-dev Jun 8, 2026
39c9ce4
fix: Don't bruteforce and whatever
Paillat-dev Jun 8, 2026
b346fcd
style(pre-commit): auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Jun 8, 2026
820460a
chore: Invert condition to be more readable
Paillat-dev Jun 8, 2026
05cf65f
Merge branch 'master' into fix/voice-rec-2
Paillat-dev Jun 15, 2026
326b72a
Merge branch 'master' into fix/voice-rec-2
Paillat-dev Jul 22, 2026
0204360
Merge branch 'master' into fix/voice-rec-2
Lulalaby Aug 29, 2026
cb46392
style(pre-commit): auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Aug 29, 2026
f53d394
Merge branch 'master' into fix/voice-rec-2
Paillat-dev Sep 2, 2026
10a5e8c
Merge branch 'master' into fix/voice-rec-2
Paillat-dev Sep 5, 2026
6b70727
Merge branch 'master' into fix/voice-rec-2
Paillat-dev Nov 11, 2026
e5c5343
Update discord/voice/receive/reader.py
Paillat-dev Nov 11, 2026
ce4eeda
fix: Pin davey<0.2.0
Paillat-dev Nov 11, 2026
d3e65e2
fix: Add voice to included packages
Paillat-dev Nov 11, 2026
25f5ae3
Merge branch 'master' into fix/voice-rec-2
Paillat-dev Nov 11, 2026
fb832b2
Merge branch 'master' into fix/voice-rec-2
Paillat-dev Nov 16, 2026
07f908e
Merge branch 'master' into fix/voice-rec-2
Paillat-dev Nov 17, 2026
2b5886c
chore: Remove dead code
Paillat-dev Nov 17, 2026
e05393f
chore: Better imports management in voice
Paillat-dev Nov 17, 2026
41eab49
Update discord/voice/client.py
Paillat-dev Nov 17, 2026
5decfa3
Update discord/voice/client.py
Paillat-dev Nov 17, 2026
6e9714b
fix: Threadsafe Future and logging
Paillat-dev Nov 17, 2026
d19f25d
style(pre-commit): auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Nov 17, 2026
191335e
fix: After callback *args typing
Paillat-dev Nov 17, 2026
dbfa290
re-run docs
Paillat-dev Nov 17, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,9 @@ These changes are available on the `master` branch, but have not yet been releas

### Changed

- Added support for Discord DAVE (Audio & Video E2EE) for voice-receive related features
and refactored the voice-reception system.
([#3159](https://github.com/Pycord-Development/pycord/pull/3159))
- Simplify and optimize the `utils.get()` function.
([#3283](https://github.com/Pycord-Development/pycord/pull/3283))
- Changed `Label.set_radio_group()` and `Label.set_file_upload()` to no longer accept a
Expand Down
75 changes: 16 additions & 59 deletions discord/opus.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,21 +36,16 @@
from collections.abc import Callable
from typing import TYPE_CHECKING, Any, Literal, TypedDict, TypeVar

try:
import davey

HAS_DAVEY = True
except ImportError:
HAS_DAVEY = False

from .errors import DiscordException

if TYPE_CHECKING:
import davey

from discord.member import Member
from discord.sinks.core import Sink
from discord.user import User
from discord.voice.client import VoiceClient
from discord.voice.packets import FakePacket, VoiceData
from discord.voice.packets import VoiceData
from discord.voice.packets.core import Packet
from discord.voice.receive.router import PacketRouter

Expand Down Expand Up @@ -601,7 +596,7 @@ def _get_cached_member(self) -> User | Member | None:
return self._get_user(self._cached_id) if self._cached_id else None

def _flag_ready_state(self) -> None:
if self._buffer.peek():
if self._buffer.is_ready():
self.router.waiter.register(self)
else:
self.router.waiter.unregister(self)
Expand All @@ -610,6 +605,9 @@ def push_packet(self, packet: Packet) -> None:
self._buffer.push(packet)
self._flag_ready_state()

def process_packet(self, packet: Packet) -> VoiceData:
return self._process_packet(packet)

def pop_data(self, *, timeout: float = 0) -> VoiceData | None:
packet = self._get_next_packet(timeout)
self._flag_ready_state()
Expand All @@ -633,31 +631,7 @@ def destroy(self) -> None:
self._flag_ready_state()

def _get_next_packet(self, timeout: float) -> Packet | None:
packet = self._buffer.pop(timeout=timeout)

if packet is None:
if self._buffer:
packets = self._buffer.flush()
if any(packets[1:]):
_log.warning(
"%s packets were lost being flushed in decoder-%s",
len(packets) - 1,
self.ssrc,
)
return packets[0]
return
elif not packet:
_log.debug("Making fake packet")
packet = self._make_fakepacket()
return packet

def _make_fakepacket(self) -> FakePacket:
from discord.voice.packets import FakePacket
from discord.voice.utils.wrapped import add_wrapped

seq = add_wrapped(self._last_seq, 1)
ts = add_wrapped(self._last_ts, Decoder.SAMPLES_PER_FRAME, wrap=2**32)
return FakePacket(self.ssrc, seq, ts)
return self._buffer.pop(timeout=timeout)

def _process_packet(self, packet: Packet) -> VoiceData:
_log.debug("Processing packet %s", packet)
Expand Down Expand Up @@ -704,31 +678,14 @@ def _decode_packet(self, packet: Packet) -> tuple[Packet, bytes]:
packet.decrypted_data is not None,
)

# personally, the best variable
other_code = True

if packet:
other_code = False
try:
pcm = self._decoder.decode(packet.decrypted_data, fec=False)

if other_code:
next_packet = self._buffer.peek_next()

if next_packet is not None:
nextdata: bytes = next_packet.decrypted_data # type: ignore

_log.debug(
"Generating fec packet: fake=%s, fec=%s",
packet.sequence,
next_packet.sequence,
)
pcm = self._decoder.decode(nextdata, fec=True)
else:
pcm = self._decoder.decode(None, fec=False)

if HAS_DAVEY:
if user_id is not None and in_dave and dave.can_passthrough(user_id):
_log.debug("User ID %s can passthrough, decrypting with DAVE", user_id)
pcm = dave.decrypt(user_id, davey.MediaType.audio, pcm)
except OpusError:
_log.warning(
"Opus decode failed for packet seq=%s, using PLC",
packet.sequence,
exc_info=True,
)
pcm = self._decoder.decode(None, fec=False)

return packet, pcm
7 changes: 5 additions & 2 deletions discord/player.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@
from .oggparse import OggStream
from .opus import OPUS_SILENCE
from .opus import Encoder as OpusEncoder
from .utils import MISSING
from .utils import MISSING, log_future_exception

if TYPE_CHECKING:
from typing_extensions import Self
Expand Down Expand Up @@ -928,9 +928,12 @@ def set_source(self, source: AudioSource) -> None:

def _speak(self, speaking: SpeakingState) -> None:
try:
asyncio.run_coroutine_threadsafe(
future = asyncio.run_coroutine_threadsafe(
self.client.ws.speak(speaking), self.client.client.loop
)
log_future_exception(
future, log=_log, message="Speaking call in player failed"
)
except Exception as exc:
_log.exception("Speaking call in player failed", exc_info=exc)

Expand Down
31 changes: 28 additions & 3 deletions discord/sinks/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,10 @@
from .errors import SinkException

if TYPE_CHECKING:
from ..member import Member
from ..user import User
from ..voice import VoiceClient
from ..voice.packets import VoiceData

__all__ = (
"Filters",
Expand Down Expand Up @@ -210,6 +213,8 @@ class Sink(Filters):
Audio may only be formatted after recording is finished.
"""

__sink_listeners__: list[tuple[str, str]] = []

def __init__(self, *, filters=None):
if filters is None:
filters = default_filters
Expand All @@ -222,18 +227,38 @@ def __init__(self, *, filters=None):
def client(self) -> VoiceClient | None:
return self.vc

@property
def recording(self) -> bool:
"""Whether the voice client is currently recording."""
return self.vc is not None and self.vc.is_recording()

def is_opus(self) -> bool:
"""Whether this sink accepts raw opus packets instead of decoded PCM."""
return False

def walk_children(self):
"""Yields child sinks. Base implementation yields nothing."""
return
yield # make it a generator

def init(self, vc: VoiceClient): # called under listen
self.vc = vc
super().init()

@Filters.container
def write(self, data, user):
def write(self, data: VoiceData | bytes, user: User | Member | None) -> None:
from ..voice.packets import VoiceData

if isinstance(data, VoiceData):
pcm_data = data.pcm
else:
pcm_data = data

if user not in self.audio_data:
file = io.BytesIO()
self.audio_data.update({user: AudioData(file)})

file = self.audio_data[user]
file.write(data)
self.audio_data[user].write(pcm_data)

def cleanup(self):
self.finished = True
Expand Down
2 changes: 1 addition & 1 deletion discord/sinks/m4a.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ def format_audio(self, audio):
M4ASinkError
Formatting the audio failed.
"""
if self.vc.recording:
if self.recording:
raise M4ASinkError(
"Audio may only be formatted after recording is finished."
)
Expand Down
2 changes: 1 addition & 1 deletion discord/sinks/mka.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ def format_audio(self, audio):
MKASinkError
Formatting the audio failed.
"""
if self.vc.recording:
if self.recording:
raise MKASinkError(
"Audio may only be formatted after recording is finished."
)
Expand Down
2 changes: 1 addition & 1 deletion discord/sinks/mkv.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ def format_audio(self, audio):
MKVSinkError
Formatting the audio failed.
"""
if self.vc.recording:
if self.recording:
raise MKVSinkError(
"Audio may only be formatted after recording is finished."
)
Expand Down
2 changes: 1 addition & 1 deletion discord/sinks/mp3.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ def format_audio(self, audio):
MP3SinkError
Formatting the audio failed.
"""
if self.vc.recording:
if self.recording:
raise MP3SinkError(
"Audio may only be formatted after recording is finished."
)
Expand Down
2 changes: 1 addition & 1 deletion discord/sinks/mp4.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ def format_audio(self, audio):
MP4SinkError
Formatting the audio failed.
"""
if self.vc.recording:
if self.recording:
raise MP4SinkError(
"Audio may only be formatted after recording is finished."
)
Expand Down
2 changes: 1 addition & 1 deletion discord/sinks/ogg.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ def format_audio(self, audio):
OGGSinkError
Formatting the audio failed.
"""
if self.vc.recording:
if self.recording:
raise OGGSinkError(
"Audio may only be formatted after recording is finished."
)
Expand Down
18 changes: 12 additions & 6 deletions discord/sinks/wave.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,9 @@
"""

import wave
from io import BytesIO

from ..opus import Decoder as OpusDecoder
from .core import Filters, Sink, default_filters
from .errors import WaveSinkError

Expand Down Expand Up @@ -54,16 +56,20 @@ def format_audio(self, audio):
WaveSinkError
Formatting the audio failed.
"""
if self.vc.recording:
if self.recording:
raise WaveSinkError(
"Audio may only be formatted after recording is finished."
)
data = audio.file

with wave.open(data, "wb") as f:
f.setnchannels(self.vc.decoder.CHANNELS)
f.setsampwidth(self.vc.decoder.SAMPLE_SIZE // self.vc.decoder.CHANNELS)
f.setframerate(self.vc.decoder.SAMPLING_RATE)
audio.file.seek(0)
pcm_data = audio.file.read()

data = BytesIO()
with wave.open(data, "wb") as f:
f.setnchannels(OpusDecoder.CHANNELS)
f.setsampwidth(OpusDecoder.SAMPLE_SIZE // OpusDecoder.CHANNELS)
f.setframerate(OpusDecoder.SAMPLING_RATE)
f.writeframes(pcm_data)
data.seek(0)
audio.file = data
audio.on_format(self.encoding)
34 changes: 30 additions & 4 deletions discord/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@
Mapping,
Sequence,
)
from concurrent.futures import Future
from inspect import isawaitable as _isawaitable
from inspect import signature as _signature
from operator import attrgetter
Expand All @@ -61,12 +62,14 @@
ForwardRef,
Generic,
Literal,
ParamSpec,
Protocol,
TypeVar,
Union,
overload,
)

from typing_extensions import LiteralString
from typing_extensions import deprecated as ext_deprecated

if TYPE_CHECKING:
Expand Down Expand Up @@ -179,6 +182,8 @@ class _RequestLike(Protocol):
T = TypeVar("T")
T_co = TypeVar("T_co", covariant=True)
_Iter = Iterator[T] | AsyncIterator[T]
_MC_P = ParamSpec("_MC_P")
_MC_T = TypeVar("_MC_T")


class CachedSlotProperty(Generic[T, T_co]):
Expand Down Expand Up @@ -861,7 +866,11 @@ def _parse_ratelimit_header(request: Any, *, use_clock: bool = False) -> float:
return (reset - now).total_seconds()


async def maybe_coroutine(f, *args, **kwargs):
async def maybe_coroutine(
f: Callable[_MC_P, _MC_T | Awaitable[_MC_T]],
*args: _MC_P.args,
**kwargs: _MC_P.kwargs,
) -> _MC_T:
value = f(*args, **kwargs)
if _isawaitable(value):
return await value
Expand Down Expand Up @@ -1594,13 +1603,13 @@ def users_to_csv(users: Iterable[Snowflake]) -> io.BytesIO:
def get_missing_voice_dependencies() -> tuple[str, ...]:
missing: list[str] = []
try:
import nacl.secret
import nacl.utils
import nacl.secret # pyright: ignore[reportUnusedImport]
import nacl.utils # pyright: ignore[reportUnusedImport]
except ImportError:
missing.append("PyNaCl")

try:
import davey
import davey # pyright: ignore[reportUnusedImport]
except ImportError:
missing.append("davey")
return tuple(missing)
Expand Down Expand Up @@ -1643,3 +1652,20 @@ def _get_event_loop() -> asyncio.AbstractEventLoop:
asyncio.set_event_loop(loop)
return loop
return asyncio.get_event_loop()


def log_future_exception(
f: Future[Any], # pyright: ignore[reportExplicitAny]
log: logging.Logger,
message: LiteralString,
*args: object,
) -> None:
def callback(f: Future[object]) -> None:
if not f.cancelled() and (exc := f.exception()) is not None:
log.exception(
message,
*args,
exc_info=exc,
)

f.add_done_callback(callback)
4 changes: 2 additions & 2 deletions discord/voice/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@
from ..errors import MissingVoiceDependenciesError
from ..utils import get_missing_voice_dependencies

if missing := get_missing_voice_dependencies():
raise MissingVoiceDependenciesError(missing=missing)
if _missing := get_missing_voice_dependencies():
raise MissingVoiceDependenciesError(missing=_missing)

from ._types import *
from .client import *
Expand Down
Loading
Loading