Big News: Socket Selected for OpenAI's Cybersecurity Grant Program.Details
Socket
Book a DemoSign in
Socket

asyncyt

Package Overview
Dependencies
Maintainers
1
Versions
33
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

asyncyt

A fully asynchronous media downloader for 1000+ websites, powered by yt-dlp and FFmpeg

pipPyPI
Version
1.4.6
Maintainers
1

AsyncYT

PyPI - Version Downloads License

AsyncYT is a fully async, high-performance media downloader for 1000+ websites powered by yt-dlp and ffmpeg.
It comes with auto binary setup, progress tracking, playlist support, search, and clean API models using pydantic.

✨ Features

  • Fully Async Architecture – every operation is non‑blocking and await‑ready.
  • 🎥 Video, Audio, and Playlist Support – download any media you throw at it.
  • 🌐 Automatic Binary Management – downloads yt-dlp and ffmpeg automatically if not found, with update support and resume-capable downloads.
  • 🎛 Rich FFmpeg Encoding Configuration – control video/audio codecs, CRF, bitrates, presets, pixel formats, scale, FPS, VBV, and more via the new EncodingConfig model — translated directly into yt-dlp --postprocessor-args flags, no separate FFmpeg process needed.
  • 📡 Real‑Time Progress Tracking – granular download and FFmpeg encoding progress (percentage, FPS, speed multiplier, bitrate, frame count, elapsed time), perfect for UI updates or WebSockets.
  • 🔀 Smart Postprocessor Routing – encoding args are automatically routed to the right yt-dlp postprocessor (VideoConvertor, ExtractAudio, Merger, VideoRemuxer) depending on your config.
  • 🔁 Resilient Downloads – configurable retries, fragment retries, rate limiting, proxy support, cookies, and resume-capable binary downloads with exponential back-off.
  • 🔍 Video & Playlist Info – retrieve full metadata (title, duration, uploader, view/like count, formats, thumbnail) before downloading.
  • 🔎 Built-in Search – search YouTube directly and get back typed VideoInfo results.
  • 🛡 Strongly Typed Models – every input and output is a validated pydantic model with schema extras and field-level docs.
  • 📚 Rich Enum Library – type-safe enums for qualities, codecs, presets, pixel formats, audio channels, subtitle formats, progress statuses, and more.
  • 🧩 Clean Exception Hierarchy – specific exceptions for every failure mode (download canceled, already exists, not found, yt-dlp errors, etc.).
  • 🔗 URL Cleaning Utilities – normalises YouTube watch, youtu.be, /shorts/, and /embed/ URLs automatically.
  • 📂 Safe File Management – unique filename generation, overwrite control, and atomic temp-dir → output-dir moves.
  • 🖥 Cross-Platform – Windows, macOS, and Linux; correct binaries are selected per platform automatically.

📋 Requirements

  • Python 3.11+
  • Cross-platform – Windows, macOS, Linux
  • Optional: yt-dlp and ffmpeg (auto-downloaded if not present)

📦 Install

pip install asyncyt

🚀 Quick Start

import asyncio
from asyncyt import AsyncYT, DownloadConfig, Quality
from asyncyt.exceptions import AsyncYTBase

async def main():
    downloader = AsyncYT()
    await downloader.setup_binaries()

    config = DownloadConfig(quality=Quality.HD_720P)

    info = await downloader.get_video_info("https://www.youtube.com/watch?v=dQw4w9WgXcQ")
    print(f"Downloading: {info.title}")

    filename = await downloader.download(info.url, config)
    print(f"Downloaded to: {filename}")

asyncio.run(main())

For more examples check the Examples folder.

🎛 Encoding Configuration

AsyncYT exposes a rich EncodingConfig model that gives you full control over how FFmpeg processes your media. It maps directly onto yt-dlp's --postprocessor-args / --ppa flags — no extra FFmpeg invocations.

from asyncyt import AsyncYT, DownloadConfig, Quality, VideoFormat
from asyncyt.encoding import EncodingConfig, VideoEncodingConfig, AudioEncodingConfig
from asyncyt.enums import VideoCodec, AudioCodec, Preset, PixelFormat

config = DownloadConfig(
    quality=Quality.HD_1080P,
    video_format=VideoFormat.MP4,
    embed_metadata=True,
    embed_thumbnail=True,
    encoding=EncodingConfig(
        video=VideoEncodingConfig(
            codec=VideoCodec.H264,
            crf=20,
            preset=Preset.SLOW,
            pixel_format=PixelFormat.YUV420P,
        ),
        audio=AudioEncodingConfig(
            codec=AudioCodec.AAC,
            bitrate="192k",
        ),
        overwrite=True,
    ),
)

VideoEncodingConfig options

FieldTypeDescription
codecVideoCodecFFmpeg video codec (e.g. libx264, hevc_nvenc)
crfint (0–63)Constant Rate Factor — quality vs. size. Mutually exclusive with bitrate.
bitratestrTarget video bitrate, e.g. "2M", "800k"
maxratestrMax bitrate cap for VBV, e.g. "4M"
bufsizestrVBV buffer size, e.g. "8M"
presetPresetEncoding speed preset (ultrafastplacebo)
tuneTuneOptionx264/x265 tune (film, animation, grain …)
pixel_formatPixelFormatOutput pixel format (yuv420p, yuv420p10le …)
widthintOutput width in pixels (aspect ratio preserved when height omitted)
heightintOutput height in pixels (aspect ratio preserved when width omitted)
fpsint | floatForce output frame rate
extra_argsList[str]Raw FFmpeg video args appended verbatim

AudioEncodingConfig options

FieldTypeDescription
codecAudioCodecFFmpeg audio codec (e.g. aac, libmp3lame, libopus)
bitratestrTarget audio bitrate, e.g. "192k", "320k"
qualityint (0–10)VBR quality (codec-specific scale)
sample_rateintOutput sample rate in Hz, e.g. 44100, 48000
channelsAudioChannelsOutput channel layout (MONO, STEREO, SURROUND_5_1 …)
extra_argsList[str]Raw FFmpeg audio args appended verbatim

EncodingConfig options

FieldTypeDescription
videoVideoEncodingConfigVideo encoding settings
audioAudioEncodingConfigAudio encoding settings
overwriteboolPass -y to FFmpeg to overwrite existing output files
extra_global_argsList[str]Raw FFmpeg global args, e.g. ["-threads", "4"]

📡 Progress Tracking

Pass any async or sync callable as progress_callback to receive live DownloadProgress updates:

from asyncyt import AsyncYT, DownloadConfig
from asyncyt.basemodels import DownloadProgress
from asyncyt.enums import ProgressStatus

async def on_progress(p: DownloadProgress):
    if p.status == ProgressStatus.DOWNLOADING:
        print(f"[Download] {p.percentage:.1f}%  {p.speed}  ETA {p.eta}s")
    elif p.status == ProgressStatus.ENCODING:
        print(f"[Encode]   {p.encoding_percentage:.1f}%  fps={p.encoding_fps}  speed={p.encoding_speed}")
    elif p.status == ProgressStatus.MERGING:
        print("[Merging streams...]")
    elif p.status == ProgressStatus.COMPLETED:
        print("Done!")

downloader = AsyncYT()
await downloader.setup_binaries()
await downloader.download("https://youtu.be/dQw4w9WgXcQ", progress_callback=on_progress)

DownloadProgress fields

FieldDescription
idDownload ID (SHA-256 hash of URL + config)
urlDownload URL
titleVideo title
statusCurrent phase (downloading, encoding, merging, remuxing, completed …)
percentageDownload progress 0–100
downloaded_bytesBytes downloaded so far
total_bytesTotal bytes expected
speedDownload speed string, e.g. "3.20MiB/s"
etaEstimated seconds remaining
encoding_percentageFFmpeg encode progress 0–100
encoding_fpsFrames per second during encoding
encoding_speedEncoding speed multiplier, e.g. "2.50x"
encoding_frameCurrent frame being encoded
encoding_bitrateCurrent output bitrate during encode
encoding_sizeOutput size so far during encode
encoding_timeElapsed encode time as HH:MM:SS.mmm
results = await downloader.search("Eminem - Mockingbird", max_results=5)
for video in results:
    print(video.title, video.url, video.duration)

📋 Playlist Download

from asyncyt.basemodels import PlaylistRequest, DownloadConfig
from asyncyt.enums import Quality

request = PlaylistRequest(
    url="https://www.youtube.com/playlist?list=PL...",
    config=DownloadConfig(quality=Quality.HD_720P),
    max_videos=20,
)

response = await downloader.download_playlist(request=request)
print(f"Downloaded {response.successful_downloads} of {response.total_videos}")
print("Failed:", response.failed_downloads)

⚙️ DownloadConfig Reference

FieldDefaultDescription
output_path"./downloads"Output directory (created automatically)
qualityQuality.BESTVideo quality setting
audio_formatNoneAudio format for extraction
video_formatNoneVideo container format
extract_audioFalseExtract audio only
embed_subsFalseEmbed subtitles in video
write_subsFalseWrite subtitle files
subtitle_lang"en"Subtitle language code
write_thumbnailFalseDownload thumbnail
embed_thumbnailFalseEmbed thumbnail in file
embed_metadataTrueEmbed metadata
write_info_jsonFalseWrite yt-dlp info JSON
write_live_chatFalseDownload live chat
custom_filenameNoneCustom yt-dlp output template
cookies_fileNonePath to cookies file
proxyNoneProxy URL
rate_limitNoneRate limit e.g. "1M" or "500K"
retries3Number of retries (0–10)
fragment_retries3Fragment retries (0–10)
custom_options{}Extra yt-dlp options as key→value dict
encodingNoneEncodingConfig for fine-grained FFmpeg control

🎬 Available Enums

EnumValues (examples)
QualityBEST, WORST, AUDIO_ONLY, VIDEO_ONLY, HD_720P, HD_1080P, UHD_4K, UHD_8K
VideoFormatMP4, MKV, WEBM, AVI, MOV, FLV, GIF
AudioFormatMP3, AAC, FLAC, OPUS, OGG, WAV, ALAC
VideoCodecH264, H265, VP9, AV1, H264_NVENC, HEVC_NVENC, H264_QSV
AudioCodecAAC, MP3, OPUS, FLAC, ALAC, AC3, COPY
PresetULTRAFAST, FAST, MEDIUM, SLOW, VERYSLOW, PLACEBO
TuneOptionFILM, ANIMATION, GRAIN, FASTDECODE, ZEROLATENCY
PixelFormatYUV420P, YUV420P10LE, YUV444P, RGB24, RGBA
AudioChannelsMONO, STEREO, SURROUND_5_1, SURROUND_7_1
ProgressStatusDOWNLOADING, ENCODING, MERGING, REMUXING, COMPLETED

⚠️ Exceptions

All exceptions extend AsyncYTBase.

ExceptionWhen raised
DownloadAlreadyExistsErrorA download with the same ID is already running
DownloadNotFoundErrorAttempting to cancel a download that doesn't exist
DownloadGotCanceledErrorA download was cancelled
YtdlpDownloadErroryt-dlp exited with a non-zero return code
YtdlpSearchErroryt-dlp search failed
YtdlpGetInfoErroryt-dlp failed to retrieve video info
YtdlpPlaylistGetInfoErroryt-dlp failed to retrieve playlist info
from asyncyt.exceptions import AsyncYTBase, YtdlpDownloadError

try:
    await downloader.download(url, config)
except YtdlpDownloadError as e:
    print(f"yt-dlp failed (code {e.error_code}):\n{e.output}")
except AsyncYTBase as e:
    print(f"AsyncYT error: {e}")

🌐 Supported Sites

AsyncYT supports 1000+ websites through yt-dlp, including:

  • YouTube, YouTube Music
  • Twitch, TikTok, Instagram
  • Twitter, Reddit, Facebook
  • Vimeo, Dailymotion, and many more

See full list of supported sites →

📖 Documentation

👉 Read the Docs

🤝 Contributing

Contributions are welcome! Feel free to open an issue or pull request.

📜 License

MIT © MahiroX36

Keywords

async

FAQs

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts