YTShortMakerArchx commited on
Commit
3ba60cf
·
verified ·
1 Parent(s): cb227ac

Update main.rs

Browse files
Files changed (1) hide show
  1. main.rs +1045 -1004
main.rs CHANGED
@@ -1,38 +1,46 @@
1
- // v5
2
- use axum::{
3
- extract::{Path, Query, State},
4
- http::{HeaderMap, HeaderValue, StatusCode},
5
- response::{IntoResponse, Json},
6
- routing::{delete, get, post},
7
- Router,
 
 
 
 
 
8
  };
9
- use axum::extract::DefaultBodyLimit;
10
- use chrono::{DateTime, Utc};
11
- use parking_lot::Mutex;
12
  use serde::{Deserialize, Serialize};
13
  use sha2::{Digest, Sha256};
14
  use std::collections::{HashMap, VecDeque};
15
- use std::path::PathBuf;
16
- use std::sync::Arc;
17
- use std::time::{Duration, Instant};
 
 
18
  use tokio::io::{AsyncBufReadExt, BufReader};
19
- use tokio::process::Child;
20
- use tracing::info;
21
  use uuid::Uuid;
22
 
23
  // =============================================================================
24
- // CONFIG
25
  // =============================================================================
 
26
  lazy_static::lazy_static! {
27
- static ref HF_DATASET: String = std::env::var("HF_DATASET")
28
  .unwrap_or_else(|_| "YTShortMakerArchx/BG_VIDS_ARCHX_YT".to_string());
29
- static ref HF_TOKEN: String = std::env::var("HF_TOKEN").unwrap_or_default();
30
- static ref APP_KEY: String = std::env::var("APP_KEY")
31
  .unwrap_or_else(|_| "archx_3f9d15f52n48d41h5fj8a7e2b_private".to_string());
32
- static ref UI_ORIGIN: String = std::env::var("UI_ORIGIN")
33
  .unwrap_or_else(|_| "https://shortgen-archx.pages.dev".to_string());
34
  }
35
 
 
36
  const AUDIO_DIR: &str = "/tmp/audio";
37
  const OUTPUT_DIR: &str = "/tmp/out";
38
  const JOBS_DIR: &str = "/tmp/jobs";
@@ -41,33 +49,14 @@ const HF_CACHE_DIR: &str = "/tmp/hf_cache";
41
 
42
  const GENERATE_LIMIT: usize = 3;
43
  const STATUS_LIMIT: usize = 1000;
44
- const JOB_TIMEOUT_SECS: i64 = 900;
45
- const CACHE_TIMEOUT: u64 = 300;
46
  const MAX_CONCURRENT: usize = 1;
47
- const AVG_JOB_DURATION_S: f64 = 360.0;
48
 
49
  // =============================================================================
50
- // TYPES
51
  // =============================================================================
52
- type JobMap = Arc<Mutex<HashMap<String, Job>>>;
53
- type Queue = Arc<Mutex<VecDeque<String>>>;
54
- type RunningSet = Arc<Mutex<Vec<String>>>;
55
- type ClientMap = Arc<Mutex<HashMap<String, ClientRecord>>>;
56
- type RateLimitMap = Arc<Mutex<HashMap<String, Vec<Instant>>>>;
57
- type VideoCache = Arc<Mutex<HashMap<String, (Instant, Vec<String>)>>>;
58
- type FfmpegProcs = Arc<Mutex<HashMap<String, Child>>>;
59
-
60
- #[derive(Debug, Clone, Serialize, Deserialize)]
61
- struct ClientRecord {
62
- token: String,
63
- fingerprint: String,
64
- #[serde(with = "chrono::serde::ts_seconds")]
65
- created_at: DateTime<Utc>,
66
- #[serde(with = "chrono::serde::ts_seconds")]
67
- last_seen: DateTime<Utc>,
68
- job_count: usize,
69
- jobs: Vec<String>,
70
- }
71
 
72
  #[derive(Debug, Clone, Serialize, Deserialize)]
73
  struct Job {
@@ -77,9 +66,7 @@ struct Job {
77
  queue_position: Option<usize>,
78
  progress: u8,
79
  message: String,
80
- #[serde(with = "chrono::serde::ts_seconds")]
81
  created_at: DateTime<Utc>,
82
- #[serde(with = "chrono::serde::ts_seconds")]
83
  updated_at: DateTime<Utc>,
84
  error: Option<String>,
85
  output_path: Option<String>,
@@ -87,11 +74,21 @@ struct Job {
87
  subs_path: Option<String>,
88
  background: Option<String>,
89
  requested_duration: Option<f64>,
90
- total_duration: Option<f64>,
91
  ffmpeg_frame: u64,
92
  ffmpeg_fps: f64,
93
  ffmpeg_out_time: f64,
94
  ffmpeg_speed: f64,
 
 
 
 
 
 
 
 
 
 
 
95
  }
96
 
97
  #[derive(Debug, Deserialize)]
@@ -102,1205 +99,1249 @@ struct GenerateRequest {
102
  duration: Option<f64>,
103
  }
104
 
105
- #[derive(Debug, Deserialize)]
106
- struct JobQuery {
107
- slim: Option<bool>,
 
 
 
 
 
 
 
108
  }
109
 
110
- // =============================================================================
111
- // APP STATE
112
- // =============================================================================
113
- #[derive(Clone)]
 
 
 
114
  struct AppState {
115
- jobs: JobMap,
116
- queue: Queue,
117
- running: RunningSet,
118
- clients: ClientMap,
119
- rate_limits: RateLimitMap,
120
  video_cache: VideoCache,
121
- ffmpeg_procs: FfmpegProcs,
122
  }
123
 
124
  // =============================================================================
125
- // CLIENT HELPERS
126
  // =============================================================================
127
- fn client_file(token: &str) -> PathBuf {
128
- PathBuf::from(CLIENT_DIR).join(format!("{}.json", &token[..8.min(token.len())]))
129
- }
130
 
131
- fn load_client(token: &str, clients: &ClientMap) -> Option<ClientRecord> {
132
- if let Some(rec) = clients.lock().get(token) {
133
- return Some(rec.clone());
134
- }
135
- let path = client_file(token);
136
- if path.exists() {
137
- if let Ok(data) = std::fs::read_to_string(path) {
138
- if let Ok(rec) = serde_json::from_str::<ClientRecord>(&data) {
139
- clients.lock().insert(token.to_string(), rec.clone());
140
- return Some(rec);
141
- }
142
  }
143
  }
144
- None
145
  }
146
 
147
- fn save_client(rec: &ClientRecord, clients: &ClientMap) {
148
- clients.lock().insert(rec.token.clone(), rec.clone());
149
- let path = client_file(&rec.token);
150
- let _ = std::fs::write(path, serde_json::to_string(rec).unwrap());
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
151
  }
152
 
153
- fn fingerprint(headers: &HeaderMap) -> String {
154
- let ip = headers
155
- .get("x-forwarded-for")
156
- .and_then(|v| v.to_str().ok())
157
- .unwrap_or("unknown");
158
- let ua = headers.get("user-agent").and_then(|v| v.to_str().ok()).unwrap_or("");
159
- let accept = headers.get("accept").and_then(|v| v.to_str().ok()).unwrap_or("");
160
- let data = format!("{}:{}:{}", ip, ua, accept);
161
  let mut hasher = Sha256::new();
162
- hasher.update(data.as_bytes());
163
- format!("{:x}", hasher.finalize())
164
  }
165
 
166
- async fn resolve_client(headers: &HeaderMap, state: &AppState) -> ClientRecord {
167
- let token = headers
168
- .get("X-Client-ID")
169
- .and_then(|v| v.to_str().ok())
170
- .unwrap_or("")
171
- .to_string();
172
-
173
- if !token.is_empty() {
174
- if let Some(mut rec) = load_client(&token, &state.clients) {
175
- rec.last_seen = Utc::now();
176
- save_client(&rec, &state.clients);
177
- return rec;
178
- } else {
179
- let fp = fingerprint(headers);
180
- let rec = ClientRecord {
181
- token: token.clone(),
182
- fingerprint: fp,
183
- created_at: Utc::now(),
184
- last_seen: Utc::now(),
185
- job_count: 0,
186
- jobs: vec![],
187
- };
188
- save_client(&rec, &state.clients);
189
- return rec;
190
- }
191
- }
192
-
193
- let fp = fingerprint(headers);
194
- {
195
- let map = state.clients.lock();
196
- for rec in map.values() {
197
- if rec.fingerprint == fp {
198
- let mut rec = rec.clone();
199
- rec.last_seen = Utc::now();
200
- drop(map);
201
- save_client(&rec, &state.clients);
202
- return rec;
203
- }
204
- }
205
  }
206
- let rec = ClientRecord {
207
- token: Uuid::new_v4().to_string().replace('-', ""),
208
- fingerprint: fp,
209
- created_at: Utc::now(),
210
- last_seen: Utc::now(),
211
- job_count: 0,
212
- jobs: vec![],
213
- };
214
- save_client(&rec, &state.clients);
215
- rec
216
  }
217
 
218
- // =============================================================================
219
- // RATE LIMITING
220
- // =============================================================================
221
- fn rate_limit(key: &str, limit: usize, window: Duration, state: &AppState) -> bool {
222
- let mut map = state.rate_limits.lock();
223
- let now = Instant::now();
224
- let entries = map.entry(key.to_string()).or_insert_with(Vec::new);
225
- entries.retain(|t| now.duration_since(*t) < window);
226
- if entries.len() >= limit {
227
  return false;
228
  }
229
- entries.push(now);
230
  true
231
  }
232
 
233
- // =============================================================================
234
- // UTILITIES
235
- // =============================================================================
236
- fn validate_app_key(headers: &HeaderMap) -> bool {
237
- if APP_KEY.is_empty() || *APP_KEY == "archnemix-secret-key-change-in-production" {
238
- return true;
 
 
 
 
 
 
 
239
  }
240
- if let Some(key) = headers.get("X-APP-KEY").and_then(|v| v.to_str().ok()) {
241
- if key == APP_KEY.as_str() {
242
- return true;
243
- }
 
 
 
 
 
 
 
244
  }
245
- if let Some(auth) = headers.get("Authorization").and_then(|v| v.to_str().ok()) {
246
- if auth.starts_with("Bearer ") && &auth[7..] == APP_KEY.as_str() {
247
- return true;
248
- }
249
  }
250
- false
 
 
 
 
 
251
  }
252
 
253
- fn validate_origin(headers: &HeaderMap) -> bool {
254
- let origin = headers
255
- .get("origin")
256
- .or_else(|| headers.get("referer"))
257
- .and_then(|v| v.to_str().ok())
258
- .unwrap_or("");
259
- if origin.is_empty() {
260
- return true;
 
 
 
 
 
 
 
 
 
261
  }
262
- let allowed = [
263
- "https://shortgen-archx.pages.dev",
264
- "http://localhost:3000",
265
- "http://127.0.0.1:3000",
266
- "http://localhost:5500",
267
- "http://127.0.0.1:5500",
268
- "https://huggingface.co",
269
- ];
270
- allowed.iter().any(|&a| origin.starts_with(a))
271
  }
272
 
273
  // =============================================================================
274
- // DATASET HELPERS
275
  // =============================================================================
276
- async fn list_videos_from_dataset(category: &str, state: &AppState) -> Vec<String> {
 
277
  let cache_key = format!("videos_{}", category);
 
 
278
  {
279
- let cache = state.video_cache.lock();
280
- if let Some((ts, list)) = cache.get(&cache_key) {
281
- if ts.elapsed() < Duration::from_secs(CACHE_TIMEOUT) {
282
- return list.clone();
283
  }
284
  }
285
  }
286
-
 
 
287
  let client = reqwest::Client::new();
288
- let url = format!(
289
- "https://huggingface.co/api/datasets/{}/tree/main/{}",
290
- *HF_DATASET, category
291
- );
292
- let resp = client
293
- .get(&url)
294
- .header("Authorization", format!("Bearer {}", *HF_TOKEN))
295
- .send()
296
- .await;
297
-
298
- let mut videos = vec![];
299
- if let Ok(resp) = resp {
300
  if let Ok(files) = resp.json::<Vec<serde_json::Value>>().await {
301
- for file in files {
302
- if let Some(path) = file.get("path").and_then(|p| p.as_str()) {
303
- if path.ends_with(".mp4") {
304
- let name = path.rsplit('/').next().unwrap_or("").replace(".mp4", "");
305
- videos.push(name);
306
- }
307
- }
 
 
 
 
 
308
  }
309
  }
310
  }
311
- if videos.is_empty() {
312
- videos = (1..=6).map(|i| format!("mc{}", i)).collect();
313
- }
314
- state.video_cache.lock().insert(cache_key, (Instant::now(), videos.clone()));
315
- videos
316
  }
317
 
318
- async fn download_video_from_dataset(video_name: &str, category: &str) -> Result<String, String> {
319
- let video_name = video_name.replace(".mp4", "");
320
- let cache_path = PathBuf::from(HF_CACHE_DIR).join(format!("{}.mp4", video_name));
321
- if cache_path.exists() {
322
- return Ok(cache_path.to_string_lossy().to_string());
323
- }
324
-
325
- let client = reqwest::Client::new();
326
- for candidate in &[
327
  format!("{}/{}.mp4", category, video_name),
328
  format!("{}.mp4", video_name),
329
- ] {
330
- let url = format!(
331
- "https://huggingface.co/datasets/{}/resolve/main/{}",
332
- *HF_DATASET, candidate
333
- );
334
- let resp = client
335
- .get(&url)
336
- .header("Authorization", format!("Bearer {}", *HF_TOKEN))
337
- .send()
338
- .await;
339
- if let Ok(resp) = resp {
 
 
 
 
 
 
 
 
 
340
  if resp.status().is_success() {
341
- let bytes = resp.bytes().await.map_err(|e| e.to_string())?;
342
- tokio::fs::create_dir_all(HF_CACHE_DIR).await.ok();
343
- tokio::fs::write(&cache_path, bytes).await.map_err(|e| e.to_string())?;
344
- return Ok(cache_path.to_string_lossy().to_string());
 
345
  }
346
  }
347
  }
348
- Err(format!("Video '{}' not found", video_name))
 
349
  }
350
 
351
  // =============================================================================
352
- // FILE HELPERS
353
  // =============================================================================
354
- async fn save_base64_audio(data: &str, path: &PathBuf) -> Result<usize, String> {
355
- use base64::{engine::general_purpose, Engine as _};
356
- let data = if data.starts_with("data:audio/") {
357
- data.split(',').nth(1).unwrap_or(data)
358
- } else {
359
- data
360
- };
361
- let bytes = general_purpose::STANDARD.decode(data).map_err(|e| e.to_string())?;
362
- if bytes.len() > 20 * 1024 * 1024 {
363
- return Err("Audio too large (max 20 MB)".to_string());
364
- }
365
- tokio::fs::write(path, &bytes).await.map_err(|e| e.to_string())?;
366
- Ok(bytes.len())
367
  }
368
 
369
- async fn save_subtitles(ass: &str, path: &PathBuf) -> Result<(), String> {
370
- if !ass.contains("[Script Info]") || !ass.contains("[Events]") {
371
- return Err("Invalid ASS subtitle format".to_string());
372
- }
373
- if ass.len() > 500 * 1024 {
374
- return Err("Subtitles too large (max 500 KB)".to_string());
375
  }
376
- tokio::fs::write(path, ass).await.map_err(|e| e.to_string())?;
377
- Ok(())
378
  }
379
 
380
- fn get_media_duration(path: &PathBuf) -> f64 {
381
- let output = std::process::Command::new("ffprobe")
382
- .args([
383
- "-v", "error",
384
- "-show_entries", "format=duration",
385
- "-of", "default=noprint_wrappers=1:nokey=1",
386
- path.to_str().unwrap_or(""),
387
- ])
388
- .output();
389
- if let Ok(out) = output {
390
- if let Ok(stdout) = String::from_utf8(out.stdout) {
391
- if let Ok(dur) = stdout.trim().parse::<f64>() {
392
- return dur;
393
- }
394
  }
 
 
 
 
 
 
 
 
 
 
 
395
  }
396
- if let Ok(meta) = std::fs::metadata(path) {
397
- return (meta.len() as f64 / 16000.0).max(1.0).min(180.0);
 
 
 
 
 
 
 
 
 
 
 
398
  }
399
- 30.0
 
 
 
 
 
 
 
 
 
 
400
  }
401
 
402
  // =============================================================================
403
  // JOB MANAGEMENT
404
  // =============================================================================
405
- fn create_job(job_id: &str, client_token: &str) -> Job {
406
- let now = Utc::now();
407
- Job {
408
- id: job_id.to_string(),
409
- client_token: client_token.to_string(),
410
  status: "queued".to_string(),
411
  queue_position: None,
412
  progress: 0,
413
- message: "Waiting in queue\u{2026}".to_string(),
414
- created_at: now,
415
- updated_at: now,
416
  error: None,
417
  output_path: None,
418
  audio_path: None,
419
  subs_path: None,
420
  background: None,
421
  requested_duration: None,
422
- total_duration: None,
423
  ffmpeg_frame: 0,
424
  ffmpeg_fps: 0.0,
425
  ffmpeg_out_time: 0.0,
426
  ffmpeg_speed: 0.0,
427
- }
428
- }
429
-
430
- fn update_job(job_id: &str, state: &AppState, f: impl FnOnce(&mut Job)) {
431
- // Capture the data to write while holding the lock briefly
432
- let (job_data, path) = {
433
- let mut jobs = state.jobs.lock();
434
- if let Some(job) = jobs.get_mut(job_id) {
435
- f(job);
436
- job.updated_at = Utc::now();
437
- let data = serde_json::to_string(&*job).unwrap();
438
- let path = PathBuf::from(JOBS_DIR).join(format!("{}.json", job_id));
439
- (Some(data), path)
440
- } else {
441
- (None, PathBuf::new())
442
- }
443
  };
444
- if let Some(data) = job_data {
445
- // Spawn a blocking task to write the file – doesn't hold the lock
446
- tokio::task::spawn_blocking(move || {
447
- let _ = std::fs::write(path, data);
448
- });
449
- }
450
  }
451
 
452
- fn load_job(job_id: &str) -> Option<Job> {
453
- let path = PathBuf::from(JOBS_DIR).join(format!("{}.json", job_id));
454
- if path.exists() {
455
- if let Ok(data) = std::fs::read_to_string(path) {
456
- if let Ok(job) = serde_json::from_str(&data) {
457
- return Some(job);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
458
  }
459
  }
 
460
  }
461
- None
462
- }
463
-
464
- fn cleanup_old_jobs(state: &AppState) {
465
- let now = Utc::now();
466
- let mut jobs = state.jobs.lock();
467
- let to_remove: Vec<String> = jobs
468
- .iter()
469
- .filter(|(_, j)| (now - j.updated_at).num_seconds() > 3600)
470
- .map(|(id, _)| id.clone())
471
- .collect();
472
- for id in to_remove {
473
- jobs.remove(&id);
474
- state.queue.lock().retain(|jid| jid != &id);
475
- state.running.lock().retain(|jid| jid != &id);
476
- let _ = std::fs::remove_file(PathBuf::from(JOBS_DIR).join(format!("{}.json", id)));
477
- let _ = std::fs::remove_file(PathBuf::from(AUDIO_DIR).join(format!("{}.mp3", id)));
478
- let _ = std::fs::remove_file(PathBuf::from(AUDIO_DIR).join(format!("{}.ass", id)));
479
- let _ = std::fs::remove_file(PathBuf::from(OUTPUT_DIR).join(format!("{}.mp4", id)));
480
- }
481
- }
482
-
483
- // =============================================================================
484
- // QUEUE HELPERS
485
- // =============================================================================
486
- fn queue_position(job_id: &str, state: &AppState) -> Option<usize> {
487
- state.queue.lock().iter().position(|jid| jid == job_id).map(|i| i + 1)
488
- }
489
-
490
- fn queue_eta(position: usize, job_duration: Option<f64>, state: &AppState) -> serde_json::Value {
491
- let running_remaining = {
492
- let running = state.running.lock();
493
- if running.is_empty() {
494
- AVG_JOB_DURATION_S
495
- } else {
496
- let mut min_remaining = AVG_JOB_DURATION_S;
497
- for jid in running.iter() {
498
- if let Some(job) = state.jobs.lock().get(jid) {
499
- let total = job.total_duration.unwrap_or(AVG_JOB_DURATION_S);
500
- let remaining = (total - job.ffmpeg_out_time).max(0.0);
501
- if remaining < min_remaining {
502
- min_remaining = remaining;
503
- }
504
- }
505
- }
506
- min_remaining
507
- }
508
- };
509
-
510
- let queued_ahead = (position - 1) as f64;
511
- let total_wait_s = running_remaining + queued_ahead * AVG_JOB_DURATION_S;
512
- let own_duration = job_duration.unwrap_or(AVG_JOB_DURATION_S);
513
- let total_s = total_wait_s + own_duration;
514
- let low_s = (total_wait_s * 0.75) as i32;
515
- let high_s = (total_wait_s * 1.2) as i32;
516
-
517
- let fmt = |s: i32| -> String {
518
- if s < 60 {
519
- format!("{}s", s)
520
- } else {
521
- let m = s / 60;
522
- let sec = s % 60;
523
- if sec == 0 { format!("{}m", m) } else { format!("{}m {:02}s", m, sec) }
524
- }
525
- };
526
-
527
- serde_json::json!({
528
- "queue_position": position,
529
- "jobs_ahead": position,
530
- "wait_low_s": low_s,
531
- "wait_high_s": high_s,
532
- "wait_low_human": fmt(low_s),
533
- "wait_high_human": fmt(high_s),
534
- "total_with_own_s": total_s as i32,
535
- "message": format!(
536
- "Position {} in queue \u{2014} roughly {}\u{2013}{} wait, likely less",
537
- position, fmt(low_s), fmt(high_s)
538
- ),
539
- })
540
- }
541
-
542
- fn refresh_queue_positions(state: &AppState) {
543
- let queue = state.queue.lock();
544
- for (i, jid) in queue.iter().enumerate() {
545
- let pos = i + 1;
546
- if let Some(job) = state.jobs.lock().get_mut(jid) {
547
- job.queue_position = Some(pos);
548
- job.message = queue_eta(pos, job.requested_duration, state)["message"]
549
- .as_str()
550
- .unwrap_or("")
551
- .to_string();
552
- }
553
- }
554
  }
555
 
556
- async fn queue_worker(state: AppState) {
557
- loop {
558
- tokio::time::sleep(Duration::from_secs(2)).await;
559
- if state.running.lock().len() >= MAX_CONCURRENT {
560
- continue;
561
- }
562
- let next_job = state.queue.lock().pop_front();
563
- if let Some(job_id) = next_job {
564
- let job_opt = state.jobs.lock().get(&job_id).cloned();
565
- if let Some(job) = job_opt {
566
- if job.status != "queued" {
567
- continue;
568
- }
569
- state.running.lock().push(job_id.clone());
570
- update_job(&job_id, &state, |j| {
571
- j.status = "processing".to_string();
572
- j.queue_position = None;
573
- });
574
- refresh_queue_positions(&state);
575
- let state_clone = state.clone();
576
- tokio::spawn(async move {
577
- process_video_task(job_id, state_clone).await;
578
- });
579
- }
580
  }
581
  }
582
  }
583
 
584
  // =============================================================================
585
- // FFMPEG PROCESSING
586
  // =============================================================================
587
- async fn process_video_task(job_id: String, state: AppState) {
588
- info!("Job {}: starting single-pass encode", &job_id[..8.min(job_id.len())]);
589
-
590
- update_job(&job_id, &state, |j| {
591
- j.status = "processing".to_string();
592
- j.progress = 10;
593
- j.message = "Downloading background video\u{2026}".to_string();
594
- j.queue_position = None;
595
- });
596
-
597
- let (audio_path, subs_path, background, requested_duration) = {
598
- let jobs = state.jobs.lock();
599
- let job = match jobs.get(&job_id) {
600
- Some(j) => j.clone(),
601
- None => return,
602
- };
603
- (
604
- job.audio_path.clone().unwrap_or_default(),
605
- job.subs_path.clone().unwrap_or_default(),
606
- job.background.clone().unwrap_or_else(|| "mc1".to_string()),
607
- job.requested_duration,
608
- )
609
- };
610
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
611
  let bg_path = match download_video_from_dataset(&background, "minecraft").await {
612
  Ok(p) => p,
613
  Err(e) => {
614
- update_job(&job_id, &state, |j| {
615
- j.status = "failed".to_string();
616
- j.error = Some(e);
617
- });
618
- state.running.lock().retain(|jid| jid != &job_id);
619
- refresh_queue_positions(&state);
620
  return;
621
  }
622
  };
623
-
624
- update_job(&job_id, &state, |j| {
625
- j.progress = 20;
626
- j.message = "Analysing media\u{2026}".to_string();
627
- });
628
-
629
- let audio_dur = requested_duration
630
- .unwrap_or_else(|| get_media_duration(&PathBuf::from(&audio_path)));
631
- let video_dur = get_media_duration(&PathBuf::from(&bg_path));
632
-
633
- if !(1.0..=180.0).contains(&audio_dur) {
634
- update_job(&job_id, &state, |j| {
635
- j.status = "failed".to_string();
636
- j.error = Some("Audio duration out of range (1\u{2013}180 s)".to_string());
637
- });
638
- state.running.lock().retain(|jid| jid != &job_id);
639
- refresh_queue_positions(&state);
 
 
640
  return;
641
  }
642
-
643
- let bg_input_args: Vec<String> = if video_dur > audio_dur {
 
 
 
 
644
  let max_start = video_dur - audio_dur;
645
- let start = max_start * 0.3;
646
- vec![
647
- "-ss".to_string(), format!("{:.3}", start),
648
- "-t".to_string(), format!("{:.3}", audio_dur),
649
- "-i".to_string(), bg_path.clone(),
650
- ]
651
  } else {
652
- let loop_n = (audio_dur / video_dur) as i32 + 2;
653
- vec![
654
- "-stream_loop".to_string(), loop_n.to_string(),
655
- "-i".to_string(), bg_path.clone(),
656
- ]
657
- };
658
-
659
- let subs_escaped = subs_path.replace('\\', "/").replace(':', "\\:");
660
  let vf = format!(
661
  "[0:v]ass='{}',scale=1080:1920:force_original_aspect_ratio=increase,crop=1080:1920,setsar=1[v]",
662
- subs_escaped
663
  );
664
-
665
  let output_path = PathBuf::from(OUTPUT_DIR).join(format!("{}.mp4", job_id));
666
-
667
- let mut cmd_args: Vec<String> = vec![
668
- "-y".to_string(), "-hide_banner".to_string(),
669
- "-loglevel".to_string(), "error".to_string(),
 
670
  ];
671
- cmd_args.extend(bg_input_args);
672
- cmd_args.extend([
673
- "-i".to_string(), audio_path.clone(),
674
- "-filter_complex".to_string(), vf,
675
- "-map".to_string(), "[v]".to_string(),
676
- "-map".to_string(), "1:a".to_string(),
677
- "-c:v".to_string(), "libx264".to_string(),
678
- "-preset".to_string(), "medium".to_string(),
679
- "-crf".to_string(), "16".to_string(),
680
- "-minrate".to_string(), "8M".to_string(),
681
- "-maxrate".to_string(), "16M".to_string(),
682
- "-bufsize".to_string(), "16M".to_string(),
683
- "-profile:v".to_string(), "high".to_string(),
684
- "-level:v".to_string(), "4.2".to_string(),
685
- "-pix_fmt".to_string(), "yuv420p".to_string(),
686
- "-c:a".to_string(), "aac".to_string(),
687
- "-b:a".to_string(), "192k".to_string(),
688
- "-shortest".to_string(),
689
- "-movflags".to_string(), "+faststart".to_string(),
690
- "-threads".to_string(), "0".to_string(),
691
- "-progress".to_string(), "pipe:2".to_string(),
692
- "-t".to_string(), format!("{:.3}", audio_dur),
693
- output_path.to_string_lossy().to_string(),
694
  ]);
695
-
696
- update_job(&job_id, &state, |j| {
697
- j.progress = 40;
698
- j.message = "Encoding\u{2026} (single-pass)".to_string();
699
- j.total_duration = Some(audio_dur);
700
- });
701
-
702
- let mut proc = match tokio::process::Command::new("ffmpeg")
 
703
  .args(&cmd_args)
704
- .stdout(std::process::Stdio::null())
705
- .stderr(std::process::Stdio::piped())
706
  .spawn()
707
  {
708
- Ok(p) => p,
709
  Err(e) => {
710
- update_job(&job_id, &state, |j| {
711
- j.status = "failed".to_string();
712
- j.error = Some(format!("Failed to spawn ffmpeg: {}", e));
713
- });
714
- state.running.lock().retain(|jid| jid != &job_id);
715
- refresh_queue_positions(&state);
716
  return;
717
  }
718
  };
719
-
720
- let pid = proc.id();
721
- let stderr = proc.stderr.take().unwrap();
722
- let mut reader = BufReader::new(stderr).lines();
723
-
724
- let mut frame: u64 = 0;
725
- let mut fps: f64 = 0.0;
726
- let mut speed: f64 = 0.0;
727
- let mut out_time_s: f64 = 0.0;
728
-
729
- let timeout = tokio::time::Duration::from_secs((audio_dur * 5.0) as u64 + 120);
730
- let encode_start = tokio::time::Instant::now();
731
-
732
- loop {
733
- {
734
- let jobs = state.jobs.lock();
735
- if let Some(j) = jobs.get(&job_id) {
736
- if j.status == "failed" {
737
- if let Some(p) = pid {
738
- let _ = std::process::Command::new("kill")
739
- .args(["-9", &p.to_string()])
740
- .output();
741
- }
742
- drop(jobs);
743
- state.running.lock().retain(|jid| jid != &job_id);
744
- refresh_queue_positions(&state);
745
- return;
746
- }
747
  }
748
- }
749
-
750
- if encode_start.elapsed() > timeout {
751
- if let Some(p) = pid {
752
- let _ = std::process::Command::new("kill")
753
- .args(["-9", &p.to_string()])
754
- .output();
755
  }
756
- update_job(&job_id, &state, |j| {
757
- j.status = "failed".to_string();
758
- j.error = Some("Encoding timed out \u{2014} try a shorter script".to_string());
759
- });
760
- state.running.lock().retain(|jid| jid != &job_id);
761
- refresh_queue_positions(&state);
762
- return;
763
- }
764
-
765
- match tokio::time::timeout(
766
- tokio::time::Duration::from_millis(500),
767
- reader.next_line(),
768
- ).await {
769
- Ok(Ok(Some(line))) => {
770
- if let Some((k, v)) = line.split_once('=') {
771
- let k = k.trim();
772
- let v = v.trim();
773
- match k {
774
- "frame" => frame = v.parse().unwrap_or(frame),
775
- "fps" => fps = v.parse().unwrap_or(fps),
776
- "speed" => speed = v.replace('x', "").parse().unwrap_or(speed),
777
- "out_time_ms" => {
778
- out_time_s = v.parse::<f64>().unwrap_or(0.0) / 1_000_000.0
779
- }
780
- "out_time" => {
781
- let parts: Vec<&str> = v.split(':').collect();
782
- if parts.len() == 3 {
783
- let h: f64 = parts[0].parse().unwrap_or(0.0);
784
- let m: f64 = parts[1].parse().unwrap_or(0.0);
785
- let s: f64 = parts[2].parse().unwrap_or(0.0);
786
- out_time_s = h * 3600.0 + m * 60.0 + s;
787
- }
788
- }
789
- "progress" => {
790
- let ratio = if audio_dur > 0.0 {
791
- (out_time_s / audio_dur).min(1.0)
792
- } else { 0.0 };
793
- let mapped = 40 + (ratio * 55.0) as u8;
794
- let msg = if audio_dur > 0.0 && speed > 0.0 {
 
 
 
 
 
 
 
 
 
795
  format!(
796
- "Encoding {:.1}s / {:.1}s ({:.1}\u{d7} speed)",
797
- out_time_s, audio_dur, speed
798
  )
799
  } else {
800
- "Encoding\u{2026}".to_string()
801
  };
802
- update_job(&job_id, &state, |j| {
803
- j.progress = mapped;
804
- j.ffmpeg_frame = frame;
805
- j.ffmpeg_fps = fps;
806
- j.ffmpeg_out_time = out_time_s;
807
- j.ffmpeg_speed = speed;
808
- j.message = msg;
809
- });
810
- if v == "end" { break; }
811
  }
812
- _ => {}
 
 
 
813
  }
814
  }
 
815
  }
816
- Ok(Ok(None)) => break,
817
- Ok(Err(_)) => break,
818
- Err(_) => {}
819
  }
820
- }
821
-
822
- let exit_status = proc.wait().await;
823
- state.ffmpeg_procs.lock().remove(&job_id);
824
-
825
- match exit_status {
826
- Ok(status) if status.success() => {}
827
- Ok(status) => {
828
- update_job(&job_id, &state, |j| {
829
- j.status = "failed".to_string();
830
- j.error = Some(format!("FFmpeg exited with code {}", status.code().unwrap_or(-1)));
831
- });
832
- state.running.lock().retain(|jid| jid != &job_id);
833
- refresh_queue_positions(&state);
 
 
 
 
834
  return;
835
  }
836
- Err(e) => {
837
- update_job(&job_id, &state, |j| {
838
- j.status = "failed".to_string();
839
- j.error = Some(format!("FFmpeg wait error: {}", e));
840
- });
841
- state.running.lock().retain(|jid| jid != &job_id);
842
- refresh_queue_positions(&state);
843
  return;
844
  }
845
  }
846
-
847
- if !output_path.exists()
848
- || std::fs::metadata(&output_path).map(|m| m.len() == 0).unwrap_or(true)
849
- {
850
- update_job(&job_id, &state, |j| {
851
- j.status = "failed".to_string();
852
- j.error = Some("Output file missing after encode".to_string());
853
- });
854
- state.running.lock().retain(|jid| jid != &job_id);
855
- refresh_queue_positions(&state);
856
  return;
857
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
858
 
859
- let size_mb = std::fs::metadata(&output_path)
860
- .map(|m| m.len() as f64 / 1024.0 / 1024.0)
861
- .unwrap_or(0.0);
862
-
863
- let _ = tokio::fs::remove_file(&audio_path).await;
864
- let _ = tokio::fs::remove_file(&subs_path).await;
865
 
866
- info!("Job {}: done {:.2} MB", &job_id[..8.min(job_id.len())], size_mb);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
867
 
868
- update_job(&job_id, &state, |j| {
869
- j.status = "completed".to_string();
870
- j.progress = 100;
871
- j.message = format!(
872
- "Done! {:.1} MB \u{2022} CRF 16 \u{2022} medium \u{2022} 8\u{2013}16 Mbps",
873
- size_mb
874
- );
875
- j.output_path = Some(output_path.to_string_lossy().to_string());
876
- });
877
 
878
- state.running.lock().retain(|jid| jid != &job_id);
879
- refresh_queue_positions(&state);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
880
  }
881
 
882
  // =============================================================================
883
  // ENDPOINTS
884
  // =============================================================================
885
 
886
- async fn root() -> impl IntoResponse {
887
- Json(serde_json::json!({
 
888
  "name": "ArchNemix Shorts Generator API",
889
- "version": "5.0.0",
 
890
  "queue": {
891
  "max_concurrent": MAX_CONCURRENT,
892
  "avg_job_duration_s": AVG_JOB_DURATION_S,
893
  },
894
  "endpoints": {
895
- "register": "GET /register",
896
- "generate": "POST /generate",
897
- "cancel": "DELETE /job/{id}",
898
  "job_status": "GET /job/{id}",
899
- "queue": "GET /queue",
900
- "download": "GET /download/{id}",
901
- "delete": "DELETE /video/{id}",
902
- "videos": "GET /videos/{category}",
903
- "health": "GET /health",
 
904
  },
905
  }))
906
  }
907
 
908
- async fn register(State(state): State<AppState>, headers: HeaderMap) -> impl IntoResponse {
909
- let client = resolve_client(&headers, &state).await;
910
- let mut response_headers = HeaderMap::new();
911
- response_headers.insert("X-Client-ID", HeaderValue::from_str(&client.token).unwrap());
912
- (
913
- response_headers,
914
- Json(serde_json::json!({
915
  "client_token": client.token,
916
  "is_new": client.job_count == 0,
917
  "job_count": client.job_count,
918
- "instructions": "Store client_token in localStorage as 'archx_client_id'. Send it as the X-Client-ID header on every request."
919
- })),
920
- )
921
  }
922
 
923
- async fn health(State(state): State<AppState>) -> impl IntoResponse {
924
- let videos = list_videos_from_dataset("minecraft", &state).await;
925
- Json(serde_json::json!({
 
 
 
 
 
926
  "status": "healthy",
927
  "timestamp": Utc::now().to_rfc3339(),
928
  "videos": videos.len(),
929
- "running": state.running.lock().len(),
930
- "queued": state.queue.lock().len(),
931
- "active_jobs": state.jobs.lock().values().filter(|j| j.status == "processing").count(),
932
  }))
933
  }
934
 
935
- async fn queue_status(State(state): State<AppState>) -> impl IntoResponse {
936
- let running = state.running.lock().len();
937
- let waiting = state.queue.lock().len();
938
- Json(serde_json::json!({
 
 
939
  "running": running,
940
  "waiting": waiting,
941
  "total_active": running + waiting,
942
  "avg_job_s": AVG_JOB_DURATION_S,
943
- "estimated_wait_s": if running == 0 {
944
- (waiting as f64 * AVG_JOB_DURATION_S) as u64
945
- } else {
946
- ((waiting + 1) as f64 * AVG_JOB_DURATION_S) as u64
947
- },
948
  "message": if running + waiting == 0 {
949
- "No jobs running \u{2014} submit yours now!".to_string()
950
  } else {
951
- format!("{} running, {} in queue", running, waiting)
952
  },
953
  }))
954
  }
955
 
956
- async fn list_videos(
957
- Path(category): Path<String>,
958
- State(state): State<AppState>,
959
- ) -> impl IntoResponse {
960
- let videos = list_videos_from_dataset(&category, &state).await;
961
- Json(serde_json::json!({
962
- "category": category,
963
  "videos": videos,
964
  "count": videos.len(),
965
  }))
966
  }
967
 
 
968
  async fn generate(
969
- State(state): State<AppState>,
970
- headers: HeaderMap,
971
- Json(payload): Json<GenerateRequest>,
972
- ) -> impl IntoResponse {
973
- if !validate_app_key(&headers) {
974
- return (StatusCode::FORBIDDEN, Json(serde_json::json!({"detail": "Invalid API key"}))).into_response();
975
  }
976
- if !validate_origin(&headers) {
977
- return (StatusCode::FORBIDDEN, Json(serde_json::json!({"detail": "Invalid origin"}))).into_response();
 
 
 
 
 
978
  }
979
-
980
- let client = resolve_client(&headers, &state).await;
981
- let token = client.token.clone();
982
-
983
- if !rate_limit(&format!("generate:{}", token), GENERATE_LIMIT, Duration::from_secs(3600), &state) {
984
- return (
985
- StatusCode::TOO_MANY_REQUESTS,
986
- Json(serde_json::json!({"detail": format!("Rate limit: max {} requests/hour", GENERATE_LIMIT)})),
987
- ).into_response();
 
 
988
  }
989
-
990
- cleanup_old_jobs(&state);
991
-
992
- let active = state.jobs.lock().values().any(|j| {
993
- j.client_token == token && (j.status == "queued" || j.status == "processing")
994
- });
995
- if active {
996
- return (
997
- StatusCode::CONFLICT,
998
- Json(serde_json::json!({"detail": "You already have an active job. Wait for it to finish or cancel it first."})),
999
- ).into_response();
1000
- }
1001
-
1002
- let job_id = Uuid::new_v4().to_string().replace('-', "");
1003
  let audio_path = PathBuf::from(AUDIO_DIR).join(format!("{}.mp3", job_id));
1004
  let subs_path = PathBuf::from(AUDIO_DIR).join(format!("{}.ass", job_id));
1005
-
1006
- let mut job = create_job(&job_id, &token);
1007
- job.audio_path = Some(audio_path.to_string_lossy().to_string());
1008
- job.subs_path = Some(subs_path.to_string_lossy().to_string());
1009
- job.background = Some(payload.background.clone());
1010
- job.requested_duration = payload.duration;
1011
- state.jobs.lock().insert(job_id.clone(), job);
1012
-
1013
- if let Err(e) = save_base64_audio(&payload.audio_base64, &audio_path).await {
1014
- update_job(&job_id, &state, |j| {
1015
- j.status = "failed".to_string();
1016
- j.error = Some(e.clone());
1017
- });
1018
- return (StatusCode::BAD_REQUEST, Json(serde_json::json!({"detail": e}))).into_response();
1019
  }
1020
- if let Err(e) = save_subtitles(&payload.subtitles_ass, &subs_path).await {
1021
- update_job(&job_id, &state, |j| {
1022
- j.status = "failed".to_string();
1023
- j.error = Some(e.clone());
1024
- });
1025
- return (StatusCode::BAD_REQUEST, Json(serde_json::json!({"detail": e}))).into_response();
 
1026
  }
1027
-
1028
- {
1029
- let mut clients = state.clients.lock();
1030
- if let Some(rec) = clients.get_mut(&token) {
1031
- rec.job_count += 1;
1032
- rec.jobs.push(job_id.clone());
1033
- if rec.jobs.len() > 50 {
1034
- let len = rec.jobs.len();
1035
- rec.jobs = rec.jobs[len - 50..].to_vec();
1036
- }
1037
- let rec_clone = rec.clone();
1038
- drop(clients);
1039
- save_client(&rec_clone, &state.clients);
1040
- }
1041
  }
1042
-
 
 
1043
  let position = {
1044
- let mut queue = state.queue.lock();
 
1045
  queue.push_back(job_id.clone());
1046
- queue.len()
1047
  };
1048
- let running = state.running.lock().len();
1049
- let queue_pos = if running == 0 { 0 } else { position };
1050
- refresh_queue_positions(&state);
1051
-
1052
- let eta = if queue_pos == 0 {
1053
- serde_json::json!({"message": "Starting very soon\u{2026}", "wait_low_s": 0, "wait_high_s": 30})
 
 
 
 
 
 
1054
  } else {
1055
- queue_eta(queue_pos, payload.duration, &state)
 
 
1056
  };
1057
-
1058
- let mut h = HeaderMap::new();
1059
- h.insert("X-Client-ID", HeaderValue::from_str(&token).unwrap());
1060
- (
1061
- StatusCode::OK,
1062
- h,
1063
- Json(serde_json::json!({
1064
  "job_id": job_id,
1065
- "client_token": token,
1066
  "status": "queued",
1067
- "queue_position": if queue_pos > 0 { queue_pos } else { 1 },
1068
  "queue": eta,
1069
  "check_status": format!("/job/{}", job_id),
1070
- })),
1071
- ).into_response()
1072
  }
1073
 
1074
- async fn job_status(
1075
- Path(job_id): Path<String>,
1076
- _query: Query<JobQuery>,
1077
- State(state): State<AppState>,
1078
- _headers: HeaderMap,
1079
- ) -> impl IntoResponse {
1080
- if !rate_limit(&format!("status:{}", job_id), STATUS_LIMIT, Duration::from_secs(3600), &state) {
1081
- return (StatusCode::OK, Json(serde_json::json!({"job_id": job_id, "status": "rate_limited"}))).into_response();
1082
  }
1083
-
1084
- let job = state.jobs.lock().get(&job_id).cloned().or_else(|| load_job(&job_id));
1085
- let mut job = match job {
1086
- Some(j) => j,
1087
- None => return (StatusCode::NOT_FOUND, Json(serde_json::json!({"detail": "Job not found"}))).into_response(),
1088
- };
1089
-
1090
- if (Utc::now() - job.updated_at).num_seconds() > JOB_TIMEOUT_SECS
1091
- && job.status != "completed"
1092
- && job.status != "failed"
1093
- {
1094
- job.status = "failed".to_string();
1095
- job.error = Some("Job timed out".to_string());
1096
- update_job(&job_id, &state, |j| {
1097
- j.status = "failed".to_string();
1098
- j.error = Some("Job timed out".to_string());
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1099
  });
 
 
 
 
 
 
 
 
 
 
 
1100
  }
 
 
 
1101
 
1102
- let pos = queue_position(&job_id, &state);
1103
- let mut resp = serde_json::json!({
1104
- "job_id": job.id,
1105
- "status": job.status,
1106
- "progress": job.progress,
1107
- "message": job.message,
1108
- "queue_position": pos,
1109
- "queue": if let Some(p) = pos {
1110
- queue_eta(p, job.requested_duration, &state)
1111
- } else {
1112
- serde_json::Value::Null
1113
- },
1114
- "created_at": job.created_at.to_rfc3339(),
1115
- "updated_at": job.updated_at.to_rfc3339(),
1116
- "encode_stats": {
1117
- "frame": job.ffmpeg_frame,
1118
- "fps": job.ffmpeg_fps,
1119
- "out_time_s": job.ffmpeg_out_time,
1120
- "total_s": job.total_duration.unwrap_or(0.0),
1121
- "speed": job.ffmpeg_speed,
1122
- },
1123
- });
1124
-
1125
- if job.status == "completed" && job.output_path.is_some() {
1126
- resp["download_url"] = serde_json::Value::String(format!("/download/{}", job_id));
1127
  }
1128
- if let Some(err) = job.error {
1129
- resp["error"] = serde_json::Value::String(err);
 
 
 
 
1130
  }
1131
-
1132
- (StatusCode::OK, Json(resp)).into_response()
 
 
 
1133
  }
1134
 
1135
- async fn download_video(
1136
- Path(job_id): Path<String>,
1137
- State(state): State<AppState>,
1138
- ) -> impl IntoResponse {
1139
- let output_path = PathBuf::from(OUTPUT_DIR).join(format!("{}.mp4", job_id));
1140
  if !output_path.exists() {
1141
- return (StatusCode::NOT_FOUND, Json(serde_json::json!({"detail": "Video not found or not ready"}))).into_response();
1142
  }
1143
- if let Some(job) = state.jobs.lock().get(&job_id) {
 
 
1144
  if job.status != "completed" {
1145
- return (StatusCode::BAD_REQUEST, Json(serde_json::json!({"detail": "Video not ready yet"}))).into_response();
1146
  }
1147
  }
1148
- let file = match tokio::fs::read(&output_path).await {
1149
- Ok(data) => data,
1150
- Err(_) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({"detail": "Failed to read video"}))).into_response(),
1151
- };
1152
- let filename = format!(
1153
- "attachment; filename=\"archnemix-short-{}.mp4\"",
1154
- &job_id[..8.min(job_id.len())]
1155
- );
1156
- (
1157
- StatusCode::OK,
1158
- [
1159
- ("Content-Type", "video/mp4".to_string()),
1160
- ("Content-Disposition", filename),
1161
- ("Cache-Control", "no-cache".to_string()),
1162
- ],
1163
- file,
1164
- ).into_response()
 
 
 
 
 
 
1165
  }
1166
 
1167
- async fn delete_video(
1168
- Path(job_id): Path<String>,
1169
- State(state): State<AppState>,
1170
- headers: HeaderMap,
1171
- ) -> impl IntoResponse {
1172
- if !validate_app_key(&headers) {
1173
- return (StatusCode::FORBIDDEN, Json(serde_json::json!({"detail": "Invalid API key"}))).into_response();
1174
  }
1175
- let output_path = PathBuf::from(OUTPUT_DIR).join(format!("{}.mp4", job_id));
 
1176
  let removed = if output_path.exists() {
1177
  tokio::fs::remove_file(&output_path).await.is_ok()
1178
  } else {
1179
  false
1180
  };
1181
- if let Some(job) = state.jobs.lock().get_mut(&job_id) {
1182
- job.output_path = None;
1183
- job.message = "Video deleted by user".to_string();
 
 
 
1184
  }
1185
- (StatusCode::OK, Json(serde_json::json!({"job_id": job_id, "deleted": removed}))).into_response()
 
 
 
 
1186
  }
1187
 
1188
- async fn debug_dataset(State(_state): State<AppState>) -> impl IntoResponse {
1189
- let client = reqwest::Client::new();
1190
- let url = format!("https://huggingface.co/api/datasets/{}/tree/main", *HF_DATASET);
1191
- let resp = client
1192
- .get(&url)
1193
- .header("Authorization", format!("Bearer {}", *HF_TOKEN))
1194
- .send()
1195
- .await;
1196
- match resp {
1197
- Ok(r) => {
1198
- let files: Vec<serde_json::Value> = r.json().await.unwrap_or_default();
1199
- let mc: Vec<_> = files
1200
- .iter()
1201
- .filter_map(|f| f.get("path").and_then(|p| p.as_str()))
1202
- .filter(|p| p.contains("minecraft") && p.ends_with(".mp4"))
1203
- .collect();
1204
- Json(serde_json::json!({
1205
- "dataset": *HF_DATASET,
1206
- "total_files": files.len(),
1207
- "minecraft": mc,
1208
- })).into_response()
1209
- }
1210
- Err(e) => Json(serde_json::json!({"status": "error", "error": e.to_string()})).into_response(),
1211
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1212
  }
1213
 
1214
  // =============================================================================
1215
- // STARTUP
1216
  // =============================================================================
1217
- #[tokio::main]
1218
- async fn main() {
1219
- tracing_subscriber::fmt::init();
1220
 
1221
- for d in [AUDIO_DIR, OUTPUT_DIR, JOBS_DIR, CLIENT_DIR, HF_CACHE_DIR] {
1222
- tokio::fs::create_dir_all(d).await.unwrap();
 
 
 
 
 
1223
  }
1224
-
1225
- let state = AppState {
 
 
 
 
 
 
 
 
 
1226
  jobs: Arc::new(Mutex::new(HashMap::new())),
1227
- queue: Arc::new(Mutex::new(VecDeque::new())),
1228
- running: Arc::new(Mutex::new(Vec::new())),
1229
  clients: Arc::new(Mutex::new(HashMap::new())),
 
 
1230
  rate_limits: Arc::new(Mutex::new(HashMap::new())),
1231
  video_cache: Arc::new(Mutex::new(HashMap::new())),
1232
- ffmpeg_procs: Arc::new(Mutex::new(HashMap::new())),
1233
- };
1234
-
1235
- if let Ok(entries) = std::fs::read_dir(CLIENT_DIR) {
1236
- for entry in entries.flatten() {
1237
- if let Ok(data) = std::fs::read_to_string(entry.path()) {
1238
- if let Ok(rec) = serde_json::from_str::<ClientRecord>(&data) {
1239
- state.clients.lock().insert(rec.token.clone(), rec);
1240
- }
1241
- }
1242
- }
1243
- }
1244
-
1245
- let worker_state = state.clone();
1246
- tokio::spawn(async move { queue_worker(worker_state).await });
1247
-
1248
  let state_clone = state.clone();
1249
- tokio::spawn(async move { list_videos_from_dataset("minecraft", &state_clone).await });
1250
-
1251
- let app = Router::new()
1252
- .route("/", get(root))
1253
- .route("/register", get(register))
1254
- .route("/health", get(health))
1255
- .route("/queue", get(queue_status))
1256
- .route("/videos/:category", get(list_videos))
1257
- .route("/generate", post(generate))
1258
- .route("/job/:job_id", get(job_status))
1259
- .route("/job/:job_id", delete(|
1260
- State(state): State<AppState>,
1261
- Path(job_id): Path<String>
1262
- | async move {
1263
- let job = state.jobs.lock().get(&job_id).cloned();
1264
- let job = match job {
1265
- Some(j) => j,
1266
- None => return (StatusCode::OK, Json(serde_json::json!({
1267
- "job_id": job_id,
1268
- "cancelled": false,
1269
- "reason": "not found"
1270
- }))).into_response(),
1271
- };
1272
- if job.status == "completed" || job.status == "failed" {
1273
- return (StatusCode::OK, Json(serde_json::json!({
1274
- "job_id": job_id,
1275
- "cancelled": false,
1276
- "reason": job.status
1277
- }))).into_response();
1278
- }
1279
- // Extract child BEFORE awaiting to avoid holding lock across await
1280
- let child = state.ffmpeg_procs.lock().remove(&job_id);
1281
- if let Some(mut child) = child {
1282
- let _ = child.kill().await;
1283
- }
1284
- state.queue.lock().retain(|jid| jid != &job_id);
1285
- state.running.lock().retain(|jid| jid != &job_id);
1286
- update_job(&job_id, &state, |j| {
1287
- j.status = "failed".to_string();
1288
- j.error = Some("Cancelled by controller \u{2014} client disconnected".to_string());
1289
- });
1290
- refresh_queue_positions(&state);
1291
- info!("Job {} cancelled", &job_id[..8.min(job_id.len())]);
1292
- (StatusCode::OK, Json(serde_json::json!({
1293
- "job_id": job_id,
1294
- "cancelled": true
1295
- }))).into_response()
1296
- }))
1297
- .route("/download/:job_id", get(download_video))
1298
- .route("/video/:job_id", delete(delete_video))
1299
- .route("/debug/dataset", get(debug_dataset))
1300
- .layer(DefaultBodyLimit::max(20 * 1024 * 1024))
1301
- .with_state(state);
1302
-
1303
- let listener = tokio::net::TcpListener::bind("0.0.0.0:7860").await.unwrap();
1304
- info!("Server listening on http://0.0.0.0:7860");
1305
- axum::serve(listener, app).await.unwrap();
1306
  }
 
1
+ /**
2
+ * ArchNemix Shorts Generator API - Rust v5.1.0
3
+ * ════════════════════════════════════════════════════════════════════════════
4
+ * Exact mirror of Python/Node.js/Go FFmpeg backends
5
+ * Uses native FFmpeg CLI tool via tokio::process
6
+ * Endpoints, request/response formats, and video cleanup match all versions
7
+ */
8
+
9
+ use actix_cors::Cors;
10
+ use actix_files::NamedFile;
11
+ use actix_web::{
12
+ delete, get, post, web, App, Error, HttpRequest, HttpResponse, HttpServer, Responder,
13
  };
14
+ use base64::{engine::general_purpose, Engine as _};
15
+ use chrono::{DateTime, Duration, Utc};
 
16
  use serde::{Deserialize, Serialize};
17
  use sha2::{Digest, Sha256};
18
  use std::collections::{HashMap, VecDeque};
19
+ use std::env;
20
+ use std::fs;
21
+ use std::path::{Path, PathBuf};
22
+ use std::process::Stdio;
23
+ use std::sync::{Arc, Mutex};
24
  use tokio::io::{AsyncBufReadExt, BufReader};
25
+ use tokio::process::Command;
26
+ use tokio::time::{sleep, timeout, Duration as TokioDuration};
27
  use uuid::Uuid;
28
 
29
  // =============================================================================
30
+ // CONFIGURATION
31
  // =============================================================================
32
+
33
  lazy_static::lazy_static! {
34
+ static ref HF_DATASET: String = env::var("HF_DATASET")
35
  .unwrap_or_else(|_| "YTShortMakerArchx/BG_VIDS_ARCHX_YT".to_string());
36
+ static ref HF_TOKEN: String = env::var("HF_TOKEN").unwrap_or_default();
37
+ static ref APP_KEY: String = env::var("APP_KEY")
38
  .unwrap_or_else(|_| "archx_3f9d15f52n48d41h5fj8a7e2b_private".to_string());
39
+ static ref UI_ORIGIN: String = env::var("UI_ORIGIN")
40
  .unwrap_or_else(|_| "https://shortgen-archx.pages.dev".to_string());
41
  }
42
 
43
+ const BASE_DIR: &str = "/tmp";
44
  const AUDIO_DIR: &str = "/tmp/audio";
45
  const OUTPUT_DIR: &str = "/tmp/out";
46
  const JOBS_DIR: &str = "/tmp/jobs";
 
49
 
50
  const GENERATE_LIMIT: usize = 3;
51
  const STATUS_LIMIT: usize = 1000;
52
+ const JOB_TIMEOUT: i64 = 900; // 15 min
53
+
54
  const MAX_CONCURRENT: usize = 1;
55
+ const AVG_JOB_DURATION_S: i64 = 360; // 6 minutes
56
 
57
  // =============================================================================
58
+ // DATA STRUCTURES
59
  // =============================================================================
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
 
61
  #[derive(Debug, Clone, Serialize, Deserialize)]
62
  struct Job {
 
66
  queue_position: Option<usize>,
67
  progress: u8,
68
  message: String,
 
69
  created_at: DateTime<Utc>,
 
70
  updated_at: DateTime<Utc>,
71
  error: Option<String>,
72
  output_path: Option<String>,
 
74
  subs_path: Option<String>,
75
  background: Option<String>,
76
  requested_duration: Option<f64>,
 
77
  ffmpeg_frame: u64,
78
  ffmpeg_fps: f64,
79
  ffmpeg_out_time: f64,
80
  ffmpeg_speed: f64,
81
+ total_duration: f64,
82
+ }
83
+
84
+ #[derive(Debug, Clone, Serialize, Deserialize)]
85
+ struct ClientRecord {
86
+ token: String,
87
+ fingerprint: String,
88
+ created_at: DateTime<Utc>,
89
+ last_seen: DateTime<Utc>,
90
+ job_count: u64,
91
+ jobs: Vec<String>,
92
  }
93
 
94
  #[derive(Debug, Deserialize)]
 
99
  duration: Option<f64>,
100
  }
101
 
102
+ #[derive(Debug, Serialize)]
103
+ struct QueueEta {
104
+ queue_position: usize,
105
+ jobs_ahead: usize,
106
+ wait_low_s: i64,
107
+ wait_high_s: i64,
108
+ wait_low_human: String,
109
+ wait_high_human: String,
110
+ total_with_own_s: i64,
111
+ message: String,
112
  }
113
 
114
+ type Jobs = Arc<Mutex<HashMap<String, Job>>>;
115
+ type Clients = Arc<Mutex<HashMap<String, ClientRecord>>>;
116
+ type JobQueue = Arc<Mutex<VecDeque<String>>>;
117
+ type RunningJobs = Arc<Mutex<Vec<String>>>;
118
+ type RateLimits = Arc<Mutex<HashMap<String, Vec<i64>>>>;
119
+ type VideoCache = Arc<Mutex<HashMap<String, (i64, Vec<String>)>>>;
120
+
121
  struct AppState {
122
+ jobs: Jobs,
123
+ clients: Clients,
124
+ job_queue: JobQueue,
125
+ running_jobs: RunningJobs,
126
+ rate_limits: RateLimits,
127
  video_cache: VideoCache,
 
128
  }
129
 
130
  // =============================================================================
131
+ // HELPERS
132
  // =============================================================================
 
 
 
133
 
134
+ fn format_duration(seconds: i64) -> String {
135
+ if seconds < 60 {
136
+ format!("{}s", seconds)
137
+ } else {
138
+ let m = seconds / 60;
139
+ let s = seconds % 60;
140
+ if s > 0 {
141
+ format!("{}m {:02}s", m, s)
142
+ } else {
143
+ format!("{}m", m)
 
144
  }
145
  }
 
146
  }
147
 
148
+ fn queue_eta(position: usize, job_duration: Option<f64>, running_jobs: &[String], jobs: &HashMap<String, Job>) -> QueueEta {
149
+ let mut running_remaining = AVG_JOB_DURATION_S;
150
+
151
+ for jid in running_jobs {
152
+ if let Some(j) = jobs.get(jid) {
153
+ let total = if j.total_duration > 0.0 { j.total_duration as i64 } else { AVG_JOB_DURATION_S };
154
+ let out = j.ffmpeg_out_time as i64;
155
+ let remaining = (total - out).max(0);
156
+ running_remaining = running_remaining.min(remaining);
157
+ }
158
+ }
159
+
160
+ let queued_ahead = (position as i64 - 1).max(0);
161
+ let total_wait_s = running_remaining + queued_ahead * AVG_JOB_DURATION_S;
162
+ let own_duration = job_duration.map(|d| d as i64).unwrap_or(AVG_JOB_DURATION_S);
163
+ let total_s = total_wait_s + own_duration;
164
+
165
+ let low_s = (total_wait_s as f64 * 0.75) as i64;
166
+ let high_s = (total_wait_s as f64 * 1.2) as i64;
167
+
168
+ QueueEta {
169
+ queue_position: position,
170
+ jobs_ahead: position,
171
+ wait_low_s: low_s,
172
+ wait_high_s: high_s,
173
+ wait_low_human: format_duration(low_s),
174
+ wait_high_human: format_duration(high_s),
175
+ total_with_own_s: total_s,
176
+ message: format!(
177
+ "Position {} in queue — roughly {}–{} wait, likely less",
178
+ position,
179
+ format_duration(low_s),
180
+ format_duration(high_s)
181
+ ),
182
+ }
183
  }
184
 
185
+ fn fingerprint(req: &HttpRequest) -> String {
186
+ let conn_info = req.connection_info();
187
+ let ip = conn_info.peer_addr().unwrap_or("unknown");
188
+ let ua = req.headers().get("user-agent").and_then(|h| h.to_str().ok()).unwrap_or("");
189
+ let accept = req.headers().get("accept").and_then(|h| h.to_str().ok()).unwrap_or("");
190
+
 
 
191
  let mut hasher = Sha256::new();
192
+ hasher.update(format!("{}:{}:{}", ip, ua, accept));
193
+ hex::encode(hasher.finalize())
194
  }
195
 
196
+ fn validate_app_key(req: &HttpRequest) -> bool {
197
+ if APP_KEY.is_empty() || *APP_KEY == "archnemix-secret-key-change-in-production" {
198
+ return true;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
199
  }
200
+
201
+ let key = req
202
+ .headers()
203
+ .get("X-APP-KEY")
204
+ .or_else(|| req.headers().get("Authorization"))
205
+ .and_then(|h| h.to_str().ok())
206
+ .unwrap_or("")
207
+ .replace("Bearer ", "");
208
+
209
+ key == *APP_KEY
210
  }
211
 
212
+ fn rate_limit(key: &str, limit: usize, window: i64, rate_limits: &mut HashMap<String, Vec<i64>>) -> bool {
213
+ let now = Utc::now().timestamp();
214
+ let timestamps = rate_limits.entry(key.to_string()).or_insert_with(Vec::new);
215
+ timestamps.retain(|&t| now - t < window);
216
+
217
+ if timestamps.len() >= limit {
 
 
 
218
  return false;
219
  }
220
+ timestamps.push(now);
221
  true
222
  }
223
 
224
+ async fn save_base64_audio(data: &str, path: &Path) -> Result<usize, String> {
225
+ let data = if data.starts_with("data:audio/") {
226
+ data.split(',').nth(1).ok_or("Invalid base64 format")?
227
+ } else {
228
+ data
229
+ };
230
+
231
+ let audio_bytes = general_purpose::STANDARD
232
+ .decode(data)
233
+ .map_err(|e| format!("Base64 decode error: {}", e))?;
234
+
235
+ if audio_bytes.len() > 15 * 1024 * 1024 {
236
+ return Err("Audio too large (max 15 MB)".to_string());
237
  }
238
+
239
+ tokio::fs::write(path, &audio_bytes)
240
+ .await
241
+ .map_err(|e| format!("File write error: {}", e))?;
242
+
243
+ Ok(audio_bytes.len())
244
+ }
245
+
246
+ async fn save_subtitles(ass: &str, path: &Path) -> Result<(), String> {
247
+ if !ass.contains("[Script Info]") || !ass.contains("[Events]") {
248
+ return Err("Invalid ASS subtitle format".to_string());
249
  }
250
+
251
+ if ass.len() > 500 * 1024 {
252
+ return Err("Subtitles too large (max 500 KB)".to_string());
 
253
  }
254
+
255
+ tokio::fs::write(path, ass)
256
+ .await
257
+ .map_err(|e| format!("File write error: {}", e))?;
258
+
259
+ Ok(())
260
  }
261
 
262
+ async fn get_media_duration(path: &Path) -> f64 {
263
+ let output = Command::new("ffprobe")
264
+ .args(&[
265
+ "-v", "error",
266
+ "-show_entries", "format=duration",
267
+ "-of", "default=noprint_wrappers=1:nokey=1",
268
+ path.to_str().unwrap(),
269
+ ])
270
+ .output()
271
+ .await;
272
+
273
+ if let Ok(output) = output {
274
+ if let Ok(s) = String::from_utf8(output.stdout) {
275
+ if let Ok(dur) = s.trim().parse::<f64>() {
276
+ return dur;
277
+ }
278
+ }
279
  }
280
+
281
+ // Fallback estimate
282
+ if let Ok(metadata) = tokio::fs::metadata(path).await {
283
+ return (metadata.len() as f64 / 16000.0).clamp(1.0, 180.0);
284
+ }
285
+
286
+ 30.0
 
 
287
  }
288
 
289
  // =============================================================================
290
+ // HUGGINGFACE DATASET
291
  // =============================================================================
292
+
293
+ async fn list_videos_from_dataset(category: &str, cache: &Arc<Mutex<HashMap<String, (i64, Vec<String>)>>>) -> Vec<String> {
294
  let cache_key = format!("videos_{}", category);
295
+
296
+ // Check cache
297
  {
298
+ let cache_lock = cache.lock().unwrap();
299
+ if let Some((ts, data)) = cache_lock.get(&cache_key) {
300
+ if Utc::now().timestamp() - ts < 300 {
301
+ return data.clone();
302
  }
303
  }
304
  }
305
+
306
+ // Fetch from HF
307
+ let url = format!("https://huggingface.co/api/datasets/{}/tree/main/{}", *HF_DATASET, category);
308
  let client = reqwest::Client::new();
309
+ let mut req = client.get(&url);
310
+
311
+ if !HF_TOKEN.is_empty() {
312
+ req = req.header("Authorization", format!("Bearer {}", *HF_TOKEN));
313
+ }
314
+
315
+ if let Ok(resp) = req.send().await {
 
 
 
 
 
316
  if let Ok(files) = resp.json::<Vec<serde_json::Value>>().await {
317
+ let result: Vec<String> = files
318
+ .iter()
319
+ .filter(|f| f["type"] == "file" && f["path"].as_str().unwrap_or("").ends_with(".mp4"))
320
+ .filter_map(|f| {
321
+ let path = f["path"].as_str()?;
322
+ Path::new(path).file_stem()?.to_str().map(String::from)
323
+ })
324
+ .collect();
325
+
326
+ if !result.is_empty() {
327
+ cache.lock().unwrap().insert(cache_key, (Utc::now().timestamp(), result.clone()));
328
+ return result;
329
  }
330
  }
331
  }
332
+
333
+ // Fallback
334
+ (1..=6).map(|i| format!("mc{}", i)).collect()
 
 
335
  }
336
 
337
+ async fn download_video_from_dataset(video_name: &str, category: &str) -> Result<PathBuf, String> {
338
+ let video_name = video_name.trim_end_matches(".mp4");
339
+ let paths = vec![
 
 
 
 
 
 
340
  format!("{}/{}.mp4", category, video_name),
341
  format!("{}.mp4", video_name),
342
+ ];
343
+
344
+ for path in paths {
345
+ let url = format!("https://huggingface.co/datasets/{}/resolve/main/{}", *HF_DATASET, path);
346
+ let local_path = PathBuf::from(HF_CACHE_DIR).join(format!("{}.mp4", video_name));
347
+
348
+ // Check cache
349
+ if local_path.exists() {
350
+ return Ok(local_path);
351
+ }
352
+
353
+ // Download
354
+ let client = reqwest::Client::new();
355
+ let mut req = client.get(&url);
356
+
357
+ if !HF_TOKEN.is_empty() {
358
+ req = req.header("Authorization", format!("Bearer {}", *HF_TOKEN));
359
+ }
360
+
361
+ if let Ok(resp) = req.send().await {
362
  if resp.status().is_success() {
363
+ if let Ok(bytes) = resp.bytes().await {
364
+ if tokio::fs::write(&local_path, bytes).await.is_ok() {
365
+ return Ok(local_path);
366
+ }
367
+ }
368
  }
369
  }
370
  }
371
+
372
+ Err(format!("Video '{}' not found in dataset", video_name))
373
  }
374
 
375
  // =============================================================================
376
+ // CLIENT MANAGEMENT
377
  // =============================================================================
378
+
379
+ fn load_client(token: &str, clients: &Clients) -> Option<ClientRecord> {
380
+ clients.lock().unwrap().get(token).cloned()
 
 
 
 
 
 
 
 
 
 
381
  }
382
 
383
+ fn save_client(record: &ClientRecord, clients: &Clients) {
384
+ clients.lock().unwrap().insert(record.token.clone(), record.clone());
385
+
386
+ let path = PathBuf::from(CLIENT_DIR).join(format!("{}.json", &record.token[..8]));
387
+ if let Ok(json) = serde_json::to_string(&record) {
388
+ let _ = std::fs::write(path, json);
389
  }
 
 
390
  }
391
 
392
+ fn resolve_client(req: &HttpRequest, clients: &Clients) -> ClientRecord {
393
+ let token = req
394
+ .headers()
395
+ .get("X-Client-ID")
396
+ .and_then(|h| h.to_str().ok())
397
+ .unwrap_or("")
398
+ .trim();
399
+
400
+ if !token.is_empty() {
401
+ if let Some(mut rec) = load_client(token, clients) {
402
+ rec.last_seen = Utc::now();
403
+ save_client(&rec, clients);
404
+ return rec;
 
405
  }
406
+
407
+ let rec = ClientRecord {
408
+ token: token.to_string(),
409
+ fingerprint: fingerprint(req),
410
+ created_at: Utc::now(),
411
+ last_seen: Utc::now(),
412
+ job_count: 0,
413
+ jobs: vec![],
414
+ };
415
+ save_client(&rec, clients);
416
+ return rec;
417
  }
418
+
419
+ let fp = fingerprint(req);
420
+ {
421
+ let clients_lock = clients.lock().unwrap();
422
+ for rec in clients_lock.values() {
423
+ if rec.fingerprint == fp {
424
+ let mut rec = rec.clone();
425
+ rec.last_seen = Utc::now();
426
+ drop(clients_lock);
427
+ save_client(&rec, clients);
428
+ return rec;
429
+ }
430
+ }
431
  }
432
+
433
+ let rec = ClientRecord {
434
+ token: Uuid::new_v4().to_string().replace("-", ""),
435
+ fingerprint: fp,
436
+ created_at: Utc::now(),
437
+ last_seen: Utc::now(),
438
+ job_count: 0,
439
+ jobs: vec![],
440
+ };
441
+ save_client(&rec, clients);
442
+ rec
443
  }
444
 
445
  // =============================================================================
446
  // JOB MANAGEMENT
447
  // =============================================================================
448
+
449
+ fn create_job(job_id: String, client_token: String, jobs: &Jobs) -> Job {
450
+ let job = Job {
451
+ id: job_id.clone(),
452
+ client_token,
453
  status: "queued".to_string(),
454
  queue_position: None,
455
  progress: 0,
456
+ message: "Waiting in queue...".to_string(),
457
+ created_at: Utc::now(),
458
+ updated_at: Utc::now(),
459
  error: None,
460
  output_path: None,
461
  audio_path: None,
462
  subs_path: None,
463
  background: None,
464
  requested_duration: None,
 
465
  ffmpeg_frame: 0,
466
  ffmpeg_fps: 0.0,
467
  ffmpeg_out_time: 0.0,
468
  ffmpeg_speed: 0.0,
469
+ total_duration: 0.0,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
470
  };
471
+
472
+ jobs.lock().unwrap().insert(job_id.clone(), job.clone());
473
+ persist_job(&job_id, jobs);
474
+ job
 
 
475
  }
476
 
477
+ fn update_job(job_id: &str, updates: HashMap<&str, serde_json::Value>, jobs: &Jobs) {
478
+ let mut jobs_lock = jobs.lock().unwrap();
479
+ if let Some(job) = jobs_lock.get_mut(job_id) {
480
+ for (key, value) in updates {
481
+ match key {
482
+ "status" => job.status = value.as_str().unwrap_or("").to_string(),
483
+ "progress" => job.progress = value.as_u64().unwrap_or(0) as u8,
484
+ "message" => job.message = value.as_str().unwrap_or("").to_string(),
485
+ "error" => job.error = value.as_str().map(String::from),
486
+ "output_path" => job.output_path = value.as_str().map(String::from),
487
+ "audio_path" => job.audio_path = value.as_str().map(String::from),
488
+ "subs_path" => job.subs_path = value.as_str().map(String::from),
489
+ "background" => job.background = value.as_str().map(String::from),
490
+ "requested_duration" => job.requested_duration = value.as_f64(),
491
+ "queue_position" => job.queue_position = value.as_u64().map(|v| v as usize),
492
+ "ffmpeg_frame" => job.ffmpeg_frame = value.as_u64().unwrap_or(0),
493
+ "ffmpeg_fps" => job.ffmpeg_fps = value.as_f64().unwrap_or(0.0),
494
+ "ffmpeg_out_time" => job.ffmpeg_out_time = value.as_f64().unwrap_or(0.0),
495
+ "ffmpeg_speed" => job.ffmpeg_speed = value.as_f64().unwrap_or(0.0),
496
+ "total_duration" => job.total_duration = value.as_f64().unwrap_or(0.0),
497
+ _ => {}
498
  }
499
  }
500
+ job.updated_at = Utc::now();
501
  }
502
+ drop(jobs_lock);
503
+ persist_job(job_id, jobs);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
504
  }
505
 
506
+ fn persist_job(job_id: &str, jobs: &Jobs) {
507
+ if let Some(job) = jobs.lock().unwrap().get(job_id) {
508
+ let path = PathBuf::from(JOBS_DIR).join(format!("{}.json", job_id));
509
+ if let Ok(json) = serde_json::to_string(&job) {
510
+ let _ = std::fs::write(path, json);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
511
  }
512
  }
513
  }
514
 
515
  // =============================================================================
516
+ // VIDEO PROCESSING
517
  // =============================================================================
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
518
 
519
+ async fn process_video_task(
520
+ job_id: String,
521
+ audio_path: PathBuf,
522
+ subs_path: PathBuf,
523
+ background: String,
524
+ duration: Option<f64>,
525
+ state: web::Data<AppState>,
526
+ ) {
527
+ log::info!("Job {}: starting encode", &job_id[..8]);
528
+
529
+ let mut updates = HashMap::new();
530
+ updates.insert("status", serde_json::json!("processing"));
531
+ updates.insert("progress", serde_json::json!(10));
532
+ updates.insert("message", serde_json::json!("Downloading background video..."));
533
+ updates.insert("queue_position", serde_json::json!(null));
534
+ update_job(&job_id, updates, &state.jobs);
535
+
536
+ // Download background
537
  let bg_path = match download_video_from_dataset(&background, "minecraft").await {
538
  Ok(p) => p,
539
  Err(e) => {
540
+ let mut updates = HashMap::new();
541
+ updates.insert("status", serde_json::json!("failed"));
542
+ updates.insert("error", serde_json::json!(e));
543
+ update_job(&job_id, updates, &state.jobs);
 
 
544
  return;
545
  }
546
  };
547
+
548
+ let mut updates = HashMap::new();
549
+ updates.insert("progress", serde_json::json!(20));
550
+ updates.insert("message", serde_json::json!("Analysing media..."));
551
+ update_job(&job_id, updates, &state.jobs);
552
+
553
+ let audio_dur = if let Some(d) = duration {
554
+ d
555
+ } else {
556
+ get_media_duration(&audio_path).await
557
+ };
558
+
559
+ let video_dur = get_media_duration(&bg_path).await;
560
+
561
+ if audio_dur < 1.0 || audio_dur > 180.0 {
562
+ let mut updates = HashMap::new();
563
+ updates.insert("status", serde_json::json!("failed"));
564
+ updates.insert("error", serde_json::json!("Audio duration out of range (1-180 s)"));
565
+ update_job(&job_id, updates, &state.jobs);
566
  return;
567
  }
568
+
569
+ log::info!("Job {}: audio={:.2}s bg={:.2}s", &job_id[..8], audio_dur, video_dur);
570
+
571
+ // Build FFmpeg command
572
+ let mut bg_args = Vec::new();
573
+ if video_dur > audio_dur {
574
  let max_start = video_dur - audio_dur;
575
+ let start: f64 = rand::random::<f64>() * max_start;
576
+ bg_args.extend_from_slice(&[
577
+ "-ss", &format!("{:.3}", start),
578
+ "-t", &format!("{:.3}", audio_dur),
579
+ "-i", bg_path.to_str().unwrap(),
580
+ ]);
581
  } else {
582
+ let loop_n = ((audio_dur / video_dur) as i32) + 2;
583
+ bg_args.extend_from_slice(&[
584
+ "-stream_loop", &loop_n.to_string(),
585
+ "-i", bg_path.to_str().unwrap(),
586
+ ]);
587
+ }
588
+
589
+ let subs_str = subs_path.to_str().unwrap().replace("\\", "/").replace(":", "\\:");
590
  let vf = format!(
591
  "[0:v]ass='{}',scale=1080:1920:force_original_aspect_ratio=increase,crop=1080:1920,setsar=1[v]",
592
+ subs_str
593
  );
594
+
595
  let output_path = PathBuf::from(OUTPUT_DIR).join(format!("{}.mp4", job_id));
596
+
597
+ let mut cmd_args = vec![
598
+ "-y",
599
+ "-hide_banner",
600
+ "-loglevel", "error",
601
  ];
602
+ cmd_args.extend(bg_args.iter().map(|s| s.as_str()));
603
+ cmd_args.extend_from_slice(&[
604
+ "-i", audio_path.to_str().unwrap(),
605
+ "-filter_complex", &vf,
606
+ "-map", "[v]",
607
+ "-map", "1:a",
608
+ "-c:v", "libx264",
609
+ "-preset", "medium",
610
+ "-crf", "16",
611
+ "-minrate", "8M",
612
+ "-maxrate", "16M",
613
+ "-bufsize", "16M",
614
+ "-profile:v", "high",
615
+ "-level:v", "4.2",
616
+ "-pix_fmt", "yuv420p",
617
+ "-c:a", "aac",
618
+ "-b:a", "192k",
619
+ "-shortest",
620
+ "-movflags", "+faststart",
621
+ "-threads", "0",
622
+ "-progress", "pipe:2",
623
+ "-t", &format!("{:.3}", audio_dur),
624
+ output_path.to_str().unwrap(),
625
  ]);
626
+
627
+ let mut updates = HashMap::new();
628
+ updates.insert("progress", serde_json::json!(40));
629
+ updates.insert("message", serde_json::json!("Encoding... (single-pass)"));
630
+ updates.insert("total_duration", serde_json::json!(audio_dur));
631
+ update_job(&job_id, updates, &state.jobs);
632
+
633
+ // Run FFmpeg
634
+ let mut child = match Command::new("ffmpeg")
635
  .args(&cmd_args)
636
+ .stderr(Stdio::piped())
 
637
  .spawn()
638
  {
639
+ Ok(c) => c,
640
  Err(e) => {
641
+ let mut updates = HashMap::new();
642
+ updates.insert("status", serde_json::json!("failed"));
643
+ updates.insert("error", serde_json::json!(format!("FFmpeg spawn failed: {}", e)));
644
+ update_job(&job_id, updates, &state.jobs);
 
 
645
  return;
646
  }
647
  };
648
+
649
+ let stderr = child.stderr.take().unwrap();
650
+ let reader = BufReader::new(stderr);
651
+ let mut lines = reader.lines();
652
+
653
+ let job_id_clone = job_id.clone();
654
+ let state_clone = state.clone();
655
+
656
+ tokio::spawn(async move {
657
+ let mut last_update = std::time::Instant::now();
658
+
659
+ while let Ok(Some(line)) = lines.next_line().await {
660
+ if line.is_empty() {
661
+ continue;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
662
  }
663
+
664
+ let parts: Vec<&str> = line.split('=').collect();
665
+ if parts.len() != 2 {
666
+ continue;
 
 
 
667
  }
668
+
669
+ let key = parts[0].trim();
670
+ let val = parts[1].trim();
671
+
672
+ match key {
673
+ "frame" => {
674
+ if let Ok(frame) = val.parse::<u64>() {
675
+ let mut updates = HashMap::new();
676
+ updates.insert("ffmpeg_frame", serde_json::json!(frame));
677
+ update_job(&job_id_clone, updates, &state_clone.jobs);
678
+ }
679
+ }
680
+ "fps" => {
681
+ if let Ok(fps) = val.parse::<f64>() {
682
+ let mut updates = HashMap::new();
683
+ updates.insert("ffmpeg_fps", serde_json::json!(fps));
684
+ update_job(&job_id_clone, updates, &state_clone.jobs);
685
+ }
686
+ }
687
+ "out_time_ms" => {
688
+ if let Ok(ms) = val.parse::<u64>() {
689
+ let out_time_s = ms as f64 / 1_000_000.0;
690
+ let mut updates = HashMap::new();
691
+ updates.insert("ffmpeg_out_time", serde_json::json!(out_time_s));
692
+ update_job(&job_id_clone, updates, &state_clone.jobs);
693
+ }
694
+ }
695
+ "speed" => {
696
+ let speed = val.replace("x", "").parse::<f64>().unwrap_or(0.0);
697
+ let mut updates = HashMap::new();
698
+ updates.insert("ffmpeg_speed", serde_json::json!(speed));
699
+ update_job(&job_id_clone, updates, &state_clone.jobs);
700
+ }
701
+ "progress" => {
702
+ let now = std::time::Instant::now();
703
+ if val == "end" || now.duration_since(last_update).as_millis() >= 500 {
704
+ last_update = now;
705
+
706
+ let jobs_lock = state_clone.jobs.lock().unwrap();
707
+ if let Some(job) = jobs_lock.get(&job_id_clone) {
708
+ let ratio = if job.total_duration > 0.0 {
709
+ (job.ffmpeg_out_time / job.total_duration).min(1.0)
710
+ } else {
711
+ 0.0
712
+ };
713
+ let mapped = (40.0 + ratio * 55.0) as u8;
714
+
715
+ let message = if job.total_duration > 0.0 && job.ffmpeg_speed > 0.0 {
716
  format!(
717
+ "Encoding {:.1}s / {:.1}s ({:.1}x speed)",
718
+ job.ffmpeg_out_time, job.total_duration, job.ffmpeg_speed
719
  )
720
  } else {
721
+ "Encoding...".to_string()
722
  };
723
+
724
+ drop(jobs_lock);
725
+
726
+ let mut updates = HashMap::new();
727
+ updates.insert("progress", serde_json::json!(mapped));
728
+ updates.insert("message", serde_json::json!(message));
729
+ update_job(&job_id_clone, updates, &state_clone.jobs);
 
 
730
  }
731
+ }
732
+
733
+ if val == "end" {
734
+ break;
735
  }
736
  }
737
+ _ => {}
738
  }
 
 
 
739
  }
740
+ });
741
+
742
+ let timeout_dur = TokioDuration::from_secs(((audio_dur * 5.0) as u64 + 480).max(480));
743
+ match timeout(timeout_dur, child.wait()).await {
744
+ Ok(Ok(status)) => {
745
+ if !status.success() {
746
+ let mut updates = HashMap::new();
747
+ updates.insert("status", serde_json::json!("failed"));
748
+ updates.insert("error", serde_json::json!(format!("FFmpeg exited with code {:?}", status.code())));
749
+ update_job(&job_id, updates, &state.jobs);
750
+ return;
751
+ }
752
+ }
753
+ Ok(Err(e)) => {
754
+ let mut updates = HashMap::new();
755
+ updates.insert("status", serde_json::json!("failed"));
756
+ updates.insert("error", serde_json::json!(format!("FFmpeg wait error: {}", e)));
757
+ update_job(&job_id, updates, &state.jobs);
758
  return;
759
  }
760
+ Err(_) => {
761
+ let _ = child.kill().await;
762
+ let mut updates = HashMap::new();
763
+ updates.insert("status", serde_json::json!("failed"));
764
+ updates.insert("error", serde_json::json!("Encoding timed out — try a shorter script"));
765
+ update_job(&job_id, updates, &state.jobs);
 
766
  return;
767
  }
768
  }
769
+
770
+ if !output_path.exists() || output_path.metadata().map(|m| m.len()).unwrap_or(0) == 0 {
771
+ let mut updates = HashMap::new();
772
+ updates.insert("status", serde_json::json!("failed"));
773
+ updates.insert("error", serde_json::json!("Output file missing after encode"));
774
+ update_job(&job_id, updates, &state.jobs);
 
 
 
 
775
  return;
776
  }
777
+
778
+ let size_mb = output_path.metadata().unwrap().len() as f64 / 1024.0 / 1024.0;
779
+ log::info!("Job {}: done {:.2} MB", &job_id[..8], size_mb);
780
+
781
+ // Cleanup input files
782
+ let _ = tokio::fs::remove_file(audio_path).await;
783
+ let _ = tokio::fs::remove_file(subs_path).await;
784
+
785
+ let mut updates = HashMap::new();
786
+ updates.insert("status", serde_json::json!("completed"));
787
+ updates.insert("progress", serde_json::json!(100));
788
+ updates.insert("message", serde_json::json!(format!("Done! {:.1} MB", size_mb)));
789
+ updates.insert("output_path", serde_json::json!(output_path.to_str().unwrap()));
790
+ update_job(&job_id, updates, &state.jobs);
791
+ }
792
 
793
+ // =============================================================================
794
+ // QUEUE WORKER
795
+ // =============================================================================
 
 
 
796
 
797
+ async fn queue_worker(state: web::Data<AppState>) {
798
+ loop {
799
+ sleep(TokioDuration::from_secs(2)).await;
800
+
801
+ let running_count = state.running_jobs.lock().unwrap().len();
802
+ if running_count >= MAX_CONCURRENT {
803
+ continue;
804
+ }
805
+
806
+ let job_id = {
807
+ let mut queue = state.job_queue.lock().unwrap();
808
+ if queue.is_empty() {
809
+ continue;
810
+ }
811
+ queue.pop_front()
812
+ };
813
+
814
+ if let Some(job_id) = job_id {
815
+ let job = state.jobs.lock().unwrap().get(&job_id).cloned();
816
+
817
+ if let Some(job) = job {
818
+ if job.status == "failed" || job.status == "completed" {
819
+ continue;
820
+ }
821
+
822
+ state.running_jobs.lock().unwrap().push(job_id.clone());
823
+
824
+ let audio_path = PathBuf::from(job.audio_path.clone().unwrap_or_default());
825
+ let subs_path = PathBuf::from(job.subs_path.clone().unwrap_or_default());
826
+ let background = job.background.clone().unwrap_or_else(|| "mc1".to_string());
827
+ let duration = job.requested_duration;
828
+
829
+ let state_clone = state.clone();
830
+ let job_id_clone = job_id.clone();
831
+
832
+ tokio::spawn(async move {
833
+ process_video_task(job_id_clone.clone(), audio_path, subs_path, background, duration, state_clone.clone()).await;
834
+ state_clone.running_jobs.lock().unwrap().retain(|id| id != &job_id_clone);
835
+ });
836
+ }
837
+ }
838
+ }
839
+ }
840
 
841
+ // =============================================================================
842
+ // VIDEO CLEANUP (1-hour TTL)
843
+ // =============================================================================
 
 
 
 
 
 
844
 
845
+ async fn cleanup_old_videos() {
846
+ loop {
847
+ sleep(TokioDuration::from_secs(600)).await; // 10 minutes
848
+
849
+ let cutoff_time = Utc::now() - Duration::seconds(3600); // 1 hour ago
850
+ let mut cleaned_count = 0;
851
+ let mut cleaned_size_mb = 0.0;
852
+
853
+ if let Ok(entries) = std::fs::read_dir(OUTPUT_DIR) {
854
+ for entry in entries.flatten() {
855
+ if let Ok(path) = entry.path().canonicalize() {
856
+ if path.extension().and_then(|s| s.to_str()) != Some("mp4") {
857
+ continue;
858
+ }
859
+
860
+ if let Ok(metadata) = entry.metadata() {
861
+ if let Ok(modified) = metadata.modified() {
862
+ let modified_dt: DateTime<Utc> = modified.into();
863
+ if modified_dt < cutoff_time {
864
+ let size_mb = metadata.len() as f64 / 1024.0 / 1024.0;
865
+ if std::fs::remove_file(&path).is_ok() {
866
+ cleaned_count += 1;
867
+ cleaned_size_mb += size_mb;
868
+ log::info!("Cleaned up {} ({:.1}MB)", path.file_name().unwrap().to_string_lossy(), size_mb);
869
+ }
870
+ }
871
+ }
872
+ }
873
+ }
874
+ }
875
+ }
876
+
877
+ if cleaned_count > 0 {
878
+ log::info!("Cleaned {} videos, freed {:.1}MB", cleaned_count, cleaned_size_mb);
879
+ }
880
+ }
881
  }
882
 
883
  // =============================================================================
884
  // ENDPOINTS
885
  // =============================================================================
886
 
887
+ #[get("/")]
888
+ async fn root() -> impl Responder {
889
+ HttpResponse::Ok().json(serde_json::json!({
890
  "name": "ArchNemix Shorts Generator API",
891
+ "version": "5.1.0",
892
+ "language": "Rust",
893
  "queue": {
894
  "max_concurrent": MAX_CONCURRENT,
895
  "avg_job_duration_s": AVG_JOB_DURATION_S,
896
  },
897
  "endpoints": {
898
+ "register": "GET /register",
899
+ "generate": "POST /generate",
900
+ "cancel": "DELETE /job/{id}",
901
  "job_status": "GET /job/{id}",
902
+ "queue": "GET /queue",
903
+ "stream": "GET /stream/{id}",
904
+ "download": "GET /download/{id}",
905
+ "delete": "DELETE /video/{id}",
906
+ "videos": "GET /videos/{category}",
907
+ "health": "GET /health",
908
  },
909
  }))
910
  }
911
 
912
+ #[get("/register")]
913
+ async fn register(req: HttpRequest, state: web::Data<AppState>) -> impl Responder {
914
+ let client = resolve_client(&req, &state.clients);
915
+ HttpResponse::Ok()
916
+ .insert_header(("X-Client-ID", client.token.clone()))
917
+ .json(serde_json::json!({
 
918
  "client_token": client.token,
919
  "is_new": client.job_count == 0,
920
  "job_count": client.job_count,
921
+ "instructions": "Store client_token in localStorage as 'archx_client_id'. Send it as the X-Client-ID header on every request.",
922
+ }))
 
923
  }
924
 
925
+ #[get("/health")]
926
+ async fn health(state: web::Data<AppState>) -> impl Responder {
927
+ let videos = list_videos_from_dataset("minecraft", &state.video_cache).await;
928
+ let running = state.running_jobs.lock().unwrap().len();
929
+ let queued = state.job_queue.lock().unwrap().len();
930
+ let active = state.jobs.lock().unwrap().values().filter(|j| j.status == "processing").count();
931
+
932
+ HttpResponse::Ok().json(serde_json::json!({
933
  "status": "healthy",
934
  "timestamp": Utc::now().to_rfc3339(),
935
  "videos": videos.len(),
936
+ "running": running,
937
+ "queued": queued,
938
+ "active_jobs": active,
939
  }))
940
  }
941
 
942
+ #[get("/queue")]
943
+ async fn queue_status(state: web::Data<AppState>) -> impl Responder {
944
+ let running = state.running_jobs.lock().unwrap().len();
945
+ let waiting = state.job_queue.lock().unwrap().len();
946
+
947
+ HttpResponse::Ok().json(serde_json::json!({
948
  "running": running,
949
  "waiting": waiting,
950
  "total_active": running + waiting,
951
  "avg_job_s": AVG_JOB_DURATION_S,
952
+ "estimated_wait_s": if running == 0 { waiting as i64 * AVG_JOB_DURATION_S } else { (waiting as i64 + 1) * AVG_JOB_DURATION_S },
 
 
 
 
953
  "message": if running + waiting == 0 {
954
+ "No jobs running — submit yours now!"
955
  } else {
956
+ &format!("{} running, {} in queue", running, waiting)
957
  },
958
  }))
959
  }
960
 
961
+ #[get("/videos/{category}")]
962
+ async fn list_videos(category: web::Path<String>, state: web::Data<AppState>) -> impl Responder {
963
+ let videos = list_videos_from_dataset(&category, &state.video_cache).await;
964
+ HttpResponse::Ok().json(serde_json::json!({
965
+ "category": category.as_str(),
 
 
966
  "videos": videos,
967
  "count": videos.len(),
968
  }))
969
  }
970
 
971
+ #[post("/generate")]
972
  async fn generate(
973
+ req: HttpRequest,
974
+ body: web::Json<GenerateRequest>,
975
+ state: web::Data<AppState>,
976
+ ) -> impl Responder {
977
+ if !validate_app_key(&req) {
978
+ return HttpResponse::Forbidden().json(serde_json::json!({"error": "Invalid API key"}));
979
  }
980
+
981
+ let client = resolve_client(&req, &state.clients);
982
+
983
+ if !rate_limit(&format!("generate:{}", client.token), GENERATE_LIMIT, 3600, &mut state.rate_limits.lock().unwrap()) {
984
+ return HttpResponse::TooManyRequests().json(serde_json::json!({
985
+ "error": format!("Rate limit: max {} requests/hour", GENERATE_LIMIT)
986
+ }));
987
  }
988
+
989
+ // Check for active jobs
990
+ let active_for_client = state.jobs.lock().unwrap()
991
+ .values()
992
+ .filter(|j| j.client_token == client.token && (j.status == "queued" || j.status == "processing"))
993
+ .count();
994
+
995
+ if active_for_client > 0 {
996
+ return HttpResponse::Conflict().json(serde_json::json!({
997
+ "error": "You already have an active job. Wait for it to finish or cancel it first."
998
+ }));
999
  }
1000
+
1001
+ let job_id = Uuid::new_v4().to_string();
 
 
 
 
 
 
 
 
 
 
 
 
1002
  let audio_path = PathBuf::from(AUDIO_DIR).join(format!("{}.mp3", job_id));
1003
  let subs_path = PathBuf::from(AUDIO_DIR).join(format!("{}.ass", job_id));
1004
+
1005
+ create_job(job_id.clone(), client.token.clone(), &state.jobs);
1006
+
1007
+ if let Err(e) = save_base64_audio(&body.audio_base64, &audio_path).await {
1008
+ let mut updates = HashMap::new();
1009
+ updates.insert("status", serde_json::json!("failed"));
1010
+ updates.insert("error", serde_json::json!(e));
1011
+ update_job(&job_id, updates, &state.jobs);
1012
+ return HttpResponse::BadRequest().json(serde_json::json!({"error": e}));
 
 
 
 
 
1013
  }
1014
+
1015
+ if let Err(e) = save_subtitles(&body.subtitles_ass, &subs_path).await {
1016
+ let mut updates = HashMap::new();
1017
+ updates.insert("status", serde_json::json!("failed"));
1018
+ updates.insert("error", serde_json::json!(e));
1019
+ update_job(&job_id, updates, &state.jobs);
1020
+ return HttpResponse::BadRequest().json(serde_json::json!({"error": e}));
1021
  }
1022
+
1023
+ let mut updates = HashMap::new();
1024
+ updates.insert("audio_path", serde_json::json!(audio_path.to_str().unwrap()));
1025
+ updates.insert("subs_path", serde_json::json!(subs_path.to_str().unwrap()));
1026
+ updates.insert("background", serde_json::json!(&body.background));
1027
+ updates.insert("requested_duration", serde_json::json!(body.duration));
1028
+ update_job(&job_id, updates, &state.jobs);
1029
+
1030
+ // Update client
1031
+ let mut client = client;
1032
+ client.job_count += 1;
1033
+ client.jobs.push(job_id.clone());
1034
+ if client.jobs.len() > 50 {
1035
+ client.jobs = client.jobs[client.jobs.len() - 50..].to_vec();
1036
  }
1037
+ save_client(&client, &state.clients);
1038
+
1039
+ // Add to queue
1040
  let position = {
1041
+ let running = state.running_jobs.lock().unwrap();
1042
+ let mut queue = state.job_queue.lock().unwrap();
1043
  queue.push_back(job_id.clone());
1044
+ if running.is_empty() { 0 } else { queue.len() }
1045
  };
1046
+
1047
+ let eta = if position == 0 {
1048
+ QueueEta {
1049
+ queue_position: 1,
1050
+ jobs_ahead: 1,
1051
+ wait_low_s: 0,
1052
+ wait_high_s: 30,
1053
+ wait_low_human: "0s".to_string(),
1054
+ wait_high_human: "30s".to_string(),
1055
+ total_with_own_s: 30,
1056
+ message: "Starting very soon...".to_string(),
1057
+ }
1058
  } else {
1059
+ let running = state.running_jobs.lock().unwrap();
1060
+ let jobs = state.jobs.lock().unwrap();
1061
+ queue_eta(position, body.duration, &running, &jobs)
1062
  };
1063
+
1064
+ HttpResponse::Ok()
1065
+ .insert_header(("X-Client-ID", client.token.clone()))
1066
+ .json(serde_json::json!({
 
 
 
1067
  "job_id": job_id,
1068
+ "client_token": client.token,
1069
  "status": "queued",
1070
+ "queue_position": if position > 0 { position } else { 1 },
1071
  "queue": eta,
1072
  "check_status": format!("/job/{}", job_id),
1073
+ }))
 
1074
  }
1075
 
1076
+ #[get("/job/{job_id}")]
1077
+ async fn job_status(job_id: web::Path<String>, state: web::Data<AppState>) -> impl Responder {
1078
+ if !rate_limit(&format!("status:{}", job_id), STATUS_LIMIT, 3600, &mut state.rate_limits.lock().unwrap()) {
1079
+ return HttpResponse::Ok().json(serde_json::json!({"job_id": job_id.as_str(), "status": "rate_limited"}));
 
 
 
 
1080
  }
1081
+
1082
+ let job = state.jobs.lock().unwrap().get(job_id.as_str()).cloned();
1083
+
1084
+ if let Some(mut job) = job {
1085
+ // Check timeout
1086
+ if (Utc::now() - job.updated_at).num_seconds() > JOB_TIMEOUT {
1087
+ if job.status != "completed" && job.status != "failed" {
1088
+ let mut updates = HashMap::new();
1089
+ updates.insert("status", serde_json::json!("failed"));
1090
+ updates.insert("error", serde_json::json!("Job timed out"));
1091
+ update_job(&job_id, updates, &state.jobs);
1092
+ job.status = "failed".to_string();
1093
+ job.error = Some("Job timed out".to_string());
1094
+ }
1095
+ }
1096
+
1097
+ let queue_pos = state.job_queue.lock().unwrap()
1098
+ .iter()
1099
+ .position(|id| id == job_id.as_str())
1100
+ .map(|p| p + 1);
1101
+
1102
+ let eta = if let Some(pos) = queue_pos {
1103
+ let running = state.running_jobs.lock().unwrap();
1104
+ let jobs = state.jobs.lock().unwrap();
1105
+ Some(queue_eta(pos, job.requested_duration, &running, &jobs))
1106
+ } else {
1107
+ None
1108
+ };
1109
+
1110
+ let mut resp = serde_json::json!({
1111
+ "job_id": job.id,
1112
+ "status": job.status,
1113
+ "progress": job.progress,
1114
+ "message": job.message,
1115
+ "queue_position": queue_pos,
1116
+ "queue": eta,
1117
+ "created_at": job.created_at.to_rfc3339(),
1118
+ "updated_at": job.updated_at.to_rfc3339(),
1119
+ "encode_stats": {
1120
+ "frame": job.ffmpeg_frame,
1121
+ "fps": job.ffmpeg_fps,
1122
+ "out_time_s": job.ffmpeg_out_time,
1123
+ "total_s": job.total_duration,
1124
+ "speed": job.ffmpeg_speed,
1125
+ },
1126
  });
1127
+
1128
+ if job.status == "completed" && job.output_path.is_some() {
1129
+ resp["download_url"] = serde_json::json!(format!("/download/{}", job.id));
1130
+ resp["stream_url"] = serde_json::json!(format!("/stream/{}", job.id));
1131
+ }
1132
+
1133
+ if let Some(err) = job.error {
1134
+ resp["error"] = serde_json::json!(err);
1135
+ }
1136
+
1137
+ return HttpResponse::Ok().json(resp);
1138
  }
1139
+
1140
+ HttpResponse::NotFound().json(serde_json::json!({"error": "Job not found"}))
1141
+ }
1142
 
1143
+ #[get("/stream/{job_id}")]
1144
+ async fn stream_video(job_id: web::Path<String>, state: web::Data<AppState>) -> Result<NamedFile, Error> {
1145
+ let output_path = PathBuf::from(OUTPUT_DIR).join(format!("{}.mp4", job_id.as_str()));
1146
+
1147
+ if !output_path.exists() {
1148
+ return Err(actix_web::error::ErrorNotFound("Video not found or not ready"));
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1149
  }
1150
+
1151
+ let job = state.jobs.lock().unwrap().get(job_id.as_str()).cloned();
1152
+ if let Some(job) = job {
1153
+ if job.status != "completed" {
1154
+ return Err(actix_web::error::ErrorBadRequest("Video not ready yet"));
1155
+ }
1156
  }
1157
+
1158
+ Ok(NamedFile::open(output_path)?
1159
+ .set_content_type("video/mp4".parse().unwrap())
1160
+ .use_etag(false)
1161
+ .use_last_modified(false))
1162
  }
1163
 
1164
+ #[get("/download/{job_id}")]
1165
+ async fn download_video(job_id: web::Path<String>, state: web::Data<AppState>) -> Result<NamedFile, Error> {
1166
+ let output_path = PathBuf::from(OUTPUT_DIR).join(format!("{}.mp4", job_id.as_str()));
1167
+
 
1168
  if !output_path.exists() {
1169
+ return Err(actix_web::error::ErrorNotFound("Video not found or not ready"));
1170
  }
1171
+
1172
+ let job = state.jobs.lock().unwrap().get(job_id.as_str()).cloned();
1173
+ if let Some(job) = job {
1174
  if job.status != "completed" {
1175
+ return Err(actix_web::error::ErrorBadRequest("Video not ready yet"));
1176
  }
1177
  }
1178
+
1179
+ // Schedule deletion after 5 seconds
1180
+ let output_path_clone = output_path.clone();
1181
+ let job_id_clone = job_id.clone();
1182
+ let state_clone = state.clone();
1183
+ tokio::spawn(async move {
1184
+ sleep(TokioDuration::from_secs(5)).await;
1185
+ let _ = tokio::fs::remove_file(&output_path_clone).await;
1186
+
1187
+ let mut updates = HashMap::new();
1188
+ updates.insert("output_path", serde_json::json!(null));
1189
+ updates.insert("message", serde_json::json!("Downloaded and cleaned up"));
1190
+ update_job(&job_id_clone, updates, &state_clone.jobs);
1191
+ });
1192
+
1193
+ Ok(NamedFile::open(output_path)?
1194
+ .set_content_disposition(actix_web::http::header::ContentDisposition {
1195
+ disposition: actix_web::http::header::DispositionType::Attachment,
1196
+ parameters: vec![actix_web::http::header::DispositionParam::Filename(
1197
+ format!("archnemix-short-{}.mp4", &job_id.as_str()[..8])
1198
+ )],
1199
+ })
1200
+ .set_content_type("video/mp4".parse().unwrap()))
1201
  }
1202
 
1203
+ #[delete("/video/{job_id}")]
1204
+ async fn delete_video(req: HttpRequest, job_id: web::Path<String>, state: web::Data<AppState>) -> impl Responder {
1205
+ if !validate_app_key(&req) {
1206
+ return HttpResponse::Forbidden().json(serde_json::json!({"error": "Invalid API key"}));
 
 
 
1207
  }
1208
+
1209
+ let output_path = PathBuf::from(OUTPUT_DIR).join(format!("{}.mp4", job_id.as_str()));
1210
  let removed = if output_path.exists() {
1211
  tokio::fs::remove_file(&output_path).await.is_ok()
1212
  } else {
1213
  false
1214
  };
1215
+
1216
+ if removed {
1217
+ let mut updates = HashMap::new();
1218
+ updates.insert("output_path", serde_json::json!(null));
1219
+ updates.insert("message", serde_json::json!("Video deleted by user"));
1220
+ update_job(&job_id, updates, &state.jobs);
1221
  }
1222
+
1223
+ HttpResponse::Ok().json(serde_json::json!({
1224
+ "job_id": job_id.as_str(),
1225
+ "deleted": removed,
1226
+ }))
1227
  }
1228
 
1229
+ #[delete("/job/{job_id}")]
1230
+ async fn cancel_job(req: HttpRequest, job_id: web::Path<String>, state: web::Data<AppState>) -> impl Responder {
1231
+ if !validate_app_key(&req) {
1232
+ return HttpResponse::Forbidden().json(serde_json::json!({"error": "Invalid API key"}));
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1233
  }
1234
+
1235
+ let job = state.jobs.lock().unwrap().get(job_id.as_str()).cloned();
1236
+
1237
+ if job.is_none() {
1238
+ return HttpResponse::Ok().json(serde_json::json!({
1239
+ "job_id": job_id.as_str(),
1240
+ "cancelled": false,
1241
+ "reason": "not found",
1242
+ }));
1243
+ }
1244
+
1245
+ let job = job.unwrap();
1246
+ if job.status == "completed" || job.status == "failed" {
1247
+ return HttpResponse::Ok().json(serde_json::json!({
1248
+ "job_id": job_id.as_str(),
1249
+ "cancelled": false,
1250
+ "reason": job.status,
1251
+ }));
1252
+ }
1253
+
1254
+ state.running_jobs.lock().unwrap().retain(|id| id != job_id.as_str());
1255
+ state.job_queue.lock().unwrap().retain(|id| id != job_id.as_str());
1256
+
1257
+ let output_path = PathBuf::from(OUTPUT_DIR).join(format!("{}.mp4", job_id.as_str()));
1258
+ let _ = tokio::fs::remove_file(&output_path).await;
1259
+
1260
+ let mut updates = HashMap::new();
1261
+ updates.insert("status", serde_json::json!("failed"));
1262
+ updates.insert("error", serde_json::json!("Cancelled by controller — client disconnected"));
1263
+ update_job(&job_id, updates, &state.jobs);
1264
+
1265
+ log::info!("Job {} cancelled via controller request", job_id.as_str());
1266
+
1267
+ HttpResponse::Ok().json(serde_json::json!({
1268
+ "job_id": job_id.as_str(),
1269
+ "cancelled": true,
1270
+ }))
1271
  }
1272
 
1273
  // =============================================================================
1274
+ // MAIN
1275
  // =============================================================================
 
 
 
1276
 
1277
+ #[actix_web::main]
1278
+ async fn main() -> std::io::Result<()> {
1279
+ env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));
1280
+
1281
+ // Create directories
1282
+ for dir in &[AUDIO_DIR, OUTPUT_DIR, JOBS_DIR, CLIENT_DIR, HF_CACHE_DIR] {
1283
+ fs::create_dir_all(dir)?;
1284
  }
1285
+
1286
+ log::info!("============================================================");
1287
+ log::info!("ArchNemix Shorts Generator API v5.1.0 (Rust)");
1288
+ log::info!("Dataset : {}", *HF_DATASET);
1289
+ log::info!("Concurrent : {}", MAX_CONCURRENT);
1290
+ log::info!("Avg job : {}s ({}m)", AVG_JOB_DURATION_S, AVG_JOB_DURATION_S / 60);
1291
+ log::info!("Quality : CRF 16 · medium · 8-16 Mbps · AAC 192k");
1292
+ log::info!("Video path : stream from /tmp, delete on download");
1293
+ log::info!("============================================================");
1294
+
1295
+ let state = web::Data::new(AppState {
1296
  jobs: Arc::new(Mutex::new(HashMap::new())),
 
 
1297
  clients: Arc::new(Mutex::new(HashMap::new())),
1298
+ job_queue: Arc::new(Mutex::new(VecDeque::new())),
1299
+ running_jobs: Arc::new(Mutex::new(Vec::new())),
1300
  rate_limits: Arc::new(Mutex::new(HashMap::new())),
1301
  video_cache: Arc::new(Mutex::new(HashMap::new())),
1302
+ });
1303
+
1304
+ // Start workers
 
 
 
 
 
 
 
 
 
 
 
 
 
1305
  let state_clone = state.clone();
1306
+ tokio::spawn(async move {
1307
+ queue_worker(state_clone).await;
1308
+ });
1309
+
1310
+ tokio::spawn(cleanup_old_videos());
1311
+
1312
+ let port = env::var("PORT").unwrap_or_else(|_| "7860".to_string());
1313
+
1314
+ log::info!("Ready on port {}", port);
1315
+
1316
+ HttpServer::new(move || {
1317
+ let cors = Cors::default()
1318
+ .allowed_origin(&*UI_ORIGIN)
1319
+ .allowed_origin("http://localhost:3000")
1320
+ .allowed_origin("http://127.0.0.1:3000")
1321
+ .allowed_origin("http://localhost:5500")
1322
+ .allowed_origin("http://127.0.0.1:5500")
1323
+ .allowed_origin("https://huggingface.co")
1324
+ .allow_any_method()
1325
+ .allow_any_header()
1326
+ .expose_any_header()
1327
+ .max_age(600);
1328
+
1329
+ App::new()
1330
+ .wrap(cors)
1331
+ .app_data(state.clone())
1332
+ .service(root)
1333
+ .service(register)
1334
+ .service(health)
1335
+ .service(queue_status)
1336
+ .service(list_videos)
1337
+ .service(generate)
1338
+ .service(job_status)
1339
+ .service(stream_video)
1340
+ .service(download_video)
1341
+ .service(delete_video)
1342
+ .service(cancel_job)
1343
+ })
1344
+ .bind(("0.0.0.0", port.parse().unwrap()))?
1345
+ .run()
1346
+ .await
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1347
  }