dash-mpd-cli 0.2.3

Download content from a DASH-MPEG or DASH-WebM MPD manifest
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
//! dash-mpd-cli
//!
//! A commandline application for downloading media content from a DASH MPD file, as used for on-demand
//! replay of TV content and video streaming services like YouTube.
//!
//! [DASH](https://en.wikipedia.org/wiki/Dynamic_Adaptive_Streaming_over_HTTP) (dynamic adaptive
//! streaming over HTTP), also called MPEG-DASH, is a technology used for media streaming over the web,
//! commonly used for video on demand (VOD) services. The Media Presentation Description (MPD) is a
//! description of the resources (manifest or “playlist”) forming a streaming service, that a DASH
//! client uses to determine which assets to request in order to perform adaptive streaming of the
//! content. DASH MPD manifests can be used both with content encoded as MPEG and as WebM.
//!
//! This commandline application allows you to download content (audio or video) described by an MPD
//! manifest. This involves selecting the alternative with the most appropriate encoding (in terms of
//! bitrate, codec, etc.), fetching segments of the content using HTTP or HTTPS requests and muxing
//! audio and video segments together. It builds on the [dash-mpd](https://crates.io/crates/dash-mpd)
//! crate.
//
//
// Example usage: dash-mpd-cli --timeout 5 --output=/tmp/foo.mp4 https://v.redd.it/zv89llsvexdz/DASHPlaylist.mpd

use std::env;
use std::path::Path;
use std::net::IpAddr;
use std::str::FromStr;
use std::time::Duration;
use std::sync::Arc;
use std::collections::HashMap;
use fs_err as fs;
use reqwest::header;
use clap::{Arg, ArgAction, ValueHint};
use number_prefix::{NumberPrefix, Prefix};
use indicatif::{ProgressBar, ProgressStyle};
use anyhow::Result;
use dash_mpd::fetch::DashDownloader;
use dash_mpd::fetch::ProgressObserver;

#[cfg(feature = "cookies")]
use bench_scraper::{find_cookies, KnownBrowser};


struct DownloadProgressBar {
    bar: ProgressBar,
}

impl DownloadProgressBar {
    pub fn new() -> Self {
        let b = ProgressBar::new(100)
            .with_style(ProgressStyle::default_bar()
                        .template("[{elapsed}] [{bar:50.cyan/blue}] {wide_msg}")
                        .expect("building progress bar")
                        .progress_chars("#>-"));
        Self { bar: b }
    }
}

impl ProgressObserver for DownloadProgressBar {
    fn update(&self, percent: u32, message: &str) {
        if percent <= 100 {
            self.bar.set_position(percent.into());
            self.bar.set_message(message.to_string());
        }
        if percent == 100 {
            self.bar.finish_with_message("Done");
        }
    }
}


#[cfg(feature = "cookies")]
fn known_browser_names() -> String {
    use strum::IntoEnumIterator;

    KnownBrowser::iter()
        .map(|b| format!("{b:?}"))
        .collect::<Vec<_>>()
        .join(", ")
}

#[cfg(not(feature = "cookies"))]
fn known_browser_names() -> String {
    String::from("")
}


#[tokio::main]
async fn main () -> Result<()> {
    env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info,reqwest=warn")).init();
    #[allow(unused_mut)]
    let mut clap = clap::Command::new("dash-mpd-cli")
        .about("Download content from an MPEG-DASH streaming media manifest")
        .version(clap::crate_version!())
        .arg(Arg::new("user-agent")
             .long("user-agent")
             .short('U')
             .num_args(1))
        .arg(Arg::new("proxy")
             .long("proxy")
             .value_name("URL")
             .num_args(1)
             .help("URL of Socks or HTTP proxy (e.g. https://example.net/ or socks5://example.net/)."))
        .arg(Arg::new("no-proxy")
             .long("no-proxy")
             .action(ArgAction::SetTrue)
             .num_args(0)
             .conflicts_with("proxy")
             .help("Disable use of Socks or HTTP proxy even if related environment variables are set."))
        .arg(Arg::new("timeout")
             .long("timeout")
             .value_name("SECONDS")
             .num_args(1)
             .help("Timeout for network requests (from the start to the end of the request), in seconds."))
        .arg(Arg::new("sleep-requests")
             .long("sleep-requests")
             .value_name("SECONDS")
             .num_args(1)
             .value_parser(clap::value_parser!(u8))
             .help("Number of seconds to sleep between network requests (default 0)."))
        .arg(Arg::new("limit-rate")
             .long("limit-rate")
             .short('r')
             .value_name("RATE")
             .num_args(1)
             .help("Maximum network bandwidth in octets per second (default no limit), e.g. 200K, 1M."))
        .arg(Arg::new("max-error-count")
             .long("max-error-count")
             .value_name("COUNT")
             .num_args(1)
             .value_parser(clap::value_parser!(u32))
             .help("Abort after COUNT non-transient network errors.")
             .long_help("Maximum number of non-transient network errors that should be ignored before a download is aborted (default is 10)."))
        .arg(Arg::new("source-address")
             .long("source-address")
             .num_args(1)
	     .long_help("Source IP address to use for network requests, either IPv4 or IPv6. Network requests will be made using the version of this IP address (e.g. using an IPv6 source-address will select IPv6 network traffic)."))
        .arg(Arg::new("add-root-certificate")
             .long("add-root-certificate")
             .value_name("CERT")
             .num_args(1)
             .value_hint(ValueHint::FilePath)
             .help("Add a root certificate (in PEM format) to be used when verifying TLS network connections."))
        .arg(Arg::new("client-identity-certificate")
             .long("client-identity-certificate")
             .value_name("CERT")
             .num_args(1)
             .value_hint(ValueHint::FilePath)
             .help("Client private key and certificate (in PEM format) to be used when authenticating TLS network connections."))
        .arg(Arg::new("quality")
             .long("quality")
             .num_args(1)
             .value_parser(["best", "worst"])
             .help("Prefer best quality (and highest bandwidth) representation, or lowest quality."))
        .arg(Arg::new("prefer-language")
             .long("prefer-language")
             .value_name("LANG")
             .num_args(1)
             .long_help("Preferred language when multiple audio streams with different languages are available. Must be in RFC 5646 format (e.g. fr or en-AU). If a preference is not specified and multiple audio streams are present, the first one listed in the DASH manifest will be downloaded."))
        .arg(Arg::new("video-only")
             .long("video-only")
             .action(ArgAction::SetTrue)
             .num_args(0)
             .conflicts_with("audio-only")
             .help("If media stream has separate audio and video streams, only download the video stream."))
        .arg(Arg::new("audio-only")
             .long("audio-only")
             .action(ArgAction::SetTrue)
             .num_args(0)
             .conflicts_with("video-only")
             .help("If media stream has separate audio and video streams, only download the audio stream."))
        .arg(Arg::new("simulate")
             .long("simulate")
             .action(ArgAction::SetTrue)
             .num_args(0)
             .conflicts_with("write-subs")
             .conflicts_with("keep-video")
             .conflicts_with("keep-audio")
             .help("Download the manifest and print diagnostic information, but do not download audio, video or subtitle content, and write nothing to disk."))
        .arg(Arg::new("write-subs")
             .long("write-subs")
             .action(ArgAction::SetTrue)
             .num_args(0)
             .help("Write subtitle file, if subtitles are available."))
        .arg(Arg::new("keep-video")
             .long("keep-video")
             .value_name("VIDEO-PATH")
             .num_args(1)
             .value_hint(ValueHint::FilePath)
             .help("Keep video stream in file specified by VIDEO-PATH."))
        .arg(Arg::new("keep-audio")
             .long("keep-audio")
             .value_name("AUDIO-PATH")
             .num_args(1)
             .value_hint(ValueHint::FilePath)
             .help("Keep audio stream (if audio is available as a separate media stream) in file specified by AUDIO-PATH."))
        .arg(Arg::new("key")
             .long("key")
             .value_name("KID:KEY")
             .num_args(1)
             .action(clap::ArgAction::Append)
             .long_help("Use KID:KEY to decrypt encrypted media streams. KID should be either a track id in decimal (e.g. 1), or a 128-bit keyid (32 hexadecimal characters). KEY should be 32 hexadecimal characters. Example: --key eb676abbcb345e96bbcf616630f1a3da:100b6c20940f779a4589152b57d2dacb. You can use this option multiple times."))
        .arg(Arg::new("save-fragments")
             .long("save-fragments")
             .value_name("FRAGMENTS-DIR")
             .value_hint(ValueHint::DirPath)
             .num_args(1)
             .help("Save media fragments to this directory (will be created if it does not exist)."))
        .arg(Arg::new("ignore-content-type")
             .long("ignore-content-type")
             .action(ArgAction::SetTrue)
             .num_args(0)
             .help("Don't check the content-type of media fragments (may be required for some poorly configured servers)."))
        .arg(Arg::new("add-header")
             .long("add-header")
             .value_name("NAME:VALUE")
             .num_args(1)
             .action(clap::ArgAction::Append)
             .long_help("Add a custom HTTP header and its value, separated by a colon ':'. You can use this option multiple times."))
        .arg(Arg::new("referer")
             .long("referer")
             .alias("referrer")
             .value_name("URL")
             .num_args(1)
             .help("Specify content of Referer HTTP header."))
        .arg(Arg::new("quiet")
             .short('q')
             .long("quiet")
             .action(ArgAction::SetTrue)
             .num_args(0)
             .conflicts_with("verbose"))
        .arg(Arg::new("verbose")
             .short('v')
             .long("verbose")
             .action(clap::ArgAction::Count)
             .help("Level of verbosity (can be used several times)."))
        .arg(Arg::new("no-progress")
             .long("no-progress")
             .action(ArgAction::SetTrue)
             .num_args(0)
             .help("Disable the progress bar"))
        .arg(Arg::new("no-xattr")
             .long("no-xattr")
             .action(ArgAction::SetTrue)
             .num_args(0)
             .help("Don't record metainformation as extended attributes in the output file."))
        .arg(Arg::new("ffmpeg-location")
             .long("ffmpeg-location")
             .value_name("PATH")
             .value_hint(ValueHint::ExecutablePath)
             .num_args(1)
             .help("Path to the ffmpeg binary (necessary if not located in your PATH)."))
        .arg(Arg::new("vlc-location")
             .long("vlc-location")
             .value_name("PATH")
             .value_hint(ValueHint::ExecutablePath)
             .num_args(1)
             .help("Path to the VLC binary (necessary if not located in your PATH)."))
        .arg(Arg::new("mkvmerge-location")
             .long("mkvmerge-location")
             .value_name("PATH")
             .value_hint(ValueHint::ExecutablePath)
             .num_args(1)
             .help("Path to the mkvmerge binary (necessary if not located in your PATH)."))
        .arg(Arg::new("mp4box-location")
             .long("mp4box-location")
             .value_name("PATH")
             .value_hint(ValueHint::ExecutablePath)
             .num_args(1)
             .help("Path to the MP4Box binary (necessary if not located in your PATH)."))
        .arg(Arg::new("mp4decrypt-location")
             .long("mp4decrypt-location")
             .value_name("PATH")
             .value_hint(ValueHint::ExecutablePath)
             .num_args(1)
             .help("Path to the mp4decrypt binary (necessary if not located in your PATH)."))
        .arg(Arg::new("output-file")
             .long("output")
             .value_name("PATH")
             .value_hint(ValueHint::FilePath)
             .short('o')
             .num_args(1)
             .help("Save media content to this file."))
        .arg(Arg::new("url")
             .value_name("MPD-URL")
             .value_hint(ValueHint::Url)
             .required(true)
             .num_args(1)
             .index(1)
             .help("URL of the DASH manifest to retrieve."));
    #[allow(unused_variables)]
    let known_browser_names = known_browser_names();
    #[cfg(feature = "cookies")] {
        clap = clap
            .arg(Arg::new("cookies-from-browser")
                 .long("cookies-from-browser")
                 .value_name("BROWSER")
                 .num_args(1)
                 .help(format!("Load cookies from BROWSER ({known_browser_names}).")))
            .arg(Arg::new("list-cookie-sources")
                 .long("list-cookie-sources")
                 .action(ArgAction::SetTrue)
                 .num_args(0)
                 .exclusive(true)
                 .help("Show valid values for BROWSER argument to --cookies-from-browser on this computer, then exit."));
    }
    let matches = clap.get_matches();

    // TODO: add --abort-on-error
    // TODO: add --fragment-retries arg
    // TODO: add --mtime arg (Last-modified header)
    #[cfg(feature = "cookies")]
    if matches.get_flag("list-cookie-sources") {
        eprintln!("On this computer, cookies are available from the following browsers:");
        let browsers = find_cookies()
            .expect("reading cookies from browser");
        for b in browsers.iter() {
            eprintln!("  {:?} ({} cookies)", b.browser, b.cookies.len());
        }
        std::process::exit(3);
    }
    let verbosity = matches.get_count("verbose");
    let ua = match matches.get_one::<String>("user-agent") {
        Some(ua) => ua,
        None => concat!("dash-mpd-cli/", env!("CARGO_PKG_VERSION")),
    };
    let mut cb = reqwest::Client::builder()
        .user_agent(ua)
        .gzip(true);
    #[cfg(feature = "cookies")]
    if let Some(browser) = matches.get_one::<String>("cookies-from-browser") {
        if let Some(wanted) = match browser.as_str() {
            "Firefox" => Some(KnownBrowser::Firefox),
            "Chrome" => Some(KnownBrowser::Chrome),
            "ChromeBeta" => Some(KnownBrowser::ChromeBeta),
            "Chromium" => Some(KnownBrowser::Chromium),
            #[cfg(target_os = "windows")]
            "Edge" => Some(KnownBrowser::Edge),
            #[cfg(target_os = "macos")]
            "Safari" => Some(KnownBrowser::Safari),
            _ => None,
        } {
            let jar = reqwest::cookie::Jar::default();
            let browsers = find_cookies()
                .expect("reading cookies from browser");
            let targets = browsers.iter()
                .filter(|b| b.browser == wanted);
            let mut targets_found = false;
            for b in targets {
                targets_found = true;
                for c in &b.cookies {
                    let set_cookie = c.get_set_cookie_header();
                    if let Ok(url) = reqwest::Url::parse(&c.get_url()) {
                        jar.add_cookie_str(&set_cookie, &url);
                    }
                }
            }
            if targets_found {
                cb = cb.cookie_store(true).cookie_provider(Arc::new(jar));
            } else {
                eprintln!("Can't access cookies from {browser}.");
                eprintln!("On this computer, cookies are available from the following browsers:");
                for b in browsers.iter() {
                    eprintln!("  {:?} ({} cookies)", b.browser, b.cookies.len());
                }
            }
        } else {
            eprintln!("Ignoring unknown browser {browser}. Try one of {known_browser_names}.");
        }
    }
    if verbosity > 2 {
       cb = cb.connection_verbose(true);
    }
    if let Some(p) = matches.get_one::<String>("proxy") {
        let proxy = reqwest::Proxy::all(p)
            .expect("connecting to HTTP proxy");
        cb = cb.proxy(proxy);
    }
    if matches.get_flag("no-proxy") {
        cb = cb.no_proxy();
    }
    if let Some(src) = matches.get_one::<String>("source-address") {
       if let Ok(local_addr) = IpAddr::from_str(src) {
          cb = cb.local_address(local_addr);
       } else {
          eprintln!("Ignoring invalid argument to --source-address: {src}");
       }
    }
    if let Some(seconds) = matches.get_one::<String>("timeout") {
        if let Ok(secs) = seconds.parse::<u64>() {
            cb = cb.timeout(Duration::new(secs, 0));
        } else {
            eprintln!("Ignoring invalid value for --timeout: {seconds}");
        }
    } else {
        cb = cb.timeout(Duration::new(30, 0));
    }
    if let Some(hvs) = matches.get_many::<String>("add-header") {
        let mut headers = HashMap::new();
        for hv in hvs.collect::<Vec<_>>() {
            if let Some((h, v)) = hv.split_once(':') {
                headers.insert(h.to_string(), v.to_string());
            } else {
                eprintln!("Ignoring badly formed header:value argument to --add-header");
            }
        }
        if let Some(url) = matches.get_one::<String>("referer") {
            headers.insert("referer".to_string(), url.to_string());
        }
        let hmap: header::HeaderMap = (&headers).try_into()
            .expect("valid HTTP headers");
        cb = cb.default_headers(hmap);
    }
    if let Some(rcs) = matches.get_many::<String>("add-root-certificate") {
        for rc in rcs {
            match fs::read(rc) {
                Ok(pem) => {
                    match reqwest::Certificate::from_pem(&pem) {
                        Ok(cert) => {
                            cb = cb.add_root_certificate(cert);
                        },
                        Err(e) => {
                            eprintln!("Can't decode root certificate: {e}");
                            std::process::exit(6);
                        },
                    }
                },
                Err(e) => {
                    eprintln!("Can't read root certificate: {e}");
                    std::process::exit(5);
                },
            }
        }
    }
    if let Some(cc) = matches.get_one::<String>("client-identity-certificate") {
        match fs::read(cc) {
            Ok(pem) => {
                match reqwest::Identity::from_pem(&pem) {
                    Ok(id) => {
                        cb = cb.identity(id);
                    },
                    Err(e) => {
                        eprintln!("Can't decode client certificate: {e}");
                        std::process::exit(8);
                    },
                }
            },
            Err(e) => {
                eprintln!("Can't read client certificate: {e}");
                std::process::exit(7);
            },
        }
    }
    let client = cb.build()
        .expect("creating HTTP client");
    let url = matches.get_one::<String>("url").unwrap();
    let mut dl = DashDownloader::new(url)
        .with_http_client(client);
    if !matches.get_flag("no-progress") && !matches.get_flag("quiet") {
        dl = dl.add_progress_observer(Arc::new(DownloadProgressBar::new()));
    }
    if let Some(seconds) = matches.get_one::<u8>("sleep-requests") {
        dl = dl.sleep_between_requests(*seconds);
    }
    if let Some(limit) = matches.get_one::<String>("limit-rate") {
        // We allow k, M, G, T suffixes, as per 100k, 1M, 0.4G
        if let Ok(np) = limit.parse::<NumberPrefix<f64>>() {
            let bps = match np {
                NumberPrefix::Standalone(bps) => bps,
                NumberPrefix::Prefixed(pfx, n) => match pfx {
                    Prefix::Kilo => n * 1024.0,
                    Prefix::Mega => n * 1024.0 * 1024.0,
                    Prefix::Giga => n * 1024.0 * 1024.0 * 1024.0,
                    Prefix::Tera => n * 1024.0 * 1024.0 * 1024.0 * 1024.0,
                    _ => {
                        eprintln!("Ignoring unrecognized suffix on limit-rate");
                        0.0
                    },
                },
            };
            if bps > 0.0 {
                dl = dl.with_rate_limit(bps as u64);
            } else {
                eprintln!("Ignoring negative value for limit-rate");
            }
        } else {
            eprintln!("Ignoring badly formed value for limit-rate");
        }
    }
    if let Some(count) = matches.get_one::<u32>("max-error-count") {
        dl = dl.max_error_count(*count);
    }
    if matches.get_flag("audio-only") {
        dl = dl.audio_only();
    }
    if matches.get_flag("video-only") {
        dl = dl.video_only();
    }
    if matches.get_flag("simulate") {
        dl = dl.fetch_audio(false)
            .fetch_video(false)
            .fetch_subtitles(false);
    }
    if let Some(path) = matches.get_one::<String>("keep-video") {
        dl = dl.keep_video_as(path);
    }
    if let Some(path) = matches.get_one::<String>("keep-audio") {
        dl = dl.keep_audio_as(path);
    }
    if let Some(kvs) = matches.get_many::<String>("key") {
        for kv in kvs.collect::<Vec<_>>() {
            if let Some((kid, key)) = kv.split_once(':') {
                if key.len() != 32 {
                    eprintln!("Ignoring invalid format for KEY (should be 32 hex digits)");
                } else {
                    dl = dl.add_decryption_key(String::from(kid), String::from(key));
                }
            } else {
                eprintln!("Ignoring badly formed KID:KEY argument to --key");
            }
        }
    }
    if let Some(fragments_dir) = matches.get_one::<String>("save-fragments") {
        dl = dl.save_fragments_to(Path::new(fragments_dir));
    }
    if matches.get_flag("write-subs") {
        dl = dl.fetch_subtitles(true);
    }
    if matches.get_flag("ignore-content-type") {
        dl = dl.without_content_type_checks();
    }
    if matches.get_flag("no-xattr") {
        dl = dl.record_metainformation(false);
    }
    if let Some(ffmpeg_path) = matches.get_one::<String>("ffmpeg-location") {
        dl = dl.with_ffmpeg(ffmpeg_path);
    }
    if let Some(path) = matches.get_one::<String>("vlc-location") {
        dl = dl.with_vlc(path);
    }
    if let Some(path) = matches.get_one::<String>("mkvmerge-location") {
        dl = dl.with_mkvmerge(path);
    }
    if let Some(path) = matches.get_one::<String>("mp4box-location") {
        dl = dl.with_mp4box(path);
    }
    if let Some(path) = matches.get_one::<String>("mp4decrypt-location") {
        dl = dl.with_mp4decrypt(path);
    }
    if let Some(q) = matches.get_one::<String>("quality") {
        if q.eq("best") {
            // DashDownloader defaults to worst quality
            dl = dl.best_quality();
        }
    }
    if let Some(lang) = matches.get_one::<String>("prefer-language") {
        dl = dl.prefer_language(lang.to_string());
    }
    dl = dl.verbosity(verbosity);
    if let Some(out) = matches.get_one::<String>("output-file") {
        if let Err(e) = dl.download_to(out).await {
            eprintln!("Download failed: {e}");
        }
    } else {
        match dl.download().await {
            Ok(out) => {
                if !matches.get_flag("simulate") {
                    println!("Downloaded DASH content to {out:?}");
                }
            },
            Err(e) => {
                eprintln!("Download failed: {e}");
                std::process::exit(2);
            },
        }
    }
    std::process::exit(0)
}