ytaudio: stream yt-dlp into growing file for Lavalink local source
Lavalink's local loader rejects FIFOs and nonexistent files, but loads a regular file instantly even while it grows. Spawn yt-dlp with -o - writing into a pre-created regular file, wait until >=64KB is present, then load the path so the node's ffmpeg decodes it live. Skipping kills the process and deletes the file; falls back to mp3 download if streaming fails.
This commit is contained in:
+267
-28
@@ -12,9 +12,16 @@ should own initialize()/close(). Other cogs (e.g. ttstoy) simply call
|
||||
``lavalink.get_player(guild_id)`` and share this connection.
|
||||
|
||||
Playback path:
|
||||
yt-dlp downloads bestaudio -> ffmpeg transcodes to mp3 -> the mp3 file is
|
||||
loaded through Lavalink's ``local`` source and played. The mp3 is deleted
|
||||
when the track finishes / is skipped / on stop.
|
||||
yt-dlp resolves metadata (download=False, ~1s), then we run yt-dlp again with
|
||||
``-o -`` writing the raw bestaudio stream into a pre-created regular file. Once
|
||||
that file has data, Lavalink's ``local`` source plays from it while yt-dlp keeps
|
||||
filling it (its own ffmpeg decodes it live), so audio flows through the shared
|
||||
Lavalink player without touching Lavalink's unreliable youtube/http sources and
|
||||
without transcoding on our side. A regular file is used instead of a FIFO
|
||||
because this Lavalink build's local loader rejects non-regular files. No full
|
||||
download before playback, so tracks start within a few seconds and skipping
|
||||
(killing the yt-dlp process) is instant. If streaming fails it falls back to
|
||||
downloading the audio to mp3 and playing it through the ``local`` source.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
@@ -22,7 +29,10 @@ import functools
|
||||
import logging
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import time as _time
|
||||
import uuid
|
||||
from typing import Dict, List, Optional
|
||||
|
||||
import discord
|
||||
@@ -50,6 +60,8 @@ YTDLP_BASE_OPTS = {
|
||||
"ignoreerrors": False,
|
||||
"default_search": "ytsearch",
|
||||
"source_address": "0.0.0.0",
|
||||
"socket_timeout": 20,
|
||||
"retries": 2,
|
||||
"postprocessors": [
|
||||
{
|
||||
"key": "FFmpegExtractAudio",
|
||||
@@ -59,18 +71,43 @@ YTDLP_BASE_OPTS = {
|
||||
],
|
||||
}
|
||||
|
||||
# Max seconds to wait for yt-dlp to resolve a stream URL before giving up.
|
||||
RESOLVE_TIMEOUT = 30
|
||||
|
||||
# How long to wait for Lavalink to load the growing stream file as a track.
|
||||
STREAM_LOAD_TIMEOUT = 15
|
||||
# Minimum bytes yt-dlp must have written before we let Lavalink probe/play the file.
|
||||
STREAM_READY_MIN_BYTES = 64 * 1024
|
||||
|
||||
|
||||
class QueuedTrack:
|
||||
"""A track queued for a guild, resolved lazily at play time."""
|
||||
|
||||
__slots__ = ("query", "requester", "channel", "title", "mp3_path", "status_msg")
|
||||
__slots__ = (
|
||||
"query",
|
||||
"requester",
|
||||
"channel",
|
||||
"title",
|
||||
"stream_url",
|
||||
"stream_ext",
|
||||
"mp3_path",
|
||||
"stream_path",
|
||||
"procs",
|
||||
"skip_evt",
|
||||
"status_msg",
|
||||
)
|
||||
|
||||
def __init__(self, query: str, requester: discord.abc.User, channel):
|
||||
self.query = query
|
||||
self.requester = requester
|
||||
self.channel = channel
|
||||
self.title: Optional[str] = None
|
||||
self.stream_url: Optional[str] = None
|
||||
self.stream_ext: Optional[str] = "webm"
|
||||
self.mp3_path: Optional[str] = None
|
||||
self.stream_path: Optional[str] = None
|
||||
self.procs: List[subprocess.Popen] = []
|
||||
self.skip_evt: Optional[asyncio.Event] = None
|
||||
self.status_msg = None
|
||||
|
||||
|
||||
@@ -147,6 +184,9 @@ class YTAudio(commands.Cog):
|
||||
self._connect_task: Optional[asyncio.Task] = None
|
||||
self.mp3_dir = cog_data_path(self) / "mp3cache"
|
||||
self.mp3_dir.mkdir(parents=True, exist_ok=True)
|
||||
self.stream_dir = cog_data_path(self) / "streams"
|
||||
self.stream_dir.mkdir(parents=True, exist_ok=True)
|
||||
self._spawned = set()
|
||||
self._ytdlp_opts = dict(YTDLP_BASE_OPTS)
|
||||
self._ytdlp_opts["outtmpl"] = str(self.mp3_dir / "%(id)s.%(ext)s")
|
||||
|
||||
@@ -272,61 +312,243 @@ class YTAudio(commands.Cog):
|
||||
info = info["entries"][0]
|
||||
return info
|
||||
|
||||
def _blocking_extract_stream(self, query: str) -> dict:
|
||||
# download=False: only resolve metadata + the direct media URL.
|
||||
opts = dict(self._ytdlp_opts)
|
||||
opts.pop("postprocessors", None)
|
||||
opts.pop("outtmpl", None)
|
||||
with yt_dlp.YoutubeDL(opts) as ydl:
|
||||
info = ydl.extract_info(query, download=False)
|
||||
if "entries" in info: # search/playlist -> first entry
|
||||
info = info["entries"][0] or {}
|
||||
return info
|
||||
|
||||
def _skipped(self, track: QueuedTrack) -> bool:
|
||||
return track.skip_evt is not None and track.skip_evt.is_set()
|
||||
|
||||
async def _run_resolve_or_skip(self, fut, track: QueuedTrack):
|
||||
# Runs a blocking resolver future; returns its result, or None if a
|
||||
# skip was requested (or the resolver exceeded RESOLVE_TIMEOUT).
|
||||
skip_evt = track.skip_evt
|
||||
if self._skipped(track):
|
||||
return None
|
||||
skip_task = None
|
||||
tasks = {fut}
|
||||
if skip_evt is not None:
|
||||
skip_task = asyncio.create_task(skip_evt.wait())
|
||||
tasks.add(skip_task)
|
||||
done, pending = await asyncio.wait(
|
||||
tasks, timeout=RESOLVE_TIMEOUT, return_when=asyncio.FIRST_COMPLETED
|
||||
)
|
||||
for t in pending:
|
||||
t.cancel()
|
||||
if skip_task is not None and skip_evt.is_set():
|
||||
return None
|
||||
if fut not in done:
|
||||
return None
|
||||
return fut.result()
|
||||
|
||||
async def _resolve_to_stream(self, track: QueuedTrack):
|
||||
loop = asyncio.get_running_loop()
|
||||
fut = loop.run_in_executor(
|
||||
None, functools.partial(self._blocking_extract_stream, track.query)
|
||||
)
|
||||
info = await self._run_resolve_or_skip(fut, track)
|
||||
if info is None:
|
||||
return None
|
||||
track.title = info.get("title", track.query)
|
||||
url = info.get("url")
|
||||
if not url:
|
||||
raise ValueError("No streamable URL for: {}".format(track.query))
|
||||
track.stream_url = url
|
||||
track.stream_ext = info.get("ext") or "webm"
|
||||
return track
|
||||
|
||||
async def _resolve_to_mp3(self, track: QueuedTrack):
|
||||
loop = asyncio.get_running_loop()
|
||||
hook = self._make_progress_hook(loop, track)
|
||||
info = await loop.run_in_executor(
|
||||
fut = loop.run_in_executor(
|
||||
None, functools.partial(self._blocking_extract, track.query, hook)
|
||||
)
|
||||
info = await self._run_resolve_or_skip(fut, track)
|
||||
if info is None:
|
||||
return None
|
||||
track.title = info.get("title", track.query)
|
||||
vid = info.get("id")
|
||||
mp3_path = self.mp3_dir / f"{vid}.mp3"
|
||||
track.mp3_path = str(mp3_path)
|
||||
return track
|
||||
|
||||
def _cleanup_file(self, track: Optional[QueuedTrack]):
|
||||
if track and track.mp3_path and os.path.isfile(track.mp3_path):
|
||||
# ------------------------------------------------------------------
|
||||
# Live streaming: yt-dlp raw stream -> growing file -> Lavalink local source
|
||||
# ------------------------------------------------------------------
|
||||
@staticmethod
|
||||
def _fetch_target(query: str) -> str:
|
||||
q = query.strip()
|
||||
if q.startswith(("http://", "https://", "www.")):
|
||||
return q
|
||||
return "ytsearch1:" + q
|
||||
|
||||
def _spawn_stream_pipeline(self, track: QueuedTrack) -> bool:
|
||||
if not track.stream_path:
|
||||
return False
|
||||
ytdlp_cmd = [
|
||||
sys.executable,
|
||||
"-m",
|
||||
"yt_dlp",
|
||||
"--quiet",
|
||||
"--no-warnings",
|
||||
"--no-playlist",
|
||||
"-f",
|
||||
"bestaudio/best",
|
||||
"-o",
|
||||
"-",
|
||||
self._fetch_target(track.query),
|
||||
]
|
||||
# Create the regular file ourselves so it exists immediately (Lavalink's
|
||||
# local loader rejects non-regular files like FIFOs) and let yt-dlp stream
|
||||
# its stdout straight into it as the node plays.
|
||||
try:
|
||||
os.remove(track.mp3_path)
|
||||
fh = open(track.stream_path, "wb")
|
||||
except OSError:
|
||||
log.warning("Could not delete mp3: %s", track.mp3_path)
|
||||
log.exception("YTAudio: could not create stream file for %s", track.query)
|
||||
return False
|
||||
try:
|
||||
proc = subprocess.Popen(ytdlp_cmd, stdout=fh, stderr=subprocess.DEVNULL)
|
||||
except Exception:
|
||||
fh.close()
|
||||
log.exception("YTAudio: failed to spawn yt-dlp stream for %s", track.query)
|
||||
return False
|
||||
fh.close()
|
||||
track.procs = [proc]
|
||||
self._spawned.add(proc)
|
||||
asyncio.get_running_loop().create_task(self._watch_procs(track.procs))
|
||||
return True
|
||||
|
||||
async def _wait_stream_ready(self, track: QueuedTrack) -> bool:
|
||||
deadline = _time.monotonic() + STREAM_LOAD_TIMEOUT
|
||||
while _time.monotonic() < deadline:
|
||||
try:
|
||||
if os.path.getsize(track.stream_path) >= STREAM_READY_MIN_BYTES:
|
||||
return True
|
||||
except OSError:
|
||||
pass
|
||||
if track.procs and track.procs[0].poll() is not None:
|
||||
# yt-dlp exited before producing enough data.
|
||||
return False
|
||||
await asyncio.sleep(0.2)
|
||||
return False
|
||||
|
||||
async def _watch_procs(self, procs):
|
||||
for proc in procs:
|
||||
try:
|
||||
await asyncio.get_running_loop().run_in_executor(None, proc.wait)
|
||||
except Exception:
|
||||
pass
|
||||
for proc in procs:
|
||||
self._spawned.discard(proc)
|
||||
|
||||
def _cleanup_file(self, track: Optional[QueuedTrack]):
|
||||
if not track:
|
||||
return
|
||||
for proc in track.procs:
|
||||
try:
|
||||
if proc.poll() is None:
|
||||
proc.kill()
|
||||
except Exception:
|
||||
pass
|
||||
track.procs = []
|
||||
for path in (track.stream_path, track.mp3_path):
|
||||
if path and os.path.exists(path):
|
||||
try:
|
||||
os.remove(path)
|
||||
except OSError:
|
||||
log.warning("Could not delete file: %s", path)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Playback
|
||||
# ------------------------------------------------------------------
|
||||
async def _load_local(self, player, track: QueuedTrack) -> bool:
|
||||
loaded = await asyncio.wait_for(
|
||||
player.load_tracks(track.stream_path or track.mp3_path),
|
||||
timeout=STREAM_LOAD_TIMEOUT,
|
||||
)
|
||||
ok_types = (
|
||||
lavalink.enums.LoadType.TRACK_LOADED,
|
||||
lavalink.enums.LoadType.PLAYLIST_LOADED,
|
||||
)
|
||||
if loaded.has_error or loaded.load_type not in ok_types or not loaded.tracks:
|
||||
return False
|
||||
player.add(requester=track.requester, track=loaded.tracks[0])
|
||||
if not player.is_playing:
|
||||
await player.play()
|
||||
return True
|
||||
|
||||
async def _play_stream(self, player, track: QueuedTrack) -> Optional[bool]:
|
||||
# Returns True (playing), False (streaming failed), or None (skipped).
|
||||
if self._skipped(track):
|
||||
return None
|
||||
info_ok = await self._resolve_to_stream(track)
|
||||
if info_ok is None:
|
||||
return None
|
||||
if self._skipped(track):
|
||||
return None
|
||||
track.stream_path = str(
|
||||
self.stream_dir / "stream-{}.{}".format(uuid.uuid4().hex, track.stream_ext)
|
||||
)
|
||||
if not self._spawn_stream_pipeline(track):
|
||||
return False
|
||||
if not await self._wait_stream_ready(track):
|
||||
log.warning("YTAudio: stream never became ready for %s", track.query)
|
||||
return False
|
||||
if self._skipped(track):
|
||||
return None
|
||||
return await self._load_local(player, track)
|
||||
|
||||
async def _play_track(self, guild_id: int, track: QueuedTrack, done_event: asyncio.Event):
|
||||
status_msg = None
|
||||
if track.channel is not None:
|
||||
try:
|
||||
status_msg = await track.channel.send(
|
||||
"Downloading: {} (0%)".format(track.query)
|
||||
)
|
||||
status_msg = await track.channel.send("Loading: {}".format(track.query))
|
||||
except Exception:
|
||||
status_msg = None
|
||||
track.status_msg = status_msg
|
||||
await self._resolve_to_mp3(track)
|
||||
player = lavalink.get_player(guild_id)
|
||||
gp = self.players.get(guild_id)
|
||||
if gp:
|
||||
await player.set_volume(gp.volume)
|
||||
loaded = await player.load_tracks(track.mp3_path)
|
||||
if loaded.has_error or loaded.load_type != lavalink.enums.LoadType.TRACK_LOADED:
|
||||
log.error("YTAudio: failed to load mp3 into Lavalink: %s", track.mp3_path)
|
||||
if status_msg is not None:
|
||||
|
||||
# Fast path: live-stream via yt-dlp -> growing file -> Lavalink local source.
|
||||
result = False
|
||||
try:
|
||||
await status_msg.edit(content="Failed to load: {}".format(track.query))
|
||||
result = await self._play_stream(player, track)
|
||||
except asyncio.TimeoutError:
|
||||
log.warning("YTAudio: stream load timed out for %s", track.query)
|
||||
except Exception:
|
||||
pass
|
||||
log.exception("YTAudio: streaming failed for %s", track.query)
|
||||
|
||||
if result is None:
|
||||
done_event.set()
|
||||
return
|
||||
player.add(requester=track.requester, track=loaded.tracks[0])
|
||||
if not player.is_playing:
|
||||
await player.play()
|
||||
if status_msg is not None:
|
||||
|
||||
# Fallback: download + transcode to mp3, play via local source.
|
||||
if not result:
|
||||
await self._safe_edit(track, "Stream unavailable, downloading: {}".format(track.query))
|
||||
self._cleanup_file(track)
|
||||
try:
|
||||
await status_msg.edit(content="Now playing: {}".format(track.title or track.query))
|
||||
resolved = await self._resolve_to_mp3(track)
|
||||
if resolved is not None:
|
||||
result = await self._load_local(player, track)
|
||||
except Exception:
|
||||
pass
|
||||
log.exception("YTAudio: fallback download failed for %s", track.query)
|
||||
|
||||
if not result:
|
||||
log.error("YTAudio: failed to load track into Lavalink: %s", track.query)
|
||||
await self._safe_edit(track, "Failed to load: {}".format(track.query))
|
||||
done_event.set()
|
||||
return
|
||||
|
||||
await self._safe_edit(track, "Now playing: {}".format(track.title or track.query))
|
||||
|
||||
def _get_gp(self, guild_id: int) -> GuildPlayer:
|
||||
gp = self.players.get(guild_id)
|
||||
@@ -368,6 +590,7 @@ class YTAudio(commands.Cog):
|
||||
gp = self._get_gp(ctx.guild.id)
|
||||
gp.volume = await self.config.guild(ctx.guild).volume()
|
||||
track = QueuedTrack(query, ctx.author, ctx.channel)
|
||||
track.skip_evt = asyncio.Event()
|
||||
already_active = gp.current is not None or bool(gp.pending)
|
||||
gp.enqueue(track)
|
||||
if already_active:
|
||||
@@ -385,6 +608,9 @@ class YTAudio(commands.Cog):
|
||||
player = lavalink.get_player(ctx.guild.id)
|
||||
except Exception:
|
||||
return await ctx.send("Nothing is playing.")
|
||||
# Abort any in-flight resolve/spawn for the current track.
|
||||
if gp.current is not None and gp.current.skip_evt is not None:
|
||||
gp.current.skip_evt.set()
|
||||
# Stopping fires TRACK_END, which the event handler uses to advance
|
||||
# the queue. Do not set next_event here or it would skip two tracks.
|
||||
await player.stop()
|
||||
@@ -396,6 +622,8 @@ class YTAudio(commands.Cog):
|
||||
"""Stop playback and clear the queue."""
|
||||
gp = self.players.get(ctx.guild.id)
|
||||
if gp:
|
||||
if gp.current is not None and gp.current.skip_evt is not None:
|
||||
gp.current.skip_evt.set()
|
||||
gp.clear_pending()
|
||||
gp.next_event.set()
|
||||
try:
|
||||
@@ -487,6 +715,8 @@ class YTAudio(commands.Cog):
|
||||
"""Leave the voice channel and clear state."""
|
||||
gp = self.players.get(ctx.guild.id)
|
||||
if gp:
|
||||
if gp.current is not None and gp.current.skip_evt is not None:
|
||||
gp.current.skip_evt.set()
|
||||
gp.clear_pending()
|
||||
gp.next_event.set()
|
||||
try:
|
||||
@@ -512,9 +742,18 @@ class YTAudio(commands.Cog):
|
||||
pass
|
||||
# This cog owns the connection: close it on unload.
|
||||
await self._safe_close()
|
||||
# Sweep leftover mp3s.
|
||||
# Kill any in-flight streaming pipelines.
|
||||
for proc in list(self._spawned):
|
||||
try:
|
||||
shutil.rmtree(self.mp3_dir, ignore_errors=True)
|
||||
self.mp3_dir.mkdir(parents=True, exist_ok=True)
|
||||
if proc.poll() is None:
|
||||
proc.kill()
|
||||
except Exception:
|
||||
pass
|
||||
self._spawned.clear()
|
||||
# Sweep leftover mp3s and stream files.
|
||||
for directory in (self.mp3_dir, self.stream_dir):
|
||||
try:
|
||||
shutil.rmtree(directory, ignore_errors=True)
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
Reference in New Issue
Block a user