Struct Youtube

Source
pub struct Youtube {
    pub libraries: Libraries,
    pub output_dir: PathBuf,
    pub args: Vec<String>,
    pub timeout: Duration,
    pub cache: Option<Arc<VideoCache>>,
    pub download_cache: Option<Arc<DownloadCache>>,
    pub download_manager: Arc<DownloadManager>,
}
Expand description

A YouTube video fetcher that uses yt-dlp to fetch video information and download it.

The ‘yt-dlp’ executable and ‘ffmpeg’ build can be installed with this fetcher.

The video can be downloaded with or without its audio, and the audio and video can be combined. The video thumbnail can also be downloaded.

The major implementations of this struct are located in the ‘fetcher’ module.

§Examples

let libraries_dir = PathBuf::from("libs");
let output_dir = PathBuf::from("output");

let youtube = libraries_dir.join("yt-dlp");
let ffmpeg = libraries_dir.join("ffmpeg");

let libraries = Libraries::new(youtube, ffmpeg);
let mut fetcher = Youtube::new(libraries, output_dir)?;

let url = String::from("https://www.youtube.com/watch?v=dQw4w9WgXcQ");
let video = fetcher.fetch_video_infos(url).await?;
println!("Video title: {}", video.title);

fetcher.download_video(&video, "video.mp4").await?;

Fields§

§libraries: Libraries

The required libraries.

§output_dir: PathBuf

The directory where the video (or formats) will be downloaded.

§args: Vec<String>

The arguments to pass to ‘yt-dlp’.

§timeout: Duration

The timeout for command execution.

§cache: Option<Arc<VideoCache>>

The cache for video metadata.

§download_cache: Option<Arc<DownloadCache>>

The cache for downloaded files.

§download_manager: Arc<DownloadManager>

The download manager for managing parallel downloads.

Implementations§

Source§

impl Youtube

Source

pub async fn fetch_video_infos(&self, url: String) -> Result<Video>

Fetch the video information from the given URL.

§Arguments
  • url - The URL of the video to fetch.
§Errors

This function will return an error if the video information could not be fetched.

§Examples
let fetcher = Youtube::new(libraries, output_dir)?;

let url = String::from("https://www.youtube.com/watch?v=dQw4w9WgXcQ");
let video = fetcher.fetch_video_infos(url).await?;
Source

pub async fn download_video_from_url( &self, url: String, output: impl AsRef<str> + Debug + Display, ) -> Result<PathBuf>

Fetch the video from the given URL, download it (video with audio) and returns its path. Be careful, this function may take a while to execute.

§Arguments
  • url - The URL of the video to download.
  • output - The name of the file to save the video to.
§Errors

This function will return an error if the video could not be fetched or downloaded.

§Examples
let fetcher = Youtube::new(libraries, output_dir)?;

let url = String::from("https://www.youtube.com/watch?v=dQw4w9WgXcQ");
let video_path = fetcher.download_video_from_url(url, "my-video.mp4").await?;
Source

pub async fn download_video( &self, video: &Video, output: impl AsRef<str> + Debug + Display, ) -> Result<PathBuf>

Fetch the video, download it (video with audio) and returns its path. Be careful, this function may take a while to execute.

§Arguments
  • video - The video to download.
  • output - The name of the file to save the video to.
§Errors

This function will return an error if the video could not be downloaded.

§Examples
let fetcher = Youtube::new(libraries, output_dir)?;

let url = String::from("https://www.youtube.com/watch?v=dQw4w9WgXcQ");
let video = fetcher.fetch_video_infos(url).await?;

let video_path = fetcher.download_video(&video, "my-video.mp4").await?;
Source

pub async fn download_video_stream_from_url( &self, url: String, output: impl AsRef<str> + Debug + Display, ) -> Result<PathBuf>

Fetch the video from the given URL, download it and returns its path. Be careful, this function may take a while to execute.

§Arguments
  • url - The URL of the video to download.
  • output - The name of the file to save the video to.
§Errors

This function will return an error if the video could not be fetched or downloaded.

§Examples
let fetcher = Youtube::new(libraries, output_dir)?;

let url = String::from("https://www.youtube.com/watch?v=dQw4w9WgXcQ");
let video_path = fetcher.download_video_stream_from_url(url, "my-video-stream.mp4").await?;
Source

pub async fn download_video_stream( &self, video: &Video, output: impl AsRef<str> + Debug + Display, ) -> Result<PathBuf>

Download the video only, and returns its path. Be careful, this function may take a while to execute.

§Arguments
  • video - The video to download.
  • output - The name of the file to save the video to.
§Errors

This function will return an error if the video could not be fetched or downloaded.

§Examples
let fetcher = Youtube::new(libraries, output_dir)?;

let url = String::from("https://www.youtube.com/watch?v=dQw4w9WgXcQ");
let video = fetcher.fetch_video_infos(url).await?;

let video_path = fetcher.download_video_stream(&video, "my-video-stream.mp4").await?;
Source

pub async fn download_audio_stream_from_url( &self, url: String, output: impl AsRef<str> + Debug + Display, ) -> Result<PathBuf>

Fetch the audio stream from the given URL, download it and returns its path. Be careful, this function may take a while to execute.

§Arguments
  • url - The URL of the video to download.
  • output - The name of the file to save the audio to.
§Errors

This function will return an error if the video could not be fetched or downloaded.

§Examples
let fetcher = Youtube::new(libraries, output_dir)?;

let url = String::from("https://www.youtube.com/watch?v=dQw4w9WgXcQ");
let audio_path = fetcher.download_audio_stream_from_url(url, "my-audio.mp3").await?;
Source

pub async fn download_audio_stream( &self, video: &Video, output: impl AsRef<str> + Debug + Display, ) -> Result<PathBuf>

Fetch the audio stream, download it and returns its path. Be careful, this function may take a while to execute.

§Arguments
  • video - The video to download the audio from.
  • output - The name of the file to save the audio to.
§Errors

This function will return an error if the audio could not be downloaded.

§Examples
let fetcher = Youtube::new(libraries, output_dir)?;

let url = String::from("https://www.youtube.com/watch?v=dQw4w9WgXcQ");
let video = fetcher.fetch_video_infos(url).await?;

let audio_path = fetcher.download_audio_stream(&video, "my-audio.mp3").await?;
Source

pub async fn download_format( &self, format: &Format, output: impl AsRef<str> + Debug + Display, ) -> Result<PathBuf>

Downloads a format. Be careful, this function may take a while to execute.

§Arguments
  • format - The format to download.
  • output - The name of the file to save the format to.
§Errors

This function will return an error if the video could not be downloaded.

§Examples
let fetcher = Youtube::new(libraries, output_dir)?;

let url = String::from("https://www.youtube.com/watch?v=dQw4w9WgXcQ");
let video = fetcher.fetch_video_infos(url).await?;

let video_format = video.best_video_format().unwrap();
let format_path = fetcher.download_format(&video_format, "my-video-stream.mp4").await?;

let audio_format = video.worst_audio_format().unwrap();
let audio_path = fetcher.download_format(&audio_format, "my-audio-stream.mp3").await?;
Source

pub async fn download_format_with_preferences( &self, format: &Format, output: impl AsRef<str> + Debug + Display, video_quality: Option<VideoQuality>, audio_quality: Option<AudioQuality>, video_codec: Option<VideoCodecPreference>, audio_codec: Option<AudioCodecPreference>, ) -> Result<PathBuf>

Downloads a format with specific quality and codec preferences.

This method allows fine-grained control over the download process by specifying quality and codec preferences for both video and audio components of the format.

§Arguments
  • format - The format to download
  • output - The name of the output file
  • video_quality - Optional video quality preference
  • audio_quality - Optional audio quality preference
  • video_codec - Optional video codec preference
  • audio_codec - Optional audio codec preference
§Returns
  • PathBuf - The path to the downloaded format
§Errors

This function will return an error if the video could not be downloaded.

Source

pub async fn get_video_by_id(&self, video_id: &str) -> Option<Video>

Retrieve a video by its ID, checking the cache first if available

§Arguments
  • video_id - The ID of the video to find
§Returns
  • Option<Video> - The video if found, None otherwise
Source§

impl Youtube

Source

pub async fn download_thumbnail_from_url( &self, url: String, output: impl AsRef<str> + Debug + Display, ) -> Result<PathBuf>

Downloads the thumbnail of the video from the given URL, usually in the highest resolution available. Be careful, this function may take a while to execute.

§Arguments
  • url - The URL of the video to download the thumbnail from.
  • output - The name of the file to save the thumbnail to.
§Errors

This function will return an error if the thumbnail could not be downloaded.

§Examples
let fetcher = Youtube::new(libraries, output_dir)?;

let url = String::from("https://www.youtube.com/watch?v=dQw4w9WgXcQ");
let thumbnail_path = fetcher.download_thumbnail_from_url(url, "thumbnail.jpg").await?;
Source

pub async fn download_thumbnail( &self, video: &Video, output: impl AsRef<str> + Debug + Display, ) -> Result<PathBuf>

Downloads the thumbnail of the video, usually in the highest resolution available. Be careful, this function may take a while to execute.

§Arguments
  • url - The URL of the video to download the thumbnail from.
  • file_name - The name of the file to save the thumbnail to.
§Errors

This function will return an error if the thumbnail could not be fetched or downloaded.

§Examples
let fetcher = Youtube::new(libraries, output_dir)?;

let url = String::from("https://www.youtube.com/watch?v=dQw4w9WgXcQ");
let video = fetcher.fetch_video_infos(url).await?;

let thumbnail_path = fetcher.download_thumbnail(&video, "thumbnail.jpg").await?;
Source

pub async fn download_thumbnail_from_video( &self, video: &Video, file_name: impl AsRef<str> + Debug + Display, ) -> Result<PathBuf>

Source§

impl Youtube

Source

pub fn new( libraries: Libraries, output_dir: impl AsRef<Path> + Debug, ) -> Result<Self>

Creates a new YouTube fetcher with the given yt-dlp executable, ffmpeg executable and video URL. The output directory can be void if you only want to fetch the video information.

§Arguments
  • libraries - The required libraries.
  • output_dir - The directory where the video will be downloaded.
§Errors

This function will return an error if the parent directories of the executables and output directory could not be created.

§Examples
let libraries_dir = PathBuf::from("libs");
let output_dir = PathBuf::from("output");

let youtube = libraries_dir.join("yt-dlp");
let ffmpeg = libraries_dir.join("ffmpeg");

let libraries = Libraries::new(youtube, ffmpeg);
let fetcher = Youtube::new(libraries, output_dir)?;
Source

pub fn with_download_manager_config( libraries: Libraries, output_dir: impl AsRef<Path> + Debug, download_manager_config: ManagerConfig, ) -> Result<Self>

Creates a new YouTube fetcher with a custom download manager configuration.

§Arguments
  • libraries - The required libraries.
  • output_dir - The directory where the video will be downloaded.
  • download_manager_config - The configuration for the download manager.
§Errors

This function will return an error if the parent directories of the executables and output directory could not be created.

Source

pub async fn with_new_binaries( executables_dir: impl AsRef<Path> + Debug, output_dir: impl AsRef<Path> + Debug, ) -> Result<Self>

Creates a new YouTube fetcher, and installs the yt-dlp and ffmpeg binaries. The output directory can be void if you only want to fetch the video information. Be careful, this function may take a while to execute.

§Arguments
  • executables_dir - The directory where the binaries will be installed.
  • output_dir - The directory where the video will be downloaded.
§Errors

This function will return an error if the executables could not be installed.

§Examples
let executables_dir = PathBuf::from("libs");
let output_dir = PathBuf::from("output");

let fetcher = Youtube::with_new_binaries(executables_dir, output_dir).await?;
Source

pub fn with_args(&mut self, args: Vec<String>) -> &mut Self

Sets the arguments to pass to yt-dlp.

§Arguments
  • args - The arguments to pass to yt-dlp.
§Examples
let mut fetcher = Youtube::new(libraries, output_dir)?;

let args = vec!["--no-progress".to_string()];
fetcher.with_args(args);
Source

pub fn with_timeout(&mut self, timeout: Duration) -> &mut Self

Sets the timeout for command execution.

§Arguments
  • timeout - The timeout duration for command execution.
§Examples
let mut fetcher = Youtube::new(libraries, output_dir)?;

// Set a longer timeout for large videos
fetcher.with_timeout(Duration::from_secs(300));
Source

pub fn with_arg(&mut self, arg: impl AsRef<str>) -> &mut Self

Adds an argument to pass to yt-dlp.

§Arguments
  • arg - The argument to pass to yt-dlp.
§Examples
let mut fetcher = Youtube::new(libraries, output_dir)?;

fetcher.with_arg("--no-progress");
Source

pub async fn update_downloader(&self) -> Result<()>

Updates the yt-dlp executable. Be careful, this function may take a while to execute.

§Errors

This function will return an error if the yt-dlp executable could not be updated.

§Examples
let fetcher = Youtube::new(libraries, output_dir)?;

fetcher.update_downloader().await?;
Source

pub async fn combine_audio_and_video( &self, audio_file: impl AsRef<str> + Debug + Display, video_file: impl AsRef<str> + Debug + Display, output_file: impl AsRef<str> + Debug + Display, ) -> Result<PathBuf>

Combines the audio and video files into a single file. Be careful, this function may take a while to execute.

§Arguments
  • audio_file - The name of the audio file to combine.
  • video_file - The name of the video file to combine.
  • output_file - The name of the output file.
§Errors

This function will return an error if the audio and video files could not be combined.

§Examples
let fetcher = Youtube::new(libraries, output_dir)?;

let url = String::from("https://www.youtube.com/watch?v=dQw4w9WgXcQ");
let video = fetcher.fetch_video_infos(url).await?;

let audio_format = video.best_audio_format().unwrap();
let audio_path = fetcher.download_format(&audio_format, "audio-stream.mp3").await?;

let video_format = video.worst_video_format().unwrap();
let format_path = fetcher.download_format(&video_format, "video-stream.mp4").await?;

let output_path = fetcher.combine_audio_and_video("audio-stream.mp3", "video-stream.mp4", "my-output.mp4").await?;
Source

pub fn with_cache( &mut self, cache_dir: impl AsRef<Path> + Debug, ttl: Option<u64>, ) -> Result<&mut Self>

Enables caching of video metadata.

§Arguments
  • cache_dir - The directory where to store the cache.
  • ttl - The time-to-live for cache entries in seconds (default: 24 hours).
§Errors

This function will return an error if the cache directory could not be created.

§Examples
let mut fetcher = Youtube::new(libraries, output_dir)?;

// Enable video metadata caching
fetcher.with_cache(PathBuf::from("cache"), None)?;
Source

pub fn with_download_cache( &mut self, cache_dir: impl AsRef<Path> + Debug, ttl: Option<u64>, ) -> Result<&mut Self>

Enables caching of downloaded files.

§Arguments
  • cache_dir - The directory where to store the cache.
  • ttl - The time-to-live for cache entries in seconds (default: 7 days).
§Errors

This function will return an error if the cache directory could not be created.

§Examples
let mut fetcher = Youtube::new(libraries, output_dir)?;

// Enable downloaded files caching
fetcher.with_download_cache(PathBuf::from("cache"), None)?;
Source

pub async fn download_video_with_priority( &self, video: &Video, output: impl AsRef<str> + Debug, priority: Option<DownloadPriority>, ) -> Result<u64>

Download a video using the download manager with priority.

This method adds the video download to the download queue with the specified priority. The download will be processed according to its priority and the current load.

§Arguments
  • video - The video to download.
  • output - The name of the file to save the video to.
  • priority - The download priority (optional).
§Returns

The download ID that can be used to track the download status.

§Errors

This function will return an error if the video information could not be retrieved.

Source

pub async fn download_video_with_progress<F>( &self, video: &Video, output: impl AsRef<str> + Debug, progress_callback: F, ) -> Result<u64>
where F: Fn(u64, u64) + Send + Sync + 'static,

Download a video using the download manager with progress tracking.

This method adds the video download to the download queue and provides progress updates.

§Arguments
  • video - The video to download.
  • output - The name of the file to save the video to.
  • progress_callback - A function that will be called with progress updates.
§Returns

The download ID that can be used to track the download status.

§Errors

This function will return an error if the video information could not be retrieved.

Source

pub async fn get_download_status( &self, download_id: u64, ) -> Option<DownloadStatus>

Get the status of a download.

§Arguments
  • download_id - The ID of the download to check.
§Returns

The download status, or None if the download ID is not found.

Source

pub async fn cancel_download(&self, download_id: u64) -> bool

Cancel a download.

§Arguments
  • download_id - The ID of the download to cancel.
§Returns

true if the download was canceled, false if it was not found or already completed.

Source

pub async fn wait_for_download( &self, download_id: u64, ) -> Option<DownloadStatus>

Wait for a download to complete.

§Arguments
  • download_id - The ID of the download to wait for.
§Returns

The final download status, or None if the download ID is not found.

Source

pub async fn download_video_with_quality( &self, url: impl AsRef<str> + Debug + Display, output: impl AsRef<str> + Debug + Display, video_quality: VideoQuality, video_codec: VideoCodecPreference, audio_quality: AudioQuality, audio_codec: AudioCodecPreference, ) -> Result<PathBuf>

Downloads a video with the specified video and audio quality preferences.

§Arguments
  • url - The URL of the video to download
  • output - The name of the output file
  • video_quality - The desired video quality
  • video_codec - The preferred video codec
  • audio_quality - The desired audio quality
  • audio_codec - The preferred audio codec
§Returns

The path to the downloaded video file

§Example
let url = String::from("https://www.youtube.com/watch?v=dQw4w9WgXcQ");

// Download a high quality video with VP9 codec and high quality audio with Opus codec
let video_path = fetcher.download_video_with_quality(
    url,
    "my-video.mp4",
    VideoQuality::High,
    VideoCodecPreference::VP9,
    AudioQuality::High,
    AudioCodecPreference::Opus
).await?;
Source

pub async fn download_video_stream_with_quality( &self, url: impl AsRef<str> + Debug + Display, output: impl AsRef<str> + Debug + Display, quality: VideoQuality, codec: VideoCodecPreference, ) -> Result<PathBuf>

Downloads a video stream with the specified quality preferences.

§Arguments
  • url - The URL of the video to download
  • output - The name of the output file
  • quality - The desired video quality
  • codec - The preferred video codec
§Returns

The path to the downloaded video file

§Example
let url = String::from("https://www.youtube.com/watch?v=dQw4w9WgXcQ");

// Download a medium quality video with AVC1 codec
let video_path = fetcher.download_video_stream_with_quality(
    url,
    "video-only.mp4",
    VideoQuality::Medium,
    VideoCodecPreference::AVC1
).await?;
Source

pub async fn download_audio_stream_with_quality( &self, url: impl AsRef<str> + Debug + Display, output: impl AsRef<str> + Debug + Display, quality: AudioQuality, codec: AudioCodecPreference, ) -> Result<PathBuf>

Downloads an audio stream with the specified quality preferences.

§Arguments
  • url - The URL of the video to download
  • output - The name of the output file
  • quality - The desired audio quality
  • codec - The preferred audio codec
§Returns

The path to the downloaded audio file

§Example
let url = String::from("https://www.youtube.com/watch?v=dQw4w9WgXcQ");

// Download a high quality audio with Opus codec
let audio_path = fetcher.download_audio_stream_with_quality(
    url,
    "audio-only.mp3",
    AudioQuality::High,
    AudioCodecPreference::Opus
).await?;

Trait Implementations§

Source§

impl Clone for Youtube

Source§

fn clone(&self) -> Youtube

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Youtube

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for Youtube

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> ErasedDestructor for T
where T: 'static,

Source§

impl<T> MaybeSendSync for T