aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--crates/yt/src/yt_dlp/hooks.rs265
1 files changed, 173 insertions, 92 deletions
diff --git a/crates/yt/src/yt_dlp/hooks.rs b/crates/yt/src/yt_dlp/hooks.rs
index de52b98..448c1ee 100644
--- a/crates/yt/src/yt_dlp/hooks.rs
+++ b/crates/yt/src/yt_dlp/hooks.rs
@@ -44,7 +44,61 @@ macro_rules! json_get_default {
};
}
+/// A very basic ring buffer implementation.
+///
+/// Makes no guaranties over the order of items returned.
+struct RingBuf<const N: usize> {
+ data: [f64; N],
+ idx: usize,
+ items: usize,
+}
+
+impl<const N: usize> RingBuf<N> {
+ const fn new() -> Self {
+ Self {
+ data: [0.0; N],
+ idx: 0,
+ items: 0,
+ }
+ }
+ fn append_non_null(&mut self, value: f64) {
+ if value == 0.0 {
+ return;
+ }
+
+ self.items += 1;
+ self.data[self.idx] = value;
+
+ if self.idx == N - 1 {
+ self.idx = 0;
+ } else {
+ self.idx += 1;
+ }
+ }
+ fn get(&self) -> &[f64] {
+ if self.items < N {
+ &self.data[..self.items]
+ } else {
+ &self.data
+ }
+ }
+ fn is_empty(&self) -> bool {
+ self.get().is_empty()
+ }
+
+ fn average(&self) -> f64 {
+ let all = self.get();
+
+ #[expect(clippy::cast_precision_loss, reason = "length will always be <= 10")]
+ {
+ all.iter().copied().sum::<f64>() / (all.len() as f64)
+ }
+ }
+}
+
static TITLES: Mutex<Option<HashSet<String>>> = Mutex::new(None);
+static DOWNLOAD_SPEED_WINDOW: Mutex<RingBuf<20>> = Mutex::new(RingBuf::new());
+static DOWNLOAD_ETA_WINDOW: Mutex<RingBuf<20>> = Mutex::new(RingBuf::new());
fn format_bytes(bytes: u64) -> String {
let bytes = Bytes::new(bytes);
@@ -93,98 +147,7 @@ pub(crate) fn progress_hook(
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])),
- }
- }
- }
+ "downloading" => downloading_progress(&input, info_dict)?,
"finished" => {
let should_use_color = SHOULD_DISPLAY_COLOR.load(Ordering::Relaxed);
let title = get_title(info_dict);
@@ -355,5 +318,123 @@ fn maybe_setup_post_processor_progress(pc: ProgressChange) {
.expect("The recieving end should not be dropped before we drop the tx");
}
+fn downloading_progress(
+ input: &serde_json::Map<String, serde_json::Value>,
+ info_dict: &serde_json::Map<String, serde_json::Value>,
+) -> Result<(), std::io::Error> {
+ let elapsed = json_get_default!(input, "elapsed", as_f64, 0.0);
+ let eta = {
+ let mut window = DOWNLOAD_ETA_WINDOW.lock().unwrap();
+ window.append_non_null(json_get_default!(input, "eta", as_f64, 0.0));
+
+ if window.is_empty() {
+ // TODO: Ideally we would format the progress differently here <2026-11-27>
+ 0.0
+ } else {
+ window.average()
+ }
+ };
+ let speed: f64 = {
+ let mut window = DOWNLOAD_SPEED_WINDOW.lock().unwrap();
+ window.append_non_null(json_get_default!(input, "speed", as_f64, 0.0));
+
+ if window.is_empty() {
+ // TODO: Ideally we would format the progress differently here <2026-11-27>
+ 0.0
+ } else {
+ window.average()
+ }
+ };
+
+ 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])),
+ }
+ }
+
+ Ok(())
+}
+
wrap_progress_hook!(progress_hook, wrapped_progress_hook);
wrap_post_processor_hook!(post_processor_hook, wrapped_post_processor_hook);