yt-dlp 2.7.2

🎬️ A Rust library (with auto dependencies installation) for Youtube downloading
Documentation
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
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
//! Cache backend trait definitions and dispatch enums.
//!
//! This module defines the backend traits (`VideoBackend`, `PlaylistBackend`, `FileBackend`)
//! and provides persistent-layer dispatch enums that delegate to the correct concrete
//! backend based on enabled features. The in-memory Moka backend is separate and used
//! as the L1 layer; the persistent enum is the L2 layer.

use std::future::Future;
#[cfg(persistent_cache)]
use std::path::Path;
use std::path::PathBuf;

#[cfg(persistent_cache)]
use crate::cache::config::{CacheConfig, PersistentBackendKind};
use crate::cache::video::{CachedFile, CachedThumbnail, CachedVideo};
use crate::error::Result;
use crate::model::Video;
use crate::model::playlist::Playlist;
use crate::model::selector::FormatPreferences;

#[cfg(feature = "cache-json")]
pub mod json;
#[cfg(feature = "cache-memory")]
pub mod memory;
#[cfg(feature = "cache-redb")]
pub mod redb;
#[cfg(feature = "cache-redis")]
pub mod redis;

// ── Shared constants ──

/// Default time-to-live for cached videos (24 hours).
pub(crate) const DEFAULT_VIDEO_TTL: u64 = 24 * 60 * 60;
/// Default time-to-live for cached playlists (6 hours).
pub(crate) const DEFAULT_PLAYLIST_TTL: u64 = 6 * 60 * 60;
/// Default time-to-live for cached files (7 days).
pub(crate) const DEFAULT_FILE_TTL: u64 = 7 * 24 * 60 * 60;

// ── Shared helpers ──

/// Compute a stable FNV-1a 64-bit hex hash of a URL.
///
/// Uses a manual implementation for cross-version stability
/// (unlike `DefaultHasher`, which can change between Rust releases).
#[cfg(persistent_cache)]
pub(crate) fn url_hash(url: &str) -> String {
    const FNV_OFFSET: u64 = 0xcbf29ce484222325;
    const FNV_PRIME: u64 = 0x00000100000001B3;
    let mut hash = FNV_OFFSET;
    for byte in url.as_bytes() {
        hash ^= *byte as u64;
        hash = hash.wrapping_mul(FNV_PRIME);
    }
    format!("{:016x}", hash)
}

/// Copy a source file into the cache directory, creating parent directories as needed.
///
/// Returns the destination path (`cache_dir` joined with `relative_path`).
#[cfg(persistent_cache)]
pub(crate) async fn copy_to_cache(cache_dir: &Path, relative_path: &str, source_path: &Path) -> Result<PathBuf> {
    let dest_path = cache_dir.join(relative_path);
    if let Some(parent) = dest_path.parent() {
        tokio::fs::create_dir_all(parent).await?;
    }
    tokio::fs::copy(source_path, &dest_path).await?;
    Ok(dest_path)
}

/// Delegates a method call to the active backend variant.
///
/// Expands to a `match self` block that forwards the call to whichever
/// concrete backend is selected at runtime, respecting feature gates.
#[cfg(persistent_cache)]
macro_rules! delegate_to_backend {
    ($self:ident . $method:ident ( $($arg:expr),* )) => {
        match $self {
            #[cfg(feature = "cache-json")]
            Self::Json(b) => b.$method($($arg),*).await,
            #[cfg(feature = "cache-redb")]
            Self::Redb(b) => b.$method($($arg),*).await,
            #[cfg(feature = "cache-redis")]
            Self::Redis(b) => b.$method($($arg),*).await,
        }
    };
}

#[cfg(feature = "cache-json")]
use json::{JsonFileCache, JsonPlaylistCache, JsonVideoCache};
#[cfg(feature = "cache-redb")]
use redb::{RedbFileCache, RedbPlaylistCache, RedbVideoCache};
#[cfg(feature = "cache-redis")]
use redis::{RedisFileCache, RedisPlaylistCache, RedisVideoCache};

/// Trait for video cache backend implementations.
pub trait VideoBackend: Send + Sync + std::fmt::Debug {
    /// Retrieves a video by its URL.
    ///
    /// # Arguments
    ///
    /// * `url` - The URL of the video to retrieve
    ///
    /// # Errors
    ///
    /// Returns an error if the backend lookup fails.
    ///
    /// # Returns
    ///
    /// The cached `Video` if found, or `None` if not present.
    fn get(&self, url: &str) -> impl Future<Output = Result<Option<Video>>> + Send;

    /// Stores a video in the cache.
    ///
    /// # Arguments
    ///
    /// * `url` - The URL to use as the cache key
    /// * `video` - The video metadata to cache
    ///
    /// # Errors
    ///
    /// Returns an error if the write operation fails.
    fn put(&self, url: String, video: Video) -> impl Future<Output = Result<()>> + Send;

    /// Removes a video from the cache by URL.
    ///
    /// # Arguments
    ///
    /// * `url` - The URL of the video to remove
    ///
    /// # Errors
    ///
    /// Returns an error if the removal operation fails.
    fn remove(&self, url: &str) -> impl Future<Output = Result<()>> + Send;

    /// Cleans expired entries from the cache.
    ///
    /// # Errors
    ///
    /// Returns an error if the cleanup operation fails.
    fn clean(&self) -> impl Future<Output = Result<()>> + Send;

    /// Retrieves a video by its ID.
    ///
    /// # Arguments
    ///
    /// * `id` - The unique identifier of the video
    ///
    /// # Errors
    ///
    /// Returns an error if the backend lookup fails.
    ///
    /// # Returns
    ///
    /// The cached video entry.
    fn get_by_id(&self, id: &str) -> impl Future<Output = Result<CachedVideo>> + Send;
}

/// Trait for playlist cache backend implementations.
pub trait PlaylistBackend: Send + Sync + std::fmt::Debug {
    /// Retrieves a playlist by its URL.
    ///
    /// # Arguments
    ///
    /// * `url` - The URL of the playlist to retrieve
    ///
    /// # Errors
    ///
    /// Returns an error if the backend lookup fails.
    ///
    /// # Returns
    ///
    /// The cached `Playlist` if found, or `None` if not present.
    fn get(&self, url: &str) -> impl Future<Output = Result<Option<Playlist>>> + Send;

    /// Retrieves a playlist by its ID.
    ///
    /// # Arguments
    ///
    /// * `id` - The unique identifier of the playlist
    ///
    /// # Errors
    ///
    /// Returns an error if the backend lookup fails.
    ///
    /// # Returns
    ///
    /// The cached `Playlist` if found, or `None` if not present.
    fn get_by_id(&self, id: &str) -> impl Future<Output = Result<Option<Playlist>>> + Send;

    /// Stores a playlist in the cache.
    ///
    /// # Arguments
    ///
    /// * `url` - The URL to use as the cache key
    /// * `playlist` - The playlist to cache
    ///
    /// # Errors
    ///
    /// Returns an error if the write operation fails.
    fn put(&self, url: String, playlist: Playlist) -> impl Future<Output = Result<()>> + Send;

    /// Invalidates (removes) a playlist from the cache by URL.
    ///
    /// # Arguments
    ///
    /// * `url` - The URL of the playlist to invalidate
    ///
    /// # Errors
    ///
    /// Returns an error if the invalidation operation fails.
    fn invalidate(&self, url: &str) -> impl Future<Output = Result<()>> + Send;

    /// Cleans expired entries from the cache.
    ///
    /// # Errors
    ///
    /// Returns an error if the cleanup operation fails.
    fn clean(&self) -> impl Future<Output = Result<()>> + Send;

    /// Clears all entries from the cache.
    ///
    /// # Errors
    ///
    /// Returns an error if the clear operation fails.
    fn clear_all(&self) -> impl Future<Output = Result<()>> + Send;
}

/// Trait for file cache backend implementations.
pub trait FileBackend: Send + Sync + std::fmt::Debug {
    /// Retrieves a file from the cache by its hash.
    ///
    /// # Arguments
    ///
    /// * `hash` - The content hash of the file
    ///
    /// # Returns
    ///
    /// The cached file entry and its path, or `None` if not found.
    ///
    /// # Errors
    ///
    /// Returns an error if the underlying I/O or deserialization fails.
    fn get_by_hash(&self, hash: &str) -> impl Future<Output = Result<Option<(CachedFile, PathBuf)>>> + Send;

    /// Retrieves a file from the cache by video ID and format ID.
    ///
    /// # Arguments
    ///
    /// * `video_id` - The video identifier
    /// * `format_id` - The format identifier
    ///
    /// # Returns
    ///
    /// The cached file entry and its path, or `None` if not found.
    ///
    /// # Errors
    ///
    /// Returns an error if the underlying I/O or deserialization fails.
    fn get_by_video_and_format(
        &self,
        video_id: &str,
        format_id: &str,
    ) -> impl Future<Output = Result<Option<(CachedFile, PathBuf)>>> + Send;

    /// Retrieves a file from the cache based on video ID and quality preferences.
    ///
    /// # Arguments
    ///
    /// * `video_id` - The video identifier
    /// * `preferences` - The format preferences to match against
    ///
    /// # Returns
    ///
    /// The cached file entry and its path, or `None` if no match.
    ///
    /// # Errors
    ///
    /// Returns an error if the underlying I/O or deserialization fails.
    fn get_by_video_and_preferences(
        &self,
        video_id: &str,
        preferences: &FormatPreferences,
    ) -> impl Future<Output = Result<Option<(CachedFile, PathBuf)>>> + Send;

    /// Store a file in the cache.
    ///
    /// # Arguments
    ///
    /// * `file` - The cached file metadata
    /// * `source_path` - Path to the source file to store
    ///
    /// # Errors
    ///
    /// Returns an error if the file cannot be stored.
    ///
    /// # Returns
    ///
    /// The path where the file was cached.
    fn put(&self, file: CachedFile, source_path: &std::path::Path) -> impl Future<Output = Result<PathBuf>> + Send;

    /// Removes a file from the cache by its ID.
    ///
    /// # Arguments
    ///
    /// * `id` - The unique identifier of the cached file
    ///
    /// # Errors
    ///
    /// Returns an error if the removal operation fails.
    fn remove(&self, id: &str) -> impl Future<Output = Result<()>> + Send;

    /// Cleans expired entries from the cache.
    ///
    /// # Errors
    ///
    /// Returns an error if the cleanup operation fails.
    fn clean(&self) -> impl Future<Output = Result<()>> + Send;

    /// Retrieve a thumbnail from the cache by video ID.
    ///
    /// # Arguments
    ///
    /// * `video_id` - The video identifier
    ///
    /// # Returns
    ///
    /// The cached thumbnail entry and its path, or `None` if not found.
    ///
    /// # Errors
    ///
    /// Returns an error if the underlying I/O or deserialization fails.
    fn get_thumbnail_by_video_id(
        &self,
        video_id: &str,
    ) -> impl Future<Output = Result<Option<(CachedThumbnail, PathBuf)>>> + Send;

    /// Store a thumbnail in the cache.
    ///
    /// # Arguments
    ///
    /// * `thumbnail` - The cached thumbnail metadata
    /// * `source_path` - Path to the source thumbnail file
    ///
    /// # Errors
    ///
    /// Returns an error if the thumbnail cannot be stored.
    ///
    /// # Returns
    ///
    /// The path where the thumbnail was cached.
    fn put_thumbnail(
        &self,
        thumbnail: CachedThumbnail,
        source_path: &std::path::Path,
    ) -> impl Future<Output = Result<PathBuf>> + Send;

    /// Retrieve a subtitle from the cache by video ID and language.
    ///
    /// # Arguments
    ///
    /// * `video_id` - The video identifier
    /// * `language` - The subtitle language code
    ///
    /// # Returns
    ///
    /// The cached subtitle file entry and its path, or `None` if not found.
    ///
    /// # Errors
    ///
    /// Returns an error if the underlying I/O or deserialization fails.
    fn get_subtitle_by_language(
        &self,
        video_id: &str,
        language: &str,
    ) -> impl Future<Output = Result<Option<(CachedFile, PathBuf)>>> + Send;
}

// ── Persistent backend dispatch enums ──

/// Enum dispatch for persistent video backends.
///
/// All features' variants are included when their respective feature is enabled.
/// The active backend is selected at construction time via `PersistentBackendKind::resolve`.
#[cfg(persistent_cache)]
#[derive(Debug)]
pub enum PersistentVideoBackend {
    #[cfg(feature = "cache-json")]
    Json(JsonVideoCache),
    #[cfg(feature = "cache-redb")]
    Redb(RedbVideoCache),
    #[cfg(feature = "cache-redis")]
    Redis(RedisVideoCache),
}

/// Enum dispatch for persistent playlist backends.
#[cfg(persistent_cache)]
#[derive(Debug)]
pub enum PersistentPlaylistBackend {
    #[cfg(feature = "cache-json")]
    Json(JsonPlaylistCache),
    #[cfg(feature = "cache-redb")]
    Redb(RedbPlaylistCache),
    #[cfg(feature = "cache-redis")]
    Redis(RedisPlaylistCache),
}

/// Enum dispatch for persistent file backends.
#[cfg(persistent_cache)]
#[derive(Debug)]
pub enum PersistentFileBackend {
    #[cfg(feature = "cache-json")]
    Json(JsonFileCache),
    #[cfg(feature = "cache-redb")]
    Redb(RedbFileCache),
    #[cfg(feature = "cache-redis")]
    Redis(RedisFileCache),
}

// ── Persistent video backend constructors & dispatch ──

#[cfg(persistent_cache)]
impl PersistentVideoBackend {
    /// Creates the persistent video backend for the selected kind.
    ///
    /// # Arguments
    ///
    /// * `config` - The cache configuration specifying directories, TTLs, and backend settings.
    /// * `ttl` - Time-to-live in seconds
    ///
    /// # Errors
    ///
    /// Returns `Error::AmbiguousCacheBackend` if `kind` is `None` and multiple backends are compiled in.
    /// Returns an error if the selected backend fails to initialize.
    pub async fn new(config: &CacheConfig, ttl: Option<u64>) -> Result<Self> {
        match PersistentBackendKind::resolve(config.persistent_backend)? {
            #[cfg(feature = "cache-json")]
            PersistentBackendKind::Json => Ok(Self::Json(JsonVideoCache::new(config.cache_dir.clone(), ttl).await?)),
            #[cfg(feature = "cache-redb")]
            PersistentBackendKind::Redb => Ok(Self::Redb(RedbVideoCache::new(config.cache_dir.clone(), ttl).await?)),
            #[cfg(feature = "cache-redis")]
            PersistentBackendKind::Redis => {
                let url = config.redis_url.as_deref().unwrap_or("redis://127.0.0.1/");
                Ok(Self::Redis(RedisVideoCache::new(url, ttl).await?))
            }
        }
    }
}

#[cfg(persistent_cache)]
impl VideoBackend for PersistentVideoBackend {
    async fn get(&self, url: &str) -> Result<Option<Video>> {
        delegate_to_backend!(self.get(url))
    }

    async fn put(&self, url: String, video: Video) -> Result<()> {
        delegate_to_backend!(self.put(url, video))
    }

    async fn remove(&self, url: &str) -> Result<()> {
        delegate_to_backend!(self.remove(url))
    }

    async fn clean(&self) -> Result<()> {
        delegate_to_backend!(self.clean())
    }

    async fn get_by_id(&self, id: &str) -> Result<CachedVideo> {
        delegate_to_backend!(self.get_by_id(id))
    }
}

// ── Persistent playlist backend constructors & dispatch ──

#[cfg(persistent_cache)]
impl PersistentPlaylistBackend {
    /// Creates the persistent playlist backend for the selected kind.
    ///
    /// # Arguments
    ///
    /// * `config` - The cache configuration specifying directories, TTLs, and backend settings.
    /// * `ttl` - Time-to-live in seconds
    ///
    /// # Errors
    ///
    /// Returns `Error::AmbiguousCacheBackend` if `kind` is `None` and multiple backends are compiled in.
    /// Returns an error if the selected backend fails to initialize.
    pub async fn new(config: &CacheConfig, ttl: Option<u64>) -> Result<Self> {
        match PersistentBackendKind::resolve(config.persistent_backend)? {
            #[cfg(feature = "cache-json")]
            PersistentBackendKind::Json => Ok(Self::Json(JsonPlaylistCache::new(config.cache_dir.clone(), ttl).await?)),
            #[cfg(feature = "cache-redb")]
            PersistentBackendKind::Redb => Ok(Self::Redb(RedbPlaylistCache::new(config.cache_dir.clone(), ttl).await?)),
            #[cfg(feature = "cache-redis")]
            PersistentBackendKind::Redis => {
                let url = config.redis_url.as_deref().unwrap_or("redis://127.0.0.1/");
                Ok(Self::Redis(RedisPlaylistCache::new(url, ttl).await?))
            }
        }
    }
}

#[cfg(persistent_cache)]
impl PlaylistBackend for PersistentPlaylistBackend {
    async fn get(&self, url: &str) -> Result<Option<Playlist>> {
        delegate_to_backend!(self.get(url))
    }

    async fn get_by_id(&self, id: &str) -> Result<Option<Playlist>> {
        delegate_to_backend!(self.get_by_id(id))
    }

    async fn put(&self, url: String, playlist: Playlist) -> Result<()> {
        delegate_to_backend!(self.put(url, playlist))
    }

    async fn invalidate(&self, url: &str) -> Result<()> {
        delegate_to_backend!(self.invalidate(url))
    }

    async fn clean(&self) -> Result<()> {
        delegate_to_backend!(self.clean())
    }

    async fn clear_all(&self) -> Result<()> {
        delegate_to_backend!(self.clear_all())
    }
}

// ── Persistent file backend constructors & dispatch ──

#[cfg(persistent_cache)]
impl PersistentFileBackend {
    /// Creates the persistent file backend for the selected kind.
    ///
    /// # Arguments
    ///
    /// * `config` - The cache configuration specifying directories, TTLs, and backend settings.
    /// * `ttl` - Time-to-live in seconds
    ///
    /// # Errors
    ///
    /// Returns `Error::AmbiguousCacheBackend` if `kind` is `None` and multiple backends are compiled in.
    /// Returns an error if the selected backend fails to initialize.
    pub async fn new(config: &CacheConfig, ttl: Option<u64>) -> Result<Self> {
        match PersistentBackendKind::resolve(config.persistent_backend)? {
            #[cfg(feature = "cache-json")]
            PersistentBackendKind::Json => Ok(Self::Json(JsonFileCache::new(config.cache_dir.clone(), ttl).await?)),
            #[cfg(feature = "cache-redb")]
            PersistentBackendKind::Redb => Ok(Self::Redb(RedbFileCache::new(config.cache_dir.clone(), ttl).await?)),
            #[cfg(feature = "cache-redis")]
            PersistentBackendKind::Redis => {
                let url = config.redis_url.as_deref().unwrap_or("redis://127.0.0.1/");
                Ok(Self::Redis(
                    RedisFileCache::new(url, config.cache_dir.clone(), ttl).await?,
                ))
            }
        }
    }
}

#[cfg(persistent_cache)]
impl FileBackend for PersistentFileBackend {
    async fn get_by_hash(&self, hash: &str) -> Result<Option<(CachedFile, PathBuf)>> {
        delegate_to_backend!(self.get_by_hash(hash))
    }

    async fn get_by_video_and_format(&self, video_id: &str, format_id: &str) -> Result<Option<(CachedFile, PathBuf)>> {
        delegate_to_backend!(self.get_by_video_and_format(video_id, format_id))
    }

    async fn get_by_video_and_preferences(
        &self,
        video_id: &str,
        preferences: &FormatPreferences,
    ) -> Result<Option<(CachedFile, PathBuf)>> {
        delegate_to_backend!(self.get_by_video_and_preferences(video_id, preferences))
    }

    async fn put(&self, file: CachedFile, source_path: &std::path::Path) -> Result<PathBuf> {
        delegate_to_backend!(self.put(file, source_path))
    }

    async fn remove(&self, id: &str) -> Result<()> {
        delegate_to_backend!(self.remove(id))
    }

    async fn clean(&self) -> Result<()> {
        delegate_to_backend!(self.clean())
    }

    async fn get_thumbnail_by_video_id(&self, video_id: &str) -> Result<Option<(CachedThumbnail, PathBuf)>> {
        delegate_to_backend!(self.get_thumbnail_by_video_id(video_id))
    }

    async fn put_thumbnail(&self, thumbnail: CachedThumbnail, source_path: &std::path::Path) -> Result<PathBuf> {
        delegate_to_backend!(self.put_thumbnail(thumbnail, source_path))
    }

    async fn get_subtitle_by_language(&self, video_id: &str, language: &str) -> Result<Option<(CachedFile, PathBuf)>> {
        delegate_to_backend!(self.get_subtitle_by_language(video_id, language))
    }
}