### Example Label Usage Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/additional-types.md Example of how to instantiate a Label struct with a language and content. ```rust pub struct Label { pub lang: Some("en"), pub content: Some("English - 1080p"), } ``` -------------------------------- ### Complete DashDownloader Example Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/dash-downloader.md This example demonstrates how to initialize DashDownloader, set quality and language preferences, configure an HTTP client with a timeout, and download the stream to a specified output path. Ensure you have the necessary dependencies and Tokio runtime configured. ```rust use dash_mpd::fetch::DashDownloader; use std::path::PathBuf; use std::time::Duration; #[tokio::main] async fn main() -> Result<(), Box> { let url = "https://example.com/stream.mpd"; let output = PathBuf::from("/tmp/video.mp4"); DashDownloader::new(url) .best_quality() .prefer_language("en".into()) .prefer_video_height(1080) .fetch_subtitles(true) .with_http_client( reqwest::Client::builder() .timeout(Duration::from_secs(30)) .build()? ) .download_to(output) .await?; Ok(()) } ``` -------------------------------- ### Install libav development libraries and build Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/features-and-configuration.md Installs the necessary libav development libraries for your system and then builds the project with the 'libav' feature enabled. This is required for media muxing via ffmpeg's libav library. ```bash sudo apt install libavformat-dev libavcodec-dev libavutil-dev cargo build --features libav ``` -------------------------------- ### Example: Handling Download Errors Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/utility-functions.md Demonstrates how to handle potential errors during the download process using a match statement. This example specifically catches network timeouts and decryption failures, with a general catch-all for other errors. ```rust match DashDownloader::new(url).download().await { Ok(path) => println!("Downloaded to: {path:?}"), Err(DashMpdError::NetworkTimeout(_)) => println!("Download timed out"), Err(DashMpdError::Decrypting(msg)) => println!("Decryption failed: {msg}"), Err(e) => println!("Download error: {e}"), } ``` -------------------------------- ### Implement and Use ProgressObserver Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/utility-functions.md Example of implementing the `ProgressObserver` trait and attaching it to a `DashDownloader`. This allows for real-time feedback during the download process. ```rust use dash_mpd::fetch::{DashDownloader, ProgressObserver}; use std::sync::Arc; struct MyObserver; impl ProgressObserver for MyObserver { fn update(&self, percent: u32, bandwidth: u64, message: &str) { println!("{}% - {} bytes/sec - {}", percent, bandwidth, message); } } let observer = Arc::new(MyObserver); DashDownloader::new(url) .add_progress_observer(observer) .download() .await?; ``` -------------------------------- ### Example Usage of DashDownloader with ProgressObserver Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/modules.md Demonstrates how to create a DashDownloader instance and attach a custom ConsoleObserver to receive progress updates during downloads. ```rust use dash_mpd::fetch::{DashDownloader, ProgressObserver}; use std::sync::Arc; struct ConsoleObserver; impl ProgressObserver for ConsoleObserver { fn update(&self, percent: u32, bandwidth: u64, message: &str) { println!("[{}%] {} - {} bytes/s", percent, message, bandwidth); } } let downloader = DashDownloader::new(url) .add_progress_observer(Arc::new(ConsoleObserver)); ``` -------------------------------- ### macOS Package Installation Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/features-and-configuration.md Installs necessary external tools for download functionality on macOS using Homebrew. ```bash brew install ffmpeg mkvtoolnix videolan/vlc/vlc gpac ``` -------------------------------- ### DashDownloader::new Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/dash-downloader.md Creates a new DashDownloader instance for a given DASH MPD manifest URL. This is the entry point for configuring and starting a download. ```APIDOC ## DashDownloader::new ### Description Create a new `DashDownloader` for the specified DASH manifest URL. ### Method `pub fn new(mpd_url: &str) -> DashDownloader` ### Parameters #### Path Parameters - **mpd_url** (string) - Required - URL of the DASH MPD manifest file ### Returns A new `DashDownloader` instance with default settings. ### Panics Will panic if `mpd_url` cannot be parsed as a valid URL. ### Example ```rust use dash_mpd::fetch::DashDownloader; let downloader = DashDownloader::new("https://example.com/stream.mpd"); ``` ``` -------------------------------- ### Linux Package Installation Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/features-and-configuration.md Installs necessary external tools for download functionality on Debian/Ubuntu and Fedora systems using their respective package managers. ```bash # Debian/Ubuntu sudo apt install ffmpeg mkvtoolnix vlc gpac # Fedora sudo dnf install ffmpeg mkvtoolnix vlc gpac ``` -------------------------------- ### Example: Iterating and Matching Subtitle Types Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/utility-functions.md Demonstrates how to iterate through AdaptationSets, identify subtitle streams using `is_subtitle_adaptation`, and then determine their specific format using the `subtitle_type` function. This example shows a common pattern for handling different subtitle types in a DASH MPD. ```rust use dash_mpd::{is_subtitle_adaptation, subtitle_type, SubtitleType}; for adaptation_set in &period.AdaptationSet { if is_subtitle_adaptation(&adaptation_set) { match subtitle_type(&adaptation_set) { SubtitleType::WebVTT => println!("WebVTT subtitles"), SubtitleType::TTML => println!("TTML subtitles"), SubtitleType::SRT => println!("SRT subtitles"), _ => println!("Other subtitle format"), } } } ``` -------------------------------- ### Download Media with Best Quality Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/README.md Use the DashDownloader to fetch media content from a given MPD URL. This example automatically selects the best available quality stream. ```rust use dash_mpd::fetch::DashDownloader; #[tokio::main] async fn main() -> Result<(), Box> { DashDownloader::new("https://example.com/stream.mpd") .best_quality() .download() .await?; Ok(()) } ``` -------------------------------- ### MPD to_string Method Example Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/mpd-types.md Demonstrates how to create an MPD instance and convert it into an XML string representation using the `to_string` method. This is useful for generating MPD manifests. ```rust use dash_mpd::MPD; let mpd = MPD { mpdtype: Some("static".into()), xmlns: Some("urn:mpeg:dash:schema:mpd:2011".into()), mediaPresentationDuration: Some(std::time::Duration::new(3600, 0)), minBufferTime: Some(std::time::Duration::new(3, 0)), ..Default::default() }; let xml_string = mpd.to_string(); ``` -------------------------------- ### Use XsDatetime for Availability Time Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/utility-functions.md Example demonstrating how to access and print an `XsDatetime` value, specifically for an `availabilityStartTime` field from an MPD object. ```rust use dash_mpd::XsDatetime; if let Some(avail_start) = &mpd.availabilityStartTime { println!("Availability started at: {}", avail_start); } ``` -------------------------------- ### Download and Decrypt DASH Content Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/modules.md Example of downloading DASH content and applying decryption using DashDownloader. It shows how to set the decryption key and preferred decryptor tool. ```rust use dash_mpd::fetch::DashDownloader; use std::path::PathBuf; #[tokio::main] async fn main() -> Result<(), Box> { let url = "https://example.com/protected-stream.mpd"; DashDownloader::new(url) .add_decryption_key("1".to_string(), "0123456789abcdef0123456789abcdef".to_string()) .with_decryptor_preference("mp4decrypt") .download_to(PathBuf::from("output.mp4")) .await?; Ok(()) } ``` -------------------------------- ### Apply XSLT stylesheet during download Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/features-and-configuration.md Demonstrates how to apply an XSLT stylesheet to an MPD manifest before downloading. This requires the 'xee-xslt' feature to be enabled and the 'xsltproc' tool to be installed. ```rust use dash_mpd::fetch::DashDownloader; DashDownloader::new(url) .with_xslt_stylesheet("/path/to/stylesheet.xslt") .download() .await?; ``` -------------------------------- ### Handle Download Errors Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/INDEX.md Implement robust error handling for download operations. This example shows how to match against specific `DashMpdError` variants like `NetworkTimeout` and general errors. ```rust match DashDownloader::new(url).download().await { Ok(path) => println!("Downloaded to: {path:?}"), Err(DashMpdError::NetworkTimeout(_)) => println!("Timeout"), Err(e) => println!("Error: {e}"), } ``` -------------------------------- ### AudioChannelConfiguration Struct Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/additional-types.md Defines the audio channel layout using a scheme URI and an optional value. Common schemes include MPEG-2 and Dolby, with example values for stereo and surround sound. ```rust pub struct AudioChannelConfiguration { pub schemeIdUri: String, pub value: Option, } ``` -------------------------------- ### Initialize Tokio Runtime for Async Operations Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/modules.md Demonstrates how to set up a tokio async runtime context for calling async functions like `download()` from the fetch, media, or decryption modules. Choose the appropriate `#[tokio::main]` attribute or manual runtime creation based on your needs. ```rust #[tokio::main] async fn main() { let result = DashDownloader::new(url).download().await; } ``` ```rust #[tokio::main(flavor = "multi_thread", worker_threads = 4)] async fn main() { // ... } ``` ```rust fn main() { tokio::runtime::Runtime::new().unwrap().block_on(async { let result = DashDownloader::new(url).download().await; }); } ``` -------------------------------- ### Range Struct Definition Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/additional-types.md Defines a time range for metrics reporting. Specify the start time and duration of the range. ```rust pub struct Range { pub starttime: Option, pub duration: Option, } ``` -------------------------------- ### Configure Video Quality and Resolution Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/INDEX.md Customize the download by specifying preferences for video quality and resolution. Use `.best_quality()` to select the highest available quality and `.prefer_video_height()` to target a specific resolution. ```rust DashDownloader::new(url) .best_quality() .prefer_video_height(1080) .download() .await?; ``` -------------------------------- ### Download with Custom Tool Paths Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/usage-examples.md Provide custom paths to external tools like FFmpeg, mkvmerge, and MP4Box if they are not in the system's PATH. ```rust use dash_mpd::fetch::DashDownloader; #[tokio::main] async fn main() -> Result<(), Box> { DashDownloader::new("https://example.com/stream.mpd") .with_ffmpeg("/opt/ffmpeg/bin/ffmpeg") .with_mkvmerge("/opt/mkvmerge/bin/mkvmerge") .with_mp4box("/opt/mp4box/bin/MP4Box") .download() .await?; Ok(()) } ``` -------------------------------- ### Create DashDownloader Instance Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/dash-downloader.md Instantiate a DashDownloader for a given DASH manifest URL. This sets up the downloader with default quality, role, and fetch preferences. ```rust use dash_mpd::fetch::DashDownloader; let downloader = DashDownloader::new("https://example.com/stream.mpd"); ``` -------------------------------- ### with_ffmpeg Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/dash-downloader.md Sets the path to the FFmpeg executable. If not provided, it defaults to 'ffmpeg'. ```APIDOC ## with_ffmpeg ### Description Sets the path to the FFmpeg executable. ### Method `with_ffmpeg(mut self, ffmpeg_path: &str) -> DashDownloader` ### Parameters #### Path Parameters - **ffmpeg_path** (string) - Required - The path to the FFmpeg executable. ``` -------------------------------- ### Download Media Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/INDEX.md Initiate a media download from a given URL using `DashDownloader::new` and the `download` method. This is the most basic download operation. ```rust DashDownloader::new(url).download().await?; ``` -------------------------------- ### UTCTiming Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/additional-types.md Specifies how to obtain the current UTC time for synchronized playback, supporting various schemes like HTTP HEAD, HTTP GET, and NTP. ```APIDOC ## UTCTiming ### Description Specifies how to obtain the current UTC time for synchronized playback. ### Fields - `schemeIdUri` (String) - URI identifying the timing scheme - `value` (Option) - Timing information value ### Common Schemes - urn:mpeg:dash:utc:http-head: (HTTP HEAD request) - urn:mpeg:dash:utc:http-xsdate: (HTTP GET returning XSD dateTime) - urn:mpeg:dash:utc:http-iso: (HTTP GET returning ISO 8601) - urn:mpeg:dash:utc:ntp: (NTP timing) ``` -------------------------------- ### Configure VLC Path Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/dash-downloader.md Set the path to the VLC executable. Defaults to 'vlc' or a common Windows path. ```rust pub fn with_vlc(mut self, vlc_path: &str) -> DashDownloader ``` -------------------------------- ### with_vlc Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/dash-downloader.md Sets the path to the VLC executable. Defaults to 'vlc' or a common Windows path. ```APIDOC ## with_vlc ### Description Sets the path to the VLC executable. ### Method `with_vlc(mut self, vlc_path: &str) -> DashDownloader` ### Parameters #### Path Parameters - **vlc_path** (string) - Required - The path to the VLC executable. ``` -------------------------------- ### Download with Progress Tracking Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/usage-examples.md Implement a custom progress observer to monitor download progress, including percentage, bandwidth, and status messages. ```rust use dash_mpd::fetch::{DashDownloader, ProgressObserver}; use std::sync::Arc; use std::sync::atomic::{AtomicU32, Ordering}; struct ProgressTracker { current_percent: Arc, } impl ProgressObserver for ProgressTracker { fn update(&self, percent: u32, bandwidth: u64, message: &str) { self.current_percent.store(percent, Ordering::Relaxed); eprintln!("[{:3}%] {} - {} Mbps", percent, message, bandwidth / 1_000_000); } } #[tokio::main] async fn main() -> Result<(), Box> { let tracker = Arc::new(ProgressTracker { current_percent: Arc::new(AtomicU32::new(0)), }); let observer = Arc::new(ProgressTracker { current_percent: tracker.current_percent.clone(), }); DashDownloader::new("https://example.com/stream.mpd") .add_progress_observer(observer) .download() .await?; Ok(()) } ``` -------------------------------- ### Build with experimental HTTP/3 support Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/features-and-configuration.md To enable experimental HTTP/3 support, you need to set the `RUSTFLAGS` environment variable and include the `http3` feature. ```bash RUSTFLAGS='--cfg reqwest_unstable' cargo build ``` -------------------------------- ### Download with Language and Quality Preferences Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/usage-examples.md Downloads a DASH stream, prioritizing specific audio/subtitle languages and video height. Requires `tokio`. ```rust use dash_mpd::fetch::DashDownloader; #[tokio::main] async fn main() -> Result<(), Box> { let url = "https://example.com/stream.mpd"; DashDownloader::new(url) .best_quality() .prefer_language("en".into()) // English audio & subtitles .prefer_video_height(1080) // 1080p preferred .fetch_subtitles(true) // Get subtitles .download() .await?; Ok(()) } ``` -------------------------------- ### Enable warnings for ignored XML elements Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/features-and-configuration.md This example shows a comment indicating that when the 'warn_ignored_elements' feature is enabled, warnings will be produced for unused XML elements in the manifest. These warnings are output to stderr during manifest parsing. ```rust // When enabled, produces warnings for: // Unused XML element in manifest: /MPD/ServiceDescription[1]/UnknownElement ``` -------------------------------- ### Configure Minimal Binary Size Build Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/features-and-configuration.md Optimize for minimal binary size in release builds by setting opt-level to 'z', enabling link-time optimization (lto), reducing codegen-units to 1, and enabling stripping. ```toml [profile.release] opt-level = "z" # Optimize for size lto = true codegen-units = 1 strip = true ``` -------------------------------- ### Period Structure Definition Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/mpd-types.md Defines the structure for a Period in an MPD, representing a sequence of media with identical duration and data streams. Includes fields for ID, duration, start time, and various media-related elements. ```rust pub struct Period { pub id: Option, pub duration: Option, pub start: Option, pub bitstreamSwitching: Option, pub xlink_href: Option, pub xlink_actuate: Option, pub BaseURL: Vec, pub SegmentBase: Option, pub SegmentList: Option, pub SegmentTemplate: Option, pub AssetIdentifier: Vec, pub EventStream: Vec, pub ServiceDescription: Vec, pub ContentProtection: Vec, pub AdaptationSet: Vec, pub Subset: Vec, pub BaseURL: Vec, } ``` -------------------------------- ### Configure MP4Box Path Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/dash-downloader.md Set the path to the MP4Box executable. ```rust pub fn with_mp4box(mut self, path: &str) -> DashDownloader ``` -------------------------------- ### Add Progress Tracking Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/INDEX.md Integrate progress monitoring into your downloads by providing an observer object. This allows you to track the download status and progress in real-time. ```rust DashDownloader::new(url) .add_progress_observer(observer) .download() .await?; ``` -------------------------------- ### Simple Download Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/usage-examples.md Performs a basic download of a DASH stream to the default location, selecting the worst quality available. Requires the `tokio` runtime. ```rust use dash_mpd::fetch::DashDownloader; #[tokio::main] async fn main() -> Result<(), Box> { let url = "https://storage.googleapis.com/shaka-demo-assets/heliocentrism/heliocentrism.mpd"; match DashDownloader::new(url) .worst_quality() .download() .await { Ok(path) => println!("Downloaded to: {path:?}"), Err(e) => eprintln!("Download failed: {e}"), } Ok(()) } ``` -------------------------------- ### Configure FFmpeg Path Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/dash-downloader.md Set the path to the FFmpeg executable. Defaults to 'ffmpeg'. ```rust pub fn with_ffmpeg(mut self, ffmpeg_path: &str) -> DashDownloader ``` -------------------------------- ### Build with Nightly for Maximum Features Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/features-and-configuration.md Build the project with all features enabled using a nightly Rust toolchain. This is necessary for certain unstable features. ```bash RUSTFLAGS='--cfg reqwest_unstable' cargo +nightly build --all-features ``` -------------------------------- ### DashDownloader::with_authentication Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/dash-downloader.md Configures HTTP Basic Authentication credentials to be used for network requests. ```APIDOC ## DashDownloader::with_authentication ### Description Set HTTP Basic Authentication credentials for network requests. ### Method `pub fn with_authentication(mut self, username: &str, password: &str) -> DashDownloader` ### Parameters #### Path Parameters - **username** (string) - Required - Username for authentication - **password** (string) - Required - Password for authentication ### Returns The `DashDownloader` instance with basic authentication configured. ``` -------------------------------- ### Configure External Tools Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/INDEX.md Specify paths to external tools like FFmpeg or preferred muxers for processing downloaded media. This allows integration with your existing media toolchain. ```rust DashDownloader::new(url) .with_ffmpeg("/custom/path") .with_muxer_preference("mp4", "ffmpeg,vlc") .download() .await?; ``` -------------------------------- ### Download Media Content with DashDownloader Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/api-reference-overview.md Utilize the `DashDownloader` from the `dash_mpd::fetch` module to download streaming media. Configure download quality (e.g., `worst_quality()`) and handle potential download errors asynchronously. ```rust use dash_mpd::fetch::DashDownloader; #[tokio::main] async fn main() { let url = "https://example.com/stream.mpd"; match DashDownloader::new(url) .worst_quality() .download() .await { Ok(path) => println!("Downloaded to: {path:?}"), Err(e) => eprintln!("Download failed: {e}"), } } ``` -------------------------------- ### Download with Specific Resolution Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/usage-examples.md Downloads a DASH stream, specifying preferred video width and height for a target resolution. Requires `tokio`. ```rust use dash_mpd::fetch::DashDownloader; #[tokio::main] async fn main() -> Result<(), Box> { let url = "https://example.com/stream.mpd"; DashDownloader::new(url) .prefer_video_width(1920) // 1080p: width=1920 .prefer_video_height(1080) // 1080p: height=1080 .download() .await?; Ok(()) } ``` -------------------------------- ### Enable fetch feature for downloads Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/features-and-configuration.md This Rust code snippet demonstrates how to use the `DashDownloader` when the `fetch` feature is enabled. It requires the `tokio` runtime. ```rust #[cfg(feature = "fetch")] use dash_mpd::fetch::DashDownloader; #[cfg(feature = "fetch")] #[tokio::main] async fn main() { let _ = DashDownloader::new("https://example.com/stream.mpd").download().await; } ``` -------------------------------- ### with_mp4box Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/dash-downloader.md Sets the path to the MP4Box executable. ```APIDOC ## with_mp4box ### Description Sets the path to the MP4Box executable. ### Method `with_mp4box(mut self, path: &str) -> DashDownloader` ### Parameters #### Path Parameters - **path** (string) - Required - The path to the MP4Box executable. ``` -------------------------------- ### Download Live Stream (Pseudo-live) Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/usage-examples.md Configure the downloader to handle live streams by allowing them and setting a force duration and sleep interval between requests. ```rust use dash_mpd::fetch::DashDownloader; use std::time::Duration; #[tokio::main] async fn main() -> Result<(), Box> { DashDownloader::new("https://example.com/pseudo-live.mpd") .allow_live_streams(true) .force_duration(600.0) // 10 minutes .sleep_between_requests(1) // 1 second between requests .download() .await?; Ok(()) } ``` -------------------------------- ### Download with Basic Authentication Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/usage-examples.md Download MPD streams that require basic HTTP authentication by providing a username and password. ```rust use dash_mpd::fetch::DashDownloader; #[tokio::main] async fn main() -> Result<(), Box> { DashDownloader::new("https://example.com/protected.mpd") .with_authentication("username", "password") .download() .await?; Ok(()) } ``` -------------------------------- ### Configure ffmpeg Location Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/modules.md Specify a custom path to the ffmpeg executable when initializing DashDownloader. This is useful if ffmpeg is not in the system's PATH. ```rust DashDownloader::new(url) .with_ffmpeg("/custom/path/to/ffmpeg") ``` -------------------------------- ### Download Content from MPD Manifest Source: https://github.com/emarsden/dash-mpd-rs/blob/main/README.md This asynchronous snippet shows how to download media content specified in an MPD manifest using the `DashDownloader`. It allows selecting the worst quality stream by default. Note that this is an async operation. ```rust use dash_mpd::fetch::DashDownloader; let url = "https://storage.googleapis.com/shaka-demo-assets/heliocentrism/heliocentrism.mpd"; match DashDownloader::new(url) .worst_quality() .download().await { Ok(path) => println!("Downloaded to {path:?}"), Err(e) => eprintln!("Download failed: {e:?}"), } ``` -------------------------------- ### Allow Live Streams Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/dash-downloader.md Configure whether to allow downloading from dynamic DASH manifests (live streams). Note that genuine live streams require clock-based throttling to function correctly. ```rust pub fn allow_live_streams(mut self, value: bool) -> DashDownloader ``` -------------------------------- ### Build with musl and rustls Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/features-and-configuration.md This command builds the project for musl libc using the `rustls` feature and disabling default features. Ensure `RUSTFLAGS` are set for PIC. ```bash RUSTFLAGS=-Crelocation-model=pic cargo build --target x86_64-unknown-linux-musl --features rustls --no-default-features ``` -------------------------------- ### with_shaka_packager Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/dash-downloader.md Sets the path to the shaka-packager executable. ```APIDOC ## with_shaka_packager ### Description Sets the path to the shaka-packager executable. ### Method `with_shaka_packager(mut self, path: &str) -> DashDownloader` ### Parameters #### Path Parameters - **path** (string) - Required - The path to the shaka-packager executable. ``` -------------------------------- ### Download with Custom Output Path Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/usage-examples.md Downloads a DASH stream and saves it to a specified file path. Uses `best_quality()` to select the highest quality stream. Requires `tokio` and `std::path::PathBuf`. ```rust use dash_mpd::fetch::DashDownloader; use std::path::PathBuf; #[tokio::main] async fn main() -> Result<(), Box> { let url = "https://example.com/stream.mpd"; let output = PathBuf::from("/tmp/video.mp4"); DashDownloader::new(url) .best_quality() .download_to(output) .await?; println!("Download complete!"); Ok(()) } ``` -------------------------------- ### Static Linking (musl) MPD Configuration Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/features-and-configuration.md Configure for static linking with musl for portable static binaries. This requires specific features like 'fetch' and 'rustls'. ```bash RUSTFLAGS="-C relocation-model=pic" \ cargo build --release --target x86_64-unknown-linux-musl \ --features "fetch,rustls" --no-default-features ``` -------------------------------- ### Configure MP4Decrypt Path Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/dash-downloader.md Set the path to the mp4decrypt executable from the Bento4 suite. ```rust pub fn with_mp4decrypt(mut self, path: &str) -> DashDownloader ``` -------------------------------- ### Download with Custom Muxer Preferences Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/usage-examples.md Specify preferred muxers and their associated tools for different output formats like MKV and MP4. ```rust use dash_mpd::fetch::DashDownloader; #[tokio::main] async fn main() -> Result<(), Box> { DashDownloader::new("https://example.com/stream.mpd") .with_muxer_preference("mkv", "mkvmerge,ffmpeg,vlc") .with_muxer_preference("mp4", "ffmpeg,vlc,mp4box") .download() .await?; Ok(()) } ``` -------------------------------- ### Configure HTTP Client for DashDownloader Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/dash-downloader.md Provide a custom reqwest::Client to the DashDownloader for advanced HTTP request configuration, such as setting timeouts or user agents. This is useful for controlling network behavior during downloads. ```rust use dash_mpd::fetch::DashDownloader; use std::time::Duration; let client = reqwest::Client::builder() .timeout(Duration::from_secs(30)) .user_agent("MyPlayer/1.0") .build() .unwrap(); let downloader = DashDownloader::new(url) .with_http_client(client); ``` -------------------------------- ### Enable Hickory DNS resolver Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/features-and-configuration.md To use the Hickory DNS resolver instead of the system's, enable the `hickory-dns` feature along with `fetch`. ```toml [dependencies] dash-mpd = { version = "0.20", features = ["fetch", "hickory-dns"] } ``` -------------------------------- ### Enable Verbose Logging with Tracing Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/features-and-configuration.md Enable detailed logging by initializing the tracing subscriber with the DEBUG level. This helps in diagnosing issues by providing more granular output. ```rust use tracing_subscriber; // In main() tracing_subscriber::fmt() .with_max_level(tracing::Level::DEBUG) .init(); DashDownloader::new(url) .verbosity(2) // 0=none, 1=info, 2=debug .download() .await? ``` -------------------------------- ### Configure Release Build Optimizations Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/features-and-configuration.md Optimize for performance in release builds by setting opt-level to 3, enabling link-time optimization (lto), and reducing codegen-units to 1. ```toml [profile.release] opt-level = 3 lto = true codegen-units = 1 ``` -------------------------------- ### Enable Sandbox on DashDownloader Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/modules.md Conditionally enables sandboxing for DashDownloader on Linux using the 'fetch' and 'sandbox' features. Sandboxing restricts filesystem access and network binding. ```rust use dash_mpd::fetch::DashDownloader; #[cfg(target_os = "linux")] let downloader = DashDownloader::new(url) .sandbox(true); #[cfg(not(target_os = "linux"))] let downloader = DashDownloader::new(url); downloader.download().await?; ``` -------------------------------- ### allow_live_streams Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/dash-downloader.md Allow downloading from dynamic DASH manifests (live streams). Note: Genuine live streams won't work without clock-based throttling. ```APIDOC ## allow_live_streams ### Description Allow downloading from dynamic DASH manifests (live streams). Note: Genuine live streams won't work without clock-based throttling. ### Method ```rust pub fn allow_live_streams(mut self, value: bool) -> DashDownloader ``` ### Parameters #### Query Parameters - **value** (bool) - Required - Whether to allow live streams ``` -------------------------------- ### add_progress_observer Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/dash-downloader.md Register an observer to receive download progress updates. The observer will receive updates on percentage completion, bandwidth usage, and status messages. ```APIDOC ## add_progress_observer ### Description Register an observer to receive download progress updates. ### Method Signature ```rust pub fn add_progress_observer(mut self, observer: Arc) -> DashDownloader ``` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Parameters - **observer** (Arc) - Required - Observer implementing ProgressObserver trait. The observer receives updates with: percent (0-100), bandwidth (octets/sec), and status message. ``` -------------------------------- ### Download with Custom HTTP Client Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/usage-examples.md Configure a custom reqwest client with specific timeouts, user agents, and certificate validation settings for downloading MPD streams. ```rust use dash_mpd::fetch::DashDownloader; use std::time::Duration; #[tokio::main] async fn main() -> Result<(), Box> { let client = reqwest::Client::builder() .timeout(Duration::from_secs(30)) .user_agent("MyPlayer/1.0") .danger_accept_invalid_certs(true) // For testing only! .build()?; DashDownloader::new("https://example.com/stream.mpd") .with_http_client(client) .with_referer("https://example.com") .download() .await?; Ok(()) } ``` -------------------------------- ### Configure Shaka Packager Path Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/dash-downloader.md Set the path to the shaka-packager executable. ```rust pub fn with_shaka_packager(mut self, path: &str) -> DashDownloader ``` -------------------------------- ### Add Dependencies to Cargo.toml Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/README.md Include the dash-mpd and tokio crates in your project's Cargo.toml file. The dash-mpd crate includes download support by default. ```toml [dependencies] dash-mpd = "0.20" # Includes download support by default tokio = { version = "1", features = ["full"] } ``` -------------------------------- ### Download Stream to Specified Path Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/dash-downloader.md Downloads a stream to a specific output file path. Ensure the output path is valid and the directory exists. Returns the output path or an error. ```rust use std::path::PathBuf; let output = PathBuf::from("/tmp/stream.mp4"); let path = DashDownloader::new(url) .best_quality() .with_referer("https://example.com") .download_to(output) .await?; ``` -------------------------------- ### ProgressObserver Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/modules.md A trait for observing download progress. Implement this trait to receive updates on download percentage, bandwidth, and status messages. ```APIDOC ## Trait: ProgressObserver ### Description Trait for receiving progress notifications during media downloads. ### Methods #### update ##### Description Called with progress updates during the download process. ##### Parameters - **percent** (u32) - The current download progress percentage. - **bandwidth** (u64) - The current download bandwidth in bytes per second. - **message** (&str) - A status message describing the current operation. ### Example ```rust use dash_mpd::fetch::ProgressObserver; use std::sync::Arc; struct ConsoleObserver; impl ProgressObserver for ConsoleObserver { fn update(&self, percent: u32, bandwidth: u64, message: &str) { println!("[{}%] {} - {} bytes/s", percent, message, bandwidth); } } // Usage with DashDownloader would involve passing an Arc // let downloader = DashDownloader::new(url).add_progress_observer(Arc::new(ConsoleObserver)); ``` ``` -------------------------------- ### Set Download Rate Limit Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/features-and-configuration.md Configure a specific download rate limit for the `DashDownloader`. The value is in bits per second. ```rust DashDownloader::new(url) .with_rate_limit(5_000_000) // 5 Mbps ``` -------------------------------- ### save_fragments_to Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/dash-downloader.md Save downloaded media fragments to a directory instead of deleting them. The directory will be created if it doesn't exist. ```APIDOC ## save_fragments_to ### Description Save downloaded media fragments to a directory instead of deleting them. The directory will be created if it doesn't exist. ### Method Signature ```rust pub fn save_fragments_to>(mut self, fragment_path: P) -> DashDownloader ``` ### Parameters #### Path Parameters - **fragment_path** (Path) - Required - Directory to save fragments ``` -------------------------------- ### DashDownloader::with_http_client Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/dash-downloader.md Provides a custom `reqwest::Client` for making HTTP requests. This allows for advanced configuration such as timeouts, proxies, and custom headers. ```APIDOC ## DashDownloader::with_http_client ### Description Provide a custom `reqwest::Client` for HTTP requests. Allows configuration of proxies, custom headers, timeouts, TLS settings, etc. ### Method `pub fn with_http_client(mut self, client: HttpClient) -> DashDownloader` ### Parameters #### Path Parameters - **client** (HttpClient) - Optional - Pre-configured reqwest HTTP client ### Returns The `DashDownloader` instance with the custom HTTP client configured. ### Example ```rust use dash_mpd::fetch::DashDownloader; use std::time::Duration; let client = reqwest::Client::builder() .timeout(Duration::from_secs(30)) .user_agent("MyPlayer/1.0") .build() .unwrap(); let downloader = DashDownloader::new(url) .with_http_client(client); ``` ``` -------------------------------- ### download Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/dash-downloader.md Initiates the download of the stream to a temporary directory with an auto-generated filename. Returns the path to the downloaded file upon success. ```APIDOC ## download ### Description Download the stream to a temporary directory with auto-generated filename. ### Method Signature ```rust pub async fn download(mut self) -> Result ``` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Returns - **Result** - Path to the downloaded file or an error. ### Example ```rust let path = DashDownloader::new(url) .worst_quality() .download() .await?; println!("Downloaded to: {path:?}"); ``` ``` -------------------------------- ### Configure sandbox feature for Linux Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/features-and-configuration.md Enables the 'fetch' and 'sandbox' features for Linux systems, requiring kernel 5.13+ with Landlock support. This configuration restricts filesystem access and limits process capabilities for security. ```toml [cfg(target_os = "linux")] [dependencies] dash-mpd = { version = "0.20", features = ["fetch", "sandbox"] } ``` -------------------------------- ### Download Stream to Temporary Directory Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/dash-downloader.md Initiates the download of a stream to a temporary directory with an auto-generated filename. Returns the path to the downloaded file or an error. ```rust let path = DashDownloader::new(url) .worst_quality() .download() .await?; println!("Downloaded to: {path:?}"); ``` -------------------------------- ### Find Audio Streams by Language and Bitrate Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/usage-examples.md Filters for audio adaptation sets and lists them by language, along with the bitrates of their representations. Helps in selecting audio tracks. ```rust use dash_mpd::{parse, is_audio_adaptation}; fn main() -> Result<(), Box> { let mpd = parse(xml)?; for period in &mpd.periods { for adaptation in period.AdaptationSet.iter().filter(is_audio_adaptation) { let lang = adaptation.lang.as_deref().unwrap_or("unknown"); println!("Audio: {} ({} bitrates)", lang, adaptation.representations.len()); for rep in &adaptation.representations { if let Some(bw) = rep.bandwidth { println!(" {}kbps", bw / 1000); } } } } Ok(()) } ``` -------------------------------- ### Configure SOCKS5 proxy for downloads Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/features-and-configuration.md This Rust code shows how to configure a `reqwest::Client` to use a SOCKS5 proxy when the `socks` feature is enabled. ```rust #[cfg(feature = "socks")] let client = reqwest::Client::builder() .proxy(reqwest::Proxy::all("socks5://proxy.example.com:1080")?) .build()?; ``` -------------------------------- ### with_mp4decrypt Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/dash-downloader.md Sets the path to the mp4decrypt executable from the Bento4 suite. ```APIDOC ## with_mp4decrypt ### Description Sets the path to the mp4decrypt executable from the Bento4 suite. ### Method `with_mp4decrypt(mut self, path: &str) -> DashDownloader` ### Parameters #### Path Parameters - **path** (string) - Required - The path to the mp4decrypt executable. ``` -------------------------------- ### Generate an MPD Manifest Struct Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/api-reference-overview.md Create an `MPD` struct, populating fields like `ProgramInformation` and `Title`, to represent a Media Presentation Description. Convert the struct to an XML string using its `to_string()` method. ```rust use dash_mpd::{MPD, ProgramInformation, Title}; let pi = ProgramInformation { Title: Some(Title { content: Some("My Stream".into()) }), ..Default::default() }; let mpd = MPD { mpdtype: Some("static".into()), xmlns: Some("urn:mpeg:dash:schema:mpd:2011".into()), ProgramInformation: vec![pi], ..Default::default() }; let xml = mpd.to_string(); ``` -------------------------------- ### Download Video Only (Keep Separate) Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/usage-examples.md Downloads only the video component of a DASH stream and keeps it in its original format (e.g., H.264). Requires `tokio` and `std::path::PathBuf`. ```rust use dash_mpd::fetch::DashDownloader; use std::path::PathBuf; #[tokio::main] async fn main() -> Result<(), Box> { let url = "https://example.com/stream.mpd"; DashDownloader::new(url) .video_only() .keep_video_as("/tmp/video_stream.h264") .download() .await?; Ok(()) } ``` -------------------------------- ### Initialization Struct Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/additional-types.md Specifies the initialization segment required before media segments can be decoded, including its source URL and byte range. ```rust pub struct Initialization { pub sourceURL: Option, pub range: Option, } ``` -------------------------------- ### parse Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/utility-functions.md Parses an XML string containing a DASH Media Presentation Description manifest into an `MPD` structure. Handles potential XML parsing or deserialization errors. ```APIDOC ## parse ### Description Parse an XML string containing a DASH Media Presentation Description manifest into an `MPD` structure. ### Function Signature ```rust pub fn parse(xml: &str) -> Result ``` ### Parameters #### Path Parameters - **xml** (string) - Required - XML string containing the MPD manifest ### Returns - `Result` - The parsed MPD structure or a parsing error. ### Errors - `DashMpdError::Parsing(String)` - XML parsing or deserialization failed ### Example ```rust use dash_mpd::parse; let xml = r###" "###; match parse(xml) { Ok(mpd) => println!("Parsed MPD with {} periods", mpd.periods.len()), Err(e) => eprintln!("Parse error: {}", e), } ``` ``` -------------------------------- ### Set Worst Quality Preference (Default) Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/dash-downloader.md Prefer the Representation with the lowest bitrate. This is the default setting. ```rust pub fn worst_quality(mut self) -> DashDownloader ``` -------------------------------- ### download_to Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/dash-downloader.md Downloads the stream to a specified output file path. Returns the output path upon successful download. ```APIDOC ## download_to ### Description Download the stream to a specified output file path. ### Method Signature ```rust pub async fn download_to>(mut self, out: P) -> Result ``` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Parameters - **out** (Path) - Required - Output file path. ### Returns - **Result** - The output path or an error. ### Example ```rust use std::path::PathBuf; let output = PathBuf::from("/tmp/stream.mp4"); let path = DashDownloader::new(url) .best_quality() .with_referer("https://example.com") .download_to(output) .await?; ``` ``` -------------------------------- ### Enable fetch and http2 features Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/features-and-configuration.md To use HTTP/2 with dash-mpd, ensure both the `fetch` and `http2` features are enabled in Cargo.toml. ```toml [dependencies] dash-mpd = { version = "0.20", features = ["fetch"], default-features = false } ``` -------------------------------- ### Set Preferred Language Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/dash-downloader.md Set the preferred language for both audio and subtitles. Must be in RFC 5646 format. ```rust pub fn prefer_language(mut self, lang: String) -> DashDownloader ``` -------------------------------- ### Implement ProgressObserver Trait Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/modules.md A trait for observing download progress, providing updates on percentage, bandwidth, and status messages. Requires Send and Sync. ```rust pub trait ProgressObserver: Send + Sync { fn update(&self, percent: u32, bandwidth: u64, message: &str); } ``` -------------------------------- ### Configure XSLT stylesheet processing Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/features-and-configuration.md Enables the 'fetch' and 'xee-xslt' features in Cargo.toml to allow XSLT stylesheet processing for MPD manifests. This requires the 'xee-xslt-compiler' crate and the 'xsltproc' tool. ```toml [dependencies] dash-mpd = { version = "0.20", features = ["fetch", "xee-xslt"] } ``` -------------------------------- ### Generate MPD Manifest Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/INDEX.md Create an MPD manifest programmatically by constructing an `MPD` struct and then serializing it to an XML string using the `to_string` method. ```rust let mpd = MPD { /* fields */ }; let xml = mpd.to_string(); ``` -------------------------------- ### Use Index Range for Segments Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/dash-downloader.md Configure whether to use sidx/Cue indexes for SegmentBase@indexRange addressing. When true, byte ranges are used; when false, content is downloaded as a single chunk. ```rust pub fn use_index_range(mut self, value: bool) -> DashDownloader ``` -------------------------------- ### Enable sandbox feature in Rust code Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/features-and-configuration.md Conditionally enables the 'fetch' and 'sandbox' features at compile time for Linux, then initializes DashDownloader with sandboxing enabled. This restricts filesystem access and limits process capabilities. ```rust #[cfg(all(feature = "fetch", feature = "sandbox", target_os = "linux"))] let downloader = DashDownloader::new(url).sandbox(true); ``` -------------------------------- ### Enable rustls TLS implementation Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/features-and-configuration.md To use the pure Rust TLS implementation, enable the `rustls` feature and disable default features. ```toml [dependencies] dash-mpd = { version = "0.20", features = ["fetch", "rustls"], default-features = false } ``` -------------------------------- ### DashDownloader::with_referer Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/dash-downloader.md Sets the HTTP Referer header for all network requests made by the downloader, including manifest and segment fetches. ```APIDOC ## DashDownloader::with_referer ### Description Set the HTTP Referer header used in all network requests (manifest, segments, subtitles). ### Method `pub fn with_referer(mut self, referer: String) -> DashDownloader` ### Parameters #### Path Parameters - **referer** (string) - Optional - Referer header value ### Returns The `DashDownloader` instance with the referer header configured. ``` -------------------------------- ### prefer_language Source: https://github.com/emarsden/dash-mpd-rs/blob/main/_autodocs/dash-downloader.md Set the preferred language for both audio and subtitles. Must be in RFC 5646 format. ```APIDOC ## prefer_language ### Description Set the preferred language for both audio and subtitles. Must be in RFC 5646 format. ### Method ```rust pub fn prefer_language(mut self, lang: String) -> DashDownloader ``` ### Parameters #### Request Body - **lang** (String) - Required - Language code (e.g., "en", "fr-FR", "en-AU") ```