This commit is contained in:
@@ -0,0 +1,6 @@
|
||||
**/.git
|
||||
**/.agents
|
||||
**/.codex
|
||||
**/target
|
||||
/media
|
||||
**/.DS_Store
|
||||
@@ -0,0 +1,45 @@
|
||||
name: Build and Publish
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- 'v*.*.*'
|
||||
|
||||
env:
|
||||
IMAGE_NAME: ultradesu/lan-play
|
||||
|
||||
jobs:
|
||||
build_docker:
|
||||
name: Build and Publish Docker Image
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v3
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Login to Docker Hub
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
|
||||
- name: Extract metadata
|
||||
id: meta
|
||||
run: |
|
||||
VERSION=$(grep '^version' Cargo.toml | head -1 | cut -d'"' -f2)
|
||||
TAG_NAME=${GITHUB_REF#refs/tags/}
|
||||
echo "docker_tags=${IMAGE_NAME}:${TAG_NAME},${IMAGE_NAME}:${VERSION},${IMAGE_NAME}:latest" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Build and push Docker image
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: .
|
||||
platforms: linux/amd64,linux/arm64
|
||||
push: true
|
||||
tags: ${{ steps.meta.outputs.docker_tags }}
|
||||
cache-from: type=registry,ref=${{ env.IMAGE_NAME }}:buildcache
|
||||
cache-to: type=registry,ref=${{ env.IMAGE_NAME }}:buildcache,mode=max
|
||||
@@ -0,0 +1 @@
|
||||
/target
|
||||
Generated
+1017
File diff suppressed because it is too large
Load Diff
+18
@@ -0,0 +1,18 @@
|
||||
[package]
|
||||
name = "lan-play"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
anyhow = "1"
|
||||
axum = "0.8"
|
||||
clap = { version = "4", features = ["derive"] }
|
||||
mime_guess = "2"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
tempfile = "3"
|
||||
tokio = { version = "1", features = ["full"] }
|
||||
tokio-util = { version = "0.7", features = ["io"] }
|
||||
tracing = "0.1"
|
||||
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||
uuid = { version = "1", features = ["v4"] }
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
FROM rust:1-bookworm AS builder
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY Cargo.toml Cargo.lock ./
|
||||
COPY src ./src
|
||||
COPY web ./web
|
||||
|
||||
RUN cargo build --release --locked
|
||||
|
||||
FROM debian:bookworm-slim
|
||||
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends ca-certificates ffmpeg \
|
||||
&& useradd --system --uid 10001 --create-home lanplay \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
COPY --from=builder /app/target/release/lan-play /usr/local/bin/lan-play
|
||||
|
||||
USER lanplay
|
||||
WORKDIR /home/lanplay
|
||||
|
||||
EXPOSE 8080
|
||||
ENTRYPOINT ["lan-play"]
|
||||
CMD ["/media", "--bind", "0.0.0.0:8080"]
|
||||
@@ -0,0 +1,43 @@
|
||||
# lan-play
|
||||
|
||||
A small self-hosted web player for local video libraries.
|
||||
|
||||
lan-play makes folders with movies, shows, and anime easy to watch on TVs and
|
||||
other devices with a web browser. Point it at a media directory, open the web
|
||||
interface, and play files without setting up a database or importing a library.
|
||||
|
||||
## Features
|
||||
|
||||
- Folder-based media browser with animated previews
|
||||
- Live remuxing and transcoding to browser-compatible MPEG-DASH
|
||||
- Multiple audio track selection
|
||||
- Embedded and external ASS, SSA, SRT, and WebVTT subtitles
|
||||
- Automatic subtitle discovery in nearby folders
|
||||
- Fullscreen TV-friendly interface with episode navigation
|
||||
- No database, accounts, or library indexing
|
||||
|
||||
## Docker
|
||||
|
||||
```bash
|
||||
docker run --rm \
|
||||
-p 8080:8080 \
|
||||
-v /path/to/videos:/media:ro \
|
||||
ultradesu/lan-play:latest
|
||||
```
|
||||
|
||||
Open `http://HOST:8080` on your TV or another device on the same network.
|
||||
|
||||
## Run from source
|
||||
|
||||
Requires Rust, `ffmpeg`, and `ffprobe`.
|
||||
|
||||
```bash
|
||||
cargo run --release -- /path/to/videos
|
||||
```
|
||||
|
||||
Use `--bind 127.0.0.1:8080` when placing lan-play behind a reverse proxy.
|
||||
|
||||
## Notes
|
||||
|
||||
lan-play is intended for trusted local networks. It does not provide
|
||||
authentication and should not be exposed directly to the public internet.
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::{
|
||||
Router,
|
||||
routing::{delete, get, post},
|
||||
};
|
||||
use tokio::sync::Semaphore;
|
||||
|
||||
use crate::{config::Config, diagnostics, media, media::dash::DashManager, web};
|
||||
|
||||
pub struct AppState {
|
||||
pub config: Config,
|
||||
pub dash: DashManager,
|
||||
pub preview_jobs: Semaphore,
|
||||
}
|
||||
|
||||
impl AppState {
|
||||
pub fn new(config: Config) -> anyhow::Result<Self> {
|
||||
Ok(Self {
|
||||
config,
|
||||
dash: DashManager::new()?,
|
||||
preview_jobs: Semaphore::new(2),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn router(state: Arc<AppState>) -> Router {
|
||||
Router::new()
|
||||
.route("/", get(web::index))
|
||||
.route("/alpine.min.js", get(web::alpine))
|
||||
.route("/dash.all.min.js", get(web::dash))
|
||||
.route("/dash.all.min.js.map", get(web::dash_source_map))
|
||||
.route("/controlbar.min.js", get(web::controlbar_javascript))
|
||||
.route("/controlbar.css", get(web::controlbar_styles))
|
||||
.route("/bootstrap-icons.min.css", get(web::bootstrap_icon_styles))
|
||||
.route(
|
||||
"/fonts/bootstrap-icons.woff2",
|
||||
get(web::bootstrap_icon_font),
|
||||
)
|
||||
.route("/js/api.js", get(web::api_javascript))
|
||||
.route("/js/library.js", get(web::library_javascript))
|
||||
.route("/js/location.js", get(web::location_javascript))
|
||||
.route("/js/preferences.js", get(web::preferences_javascript))
|
||||
.route("/js/player.js", get(web::player_javascript))
|
||||
.route("/styles.css", get(web::styles))
|
||||
.route("/api/info", get(diagnostics::info))
|
||||
.route("/api/browse", get(media::browse::browse))
|
||||
.route("/api/probe", get(media::probe::probe))
|
||||
.route("/api/preview", get(media::preview::sprite))
|
||||
.route("/api/stream", get(media::stream::stream))
|
||||
.route("/api/subtitles", get(media::subtitles::list))
|
||||
.route("/api/subtitles/{index}", get(media::subtitles::extract))
|
||||
.route(
|
||||
"/api/subtitles/external/{id}",
|
||||
get(media::subtitles::extract_external),
|
||||
)
|
||||
.route("/api/dash", post(media::dash::start))
|
||||
.route("/api/dash/{session}", delete(media::dash::stop))
|
||||
.route("/api/dash/{session}/{asset}", get(media::dash::asset))
|
||||
.with_state(state)
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
use std::{net::SocketAddr, path::PathBuf};
|
||||
|
||||
use anyhow::{Context, ensure};
|
||||
use clap::Parser;
|
||||
|
||||
#[derive(Debug, Clone, Parser)]
|
||||
#[command(version, about = "A small LAN media browser for smart TVs")]
|
||||
pub struct Config {
|
||||
/// Directory exposed as the media library.
|
||||
pub media_root: PathBuf,
|
||||
|
||||
/// HTTP listen address.
|
||||
#[arg(long, default_value = "0.0.0.0:8080")]
|
||||
pub bind: SocketAddr,
|
||||
|
||||
/// ffprobe executable.
|
||||
#[arg(long, default_value = "ffprobe")]
|
||||
pub ffprobe: PathBuf,
|
||||
|
||||
/// ffmpeg executable used for DASH packaging and transcoding.
|
||||
#[arg(long, default_value = "ffmpeg")]
|
||||
pub ffmpeg: PathBuf,
|
||||
}
|
||||
|
||||
impl Config {
|
||||
pub fn prepare(mut self) -> anyhow::Result<Self> {
|
||||
ensure!(self.media_root.is_dir(), "media root is not a directory");
|
||||
self.media_root = self
|
||||
.media_root
|
||||
.canonicalize()
|
||||
.context("failed to resolve media root")?;
|
||||
Ok(self)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::{Json, extract::State};
|
||||
use serde::Serialize;
|
||||
use tokio::process::Command;
|
||||
|
||||
use crate::app::AppState;
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct Diagnostics {
|
||||
application: &'static str,
|
||||
version: &'static str,
|
||||
build: &'static str,
|
||||
platform: String,
|
||||
ffmpeg: ToolInfo,
|
||||
ffprobe: ToolInfo,
|
||||
media_root: String,
|
||||
bind: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct ToolInfo {
|
||||
path: String,
|
||||
version: String,
|
||||
}
|
||||
|
||||
pub async fn info(State(state): State<Arc<AppState>>) -> Json<Diagnostics> {
|
||||
let (ffmpeg, ffprobe) = tokio::join!(
|
||||
tool_info(&state.config.ffmpeg),
|
||||
tool_info(&state.config.ffprobe)
|
||||
);
|
||||
Json(Diagnostics {
|
||||
application: env!("CARGO_PKG_NAME"),
|
||||
version: env!("CARGO_PKG_VERSION"),
|
||||
build: if cfg!(debug_assertions) {
|
||||
"debug"
|
||||
} else {
|
||||
"release"
|
||||
},
|
||||
platform: format!("{} / {}", std::env::consts::OS, std::env::consts::ARCH),
|
||||
ffmpeg,
|
||||
ffprobe,
|
||||
media_root: state.config.media_root.display().to_string(),
|
||||
bind: state.config.bind.to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
async fn tool_info(path: &std::path::Path) -> ToolInfo {
|
||||
let version = match Command::new(path).arg("-version").output().await {
|
||||
Ok(output) if output.status.success() => first_line(&output.stdout),
|
||||
Ok(output) => format!("Unavailable ({})", output.status),
|
||||
Err(error) => format!("Unavailable ({error})"),
|
||||
};
|
||||
ToolInfo {
|
||||
path: path.display().to_string(),
|
||||
version,
|
||||
}
|
||||
}
|
||||
|
||||
fn first_line(output: &[u8]) -> String {
|
||||
String::from_utf8_lossy(output)
|
||||
.lines()
|
||||
.next()
|
||||
.unwrap_or("Unknown")
|
||||
.trim()
|
||||
.to_owned()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::first_line;
|
||||
|
||||
#[test]
|
||||
fn keeps_only_the_tool_version_line() {
|
||||
assert_eq!(
|
||||
first_line(b"ffmpeg version 7.1\nconfiguration: test\n"),
|
||||
"ffmpeg version 7.1"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
use axum::{
|
||||
Json,
|
||||
http::StatusCode,
|
||||
response::{IntoResponse, Response},
|
||||
};
|
||||
use serde_json::json;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct AppError {
|
||||
status: StatusCode,
|
||||
message: String,
|
||||
}
|
||||
|
||||
impl AppError {
|
||||
pub fn bad_request(message: impl Into<String>) -> Self {
|
||||
Self {
|
||||
status: StatusCode::BAD_REQUEST,
|
||||
message: message.into(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn not_found(message: impl Into<String>) -> Self {
|
||||
Self {
|
||||
status: StatusCode::NOT_FOUND,
|
||||
message: message.into(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn internal(error: impl std::fmt::Display) -> Self {
|
||||
tracing::error!(%error, "request failed");
|
||||
Self {
|
||||
status: StatusCode::INTERNAL_SERVER_ERROR,
|
||||
message: "internal server error".into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoResponse for AppError {
|
||||
fn into_response(self) -> Response {
|
||||
(self.status, Json(json!({ "error": self.message }))).into_response()
|
||||
}
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
mod app;
|
||||
mod config;
|
||||
mod diagnostics;
|
||||
mod error;
|
||||
mod media;
|
||||
mod web;
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use clap::Parser;
|
||||
use config::Config;
|
||||
use tracing::info;
|
||||
|
||||
use crate::app::AppState;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
tracing_subscriber::fmt()
|
||||
.with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
|
||||
.init();
|
||||
|
||||
let config = Config::parse().prepare()?;
|
||||
let listener = tokio::net::TcpListener::bind(config.bind).await?;
|
||||
info!(address = %config.bind, media_root = %config.media_root.display(), "lan-play started");
|
||||
let state = Arc::new(AppState::new(config)?);
|
||||
|
||||
axum::serve(listener, app::router(state)).await?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
use std::{path::Path, sync::Arc};
|
||||
|
||||
use axum::{
|
||||
Json,
|
||||
extract::{Query, State},
|
||||
};
|
||||
use serde::Serialize;
|
||||
use tokio::fs;
|
||||
|
||||
use crate::{
|
||||
app::AppState,
|
||||
error::AppError,
|
||||
media::{PathQuery, path},
|
||||
};
|
||||
|
||||
const MEDIA_EXTENSIONS: &[&str] = &["mkv", "mp4", "m4v", "avi", "mov", "webm"];
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct Entry {
|
||||
name: String,
|
||||
path: String,
|
||||
kind: &'static str,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct Directory {
|
||||
path: String,
|
||||
parent: Option<String>,
|
||||
entries: Vec<Entry>,
|
||||
}
|
||||
|
||||
pub async fn browse(
|
||||
State(state): State<Arc<AppState>>,
|
||||
Query(query): Query<PathQuery>,
|
||||
) -> Result<Json<Directory>, AppError> {
|
||||
let config = &state.config;
|
||||
let directory = path::resolve(config, &query.path)?;
|
||||
if !directory.is_dir() {
|
||||
return Err(AppError::bad_request("path is not a directory"));
|
||||
}
|
||||
|
||||
let mut reader = fs::read_dir(&directory).await.map_err(AppError::internal)?;
|
||||
let mut entries = Vec::new();
|
||||
while let Some(item) = reader.next_entry().await.map_err(AppError::internal)? {
|
||||
let file_type = item.file_type().await.map_err(AppError::internal)?;
|
||||
let item_path = item.path();
|
||||
let kind = if file_type.is_dir() {
|
||||
"directory"
|
||||
} else if file_type.is_file() && is_media(&item_path) {
|
||||
"media"
|
||||
} else {
|
||||
continue;
|
||||
};
|
||||
entries.push(Entry {
|
||||
name: item.file_name().to_string_lossy().into_owned(),
|
||||
path: path::relative(config, &item_path)?,
|
||||
kind,
|
||||
});
|
||||
}
|
||||
entries.sort_by_key(|entry| (entry.kind != "directory", entry.name.to_lowercase()));
|
||||
|
||||
let current = path::relative(config, &directory)?;
|
||||
let parent = directory
|
||||
.parent()
|
||||
.filter(|parent| parent.starts_with(&config.media_root))
|
||||
.and_then(|parent| path::relative(config, parent).ok());
|
||||
Ok(Json(Directory {
|
||||
path: current,
|
||||
parent,
|
||||
entries,
|
||||
}))
|
||||
}
|
||||
|
||||
fn is_media(path: &Path) -> bool {
|
||||
path.extension()
|
||||
.and_then(|value| value.to_str())
|
||||
.is_some_and(|value| MEDIA_EXTENSIONS.contains(&value.to_ascii_lowercase().as_str()))
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
mod process;
|
||||
mod session;
|
||||
|
||||
use std::{collections::HashMap, path::PathBuf, sync::Arc};
|
||||
|
||||
use axum::{
|
||||
Json,
|
||||
body::Body,
|
||||
extract::{Path, Query, State},
|
||||
http::{StatusCode, header},
|
||||
response::{IntoResponse, Response},
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tempfile::TempDir;
|
||||
use tokio::{fs, sync::Mutex};
|
||||
|
||||
use crate::{
|
||||
app::AppState,
|
||||
error::AppError,
|
||||
media::{path, playback},
|
||||
};
|
||||
|
||||
use self::session::DashSession;
|
||||
|
||||
pub struct DashManager {
|
||||
_root: TempDir,
|
||||
root_path: PathBuf,
|
||||
sessions: Mutex<HashMap<String, Arc<DashSession>>>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct StartResponse {
|
||||
session_id: String,
|
||||
manifest_url: String,
|
||||
duration_seconds: Option<f64>,
|
||||
start_seconds: f64,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct StartQuery {
|
||||
path: String,
|
||||
#[serde(default)]
|
||||
start: f64,
|
||||
}
|
||||
|
||||
impl DashManager {
|
||||
pub fn new() -> anyhow::Result<Self> {
|
||||
let root = tempfile::Builder::new()
|
||||
.prefix("lan-play-dash-")
|
||||
.tempdir()?;
|
||||
Ok(Self {
|
||||
root_path: root.path().to_owned(),
|
||||
_root: root,
|
||||
sessions: Mutex::new(HashMap::new()),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn start(
|
||||
State(state): State<Arc<AppState>>,
|
||||
Query(query): Query<StartQuery>,
|
||||
) -> Result<Json<StartResponse>, AppError> {
|
||||
if !query.start.is_finite() || query.start < 0.0 {
|
||||
return Err(AppError::bad_request("invalid playback start position"));
|
||||
}
|
||||
let media = path::resolve(&state.config, &query.path)?;
|
||||
if !media.is_file() {
|
||||
return Err(AppError::bad_request("path is not a media file"));
|
||||
}
|
||||
|
||||
let plan = playback::plan(&state.config, &media).await?;
|
||||
if plan
|
||||
.duration_seconds
|
||||
.is_some_and(|duration| query.start >= duration)
|
||||
{
|
||||
return Err(AppError::bad_request(
|
||||
"playback start is beyond the file duration",
|
||||
));
|
||||
}
|
||||
let duration_seconds = plan.duration_seconds;
|
||||
let session = DashSession::start(
|
||||
&state.config.ffmpeg,
|
||||
&state.dash.root_path,
|
||||
&media,
|
||||
&plan,
|
||||
query.start,
|
||||
)
|
||||
.await?;
|
||||
let session_id = session.id().to_owned();
|
||||
state
|
||||
.dash
|
||||
.sessions
|
||||
.lock()
|
||||
.await
|
||||
.insert(session_id.clone(), Arc::new(session));
|
||||
|
||||
Ok(Json(StartResponse {
|
||||
manifest_url: format!("/api/dash/{session_id}/manifest.mpd"),
|
||||
session_id,
|
||||
duration_seconds,
|
||||
start_seconds: query.start,
|
||||
}))
|
||||
}
|
||||
|
||||
pub async fn asset(
|
||||
State(state): State<Arc<AppState>>,
|
||||
Path((session_id, asset)): Path<(String, String)>,
|
||||
) -> Result<Response, AppError> {
|
||||
if !session::valid_asset_name(&asset) {
|
||||
return Err(AppError::bad_request("invalid DASH asset name"));
|
||||
}
|
||||
let session = state
|
||||
.dash
|
||||
.sessions
|
||||
.lock()
|
||||
.await
|
||||
.get(&session_id)
|
||||
.cloned()
|
||||
.ok_or_else(|| AppError::not_found("DASH session not found"))?;
|
||||
let file = session.asset_path(&asset);
|
||||
let bytes = fs::read(file)
|
||||
.await
|
||||
.map_err(|_| AppError::not_found("DASH asset not ready"))?;
|
||||
let content_type = asset_content_type(&asset);
|
||||
Ok((
|
||||
StatusCode::OK,
|
||||
[
|
||||
(header::CONTENT_TYPE, content_type),
|
||||
(header::CACHE_CONTROL, "no-store"),
|
||||
],
|
||||
Body::from(bytes),
|
||||
)
|
||||
.into_response())
|
||||
}
|
||||
|
||||
fn asset_content_type(asset: &str) -> &'static str {
|
||||
if asset.ends_with(".mpd") {
|
||||
"application/dash+xml"
|
||||
} else if dash_stream_index(asset).is_some_and(|stream| stream > 0) {
|
||||
"audio/iso.segment"
|
||||
} else if asset.ends_with(".m4s") || asset.ends_with(".mp4") {
|
||||
"video/iso.segment"
|
||||
} else {
|
||||
"application/octet-stream"
|
||||
}
|
||||
}
|
||||
|
||||
fn dash_stream_index(asset: &str) -> Option<usize> {
|
||||
let start = asset.find("stream")? + "stream".len();
|
||||
let digits: String = asset[start..]
|
||||
.chars()
|
||||
.take_while(|character| character.is_ascii_digit())
|
||||
.collect();
|
||||
digits.parse().ok()
|
||||
}
|
||||
|
||||
pub async fn stop(
|
||||
State(state): State<Arc<AppState>>,
|
||||
Path(session_id): Path<String>,
|
||||
) -> Result<StatusCode, AppError> {
|
||||
let session = state
|
||||
.dash
|
||||
.sessions
|
||||
.lock()
|
||||
.await
|
||||
.remove(&session_id)
|
||||
.ok_or_else(|| AppError::not_found("DASH session not found"))?;
|
||||
session.stop().await;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::asset_content_type;
|
||||
|
||||
#[test]
|
||||
fn uses_media_specific_content_types() {
|
||||
assert_eq!(asset_content_type("manifest.mpd"), "application/dash+xml");
|
||||
assert_eq!(asset_content_type("init-stream0.m4s"), "video/iso.segment");
|
||||
assert_eq!(
|
||||
asset_content_type("chunk-stream0-00001.m4s"),
|
||||
"video/iso.segment"
|
||||
);
|
||||
assert_eq!(asset_content_type("init-stream1.m4s"), "audio/iso.segment");
|
||||
assert_eq!(
|
||||
asset_content_type("chunk-stream1-00001.m4s"),
|
||||
"audio/iso.segment"
|
||||
);
|
||||
assert_eq!(asset_content_type("init-stream2.m4s"), "audio/iso.segment");
|
||||
assert_eq!(
|
||||
asset_content_type("chunk-stream7-00001.m4s"),
|
||||
"audio/iso.segment"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
use std::{fs::OpenOptions, path::Path, process::Stdio};
|
||||
|
||||
use tokio::process::{Child, Command};
|
||||
|
||||
use crate::error::AppError;
|
||||
use crate::media::playback::PlaybackPlan;
|
||||
|
||||
const SEEK_PREROLL_SECONDS: f64 = 3.0;
|
||||
|
||||
pub fn spawn(
|
||||
ffmpeg: &Path,
|
||||
media: &Path,
|
||||
directory: &Path,
|
||||
plan: &PlaybackPlan,
|
||||
start_seconds: f64,
|
||||
) -> Result<Child, AppError> {
|
||||
let log = OpenOptions::new()
|
||||
.create(true)
|
||||
.truncate(true)
|
||||
.write(true)
|
||||
.open(directory.join("ffmpeg.log"))
|
||||
.map_err(AppError::internal)?;
|
||||
let mut command = Command::new(ffmpeg);
|
||||
command.current_dir(directory).args(["-v", "warning"]);
|
||||
let (input_seek, output_trim) = seek_offsets(start_seconds);
|
||||
if input_seek > 0.0 {
|
||||
command.args(["-ss", &format!("{input_seek:.3}")]);
|
||||
}
|
||||
command
|
||||
// Build a small lead over playback so transient encoder, disk or network
|
||||
// jitter does not leave the player waiting at the live edge.
|
||||
.args(["-readrate", "1.15"]);
|
||||
if output_trim > 0.0 {
|
||||
command.args(["-readrate_initial_burst", &format!("{output_trim:.3}")]);
|
||||
}
|
||||
command.args(["-i"]).arg(media);
|
||||
if output_trim > 0.0 {
|
||||
command.args(["-ss", &format!("{output_trim:.3}")]);
|
||||
}
|
||||
command
|
||||
.args(plan.ffmpeg_output_args())
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::from(log))
|
||||
.kill_on_drop(true)
|
||||
.spawn()
|
||||
.map_err(AppError::internal)
|
||||
}
|
||||
|
||||
fn seek_offsets(start_seconds: f64) -> (f64, f64) {
|
||||
let input_seek = (start_seconds - SEEK_PREROLL_SECONDS).max(0.0);
|
||||
(input_seek, start_seconds - input_seek)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::seek_offsets;
|
||||
|
||||
#[test]
|
||||
fn seek_keeps_a_short_accurate_preroll() {
|
||||
assert_eq!(seek_offsets(0.0), (0.0, 0.0));
|
||||
assert_eq!(seek_offsets(2.0), (0.0, 2.0));
|
||||
assert_eq!(seek_offsets(100.0), (97.0, 3.0));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
use std::{
|
||||
path::{Component, Path, PathBuf},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use tokio::{fs, process::Child, sync::Mutex, time};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::{error::AppError, media::playback::PlaybackPlan};
|
||||
|
||||
use super::process;
|
||||
|
||||
pub struct DashSession {
|
||||
id: String,
|
||||
directory: PathBuf,
|
||||
process: Mutex<Option<Child>>,
|
||||
}
|
||||
|
||||
impl DashSession {
|
||||
pub async fn start(
|
||||
ffmpeg: &Path,
|
||||
root: &Path,
|
||||
media: &Path,
|
||||
plan: &PlaybackPlan,
|
||||
start_seconds: f64,
|
||||
) -> Result<Self, AppError> {
|
||||
let id = Uuid::new_v4().simple().to_string();
|
||||
let directory = root.join(&id);
|
||||
fs::create_dir(&directory)
|
||||
.await
|
||||
.map_err(AppError::internal)?;
|
||||
let mut child = match process::spawn(ffmpeg, media, &directory, plan, start_seconds) {
|
||||
Ok(child) => child,
|
||||
Err(error) => {
|
||||
fs::remove_dir_all(&directory).await.ok();
|
||||
return Err(error);
|
||||
}
|
||||
};
|
||||
wait_until_ready(&mut child, &directory, plan.audio_count()).await?;
|
||||
Ok(Self {
|
||||
id,
|
||||
directory,
|
||||
process: Mutex::new(Some(child)),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn id(&self) -> &str {
|
||||
&self.id
|
||||
}
|
||||
|
||||
pub fn asset_path(&self, name: &str) -> PathBuf {
|
||||
self.directory.join(name)
|
||||
}
|
||||
|
||||
pub async fn stop(&self) {
|
||||
if let Some(mut child) = self.process.lock().await.take() {
|
||||
if child.try_wait().ok().flatten().is_none() {
|
||||
child.start_kill().ok();
|
||||
}
|
||||
child.wait().await.ok();
|
||||
}
|
||||
fs::remove_dir_all(&self.directory).await.ok();
|
||||
}
|
||||
}
|
||||
|
||||
async fn wait_until_ready(
|
||||
child: &mut Child,
|
||||
directory: &Path,
|
||||
audio_count: usize,
|
||||
) -> Result<(), AppError> {
|
||||
for _ in 0..1800 {
|
||||
if ready(directory, audio_count).await {
|
||||
return Ok(());
|
||||
}
|
||||
if child.try_wait().map_err(AppError::internal)?.is_some() {
|
||||
return Err(startup_error(directory, "ffmpeg stopped before DASH became ready").await);
|
||||
}
|
||||
time::sleep(Duration::from_millis(50)).await;
|
||||
}
|
||||
child.start_kill().ok();
|
||||
child.wait().await.ok();
|
||||
Err(startup_error(directory, "timed out waiting for live DASH segments").await)
|
||||
}
|
||||
|
||||
async fn ready(directory: &Path, audio_count: usize) -> bool {
|
||||
let manifest = match fs::read_to_string(directory.join("manifest.mpd")).await {
|
||||
Ok(value) => value,
|
||||
Err(_) => return false,
|
||||
};
|
||||
if !manifest.contains("type=\"dynamic\"") && !manifest.contains("type=\"static\"") {
|
||||
return false;
|
||||
}
|
||||
if !stream_ready(directory, 0).await {
|
||||
return false;
|
||||
}
|
||||
for stream in 1..=audio_count {
|
||||
if !stream_ready(directory, stream).await {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
async fn stream_ready(directory: &Path, stream: usize) -> bool {
|
||||
directory.join(format!("init-stream{stream}.m4s")).is_file()
|
||||
&& has_segment(directory, stream).await
|
||||
}
|
||||
|
||||
async fn has_segment(directory: &Path, stream: usize) -> bool {
|
||||
let prefix = format!("chunk-stream{stream}-");
|
||||
let mut entries = match fs::read_dir(directory).await {
|
||||
Ok(value) => value,
|
||||
Err(_) => return false,
|
||||
};
|
||||
while let Ok(Some(entry)) = entries.next_entry().await {
|
||||
let name = entry.file_name();
|
||||
let name = name.to_string_lossy();
|
||||
if name.starts_with(&prefix) && name.ends_with(".m4s") {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
async fn startup_error(directory: &Path, fallback: &str) -> AppError {
|
||||
let log = fs::read_to_string(directory.join("ffmpeg.log"))
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
fs::remove_dir_all(directory).await.ok();
|
||||
let details = log.trim();
|
||||
AppError::bad_request(if details.is_empty() {
|
||||
fallback.to_owned()
|
||||
} else {
|
||||
format!("{fallback}: {details}")
|
||||
})
|
||||
}
|
||||
|
||||
pub fn valid_asset_name(name: &str) -> bool {
|
||||
let mut components = Path::new(name).components();
|
||||
!name.is_empty()
|
||||
&& matches!(components.next(), Some(Component::Normal(_)))
|
||||
&& components.next().is_none()
|
||||
&& matches!(
|
||||
Path::new(name).extension().and_then(|value| value.to_str()),
|
||||
Some("mpd" | "m4s" | "mp4")
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::valid_asset_name;
|
||||
|
||||
#[test]
|
||||
fn accepts_flat_dash_assets_only() {
|
||||
assert!(valid_asset_name("manifest.mpd"));
|
||||
assert!(valid_asset_name("chunk-stream0-00001.m4s"));
|
||||
assert!(!valid_asset_name("../secret.mp4"));
|
||||
assert!(!valid_asset_name("nested/chunk.m4s"));
|
||||
assert!(!valid_asset_name("notes.txt"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
pub mod browse;
|
||||
pub mod dash;
|
||||
pub mod path;
|
||||
pub mod playback;
|
||||
pub mod preview;
|
||||
pub mod probe;
|
||||
pub mod stream;
|
||||
pub mod subtitles;
|
||||
|
||||
use serde::Deserialize;
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct PathQuery {
|
||||
#[serde(default)]
|
||||
pub path: String,
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
|
||||
use crate::{config::Config, error::AppError};
|
||||
|
||||
pub fn resolve(config: &Config, relative: &str) -> Result<PathBuf, AppError> {
|
||||
let relative = Path::new(relative);
|
||||
if relative.is_absolute()
|
||||
|| relative
|
||||
.components()
|
||||
.any(|part| !matches!(part, Component::Normal(_)))
|
||||
{
|
||||
return Err(AppError::bad_request("invalid media path"));
|
||||
}
|
||||
|
||||
let candidate = config.media_root.join(relative);
|
||||
let canonical = candidate
|
||||
.canonicalize()
|
||||
.map_err(|_| AppError::not_found("media path not found"))?;
|
||||
if !canonical.starts_with(&config.media_root) {
|
||||
return Err(AppError::bad_request("media path escapes the library"));
|
||||
}
|
||||
Ok(canonical)
|
||||
}
|
||||
|
||||
pub fn relative(config: &Config, absolute: &Path) -> Result<String, AppError> {
|
||||
absolute
|
||||
.strip_prefix(&config.media_root)
|
||||
.map(|path| path.to_string_lossy().replace('\\', "/"))
|
||||
.map_err(AppError::internal)
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum VideoPipeline {
|
||||
Copy,
|
||||
Encode(VideoEncoder),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum VideoEncoder {
|
||||
Libx264,
|
||||
}
|
||||
|
||||
impl VideoPipeline {
|
||||
pub fn ffmpeg_args(self, segment_seconds: u8) -> Vec<String> {
|
||||
match self {
|
||||
Self::Copy => vec!["-c:v".into(), "copy".into()],
|
||||
Self::Encode(encoder) => encoder.ffmpeg_args(segment_seconds),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl VideoEncoder {
|
||||
pub fn portable_software() -> Self {
|
||||
Self::Libx264
|
||||
}
|
||||
|
||||
fn ffmpeg_args(self, segment_seconds: u8) -> Vec<String> {
|
||||
match self {
|
||||
Self::Libx264 => vec![
|
||||
"-c:v".into(),
|
||||
"libx264".into(),
|
||||
"-preset".into(),
|
||||
"veryfast".into(),
|
||||
"-crf".into(),
|
||||
"20".into(),
|
||||
"-vf".into(),
|
||||
"scale=trunc(iw/2)*2:trunc(ih/2)*2,format=yuv420p".into(),
|
||||
"-force_key_frames".into(),
|
||||
format!("expr:gte(t,n_forced*{segment_seconds})"),
|
||||
"-sc_threshold".into(),
|
||||
"0".into(),
|
||||
],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{VideoEncoder, VideoPipeline};
|
||||
|
||||
#[test]
|
||||
fn libx264_profile_is_browser_compatible_and_segment_aligned() {
|
||||
let args = VideoPipeline::Encode(VideoEncoder::Libx264).ffmpeg_args(2);
|
||||
assert!(args.windows(2).any(|pair| pair == ["-c:v", "libx264"]));
|
||||
assert!(args.windows(2).any(|pair| pair == ["-crf", "20"]));
|
||||
assert!(
|
||||
args.windows(2)
|
||||
.any(|pair| { pair == ["-force_key_frames", "expr:gte(t,n_forced*2)"] })
|
||||
);
|
||||
assert!(args.iter().any(|arg| arg.contains("format=yuv420p")));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
mod encoder;
|
||||
mod planner;
|
||||
mod profile;
|
||||
|
||||
pub use encoder::{VideoEncoder, VideoPipeline};
|
||||
pub use planner::plan;
|
||||
pub use profile::PlaybackPlan;
|
||||
@@ -0,0 +1,60 @@
|
||||
use std::path::Path;
|
||||
|
||||
use crate::{config::Config, error::AppError, media::probe};
|
||||
|
||||
use super::{PlaybackPlan, VideoEncoder, VideoPipeline};
|
||||
|
||||
pub async fn plan(config: &Config, media: &Path) -> Result<PlaybackPlan, AppError> {
|
||||
let metadata = probe::run(config, media).await?;
|
||||
let video = metadata
|
||||
.streams
|
||||
.iter()
|
||||
.find(|stream| stream.codec_type.as_deref() == Some("video"))
|
||||
.ok_or_else(|| AppError::bad_request("media file has no video stream"))?;
|
||||
let video_pipeline =
|
||||
select_video_pipeline(video.codec_name.as_deref(), video.pix_fmt.as_deref());
|
||||
let audio_streams = metadata
|
||||
.streams
|
||||
.iter()
|
||||
.filter(|stream| stream.codec_type.as_deref() == Some("audio"))
|
||||
.map(|stream| stream.index)
|
||||
.collect();
|
||||
let duration_seconds = metadata
|
||||
.format
|
||||
.and_then(|format| format.duration)
|
||||
.and_then(|duration| duration.parse().ok());
|
||||
Ok(PlaybackPlan::live_dash(
|
||||
video_pipeline,
|
||||
audio_streams,
|
||||
duration_seconds,
|
||||
))
|
||||
}
|
||||
|
||||
fn select_video_pipeline(codec: Option<&str>, pixel_format: Option<&str>) -> VideoPipeline {
|
||||
if codec == Some("h264") && matches!(pixel_format, Some("yuv420p" | "yuvj420p")) {
|
||||
VideoPipeline::Copy
|
||||
} else {
|
||||
VideoPipeline::Encode(VideoEncoder::portable_software())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{VideoEncoder, VideoPipeline, select_video_pipeline};
|
||||
|
||||
#[test]
|
||||
fn copies_only_browser_compatible_h264() {
|
||||
assert_eq!(
|
||||
select_video_pipeline(Some("h264"), Some("yuv420p")),
|
||||
VideoPipeline::Copy
|
||||
);
|
||||
assert_eq!(
|
||||
select_video_pipeline(Some("mpeg4"), Some("yuv420p")),
|
||||
VideoPipeline::Encode(VideoEncoder::Libx264)
|
||||
);
|
||||
assert_eq!(
|
||||
select_video_pipeline(Some("h264"), Some("yuv420p10le")),
|
||||
VideoPipeline::Encode(VideoEncoder::Libx264)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
use super::VideoPipeline;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct PlaybackPlan {
|
||||
pub video_pipeline: VideoPipeline,
|
||||
pub audio_streams: Vec<u32>,
|
||||
pub duration_seconds: Option<f64>,
|
||||
pub segment_seconds: u8,
|
||||
}
|
||||
|
||||
impl PlaybackPlan {
|
||||
pub fn live_dash(
|
||||
video_pipeline: VideoPipeline,
|
||||
audio_streams: Vec<u32>,
|
||||
duration_seconds: Option<f64>,
|
||||
) -> Self {
|
||||
Self {
|
||||
video_pipeline,
|
||||
audio_streams,
|
||||
duration_seconds,
|
||||
segment_seconds: 2,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn audio_count(&self) -> usize {
|
||||
self.audio_streams.len()
|
||||
}
|
||||
|
||||
pub fn ffmpeg_output_args(&self) -> Vec<String> {
|
||||
let mut args = vec!["-map".into(), "0:v:0".into()];
|
||||
args.extend(self.video_pipeline.ffmpeg_args(self.segment_seconds));
|
||||
for stream in &self.audio_streams {
|
||||
args.extend(["-map".into(), format!("0:{stream}")]);
|
||||
}
|
||||
if !self.audio_streams.is_empty() {
|
||||
args.extend([
|
||||
"-c:a".into(),
|
||||
"aac".into(),
|
||||
"-profile:a".into(),
|
||||
"aac_low".into(),
|
||||
"-b:a".into(),
|
||||
"192k".into(),
|
||||
"-ac".into(),
|
||||
"2".into(),
|
||||
]);
|
||||
}
|
||||
let mut adaptation_sets = vec!["id=0,streams=0".to_owned()];
|
||||
adaptation_sets.extend(
|
||||
(1..=self.audio_streams.len()).map(|output| format!("id={output},streams={output}")),
|
||||
);
|
||||
args.extend([
|
||||
"-sn".into(),
|
||||
"-f".into(),
|
||||
"dash".into(),
|
||||
"-seg_duration".into(),
|
||||
self.segment_seconds.to_string(),
|
||||
"-update_period".into(),
|
||||
"1".into(),
|
||||
"-use_template".into(),
|
||||
"1".into(),
|
||||
"-use_timeline".into(),
|
||||
"1".into(),
|
||||
"-window_size".into(),
|
||||
"0".into(),
|
||||
"-extra_window_size".into(),
|
||||
"0".into(),
|
||||
"-adaptation_sets".into(),
|
||||
adaptation_sets.join(" "),
|
||||
"manifest.mpd".into(),
|
||||
]);
|
||||
args
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{PlaybackPlan, VideoPipeline};
|
||||
|
||||
#[test]
|
||||
fn live_profile_copies_video_and_encodes_audio_to_aac() {
|
||||
let args = PlaybackPlan::live_dash(VideoPipeline::Copy, vec![1, 3], Some(120.0))
|
||||
.ffmpeg_output_args();
|
||||
assert!(args.windows(2).any(|pair| pair == ["-c:v", "copy"]));
|
||||
assert!(args.windows(2).any(|pair| pair == ["-c:a", "aac"]));
|
||||
assert!(args.windows(2).any(|pair| pair == ["-ac", "2"]));
|
||||
assert!(args.windows(2).any(|pair| pair == ["-map", "0:1"]));
|
||||
assert!(args.windows(2).any(|pair| pair == ["-map", "0:3"]));
|
||||
assert!(args.windows(2).any(|pair| {
|
||||
pair == [
|
||||
"-adaptation_sets",
|
||||
"id=0,streams=0 id=1,streams=1 id=2,streams=2",
|
||||
]
|
||||
}));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
use std::{
|
||||
collections::hash_map::DefaultHasher,
|
||||
hash::{Hash, Hasher},
|
||||
process::Stdio,
|
||||
sync::Arc,
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use axum::{
|
||||
body::Body,
|
||||
extract::{Query, State},
|
||||
http::header,
|
||||
response::{IntoResponse, Response},
|
||||
};
|
||||
use tokio::process::Command;
|
||||
|
||||
use crate::{
|
||||
app::AppState,
|
||||
error::AppError,
|
||||
media::{PathQuery, path, probe},
|
||||
};
|
||||
|
||||
const FRAME_COUNT: usize = 10;
|
||||
const FRAME_WIDTH: usize = 320;
|
||||
const FRAME_HEIGHT: usize = 180;
|
||||
|
||||
pub async fn sprite(
|
||||
State(state): State<Arc<AppState>>,
|
||||
Query(query): Query<PathQuery>,
|
||||
) -> Result<Response, AppError> {
|
||||
let media = path::resolve(&state.config, &query.path)?;
|
||||
if !media.is_file() {
|
||||
return Err(AppError::bad_request("path is not a media file"));
|
||||
}
|
||||
let _permit = state
|
||||
.preview_jobs
|
||||
.acquire()
|
||||
.await
|
||||
.map_err(AppError::internal)?;
|
||||
let metadata = probe::run(&state.config, &media).await?;
|
||||
let duration = metadata
|
||||
.format
|
||||
.and_then(|format| format.duration)
|
||||
.and_then(|value| value.parse::<f64>().ok())
|
||||
.filter(|value| value.is_finite() && *value > 0.0)
|
||||
.ok_or_else(|| AppError::bad_request("media duration is unavailable"))?;
|
||||
|
||||
let timestamps = preview_timestamps(&query.path, duration);
|
||||
let mut command = Command::new(&state.config.ffmpeg);
|
||||
command.args(["-v", "error"]);
|
||||
for timestamp in timestamps {
|
||||
command
|
||||
.args(["-ss", &format!("{timestamp:.3}"), "-i"])
|
||||
.arg(&media);
|
||||
}
|
||||
let filter = sprite_filter();
|
||||
command
|
||||
.args([
|
||||
"-filter_complex",
|
||||
&filter,
|
||||
"-map",
|
||||
"[sprite]",
|
||||
"-frames:v",
|
||||
"1",
|
||||
"-c:v",
|
||||
"mjpeg",
|
||||
"-q:v",
|
||||
"5",
|
||||
"-f",
|
||||
"image2pipe",
|
||||
"pipe:1",
|
||||
])
|
||||
.stdin(Stdio::null())
|
||||
.kill_on_drop(true);
|
||||
let output = tokio::time::timeout(Duration::from_secs(30), command.output())
|
||||
.await
|
||||
.map_err(|_| AppError::bad_request("preview generation timed out"))?
|
||||
.map_err(AppError::internal)?;
|
||||
if !output.status.success() || output.stdout.is_empty() {
|
||||
let details = String::from_utf8_lossy(&output.stderr);
|
||||
return Err(AppError::bad_request(format!(
|
||||
"failed to create preview: {}",
|
||||
details.trim()
|
||||
)));
|
||||
}
|
||||
Ok((
|
||||
[
|
||||
(header::CONTENT_TYPE, "image/jpeg"),
|
||||
(header::CACHE_CONTROL, "private, max-age=3600"),
|
||||
],
|
||||
Body::from(output.stdout),
|
||||
)
|
||||
.into_response())
|
||||
}
|
||||
|
||||
fn preview_timestamps(path: &str, duration: f64) -> [f64; FRAME_COUNT] {
|
||||
let mut hasher = DefaultHasher::new();
|
||||
path.hash(&mut hasher);
|
||||
let mut seed = hasher.finish();
|
||||
std::array::from_fn(|index| {
|
||||
seed ^= seed << 13;
|
||||
seed ^= seed >> 7;
|
||||
seed ^= seed << 17;
|
||||
let jitter = (seed as f64 / u64::MAX as f64 - 0.5) * 0.06;
|
||||
let position = ((index as f64 + 0.5) / FRAME_COUNT as f64 + jitter).clamp(0.02, 0.98);
|
||||
position * duration
|
||||
})
|
||||
}
|
||||
|
||||
fn sprite_filter() -> String {
|
||||
let mut filters = (0..FRAME_COUNT)
|
||||
.map(|index| {
|
||||
format!(
|
||||
"[{index}:v:0]setpts=PTS-STARTPTS,scale={FRAME_WIDTH}:{FRAME_HEIGHT}:force_original_aspect_ratio=decrease,pad={FRAME_WIDTH}:{FRAME_HEIGHT}:(ow-iw)/2:(oh-ih)/2:black,setsar=1[v{index}]"
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let inputs = (0..FRAME_COUNT)
|
||||
.map(|index| format!("[v{index}]"))
|
||||
.collect::<String>();
|
||||
let layout = (0..FRAME_COUNT)
|
||||
.map(|index| {
|
||||
format!(
|
||||
"{}_{}",
|
||||
(index % 5) * FRAME_WIDTH,
|
||||
(index / 5) * FRAME_HEIGHT
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("|");
|
||||
filters.push(format!(
|
||||
"{inputs}xstack=inputs={FRAME_COUNT}:layout={layout}[sprite]"
|
||||
));
|
||||
filters.join(";")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{FRAME_COUNT, preview_timestamps, sprite_filter};
|
||||
|
||||
#[test]
|
||||
fn timestamps_are_stable_and_inside_the_video() {
|
||||
let first = preview_timestamps("series/episode.mkv", 100.0);
|
||||
let second = preview_timestamps("series/episode.mkv", 100.0);
|
||||
assert_eq!(first, second);
|
||||
assert!(first.iter().all(|value| *value >= 2.0 && *value <= 98.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sprite_contains_every_input() {
|
||||
let filter = sprite_filter();
|
||||
assert!(filter.contains(&format!("xstack=inputs={FRAME_COUNT}")));
|
||||
for index in 0..FRAME_COUNT {
|
||||
assert!(filter.contains(&format!("[{index}:v:0]")));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
use std::{path::Path, process::Stdio, sync::Arc};
|
||||
|
||||
use axum::{
|
||||
Json,
|
||||
extract::{Query, State},
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tokio::process::Command;
|
||||
|
||||
use crate::{
|
||||
app::AppState,
|
||||
config::Config,
|
||||
error::AppError,
|
||||
media::{PathQuery, path},
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct Probe {
|
||||
#[serde(default)]
|
||||
pub streams: Vec<Stream>,
|
||||
pub format: Option<Format>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct Stream {
|
||||
pub index: u32,
|
||||
pub codec_name: Option<String>,
|
||||
pub codec_type: Option<String>,
|
||||
pub pix_fmt: Option<String>,
|
||||
#[serde(default)]
|
||||
pub tags: serde_json::Map<String, serde_json::Value>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct Format {
|
||||
pub format_name: Option<String>,
|
||||
pub duration: Option<String>,
|
||||
}
|
||||
|
||||
pub async fn probe(
|
||||
State(state): State<Arc<AppState>>,
|
||||
Query(query): Query<PathQuery>,
|
||||
) -> Result<Json<Probe>, AppError> {
|
||||
let media = path::resolve(&state.config, &query.path)?;
|
||||
Ok(Json(run(&state.config, &media).await?))
|
||||
}
|
||||
|
||||
pub async fn run(config: &Config, media: &Path) -> Result<Probe, AppError> {
|
||||
let output = Command::new(&config.ffprobe)
|
||||
.args([
|
||||
"-v",
|
||||
"error",
|
||||
"-show_format",
|
||||
"-show_streams",
|
||||
"-of",
|
||||
"json",
|
||||
])
|
||||
.arg(media)
|
||||
.stdin(Stdio::null())
|
||||
.output()
|
||||
.await
|
||||
.map_err(AppError::internal)?;
|
||||
if !output.status.success() {
|
||||
return Err(AppError::internal(String::from_utf8_lossy(&output.stderr)));
|
||||
}
|
||||
serde_json::from_slice(&output.stdout).map_err(AppError::internal)
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::{
|
||||
body::Body,
|
||||
extract::{Query, State},
|
||||
http::{HeaderMap, StatusCode, header},
|
||||
response::Response,
|
||||
};
|
||||
use tokio::{
|
||||
fs::File,
|
||||
io::{AsyncReadExt, AsyncSeekExt, SeekFrom},
|
||||
};
|
||||
|
||||
use crate::{
|
||||
app::AppState,
|
||||
error::AppError,
|
||||
media::{PathQuery, path},
|
||||
};
|
||||
|
||||
pub async fn stream(
|
||||
State(state): State<Arc<AppState>>,
|
||||
Query(query): Query<PathQuery>,
|
||||
headers: HeaderMap,
|
||||
) -> Result<Response<Body>, AppError> {
|
||||
let media = path::resolve(&state.config, &query.path)?;
|
||||
if !media.is_file() {
|
||||
return Err(AppError::bad_request("path is not a file"));
|
||||
}
|
||||
let mut file = File::open(&media).await.map_err(AppError::internal)?;
|
||||
let size = file.metadata().await.map_err(AppError::internal)?.len();
|
||||
let (start, end, status) = match headers.get(header::RANGE).and_then(|v| v.to_str().ok()) {
|
||||
Some(value) => {
|
||||
let (start, end) = parse_range(value, size)?;
|
||||
(start, end, StatusCode::PARTIAL_CONTENT)
|
||||
}
|
||||
None => (0, size.saturating_sub(1), StatusCode::OK),
|
||||
};
|
||||
let length = end - start + 1;
|
||||
file.seek(SeekFrom::Start(start))
|
||||
.await
|
||||
.map_err(AppError::internal)?;
|
||||
let body = Body::from_stream(tokio_util::io::ReaderStream::new(file.take(length)));
|
||||
let mime = mime_guess::from_path(&media).first_or_octet_stream();
|
||||
|
||||
let mut response = Response::builder()
|
||||
.status(status)
|
||||
.header(header::ACCEPT_RANGES, "bytes")
|
||||
.header(header::CONTENT_LENGTH, length)
|
||||
.header(header::CONTENT_TYPE, mime.as_ref());
|
||||
if status == StatusCode::PARTIAL_CONTENT {
|
||||
response = response.header(header::CONTENT_RANGE, format!("bytes {start}-{end}/{size}"));
|
||||
}
|
||||
response.body(body).map_err(AppError::internal)
|
||||
}
|
||||
|
||||
fn parse_range(value: &str, size: u64) -> Result<(u64, u64), AppError> {
|
||||
let value = value
|
||||
.strip_prefix("bytes=")
|
||||
.ok_or_else(|| AppError::bad_request("invalid range"))?;
|
||||
let (start, end) = value
|
||||
.split_once('-')
|
||||
.ok_or_else(|| AppError::bad_request("invalid range"))?;
|
||||
let start = start
|
||||
.parse::<u64>()
|
||||
.map_err(|_| AppError::bad_request("invalid range"))?;
|
||||
let end = if end.is_empty() {
|
||||
size.saturating_sub(1)
|
||||
} else {
|
||||
end.parse()
|
||||
.map_err(|_| AppError::bad_request("invalid range"))?
|
||||
};
|
||||
if size == 0 || start > end || end >= size {
|
||||
return Err(AppError::bad_request("range outside file"));
|
||||
}
|
||||
Ok((start, end))
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
use std::{process::Stdio, sync::Arc};
|
||||
|
||||
use axum::{
|
||||
Json,
|
||||
body::Body,
|
||||
extract::{Path, Query, State},
|
||||
http::header,
|
||||
response::{IntoResponse, Response},
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tokio::process::Command;
|
||||
use tokio_util::io::ReaderStream;
|
||||
|
||||
use crate::{
|
||||
app::AppState,
|
||||
error::AppError,
|
||||
media::{PathQuery, path, probe},
|
||||
};
|
||||
|
||||
mod discovery;
|
||||
mod matching;
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct Subtitle {
|
||||
index: Option<u32>,
|
||||
id: Option<String>,
|
||||
source: &'static str,
|
||||
codec: String,
|
||||
language: Option<String>,
|
||||
title: Option<String>,
|
||||
supported: bool,
|
||||
confidence: Option<&'static str>,
|
||||
score: Option<u8>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct ExtractQuery {
|
||||
path: String,
|
||||
#[serde(default)]
|
||||
start: f64,
|
||||
}
|
||||
|
||||
pub async fn list(
|
||||
State(state): State<Arc<AppState>>,
|
||||
Query(query): Query<PathQuery>,
|
||||
) -> Result<Json<Vec<Subtitle>>, AppError> {
|
||||
let media = path::resolve(&state.config, &query.path)?;
|
||||
let info = probe::run(&state.config, &media).await?;
|
||||
let mut subtitles = info
|
||||
.streams
|
||||
.into_iter()
|
||||
.filter(|stream| stream.codec_type.as_deref() == Some("subtitle"))
|
||||
.map(|stream| {
|
||||
let codec = stream.codec_name.unwrap_or_else(|| "unknown".into());
|
||||
Subtitle {
|
||||
index: Some(stream.index),
|
||||
id: None,
|
||||
source: "embedded",
|
||||
supported: matches!(
|
||||
codec.as_str(),
|
||||
"subrip" | "srt" | "ass" | "ssa" | "webvtt" | "mov_text"
|
||||
),
|
||||
language: tag(&stream.tags, "language"),
|
||||
title: tag(&stream.tags, "title"),
|
||||
codec,
|
||||
confidence: None,
|
||||
score: None,
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
subtitles.extend(
|
||||
discovery::find(&state.config, &media)
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(|candidate| Subtitle {
|
||||
index: None,
|
||||
id: Some(candidate.id),
|
||||
source: "external",
|
||||
codec: candidate.codec,
|
||||
language: None,
|
||||
title: Some(candidate.label),
|
||||
supported: true,
|
||||
confidence: Some(candidate.confidence.as_str()),
|
||||
score: Some(candidate.score),
|
||||
}),
|
||||
);
|
||||
Ok(Json(subtitles))
|
||||
}
|
||||
|
||||
pub async fn extract(
|
||||
State(state): State<Arc<AppState>>,
|
||||
Path(index): Path<u32>,
|
||||
Query(query): Query<ExtractQuery>,
|
||||
) -> Result<Response, AppError> {
|
||||
if !query.start.is_finite() || query.start < 0.0 {
|
||||
return Err(AppError::bad_request("invalid subtitle start position"));
|
||||
}
|
||||
let media = path::resolve(&state.config, &query.path)?;
|
||||
stream_webvtt(
|
||||
&state.config.ffmpeg,
|
||||
&media,
|
||||
&format!("0:{index}"),
|
||||
query.start,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn extract_external(
|
||||
State(state): State<Arc<AppState>>,
|
||||
Path(id): Path<String>,
|
||||
Query(query): Query<ExtractQuery>,
|
||||
) -> Result<Response, AppError> {
|
||||
if !query.start.is_finite() || query.start < 0.0 {
|
||||
return Err(AppError::bad_request("invalid subtitle start position"));
|
||||
}
|
||||
let media = path::resolve(&state.config, &query.path)?;
|
||||
let candidate = discovery::resolve_id(&state.config, &media, &id).await?;
|
||||
stream_webvtt(&state.config.ffmpeg, &candidate.path, "0:0", query.start).await
|
||||
}
|
||||
|
||||
async fn stream_webvtt(
|
||||
ffmpeg: &std::path::Path,
|
||||
input: &std::path::Path,
|
||||
map: &str,
|
||||
start: f64,
|
||||
) -> Result<Response, AppError> {
|
||||
let mut command = Command::new(ffmpeg);
|
||||
command.args(["-v", "error"]);
|
||||
if start > 0.0 {
|
||||
command.args(["-ss", &format!("{start:.3}")]);
|
||||
}
|
||||
let mut child = command
|
||||
.arg("-i")
|
||||
.arg(input)
|
||||
.args(["-map", map, "-f", "webvtt", "pipe:1"])
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null())
|
||||
.spawn()
|
||||
.map_err(AppError::internal)?;
|
||||
let stdout = child
|
||||
.stdout
|
||||
.take()
|
||||
.ok_or_else(|| AppError::internal("ffmpeg stdout unavailable"))?;
|
||||
tokio::spawn(async move {
|
||||
let _ = child.wait().await;
|
||||
});
|
||||
Ok((
|
||||
[(header::CONTENT_TYPE, "text/vtt; charset=utf-8")],
|
||||
Body::from_stream(ReaderStream::new(stdout)),
|
||||
)
|
||||
.into_response())
|
||||
}
|
||||
|
||||
fn tag(tags: &serde_json::Map<String, serde_json::Value>, name: &str) -> Option<String> {
|
||||
tags.get(name)
|
||||
.or_else(|| tags.get(&name.to_uppercase()))
|
||||
.and_then(|value| value.as_str())
|
||||
.map(str::to_owned)
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
use std::{
|
||||
collections::{HashSet, VecDeque, hash_map::DefaultHasher},
|
||||
hash::{Hash, Hasher},
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
use tokio::fs;
|
||||
|
||||
use crate::{config::Config, error::AppError, media::path};
|
||||
|
||||
use super::matching::{self, Confidence};
|
||||
|
||||
const SUBTITLE_EXTENSIONS: &[&str] = &["ass", "ssa", "srt", "vtt"];
|
||||
const MAX_DEPTH: usize = 3;
|
||||
const MAX_ENTRIES: usize = 2_000;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Candidate {
|
||||
pub id: String,
|
||||
pub path: PathBuf,
|
||||
pub relative_path: String,
|
||||
pub codec: String,
|
||||
pub label: String,
|
||||
pub score: u8,
|
||||
pub confidence: Confidence,
|
||||
}
|
||||
|
||||
pub async fn find(config: &Config, video: &Path) -> Result<Vec<Candidate>, AppError> {
|
||||
let mut roots = Vec::new();
|
||||
if let Some(parent) = video.parent() {
|
||||
roots.push((parent.to_owned(), MAX_DEPTH));
|
||||
if let Some(grandparent) = parent.parent().filter(|path| *path != config.media_root)
|
||||
&& grandparent.starts_with(&config.media_root)
|
||||
{
|
||||
roots.push((grandparent.to_owned(), 2));
|
||||
}
|
||||
}
|
||||
|
||||
let mut queue = VecDeque::from(roots);
|
||||
let mut visited = HashSet::new();
|
||||
let mut scanned = 0;
|
||||
let mut candidates = Vec::new();
|
||||
while let Some((directory, depth)) = queue.pop_front() {
|
||||
if !visited.insert(directory.clone()) {
|
||||
continue;
|
||||
}
|
||||
let mut reader = match fs::read_dir(&directory).await {
|
||||
Ok(reader) => reader,
|
||||
Err(_) => continue,
|
||||
};
|
||||
while scanned < MAX_ENTRIES {
|
||||
let Some(entry) = reader.next_entry().await.map_err(AppError::internal)? else {
|
||||
break;
|
||||
};
|
||||
scanned += 1;
|
||||
let file_type = entry.file_type().await.map_err(AppError::internal)?;
|
||||
if file_type.is_symlink() {
|
||||
continue;
|
||||
}
|
||||
let candidate_path = entry.path();
|
||||
if file_type.is_dir() && depth > 0 {
|
||||
queue.push_back((candidate_path, depth - 1));
|
||||
} else if file_type.is_file()
|
||||
&& is_subtitle(&candidate_path)
|
||||
&& let Some(candidate) = make_candidate(config, video, candidate_path)?
|
||||
{
|
||||
candidates.push(candidate);
|
||||
}
|
||||
}
|
||||
if scanned >= MAX_ENTRIES {
|
||||
break;
|
||||
}
|
||||
}
|
||||
candidates.sort_by(|left, right| {
|
||||
right
|
||||
.score
|
||||
.cmp(&left.score)
|
||||
.then_with(|| left.relative_path.cmp(&right.relative_path))
|
||||
});
|
||||
candidates.dedup_by(|left, right| left.path == right.path);
|
||||
Ok(candidates)
|
||||
}
|
||||
|
||||
pub async fn resolve_id(config: &Config, video: &Path, id: &str) -> Result<Candidate, AppError> {
|
||||
find(config, video)
|
||||
.await?
|
||||
.into_iter()
|
||||
.find(|candidate| candidate.id == id)
|
||||
.ok_or_else(|| AppError::not_found("external subtitle not found"))
|
||||
}
|
||||
|
||||
fn make_candidate(
|
||||
config: &Config,
|
||||
video: &Path,
|
||||
subtitle: PathBuf,
|
||||
) -> Result<Option<Candidate>, AppError> {
|
||||
let Some(matched) = matching::score(video, &subtitle) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let relative_path = path::relative(config, &subtitle)?;
|
||||
let codec = subtitle
|
||||
.extension()
|
||||
.and_then(|value| value.to_str())
|
||||
.unwrap_or("unknown")
|
||||
.to_ascii_lowercase();
|
||||
Ok(Some(Candidate {
|
||||
id: candidate_id(&relative_path),
|
||||
path: subtitle,
|
||||
relative_path,
|
||||
codec,
|
||||
label: matched.label,
|
||||
score: matched.score,
|
||||
confidence: matched.confidence,
|
||||
}))
|
||||
}
|
||||
|
||||
fn candidate_id(relative_path: &str) -> String {
|
||||
let mut hasher = DefaultHasher::new();
|
||||
relative_path.hash(&mut hasher);
|
||||
format!("{:016x}", hasher.finish())
|
||||
}
|
||||
|
||||
fn is_subtitle(path: &Path) -> bool {
|
||||
path.extension()
|
||||
.and_then(|value| value.to_str())
|
||||
.is_some_and(|value| SUBTITLE_EXTENSIONS.contains(&value.to_ascii_lowercase().as_str()))
|
||||
}
|
||||
@@ -0,0 +1,237 @@
|
||||
use std::path::Path;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Confidence {
|
||||
Certain,
|
||||
Likely,
|
||||
Ambiguous,
|
||||
}
|
||||
|
||||
impl Confidence {
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::Certain => "certain",
|
||||
Self::Likely => "likely",
|
||||
Self::Ambiguous => "ambiguous",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Match {
|
||||
pub score: u8,
|
||||
pub confidence: Confidence,
|
||||
pub label: String,
|
||||
}
|
||||
|
||||
pub fn score(video: &Path, subtitle: &Path) -> Option<Match> {
|
||||
let video_stem = stem(video)?;
|
||||
let subtitle_stem = stem(subtitle)?;
|
||||
let video_name = Normalized::new(&video_stem);
|
||||
let subtitle_name = Normalized::new(&subtitle_stem);
|
||||
if video_name.tokens.is_empty() || subtitle_name.tokens.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let exact = video_name.tokens == subtitle_name.tokens;
|
||||
let contains_video = contains_sequence(&subtitle_name.tokens, &video_name.tokens);
|
||||
let same_directory = video.parent() == subtitle.parent();
|
||||
let episode_video = video_name.episode();
|
||||
let episode_subtitle = subtitle_name.episode();
|
||||
|
||||
if !contains_video
|
||||
&& episode_video.is_some()
|
||||
&& episode_subtitle.is_some()
|
||||
&& episode_video != episode_subtitle
|
||||
{
|
||||
return None;
|
||||
}
|
||||
|
||||
let similarity = jaccard(&video_name.tokens, &subtitle_name.tokens);
|
||||
let (score, confidence) = if exact {
|
||||
(100, Confidence::Certain)
|
||||
} else if contains_video {
|
||||
(95, Confidence::Certain)
|
||||
} else {
|
||||
let mut value = (similarity * 55.0).round() as u8;
|
||||
if episode_video.is_some() && episode_video == episode_subtitle {
|
||||
value = value.saturating_add(30);
|
||||
}
|
||||
if same_directory {
|
||||
value = value.saturating_add(10);
|
||||
}
|
||||
let confidence = if value >= 75 {
|
||||
Confidence::Likely
|
||||
} else {
|
||||
Confidence::Ambiguous
|
||||
};
|
||||
(value.min(94), confidence)
|
||||
};
|
||||
if score < 40 {
|
||||
return None;
|
||||
}
|
||||
|
||||
Some(Match {
|
||||
score,
|
||||
confidence,
|
||||
label: candidate_label(video, subtitle, contains_video),
|
||||
})
|
||||
}
|
||||
|
||||
fn stem(path: &Path) -> Option<String> {
|
||||
path.file_stem()
|
||||
.map(|value| value.to_string_lossy().into_owned())
|
||||
}
|
||||
|
||||
struct Normalized {
|
||||
tokens: Vec<String>,
|
||||
}
|
||||
|
||||
impl Normalized {
|
||||
fn new(value: &str) -> Self {
|
||||
let mut tokens = Vec::new();
|
||||
let mut current = String::new();
|
||||
let mut digit = None;
|
||||
for character in value.chars().flat_map(char::to_lowercase) {
|
||||
if !character.is_alphanumeric() {
|
||||
push_token(&mut tokens, &mut current);
|
||||
digit = None;
|
||||
continue;
|
||||
}
|
||||
let is_digit = character.is_numeric();
|
||||
if digit.is_some_and(|previous| previous != is_digit) {
|
||||
push_token(&mut tokens, &mut current);
|
||||
}
|
||||
digit = Some(is_digit);
|
||||
current.push(character);
|
||||
}
|
||||
push_token(&mut tokens, &mut current);
|
||||
Self { tokens }
|
||||
}
|
||||
|
||||
fn episode(&self) -> Option<u32> {
|
||||
for window in self.tokens.windows(4) {
|
||||
if window[0] == "s"
|
||||
&& window[2] == "e"
|
||||
&& let Ok(value) = window[3].parse()
|
||||
{
|
||||
return Some(value);
|
||||
}
|
||||
}
|
||||
let technical_boundary = self.tokens.iter().position(|token| {
|
||||
token
|
||||
.parse::<u32>()
|
||||
.is_ok_and(|value| is_technical_number(value, None))
|
||||
});
|
||||
self.tokens
|
||||
.iter()
|
||||
.enumerate()
|
||||
.take(technical_boundary.unwrap_or(self.tokens.len()))
|
||||
.filter_map(|(index, token)| {
|
||||
let value: u32 = token.parse().ok()?;
|
||||
if is_technical_number(value, self.tokens.get(index.wrapping_sub(1))) {
|
||||
None
|
||||
} else {
|
||||
Some(value)
|
||||
}
|
||||
})
|
||||
.next_back()
|
||||
}
|
||||
}
|
||||
|
||||
fn push_token(tokens: &mut Vec<String>, current: &mut String) {
|
||||
if !current.is_empty() {
|
||||
tokens.push(std::mem::take(current));
|
||||
}
|
||||
}
|
||||
|
||||
fn is_technical_number(value: u32, previous: Option<&String>) -> bool {
|
||||
matches!(
|
||||
value,
|
||||
240 | 264 | 265 | 360 | 480 | 576 | 720 | 1080 | 1440 | 2160 | 4320
|
||||
) || previous.is_some_and(|token| matches!(token.as_str(), "x" | "h"))
|
||||
}
|
||||
|
||||
fn contains_sequence(haystack: &[String], needle: &[String]) -> bool {
|
||||
needle.len() <= haystack.len()
|
||||
&& haystack
|
||||
.windows(needle.len())
|
||||
.any(|window| window == needle)
|
||||
}
|
||||
|
||||
fn jaccard(left: &[String], right: &[String]) -> f32 {
|
||||
let common = left.iter().filter(|token| right.contains(token)).count();
|
||||
let union = left.len() + right.len() - common;
|
||||
if union == 0 {
|
||||
0.0
|
||||
} else {
|
||||
common as f32 / union as f32
|
||||
}
|
||||
}
|
||||
|
||||
fn candidate_label(video: &Path, subtitle: &Path, contains_video: bool) -> String {
|
||||
let video_stem = stem(video).unwrap_or_default();
|
||||
let subtitle_stem = stem(subtitle).unwrap_or_default();
|
||||
let suffix = if contains_video {
|
||||
subtitle_stem
|
||||
.strip_prefix(&video_stem)
|
||||
.unwrap_or("")
|
||||
.trim_matches(|character: char| !character.is_alphanumeric())
|
||||
.to_owned()
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
let folder = (video.parent() != subtitle.parent())
|
||||
.then(|| subtitle.parent()?.file_name()?.to_str().map(str::to_owned))
|
||||
.flatten();
|
||||
match (folder, suffix.is_empty()) {
|
||||
(Some(folder), false) => format!("{folder} · {suffix}"),
|
||||
(Some(folder), true) => folder,
|
||||
(None, false) => suffix,
|
||||
(None, true) => "External".to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::path::Path;
|
||||
|
||||
use super::{Confidence, score};
|
||||
|
||||
#[test]
|
||||
fn exact_stems_are_certain() {
|
||||
let result = score(
|
||||
Path::new("05. Famous Shooter.avi"),
|
||||
Path::new("05. Famous Shooter.ass"),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(result.confidence, Confidence::Certain);
|
||||
assert_eq!(result.score, 100);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn release_suffixes_are_certain_and_become_labels() {
|
||||
let result = score(
|
||||
Path::new("Show - 01 [1080p WEB-DL].mkv"),
|
||||
Path::new("Show - 01 [1080p WEB-DL]-RELEASE2.ass"),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(result.confidence, Confidence::Certain);
|
||||
assert_eq!(result.label, "RELEASE2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_a_neighboring_episode() {
|
||||
assert!(score(Path::new("Show - 01.mkv"), Path::new("Show - 02.ass")).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn folder_names_are_labels_not_languages() {
|
||||
let result = score(
|
||||
Path::new("Show/01.mkv"),
|
||||
Path::new("Show/SUBS/Variant A/01.srt"),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(result.label, "Variant A");
|
||||
}
|
||||
}
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
use axum::{
|
||||
body::Body,
|
||||
http::header,
|
||||
response::{Html, IntoResponse},
|
||||
};
|
||||
|
||||
pub async fn index() -> impl IntoResponse {
|
||||
(
|
||||
[(header::CACHE_CONTROL, "no-store")],
|
||||
Html(include_str!("../web/index.html")),
|
||||
)
|
||||
}
|
||||
pub async fn alpine() -> impl IntoResponse {
|
||||
(
|
||||
[(header::CONTENT_TYPE, "text/javascript; charset=utf-8")],
|
||||
include_str!("../web/alpine.min.js"),
|
||||
)
|
||||
}
|
||||
pub async fn dash() -> impl IntoResponse {
|
||||
javascript(include_str!("../web/dash.all.min.js"))
|
||||
}
|
||||
pub async fn dash_source_map() -> impl IntoResponse {
|
||||
(
|
||||
[(header::CONTENT_TYPE, "application/json; charset=utf-8")],
|
||||
r#"{"version":3,"sources":[],"names":[],"mappings":""}"#,
|
||||
)
|
||||
}
|
||||
pub async fn controlbar_javascript() -> impl IntoResponse {
|
||||
javascript(include_str!("../web/controlbar.min.js"))
|
||||
}
|
||||
pub async fn api_javascript() -> impl IntoResponse {
|
||||
javascript(include_str!("../web/js/api.js"))
|
||||
}
|
||||
pub async fn library_javascript() -> impl IntoResponse {
|
||||
javascript(include_str!("../web/js/library.js"))
|
||||
}
|
||||
pub async fn location_javascript() -> impl IntoResponse {
|
||||
javascript(include_str!("../web/js/location.js"))
|
||||
}
|
||||
pub async fn preferences_javascript() -> impl IntoResponse {
|
||||
javascript(include_str!("../web/js/preferences.js"))
|
||||
}
|
||||
pub async fn player_javascript() -> impl IntoResponse {
|
||||
javascript(include_str!("../web/js/player.js"))
|
||||
}
|
||||
fn javascript(source: &'static str) -> impl IntoResponse {
|
||||
(
|
||||
[
|
||||
(header::CONTENT_TYPE, "text/javascript; charset=utf-8"),
|
||||
(header::CACHE_CONTROL, "no-store"),
|
||||
],
|
||||
source,
|
||||
)
|
||||
}
|
||||
pub async fn styles() -> impl IntoResponse {
|
||||
stylesheet(include_str!("../web/styles.css"))
|
||||
}
|
||||
pub async fn controlbar_styles() -> impl IntoResponse {
|
||||
stylesheet(include_str!("../web/vendor/controlbar/controlbar.css"))
|
||||
}
|
||||
pub async fn bootstrap_icon_styles() -> impl IntoResponse {
|
||||
stylesheet(include_str!(
|
||||
"../web/vendor/bootstrap-icons/bootstrap-icons.min.css"
|
||||
))
|
||||
}
|
||||
pub async fn bootstrap_icon_font() -> impl IntoResponse {
|
||||
(
|
||||
[(header::CONTENT_TYPE, "font/woff2")],
|
||||
Body::from(
|
||||
include_bytes!("../web/vendor/bootstrap-icons/fonts/bootstrap-icons.woff2").as_slice(),
|
||||
),
|
||||
)
|
||||
}
|
||||
fn stylesheet(source: &'static str) -> impl IntoResponse {
|
||||
(
|
||||
[
|
||||
(header::CONTENT_TYPE, "text/css; charset=utf-8"),
|
||||
(header::CACHE_CONTROL, "no-store"),
|
||||
],
|
||||
source,
|
||||
)
|
||||
}
|
||||
Vendored
+5
File diff suppressed because one or more lines are too long
Vendored
+1
File diff suppressed because one or more lines are too long
Vendored
+3
File diff suppressed because one or more lines are too long
@@ -0,0 +1,14 @@
|
||||
# dash.js BSD License Agreement
|
||||
|
||||
The copyright in this software is being made available under the BSD License, included below. This software may be subject to other third party and contributor rights, including patent rights, and no such rights are granted under this license.
|
||||
|
||||
**Copyright (c) 2015, Dash Industry Forum.
|
||||
**All rights reserved.**
|
||||
|
||||
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
|
||||
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
|
||||
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
|
||||
* Neither the name of the Dash Industry Forum nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
|
||||
|
||||
**THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.**
|
||||
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<title>Lan Play</title>
|
||||
<link rel="stylesheet" href="/bootstrap-icons.min.css">
|
||||
<link rel="stylesheet" href="/controlbar.css?v=14">
|
||||
<link rel="stylesheet" href="/styles.css?v=20">
|
||||
<script defer src="/dash.all.min.js"></script>
|
||||
<script defer src="/controlbar.min.js?v=16"></script>
|
||||
<script defer src="/js/api.js?v=20"></script>
|
||||
<script defer src="/js/location.js?v=14"></script>
|
||||
<script defer src="/js/preferences.js?v=15"></script>
|
||||
<script defer src="/js/player.js?v=17"></script>
|
||||
<script defer src="/js/library.js?v=20"></script>
|
||||
<script defer src="/alpine.min.js"></script>
|
||||
</head>
|
||||
<body x-data="library" x-init="restoreLocation()" :class="{ 'player-open': selected }" @keydown.escape.window="infoOpen ? closeInfo() : closePlayer()" x-cloak>
|
||||
<header>
|
||||
<div><h1>Lan Play</h1><div class="path" x-text="currentPath || '/' "></div></div>
|
||||
<div class="view-switch" role="group" aria-label="Library view">
|
||||
<button type="button" title="Grid view" @click="setViewMode('grid')" :class="{ active: viewMode === 'grid' }"><i class="bi bi-grid-fill"></i></button>
|
||||
<button type="button" title="Table view" @click="setViewMode('table')" :class="{ active: viewMode === 'table' }"><i class="bi bi-list-ul"></i></button>
|
||||
<button type="button" title="System information" @click="openInfo()"><i class="bi bi-info-circle"></i></button>
|
||||
</div>
|
||||
</header>
|
||||
<main>
|
||||
<p x-show="loading">Loading…</p>
|
||||
<p class="error" x-show="error" x-text="error"></p>
|
||||
<div class="entries" x-show="viewMode === 'grid'">
|
||||
<button type="button" class="directory" x-show="parentPath !== null" @click="browse(parentPath)"><span class="entry-preview">📁</span><span class="entry-name">..</span></button>
|
||||
<template x-for="entry in entries" :key="entry.path">
|
||||
<button type="button" @click="openEntry(entry)" :class="entry.kind"
|
||||
@mouseenter="startPreview(entry)" @mouseleave="stopPreview(entry)"
|
||||
@focus="startPreview(entry)" @blur="stopPreview(entry)">
|
||||
<span class="entry-preview" :class="{ 'entry-preview-media': entry.kind === 'media' }" :style="previewStyle(entry)">
|
||||
<i class="bi bi-arrow-repeat preview-spinner" x-show="entry.kind === 'media' && previewStates[entry.path] === 'loading'"></i>
|
||||
<span x-show="entry.kind === 'directory' || previewStates[entry.path] !== 'ready'" x-text="entry.kind === 'directory' ? '📁' : (previewStates[entry.path] === 'error' ? '!' : '')"></span>
|
||||
</span>
|
||||
<span class="entry-name"><span class="entry-name-track" x-text="entry.name"></span></span>
|
||||
</button>
|
||||
</template>
|
||||
</div>
|
||||
<div class="entry-table-wrap" x-show="viewMode === 'table'">
|
||||
<table class="entry-table">
|
||||
<thead><tr><th>Preview</th><th>Name</th><th>Type</th></tr></thead>
|
||||
<tbody>
|
||||
<tr x-show="parentPath !== null" @click="browse(parentPath)" tabindex="0" @keydown.enter="browse(parentPath)"><td class="table-preview">📁</td><td>..</td><td>Folder</td></tr>
|
||||
<template x-for="entry in entries" :key="entry.path">
|
||||
<tr @click="openEntry(entry)" tabindex="0" @keydown.enter="openEntry(entry)"
|
||||
@mouseenter="startPreview(entry)" @mouseleave="stopPreview(entry)"
|
||||
@focus="startPreview(entry)" @blur="stopPreview(entry)">
|
||||
<td><span class="table-preview" :class="{ 'entry-preview-media': entry.kind === 'media' }" :style="previewStyle(entry)">
|
||||
<i class="bi bi-arrow-repeat preview-spinner" x-show="entry.kind === 'media' && previewStates[entry.path] === 'loading'"></i>
|
||||
<span x-show="entry.kind === 'directory' || previewStates[entry.path] === 'error'" x-text="entry.kind === 'directory' ? '📁' : '!'"></span>
|
||||
</span></td>
|
||||
<td><span class="entry-name table-name"><span class="entry-name-track" x-text="entry.name"></span></span></td>
|
||||
<td x-text="entry.kind === 'directory' ? 'Folder' : 'Video'"></td>
|
||||
</tr>
|
||||
</template>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</main>
|
||||
<div class="info-backdrop" x-show="infoOpen" @click.self="closeInfo()" x-cloak>
|
||||
<section class="info-dialog" role="dialog" aria-modal="true" aria-labelledby="info-title">
|
||||
<button class="info-close" type="button" title="Close" aria-label="Close" @click="closeInfo()"><i class="bi bi-x-lg"></i></button>
|
||||
<h2 id="info-title">System information</h2>
|
||||
<div class="info-loading" x-show="infoLoading"><i class="bi bi-arrow-repeat preview-spinner"></i> Loading diagnostics…</div>
|
||||
<p class="error" x-show="infoError" x-text="infoError"></p>
|
||||
<dl class="info-grid" x-show="diagnostics && !infoLoading">
|
||||
<dt>Application</dt><dd x-text="`${diagnostics.application} ${diagnostics.version} (${diagnostics.build})`"></dd>
|
||||
<dt>Interface</dt><dd x-text="`UI ${diagnostics.interface}`"></dd>
|
||||
<dt>dash.js</dt><dd x-text="diagnostics.dashjs"></dd>
|
||||
<dt>Platform</dt><dd x-text="diagnostics.platform"></dd>
|
||||
<dt>Display</dt><dd x-text="diagnostics.display"></dd>
|
||||
<dt>FFmpeg</dt><dd><span x-text="diagnostics.ffmpeg.version"></span><small x-text="diagnostics.ffmpeg.path"></small></dd>
|
||||
<dt>FFprobe</dt><dd><span x-text="diagnostics.ffprobe.version"></span><small x-text="diagnostics.ffprobe.path"></small></dd>
|
||||
<dt>Media root</dt><dd x-text="diagnostics.media_root"></dd>
|
||||
<dt>Listen address</dt><dd x-text="diagnostics.bind"></dd>
|
||||
<dt>Browser APIs</dt><dd x-text="`MSE ${diagnostics.mediaSource ? 'yes' : 'no'} · Fullscreen ${diagnostics.fullscreen ? 'yes' : 'no'}`"></dd>
|
||||
<dt>Browser</dt><dd class="info-browser" x-text="diagnostics.browser"></dd>
|
||||
</dl>
|
||||
</section>
|
||||
</div>
|
||||
<section class="player" x-ref="playerShell" x-show="selected" x-cloak>
|
||||
<button class="player-close" type="button" aria-label="Close player" title="Close" @click="closePlayer()">
|
||||
<i class="bi bi-x-lg" aria-hidden="true"></i>
|
||||
</button>
|
||||
<div class="video-wrapper" x-ref="videoWrapper">
|
||||
<video x-ref="video" playsinline preload="metadata"></video>
|
||||
<div class="player-title" x-text="mediaTitle()"></div>
|
||||
<div class="player-status" :class="{ 'player-status-compact': playerLoadingCompact }" x-show="playerLoading" role="status">
|
||||
<i class="bi bi-arrow-repeat player-spinner" aria-hidden="true"></i>
|
||||
<span x-text="playerLoadingCompact ? 'Preparing stream at the new position…' : 'Preparing DASH stream…'"></span>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,31 @@
|
||||
(function () {
|
||||
async function request(url, options) {
|
||||
const response = await fetch(url, options);
|
||||
if (!response.ok) {
|
||||
let message = `HTTP ${response.status}`;
|
||||
try { message = (await response.json()).error || message; } catch (_) {}
|
||||
throw new Error(message);
|
||||
}
|
||||
return response;
|
||||
}
|
||||
|
||||
window.LanPlayApi = {
|
||||
async browse(path) {
|
||||
return (await request(`/api/browse?path=${encodeURIComponent(path)}`)).json();
|
||||
},
|
||||
|
||||
async info() {
|
||||
return (await request('/api/info')).json();
|
||||
},
|
||||
async startDash(path, startSeconds = 0) {
|
||||
const query = `path=${encodeURIComponent(path)}&start=${encodeURIComponent(startSeconds)}`;
|
||||
return (await request(`/api/dash?${query}`, { method: 'POST' })).json();
|
||||
},
|
||||
async stopDash(sessionId) {
|
||||
await request(`/api/dash/${sessionId}`, { method: 'DELETE' });
|
||||
},
|
||||
async subtitles(path) {
|
||||
return (await request(`/api/subtitles?path=${encodeURIComponent(path)}`)).json();
|
||||
}
|
||||
};
|
||||
})();
|
||||
@@ -0,0 +1,262 @@
|
||||
document.addEventListener('alpine:init', () => {
|
||||
Alpine.data('library', () => ({
|
||||
currentPath: '', parentPath: null, entries: [], selected: null,
|
||||
loading: false, playerLoading: false, playerLoadingCompact: false,
|
||||
error: '', playerController: null, viewMode: 'grid',
|
||||
infoOpen: false, infoLoading: false, infoError: '', diagnostics: null,
|
||||
previewFrames: {}, previewUrls: {}, previewStates: {}, previewTimers: {},
|
||||
previewActive: {}, previewImages: {}, previewGeneration: 0,
|
||||
|
||||
init() {
|
||||
try { this.viewMode = localStorage.getItem('lan-play:view') || 'grid'; } catch (_) {}
|
||||
this.locationHandler = () => { this.restoreLocation(); };
|
||||
this.resizeHandler = () => { this.scheduleMarqueeCheck(); };
|
||||
window.addEventListener('popstate', this.locationHandler);
|
||||
window.addEventListener('resize', this.resizeHandler);
|
||||
},
|
||||
|
||||
destroy() {
|
||||
this.stopAllPreviews();
|
||||
this.cancelPreviewLoads();
|
||||
window.removeEventListener('popstate', this.locationHandler);
|
||||
window.removeEventListener('resize', this.resizeHandler);
|
||||
if (this.marqueeFrame) window.cancelAnimationFrame(this.marqueeFrame);
|
||||
if (this.playerController) this.playerController.dispose();
|
||||
},
|
||||
|
||||
async restoreLocation() {
|
||||
const location = window.LanPlayLocation.read();
|
||||
if (this.playerController) await this.playerController.stop();
|
||||
this.selected = null;
|
||||
await this.browse(location.path, false);
|
||||
if (location.play) {
|
||||
await this.play({
|
||||
path: location.play,
|
||||
name: window.LanPlayLocation.fileName(location.play),
|
||||
kind: 'media'
|
||||
}, false);
|
||||
}
|
||||
},
|
||||
|
||||
async browse(path, updateLocation = true) {
|
||||
this.stopAllPreviews();
|
||||
this.cancelPreviewLoads();
|
||||
this.loading = true;
|
||||
this.error = '';
|
||||
try {
|
||||
const data = await window.LanPlayApi.browse(path);
|
||||
this.currentPath = data.path;
|
||||
this.parentPath = data.parent;
|
||||
this.entries = data.entries;
|
||||
if (updateLocation) window.LanPlayLocation.write(data.path, null, false);
|
||||
await this.$nextTick();
|
||||
this.preloadPreviews(data.entries);
|
||||
this.scheduleMarqueeCheck();
|
||||
} catch (error) { this.error = error.message; }
|
||||
finally { this.loading = false; }
|
||||
},
|
||||
|
||||
async play(entry, updateLocation = true) {
|
||||
this.stopAllPreviews();
|
||||
this.enterFullscreen();
|
||||
this.error = '';
|
||||
this.selected = entry;
|
||||
this.playerLoading = true;
|
||||
if (updateLocation) window.LanPlayLocation.write(this.currentPath, entry.path, false);
|
||||
await this.$nextTick();
|
||||
if (!this.playerController) {
|
||||
this.playerController = new window.LanPlayPlayer(
|
||||
this.$refs.video,
|
||||
this.$refs.videoWrapper,
|
||||
(message) => { this.error = message; },
|
||||
(loading, compact = false) => {
|
||||
this.playerLoading = loading;
|
||||
this.playerLoadingCompact = loading && compact;
|
||||
},
|
||||
() => { this.playNext(); }
|
||||
);
|
||||
}
|
||||
this.playerController.setNextAvailable(Boolean(this.nextEntry()));
|
||||
try { await this.playerController.play(entry); }
|
||||
catch (error) { this.error = error.message; }
|
||||
finally {
|
||||
this.playerLoading = false;
|
||||
this.playerLoadingCompact = false;
|
||||
}
|
||||
},
|
||||
|
||||
nextEntry() {
|
||||
if (!this.selected) return null;
|
||||
const media = this.entries.filter((entry) => entry.kind === 'media');
|
||||
const index = media.findIndex((entry) => entry.path === this.selected.path);
|
||||
return index >= 0 ? media[index + 1] || null : null;
|
||||
},
|
||||
|
||||
async playNext() {
|
||||
const next = this.nextEntry();
|
||||
if (next) await this.play(next);
|
||||
},
|
||||
|
||||
mediaTitle() {
|
||||
if (!this.selected || !this.selected.name) return '';
|
||||
return this.selected.name.replace(/\.[^.]+$/, '');
|
||||
},
|
||||
|
||||
setViewMode(mode) {
|
||||
this.viewMode = mode === 'table' ? 'table' : 'grid';
|
||||
try { localStorage.setItem('lan-play:view', this.viewMode); } catch (_) {}
|
||||
this.$nextTick(() => this.scheduleMarqueeCheck());
|
||||
},
|
||||
|
||||
scheduleMarqueeCheck() {
|
||||
if (this.marqueeFrame) window.cancelAnimationFrame(this.marqueeFrame);
|
||||
this.marqueeFrame = window.requestAnimationFrame(() => {
|
||||
this.marqueeFrame = null;
|
||||
document.querySelectorAll('.entry-name').forEach((container) => {
|
||||
if (container.clientWidth <= 0) return;
|
||||
const text = container.querySelector('.entry-name-track');
|
||||
container.classList.toggle('is-overflowing', Boolean(text) && text.scrollWidth > container.clientWidth + 1);
|
||||
});
|
||||
});
|
||||
},
|
||||
|
||||
openEntry(entry) {
|
||||
return entry.kind === 'directory' ? this.browse(entry.path) : this.play(entry);
|
||||
},
|
||||
|
||||
async openInfo() {
|
||||
this.infoOpen = true;
|
||||
this.infoLoading = true;
|
||||
this.infoError = '';
|
||||
try {
|
||||
const server = await window.LanPlayApi.info();
|
||||
let dashVersion = 'Unknown';
|
||||
try { dashVersion = dashjs.MediaPlayer().create().getVersion(); } catch (_) {}
|
||||
this.diagnostics = {
|
||||
...server,
|
||||
interface: '20',
|
||||
dashjs: dashVersion,
|
||||
browser: navigator.userAgent,
|
||||
display: `${window.screen.width}×${window.screen.height} @ ${window.devicePixelRatio || 1}x`,
|
||||
fullscreen: Boolean(document.documentElement.requestFullscreen || document.documentElement.webkitRequestFullscreen),
|
||||
mediaSource: 'MediaSource' in window
|
||||
};
|
||||
} catch (error) {
|
||||
this.infoError = error.message;
|
||||
} finally {
|
||||
this.infoLoading = false;
|
||||
}
|
||||
},
|
||||
|
||||
closeInfo() {
|
||||
this.infoOpen = false;
|
||||
},
|
||||
|
||||
previewStyle(entry) {
|
||||
if (this.previewStates[entry.path] !== 'ready') return '';
|
||||
const url = this.previewUrls[entry.path];
|
||||
if (!url) return '';
|
||||
const frame = this.previewFrames[entry.path] || 0;
|
||||
const column = frame % 5;
|
||||
const row = Math.floor(frame / 5);
|
||||
return `background-image:url("${url}");background-position:${column * 25}% ${row * 100}%`;
|
||||
},
|
||||
|
||||
startPreview(entry) {
|
||||
if (!entry || entry.kind !== 'media') return;
|
||||
this.previewActive[entry.path] = true;
|
||||
this.stopPreview(entry);
|
||||
this.previewActive[entry.path] = true;
|
||||
if (this.previewStates[entry.path] !== 'ready') return;
|
||||
this.previewFrames[entry.path] = 0;
|
||||
this.previewTimers[entry.path] = window.setInterval(() => {
|
||||
this.previewFrames[entry.path] = ((this.previewFrames[entry.path] || 0) + 1) % 10;
|
||||
}, 500);
|
||||
},
|
||||
|
||||
stopPreview(entry) {
|
||||
if (!entry) return;
|
||||
this.previewActive[entry.path] = false;
|
||||
const timer = this.previewTimers[entry.path];
|
||||
if (timer) window.clearInterval(timer);
|
||||
delete this.previewTimers[entry.path];
|
||||
this.previewFrames[entry.path] = 0;
|
||||
},
|
||||
|
||||
stopAllPreviews() {
|
||||
Object.values(this.previewTimers).forEach((timer) => window.clearInterval(timer));
|
||||
this.previewTimers = {};
|
||||
this.previewActive = {};
|
||||
},
|
||||
|
||||
preloadPreviews(entries) {
|
||||
const generation = this.previewGeneration;
|
||||
entries.filter((entry) => entry.kind === 'media').forEach((entry) => {
|
||||
const path = entry.path;
|
||||
const url = `/api/preview?path=${encodeURIComponent(path)}`;
|
||||
const image = new Image();
|
||||
this.previewUrls[path] = url;
|
||||
this.previewStates[path] = 'loading';
|
||||
this.previewImages[path] = image;
|
||||
image.onload = () => {
|
||||
if (generation !== this.previewGeneration) return;
|
||||
this.previewStates[path] = 'ready';
|
||||
delete this.previewImages[path];
|
||||
if (this.previewActive[path]) this.startPreview(entry);
|
||||
};
|
||||
image.onerror = () => {
|
||||
if (generation !== this.previewGeneration) return;
|
||||
this.previewStates[path] = 'error';
|
||||
delete this.previewImages[path];
|
||||
};
|
||||
image.src = url;
|
||||
});
|
||||
},
|
||||
|
||||
cancelPreviewLoads() {
|
||||
this.previewGeneration += 1;
|
||||
Object.values(this.previewImages).forEach((image) => {
|
||||
image.onload = null;
|
||||
image.onerror = null;
|
||||
image.src = '';
|
||||
});
|
||||
this.previewImages = {};
|
||||
this.previewFrames = {};
|
||||
this.previewUrls = {};
|
||||
this.previewStates = {};
|
||||
},
|
||||
|
||||
enterFullscreen() {
|
||||
if (document.fullscreenElement || document.webkitFullscreenElement) return;
|
||||
const root = document.documentElement;
|
||||
const request = root.requestFullscreen || root.webkitRequestFullscreen;
|
||||
if (request) {
|
||||
try {
|
||||
const result = request.call(root);
|
||||
if (result && result.catch) result.catch(() => {});
|
||||
} catch (_) {}
|
||||
}
|
||||
},
|
||||
|
||||
exitFullscreen() {
|
||||
if (!document.fullscreenElement && !document.webkitFullscreenElement) return;
|
||||
const exit = document.exitFullscreen || document.webkitExitFullscreen;
|
||||
if (exit) {
|
||||
try {
|
||||
const result = exit.call(document);
|
||||
if (result && result.catch) result.catch(() => {});
|
||||
} catch (_) {}
|
||||
}
|
||||
},
|
||||
|
||||
async closePlayer(updateLocation = true) {
|
||||
this.exitFullscreen();
|
||||
this.selected = null;
|
||||
this.playerLoading = false;
|
||||
this.playerLoadingCompact = false;
|
||||
if (updateLocation) window.LanPlayLocation.write(this.currentPath, null, false);
|
||||
await this.$nextTick();
|
||||
if (this.playerController) this.playerController.stop();
|
||||
}
|
||||
}));
|
||||
});
|
||||
@@ -0,0 +1,24 @@
|
||||
(function () {
|
||||
function read() {
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
return {
|
||||
path: params.get('path') || '',
|
||||
play: params.get('play') || null
|
||||
};
|
||||
}
|
||||
|
||||
function write(path, play, replace) {
|
||||
const url = new URL(window.location.href);
|
||||
path ? url.searchParams.set('path', path) : url.searchParams.delete('path');
|
||||
play ? url.searchParams.set('play', play) : url.searchParams.delete('play');
|
||||
const next = `${url.pathname}${url.search}`;
|
||||
window.history[replace ? 'replaceState' : 'pushState']({}, '', next);
|
||||
}
|
||||
|
||||
function fileName(path) {
|
||||
const parts = path.split('/');
|
||||
return parts[parts.length - 1] || path;
|
||||
}
|
||||
|
||||
window.LanPlayLocation = { read, write, fileName };
|
||||
})();
|
||||
@@ -0,0 +1,265 @@
|
||||
(function () {
|
||||
class LanPlayPlayer {
|
||||
constructor(video, wrapper, onError, onLoading, onNext) {
|
||||
this.video = video;
|
||||
this.wrapper = wrapper;
|
||||
this.onError = onError;
|
||||
this.onLoading = onLoading;
|
||||
this.onNext = onNext;
|
||||
this.dashPlayer = null;
|
||||
this.controlBar = null;
|
||||
this.sessionId = null;
|
||||
this.mediaPath = null;
|
||||
this.dashPreferencesApplied = false;
|
||||
this.currentEntry = null;
|
||||
this.nextAvailable = false;
|
||||
this.restarting = false;
|
||||
this.operation = 0;
|
||||
this.freezeFrame = null;
|
||||
this.playingHandler = null;
|
||||
this.subtitleUrls = [];
|
||||
}
|
||||
|
||||
async play(entry, startSeconds = 0, preserveFrame = false) {
|
||||
const framePreserved = preserveFrame && this.captureFrame();
|
||||
this.onLoading(true, framePreserved);
|
||||
this.stop({ preserveFrame: framePreserved });
|
||||
const operation = ++this.operation;
|
||||
this.currentEntry = entry;
|
||||
this.mediaPath = entry.path;
|
||||
this.dashPreferencesApplied = false;
|
||||
const session = await window.LanPlayApi.startDash(entry.path, startSeconds);
|
||||
if (operation !== this.operation) {
|
||||
window.LanPlayApi.stopDash(session.session_id).catch(() => {});
|
||||
return;
|
||||
}
|
||||
this.sessionId = session.session_id;
|
||||
this.dashPlayer = dashjs.MediaPlayer().create();
|
||||
this.dashPlayer.updateSettings({
|
||||
streaming: {
|
||||
buffer: {
|
||||
bufferTimeDefault: 8,
|
||||
bufferTimeAtTopQuality: 8,
|
||||
bufferTimeAtTopQualityLongForm: 8
|
||||
}
|
||||
}
|
||||
});
|
||||
this.dashPlayer.initialize(this.video, null, true);
|
||||
await this.addExternalSubtitles(entry.path, session.start_seconds, operation);
|
||||
if (operation !== this.operation) return;
|
||||
this.controlBar = new DashControlBarModule.ControlBar(this.dashPlayer, this.video);
|
||||
this.controlBar.init(this.wrapper);
|
||||
this.controlBar.setVodDuration(session.duration_seconds, session.start_seconds);
|
||||
if (typeof this.controlBar.onSeekRequested === 'function') {
|
||||
this.controlBar.onSeekRequested((time) => this.seek(time));
|
||||
}
|
||||
if (typeof this.controlBar.onNextRequested === 'function') {
|
||||
this.controlBar.onNextRequested(() => this.onNext());
|
||||
}
|
||||
if (typeof this.controlBar.setNextAvailable === 'function') {
|
||||
this.controlBar.setNextAvailable(this.nextAvailable);
|
||||
}
|
||||
this.controlBar.onTrackSelected((type, track) => this.rememberTrack(type, track));
|
||||
this.controlBar.disable();
|
||||
const controlBar = this.controlBar;
|
||||
this.dashPlayer.on(dashjs.MediaPlayer.events.ERROR, (event) => {
|
||||
if (operation !== this.operation) return;
|
||||
const message = event && event.error && event.error.message;
|
||||
this.onError(message || 'DASH playback error');
|
||||
});
|
||||
this.dashPlayer.on(dashjs.MediaPlayer.events.STREAM_INITIALIZED, () => {
|
||||
if (operation !== this.operation || this.controlBar !== controlBar) return;
|
||||
this.applyDashPreferences();
|
||||
controlBar.enable();
|
||||
controlBar.refreshTracks();
|
||||
});
|
||||
this.playingHandler = () => {
|
||||
if (operation !== this.operation) return;
|
||||
this.playingHandler = null;
|
||||
this.clearFreezeFrame();
|
||||
this.onLoading(false, false);
|
||||
};
|
||||
this.video.addEventListener('playing', this.playingHandler, { once: true });
|
||||
this.dashPlayer.attachSource(session.manifest_url);
|
||||
if (!framePreserved) this.onLoading(false, false);
|
||||
}
|
||||
|
||||
async seek(time) {
|
||||
if (this.restarting || !this.currentEntry) return;
|
||||
this.restarting = true;
|
||||
const entry = this.currentEntry;
|
||||
try { await this.play(entry, time, true); }
|
||||
catch (error) {
|
||||
this.onError(error.message);
|
||||
this.clearFreezeFrame();
|
||||
this.onLoading(false, false);
|
||||
} finally { this.restarting = false; }
|
||||
}
|
||||
|
||||
setNextAvailable(available) {
|
||||
this.nextAvailable = Boolean(available);
|
||||
if (this.controlBar && typeof this.controlBar.setNextAvailable === 'function') {
|
||||
this.controlBar.setNextAvailable(this.nextAvailable);
|
||||
}
|
||||
}
|
||||
|
||||
applyDashPreferences() {
|
||||
if (this.dashPreferencesApplied || !this.mediaPath) return;
|
||||
['audio', 'video'].forEach((type) => {
|
||||
const tracks = this.dashPlayer.getTracksFor(type) || [];
|
||||
const preferred = window.LanPlayPreferences.find(this.mediaPath, type, tracks);
|
||||
if (preferred) this.dashPlayer.setCurrentTrack(preferred);
|
||||
});
|
||||
const textTracks = this.dashPlayer.getTracksFor('text') || [];
|
||||
const preferredText = window.LanPlayPreferences.find(this.mediaPath, 'subtitle', textTracks);
|
||||
if (preferredText === null) {
|
||||
this.dashPlayer.setTextTrack(-1);
|
||||
} else if (preferredText) {
|
||||
const index = textTracks.indexOf(preferredText);
|
||||
if (index >= 0) this.dashPlayer.setTextTrack(index);
|
||||
}
|
||||
this.dashPreferencesApplied = true;
|
||||
}
|
||||
|
||||
rememberTrack(type, track) {
|
||||
if (!this.mediaPath) return;
|
||||
if (type === 'nativeText') {
|
||||
const tracks = Array.from(this.video.textTracks || []);
|
||||
window.LanPlayPreferences.remember(this.mediaPath, 'subtitle', track, tracks.indexOf(track));
|
||||
return;
|
||||
}
|
||||
const preferenceType = type === 'text' ? 'subtitle' : type;
|
||||
const tracks = this.dashPlayer.getTracksFor(type) || [];
|
||||
window.LanPlayPreferences.remember(this.mediaPath, preferenceType, track, tracks.indexOf(track));
|
||||
}
|
||||
|
||||
async addExternalSubtitles(path, startSeconds = 0, operation = this.operation) {
|
||||
let subtitles = [];
|
||||
try { subtitles = await window.LanPlayApi.subtitles(path); } catch (_) { return; }
|
||||
if (operation !== this.operation) return;
|
||||
const loaded = await Promise.all(subtitles.filter((item) => item.supported).map(async (subtitle, ordinal) => {
|
||||
const query = new URLSearchParams({ path, start: String(startSeconds) });
|
||||
const url = subtitle.source === 'external'
|
||||
? `/api/subtitles/external/${encodeURIComponent(subtitle.id)}?${query}`
|
||||
: `/api/subtitles/${subtitle.index}?${query}`;
|
||||
try {
|
||||
const response = await fetch(url);
|
||||
if (!response.ok) return null;
|
||||
const contents = await response.text();
|
||||
const objectUrl = URL.createObjectURL(new Blob([contents], { type: 'text/vtt' }));
|
||||
return { subtitle, ordinal, objectUrl };
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
}));
|
||||
if (operation !== this.operation) {
|
||||
loaded.filter(Boolean).forEach((item) => URL.revokeObjectURL(item.objectUrl));
|
||||
return;
|
||||
}
|
||||
loaded.filter(Boolean).forEach(({ subtitle, ordinal, objectUrl }) => {
|
||||
const label = subtitle.title || subtitle.language || `Subtitle ${ordinal + 1}`;
|
||||
const idPart = subtitle.source === 'external' ? subtitle.id : subtitle.index;
|
||||
this.subtitleUrls.push(objectUrl);
|
||||
this.dashPlayer.addExternalSubtitle(new dashjs.ExternalSubtitle({
|
||||
id: `lan-play-${subtitle.source}-${idPart}`,
|
||||
url: objectUrl,
|
||||
language: label,
|
||||
mimeType: 'text/vtt',
|
||||
bandwidth: 256,
|
||||
periodId: '0'
|
||||
}));
|
||||
});
|
||||
}
|
||||
|
||||
captureFrame() {
|
||||
if (this.video.readyState < 2 || !this.video.videoWidth || !this.video.videoHeight) return false;
|
||||
try {
|
||||
this.clearFreezeFrame();
|
||||
const canvas = document.createElement('canvas');
|
||||
const width = Math.max(1, this.wrapper.clientWidth);
|
||||
const height = Math.max(1, this.wrapper.clientHeight);
|
||||
canvas.width = Math.min(width, 1920);
|
||||
canvas.height = Math.min(height, 1080);
|
||||
canvas.className = 'player-freeze-frame';
|
||||
const context = canvas.getContext('2d');
|
||||
context.fillStyle = '#000';
|
||||
context.fillRect(0, 0, canvas.width, canvas.height);
|
||||
const scale = Math.min(canvas.width / this.video.videoWidth, canvas.height / this.video.videoHeight);
|
||||
const drawWidth = this.video.videoWidth * scale;
|
||||
const drawHeight = this.video.videoHeight * scale;
|
||||
context.drawImage(
|
||||
this.video,
|
||||
(canvas.width - drawWidth) / 2,
|
||||
(canvas.height - drawHeight) / 2,
|
||||
drawWidth,
|
||||
drawHeight
|
||||
);
|
||||
this.wrapper.appendChild(canvas);
|
||||
this.freezeFrame = canvas;
|
||||
return true;
|
||||
} catch (_) {
|
||||
this.clearFreezeFrame();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
clearFreezeFrame() {
|
||||
if (this.freezeFrame) this.freezeFrame.remove();
|
||||
this.freezeFrame = null;
|
||||
}
|
||||
|
||||
stop(options = {}) {
|
||||
this.operation += 1;
|
||||
if (this.playingHandler) {
|
||||
this.video.removeEventListener('playing', this.playingHandler);
|
||||
this.playingHandler = null;
|
||||
}
|
||||
if (!options.preserveFrame) this.clearFreezeFrame();
|
||||
this.revokeSubtitleUrls();
|
||||
if (this.controlBar) {
|
||||
this.controlBar.destroy();
|
||||
this.controlBar = null;
|
||||
}
|
||||
if (this.dashPlayer) {
|
||||
this.dashPlayer.destroy();
|
||||
this.dashPlayer = null;
|
||||
}
|
||||
this.video.pause();
|
||||
this.video.removeAttribute('src');
|
||||
while (this.video.firstChild) this.video.removeChild(this.video.firstChild);
|
||||
this.video.load();
|
||||
this.mediaPath = null;
|
||||
this.dashPreferencesApplied = false;
|
||||
this.currentEntry = null;
|
||||
if (this.sessionId) {
|
||||
const sessionId = this.sessionId;
|
||||
this.sessionId = null;
|
||||
window.LanPlayApi.stopDash(sessionId).catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
dispose() {
|
||||
this.operation += 1;
|
||||
if (this.playingHandler) this.video.removeEventListener('playing', this.playingHandler);
|
||||
this.playingHandler = null;
|
||||
this.clearFreezeFrame();
|
||||
this.revokeSubtitleUrls();
|
||||
if (this.controlBar) this.controlBar.destroy();
|
||||
if (this.dashPlayer) this.dashPlayer.destroy();
|
||||
if (this.sessionId) {
|
||||
fetch(`/api/dash/${this.sessionId}`, { method: 'DELETE', keepalive: true }).catch(() => {});
|
||||
}
|
||||
this.controlBar = null;
|
||||
this.dashPlayer = null;
|
||||
this.sessionId = null;
|
||||
this.currentEntry = null;
|
||||
}
|
||||
|
||||
revokeSubtitleUrls() {
|
||||
this.subtitleUrls.forEach((url) => URL.revokeObjectURL(url));
|
||||
this.subtitleUrls = [];
|
||||
}
|
||||
}
|
||||
|
||||
window.LanPlayPlayer = LanPlayPlayer;
|
||||
})();
|
||||
@@ -0,0 +1,63 @@
|
||||
(function () {
|
||||
const prefix = 'lan-play:release:v1:';
|
||||
|
||||
function folder(path) {
|
||||
const index = path.lastIndexOf('/');
|
||||
return index < 0 ? '' : path.slice(0, index);
|
||||
}
|
||||
|
||||
function key(path) {
|
||||
return `${prefix}${folder(path)}`;
|
||||
}
|
||||
|
||||
function load(path) {
|
||||
try { return JSON.parse(localStorage.getItem(key(path))) || {}; }
|
||||
catch (_) { return {}; }
|
||||
}
|
||||
|
||||
function store(path, value) {
|
||||
try { localStorage.setItem(key(path), JSON.stringify(value)); } catch (_) {}
|
||||
}
|
||||
|
||||
function label(track) {
|
||||
const labels = track && track.labels || [];
|
||||
const selected = labels.find((item) => item.text) || labels[0];
|
||||
return selected && selected.text || track && track.label || '';
|
||||
}
|
||||
|
||||
function descriptor(track, ordinal) {
|
||||
if (!track) return { off: true };
|
||||
return {
|
||||
off: false,
|
||||
lang: track.lang || track.language || '',
|
||||
label: label(track),
|
||||
roles: (track.roles || []).map((role) => role.value || role).filter(Boolean).sort(),
|
||||
ordinal
|
||||
};
|
||||
}
|
||||
|
||||
function remember(path, type, track, ordinal) {
|
||||
const profile = load(path);
|
||||
profile[type] = descriptor(track, ordinal);
|
||||
store(path, profile);
|
||||
}
|
||||
|
||||
function find(path, type, tracks) {
|
||||
const wanted = load(path)[type];
|
||||
if (!wanted) return undefined;
|
||||
if (wanted.off) return null;
|
||||
const described = tracks.map((track, ordinal) => ({ track, ordinal, value: descriptor(track, ordinal) }));
|
||||
let matches = described.filter((item) => wanted.lang && item.value.lang === wanted.lang);
|
||||
if (wanted.label) {
|
||||
const labeled = matches.filter((item) => item.value.label === wanted.label);
|
||||
if (labeled.length) matches = labeled;
|
||||
}
|
||||
if (!matches.length && wanted.label) {
|
||||
matches = described.filter((item) => item.value.label === wanted.label);
|
||||
}
|
||||
if (!matches.length && !wanted.lang && !wanted.label) matches = described;
|
||||
return (matches.find((item) => item.ordinal === wanted.ordinal) || matches[0] || {}).track;
|
||||
}
|
||||
|
||||
window.LanPlayPreferences = { folder, load, remember, find };
|
||||
})();
|
||||
@@ -0,0 +1,36 @@
|
||||
const assert = require('node:assert/strict');
|
||||
const test = require('node:test');
|
||||
|
||||
const values = new Map();
|
||||
global.window = global;
|
||||
global.localStorage = {
|
||||
getItem: (key) => values.get(key) || null,
|
||||
setItem: (key, value) => values.set(key, value)
|
||||
};
|
||||
require('./preferences.js');
|
||||
|
||||
test('restores a matching track for the next file in the same folder', () => {
|
||||
const firstEpisode = 'Anime/Show/episode-01.mkv';
|
||||
const nextEpisode = 'Anime/Show/episode-02.mkv';
|
||||
const tracks = [{ lang: 'en' }, { lang: 'ja' }];
|
||||
LanPlayPreferences.remember(firstEpisode, 'audio', tracks[1], 1);
|
||||
assert.equal(LanPlayPreferences.find(nextEpisode, 'audio', tracks), tracks[1]);
|
||||
});
|
||||
|
||||
test('does not apply a profile from another folder', () => {
|
||||
const tracks = [{ lang: 'ja' }];
|
||||
assert.equal(LanPlayPreferences.find('Anime/Other/episode-01.mkv', 'audio', tracks), undefined);
|
||||
});
|
||||
|
||||
test('falls back to the player default when the saved track is unavailable', () => {
|
||||
const tracks = [{ lang: 'en' }];
|
||||
assert.equal(LanPlayPreferences.find('Anime/Show/episode-03.mkv', 'audio', tracks), undefined);
|
||||
});
|
||||
|
||||
test('remembers disabled subtitles for the release folder', () => {
|
||||
LanPlayPreferences.remember('Series/Season/episode-01.mkv', 'subtitle', null, -1);
|
||||
assert.equal(
|
||||
LanPlayPreferences.find('Series/Season/episode-02.mkv', 'subtitle', [{ language: 'en' }]),
|
||||
null
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,61 @@
|
||||
:root { color-scheme: dark; font-family: system-ui, sans-serif; background: #101216; color: #f4f4f4; }
|
||||
* { box-sizing: border-box; }
|
||||
body { margin: 0; }
|
||||
body.player-open { overflow: hidden; }
|
||||
[x-cloak] { display: none !important; }
|
||||
header { position: sticky; top: 0; display: flex; align-items: center; justify-content: space-between; gap: 1rem; padding: 1rem 2rem; background: #181b21; z-index: 1; }
|
||||
h1 { margin: 0 0 .35rem; }
|
||||
.path { color: #aab2c0; }
|
||||
.view-switch { display: flex; gap: .35rem; padding: .3rem; border-radius: .55rem; background: #101216; }
|
||||
.view-switch button { width: 2.7rem; height: 2.35rem; border: 0; border-radius: .4rem; background: transparent; color: #aab2c0; font-size: 1.15rem; cursor: pointer; }
|
||||
.view-switch button.active { background: #354156; color: #fff; }
|
||||
.view-switch button:hover, .view-switch button:focus { outline: none; background: #303746; color: #fff; }
|
||||
main { padding: 1.5rem 2rem; }
|
||||
.entries { display: grid; grid-template-columns: repeat(auto-fill, minmax(16rem, 1fr)); gap: .9rem; }
|
||||
.entries button { min-width: 0; min-height: 3.5rem; padding: .65rem; border: 2px solid transparent; border-radius: .6rem; background: #252a33; color: inherit; text-align: left; font-size: 1.05rem; cursor: pointer; }
|
||||
.entries button.media, .entries button.directory { display: grid; grid-template-rows: auto auto; gap: .65rem; }
|
||||
.entry-preview { display: grid; place-items: center; min-height: 2.2rem; border-radius: .4rem; font-size: 1.35rem; }
|
||||
.entry-preview-media { width: 100%; aspect-ratio: 16 / 9; min-height: 0; overflow: hidden; background-color: #171a20; background-repeat: no-repeat; background-size: 500% 200%; font-size: 2rem; transition: background-image .15s ease; }
|
||||
.preview-spinner { animation: player-spin 1s linear infinite; color: #aab2c0; }
|
||||
.entry-name { display: block; width: 100%; overflow: hidden; white-space: nowrap; }
|
||||
.entry-name-track { display: inline-block; min-width: max-content; }
|
||||
.entry-name.is-overflowing .entry-name-track { animation: entry-marquee 14s linear infinite; }
|
||||
@keyframes entry-marquee { from { transform: translateX(0); } to { transform: translateX(-100%); } }
|
||||
.entries button:focus { outline: none; border-color: #69a7ff; background: #303746; }
|
||||
.entry-table-wrap { overflow-x: auto; border: 1px solid #343a45; border-radius: .65rem; }
|
||||
.entry-table { width: 100%; border-collapse: collapse; table-layout: fixed; background: #20242c; }
|
||||
.entry-table th { padding: .65rem .8rem; color: #aab2c0; background: #181b21; text-align: left; font-size: .85rem; text-transform: uppercase; letter-spacing: .04em; }
|
||||
.entry-table th:first-child { width: 11rem; }
|
||||
.entry-table th:last-child { width: 7rem; }
|
||||
.entry-table td { height: 5.25rem; padding: .45rem .8rem; border-top: 1px solid #343a45; overflow: hidden; color: #dce1e8; }
|
||||
.entry-table tbody tr { cursor: pointer; }
|
||||
.entry-table tbody tr:hover, .entry-table tbody tr:focus { outline: none; background: #303746; }
|
||||
.table-preview { display: grid; place-items: center; width: 8rem; aspect-ratio: 16 / 9; overflow: hidden; border-radius: .35rem; background-color: #171a20; background-repeat: no-repeat; background-size: 500% 200%; font-size: 1.35rem; }
|
||||
.table-name { font-size: 1rem; }
|
||||
.info-backdrop { position: fixed; inset: 0; z-index: 60; display: grid; place-items: center; padding: 1.5rem; background: rgba(0,0,0,.72); }
|
||||
.info-dialog { position: relative; width: min(46rem, 100%); max-height: calc(100vh - 3rem); overflow: auto; padding: 1.4rem 1.5rem 1.5rem; border: 1px solid #465064; border-radius: .8rem; background: #1d222b; box-shadow: 0 1rem 4rem rgba(0,0,0,.55); }
|
||||
.info-dialog h2 { margin: 0 3rem 1.2rem 0; }
|
||||
.info-close { position: absolute; top: .9rem; right: .9rem; width: 2.5rem; height: 2.5rem; border: 0; border-radius: 50%; background: #303746; color: #fff; cursor: pointer; }
|
||||
.info-loading { display: flex; align-items: center; gap: .65rem; color: #aab2c0; }
|
||||
.info-grid { display: grid; grid-template-columns: 8rem minmax(0, 1fr); gap: .7rem 1rem; margin: 0; }
|
||||
.info-grid dt { color: #9ea8b8; }
|
||||
.info-grid dd { min-width: 0; margin: 0; overflow-wrap: anywhere; }
|
||||
.info-grid small { display: block; margin-top: .2rem; color: #7f8999; }
|
||||
.info-browser { font-size: .82rem; color: #b9c0cb; }
|
||||
@media (max-width: 38rem) { .info-grid { grid-template-columns: 1fr; gap: .2rem; } .info-grid dd { margin-bottom: .65rem; } }
|
||||
.error { color: #ff8989; }
|
||||
.player { position: fixed; inset: 0; z-index: 5; display: flex; flex-direction: column; background: #000; }
|
||||
.player-close { position: absolute; top: 1.25rem; right: 1.25rem; z-index: 40; width: 4rem; height: 4rem; display: grid; place-items: center; padding: 0; border: 2px solid rgba(255,255,255,.7); border-radius: 50%; background: rgba(0,0,0,.65); color: #fff; font-size: 1.8rem; cursor: pointer; opacity: 1; transition: opacity .2s ease, transform .2s ease; }
|
||||
.player-close.player-close-hidden { opacity: 0; pointer-events: none; }
|
||||
.player-close:hover, .player-close:focus { outline: none; border-color: #fff; background: rgba(30,35,45,.95); transform: scale(1.05); }
|
||||
.video-wrapper { position: relative; flex: 1; min-height: 0; overflow: hidden; }
|
||||
.video-wrapper video { display: block; width: 100%; height: 100%; object-fit: contain; }
|
||||
.player-title { position: absolute; inset: 0 0 auto; z-index: 18; min-height: 7rem; padding: 1.4rem 6.5rem 3rem 1.6rem; overflow: hidden; color: #fff; background: linear-gradient(to bottom, rgba(0,0,0,.78) 0%, rgba(0,0,0,.42) 42%, transparent 100%); font-size: clamp(1.05rem, 2vw, 1.55rem); font-weight: 600; line-height: 1.3; text-overflow: ellipsis; white-space: nowrap; text-shadow: 0 1px 3px #000; opacity: 1; transition: opacity .2s ease; pointer-events: none; }
|
||||
.player-title.player-title-hidden { opacity: 0; }
|
||||
.player-freeze-frame { position: absolute; inset: 0; z-index: 15; width: 100%; height: 100%; object-fit: contain; background: #000; }
|
||||
.video-wrapper .cb-controlbar { --cb-accent: #69a7ff; font-family: system-ui, sans-serif; }
|
||||
.player-status { position: absolute; inset: 0; z-index: 20; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 1rem; color: #f4f4f4; background: #000; font-size: 1.1rem; }
|
||||
.player-status-compact { inset: 1rem auto auto 50%; transform: translateX(-50%); flex-direction: row; padding: .6rem .9rem; border-radius: .5rem; background: rgba(0,0,0,.72); font-size: .9rem; white-space: nowrap; pointer-events: none; }
|
||||
.player-status-compact .player-spinner { font-size: 1.15rem; }
|
||||
.player-spinner { font-size: 3rem; animation: player-spin 1s linear infinite; }
|
||||
@keyframes player-spin { to { transform: rotate(360deg); } }
|
||||
Vendored
+21
@@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2019-2024 The Bootstrap Authors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
File diff suppressed because one or more lines are too long
Binary file not shown.
Vendored
+1317
File diff suppressed because it is too large
Load Diff
Vendored
+339
@@ -0,0 +1,339 @@
|
||||
/* ============================================================
|
||||
dash.js Controlbar – Standalone CSS
|
||||
============================================================
|
||||
Include this stylesheet alongside ControlBar.js.
|
||||
Requires Bootstrap Icons CSS for icon display.
|
||||
|
||||
Theming: override --cb-accent and --cb-danger on the
|
||||
.cb-controlbar selector (or any ancestor) to customise
|
||||
highlight and live-indicator colours.
|
||||
============================================================ */
|
||||
|
||||
/* ---- Default theme variables ---- */
|
||||
.cb-controlbar {
|
||||
--cb-accent: #5b8def;
|
||||
--cb-danger: #e74c3c;
|
||||
}
|
||||
|
||||
.cb-skip-btn {
|
||||
min-width: 2.5rem;
|
||||
font-size: 0.8rem;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
/* ---- Utility: hidden element (replaces Bootstrap d-none) ---- */
|
||||
.cb-hidden-element {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
/* ---- Control Bar container ---- */
|
||||
.cb-controlbar {
|
||||
position: absolute;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
background: linear-gradient(transparent, rgba(0, 0, 0, 0.85));
|
||||
padding: 2rem 1rem 0.5rem 1rem;
|
||||
z-index: 10;
|
||||
transition: opacity 0.3s ease, visibility 0.3s ease;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.35rem;
|
||||
}
|
||||
|
||||
.cb-controlbar.cb-hidden {
|
||||
opacity: 0;
|
||||
visibility: hidden;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.cb-controlbar.cb-disabled {
|
||||
pointer-events: none;
|
||||
opacity: 0.3;
|
||||
}
|
||||
|
||||
/* ---- Seekbar ---- */
|
||||
.cb-seekbar-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.cb-seekbar {
|
||||
flex: 1;
|
||||
height: 4px;
|
||||
background: rgba(255, 255, 255, 0.2);
|
||||
border-radius: 2px;
|
||||
position: relative;
|
||||
cursor: pointer;
|
||||
transition: height 0.1s;
|
||||
}
|
||||
|
||||
.cb-seekbar:hover {
|
||||
height: 6px;
|
||||
}
|
||||
|
||||
.cb-seekbar-buffer {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
height: 100%;
|
||||
background: rgba(255, 255, 255, 0.3);
|
||||
border-radius: 2px;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.cb-seekbar-played {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
height: 100%;
|
||||
background: var(--cb-accent);
|
||||
border-radius: 2px;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.cb-seekbar-played::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
right: -6px;
|
||||
top: 50%;
|
||||
transform: translateY(-50%);
|
||||
width: 12px;
|
||||
height: 12px;
|
||||
background: var(--cb-accent);
|
||||
border-radius: 50%;
|
||||
opacity: 0;
|
||||
transition: opacity 0.1s;
|
||||
}
|
||||
|
||||
.cb-seekbar:hover .cb-seekbar-played::after {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
/* ---- Control buttons row ---- */
|
||||
.cb-controls-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.cb-btn {
|
||||
background: none;
|
||||
border: none;
|
||||
color: #fff;
|
||||
font-size: 1.1rem;
|
||||
cursor: pointer;
|
||||
padding: 0.25rem;
|
||||
opacity: 0.85;
|
||||
transition: opacity 0.15s;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.cb-btn:hover {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.cb-time {
|
||||
font-size: 0.8rem;
|
||||
color: #fff;
|
||||
font-variant-numeric: tabular-nums;
|
||||
white-space: nowrap;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.cb-time-separator {
|
||||
opacity: 0.4;
|
||||
}
|
||||
|
||||
.cb-spacer {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
/* ---- Volume ---- */
|
||||
.cb-volume-group {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.25rem;
|
||||
}
|
||||
|
||||
.cb-volume-slider {
|
||||
width: 80px;
|
||||
height: 4px;
|
||||
-webkit-appearance: none;
|
||||
appearance: none;
|
||||
background: rgba(255, 255, 255, 0.3);
|
||||
border-radius: 2px;
|
||||
outline: none;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.cb-volume-slider::-webkit-slider-thumb {
|
||||
-webkit-appearance: none;
|
||||
width: 12px;
|
||||
height: 12px;
|
||||
background: #fff;
|
||||
border-radius: 50%;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.cb-volume-slider::-moz-range-thumb {
|
||||
width: 12px;
|
||||
height: 12px;
|
||||
background: #fff;
|
||||
border-radius: 50%;
|
||||
cursor: pointer;
|
||||
border: none;
|
||||
}
|
||||
|
||||
/* ---- Playback rate controls ---- */
|
||||
.cb-rate-group {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.15rem;
|
||||
margin: 0 0.25rem;
|
||||
}
|
||||
|
||||
.cb-rate-display {
|
||||
color: #e0e0e0;
|
||||
font-size: 0.75rem;
|
||||
min-width: 2.5rem;
|
||||
text-align: center;
|
||||
cursor: pointer;
|
||||
user-select: none;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.cb-rate-display:hover {
|
||||
color: #ffffff;
|
||||
}
|
||||
|
||||
.cb-btn-sm {
|
||||
font-size: 0.7rem;
|
||||
padding: 0.1rem 0.3rem;
|
||||
}
|
||||
|
||||
/* ---- Live indicator ---- */
|
||||
.cb-live-indicator {
|
||||
cursor: pointer;
|
||||
color: #8a8aa0;
|
||||
}
|
||||
|
||||
.cb-live-indicator.cb-at-live-edge {
|
||||
color: var(--cb-danger);
|
||||
}
|
||||
|
||||
.cb-live-indicator .bi-circle-fill {
|
||||
font-size: 0.5rem;
|
||||
vertical-align: middle;
|
||||
}
|
||||
|
||||
/* ---- Thumbnail preview ---- */
|
||||
.cb-thumbnail-container {
|
||||
position: absolute;
|
||||
bottom: 100%;
|
||||
pointer-events: none;
|
||||
z-index: 20;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.cb-thumbnail-elem {
|
||||
border: 2px solid #fff;
|
||||
border-radius: 4px;
|
||||
overflow: hidden;
|
||||
transform-origin: center bottom;
|
||||
}
|
||||
|
||||
.cb-thumbnail-time {
|
||||
font-size: 0.7rem;
|
||||
color: #fff;
|
||||
background: rgba(0, 0, 0, 0.7);
|
||||
padding: 1px 6px;
|
||||
border-radius: 3px;
|
||||
margin-top: 4px;
|
||||
display: inline-block;
|
||||
}
|
||||
|
||||
/* ---- Menu anchors and menus ---- */
|
||||
.cb-menu-anchor {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
/* Menus — always dark (overlays video) */
|
||||
.cb-menu {
|
||||
position: absolute;
|
||||
bottom: 100%;
|
||||
right: 0;
|
||||
background: rgba(20, 20, 40, 0.95);
|
||||
border: 1px solid #2d2d50;
|
||||
border-radius: 6px;
|
||||
min-width: 180px;
|
||||
max-height: min(400px, 60vh);
|
||||
overflow-y: auto;
|
||||
padding: 0.25rem 0;
|
||||
margin-bottom: 0.5rem;
|
||||
backdrop-filter: blur(10px);
|
||||
z-index: 30;
|
||||
}
|
||||
|
||||
/* Scrollbar styling for menus */
|
||||
.cb-menu::-webkit-scrollbar {
|
||||
width: 6px;
|
||||
}
|
||||
|
||||
.cb-menu::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.cb-menu::-webkit-scrollbar-thumb {
|
||||
background: rgba(255, 255, 255, 0.2);
|
||||
border-radius: 3px;
|
||||
}
|
||||
|
||||
.cb-menu::-webkit-scrollbar-thumb:hover {
|
||||
background: rgba(255, 255, 255, 0.35);
|
||||
}
|
||||
|
||||
/* Firefox scrollbar */
|
||||
.cb-menu {
|
||||
scrollbar-width: thin;
|
||||
scrollbar-color: rgba(255, 255, 255, 0.2) transparent;
|
||||
}
|
||||
|
||||
.cb-menu-title {
|
||||
padding: 0.35rem 0.75rem;
|
||||
font-size: 0.7rem;
|
||||
font-weight: 600;
|
||||
color: rgba(255, 255, 255, 0.5);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.03em;
|
||||
}
|
||||
|
||||
.cb-menu-item {
|
||||
padding: 0.35rem 0.75rem;
|
||||
font-size: 0.8rem;
|
||||
cursor: pointer;
|
||||
color: #e0e0e0;
|
||||
transition: background 0.1s;
|
||||
}
|
||||
|
||||
.cb-menu-item:hover {
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
}
|
||||
|
||||
.cb-menu-item-selected {
|
||||
color: var(--cb-accent);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.cb-menu-item-selected::before {
|
||||
content: '✓ ';
|
||||
}
|
||||
|
||||
/* ---- Fullscreen wrapper helper ---- */
|
||||
.cb-fullscreen {
|
||||
/* Applied to the wrapper element when entering fullscreen */
|
||||
}
|
||||
Reference in New Issue
Block a user