1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
use std::future::Future;
use std::path::PathBuf;
use std::sync::Arc;
use crate::download::config::postprocess::PostProcessConfig;
use crate::error::Result;
use crate::model::Video;
use crate::{Downloader, download, events, metadata};
impl Downloader {
/// Fluent method to fetch video info and return self for chaining.
///
/// This is useful for building operation pipelines.
///
/// # Arguments
///
/// * `url` - The YouTube video URL
///
/// # Returns
///
/// A tuple of (self, video) for method chaining
///
/// # Examples
///
/// ```rust,no_run
/// # use std::path::PathBuf;
/// # use yt_dlp::Downloader;
/// # use yt_dlp::client::deps::Libraries;
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let libs = Libraries::new(PathBuf::from("yt-dlp"), PathBuf::from("ffmpeg"));
/// let (downloader, video) = Downloader::builder(libs, "output")
/// .build()
/// .await?
/// .fetch("https://youtube.com/watch?v=gXtp6C-3JKo")
/// .await?;
///
/// println!("Title: {}", video.title);
/// # Ok(())
/// # }
/// ```
pub async fn fetch(self, url: impl AsRef<str>) -> Result<(Self, Video)> {
let url_str = url.as_ref();
tracing::debug!(url = url_str, "📡 Fetching video info (fluent API)");
let video = self.fetch_video_infos(url_str.to_string()).await?;
tracing::debug!(
video_id = video.id,
video_title = video.title,
"✅ Video info fetched (fluent API)"
);
Ok((self, video))
}
/// Fluent method to download a video and return self for chaining.
///
/// # Arguments
///
/// * `video` - The video to download
/// * `output` - The output filename
///
/// # Examples
///
/// ```rust,no_run
/// # use yt_dlp::Downloader;
/// # use yt_dlp::client::deps::Libraries;
/// # use yt_dlp::model::Video;
/// # use yt_dlp::download::PostProcessConfig;
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # use std::path::PathBuf;
/// # let libs = Libraries::new(PathBuf::from("yt-dlp"), PathBuf::from("ffmpeg"));
/// let (downloader, video) = Downloader::builder(libs, "output")
/// .build()
/// .await?
/// .fetch("https://youtube.com/watch?v=gXtp6C-3JKo")
/// .await?;
///
/// // Download the video, then enrich it with metadata
/// let downloader = downloader
/// .download_and_continue(&video, "output.mp4")
/// .await?
/// .postprocess_video(
/// "output.mp4",
/// "output_processed.mp4",
/// PostProcessConfig::new(),
/// )
/// .await?;
/// # Ok(())
/// # }
/// ```
pub async fn download_and_continue(self, video: &Video, output: impl AsRef<str>) -> Result<Self> {
tracing::debug!(
video_id = video.id,
video_title = video.title,
output = output.as_ref(),
"📥 Downloading video (fluent API)"
);
self.download_video(video, output).await?;
tracing::debug!(video_id = video.id, "✅ Video downloaded (fluent API)");
Ok(self)
}
/// Fluent method to download a video to a specific path and return self for chaining.
///
/// Unlike [`download_and_continue`](Self::download_and_continue), this method writes
/// the file to the exact path specified, ignoring the configured `output_dir`.
///
/// # Arguments
///
/// * `video` - The video to download
/// * `output` - The full output path
pub async fn download_and_continue_to_path(self, video: &Video, output: impl Into<PathBuf>) -> Result<Self> {
let output_path = output.into();
tracing::debug!(
video_id = video.id,
video_title = video.title,
output = ?output_path,
"📥 Downloading video to path (fluent API)"
);
self.download_video_to_path(video, output_path).await?;
tracing::debug!(video_id = video.id, "✅ Video downloaded to path (fluent API)");
Ok(self)
}
/// Chain multiple operations in a pipeline.
///
/// This method allows you to chain fetch -> download -> metadata operations.
///
/// # Examples
///
/// ```rust,no_run
/// # use yt_dlp::Downloader;
/// # use yt_dlp::client::deps::Libraries;
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # use std::path::PathBuf;
/// # let libs = Libraries::new(PathBuf::from("yt-dlp"), PathBuf::from("ffmpeg"));
/// Downloader::builder(libs, "output")
/// .build()
/// .await?
/// .pipeline(
/// "https://youtube.com/watch?v=gXtp6C-3JKo",
/// |yt, video| async move {
/// yt.download_video(&video, "video.mp4").await?;
/// Ok(yt)
/// },
/// )
/// .await?;
/// # Ok(())
/// # }
/// ```
pub async fn pipeline<F, Fut>(self, url: impl AsRef<str>, operation: F) -> Result<Self>
where
F: FnOnce(Self, Video) -> Fut,
Fut: Future<Output = Result<Self>>,
{
let url_str = url.as_ref();
tracing::info!(url = url_str, "📥 Starting download pipeline");
let video = self.fetch_video_infos(url_str).await?;
tracing::debug!(
video_id = video.id,
video_title = video.title,
"📡 Video fetched, executing pipeline operation"
);
let result = operation(self, video).await?;
tracing::info!("✅ Pipeline completed");
Ok(result)
}
/// Applies post-processing to a video file using FFmpeg.
///
/// This method allows you to apply various post-processing operations such as:
/// - Codec conversion (H.264, H.265, VP9, AV1)
/// - Bitrate adjustment
/// - Resolution scaling
/// - Video filters (crop, rotate, brightness, contrast, etc.)
///
/// # Arguments
///
/// * `input_path` - Path to the input video file
/// * `output` - The output filename
/// * `config` - Post-processing configuration
///
/// # Errors
///
/// Returns an error if FFmpeg execution fails
///
/// # Returns
///
/// The path to the processed video file
///
/// # Examples
///
/// ```rust,no_run
/// # use yt_dlp::Downloader;
/// # use yt_dlp::download::{PostProcessConfig, VideoCodec, AudioCodec, Resolution};
/// # use std::path::PathBuf;
/// # use yt_dlp::client::deps::Libraries;
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let libraries = Libraries::new(PathBuf::from("libs/yt-dlp"), PathBuf::from("libs/ffmpeg"));
/// # let downloader = Downloader::builder(libraries, "output").build().await?;
/// let config = PostProcessConfig::new()
/// .with_video_codec(VideoCodec::H264)
/// .with_audio_codec(AudioCodec::AAC)
/// .with_video_bitrate("2M")
/// .with_resolution(Resolution::HD);
///
/// let processed = downloader.postprocess_video("input.mp4", "output.mp4", config).await?;
/// # Ok(())
/// # }
/// ```
pub async fn postprocess_video(
&self,
input_path: impl Into<PathBuf>,
output: impl AsRef<str>,
config: download::config::postprocess::PostProcessConfig,
) -> Result<PathBuf> {
let input = input_path.into();
let output_path = self.output_dir.join(output.as_ref());
tracing::debug!(
input = ?input,
output = ?output_path,
video_codec = ?config.video_codec,
audio_codec = ?config.audio_codec,
"✂️ Applying post-processing to video"
);
self.postprocess_video_to_path(input, output_path, config).await
}
/// Applies post-processing to a video file, saving to a specific path.
///
/// Unlike [`postprocess_video`](Self::postprocess_video), this method writes the file
/// to the exact path specified, ignoring the configured `output_dir`.
///
/// # Arguments
///
/// * `input_path` - Path to the input video file
/// * `output` - The full path for the processed output file
/// * `config` - Post-processing configuration
pub async fn postprocess_video_to_path(
&self,
input_path: impl Into<PathBuf>,
output: impl Into<PathBuf>,
config: PostProcessConfig,
) -> Result<PathBuf> {
let input_path = input_path.into();
let output_path = output.into();
tracing::debug!(
input = ?input_path,
output = ?output_path,
video_codec = ?config.video_codec,
audio_codec = ?config.audio_codec,
video_bitrate = ?config.video_bitrate,
audio_bitrate = ?config.audio_bitrate,
resolution = ?config.resolution,
filters_count = config.filters.len(),
"✂️ Applying post-processing to video file"
);
let result =
metadata::postprocess::apply_postprocess(input_path, output_path, &config, &self.libraries, self.timeout)
.await?;
tracing::info!(
output = ?result,
"✅ Post-processing completed"
);
Ok(result)
}
/// Returns a stream of all download events.
///
/// This method creates a new subscriber to the event bus and returns
/// a stream that can be used to receive all future events.
///
/// # Examples
///
/// ```rust,no_run
/// # use yt_dlp::Downloader;
/// # use yt_dlp::client::deps::Libraries;
/// # use tokio_stream::StreamExt;
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # use std::path::PathBuf;
/// # let libs = Libraries::new(PathBuf::from("yt-dlp"), PathBuf::from("ffmpeg"));
/// let downloader = Downloader::builder(libs, "output").build().await?;
/// let mut stream = downloader.event_stream();
///
/// while let Some(Ok(event)) = stream.next().await {
/// println!("Event: {}", event.event_type());
/// }
/// # Ok(())
/// # }
/// ```
pub fn event_stream(
&self,
) -> impl tokio_stream::Stream<
Item = std::result::Result<
Arc<events::DownloadEvent>,
tokio_stream::wrappers::errors::BroadcastStreamRecvError,
>,
> {
tracing::debug!(
subscriber_count = self.event_bus.subscriber_count(),
"🔔 Creating event stream"
);
self.event_bus.stream()
}
/// Subscribes to download events.
///
/// Returns a broadcast receiver that can be used to receive events.
///
/// # Returns
///
/// A broadcast receiver for download events
pub fn subscribe_events(&self) -> tokio::sync::broadcast::Receiver<Arc<events::DownloadEvent>> {
tracing::debug!(
subscriber_count = self.event_bus.subscriber_count(),
"🔔 Creating event subscription"
);
let receiver = self.event_bus.subscribe();
tracing::debug!(
subscriber_count = self.event_bus.subscriber_count(),
"🔔 Event subscription created"
);
receiver
}
/// Returns the number of active event subscribers.
///
/// # Returns
///
/// The number of currently active event subscribers.
pub fn event_subscriber_count(&self) -> usize {
self.event_bus.subscriber_count()
}
#[cfg(feature = "statistics")]
/// Returns a reference to the statistics tracker.
///
/// Call [`stats::StatisticsTracker::snapshot`] to obtain aggregate metrics for all
/// downloads and metadata fetches that have occurred since the tracker was created.
///
/// # Examples
///
/// ```rust,no_run
/// # use yt_dlp::Downloader;
/// # use yt_dlp::client::deps::Libraries;
/// # use std::path::PathBuf;
/// # #[tokio::main]
/// # async fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
/// # let libs = Libraries::new(PathBuf::from("yt-dlp"), PathBuf::from("ffmpeg"));
/// let downloader = Downloader::builder(libs, "output").build().await?;
///
/// // ... perform downloads ...
///
/// let snapshot = downloader.statistics().snapshot().await;
/// println!("Completed: {}", snapshot.downloads.completed);
/// # Ok(())
/// # }
/// ```
pub fn statistics(&self) -> &crate::stats::StatisticsTracker {
&self.statistics
}
#[cfg(feature = "hooks")]
/// Registers a Rust hook for download events.
///
/// Hooks are called asynchronously for each event and can be filtered
/// to only receive specific event types.
///
/// # Arguments
///
/// * `hook` - The hook to register
///
/// # Examples
///
/// ```rust,no_run
/// # #[cfg(feature = "hooks")]
/// # {
/// # use yt_dlp::Downloader;
/// # use yt_dlp::client::deps::Libraries;
/// # use yt_dlp::events::{EventHook, EventFilter, DownloadEvent, HookResult};
/// # use async_trait::async_trait;
/// # use std::path::PathBuf;
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let libs = Libraries::new(PathBuf::from("yt-dlp"), PathBuf::from("ffmpeg"));
/// # let mut downloader = Downloader::builder(libs, "output").build().await?;
/// #[derive(Clone)]
/// struct MyHook;
///
/// #[async_trait]
/// impl EventHook for MyHook {
/// async fn on_event(&self, event: &DownloadEvent) -> HookResult {
/// println!("Event: {}", event.event_type());
/// Ok(())
/// }
///
/// fn filter(&self) -> EventFilter {
/// EventFilter::only_terminal()
/// }
/// }
///
/// downloader.register_hook(MyHook).await;
/// # Ok(())
/// # }
/// # }
/// ```
pub async fn register_hook(&mut self, hook: impl events::EventHook + 'static) {
tracing::debug!(has_registry = self.hook_registry.is_some(), "🔔 Registering event hook");
if let Some(ref mut registry) = self.hook_registry {
registry.register(hook).await;
tracing::debug!("✅ Event hook registered");
} else {
tracing::warn!("Hook registry not available, hook not registered");
}
}
#[cfg(feature = "webhooks")]
/// Registers a webhook for download events.
///
/// Webhooks are called via HTTP POST with a JSON payload containing the event.
///
/// # Arguments
///
/// * `config` - The webhook configuration
///
/// # Examples
///
/// ```rust,no_run
/// # #[cfg(feature = "webhooks")]
/// # {
/// # use yt_dlp::Downloader;
/// # use yt_dlp::client::deps::Libraries;
/// # use yt_dlp::events::{WebhookConfig, WebhookMethod, EventFilter};
/// # use std::path::PathBuf;
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let libs = Libraries::new(PathBuf::from("yt-dlp"), PathBuf::from("ffmpeg"));
/// # let mut downloader = Downloader::builder(libs, "output").build().await?;
/// let webhook = WebhookConfig::new("https://example.com/webhook")
/// .with_method(WebhookMethod::Post)
/// .with_filter(EventFilter::only_completed());
///
/// downloader.register_webhook(webhook).await;
/// # Ok(())
/// # }
/// # }
/// ```
pub async fn register_webhook(&mut self, config: events::WebhookConfig) {
tracing::debug!(
url = config.url(),
has_delivery = self.webhook_delivery.is_some(),
"🔔 Registering webhook"
);
if let Some(ref mut delivery) = self.webhook_delivery {
delivery.register(config).await;
tracing::debug!("✅ Webhook registered");
} else {
tracing::warn!("Webhook delivery not available, webhook not registered");
}
}
}