From 780dd251d8f550fb461b7cdaeeee4ec6589609d8 Mon Sep 17 00:00:00 2001 From: Benedikt Peetz Date: Sat, 7 Nov 2026 15:09:37 +0100 Subject: feat(yt/cmds/download): Don't construct multiple yt_dlp instances This change also switches to the new yt_dlp option format and the new config macro. --- .../download/implm/download/download_options.rs | 127 -------- .../src/commands/download/implm/download/hooks.rs | 359 --------------------- .../yt/src/commands/download/implm/download/mod.rs | 92 ++++-- crates/yt/src/commands/download/implm/mod.rs | 6 +- crates/yt/src/commands/download/mod.rs | 3 - crates/yt/src/yt_dlp/download_options.rs | 143 ++++++++ crates/yt/src/yt_dlp/hooks.rs | 359 +++++++++++++++++++++ 7 files changed, 564 insertions(+), 525 deletions(-) delete mode 100644 crates/yt/src/commands/download/implm/download/download_options.rs delete mode 100644 crates/yt/src/commands/download/implm/download/hooks.rs create mode 100644 crates/yt/src/yt_dlp/download_options.rs create mode 100644 crates/yt/src/yt_dlp/hooks.rs (limited to 'crates') diff --git a/crates/yt/src/commands/download/implm/download/download_options.rs b/crates/yt/src/commands/download/implm/download/download_options.rs deleted file mode 100644 index 4174266..0000000 --- a/crates/yt/src/commands/download/implm/download/download_options.rs +++ /dev/null @@ -1,127 +0,0 @@ -// yt - A fully featured command line YouTube client -// -// Copyright (C) 2024 Benedikt Peetz -// Copyright (C) 2025 Benedikt Peetz -// SPDX-License-Identifier: GPL-3.0-or-later -// -// This file is part of Yt. -// -// You should have received a copy of the License along with this program. -// If not, see . - -use anyhow::Context; -use serde_json::{Value, json}; -use yt_dlp::{YoutubeDL, options::YoutubeDLOptions}; - -use crate::app::App; - -use super::hooks::{wrapped_progress_hook, wrapped_post_processor_hook}; - -pub(crate) fn download_opts( - app: &App, - subtitle_langs: Option<&str>, -) -> anyhow::Result { - let base = YoutubeDLOptions::new() - .with_progress_hook(wrapped_progress_hook) - .with_post_processor_hook(wrapped_post_processor_hook) - .set("extract_flat", "in_playlist") - .set( - "extractor_args", - json! { - { - "youtube": { - "comment_sort": [ "top" ], - "max_comments": [ "150", "all", "100" ] - } - } - }, - ) - .set("prefer_free_formats", true) - .set("ffmpeg_location", env!("FFMPEG_LOCATION")) - .set("format", "bestvideo[height<=?1080]+bestaudio/best") - .set("fragment_retries", 10) - .set("getcomments", true) - .set("ignoreerrors", false) - .set("retries", 10) - .set("writeinfojson", true) - // NOTE: This results in a constant warning message. <2025-01-04> - //.set("writeannotations", true) - .set("writesubtitles", true) - .set("writeautomaticsub", true) - .set( - "outtmpl", - json! { - { - "default": app.config.paths.download_dir.join("%(channel)s/%(title)s.%(ext)s"), - "chapter": "%(title)s - %(section_number)03d %(section_title)s [%(id)s].%(ext)s" - } - }, - ) - .set("compat_opts", json! {{}}) - .set("forceprint", json! {{}}) - .set("print_to_file", json! {{}}) - .set("windowsfilenames", false) - .set("restrictfilenames", false) - .set("trim_file_names", false) - .set( - "postprocessors", - json! { - [ - { - "api": "https://sponsor.ajay.app", - "categories": [ - "interaction", - "intro", - "music_offtopic", - "sponsor", - "outro", - "poi_highlight", - "preview", - "selfpromo", - "filler", - "chapter" - ], - "key": "SponsorBlock", - "when": "after_filter" - }, - { - "force_keyframes": false, - "key": "ModifyChapters", - "remove_chapters_patterns": [], - "remove_ranges": [], - "remove_sponsor_segments": [ "sponsor" ], - "sponsorblock_chapter_title": "[SponsorBlock]: %(category_names)l" - }, - { - "add_chapters": true, - "add_infojson": null, - "add_metadata": false, - "key": "FFmpegMetadata" - }, - { - "key": "FFmpegConcat", - "only_multi_video": true, - "when": "playlist" - } - ] - }, - ) - .set( - "subtitleslangs", - Value::Array( - subtitle_langs - .unwrap_or("") - .split(',') - .map(|val| Value::String(val.to_owned())) - .collect::>(), - ), - ); - - if let Some(cookies) = &app.config.global.cookies { - base.set("cookies", cookies.to_str()) - } else { - base - } - .build() - .context("Failed to instanciate download yt_dlp") -} diff --git a/crates/yt/src/commands/download/implm/download/hooks.rs b/crates/yt/src/commands/download/implm/download/hooks.rs deleted file mode 100644 index de52b98..0000000 --- a/crates/yt/src/commands/download/implm/download/hooks.rs +++ /dev/null @@ -1,359 +0,0 @@ -// yt - A fully featured command line YouTube client -// -// Copyright (C) 2025 Benedikt Peetz -// SPDX-License-Identifier: GPL-3.0-or-later -// -// This file is part of Yt. -// -// You should have received a copy of the License along with this program. -// If not, see . - -use std::{ - collections::HashSet, - io::{Write, stderr}, - process, - sync::{ - Mutex, OnceLock, - atomic::{AtomicUsize, Ordering}, - mpsc::{self, Sender}, - }, - thread, - time::Duration, -}; - -use colors::{Colorize, IntoCanvas}; -use log::{Level, log_enabled}; -use yt_dlp::{json_cast, json_get, json_try_get, wrap_post_processor_hook, wrap_progress_hook}; - -use crate::{ - ansi_escape_codes::{clear_whole_line, cursor_up, erase_from_cursor_to_bottom, move_to_col}, - config::SHOULD_DISPLAY_COLOR, - select::duration::MaybeDuration, - shared::bytes::Bytes, -}; - -macro_rules! json_get_default { - ($value:expr, $name:literal, $convert:ident, $default:expr) => { - $value.get($name).map_or($default, |v| { - if v == &serde_json::Value::Null { - $default - } else { - json_cast!(@log_key $name, v, $convert) - } - }) - }; -} - -static TITLES: Mutex>> = Mutex::new(None); - -fn format_bytes(bytes: u64) -> String { - let bytes = Bytes::new(bytes); - bytes.to_string() -} - -fn format_speed(speed: f64) -> String { - #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] - let bytes = Bytes::new(speed.floor() as u64); - format!("{bytes}/s") -} -fn get_title(info_dict: &serde_json::Map) -> String { - if let Some(ext) = json_try_get!(info_dict, "ext", as_str) { - match ext { - "vtt" => { - format!( - "Subtitles ({})", - json_get_default!(info_dict, "name", as_str, "") - ) - } - "webm" | "mp4" | "mp3" | "m4a" => { - json_get_default!(info_dict, "title", as_str, "").to_owned() - } - other => panic!("The extension '{other}' is not yet implemented"), - } - } else { - json_get_default!(info_dict, "title", as_str, "").to_owned() - } -} - -/// # Panics -/// If expectations fail. -#[expect( - clippy::needless_pass_by_value, - reason = "We need to conform to the expected function signature" -)] -pub(crate) fn progress_hook( - input: serde_json::Map, -) -> Result<(), std::io::Error> { - // Only add the handler, if the log-level is higher than Debug (this avoids covering debug - // messages). - if log_enabled!(Level::Debug) { - return Ok(()); - } - - let info_dict = json_get!(input, "info_dict", as_object); - - match json_get!(input, "status", as_str) { - "downloading" => { - let elapsed = json_get_default!(input, "elapsed", as_f64, 0.0); - let eta = json_get_default!(input, "eta", as_f64, 0.0); - let speed = json_get_default!(input, "speed", as_f64, 0.0); - - let downloaded_bytes = json_get!(input, "downloaded_bytes", as_u64); - let (total_bytes, bytes_is_estimate): (u64, &'static str) = { - let total_bytes = json_get_default!(input, "total_bytes", as_u64, 0); - - if total_bytes == 0 { - #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] - let maybe_estimate = - json_get_default!(input, "total_bytes_estimate", as_f64, 0.0) as u64; - - #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] - if maybe_estimate == 0 { - // The download speed should be in bytes - // per second and the eta in seconds. - // Thus multiplying them gets us the raw bytes - // (which were estimated by `yt_dlp`, from their `info.json`) - let bytes_still_needed = (speed * eta).ceil() as u64; - - (downloaded_bytes + bytes_still_needed, "~") - } else { - (maybe_estimate, "~") - } - } else { - (total_bytes, "") - } - }; - - let percent: f64 = { - if total_bytes == 0 { - 100.0 - } else { - #[allow( - clippy::cast_possible_truncation, - clippy::cast_sign_loss, - clippy::cast_precision_loss - )] - { - (downloaded_bytes as f64 / total_bytes as f64) * 100.0 - } - } - }; - - clear_whole_line(stderr()); - move_to_col(stderr(), 1); - - let should_use_color = SHOULD_DISPLAY_COLOR.load(Ordering::Relaxed); - - let title = get_title(info_dict); - - eprint!( - "{} [{}/{} at {}] -> [{} of {}{} {}] ", - (&title).bold().blue().render(should_use_color), - MaybeDuration::from_secs_f64(elapsed) - .bold() - .yellow() - .render(should_use_color), - MaybeDuration::from_secs_f64(eta) - .bold() - .yellow() - .render(should_use_color), - format_speed(speed).bold().green().render(should_use_color), - format_bytes(downloaded_bytes) - .bold() - .red() - .render(should_use_color), - bytes_is_estimate.bold().red().render(should_use_color), - format_bytes(total_bytes) - .bold() - .red() - .render(should_use_color), - format!("{percent:.02}%") - .bold() - .cyan() - .render(should_use_color), - ); - stderr().flush()?; - - { - let mut titles = TITLES.lock().expect("The lock should work"); - - match titles.as_mut() { - Some(titles) => { - titles.insert(title); - } - None => *titles = Some(HashSet::from_iter([title])), - } - } - } - "finished" => { - let should_use_color = SHOULD_DISPLAY_COLOR.load(Ordering::Relaxed); - let title = get_title(info_dict); - - let has_already_been_printed = { - let titles = TITLES.lock().expect("The lock should work"); - - match titles.as_ref() { - Some(titles) => titles.contains(&title), - None => false, - } - }; - - if has_already_been_printed { - eprintln!("-> Finished downloading."); - } else { - eprintln!( - "Download of {} already finished.", - title.bold().blue().render(should_use_color) - ); - } - } - "error" => { - // TODO: This should probably return an Err. But I'm not so sure where the error would - // bubble up to (i.e., who would catch it) <2025-01-21> - eprintln!("-> Error while downloading: {}", get_title(info_dict)); - process::exit(1); - } - other => unreachable!("'{other}' should not be a valid state!"), - } - - Ok(()) -} - -// postprocessor_hooks: A list of functions that get called on postprocessing -// progress, with a dictionary with the entries -// * status: One of "started", "processing", or "finished". -// Check this first and ignore unknown values. -// * postprocessor: Name of the postprocessor -// * info_dict: The extracted info_dict -// -// Progress hooks are guaranteed to be called at least twice -// (with status "started" and "finished") if the processing is successful. -#[expect( - clippy::needless_pass_by_value, - clippy::unnecessary_wraps, - reason = "The macro expects this function signature" -)] -pub(crate) fn post_processor_hook( - input: serde_json::Map, -) -> Result<(), std::io::Error> { - // Only add the handler, if the log-level is higher than Debug (this avoids covering debug - // messages). - if log_enabled!(Level::Debug) { - return Ok(()); - } - - let info_dict = json_get!(input, "info_dict", as_object); - - match json_get!(input, "status", as_str) { - "started" => { - // Normally `yt_dlp` just gives us a `started` and a `finished` message, so we show all - // the post_processors that have currently been recorded as `started` and not yet as - // `finished`. - let post_processor = json_get!(input, "postprocessor", as_str); - maybe_setup_post_processor_progress(ProgressChange::Started( - post_processor.to_string(), - )); - } - "processing" => { - let post_processor = json_get!(input, "postprocessor", as_str); - let title = get_title(info_dict); - - eprintln!("Processesing actually triggered, `{post_processor}` for `{title}`",); - } - "finished" => { - let post_processor = json_get!(input, "postprocessor", as_str); - maybe_setup_post_processor_progress(ProgressChange::Finished( - post_processor.to_string(), - )); - - // let should_use_color = SHOULD_DISPLAY_COLOR.load(Ordering::Relaxed); - // let title = get_title(info_dict); - // - // eprintln!( - // "{} ({}) finished.", - // title.bold().blue().render(should_use_color), - // post_processor.bold().green().render(should_use_color), - // ); - } - other => unreachable!("'{other}' should not be a valid state!"), - } - - Ok(()) -} - -enum ProgressChange { - Started(String), - Finished(String), -} - -fn maybe_setup_post_processor_progress(pc: ProgressChange) { - fn new_state_id() -> usize { - static COUNTER: AtomicUsize = AtomicUsize::new(0); - COUNTER.fetch_add(1, Ordering::Relaxed) - } - static TX: OnceLock> = const { OnceLock::new() }; - - let should_use_color = SHOULD_DISPLAY_COLOR.load(Ordering::Relaxed); - - let tx = TX.get_or_init(|| { - let (tx, rx) = mpsc::channel(); - thread::spawn(move || { - fn process_new_data(data: &mut HashSet, new_data: ProgressChange) { - match new_data { - ProgressChange::Started(name) => { - data.insert(name); - } - ProgressChange::Finished(name) => { - data.remove(&name); - } - } - } - - let mut data = HashSet::new(); - - 'main: loop { - let previous_length = data.len(); - - match rx.recv_timeout(Duration::from_millis(100)) { - Ok(new_data) => process_new_data(&mut data, new_data), - Err(err) => match err { - mpsc::RecvTimeoutError::Timeout => (), - mpsc::RecvTimeoutError::Disconnected => break 'main, - }, - } - - // If we received multiple things at once, process them all at once. - while let Ok(new_data) = rx.try_recv() { - process_new_data(&mut data, new_data); - } - - let spinner = match new_state_id() % 4 { - 0 => '|', - 1 => '/', - 2 => '-', - 3 => '\\', - _ => unreachable!("The `mod` operation does not permit these numbers"), - }; - - cursor_up(stderr(), previous_length); - erase_from_cursor_to_bottom(stderr()); - for post_processor in &data { - clear_whole_line(stderr()); - move_to_col(stderr(), 1); - - eprintln!( - "[{spinner}] {} ", - post_processor.blue().bold().render(should_use_color) - ); - } - } - }); - tx - }); - - tx.send(pc) - .expect("The recieving end should not be dropped before we drop the tx"); -} - -wrap_progress_hook!(progress_hook, wrapped_progress_hook); -wrap_post_processor_hook!(post_processor_hook, wrapped_post_processor_hook); diff --git a/crates/yt/src/commands/download/implm/download/mod.rs b/crates/yt/src/commands/download/implm/download/mod.rs index 39f7960..fd28a63 100644 --- a/crates/yt/src/commands/download/implm/download/mod.rs +++ b/crates/yt/src/commands/download/implm/download/mod.rs @@ -13,24 +13,20 @@ use std::{collections::HashMap, path::PathBuf, sync::Arc, time::Duration}; use crate::{ app::App, - commands::download::implm::download::download_options::download_opts, shared::bytes::Bytes, storage::{ db::{extractor_hash::ExtractorHash, insert::Operations, video::Video}, notify::{wait_for_cache_reduction, wait_for_db_write}, }, - yt_dlp::get_current_cache_allocation, + yt_dlp::{download_options::download_opts, get_current_cache_allocation}, }; use anyhow::{Context, Result, bail}; use log::{debug, error, info, warn}; +use serde_json::{Value, json}; use tokio::{select, task::JoinHandle, time}; use yt_dlp::YoutubeDL; -#[allow(clippy::module_name_repetitions)] -pub(crate) mod download_options; -pub(crate) mod hooks; - #[derive(Debug)] #[allow(clippy::module_name_repetitions)] pub(crate) struct CurrentDownload { @@ -40,12 +36,23 @@ pub(crate) struct CurrentDownload { } impl CurrentDownload { - fn new_from_video(app: &App, video: Video) -> Result { + fn new_from_video(mut yt_dlp: YoutubeDL, video: Video) -> Self { let extractor_hash = video.extractor_hash; - debug!("Download started: {}", &video.title); - let yt_dlp = Arc::new(download_opts(app, video.subtitle_langs.as_deref())?); + debug!("Download started: {}", video.title); + if let Some(langs) = video.subtitle_langs.as_ref() { + yt_dlp.set_option( + "subtitleslangs", + Value::Array( + langs + .split(',') + .map(|val| Value::String(val.to_owned())) + .collect::>(), + ), + ); + } + let yt_dlp = Arc::new(yt_dlp); let local_yt_dlp = Arc::clone(&yt_dlp); let task_handle = tokio::task::spawn_blocking(move || { @@ -57,25 +64,26 @@ impl CurrentDownload { Ok((result.remove(0), video)) }); - Ok(Self { + Self { task_handle, yt_dlp, extractor_hash, - }) + } } - fn abort(self) -> Result<()> { + fn abort(self) -> Result { debug!("Cancelling download."); + self.yt_dlp.close()?; - Ok(()) + Ok(Arc::into_inner(self.yt_dlp).expect("No other references should be life")) } fn is_finished(&self) -> bool { self.task_handle.is_finished() } - async fn finalize(self, app: &App) -> Result<()> { + async fn finalize(self, app: &App) -> Result { let (result, mut video) = self.task_handle.await??; let mut ops = Operations::new("Downloader: Set download path"); @@ -90,7 +98,7 @@ impl CurrentDownload { result.display() ); - Ok(()) + Ok(Arc::into_inner(self.yt_dlp).expect("No other references should be life")) } } @@ -111,23 +119,20 @@ pub(crate) struct Downloader { video_size_cache: HashMap, printed_warning: bool, cached_cache_allocation: Option, -} - -impl Default for Downloader { - fn default() -> Self { - Self::new() - } + yt_dlp: Option, } impl Downloader { - #[must_use] - pub(crate) fn new() -> Self { - Self { + pub(crate) fn new(app: &App) -> Result { + let yt_dlp = download_opts(app, None)?; + + Ok(Self { current_download: None, video_size_cache: HashMap::new(), printed_warning: false, cached_cache_allocation: None, - } + yt_dlp: Some(yt_dlp), + }) } /// Check if enough cache is available. @@ -168,7 +173,7 @@ impl Downloader { Waiting for cache size reduction..", next_video.title, Bytes::new(video_size), - &cache_allocation, + cache_allocation, Bytes::new(max_cache_size) ); self.printed_warning = true; @@ -228,7 +233,7 @@ impl Downloader { if current_download.is_finished() { // The download is done, finalize it and leave it removed. - current_download.finalize(&app).await?; + self.yt_dlp = Some(current_download.finalize(&app).await?); continue; } @@ -244,11 +249,16 @@ impl Downloader { ); // Replace the currently downloading video - current_download - .abort() - .context("Failed to abort last download")?; + self.yt_dlp = Some( + current_download + .abort() + .context("Failed to abort last download")?, + ); - let new_current_download = CurrentDownload::new_from_video(&app, next_video)?; + let new_current_download = CurrentDownload::new_from_video( + self.yt_dlp.take().expect("Should be some here"), + next_video, + ); self.current_download = Some(new_current_download); } @@ -257,7 +267,10 @@ impl Downloader { "No video is being downloaded right now, setting it to '{}'", next_video.title ); - let new_current_download = CurrentDownload::new_from_video(&app, next_video)?; + let new_current_download = CurrentDownload::new_from_video( + self.yt_dlp.take().expect("Should be some here"), + next_video, + ); self.current_download = Some(new_current_download); } @@ -277,7 +290,20 @@ impl Downloader { if let Some(value) = self.video_size_cache.get(&video.extractor_hash) { Ok(*value) } else { - let size = video.get_approx_size()?; + let size = { + let mut yt_dlp = self.yt_dlp.take().expect("Should be some here"); + let size = yt_dlp.with_reset_option("getcomments", false, |yt_dlp| { + yt_dlp.with_reset_option("writeinfojson", false, |yt_dlp| { + yt_dlp.with_reset_option("extractor_args", json! {{}}, |yt_dlp| { + video.get_approx_size(yt_dlp) + }) + }) + })?; + + self.yt_dlp = Some(yt_dlp); + + size + }; assert_eq!( self.video_size_cache.insert(video.extractor_hash, size), diff --git a/crates/yt/src/commands/download/implm/mod.rs b/crates/yt/src/commands/download/implm/mod.rs index c74a909..8647a54 100644 --- a/crates/yt/src/commands/download/implm/mod.rs +++ b/crates/yt/src/commands/download/implm/mod.rs @@ -32,7 +32,7 @@ impl DownloadCommand { max_cache_size, } = self; - let max_cache_size = max_cache_size.unwrap_or(app.config.download.max_cache_size.as_u64()); + let max_cache_size = app.config.download.max_cache_size.as_u64(); info!("Max cache size: '{}'", Bytes::new(max_cache_size)); clear_stale_downloaded_paths(&app).await?; @@ -46,8 +46,8 @@ impl DownloadCommand { ops.commit(&app).await?; } - download::Downloader::new() - .consume(app, max_cache_size) + download::Downloader::new(&app)? + .consume(app, max_cache_size, count) .await?; Ok(()) diff --git a/crates/yt/src/commands/download/mod.rs b/crates/yt/src/commands/download/mod.rs index 15026ba..f765803 100644 --- a/crates/yt/src/commands/download/mod.rs +++ b/crates/yt/src/commands/download/mod.rs @@ -21,9 +21,6 @@ pub(super) struct DownloadCommand { #[arg(short, long)] force: bool, - /// The maximum size the download dir should have. - #[arg(short, long, value_parser = byte_parser)] - max_cache_size: Option, } fn byte_parser(input: &str) -> Result { diff --git a/crates/yt/src/yt_dlp/download_options.rs b/crates/yt/src/yt_dlp/download_options.rs new file mode 100644 index 0000000..d81f595 --- /dev/null +++ b/crates/yt/src/yt_dlp/download_options.rs @@ -0,0 +1,143 @@ +// yt - A fully featured command line YouTube client +// +// Copyright (C) 2024 Benedikt Peetz +// Copyright (C) 2025 Benedikt Peetz +// SPDX-License-Identifier: GPL-3.0-or-later +// +// This file is part of Yt. +// +// You should have received a copy of the License along with this program. +// If not, see . + +use anyhow::Context; +use log::info; +use serde_json::{Value, json}; +use yt_dlp::{YoutubeDL, options::YoutubeDLOptions}; + +use crate::{app::App, yt_dlp::match_filters::ignore_member_only_wrapped}; + +use super::hooks::{wrapped_post_processor_hook, wrapped_progress_hook}; + +pub(crate) fn download_opts(app: &App, subtitle_langs: Option<&str>) -> anyhow::Result { + let base = YoutubeDLOptions::new() + .with_progress_hook(wrapped_progress_hook) + .with_post_processor_hook(wrapped_post_processor_hook) + .set("extract_flat", "in_playlist") + .set( + "extractor_args", + json! { + { + "youtube": { + "comment_sort": [ "top" ], + "max_comments": [ "150", "all", "100" ] + } + } + }, + ) + .set("prefer_free_formats", true) + .set("ffmpeg_location", env!("FFMPEG_LOCATION")) + .set("format", "bestvideo[height<=?1080]+bestaudio/best") + .set("fragment_retries", 10) + .set("getcomments", true) + .set("ignoreerrors", false) + .set("retries", 10) + .set("writeinfojson", true) + // NOTE: This results in a constant warning message. <2025-01-04> + //.set("writeannotations", true) + .set("writesubtitles", true) + .set("writeautomaticsub", true) + .set( + "outtmpl", + json! { + { + "default": app.config.paths.download_dir.join("%(channel)s/%(title)s.%(ext)s"), + "chapter": "%(title)s - %(section_number)03d %(section_title)s [%(id)s].%(ext)s" + } + }, + ) + .set("compat_opts", json! {{}}) + .set("forceprint", json! {{}}) + .set("print_to_file", json! {{}}) + .set("windowsfilenames", false) + .set("restrictfilenames", false) + .set("trim_file_names", false) + .set( + "postprocessors", + json! { + [ + { + "api": "https://sponsor.ajay.app", + "categories": [ + "interaction", + "intro", + "music_offtopic", + "sponsor", + "outro", + "poi_highlight", + "preview", + "selfpromo", + "filler", + "chapter" + ], + "key": "SponsorBlock", + "when": "after_filter" + }, + { + "force_keyframes": false, + "key": "ModifyChapters", + "remove_chapters_patterns": [], + "remove_ranges": [], + "remove_sponsor_segments": [ "sponsor" ], + "sponsorblock_chapter_title": "[SponsorBlock]: %(category_names)l" + }, + { + "add_chapters": true, + "add_infojson": null, + "add_metadata": false, + "key": "FFmpegMetadata" + }, + { + "key": "FFmpegConcat", + "only_multi_video": true, + "when": "playlist" + } + ] + }, + ) + .set( + "subtitleslangs", + Value::Array( + subtitle_langs + .unwrap_or("") + .split(',') + .map(|val| Value::String(val.to_owned())) + .collect::>(), + ), + ) + .add_match_filter(ignore_member_only_wrapped); + + let base = if let Some(cookies) = &app.config.download.cookies { + base.set("cookiefile", cookies.to_str()) + } else if let Some(cookies_from_browser) = &app.config.download.cookies_from_browser { + base.set( + "cookiesfrombrowser", + Value::Array(vec![cookies_from_browser.to_owned().into()]), + ) + } else { + base + }; + + let base = { + let mut final_base = base; + + for (key, value) in &app.config.update.yt_dlp_options { + info!("Adding additional yt-dlp freeform option: {key} to {value}"); + final_base = final_base.set(key, value.to_owned()); + } + + final_base + }; + + base.build() + .context("Failed to instanciate download yt_dlp") +} diff --git a/crates/yt/src/yt_dlp/hooks.rs b/crates/yt/src/yt_dlp/hooks.rs new file mode 100644 index 0000000..de52b98 --- /dev/null +++ b/crates/yt/src/yt_dlp/hooks.rs @@ -0,0 +1,359 @@ +// yt - A fully featured command line YouTube client +// +// Copyright (C) 2025 Benedikt Peetz +// SPDX-License-Identifier: GPL-3.0-or-later +// +// This file is part of Yt. +// +// You should have received a copy of the License along with this program. +// If not, see . + +use std::{ + collections::HashSet, + io::{Write, stderr}, + process, + sync::{ + Mutex, OnceLock, + atomic::{AtomicUsize, Ordering}, + mpsc::{self, Sender}, + }, + thread, + time::Duration, +}; + +use colors::{Colorize, IntoCanvas}; +use log::{Level, log_enabled}; +use yt_dlp::{json_cast, json_get, json_try_get, wrap_post_processor_hook, wrap_progress_hook}; + +use crate::{ + ansi_escape_codes::{clear_whole_line, cursor_up, erase_from_cursor_to_bottom, move_to_col}, + config::SHOULD_DISPLAY_COLOR, + select::duration::MaybeDuration, + shared::bytes::Bytes, +}; + +macro_rules! json_get_default { + ($value:expr, $name:literal, $convert:ident, $default:expr) => { + $value.get($name).map_or($default, |v| { + if v == &serde_json::Value::Null { + $default + } else { + json_cast!(@log_key $name, v, $convert) + } + }) + }; +} + +static TITLES: Mutex>> = Mutex::new(None); + +fn format_bytes(bytes: u64) -> String { + let bytes = Bytes::new(bytes); + bytes.to_string() +} + +fn format_speed(speed: f64) -> String { + #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] + let bytes = Bytes::new(speed.floor() as u64); + format!("{bytes}/s") +} +fn get_title(info_dict: &serde_json::Map) -> String { + if let Some(ext) = json_try_get!(info_dict, "ext", as_str) { + match ext { + "vtt" => { + format!( + "Subtitles ({})", + json_get_default!(info_dict, "name", as_str, "") + ) + } + "webm" | "mp4" | "mp3" | "m4a" => { + json_get_default!(info_dict, "title", as_str, "").to_owned() + } + other => panic!("The extension '{other}' is not yet implemented"), + } + } else { + json_get_default!(info_dict, "title", as_str, "").to_owned() + } +} + +/// # Panics +/// If expectations fail. +#[expect( + clippy::needless_pass_by_value, + reason = "We need to conform to the expected function signature" +)] +pub(crate) fn progress_hook( + input: serde_json::Map, +) -> Result<(), std::io::Error> { + // Only add the handler, if the log-level is higher than Debug (this avoids covering debug + // messages). + if log_enabled!(Level::Debug) { + return Ok(()); + } + + let info_dict = json_get!(input, "info_dict", as_object); + + match json_get!(input, "status", as_str) { + "downloading" => { + let elapsed = json_get_default!(input, "elapsed", as_f64, 0.0); + let eta = json_get_default!(input, "eta", as_f64, 0.0); + let speed = json_get_default!(input, "speed", as_f64, 0.0); + + let downloaded_bytes = json_get!(input, "downloaded_bytes", as_u64); + let (total_bytes, bytes_is_estimate): (u64, &'static str) = { + let total_bytes = json_get_default!(input, "total_bytes", as_u64, 0); + + if total_bytes == 0 { + #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] + let maybe_estimate = + json_get_default!(input, "total_bytes_estimate", as_f64, 0.0) as u64; + + #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] + if maybe_estimate == 0 { + // The download speed should be in bytes + // per second and the eta in seconds. + // Thus multiplying them gets us the raw bytes + // (which were estimated by `yt_dlp`, from their `info.json`) + let bytes_still_needed = (speed * eta).ceil() as u64; + + (downloaded_bytes + bytes_still_needed, "~") + } else { + (maybe_estimate, "~") + } + } else { + (total_bytes, "") + } + }; + + let percent: f64 = { + if total_bytes == 0 { + 100.0 + } else { + #[allow( + clippy::cast_possible_truncation, + clippy::cast_sign_loss, + clippy::cast_precision_loss + )] + { + (downloaded_bytes as f64 / total_bytes as f64) * 100.0 + } + } + }; + + clear_whole_line(stderr()); + move_to_col(stderr(), 1); + + let should_use_color = SHOULD_DISPLAY_COLOR.load(Ordering::Relaxed); + + let title = get_title(info_dict); + + eprint!( + "{} [{}/{} at {}] -> [{} of {}{} {}] ", + (&title).bold().blue().render(should_use_color), + MaybeDuration::from_secs_f64(elapsed) + .bold() + .yellow() + .render(should_use_color), + MaybeDuration::from_secs_f64(eta) + .bold() + .yellow() + .render(should_use_color), + format_speed(speed).bold().green().render(should_use_color), + format_bytes(downloaded_bytes) + .bold() + .red() + .render(should_use_color), + bytes_is_estimate.bold().red().render(should_use_color), + format_bytes(total_bytes) + .bold() + .red() + .render(should_use_color), + format!("{percent:.02}%") + .bold() + .cyan() + .render(should_use_color), + ); + stderr().flush()?; + + { + let mut titles = TITLES.lock().expect("The lock should work"); + + match titles.as_mut() { + Some(titles) => { + titles.insert(title); + } + None => *titles = Some(HashSet::from_iter([title])), + } + } + } + "finished" => { + let should_use_color = SHOULD_DISPLAY_COLOR.load(Ordering::Relaxed); + let title = get_title(info_dict); + + let has_already_been_printed = { + let titles = TITLES.lock().expect("The lock should work"); + + match titles.as_ref() { + Some(titles) => titles.contains(&title), + None => false, + } + }; + + if has_already_been_printed { + eprintln!("-> Finished downloading."); + } else { + eprintln!( + "Download of {} already finished.", + title.bold().blue().render(should_use_color) + ); + } + } + "error" => { + // TODO: This should probably return an Err. But I'm not so sure where the error would + // bubble up to (i.e., who would catch it) <2025-01-21> + eprintln!("-> Error while downloading: {}", get_title(info_dict)); + process::exit(1); + } + other => unreachable!("'{other}' should not be a valid state!"), + } + + Ok(()) +} + +// postprocessor_hooks: A list of functions that get called on postprocessing +// progress, with a dictionary with the entries +// * status: One of "started", "processing", or "finished". +// Check this first and ignore unknown values. +// * postprocessor: Name of the postprocessor +// * info_dict: The extracted info_dict +// +// Progress hooks are guaranteed to be called at least twice +// (with status "started" and "finished") if the processing is successful. +#[expect( + clippy::needless_pass_by_value, + clippy::unnecessary_wraps, + reason = "The macro expects this function signature" +)] +pub(crate) fn post_processor_hook( + input: serde_json::Map, +) -> Result<(), std::io::Error> { + // Only add the handler, if the log-level is higher than Debug (this avoids covering debug + // messages). + if log_enabled!(Level::Debug) { + return Ok(()); + } + + let info_dict = json_get!(input, "info_dict", as_object); + + match json_get!(input, "status", as_str) { + "started" => { + // Normally `yt_dlp` just gives us a `started` and a `finished` message, so we show all + // the post_processors that have currently been recorded as `started` and not yet as + // `finished`. + let post_processor = json_get!(input, "postprocessor", as_str); + maybe_setup_post_processor_progress(ProgressChange::Started( + post_processor.to_string(), + )); + } + "processing" => { + let post_processor = json_get!(input, "postprocessor", as_str); + let title = get_title(info_dict); + + eprintln!("Processesing actually triggered, `{post_processor}` for `{title}`",); + } + "finished" => { + let post_processor = json_get!(input, "postprocessor", as_str); + maybe_setup_post_processor_progress(ProgressChange::Finished( + post_processor.to_string(), + )); + + // let should_use_color = SHOULD_DISPLAY_COLOR.load(Ordering::Relaxed); + // let title = get_title(info_dict); + // + // eprintln!( + // "{} ({}) finished.", + // title.bold().blue().render(should_use_color), + // post_processor.bold().green().render(should_use_color), + // ); + } + other => unreachable!("'{other}' should not be a valid state!"), + } + + Ok(()) +} + +enum ProgressChange { + Started(String), + Finished(String), +} + +fn maybe_setup_post_processor_progress(pc: ProgressChange) { + fn new_state_id() -> usize { + static COUNTER: AtomicUsize = AtomicUsize::new(0); + COUNTER.fetch_add(1, Ordering::Relaxed) + } + static TX: OnceLock> = const { OnceLock::new() }; + + let should_use_color = SHOULD_DISPLAY_COLOR.load(Ordering::Relaxed); + + let tx = TX.get_or_init(|| { + let (tx, rx) = mpsc::channel(); + thread::spawn(move || { + fn process_new_data(data: &mut HashSet, new_data: ProgressChange) { + match new_data { + ProgressChange::Started(name) => { + data.insert(name); + } + ProgressChange::Finished(name) => { + data.remove(&name); + } + } + } + + let mut data = HashSet::new(); + + 'main: loop { + let previous_length = data.len(); + + match rx.recv_timeout(Duration::from_millis(100)) { + Ok(new_data) => process_new_data(&mut data, new_data), + Err(err) => match err { + mpsc::RecvTimeoutError::Timeout => (), + mpsc::RecvTimeoutError::Disconnected => break 'main, + }, + } + + // If we received multiple things at once, process them all at once. + while let Ok(new_data) = rx.try_recv() { + process_new_data(&mut data, new_data); + } + + let spinner = match new_state_id() % 4 { + 0 => '|', + 1 => '/', + 2 => '-', + 3 => '\\', + _ => unreachable!("The `mod` operation does not permit these numbers"), + }; + + cursor_up(stderr(), previous_length); + erase_from_cursor_to_bottom(stderr()); + for post_processor in &data { + clear_whole_line(stderr()); + move_to_col(stderr(), 1); + + eprintln!( + "[{spinner}] {} ", + post_processor.blue().bold().render(should_use_color) + ); + } + } + }); + tx + }); + + tx.send(pc) + .expect("The recieving end should not be dropped before we drop the tx"); +} + +wrap_progress_hook!(progress_hook, wrapped_progress_hook); +wrap_post_processor_hook!(post_processor_hook, wrapped_post_processor_hook); -- cgit v1.3.1