S012: HLS, DASH, RTSP and MMS

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
astar76 2026-11-25 13:18:25 -06:00
commit d26c59ee26
22 changed files with 3608 additions and 7 deletions

3
Cargo.lock generated
View file

@ -2768,9 +2768,11 @@ dependencies = [
name = "medlar-core"
version = "0.1.0"
dependencies = [
"aes",
"arc-swap",
"base64 0.23.1",
"bytes",
"cbc",
"chrono",
"dirs",
"fastrand",
@ -2785,6 +2787,7 @@ dependencies = [
"rcgen",
"regex",
"reqwest",
"roxmltree 0.21.2",
"rusqlite",
"russh",
"russh-sftp",

View file

@ -6,9 +6,11 @@ license.workspace = true
description = "Medlar's engine, store and settings"
[dependencies]
aes = "0.9"
arc-swap = "1.9.5"
base64 = "0.23"
bytes = "1.10"
cbc = "0.2"
chrono = { version = "0.4", default-features = false, features = ["clock", "std"] }
dirs = "6"
futures-lite = "2.6"
@ -19,6 +21,7 @@ log = { workspace = true, features = ["std"] }
md-5 = "0.11.0"
percent-encoding = "2.3.2"
regex = { version = "1", default-features = false, features = ["std", "unicode-case", "unicode-perl"] }
roxmltree = "0.21"
# Pinned: D-017.
reqwest = { version = "=0.13.5", default-features = false, features = ["rustls-no-provider", "socks"] }
# ring, as everywhere else: aws-lc-rs would be a second one.
@ -32,7 +35,7 @@ rustls-platform-verifier = "0.7.1"
serde.workspace = true
serde_json.workspace = true
sha2 = "0.11.1"
tokio = { version = "1.54.1", features = ["rt-multi-thread", "macros", "sync", "time", "net", "io-util"] }
tokio = { version = "1.54.1", features = ["rt-multi-thread", "macros", "sync", "time", "net", "io-util", "process"] }
tokio-rustls = { version = "0.26", default-features = false }
tower-service = "0.3"
url = "2"

View file

@ -270,6 +270,16 @@
"error.wrong_content.why": "{server} sent a web page instead of the file. The link may be old, or need a login.",
"error.no_resume": "Can't be continued",
"error.no_resume.why": "{server} no longer sends the rest of a file, only all of it. What is here was kept.",
"error.tool": "A program is missing",
"error.tool.why": "A program this download needs is not on this computer. Install it, then try again.",
"error.tool.ffmpeg": "Streams need the program ffmpeg, which is not on this computer. Install it, then try again.",
"error.drm": "Copy protected",
"error.drm.why": "{server} sends this stream with copy protection. Medlar does not get around it, so nothing was downloaded.",
"error.media": "Stream can't be saved",
"error.media.why": "ffmpeg could not make a file of what {server} sent.",
"error.media.choice": "{server} no longer offers the chosen quality or language.",
"error.media.empty": "{server} sent no sound or picture.",
"error.proxy.stream": "The stream from {server} can't go through the proxy, and Medlar does not connect without it.",
"error.disk_full": "Disk is full",
"error.disk_full.why": "There is not enough space in {folder}. The download goes on when there is.",
"error.read_only": "Disk is read-only",

View file

@ -102,6 +102,9 @@ impl ErrorKind {
Tls => (Serious, Retry::Never, Fix::TryAgain),
Disk => (Serious, later(30, 600), Fix::ChangeFolder),
List => (Serious, later(30, 600), Fix::TryAgain),
Drm => (Blocked, Retry::Never, Fix::EditLink),
Tool => (Blocked, Retry::Never, Fix::TryAgain),
Media => (Serious, Retry::Never, Fix::TryAgain),
Crashed => (Serious, Retry::Never, Fix::TryAgain),
}
}

View file

@ -5,6 +5,7 @@ mod fetch;
mod monitor;
pub(crate) mod name;
mod parts;
mod piece;
mod probe;
pub use download::{Options, Shared, download};
@ -13,6 +14,7 @@ pub(crate) use fetch::same_body;
pub use fetch::{Link, OVERLAP, compare, fetch, same_bytes};
pub use monitor::{Monitor, PartEvent, PartId, PartState, PartView, Snapshot};
pub use name::safe as safe_name;
pub(crate) use piece::piece;
pub use probe::{Probe, probe};
use crate::model::ErrorKind;
@ -20,7 +22,7 @@ use crate::sftp::HostKeys;
use crate::site::{Access, same_site};
use crate::tls::Trust;
use crate::transport::{Remote, Way};
use crate::{disk, redact, store};
use crate::{disk, redact, store, stream};
use reqwest::header::{self, HeaderMap, HeaderName, HeaderValue};
pub(crate) use reqwest::Response;
use reqwest::{RequestBuilder, StatusCode, redirect};
@ -209,7 +211,7 @@ impl Source {
pub fn new(url: &str) -> Result<Source> {
let url = Url::parse(url).map_err(|_| Error::Link)?;
let remote = Remote::of(&url).map(Arc::new);
if !(remote.is_some() || matches!(url.scheme(), "http" | "https")) || url.host_str().is_none_or(str::is_empty) {
if !(remote.is_some() || matches!(url.scheme(), "http" | "https") || stream::recorded(&url)) || url.host_str().is_none_or(str::is_empty) {
return Err(Error::Link);
}
Ok(Source { url, headers: HeaderMap::new(), access: None, remote })
@ -270,6 +272,9 @@ impl Source {
if let Some(remote) = &self.remote {
return remote.respond(client, self, range).await;
}
if stream::recorded(&self.url) {
return Err(Error::Link);
}
let mut here = self.clone();
for _ in 0..=HOPS {
let request = |client: &Client, headers: &HeaderMap| -> RequestBuilder {

View file

@ -66,6 +66,7 @@ pub struct Monitor {
events: broadcast::Sender<PartEvent>,
state: Mutex<(Snapshot, Vec<Arc<LivePart>>)>,
flow: Arc<Flow>,
finish: watch::Sender<bool>,
}
impl Monitor {
@ -75,7 +76,7 @@ impl Monitor {
}
pub fn with_flow(cap: u32, flow: Flow) -> Monitor {
Monitor { cap: watch::Sender::new(cap), events: broadcast::Sender::new(1024), state: Mutex::default(), flow: Arc::new(flow) }
Monitor { cap: watch::Sender::new(cap), events: broadcast::Sender::new(1024), state: Mutex::default(), flow: Arc::new(flow), finish: watch::Sender::new(false) }
}
/// The limits that count for it.
@ -88,6 +89,15 @@ impl Monitor {
self.cap.send_replace(cap);
}
/// What has no end of its own ends here, and is made a whole file of.
pub fn finish(&self) {
self.finish.send_replace(true);
}
pub(crate) fn finishing(&self) -> watch::Receiver<bool> {
self.finish.subscribe()
}
pub fn subscribe(&self) -> broadcast::Receiver<PartEvent> {
self.events.subscribe()
}
@ -103,12 +113,12 @@ impl Monitor {
shot
}
pub(super) fn cap(&self) -> watch::Receiver<u32> {
pub(crate) fn cap(&self) -> watch::Receiver<u32> {
self.cap.subscribe()
}
/// The snapshot first: whoever sees the events finds them in it.
pub(super) fn publish(&self, shot: Snapshot, parts: Vec<Arc<LivePart>>, events: impl Iterator<Item = PartEvent>) {
pub(crate) fn publish(&self, shot: Snapshot, parts: Vec<Arc<LivePart>>, events: impl Iterator<Item = PartEvent>) {
*self.state.lock().unwrap() = (shot, parts);
for e in events {
// Nobody has to listen.

View file

@ -0,0 +1,74 @@
//! Something small, whole and in memory: lists, keys and pieces of streams.
use super::*;
use crate::limit::Flow;
use std::sync::atomic::{AtomicU64, Ordering};
#[derive(Debug)]
pub(crate) struct Piece {
/// Where the redirects ended.
pub url: Url,
pub mime: Option<String>,
pub body: Vec<u8>,
}
/// Fails when it is larger than `most`. `range` is the first byte and the one after the last. Adds to `received` what comes.
pub(crate) async fn piece(
client: &Client,
source: &Source,
range: Option<(u64, u64)>,
most: u64,
flow: &Flow,
received: &AtomicU64,
stop: &mut Stop,
) -> Result<Piece> {
let asked = range.map(|(first, end)| format!("bytes={first}-{}", end - 1));
let mut response = source.get(client, asked, None, stop).await?;
let headers = response.headers();
let expected = match (range, response.status()) {
(None, StatusCode::OK) => content_length(headers),
(Some((first, end)), StatusCode::PARTIAL_CONTENT) => {
let got = ContentRange::of(headers).filter(|r| r.first == first && r.last < end);
let got = got.ok_or_else(|| Error::BadReply("another range than asked for".into()))?;
if got.last + 1 < end && got.total.is_none_or(|total| got.last + 1 < total) {
return Err(Error::BadReply("less than asked for".into()));
}
Some(got.len())
}
(Some(_), StatusCode::OK) => return Err(Error::RangeIgnored),
_ => return Err(status_error(&response)),
};
let url = response.url().clone();
check_encoding(headers, &url)?;
let too_large = || Error::BadReply(format!("larger than {most}"));
if expected.is_some_and(|n| n > most) {
return Err(too_large());
}
let mime = name::mime(headers);
let mut body = Vec::with_capacity(expected.unwrap_or(0) as usize);
let work = async {
let cut = |e: reqwest::Error, got| if e.is_timeout() { e.into() } else { Error::Cut { got, expected } };
while let Some(chunk) = client.wait(async { response.chunk().await.map_err(|e| cut(e, body.len() as u64)) }).await? {
let mut rest = &chunk[..];
while !rest.is_empty() {
let (now, later) = rest.split_at(flow.take(rest.len() as u64).await as usize);
body.extend_from_slice(now);
received.fetch_add(now.len() as u64, Ordering::Relaxed);
rest = later;
}
if body.len() as u64 > most {
return Err(too_large());
}
}
Ok(())
};
tokio::select! {
biased;
_ = stopped(stop) => return Err(Error::Stopped),
done = work => done?,
}
match expected {
Some(n) if n != body.len() as u64 => Err(Error::Cut { got: body.len() as u64, expected }),
_ => Ok(Piece { url, mime, body }),
}
}

View file

@ -30,6 +30,7 @@ pub mod site;
pub mod snapshot;
pub mod speed;
pub mod store;
pub mod stream;
pub mod strings;
pub mod tls;
mod transport;

View file

@ -20,6 +20,7 @@ use crate::settings::Limits;
use crate::snapshot::{Counters, Line, Log, Snapshot, TaskView, Totals};
use crate::speed::{History, Meter};
use crate::store::{self, Store};
use crate::stream::{self, Tools};
use crate::{adopt, disk, host, redact, site, strings, tr};
use arc_swap::ArcSwap;
use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque};
@ -108,6 +109,8 @@ struct Entry {
connections: u32,
wanted: u32,
resumable: Option<bool>,
/// Its next run ends a stream at once.
finish: bool,
meter: Meter,
history: Arc<History>,
/// Bytes of the second that isn't over.
@ -135,6 +138,7 @@ impl Entry {
connections: 0,
wanted: 0,
resumable: None,
finish: false,
meter: Meter::default(),
history: Arc::default(),
second: 0,
@ -556,6 +560,7 @@ impl Actor {
}
Command::Resume(_) => result = self.resume(id),
Command::Pause(_) => result = self.hold(id),
Command::Finish(_) => result = self.finish(id),
Command::Stop(_) => {
result = self.hold(id).and_then(|()| {
if matches!(state, Done | Gone) {
@ -874,6 +879,25 @@ impl Actor {
}
}
/// Ends a stream: now, or in a run of its own when it doesn't run.
fn finish(&mut self, id: TaskId) -> Result<()> {
let e = &self.entries[&id];
if stream::kind_of(&e.task).is_none() || matches!(e.task.state, State::Checking | State::Finishing | State::Done | State::Gone) {
return Ok(());
}
match &e.work {
Some(Work::Run(run)) if e.task.state == State::Running => run.monitor.finish(),
_ => {
self.entry(id).finish = true;
self.resume(id)?;
self.forces += 1;
self.entry(id).forced = self.forces;
self.choose = true;
}
}
Ok(())
}
/// Takes a running one's place away.
fn suspend(&mut self, id: TaskId) {
if self.entries[&id].task.state == State::Running {
@ -959,11 +983,18 @@ impl Actor {
flow.set(task.speed_limit);
let monitor = Arc::new(Monitor::with_flow(unlimited(self.config.limits.parts_per_download), flow));
let run = Run { stop, monitor: monitor.clone(), since: Instant::now(), received: 0, known: false, had: self.entries[&id].downloaded };
if std::mem::take(&mut self.entry(id).finish) {
monitor.finish();
}
let (shared, options, to) = (self.config.shared.clone(), self.config.options.clone(), self.to.clone());
let sites = self.config.sites.clone();
self.runtime().spawn(async move {
let work = tokio::spawn(async move {
let source = site::source(sites.as_ref(), &task, &stopped).await?;
if stream::kind_of(&task).is_some() {
let request = stream::Request { id, source, choice: Default::default(), tools: &Tools::find(), options: &options };
return stream::download(&shared, request, &monitor, stopped).await;
}
download(&shared, id, source, &options, &monitor, stopped).await
});
let result = match work.await {

View file

@ -98,6 +98,8 @@ pub enum Command {
Pause(TaskId),
/// Back in line, also after a failure.
Resume(TaskId),
/// What goes on until it is stopped, like a live stream, ends here: what there is becomes the file.
Finish(TaskId),
/// Pauses it and puts it last.
Stop(TaskId),
/// Can be undone for `Config::undo`, and until the program ends.
@ -131,7 +133,7 @@ impl Command {
use Command::*;
match self {
Add(_) | Adopt { .. } => None,
Start(id) | Pause(id) | Resume(id) | Stop(id) | Restore(id) | Redownload(id) | KeepBoth(id) | AwaitLink(id) => Some(*id),
Start(id) | Pause(id) | Resume(id) | Stop(id) | Finish(id) | Restore(id) | Redownload(id) | KeepBoth(id) | AwaitLink(id) => Some(*id),
Remove { id, .. } | Move { id, .. } | Rename { id, .. } | Edit { id, .. } | Continue { id, .. } => Some(*id),
}
}

View file

@ -129,6 +129,12 @@ named_enum!(
Killed = "killed",
/// Waits for a link from its page.
Link = "link",
/// A program that is needed is not on this computer.
Tool = "tool",
/// Copy protection, which is never worked around.
Drm = "drm",
/// Sound and picture that can't be made a file of.
Media = "media",
Crashed = "crashed",
}
);

View file

@ -0,0 +1,479 @@
//! DASH manifests (ISO/IEC 23009-1): those that are whole, and simple ones that grow.
use super::list::*;
use super::{drm, odd};
use crate::http::Result;
use roxmltree::{Document, Node};
use url::Url;
/// More than any film has. Numbers in a manifest must not make us count for ever.
const MOST: u64 = 200_000;
/// Pieces taken of a file that has all in one.
pub(super) const CHUNK: u64 = 4 << 20;
#[derive(Debug)]
pub(super) struct Manifest {
pub found: Found,
periods: Vec<Period>,
pace: f64,
/// Seconds since 1970.
begins: Option<f64>,
depth: Option<f64>,
}
#[derive(Debug)]
struct Period {
start: f64,
length: Option<f64>,
sets: Vec<Rendition>,
}
#[derive(Debug)]
struct Rendition {
variant: Variant,
/// Not video.
sound: bool,
base: Url,
segments: Segments,
}
#[derive(Debug)]
enum Segments {
Template { init: Option<String>, media: String, number: u64, end_number: Option<u64>, scale: f64, each: Option<u64>, times: Vec<(u64, u64)>, offset: u64 },
List { init: Option<Piece>, media: Vec<Piece>, seconds: f64 },
Whole,
}
pub(super) fn parse(text: &str, base: &Url) -> Result<Manifest> {
let doc = Document::parse(text.trim_start_matches('\u{feff}')).map_err(|_| odd("manifest"))?;
let mpd = doc.root_element();
if mpd.tag_name().name() != "MPD" {
return Err(odd("no manifest"));
}
// Widevine, PlayReady, FairPlay, ClearKey: all announce themselves like this.
if doc.descendants().any(|n| n.tag_name().name() == "ContentProtection") {
return Err(drm());
}
let live = mpd.attribute("type") == Some("dynamic");
let length = mpd.attribute("mediaPresentationDuration").and_then(seconds);
let base = base_url(mpd, base)?;
let mut periods: Vec<Period> = vec![];
for p in children(mpd, "Period") {
if p.attributes().any(|a| a.name() == "href") {
return Err(odd("a period elsewhere"));
}
let own = p.attribute("start").and_then(seconds);
let start = own.or_else(|| periods.last().map_or(Some(0.0), |l| Some(l.start + l.length?))).ok_or_else(|| odd("period"))?;
if let Some(last) = periods.last_mut().filter(|l| l.length.is_none()) {
last.length = Some(start - last.start);
}
let mut period = Period { start, length: p.attribute("duration").and_then(seconds), sets: vec![] };
let base = base_url(p, &base)?;
for set in children(p, "AdaptationSet") {
let base = base_url(set, &base)?;
for r in children(set, "Representation") {
period.sets.extend(rendition(p, set, r, &base)?);
}
}
periods.push(period);
}
if let Some(last) = periods.last_mut().filter(|l| l.length.is_none() && !live) {
last.length = length.map(|n| n - last.start);
}
let first = periods.iter().find(|p| !p.sets.is_empty()).ok_or_else(|| odd("no streams"))?;
let mut found = Found { kind: Kind::Dash, live, duration: length.filter(|_| !live), videos: vec![], audios: vec![] };
for r in &first.sets {
let list = if r.sound { &mut found.audios } else { &mut found.videos };
if !list.iter().any(|v| v.id == r.variant.id) {
list.push(r.variant.clone());
}
}
sort(&mut found.videos);
sort(&mut found.audios);
Ok(Manifest {
found,
periods,
pace: mpd.attribute("minimumUpdatePeriod").and_then(seconds).unwrap_or(4.0).clamp(0.5, 60.0),
begins: mpd.attribute("availabilityStartTime").and_then(date),
depth: mpd.attribute("timeShiftBufferDepth").and_then(seconds),
})
}
fn children<'a, 'b: 'a>(node: Node<'a, 'b>, name: &'static str) -> impl Iterator<Item = Node<'a, 'b>> {
node.children().filter(move |n| n.tag_name().name() == name)
}
fn child<'a, 'b: 'a>(node: Node<'a, 'b>, name: &'static str) -> Option<Node<'a, 'b>> {
children(node, name).next()
}
/// The first of several: the others are the same on other servers.
fn base_url(node: Node, base: &Url) -> Result<Url> {
match child(node, "BaseURL").and_then(|b| b.text()) {
Some(text) => web(base, text).ok_or_else(|| odd("base")),
None => Ok(base.clone()),
}
}
/// None for what is neither picture nor sound.
fn rendition(period: Node, set: Node, r: Node, base: &Url) -> Result<Option<Rendition>> {
let either = |name| r.attribute(name).or(set.attribute(name));
let mime = either("mimeType").or(set.attribute("contentType")).unwrap_or_default();
let sound = match mime.split('/').next() {
Some("video") => false,
Some("audio") => true,
_ => return Ok(None),
};
// Pictures for the seek bar.
if children(set, "EssentialProperty").chain(children(r, "EssentialProperty")).any(|p| p.attribute("schemeIdUri").is_some_and(|s| s.contains("trick"))) {
return Ok(None);
}
let number = |name| either(name).and_then(|n| n.parse::<u32>().ok());
let id = r.attribute("id").unwrap_or_default().to_string();
let bandwidth = r.attribute("bandwidth").and_then(|b| b.parse().ok()).unwrap_or(0);
let main = children(set, "Role").any(|role| role.attribute("value") == Some("main"));
let variant = Variant {
bandwidth,
size: number("width").zip(number("height")),
codecs: either("codecs").unwrap_or_default().to_string(),
language: set.attribute("lang").map(String::from),
preferred: sound && main,
..Variant::new(id)
};
let base = base_url(r, base)?;
let levels = [r, set, period];
let template: Vec<Node> = levels.iter().filter_map(|n| child(*n, "SegmentTemplate")).collect();
let list: Vec<Node> = levels.iter().filter_map(|n| child(*n, "SegmentList")).collect();
fn attr<'a>(nodes: &[Node<'a, 'a>], name: &str) -> Option<&'a str> {
nodes.iter().find_map(|n| n.attribute(name))
}
let segments = if !template.is_empty() {
let int = |name, or| attr(&template, name).map_or(Some(or), |n| n.parse().ok()).ok_or_else(|| odd("template"));
let times = template.iter().find_map(|n| child(*n, "SegmentTimeline")).map(|t| timeline(t, period)).transpose()?;
let each = attr(&template, "duration").and_then(|d| d.parse().ok()).filter(|d| *d > 0);
if each.is_none() && times.is_none() {
return Err(odd("template"));
}
let scale: u64 = int("timescale", 1)?;
Segments::Template {
init: attr(&template, "initialization").map(|t| fill(t, &variant, 0, 0)).transpose()?,
media: attr(&template, "media").ok_or_else(|| odd("template"))?.to_string(),
number: int("startNumber", 1)?,
end_number: attr(&template, "endNumber").and_then(|n| n.parse().ok()),
scale: scale.max(1) as f64,
each: each.filter(|_| times.is_none()),
times: times.unwrap_or_default(),
offset: int("presentationTimeOffset", 0)?,
}
} else if !list.is_empty() {
let piece = |link: Option<&str>, range: Option<&str>| -> Result<Piece> {
let url = link.map_or(Some(base.clone()), |l| web(&base, l)).ok_or_else(|| odd("link"))?;
Ok(Piece { url, range: range.map(|r| byte_range(r).ok_or_else(|| odd("range"))).transpose()? })
};
let init = list.iter().find_map(|n| child(*n, "Initialization"));
let media = list.iter().map(|n| children(*n, "SegmentURL").collect::<Vec<_>>()).find(|m| !m.is_empty()).unwrap_or_default();
let scale = attr(&list, "timescale").and_then(|n| n.parse().ok()).filter(|n: &f64| *n > 0.0).unwrap_or(1.0);
Segments::List {
init: init.map(|i| piece(i.attribute("sourceURL"), i.attribute("range"))).transpose()?,
media: media.iter().map(|m| piece(m.attribute("media"), m.attribute("mediaRange"))).collect::<Result<_>>()?,
seconds: attr(&list, "duration").and_then(|n| n.parse::<f64>().ok()).unwrap_or(0.0) / scale,
}
} else {
Segments::Whole
};
Ok(Some(Rendition { variant, sound, base, segments }))
}
/// Start and length of each.
fn timeline(node: Node, period: Node) -> Result<Vec<(u64, u64)>> {
let mut times: Vec<(u64, u64)> = vec![];
let entries: Vec<Node> = children(node, "S").collect();
let mut t = 0u64;
for (i, s) in entries.iter().enumerate() {
let int = |name| s.attribute(name).and_then(|n| n.parse::<u64>().ok());
let d = int("d").filter(|d| *d > 0).ok_or_else(|| odd("timeline"))?;
t = int("t").unwrap_or(t);
let more = match s.attribute("r").map(|r| r.parse::<i64>()) {
None => 0,
Some(Ok(r)) if r >= 0 => r as u64,
// Up to the next one, or the end of the period.
Some(Ok(_)) => {
let next = entries.get(i + 1).and_then(|n| n.attribute("t")).and_then(|n| n.parse::<u64>().ok());
let scale = node.parent_element().and_then(|p| p.attribute("timescale")).and_then(|n| n.parse::<f64>().ok()).unwrap_or(1.0);
let of_period = || Some((period.attribute("duration").and_then(seconds)? * scale) as u64 + entries[0].attribute("t").and_then(|t| t.parse().ok()).unwrap_or(0));
let end = next.or_else(of_period).ok_or_else(|| odd("timeline"))?;
end.saturating_sub(t).div_ceil(d).saturating_sub(1)
}
Some(Err(_)) => return Err(odd("timeline")),
};
if more >= MOST || times.len() as u64 + more >= MOST {
return Err(odd("timeline"));
}
for _ in 0..=more {
times.push((t, d));
t = t.checked_add(d).ok_or_else(|| odd("timeline"))?;
}
}
Ok(times)
}
/// `$Number%05d$` and the like.
fn fill(template: &str, v: &Variant, number: u64, time: u64) -> Result<String> {
let mut out = String::new();
let mut rest = template;
while let Some((before, after)) = rest.split_once('$') {
out += before;
let (name, after) = after.split_once('$').ok_or_else(|| odd("template"))?;
rest = after;
let (name, format) = name.split_once('%').unwrap_or((name, ""));
let width: usize = match format.strip_suffix('d') {
Some(w) => w.parse().ok().filter(|w| *w <= 32).ok_or_else(|| odd("template"))?,
None => 0,
};
match name {
"" => out.push('$'),
"RepresentationID" => out += &v.id,
"Number" => out += &format!("{number:0width$}"),
"Time" => out += &format!("{time:0width$}"),
"Bandwidth" => out += &format!("{:0width$}", v.bandwidth),
_ => return Err(odd("template")),
}
}
Ok(out + rest)
}
fn byte_range(text: &str) -> Option<(u64, u64)> {
let (first, last) = text.split_once('-')?;
let (first, last): (u64, u64) = (first.trim().parse().ok()?, last.trim().parse().ok()?);
(first <= last).then_some((first, last.checked_add(1)?))
}
/// `P1DT2H3M4.5S`
fn seconds(text: &str) -> Option<f64> {
let (days, time) = text.trim().strip_prefix('P')?.split_once('T').unwrap_or((text.trim().strip_prefix('P')?, ""));
let mut total = 0.0;
for (text, units) in [(days, &[('D', 86400.0)][..]), (time, &[('H', 3600.0), ('M', 60.0), ('S', 1.0)])] {
let mut digits = String::new();
for c in text.chars() {
if c.is_ascii_digit() || c == '.' {
digits.push(c);
} else {
let unit = units.iter().find(|(u, _)| *u == c)?.1;
total += std::mem::take(&mut digits).parse::<f64>().ok()? * unit;
}
}
}
Some(total)
}
fn date(text: &str) -> Option<f64> {
let parsed = chrono::DateTime::parse_from_rfc3339(text).or_else(|_| chrono::DateTime::parse_from_rfc3339(&format!("{text}Z"))).ok()?;
Some(parsed.timestamp_millis() as f64 / 1000.0)
}
impl Manifest {
/// `now` in seconds since 1970.
pub fn media(&self, variant: &Variant, now: f64) -> Result<Media> {
let live = self.found.live;
let sound = self.found.audios.iter().any(|a| a.id == variant.id);
let mut media = Media { ended: !live, pace: self.pace, ..Media::default() };
for period in &self.periods {
let Some(r) = period.closest(variant, sound) else { continue };
// The start tells periods apart, also when old ones are dropped from the manifest.
let stretch = (period.start * 1000.0) as u64;
if matches!(r.segments, Segments::Whole) {
if self.periods.len() > 1 || live {
return Err(odd("several files"));
}
media.whole = Some(r.base.clone());
return Ok(media);
}
media.segments.extend(r.expand(period, stretch, live.then(|| self.window(period, now)).flatten())?);
}
if media.segments.len() as u64 > MOST {
return Err(odd("too many"));
}
if !live {
// The place in the list is what stays.
for (i, s) in media.segments.iter_mut().enumerate() {
(s.seq, s.next) = (i as u64, i as u64 + 1);
}
}
Ok(media)
}
/// What of a growing period is there: from and to, in seconds since its start.
fn window(&self, period: &Period, now: f64) -> Option<(f64, f64)> {
let to = now - self.begins? - period.start;
let to = period.length.map_or(to, |n| to.min(n));
Some((self.depth.map_or(0.0, |d| (to - d).max(0.0)), to))
}
}
impl Period {
/// The same one, or what comes next to it.
fn closest(&self, variant: &Variant, sound: bool) -> Option<&Rendition> {
let same = self.sets.iter().find(|r| r.variant.id == variant.id && r.sound == sound);
let mut fit: Vec<&Rendition> = self.sets.iter().filter(|r| r.sound == sound).collect();
fit.sort_by_key(|r| (r.variant.language != variant.language, r.variant.bandwidth.abs_diff(variant.bandwidth)));
same.or(fit.first().copied())
}
}
impl Rendition {
fn expand(&self, period: &Period, stretch: u64, window: Option<(f64, f64)>) -> Result<Vec<Segment>> {
let segment = |seq, next, seconds, piece, init: &Option<Piece>| Segment { stretch, seq, next, seconds, piece, key: None, init: init.clone(), init_key: None };
match &self.segments {
Segments::Whole => Ok(vec![]),
Segments::List { init, media, seconds } => {
let numbered = media.iter().enumerate().map(|(i, p)| (i as u64, p));
Ok(numbered.map(|(i, p)| segment(i, i + 1, *seconds, p.clone(), init)).collect())
}
Segments::Template { init, media, number, end_number, scale, each, times, offset } => {
let at = |number, time| -> Result<Piece> {
let url = web(&self.base, &fill(media, &self.variant, number, time)?).ok_or_else(|| odd("link"))?;
Ok(Piece { url, range: None })
};
let init = match init {
Some(link) => Some(Piece { url: web(&self.base, link).ok_or_else(|| odd("link"))?, range: None }),
None => None,
};
let Some(each) = each else {
let numbered = times.iter().zip(*number..);
return numbered.map(|(&(t, d), n)| Ok(segment(t, t + d, d as f64 / scale, at(n, t)?, &init))).collect();
};
let long = *each as f64 / scale;
let (from, to) = match window {
// Only those that are whole.
Some((from, to)) => ((from / long).ceil().max(0.0) as u64, (to / long).floor().max(0.0) as u64),
None => (0, (period.length.ok_or_else(|| odd("period"))? / long - 1e-6).ceil().max(0.0) as u64),
};
let to = end_number.map_or(to, |e| to.min((e + 1).saturating_sub(*number)));
if to.saturating_sub(from) > MOST {
return Err(odd("too many"));
}
(from..to).map(|i| Ok(segment(i, i + 1, long, at(number + i, offset + i * each)?, &init))).collect()
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::http::Error;
use crate::model::ErrorKind;
fn base() -> Url {
Url::parse("https://h/a/m.mpd").unwrap()
}
fn manifest(text: &str) -> Manifest {
parse(text, &base()).unwrap()
}
fn paths(m: &Media) -> Vec<&str> {
m.segments.iter().map(|s| s.piece.url.path()).collect()
}
const NUMBERED: &str = r#"<MPD xmlns="urn:mpeg:dash:schema:mpd:2011" type="static" mediaPresentationDuration="PT9.5S"><Period>
<AdaptationSet contentType="video" mimeType="video/mp4"><SegmentTemplate timescale="1000" duration="4000" initialization="$RepresentationID$/i.mp4" media="$RepresentationID$/$Number%03d$.m4s"/>
<Representation id="low" bandwidth="100" width="640" height="360"/><Representation id="high" bandwidth="900" width="1920" height="1080"/></AdaptationSet>
<AdaptationSet mimeType="audio/mp4" lang="de"><Representation id="s" bandwidth="64"><BaseURL>sound/</BaseURL>
<SegmentTemplate timescale="10" media="$Time$$$.m4s"><SegmentTimeline><S t="5" d="40" r="1"/><S d="15"/></SegmentTimeline></SegmentTemplate></Representation></AdaptationSet>
<AdaptationSet mimeType="application/ttml+xml"><Representation id="t"/></AdaptationSet></Period></MPD>"#;
#[test]
fn templates() {
let m = manifest(NUMBERED);
assert_eq!(m.found.duration, Some(9.5));
let picked = m.found.pick(&Choice::default()).unwrap();
assert_eq!(picked.iter().map(|v| v.id.as_str()).collect::<Vec<_>>(), ["high", "s"]);
let video = m.media(&picked[0], 0.0).unwrap();
assert!(video.ended);
assert_eq!(paths(&video), ["/a/high/001.m4s", "/a/high/002.m4s", "/a/high/003.m4s"]);
assert_eq!(video.segments[0].init.as_ref().unwrap().url.path(), "/a/high/i.mp4");
let sound = m.media(&picked[1], 0.0).unwrap();
assert_eq!(paths(&sound), ["/a/sound/5$.m4s", "/a/sound/45$.m4s", "/a/sound/85$.m4s"]);
assert_eq!(sound.segments[2].seconds, 1.5);
let small = Choice { max_height: Some(480), audio: Pick::None, ..Choice::default() };
assert_eq!(m.found.pick(&small).unwrap()[0].id, "low");
}
#[test]
fn lists_and_single_files() {
let m = manifest(
r#"<MPD mediaPresentationDuration="PT4S"><Period><AdaptationSet mimeType="video/mp4"><Representation id="v" bandwidth="1"><BaseURL>v.mp4</BaseURL>
<SegmentList duration="2"><Initialization range="0-9"/><SegmentURL mediaRange="10-19"/><SegmentURL media="x.mp4"/></SegmentList></Representation></AdaptationSet>
<AdaptationSet mimeType="audio/mp4"><Representation id="a"><BaseURL>a.mp4</BaseURL><SegmentBase indexRange="0-5"/></Representation></AdaptationSet></Period></MPD>"#,
);
let v = m.media(&m.found.videos[0], 0.0).unwrap();
assert_eq!(v.segments[0].piece.range, Some((10, 20)));
assert_eq!(paths(&v), ["/a/v.mp4", "/a/x.mp4"]);
assert_eq!(v.segments[0].init.as_ref().unwrap().range, Some((0, 10)));
assert_eq!(m.media(&m.found.audios[0], 0.0).unwrap().whole.unwrap().path(), "/a/a.mp4");
}
#[test]
fn periods_follow_each_other() {
let set = |id: &str| format!(r#"<AdaptationSet mimeType="video/mp4"><Representation id="{id}" bandwidth="1"><SegmentTemplate duration="2" media="{id}$Number$"/></Representation></AdaptationSet>"#);
let m = manifest(&format!(
r#"<MPD mediaPresentationDuration="PT10S"><Period duration="PT4S">{}</Period><Period>{}</Period></MPD>"#,
set("a"),
set("b")
));
let v = m.media(&m.found.videos[0], 0.0).unwrap();
assert_eq!(paths(&v), ["/a/a1", "/a/a2", "/a/b1", "/a/b2", "/a/b3"]);
assert_eq!(v.segments.iter().map(|s| (s.stretch, s.seq)).collect::<Vec<_>>(), [(0, 0), (0, 1), (4000, 2), (4000, 3), (4000, 4)]);
}
#[test]
fn growing_ones() {
let m = manifest(
r#"<MPD type="dynamic" availabilityStartTime="1970-01-01T00:01:40Z" minimumUpdatePeriod="PT2S" timeShiftBufferDepth="PT6S"><Period start="PT0S">
<AdaptationSet mimeType="video/mp4"><Representation id="v" bandwidth="1"><SegmentTemplate duration="2" startNumber="0" media="$Number$"/></Representation></AdaptationSet></Period></MPD>"#,
);
assert!(m.found.live);
let v = m.media(&m.found.videos[0], 121.0).unwrap();
assert!(!v.ended);
assert_eq!(paths(&v), ["/a/8", "/a/9"], "those of the last 6 seconds that are whole");
}
#[test]
fn protected_ones_are_refused() {
for uuid in ["edef8ba9-79d6-4ace-a3c8-27dcd51d21ed", "9a04f079-9840-4286-ab92-e65be0885f95", "94ce86fb-07ff-4f43-adb8-93d2fa968ca2"] {
let text = NUMBERED.replace("<SegmentTimeline>", &format!(r#"<SegmentTimeline><ContentProtection schemeIdUri="urn:uuid:{uuid}"/>"#));
assert!(matches!(parse(&text, &base()), Err(Error::Conn { kind: ErrorKind::Drm, .. })));
}
}
#[test]
fn nonsense_is_no_manifest() {
let with = |inner: &str| format!(r#"<MPD mediaPresentationDuration="PT4S"><Period><AdaptationSet mimeType="video/mp4"><Representation id="v">{inner}</Representation></AdaptationSet></Period></MPD>"#);
let media = |text: &str| parse(text, &base()).and_then(|m| m.media(&m.found.videos[0].clone(), 0.0));
for text in [
"",
"<html/>",
"<MPD/>",
r#"<!DOCTYPE x [<!ENTITY a "b">]><MPD>&a;</MPD>"#,
&with(r#"<SegmentTemplate media="a"/>"#),
&with(r#"<SegmentTemplate duration="1" media="file:///etc/passwd"/>"#),
&with(r#"<SegmentTemplate duration="1" media="$Number%999999999d$"/>"#),
&with(r#"<SegmentTemplate duration="1" timescale="99999999999" media="$Number$"/>"#),
&with(r#"<SegmentTemplate media="a"><SegmentTimeline><S d="1" r="99999999999"/></SegmentTimeline></SegmentTemplate>"#),
&with(r#"<SegmentTemplate media="a"><SegmentTimeline><S d="0"/></SegmentTimeline></SegmentTemplate>"#),
&with(r#"<BaseURL>file:///etc/</BaseURL>"#),
] {
assert!(matches!(media(text), Err(Error::BadReply(_))), "{text}");
}
}
#[test]
fn times() {
assert_eq!(seconds("P1DT2H3M4.5S"), Some(86400.0 + 7200.0 + 180.0 + 4.5));
assert_eq!(seconds("PT0S"), Some(0.0));
assert_eq!(seconds("5"), None);
assert_eq!(date("1970-01-01T00:00:01"), Some(1.0));
assert_eq!(date("1970-01-01T01:00:01.5+01:00"), Some(1.5));
}
}

View file

@ -0,0 +1,388 @@
//! Lists and pieces from the server, and which pieces are still wanted.
use super::list::*;
use super::tape::{Record, Tape};
use super::{PARALLEL, dash, drm, hls, odd};
use crate::host::{self, Hosts, Member, Permit};
use crate::http::{self, Client, Error, Monitor, Options, Result, Shared, Source, Stop, stopped};
use crate::limit::{Flow, Group};
use crate::model::HostProfile;
use crate::store::Store;
use aes::cipher::block_padding::Pkcs7;
use aes::cipher::{BlockModeDecrypt, KeyIvInit};
use std::collections::{HashMap, HashSet, VecDeque};
use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use url::Url;
const MOST_LIST: u64 = 32 << 20;
/// Held in memory.
const MOST_PIECE: u64 = 256 << 20;
/// What a growing list is joined at, from its end.
const FROM_END: usize = 3;
pub(super) fn now() -> f64 {
crate::model::now() as f64 / 1000.0
}
/// Worth another try.
pub(super) fn passing(e: &Error) -> bool {
match e {
Error::Net(_) | Error::Idle | Error::Cut { .. } => true,
Error::Status { code, .. } => matches!(code, 408 | 425 | 429 | 500..=599),
_ => false,
}
}
pub(super) struct Opened {
pub found: Found,
pub manifest: Option<dash::Manifest>,
/// The link itself was the list of one variant.
pub media: Option<Media>,
}
/// One download's way to its servers.
pub(super) struct Net {
client: Client,
pub source: Source,
options: Options,
flow: Arc<Flow>,
received: Arc<AtomicU64>,
places: Option<Places>,
width: AtomicU32,
/// Held while one is asked for: the others wait for it.
keys: tokio::sync::Mutex<HashMap<Url, [u8; 16]>>,
}
/// Connections are shared with the other downloads.
struct Places {
hosts: Arc<Hosts>,
store: Arc<Store>,
members: Mutex<HashMap<String, Arc<Member>>>,
/// Connections between two pieces.
idle: Mutex<Vec<(String, Permit)>>,
}
impl Net {
pub fn new(shared: &Shared, source: &Source, options: &Options, monitor: &Monitor, received: Arc<AtomicU64>) -> Net {
let places = Places { hosts: shared.hosts.clone(), store: shared.store.clone(), members: Mutex::default(), idle: Mutex::default() };
Net {
client: shared.client.clone(),
source: source.clone(),
options: options.clone(),
flow: monitor.flow().clone(),
received,
places: Some(places),
width: AtomicU32::new(PARALLEL),
keys: tokio::sync::Mutex::default(),
}
}
/// For a look at what there is.
pub fn plain(client: &Client, source: &Source) -> Net {
Net {
client: client.clone(),
source: source.clone(),
options: Options { tries: 1, ..Options::default() },
flow: Arc::new(Flow::free()),
received: Arc::default(),
places: None,
width: AtomicU32::new(1),
keys: tokio::sync::Mutex::default(),
}
}
/// As many pieces at once as the server stands.
pub fn width(&self) -> u32 {
self.width.load(Ordering::Relaxed)
}
async fn text(&self, url: &Url, stop: &mut Stop) -> Result<(Url, String)> {
let at = if *url == self.source.url { self.source.clone() } else { self.source.at(url) };
let got = http::piece(&self.client, &at, None, MOST_LIST, &self.flow, &AtomicU64::new(0), stop).await?;
if got.mime.as_deref() == Some("text/html") {
return Err(Error::Page);
}
Ok((got.url, String::from_utf8_lossy(&got.body).into_owned()))
}
pub async fn open(&self, stop: &mut Stop) -> Result<Opened> {
let (base, text) = self.text(&self.source.url, stop).await?;
if text.trim_start_matches('\u{feff}').trim_start().starts_with('<') {
let manifest = dash::parse(&text, &base)?;
return Ok(Opened { found: manifest.found.clone(), manifest: Some(manifest), media: None });
}
Ok(match hls::parse(&text, &base)? {
hls::List::Master(found) => Opened { found, manifest: None, media: None },
hls::List::Media(media) => {
let only = Variant { url: Some(self.source.url.clone()), ..Variant::new(String::new()) };
let found = Found { kind: Kind::Hls, live: !media.ended, duration: None, videos: vec![only], audios: vec![] };
Opened { found, manifest: None, media: Some(media) }
}
})
}
/// The lists of the variants, as they are now. `root` is the kind of the first link, unless it is a list of lists.
pub async fn refresh(&self, root: &Option<Kind>, variants: &[Variant], stop: &mut Stop) -> Result<Vec<Media>> {
if *root == Some(Kind::Dash) {
let (base, text) = self.text(&self.source.url, stop).await?;
let manifest = dash::parse(&text, &base)?;
return variants.iter().map(|v| manifest.media(v, now())).collect();
}
let mut media = vec![];
for v in variants {
let (base, text) = self.text(v.url.as_ref().ok_or_else(|| odd("link"))?, stop).await?;
match hls::parse(&text, &base)? {
hls::List::Media(m) => media.push(m),
hls::List::Master(_) => return Err(odd("a list of lists in a list")),
}
}
Ok(media)
}
/// A single file is taken in pieces too.
pub async fn split(&self, media: &mut Media, stop: &mut Stop) -> Result<()> {
let Some(url) = media.whole.take() else { return Ok(()) };
let probe = http::probe(&self.client, &self.source.at(&url), stop).await?;
let size = probe.version.size.filter(|n| probe.ranges && *n > 0);
let ranges: Vec<Option<(u64, u64)>> = match size {
Some(size) => (0..size.div_ceil(dash::CHUNK)).map(|i| Some((i * dash::CHUNK, ((i + 1) * dash::CHUNK).min(size)))).collect(),
None => vec![None],
};
let each = |(i, range): (usize, Option<(u64, u64)>)| Segment {
stretch: 0,
seq: i as u64,
next: i as u64 + 1,
// Not known, but the same for all.
seconds: range.map_or(1.0, |(a, b)| (b - a) as f64 / dash::CHUNK as f64),
piece: Piece { url: url.clone(), range },
key: None,
init: None,
init_key: None,
};
media.segments = ranges.into_iter().enumerate().map(each).collect();
media.ended = true;
Ok(())
}
/// Tries again where that may help.
pub async fn piece(&self, want: &Want, stop: &mut Stop) -> Result<Vec<u8>> {
let mut data = self.get(&want.piece, MOST_PIECE, stop).await?;
if let Some(key) = &want.key {
let bytes = self.key(&key.url, stop).await?;
let plain = cbc::Decryptor::<aes::Aes128>::new(&bytes.into(), &key.iv.into()).decrypt_padded::<Pkcs7>(&mut data);
let n = plain.map_err(|_| odd("the key does not fit"))?.len();
data.truncate(n);
}
if want.record.init && [b"pssh", b"encv", b"enca"].iter().any(|name| data.windows(4).any(|w| w == *name)) {
return Err(drm());
}
Ok(data)
}
async fn key(&self, url: &Url, stop: &mut Stop) -> Result<[u8; 16]> {
let mut keys = self.keys.lock().await;
if let Some(key) = keys.get(url) {
return Ok(*key);
}
let got = self.get(&Piece { url: url.clone(), range: None }, 1 << 10, stop).await?;
let key: [u8; 16] = got.try_into().map_err(|_| odd("no key"))?;
keys.insert(url.clone(), key);
Ok(key)
}
async fn get(&self, piece: &Piece, most: u64, stop: &mut Stop) -> Result<Vec<u8>> {
let mut fails = 0;
loop {
let permit = self.permit(&piece.url, stop).await?;
let got = http::piece(&self.client, &self.source.at(&piece.url), piece.range, most, &self.flow, &self.received, stop).await;
let e = match got {
Ok(got) => {
self.back(&piece.url, permit);
return Ok(got.body);
}
Err(e) => e,
};
drop(permit);
fails += 1;
if !passing(&e) || fails >= self.options.tries {
return Err(e);
}
let mut wait = self.options.backoff.saturating_mul(1 << (fails - 1).min(10)).min(self.options.max_wait);
if let Error::Status { code, retry_after } = &e {
if matches!(code, 429 | 503) {
let _ = self.width.try_update(Ordering::Relaxed, Ordering::Relaxed, |n| (n > 1).then_some(n - 1));
}
match retry_after {
Some(asked) if *asked > self.options.max_wait => return Err(e),
Some(asked) => wait = wait.max(*asked),
None => {}
}
}
tokio::select! {
_ = stopped(stop) => return Err(Error::Stopped),
_ = tokio::time::sleep(wait) => {}
}
}
}
/// A place for a connection to the host of `url`.
async fn permit(&self, url: &Url, stop: &mut Stop) -> Result<Option<Permit>> {
let Some(places) = &self.places else { return Ok(None) };
let host = host::key(url);
{
let mut idle = places.idle.lock().unwrap();
idle.retain(|(_, permit)| !permit.revoked());
if let Some(i) = idle.iter().position(|(h, _)| *h == host) {
return Ok(Some(idle.swap_remove(i).1));
}
// It goes to others meanwhile.
idle.clear();
}
let member = places.members.lock().unwrap().get(&host).cloned();
let member = match member {
Some(member) => member,
None => {
let (store, asked) = (places.store.clone(), host.clone());
let known: HostProfile = super::run(&store, move |s| Ok(s.host(&asked)?)).await?.unwrap_or_default();
let at = self.source.at(url);
places.hosts.set_host_cap(&host, at.max_connections().or(known.max_connections));
self.flow.put_limited(Group::Host(host.clone()), at.speed_limit().or(known.speed_limit));
places.members.lock().unwrap().entry(host.clone()).or_insert_with(|| Arc::new(places.hosts.join(&host))).clone()
}
};
loop {
if let Some(permit) = member.open(self.width(), self.flow.weight(), Instant::now()) {
return Ok(Some(permit));
}
tokio::select! {
_ = stopped(stop) => return Err(Error::Stopped),
_ = tokio::time::sleep(Duration::from_millis(50)) => {}
}
}
}
/// The connection can bring the next one.
fn back(&self, url: &Url, permit: Option<Permit>) {
if let (Some(places), Some(permit)) = (&self.places, permit)
&& !permit.revoked()
{
places.idle.lock().unwrap().push((host::key(url), permit));
}
}
/// Nothing is wanted for a while.
pub fn rest(&self) {
if let Some(places) = &self.places {
places.idle.lock().unwrap().clear();
for member in places.members.lock().unwrap().values() {
member.wants(0, self.flow.weight());
}
}
}
}
/// A piece to download, and where it belongs.
pub(super) struct Want {
pub record: Record,
pub piece: Piece,
pub key: Option<Key>,
/// Seconds from the start, in milliseconds: tracks go on side by side.
pub place: u64,
}
/// What of one track is wanted.
pub(super) struct Feed {
track: u32,
group: u32,
/// The last one: its stretch and number, and the number that should follow.
last: Option<(u64, u64, u64)>,
/// What the group starts with. None: not known any more.
init: Option<Option<Piece>>,
have: HashSet<(bool, u32, u64)>,
/// How often the numbers of a growing list began anew.
epoch: u64,
taken: u64,
most: Option<u64>,
}
const EPOCH: u32 = 48;
impl Feed {
pub fn new(track: u32, tape: &Tape, seconds: Option<u64>) -> Feed {
let mine = || tape.records.iter().filter(|r| r.track == track);
let last = mine().filter(|r| !r.init).max_by_key(|r| (r.stretch, r.seq));
Feed {
track,
group: mine().map(|r| r.group).max().unwrap_or(0),
last: last.map(|r| (r.stretch, r.seq, r.seq + 1)),
init: None,
have: mine().map(|r| (r.init, r.group, r.seq)).collect(),
epoch: last.map_or(0, |r| r.stretch >> EPOCH),
taken: tape.length(track),
most: seconds.filter(|_| tape.head.live).map(|s| s * 1000),
}
}
pub fn full(&self) -> bool {
self.most.is_some_and(|most| self.taken >= most)
}
pub fn take(&mut self, media: &Media, live: bool, queue: &mut VecDeque<Want>) {
if !live {
return self.all(media, queue);
}
let first = self.last.is_none();
if let (Some((stretch, seq, _)), Some(end)) = (self.last, media.segments.last())
&& (end.stretch + (self.epoch << EPOCH), end.seq + media.segments.len() as u64) < (stretch, seq)
{
self.epoch += 1;
}
let skip = if first && !media.from_start && !media.ended { media.segments.len().saturating_sub(FROM_END) } else { 0 };
for s in &media.segments[skip..] {
if self.full() {
return;
}
let stretch = s.stretch + (self.epoch << EPOCH);
if self.last.is_some_and(|(st, seq, _)| (stretch, s.seq) <= (st, seq)) {
continue;
}
let follows = self.last.is_none_or(|(st, _, next)| st == stretch && next == s.seq) && self.init.as_ref().is_none_or(|i| *i == s.init);
if !follows {
self.group += 1;
}
let fresh = !follows || first && !self.have.contains(&(true, self.group, 0));
self.want(s, stretch, fresh, queue);
self.last = Some((stretch, s.seq, s.next));
self.init = Some(s.init.clone());
self.taken += (s.seconds * 1000.0) as u64;
}
}
/// The same groups each time.
fn all(&mut self, media: &Media, queue: &mut VecDeque<Want>) {
let mut before: Option<&Segment> = None;
let (mut group, mut place) = (0, 0);
for s in &media.segments {
let fresh = before.is_none_or(|b| b.stretch != s.stretch || b.init != s.init);
group += u32::from(fresh && before.is_some());
self.group = group;
let at = queue.len();
self.want(s, s.stretch, fresh && !self.have.contains(&(true, group, 0)), queue);
queue.range_mut(at..).for_each(|w| w.place = place);
place += (s.seconds * 1000.0) as u64;
before = Some(s);
}
}
fn want(&mut self, s: &Segment, stretch: u64, fresh: bool, queue: &mut VecDeque<Want>) {
let record = Record { track: self.track, group: self.group, init: false, stretch, seq: s.seq, ms: (s.seconds * 1000.0) as u32, at: 0, len: 0 };
if fresh && let Some(init) = &s.init {
queue.push_back(Want { record: Record { init: true, seq: 0, ms: 0, ..record }, piece: init.clone(), key: s.init_key.clone(), place: 0 });
}
if self.have.insert((false, self.group, s.seq)) {
queue.push_back(Want { record, piece: s.piece.clone(), key: s.key.clone(), place: 0 });
}
}
}

View file

@ -0,0 +1,306 @@
//! The ffmpeg that is on this computer: finding it, running it, stopping it.
//!
//! It gets lists of arguments, never a shell. What must not be seen among the arguments goes through its standard input.
use crate::http::{Error, Result};
use crate::model::ErrorKind;
use crate::redact;
use std::collections::VecDeque;
use std::ffi::{OsStr, OsString};
use std::fmt;
use std::io;
use std::path::{Path, PathBuf};
use std::process::Stdio;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::process::{Child, ChildStdout, Command};
use tokio::sync::watch;
use tokio::task::JoinHandle;
/// Lines of its log that are kept.
const TAIL: usize = 40;
/// Longer ones are cut.
const LINE: u64 = 4096;
/// Programs that other people make.
#[derive(Debug, Clone, Default)]
pub struct Tools {
pub ffmpeg: Option<PathBuf>,
}
impl Tools {
/// Next to Medlar first, then where programs are.
pub fn find() -> Tools {
let beside = std::env::current_exe().ok().and_then(|exe| Some(exe.parent()?.to_path_buf()));
let path = std::env::var_os("PATH").unwrap_or_default();
Tools { ffmpeg: find("ffmpeg", beside.as_deref(), &path) }
}
pub fn ffmpeg(&self) -> Result<&Path> {
self.ffmpeg.as_deref().ok_or(Error::because(ErrorKind::Tool, "error.tool.ffmpeg"))
}
}
fn find(name: &str, beside: Option<&Path>, path: &OsStr) -> Option<PathBuf> {
let runs = |p: &PathBuf| p.is_absolute() && p.is_file() && rustix::fs::access(p, rustix::fs::Access::EXEC_OK).is_ok();
beside.map(Path::to_path_buf).into_iter().chain(std::env::split_paths(path)).map(|dir| dir.join(name)).find(runs)
}
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct Progress {
/// Where in the recording or film it is.
pub time: Duration,
/// Bytes written.
pub bytes: u64,
}
/// What to run. Use `input` for links: it says which protocols may follow.
#[derive(Default)]
pub struct Job {
args: Vec<OsString>,
stdin: Option<Vec<u8>>,
output: bool,
}
/// Without what goes to its standard input.
impl fmt::Debug for Job {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", self.args)
}
}
impl Job {
pub fn new() -> Job {
let mut job = Job::default();
job.args(["-hide_banner", "-nostdin", "-nostats", "-loglevel", "warning", "-progress", "pipe:2", "-y"]);
job
}
pub fn arg(&mut self, arg: impl AsRef<OsStr>) -> &mut Job {
self.args.push(arg.as_ref().into());
self
}
pub fn args<A: AsRef<OsStr>>(&mut self, args: impl IntoIterator<Item = A>) -> &mut Job {
self.args.extend(args.into_iter().map(|a| a.as_ref().into()));
self
}
/// With the protocols it may use, also through what it finds in there.
pub fn input(&mut self, protocols: &str, input: impl AsRef<OsStr>) -> &mut Job {
self.args(["-protocol_whitelist", protocols, "-i"]).arg(input)
}
/// What it reads as `pipe:0`.
pub fn stdin(&mut self, bytes: impl Into<Vec<u8>>) -> &mut Job {
self.stdin = Some(bytes.into());
self
}
/// The file it makes. `muxer` is ffmpeg's name of the format.
pub fn file(&mut self, muxer: &str, path: &Path) -> &mut Job {
let mut url = OsString::from("file:");
url.push(path);
self.args(["-f", muxer]).arg(url)
}
/// What it makes is read from `Running::output`.
pub fn pipe(&mut self, muxer: &str) -> &mut Job {
self.output = true;
self.args(["-f", muxer, "pipe:1"])
}
#[cfg(test)]
pub(super) fn script(&self) -> Option<&[u8]> {
self.stdin.as_deref()
}
pub fn start(self, ffmpeg: &Path) -> Result<Running> {
let mut command = Command::new(ffmpeg);
command.args(&self.args).env("AV_LOG_FORCE_NOCOLOR", "1").process_group(0).kill_on_drop(true);
// The user's proxy is never passed on by accident.
for name in ["http_proxy", "https_proxy", "HTTPS_PROXY", "all_proxy", "ALL_PROXY"] {
command.env_remove(name);
}
command.stdin(if self.stdin.is_some() { Stdio::piped() } else { Stdio::null() });
command.stdout(if self.output { Stdio::piped() } else { Stdio::null() }).stderr(Stdio::piped());
let mut child = command.spawn().map_err(|e| {
log::warn!("{} does not start: {e}", ffmpeg.display());
Error::because(ErrorKind::Tool, "error.tool.ffmpeg")
})?;
if let (Some(mut stdin), Some(bytes)) = (child.stdin.take(), self.stdin) {
// It may end without reading all of it.
tokio::spawn(async move { drop(stdin.write_all(&bytes).await) });
}
let (progress, seen) = watch::channel(Progress::default());
let tail = Arc::new(Mutex::new(VecDeque::new()));
let stderr = child.stderr.take().expect("it is piped");
let reader = tokio::spawn(listen(stderr, progress, tail.clone()));
Ok(Running { output: child.stdout.take(), child, seen, tail, reader })
}
}
/// Reads to the end, so that it never waits for us.
async fn listen(stderr: impl tokio::io::AsyncRead + Unpin, progress: watch::Sender<Progress>, tail: Arc<Mutex<VecDeque<String>>>) {
let mut lines = BufReader::new(stderr);
let mut line = vec![];
let mut now = Progress::default();
loop {
line.clear();
let mut short = tokio::io::AsyncReadExt::take(&mut lines, LINE);
match short.read_until(b'\n', &mut line).await {
Ok(0) | Err(_) => return,
Ok(_) => {}
}
let text = String::from_utf8_lossy(&line);
let text = text.trim();
if text.is_empty() {
continue;
}
if now.read(text) {
if text.starts_with("progress=") {
progress.send_replace(now);
}
continue;
}
let mut tail = tail.lock().unwrap();
if tail.len() == TAIL {
tail.pop_front();
}
tail.push_back(redact::text(text));
}
}
impl Progress {
/// Whether the line is one of its reports.
fn read(&mut self, line: &str) -> bool {
let Some((key, value)) = line.split_once('=') else { return false };
let value = value.trim();
match key {
"out_time_us" => self.time = value.parse().map_or(self.time, Duration::from_micros),
"total_size" => self.bytes = value.parse().unwrap_or(self.bytes),
"frame" | "fps" | "bitrate" | "out_time_ms" | "out_time" | "dup_frames" | "drop_frames" | "speed" | "progress" => {}
_ => return key.starts_with("stream_") && key.ends_with("_q"),
}
true
}
}
/// Killed when it is dropped.
#[derive(Debug)]
pub struct Running {
pub output: Option<ChildStdout>,
child: Child,
seen: watch::Receiver<Progress>,
tail: Arc<Mutex<VecDeque<String>>>,
reader: JoinHandle<()>,
}
/// How it failed.
#[derive(Debug)]
pub struct Failed {
/// The end of its log, without secrets.
pub tail: Vec<String>,
}
impl Running {
pub fn progress(&self) -> watch::Receiver<Progress> {
self.seen.clone()
}
/// Asks it to end what it makes properly. `end` tells when it did.
pub fn finish(&self) {
let pid = self.child.id().and_then(|id| rustix::process::Pid::from_raw(id.cast_signed()));
if let Some(pid) = pid {
let _ = rustix::process::kill_process(pid, rustix::process::Signal::INT);
}
}
pub async fn kill(mut self) {
let _ = self.child.kill().await;
}
/// Waits for its end. Read all of `output` before.
pub async fn end(&mut self) -> io::Result<std::result::Result<(), Failed>> {
drop(self.output.take());
let status = self.child.wait().await?;
let _ = tokio::time::timeout(Duration::from_secs(1), &mut self.reader).await;
if status.success() {
return Ok(Ok(()));
}
let tail: Vec<String> = self.tail.lock().unwrap().iter().cloned().collect();
log::debug!("ffmpeg failed ({status}): {}", tail.join(" / "));
Ok(Err(Failed { tail }))
}
}
impl Failed {
pub fn says(&self, what: &str) -> bool {
self.tail.iter().any(|line| line.contains(what))
}
/// What its messages mean. They themselves are for the log only.
pub fn error(&self) -> Error {
use ErrorKind::*;
let known = [
("No space left", DiskFull),
("401 Unauthorized", Login),
("403 Forbidden", Forbidden),
("404 Not Found", NotFound),
("Connection refused", Refused),
("timed out", Timeout),
("Failed to resolve", Dns),
("No route to host", Unreachable),
("Network is unreachable", Unreachable),
];
let Some((_, kind)) = known.iter().find(|(text, _)| self.says(text)) else { return Error::conn(Media) };
match kind {
DiskFull => Error::Disk(io::Error::from(io::ErrorKind::StorageFull).into()),
Login => Error::conn(Login),
Forbidden => Error::because(Forbidden, "error.forbidden.plain"),
NotFound => Error::because(NotFound, "error.not_found.plain"),
kind => Error::conn(*kind),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn programs_are_found() {
let dir = tempfile::tempdir().unwrap();
let here = dir.path().join("tool");
assert_eq!(find("tool", None, dir.path().as_os_str()), None);
std::fs::write(&here, "").unwrap();
assert_eq!(find("tool", None, dir.path().as_os_str()), None, "it can't be run");
rustix::fs::chmod(&here, rustix::fs::Mode::RWXU).unwrap();
assert_eq!(find("tool", None, dir.path().as_os_str()).as_ref(), Some(&here));
assert_eq!(find("tool", Some(dir.path()), OsStr::new("")).as_ref(), Some(&here));
// Never from the current folder.
assert_eq!(find("tool", None, OsStr::new(".:")), None);
assert!(matches!(Tools::default().ffmpeg(), Err(Error::Conn { kind: ErrorKind::Tool, .. })));
}
#[test]
fn reports_are_told_from_messages() {
let mut p = Progress::default();
for line in ["frame=10", "out_time_us=2500000", "out_time=00:00:02.500000", "total_size=77", "speed=1x", "stream_0_0_q=-1.0", "out_time_us=N/A"] {
assert!(p.read(line), "{line}");
}
assert_eq!(p, Progress { time: Duration::from_millis(2500), bytes: 77 });
assert!(!p.read("Error opening a=b"));
assert!(!p.read("Invalid data found"));
}
#[test]
fn its_messages_are_understood() {
let of = |text: &str| Failed { tail: vec!["x".into(), text.into()] }.error();
assert!(matches!(of("Server returned 401 Unauthorized (authorization failed)"), Error::Conn { kind: ErrorKind::Login, .. }));
assert!(matches!(of("rtsp://h: Connection refused"), Error::Conn { kind: ErrorKind::Refused, .. }));
assert!(matches!(of("av_interleaved_write_frame(): No space left on device"), Error::Disk(_)));
assert!(matches!(of("something else"), Error::Conn { kind: ErrorKind::Media, .. }));
}
}

View file

@ -0,0 +1,304 @@
//! HLS lists (RFC 8216).
use super::list::*;
use super::{drm, odd};
use crate::http::Result;
use std::collections::HashMap;
use url::Url;
pub(super) enum List {
Master(Found),
Media(Media),
}
pub(super) fn parse(text: &str, base: &Url) -> Result<List> {
let text = text.trim_start_matches('\u{feff}');
if !text.trim_start().starts_with("#EXTM3U") {
return Err(odd("no list of streams"));
}
if text.lines().any(|l| l.starts_with("#EXT-X-STREAM-INF:")) { master(text, base).map(List::Master) } else { media(text, base).map(List::Media) }
}
fn tag<'a>(line: &'a str, name: &str) -> Option<&'a str> {
line.strip_prefix(name)?.strip_prefix(':').map(str::trim)
}
/// `A=1,B="x,y"`
fn attributes(text: &str) -> HashMap<&str, &str> {
let mut found = HashMap::new();
let mut rest = text;
while let Some((name, after)) = rest.split_once('=') {
let (value, after) = match after.strip_prefix('"').and_then(|a| a.split_once('"')) {
Some((value, after)) => (value, after.split_once(',').map_or("", |(_, a)| a)),
None => after.split_once(',').unwrap_or((after, "")),
};
found.insert(name.trim(), value.trim());
rest = after;
}
found
}
/// Keys that the list itself offers are fine, anything else is copy protection.
fn check_key(a: &HashMap<&str, &str>) -> Result<bool> {
let format = a.get("KEYFORMAT").copied().unwrap_or("identity");
match a.get("METHOD").copied() {
Some("NONE") => Ok(false),
Some("AES-128") if format == "identity" => Ok(true),
_ => Err(drm()),
}
}
fn check_protection(line: &str) -> Result<()> {
if let Some(a) = tag(line, "#EXT-X-SESSION-KEY") {
check_key(&attributes(a))?;
}
// Adobe's.
if line.starts_with("#EXT-X-FAXS-CM") { Err(drm()) } else { Ok(()) }
}
fn master(text: &str, base: &Url) -> Result<Found> {
let mut found = Found { kind: Kind::Hls, live: false, duration: None, videos: vec![], audios: vec![] };
let mut info: Option<HashMap<&str, &str>> = None;
for line in text.lines().map(str::trim) {
check_protection(line)?;
if let Some(a) = tag(line, "#EXT-X-STREAM-INF") {
info = Some(attributes(a));
} else if let Some(a) = tag(line, "#EXT-X-MEDIA") {
let a = attributes(a);
let text = |name| a.get(name).map(|v: &&str| v.to_string());
// Without a link it is in the video.
let Some(url) = a.get("URI").filter(|_| a.get("TYPE") == Some(&"AUDIO")) else { continue };
let Some(url) = web(base, url) else { continue };
let (group, name) = (text("GROUP-ID").unwrap_or_default(), text("NAME").unwrap_or_default());
let id = format!("{group}/{name}/{}", text("LANGUAGE").unwrap_or_default());
found.audios.push(Variant {
language: text("LANGUAGE"),
name: Some(name),
sound: Some(group),
preferred: a.get("DEFAULT") == Some(&"YES"),
url: Some(url),
..Variant::new(id)
});
} else if !line.is_empty() && !line.starts_with('#')
&& let Some(a) = info.take()
{
let Some(url) = web(base, line) else { continue };
let bandwidth = a.get("BANDWIDTH").and_then(|b| b.parse().ok()).unwrap_or(0);
let size = a.get("RESOLUTION").and_then(|r| r.split_once('x')).and_then(|(w, h)| Some((w.parse().ok()?, h.parse().ok()?)));
let (w, h) = size.unwrap_or_default();
found.videos.push(Variant {
bandwidth,
size,
codecs: a.get("CODECS").map(|c| c.to_string()).unwrap_or_default(),
sound: a.get("AUDIO").map(|g| g.to_string()),
url: Some(url),
..Variant::new(format!("{w}x{h}@{bandwidth}"))
});
}
}
// A video whose sound has no link of its own has it inside.
for v in &mut found.videos {
v.sound = v.sound.take().filter(|g| found.audios.iter().any(|a| a.sound.as_ref() == Some(g)));
}
sort(&mut found.videos);
// The same again on another server.
found.videos.dedup_by(|b, a| a.id == b.id && a.sound == b.sound && a.codecs == b.codecs);
if found.videos.is_empty() { Err(odd("no variants")) } else { Ok(found) }
}
fn media(text: &str, base: &Url) -> Result<Media> {
let mut media = Media { pace: 6.0, ..Media::default() };
let (mut seq, mut breaks) = (0u64, 0u64);
let (mut key, mut init, mut seconds, mut range, mut gap) = (None::<(Url, Option<[u8; 16]>)>, None, 0.0, None, false);
let mut init_key = None;
// Where the last range of each file ended.
let mut ends: HashMap<Url, u64> = HashMap::new();
for line in text.lines().map(str::trim) {
check_protection(line)?;
if let Some(n) = tag(line, "#EXT-X-TARGETDURATION") {
media.pace = n.parse::<f64>().ok().filter(|n| n.is_finite()).unwrap_or(media.pace).clamp(0.5, 60.0);
} else if let Some(n) = tag(line, "#EXT-X-MEDIA-SEQUENCE") {
seq = n.parse().map_err(|_| odd("sequence"))?;
} else if let Some(n) = tag(line, "#EXT-X-DISCONTINUITY-SEQUENCE") {
breaks = n.parse().map_err(|_| odd("sequence"))?;
} else if line == "#EXT-X-DISCONTINUITY" {
breaks += 1;
} else if line == "#EXT-X-ENDLIST" {
media.ended = true;
} else if line == "#EXT-X-GAP" {
gap = true;
} else if let Some(kind) = tag(line, "#EXT-X-PLAYLIST-TYPE") {
media.from_start = kind == "EVENT";
} else if let Some(a) = tag(line, "#EXT-X-KEY") {
let a = attributes(a);
key = if check_key(&a)? {
let url = a.get("URI").and_then(|u| web(base, u)).ok_or_else(|| odd("key"))?;
Some((url, a.get("IV").map(|iv| parse_iv(iv).ok_or_else(|| odd("iv"))).transpose()?))
} else {
None
};
} else if let Some(a) = tag(line, "#EXT-X-MAP") {
let a = attributes(a);
let url = a.get("URI").and_then(|u| web(base, u)).ok_or_else(|| odd("map"))?;
let range = match a.get("BYTERANGE") {
Some(text) => Some(byte_range(text, 0).ok_or_else(|| odd("range"))?),
None => None,
};
init = Some(Piece { url, range });
// RFC 8216 4.3.2.5: an encrypted one has to say its IV.
init_key = key.clone().map(|(url, iv)| Key { url, iv: iv.unwrap_or_default() });
} else if let Some(text) = tag(line, "#EXTINF") {
seconds = text.split(',').next().and_then(|s| s.trim().parse().ok()).filter(|s: &f64| s.is_finite() && *s >= 0.0).unwrap_or(0.0);
} else if let Some(text) = tag(line, "#EXT-X-BYTERANGE") {
range = Some(text.to_string());
} else if !line.is_empty() && !line.starts_with('#') {
let url = web(base, line).ok_or_else(|| odd("link"))?;
let range = match range.take() {
Some(text) => Some(byte_range(&text, ends.get(&url).copied().unwrap_or(0)).ok_or_else(|| odd("range"))?),
None => None,
};
if let Some((_, end)) = range {
ends.insert(url.clone(), end);
}
let key = key.clone().map(|(url, iv)| Key { url, iv: iv.unwrap_or(u128::from(seq).to_be_bytes()) });
if !std::mem::take(&mut gap) {
let piece = Piece { url, range };
media.segments.push(Segment { stretch: breaks, seq, next: seq.wrapping_add(1), seconds, piece, key, init: init.clone(), init_key: init_key.clone() });
}
seq = seq.checked_add(1).ok_or_else(|| odd("sequence"))?;
}
}
if media.ended {
// Servers count these as they like; the place in the list is what stays.
for (i, s) in media.segments.iter_mut().enumerate() {
(s.seq, s.next) = (i as u64, i as u64 + 1);
}
}
Ok(media)
}
/// `length[@start]`
fn byte_range(text: &str, after: u64) -> Option<(u64, u64)> {
let (len, start) = match text.split_once('@') {
Some((len, start)) => (len, start.trim().parse().ok()?),
None => (text, after),
};
let len: u64 = len.trim().parse().ok().filter(|n| *n > 0)?;
Some((start, start.checked_add(len)?))
}
fn parse_iv(text: &str) -> Option<[u8; 16]> {
let hex = text.strip_prefix("0x").or(text.strip_prefix("0X"))?;
Some(u128::from_str_radix(hex, 16).ok()?.to_be_bytes())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::http::Error;
use crate::model::ErrorKind;
fn base() -> Url {
Url::parse("https://h/a/list.m3u8?t=1").unwrap()
}
fn list(text: &str) -> Media {
match parse(text, &base()) {
Ok(List::Media(m)) => m,
_ => panic!("no media list: {text}"),
}
}
fn found(text: &str) -> Found {
match parse(text, &base()) {
Ok(List::Master(f)) => f,
_ => panic!("no master list: {text}"),
}
}
fn refused(text: &str) -> bool {
matches!(parse(text, &base()), Err(Error::Conn { kind: ErrorKind::Drm, .. }))
}
#[test]
fn variants_and_sound() {
let f = found(
"#EXTM3U\n#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID=\"a\",NAME=\"English, plain\",LANGUAGE=\"en\",URI=\"en.m3u8\"\n\
#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID=\"a\",NAME=\"Deutsch\",LANGUAGE=\"de\",DEFAULT=YES,URI=\"de.m3u8\"\n\
#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID=\"in\",NAME=\"x\"\n\
#EXT-X-STREAM-INF:BANDWIDTH=100,RESOLUTION=640x360,CODECS=\"avc1,mp4a\",AUDIO=\"a\"\nlow.m3u8\n\
#EXT-X-STREAM-INF:BANDWIDTH=300,RESOLUTION=1920x1080,AUDIO=\"a\"\nhigh.m3u8\n\
#EXT-X-STREAM-INF:BANDWIDTH=300,RESOLUTION=1920x1080,AUDIO=\"a\"\nhttps://other/high.m3u8\n\
#EXT-X-STREAM-INF:BANDWIDTH=200,RESOLUTION=1280x720,AUDIO=\"in\"\nmid.m3u8\n",
);
let ids: Vec<&str> = f.videos.iter().map(|v| v.id.as_str()).collect();
assert_eq!(ids, ["1920x1080@300", "1280x720@200", "640x360@100"]);
assert_eq!(f.audios[0].name.as_deref(), Some("English, plain"));
let picked = |choice: Choice| f.pick(&choice).map(|v| v.into_iter().map(|v| v.url.unwrap().path().to_string()).collect::<Vec<_>>());
assert_eq!(picked(Choice::default()).unwrap(), ["/a/high.m3u8", "/a/de.m3u8"]);
assert_eq!(picked(Choice { max_height: Some(720), ..Choice::default() }).unwrap(), ["/a/mid.m3u8"], "its sound is inside");
assert_eq!(picked(Choice { max_height: Some(100), ..Choice::default() }).unwrap()[0], "/a/low.m3u8");
let english = Pick::One(f.audios[0].id.clone());
assert_eq!(picked(Choice { video: Pick::None, audio: english, ..Choice::default() }).unwrap(), ["/a/en.m3u8"]);
assert_eq!(picked(Choice { video: Pick::One("gone".into()), ..Choice::default() }), None);
}
#[test]
fn segments() {
let m = list(
"#EXTM3U\n#EXT-X-TARGETDURATION:4\n#EXT-X-MEDIA-SEQUENCE:7\n#EXT-X-MAP:URI=\"i.mp4\",BYTERANGE=\"10@5\"\n\
#EXTINF:3.5,title\n#EXT-X-BYTERANGE:100@20\nall.m4s\n#EXTINF:4,\n#EXT-X-BYTERANGE:50\nall.m4s\n\
#EXT-X-DISCONTINUITY\n#EXT-X-GAP\n#EXTINF:4,\nnone.m4s\n#EXTINF:1,\n../x.m4s\n",
);
assert!(!m.ended && !m.from_start);
assert_eq!(m.pace, 4.0);
let seen: Vec<_> = m.segments.iter().map(|s| (s.stretch, s.seq, s.seconds, s.piece.url.path(), s.piece.range)).collect();
assert_eq!(seen, [(0, 7, 3.5, "/a/all.m4s", Some((20, 120))), (0, 8, 4.0, "/a/all.m4s", Some((120, 170))), (1, 10, 1.0, "/x.m4s", None)]);
assert_eq!(m.segments[0].init.as_ref().unwrap().range, Some((5, 15)));
}
#[test]
fn keys() {
let m = list(
"#EXTM3U\n#EXT-X-MEDIA-SEQUENCE:5\n#EXT-X-KEY:METHOD=AES-128,URI=\"k\"\n#EXTINF:1,\na\n\
#EXT-X-KEY:METHOD=AES-128,URI=\"k2\",IV=0x0102\n#EXTINF:1,\nb\n#EXT-X-KEY:METHOD=NONE\n#EXTINF:1,\nc\n#EXT-X-ENDLIST\n",
);
let iv = |n: u128| n.to_be_bytes();
assert_eq!(m.segments[0].key.as_ref().unwrap().iv, iv(5), "the sequence number of the server");
assert_eq!(m.segments[1].key.as_ref().unwrap().iv, iv(0x102));
assert_eq!(m.segments[2].key, None);
assert_eq!(m.segments[2].seq, 2);
}
#[test]
fn protected_ones_are_refused() {
for key in [
"METHOD=SAMPLE-AES,URI=\"skd://x\",KEYFORMAT=\"com.apple.streamingkeydelivery\"",
"METHOD=SAMPLE-AES,URI=\"k\"",
"METHOD=SAMPLE-AES-CTR,URI=\"data:x\",KEYFORMAT=\"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed\"",
"METHOD=AES-128,URI=\"k\",KEYFORMAT=\"com.microsoft.playready\"",
"METHOD=ISO-23001-7,URI=\"k\"",
] {
assert!(refused(&format!("#EXTM3U\n#EXT-X-KEY:{key}\n#EXTINF:1,\na\n")), "{key}");
assert!(refused(&format!("#EXTM3U\n#EXT-X-SESSION-KEY:{key}\n#EXT-X-STREAM-INF:BANDWIDTH=1\na\n")), "{key}");
}
assert!(refused("#EXTM3U\n#EXT-X-FAXS-CM:URI=\"x\"\n#EXTINF:1,\na\n"));
}
#[test]
fn nonsense_is_no_list() {
let bad = |text: &str| matches!(parse(text, &base()), Err(Error::BadReply(_)));
for text in [
"",
"<html>",
"#EXTM3U\n#EXTINF:1,\nfile:///etc/passwd\n",
"#EXTM3U\n#EXT-X-KEY:METHOD=AES-128,URI=\"file:///k\"\n#EXTINF:1,\na\n",
"#EXTM3U\n#EXT-X-BYTERANGE:x\na\n",
"#EXTM3U\n#EXT-X-BYTERANGE:18446744073709551615@5\na\n",
"#EXTM3U\n#EXT-X-MEDIA-SEQUENCE:18446744073709551615\n#EXTINF:1,\na\n",
"#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=1\n",
] {
assert!(bad(text), "{text}");
}
}
}

View file

@ -0,0 +1,163 @@
//! Makes one file of all that arrived, without changing sound or picture.
//!
//! ffmpeg reads the pieces from sockets that only this user can open, so that they need no second place on disk.
use super::ffmpeg::{Job, Running};
use super::disk_error;
use super::tape::{Record, Tape};
use crate::disk::{PartialFile, blocking};
use crate::http::{Error, Result, Stop, stopped};
use crate::model::ErrorKind;
use std::io;
use std::os::unix::fs::DirBuilderExt;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicU32, Ordering};
use tokio::io::AsyncWriteExt;
use tokio::net::UnixListener;
use tokio::task::JoinSet;
/// What streams are made of. Keeps pieces from pretending to be lists that lead to other files.
const FORMATS: &str = "mpegts,mov,mp4,m4a,3gp,3g2,mj2,matroska,webm,aac,ac3,eac3,mp3,flac,ogg,asf,concat";
const BLOCK: u64 = 1 << 20;
/// Gone with everything in it when dropped.
struct Sockets {
dir: PathBuf,
serving: JoinSet<()>,
next: u32,
}
impl Sockets {
fn new() -> io::Result<Sockets> {
static NEXT: AtomicU32 = AtomicU32::new(0);
let base = std::env::var_os("XDG_RUNTIME_DIR").map(PathBuf::from).filter(|d| d.is_dir()).unwrap_or_else(std::env::temp_dir);
loop {
let name = format!("medlar-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed));
let dir = base.join(name);
match std::fs::DirBuilder::new().mode(0o700).create(&dir) {
Ok(()) => return Ok(Sockets { dir, serving: JoinSet::new(), next: 0 }),
// Left by one that was killed, with the same number.
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue,
Err(e) => return Err(e),
}
}
}
/// The address of a socket that gives out what `pieces` say, once.
fn serve(&mut self, what: Served) -> Result<String> {
let path = self.dir.join(self.next.to_string());
self.next += 1;
let listener = UnixListener::bind(&path).map_err(disk_error)?;
self.serving.spawn(async move {
let Ok((mut to, _)) = listener.accept().await else { return };
let sent = match what {
Served::Text(text) => to.write_all(text.as_bytes()).await.map_err(disk_error),
Served::Pieces(file, pieces) => send(&file, &pieces, &mut to).await,
};
if let Err(e) = sent {
log::debug!("joining: {e:?}");
}
let _ = to.shutdown().await;
});
Ok(format!("unix:{}", path.display()))
}
}
impl Drop for Sockets {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.dir);
}
}
enum Served {
Text(String),
Pieces(Arc<PartialFile>, Vec<Record>),
}
async fn send(file: &PartialFile, pieces: &[Record], to: &mut (impl AsyncWriteExt + Unpin)) -> Result<()> {
for p in pieces {
let mut at = p.at;
while at < p.at + p.len {
let n = BLOCK.min(p.at + p.len - at);
to.write_all(&file.read_at(n as usize, at).await?).await.map_err(disk_error)?;
at += n;
}
}
Ok(())
}
/// ffmpeg's name for the format a file name asks for.
pub(super) fn muxer(ext: &str) -> Option<&'static str> {
Some(match ext.to_ascii_lowercase().as_str() {
"mp4" | "m4v" => "mp4",
"m4a" => "ipod",
"mkv" | "mka" => "matroska",
"webm" => "webm",
"mov" => "mov",
"ts" => "mpegts",
_ => return None,
})
}
/// What holds anything.
pub(super) const ANYTHING: &str = "matroska";
/// Writes `to`, in the format of `muxer` or, where that can't hold it, in `ANYTHING`. Nothing is left there when it fails.
pub(super) async fn join(ffmpeg: &Path, tape: &Tape, muxer: &str, to: &Path, stop: &mut Stop) -> Result<()> {
let mut result = once(ffmpeg, tape, muxer, to, stop).await;
if muxer != ANYTHING && matches!(result, Err(Error::Conn { kind: ErrorKind::Media, .. })) {
log::debug!("{muxer} can't hold it");
result = once(ffmpeg, tape, ANYTHING, to, stop).await;
}
if result.is_err() {
let _ = std::fs::remove_file(to);
}
result
}
async fn once(ffmpeg: &Path, tape: &Tape, muxer: &str, to: &Path, stop: &mut Stop) -> Result<()> {
let mut sockets = Sockets::new().map_err(disk_error)?;
let tracks: Vec<Vec<Vec<Record>>> = (0..tape.head.tracks.len() as u32).map(|t| tape.groups(t)).filter(|g| !g.is_empty()).collect();
if tracks.is_empty() {
return Err(Error::because(ErrorKind::Media, "error.media.empty"));
}
let single = tracks.iter().all(|groups| groups.len() == 1);
let mut job = Job::new();
for (i, groups) in tracks.iter().enumerate() {
let mut addresses = vec![];
for group in groups {
addresses.push(sockets.serve(Served::Pieces(tape.file.clone(), group.clone()))?);
}
// Their clocks are the same one.
if i > 0 && single {
job.args(["-isync", "0"]);
}
job.args(["-format_whitelist", FORMATS]);
match &addresses[..] {
[one] => job.input("unix", one),
many => {
let list = many.iter().map(|a| format!("file '{a}'\n")).collect::<String>();
let list = sockets.serve(Served::Text(format!("ffconcat version 1.0\n{list}")))?;
job.args(["-f", "concat", "-safe", "0"]).input("unix", list)
}
};
}
match tracks.len() {
1 => job.args(["-map", "0:v?", "-map", "0:a?"]),
_ => job.args(["-map", "0:v?", "-map", "1:a?"]),
};
job.args(["-c", "copy"]).file(muxer, to);
let mut running = job.start(ffmpeg)?;
ended(&mut running, stop).await?;
let to = to.to_path_buf();
blocking(move || std::fs::File::open(to).and_then(|f| f.sync_all()).map_err(disk_error)).await
}
async fn ended(running: &mut Running, stop: &mut Stop) -> Result<()> {
tokio::select! {
biased;
_ = stopped(stop) => Err(Error::Stopped),
end = running.end() => end?.map_err(|failed| failed.error()),
}
}

View file

@ -0,0 +1,156 @@
//! What lists of streams have in common.
use serde::{Deserialize, Serialize};
use url::Url;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum Kind {
Hls,
Dash,
Rtsp,
Mms,
}
/// What can be downloaded from a link.
#[derive(Debug, Clone)]
pub struct Found {
pub kind: Kind,
/// Goes on until it is stopped.
pub live: bool,
/// Seconds.
pub duration: Option<f64>,
/// Best first. With sound in them, unless they name their `sound`.
pub videos: Vec<Variant>,
/// Sound that comes on its own. Best first.
pub audios: Vec<Variant>,
}
/// One quality or language.
#[derive(Debug, Clone, PartialEq)]
pub struct Variant {
/// Stays the same when the list is read again.
pub id: String,
/// Bits per second.
pub bandwidth: u64,
pub size: Option<(u32, u32)>,
pub codecs: String,
pub language: Option<String>,
pub name: Option<String>,
/// The group of `audios` that goes with it, or the one it is in.
pub sound: Option<String>,
/// The one to take when none is asked for.
pub preferred: bool,
/// Where its own list is (HLS).
pub(super) url: Option<Url>,
}
impl Variant {
pub(super) fn new(id: String) -> Variant {
Variant { id, bandwidth: 0, size: None, codecs: String::new(), language: None, name: None, sound: None, preferred: false, url: None }
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum Pick {
#[default]
Best,
None,
/// `Variant::id`
One(String),
}
/// What the user chose of a stream.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct Choice {
pub video: Pick,
pub audio: Pick,
/// The best that is no higher, for `Pick::Best`.
pub max_height: Option<u32>,
/// A recording ends by itself after so many seconds or bytes.
pub seconds: Option<u64>,
pub bytes: Option<u64>,
}
impl Found {
/// What to download. None when the choice doesn't fit, or there is nothing.
pub(super) fn pick(&self, choice: &Choice) -> Option<Vec<Variant>> {
let by_id = |from: &[Variant], id: &str| from.iter().find(|v| v.id == id).cloned();
let video = match &choice.video {
Pick::None => None,
Pick::One(id) => Some(by_id(&self.videos, id)?),
Pick::Best => {
let fits = |v: &&Variant| choice.max_height.is_none_or(|max| v.size.is_none_or(|(_, h)| h <= max));
self.videos.iter().find(fits).or(self.videos.last()).cloned()
}
};
let audio = match &choice.audio {
Pick::None => None,
Pick::One(id) => Some(by_id(&self.audios, id)?),
Pick::Best => {
let group = video.as_ref().and_then(|v| v.sound.as_ref());
// A video that names no group has its sound in it, unless there is none of it (DASH).
let apart = self.kind == Kind::Dash || video.is_none();
let fits = |a: &&Variant| apart || (group.is_some() && a.sound.as_ref() == group);
let best = self.audios.iter().filter(fits);
best.clone().find(|a| a.preferred).or(best.clone().next()).cloned()
}
};
let picked: Vec<Variant> = video.into_iter().chain(audio).collect();
(!picked.is_empty()).then_some(picked)
}
}
/// A piece of a file, or all of it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) struct Piece {
pub url: Url,
/// First byte and the one after the last.
pub range: Option<(u64, u64)>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) struct Key {
pub url: Url,
pub iv: [u8; 16],
}
#[derive(Debug, Clone, PartialEq)]
pub(super) struct Segment {
/// Pieces with the same one can be put together as they are.
pub stretch: u64,
pub seq: u64,
/// The `seq` of the one after it.
pub next: u64,
pub seconds: f64,
pub piece: Piece,
pub key: Option<Key>,
/// Comes before all others of the stretch.
pub init: Option<Piece>,
pub init_key: Option<Key>,
}
/// One variant, as its list is now.
#[derive(Debug, Clone, Default)]
pub(super) struct Media {
pub segments: Vec<Segment>,
/// There will be no more.
pub ended: bool,
/// All since the start, though it goes on.
pub from_start: bool,
/// Seconds between two looks.
pub pace: f64,
/// All of it is in one file.
pub whole: Option<Url>,
}
/// Lists may lead to the web only.
pub(super) fn web(base: &Url, link: &str) -> Option<Url> {
let url = base.join(link.trim()).ok()?;
(matches!(url.scheme(), "http" | "https") && url.has_host()).then_some(url)
}
/// Best first: the higher picture, then more bits.
pub(super) fn sort(variants: &mut [Variant]) {
variants.sort_by_key(|v| std::cmp::Reverse((v.size.map_or(0, |(_, h)| h), v.bandwidth)));
}

View file

@ -0,0 +1,507 @@
//! Streams: HLS and DASH in pieces that are joined, RTSP and MMS recorded through ffmpeg. Nothing is converted.
//!
//! Copy protection is recognised and refused. The only keys used are those a list hands to everyone (AES-128).
mod dash;
pub mod ffmpeg;
mod fetch;
mod hls;
mod join;
mod list;
mod record;
mod tape;
pub use ffmpeg::Tools;
pub use list::{Choice, Found, Kind, Pick, Variant};
use crate::disk::{self, PartialFile, blocking};
use crate::http::{Client, Error, Monitor, Options, PartState, PartView, Result, Shared, Snapshot, Source, Stop, safe_name, stopped};
use crate::model::{ErrorKind, Part, Task, TaskId};
use crate::store::Store;
use fetch::{Feed, Net, Want};
use list::Media;
use std::collections::VecDeque;
use std::io;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Duration;
use tape::{Head, Tape, Track};
use tokio::task::JoinSet;
use tokio::time::Instant;
use url::Url;
/// Pieces that are downloaded at once.
const PARALLEL: u32 = 4;
/// Ending of what ffmpeg is making, after that of the unfinished file.
const JOINING: &str = ".join";
fn odd(what: &str) -> Error {
Error::BadReply(format!("stream: {what}"))
}
fn drm() -> Error {
Error::conn(ErrorKind::Drm)
}
fn disk_error(e: io::Error) -> Error {
Error::Disk(e.into())
}
/// Links that ffmpeg has to open.
pub(crate) fn recorded(url: &Url) -> bool {
matches!(url.scheme(), "rtsp" | "mms" | "mmsh" | "mmst")
}
/// What kind of stream a link is, if it is one. `mime` is what the server called it, if that is known.
pub fn kind(url: &Url, mime: Option<&str>) -> Option<Kind> {
if recorded(url) {
return Some(if url.scheme() == "rtsp" { Kind::Rtsp } else { Kind::Mms });
}
if !matches!(url.scheme(), "http" | "https") {
return None;
}
let path = url.path().to_ascii_lowercase();
match mime.map(str::to_ascii_lowercase).as_deref() {
Some("application/vnd.apple.mpegurl" | "application/x-mpegurl" | "audio/mpegurl" | "audio/x-mpegurl") if !path.ends_with(".m3u") => Some(Kind::Hls),
Some("application/dash+xml") => Some(Kind::Dash),
_ if path.ends_with(".m3u8") => Some(Kind::Hls),
_ if path.ends_with(".mpd") => Some(Kind::Dash),
_ => None,
}
}
/// Of a task, as far as it is known.
pub fn kind_of(task: &Task) -> Option<Kind> {
kind(&Url::parse(&task.url).ok()?, task.mime.as_deref())
}
/// What there is to choose from. Nothing is known of a stream that ffmpeg has to open.
pub async fn probe(client: &Client, source: &Source, stop: &mut Stop) -> Result<Found> {
if let Some(kind) = kind(&source.url, None).filter(|k| matches!(k, Kind::Rtsp | Kind::Mms)) {
return Ok(Found { kind, live: true, duration: None, videos: vec![], audios: vec![] });
}
let net = Net::plain(client, source);
let mut opened = net.open(stop).await?;
// A master list doesn't say whether what it leads to goes on.
if opened.found.kind == Kind::Hls && opened.media.is_none() {
let first = opened.found.videos.first().cloned().ok_or_else(|| odd("no variants"))?;
opened.media = net.refresh(&None, &[first], stop).await?.pop();
}
if let Some(media) = &opened.media {
opened.found.live = !media.ended;
opened.found.duration = media.ended.then(|| media.segments.iter().map(|s| s.seconds).sum());
}
Ok(opened.found)
}
/// What a download of a stream needs to know.
pub struct Request<'a> {
pub id: TaskId,
pub source: Source,
pub choice: Choice,
pub tools: &'a Tools,
pub options: &'a Options,
}
/// Starts or continues the task and returns the finished file. Doesn't touch the task's state. A stream that goes on ends with
/// `monitor.finish`, or at the limits of the choice; stopping it keeps what is there, to go on later.
pub async fn download(shared: &Shared, request: Request<'_>, monitor: &Monitor, mut stop: Stop) -> Result<PathBuf> {
let Request { id, source, choice, tools, options } = request;
let ffmpeg = tools.ffmpeg()?.to_path_buf();
let store = &shared.store;
let (task, parts) = run(store, move |s| Ok((s.task(id)?, s.parts(id)?))).await?;
let partial = {
let (folder, name) = (task.folder.clone(), task.name.clone());
let begun = !parts.is_empty();
blocking(move || if begun { PartialFile::reopen(&folder, &name) } else { Ok(None) }).await?
};
let done: u64 = parts.iter().map(|p| p.done).sum();
let mut tape = None;
let mut empty = None;
match partial {
Some(file) if Tape::is(&file).await? => {
let file = Arc::new(file);
match Tape::open(file.clone(), done).await? {
Some(found) => tape = Some(found),
// Killed before anything of it was safe.
None if done == 0 => empty = Some(file),
None => return Err(Error::Changed),
}
}
Some(file) if done == 0 && file.size()? == 0 => empty = Some(Arc::new(file)),
// Joined already, and then interrupted.
Some(file) if file.size()? > 0 => return finish(store, id, file).await,
Some(_) => return Err(Error::Missing),
None if done > 0 => {
let path = task.folder.join(&task.name);
let whole = parts.iter().all(|p| p.end == Some(p.start + p.done));
if whole && path.symlink_metadata().is_ok_and(|m| m.is_file() && m.len() == done) {
return Ok(path);
}
return Err(Error::Missing);
}
None => {}
}
let mut meter = Meter::new(store.clone(), id, options);
let finishing = *monitor.finishing().borrow();
let kind = kind_of(&task).unwrap_or(Kind::Hls);
let mut job = Work { shared, task: &task, options, choice: &choice, monitor, ffmpeg: &ffmpeg };
let mut tape = match tape {
// The user wants what there is.
Some(tape) if finishing && tape.head.live && !tape.records.is_empty() => tape,
tape if matches!(kind, Kind::Rtsp | Kind::Mms) => {
let mut tape = match tape {
Some(tape) => tape,
None => job.create(empty, Head { live: true, tracks: vec![Track { id: String::new(), total: None }] }, &source.url, false).await?,
};
let result = record::record(&ffmpeg, &shared.client, &source, &choice, &mut tape, &mut meter, monitor, &mut stop).await;
meter.save(&tape).await?;
result?;
tape
}
tape => {
let net = Arc::new(Net::new(shared, &source, options, monitor, meter.received.clone()));
job.pieces(net, tape, empty, &mut meter, &mut stop).await?
}
};
meter.save(&tape).await?;
let file = job.join(&mut tape, &mut stop).await?;
drop(tape);
finish(store, id, file).await
}
async fn run<T: Send + 'static>(store: &Arc<Store>, work: impl FnOnce(&Store) -> Result<T> + Send + 'static) -> Result<T> {
let store = store.clone();
blocking(move || work(&store)).await
}
/// Gives a joined file its name.
async fn finish(store: &Arc<Store>, id: TaskId, file: PartialFile) -> Result<PathBuf> {
let matroska = file.read_at(4, 0).await.is_ok_and(|start| start == [0x1a, 0x45, 0xdf, 0xa3]);
run(store, move |store| {
let size = file.size()?;
store.save_parts(id, vec![Part { start: 0, end: Some(size), done: size }])?;
let task = store.task(id)?;
let (stem, ext) = crate::http::name::split(&task.name);
// The format that was asked for could not hold it.
let name = match ext {
Some(ext) if matroska && !matches!(join::muxer(ext), Some(join::ANYTHING | "webm")) => format!("{stem}.mkv"),
_ => task.name.clone(),
};
file.finish(&name, size, |name| {
let name = name.to_string();
store.edit_task(id, move |task| (task.name, task.size) = (name, Some(size)))?;
Ok(())
})
})
.await
}
struct Work<'a> {
shared: &'a Shared,
task: &'a Task,
options: &'a Options,
choice: &'a Choice,
monitor: &'a Monitor,
ffmpeg: &'a Path,
}
impl Work<'_> {
/// A new tape, under a free name.
async fn create(&self, empty: Option<Arc<PartialFile>>, head: Head, url: &Url, sound: bool) -> Result<Tape> {
let file = match empty {
Some(file) => {
file.clear()?;
file
}
None => {
let wanted = name(&self.task.name, url, if sound { "m4a" } else { "mp4" });
let (id, folder) = (self.task.id, self.task.folder.clone());
let file = run(&self.shared.store, move |store| {
let _names = disk::names();
let (file, name) = PartialFile::create(&folder, &wanted, &store.used_names(&folder, id)?)?;
store.edit_task(id, move |task| task.name = name)?;
store.save_parts(id, vec![Part { start: 0, end: None, done: 0 }])?;
Ok(file)
});
Arc::new(file.await?)
}
};
Tape::create(file, head).await
}
/// Downloads the pieces of a list, until it ends or is told to.
async fn pieces(&mut self, net: Arc<Net>, tape: Option<Tape>, empty: Option<Arc<PartialFile>>, meter: &mut Meter, stop: &mut Stop) -> Result<Tape> {
let opened = net.open(stop).await?;
let picked = opened.found.pick(self.choice).ok_or(Error::because(ErrorKind::Media, "error.media.choice"))?;
let sound = !picked.iter().any(|p| opened.found.videos.contains(p));
let is_master = opened.media.is_none() && opened.manifest.is_none();
let root = if is_master { None } else { Some(opened.found.kind) };
let mut media = match (&opened.manifest, opened.media) {
(Some(manifest), _) => picked.iter().map(|v| manifest.media(v, fetch::now())).collect::<Result<Vec<_>>>()?,
(None, Some(media)) => vec![media],
(None, None) => net.refresh(&root, &picked, stop).await?,
};
for m in &mut media {
net.split(m, stop).await?;
}
let live = media.iter().any(|m| !m.ended);
if media.iter().any(|m| m.segments.is_empty()) && !live {
return Err(odd("no segments"));
}
let total = |m: &Media| (!live).then_some(m.segments.len() as u64);
let head = Head { live, tracks: picked.iter().zip(&media).map(|(v, m)| Track { id: v.id.clone(), total: total(m) }).collect() };
let mut tape = match tape {
Some(tape) => {
// A recording may have ended meanwhile.
let same = if tape.head.live { tape.head.tracks.iter().map(|t| &t.id).eq(head.tracks.iter().map(|t| &t.id)) } else { tape.head == head };
if !same {
return Err(Error::Changed);
}
tape
}
None => self.create(empty, head, &net.source.url, sound).await?,
};
let live = tape.head.live;
meter.whole = (!live).then(|| media.iter().flat_map(|m| &m.segments).map(|s| (s.seconds * 1000.0) as u64).sum());
let mut feeds: Vec<Feed> = (0..picked.len() as u32).map(|track| Feed::new(track, &tape, self.choice.seconds)).collect();
let mut queue: VecDeque<Want> = VecDeque::new();
let mut ended = add(&mut feeds, &media, live, &mut queue);
// Picture and sound side by side.
queue.make_contiguous().sort_by_key(|w| w.place);
let (mut running, mut lists) = (JoinSet::new(), JoinSet::new());
let mut finish = self.monitor.finishing();
let cap = self.monitor.cap();
let (mut failed, mut silent) = (None, 0);
let mut pace = wait_of(&media, false);
let mut look = Instant::now() + pace;
loop {
let full = live && self.choice.bytes.is_some_and(|most| tape.end >= most);
if failed.is_some() || full {
queue.clear();
}
ended |= full;
let width = (*cap.borrow()).min(net.width()).min(self.monitor.flow().connections()).max(1) as usize;
while running.len() < width && let Some(want) = queue.pop_front() {
let (net, mut stop) = (net.clone(), stop.clone());
running.spawn(async move {
let got = net.piece(&want, &mut stop).await;
(want, got)
});
}
if running.is_empty() && queue.is_empty() {
if ended || failed.is_some() {
break;
}
net.rest();
}
if live && !ended && failed.is_none() && lists.is_empty() && Instant::now() >= look {
let (net, picked, mut stop) = (net.clone(), picked.clone(), stop.clone());
lists.spawn(async move { net.refresh(&root, &picked, &mut stop).await });
}
tokio::select! {
biased;
_ = stopped(stop) => {
failed = Some(Error::Stopped);
break;
}
_ = stopped(&mut finish), if live && !ended => {
ended = true;
queue.clear();
}
Some(got) = running.join_next() => match got {
Ok((want, Ok(data))) => tape.append(want.record, &data).await?,
// It is gone already, the rest goes on.
Ok((_, Err(Error::Status { code: 404 | 410, .. }))) if live => {}
Ok((_, Err(e))) => failed = failed.or(Some(e)),
Err(e) => std::panic::resume_unwind(e.into_panic()),
},
Some(list) = lists.join_next() => match list {
Ok(Ok(now)) => {
silent = 0;
let changed = now.iter().zip(&media).any(|(a, b)| a.segments.last() != b.segments.last());
media = now;
pace = wait_of(&media, !changed);
ended |= add(&mut feeds, &media, live, &mut queue);
look = Instant::now() + pace;
}
Ok(Err(Error::Stopped)) => {}
// The end of many.
Ok(Err(Error::Status { code: 404 | 410, .. })) if !tape.records.is_empty() => ended = true,
Ok(Err(e)) => {
silent += 1;
if silent >= self.options.tries || !fetch::passing(&e) {
failed = failed.or(Some(e));
}
look = Instant::now() + pace;
}
Err(e) => std::panic::resume_unwind(e.into_panic()),
},
_ = tokio::time::sleep(meter.tick()) => {}
}
meter.look(&tape, running.len() as u32, self.monitor).await?;
}
// Ends the requests, not what is on the tape.
running.shutdown().await;
meter.save(&tape).await?;
meter.show(&tape, 0, self.monitor);
match failed {
Some(e) => Err(e),
None => Ok(tape),
}
}
/// The joined file takes the place of the tape.
async fn join(&self, tape: &mut Tape, stop: &mut Stop) -> Result<PartialFile> {
let from = tape.file.path().to_path_buf();
let mut to = from.clone().into_os_string();
to.push(JOINING);
let to = PathBuf::from(to);
let ext = self.shared.store.task(self.task.id)?.name;
let muxer = crate::http::name::split(&ext).1.and_then(join::muxer).unwrap_or(join::ANYTHING);
join::join(self.ffmpeg, tape, muxer, &to, stop).await?;
blocking(move || {
std::fs::rename(&to, &from).map_err(disk_error)?;
PartialFile::hold(from)?.ok_or(Error::Missing)
})
.await
}
}
/// Puts what is new in the queue. True when there will be no more.
fn add(feeds: &mut [Feed], media: &[Media], live: bool, queue: &mut VecDeque<Want>) -> bool {
let mut over = true;
for (feed, media) in feeds.iter_mut().zip(media) {
feed.take(media, live, queue);
over &= media.ended || feed.full();
}
over
}
/// Until the next look at lists that grow.
fn wait_of(media: &[Media], same: bool) -> Duration {
let pace = media.iter().map(|m| m.pace).fold(60.0, f64::min);
Duration::from_secs_f64(if same { pace / 2.0 } else { pace })
}
/// Names that say nothing.
const PLAIN: &[&str] = &["master", "index", "playlist", "manifest", "chunklist", "main", "stream", "live", "video", "prog_index", "media"];
/// The name for a stream without one, with an ending for what it becomes.
fn name(given: &str, url: &Url, ext: &str) -> String {
let given = safe_name(given).filter(|n| !n.is_empty());
let mut words: Vec<String> = url.path_segments().into_iter().flatten().rev().filter_map(decoded).collect();
words.extend(url.host_str().and_then(safe_name));
let stem = |n: &str| n.rsplit_once('.').filter(|(s, e)| !s.is_empty() && matches!(e.to_ascii_lowercase().as_str(), "m3u8" | "m3u" | "mpd" | "sdp")).map_or(n.to_string(), |(s, _)| s.to_string());
let telling = words.iter().map(|w| stem(w)).find(|w| !PLAIN.contains(&w.to_ascii_lowercase().as_str()));
let name = given.map(|n| stem(&n)).filter(|n| !PLAIN.contains(&n.to_ascii_lowercase().as_str())).or(telling).unwrap_or_else(|| "stream".into());
match crate::http::name::split(&name).1.and_then(join::muxer) {
Some(_) => name,
None => safe_name(&format!("{name}.{ext}")).unwrap_or_else(|| format!("stream.{ext}")),
}
}
fn decoded(segment: &str) -> Option<String> {
safe_name(&percent_encoding::percent_decode_str(segment).decode_utf8_lossy())
}
/// What others see of it, and what is safe on disk.
struct Meter {
store: Arc<Store>,
id: TaskId,
received: Arc<AtomicU64>,
/// Milliseconds of all tracks, when that is known.
whole: Option<u64>,
tick: Duration,
checkpoint: Duration,
saved: (u64, Instant),
shown: (u64, Instant),
speed: f64,
}
impl Meter {
fn new(store: Arc<Store>, id: TaskId, options: &Options) -> Meter {
let now = Instant::now();
let (tick, checkpoint) = (options.tick, options.checkpoint);
Meter { store, id, received: Arc::default(), whole: None, tick, checkpoint, saved: (0, now), shown: (0, now), speed: 0.0 }
}
fn tick(&self) -> Duration {
self.tick
}
fn came(&self, n: u64) {
self.received.fetch_add(n, Ordering::Relaxed);
}
async fn look(&mut self, tape: &Tape, connections: u32, monitor: &Monitor) -> Result<()> {
if self.shown.1.elapsed() >= self.tick {
self.show(tape, connections, monitor);
}
if self.saved.1.elapsed() >= self.checkpoint {
self.save(tape).await?;
}
Ok(())
}
fn show(&mut self, tape: &Tape, connections: u32, monitor: &Monitor) {
let received = self.received.load(Ordering::Relaxed);
let dt = self.shown.1.elapsed().as_secs_f64().max(0.001);
let now = received.saturating_sub(self.shown.0) as f64 / dt;
self.speed = self.speed * 0.7 + now * 0.3;
self.shown = (received, Instant::now());
// Its size is a guess from how long it is, so that there is something to show.
let here: u64 = tape.records.iter().map(|r| u64::from(r.ms)).sum();
let size = self.whole.filter(|_| here > 0).map(|whole| (tape.end as f64 * (whole as f64 / here as f64).max(1.0)) as u64);
let state = if connections > 0 { PartState::Running } else { PartState::Waiting };
let part = PartView { id: 0, start: 0, end: size, done: tape.end, state, speed: self.speed, fails: 0 };
let shot = Snapshot { size, parts: vec![part], connections, wanted: connections, received, speed: self.speed, ..Default::default() };
monitor.publish(shot, vec![], std::iter::empty());
}
/// Data first, then the record of it.
async fn save(&mut self, tape: &Tape) -> Result<()> {
let (end, file, id) = (tape.end, tape.file.clone(), self.id);
if self.saved.0 != end {
run(&self.store, move |store| {
file.sync()?;
Ok(store.save_parts(id, vec![Part { start: 0, end: None, done: end }])?)
})
.await?;
}
self.saved = (end, Instant::now());
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn kinds() {
let of = |url: &str, mime| kind(&Url::parse(url).unwrap(), mime);
assert_eq!(of("https://h/a/Master.M3U8?x=1", None), Some(Kind::Hls));
assert_eq!(of("https://h/a", Some("application/vnd.apple.mpegURL")), Some(Kind::Hls));
assert_eq!(of("https://h/a.mpd", None), Some(Kind::Dash));
assert_eq!(of("rtsp://h/a", None), Some(Kind::Rtsp));
assert_eq!(of("mms://h/a.wmv", None), Some(Kind::Mms));
for (url, mime) in [("https://h/songs.m3u", Some("audio/x-mpegurl")), ("https://h/a.mp4", Some("video/mp4")), ("ftp://h/a.m3u8", None)] {
assert_eq!(of(url, mime), None, "{url}");
}
}
#[test]
fn names() {
let of = |given: &str, url: &str| name(given, &Url::parse(url).unwrap(), "mp4");
assert_eq!(of("", "https://h/my%20film/master.m3u8?t=1"), "my film.mp4");
assert_eq!(of("", "https://h/film.m3u8"), "film.mp4");
assert_eq!(of("", "https://h.org/index.m3u8"), "h.org.mp4");
assert_eq!(of("index.m3u8", "https://h.org/a/index.m3u8"), "a.mp4");
assert_eq!(of("Mine.mkv", "https://h/x.m3u8"), "Mine.mkv");
assert_eq!(of("Part 1.5", "https://h/x.m3u8"), "Part 1.5.mp4");
assert_eq!(of("../../x", "rtsp://h/cam"), "x.mp4");
}
}

View file

@ -0,0 +1,223 @@
//! Streams that ffmpeg has to receive itself: RTSP and MMS.
use super::ffmpeg::Job;
use super::list::Choice;
use super::tape::{Record, Tape};
use super::{Meter, disk_error, odd};
use crate::auth::Login;
use crate::http::{Error, Monitor, Result, Source, Stop, Client, stopped};
use crate::model::ErrorKind;
use std::path::Path;
use std::time::Duration;
use tokio::io::AsyncReadExt;
use tokio::time::{Instant, timeout};
use url::Url;
/// What ffmpeg writes is kept in pieces of this size, or of a second.
const PIECE: usize = 256 << 10;
const EVERY: Duration = Duration::from_secs(1);
/// Nothing comes for so long: the stream is gone.
const SILENCE: Duration = Duration::from_secs(20);
/// For ffmpeg to end properly when the download is paused.
const GRACE: Duration = Duration::from_millis(800);
/// Where to ask, in this order.
fn addresses(url: &Url) -> Vec<(String, &'static str)> {
let with = |scheme: &str| format!("{scheme}{}", &url.as_str()[url.scheme().len()..]);
let (http, tcp) = ((with("mmsh"), "mmsh,http,tcp"), (with("mmst"), "mmst,tcp"));
match url.scheme() {
"rtsp" => vec![(url.to_string(), "rtsp,rtp,udp,tcp")],
"mmsh" => vec![http],
"mmst" => vec![tcp],
// The old name for both. Its own port is that of the second.
_ if url.port() == Some(1755) => vec![tcp, http],
_ => vec![http, tcp],
}
}
/// A login must not be among the arguments, where everyone can read them.
fn input(job: &mut Job, address: &str, protocols: &str, login: Option<&Login>) -> Result<()> {
let wait = &SILENCE.as_micros().to_string()[..];
let options = if address.starts_with("rtsp:") { &[("rtsp_flags", "prefer_tcp"), ("timeout", wait)][..] } else { &[] };
let Some(login) = login else {
for (name, value) in options {
job.arg(format!("-{name}")).arg(value);
}
job.input(protocols, address);
return Ok(());
};
let encode = |text: &str| percent_encoding::utf8_percent_encode(text, percent_encoding::NON_ALPHANUMERIC).to_string();
let (scheme, rest) = address.split_once("://").ok_or(Error::Link)?;
let with = format!("{scheme}://{}:{}@{rest}", encode(&login.user), encode(&login.password)).replace('\'', r"'\''");
if with.contains(['\n', '\r']) {
return Err(Error::Link);
}
let options: String = options.iter().map(|(name, value)| format!("option {name} {value}\n")).collect();
job.args(["-f", "concat", "-safe", "0"]).input(&format!("pipe,{protocols}"), "pipe:0");
job.stdin(format!("ffconcat version 1.0\nfile '{with}'\n{options}"));
Ok(())
}
/// Adds to the tape until the stream ends, a limit is reached or `monitor.finish` is called.
#[allow(clippy::too_many_arguments)]
pub(super) async fn record(
ffmpeg: &Path,
client: &Client,
source: &Source,
choice: &Choice,
tape: &mut Tape,
meter: &mut Meter,
monitor: &Monitor,
stop: &mut Stop,
) -> Result<()> {
let way = tokio::select! {
_ = stopped(stop) => return Err(Error::Stopped),
way = source.way(client) => way?,
};
// Straight to the server would show it who asks.
if way.proxy.is_some() {
return Err(Error::because(ErrorKind::Proxy, "error.proxy.stream"));
}
let had = tape.records.len();
let mut first = None;
for (address, protocols) in addresses(&source.url) {
let mut job = Job::new();
input(&mut job, &address, protocols, way.login.as_ref())?;
let result = run(ffmpeg, job, choice, tape, meter, monitor, stop).await;
use ErrorKind::{Login, Dns, Tool};
let other_way = match &result {
Err(Error::Conn { kind, .. }) => !matches!(kind, Login | Dns | Tool),
Err(Error::Idle) => true,
_ => false,
};
if !other_way || tape.records.len() > had {
return result;
}
first = first.or(result.err());
}
Err(first.unwrap_or(Error::Link))
}
async fn run(ffmpeg: &Path, mut job: Job, choice: &Choice, tape: &mut Tape, meter: &mut Meter, monitor: &Monitor, stop: &mut Stop) -> Result<()> {
let had = tape.length(0);
let full = |tape: &Tape| choice.bytes.is_some_and(|most| tape.records.iter().map(|r| r.len).sum::<u64>() >= most);
if let Some(seconds) = choice.seconds {
let left = (seconds * 1000).saturating_sub(had);
if left == 0 {
return Ok(());
}
job.args(["-t", &format!("{}ms", left)]);
}
if full(tape) {
return Ok(());
}
job.args(["-map", "0:v?", "-map", "0:a?", "-c", "copy", "-flush_packets", "1"]).pipe("matroska");
let mut running = job.start(ffmpeg)?;
let mut output = running.output.take().ok_or_else(|| odd("no output"))?;
let group = tape.records.iter().map(|r| r.group + 1).max().unwrap_or(0);
let progress = running.progress();
let mut finish = monitor.finishing();
let (mut seq, mut ms, mut buf) = (0u64, 0u64, Vec::with_capacity(PIECE));
let (mut asked, mut paused, mut since, mut came) = (false, false, Instant::now(), Instant::now());
let mut kill_at = None;
loop {
let mut chunk = [0; 16 << 10];
let read = tokio::select! {
biased;
_ = stopped(stop), if !paused => {
paused = true;
running.finish();
kill_at = Some(Instant::now() + GRACE);
None
}
_ = stopped(&mut finish), if !asked && !paused => {
asked = true;
running.finish();
kill_at = Some(Instant::now() + SILENCE);
None
}
n = output.read(&mut chunk) => Some(n.map_err(disk_error)?),
_ = tokio::time::sleep(meter.tick()) => None,
};
if let Some(n) = read {
let mut rest = &chunk[..n];
while !rest.is_empty() {
// What is here is kept, whatever the limits say.
let n = tokio::select! {
biased;
_ = stopped(stop), if !paused => rest.len(),
n = monitor.flow().take(rest.len() as u64) => n as usize,
};
buf.extend_from_slice(&rest[..n]);
meter.came(n as u64);
rest = &rest[n..];
}
came = Instant::now();
}
let over = read == Some(0);
if !buf.is_empty() && (over || buf.len() >= PIECE || since.elapsed() >= EVERY) {
let now = progress.borrow().time.as_millis() as u64;
// The end of the last report comes late.
let record = Record { track: 0, group, init: false, stretch: u64::from(group), seq, ms: now.saturating_sub(ms) as u32, at: 0, len: 0 };
tape.append(record, &buf).await?;
(seq, ms, since) = (seq + 1, ms.max(now), Instant::now());
buf.clear();
if full(tape) && !asked && !paused {
asked = true;
running.finish();
kill_at = Some(Instant::now() + SILENCE);
}
}
meter.look(tape, 1, monitor).await?;
if over {
break;
}
let late = kill_at.is_some_and(|at| Instant::now() >= at);
if late || (!asked && !paused && came.elapsed() > SILENCE + EVERY) {
running.kill().await;
if !buf.is_empty() {
let record = Record { track: 0, group, init: false, stretch: u64::from(group), seq, ms: 0, at: 0, len: 0 };
tape.append(record, &buf).await?;
}
return if paused { Err(Error::Stopped) } else if asked { Ok(()) } else { Err(Error::Idle) };
}
}
let end = timeout(GRACE, running.end()).await;
if paused {
return Err(Error::Stopped);
}
if asked {
return Ok(());
}
match end {
Ok(Ok(Ok(()))) if seq > 0 => Ok(()),
Ok(Ok(Ok(()))) => Err(Error::because(ErrorKind::Media, "error.media.empty")),
Ok(Ok(Err(failed))) if seq == 0 => Err(failed.error()),
Ok(Err(e)) => Err(disk_error(e)),
_ => Err(Error::Cut { got: tape.end, expected: None }),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn where_to_ask() {
let of = |url: &str| addresses(&Url::parse(url).unwrap()).into_iter().map(|a| a.0).collect::<Vec<_>>();
assert_eq!(of("rtsp://h:8554/a?b"), ["rtsp://h:8554/a?b"]);
assert_eq!(of("mms://h/a.wmv"), ["mmsh://h/a.wmv", "mmst://h/a.wmv"]);
assert_eq!(of("mms://h:1755/a"), ["mmst://h:1755/a", "mmsh://h:1755/a"]);
}
#[test]
fn logins_stay_off_the_arguments() {
let login = Login { user: "me@x".into(), password: "S3CRET'\n".into() };
let mut job = Job::new();
input(&mut job, "rtsp://h/it's", "rtsp,tcp", Some(&login)).unwrap();
let shown = format!("{job:?}");
let script = String::from_utf8(job.script().unwrap().to_vec()).unwrap();
assert!(script.contains(r"file 'rtsp://me%40x:S3CRET%27%0A@h/it'\''s'"), "{script}");
assert!(!shown.contains("S3CRET"), "{shown}");
}
}

View file

@ -0,0 +1,174 @@
//! The unfinished file of a stream: what arrived, in the order it arrived, with what belongs where.
//!
//! One file, so that moving, renaming and binning it is the same as for any other download.
use crate::disk::PartialFile;
use crate::http::Result;
use serde::{Deserialize, Serialize};
use std::sync::Arc;
const MAGIC: &[u8; 8] = b"MedlarS1";
const RECORD: u64 = 48;
const MARK: u32 = 0x4d64_6c52;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub(super) struct Head {
pub live: bool,
/// What it is of, to notice when the server has another one now.
pub tracks: Vec<Track>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub(super) struct Track {
pub id: String,
/// Segments. None while it grows.
pub total: Option<u64>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) struct Record {
pub track: u32,
/// Put together as they are.
pub group: u32,
pub init: bool,
pub stretch: u64,
pub seq: u64,
/// Length of the recording in it, in milliseconds.
pub ms: u32,
pub at: u64,
pub len: u64,
}
#[derive(Debug)]
pub(super) struct Tape {
pub file: Arc<PartialFile>,
pub head: Head,
pub records: Vec<Record>,
/// Where the next one goes.
pub end: u64,
}
impl Tape {
/// Whether the file is one. An empty one may become one.
pub async fn is(file: &PartialFile) -> Result<bool> {
Ok(file.size()? >= MAGIC.len() as u64 && file.read_at(MAGIC.len(), 0).await? == MAGIC)
}
pub async fn create(file: Arc<PartialFile>, head: Head) -> Result<Tape> {
let text = serde_json::to_vec(&head).expect("plain data");
let mut buf = MAGIC.to_vec();
buf.extend((text.len() as u32).to_le_bytes());
buf.extend(text);
let end = buf.len() as u64;
file.write_at(buf, end as usize, 0).await?;
Ok(Tape { file, head, records: vec![], end })
}
/// `safe` is how much of it was safe on disk. What came after may be half there: it is written over.
/// None when even the head is not whole.
pub async fn open(file: Arc<PartialFile>, safe: u64) -> Result<Option<Tape>> {
let safe = safe.min(file.size()?);
let start = MAGIC.len() as u64 + 4;
if safe < start {
return Ok(None);
}
let len = file.read_at(4, start - 4).await?;
let len = u64::from(u32::from_le_bytes(len.try_into().expect("four")));
if safe < start + len {
return Ok(None);
}
let Ok(head) = serde_json::from_slice(&file.read_at(len as usize, start).await?) else { return Ok(None) };
let mut tape = Tape { file, head, records: vec![], end: start + len };
while tape.end + RECORD <= safe {
let bytes = tape.file.read_at(RECORD as usize, tape.end).await?;
let Some(record) = Record::read(&bytes, tape.end + RECORD).filter(|r| r.at.checked_add(r.len).is_some_and(|end| end <= safe)) else { break };
tape.end = record.at + record.len;
tape.records.push(record);
}
Ok(Some(tape))
}
/// `at` and `len` are filled in.
pub async fn append(&mut self, mut record: Record, data: &[u8]) -> Result<()> {
(record.at, record.len) = (self.end + RECORD, data.len() as u64);
let mut buf = record.bytes();
buf.extend_from_slice(data);
let n = buf.len();
self.file.write_at(buf, n, self.end).await?;
self.end += n as u64;
self.records.push(record);
Ok(())
}
/// The groups of a track, each in order with what comes first at its start.
pub fn groups(&self, track: u32) -> Vec<Vec<Record>> {
let mut mine: Vec<Record> = self.records.iter().copied().filter(|r| r.track == track).collect();
mine.sort_by_key(|r| (r.group, !r.init, r.seq));
mine.dedup_by_key(|r| (r.group, r.init, r.seq));
let groups = mine.chunk_by(|a, b| a.group == b.group).map(<[Record]>::to_vec);
groups.filter(|g| g.iter().any(|r| !r.init)).collect()
}
/// Milliseconds of the track.
pub fn length(&self, track: u32) -> u64 {
self.records.iter().filter(|r| r.track == track).map(|r| u64::from(r.ms)).sum()
}
}
impl Record {
fn bytes(&self) -> Vec<u8> {
let mut b = Vec::with_capacity(RECORD as usize + self.len as usize);
for n in [MARK, self.track, self.group, u32::from(self.init), self.ms, 0] {
b.extend(n.to_le_bytes());
}
for n in [self.stretch, self.seq, self.len] {
b.extend(n.to_le_bytes());
}
b
}
fn read(b: &[u8], at: u64) -> Option<Record> {
let small = |i: usize| u32::from_le_bytes(b[i * 4..i * 4 + 4].try_into().expect("four"));
let big = |i: usize| u64::from_le_bytes(b[24 + i * 8..32 + i * 8].try_into().expect("eight"));
(small(0) == MARK).then(|| Record { track: small(1), group: small(2), init: small(3) == 1, ms: small(4), stretch: big(0), seq: big(1), at, len: big(2) })
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::HashSet;
fn record(track: u32, group: u32, init: bool, seq: u64) -> Record {
Record { track, group, init, stretch: 0, seq, ms: 500, at: 0, len: 0 }
}
#[tokio::test]
async fn goes_on_after_a_torn_end() {
let dir = tempfile::tempdir().unwrap();
let (file, name) = PartialFile::create(dir.path(), "a.mp4", &HashSet::new()).unwrap();
assert!(!Tape::is(&file).await.unwrap());
let head = Head { live: false, tracks: vec![Track { id: "v".into(), total: Some(3) }] };
let mut tape = Tape::create(Arc::new(file), head.clone()).await.unwrap();
for (r, data) in [(record(0, 1, false, 5), "two"), (record(0, 0, false, 1), "one"), (record(0, 0, true, 0), "i"), (record(1, 0, true, 0), "only")] {
tape.append(r, data.as_bytes()).await.unwrap();
}
let (whole, records) = (tape.end, tape.records.clone());
tape.append(record(0, 1, false, 6), &[7; 1000]).await.unwrap();
let end = tape.end;
drop(tape);
let file = Arc::new(PartialFile::reopen(dir.path(), &name).unwrap().unwrap());
assert!(Tape::is(&file).await.unwrap());
for safe in [whole, whole + 10, end - 1] {
let tape = Tape::open(file.clone(), safe).await.unwrap().unwrap();
assert_eq!((tape.end, &tape.records, &tape.head), (whole, &records, &head));
}
assert!(Tape::open(file.clone(), 5).await.unwrap().is_none());
let tape = Tape::open(file, end).await.unwrap().unwrap();
assert_eq!(tape.records.len(), 5);
let order: Vec<Vec<(bool, u64)>> = tape.groups(0).iter().map(|g| g.iter().map(|r| (r.init, r.seq)).collect()).collect();
assert_eq!(order, [vec![(true, 0), (false, 1)], vec![(false, 5), (false, 6)]]);
assert!(tape.groups(1).is_empty());
assert_eq!(tape.length(0), 2000);
}
}

Some files were not shown because too many files have changed in this diff Show more