use std::fs;
use std::env;
use std::net::SocketAddr;
use std::time::Duration;
use std::path::{Path, PathBuf};
use axum::{routing::get, Router};
use axum::http::header;
use axum_server::{Handle, bind};
use ffprobe::ffprobe;
use file_format::FileFormat;
use tracing_subscriber::EnvFilter;
use tracing_subscriber::prelude::*;
use dash_mpd::fetch::DashDownloader;
use anyhow::Result;
fn check_file_size_approx(p: &Path, expected: u64) {
let meta = fs::metadata(p).unwrap();
let ratio = meta.len() as f64 / expected as f64;
assert!(0.9 < ratio && ratio < 1.1, "File sizes: expected {expected}, got {}", meta.len());
}
#[tokio::main]
async fn main() -> Result<()> {
let fmt_layer = tracing_subscriber::fmt::layer()
.compact();
let filter_layer = EnvFilter::try_from_default_env()
.or_else(|_| EnvFilter::try_new("info,reqwest=warn"))
.unwrap();
tracing_subscriber::registry()
.with(filter_layer)
.with(fmt_layer)
.init();
let mut mpd = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
mpd.push("tests");
mpd.push("fixtures");
mpd.push("telenet-mid-ad-rolls");
mpd.set_extension("mpd");
let mpd = fs::read_to_string(mpd).unwrap();
let app = Router::new()
.route("/mpd", get(
|| async { ([(header::CONTENT_TYPE, "application/dash+xml")], mpd) }));
let server_handle: Handle<SocketAddr> = Handle::new();
let backend_handle = server_handle.clone();
let backend = async move {
bind("127.0.0.1:6669".parse().unwrap())
.handle(backend_handle)
.serve(app.into_make_service()).await
.unwrap()
};
tokio::spawn(backend);
tokio::time::sleep(Duration::from_millis(500)).await;
let out = env::temp_dir().join("nothx.mp4");
let mut xslt = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
xslt.push("tests");
xslt.push("fixtures");
xslt.push("rewrite-drop-dai");
xslt.set_extension("xslt");
DashDownloader::new("http://localhost:6669/mpd")
.worst_quality()
.with_xslt_stylesheet(xslt)
.with_muxer_preference("mp4", "mp4box")
.download_to(out.clone()).await
.unwrap();
server_handle.shutdown();
check_file_size_approx(&out, 256_234_645);
let format = FileFormat::from_file(out.clone()).unwrap();
assert_eq!(format, FileFormat::Mpeg4Part14Video);
let meta = ffprobe(out.clone()).unwrap();
assert_eq!(meta.streams.len(), 2);
let video = &meta.streams[0];
assert_eq!(video.codec_type, Some(String::from("video")));
assert_eq!(video.codec_name, Some(String::from("h264")));
println!("Your uninfested content is at {}", out.display());
Ok(())
}