File size: 5,648 Bytes
03b405b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
const fs = require("node:fs");
const fsp = require("node:fs/promises");
const path = require("node:path");
const { paths } = require("../config/paths");
const { config } = require("../config/env");
const { updateJob, event } = require("./jobs");
const { downloadVideo } = require("../downloader/ytdlp");
const { validateFileSize } = require("../security/validation");
const { sha256File } = require("../security/checksum");
const { getCached, saveCache, cachePathFor } = require("../cache/cache");
const { probe, verifyMedia } = require("../ffmpeg/ffprobe");
const { buildPlan } = require("../ffmpeg/planner");
const { splitIfNeeded } = require("../ffmpeg/splitter");
const { compressVideo } = require("../ffmpeg/ffmpeg");
const { logger } = require("../monitoring/logger");
const { analyzeQuality } = require("../ffmpeg/quality.analyzer");

async function processJob(job, botApi, progress) {
  const startedAt = new Date().toISOString();
  updateJob(job.id, { status: "downloading", stage: "starting", attempts: job.attempts + 1, startedAt });
  event(job.id, "info", "Job started");
  let inputPath = job.inputPath;
  if (job.type === "link") {
    progress(job, 5, "downloading", "Downloading video link");
    inputPath = await downloadVideo(job.sourceUrl, job.id, (p) => {
      progress(job, Math.min(35, Math.round((p.percent || 0) * 0.3)), "downloading", `Downloading ${p.percent?.toFixed(1) || 0}%`);
    });
    updateJob(job.id, { inputPath });
  }

  progress(job, 38, "validating", "Checking file integrity");
  validateFileSize(inputPath);
  await verifyMedia(inputPath);
  const inputHash = await sha256File(inputPath);
  updateJob(job.id, { checksum: inputHash });

  const cached = getCached(inputHash, job.mode);
  if (cached) {
    progress(job, 85, "uploading", "Cached optimized video found");
    await sendOutputs(botApi, job, cached.outputPaths);
    updateJob(job.id, { status: "completed", stage: "cache-hit", progress: 100, outputPaths: cached.outputPaths, finishedAt: new Date().toISOString() });
    return;
  }

  progress(job, 42, "probing", "Reading video technical details");
  const info = await probe(inputPath);
  if (info.duration > config.limits.maxVideoDurationMinutes * 60) {
    throw new Error(`Video is longer than the configured limit of ${config.limits.maxVideoDurationMinutes} minutes.`);
  }

  progress(job, 47, "planning", "Choosing best compression settings");
  const plan = await buildPlan(info, job.mode);
  const workDir = path.join(paths.output, job.id);
  await fsp.mkdir(workDir, { recursive: true });

  progress(job, 50, "splitting", "Splitting long video when needed");
  const segments = await splitIfNeeded(inputPath, workDir, info, plan);
  const outputs = [];
  const width = String(segments.length).length;

  for (const segment of segments) {
    const name = `optimized_part_${String(segment.index).padStart(width, "0")}_of_${String(segments.length).padStart(width, "0")}.mp4`;
    const output = cachePathFor(inputHash, `${plan.mode}_${name}`);
    const segmentInfo = segment.path === inputPath ? info : await probe(segment.path);
    const compResult = compressVideo({
      inputPath: segment.path,
      outputPath: output,
      presetId: plan.mode,
      codec: config.video.preferredEncoder || "h264",
      keepAudio: true,
      onProgress: (pObj) => {
        const ffPercent = pObj.percentage;
        const segmentBase = 55 + ((segment.index - 1) / segments.length) * 30;
        const segmentShare = ffPercent / 100 * (30 / segments.length);
        
        let statsSuffix = ``;
        if (pObj.speed) {
          statsSuffix = ` | ${ffPercent}% | FPS: ${pObj.currentFps} | Speed: ${pObj.speed}x | ETA: ${pObj.etaSeconds}s`;
        }
        
        progress(job, Math.round(segmentBase + segmentShare), "compressing", `Compressing part ${segment.index}/${segments.length}${statsSuffix}`);
      },
      info: segmentInfo
    });
    await compResult.promise;
    outputs.push(output);
  }

  const sizeBefore = fs.statSync(inputPath).size;
  const sizeAfter = outputs.reduce((sum, file) => sum + fs.statSync(file).size, 0);
  const qualityMetrics = outputs[0] ? await analyzeQuality(inputPath, outputs[0]).catch(() => null) : null;
  const firstSsim = qualityMetrics ? qualityMetrics.ssim : null;

  progress(job, 88, "uploading", "Uploading optimized video");
  const fileId = await sendOutputs(botApi, job, outputs);

  saveCache({
    inputHash,
    mode: job.mode,
    fileId,
    outputPaths: outputs,
    sizeBefore,
    sizeAfter,
    duration: info.duration || 0,
    platform: job.type === "link" ? "url" : "telegram",
    metadata: { info, plan, ssim: firstSsim }
  });

  updateJob(job.id, { status: "completed", stage: "completed", progress: 100, outputPaths: outputs, finishedAt: new Date().toISOString(), metadata: { info, plan, ssim: firstSsim, sizeBefore, sizeAfter } });
  event(job.id, "info", "Job completed", { outputs });
}

async function sendOutputs(botApi, job, outputs) {
  let fileId = null;
  for (const file of outputs) {
    const res = await botApi.sendVideo(job.chatId, { source: file }, {
      caption: `🎥 Optimized video (${path.basename(file)})`
    }).catch(async (err) => {
      logger.debug(`sendVideo failed, falling back to sendDocument: ${err.message}`);
      return await botApi.sendDocument(job.chatId, { source: file }, {
        caption: `📄 Optimized video file (${path.basename(file)})`
      });
    });

    if (res && res.video) {
      fileId = res.video.file_id;
    } else if (res && res.document) {
      fileId = res.document.file_id;
    }
  }
  return fileId;
}

module.exports = { processJob };