File size: 1,168 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
const path = require("node:path");
const { copySegment } = require("./ffmpeg");

function planSegments(duration, splitSeconds) {
  if (duration <= splitSeconds + 20) return [{ index: 1, start: 0, duration }];
  const segments = [];
  let start = 0;
  let index = 1;
  while (start < duration) {
    const remaining = duration - start;
    const length = remaining <= splitSeconds + 20 ? remaining : splitSeconds;
    segments.push({ index, start, duration: length });
    start += length;
    index += 1;
  }
  return segments;
}

async function splitIfNeeded(inputPath, outDir, info, plan) {
  const segments = planSegments(info.duration, plan.splitSeconds);
  if (segments.length === 1) return [{ ...segments[0], path: inputPath, copied: false }];
  const width = String(segments.length).length;
  const result = [];
  for (const segment of segments) {
    const output = path.join(outDir, `source_part_${String(segment.index).padStart(width, "0")}.mp4`);
    await copySegment(inputPath, output, segment.start, segment.duration);
    result.push({ ...segment, path: output, copied: true });
  }
  return result;
}

module.exports = { planSegments, splitIfNeeded };