### Example: merging video and audio with FfmpegMerger Source: https://github.com/4thel00z/ytdown/blob/master/_autodocs/api-reference/postprocess.md Example of using FfmpegMerger::new() to merge video and audio files, then removing the temporary input files. The merge call returns a Result that must be handled. ```rust use ytdown::postprocess::FfmpegMerger; let merger = FfmpegMerger::new(); merger.merge(&video_tmp, &audio_tmp, &dest).await?; std::fs::remove_file(&video_tmp).await; std::fs::remove_file(&audio_tmp).await; ``` -------------------------------- ### Example: merging with custom ffmpeg binary and error handling Source: https://github.com/4thel00z/ytdown/blob/master/_autodocs/api-reference/postprocess.md Example of using FfmpegMerger::with_binary() to specify a custom ffmpeg path and handling the merge result, printing 'muxed' on success or an error message on failure. ```rust use ytdown::{Error, postprocess::FfmpegMerger}; let merger = FfmpegMerger::with_binary("/opt/ffmpeg/bin/ffmpeg"); match merger.merge(video, audio, out).await { Ok(()) => eprintln!("muxed"), Err(Error::Postprocess(msg)) => eprintln!("ffmpeg failed: {msg}"), } ``` -------------------------------- ### Install @4thel00z/ytdown and deploy the reference proxy Source: https://github.com/4thel00z/ytdown/blob/master/README.md Install the SDK and deploy the reference Cloudflare Worker proxy. The proxy is required because YouTube's APIs do not send CORS headers; without it the SDK will not work against YouTube. ```bash npm install @4thel00z/ytdown # deploy the reference proxy (or bring your own): cd web/proxy && npx wrangler deploy ``` -------------------------------- ### Example: converting WebM to MP4 with FfmpegMerger Source: https://github.com/4thel00z/ytdown/blob/master/_autodocs/api-reference/postprocess.md Example of converting a WebM file to MP4, which re-encodes to H.264 video and AAC audio. The output extension selects the codec arguments. ```rust let merger = FfmpegMerger::new(); merger.convert(&input_webm, &output_mp4).await?; // re-encodes to H.264/AAC ``` -------------------------------- ### HttpRequest POST example Source: https://github.com/4thel00z/ytdown/blob/master/_autodocs/api-reference/transport.md Shows how to build a POST request with headers and a body using the HttpRequest::post constructor. ```rust let req = HttpRequest::post("innertube", "https://www.youtube.com/youtubei/v1/player") .header("Content-Type", "application/json") .header("X-Goog-Api-Key", "…") .body(payload); ``` -------------------------------- ### Install ytdown CLI Source: https://github.com/4thel00z/ytdown/blob/master/README.md Installs the ytdown binary from the ytdown-cli crate. ```sh cargo install ytdown-cli ``` -------------------------------- ### ytdown CLI usage examples Source: https://github.com/4thel00z/ytdown/blob/master/_autodocs/api-reference/cli.md A set of example commands demonstrating common ytdown invocations: fetching video info, listing formats, searching, downloading with format and output options, using cookies, and generating shell completions. ```sh ytdown info "https://www.youtube.com/watch?v=dQw4w9WgXcQ" --pretty | jq .title ``` ```sh ytdown formats "https://youtu.be/dQw4w9WgXcQ" --json ``` ```sh ytdown search "rust async" -n 5 ``` ```sh ytdown get "https://youtu.be/dQw4w9WgXcQ" -f bestaudio -o 'audio/{id}.m4a' ``` ```sh ytdown get 'https://www.youtube.com/playlist?list=PL…' --limit 10 -o '{index} - {title}.{ext}' ``` ```sh ytdown --cookies cookies.txt get "https://www.youtube.com/watch?v=…" ``` ```sh ytdown completions bash > /tmp/ytdown.bash ``` -------------------------------- ### Install ytdown-py with uv Source: https://github.com/4thel00z/ytdown/blob/master/ytdown-py/README.md Install the ytdown-py package. The first command installs from PyPI; the second installs from source when no prebuilt wheel is available (platforms other than Linux x86_64 and macOS arm64) and requires a Rust toolchain. ```sh uv add ytdown-py ``` ```sh uv add "git+https://github.com/4thel00z/ytdown#subdirectory=ytdown-py" ``` -------------------------------- ### GET / Source: https://github.com/4thel00z/ytdown/blob/master/_autodocs/endpoints.md Serves the self-contained demo HTML page with the wasm and glue inlined at build time. No authentication, request body, or query parameters are required. ```APIDOC ## GET / ### Description Serves the self-contained demo HTML page (wasm + glue inlined at build time). ### Method GET ### Endpoint / ### Parameters None ### Response #### Success Response (200) - **body** (string) - The demo HTML page. #### Response Example (HTML content) ``` -------------------------------- ### CookieTransport usage example Source: https://github.com/4thel00z/ytdown/blob/master/_autodocs/api-reference/cookies.md Example of constructing a CookieTransport with a ReqwestClient and a parsed Netscape cookie jar, then wrapping it in an ExtractorContext. This shows manual setup; Ytdown::builder().cookies(jar) wires this automatically when the jar is non-empty. ```rust use ytdown::cookies::{CookieJar, CookieTransport}; let inner: std::sync::Arc = std::sync::Arc::new(ReqwestClient::new(reqwest::Client::new())); let jar = CookieJar::parse_netscape(&fs_text)?; let auth = CookieTransport::new(inner, jar); let ctx = ExtractorContext::new(std::sync::Arc::new(auth)); ``` -------------------------------- ### Configure and await a download with progress Source: https://github.com/4thel00z/ytdown/blob/master/_autodocs/api-reference/ytdown.md Example of configuring a download with concurrency, chunk size, retries, resume, and a progress callback. The builder is awaited directly. Defaults are concurrency=1, chunk_size=10 MiB, retries=3, resume=true. ```rust yt.download(fmt, "out.mp4") .concurrency(4) .chunk_size(5 * 1024 * 1024) .retries(5) .resume(true) .progress(|p| { if let Some(pct) = p.percent() { eprintln!("{pct:.1}%"); } }) .await?; ``` -------------------------------- ### Using best_video_audio for merged download Source: https://github.com/4thel00z/ytdown/blob/master/_autodocs/api-reference/format.md Example usage: select best video and audio pair and download merged output. ```rust let (video, audio) = video.formats().best_video_audio()?; yt.download_merged(video, audio, Path::new("out.mp4")).await?; // When only progressive formats exist, both tuple elements are the same format. ``` -------------------------------- ### Run the local demo server with make serve Source: https://github.com/4thel00z/ytdown/blob/master/README.md Build the WASM bundle and launch the demo server. The server hosts a single-file demo page and a local CORS proxy on http://127.0.0.1:8080, so resolving and downloading work with no extra setup. ```bash make serve # equivalent to: cd web && bun run build:wasm cargo run -p ytdown-cli --features serve -- serve --open ``` -------------------------------- ### ytdown get command usage Source: https://github.com/4thel00z/ytdown/blob/master/_autodocs/api-reference/cli.md Shows the general syntax for the `get` command, which downloads a video, playlist, channel, or `ytsearch:` result set. The command accepts a URL and optional flags as listed in the table. ```text ytdown get [FLAGS] ``` -------------------------------- ### ytdown CLI usage examples Source: https://github.com/4thel00z/ytdown/blob/master/README.md Common ytdown CLI usage examples: inspecting formats, downloading with output templates, explicit format selection, fetching metadata as JSON, searching, and downloading playlists/channels entry-by-entry. ```sh # Inspect available formats ytdown formats https://youtu.be/dQw4w9WgXcQ # Download: best merged video+audio (needs ffmpeg), or best progressive ytdown get https://youtu.be/dQw4w9WgXcQ -o '{title}.{ext}' # Explicit formats: keywords, itags, or video+audio merge pairs ytdown get -f 137+140 https://youtu.be/dQw4w9WgXcQ # Metadata as JSON, search from the terminal ytdown info https://youtu.be/dQw4w9WgXcQ | jq .title ytdown search "rust async" -n 5 # Playlists/channels download entry-by-entry ytdown get 'https://www.youtube.com/playlist?list=…' --limit 10 -o '{index} - {title}.{ext}' ``` -------------------------------- ### Selecting best progressive format with max_height Source: https://github.com/4thel00z/ytdown/blob/master/_autodocs/api-reference/format.md Example usage: chain filter methods and terminal method to get the best progressive format with height <= 720. ```rust use ytdown::FormatSelector; let sel = FormatSelector::new(&video.formats); let best = sel.progressive().max_height(720).best_video()?; ``` -------------------------------- ### sapisid_hash usage example Source: https://github.com/4thel00z/ytdown/blob/master/_autodocs/api-reference/cookies.md Example usage of sapisid_hash with a sample SAPISID, origin, and Unix timestamp. The comment shows the expected output format: SAPISIDHASH followed by the timestamp and a 40-character hex SHA1 hash. ```rust let auth = sapisid_hash("abc123", "https://www.youtube.com", 1_700_000_000); // "SAPISIDHASH 1700000000_<40 hex chars>" ``` -------------------------------- ### Constructing Format with default and mutating fields Source: https://github.com/4thel00z/ytdown/blob/master/_autodocs/api-reference/types.md Shows the documented construction pattern for Format: use Format::default() then mutate fields. The example sets video and audio streams and asserts the kind is Progressive. ```rust let mut fmt = Format::default(); fmt.video = Some(VideoStream { width: Some(1280), height: Some(720), fps: Some(30.0), codec: "avc1.64001F".into() }); fmt.audio = Some(AudioStream::default()); assert!(fmt.kind() == FormatKind::Progressive); ``` -------------------------------- ### Create ReqwestClient and execute a request Source: https://github.com/4thel00z/ytdown/blob/master/_autodocs/api-reference/transport.md Shows how to create a ReqwestClient with default settings and execute an HTTP GET request. The execute method returns a Result that must be awaited. ```rust use ytdown::ReqwestClient; let client = ReqwestClient::new(reqwest::Client::new()); let resp = client .execute(HttpRequest::get("test", "https://example.com/x")) .await?; ``` -------------------------------- ### DownloadBuilder<'a> Source: https://github.com/4thel00z/ytdown/blob/master/_autodocs/api-reference/ytdown.md Documentation for the DownloadBuilder struct, including its builder methods and usage examples. ```APIDOC ## DownloadBuilder<'a> ### Description A configurable, awaitable download of one format to a path. Implements `IntoFuture` so it can be awaited directly. ### Method `await` (via `IntoFuture`) ### Endpoint `yt.download(fmt, "out.mp4")` ### Parameters #### Builder Methods - **progress** (`impl Fn(Progress) + Send + Sync + 'static`) - Required - Observe progress; `f` receives `Progress` snapshots (~250 ms tick + final). - **concurrency** (`usize`) - Required - Parallel range-chunk connections (1 = sequential streaming). Default: `1`. - **chunk_size** (`u64`) - Required - Chunk size in bytes for the parallel path; only effective with `concurrency > 1` and range-supporting servers. Default: `10 MiB`. - **retries** (`u32`) - Required - Max retry attempts per request, jittered exponential backoff (500 ms · 2ⁿ). Default: `3`. - **resume** (`bool`) - Required - Resume from an existing partial file. Default: `true`. ### Request Example ```rust yt.download(fmt, "out.mp4") .concurrency(4) .chunk_size(5 * 1024 * 1024) .retries(5) .resume(true) .progress(|p| { if let Some(pct) = p.percent() { eprintln!("{pct:.1}%"); } }) .await?; ``` ### Response #### Success Response - **Output** (`Result<()>`) - Ok on success. #### Error Handling - **Error::Network** - On retry exhaustion, with `stage: "download"` and `message`. #### Response Example ```rust let builder = yt.download(fmt, "out.mp4").retries(1); match builder.await { Ok(()) => eprintln!("saved"), Err(Error::Network { stage: "download", message }) => eprintln!("failed: {message}"), Err(e) => eprintln!("other error: {e:#}"), } ``` ``` -------------------------------- ### build builder method with usage example Source: https://github.com/4thel00z/ytdown/blob/master/_autodocs/api-reference/ytdown.md Builds a fully wired Ytdown (transport + registry + downloader). Returns Error::Network { stage: "client-build", message } if the default HTTP client cannot be built. Native-only. ```rust pub fn build(self) -> Result ``` ```rust let yt = Ytdown::builder().user_agent("my-app/1.0").build()?; ``` -------------------------------- ### Download a format with Ytdown::download Source: https://github.com/4thel00z/ytdown/blob/master/_autodocs/api-reference/ytdown.md Example of downloading a format with Ytdown::download. Requires a resolved video and a destination path. ```rust let yt = Ytdown::builder().build()?; let fmt = video.formats().best_progressive()?; yt.download(fmt, Path::new("out.mp4")).await?; ``` -------------------------------- ### Use Ytdown class to resolve and download Source: https://github.com/4thel00z/ytdown/blob/master/_autodocs/api-reference/ts-sdk.md Shows how to use the `Ytdown` class from the package: create an instance with a proxy URL, resolve a YouTube URL to get video info, and download the first format with a filename and progress callback. ```ts import { Ytdown } from "@4thel00z/ytdown"; const yt = await Ytdown.create({ proxy: "https://ytdown-proxy..workers.dev" }); const info = await yt.resolve("https://youtu.be/dQw4w9WgXcQ"); // info: resolved VideoInfo with formats; pick one and download: await yt.download(info.formats[0].url, { filename: "video.mp4", onProgress: (p) => console.log(p.percent), }); ``` -------------------------------- ### FormatSelector usage example Source: https://github.com/4thel00z/ytdown/blob/master/_autodocs/api-reference/python.md Example usage of FormatSelector methods on a VideoInfo object. Shows chaining filters and calling terminal methods; best_video_audio raises FormatNotFoundError when neither split streams nor a progressive format exists. ```python fmt = info.select().progressive().max_height(720).best_video() # may raise FormatNotFoundError audio = info.select().audio_only().best_audio() video, audio = info.select().best_video_audio() ``` -------------------------------- ### Using HttpResponse methods Source: https://github.com/4thel00z/ytdown/blob/master/_autodocs/api-reference/transport.md Example usage of HttpResponse methods: execute a request, check is_success(), and retrieve a header case-insensitively. ```rust let resp = ctx.http.execute(req).await?; if resp.is_success() { if let Some(final) = resp.header("x-final") { … } } ``` -------------------------------- ### Download with custom DownloadOptions Source: https://github.com/4thel00z/ytdown/blob/master/_autodocs/api-reference/download.md Example of using Downloader directly with custom options: concurrency 4, chunk size 512 KiB, and a Cookie header. The call is awaited and returns a Result; note that application code normally uses Ytdown::download with DownloadBuilder instead. ```rust use ytdown::{DownloadOptions, Downloader}; let dl = Downloader::new(reqwest::Client::new()); dl.download( "https://cdn.example/v.mp4", Path::new("out.mp4"), DownloadOptions { concurrency: 4, chunk_size: 512 * 1024, headers: vec![("Cookie".into(), "tt_chain_token=abc".into())], ..DownloadOptions::default() }, ) .await?; ``` -------------------------------- ### Progress::percent usage example Source: https://github.com/4thel00z/ytdown/blob/master/_autodocs/api-reference/download.md Shows how to construct a Progress instance and call percent. With bytes_downloaded: 50 and total_bytes: Some(200), percent returns Some(25.0). ```rust use ytdown::Progress; let p = Progress { bytes_downloaded: 50, total_bytes: Some(200), speed_bps: None, eta: None, }; assert_eq!(p.percent(), Some(25.0)); ``` -------------------------------- ### Merge video and audio with Ytdown::download_merged Source: https://github.com/4thel00z/ytdown/blob/master/_autodocs/api-reference/ytdown.md Example of merging video and audio streams with Ytdown::download_merged. On failure, the muxed output may be missing but temporaries are cleaned up. ```rust let (v, a) = video.formats().best_video_audio()?; yt.download_merged(v, a, Path::new("out.mp4")).await?; // on failure the muxed output may be missing, temporaries are cleaned up ``` -------------------------------- ### Iterating a Collection Source: https://github.com/4thel00z/ytdown/blob/master/_autodocs/api-reference/python.md Shows how to iterate a Collection lazily, fetching pages one by one. The example resolves a search query and prints the first entry's id and title. ```python from ytdown import Collection, Entry col = yt.resolve("ytsearch:rust") for entry in col: # lazy page-by-page iteration print(entry.id, entry.title) break ``` -------------------------------- ### Mock Extractor implementation Source: https://github.com/4thel00z/ytdown/blob/master/_autodocs/api-reference/extractor.md Example mock extractor implementing the Extractor trait. Shows the required methods and a sample extract that returns an error. ```rust struct Dummy; #[async_trait::async_trait] impl Extractor for Dummy { fn name(&self) -> &'static str { "dummy" } fn matches(&self, url: &url::Url) -> bool { url.host_str() == Some("dummy.test") } async fn extract(&self, ctx: &ExtractorContext, url: &url::Url) -> Result { // … build a VideoInfo and return MediaInfo::Single(..) Err(Error::UnsupportedUrl(url.to_string())) } } ``` -------------------------------- ### get [FLAGS] Source: https://github.com/4thel00z/ytdown/blob/master/_autodocs/api-reference/cli.md Download a video, playlist, channel, or `ytsearch:` result set. Supports format selection, output templates, parallel downloads, and an interactive picker. ```APIDOC ## `get` — `cli/src/get.rs` ### Description Download a video, playlist, channel, or `ytsearch:` result set. Behavior: resolution happens per entry; collections download entry-by-entry, honoring `--skip`/`--limit`; per-entry failures are logged and counted, with a single aggregate error (` of downloads failed`) at the end. ### Method CLI command ### Endpoint `ytdown get [FLAGS]` ### Parameters #### Positional Arguments - **URL** (string) - Required - The URL to download. #### Optional Flags - **-f, --format ** (FormatSpec) - Optional - Format selection (see format values below). - **--max-height ** (u32) - Optional - Only consider formats up to this height (keyword specs only). - **--container ** (enum) - Optional - Only consider formats in this container (keyword specs only). - **-o, --output