SPB Git

Repository Public

media.ts 5.0 KB 126 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : MacLustr Vision8 * File             : server/src/media.ts9 * Module           : server10 * Repository       : https://git.spboucher.ai/maclustr-vision11 * Project Website  : https://camera.spboucher.ai12 * Created          : 2026-11-3013 * Last Modified    : 2026-11-3014 *15 * Author           : Simon-Pierre Boucher16 * Position         : Professor of Finance17 * Institution      : Université du Québec en Outaouais (UQO)18 * Organization     : SP Boucher19 * Website          : https://spboucher.ai20 * Git              : https://git.spboucher.ai21 *22 * Preferred Contact: admin@spboucher.ai23 * Technical Contact: dev@spboucher.ai24 * Security/Admin   : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License          : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142// Outils média : exécution de FFmpeg/ffprobe par arguments structurés (jamais de shell), empreintes.43import { spawn } from 'node:child_process';44import crypto from 'node:crypto';45import fs from 'node:fs';46import type { Config } from './config.ts';4748export type RunResult = { code: number | null; stdout: string; stderr: string; timedOut: boolean };4950export function run(bin: string, args: string[], opts: { timeoutMs?: number; env?: NodeJS.ProcessEnv; maxOut?: number } = {}): Promise<RunResult> {51  return new Promise((resolve) => {52    const child = spawn(bin, args, { stdio: ['ignore', 'pipe', 'pipe'], env: opts.env || process.env });53    const max = opts.maxOut ?? 4 * 1024 * 1024;54    let stdout = '';55    let stderr = '';56    let timedOut = false;57    child.stdout.on('data', (d) => {58      if (stdout.length < max) stdout += d;59    });60    child.stderr.on('data', (d) => {61      if (stderr.length < max) stderr += d;62    });63    const timer = opts.timeoutMs64      ? setTimeout(() => {65          timedOut = true;66          child.kill('SIGKILL');67        }, opts.timeoutMs)68      : null;69    child.on('error', (e) => {70      if (timer) clearTimeout(timer);71      resolve({ code: -1, stdout, stderr: stderr + String(e), timedOut });72    });73    child.on('close', (code) => {74      if (timer) clearTimeout(timer);75      resolve({ code, stdout, stderr, timedOut });76    });77  });78}7980export type Probe = { durationMs: number; codec: string | null; width: number | null; height: number | null; hasAudio: boolean; sizeBytes: number };8182export async function probe(cfg: Config, file: string): Promise<Probe | null> {83  const r = await run(cfg.ffprobeBin, ['-v', 'error', '-print_format', 'json', '-show_format', '-show_streams', file], { timeoutMs: 30000 });84  if (r.code !== 0) return null;85  try {86    const j = JSON.parse(r.stdout);87    const v = (j.streams || []).find((s: any) => s.codec_type === 'video');88    if (!v) return null;89    const dur = parseFloat(j.format?.duration ?? 'NaN');90    return {91      durationMs: Number.isFinite(dur) ? Math.round(dur * 1000) : 0,92      codec: v.codec_name || null,93      width: v.width || null,94      height: v.height || null,95      hasAudio: (j.streams || []).some((s: any) => s.codec_type === 'audio'),96      sizeBytes: Number(j.format?.size || fs.statSync(file).size),97    };98  } catch {99    return null;100  }101}102103export function sha256File(file: string): Promise<string> {104  return new Promise((resolve, reject) => {105    const h = crypto.createHash('sha256');106    fs.createReadStream(file)107      .on('data', (d) => h.update(d))108      .on('error', reject)109      .on('end', () => resolve(h.digest('hex')));110  });111}112113/** Remux sans réencodage (réparation d'un segment partiel, MP4 de lecture ou d'export). */114export async function remux(cfg: Config, input: string, output: string, format: 'matroska' | 'mp4'): Promise<boolean> {115  const args = ['-hide_banner', '-v', 'error', '-nostdin', '-y', '-fflags', '+genpts', '-i', input, '-map', '0:v:0', '-map', '0:a?', '-c', 'copy'];116  if (format === 'mp4') args.push('-c:a', 'aac', '-b:a', '64k', '-tag:v', 'hvc1', '-movflags', '+faststart');117  args.push('-f', format, output);118  let r = await run(cfg.ffmpegBin, args, { timeoutMs: 120000 });119  if (r.code !== 0 && format === 'mp4') {120    // H.264 : pas d'étiquette hvc1121    const alt = args.filter((a, i) => !(a === '-tag:v' || args[i - 1] === '-tag:v'));122    r = await run(cfg.ffmpegBin, alt, { timeoutMs: 120000 });123  }124  return r.code === 0;125}126
Files main
Menu

Theme