Compare commits

16 Commits

Author SHA1 Message Date
Ethanfel 9776b83ac5 fix: client bug fixes from review
- FileBrowser: reload hidden files when profile changes
- WebSocket: wrap JSON.parse in try-catch
- WebSocket: exponential backoff on reconnect (2s -> 30s max)
- WebSocket: clean up connection on destroy

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-16 20:09:21 +02:00
Ethanfel 39f873bec2 fix: server bug fixes from review
- DB: add threading.Lock on all write methods and multi-step reads
- export.py: check audio extraction return code, raise on failure
- routes/export: counter race condition fix with _counter_lock
- routes/export: delete validation accepts EXPORT_DIR_suffix siblings
- routes/export: evict old finished jobs to prevent unbounded growth
- client plan: fix 10 bugs (mpv IPC, encodePath, input_path sep, etc.)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-16 19:53:38 +02:00
Ethanfel 409eb82e5c feat: configure Linux packaging (deb + AppImage)
Renamed to 8-cut, 1200x800 window, .deb builds at 3.9MB.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-16 19:52:40 +02:00
Ethanfel 297aafa51c feat: add settings persistence via localStorage
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-16 19:50:01 +02:00
Ethanfel b4cf972d59 feat: wire up main app layout with all components
Sidebar file browser, canvas timeline, transport bar, export panel,
profile bar, keyboard shortcuts, quality-reactive stream reload.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-16 19:48:54 +02:00
Ethanfel 5cc1e52e75 feat: add profile bar component
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-16 19:10:32 +02:00
Ethanfel 6bf0b0ae99 feat: add export panel component
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-16 19:10:03 +02:00
Ethanfel b6fbda01dd feat: add canvas-based timeline component
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-16 19:07:21 +02:00
Ethanfel 51d41f0a56 feat: add file browser component
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-16 19:06:41 +02:00
Ethanfel 16bd1a9ae0 feat: add mpv TypeScript bridge
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-16 18:46:35 +02:00
Ethanfel 2036c49b52 feat: add mpv sidecar IPC and Tauri commands
Persistent BufReader + request_id matching for correct event handling.
Audio-file passed during loadfile for frame-accurate sync.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-16 18:46:01 +02:00
Ethanfel b12758c53c feat: add WebSocket client for export progress
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-16 18:41:12 +02:00
Ethanfel 3d484952c2 feat: add Svelte stores for app state
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-16 18:40:43 +02:00
Ethanfel 12dae93671 feat: add server API client module
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-16 18:34:23 +02:00
Ethanfel 1e65fd6b0f feat: scaffold Tauri + Svelte client
SvelteKit in SPA mode with Tauri v2. Builds and produces .deb bundle.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-16 18:33:45 +02:00
Ethanfel f7756320e5 docs: add Tauri + Svelte client implementation plan
15-task plan covering Rust install, Tauri scaffold, mpv sidecar,
API client, stores, UI components, keyboard shortcuts, and packaging.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-16 17:02:56 +02:00
56 changed files with 9951 additions and 55 deletions
+2
View File
@@ -3,3 +3,5 @@ __pycache__/
*.pyo
.pytest_cache/
.worktrees/
client/node_modules/
client/src-tauri/target/
+10
View File
@@ -0,0 +1,10 @@
.DS_Store
node_modules
/build
/.svelte-kit
/package
.env
.env.*
!.env.example
vite.config.js.timestamp-*
vite.config.ts.timestamp-*
+7
View File
@@ -0,0 +1,7 @@
{
"recommendations": [
"svelte.svelte-vscode",
"tauri-apps.tauri-vscode",
"rust-lang.rust-analyzer"
]
}
+3
View File
@@ -0,0 +1,3 @@
{
"svelte.enable-ts-plugin": true
}
+7
View File
@@ -0,0 +1,7 @@
# Tauri + SvelteKit + TypeScript
This template should help get you started developing with Tauri, SvelteKit and TypeScript in Vite.
## Recommended IDE Setup
[VS Code](https://code.visualstudio.com/) + [Svelte](https://marketplace.visualstudio.com/items?itemName=svelte.svelte-vscode) + [Tauri](https://marketplace.visualstudio.com/items?itemName=tauri-apps.tauri-vscode) + [rust-analyzer](https://marketplace.visualstudio.com/items?itemName=rust-lang.rust-analyzer).
+29
View File
@@ -0,0 +1,29 @@
{
"name": "client",
"version": "0.1.0",
"description": "",
"type": "module",
"scripts": {
"dev": "vite dev",
"build": "vite build",
"preview": "vite preview",
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
"tauri": "tauri"
},
"license": "MIT",
"dependencies": {
"@tauri-apps/api": "^2",
"@tauri-apps/plugin-opener": "^2"
},
"devDependencies": {
"@sveltejs/adapter-static": "^3.0.6",
"@sveltejs/kit": "^2.9.0",
"@sveltejs/vite-plugin-svelte": "^5.0.0",
"svelte": "^5.0.0",
"svelte-check": "^4.0.0",
"typescript": "~5.6.2",
"vite": "^6.0.3",
"@tauri-apps/cli": "^2"
}
}
+1189
View File
File diff suppressed because it is too large Load Diff
+7
View File
@@ -0,0 +1,7 @@
# Generated by Cargo
# will have compiled files and executables
/target/
# Generated by Tauri
# will have schema files for capabilities auto-completion
/gen/schemas
+5463
View File
File diff suppressed because it is too large Load Diff
+25
View File
@@ -0,0 +1,25 @@
[package]
name = "client"
version = "0.1.0"
description = "A Tauri App"
authors = ["you"]
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[lib]
# The `_lib` suffix may seem redundant but it is necessary
# to make the lib name unique and wouldn't conflict with the bin name.
# This seems to be only an issue on Windows, see https://github.com/rust-lang/cargo/issues/8519
name = "client_lib"
crate-type = ["staticlib", "cdylib", "rlib"]
[build-dependencies]
tauri-build = { version = "2", features = [] }
[dependencies]
tauri = { version = "2", features = [] }
tauri-plugin-opener = "2"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
+3
View File
@@ -0,0 +1,3 @@
fn main() {
tauri_build::build()
}
@@ -0,0 +1,10 @@
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default",
"description": "Capability for the main window",
"windows": ["main"],
"permissions": [
"core:default",
"opener:default"
]
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 974 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 903 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 85 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

+56
View File
@@ -0,0 +1,56 @@
use tauri::State;
use std::sync::Mutex;
use crate::mpv::Mpv;
pub struct MpvState(pub Mutex<Mpv>);
#[tauri::command]
pub fn mpv_start(state: State<MpvState>) -> Result<(), String> {
state.0.lock().unwrap().start()
}
#[tauri::command]
pub fn mpv_stop(state: State<MpvState>) -> Result<(), String> {
state.0.lock().unwrap().stop();
Ok(())
}
#[tauri::command]
pub fn mpv_load(state: State<MpvState>, video_url: String, audio_url: String) -> Result<(), String> {
state.0.lock().unwrap().load_file(&video_url, &audio_url)
}
#[tauri::command]
pub fn mpv_seek(state: State<MpvState>, time: f64) -> Result<(), String> {
state.0.lock().unwrap().seek(time)
}
#[tauri::command]
pub fn mpv_pause(state: State<MpvState>) -> Result<(), String> {
state.0.lock().unwrap().pause()
}
#[tauri::command]
pub fn mpv_resume(state: State<MpvState>) -> Result<(), String> {
state.0.lock().unwrap().resume()
}
#[tauri::command]
pub fn mpv_set_loop(state: State<MpvState>, a: f64, b: f64) -> Result<(), String> {
state.0.lock().unwrap().set_loop(a, b)
}
#[tauri::command]
pub fn mpv_clear_loop(state: State<MpvState>) -> Result<(), String> {
state.0.lock().unwrap().clear_loop()
}
#[tauri::command]
pub fn mpv_time_pos(state: State<MpvState>) -> Result<f64, String> {
state.0.lock().unwrap().time_pos()
}
#[tauri::command]
pub fn mpv_duration(state: State<MpvState>) -> Result<f64, String> {
state.0.lock().unwrap().get_duration()
}
+27
View File
@@ -0,0 +1,27 @@
mod mpv;
mod commands;
use commands::MpvState;
use mpv::Mpv;
use std::sync::Mutex;
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
tauri::Builder::default()
.plugin(tauri_plugin_opener::init())
.manage(MpvState(Mutex::new(Mpv::new())))
.invoke_handler(tauri::generate_handler![
commands::mpv_start,
commands::mpv_stop,
commands::mpv_load,
commands::mpv_seek,
commands::mpv_pause,
commands::mpv_resume,
commands::mpv_set_loop,
commands::mpv_clear_loop,
commands::mpv_time_pos,
commands::mpv_duration,
])
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
+6
View File
@@ -0,0 +1,6 @@
// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
fn main() {
client_lib::run()
}
+162
View File
@@ -0,0 +1,162 @@
use std::io::{BufRead, BufReader, Write};
use std::os::unix::net::UnixStream;
use std::process::{Child, Command};
use std::sync::atomic::{AtomicU64, Ordering};
use serde_json::{json, Value};
pub struct Mpv {
process: Option<Child>,
writer: Option<UnixStream>,
reader: Option<BufReader<UnixStream>>,
socket_path: String,
next_id: AtomicU64,
}
impl Mpv {
pub fn new() -> Self {
let socket_path = format!("/tmp/8cut-mpv-{}", std::process::id());
Mpv {
process: None,
writer: None,
reader: None,
socket_path,
next_id: AtomicU64::new(1),
}
}
pub fn start(&mut self) -> Result<(), String> {
self.stop();
let child = Command::new("mpv")
.args([
"--idle=yes",
"--force-window=no",
"--vo=null",
"--keep-open=yes",
&format!("--input-ipc-server={}", self.socket_path),
])
.spawn()
.map_err(|e| format!("Failed to start mpv: {e}"))?;
self.process = Some(child);
// Wait for socket
for _ in 0..50 {
std::thread::sleep(std::time::Duration::from_millis(100));
if let Ok(stream) = UnixStream::connect(&self.socket_path) {
stream.set_nonblocking(false).ok();
let reader_stream = stream.try_clone().map_err(|e| e.to_string())?;
self.writer = Some(stream);
self.reader = Some(BufReader::new(reader_stream));
return Ok(());
}
}
Err("Timeout waiting for mpv IPC socket".into())
}
pub fn stop(&mut self) {
if let Some(ref mut child) = self.process {
child.kill().ok();
child.wait().ok();
}
self.process = None;
self.writer = None;
self.reader = None;
std::fs::remove_file(&self.socket_path).ok();
}
/// Send a command and wait for the matching response (by request_id).
/// Skips over asynchronous mpv events while waiting.
fn send_and_recv(&mut self, cmd: Value) -> Result<Value, String> {
let id = self.next_id.fetch_add(1, Ordering::Relaxed);
let writer = self.writer.as_mut().ok_or("mpv not running")?;
let reader = self.reader.as_mut().ok_or("mpv not running")?;
let mut msg_val = cmd;
msg_val["request_id"] = json!(id);
let mut msg = serde_json::to_string(&msg_val).unwrap();
msg.push('\n');
writer.write_all(msg.as_bytes()).map_err(|e| e.to_string())?;
// Read lines until we find the response matching our request_id
let mut line = String::new();
loop {
line.clear();
reader.read_line(&mut line).map_err(|e| e.to_string())?;
let parsed: Value = serde_json::from_str(&line).map_err(|e| e.to_string())?;
// mpv events have "event" key, responses have "request_id"
if parsed.get("request_id").and_then(|v| v.as_u64()) == Some(id) {
return Ok(parsed);
}
// Otherwise it's an async event — skip it
}
}
pub fn command(&mut self, args: &[&str]) -> Result<(), String> {
let resp = self.send_and_recv(json!({ "command": args }))?;
if resp.get("error").and_then(|e| e.as_str()) != Some("success") {
return Err(format!("mpv error: {}", resp.get("error").unwrap_or(&Value::Null)));
}
Ok(())
}
pub fn set_property(&mut self, name: &str, value: Value) -> Result<(), String> {
let resp = self.send_and_recv(json!({ "command": ["set_property", name, value] }))?;
if resp.get("error").and_then(|e| e.as_str()) != Some("success") {
return Err(format!("mpv error: {}", resp.get("error").unwrap_or(&Value::Null)));
}
Ok(())
}
pub fn get_property(&mut self, name: &str) -> Result<Value, String> {
let resp = self.send_and_recv(json!({ "command": ["get_property", name] }))?;
if resp.get("error").and_then(|e| e.as_str()) != Some("success") {
return Err(format!("mpv error: {}", resp.get("error").unwrap_or(&Value::Null)));
}
Ok(resp.get("data").cloned().unwrap_or(Value::Null))
}
pub fn load_file(&mut self, video_url: &str, audio_url: &str) -> Result<(), String> {
// Pass audio-file option during load so both streams sync from the start
let options = format!("audio-file={}", audio_url);
self.command(&["loadfile", video_url, "replace", &options])
}
pub fn seek(&mut self, time: f64) -> Result<(), String> {
self.command(&["seek", &time.to_string(), "absolute"])
}
pub fn pause(&mut self) -> Result<(), String> {
self.set_property("pause", json!(true))
}
pub fn resume(&mut self) -> Result<(), String> {
self.set_property("pause", json!(false))
}
pub fn set_loop(&mut self, a: f64, b: f64) -> Result<(), String> {
self.set_property("ab-loop-a", json!(a))?;
self.set_property("ab-loop-b", json!(b))
}
pub fn clear_loop(&mut self) -> Result<(), String> {
self.set_property("ab-loop-a", json!("no"))?;
self.set_property("ab-loop-b", json!("no"))
}
pub fn time_pos(&mut self) -> Result<f64, String> {
let val = self.get_property("time-pos")?;
val.as_f64().ok_or("time-pos not a number".into())
}
pub fn get_duration(&mut self) -> Result<f64, String> {
let val = self.get_property("duration")?;
val.as_f64().ok_or("duration not a number".into())
}
}
impl Drop for Mpv {
fn drop(&mut self) {
self.stop();
}
}
+35
View File
@@ -0,0 +1,35 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "8cut",
"version": "0.1.0",
"identifier": "com.ethanfel.8cut",
"build": {
"beforeDevCommand": "pnpm dev",
"devUrl": "http://localhost:1420",
"beforeBuildCommand": "pnpm build",
"frontendDist": "../build"
},
"app": {
"windows": [
{
"title": "8-cut",
"width": 1200,
"height": 800
}
],
"security": {
"csp": null
}
},
"bundle": {
"active": true,
"targets": ["deb", "appimage"],
"icon": [
"icons/32x32.png",
"icons/128x128.png",
"icons/128x128@2x.png",
"icons/icon.icns",
"icons/icon.ico"
]
}
}
+13
View File
@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%sveltekit.assets%/favicon.png" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Tauri + SvelteKit + Typescript App</title>
%sveltekit.head%
</head>
<body data-sveltekit-preload-data="hover">
<div style="display: contents">%sveltekit.body%</div>
</body>
</html>
+113
View File
@@ -0,0 +1,113 @@
<script lang="ts" module>
// Module-level export so App can call doExport via bind:this
</script>
<script lang="ts">
import { startExport } from "$lib/api";
import {
currentFile, cursor, clips, spread, shortSide, portraitRatio,
cropCenter, format, label, category, clipName, profile,
hwEncode,
exportStatus, exportCompleted, exportTotal, subprofiles
} from "$lib/stores";
const CATEGORIES = ["", "Human", "Animal", "Vehicle", "Tool", "Music", "Nature", "Sport", "Other"];
const RATIOS = ["Off", "9:16", "4:5", "1:1"];
export async function doExport(folderSuffix: string = "") {
if (!$currentFile) return;
$exportStatus = "running";
$exportCompleted = 0;
$exportTotal = $clips;
const req = {
input_path: `${$currentFile.root}/${$currentFile.path}`,
cursor: $cursor,
name: $clipName || $currentFile.name.replace(/\.[^.]+$/, ""),
clips: $clips,
spread: $spread,
short_side: $shortSide,
portrait_ratio: $portraitRatio,
crop_center: $cropCenter,
format: $format,
label: $label,
category: $category,
profile: $profile,
folder_suffix: folderSuffix,
encoder: $hwEncode ? "h264_nvenc" : "libx264",
};
try {
await startExport(req);
} catch (e) {
$exportStatus = "error";
console.error(e);
}
}
</script>
<div class="export-panel">
<div class="row">
<button onclick={() => doExport()} disabled={$exportStatus === "running"}>
Export{#if $exportStatus === "running"} ({$exportCompleted}/{$exportTotal}){/if}
</button>
{#each $subprofiles as sub}
<button onclick={() => doExport(sub)} title="Export {sub}">
{sub}
</button>
{/each}
</div>
<div class="row">
<label>Clips <input type="number" bind:value={$clips} min="1" max="99" /></label>
<label>Spread <input type="number" bind:value={$spread} min="2" max="8" step="0.5" /></label>
<label>Size <input type="number" bind:value={$shortSide} min="0" max="4320" step="64" /></label>
<label>Ratio
<select bind:value={$portraitRatio}>
{#each RATIOS as r}
<option value={r === "Off" ? null : r}>{r}</option>
{/each}
</select>
</label>
</div>
<div class="row">
<label>Label <input type="text" bind:value={$label} /></label>
<label>Category
<select bind:value={$category}>
{#each CATEGORIES as c}
<option value={c}>{c || "---"}</option>
{/each}
</select>
</label>
<label>Format
<select bind:value={$format}>
<option>MP4</option>
<option>WebP sequence</option>
</select>
</label>
<label><input type="checkbox" bind:checked={$hwEncode} /> GPU</label>
</div>
</div>
<style>
.export-panel {
display: flex;
flex-direction: column;
gap: 4px;
padding: 4px;
font-size: 12px;
}
.row {
display: flex;
gap: 6px;
align-items: center;
flex-wrap: wrap;
}
label { display: flex; align-items: center; gap: 2px; }
input[type="number"] { width: 50px; background: #2d2d2d; color: #e0e0e0; border: 1px solid #444; }
input[type="text"] { width: 120px; background: #2d2d2d; color: #e0e0e0; border: 1px solid #444; }
select { background: #2d2d2d; color: #e0e0e0; border: 1px solid #444; }
button { background: #0066cc; color: white; border: none; padding: 4px 12px; cursor: pointer; }
button:disabled { background: #444; }
</style>
+114
View File
@@ -0,0 +1,114 @@
<script lang="ts">
import { onMount } from "svelte";
import { getFiles, getRoots, getHidden, getMarkers, hideFile, unhideFile } from "$lib/api";
import {
files, roots, hiddenFiles, currentFile, showHidden,
profile, markers, visibleFiles
} from "$lib/stores";
let selectedRoot = $state("");
onMount(async () => {
$roots = await getRoots();
if ($roots.length) {
selectedRoot = $roots[0];
await loadFiles();
}
});
// Reload hidden files when profile changes
$effect(() => {
void $profile;
if (selectedRoot) {
loadFiles();
}
});
async function loadFiles() {
$files = await getFiles(selectedRoot);
const hidden = await getHidden($profile);
$hiddenFiles = new Set(hidden);
}
async function selectFile(file: typeof $files[0]) {
$currentFile = file;
$markers = await getMarkers(file.name, $profile);
}
function formatSize(bytes: number): string {
if (bytes > 1e9) return (bytes / 1e9).toFixed(1) + " GB";
if (bytes > 1e6) return (bytes / 1e6).toFixed(0) + " MB";
return (bytes / 1e3).toFixed(0) + " KB";
}
async function toggleHidden(file: typeof $files[0]) {
if ($hiddenFiles.has(file.name)) {
await unhideFile(file.name, $profile);
} else {
await hideFile(file.name, $profile);
}
await loadFiles();
}
</script>
<div class="file-browser">
<div class="controls">
<select bind:value={selectedRoot} onchange={loadFiles}>
{#each $roots as root}
<option value={root}>{root}</option>
{/each}
</select>
<label><input type="checkbox" bind:checked={$showHidden} /> Hidden</label>
</div>
<ul class="file-list">
{#each $visibleFiles as file}
<li
class:selected={$currentFile?.path === file.path}
onclick={() => selectFile(file)}
oncontextmenu={(e) => { e.preventDefault(); toggleHidden(file); }}
>
<span class="name">{file.name}</span>
<span class="size">{formatSize(file.size)}</span>
</li>
{/each}
</ul>
</div>
<style>
.file-browser {
display: flex;
flex-direction: column;
height: 100%;
min-width: 200px;
}
.controls {
display: flex;
gap: 4px;
padding: 4px;
align-items: center;
}
.controls select {
flex: 1;
background: #2d2d2d;
color: #e0e0e0;
border: 1px solid #444;
padding: 2px;
}
.file-list {
list-style: none;
padding: 0;
margin: 0;
overflow-y: auto;
flex: 1;
}
.file-list li {
padding: 4px 8px;
cursor: pointer;
display: flex;
justify-content: space-between;
font-size: 12px;
}
.file-list li:hover { background: #333; }
.file-list li.selected { background: #0066cc; }
.size { color: #888; font-size: 11px; }
</style>
+62
View File
@@ -0,0 +1,62 @@
<script lang="ts">
import { onMount } from "svelte";
import { getProfiles } from "$lib/api";
import { profile, subprofiles } from "$lib/stores";
let profiles = $state<string[]>([]);
onMount(async () => {
profiles = await getProfiles();
if (profiles.length && !profiles.includes($profile)) {
$profile = profiles[0];
}
});
function addSubprofile() {
const name = prompt("Subprofile suffix:");
if (name && !$subprofiles.includes(name)) {
$subprofiles = [...$subprofiles, name];
}
}
function removeSubprofile(name: string) {
$subprofiles = $subprofiles.filter(s => s !== name);
}
</script>
<div class="profile-bar">
<select bind:value={$profile}>
{#each profiles as p}
<option value={p}>{p}</option>
{/each}
</select>
<span class="subs">
{#each $subprofiles as sub}
<span class="sub-tag" oncontextmenu={(e) => { e.preventDefault(); removeSubprofile(sub); }}>
{sub}
</span>
{/each}
<button onclick={addSubprofile}>+</button>
</span>
</div>
<style>
.profile-bar {
display: flex;
align-items: center;
gap: 8px;
padding: 4px;
font-size: 12px;
}
select { background: #2d2d2d; color: #e0e0e0; border: 1px solid #444; }
.subs { display: flex; gap: 4px; align-items: center; }
.sub-tag {
background: #444;
padding: 2px 6px;
border-radius: 3px;
cursor: context-menu;
font-size: 11px;
}
button { background: #333; color: #e0e0e0; border: 1px solid #555; padding: 1px 6px; cursor: pointer; }
</style>
+170
View File
@@ -0,0 +1,170 @@
<script lang="ts">
import { onMount } from "svelte";
import {
duration, cursor, playPos, markers, clips, spread, locked, clipSpan
} from "$lib/stores";
let {
onCursorChange = (_time: number) => {},
onSeek = (_time: number) => {},
onMarkerClick = (_marker: { start_time: number; output_path: string }) => {},
onMarkerDelete = (_outputPath: string) => {},
} = $props<{
onCursorChange?: (time: number) => void;
onSeek?: (time: number) => void;
onMarkerClick?: (marker: { start_time: number; output_path: string }) => void;
onMarkerDelete?: (outputPath: string) => void;
}>();
let canvas: HTMLCanvasElement;
let ctx: CanvasRenderingContext2D;
let dragging = $state(false);
const HEIGHT = 160;
function timeToX(t: number): number {
if ($duration <= 0) return 0;
return (t / $duration) * canvas.width;
}
function xToTime(x: number): number {
if ($duration <= 0) return 0;
return Math.max(0, Math.min($duration, (x / canvas.width) * $duration));
}
function draw() {
if (!ctx) return;
const w = canvas.width;
const h = canvas.height;
ctx.clearRect(0, 0, w, h);
// Background
ctx.fillStyle = "#1a1a1a";
ctx.fillRect(0, 0, w, h);
// Clip span region
if ($duration > 0) {
const x0 = timeToX($cursor);
const x1 = timeToX($cursor + $clipSpan);
ctx.fillStyle = "rgba(0, 100, 200, 0.15)";
ctx.fillRect(x0, 0, x1 - x0, h);
}
// Markers
for (const m of $markers) {
const x = timeToX(m.start_time);
ctx.fillStyle = "#22aa44";
ctx.fillRect(x - 1, 0, 3, h);
}
// Cursor
if ($duration > 0) {
const cx = timeToX($cursor);
ctx.fillStyle = "#ff4444";
ctx.fillRect(cx - 1, 0, 3, h);
}
// Play position
if ($playPos !== null && $duration > 0) {
const px = timeToX($playPos);
ctx.fillStyle = "#ffaa00";
ctx.fillRect(px - 1, 0, 2, h);
}
// Time labels
if ($duration > 0) {
ctx.fillStyle = "#888";
ctx.font = "11px monospace";
const step = Math.max(10, Math.pow(10, Math.floor(Math.log10($duration / 5))));
for (let t = 0; t <= $duration; t += step) {
const x = timeToX(t);
ctx.fillText(formatTime(t), x + 2, h - 4);
ctx.fillRect(x, h - 16, 1, 16);
}
}
}
function formatTime(s: number): string {
const m = Math.floor(s / 60);
const sec = (Math.floor(s % 60 * 10) / 10).toFixed(1);
return `${m}:${sec.padStart(4, "0")}`;
}
function handleMouseDown(e: MouseEvent) {
if ($locked) return;
dragging = true;
const time = xToTime(e.offsetX);
$cursor = time;
onCursorChange(time);
}
function handleMouseMove(e: MouseEvent) {
if (!dragging || $locked) return;
const time = xToTime(e.offsetX);
$cursor = time;
onCursorChange(time);
}
function handleMouseUp() {
dragging = false;
}
function handleDblClick(e: MouseEvent) {
const time = xToTime(e.offsetX);
for (const m of $markers) {
const mx = timeToX(m.start_time);
if (Math.abs(e.offsetX - mx) < 8) {
onMarkerClick(m);
return;
}
}
onSeek(time);
}
function handleContextMenu(e: MouseEvent) {
e.preventDefault();
for (const m of $markers) {
const mx = timeToX(m.start_time);
if (Math.abs(e.offsetX - mx) < 8) {
onMarkerDelete(m.output_path);
return;
}
}
}
// Redraw on any state change
$effect(() => {
void $duration; void $cursor; void $playPos; void $markers; void $clips; void $spread; void $clipSpan;
draw();
});
onMount(() => {
ctx = canvas.getContext("2d")!;
const obs = new ResizeObserver(() => {
canvas.width = canvas.clientWidth;
canvas.height = HEIGHT;
draw();
});
obs.observe(canvas);
return () => obs.disconnect();
});
</script>
<canvas
bind:this={canvas}
style="width:100%;height:{HEIGHT}px"
onmousedown={handleMouseDown}
onmousemove={handleMouseMove}
onmouseup={handleMouseUp}
onmouseleave={handleMouseUp}
ondblclick={handleDblClick}
oncontextmenu={handleContextMenu}
></canvas>
<style>
canvas {
display: block;
background: #1a1a1a;
cursor: crosshair;
}
</style>
+139
View File
@@ -0,0 +1,139 @@
const DEFAULT_SERVER = "http://192.168.1.51:8000";
let serverUrl = DEFAULT_SERVER;
export function setServer(url: string) {
serverUrl = url.replace(/\/+$/, "");
}
export function getServer(): string {
return serverUrl;
}
async function get<T>(path: string): Promise<T> {
const res = await fetch(`${serverUrl}${path}`);
if (!res.ok) throw new Error(`${res.status} ${res.statusText}`);
return res.json();
}
async function post<T>(path: string, body?: unknown): Promise<T> {
const res = await fetch(`${serverUrl}${path}`, {
method: "POST",
headers: body ? { "Content-Type": "application/json" } : {},
body: body ? JSON.stringify(body) : undefined,
});
if (!res.ok) throw new Error(`${res.status} ${res.statusText}`);
return res.json();
}
async function del<T>(path: string): Promise<T> {
const res = await fetch(`${serverUrl}${path}`, { method: "DELETE" });
if (!res.ok) throw new Error(`${res.status} ${res.statusText}`);
return res.json();
}
// --- Files ---
export interface VideoFile {
name: string;
path: string;
root: string;
size: number;
}
export function getRoots(): Promise<string[]> {
return get("/api/roots");
}
export function getFiles(root?: string): Promise<VideoFile[]> {
const q = root ? `?root=${encodeURIComponent(root)}` : "";
return get(`/api/files${q}`);
}
// For {path:path} routes, encode each segment individually to preserve slashes
function encodePath(p: string): string {
return p.split("/").map(encodeURIComponent).join("/");
}
export function streamUrl(path: string, root: string, quality: string): string {
return `${serverUrl}/api/stream/${encodePath(path)}?root=${encodeURIComponent(root)}&quality=${quality}`;
}
export function audioUrl(path: string, root: string): string {
return `${serverUrl}/api/audio/${encodePath(path)}?root=${encodeURIComponent(root)}`;
}
export function cacheStatus(path: string, root: string): Promise<Record<string, string>> {
return get(`/api/cache/status/${encodePath(path)}?root=${encodeURIComponent(root)}`);
}
// --- Markers & Profiles ---
export interface Marker {
start_time: number;
marker_number: number;
output_path: string;
}
export function getMarkers(filename: string, profile: string = "default"): Promise<Marker[]> {
return get(`/api/markers/${encodeURIComponent(filename)}?profile=${encodeURIComponent(profile)}`);
}
export function getProfiles(): Promise<string[]> {
return get("/api/profiles");
}
export function getLabels(): Promise<string[]> {
return get("/api/labels");
}
// --- Export ---
export interface ExportRequest {
input_path: string;
cursor: number;
name: string;
clips?: number;
spread?: number;
short_side?: number | null;
portrait_ratio?: string | null;
crop_center?: number;
format?: string;
label?: string;
category?: string;
profile?: string;
folder_suffix?: string;
encoder?: string;
}
export function startExport(req: ExportRequest): Promise<{ job_id: string }> {
return post("/api/export", req);
}
export function getExportStatus(jobId: string): Promise<{
status: string;
total: number;
completed: number;
outputs: string[];
error?: string;
}> {
return get(`/api/export/${jobId}`);
}
export function deleteExport(outputPath: string): Promise<{ deleted: string }> {
return del(`/api/export?output_path=${encodeURIComponent(outputPath)}`);
}
// --- Hidden ---
export function hideFile(filename: string, profile: string = "default"): Promise<unknown> {
return post(`/api/hidden/${encodeURIComponent(filename)}?profile=${encodeURIComponent(profile)}`);
}
export function unhideFile(filename: string, profile: string = "default"): Promise<unknown> {
return del(`/api/hidden/${encodeURIComponent(filename)}?profile=${encodeURIComponent(profile)}`);
}
export function getHidden(profile: string = "default"): Promise<string[]> {
return get(`/api/hidden?profile=${encodeURIComponent(profile)}`);
}
+41
View File
@@ -0,0 +1,41 @@
import { invoke } from "@tauri-apps/api/core";
export async function mpvStart(): Promise<void> {
return invoke("mpv_start");
}
export async function mpvStop(): Promise<void> {
return invoke("mpv_stop");
}
export async function mpvLoad(videoUrl: string, audioUrl: string): Promise<void> {
return invoke("mpv_load", { videoUrl, audioUrl });
}
export async function mpvSeek(time: number): Promise<void> {
return invoke("mpv_seek", { time });
}
export async function mpvPause(): Promise<void> {
return invoke("mpv_pause");
}
export async function mpvResume(): Promise<void> {
return invoke("mpv_resume");
}
export async function mpvSetLoop(a: number, b: number): Promise<void> {
return invoke("mpv_set_loop", { a, b });
}
export async function mpvClearLoop(): Promise<void> {
return invoke("mpv_clear_loop");
}
export async function mpvTimePos(): Promise<number> {
return invoke("mpv_time_pos");
}
export async function mpvDuration(): Promise<number> {
return invoke("mpv_duration");
}
+58
View File
@@ -0,0 +1,58 @@
import {
serverUrl, quality, clips, spread, shortSide, portraitRatio,
format, hwEncode, profile, subprofiles
} from "./stores";
import { setServer } from "./api";
import { get } from "svelte/store";
const KEY = "8cut-settings";
interface Settings {
serverUrl: string;
quality: string;
clips: number;
spread: number;
shortSide: number | null;
portraitRatio: string | null;
format: string;
hwEncode: boolean;
profile: string;
subprofiles: string[];
}
export function saveSettings() {
const data: Settings = {
serverUrl: get(serverUrl),
quality: get(quality),
clips: get(clips),
spread: get(spread),
shortSide: get(shortSide),
portraitRatio: get(portraitRatio),
format: get(format),
hwEncode: get(hwEncode),
profile: get(profile),
subprofiles: get(subprofiles),
};
localStorage.setItem(KEY, JSON.stringify(data));
}
export function loadSettings() {
const raw = localStorage.getItem(KEY);
if (!raw) return;
try {
const data: Settings = JSON.parse(raw);
if (data.serverUrl) {
serverUrl.set(data.serverUrl);
setServer(data.serverUrl);
}
if (data.quality) quality.set(data.quality);
if (data.clips) clips.set(data.clips);
if (data.spread) spread.set(data.spread);
if (data.shortSide !== undefined) shortSide.set(data.shortSide);
if (data.portraitRatio !== undefined) portraitRatio.set(data.portraitRatio);
if (data.format) format.set(data.format);
if (data.hwEncode !== undefined) hwEncode.set(data.hwEncode);
if (data.profile) profile.set(data.profile);
if (data.subprofiles) subprofiles.set(data.subprofiles);
} catch { /* ignore corrupt settings */ }
}
+66
View File
@@ -0,0 +1,66 @@
import { writable, derived } from "svelte/store";
import type { VideoFile, Marker } from "./api";
// --- Connection ---
export const serverUrl = writable("http://192.168.1.51:8000");
// --- Files ---
export const roots = writable<string[]>([]);
export const files = writable<VideoFile[]>([]);
export const hiddenFiles = writable<Set<string>>(new Set());
export const currentFile = writable<VideoFile | null>(null);
export const hideExported = writable(false);
export const showHidden = writable(false);
// --- Playback ---
export const duration = writable(0);
export const cursor = writable(0);
export const playPos = writable<number | null>(null);
export const playing = writable(false);
export const quality = writable("low");
// --- Timeline ---
export const markers = writable<Marker[]>([]);
export const locked = writable(false);
// --- Export settings ---
export const clips = writable(3);
export const spread = writable(3.0);
export const shortSide = writable<number | null>(512);
export const portraitRatio = writable<string | null>(null);
export const cropCenter = writable(0.5);
export const format = writable("MP4");
export const hwEncode = writable(false);
export const label = writable("");
export const category = writable("");
export const clipName = writable("");
export const exportFolder = writable("");
export const encoder = writable("libx264");
export const trackSubject = writable(false);
export const randPortrait = writable(false);
export const randSquare = writable(false);
// --- Profiles ---
export const profile = writable("default");
export const subprofiles = writable<string[]>([]);
// --- Export progress ---
export const exportStatus = writable<string>("idle"); // idle | running | done | error
export const exportCompleted = writable(0);
export const exportTotal = writable(0);
// --- Derived ---
export const clipSpan = derived(
[clips, spread],
([$clips, $spread]) => 8.0 + ($clips - 1) * $spread
);
export const visibleFiles = derived(
[files, hiddenFiles, showHidden],
([$files, $hidden, $showHidden]) => {
return $files.filter(f => {
if (!$showHidden && $hidden.has(f.name)) return false;
return true;
});
}
);
+48
View File
@@ -0,0 +1,48 @@
import { getServer } from "./api";
import { exportStatus, exportCompleted } from "./stores";
let socket: WebSocket | null = null;
let reconnectDelay = 2000;
export function connectExportWs() {
const wsUrl = getServer().replace(/^http/, "ws") + "/ws/export";
socket = new WebSocket(wsUrl);
socket.onopen = () => {
reconnectDelay = 2000; // reset backoff on successful connect
};
socket.onmessage = (event) => {
try {
const msg = JSON.parse(event.data);
switch (msg.type) {
case "clip_done":
exportCompleted.update(n => n + 1);
break;
case "all_done":
exportStatus.set("done");
break;
case "error":
exportStatus.set("error");
console.error("Export error:", msg.msg);
break;
}
} catch (e) {
console.error("Failed to parse WebSocket message:", e);
}
};
socket.onclose = () => {
// Reconnect with exponential backoff, max 30s
setTimeout(connectExportWs, reconnectDelay);
reconnectDelay = Math.min(reconnectDelay * 2, 30000);
};
}
export function disconnectExportWs() {
if (socket) {
socket.onclose = null; // prevent reconnect
socket.close();
socket = null;
}
}
+5
View File
@@ -0,0 +1,5 @@
// Tauri doesn't have a Node.js server to do proper SSR
// so we use adapter-static with a fallback to index.html to put the site in SPA mode
// See: https://svelte.dev/docs/kit/single-page-apps
// See: https://v2.tauri.app/start/frontend/sveltekit/ for more info
export const ssr = false;
+241
View File
@@ -0,0 +1,241 @@
<script lang="ts">
import { onMount, onDestroy } from "svelte";
import FileBrowser from "../components/FileBrowser.svelte";
import Timeline from "../components/Timeline.svelte";
import ExportPanel from "../components/ExportPanel.svelte";
import ProfileBar from "../components/ProfileBar.svelte";
import { mpvStart, mpvLoad, mpvSeek, mpvPause, mpvResume, mpvSetLoop, mpvClearLoop, mpvTimePos, mpvDuration } from "$lib/mpv";
import { streamUrl, audioUrl, deleteExport, getMarkers } from "$lib/api";
import { connectExportWs, disconnectExportWs } from "$lib/ws";
import { loadSettings, saveSettings } from "$lib/settings";
import {
currentFile, cursor, duration, playPos, playing, quality,
clips, spread, locked, markers, profile, clipSpan, subprofiles
} from "$lib/stores";
let pollInterval: ReturnType<typeof setInterval>;
let exportPanelRef: ExportPanel;
onMount(async () => {
loadSettings();
await mpvStart();
connectExportWs();
// Poll mpv for time position
pollInterval = setInterval(async () => {
if ($playing) {
try {
$playPos = await mpvTimePos();
} catch { /* mpv not ready */ }
}
}, 50);
// Auto-save settings on changes
const unsubs = [
quality.subscribe(() => saveSettings()),
clips.subscribe(() => saveSettings()),
spread.subscribe(() => saveSettings()),
profile.subscribe(() => saveSettings()),
subprofiles.subscribe(() => saveSettings()),
];
return () => unsubs.forEach(u => u());
});
onDestroy(() => {
clearInterval(pollInterval);
disconnectExportWs();
});
// Load file into mpv when currentFile OR quality changes
$effect(() => {
const file = $currentFile;
const q = $quality;
if (file) {
const vUrl = streamUrl(file.path, file.root, q);
const aUrl = audioUrl(file.path, file.root);
mpvLoad(vUrl, aUrl).then(async () => {
await new Promise(r => setTimeout(r, 500));
try { $duration = await mpvDuration(); } catch {}
});
}
});
async function handleCursorChange(time: number) {
await mpvSeek(time);
}
async function handlePlay() {
const a = $cursor;
const b = $cursor + $clipSpan;
await mpvSeek(a);
await mpvSetLoop(a, b);
await mpvResume();
$playing = true;
}
async function handlePause() {
await mpvPause();
await mpvClearLoop();
$playing = false;
}
async function handleMarkerClick(m: { start_time: number; output_path: string }) {
if ($locked) {
const span = 8.0 + ($clips - 1) * $spread;
$cursor = m.start_time + span;
await mpvSeek($cursor);
} else {
$cursor = m.start_time;
await mpvSeek(m.start_time);
}
}
async function handleMarkerDelete(outputPath: string) {
await deleteExport(outputPath);
if ($currentFile) {
$markers = await getMarkers($currentFile.name, $profile);
}
}
function handleKeydown(e: KeyboardEvent) {
const tag = (e.target as HTMLElement).tagName;
if (tag === "INPUT" || tag === "SELECT" || tag === "TEXTAREA") return;
switch (e.key) {
case " ":
e.preventDefault();
$playing ? handlePause() : handlePlay();
break;
case "e":
case "E":
exportPanelRef?.doExport();
break;
case "ArrowLeft":
$cursor = Math.max(0, $cursor - 1);
handleCursorChange($cursor);
break;
case "ArrowRight":
$cursor = Math.min($duration, $cursor + 1);
handleCursorChange($cursor);
break;
}
const num = parseInt(e.key);
if (num >= 1 && num <= 9) {
const idx = num - 1;
if (idx < $subprofiles.length) {
exportPanelRef?.doExport($subprofiles[idx]);
}
}
}
function fmtTime(s: number): string {
const m = Math.floor(s / 60);
const sec = (Math.floor(s % 60 * 10) / 10).toFixed(1);
return `${m}:${sec.padStart(4, "0")}`;
}
</script>
<svelte:window onkeydown={handleKeydown} />
<main>
<div class="layout">
<div class="sidebar">
<FileBrowser />
</div>
<div class="content">
<ProfileBar />
<div class="player-area">
<div class="video-placeholder">
{#if $currentFile}
<p>{$currentFile.name}</p>
{:else}
<p>Select a file</p>
{/if}
</div>
</div>
<Timeline
onCursorChange={handleCursorChange}
onSeek={handleCursorChange}
onMarkerClick={handleMarkerClick}
onMarkerDelete={handleMarkerDelete}
/>
<div class="transport">
<button onclick={handlePlay} disabled={!$currentFile}>Play</button>
<button onclick={handlePause}>Pause</button>
<button onclick={() => $locked = !$locked}>
{$locked ? "Locked" : "Unlocked"}
</button>
<span class="time">
{#if $duration > 0}
{fmtTime($cursor)} / {fmtTime($duration)}
{/if}
</span>
<select bind:value={$quality} style="margin-left:auto">
<option value="potato">480p</option>
<option value="low">720p</option>
<option value="medium">1080p</option>
<option value="high">Original</option>
</select>
</div>
<ExportPanel bind:this={exportPanelRef} />
</div>
</div>
</main>
<style>
:global(body) {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
background: #1e1e1e;
color: #e0e0e0;
}
main { height: 100vh; overflow: hidden; }
.layout {
display: flex;
height: 100%;
}
.sidebar {
width: 220px;
border-right: 1px solid #333;
overflow: hidden;
}
.content {
flex: 1;
display: flex;
flex-direction: column;
overflow: hidden;
}
.player-area {
flex: 1;
display: flex;
align-items: center;
justify-content: center;
background: #000;
min-height: 200px;
}
.video-placeholder {
color: #666;
text-align: center;
}
.transport {
display: flex;
align-items: center;
gap: 6px;
padding: 4px 8px;
background: #222;
}
.transport button {
background: #333;
color: #e0e0e0;
border: 1px solid #555;
padding: 4px 10px;
cursor: pointer;
}
.time {
font-family: monospace;
font-size: 13px;
}
select { background: #2d2d2d; color: #e0e0e0; border: 1px solid #444; }
</style>
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="26.6" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 308"><path fill="#FF3E00" d="M239.682 40.707C211.113-.182 154.69-12.301 113.895 13.69L42.247 59.356a82.198 82.198 0 0 0-37.135 55.056a86.566 86.566 0 0 0 8.536 55.576a82.425 82.425 0 0 0-12.296 30.719a87.596 87.596 0 0 0 14.964 66.244c28.574 40.893 84.997 53.007 125.787 27.016l71.648-45.664a82.182 82.182 0 0 0 37.135-55.057a86.601 86.601 0 0 0-8.53-55.577a82.409 82.409 0 0 0 12.29-30.718a87.573 87.573 0 0 0-14.963-66.244"></path><path fill="#FFF" d="M106.889 270.841c-23.102 6.007-47.497-3.036-61.103-22.648a52.685 52.685 0 0 1-9.003-39.85a49.978 49.978 0 0 1 1.713-6.693l1.35-4.115l3.671 2.697a92.447 92.447 0 0 0 28.036 14.007l2.663.808l-.245 2.659a16.067 16.067 0 0 0 2.89 10.656a17.143 17.143 0 0 0 18.397 6.828a15.786 15.786 0 0 0 4.403-1.935l71.67-45.672a14.922 14.922 0 0 0 6.734-9.977a15.923 15.923 0 0 0-2.713-12.011a17.156 17.156 0 0 0-18.404-6.832a15.78 15.78 0 0 0-4.396 1.933l-27.35 17.434a52.298 52.298 0 0 1-14.553 6.391c-23.101 6.007-47.497-3.036-61.101-22.649a52.681 52.681 0 0 1-9.004-39.849a49.428 49.428 0 0 1 22.34-33.114l71.664-45.677a52.218 52.218 0 0 1 14.563-6.398c23.101-6.007 47.497 3.036 61.101 22.648a52.685 52.685 0 0 1 9.004 39.85a50.559 50.559 0 0 1-1.713 6.692l-1.35 4.116l-3.67-2.693a92.373 92.373 0 0 0-28.037-14.013l-2.664-.809l.246-2.658a16.099 16.099 0 0 0-2.89-10.656a17.143 17.143 0 0 0-18.398-6.828a15.786 15.786 0 0 0-4.402 1.935l-71.67 45.674a14.898 14.898 0 0 0-6.73 9.975a15.9 15.9 0 0 0 2.709 12.012a17.156 17.156 0 0 0 18.404 6.832a15.841 15.841 0 0 0 4.402-1.935l27.345-17.427a52.147 52.147 0 0 1 14.552-6.397c23.101-6.006 47.497 3.037 61.102 22.65a52.681 52.681 0 0 1 9.003 39.848a49.453 49.453 0 0 1-22.34 33.12l-71.664 45.673a52.218 52.218 0 0 1-14.563 6.398"></path></svg>

After

Width:  |  Height:  |  Size: 1.9 KiB

+6
View File
@@ -0,0 +1,6 @@
<svg width="206" height="231" viewBox="0 0 206 231" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M143.143 84C143.143 96.1503 133.293 106 121.143 106C108.992 106 99.1426 96.1503 99.1426 84C99.1426 71.8497 108.992 62 121.143 62C133.293 62 143.143 71.8497 143.143 84Z" fill="#FFC131"/>
<ellipse cx="84.1426" cy="147" rx="22" ry="22" transform="rotate(180 84.1426 147)" fill="#24C8DB"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M166.738 154.548C157.86 160.286 148.023 164.269 137.757 166.341C139.858 160.282 141 153.774 141 147C141 144.543 140.85 142.121 140.558 139.743C144.975 138.204 149.215 136.139 153.183 133.575C162.73 127.404 170.292 118.608 174.961 108.244C179.63 97.8797 181.207 86.3876 179.502 75.1487C177.798 63.9098 172.884 53.4021 165.352 44.8883C157.82 36.3744 147.99 30.2165 137.042 27.1546C126.095 24.0926 114.496 24.2568 103.64 27.6274C92.7839 30.998 83.1319 37.4317 75.8437 46.1553C74.9102 47.2727 74.0206 48.4216 73.176 49.5993C61.9292 50.8488 51.0363 54.0318 40.9629 58.9556C44.2417 48.4586 49.5653 38.6591 56.679 30.1442C67.0505 17.7298 80.7861 8.57426 96.2354 3.77762C111.685 -1.01901 128.19 -1.25267 143.769 3.10474C159.348 7.46215 173.337 16.2252 184.056 28.3411C194.775 40.457 201.767 55.4101 204.193 71.404C206.619 87.3978 204.374 103.752 197.73 118.501C191.086 133.25 180.324 145.767 166.738 154.548ZM41.9631 74.275L62.5557 76.8042C63.0459 72.813 63.9401 68.9018 65.2138 65.1274C57.0465 67.0016 49.2088 70.087 41.9631 74.275Z" fill="#FFC131"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M38.4045 76.4519C47.3493 70.6709 57.2677 66.6712 67.6171 64.6132C65.2774 70.9669 64 77.8343 64 85.0001C64 87.1434 64.1143 89.26 64.3371 91.3442C60.0093 92.8732 55.8533 94.9092 51.9599 97.4256C42.4128 103.596 34.8505 112.392 30.1816 122.756C25.5126 133.12 23.9357 144.612 25.6403 155.851C27.3449 167.09 32.2584 177.598 39.7906 186.112C47.3227 194.626 57.153 200.784 68.1003 203.846C79.0476 206.907 90.6462 206.743 101.502 203.373C112.359 200.002 122.011 193.568 129.299 184.845C130.237 183.722 131.131 182.567 131.979 181.383C143.235 180.114 154.132 176.91 164.205 171.962C160.929 182.49 155.596 192.319 148.464 200.856C138.092 213.27 124.357 222.426 108.907 227.222C93.458 232.019 76.9524 232.253 61.3736 227.895C45.7948 223.538 31.8055 214.775 21.0867 202.659C10.3679 190.543 3.37557 175.59 0.949823 159.596C-1.47592 143.602 0.768139 127.248 7.41237 112.499C14.0566 97.7497 24.8183 85.2327 38.4045 76.4519ZM163.062 156.711L163.062 156.711C162.954 156.773 162.846 156.835 162.738 156.897C162.846 156.835 162.954 156.773 163.062 156.711Z" fill="#24C8DB"/>
</svg>

After

Width:  |  Height:  |  Size: 2.5 KiB

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

+18
View File
@@ -0,0 +1,18 @@
// Tauri doesn't have a Node.js server to do proper SSR
// so we use adapter-static with a fallback to index.html to put the site in SPA mode
// See: https://svelte.dev/docs/kit/single-page-apps
// See: https://v2.tauri.app/start/frontend/sveltekit/ for more info
import adapter from "@sveltejs/adapter-static";
import { vitePreprocess } from "@sveltejs/vite-plugin-svelte";
/** @type {import('@sveltejs/kit').Config} */
const config = {
preprocess: vitePreprocess(),
kit: {
adapter: adapter({
fallback: "index.html",
}),
},
};
export default config;
+19
View File
@@ -0,0 +1,19 @@
{
"extends": "./.svelte-kit/tsconfig.json",
"compilerOptions": {
"allowJs": true,
"checkJs": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"skipLibCheck": true,
"sourceMap": true,
"strict": true,
"moduleResolution": "bundler"
}
// Path aliases are handled by https://svelte.dev/docs/kit/configuration#alias
// except $lib which is handled by https://svelte.dev/docs/kit/configuration#files
//
// If you want to overwrite includes/excludes, make sure to copy over the relevant includes/excludes
// from the referenced tsconfig.json - TypeScript does not merge them in
}
+32
View File
@@ -0,0 +1,32 @@
import { defineConfig } from "vite";
import { sveltekit } from "@sveltejs/kit/vite";
// @ts-expect-error process is a nodejs global
const host = process.env.TAURI_DEV_HOST;
// https://vite.dev/config/
export default defineConfig(async () => ({
plugins: [sveltekit()],
// Vite options tailored for Tauri development and only applied in `tauri dev` or `tauri build`
//
// 1. prevent Vite from obscuring rust errors
clearScreen: false,
// 2. tauri expects a fixed port, fail if that port is not available
server: {
port: 1420,
strictPort: true,
host: host || false,
hmr: host
? {
protocol: "ws",
host,
port: 1421,
}
: undefined,
watch: {
// 3. tell Vite to ignore watching `src-tauri`
ignored: ["**/src-tauri/**"],
},
},
}));
+7
View File
@@ -1,4 +1,5 @@
import sqlite3
import threading
from datetime import datetime, timezone
from pathlib import Path
@@ -12,6 +13,7 @@ class ProcessedDB:
if db_path is None:
db_path = str(Path.home() / ".8cut.db")
self._path = db_path
self._lock = threading.Lock()
try:
self._con = sqlite3.connect(db_path, check_same_thread=False)
self._migrate()
@@ -86,6 +88,7 @@ class ProcessedDB:
profile: str = "default") -> None:
if not self._enabled:
return
with self._lock:
self._con.execute(
"INSERT INTO processed"
" (filename, start_time, output_path, label, category,"
@@ -134,6 +137,7 @@ class ProcessedDB:
def delete_by_output_path(self, output_path: str) -> None:
if not self._enabled:
return
with self._lock:
self._con.execute("DELETE FROM processed WHERE output_path = ?", (output_path,))
self._con.commit()
@@ -159,6 +163,7 @@ class ProcessedDB:
Returns list of deleted output_paths."""
if not self._enabled:
return []
with self._lock:
row = self._con.execute(
"SELECT filename, start_time FROM processed WHERE output_path = ?",
(output_path,),
@@ -211,6 +216,7 @@ class ProcessedDB:
def hide_file(self, filename: str, profile: str = "default") -> None:
if not self._enabled:
return
with self._lock:
self._con.execute(
"INSERT OR IGNORE INTO hidden_files (filename, profile) VALUES (?, ?)",
(filename, profile),
@@ -220,6 +226,7 @@ class ProcessedDB:
def unhide_file(self, filename: str, profile: str = "default") -> None:
if not self._enabled:
return
with self._lock:
self._con.execute(
"DELETE FROM hidden_files WHERE filename = ? AND profile = ?",
(filename, profile),
+4 -1
View File
@@ -91,7 +91,10 @@ class ExportRunner:
raise RuntimeError(msg)
if self._image_sequence:
audio_cmd = build_audio_extract_command(self._input, start, output)
subprocess.run(audio_cmd, capture_output=True, text=True, timeout=60)
audio_result = subprocess.run(audio_cmd, capture_output=True, text=True, timeout=60)
if audio_result.returncode != 0:
msg = (audio_result.stderr or "audio extraction failed")[-500:]
raise RuntimeError(msg)
return output
def _run(self):
File diff suppressed because it is too large Load Diff
+28 -4
View File
@@ -1,6 +1,8 @@
import os
import re
import shutil
import threading
import time
import uuid
from fastapi import APIRouter, HTTPException, Query
@@ -15,9 +17,12 @@ from ..config import EXPORT_DIR, MEDIA_DIRS
router = APIRouter()
_jobs: dict[str, dict] = {}
_counter_lock = threading.Lock()
_VALID_ENCODERS = {"libx264", "h264_nvenc", "h264_vaapi", "h264_qsv", "h264_amf", "h264_videotoolbox"}
_MAX_FINISHED_JOBS = 200
class CropKeyframe(BaseModel):
time: float
@@ -94,9 +99,10 @@ def start_export(req: ExportRequest):
folder = folder.rstrip(os.sep) + "_" + req.folder_suffix
image_sequence = req.format in ("WebP", "WebP sequence")
counter = _next_counter(folder, req.name)
# Build job list: (start, output_path, portrait_ratio, crop_center)
# Lock counter + directory creation to prevent race between concurrent exports
with _counter_lock:
counter = _next_counter(folder, req.name)
jobs = []
for i in range(req.clips):
start = req.cursor + i * req.spread
@@ -163,11 +169,18 @@ def start_export(req: ExportRequest):
on_error=on_error,
)
# Evict old finished jobs to prevent unbounded growth
finished = [k for k, v in _jobs.items() if v["status"] in ("done", "error")]
if len(finished) > _MAX_FINISHED_JOBS:
for k in finished[:len(finished) - _MAX_FINISHED_JOBS]:
del _jobs[k]
_jobs[job_id] = {
"status": "running",
"total": len(jobs),
"completed": completed,
"runner": runner,
"created_at": time.monotonic(),
}
runner.start()
@@ -188,12 +201,23 @@ def get_export_status(job_id: str):
}
def _is_under_export_dir(real_path: str) -> bool:
"""Check if path is under EXPORT_DIR or any EXPORT_DIR_suffix sibling."""
export_real = os.path.realpath(EXPORT_DIR).rstrip(os.sep)
# Walk up ancestors — must find EXPORT_DIR or EXPORT_DIR_suffix
d = os.path.dirname(real_path)
while d != os.path.dirname(d):
if d == export_real or d.startswith(export_real + "_"):
return True
d = os.path.dirname(d)
return False
@router.delete("/export")
def delete_export(output_path: str = Query(...)):
from ..app import db
# Validate path is under EXPORT_DIR
real = os.path.realpath(output_path)
if not real.startswith(os.path.realpath(EXPORT_DIR) + os.sep):
if not _is_under_export_dir(real):
raise HTTPException(status_code=403, detail="path outside export directory")
db.delete_by_output_path(real)
if os.path.isfile(real):