From fa3d2b3b03c127dd2da424ebf9beefbd03782520 Mon Sep 17 00:00:00 2001 From: mykola2312 <49044616+mykola2312@users.noreply.github.com> Date: Tue, 20 Feb 2024 16:39:15 +0200 Subject: [PATCH] implement function to find best audio format --- Cargo.lock | 10 ++++++++++ Cargo.toml | 1 + src/dl/yt_dlp.rs | 20 +++++++++++++++++++- src/main.rs | 3 +++ 4 files changed, 33 insertions(+), 1 deletion(-) diff --git a/Cargo.lock b/Cargo.lock index 31784d1..ca15c96 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -653,6 +653,7 @@ version = "0.1.0" dependencies = [ "anyhow", "dotenv", + "ordered-float", "serde", "serde_json", "teloxide", @@ -755,6 +756,15 @@ dependencies = [ "vcpkg", ] +[[package]] +name = "ordered-float" +version = "4.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a76df7075c7d4d01fdcb46c912dd17fba5b60c78ea480b475f2b6ab6f666584e" +dependencies = [ + "num-traits", +] + [[package]] name = "percent-encoding" version = "2.3.0" diff --git a/Cargo.toml b/Cargo.toml index 2ebbeb1..7adb4f3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,3 +12,4 @@ tokio = { version = "1.32.0", features = ["rt-multi-thread", "macros", "process" teloxide = { version = "0.12.2", git ="https://github.com/teloxide/teloxide", features = ["macros"] } serde = { version = "1.0.196", features = ["derive"] } serde_json = "1.0.113" +ordered-float = "4.2.0" diff --git a/src/dl/yt_dlp.rs b/src/dl/yt_dlp.rs index 7375a36..2d3f53d 100644 --- a/src/dl/yt_dlp.rs +++ b/src/dl/yt_dlp.rs @@ -3,6 +3,7 @@ use serde::Deserialize; use serde_json; use std::str::Utf8Error; use tokio::process::Command; +use ordered_float::OrderedFloat; #[derive(Deserialize, Debug)] pub struct YtDlpFormat { @@ -18,13 +19,17 @@ pub struct YtDlpFormat { pub abr: Option, } -#[derive(Debug)] struct VideoFormat<'a> { pub format: &'a YtDlpFormat, pub width: u16, pub height: u16, } +struct AudioFormat<'a> { + pub format: &'a YtDlpFormat, + pub abr: f32 +} + impl YtDlpFormat { pub fn process(&mut self) { if self.acodec.as_ref().is_some_and(|v| v == "none") { @@ -104,6 +109,19 @@ impl YtDlpInfo { None => None, } } + + pub fn best_audio_format(&self) -> Option<&YtDlpFormat> { + let format = self + .formats + .iter() + .filter_map(|f| Some(AudioFormat { format: f, abr: f.abr? })) + .max_by_key(|f| OrderedFloat(f.abr)); + + match format { + Some(af) => Some(af.format), + None => None, + } + } } #[derive(Debug)] diff --git a/src/main.rs b/src/main.rs index 22869b2..718fd5d 100644 --- a/src/main.rs +++ b/src/main.rs @@ -47,6 +47,9 @@ async fn main() -> anyhow::Result<()> { let video = info.best_av_format().unwrap(); println!("{}", video); + let audio = info.best_audio_format().unwrap(); + println!("{}", audio); + Ok(()) //bot_main().await }