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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
import ffmpeg from "ffmpeg-static";
import ffprobe from "ffprobe-static";
import fluent_ffmpeg, { type FfprobeData } from "fluent-ffmpeg";
import createError from "http-errors";
import { Context } from "elysia";
// import { T_Probe_v2 } from "./types";
import { NS_misc } from "./misc";
import { NS_promise } from "./promise";
import { NS_error } from "./error";
import UserAgent from "user-agents";
import { exec, execSync, spawn } from "node:child_process";
import { T_live, T_playback } from "../sub-router/ffmpeg/validator-v2";

const APP_ENV = process.env.APP_ENV;
const FFMPEG_V = process.env.FFMPEG_V;
const FFPROBE_V = process.env.FFPROBE_V;
const CPU_0V1 = process.env.CPU_0V1;

const is_prod =
  process.env.NODE_ENV === "production" ||
  APP_ENV === "prod" ||
  APP_ENV === "pre_prod";

const ffmpeg_path = is_prod ? "ffmpeg" : ffmpeg || "ffmpeg";
const ffprobe_path = is_prod ? "ffprobe" : ffprobe.path || "ffprobe";

fluent_ffmpeg.setFfmpegPath(ffmpeg_path);
fluent_ffmpeg.setFfprobePath(ffprobe_path);

let hw_encoder: any = await get_hardware_encoder();
hw_encoder =
  typeof hw_encoder !== "string" || !hw_encoder.trim()
    ? "libx264"
    : hw_encoder.trim();
// hw_encoder = "libx264";

console.log(`🚀 Using hardware encoder: ${hw_encoder}`);

const TIMEOUT_MS = 30_000; // probe + transcode timeout
const PROBE_TIMEOUT_MS = 30_000; // probe + transcode timeout

function get_hardware_encoder() {
  check_if_fFmpeg_active();

  return new Promise((resolve) => {
    // We wrap ffmpeg path in quotes in case there are spaces in the path
    const checkCmd = `"${ffmpeg_path}" -encoders | grep -E "nvenc|qsv|vaapi"`;

    exec(checkCmd, (error, stdout) => {
      if (error || !stdout) {
        return resolve(null);
      }

      const output = stdout.toLowerCase();
      if (output.includes("nvenc")) return resolve("h264_nvenc");
      if (output.includes("qsv")) return resolve("h264_qsv");
      if (output.includes("vaapi")) return resolve("h264_vaapi");

      resolve(null);
    });
  });
}

function check_if_fFmpeg_active() {
  try {
    const version = execSync(`${ffmpeg_path} -version`, { encoding: "utf8" });
    console.log("\n");
    console.log("⚙️ ", version.split("\n")[0], "\n");
    return true;
  } catch {
    console.error("❗FFmpeg not found in PATH", "\n");
    return false;
  }
}

export const NS_ffmpeg_v2 = {
  F_probe_t1,
  F_scan_raw_probe_metadata,
  F_build_ffmpeg_flags_t1,
  proc_error_pattern
};

async function F_probe_t1(arg0: {
  playback: Omit<T_playback, "picture_quality">;
  context?: Context;
  just_cmd?: boolean;
}) {
  const { context, playback, just_cmd } = arg0;

  if (!NS_misc.isValidUrlFormat(playback.url)) {
    if (playback.protocol !== "local") {
      throw createError(400, "invalid playback URL");
    }
  }

  const controller = new AbortController();

  function kill_controller() {
    controller.abort();
    console.log("[CONTROLLER] Request aborted");
  }

  const t = setTimeout(() => kill_controller(), PROBE_TIMEOUT_MS);

  const abort_signal = context?.request.signal;

  if (abort_signal) {
    if (abort_signal.aborted) {
      kill_controller();
    } else {
      abort_signal.addEventListener(
        "abort",
        () => {
          kill_controller();
        },
        {
          once: true
        }
      );
    }
  }

  const flags = [];

  flags.push("-v", "debug");

  flags.push("-protocol_whitelist", "file,http,https,tcp,tls,crypto");
  // if (playback.type === "hls") flags.push("-allowed_extensions", "ALL");

  flags.push("-probesize", `${1_000_000 * 5}`); // Limit probe size to 5MB (default is 5MB, but explicit)
  flags.push("-analyzeduration", `${1_000_000 * 5}`); // Analyze only 5 seconds (default is 5s)

  flags.push("-show_format");
  flags.push("-show_streams");

  flags.push("-print_format", "json");

  (() => {
    const playback_headers = playback.headers;

    if (
      typeof playback_headers !== "object" ||
      Array.isArray(playback_headers)
    ) {
      return;
    }

    const headers_str = Object.entries(playback_headers)
      .map(([k, v]) => `${k}: ${v}`)
      .join("\r\n");

    flags.push("-headers", headers_str + "\r\n");
  })();

  flags.push("-i", playback.url);

  if (APP_ENV === "dev") {
    console.log("[PROBE FLAGS]", flags, "\n");
  }

  if (just_cmd) {
    clearTimeout(t);

    return { cmd: flags.join(" ") };
  }

  const timeoutPromise = () =>
    new Promise<never>((_, reject) => {
      setTimeout(() => {
        clearTimeout(t);
        reject(new Error("PROBE is taking way to long"));
      }, PROBE_TIMEOUT_MS);
    });

  const [E_, R_] = await NS_promise.F_catch_promise({
    promise: Promise.race([
      probe_runner({
        ffprobe_path,
        args: flags,
        controller
      }),
      timeoutPromise()
    ])
  });

  clearTimeout(t);

  if (E_) {
    throw E_;
  }

  return R_;
}

function probe_runner(arg0: {
  ffprobe_path: string;
  args: string[];
  controller?: AbortController;
}) {
  const { ffprobe_path, args, controller } = arg0;

  return new Promise((resolve, reject) => {
    const probe = spawn(ffprobe_path, args, { signal: controller?.signal });

    let dataOutput = "";
    let errorOutput = "";

    probe.stdout.on("data", (data) => {
      dataOutput += data;
    });

    probe.stderr.on("data", (data) => {
      errorOutput += data;
    });

    probe.on("close", (code) => {
      if (code !== 0) {
        reject(
          new Error(
            JSON.stringify({
              code,
              message: `ffprobe exited with code ${code}: ${errorOutput}`
            })
          )
        );
        return;
      }

      try {
        resolve(JSON.parse(dataOutput));
      } catch (err: any) {
        reject(
          new Error(`PROBE Failed to parse ffprobe output: ${err.message}`)
        );
      }
    });

    probe.on("error", (err) => {
      // This will be called with err being an AbortError if the controller aborts
      const { message } = NS_error.F_collect_error_message({ ERR: err });

      reject(new Error(`PROBE FAILED: ${message}`));
    });
  });
}

function F_scan_raw_probe_metadata(arg0: { metadata: Record<string, any> }) {
  const { metadata } = arg0;

  const streams = metadata.streams;

  if (!streams) return;

  const audioStreams: Record<string, any>[] = [];
  const videoStreams: Record<string, any>[] = [];
  const subStreams: Record<string, any>[] = [];

  let hasSubs = false;

  // Single pass through streams
  for (const stream of streams) {
    if (stream.codec_type === "video") {
      // if (!videoStream) videoStream = stream;
      videoStreams.push(stream);
    } else if (stream.codec_type === "audio") {
      // if (!audioStream) audioStream = stream;
      audioStreams.push(stream);
    } else if (stream.codec_type === "subtitle") {
      hasSubs = true;
      subStreams.push(stream);
    }
  }

  const format = (() => {
    if (!metadata.format) return;

    const xx = metadata.format;

    return {
      name: xx.format_name,
      duration: xx.duration,
      bit_rate: xx.bit_rate,
      size: xx.size,
      probe_score: xx.probe_score
    };
  })();

  return { audioStreams, videoStreams, subStreams, format };
}

async function F_build_ffmpeg_flags_t1(arg0: {
  playback: Omit<T_playback, "picture_quality">;
  subtitles?: T_live["subtitles"];
  output_destination: NonNullable<T_live["delivery_name"]>;
  delivery_mode: T_live["delivery_mode"];
  delivery_format: T_live["delivery_format"];
  probe_metadata: Record<string, any>;
}) {
  const {
    playback,
    subtitles,
    output_destination,
    delivery_format,
    delivery_mode,
    probe_metadata
  } = arg0;

  const flags: string[] = ["-hide_banner", "-loglevel", "info", "-stats"];

  flags.push("-reconnect", "1");
  flags.push("-reconnect_streamed", "1");
  if (playback.type === "hls" && delivery_mode === "stream") flags.push("-reconnect_at_eof", "1");
  flags.push("-reconnect_delay_max", "30");
  flags.push("-rw_timeout", `${1_000_000 * 30}`);
  flags.push("-reconnect_on_network_error", "1");
  // flags.push("-reconnect_on_http_error", "429,500,502,503,504");
  flags.push("-reconnect_on_http_error", "500,502,503,504");

  // flags.push("-fflags", "+discardcorrupt+genpts+nobuffer");
  // flags.push("-live_start_index", "-2"); // For live streams: start near the end
  // flags.push("-fflags", "+discardcorrupt"); // Don't hang on truncated segments

  if (playback.type === "hls") flags.push("-http_persistent", "0");
  if (playback.type === "hls") flags.push("-http_multiple", "0");
  if (playback.type === "hls") flags.push("-http_seekable", "0");

  flags.push("-protocol_whitelist", "file,http,https,tcp,tls,crypto");
  if (playback.type === "hls") flags.push("-allowed_extensions", "ALL");

  (() => {
    const playback_headers = playback.headers;

    if (
      typeof playback_headers !== "object" ||
      Array.isArray(playback_headers)
    ) {
      return;
    }

    const headers_str = Object.entries(playback_headers)
      .map(([k, v]) => `${k}: ${v}`)
      .join("\r\n");

    flags.push("-headers", headers_str + "\r\n");
  })();

  flags.push("-i", playback.url);

  const clean_metadata = NS_ffmpeg_v2.F_scan_raw_probe_metadata({
    metadata: probe_metadata
  });

  let subs: any[] | undefined = undefined;

  (() => {
    (() => {
      if (delivery_format === "ts") {
        subs = undefined;
      }

      if (clean_metadata?.subStreams && clean_metadata.subStreams.length) {
        subs = clean_metadata.subStreams;

        return;
      }

      if (!subtitles || !subtitles.length) return;

      subs = subtitles;

      for (let i = 0; i < subtitles.length; i++) {
        const sub = subtitles[i];

        flags.push("-i", sub.url);
      }
    })();

    if (subs?.length) {
      const limit = 5;
      subs = subs.slice(0, limit);
    }
  })();

  const videoCodec = clean_metadata?.videoStreams[0].codec_name;
  const audioCodec = clean_metadata?.audioStreams[0].codec_name;

  const supported_codecs = (() => {
    switch (delivery_format) {
      case "mp4":
        {
          return {
            video: ["h264", "hevc", "vp9", "av1", "mpeg2video"],
            audio: ["aac", "mp3", "opus", "ac3"],
            subtitle: ["mov_text"]
          };
        }

        break;

      case "ts":
        {
          return {
            video: ["h264", "hevc", "mpeg2video"],
            audio: ["aac", "mp3", "ac3"],
            subtitle: []
          };
        }

        break;

      case "mkv":
        {
          return {
            video: [
              "h264",
              "hevc",
              "vp9",
              "av1",
              "mpeg2video",
              "vp8",
              "theora"
            ],
            audio: [
              "aac",
              "mp3",
              "opus",
              "ac3",
              "flac",
              "vorbis",
              "dts",
              "truehd"
            ],
            subtitle: ["srt", "ass", "ssa", "vobsub", "pgs", "webvtt"]
          };
        }

        break;
    }
  })();

  const must_re_encode =
    !supported_codecs.video.includes(videoCodec) ||
    !supported_codecs.audio.includes(audioCodec);

  flags.push("-map", "0:v");
  flags.push("-map", "0:a");

  if (subs) {
    if (clean_metadata?.subStreams.length) {
      flags.push("-map", "0:s");
    } else {
      subs.forEach((_, i) => flags.push("-map", String(i + 1)));
    }
  }

  if (!must_re_encode) {
    flags.push("-c:v", "copy");
    flags.push("-c:a", "copy");
  } else {
    flags.push("-c:v", hw_encoder || "libx264");
    flags.push("-c:a", "aac", "-b:a", "256k");
  }

  if (playback.type === "hls") flags.push("-bsf:a", "aac_adtstoasc");

  if (subs) {
    flags.push("-c:s", "mov_text");

    subs.forEach((s, i) => {
      let lang = s.lang || s.tags?.language;

      if (!lang) {
        lang = "und";
      }

      lang = lang.slice(0, 3).toLowerCase();

      flags.push(`-metadata:s:s:${i}`, `language=${lang}`);
    });
  }

  if (delivery_mode === "stream") {
    flags.push("-tune", "zerolatency");
  }

  if (must_re_encode || delivery_mode === "stream") {
    const use_ultrafast = delivery_mode === "stream";

    if (hw_encoder.includes("h264_qsv")) {
      flags.push("-preset", use_ultrafast ? "7" : "7"); // QSV uses numbers: 7 is fastest speed (ultrafast), 4 is balanced (medium)
    } else {
      flags.push("-crf", "23");
      flags.push("-preset", use_ultrafast ? "ultrafast" : "ultrafast"); // ultrafast veryfast faster medium
    }
  }

  if (must_re_encode) flags.push("-pix_fmt", "yuv420p");

  flags.push("-max_interleave_delta", "0");

  if (delivery_mode === "stream") {
    //   flags.push("-f", "ismv");
    // } else {
    flags.push("-f", delivery_format === "ts" ? "mpegts" : delivery_format);
  }

  flags.push("-avoid_negative_ts", "make_zero");

  if (delivery_mode === "download") {
    flags.push("-max_muxing_queue_size", "9999");

    flags.push("-movflags", "+faststart");

    flags.push("-y", output_destination);
  } else {
    flags.push("-fps_mode", "passthrough");

    flags.push("-movflags", "frag_keyframe+dash+delay_moov");

    flags.push("-y", "pipe:1");
  }

  return flags;
}

function proc_error_pattern() {
  const errorPatterns = [
    /^(\[error\]|\[fatal\]|\[panic\])/i,
    /error/i,
    /failed/i,
    /failure/i,
    /invalid/i,
    /unknown/i,
    /unsupported/i,
    /not found/i,
    /cannot/i,
    /could not/i,
    /unable to/i,
    /permission denied/i,
    /no such file/i,
    /broken pipe/i,
    /protocol not found/i,
    /codec not found/i,
    /encoder not found/i,
    /decoder not found/i,
    /filter not found/i,
    /option not found/i,
    /conversion failed/i,
    /av_interleaved_write_frame/i,
    /out of memory/i,
    /segmentation fault/i,
    /assertion failed/i,
    /corrupt/i,
    /truncated/i,
    /malformed/i,
    /incompatible/i,
    /mismatch/i,
    /overflow/i,
    /underflow/i,
    /timeout/i,
    /connection refused/i,
    /connection reset/i,
    /network is unreachable/i,
    /no route to host/i,
    /dns/i, // DNS resolution failures
    /unrecognized/i
  ];

  return errorPatterns;
}