File size: 2,967 Bytes
82ab794
 
 
 
 
 
 
 
 
 
 
 
 
 
d6fb15c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82ab794
 
 
 
 
 
d6fb15c
 
 
 
 
 
82ab794
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
// Geração e cache de thumbnails (posters JPG) dos vídeos.
// Estratégia para o app ficar FLUIDO:
//  - on-demand: GET /thumb/:id gera na hora se faltar (fallback).
//  - em background: warmThumbnails() pré-gera os que faltam (no boot e após uploads),
//    com baixa concorrência, para não travar a CPU. Assim, ao abrir o editor, as
//    miniaturas já estão prontas (instantâneas) em vez de gerar uma a uma na tela.
import fs from 'node:fs';
import path from 'node:path';
import { all, run } from '../db.js';
import { DIRS } from '../config.js';
import { makeThumbnail } from '../ffmpeg.js';

export function thumbPathFor(id) { return path.join(DIRS.thumbs, `thumb-${id}.jpg`); }

// Semáforo GLOBAL de ffmpeg: no máximo MAX_FFMPEG gerações ao mesmo tempo. Sem
// isso, abrir a grade com dezenas de vídeos dispara um ffmpeg por thumb e satura
// a CPU (2 vCPU na nuvem) — o servidor inteiro congela. O mapa `inflight` também
// impede gerar o MESMO thumb duas vezes quando dois pedidos chegam juntos.
const MAX_FFMPEG = 2;
let active = 0;
const waiting = [];
const inflight = new Map();
function withSlot(fn) {
  return new Promise((resolve, reject) => {
    const go = () => { active++; fn().then(resolve, reject).finally(() => { active--; const n = waiting.shift(); if (n) n(); }); };
    if (active < MAX_FFMPEG) go(); else waiting.push(go);
  });
}

// Garante o thumb de UM asset (gera se faltar) e devolve o caminho, ou null.
export async function ensureThumb(asset) {
  if (!asset || !asset.file_path || !fs.existsSync(asset.file_path)) return null;
  if (asset.thumb_path && fs.existsSync(asset.thumb_path)) return asset.thumb_path;
  const out = thumbPathFor(asset.id);
  if (fs.existsSync(out)) { run('UPDATE media_assets SET thumb_path = ? WHERE id = ?', [out, asset.id]); return out; }
  if (inflight.has(asset.id)) return inflight.get(asset.id);
  const p = withSlot(() => makeThumbnail(asset.file_path, out))
    .then(() => { run('UPDATE media_assets SET thumb_path = ? WHERE id = ?', [out, asset.id]); return out; })
    .finally(() => inflight.delete(asset.id));
  inflight.set(asset.id, p);
  return p;
}

let warming = false;
// Pré-gera, em background, todos os thumbs que faltam (baixa concorrência).
export async function warmThumbnails(concurrency = 2) {
  if (warming) return;
  warming = true;
  try {
    const list = all('SELECT * FROM media_assets ORDER BY id DESC');
    const todo = list.filter((a) => {
      if (a.thumb_path && fs.existsSync(a.thumb_path)) return false;
      if (fs.existsSync(thumbPathFor(a.id))) return false;
      return fs.existsSync(a.file_path);
    });
    if (!todo.length) return;
    let i = 0;
    const worker = async () => {
      while (i < todo.length) {
        const a = todo[i++];
        try { await ensureThumb(a); } catch {}
      }
    };
    await Promise.all(Array.from({ length: Math.min(concurrency, todo.length) }, worker));
  } finally {
    warming = false;
  }
}