video-fps-probe 0.4.0-beta.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/CHANGELOG.md +72 -0
  2. package/README.md +13 -10
  3. package/dist/analyze.js +10 -1
  4. package/dist/api/codes.js +2 -0
  5. package/dist/aspect/index.d.ts +13 -0
  6. package/dist/aspect/index.js +180 -0
  7. package/dist/aspect/rational.js +61 -0
  8. package/dist/check/index.d.ts +2 -0
  9. package/dist/check/index.js +56 -53
  10. package/dist/cjs/aspect/index.d.cts +13 -0
  11. package/dist/cjs/aspect.cjs +1 -0
  12. package/dist/cjs/check/index.d.cts +2 -0
  13. package/dist/cjs/check.cjs +1 -1
  14. package/dist/cjs/chunks/boxes-B0T2nt3e.cjs +1 -0
  15. package/dist/cjs/chunks/build-DhETwJLO.cjs +1 -0
  16. package/dist/cjs/chunks/color-xqJHSfhZ.cjs +1 -0
  17. package/dist/cjs/chunks/{compare-D7RVqlqf.cjs → compare-B_HKNwqg.cjs} +1 -1
  18. package/dist/cjs/chunks/config-CSbXzEqr.cjs +1 -0
  19. package/dist/cjs/chunks/{fallback-D9Ak2zFv.cjs → fallback-CyPIR3RM.cjs} +1 -1
  20. package/dist/cjs/chunks/{guards-Dqpjtkdn.cjs → guards-DbQNcAZS.cjs} +1 -1
  21. package/dist/cjs/chunks/isobmff-4RrRf9N-.cjs +1 -0
  22. package/dist/cjs/chunks/matroska-BhgWtuPU.cjs +1 -0
  23. package/dist/cjs/chunks/metadata-ECdzNLkE.cjs +1 -0
  24. package/dist/cjs/chunks/options-B_vLHxHd.cjs +1 -0
  25. package/dist/cjs/chunks/{probe-DDLUfr23.cjs → probe-Cn1DtL-C.cjs} +1 -1
  26. package/dist/cjs/chunks/reader-Dw11ozVU.cjs +1 -0
  27. package/dist/cjs/chunks/runtime-BgAlQQee.cjs +1 -0
  28. package/dist/cjs/chunks/{segments-i-hPN7H3.cjs → segments-B1H6bDz-.cjs} +1 -1
  29. package/dist/cjs/chunks/stats-DW7dVdFa.cjs +1 -0
  30. package/dist/cjs/color/index.d.cts +7 -0
  31. package/dist/cjs/color.cjs +1 -0
  32. package/dist/cjs/core/types.d.cts +46 -1
  33. package/dist/cjs/header/index.d.cts +3 -0
  34. package/dist/cjs/header/limits.d.cts +1 -0
  35. package/dist/cjs/header.cjs +1 -1
  36. package/dist/cjs/index.cjs +1 -1
  37. package/dist/color/codec-string.js +121 -0
  38. package/dist/color/config.js +199 -0
  39. package/dist/color/index.d.ts +7 -0
  40. package/dist/color/index.js +139 -0
  41. package/dist/color/names.js +33 -0
  42. package/dist/color/sps.js +275 -0
  43. package/dist/core/isobmff/build.js +6 -3
  44. package/dist/core/isobmff/config.js +34 -0
  45. package/dist/core/isobmff/header.js +23 -0
  46. package/dist/core/isobmff/moov.js +1 -1
  47. package/dist/core/matroska/header.js +1 -0
  48. package/dist/core/matroska/index.js +4 -2
  49. package/dist/core/options.js +1 -0
  50. package/dist/core/types.d.ts +46 -1
  51. package/dist/header/index.d.ts +3 -0
  52. package/dist/header/index.js +39 -3
  53. package/dist/header/limits.d.ts +1 -0
  54. package/dist/header/limits.js +4 -0
  55. package/dist/header/metadata.js +2 -0
  56. package/dist/standalone/own-isobmff.worker.js +1 -1
  57. package/dist/standalone/own-matroska.worker.js +1 -1
  58. package/dist/standalone/own.worker.js +1 -1
  59. package/package.json +41 -3
  60. package/dist/cjs/chunks/build-CT5g6_bs.cjs +0 -1
  61. package/dist/cjs/chunks/isobmff-B_bb5rS5.cjs +0 -1
  62. package/dist/cjs/chunks/matroska-CLoGzfKA.cjs +0 -1
  63. package/dist/cjs/chunks/reader-DNLR-_tm.cjs +0 -1
  64. package/dist/cjs/chunks/runtime-DtgT0xzU.cjs +0 -1
  65. package/dist/cjs/chunks/stats-D68frkk2.cjs +0 -1
@@ -4,7 +4,8 @@ const SPAN_SLACK_MS = 3n;
4
4
  const MAX_EXPONENT = 400;
5
5
  const NOMINAL_SLACK_PER_S = 10000000n;
6
6
  const NTSC = [24n, 30n, 48n, 60n, 120n];
7
- const STANDARD = [...[24n, 25n, 30n, 48n, 50n, 60n, 100n, 120n].map((m) => [m, 1n]), ...NTSC.map((m) => [m * 1000n, 1001n])];
7
+ const drop = (m) => [m * 1000n, 1001n];
8
+ const STANDARD = [...[24n, 25n, 30n, 48n, 50n, 60n, 100n, 120n].map((m) => [m, 1n]), ...NTSC.map(drop)];
8
9
  const RELATION = { min: 'below the minimum', max: 'above the maximum', exact: 'not', oneOf: 'not one of' };
9
10
  const BOUNDS = Object.keys(RELATION);
10
11
  const GROUPS = ['fps', 'duration', 'frameSize', 'aspectRatio', 'pixels', 'fileSize'];
@@ -14,14 +15,14 @@ const AUDIO_ENGINES = ['own', 'mp4box', 'mediabunny'];
14
15
  const RANGE = ['min', 'max'];
15
16
  const FILE_RULES = ['fileSize', 'containers', 'audio'];
16
17
  const GROUP_KEYS = {
17
- fps: [...RANGE, 'exact', 'oneOf', 'source'],
18
+ fps: [...BOUNDS, 'source'],
18
19
  duration: RANGE,
19
20
  frameSize: ['Width', 'Height', 'ShortSide', 'LongSide'].flatMap((side) => RANGE.map((b) => b + side)),
20
21
  aspectRatio: [...RANGE, 'oneOf'],
21
22
  pixels: RANGE,
22
23
  fileSize: RANGE,
23
24
  };
24
- const RULE_KEYS = [...GROUPS, 'containers', 'codecs', 'audio', 'vfr', 'uneven', 'severity'];
25
+ const RULE_KEYS = [...GROUPS, 'containers', 'codecs', 'audio', 'vfr', 'uneven', 'hdr', 'sizeBasis', 'severity'];
25
26
  const invalid = (rule, v, what) => {
26
27
  throw new TypeError(`${rule}: ${typeof v === 'number' ? v : JSON.stringify(v)} is not ${what}`);
27
28
  };
@@ -35,6 +36,7 @@ function decimal(s) {
35
36
  const n = BigInt(m[1] + (m[2] ?? ''));
36
37
  return e >= 0 ? [n * 10n ** BigInt(e), 1n] : [n, 10n ** BigInt(-e)];
37
38
  }
39
+ const quantity = (x) => (typeof x === 'number' ? decimal(String(x)) : null);
38
40
  function ratio(v, rule, amount = false) {
39
41
  const parts = typeof v === 'number' || typeof v === 'string' ? String(v).split(/[/:]/) : [];
40
42
  const [a, b] = parts.map(decimal);
@@ -43,14 +45,13 @@ function ratio(v, rule, amount = false) {
43
45
  return q && q[1] !== 0n ? q : invalid(rule, v, amount ? `a non-negative number${ratios}` : "a non-negative number or 'num/den'");
44
46
  }
45
47
  const cmp = (a, b) => a[0] * b[1] - b[0] * a[1];
46
- const ntsc = (v, q) => (/[/:]/.test(String(v)) ? [] : NTSC.filter((m) => q[0] * 1000n === q[1] * m * 999n).map((m) => [m * 1000n, 1001n]));
48
+ const ntsc = (v, q) => (/[/:]/.test(String(v)) ? [] : NTSC.filter((m) => q[0] * 1000n === q[1] * m * 999n).map(drop));
47
49
  const readings = (v, rule) => {
48
50
  const q = ratio(v, rule);
49
51
  return [q, ...ntsc(v, q)];
50
52
  };
51
53
  function close(n, a, b, slack, perSecond) {
52
- const gap = n * (a[1] * b[0] - b[1] * a[0]);
53
- return (gap < 0n ? -gap : gap) * perSecond <= slack * a[0] * b[0];
54
+ return abs(n * cmp(a, b)) * perSecond <= slack * a[0] * b[0];
54
55
  }
55
56
  const whole = (x) => Number.isSafeInteger(x) && x > 0;
56
57
  const record = (x) => !!x && typeof x === 'object' && !Array.isArray(x);
@@ -69,7 +70,6 @@ const failedWith = (e) => `the analysis failed${typeof e === 'string' && e.trim(
69
70
  const fromRational = (r) => (r && whole(r.num) && whole(r.den) ? [BigInt(r.num), BigInt(r.den)] : null);
70
71
  const gcd = (a, b) => (b === 0n ? a : gcd(b, a % b));
71
72
  const value = (q) => Number(q[0]) / Number(q[1]);
72
- const round = (x) => +x.toFixed(3);
73
73
  const micros = (q) => (q[0] * 2000000n + q[1]) / (2n * q[1]);
74
74
  function digits(q, against) {
75
75
  let d = 3;
@@ -82,28 +82,30 @@ function fraction(q) {
82
82
  return `${q[0] / g}/${q[1] / g}`;
83
83
  }
84
84
  const fpsText = (q, against = []) => (q[0] % q[1] === 0n ? `${q[0] / q[1]}` : `${digits(q, against)} (${fraction(q)})`);
85
- function steady(t) {
85
+ function onTicks(t) {
86
86
  const avg = fromRational(t.avgFps);
87
- const nominal = fromRational(t.nominalFps);
88
87
  const frames = t.presentedFrames ?? t.frames;
89
- if (!avg || !nominal || !t.timestampsQuantized || t.isVfr !== false || !whole(frames))
90
- return null;
91
- const n = BigInt(frames);
92
- return close(n, avg, nominal, SPAN_SLACK_MS, 1000n) ? [nominal, [n * nominal[1], nominal[0]]] : null;
88
+ return avg && t.timestampsQuantized && t.isVfr === false && whole(frames) ? [avg, BigInt(frames)] : null;
89
+ }
90
+ function steady(t) {
91
+ const q = onTicks(t);
92
+ const nominal = fromRational(t.nominalFps);
93
+ return q && nominal && close(q[1], q[0], nominal, SPAN_SLACK_MS, 1000n) ? [nominal, [q[1] * nominal[1], nominal[0]]] : null;
93
94
  }
94
95
  function resolution(t, cfr) {
95
- const avg = fromRational(t.avgFps);
96
- const frames = t.presentedFrames ?? t.frames;
97
- if (!avg || !t.timestampsQuantized || t.isVfr !== false || !whole(frames))
96
+ const q = onTicks(t);
97
+ if (!q)
98
98
  return undefined;
99
- return cfr ? (x) => close(1n, cfr[0], x, 1n, NOMINAL_SLACK_PER_S) : (x) => close(BigInt(frames), avg, x, SPAN_SLACK_MS, 1000n);
99
+ return cfr ? (x) => close(1n, cfr[0], x, 1n, NOMINAL_SLACK_PER_S) : (x) => close(q[1], q[0], x, SPAN_SLACK_MS, 1000n);
100
100
  }
101
101
  function printedDuration(t, result) {
102
102
  const span = t.durationSec;
103
103
  const format = result.formatDurationSec;
104
- const typical = fromRational(t.dominantFps?.rate ?? (t.isVfr === false ? t.nominalFps : null) ?? t.avgFps);
104
+ const rate = t.dominantFps?.rate ?? (t.isVfr === false ? t.nominalFps : null);
105
+ const median = rate ? null : t.medianFrameInterval;
106
+ const typical = fromRational(median ? { num: median.den, den: median.num } : (rate ?? t.avgFps));
105
107
  const matroska = result.container === 'webm' || result.container === 'matroska';
106
- const [a, b] = [span, format].map((x) => (typeof x === 'number' ? decimal(String(x)) : null));
108
+ const [a, b] = [span, format].map(quantity);
107
109
  const gap = a && b && abs(micros(a) - micros(b));
108
110
  return matroska && typical && gap != null && gap * typical[0] <= 1000000n * typical[1] ? format : (span ?? format);
109
111
  }
@@ -153,57 +155,50 @@ function fit(target, rule = {}) {
153
155
  const decimates = cmp(target, [DECIMATE_FROM[0] * closest[0], DECIMATE_FROM[1] * closest[1]]) >= 0;
154
156
  return (decimates && divided(allowed)) || [closest, 0];
155
157
  }
158
+ function known(path, v, keys, prefix = `${path}.`) {
159
+ if (!record(v))
160
+ invalid(path, v, 'an object');
161
+ for (const k of Object.keys(v))
162
+ if (!keys.includes(k))
163
+ throw new TypeError(`${prefix}${k}: not a rule; expected one of ${keys.join(', ')}`);
164
+ }
156
165
  export function check(result, rules) {
157
- const known = (path, v, keys) => {
158
- if (!v || typeof v !== 'object' || Array.isArray(v))
159
- invalid(path, v, 'an object');
160
- const prefix = path === 'rules' ? '' : `${path}.`;
161
- for (const k of Object.keys(v))
162
- if (!keys.includes(k))
163
- throw new TypeError(`${prefix}${k}: not a rule; expected one of ${keys.join(', ')}`);
164
- };
165
- known('rules', rules, RULE_KEYS);
166
+ known('rules', rules, RULE_KEYS, '');
166
167
  for (const g of GROUPS)
167
168
  if (rules[g] != null)
168
169
  known(g, rules[g], GROUP_KEYS[g]);
169
- const choices = [
170
- ['fps.source', rules.fps?.source, SOURCES],
171
- ['audio', rules.audio, ['required', 'forbidden']],
172
- ['vfr', rules.vfr, POLICIES],
173
- ['uneven', rules.uneven, POLICIES],
174
- ['severity', rules.severity, ['fail', 'warn']],
175
- ];
176
- for (const [rule, v, list] of choices)
170
+ const choices = { 'fps.source': SOURCES, audio: ['required', 'forbidden'], vfr: POLICIES, uneven: POLICIES, hdr: POLICIES, sizeBasis: ['stored', 'display'], severity: ['fail', 'warn'] };
171
+ for (const [rule, list] of Object.entries(choices)) {
172
+ const v = rule === 'fps.source' ? rules.fps?.source : rules[rule];
177
173
  if (v != null && !list.includes(v))
178
174
  invalid(rule, v, `one of ${list.join(', ')}`);
175
+ }
179
176
  const violations = [];
180
177
  const severity = rules.severity === 'warn' ? 'warn' : 'fail';
181
- const failure = result == null ? 'the analysis failed: no result' : result.error ? failedWith(result.error) : null;
178
+ const failure = result == null ? failedWith('no result') : result.error ? failedWith(result.error) : null;
182
179
  const found = failure ?? primaryTrack(result);
183
180
  const t = typeof found === 'string' ? null : found;
184
181
  const add = (rule, s, expected, actual, message) => violations.push({ rule, severity: s, expected, actual, message: `${rule}: ${message}` });
185
182
  const unknown = (rule, missing) => violations.some((v) => v.rule === rule) ||
186
183
  add(rule, 'unknown', null, null, `unknown, ${t || FILE_RULES.includes(rule) ? `no ${missing}${failure ? `; ${failure}` : ''}` : found}`);
187
- const limits = (group, rule, actual, shown, text, unit, missing, side = '', near) => {
184
+ const limits = (group, rule, actual, shown, unit, missing, side = '', text = () => `${shown}`, near) => {
188
185
  const bounds = BOUNDS.filter((b) => rule?.[b] != null).map((b) => {
189
186
  const path = `${group}.${b}${side}`;
190
187
  const values = (b === 'oneOf' ? [rule[b]].flat() : [rule[b]]).map((v) => (group === 'fps' ? readings(v, path) : [ratio(v, path, group !== 'aspectRatio')]));
191
- return [b, rule[b], values];
188
+ return [b, rule[b], values, path];
192
189
  });
193
190
  if (bounds.length === 0)
194
191
  return;
195
192
  if (!actual)
196
193
  return void unknown(group, missing);
197
- for (const [b, expected, values] of bounds) {
194
+ for (const [b, expected, values, path] of bounds) {
198
195
  const meets = (q) => near?.(q) || (b === 'min' ? cmp(actual, q) >= 0n : b === 'max' ? cmp(actual, q) <= 0n : cmp(actual, q) === 0n);
199
196
  const listed = [expected].flat();
200
197
  const named = listed.length ? `${listed.join(', ')}${unit}` : 'an empty list';
201
- const actualText = typeof text === 'string' ? text : text(values.flat());
202
198
  if (!values.flat().some(meets))
203
- add(`${group}.${b}${side}`, severity, expected, shown, `${actualText}${unit} is ${RELATION[b]} ${named}`);
199
+ add(path, severity, expected, shown, `${text(values.flat())}${unit} is ${RELATION[b]} ${named}`);
204
200
  }
205
201
  };
206
- const quantity = (x) => (typeof x === 'number' ? decimal(String(x)) : null);
207
202
  const allow = (rule, list, actual, missing) => {
208
203
  if (list == null)
209
204
  return;
@@ -225,25 +220,30 @@ export function check(result, rules) {
225
220
  return state === true;
226
221
  };
227
222
  const cfr = t && steady(t);
228
- const fps = t && judgedFps(t, rules.fps?.source, cfr);
229
- const near = t && (rules.fps?.source ?? 'avg') === 'avg' ? resolution(t, cfr) : undefined;
230
- limits('fps', rules.fps, fps, fps ? fraction(fps) : '', (against) => fpsText(fps, against), ' fps', `${rules.fps?.source ?? 'avg'} frame rate`, '', near);
223
+ const source = rules.fps?.source ?? 'avg';
224
+ const fps = t && judgedFps(t, source, cfr);
225
+ const near = t && source === 'avg' ? resolution(t, cfr) : undefined;
226
+ limits('fps', rules.fps, fps, fps ? fraction(fps) : '', ' fps', `${source} frame rate`, '', (against) => fpsText(fps, against), near);
231
227
  const exact = cfr?.[1] ?? quantity(t && printedDuration(t, result));
232
228
  const span = exact && [micros(exact), 1000000n];
233
229
  const seconds = span ? value(span) : 0;
234
- limits('duration', rules.duration, span, seconds, (against) => `${digits(span, against)}`, ' s', 'duration');
235
- const size = t ? (Math.abs(t.rotation) % 180 === 90 ? [t.height, t.width] : [t.width, t.height]) : [0, 0];
230
+ limits('duration', rules.duration, span, seconds, ' s', 'duration', '', (against) => `${digits(span, against)}`);
231
+ const display = rules.sizeBasis === 'display';
232
+ const turned = Math.abs(t?.rotation) % 180 === 90;
233
+ const size = t ? (display ? [t.displayWidth, t.displayHeight] : turned ? [t.height, t.width] : [t.width, t.height]) : [0, 0];
236
234
  const sized = size.every(whole);
237
235
  const [w, h] = sized ? size : [0, 0];
236
+ const sizeOf = display ? `display size${t?.displayWidth === undefined ? ' (needs codecConfig: true and withAspect)' : ''}` : 'frame size';
238
237
  const sides = { Width: w, Height: h, ShortSide: Math.min(w, h), LongSide: Math.max(w, h) };
239
238
  const d = rules.frameSize;
240
239
  for (const [side, x] of Object.entries(sides)) {
241
- limits('frameSize', { min: d?.[`min${side}`], max: d?.[`max${side}`] }, sized ? [BigInt(x), 1n] : null, x, `${x}`, ' px', 'frame size', side);
240
+ limits('frameSize', { min: d?.[`min${side}`], max: d?.[`max${side}`] }, sized ? [BigInt(x), 1n] : null, x, ' px', sizeOf, side);
242
241
  }
243
- const area = [BigInt(w), BigInt(h)];
244
- limits('aspectRatio', rules.aspectRatio, sized ? area : null, fraction(area), `${w}x${h} (${round(w / h)})`, '', 'frame size');
245
- limits('pixels', rules.pixels, sized ? [BigInt(w) * BigInt(h), 1n] : null, w * h, `${w * h}`, ' px', 'frame size');
246
- limits('fileSize', rules.fileSize, quantity(result?.size), result?.size ?? '', `${result?.size}`, ' bytes', 'file size');
242
+ const dar = display && fromRational(t?.displayAspectRatio);
243
+ const area = dar ? (turned || t.displayHeight !== t.height ? [dar[1], dar[0]] : dar) : [BigInt(w), BigInt(h)];
244
+ limits('aspectRatio', rules.aspectRatio, sized ? area : null, fraction(area), '', sizeOf, '', () => `${w}x${h} (${digits(area, [])})`);
245
+ limits('pixels', rules.pixels, sized ? [BigInt(w) * BigInt(h), 1n] : null, w * h, ' px', sizeOf);
246
+ limits('fileSize', rules.fileSize, quantity(result?.size), result?.size ?? '', ' bytes', 'file size');
247
247
  allow('containers', rules.containers, result?.container, 'container');
248
248
  allow('codecs', rules.codecs, t?.codecName, 'codec name');
249
249
  if (rules.audio) {
@@ -261,6 +261,9 @@ export function check(result, rules) {
261
261
  const profile = t?.rateProfile;
262
262
  const summary = record(profile) && typeof profile.summary === 'string' ? `: ${profile.summary}` : '';
263
263
  const uneven = policy('uneven', t && unevenOf(t), `${profile == null ? '' : 'uneven flag in the '}rate profile`, `the frame rate is uneven${summary}`);
264
+ const c = t?.color;
265
+ const hdr = record(c?.dolbyVision) || c?.hdr === 'pq' || c?.hdr === 'hlg' || (typeof c?.transfer === 'string' && c.transfer && c.transfer !== 'reserved' ? false : null);
266
+ policy('hdr', hdr, c === undefined ? 'color (needs codecConfig: true and withColor)' : c ? 'transfer in codecConfig' : 'color in codecConfig', 'the video is HDR');
264
267
  const report = { verdict: 'pass', violations };
265
268
  const fpsOff = violations.some((v) => v.rule.startsWith('fps.'));
266
269
  if (t && (fpsOff || vfr || uneven)) {
@@ -0,0 +1,13 @@
1
+ import type { FileResult, Rational, VideoTrackResult } from '../core/types.cjs';
2
+ export type { CodecConfig, Rational } from '../core/types.cjs';
3
+ export interface AspectInfo {
4
+ sampleAspectRatio: Rational | null;
5
+ displayAspectRatio: Rational | null;
6
+ displayWidth: number | null;
7
+ displayHeight: number | null;
8
+ }
9
+ export type AspectTrack = Pick<VideoTrackResult, 'codecName' | 'width' | 'height' | 'rotation' | 'codecConfig'>;
10
+ export declare function aspectOf(track: AspectTrack): AspectInfo | undefined;
11
+ export declare function withAspect<R extends Pick<FileResult, 'videoTracks'>>(result: R, options?: {
12
+ keepCodecConfig?: boolean;
13
+ }): R;
@@ -0,0 +1 @@
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./chunks/color-xqJHSfhZ.cjs");exports.aspectOf=e.t,exports.withAspect=e.n;
@@ -38,6 +38,8 @@ export interface CheckRules {
38
38
  audio?: 'required' | 'forbidden';
39
39
  vfr?: RatePolicy;
40
40
  uneven?: RatePolicy;
41
+ hdr?: RatePolicy;
42
+ sizeBasis?: 'stored' | 'display';
41
43
  severity?: 'fail' | 'warn';
42
44
  }
43
45
  export type CheckExpected = number | string | readonly (number | string)[] | null;
@@ -1 +1 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=[3n,2n],t=3n,n=[24n,30n,48n,60n,120n],r=[...[24n,25n,30n,48n,50n,60n,100n,120n].map(e=>[e,1n]),...n.map(e=>[e*1000n,1001n])],i={min:`below the minimum`,max:`above the maximum`,exact:`not`,oneOf:`not one of`},a=Object.keys(i),o=[`fps`,`duration`,`frameSize`,`aspectRatio`,`pixels`,`fileSize`],s=[`allow`,`warn`,`reject`],c=[`avg`,`ffprobe`,`nominal`,`dominant`],l=[`own`,`mp4box`,`mediabunny`],u=[`min`,`max`],d=[`fileSize`,`containers`,`audio`],f={fps:[...u,`exact`,`oneOf`,`source`],duration:u,frameSize:[`Width`,`Height`,`ShortSide`,`LongSide`].flatMap(e=>u.map(t=>t+e)),aspectRatio:[...u,`oneOf`],pixels:u,fileSize:u},p=[...o,`containers`,`codecs`,`audio`,`vfr`,`uneven`,`severity`],invalid=(e,t,n)=>{throw TypeError(`${e}: ${typeof t==`number`?t:JSON.stringify(t)} is not ${n}`)};function decimal(e){let t=/^(\d+)(?:\.(\d+))?(?:e([+-]?\d+))?$/i.exec(e.trim());if(!t||!Number.isFinite(Number(t[0])))return null;let n=Number(t[3]??0)-(t[2]?.length??0);if(Math.abs(n)>400)return null;let r=BigInt(t[1]+(t[2]??``));return n>=0?[r*10n**BigInt(n),1n]:[r,10n**BigInt(-n)]}function ratio(e,t,n=!1){let r=typeof e==`number`||typeof e==`string`?String(e).split(/[/:]/):[],[i,a]=r.map(decimal),o=i&&r.length===1?i:i&&a&&r.length===2&&!n?[i[0]*a[1],i[1]*a[0]]:null,s=r.length>1?`; 'num/den' and 'num:den' ratios are for fps and aspectRatio`:``;return o&&o[1]!==0n?o:invalid(t,e,n?`a non-negative number${s}`:`a non-negative number or 'num/den'`)}const cmp=(e,t)=>e[0]*t[1]-t[0]*e[1],ntsc=(e,t)=>/[/:]/.test(String(e))?[]:n.filter(e=>t[0]*1000n==t[1]*e*999n).map(e=>[e*1000n,1001n]),readings=(e,t)=>{let n=ratio(e,t);return[n,...ntsc(e,n)]};function close(e,t,n,r,i){let a=e*(t[1]*n[0]-n[1]*t[0]);return(a<0n?-a:a)*i<=r*t[0]*n[0]}const whole=e=>Number.isSafeInteger(e)&&e>0,record=e=>!!e&&typeof e==`object`&&!Array.isArray(e);function primaryTrack(e){let t=e.videoTracks,n=e.primaryTrackId;return Array.isArray(t)?t.length===0?`no video track`:t.find(e=>record(e)&&typeof n==`number`&&e.trackId===n)||`no primary track: primaryTrackId ${n===void 0?`is missing`:`${JSON.stringify(n)} matches no video track`}`:`the result has no videoTracks list`}const errorKind=e=>typeof e==`string`?`blank`:Array.isArray(e)?`a list`:`of type ${typeof e}`,failedWith=e=>`the analysis failed${typeof e==`string`&&e.trim()?`: ${e}`:`, and its error is ${errorKind(e)}`}`,fromRational=e=>e&&whole(e.num)&&whole(e.den)?[BigInt(e.num),BigInt(e.den)]:null,gcd=(e,t)=>t===0n?e:gcd(t,e%t),value=e=>Number(e[0])/Number(e[1]),round=e=>+e.toFixed(3),micros=e=>(e[0]*2000000n+e[1])/(2n*e[1]);function digits(e,t){let n=3;for(;n<12&&t.some(t=>value(t).toFixed(n)===value(e).toFixed(n));)n++;return+value(e).toFixed(n)}function fraction(e){let t=gcd(e[0],e[1])||1n;return`${e[0]/t}/${e[1]/t}`}const fpsText=(e,t=[])=>e[0]%e[1]===0n?`${e[0]/e[1]}`:`${digits(e,t)} (${fraction(e)})`;function steady(e){let n=fromRational(e.avgFps),r=fromRational(e.nominalFps),i=e.presentedFrames??e.frames;if(!n||!r||!e.timestampsQuantized||e.isVfr!==!1||!whole(i))return null;let a=BigInt(i);return close(a,n,r,t,1000n)?[r,[a*r[1],r[0]]]:null}function resolution(e,n){let r=fromRational(e.avgFps),i=e.presentedFrames??e.frames;if(r&&e.timestampsQuantized&&e.isVfr===!1&&whole(i))return n?e=>close(1n,n[0],e,1n,10000000n):e=>close(BigInt(i),r,e,t,1000n)}function printedDuration(e,t){let n=e.durationSec,r=t.formatDurationSec,i=fromRational(e.dominantFps?.rate??(e.isVfr===!1?e.nominalFps:null)??e.avgFps),a=t.container===`webm`||t.container===`matroska`,[o,s]=[n,r].map(e=>typeof e==`number`?decimal(String(e)):null),c=o&&s&&abs(micros(o)-micros(s));return a&&i&&c!=null&&c*i[0]<=1000000n*i[1]?r:n??r}function judgedFps(e,t,n){let r=/^(\d+)\/(\d+)$/.exec(e.avgFpsFfprobe??``);return t===`ffprobe`?r&&fromRational({num:+r[1],den:+r[2]}):t===`nominal`?fromRational(e.nominalFps):t===`dominant`?fromRational(e.dominantFps?.rate??(e.isVfr===!1?e.nominalFps:null)):n?.[0]??fromRational(e.avgFps)}function unevenOf(e){let t=e.rateProfile;return t==null?e.isVfr===!1||e.minFps&&e.maxFps&&e.maxFps.value<=e.minFps.value*1.075?!1:null:record(t)?t.uneven:null}const abs=e=>e<0n?-e:e;function fit(t,n={}){let list=e=>e==null?[]:[e].flat().flatMap(e=>readings(e,`fps`)),[i]=list(n.min),a=list(n.max).reduce((e,t)=>e&&cmp(e,t)>0?e:t,void 0),inside=e=>(!i||cmp(e,i)>=0)&&(!a||cmp(e,a)<=0),nearer=(e,n)=>abs(cmp(e,t))*n[1]-abs(cmp(n,t))*e[1]||cmp(e,n),nearest=e=>e.filter(inside).reduce((e,t)=>e&&nearer(e,t)<=0n?e:t,null),divided=e=>{for(let n=2n;n<=8n;n++){let r=[t[0],t[1]*n];if(e(r))return[r,Number(n)]}},o=n.oneOf==null?null:list(n.oneOf),s=n.exact==null?o:list(n.exact).filter(e=>!o||o.some(t=>cmp(t,e)===0n));if(i&&a&&cmp(i,a)>0)return null;if(!s&&inside(t))return[t,0];let c=(s??r).filter(inside),l=!s&&c.length===0,u=l?i&&cmp(t,i)<0?i:a:nearest(c);if(!u)return null;let d=l?inside:e=>c.some(t=>cmp(t,e)===0n);return cmp(t,[e[0]*u[0],e[1]*u[1]])>=0&&divided(d)||[u,0]}function check(e,t){let known=(e,t,n)=>{(!t||typeof t!=`object`||Array.isArray(t))&&invalid(e,t,`an object`);let r=e===`rules`?``:`${e}.`;for(let e of Object.keys(t))if(!n.includes(e))throw TypeError(`${r}${e}: not a rule; expected one of ${n.join(`, `)}`)};known(`rules`,t,p);for(let e of o)t[e]!=null&&known(e,t[e],f[e]);let n=[[`fps.source`,t.fps?.source,c],[`audio`,t.audio,[`required`,`forbidden`]],[`vfr`,t.vfr,s],[`uneven`,t.uneven,s],[`severity`,t.severity,[`fail`,`warn`]]];for(let[e,t,r]of n)t!=null&&!r.includes(t)&&invalid(e,t,`one of ${r.join(`, `)}`);let r=[],u=t.severity===`warn`?`warn`:`fail`,m=e==null?`the analysis failed: no result`:e.error?failedWith(e.error):null,h=m??primaryTrack(e),g=typeof h==`string`?null:h,add=(e,t,n,i,a)=>r.push({rule:e,severity:t,expected:n,actual:i,message:`${e}: ${a}`}),unknown=(e,t)=>r.some(t=>t.rule===e)||add(e,`unknown`,null,null,`unknown, ${g||d.includes(e)?`no ${t}${m?`; ${m}`:``}`:h}`),limits=(e,t,n,r,o,s,c,l=``,d)=>{let f=a.filter(e=>t?.[e]!=null).map(n=>{let r=`${e}.${n}${l}`,i=(n===`oneOf`?[t[n]].flat():[t[n]]).map(t=>e===`fps`?readings(t,r):[ratio(t,r,e!==`aspectRatio`)]);return[n,t[n],i]});if(f.length!==0){if(!n)return void unknown(e,c);for(let[t,a,c]of f){let meets=e=>d?.(e)||(t===`min`?cmp(n,e)>=0n:t===`max`?cmp(n,e)<=0n:cmp(n,e)===0n),f=[a].flat(),p=f.length?`${f.join(`, `)}${s}`:`an empty list`,m=typeof o==`string`?o:o(c.flat());c.flat().some(meets)||add(`${e}.${t}${l}`,u,a,r,`${m}${s} is ${i[t]} ${p}`)}}},quantity=e=>typeof e==`number`?decimal(String(e)):null,allow=(e,t,n,r)=>{t!=null&&((!Array.isArray(t)||t.some(e=>typeof e!=`string`))&&invalid(e,t,`a list of strings`),typeof n!=`string`||!n||n===`unknown`?unknown(e,r):t.some(e=>e.toLowerCase()===n.toLowerCase())||add(e,u,t,n,`${n} is not one of ${t.length?t.join(`, `):`an empty list`}`))},policy=(e,n,r,i)=>{let a=t[e];return!a||a===`allow`?!1:(typeof n==`boolean`?n&&add(e,a===`warn`?`warn`:u,a,!0,i):unknown(e,r),n===!0)},_=g&&steady(g),v=g&&judgedFps(g,t.fps?.source,_),y=g&&(t.fps?.source??`avg`)===`avg`?resolution(g,_):void 0;limits(`fps`,t.fps,v,v?fraction(v):``,e=>fpsText(v,e),` fps`,`${t.fps?.source??`avg`} frame rate`,``,y);let b=_?.[1]??quantity(g&&printedDuration(g,e)),x=b&&[micros(b),1000000n],S=x?value(x):0;limits(`duration`,t.duration,x,S,e=>`${digits(x,e)}`,` s`,`duration`);let C=g?Math.abs(g.rotation)%180==90?[g.height,g.width]:[g.width,g.height]:[0,0],w=C.every(whole),[T,E]=w?C:[0,0],D={Width:T,Height:E,ShortSide:Math.min(T,E),LongSide:Math.max(T,E)},O=t.frameSize;for(let[e,t]of Object.entries(D))limits(`frameSize`,{min:O?.[`min${e}`],max:O?.[`max${e}`]},w?[BigInt(t),1n]:null,t,`${t}`,` px`,`frame size`,e);let k=[BigInt(T),BigInt(E)];if(limits(`aspectRatio`,t.aspectRatio,w?k:null,fraction(k),`${T}x${E} (${round(T/E)})`,``,`frame size`),limits(`pixels`,t.pixels,w?[BigInt(T)*BigInt(E),1n]:null,T*E,`${T*E}`,` px`,`frame size`),limits(`fileSize`,t.fileSize,quantity(e?.size),e?.size??``,`${e?.size}`,` bytes`,`file size`),allow(`containers`,t.containers,e?.container,`container`),allow(`codecs`,t.codecs,g?.codecName,`codec name`),t.audio){let n=e?.engine,r=l.includes(n),i=e?.audioTrackCount,a=!m&&r&&Number.isSafeInteger(i)&&i>=0?i>0:null,o=t.audio===`required`;a===null?unknown(`audio`,`audio track count${!r&&typeof n==`string`?` (the ${n} engine reports none)`:``}`):a!==o&&add(`audio`,u,t.audio,a,`${t.audio}, the file has ${o?`no`:`an`} audio track`)}let A=policy(`vfr`,g?.isVfr,`VFR flag`,`the frame rate is variable`),j=g?.rateProfile,M=record(j)&&typeof j.summary==`string`?`: ${j.summary}`:``,N=policy(`uneven`,g&&unevenOf(g),`${j==null?``:`uneven flag in the `}rate profile`,`the frame rate is uneven${M}`),P={verdict:`pass`,violations:r},F=r.some(e=>e.rule.startsWith(`fps.`));if(g&&(F||A||N)){let e=F?v:fromRational(g.dominantFps?.rate)??fromRational(g.nominalFps),n=Math.round(g.avgFps?.value??0),r=fit(e??[whole(n)?BigInt(n):0n,1n],t.fps),i=F?`${fpsText(v,r?[r[0]]:[])} fps is not allowed`:`the frame rate is ${A?`variable`:`uneven`}`;if(!r)P.suggestedFps={value:null,reason:`${i}, and no frame rate meets every bound of the fps rule`};else if(r[0][0]>0n){let[e,t]=r,n=t>1?`, which keeps 1 of every ${t} frames`:``;P.suggestedFps={value:value(e),reason:`${i}: ${F?`convert to`:`re-encode at a constant`} ${fpsText(e)} fps${n}`}}}return P.verdict=[`fail`,`unknown`,`warn`].find(e=>r.some(t=>t.severity===e))??`pass`,P}exports.check=check;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=[3n,2n],t=3n,n=[24n,30n,48n,60n,120n],drop=e=>[e*1000n,1001n],r=[...[24n,25n,30n,48n,50n,60n,100n,120n].map(e=>[e,1n]),...n.map(drop)],i={min:`below the minimum`,max:`above the maximum`,exact:`not`,oneOf:`not one of`},a=Object.keys(i),o=[`fps`,`duration`,`frameSize`,`aspectRatio`,`pixels`,`fileSize`],s=[`allow`,`warn`,`reject`],c=[`avg`,`ffprobe`,`nominal`,`dominant`],l=[`own`,`mp4box`,`mediabunny`],u=[`min`,`max`],d=[`fileSize`,`containers`,`audio`],f={fps:[...a,`source`],duration:u,frameSize:[`Width`,`Height`,`ShortSide`,`LongSide`].flatMap(e=>u.map(t=>t+e)),aspectRatio:[...u,`oneOf`],pixels:u,fileSize:u},p=[...o,`containers`,`codecs`,`audio`,`vfr`,`uneven`,`hdr`,`sizeBasis`,`severity`],invalid=(e,t,n)=>{throw TypeError(`${e}: ${typeof t==`number`?t:JSON.stringify(t)} is not ${n}`)};function decimal(e){let t=/^(\d+)(?:\.(\d+))?(?:e([+-]?\d+))?$/i.exec(e.trim());if(!t||!Number.isFinite(Number(t[0])))return null;let n=Number(t[3]??0)-(t[2]?.length??0);if(Math.abs(n)>400)return null;let r=BigInt(t[1]+(t[2]??``));return n>=0?[r*10n**BigInt(n),1n]:[r,10n**BigInt(-n)]}const quantity=e=>typeof e==`number`?decimal(String(e)):null;function ratio(e,t,n=!1){let r=typeof e==`number`||typeof e==`string`?String(e).split(/[/:]/):[],[i,a]=r.map(decimal),o=i&&r.length===1?i:i&&a&&r.length===2&&!n?[i[0]*a[1],i[1]*a[0]]:null,s=r.length>1?`; 'num/den' and 'num:den' ratios are for fps and aspectRatio`:``;return o&&o[1]!==0n?o:invalid(t,e,n?`a non-negative number${s}`:`a non-negative number or 'num/den'`)}const cmp=(e,t)=>e[0]*t[1]-t[0]*e[1],ntsc=(e,t)=>/[/:]/.test(String(e))?[]:n.filter(e=>t[0]*1000n==t[1]*e*999n).map(drop),readings=(e,t)=>{let n=ratio(e,t);return[n,...ntsc(e,n)]};function close(e,t,n,r,i){return abs(e*cmp(t,n))*i<=r*t[0]*n[0]}const whole=e=>Number.isSafeInteger(e)&&e>0,record=e=>!!e&&typeof e==`object`&&!Array.isArray(e);function primaryTrack(e){let t=e.videoTracks,n=e.primaryTrackId;return Array.isArray(t)?t.length===0?`no video track`:t.find(e=>record(e)&&typeof n==`number`&&e.trackId===n)||`no primary track: primaryTrackId ${n===void 0?`is missing`:`${JSON.stringify(n)} matches no video track`}`:`the result has no videoTracks list`}const errorKind=e=>typeof e==`string`?`blank`:Array.isArray(e)?`a list`:`of type ${typeof e}`,failedWith=e=>`the analysis failed${typeof e==`string`&&e.trim()?`: ${e}`:`, and its error is ${errorKind(e)}`}`,fromRational=e=>e&&whole(e.num)&&whole(e.den)?[BigInt(e.num),BigInt(e.den)]:null,gcd=(e,t)=>t===0n?e:gcd(t,e%t),value=e=>Number(e[0])/Number(e[1]),micros=e=>(e[0]*2000000n+e[1])/(2n*e[1]);function digits(e,t){let n=3;for(;n<12&&t.some(t=>value(t).toFixed(n)===value(e).toFixed(n));)n++;return+value(e).toFixed(n)}function fraction(e){let t=gcd(e[0],e[1])||1n;return`${e[0]/t}/${e[1]/t}`}const fpsText=(e,t=[])=>e[0]%e[1]===0n?`${e[0]/e[1]}`:`${digits(e,t)} (${fraction(e)})`;function onTicks(e){let t=fromRational(e.avgFps),n=e.presentedFrames??e.frames;return t&&e.timestampsQuantized&&e.isVfr===!1&&whole(n)?[t,BigInt(n)]:null}function steady(e){let n=onTicks(e),r=fromRational(e.nominalFps);return n&&r&&close(n[1],n[0],r,t,1000n)?[r,[n[1]*r[1],r[0]]]:null}function resolution(e,n){let r=onTicks(e);if(r)return n?e=>close(1n,n[0],e,1n,10000000n):e=>close(r[1],r[0],e,t,1000n)}function printedDuration(e,t){let n=e.durationSec,r=t.formatDurationSec,i=e.dominantFps?.rate??(e.isVfr===!1?e.nominalFps:null),a=i?null:e.medianFrameInterval,o=fromRational(a?{num:a.den,den:a.num}:i??e.avgFps),s=t.container===`webm`||t.container===`matroska`,[c,l]=[n,r].map(quantity),u=c&&l&&abs(micros(c)-micros(l));return s&&o&&u!=null&&u*o[0]<=1000000n*o[1]?r:n??r}function judgedFps(e,t,n){let r=/^(\d+)\/(\d+)$/.exec(e.avgFpsFfprobe??``);return t===`ffprobe`?r&&fromRational({num:+r[1],den:+r[2]}):t===`nominal`?fromRational(e.nominalFps):t===`dominant`?fromRational(e.dominantFps?.rate??(e.isVfr===!1?e.nominalFps:null)):n?.[0]??fromRational(e.avgFps)}function unevenOf(e){let t=e.rateProfile;return t==null?e.isVfr===!1||e.minFps&&e.maxFps&&e.maxFps.value<=e.minFps.value*1.075?!1:null:record(t)?t.uneven:null}const abs=e=>e<0n?-e:e;function fit(t,n={}){let list=e=>e==null?[]:[e].flat().flatMap(e=>readings(e,`fps`)),[i]=list(n.min),a=list(n.max).reduce((e,t)=>e&&cmp(e,t)>0?e:t,void 0),inside=e=>(!i||cmp(e,i)>=0)&&(!a||cmp(e,a)<=0),nearer=(e,n)=>abs(cmp(e,t))*n[1]-abs(cmp(n,t))*e[1]||cmp(e,n),nearest=e=>e.filter(inside).reduce((e,t)=>e&&nearer(e,t)<=0n?e:t,null),divided=e=>{for(let n=2n;n<=8n;n++){let r=[t[0],t[1]*n];if(e(r))return[r,Number(n)]}},o=n.oneOf==null?null:list(n.oneOf),s=n.exact==null?o:list(n.exact).filter(e=>!o||o.some(t=>cmp(t,e)===0n));if(i&&a&&cmp(i,a)>0)return null;if(!s&&inside(t))return[t,0];let c=(s??r).filter(inside),l=!s&&c.length===0,u=l?i&&cmp(t,i)<0?i:a:nearest(c);if(!u)return null;let d=l?inside:e=>c.some(t=>cmp(t,e)===0n);return cmp(t,[e[0]*u[0],e[1]*u[1]])>=0&&divided(d)||[u,0]}function known(e,t,n,r=`${e}.`){record(t)||invalid(e,t,`an object`);for(let e of Object.keys(t))if(!n.includes(e))throw TypeError(`${r}${e}: not a rule; expected one of ${n.join(`, `)}`)}function check(e,t){known(`rules`,t,p,``);for(let e of o)t[e]!=null&&known(e,t[e],f[e]);let n={"fps.source":c,audio:[`required`,`forbidden`],vfr:s,uneven:s,hdr:s,sizeBasis:[`stored`,`display`],severity:[`fail`,`warn`]};for(let[e,r]of Object.entries(n)){let n=e===`fps.source`?t.fps?.source:t[e];n!=null&&!r.includes(n)&&invalid(e,n,`one of ${r.join(`, `)}`)}let r=[],u=t.severity===`warn`?`warn`:`fail`,m=e==null?failedWith(`no result`):e.error?failedWith(e.error):null,h=m??primaryTrack(e),g=typeof h==`string`?null:h,add=(e,t,n,i,a)=>r.push({rule:e,severity:t,expected:n,actual:i,message:`${e}: ${a}`}),unknown=(e,t)=>r.some(t=>t.rule===e)||add(e,`unknown`,null,null,`unknown, ${g||d.includes(e)?`no ${t}${m?`; ${m}`:``}`:h}`),limits=(e,t,n,r,o,s,c=``,l=()=>`${r}`,d)=>{let f=a.filter(e=>t?.[e]!=null).map(n=>{let r=`${e}.${n}${c}`,i=(n===`oneOf`?[t[n]].flat():[t[n]]).map(t=>e===`fps`?readings(t,r):[ratio(t,r,e!==`aspectRatio`)]);return[n,t[n],i,r]});if(f.length!==0){if(!n)return void unknown(e,s);for(let[e,t,a,s]of f){let meets=t=>d?.(t)||(e===`min`?cmp(n,t)>=0n:e===`max`?cmp(n,t)<=0n:cmp(n,t)===0n),c=[t].flat(),f=c.length?`${c.join(`, `)}${o}`:`an empty list`;a.flat().some(meets)||add(s,u,t,r,`${l(a.flat())}${o} is ${i[e]} ${f}`)}}},allow=(e,t,n,r)=>{t!=null&&((!Array.isArray(t)||t.some(e=>typeof e!=`string`))&&invalid(e,t,`a list of strings`),typeof n!=`string`||!n||n===`unknown`?unknown(e,r):t.some(e=>e.toLowerCase()===n.toLowerCase())||add(e,u,t,n,`${n} is not one of ${t.length?t.join(`, `):`an empty list`}`))},policy=(e,n,r,i)=>{let a=t[e];return!a||a===`allow`?!1:(typeof n==`boolean`?n&&add(e,a===`warn`?`warn`:u,a,!0,i):unknown(e,r),n===!0)},_=g&&steady(g),v=t.fps?.source??`avg`,y=g&&judgedFps(g,v,_),b=g&&v===`avg`?resolution(g,_):void 0;limits(`fps`,t.fps,y,y?fraction(y):``,` fps`,`${v} frame rate`,``,e=>fpsText(y,e),b);let x=_?.[1]??quantity(g&&printedDuration(g,e)),S=x&&[micros(x),1000000n],C=S?value(S):0;limits(`duration`,t.duration,S,C,` s`,`duration`,``,e=>`${digits(S,e)}`);let w=t.sizeBasis===`display`,T=Math.abs(g?.rotation)%180==90,E=g?w?[g.displayWidth,g.displayHeight]:T?[g.height,g.width]:[g.width,g.height]:[0,0],D=E.every(whole),[O,k]=D?E:[0,0],A=w?`display size${g?.displayWidth===void 0?` (needs codecConfig: true and withAspect)`:``}`:`frame size`,j={Width:O,Height:k,ShortSide:Math.min(O,k),LongSide:Math.max(O,k)},M=t.frameSize;for(let[e,t]of Object.entries(j))limits(`frameSize`,{min:M?.[`min${e}`],max:M?.[`max${e}`]},D?[BigInt(t),1n]:null,t,` px`,A,e);let N=w&&fromRational(g?.displayAspectRatio),P=N?T||g.displayHeight!==g.height?[N[1],N[0]]:N:[BigInt(O),BigInt(k)];if(limits(`aspectRatio`,t.aspectRatio,D?P:null,fraction(P),``,A,``,()=>`${O}x${k} (${digits(P,[])})`),limits(`pixels`,t.pixels,D?[BigInt(O)*BigInt(k),1n]:null,O*k,` px`,A),limits(`fileSize`,t.fileSize,quantity(e?.size),e?.size??``,` bytes`,`file size`),allow(`containers`,t.containers,e?.container,`container`),allow(`codecs`,t.codecs,g?.codecName,`codec name`),t.audio){let n=e?.engine,r=l.includes(n),i=e?.audioTrackCount,a=!m&&r&&Number.isSafeInteger(i)&&i>=0?i>0:null,o=t.audio===`required`;a===null?unknown(`audio`,`audio track count${!r&&typeof n==`string`?` (the ${n} engine reports none)`:``}`):a!==o&&add(`audio`,u,t.audio,a,`${t.audio}, the file has ${o?`no`:`an`} audio track`)}let F=policy(`vfr`,g?.isVfr,`VFR flag`,`the frame rate is variable`),I=g?.rateProfile,L=record(I)&&typeof I.summary==`string`?`: ${I.summary}`:``,R=policy(`uneven`,g&&unevenOf(g),`${I==null?``:`uneven flag in the `}rate profile`,`the frame rate is uneven${L}`),z=g?.color;policy(`hdr`,record(z?.dolbyVision)||z?.hdr===`pq`||z?.hdr===`hlg`||(typeof z?.transfer==`string`&&z.transfer&&z.transfer!==`reserved`?!1:null),z===void 0?`color (needs codecConfig: true and withColor)`:z?`transfer in codecConfig`:`color in codecConfig`,`the video is HDR`);let B={verdict:`pass`,violations:r},V=r.some(e=>e.rule.startsWith(`fps.`));if(g&&(V||F||R)){let e=V?y:fromRational(g.dominantFps?.rate)??fromRational(g.nominalFps),n=Math.round(g.avgFps?.value??0),r=fit(e??[whole(n)?BigInt(n):0n,1n],t.fps),i=V?`${fpsText(y,r?[r[0]]:[])} fps is not allowed`:`the frame rate is ${F?`variable`:`uneven`}`;if(!r)B.suggestedFps={value:null,reason:`${i}, and no frame rate meets every bound of the fps rule`};else if(r[0][0]>0n){let[e,t]=r,n=t>1?`, which keeps 1 of every ${t} frames`:``;B.suggestedFps={value:value(e),reason:`${i}: ${V?`convert to`:`re-encode at a constant`} ${fpsText(e)} fps${n}`}}}return B.verdict=[`fail`,`unknown`,`warn`].find(e=>r.some(t=>t.severity===e))??`pass`,B}exports.check=check;
@@ -0,0 +1 @@
1
+ const e=require("./reader-Dw11ozVU.cjs");var IsoBmffError=class extends Error{constructor(e,t){super(t),this.name=`IsoBmffError`,this.errorCode=e}};function readBoxHeader(t,n,r,i=0){let a=Math.min(t.byteLength,r);if(n+8>a)return null;let o=t.getUint32(n),s=e.n(t,n+4),c=8,l=o;if(o===1){if(n+16>a)return null;let e=t.getBigUint64(n+8);if(e>BigInt(2**53-1))throw new IsoBmffError(`corrupt`,`corrupt file: box '${s}' at ${i+n} has a size above 2^53-1`);l=Number(e),c=16}else o===0&&(l=r-n);if(s===`uuid`&&(c+=16),l<c)throw new IsoBmffError(`corrupt`,`corrupt file: box '${s}' at ${i+n} is smaller than its header`);let u=n+l;return{type:s,start:n,size:l,headerSize:c,end:Math.min(u,r),truncated:u>r}}function*childBoxes(e,t,n,r){let i=t;for(;i+8<=n;){let t;try{t=readBoxHeader(e,i,n)}catch(e){r?.push(e.message.replace(/^corrupt file: /,`ignored invalid child: `));return}if(!t)return;yield t,i=t.start+t.size}}function boxU64(e,t,n,r){let i=e.getBigUint64(t);if(i>BigInt(2**53-1))throw new IsoBmffError(`unsupported`,`unsupported: box '${n}' at ${r} holds a value above 2^53-1`);return Number(i)}function boxI64(e,t,n,r){let i=e.getBigInt64(t);if(i>BigInt(2**53-1)||i<-BigInt(2**53-1))throw new IsoBmffError(`unsupported`,`unsupported: box '${n}' at ${r} holds a value beyond 2^53-1`);return Number(i)}function boundEntries(e,t,n,r,i){let a=Math.max(0,Math.floor(t/n));return e>a?(i.push(`${r} declares ${e} entries but its box holds only ${a}`),a):e}Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return childBoxes}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return boxU64}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return boundEntries}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return readBoxHeader}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return boxI64}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return IsoBmffError}});
@@ -0,0 +1 @@
1
+ const e=require("./guards-DbQNcAZS.cjs"),t=require("./reader-Dw11ozVU.cjs"),n=require("./boxes-B0T2nt3e.cjs"),r=require("./rational-Dq5Vza-Q.cjs");let i=null;function videoTags(){if(i)return i;i=new Map;for(let e of`rawvideo:raw yuv22vuyyuvs|v210:v210|mjpeg:jpegmjpaAVDJAVRndmb1|mpeg4:mp4vDIVXXVID3IV2|h263:h263s263H263|dvvideo:dvcpdvc dvppdv5pdv5nAVdvAVd1dvhqdvhpdvh1dvh2dvh3dvh4dvh5dvh6|qtrle:rle |cinepak:cvid|svq1:SVQ1svq1svqi|svq3:SVQ3|vvc:vvc1vvi1|hevc:hev1hvc1dvhe|h264:avc1avc2avc3avc4ai5pai5qai52ai53ai55ai56ai1pai1qai12ai13ai15ai16AVinaivxdva1dvav|evc:evc1|vp8:vp08|vp9:vp09|av1:av01|mpeg1video:m1v m1v1mpegmp1v|mpeg2video:m2v1hdv1hdv2hdv3hdv4hdv5hdv6hdv7hdv8hdv9hdvamx5nmx5pmx4nmx4pmx3nmx3pxd51xd54xd55xd59xd5axd5bxd5cxd5dxd5exd5fxdv1xdv2xdv3xdv4xdv5xdv6xdv7xdv8xdv9xdvaxdvbxdvcxdvdxdvexdvfxdhdxdh2AVmpmp2v|jpeg2000:mjp2|png:png MNG |gif:gif |tiff:tiff|vc1:vc-1|cavs:avs2|avs3:avs3|dirac:drac|dnxhd:AVdnAVdh|prores:apchapcnapcsapcoap4hap4x|prores_raw:aprnaprh|hap:Hap1Hap5HapYHapAHapM|cfhd:CFHD|lcevc:lvc1|apv:apv1`.split(`|`)){let t=e.indexOf(`:`),n=e.slice(0,t);for(let r=t+1;r+4<=e.length;r+=4)i.set(e.slice(r,r+4),n)}return i}const a={32:`mpeg4`,33:`h264`,35:`hevc`,51:`vvc`,96:`mpeg2video`,97:`mpeg2video`,98:`mpeg2video`,99:`mpeg2video`,100:`mpeg2video`,101:`mpeg2video`,106:`mpeg1video`,108:`mjpeg`,109:`png`,110:`jpeg2000`,163:`vc1`,164:`dirac`,177:`vp9`};function isVideoFourcc(e){return videoTags().has(e)}function codecNameFor(e,t=null,n=!1){return t!==null&&a[t]?a[t]:e===`dvh1`&&n?`hevc`:videoTags().get(e)??`unknown`}const o=`no trex: sample defaults taken from tfhd`;function trunRecordSize(e){let t=0;for(let n=256;n<=2048;n<<=1)e&n&&(t+=4);return t}function parseTfhd(e,r,i,a,o,s,c=o+r-8){if(r+8>i)return null;let l=t.r(e,r+1),u=e.getUint32(r+4),d=a.trex.get(u),f=r+8,need=e=>f+e<=i,p=l&131072?o:s;if(l&1){if(!need(8))return null;p=n.i(e,f,`tfhd`,c),f+=8}l&2&&(f+=4);let m=d?d.duration:null;if(l&8){if(!need(4))return null;m=e.getUint32(f),f+=4}let h=d?d.size:0;if(l&16){if(!need(4))return null;h=e.getUint32(f)}return{flags:l,trackId:u,baseDataOffset:p,defaultDuration:m,defaultSize:h,trexMissing:!d}}function parseTrun(e,r,i,a,o,s,c,l){let u=t.r(e,r+1),d=e.getUint32(r+4),f=r+8,p=o;u&1&&(p=a.baseDataOffset+e.getInt32(f),f+=4),u&4&&(f+=4);let m=trunRecordSize(u),h;m>0?h=n.n(d,i-f,m,`trun`,c):(h=d,h>l&&(c.push(`trun count ${d} limited to ${l}`),h=l));let g=m>0&&h<d,_=!!(u&256);if(!_&&a.defaultDuration===null&&h>0)throw new n.t(`corrupt`,`corrupt file: no sample duration for track ${a.trackId}`);let v=a.defaultDuration??0,y=_?new Uint32Array(h):null,b=u&2048?new Int32Array(h):null,x=!!(u&512),S=_?0:v*h,C=p,w=0,T=0;if(m>0)for(let t=0;t<h;t++){if(_){let n=e.getUint32(f);y[t]=n,S+=n,f+=4}let n=a.defaultSize;x&&(n=e.getUint32(f),f+=4),u&1024&&(f+=4),b&&(b[t]=e.getInt32(f),f+=4),C<s&&w++,T===t&&C+n<=s&&T++,C+=n}if(!x){let e=a.defaultSize,t=Math.max(0,s-p);w=e>0?Math.min(h,Math.ceil(t/e)):Math.min(h,t),T=e>0?Math.min(h,Math.floor(t/e)):w,C=p+e*h}return{fragment:{moofIndex:0,baseDts:null,count:h,durations:y,defaultDuration:v,cts:b,durationSum:S,present:w,complete:T,trexMissing:a.trexMissing,overrun:g},dataEnd:C}}function parseMoof(e,t,r,i,a,s){let c=r,l=!1,reject=e=>{a.ffprobeReject||={moof:i,reason:e}},u=new Map;for(let e of a.tracks)u.has(e.id)||u.set(e.id,e);for(let d of n.a(e,t.start+t.headerSize,t.end,a.warnings)){if(d.type!==`traf`)continue;let t=null,f,p=null,m=0;for(let h of n.a(e,d.start+d.headerSize,d.end,a.warnings)){let d=h.start+h.headerSize;if(h.type===`tfhd`){if(t=parseTfhd(e,d,h.end,a,r,c,r+h.start),!t)continue;t.trackId===0?reject(`rejects this file: tfhd with track_ID 0`):t.trexMissing||(l=!0),m=t.baseDataOffset,f=u.get(t.trackId),f||a.warnings.push(`fragment for unknown track ${t.trackId}`)}else if(h.type===`tfdt`&&d+8<=h.end)p=e.getUint8(d)===1&&d+12<=h.end?n.i(e,d+4,`tfdt`,r+h.start):e.getUint32(d+4);else if(h.type===`trun`&&d+8<=h.end){if(l?(!t||t.trexMissing)&&reject(`misreads this file: a traf without trex is read as another track`):reject(`rejects this file: trun without a tfhd that has a trex`),!t||!f)continue;let n=f,{fragment:r,dataEnd:u}=parseTrun(e,d,h.end,t,m,a.fileSize,n.warnings,s);r.moofIndex=i,r.baseDts=p,p=null,m=u,c=u,r.trexMissing&&!n.warnings.includes(o)&&n.warnings.push(o),n.fragments.push(r)}}}}function parseSidx(e,t,r){let i=t.start+t.headerSize,a=i<t.end&&e.getUint8(i)===1;if(i+(a?32:24)>t.end)throw new n.t(`corrupt`,`corrupt file: box 'sidx' at ${r} is truncated`);let o=i+12,s=a?n.i(e,o,`sidx`,r):e.getUint32(o),c=a?n.i(e,o+8,`sidx`,r):e.getUint32(o+4);o+=a?16:8;let l=e.getUint16(o+2);o+=4;let u=r+(t.end-t.start),d=u+c,f=0,p=!1,m=[];for(let n=0;n<l&&o+12<=t.end;n++,o+=12){let t=e.getUint32(o);t&2147483648&&(p=!0);let n=t&2147483647;m.push([d,n]),d+=n,f+=e.getUint32(o+4)}return{start:r,end:u,referenceId:e.getUint32(i+4),timescale:e.getUint32(i+8),earliestPts:s,firstOffset:c,coverageEnd:d,durationSum:f,subsegments:m,hierarchical:p}}const s=2**53-1,c=[65536,0,0,0,65536,0,0,0,1<<30];function newMovie(e){return{fileSize:e,brand:null,compatibleBrands:[],hasFtyp:!1,hasMvhd:!1,timescale:1,duration:0,matrix:Int32Array.from(c),tracks:[],chapterTrackIds:new Set,hasMvex:!1,trex:new Map,moofCount:0,topLevel:[],truncated:!1,ffprobeMoofLimit:1/0,ffprobeReject:null,warnings:[]}}function newTrack(){return{id:0,enabled:!1,handler:``,timescale:0,hasMdhd:!1,mdhdDuration:0,matrix:Int32Array.from(c),sampleEntry:``,originalFormat:null,stsdCount:0,width:0,height:0,esdsObjectType:null,hasHvcc:!1,sttsCounts:new Uint32Array,sttsDeltas:new Uint32Array,cttsCounts:null,cttsOffsets:null,dtsShift:0,sampleCount:null,sampleSize:0,overruns:[],edits:[],fragments:[],warnings:[],dv:null,stss:null,stsz:null,stz2:null,stsc:null,stco:null,co64:null}}function children(e,t,r,i=0){return guard(n.a(e,t.start+t.headerSize+i,t.end,r.warnings),r,t.type)}function*guard(e,t,r){for(let i of e){if(i.truncated){if(t.strict)throw new n.t(`truncated`,`incomplete file: moov is truncated`);t.warnings.push(`'${i.type}' overruns '${r}'`)}yield i}}function payload(e){return e.start+e.headerSize}function readMatrix(e,t){let n=new Int32Array(9);for(let r=0;r<9;r++)n[r]=e.getInt32(t+r*4);return n}function normalizeTimescale(e){return e>0&&e<=2147483647?e:1}function tableRef(e){return{start:payload(e),end:e.end}}function parseStts(e,t,r){let i=payload(t);if(i+8>t.end)return;let a=e.getUint32(i+4),o=n.n(a,t.end-i-8,8,`stts`,r.warnings);o<a&&r.overruns.push(`stts`);let s=new Uint32Array(o),c=new Uint32Array(o),l=!1;for(let t=0;t<o;t++)s[t]=e.getUint32(i+8+t*8),c[t]=e.getUint32(i+12+t*8),c[t]>4294487295&&(l=!0);l&&correctLargeDeltas(s,c,r.warnings),r.sttsCounts=s,r.sttsDeltas=c}function correctLargeDeltas(e,t,n){let r=0n,i=0n;for(let a=0;a<e.length;a++){let o=BigInt(e[a]),s=t[a];if(s>4294487295){n.push(`stts delta ${s} clipped to 1`);let e=s|0;s=1,i+=BigInt(e<0?e:1)*o}else i+=BigInt(s)*o;if(r+=BigInt(s)*o,r>i){let e=(r-i)/(o>0n?o:1n),t=BigInt(s)>e?e:BigInt(s-1>>>0);r-=t*o,s=Number(BigInt(s)-t&4294967295n)}t[a]=s}}function parseCtts(e,t,r){let i=payload(t);if(i+8>t.end)return;let a=e.getUint32(i+4),o=n.n(a,t.end-i-8,8,`ctts`,r.warnings);if(o<a&&r.overruns.push(`ctts`),o===0)return;let s=[],c=[],l=0;for(let t=0;t<o;t++){let n=e.getInt32(i+8+t*8),r=e.getInt32(i+12+t*8);n<=0||(s.push(n),c.push(r),t+2<a&&r<0&&(l=Math.max(l,r===-2147483648?2147483647:-r)))}r.cttsCounts=Uint32Array.from(s),r.cttsOffsets=Int32Array.from(c),r.dtsShift=l}function parseElst(e,t,r,i,a){let o=payload(t);if(o+8>t.end)return;let c=e.getUint8(o),l=c===1?20:12,u=e.getUint32(o+4),d=t.end-o-8,f=u*l===d?u:Math.floor(d/l);if(f!==u&&r.warnings.push(`elst declares ${u} entries but its box holds ${f}`),f===0)return;r.edits.length&&(r.warnings.push(`duplicated elst: the last one is used`),r.edits=[]);let p=i.base+t.start;for(let t=0;t<f;t++){let i=o+8+t*l;if(c===1){let t=n.r(e,i+8,`elst`,p),o=e.getBigInt64(i)===-1n;o&&(r.warnings.push(`unknown elst duration: ${t===-1?`the empty edit is ignored`:`the edit lasts to the end`}`),a.ffprobeReject??={moof:-1,reason:`rejects this file: an elst duration of -1`}),r.edits.push({duration:o?t===-1?0:s:n.i(e,i,`elst`,p),mediaTime:t,rate:e.getInt32(i+16)/65536})}else r.edits.push({duration:e.getUint32(i),mediaTime:e.getInt32(i+4),rate:e.getInt32(i+8)/65536})}}function parseEsds(e,t,n){let r=t+4,descriptor=()=>{if(r+2>n)return null;let t=e.getUint8(r++),i=0;for(let t=0;t<4&&r<n;t++){let t=e.getUint8(r++);if(i=i*128+(t&127),!(t&128))break}return[t,i]},i=descriptor();if(i&&i[0]===3){if(r+3>n)return null;let t=e.getUint8(r+2);r+=3,t&128&&(r+=2),t&64&&r<n&&(r+=1+e.getUint8(r)),t&32&&(r+=2),i=descriptor()}return i&&i[0]===4&&r<n?e.getUint8(r):null}function parseStsd(e,r,i,a){let o=payload(r);if(o+8>r.end||(i.stsdCount=e.getUint32(o+4),i.stsdCount===0))return;let s;try{s=n.o(e,o+8,r.end)}catch(e){i.warnings.push(e.message);return}if(s&&(i.sampleEntry=s.type,!(i.handler===`soun`||s.start+86>s.end))){i.width=e.getUint16(s.start+32),i.height=e.getUint16(s.start+34);for(let r of n.a(e,s.start+86,s.end,a.warnings))if(r.type===`esds`)i.esdsObjectType=parseEsds(e,payload(r),r.end);else if(r.type===`hvcC`)i.hasHvcc=!0;else if(r.type===`sinf`)for(let o of n.a(e,payload(r),r.end,a.warnings))o.type===`frma`&&payload(o)+4<=o.end&&(i.originalFormat=t.n(e,payload(o)))}}function parseStbl(e,t,n,r){for(let i of children(e,t,r)){let t=payload(i);switch(i.type){case`stsd`:parseStsd(e,i,n,r);break;case`stts`:parseStts(e,i,n);break;case`ctts`:parseCtts(e,i,n);break;case`stsz`:case`stz2`:t+12<=i.end&&(n.sampleCount=e.getUint32(t+8),n.sampleSize=i.type===`stsz`?e.getUint32(t+4):0),i.type===`stsz`?n.stsz=tableRef(i):n.stz2=tableRef(i);break;case`stss`:n.stss=tableRef(i),t+8<=i.end&&e.getUint32(t+4)>Math.floor((i.end-t-8)/4)&&n.overruns.push(`stss`);break;case`stsc`:n.stsc=tableRef(i);break;case`stco`:n.stco=tableRef(i);break;case`co64`:n.co64=tableRef(i)}}}function parseMdia(e,n,r,i){for(let a of children(e,n,i)){let n=payload(a);if(a.type===`mdhd`&&n+24<=a.end){let t=e.getUint8(n)===1;if(t&&n+32>a.end)continue;r.hasMdhd=!0;let i=e.getUint32(n+(t?20:12));if(r.timescale=normalizeTimescale(i),r.timescale!==i&&r.warnings.push(`invalid mdhd timescale ${i}, using 1`),t){let t=e.getBigUint64(n+24);r.mdhdDuration=t===18446744073709551615n?0:Number(t)}else{let t=e.getUint32(n+16);r.mdhdDuration=t===4294967295?0:t}}else if(a.type===`hdlr`&&n+12<=a.end)r.handler=t.n(e,n+8);else if(a.type===`minf`)for(let t of children(e,a,i))t.type===`stbl`&&parseStbl(e,t,r,i)}}function parseTrak(e,t,n,r){let i=newTrack();i.dv=e;for(let a of children(e,t,r)){let t=payload(a);if(a.type===`tkhd`&&t+84<=a.end){let n=e.getUint8(t)===1;if(n&&t+96>a.end)continue;i.enabled=(e.getUint8(t+3)&1)==1,i.id=e.getUint32(t+(n?20:12)),i.matrix=readMatrix(e,t+(n?52:40))}else if(a.type===`edts`)for(let t of children(e,a,r))t.type===`elst`&&parseElst(e,t,i,r,n);else if(a.type===`mdia`)parseMdia(e,a,i,r);else if(a.type===`tref`){for(let t of children(e,a,r))if(t.type===`chap`)for(let r=payload(t);r+4<=t.end;r+=4)n.chapterTrackIds.add(e.getUint32(r))}}return i}function parseMoov(e,t,r,i,a=0){let o={strict:i,warnings:r.warnings,base:a};for(let i of children(e,t,o)){let t=payload(i);switch(i.type){case`mvhd`:{if(t+24>i.end)break;let n=e.getUint8(t)===1;if(n&&t+84>i.end)break;r.hasMvhd=!0,r.timescale=normalizeTimescale(e.getUint32(t+(n?20:12))),r.duration=n?Number(e.getBigUint64(t+24)):e.getUint32(t+16),t+(n?84:72)<=i.end&&(r.matrix=readMatrix(e,t+(n?48:36)));break}case`trak`:r.tracks.push(parseTrak(e,i,r,o));break;case`mvex`:r.hasMvex=!0;for(let t of children(e,i,o)){let n=payload(t);t.type===`trex`&&n+24<=t.end&&r.trex.set(e.getUint32(n+4),{duration:e.getUint32(n+12),size:e.getUint32(n+16)})}break;case`cmov`:throw new n.t(`unsupported`,`unsupported: compressed movie header (cmov)`)}}}const l=new Set([`moof`,`styp`,`sidx`,`ssix`,`emsg`,`prft`,`free`,`skip`,`uuid`]);function newPrefetch(){return{windows:[],hints:[],next:0,mfraTried:!1}}function prefetched(e,t,n){for(let[r,i]of e.windows)if(t>=r&&t+n<=r+i.byteLength)return new DataView(i.buffer,i.byteOffset+t-r,n);return null}async function prefetchNext(e,t,n,r){for(;t.next<t.hints.length&&t.hints[t.next]<=n;)t.next++;let i=[];for(let n=t.next;n<t.hints.length&&i.length<8;n++)t.hints[n]<e.size&&i.push([t.hints[n],Math.min(r,e.size-t.hints[n])]);if(t.next+=i.length,!i.length)return;let a=await e.readMany(i,4);t.windows=i.map(([e],t)=>[e,new DataView(a[t].buffer,a[t].byteOffset,a[t].byteLength)]),t.windows.every(([,e])=>startsWithFragmentBox(e))||(t.hints=[],t.next=0)}function startsWithFragmentBox(e){return e.byteLength>=8&&e.getUint32(0)>=8&&l.has(t.n(e,4))}function parseTfraOffsets(e,t,r,i,a=2**53-1){for(let o of n.a(e,t,r)){let t=o.start+o.headerSize;if(o.type!==`tfra`||t+16>o.end)continue;let n=e.getUint8(t)===1,r=e.getUint32(t+8),s=(n?16:8)+(r>>4&3)+(r>>2&3)+(r&3)+3,c=Math.min(e.getUint32(t+12),Math.floor((o.end-t-16)/s));for(let r=0;r<c;r++){let o=t+16+r*s,c=n?e.getBigUint64(o+8):BigInt(e.getUint32(o+4));c>0n&&c<BigInt(a)&&i.add(Number(c))}}}async function mfraMoofOffsets(e){try{return await readMfraOffsets(e)}catch(t){if(e.signal?.aborted||t?.name===`AbortError`)throw t;return[]}}async function readMfraOffsets(e){let r=e.size,i=Math.min(r,65536);if(i<16)return[];let a=await e.view(r-i,i,0);if(t.n(a,i-12)!==`mfro`)return[];let o=a.getUint32(i-4);if(o<24||o>Math.min(r,16777216))return[];let s=o<=i?new DataView(a.buffer,a.byteOffset+i-o,o):await e.view(r-o,o,0),c;try{c=n.o(s,0,o)}catch{return[]}if(!c||c.type!==`mfra`)return[];let l=new Set;return parseTfraOffsets(s,c.headerSize,c.end,l,r),[...l].sort((e,t)=>e-t)}function rescaleRound(e,t,n){if(!(n>0))return 0;let r=BigInt(Math.abs(e))*BigInt(t),i=BigInt(n),a=Number((r+i/2n)/i);return e<0?-a:a}function sampleTotals(e){let t=0,n=0;for(let r=0;r<e.sttsCounts.length;r++)t+=e.sttsCounts[r],n+=e.sttsCounts[r]*e.sttsDeltas[r];let r=0;for(let t of e.fragments)r+=t.count;return{moovSamples:t,moovDuration:n,fragmentSamples:r}}function sumBig(e,t,n){let r=0n,i=0n;if(n){for(let t=0;t<e.sttsCounts.length;t++)r+=BigInt(e.sttsCounts[t]),i+=BigInt(e.sttsCounts[t])*BigInt(e.sttsDeltas[t]);i<=0n&&(r=0n,i=0n)}for(let n of e.fragments)t(n.moofIndex,n.trexMissing)&&(r+=BigInt(n.count),i+=BigInt(n.durationSum));return[r,i]}function rateOf(e,t,n){return t<=0n||n<=0n?null:r.a(BigInt(e)*t,n,r.t)}function averageRates(e,t){let n=e.timescale,visible=(e,n)=>e<t.ffprobeMoofLimit&&!n,[i,a]=sumBig(e,()=>!0,!0),[o,s]=sumBig(e,visible,!0),c=e.overruns.includes(`stts`)||e.fragments.some(e=>e.overrun&&visible(e.moofIndex,e.trexMissing))?null:rateOf(n,o,s);return{avg:rateOf(n,i,a),ffprobe:c?r.o(c):null}}function missingMandatoryAtoms(e){let t=e.dv,declared=e=>t&&e&&e.start+8<=e.end?t.getUint32(e.start+4):0,n=declared(e.co64??e.stco),r=e.sttsCounts.length>0||e.overruns.includes(`stts`),i=e.sampleCount??0;return n>0&&(!r||declared(e.stsc)===0||e.sampleSize===0&&i===0)||i>0&&n===0}function editInfo(e,t,n){let r=0,i=0,a=0,o=null,c=(e.cttsOffsets?.[0]??0)+n.moovDuration;for(let n of e.edits){let l=n.duration===s?Math.max(0,c-n.mediaTime):rescaleRound(n.duration,e.timescale,t);i+=l,n.mediaTime===-1?o||(r+=l):(a++,o||={mediaTime:n.mediaTime,duration:l,rate:n.rate})}return{emptyBefore:r,firstMedia:o,editSum:i,mediaEdits:a}}function trackTiming(e,t,n,r){let i=e.mdhdDuration;n.moovDuration>0&&(i=Math.min(i,n.moovDuration));let a=e.edits.length>0&&n.moovSamples>0;a&&(i=Math.min(i,r.editSum));let o=n.moovDuration,s=null,c=timeOffsetOf(e,t);for(let t of e.fragments)t.baseDts!==null&&(o=t.baseDts),s===null&&t.count>0&&(s=o-c+(t.cts?t.cts[0]:0)),o+=t.durationSum,o>i&&(i=o);let l=completeSidxEnd(e,t);l!==null&&l>i&&(i=l);let u=null;return u=a?r.emptyBefore:n.moovSamples>0?e.cttsOffsets&&e.cttsOffsets.length?e.cttsOffsets[0]:0:s,{durationTs:i,startPts:u}}function completeSidxEnd(e,t){if(t.ffprobeMoofLimit===1/0)return null;let n=0,r=null;for(let i of t.topLevel){if(i.type===`moof`&&++n>t.ffprobeMoofLimit)break;let a=i.sidx;a&&!a.hierarchical&&a.referenceId===e.id&&a.timescale===e.timescale&&(r=a.earliestPts+a.durationSum)}return r}function timeOffsetOf(e,t){let n=0,r=0,i=0;return e.edits.forEach((e,t)=>{t===0&&e.mediaTime===-1?(n=e.duration,i=1):t===i&&e.mediaTime>=0&&(r=e.mediaTime)}),!n&&!r?0:r-rescaleRound(n,e.timescale,t.timescale)}function runsOf(e,t,n){let r=new Float64Array(e.length+1),i=new Float64Array(e.length),a=0,o=0;for(let s=0;s<e.length&&o<n;s++)e[s]<=0||(r[a]=o,i[a]=t[s],o+=Math.min(e[s],n-o),a++);return r[a]=o,{count:a,starts:r,values:i,total:o}}function runFinder(e){let t=e.starts,n=0;return r=>{if(r>=t[n]&&r<t[n+1])return n;let i=0,a=e.count-1;for(;i<a;){let e=Math.ceil((i+a)/2);t[e]<=r?i=e:a=e-1}return n=i,i}}function keyIndex(e,t){let n=e.stss;if(!n||!e.dv)return{all:!0,list:new Float64Array};let r=e.dv,i=n.start+8<=n.end?Math.min(r.getUint32(n.start+4),Math.floor((n.end-n.start-8)/4)):0;if(i===0)return{all:!1,list:Float64Array.of(0)};let a=+(r.getUint32(n.start+8)>0),o=new Float64Array(i),s=0,c=-1;for(let e=0;e<i;e++){let i=r.getUint32(n.start+8+e*4)-a;if(i<=c||i>=t)break;o[s++]=i,c=i}return{all:!1,list:o.subarray(0,s)}}function nextKeyOf(e,t,n){if(n>=t)return-1;if(e.all)return n;let r=e.list,i=0,a=r.length;for(;i<a;){let e=Math.floor((i+a)/2);r[e]<n?i=e+1:a=e}return i<r.length?r[i]:-1}function prevKeyOf(e,t){if(t<0)return-1;if(e.all)return t;let n=e.list,r=0,i=n.length;for(;r<i;){let e=Math.floor((r+i)/2);n[e]<=t?r=e+1:i=e}return r>0?n[r-1]:-1}function keep(e,t,n){let r=n;r<=0||e.len===0&&(e.first=t,e.last=t,e.len=1,r--,r===0)||((e.len>=2&&e.last!==e.first||r>=2&&t!==e.first)&&(e.bad=!0),e.last=t,e.len+=r)}function keepRange(e,t,n,r,i){let a=r,o=Math.min(i,t.total-r),s=0;for(;o>0&&!e.bad;){let r=n(a),i=Math.min(t.starts[r+1]-a,o);keep(e,t.values[r],i),a+=i,o-=i,s++}return s}function keptRate(e,t){return e.bad||e.len===0||!(e.first>0)?null:r.a(t,e.first,r.t)}function ffprobeStage1Rate(e,t,n,i,a){let o=Math.min(n,e.sampleCount??0);if(o<=0||e.sttsCounts.length===0||e.overruns.length>0)return null;let s=e.timescale,c=runsOf(e.sttsCounts,e.sttsDeltas,o),l=runFinder(c),u={len:0,first:0,last:0,bad:!1};if(e.edits.length===0)return keepRange(u,c,l,0,o),keptRate(u,s);if(!e.edits.some(e=>e.mediaTime!==-1))return null;let d=!0;for(let e=1;e<c.count&&d;e++)d=c.values[e]===c.values[0];if(d)return c.values[0]>0?r.a(s,c.values[0],r.t):null;let f=Math.min(i,2e6),p=0,m=!1,spend=e=>(p+=e,p>f&&(m=!0),m),h=new Float64Array(c.count+1);for(let e=0;e<c.count;e++)h[e+1]=h[e]+(c.starts[e+1]-c.starts[e])*c.values[e];let dtsAt=e=>{let t=l(e);return h[t]+(e-c.starts[t])*c.values[t]},durAt=e=>c.values[l(e)],g=!!e.cttsCounts&&e.cttsCounts.length>0,_=g?runsOf(e.cttsCounts,e.cttsOffsets,o):null,v=_?runFinder(_):null,offAt=e=>_&&e<_.total?_.values[v(e)]:0,y=keyIndex(e,o),nextKey=e=>nextKeyOf(y,o,e),prevKey=e=>prevKeyOf(y,e),b=e.dtsShift,firstAtOrAbove=(e,t)=>{let n=0,r=t;for(;n<r;){let t=Math.floor((n+r)/2);dtsAt(t)>=e?r=t:n=t+1}return n},search=(e,t)=>{let n=b>0?e-b:e,r=-1,i=o;for(dtsAt(o-1)-b<n&&(r=o-1);i-r>1;){let e=Math.floor((r+i)/2),t=dtsAt(e)-b;t>=n&&(i=e),t<=n&&(r=e)}let a=t?r:prevKey(r);if(a>0){let e=firstAtOrAbove(dtsAt(a),a);if(e<a){if(t)a=e;else{let t=nextKey(e);t>=0&&t<a&&(a=t)}}}if(g&&a>=0){let e=prevKey(a);for(;e>=0&&!spend(1)&&dtsAt(e)-b+offAt(e)>n;)e=prevKey(e-1);a=e}return a},x=0,S=!1;for(let n of e.edits){let r=n.mediaTime;if(!S&&r===-1)continue;if(S=!0,spend(64))break;let i=rescaleRound(n.duration,e.timescale,t.timescale),a=search(r,!1);if(a<0&&!m&&(a=search(r,!0)),m)break;a<0&&(a=0,x=0),g&&(x=a);let s=-1;if(g){let e=!1;for(let t=nextKey(a);t>=0&&!spend(1);t=nextKey(t+1)){let n=t+1<o?durAt(t):i;if(dtsAt(t)+offAt(t)+n>=i+r){if(e){s=t;break}e=!0}}if(m)break}else{let e=a,t=o;for(;e<t;){let n=Math.floor((e+t)/2);(n+1<o?dtsAt(n+1):dtsAt(o-1)+i)>=i+r?t=n:e=n+1}e<o&&(s=nextKey(e))}let d=s<0?o-a:s-a+1,f=Math.min(d,o-x);if(f>0&&(spend(keepRange(u,c,l,x,f)),x+=f),u.bad)return null;if(m)break}return m?(a?.push(`r_frame_rate not reproduced: edit list walk limit reached`),null):keptRate(u,s)}function cutRuns(e,t,n){let r=[],i=[],a=n;for(let n=0;n<e.length&&a>0;n++){let o=Math.min(e[n],a);o<=0||(r.push(o),i.push(t[n]),a-=o)}return{counts:r,values:i}}function timelineSegments(e,t){let n=[];if(t>0){let r=cutRuns(e.sttsCounts,e.sttsDeltas,t),i=e.cttsCounts&&e.cttsOffsets?cutRuns(e.cttsCounts,e.cttsOffsets,t):null;n.push({durations:{counts:r.counts,deltas:r.values},cts:i?{counts:i.counts,offsets:i.values}:null})}for(let t of e.fragments){let e=t.complete;n.push({baseDts:t.baseDts,durations:t.durations?t.durations.subarray(0,e):{counts:[e],deltas:[t.defaultDuration]},cts:t.cts?t.cts.subarray(0,e):null})}return n}function presentationWindow(e,t,n){let r=t.firstMedia;if(!r)return e.edits.length&&n.push(`edit list has no media edit`),null;t.mediaEdits>1&&n.push(`edit list has ${t.mediaEdits} media edits, only the first is applied`),r.rate!==1&&n.push(`edit rate ${r.rate} is not applied`);let i=e.fragments.length>0||r.duration<=0?r.mediaTime:r.mediaTime+r.duration;return{start:r.mediaTime,end:i}}function moovSamplesInFile(e,t,n){let r=e.dv,i=e.co64??e.stco,a=e.stsz??e.stz2;if(!r||!i||!a||!e.stsc||i.start+8>i.end||e.stsc.start+8>e.stsc.end||a.start+12>a.end)return null;let o=!!e.co64,s=Math.min(r.getUint32(i.start+4),Math.floor((i.end-i.start-8)/(o?8:4))),c=Math.min(r.getUint32(e.stsc.start+4),Math.floor((e.stsc.end-e.stsc.start-8)/12)),l=e.stsz?r.getUint32(a.start+4):0,u=e.stz2?r.getUint8(a.start+7):32,d=Math.min(r.getUint32(a.start+8),n),f=a.end-a.start-12,sizeOf=e=>{if(l)return l;let t=a.start+12;if(u===32)return(e+1)*4<=f?r.getUint32(t+e*4):0;if(u===16)return(e+1)*2<=f?r.getUint16(t+e*2):0;if(u===8)return e<f?r.getUint8(t+e):0;let n=e>>1<f?r.getUint8(t+(e>>1)):0;return e&1?n&15:n>>4},p=0,m=0,h=0,g=0;for(let n=0;n<s&&h<d;n++){for(;g+1<c&&r.getUint32(e.stsc.start+8+(g+1)*12)<=n+1;)g++;let a=c?r.getUint32(e.stsc.start+12+g*12):0,s=o?Number(r.getBigUint64(i.start+8+n*8)):r.getUint32(i.start+8+n*4);for(let e=0;e<a&&h<d;e++,h++){let e=sizeOf(h);s<t&&p++,s+e<=t&&m===h&&m++,s+=e}}return{present:p,complete:m}}function displayRotation(e,t){let n=[16n,16n,30n],r=new Int32Array(9);for(let i=0;i<3;i++)for(let a=0;a<3;a++){let o=0n;for(let r=0;r<3;r++)o+=BigInt(e[i*3+r])*BigInt(t[r*3+a])>>n[r];r[i*3+a]=Number(BigInt.asIntN(32,o))}if(r[0]===65536&&r[4]===65536&&r[8]===1<<30&&!r[1]&&!r[2]&&!r[3]&&!r[5]&&!r[6]&&!r[7])return 0;let i=r[0]/65536,a=r[1]/65536,o=Math.hypot(i,r[3]/65536),s=Math.hypot(a,r[4]/65536);return o===0||s===0?0:Math.trunc(-(Math.atan2(a/s,i/o)*180/Math.PI))||0}const u=16777216,d=65536;function isAbort(e,t){return t.signal?.aborted===!0||e?.name===`AbortError`}function containerOf(e){return e.brand===`qt `||!e.hasFtyp&&e.topLevel.length>0?`mov`:`mp4`}async function readMoov(e,t,r,i){let a=e.size,o=t.start+t.size>a;if(!o&&t.size>268435456)throw new n.t(`too-large`,`unsupported: moov larger than 256 MiB`);let s=o?Math.min(a-t.start,u):t.size,c=await e.view(t.start,s,0),l=i?new DataView(c.buffer.slice(c.byteOffset,c.byteOffset+s)):c,d=n.o(l,0,l.byteLength);if(!d)throw new n.t(`truncated`,`incomplete file: moov is truncated`);parseMoov(l,d,r,o,t.start),o&&r.warnings.push(`moov size exceeds the file; parsed what is there`)}async function walk(e,t,r){let i=e.size,a=0,o=t.readAhead.head,s=!1,c=0,l=!1,u=newPrefetch(),look=async(t,n,r)=>prefetched(u,t,n)??e.view(t,n,r);for(;a+8<=i;){if(e.checkAbort(),++c>4e6){r.warnings.push(`too many top-level boxes`);break}let f=l&&!s&&i-a<=16777216?i-a:o,p=await look(a,Math.min(16,i-a),f),m;try{m=n.o(p,0,i-a,a)}catch(e){if(!s)throw e;r.warnings.push(`ignored trailing data at ${a}: ${e.message}`);break}if(!m)break;let h={...m,start:a,end:Math.min(a+m.size,i)},g=a+m.size,_=m.truncated&&s&&h.type!==`mdat`&&h.type!==`moof`;m.truncated&&(r.truncated=!0,r.warnings.push(_?`ignored trailing data at ${a}: not a box`:`'${h.type}' at ${a} is truncated`));let v={type:h.type,start:a,end:h.end,sidx:null};if(r.topLevel.push(v),_)break;if(h.type===`ftyp`){let t=await e.view(a,Math.min(h.size,1024)),n=h.headerSize;if(n+4<=t.byteLength){r.hasFtyp=!0,r.brand=String.fromCharCode(t.getUint8(n),t.getUint8(n+1),t.getUint8(n+2),t.getUint8(n+3));for(let e=n+8;e+4<=t.byteLength;e+=4)r.compatibleBrands.push(String.fromCharCode(t.getUint8(e),t.getUint8(e+1),t.getUint8(e+2),t.getUint8(e+3)))}}else if(h.type===`moov`)s?r.warnings.push(`ignored a second moov at ${a}`):(r.moov=[a,m.size],await readMoov(e,h,r,t.codecConfig),s=!0);else if(h.type===`moof`){if(!s)throw new n.t(`corrupt`,`corrupt file: movie fragment (moof) before moov`);if(h.size>67108864)throw new n.t(`too-large`,`corrupt file: moof larger than 64 MiB at ${a}`);let c=Math.min(h.size+16,i-a),l=await look(a,c,0),f=n.o(l,0,Math.min(h.size,l.byteLength));f&&parseMoof(l,f,a,r.moofCount,r,t.maxExpandedSamples),r.moofCount++;let p=0;try{let e=n.o(l,h.size,l.byteLength);e&&e.type===`mdat`&&(p=e.size)}catch{p=0}o=p<=d?t.readAhead.fragment:Math.min(65536,Math.max(1024,2*h.size+64)),p>d&&(!u.hints.length&&!u.mfraTried&&(i-a)/(h.size+p)>16&&(u.mfraTried=!0,u.hints=await mfraMoofOffsets(e)),u.next<u.hints.length&&!prefetched(u,a+h.size+p,16)&&await prefetchNext(e,u,a,o)),t.onProgress&&r.moofCount%64==0&&t.onProgress({phase:`fragments`,done:a,total:i})}else if(h.type===`sidx`&&!m.truncated){let e=await look(a,h.size,0),t=n.o(e,0,e.byteLength);t&&(v.sidx=parseSidx(e,t,a)),v.sidx&&v.sidx.subsegments.length>1&&!u.hints.length&&(u.hints=v.sidx.subsegments.map(([e])=>e))}else if(h.type===`mfra`)break;l=h.type===`mdat`,a=g}if(!s)throw new n.t(`no-header`,`incomplete file: no moov`)}async function emulateFfprobeExtent(e,t){let n=e.size,r=new Set(t.tracks.map(e=>e.id)),i=!1,a=!1,o=!1,s=null,c=0;for(let l of t.topLevel){if(l.type===`moof`)c++;else if(l.type===`moov`)i=!0;else if(l.type===`mdat`&&l.end-l.start>8)a=!0;else if(l.type===`sidx`&&i&&l.sidx&&!l.sidx.hierarchical&&r.has(l.sidx.referenceId)){let t=l.sidx.coverageEnd===n;!t&&n>=4&&(s===null&&(s=(await e.view(n-4,4,0)).getUint32(0)),t=l.sidx.coverageEnd===n-s),t&&l.sidx.firstOffset===0&&(o=!0)}if(i&&a&&(o||l.end===n)){t.ffprobeMoofLimit=c;return}}}function layoutOf(e){let t=1/0,n=!1,r=!1;for(let i of e.topLevel)i.type===`mdat`&&(t=Math.min(t,i.start)),n||=i.type===`moof`,r||=!n&&i.type===`sidx`;let i=e.moov,a=i?i[0]:1/0;if(a===t)return null;let o=e.hasMvex?`fragmented`:t<a?`moov-at-end`:`faststart`;return{kind:o,moovOffset:i?a:null,moovSize:i?i[1]:null,sidx:r,emptyMoov:o===`fragmented`&&e.tracks.every(t=>!isVideoTrack(t,e)||!t.sampleCount)}}function isVideoTrack(e,t){return t.chapterTrackIds.has(e.id)?!1:e.handler===`vide`||e.handler!==`soun`&&isVideoFourcc(e.originalFormat??e.sampleEntry)}const f=[`presentedFrames`,`minFps`,`maxFps`,`medianFrameInterval`,`isVfr`,`vfrRatio`,`distinctDeltas`,`duplicateTimestamps`,`nominalFps`,`dominantFps`,`timestampsQuantized`];function buildVideoTrack(t,n,i,a,o){let s=e.l(a.reportedId),c=s.warnings;a.reportedId!==t.id&&c.push(`duplicate track_ID ${t.id}: reported as ${a.reportedId}`),c.push(...t.warnings);let l=t.handler===`auxv`;l&&c.push(`auxiliary video track (handler 'auxv')`);let u=missingMandatoryAtoms(t);u&&c.push(`missing mandatory sample tables: ffprobe ignores the samples and timing of this track`);let d=t.hasMdhd?t.timescale:n.timescale;t.hasMdhd||(c.push(`no mdhd: using the movie timescale`),t.timescale=d),s.fourccOrCodecId=t.sampleEntry,s.codecName=codecNameFor(t.originalFormat??t.sampleEntry,t.esdsObjectType,t.hasHvcc),t.originalFormat&&c.push(`encrypted: ${t.sampleEntry} of ${t.originalFormat}`),t.stsdCount>1&&c.push(`${t.stsdCount} sample descriptions, first used`),s.width=t.width,s.height=t.height,s.rotation=displayRotation(t.matrix,n.matrix),s.enabled=t.enabled,s.timescale=d,i.codecConfig&&(s.codecConfig={family:`isobmff-moov`,moov:t.dv,trak:n.tracks.indexOf(t)});let p=sampleTotals(t),m=n.truncated,h=0;for(let e of t.fragments)h+=e.present;let g=p.moovSamples+p.fragmentSamples,_=p.moovSamples+h;s.frames=_,s.isStill=_<=1,p.moovSamples>0&&t.fragments.length>0&&c.push(`hybrid fragmented file: moov holds ${p.moovSamples} of ${g} samples`),_<g&&c.push(`truncated: ${g-_} of ${g} samples missing`);let v=averageRates(t,n);s.avgFps=v.avg,s.avgFpsFfprobe=a.ffprobeFails?null:v.ffprobe,s.avgFpsFfprobe!==null&&s.avgFpsFfprobe!==r.o(v.avg)&&c.push(`ffprobe reads part of the fragments: avg_frame_rate ${s.avgFpsFfprobe}`),v.ffprobe===null&&!a.ffprobeFails&&g>0&&c.push(`avg_frame_rate of ffprobe is not reproduced: its header values are incomplete or overrun a box`);let y=!o||a.ffprobeFails||u?null:ffprobeStage1Rate(t,n,p.moovSamples,i.maxExpandedSamples,c);s.rFpsFfprobe=y?r.o(y):null;let b=editInfo(t,n.timescale,p);if(!u){let e=trackTiming(t,n,p,b);s.durationSec=e.durationTs/d,s.startSec=e.startPts===null?null:e.startPts/d}let x=p.moovSamples;if(t.sampleCount!==null&&t.sampleCount<x&&(c.push(`stts describes ${x} samples but the sample size table holds ${t.sampleCount}`),x=t.sampleCount),u||!o)return s.presentedFrames=0,finishProvenance(s),{result:s,enabled:t.enabled,auxiliary:l};if(m&&x>0){let e=moovSamplesInFile(t,n.fileSize,p.moovSamples);e&&e.complete<x&&(c.push(`truncated: ${e.complete} of ${x} samples complete`),x=e.complete)}let S=presentationWindow(t,b,c);S&&!t.cttsCounts&&!t.fragments.length&&S.start<=0&&(S.end<=S.start||S.end>=p.moovDuration)&&(S=null);let C=o({segments:timelineSegments(t,x),timescale:d,editWindow:S,maxExpandedSamples:i.maxExpandedSamples});c.push(...C.warnings);for(let e of f)s[e]=C[e];return C.presentedAvgFps&&(s.avgFps=C.presentedAvgFps),s.duplicateTimestamps>0&&c.push(`${s.duplicateTimestamps} duplicate timestamps`),finishProvenance(s),C.presentedAvgFps&&(s.provenance.avgFps=`exact`),{result:s,enabled:t.enabled,auxiliary:l,profile:C.profile}}function finishProvenance(e){let t=e.provenance;for(let e of[`codec`,`dimensions`,`rotation`,`frames`,`avgFps`])t[e]=`header`;e.durationSec!==null&&(t.durationSec=`header`),e.startSec!==null&&(t.startSec=`header`),e.presentedFrames!==null&&(t.presentedFrames=`exact`),e.isVfr!==null&&(t.minFps=`exact`,t.maxFps=`exact`,t.isVfr=`exact`,t.duplicateTimestamps=`exact`,t.medianFrameInterval=`exact`),e.nominalFps&&(t.nominalFps=`exact`),e.dominantFps&&(t.dominantFps=`exact`)}function pickPrimary(e){let t=null,score=e=>(e.result.frames??0)>1?e.auxiliary?.5:e.enabled?2:1:0;for(let n of e)(!t||score(n)>score(t)||score(n)===score(t)&&(n.result.frames??0)>(t.result.frames??0))&&(t=n);return t?t.result.trackId:null}function formatDuration(e,t){let n=2**53-1,r=n,i=n,a=-n,o=-n,s=-n,c=-n;for(let n of e.tracks){if(!n.hasMdhd)continue;let l=t.has(n)||n.handler===`soun`;if(missingMandatoryAtoms(n)){let e=rescaleRound(n.mdhdDuration,1e6,9e4);l?s=Math.max(s,e):c=Math.max(c,e);continue}let u=sampleTotals(n),d=trackTiming(n,e,u,editInfo(n,e.timescale,u)),f=rescaleRound(d.durationTs,1e6,n.timescale);if(d.startPts!==null){let e=rescaleRound(d.startPts,1e6,n.timescale);l?(r=Math.min(r,e),a=Math.max(a,e+f)):(i=Math.min(i,e),o=Math.max(o,e+f))}l?s=Math.max(s,f):c=Math.max(c,f)}return(r===n||r>i&&r-i<1e6)&&(r=i),(a===-n||a<o&&o-a<1e6)&&(a=o),(s===-n||s<c&&c-s<1e6)&&(s=c),r!==n&&a!==-n&&a>=r&&(s=Math.max(s,a-r)),s>0?s/1e6:null}function reportedIds(e){let t=new Map,n=new Set,r=e.reduce((e,t)=>Math.max(e,t.id),0)+1;for(let i of e)n.has(i.id)?t.set(i,r++):(n.add(i.id),t.set(i,i.id));return t}Object.defineProperty(exports,"S",{enumerable:!0,get:function(){return parseSidx}}),Object.defineProperty(exports,"_",{enumerable:!0,get:function(){return sampleTotals}}),Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return containerOf}}),Object.defineProperty(exports,"b",{enumerable:!0,get:function(){return newMovie}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return isAbort}}),Object.defineProperty(exports,"d",{enumerable:!0,get:function(){return pickPrimary}}),Object.defineProperty(exports,"f",{enumerable:!0,get:function(){return readMoov}}),Object.defineProperty(exports,"g",{enumerable:!0,get:function(){return rescaleRound}}),Object.defineProperty(exports,"h",{enumerable:!0,get:function(){return editInfo}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return buildVideoTrack}}),Object.defineProperty(exports,"l",{enumerable:!0,get:function(){return isVideoTrack}}),Object.defineProperty(exports,"m",{enumerable:!0,get:function(){return walk}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return 268435456}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return emulateFfprobeExtent}}),Object.defineProperty(exports,"p",{enumerable:!0,get:function(){return reportedIds}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return u}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return formatDuration}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return 67108864}}),Object.defineProperty(exports,"u",{enumerable:!0,get:function(){return layoutOf}}),Object.defineProperty(exports,"v",{enumerable:!0,get:function(){return trackTiming}}),Object.defineProperty(exports,"x",{enumerable:!0,get:function(){return parseMoof}}),Object.defineProperty(exports,"y",{enumerable:!0,get:function(){return parseTfraOffsets}});
@@ -0,0 +1 @@
1
+ const e=[`apcn`,`apch`,`dvpp`,`dvcp`,`jpeg`];function u16(e,t){return e[t]<<8|e[t+1]}function u32(e,t){return(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}function i32(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function fourccAt(e,t){return String.fromCharCode(e[t],e[t+1],e[t+2],e[t+3])}function*boxes(e,t,n,r=!1){let i=t;for(;i+8<=n;){let t=u32(e,i),a=fourccAt(e,i+4),o=8;if(t===1){if(i+16>n||!r&&u32(e,i+8)!==0)return;t=u32(e,i+8)*2**32+u32(e,i+12),o=16}else t===0&&(t=n-i);if(r&&a===`uuid`&&(o+=16),t<o||t>2**53-1)return;let s=Math.min(i+t,n);yield{type:a,start:i,end:s,payload:i+o},i+=t}}function sampleEntries(t){let n=[],r=boxes(t,0,t.length).next();if(r.done||r.value.type!==`stsd`)return n;let i=r.value;if(i.payload+8>i.end)return n;let a=u32(t,i.payload+4),o=0,s=``;for(let r of boxes(t,i.payload+8,i.end)){if(o++>=a)break;if(s||=r.type,r.type!==s&&!e.includes(s)&&(s!==`AV1x`||r.type!==`AVup`))continue;let i={type:r.type,children:[]};if(n.push(i),!(r.start+86>r.end))for(let e of boxes(t,r.start+86,r.end)){if(e.type===`sinf`)for(let n of boxes(t,e.payload,e.end))n.type===`frma`&&n.payload+4<=n.end&&(i.type=fourccAt(t,n.payload));i.children.push({type:e.type,start:e.payload,end:e.end})}}return n}const live=e=>ArrayBuffer.isView(e)&&e.buffer.byteLength>0,absentOrLive=e=>e==null||live(e);function lastChild(e,t,n){let r;if(t)for(let i of boxes(e,t.payload,t.end,!0))i.type===n&&(r=i);return r}function moovBoxes(e,t){let n=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),cut=e=>e?n.subarray(e.start,e.end):null,r=boxes(n,0,n.length,!0).next().value,i,a=0;if(r?.type===`moov`){for(let e of boxes(n,r.payload,r.end,!0))if(e.type===`mvhd`)i=e;else if(e.type===`trak`&&a++===t)return{stsd:cut(lastChild(n,lastChild(n,lastChild(n,lastChild(n,e,`mdia`),`minf`),`stbl`),`stsd`)),tkhd:cut(lastChild(n,e,`tkhd`)),mvhd:cut(i)}}return null}function isoConfig(e){let t=e.family===`isobmff`?e:e.family===`isobmff-moov`&&live(e.moov)?moovBoxes(e.moov,e.trak):null;return t&&live(t.stsd)&&absentOrLive(t.tkhd)&&absentOrLive(t.mvhd)?{bytes:t.stsd,entries:sampleEntries(t.stsd),tkhd:t.tkhd,mvhd:t.mvhd}:null}function firstBox(e,t){return e?.children.find(e=>e.type===t)??null}function boxPayload(e){if(!e)return null;let t=boxes(e,0,e.length).next();return t.done?null:{start:t.value.payload,end:t.value.end}}function vint(e,t,n,r){if(t>=n)return null;let i=e[t],a=1;for(;a<=8&&!(i&128>>a-1);)a++;if(a>8||t+a>n)return null;let o=r?i:i&255>>a,s=o===255>>a;for(let n=1;n<a;n++)o=o*256+e[t+n],s&&=e[t+n]===255;return[!r&&s?-1:o,a]}function*elements(e,t,n){let r=t;for(;r<n;){let t=vint(e,r,n,!0);if(!t)return;let i=vint(e,r+t[1],n,!1);if(!i||i[0]<0)return;let a=r+t[1]+i[1],o=Math.min(a+i[0],n);yield{id:t[0],start:a,end:o},r=a+i[0]}}function elementUint(e,t){if(!t||t.end===t.start||t.end-t.start>8)return null;let n=0;for(let r=t.start;r<t.end;r++)n=n*256+e[r];return n}function children(e,t,n=new Map){for(let r of elements(e,t.start,t.end))(r.id!==21936||!n.has(r.id))&&n.set(r.id,r);return n}function codecIdAt(e,t){let n=``;for(let r=t.start;r<t.end&&r<t.start+64&&e[r];r++)n+=String.fromCharCode(e[r]);return n}function matroskaConfig(e){let t=e.family===`matroska`?e.trackEntry:null;if(!live(t))return null;let n={bytes:t,codecId:``,codecPrivate:null,video:new Map,colour:new Map,mappings:[]};for(let e of elements(t,0,t.length))e.id===134?n.codecId=codecIdAt(t,e):e.id===25506?n.codecPrivate=e:e.id===224?children(t,e,n.video):e.id===16868&&n.mappings.push(children(t,e));let r=n.video.get(21936);return r&&(n.colour=children(t,r)),n}const t=new Set([100,110,122,244,44,83,86,118,128,138,139,134,135,144]),n=[0,1,1,1,12,11,10,11,16,11,40,33,24,11,20,11,32,11,80,33,18,11,15,11,64,33,160,99,4,3,3,2,2,1],r=RangeError();function unescapeRbsp(e){let t=new Uint8Array(e.length),n=0,r=0;for(let i of e)r>=2&&i===3?r=0:(t[n++]=i,r=i===0?r+1:0);return t.subarray(0,n)}function bitReader(e,t=0){let n=t*8,r=e.length*8,bit=()=>{check(n<r);let t=e[n>>3]>>7-(n&7)&1;return n++,t},bits=e=>{let t=0;for(let n=0;n<e;n++)t=t*2+bit();return t},skip=e=>{check(n+e<=r),n+=e},ue=(e=4294967294)=>{let t=0;for(;bit()===0;)check(++t<32);let n=2**t-1+bits(t);return check(n<=e),n},se=()=>{let e=ue();return e&1?(e+1)/2:e?-e/2:0};return{bit,bits,skip,ue,se}}function check(e){if(!e)throw r}function readVui(e){let{bit:t,bits:r,skip:i}=e,a={sar:null,fullRange:null,colour:null};if(t()){let e=r(8),t=e===255?[r(16),r(16)]:[n[e*2]??0,n[e*2+1]??0];a.sar=t[0]>0&&t[1]>0?[t[0],t[1]]:null}return t()&&i(1),t()&&(i(3),a.fullRange=t()===1,t()&&(a.colour=[r(8),r(8),r(8)])),a}function skipH264ScalingList(e,t){let{se:n}=e,r=8,i=8;for(let e=0;e<t;e++)i!==0&&(i=(r+n()+256)%256),r=i===0?r:i}function parseH264Sps(e){try{let n=bitReader(unescapeRbsp(e),1),{bit:r,bits:i,skip:a,ue:o,se:s}=n,c=i(8);a(16),o(31);let l=8;if(t.has(c)){let e=o(3);if(e===3&&a(1),l=o(6)+8,check(o(6)+8===l),a(1),r())for(let t=0;t<(e===3?12:8);t++)r()&&skipH264ScalingList(n,t<6?16:64)}o(12);let u=o(2);if(u===0)o(12);else if(u===1){a(1),s(),s();let e=o(255);for(let t=0;t<e;t++)s()}if(o(16),a(1),o(),o(),r()||a(1),a(1),r())for(let e=0;e<4;e++)o();return{bitDepth:l,vui:r()?readVui(n):null}}catch(e){if(e===r)return null;throw e}}function skipProfileTierLevel(e,t){let{bit:n,skip:r}=e;r(88),r(8);let i=[];for(let e=0;e<t;e++)i.push([n(),n()]);t>0&&r(2*(8-t));for(let[e,t]of i)e&&r(88),t&&r(8)}function skipHevcScalingListData(e){let{bit:t,ue:n,se:r}=e;for(let e=0;e<4;e++)for(let i=0;i<6;i+=e===3?3:1)if(t()){let t=Math.min(64,1<<4+(e<<1));if(e>1){let e=r();check(e>=-7&&e<=247)}for(let e=0;e<t;e++)r()}else{let t=n();check(i-t*(e===3?3:1)>=0)}}function skipShortTermRefPicSets(e,t){let{bit:n,skip:r,ue:i}=e,a=[];for(let e=0;e<t;e++)if(e>0&&n()){r(1),i(32767);let t=0;for(let r=0;r<=a[e-1];r++)(n()||n())&&t++;check(t<32),a.push(t)}else{let e=i(15),t=i(15);for(let n=0;n<e+t;n++)i(32767),r(1);a.push(e+t)}}function parseHevcSps(e){try{let t=bitReader(unescapeRbsp(e),2),{bit:n,bits:r,skip:i,ue:a}=t;i(4);let o=r(3);check(o<7),i(1),skipProfileTierLevel(t,o),a(15);let s=a(3);if(s===3&&i(1),a(),a(),n())for(let e=0;e<4;e++)a();let c=a(8)+8,l=a(8)+8;check(s===0||l===c);let u=a(12)+4,d=n();for(let e=d?0:o;e<=o;e++)a(),a(),a();for(let e=0;e<6;e++)a();if(n()&&n()&&skipHevcScalingListData(t),i(2),n()&&(i(8),a(),a(),i(1)),skipShortTermRefPicSets(t,a(64)),n()){let e=a(32);for(let t=0;t<e;t++)i(u+1)}return i(2),{bitDepth:c,vui:n()?readVui(t):null}}catch(e){if(e===r)return null;throw e}}function avcConfigSps(e,t){let n=t.end-t.start>=8&&e[t.start+5]&31?u16(e,t.start+6):-1;return n>=0&&t.start+8+n<=t.end?parseH264Sps(e.subarray(t.start+8,t.start+8+n)):null}function hevcConfigSps(e,t){let n=t.start+23;for(let r=0,i=t.end-t.start>=23?e[t.start+22]:0;r<i&&n+3<=t.end;r++){let r=e[n]&63,i=u16(e,n+1);n+=3;for(let a=0;a<i&&n+2<=t.end;a++){let i=u16(e,n);if(n+2+i>t.end)return null;if(r===33)return parseHevcSps(e.subarray(n+2,n+2+i));n+=2+i}}return null}const i=new Set([66,77,88]),hex2=e=>e.toString(16).padStart(2,`0`),dec2=e=>String(e).padStart(2,`0`);function reverseBits32(e){let t=0;for(let n=0;n<32;n++)t=t*2+(e&1),e>>>=1;return t}function avcFacts(e,t,n){if(t.end-t.start<6)return null;let r=e[t.start+1],a=avcConfigSps(e,t),o=t.start+6;for(let n=0,r=e[t.start+5]&31;n<r&&o+2<=t.end;n++)o+=2+u16(e,o);if(o<t.end)for(let n=0,r=e[o++];n<r&&o+2<=t.end;n++)o+=2+u16(e,o);let s=!i.has(r);return{profile:r,bitDepth:a?.bitDepth??(s?o+4<=t.end?(e[o+1]&7)+8:null:8),codecString:`${n}.${hex2(r)}${hex2(e[t.start+2])}${hex2(e[t.start+3])}`,sps:a}}function hevcFacts(e,t,n){if(t.end-t.start<23)return null;let r=t.start,i=e[r+1]>>6,a=e[r+1]&31,o=u32(e,r+2),s=a;for(let e=1;!s&&e<32;e++)o>>>31-e&1&&(s=e);let c=``;for(let t=5,n=!1;t>=0;t--){let i=e[r+6+t];(i||n)&&(c=`.${i.toString(16)}${c}`,n=!0)}let l=`${n}.${[``,`A`,`B`,`C`][i]}${a}.${reverseBits32(o).toString(16)}.${e[r+1]&32?`H`:`L`}${e[r+12]}${c}`,u=hevcConfigSps(e,t);return{profile:s,bitDepth:u?.bitDepth??(e[r+17]&7)+8,codecString:l,sps:u}}function av1Facts(e,t){if(t.end-t.start<4)return null;let n=e[t.start+1]>>5,r=e[t.start+2],i=r>>6&1,a=n>2?null:i?n===2&&r&32?12:10:8;return{profile:n,bitDepth:a,codecString:a===null?null:`av01.${n}.${dec2(e[t.start+1]&31)}${r&128?`H`:`M`}.${dec2(a)}`,sps:null}}function vp9String(e,t,n){return e===null||t===null||n===null?null:`vp09.${dec2(e)}.${dec2(t)}.${dec2(n)}`}function vpcFacts(e,t){if(t.end-t.start<7)return null;let n=e[t.start+4],r=e[t.start+6]>>4;return{profile:n,bitDepth:r,codecString:vp9String(n,e[t.start+5],r),sps:null}}function vp9PrivateFacts(e,t){let n=new Map;for(let r=t.start;r+2<=t.end;){let i=e[r],a=e[r+1];if(r+2+a>t.end)break;a===1&&!n.has(i)&&n.set(i,e[r+2]),r+=2+a}if(!n.size)return null;let r=n.get(1)??null,i=n.get(3)??null;return{profile:r,bitDepth:i,codecString:vp9String(r,n.get(2)??null,i),sps:null}}function isoConfigFacts(e,t,n){let r=firstBox(n,`avcC`);if(e===`h264`&&r)return avcFacts(t,r,n.type);let i=firstBox(n,`hvcC`);if(e===`hevc`&&i)return hevcFacts(t,i,n.type);let a=firstBox(n,`av1C`);if(e===`av1`&&a)return av1Facts(t,a);let o=firstBox(n,`vpcC`);return e===`vp9`&&o?vpcFacts(t,o):null}function matroskaConfigFacts(e,t,n){return n?e===`V_MPEG4/ISO/AVC`?avcFacts(t,n,`avc1`):e===`V_MPEGH/ISO/HEVC`?hevcFacts(t,n,`hvc1`):e===`V_AV1`?av1Facts(t,n):e===`V_VP9`?vp9PrivateFacts(t,n):null:null}function dolbyVisionString(e,t,n){return`${e}.${dec2(t)}.${dec2(n)}`}const a=`reserved|bt709|unknown|reserved|bt470m|bt470bg|smpte170m|smpte240m|film|bt2020|smpte428|smpte431|smpte432||||||||||ebu3213`.split(`|`),o=`reserved|bt709|unknown|reserved|bt470m|bt470bg|smpte170m|smpte240m|linear|log100|log316|iec61966-2-4|bt1361e|iec61966-2-1|bt2020-10|bt2020-12|smpte2084|smpte428|arib-std-b67`.split(`|`),s=`gbr|bt709|unknown|reserved|fcc|bt470bg|smpte170m|smpte240m|ycgco|bt2020nc|bt2020c|smpte2085|chroma-derived-nc|chroma-derived-c|ictcp|ipt-c2|ycgco-re|ycgco-ro`.split(`|`),c={primaries:{base:a,extended:[`vgamut`]},transfer:{base:o,extended:[`vlog`]},space:{base:s,extended:[]}};function nameOf(e,t){let n=c[e];return(t>=256?n.extended[t-256]:n.base[t])||void 0}function colorName(e,t){return t===null||t===2?null:nameOf(e,t)??null}function namedOrUnspecified(e,t){return nameOf(e,t)===void 0?2:t}const l=[`primaries`,`transfer`,`space`];function namedCodes(e){return l.map((t,n)=>namedOrUnspecified(t,e[n]))}function colorNames(e){return e?l.map((t,n)=>colorName(t,e[n])):[null,null,null]}const u=new Set([`dvh1`,`dvhe`,`dvav`,`dva1`,`dav1`]),d=[`dvcC`,`dvvC`,`dvwC`],f=new Set([1685480259,1685485123]),p=new Set([`h264`,`hevc`]);function dolbyVision(e,t){if(t.end-t.start<4)return null;let n=t.start,r=u16(e,n+2),i=t.end-t.start>=5;return{versionMajor:e[n],versionMinor:e[n+1],profile:r>>9,level:r>>3&63,rpu:!!(r&4),el:!!(r&2),bl:!!(r&1),compatibilityId:i?e[n+4]>>4:0,mdCompression:i?e[n+4]>>2&3:0}}function colrOf(e,t){if(t.end-t.start<10)return null;let n=fourccAt(e,t.start);return n!==`nclx`&&n!==`nclc`?null:{source:`colr`,codes:namedCodes([u16(e,t.start+4),u16(e,t.start+6),u16(e,t.start+8)]),fullRange:n===`nclx`?t.end-t.start>=11&&e[t.start+10]>>7==1:null}}function vpcOf(e,t){if(t.end-t.start<12||e[t.start]!==1)return null;let n=t.start+4;return{source:`vpcC`,codes:namedCodes([e[n+3],e[n+4],e[n+5]]),fullRange:(e[n+2]&1)==1}}function matroskaColour(e,t){if(!t.size)return null;let code=(n,r)=>{let i=elementUint(e,t.get(n))??2;return r.includes(i)?2:i},n=elementUint(e,t.get(21945));return{source:`Colour`,codes:[code(21947,[0,3]),code(21946,[0,3]),code(21937,[3])],fullRange:n===1?!1:n===2||null}}function hdrOf(e){return e===`smpte2084`?`pq`:e===`arib-std-b67`?`hlg`:null}function resolve(e,t,n,r,i){let a=p.has(e)?n?.sps?.vui??null:null,o=t!==null&&t.codes.some(e=>e!==2),s=o?t.codes:a?.colour?namedCodes(a.colour):null,c=o?t.source:a?.colour?`sps`:null,l=t?.fullRange??a?.fullRange??null;l===null&&e===`hevc`&&n?.sps&&(l=!1);let[u,d,f]=colorNames(s);return{range:l===null?null:l?`pc`:`tv`,primaries:u,transfer:d,space:f,source:s?.some(e=>e!==2)?c:null,bitDepth:n?.bitDepth??i,profile:n?.profile??null,codecString:n?.codecString??null,hdr:hdrOf(d),dolbyVision:r}}function isoColor(e,t){let n=isoConfig(t);if(!n)return;let r=n.entries[0];if(!r)return null;let i=n.bytes,a=null,o=null,s=null;for(let e of n.entries)for(let t of e.children){let e=t.type===`colr`?colrOf(i,t):t.type===`vpcC`?vpcOf(i,t):null;e&&(a=e,o=e.fullRange??o),d.includes(t.type)&&(s=dolbyVision(i,t)??s)}let c=isoConfigFacts(e,i,r);return s&&c&&u.has(r.type)&&(c.codecString=dolbyVisionString(r.type,s.profile,s.level)),a||c||s?resolve(e,a&&{...a,fullRange:o},c,s,null):null}function matroskaColor(e,t){let n=matroskaConfig(t);if(!n)return;let r=n.bytes,i=matroskaColour(r,n.colour),a=null;for(let e of n.mappings){let t=e.get(16877);f.has(elementUint(r,e.get(16871))??-1)&&t&&(a=dolbyVision(r,t)??a)}let o=matroskaConfigFacts(n.codecId,r,n.codecPrivate),s=elementUint(r,n.colour.get(21938));return!i&&!o&&!a&&!s?null:resolve(e,i,o,a,s||null)}function colorOf(e){let t=e.codecConfig;if(t)return t.family===`matroska`?matroskaColor(e.codecName,t):isoColor(e.codecName,t)}function withColor(e,t={}){return{...e,videoTracks:e.videoTracks.map(e=>{if(!e.codecConfig)return e;let n={...e,color:colorOf(e)};return t.keepCodecConfig||delete n.codecConfig,n})}}const m=2147483647n,abs=e=>e<0n?-e:e;function gcd(e,t){for(;t;)[e,t]=[t,e%t];return e}function avReduce(e,t,n){let r=[0n,1n],i=[1n,0n],a=e<0n!=t<0n,o=gcd(abs(e),abs(t));for(o&&(e=abs(e)/o,t=abs(t)/o),e<=n&&t<=n&&(i=[e,t],t=0n);t;){let a=e/t,o=e-t*a,s=a*i[0]+r[0],c=a*i[1]+r[1];if(s>n||c>n){i[0]&&(a=(n-r[0])/i[0]),i[1]&&(a=a<(n-r[1])/i[1]?a:(n-r[1])/i[1]),t*(2n*a*i[1]+r[1])>e*i[1]&&(i=[a*i[0]+r[0],a*i[1]+r[1]]);break}r=i,i=[s,c],e=t,t=o}return[a?-i[0]:i[0],i[1]]}function binaryExponent(e){if(e===0)return 0;let t=Math.floor(Math.log2(e));for(;2**t>e;)t--;for(;2**(t+1)<=e;)t++;return t}function avD2q(e,t){if(Number.isNaN(e))return[0n,0n];if(Math.abs(e)>Number(2147483647n)+3)return[e<0?-1n:1n,0n];let n=Math.max(binaryExponent(Math.abs(e)),0),r=1n<<BigInt(61-n);return avReduce(BigInt(Math.floor(e*Number(r)+.5)),r,t)}const h=1<<24,g=new Set([1,8,9,11]),_=new Set([2,3,6,7]);function rational([e,t]){return{num:Number(e),den:Number(t),value:Number(e)/Number(t)}}const valid=e=>e!==null&&e[0]>0n&&e[1]>0n;function vuiRatio(e){let t=e?.vui?.sar;return t?avReduce(BigInt(t[0]),BigInt(t[1]),m):null}function configSps(e,t,n){return n?e===`h264`?avcConfigSps(t,n):e===`hevc`?hevcConfigSps(t,n):null:null}function matrixOf(e,t){let n=boxPayload(e);if(!e||!n)return null;let r=n.start+t(e[n.start]);return r+36>n.end?null:Array.from({length:9},(t,n)=>BigInt(i32(e,r+n*4)))}function tkhdSizeAt(e){let t=boxPayload(e.tkhd),n=e.tkhd&&t?t.start+(e.tkhd[t.start]===1?88:76):-1;return t&&n+8<=t.end?n:-1}function matrixRatio(e,t){if(!e.tkhd||t<0||!u32(e.tkhd,t)||!u32(e.tkhd,t+4))return null;let n=matrixOf(e.tkhd,e=>e===1?52:40);if(!n)return null;let r=matrixOf(e.mvhd,e=>e===1?48:36)??Array(9).fill(0n),i=[16n,16n,30n],a=[];for(let e=0;e<3;e++)for(let t=0;t<3;t++){let o=0n;for(let a=0;a<3;a++)o+=n[e*3+a]*r[a*3+t]>>i[a];a.push(Number(BigInt.asIntN(32,o)))}if(a[0]===65536&&a[4]===65536&&a[8]===1<<30&&!a[1]&&!a[2]&&!a[3]&&!a[5]&&!a[6]&&!a[7])return null;let o=Math.hypot(a[0],a[3]),s=Math.hypot(a[1],a[4]);return o>1&&s>1&&o<h&&s<h&&Math.abs(o/s-1)>.01?avD2q(o/s,m):null}function isoRatio(e,t){let n=tkhdSizeAt(t),r=null;for(let e of t.entries)for(let n of e.children)n.type===`pasp`&&n.end-n.start>=8&&i32(t.bytes,n.start+4)&&(r=[BigInt(i32(t.bytes,n.start)),BigInt(i32(t.bytes,n.start+4))]);let i=r?.[0]?avReduce(r[0],r[1],m):matrixRatio(t,n);if(!i?.[0]&&t.tkhd&&n>=0){let r=BigInt(i32(t.tkhd,n)>>16),a=BigInt(i32(t.tkhd,n+4)>>16),o=BigInt(e.width),s=BigInt(e.height);r&&a&&o&&s&&(o!==r||s!==a)&&(i=avReduce(s*r,o*a,m))}if(valid(i))return i;let a=t.entries[0];return vuiRatio(configSps(e.codecName,t.bytes,firstBox(a,e.codecName===`h264`?`avcC`:`hvcC`)))}function matroskaCodec(e){return e.codecId===`V_MPEG4/ISO/AVC`?`h264`:e.codecId===`V_MPEGH/ISO/HEVC`?`hevc`:``}function matroskaRatio(e){let t=e.bytes,video=n=>elementUint(t,e.video.get(n)),n=video(21682)??0,r=null,i=(video(176)??0)-(video(21708)??0)-(video(21725)??0),a=(video(186)??0)-(video(21691)??0)-(video(21674)??0);if(n<4&&i>0&&a>0){let e=video(21680)??(n===0?i:null),t=video(21690)??(n===0?a:null),o=video(21432)??0;if(e&&t){let n=g.has(o)?2n:1n,s=_.has(o)?2n:1n;r=avReduce(BigInt(a)*BigInt(e)*n,BigInt(i)*BigInt(t)*s,m)}}return valid(r)?r:vuiRatio(configSps(matroskaCodec(e),t,e.codecPrivate))}function elementFloat(e,t){let n=t?t.end-t.start:0;if(!t||n!==4&&n!==8)return 0;let r=new DataView(e.buffer,e.byteOffset+t.start,n);return n===4?r.getFloat32(0):r.getFloat64(0)}function projectionRotation(e){let t=e.video.get(30320);if(!t)return 0;let n=e.bytes,r=new Map;for(let e of elements(n,t.start,t.end))r.set(e.id,e);let i=r.get(30322);if((elementUint(n,r.get(30321))??0)!==0||i&&i.end>i.start&&n[i.start]!==0)return 0;let a=elementFloat(n,r.get(30323)),o=elementFloat(n,r.get(30325));if(elementFloat(n,r.get(30324))!==0||a!==0&&Math.abs(a)!==180||Number.isNaN(o))return 0;let s=a===0?1:-1,c=o*s*Math.PI/180,l=s*Math.trunc(Math.cos(c)*65536)/65536,u=Math.trunc(-Math.sin(c)*65536)/65536,d=Math.hypot(l,s*Math.trunc(Math.sin(c)*65536)/65536),f=Math.hypot(u,Math.trunc(Math.cos(c)*65536)/65536);return d&&f&&Math.trunc(-(Math.atan2(u/f,l/d)*180/Math.PI))||0}function aspectOf(e){let t=e.codecConfig,n=t&&isoConfig(t),r=t&&!n?matroskaConfig(t):null;if(!n&&!r)return;let i=n?isoRatio(e,n):matroskaRatio(r),a=valid(i)?i:null,{width:o,height:s}=e;if(o<=0||s<=0)return{sampleAspectRatio:a&&rational(a),displayAspectRatio:null,displayWidth:null,displayHeight:null};let[c,l]=a??[1n,1n],u=Number((2n*BigInt(o)*c+l)/(2n*l)),d=e.rotation||(r?projectionRotation(r):0),f=Math.abs(d)%180==90;return{sampleAspectRatio:a&&rational(a),displayAspectRatio:a&&rational(avReduce(BigInt(o)*c,BigInt(s)*l,1048576n)),displayWidth:f?s:u,displayHeight:f?u:s}}function withAspect(e,t={}){return{...e,videoTracks:e.videoTracks.map(e=>{if(!e.codecConfig)return e;let n={...e,...aspectOf(e)};return t.keepCodecConfig||delete n.codecConfig,n})}}Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return withColor}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return withAspect}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return colorOf}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return aspectOf}});
@@ -1 +1 @@
1
- const e=require("./guards-Dqpjtkdn.cjs"),t=require("./probe-DDLUfr23.cjs"),n=require("./errors-0oBg1Ai6.cjs"),r=require("./fallback-D9Ak2zFv.cjs");async function compare(i,a,o={}){let s=t.n(a),c=[...new Set(o.engines??i.engines.filter(e=>e!==`rvfc`))],l=c.find(e=>!i.routes.has(e));if(l)throw new n.t(`engine-not-registered`,`engine ${l} is not registered`,{engine:l});let u={...i.defaults},{signal:d,timeoutMs:f,onProgress:p}=o,outcomeOf=async t=>{let o=performance.now();try{let e=await i.run(t,a,s,u,{signal:d,timeoutMs:f,onProgress:p&&(e=>p({...e,engine:t}))});if(e.type===`skipped`)return{status:`skipped`,reason:e.reason};let n=performance.now()-o,c=e.result,l=r.failureOf(c);return l===null?{status:`ok`,result:c,ms:n}:{status:`failed`,result:c,error:l,ms:n}}catch(r){if(e.t(r))throw r;let i=e.n(r)?r:Object.assign(new n.t(`worker-failed`,String(r),{engine:t,cause:r}),{reason:`crash`});return i.code===`unsupported-environment`?{status:`skipped`,reason:`unsupported-environment`}:{status:i.code===`timeout`?`timeout`:`crashed`,error:i}}},m=new Map;for(let e of c){let t=i.routes.get(e),n=t&&`kind`in t?t.kind:e;m.set(n,[...m.get(n)??[],e])}let h=new Map;await Promise.all([...m.values()].map(async e=>{for(let t of e)h.set(t,await outcomeOf(t))}));let g={},_={};for(let e of c){let t=h.get(e);t&&(g[e]=t,`result`in t&&(_[e]=t.result))}let v=t.r(_,o.reference);return{name:s,size:a.size,reference:v.reference,outcomes:g,agreement:v}}exports.compare=compare;
1
+ const e=require("./guards-DbQNcAZS.cjs"),t=require("./probe-Cn1DtL-C.cjs"),n=require("./errors-0oBg1Ai6.cjs"),r=require("./fallback-CyPIR3RM.cjs");async function compare(i,a,o={}){let s=t.n(a),c=[...new Set(o.engines??i.engines.filter(e=>e!==`rvfc`))],l=c.find(e=>!i.routes.has(e));if(l)throw new n.t(`engine-not-registered`,`engine ${l} is not registered`,{engine:l});let u={...i.defaults},{signal:d,timeoutMs:f,onProgress:p}=o,outcomeOf=async t=>{let o=performance.now();try{let e=await i.run(t,a,s,u,{signal:d,timeoutMs:f,onProgress:p&&(e=>p({...e,engine:t}))});if(e.type===`skipped`)return{status:`skipped`,reason:e.reason};let n=performance.now()-o,c=e.result,l=r.failureOf(c);return l===null?{status:`ok`,result:c,ms:n}:{status:`failed`,result:c,error:l,ms:n}}catch(r){if(e.t(r))throw r;let i=e.n(r)?r:Object.assign(new n.t(`worker-failed`,String(r),{engine:t,cause:r}),{reason:`crash`});return i.code===`unsupported-environment`?{status:`skipped`,reason:`unsupported-environment`}:{status:i.code===`timeout`?`timeout`:`crashed`,error:i}}},m=new Map;for(let e of c){let t=i.routes.get(e),n=t&&`kind`in t?t.kind:e;m.set(n,[...m.get(n)??[],e])}let h=new Map;await Promise.all([...m.values()].map(async e=>{for(let t of e)h.set(t,await outcomeOf(t))}));let g={},_={};for(let e of c){let t=h.get(e);t&&(g[e]=t,`result`in t&&(_[e]=t.result))}let v=t.r(_,o.reference);return{name:s,size:a.size,reference:v.reference,outcomes:g,agreement:v}}exports.compare=compare;
@@ -0,0 +1 @@
1
+ const e=require("./boxes-B0T2nt3e.cjs");function copy(e,t){return t?new Uint8Array(e.buffer,e.byteOffset+t.start,t.end-t.start).slice():null}function child(t,n,r){let i;for(let a of e.a(t,n.start+n.headerSize,n.end))a.type===r&&(i=a);return i}function isoBoxes(t,n){let r={family:`isobmff`,stsd:null,tkhd:null,mvhd:null},i=t?e.o(t,0,t.byteLength):null;if(!t||!i||i.type!==`moov`)return r;let a=0;for(let o of e.a(t,i.headerSize,i.end))if(o.type===`mvhd`)r.mvhd=copy(t,o);else if(o.type===`trak`&&a++===n){r.tkhd=copy(t,child(t,o,`tkhd`));let e=child(t,o,`mdia`),n=e&&child(t,e,`minf`),i=n&&child(t,n,`stbl`);r.stsd=copy(t,i&&child(t,i,`stsd`));break}return r}function isoCodecConfig(e,t){return isoBoxes(t.dv,e.tracks.indexOf(t))}exports.isoBoxes=isoBoxes,exports.isoCodecConfig=isoCodecConfig;
@@ -1 +1 @@
1
- const e=require("./guards-Dqpjtkdn.cjs"),t=require("./errors-0oBg1Ai6.cjs"),failureOf=t=>{let n=e.u(t);return t.error??(n?n.avgFps?null:`no frame rate`:`no video track`)},skippedResult=(t,n,r,i)=>({name:r,size:n.size,...e.c(i===`isobmff`?`mp4`:i??`unknown`,i?`unsupported by ${t}`:`not a recognised container`),io:{reads:0,bytesRead:0,ms:0},engine:t}),withAttempts=(e,t)=>t.length>0?{...e,attempts:t.map(({engine:e,error:t})=>({engine:e,error:t}))}:e;async function runChain(n,r,i,a,o,s,c){let l=[],u=null;for(let[d,f]of r.entries()){let p;try{let e=d===0&&c?c:await n(f,i,a,o,s);p=e.type===`result`?e.result:skippedResult(f,i,a,e.family??null)}catch(n){if(e.t(n))throw n;u=e.n(n)?n:Object.assign(new t.t(`worker-failed`,String(n),{engine:f,cause:n}),{reason:`crash`}),l.push({engine:f,error:u.message});continue}let m=failureOf(p);if(m===null||r.length===1)return withAttempts(p,l);l.push({engine:f,error:m,result:p})}for(let e=l.length-1;e>=0;e--){let{result:t}=l[e];if(t)return withAttempts(t,l.slice(0,e).concat(l.slice(e+1)))}throw u}exports.failureOf=failureOf,exports.runChain=runChain;
1
+ const e=require("./guards-DbQNcAZS.cjs"),t=require("./errors-0oBg1Ai6.cjs"),failureOf=t=>{let n=e.u(t);return t.error??(n?n.avgFps?null:`no frame rate`:`no video track`)},skippedResult=(t,n,r,i)=>({name:r,size:n.size,...e.c(i===`isobmff`?`mp4`:i??`unknown`,i?`unsupported by ${t}`:`not a recognised container`),io:{reads:0,bytesRead:0,ms:0},engine:t}),withAttempts=(e,t)=>t.length>0?{...e,attempts:t.map(({engine:e,error:t})=>({engine:e,error:t}))}:e;async function runChain(n,r,i,a,o,s,c){let l=[],u=null;for(let[d,f]of r.entries()){let p;try{let e=d===0&&c?c:await n(f,i,a,o,s);p=e.type===`result`?e.result:skippedResult(f,i,a,e.family??null)}catch(n){if(e.t(n))throw n;u=e.n(n)?n:Object.assign(new t.t(`worker-failed`,String(n),{engine:f,cause:n}),{reason:`crash`}),l.push({engine:f,error:u.message});continue}let m=failureOf(p);if(m===null||r.length===1)return withAttempts(p,l);l.push({engine:f,error:m,result:p})}for(let e=l.length-1;e>=0;e--){let{result:t}=l[e];if(t)return withAttempts(t,l.slice(0,e).concat(l.slice(e+1)))}throw u}exports.failureOf=failureOf,exports.runChain=runChain;
@@ -1 +1 @@
1
- function emptyAnalysis(e,t=null){return{container:e,brand:null,formatDurationSec:null,scan:null,videoTracks:[],audioTrackCount:0,primaryTrackId:null,error:t,warnings:[]}}function emptyTrack(e){return{trackId:e,fourccOrCodecId:``,codecName:``,width:0,height:0,rotation:0,timescale:0,frames:null,presentedFrames:null,durationSec:null,startSec:null,avgFps:null,avgFpsFfprobe:null,rFpsFfprobe:null,nominalFps:null,dominantFps:null,minFps:null,maxFps:null,isVfr:null,vfrRatio:0,distinctDeltas:0,duplicateTimestamps:0,timestampsQuantized:!1,isStill:!1,rateProfile:null,medianFrameInterval:null,provenance:{},warnings:[]}}function primaryTrack(e){return e.primaryTrackId===null?null:e.videoTracks.find(t=>t.trackId===e.primaryTrackId)??null}const e=[[`not a recognised container: empty file`,`empty-file`],[`not a recognised container`,`unrecognised`],[`unsupported: moov larger`,`too-large`],[`corrupt file: moof larger`,`too-large`],[`unsupported:`,`unsupported`],[`incomplete file: moov is truncated`,`truncated`],[`incomplete file: no moov`,`no-header`],[`incomplete header:`,`no-duration`],[`limit reached: maxBytes`,`byte-limit`],[`limit reached: maxReads`,`read-limit`],[`limit reached: maxMs`,`time-limit`],[`limit reached: maxTracks`,`structure-limit`],[`limit reached: maxTopLevelBoxes`,`structure-limit`],[`corrupt file:`,`corrupt`],[`file read failed`,`read-failed`],[`the own `,`unsupported-container`],[`unsupported by `,`unsupported-container`],[`container not read by`,`unsupported-container`],[`invalid EBML header`,`corrupt`],[`no Segment element`,`no-header`],[`no complete TrackEntry in Tracks`,`truncated`],[`no Tracks element found`,`no-header`]],t={"empty-file":`file`,unrecognised:`file`,"unsupported-container":`file`,unsupported:`file`,"too-large":`file`,"no-header":`file`,truncated:`file`,corrupt:`file`,"no-duration":`file`,"engine-failed":`file`,"byte-limit":`limit`,"read-limit":`limit`,"time-limit":`limit`,"structure-limit":`limit`,"read-failed":`io`,"load-failed":`environment`,internal:`internal`},n=[[`invalid mdhd timescale `,`invalid-timescale`],[`invalid timescale `,`invalid-timescale`],[`ignored trailing data at `,`trailing-data`],[`fragment index not read: `,`fragment-index-unread`],[`format duration unresolved: `,`duration-unresolved`],[`fragments ignored: `,`fragments-ignored`],[`too many top-level boxes`,`structure-limit`]],r=/^'(.{4})' at \d+ is truncated/;function errorCodeOf(t){if(t?.errorCode!==void 0)return t.errorCode;let n=t?.error;if(n===null)return null;if(typeof n!=`string`)return`internal`;for(let[t,r]of e)if(n.startsWith(t))return r;return t.engine!==void 0&&t.engine!==`own`?`engine-failed`:`internal`}function errorClass(e){return Object.hasOwn(t,e)?t[e]:`internal`}function warningCodeOf(e){if(typeof e!=`string`)return null;for(let[t,r]of n)if(e.startsWith(t))return r;let t=r.exec(e);return t?t[1]===`mdat`?`truncated-mdat`:`truncated-box`:null}function warningCodesOf(e){let t=new Set,listOf=e=>Array.isArray(e)?e:[];for(let n of[...listOf(e?.warnings),...listOf(e?.videoTracks).flatMap(e=>listOf(e?.warnings))]){let e=warningCodeOf(n);e&&t.add(e)}return[...t]}const field=(e,t)=>typeof e==`object`&&e&&t in e?e[t]:void 0,isProbeError=e=>field(e,`name`)===`ProbeError`&&typeof field(e,`code`)==`string`,probeCode=(e,t,n)=>isProbeError(e)?e.code===t:field(e,`name`)===n;function isAbortError(e){return probeCode(e,`aborted`,`AbortError`)}function isTimeoutError(e){return probeCode(e,`timeout`,`TimeoutError`)}Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return errorCodeOf}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return emptyAnalysis}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return errorClass}}),Object.defineProperty(exports,"l",{enumerable:!0,get:function(){return emptyTrack}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return isProbeError}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return warningCodeOf}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return isTimeoutError}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return warningCodesOf}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return isAbortError}}),Object.defineProperty(exports,"u",{enumerable:!0,get:function(){return primaryTrack}});
1
+ function emptyAnalysis(e,t=null){return{container:e,brand:null,formatDurationSec:null,scan:null,videoTracks:[],audioTrackCount:0,primaryTrackId:null,error:t,warnings:[]}}function emptyTrack(e){return{trackId:e,fourccOrCodecId:``,codecName:``,width:0,height:0,rotation:0,timescale:0,frames:null,presentedFrames:null,durationSec:null,startSec:null,avgFps:null,avgFpsFfprobe:null,rFpsFfprobe:null,nominalFps:null,dominantFps:null,minFps:null,maxFps:null,isVfr:null,vfrRatio:0,distinctDeltas:0,duplicateTimestamps:0,timestampsQuantized:!1,isStill:!1,rateProfile:null,medianFrameInterval:null,provenance:{},warnings:[]}}function primaryTrack(e){return e.primaryTrackId===null?null:e.videoTracks.find(t=>t.trackId===e.primaryTrackId)??null}const e=[[`not a recognised container: empty file`,`empty-file`],[`not a recognised container`,`unrecognised`],[`unsupported: moov larger`,`too-large`],[`corrupt file: moof larger`,`too-large`],[`unsupported:`,`unsupported`],[`incomplete file: moov is truncated`,`truncated`],[`incomplete file: no moov`,`no-header`],[`incomplete header:`,`no-duration`],[`limit reached: maxBytes`,`byte-limit`],[`limit reached: maxReads`,`read-limit`],[`limit reached: maxMs`,`time-limit`],[`limit reached: maxTracks`,`structure-limit`],[`limit reached: maxTopLevelBoxes`,`structure-limit`],[`corrupt file:`,`corrupt`],[`file read failed`,`read-failed`],[`the own `,`unsupported-container`],[`unsupported by `,`unsupported-container`],[`container not read by`,`unsupported-container`],[`invalid EBML header`,`corrupt`],[`no Segment element`,`no-header`],[`no complete TrackEntry in Tracks`,`truncated`],[`no Tracks element found`,`no-header`]],t={"empty-file":`file`,unrecognised:`file`,"unsupported-container":`file`,unsupported:`file`,"too-large":`file`,"no-header":`file`,truncated:`file`,corrupt:`file`,"no-duration":`file`,"engine-failed":`file`,"byte-limit":`limit`,"read-limit":`limit`,"time-limit":`limit`,"structure-limit":`limit`,"read-failed":`io`,"load-failed":`environment`,internal:`internal`},n=[[`invalid mdhd timescale `,`invalid-timescale`],[`invalid timescale `,`invalid-timescale`],[`ignored trailing data at `,`trailing-data`],[`fragment index not read: `,`fragment-index-unread`],[`format duration unresolved: `,`duration-unresolved`],[`fragments ignored: `,`fragments-ignored`],[`too many top-level boxes`,`structure-limit`],[`codec configuration unavailable`,`codec-config-unavailable`],[`color and aspect unavailable`,`metadata-unavailable`]],r=/^'(.{4})' at \d+ is truncated/;function errorCodeOf(t){if(t?.errorCode!==void 0)return t.errorCode;let n=t?.error;if(n===null)return null;if(typeof n!=`string`)return`internal`;for(let[t,r]of e)if(n.startsWith(t))return r;return t.engine!==void 0&&t.engine!==`own`?`engine-failed`:`internal`}function errorClass(e){return Object.hasOwn(t,e)?t[e]:`internal`}function warningCodeOf(e){if(typeof e!=`string`)return null;for(let[t,r]of n)if(e.startsWith(t))return r;let t=r.exec(e);return t?t[1]===`mdat`?`truncated-mdat`:`truncated-box`:null}function warningCodesOf(e){let t=new Set,listOf=e=>Array.isArray(e)?e:[];for(let n of[...listOf(e?.warnings),...listOf(e?.videoTracks).flatMap(e=>listOf(e?.warnings))]){let e=warningCodeOf(n);e&&t.add(e)}return[...t]}const field=(e,t)=>typeof e==`object`&&e&&t in e?e[t]:void 0,isProbeError=e=>field(e,`name`)===`ProbeError`&&typeof field(e,`code`)==`string`,probeCode=(e,t,n)=>isProbeError(e)?e.code===t:field(e,`name`)===n;function isAbortError(e){return probeCode(e,`aborted`,`AbortError`)}function isTimeoutError(e){return probeCode(e,`timeout`,`TimeoutError`)}Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return errorCodeOf}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return emptyAnalysis}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return errorClass}}),Object.defineProperty(exports,"l",{enumerable:!0,get:function(){return emptyTrack}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return isProbeError}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return warningCodeOf}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return isTimeoutError}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return warningCodesOf}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return isAbortError}}),Object.defineProperty(exports,"u",{enumerable:!0,get:function(){return primaryTrack}});
@@ -0,0 +1 @@
1
+ const e=require("./guards-DbQNcAZS.cjs"),t=require("./reader-Dw11ozVU.cjs"),n=require("./boxes-B0T2nt3e.cjs"),r=require("./build-DhETwJLO.cjs"),i=require("./stats-DW7dVdFa.cjs");async function analyzeIsoBmffDetailed(n,a){let o=r.b(n.size),fail=i=>{if(r.c(i,n))throw i;let a=i instanceof Error?i.message:String(i),s=e.c(r.a(o),i?.errorCode?a:`corrupt file: ${a}`);return s.errorCode=t.i(i),s.layout=r.u(o),s.brand=o.brand,s.warnings=o.warnings,{analysis:s,movie:o}};try{await r.m(n,a,o),await r.o(n,o);let t=e.c(r.a(o));t.brand=o.brand,t.scan=`exact`,t.warnings=o.warnings;let s=o.ffprobeReject,c=s!==null&&s.moof<o.ffprobeMoofLimit;c&&o.warnings.push(`ffprobe 8.1.1 ${s.reason}`);let l=r.p(o.tracks);[...l].some(([e,t])=>e.id!==t)&&o.warnings.push(`duplicate track_ID values`);let u=o.tracks.filter(e=>r.l(e,o)),d=u.map(e=>r.i(e,o,a,{reportedId:l.get(e)??e.id,ffprobeFails:c},i.analyzeTimeline));for(let e of d)e.result.rateProfile=await i.rateProfileOf(e.profile??null);return t.videoTracks=d.map(e=>e.result),t.audioTrackCount=o.tracks.filter(e=>e.handler===`soun`).length,t.primaryTrackId=r.d(d),t.formatDurationSec=r.s(o,new Set(u)),t.layout=r.u(o),{analysis:t,movie:o}}catch(e){return fail(e)}}async function analyzeIsoBmff(e,t){return(await analyzeIsoBmffDetailed(e,t)).analysis}exports.IsoBmffError=n.t,exports.MOOF_HARD_CAP=r.t,exports.MOOV_HARD_CAP=r.n,exports.MOOV_SUSPECT_CAP=r.r,exports.analyzeIsoBmff=analyzeIsoBmff,exports.analyzeIsoBmffDetailed=analyzeIsoBmffDetailed;
@@ -0,0 +1 @@
1
+ const e=require("./guards-DbQNcAZS.cjs"),t=require("./reader-Dw11ozVU.cjs"),n=require("./options-B_vLHxHd.cjs"),r=require("./rational-Dq5Vza-Q.cjs"),i=require("./stats-DW7dVdFa.cjs"),a=408125543,o=290298740,s=19899,c=21419,l=21420,u=357149030,d=2807729,f=17545,p=374648427,m=29637,h=2352003,g=2306383,_=22186,v=25506,y=28032,b=2327523,x=475249515,S=307544935,C=29555,w=25536,T=25541,E=26568,D=17827,O=17543,k=423732329,A=24999,j=18016,M=272869232,N=30114,P=new Set([o,u,p,x,S,524531317,M,k]);function vintLength(e){return e===0?0:Math.clz32(e)-23}function readId(e,t){if(t>=e.length)return null;let n=vintLength(e[t]);if(n<1||n>4||t+n>e.length)return null;let r=0;for(let i=0;i<n;i++)r=r*256+e[t+i];return{id:r,length:n}}function readSize(e,t){if(t>=e.length)return null;let n=e[t],r=vintLength(n);if(r<1||t+r>e.length)return null;let i=255>>r,a=(n&i)===i,o=n&i;for(let n=1;n<r;n++){let r=e[t+n];r!==255&&(a=!1),o=o*256+r}return a?{size:-1,length:r}:o>2**53-1?null:{size:o,length:r}}function readHeader(e,t,n){let r=readId(e,t);if(!r)return null;let i=readSize(e,t+r.length);return i?{id:r.id,pos:n+t,size:i.size,dataStart:n+t+r.length+i.length}:null}function headerShort(e,t){if(t>=e.length)return!0;let n=vintLength(e[t]);if(n<1||n>4)return!1;let r=t+n;return r>=e.length||e[r]!==0&&r+vintLength(e[r])>e.length}function readVint(e,t,n){let r=t<n?vintLength(e[t]):0;if(r<1||t+r>n)return null;let i=e[t]&255>>r;for(let n=1;n<r;n++)i=i*256+e[t+n];return{value:i,length:r}}function readUint(e,t,n){let r=0;for(let i=0;i<n;i++)r=r*256+e[t+i];return r}function readUintBig(e,t,n){let r=0n;for(let i=0;i<n;i++)r=r<<8n|BigInt(e[t+i]);return r}function readFloat(e,t,n){if(n===0)return 0;let r=new DataView(e.buffer,e.byteOffset+t,n);return n===4?r.getFloat32(0):n===8?r.getFloat64(0):NaN}const F=new TextDecoder;function readString(e,t,n){let r=t;for(;r<t+n&&e[r]!==0;)r++;return F.decode(e.subarray(t,r)).replace(/[^\x20-\x7e\xa0-\uffff]/g,`?`)}function*children(e,t,n){let r=t,i=Math.min(n,e.length);for(;r<i;){let t=readHeader(e,r,0);if(!t||t.size===-1||t.dataStart+t.size>i)return;yield{id:t.id,start:t.dataStart,size:t.size},r=t.dataStart+t.size}}function childUint(e,t){return t.size>6?Number(readUintBig(e,t.start,t.size)):readUint(e,t.start,t.size)}var ByteSource=class{reader;size;window;buf=new Uint8Array;base=0;#e=[];constructor(e,t){this.reader=e,this.size=e.size,this.window=t;let n=e.peek(0,Math.min(e.size,e.headWindow));n&&n.byteLength>0&&this.#t({base:0,buf:new Uint8Array(n.buffer,n.byteOffset,n.byteLength)})}has(e,t){return e>=this.base&&Math.min(this.size,e+t)<=this.base+this.buf.length}cached(e,t){let n=Math.min(this.size,e+t);return this.#e.some(t=>e>=t.base&&n<=t.base+t.buf.length)||this.reader.peek(e,n-e)!==null}async load(e,t,n=this.window){if(this.has(e,t))return;let r=Math.min(this.size,e+t);for(let t of this.#e)if(e>=t.base&&r<=t.base+t.buf.length){this.#t(t);return}let i=Math.max(t,n),a=await this.reader.view(e,i,i);this.#t({base:e,buf:new Uint8Array(a.buffer,a.byteOffset,a.byteLength)})}chunkAt(e){return this.#e.find(t=>e>=t.base&&e<t.base+t.buf.length)??null}async header(e){return this.has(e,12)||await this.load(e,12),readHeader(this.buf,e-this.base,this.base)}#t(e){this.buf=e.buf,this.base=e.base;let t=this.#e.indexOf(e);t>=0&&this.#e.splice(t,1),this.#e.unshift(e),this.#e.length>4&&(this.#e.length=4)}};const I=new Map([[o,[s]],[u,[d,f,19840,22337,29604,17505,31657,29572,3979555,3965867,4110627,4096955,17476,26916]],[p,[174]],[x,[187]],[S,[C]],[M,[17849]],[k,[A]]]),L=new Uint8Array(256);for(let e of P)L[e>>>24]=1;const R=new Uint8Array(256);R[31]=1;function isClusterAt(e,t,n){if(e[t]!==31||e[t+1]!==67||e[t+2]!==182||e[t+3]!==117)return!1;let r=readSize(e,t+4);if(!r)return!1;let i=t+4+r.length,a=r.size===-1?e.length:Math.min(e.length,i+r.size);if(r.size!==-1&&i+r.size>n)return!1;for(let t=0;t<4&&i<a;t++){let t=readId(e,i);if(!t)return!1;let n=readSize(e,i+t.length);if(!n||n.size===-1)return!1;if(t.id===231)return n.size<=8;if(t.id!==191&&t.id!==236&&t.id!==167&&t.id!==171)return!1;i+=t.length+n.length+n.size}return!1}function level1At(e,t,n,r){let i=readId(e,t);if(i?.length!==4)return!1;if(i.id===524531317)return isClusterAt(e,t,n);let a=I.get(i.id),o=readSize(e,t+4);if(!a||!o||o.size<2)return!1;let s=t+4+o.length+o.size,c=s<=r?readHeader(e,t+4+o.length,0):null;return!!c&&c.size!==-1&&c.dataStart+c.size<=s&&(a.includes(c.id)||c.id===236||c.id===191)}async function findForward(e,t,n,r,i={}){let a=i.clustersOnly?R:L,o=i.step??Math.max(e.window,65536),s=Math.max(0,t),c=Math.min(n,e.size);for(;s<c;){let t=e.chunkAt(s);if(!t||t.base+t.buf.length<e.size&&t.base+t.buf.length-s<128){if(i.canLoad&&!i.canLoad())return-1;let n=Math.min(o,c-s+64);await e.load(s,Math.min(n,e.size-s),n),t={base:e.base,buf:e.buf}}let n=t.buf,l=t.base,u=Math.min(l+n.length>=e.size?n.length:n.length-64,c-l);if(u<=s-l)break;for(let e=s-l;e<u;e++)if(a[n[e]]&&r(n,e,l))return l+e;s=l+u}return-1}function findClusterForward(e,t,n,r,i={}){return findForward(e,t,n,(e,t,n)=>isClusterAt(e,t,r-n),{...i,clustersOnly:!0})}function findLevel1Forward(e,t,n,r,i={}){let a=e.size;return findForward(e,t,n,(e,t,n)=>level1At(e,t,r-n,a-n),i)}const z=new Map([[o,`SeekHead`],[u,`Info`],[S,`Tags`]]),B=new Set([o,u,p,S,k]),V=new Map([[o,[s]],[s,[c,l]],[u,[d,f]],[p,[174]],[174,[215,m,131,185,134,v,y,h,g,_,224]],[224,[176,186,b]],[S,[C]],[C,[w,E]],[w,[T]],[E,[D,O,E]],[k,[A]],[A,[j]],[x,[187]],[187,[183]],[183,[241]]]),hex=e=>e.toString(16).toUpperCase();function withinHeaderBudget(e,t=0){return e.reader.reads<5&&e.reader.bytesFetched+Math.max(t,e.window)<=1048576}function parseDurationTag(e){let t=/^\s*(\d+):(\d{1,2}):(\d{1,2}(?:\.\d+)?)\s*$/.exec(e);return t?Number(t[1])*3600+Number(t[2])*60+Number(t[3]):null}function newTrack(){return{number:0,uid:0n,type:0,codecId:``,defaultDuration:0,frameRate:0,trackTimestampScale:1,codecDelay:0,codecPrivate:null,encoded:!1,width:0,height:0}}function finishTrack(e,t){t.trackTimestampScale>=.01||(t.trackTimestampScale=1),!t.defaultDuration&&t.frameRate>0&&(t.defaultDuration=Math.trunc(1e9/t.frameRate)),Number.isSafeInteger(t.defaultDuration)||(t.defaultDuration=0),e.tracks.push(t)}function parseMaster(e,t,n,r,i,a=null,o=null){let u=o??newTrack(),p=-1,x=-1,S=[],w=[],k=``,A=``,M=!1,walk=(n,r,i,o)=>{let N=V.get(n)??[];if(o>16)M=!0;else for(let M of children(t,r,i)){if(!N.includes(M.id))continue;let r=M.start,i=M.size,uint=()=>childUint(t,M),nest=()=>walk(M.id,r,r+i,o+1);switch(M.id){case 174:u=newTrack(),u.entry=t.slice(r,r+i),nest(),finishTrack(e,u);break;case C:S=[],w=[],nest();for(let t of w)for(let n of S.length?S:[0n])e.tagDurations.has(n)||e.tagDurations.set(n,t);break;case E:{let e=[k,A];k=A=``,nest();let t=n===29555&&(k===`DURATION`||k.startsWith(`DURATION-`))?parseDurationTag(A):null;t!==null&&w.push(t),[k,A]=e;break}case s:p=x=-1,nest(),p>=0&&x>=0&&!e.seek.has(p)&&e.seek.set(p,e.segmentData+x);break;case 215:u.number=uint();break;case m:u.uid=readUintBig(t,r,i);break;case 131:u.type=uint();break;case 185:u.disabled=!uint();break;case 134:u.codecId=readString(t,r,i);break;case h:u.defaultDuration=uint();break;case g:u.trackTimestampScale=readFloat(t,r,i);break;case _:u.codecDelay=uint();break;case y:u.encoded=!0;break;case v:u.codecPrivate=t.slice(r,r+Math.min(i,4096));break;case 176:u.width=uint();break;case 186:u.height=uint();break;case b:u.frameRate=readFloat(t,r,i);break;case d:uint()>0&&(e.timestampScale=uint());break;case f:{let n=readFloat(t,r,i);i!==0&&i!==4&&i!==8?e.warnings.push(`Duration has an invalid size of ${i} bytes`):Number.isFinite(n)?e.duration=n:e.warnings.push(`invalid Duration value ${n}`);break}case c:p=i<=4?uint():-1;break;case l:x=uint();break;case T:S.push(readUintBig(t,r,i));break;case D:k=readString(t,r,i).toUpperCase();break;case O:A=readString(t,r,i);break;case j:readString(t,r,i).startsWith(`image/`)&&e.attachedImages++;break;case 241:a?.push(e.segmentData+uint());break;default:nest()}}};walk(i,n,r,2),M&&e.warnings.push(`elements nested deeper than 16 levels ignored`)}async function headerIn(e,t){return e.cached(t,12)||withinHeaderBudget(e)?e.header(t):null}async function sparseTracks(e,t,n){let r=Math.min(n.dataStart+n.size,e.size),i=n.dataStart;for(;i<r;){let n=await headerIn(e,i);if(!n||n.size===-1)break;let a=Math.min(n.dataStart+n.size,r);if(n.id===174){let r=newTrack();for(let i=n.dataStart;i<a;){let n=await headerIn(e,i);if(!n||n.size===-1)break;let o=n.dataStart+n.size-n.pos;n.size<=65536&&n.pos+o<=a&&(e.cached(n.pos,o)||withinHeaderBudget(e,o))&&(await e.load(n.pos,o),parseMaster(t,e.buf,n.pos-e.base,n.pos-e.base+o,174,null,r)),i=n.pos+o}finishTrack(t,r)}i=n.dataStart+n.size}i<r&&t.warnings.push(`Tracks at ${n.pos} only partly read (header budget)`)}async function parseLevel1(e,t,n,r){if(r.at.add(n.pos),n.id===475249515&&(t.cuesPos??=n.pos),!B.has(n.id))return;let i=Math.max(0,Math.min(n.size,e.size-n.dataStart)),a=Math.min(i,1048576),o=e.cached(n.dataStart,a);if(n.id===374648427&&a<i&&!o){r.ids.add(n.id),await sparseTracks(e,t,n);return}if(!o&&(!withinHeaderBudget(e,a)||n.id===423732329)){n.id===374648427?(r.ids.add(n.id),await sparseTracks(e,t,n)):n.id!==423732329&&t.warnings.push(`${z.get(n.id)??hex(n.id)} element at byte ${n.pos} not read (header budget)`);return}r.ids.add(n.id),await e.load(n.dataStart,a);let s=n.dataStart-e.base;parseMaster(t,e.buf,s,s+a,n.id)}function extendSegment(e,t,n){e.segmentUnknownSize||e.segmentExtended||(e.segmentExtended=!0,e.segmentEnd=t.size,e.declaredEnd=Math.max(e.declaredEnd,t.size),e.warnings.push(`${n}: the Segment size is wrong, reading to the end of the file like ffprobe`))}async function findSegment(e,t,n){let r=n;for(let n=0;n<16&&r<e.size;n++){if(!e.cached(r,12)&&!withinHeaderBudget(e))return t.warnings.push(`Segment search stopped at ${r} (header budget)`),null;let n=await e.header(r),i=e.buf,o=r-e.base;if(i[o]===24&&i[o+1]===83&&i[o+2]===128&&i[o+3]===103)return n||(t.warnings.push(`corrupt Segment size at ${r}`),t.segmentExtended=!0,{id:a,pos:r,size:-1,dataStart:r+4+(vintLength(i[o+4])||8)});if(!n||n.size===-1)return null;r=n.dataStart+n.size}return null}async function readMatroskaHeader(e){let n={docType:`matroska`,segmentData:0,segmentEnd:0,declaredEnd:0,segmentUnknownSize:!1,segmentExtended:!1,timestampScale:1e6,duration:0,tracks:[],tagDurations:new Map,firstCluster:null,walkEnd:0,cuesPos:null,seek:new Map,attachedImages:0,warnings:[]},r=await e.header(0);if(!r||r.id!==440786851||r.size===-1||r.dataStart+r.size>e.size)throw t.a(`corrupt`,`invalid EBML header`);await e.load(r.dataStart,Math.min(r.size,4096));let i=r.dataStart-e.base;for(let t of children(e.buf,i,i+r.size))t.id===17026&&(n.docType=readString(e.buf,t.start,t.size));let canLoad=()=>withinHeaderBudget(e),s=await findSegment(e,n,r.dataStart+r.size);if(!s){let i=await findLevel1Forward(e,r.dataStart+r.size,e.size,e.size,{canLoad});if(i<0)throw t.a(`no-header`,`no Segment element`);n.warnings.push(`no valid Segment header: reading level-1 elements from ${i}`),n.segmentExtended=!0,s={id:a,pos:i,size:-1,dataStart:i}}n.segmentData=s.dataStart,n.segmentUnknownSize=s.size===-1&&!n.segmentExtended,n.declaredEnd=s.size===-1?2**53-1:s.dataStart+s.size,n.segmentEnd=Math.min(e.size,n.declaredEnd),n.declaredEnd>e.size&&s.size!==-1&&n.warnings.push(`truncated file: Segment ends ${n.declaredEnd-e.size} bytes after EOF`);let c={ids:new Set,at:new Set},l=n.segmentData,d=l,f=-1;for(;!(l>=n.segmentEnd&&(l>=e.size||(extendSegment(n,e,`Segment ends at ${l} before any Cluster`),l>=n.segmentEnd)));){if(!e.cached(l,12)&&!canLoad()){n.warnings.push(`header walk stopped at ${l} (header budget)`),f=l;break}let t=await e.header(l);if(t?.id===524531317){n.firstCluster=l;break}let r=`invalid data at ${l} before the first Cluster`;if(t&&t.size!==-1&&(P.has(t.id)||t.id===236||t.id===191)){let i=t.dataStart+t.size;if(i>n.segmentEnd&&i<=e.size&&extendSegment(n,e,`${hex(t.id)} at ${l} ends after the Segment`),await parseLevel1(e,n,t,c),d=l+1,i<=e.size){l=i;continue}r=`${hex(t.id)} at ${l} ends after the end of the file`}let i=await findLevel1Forward(e,d,e.size,Math.max(n.declaredEnd,e.size),{canLoad});if(n.warnings.push(i<0?r:`${r}: resynchronised at ${i}`),i<0)break;i>=n.segmentEnd&&extendSegment(n,e,`level-1 element at ${i} after the Segment end`),d=i+1,l=i}n.walkEnd=n.firstCluster??(f>=0?f:d);for(let t of[o,u,p,S]){let r=n.seek.get(t);if(r===void 0||c.at.has(r)||t!==290298740&&c.ids.has(t)||r>=n.segmentEnd)continue;let i=await headerIn(e,r);i?.id===t?await parseLevel1(e,n,i,c):n.warnings.push(`SeekHead entry ${hex(t)} not followed`)}if(n.cuesPos??=n.seek.get(475249515)??null,c.ids.has(357149030)||n.warnings.push(`no Info element: TimestampScale 1000000 assumed`),!n.tracks.length)throw c.ids.has(374648427)?t.a(`truncated`,`no complete TrackEntry in Tracks`):t.a(`no-header`,`no Tracks element found`);return n}const H=2147483647n,U=new Set([231,163,160,167,171,236,191]),W=new Set([161,155,251,N,30113,164,236,191]),G=new Set([231,155,251,N]);function newScanState(e,t,n,r=1/0){let i=new Map;for(let t of n){let n=Math.trunc(e.timestampScale*t.trackTimestampScale)||e.timestampScale;i.set(t.number,{track:t,tickNs:n,codecDelayTicks:Math.round(t.codecDelay/n),pts:new Float64Array(256),n:0,blocks:0,frames:0,invisible:0,missingPts:0,noPtsFrames:0,nextPts:NaN,pending:[],overLimit:0,maxPts:-1/0,maxPtsDur:0})}return{header:e,tracks:i,known:new Set(e.tracks.map(e=>e.number)),fileSize:t,maxSamples:r,clusters:0,truncated:!1,missingClusterTs:0,maxAnyTicks:-1/0,lastGood:-1,resyncs:0,afterSegment:-1,switchReads:1/0,largeWindow:0,warnings:[]}}function pushPts(e,t,n){if(e.n===e.pts.length){let t=new Float64Array(Math.max(e.n+1,Math.min(e.pts.length*2,n)));t.set(e.pts),e.pts=t}e.pts[e.n++]=t}function parseBlockHeader(e,t,n){let r=Math.min(e.length,t+n),i=readVint(e,t,r);if(!i)return null;let a=t+i.length;if(a+3>r)return null;let o=e[a]<<24>>16|e[a+1],s=e[a+2],c=1;if(s&6){if(a+4>r)return null;c=e[a+3]+1}return{track:i.value,rel:o,flags:s,laces:c}}function bigVint(e,t,n,r){if(t>=n)return`invalid`;if(t>=r)return`more`;let i=vintLength(e[t]);if(!i||t+i>n)return`invalid`;if(t+i>r)return`more`;let a=BigInt(e[t]&255>>i);for(let n=1;n<i;n++)a=a*256n+BigInt(e[t+n]);return{v:a,n:i}}function parseBlock(e,t,n,r){let i=t+n,a=Math.min(i,e.length),o=parseBlockHeader(e,t,a-t);if(!o){let n=t<a?vintLength(e[t]):0;return a<i&&(t>=a||n>0&&t+n+4>a)?`more`:`invalid`}let s=t+vintLength(e[t]);if(r&&!r.has(o.track))return`invalid`;let c=o.flags>>1&3;if(!c)return o;let l=i-s-4;if(l<0)return`invalid`;let u=o.laces,d=s+4;if(c===2)return l%u?`invalid`:o;if(c===1){let t=0;for(let n=0;n<u-1;n++){let n;do{if(l<=t)return`invalid`;if(d>=a)return`more`;n=e[d++],t+=n,l--}while(n===255)}return l<t?`invalid`:o}let f=bigVint(e,d,i,a);if(typeof f==`string`)return f;if(f.v>H)return`invalid`;let p=f.v,m=f.v;d+=f.n;for(let t=1;t<u-1;t++){if(f=bigVint(e,d,i,a),typeof f==`string`)return f;let t=p+f.v-((1n<<BigInt(7*f.n-1))-1n);if(t<0n||t>H)return`invalid`;p=t,m+=t,d+=f.n}return BigInt(i-d)<m?`invalid`:o}function emit(e,t,n,r){t.n<e.maxSamples?pushPts(t,n,e.maxSamples):t.overLimit++,n>=t.maxPts&&(t.maxPts=n,t.maxPtsDur=r),t.nextPts=n+r}function addBlock(e,t,n,r){let i=n+t.rel;i>e.maxAnyTicks&&(e.maxAnyTicks=i);let a=e.tracks.get(t.track);if(!a)return null;let o=t.laces;a.blocks++,a.frames+=o,t.flags&8&&a.invisible++;let s=r>0?r:Math.floor(a.track.defaultDuration*o/e.header.timestampScale),off=e=>Math.floor(s*e/o);if(i<0){a.noPtsFrames+=o;for(let t=0;t<o;t++)Number.isNaN(a.nextPts)?a.pending.push(off(t+1)-off(t)):emit(e,a,a.nextPts,off(t+1)-off(t));return a}let c=a.track.trackTimestampScale,l=(c===1?n:Math.floor(n/c))+t.rel-a.codecDelayTicks,u=l;for(let e of a.pending)u-=e;for(let t of a.pending.splice(0))emit(e,a,u,t),u+=t;for(let t=0;t<o;t++){if(t>0&&s===0){a.missingPts+=o-t;break}emit(e,a,l+off(t),off(t+1)-off(t))}return a}async function readBlock(e,t,n){let r=Math.min(n.size,16);for(;;){e.has(n.dataStart,r)||await e.load(n.dataStart,r);let i=parseBlock(e.buf,n.dataStart-e.base,n.size,t.known);if(i!==`more`)return i;if(r>=n.size)return`invalid`;r=Math.min(n.size,r*8)}}function cachedHeader(e,t){return e.has(t,12)?readHeader(e.buf,t-e.base,e.base):void 0}async function headerAt(e,t){return(cachedHeader(e,t)??await e.header(t))||(headerShort(e.buf,t-e.base)?`eof`:`invalid`)}function uintIn(e,t){return e.has(t.dataStart,t.size)?readUint(e.buf,t.dataStart-e.base,t.size):void 0}async function uintAt(e,t){return await e.load(t.dataStart,t.size),readUint(e.buf,t.dataStart-e.base,t.size)}function checkChild(e,t){return e.size===-1||e.dataStart+e.size>t||G.has(e.id)&&e.size>8||(e.id===163||e.id===161)&&e.size>268435456?`invalid`:null}async function walkCluster(e,t,n,r=1/0){let i=cachedHeader(e,n)??await e.header(n);if(!i||i.id!==524531317)return null;let a=t.fileSize,o=i.size===-1?1/0:i.dataStart+i.size;t.clusters++;let s=-1,c=0,l=i.dataStart,fail=e=>({next:l,videoBlocks:c,error:e});for(;l<o;){if(c>=r||t.stop)return{next:Math.min(o,l),videoBlocks:c,error:null};if(t.switchReads<=e.reader.reads&&(e.window=t.largeWindow,t.switchReads=1/0),l>=a)return o===1/0?{next:l,videoBlocks:c,error:null}:fail(`eof`);let n=cachedHeader(e,l);if(n||=await headerAt(e,l),typeof n==`string`)return fail(n);let i=U.has(n.id);if(!i&&o===1/0&&(P.has(n.id)||n.id===408125543))return{next:l,videoBlocks:c,error:null};let u=checkChild(n,o);if(u)return fail(u);i&&(t.lastGood=l);let d=n.dataStart+n.size;if(d>a)return fail(`eof`);if(n.id===231)s=uintIn(e,n)??await uintAt(e,n);else if(n.id===163||n.id===160){let r=n,i=0;if(n.id===160){r=null;for(let a=n.dataStart;a<d;){let n=cachedHeader(e,a)||await headerAt(e,a),o=typeof n==`string`?n:checkChild(n,d);if(o||typeof n==`string`)return l=a,fail(o??`invalid`);W.has(n.id)&&(t.lastGood=a),n.id===161?r=n:n.id===155&&(i=uintIn(e,n)??await uintAt(e,n)),a=n.dataStart+n.size}}if(r){let n=e.has(r.dataStart,Math.min(r.size,16))?parseBlock(e.buf,r.dataStart-e.base,r.size,t.known):`more`;if(n===`more`&&(n=await readBlock(e,t,r)),n===`invalid`)return fail(`invalid`);s<0&&(t.missingClusterTs++,s=0);let a=addBlock(t,n,s,i);t.onBlock?.(n,s,i,r),a&&a.track.type===1&&c++}}l=d}return{next:o,videoBlocks:c,error:null}}function noteResync(e,t,n,r){n<0&&r===`eof`?e.truncated=!0:++e.resyncs>5||(n<0?e.warnings.push(`invalid data at ${t}, no further level-1 element`):n>=t?e.warnings.push(`skipped ${n-t} bytes of invalid data at ${t}`):e.warnings.push(`invalid data at ${t}: resynchronised at ${n}`))}async function scanSegment(e,t,n,r){let i=t.header,a=t.fileSize,o=i.segmentUnknownSize||i.segmentExtended?1/0:i.declaredEnd,s=n;for(t.lastGood=n-1;!t.stop;){e.reader.checkAbort(),r?.(s,Math.min(a,o));let n=null,i=s;if(s>=a){s<o&&o!==1/0&&(t.truncated=!0);break}if(s>=o){o=1/0;let n=await findLevel1Forward(e,Math.max(t.lastGood+1,s),a,1/0);if(n<0)break;t.afterSegment<0&&(t.afterSegment=s),s=n;continue}let c=await headerAt(e,s);if(typeof c==`string`)n=c;else{let r=P.has(c.id)||c.id===236||c.id===191;if(c.id===408125543&&o===1/0?(t.afterSegment<0&&(t.afterSegment=s),n=`invalid`):c.size===-1?c.id===524531317?o=1/0:n=`invalid`:c.dataStart+c.size>o&&(n=`invalid`),!n){if(r&&(t.lastGood=s),c.id===524531317){let r=await walkCluster(e,t,s);r.error?(n=r.error,i=r.next):s=r.next}else c.dataStart+c.size>a?n=`eof`:s=c.dataStart+c.size}}if(!n)continue;o=1/0;let l=await findLevel1Forward(e,t.lastGood+1,a,1/0);if((n!==`invalid`||i!==t.afterSegment)&&noteResync(t,i,l,n),l<0)break;s=l}t.resyncs>5&&t.warnings.push(`${t.resyncs-5} more resynchronisation(s) after invalid data`),t.afterSegment>=0&&t.warnings.push(`data after the Segment end at ${t.afterSegment} was scanned like ffprobe does (concatenated files?)`)}async function findLastClusters(e,t,n,r){await e.load(t,n-t,n-t);let i=e.buf,a=e.base,o=[];for(let e=n-a-4;e>=t-a;e--)i[e]===31&&isClusterAt(i,e,r-a)&&o.push(a+e);return o}const K=4096,q=16777216,J=524288,Y=262144,X=5e6,ee=new Set([231,236,191,167,171]),te=n.t.perBlockMs,Z=`no DefaultDuration: avg_frame_rate and r_frame_rate `,Q=`${Z}come from the first packets, which header mode does not read`;function codecNameOf(e){for(let t of`V_AV1:av1 V_VP8:vp8 V_VP9:vp9 V_MPEG4/ISO/AVC:h264 V_MPEGH/ISO/HEVC:hevc V_MPEGI/ISO/VVC:vvc V_MPEG4/ISO/ASP:mpeg4 V_MPEG4/ISO/AP:mpeg4 V_MPEG4/ISO/SP:mpeg4 V_MPEG4/MS/V3:msmpeg4v3 V_MPEG1:mpeg1video V_MPEG2:mpeg2video V_PRORES:prores V_MJPEG:mjpeg V_FFV1:ffv1 V_THEORA:theora V_UNCOMPRESSED:rawvideo V_DIRAC:dirac`.split(` `)){let[n,r]=t.split(`:`);if(e.startsWith(n))return r}return``}function declaredRate(e){if(!(e>0))return null;let t=r.a(1e9,e,3e4),n=r.o(t);return{avg:n,r:t.num<t.den*1e3&&t.num>t.den*5?n:null}}function mergeRunStats(e,t){let n=new Map,r={minFps:null,maxFps:null,isVfr:null,vfrRatio:0,distinctDeltas:0,duplicateTimestamps:0,timestampsQuantized:!1,medianDelta:null,medianFrameInterval:null},a=0;for(let e of t){r.duplicateTimestamps+=e.duplicateTimestamps;for(let[t,r]of e.histogram)n.set(t,(n.get(t)??0)+r),a+=r}let o=[...n.keys()].sort((e,t)=>e-t);if(r.distinctDeltas=o.length,a===0)return r;let s=0,c=o.find(e=>(s+=n.get(e)??0)*2>=a)??o[0],l=i.vfrTolerance(c,e,o),u=0;for(let e of o)Math.abs(e-c)>l&&(u+=n.get(e)??0);r.medianDelta=c;let d=i.rateFromTicks(e,c);return r.medianFrameInterval=d&&{num:d.den,den:d.num,value:d.den/d.num},r.minFps=i.rateFromTicks(e,o[o.length-1]),r.maxFps=i.rateFromTicks(e,o[0]),r.isVfr=a>=2&&u>0,r.vfrRatio=u/a,r.timestampsQuantized=!r.isVfr&&o.length>1,r}function fillRates(e,t,n){e.minFps=t.minFps,e.maxFps=t.maxFps,e.isVfr=t.isVfr,e.vfrRatio=t.vfrRatio,e.distinctDeltas=t.distinctDeltas,e.duplicateTimestamps=t.duplicateTimestamps,e.timestampsQuantized=t.timestampsQuantized,e.medianFrameInterval=t.medianFrameInterval;for(let t of[`minFps`,`maxFps`,`isVfr`,`duplicateTimestamps`,`medianFrameInterval`])e.provenance[t]=n}function headerTrack(t,n,i){let a=e.l(n.number);i.codecConfig&&(a.codecConfig={family:`matroska`,trackEntry:n.entry??null}),a.fourccOrCodecId=n.codecId,a.codecName=codecNameOf(n.codecId),a.width=n.width,a.height=n.height,a.enabled=!n.disabled,a.timescale=1e9/(Math.trunc(t.timestampScale*n.trackTimestampScale)||t.timestampScale),a.provenance.codec=a.provenance.dimensions=`header`;let o=declaredRate(n.defaultDuration);o?(a.avgFpsFfprobe=o.avg,a.rFpsFfprobe=o.r,a.nominalFps={...r.a(1e9,n.defaultDuration,3e4),kind:`declared`},a.provenance.nominalFps=`header`,n.frameRate>0&&n.defaultDuration===Math.trunc(1e9/n.frameRate)&&a.warnings.push(`DefaultDuration derived from Video FrameRate ${n.frameRate}`)):a.warnings.push(Q);let s=t.tagDurations.get(n.uid);return s!==void 0&&(a.durationSec=s,a.provenance.durationSec=`header`),a}function infoDurationSec(e){return e.duration*e.timestampScale/1e9}function warnEstimatedFrames(e,t,n){let r=n.durationSec??infoDurationSec(e);r>0&&t.defaultDuration>0&&n.warnings.push(`about ${Math.round(r*1e9/t.defaultDuration)} frames (estimated from duration x DefaultDuration, assumes CFR)`)}function warnInfoDuration(e,t,n){let r=infoDurationSec(e),i=t*e.timestampScale/1e9;r>0&&Number.isFinite(i)&&r-i>Math.max(.5,.02*r)&&n.push(`Info Duration ${r.toFixed(3)} s exceeds the last block at ${i.toFixed(3)} s (false Duration or truncated file)`)}function setScannedDuration(e,t,n){e.provenance.durationSec===`header`&&e.durationSec!==null&&Math.abs(e.durationSec-t)>Math.max(2/e.timescale,1/(e.nominalFps?.value||1/0))&&e.warnings.push(`DURATION tag ${e.durationSec.toFixed(3)} s differs from the scanned ${t.toFixed(3)} s`),e.durationSec=t,e.provenance.durationSec=n}async function sampleDensity(e,t,n,r){let i=Math.min(r,16384);await e.load(n,i,i);let a=e.chunkAt(n);if(!a)return null;let o=a.buf,s=a.base,c=s+o.length,l={bytes:0,blocks:0,video:0,large:0,smallBytes:0},u=n;for(;u<c;){let e=readHeader(o,u-s,s);if(e?.id===524531317){u=e.dataStart;continue}if(!e||e.size===-1)break;let i=e.dataStart+e.size,a=e.id===163||e.id===160;if(a?e.size>268435456||i>n+r:i>c||!ee.has(e.id))break;if(a){let n=e.id===160?readHeader(o,e.dataStart-s,s):e,r=n&&(n.id===163||n.id===161)?parseBlockHeader(o,n.dataStart-s,n.size):null,a=r&&t.some(e=>e.number===r.track)?r.laces:0;l.blocks+=Math.max(1,a),l.video+=a,i-e.pos>=4096?l.large++:l.smallBytes+=i-e.pos}l.bytes=i-n,u=i}return l.blocks&&l.bytes>0?l:null}function estimateScan(e,t,n){if(!t){if(!(n>0))return null;let t=e/n>=K;return{blocks:n,large:t?n:0,smallBytes:t?0:e}}let r=e/t.bytes,i=t.video*r;return{blocks:t.blocks*r*(t.video>0&&n>i?n/i:1),large:t.large*r,smallBytes:t.smallBytes*r}}function estimateWalkMs(e,t,r){let i=Math.min(e,X,t?.video?Math.ceil(48*t.bytes/t.video):X);return n.i(r.costModel,Math.ceil(i/r.readAhead.head),i)}function planExactScan(e,t,r){let i=(t?.blocks??0)*r.costModel.perBlockMs,plan=(e,t,a)=>({window:e,reads:t,bytes:a,ms:n.i(r.costModel,t,a)+i}),a=r.readAhead.matroskaScan,o=plan(a,Math.ceil(e/a),e);if(!t)return o;let s=Math.ceil(t.large+t.smallBytes/K),c=plan(K,s,Math.min(e,s*K));return c.ms<o.ms?c:o}const $={newScanState,addBlock};async function loadEstimate(){try{return await Promise.resolve().then(()=>require("./rfps-C-pyKnu8.cjs"))}catch{return`the estimate code did not load`}}async function settle(e,t){try{return await t()}catch(t){return e.reader.checkAbort(),`the estimate failed: ${t instanceof Error?t.message:String(t)}`}}async function exactScan(e,t,n,r){let i=e.reader,a=r.onProgress,o=i.reads,s=t.header.segmentEnd-n;a?.({phase:`matroska-exact`,done:0,total:s}),await scanSegment(e,t,n,(e,t)=>{s=Math.max(s,t-n),a&&i.reads!==o&&(o=i.reads,a({phase:`matroska-exact`,done:Math.min(e-n,s),total:s}))}),a?.({phase:`matroska-exact`,done:s,total:s})}async function findFirstCluster(e,t){let n=t.firstCluster===null?null:await e.header(t.firstCluster);if(n?.id===524531317)return n.pos;let r=Math.max(t.segmentData,t.walkEnd),i=await findClusterForward(e,r,Math.min(t.segmentEnd,r+16777216),t.declaredEnd,{step:Y});if(i>=0)return i;for(let n of(await cuePositions(e,t)).slice(0,4))if((await e.header(n))?.id===524531317)return n;return null}async function cuePositions(e,t){let n=t.cuesPos===null||t.cuesPos>=t.segmentEnd?null:await e.header(t.cuesPos);if(n?.id!==475249515||n.size===-1)return[];let r=Math.min(n.size,J,e.size-n.dataStart);await e.load(n.dataStart,r,r);let i=[];return parseMaster(t,e.buf,n.dataStart-e.base,n.dataStart-e.base+r,x,i),[...new Set(i)].filter(e=>e<t.segmentEnd).sort((e,t)=>e-t)}function pickEvenly(e,t){return e.length<=t?[...e]:[...new Set(Array.from({length:t},(n,r)=>e[Math.round(r*(e.length-1)/(t-1))]))]}async function tailScan(e,t,n,r,i){let a=Math.max(i.readAhead.tail||0,4096),o=t.segmentEnd,s=-1/0;for(;;){let i=Math.max(r,t.segmentEnd-a);for(let r of i<o?await findLastClusters(e,i,o,t.declaredEnd):[]){let i=newScanState(t,e.size,n);if(await walkCluster(e,i,r),s=Math.max(s,i.maxAnyTicks),i.tracks.get(n[0].number)?.n)return{st:i,maxAnyTicks:s}}if(i<=r||a>=16777216)return null;o=i+4,a=Math.min(a*4,q)}}async function probeScan(e,t,n,r,a,o,s){let c=await tailScan(e,t,n,a,o),l=await cuePositions(e,t),u=pickEvenly(l[0]===a||!l.length?l:[a,...l.filter(e=>e>a)],8);if(!l.length){u=[a];let n=t.segmentEnd-a;for(let r=1;r<8;r++){let i=a+Math.floor(r*n/8),o=await findClusterForward(e,i,Math.min(t.segmentEnd,i+1048576),t.declaredEnd,{step:Y});o>u[u.length-1]&&u.push(o)}}let d=new Map,f=null,p=0;for(let r of u){let o=newScanState(t,e.size,n);if(await walkCluster(e,o,r,32)){p++,r===a&&(f=o);for(let e of o.tracks.values()){if(e.n<2)continue;let t=d.get(e.track.number)??[];t.push(i.analyzeTimeline({timescale:1e9/e.tickNs,pts:e.pts.subarray(0,e.n),tickQuantized:!0})),d.set(e.track.number,t)}}}s.push(`probe: ${p} cluster(s) sampled via ${l.length?`Cues`:`sync search`}, up to 32 video blocks each`),c||s.push(`probe: no video block found in the tail`),warnInfoDuration(t,c?.maxAnyTicks??-1/0,s),n.forEach((e,n)=>{let i=r[n],a=i.timescale,o=mergeRunStats(a,d.get(e.number)??[]);o.isVfr===null?p>0&&i.warnings.push(`probe: every sampled cluster holds fewer than 2 frames of this track, so no frame interval was measured; scan all frames for min, max and VFR`):fillRates(i,o,`sampled`);let s=f?.tracks.get(e.number),l=s?.n?Math.min(...s.pts.subarray(0,s.n)):null;l!==null&&(i.startSec=l/a,i.provenance.startSec=`sampled`);let u=c?.st.tracks.get(e.number);u?.n&&setScannedDuration(i,(u.maxPts+(u.maxPtsDur>0?u.maxPtsDur:o.medianDelta??0)-(l??0))/a,`sampled`),warnEstimatedFrames(t,e,i)})}function applyExact(e,t){let n=e.timescale;if(e.frames=e.presentedFrames=t.frames,e.provenance.frames=e.provenance.presentedFrames=`computed`,e.isStill=t.frames===1,t.invisible&&e.warnings.push(`${t.invisible} invisible block(s) counted as frames`),t.missingPts&&e.warnings.push(`${t.missingPts} laced frame(s) without a timestamp`),t.noPtsFrames&&e.warnings.push(`${t.noPtsFrames} frame(s) before time 0 have no timestamp; interpolated from the neighbouring frames like ffmpeg`),t.overLimit&&e.warnings.push(`per-frame statistics skipped: more than ${t.n} frames`),!t.n||t.overLimit)return t.n||e.warnings.push(`no blocks for this track`),null;let a=i.analyzeTimeline({timescale:n,pts:t.pts.subarray(0,t.n),lastDuration:t.maxPtsDur>0?t.maxPtsDur:null,tickQuantized:!0});return e.warnings.push(...a.warnings),setScannedDuration(e,a.durationSum/n,`exact`),fillRates(e,a,`exact`),e.avgFps=t.frames!==t.n&&Number.isSafeInteger(n)&&Number.isSafeInteger(a.durationSum)?r.r(n,t.frames,a.durationSum):a.avgFps,e.startSec=a.firstPts===null?null:a.firstPts/n,e.dominantFps=a.dominantFps,e.provenance.avgFps=e.provenance.startSec=e.provenance.dominantFps=`exact`,!e.nominalFps&&a.nominalFps?(e.nominalFps=a.nominalFps,e.provenance.nominalFps=`exact`):e.nominalFps&&e.avgFps&&Math.abs(e.avgFps.value/e.nominalFps.value-1)>.005&&e.warnings.push(`declared rate ${e.avgFpsFfprobe} differs from the measured average ${e.avgFps.value.toFixed(3)}`),a.duplicateTimestamps&&e.warnings.push(`${a.duplicateTimestamps} duplicate block timestamp(s) excluded from the instantaneous rates`),a.profile}async function analyzeMatroska(t,n){let r=new ByteSource(t,n.readAhead.head),a=await readMatroskaHeader(r),o=e.c(a.docType===`webm`?`webm`:`matroska`),s=o.warnings;o.brand=a.docType,o.scan=`header`,s.push(...a.warnings),a.docType!==`webm`&&a.docType!==`matroska`&&s.push(`unexpected DocType '${a.docType}'`),a.segmentUnknownSize&&s.push(`Segment has an unknown size (live or unfinished recording)`),o.formatDurationSec=a.duration===0?null:Math.trunc(a.duration*a.timestampScale*1e3/1e6)/1e6,o.audioTrackCount=a.tracks.filter(e=>e.type===2).length,a.attachedImages&&s.push(`${a.attachedImages} attached image(s) ignored: ffprobe lists them as attached_pic video streams`);let c=a.tracks.filter(e=>e.type===1);if(!c.length)return s.push(`no video track`),o;o.primaryTrackId=c[0].number,o.videoTracks=c.map(e=>headerTrack(a,e,n));let l=n.matroskaMode,u=null;if(l!==`header`&&(u=await findFirstCluster(r,a),u===null&&s.push(`no Cluster found: nothing to scan`)),u===null)return c.forEach((e,t)=>warnEstimatedFrames(a,e,o.videoTracks[t])),o;let d=a.segmentEnd-u,f=c[0],p=a.tagDurations.get(f.uid)??infoDurationSec(a),m=p>0&&f.defaultDuration>0?p*1e9/f.defaultDuration:0,h=await sampleDensity(r,c,u,d),g=planExactScan(d,estimateScan(d,h,m),n),_=f.defaultDuration?null:await loadEstimate();if(l===`auto`){let e=typeof _==`object`&&_&&!_.setupUnsupported(a)?estimateWalkMs(d,h,n):0;l=g.ms<=n.exactBudgetMs+e?`exact`:`probe`;let t=e?` plus the ${e.toFixed(0)} ms that probe mode reads for the ffprobe estimate`:``;l===`probe`&&s.push(`exact block scan skipped: predicted ${g.ms.toFixed(0)} ms exceeds the ${n.exactBudgetMs} ms budget${t}`)}let v=o.videoTracks[0],note=e=>{typeof e!=`string`&&(v.avgFpsFfprobe=e.avg,v.rFpsFfprobe=e.r),v.warnings[v.warnings.indexOf(Q)]=typeof e==`string`?`${Z}not reproduced (${e})`:`${Z}estimated like ffprobe from ${e.packets} video packets`};if(l===`exact`){r.window=g.window;let e=newScanState(a,r.size,c,n.maxExpandedSamples);g.window<n.readAhead.matroskaScan&&(e.switchReads=t.reads+2*g.reads+16,e.largeWindow=n.readAhead.matroskaScan);let l=typeof _==`object`&&_?_.attachEstimate(r,a,$,e):_;await exactScan(r,e,u,n),l!==null&&note(typeof l==`function`?await settle(r,l):l),o.scan=`exact`,s.push(...e.warnings),e.truncated&&s.push(`truncated file: the last Cluster or block ends beyond EOF`),e.missingClusterTs&&s.push(`${e.missingClusterTs} block(s) in Clusters without a Timestamp`),warnInfoDuration(a,e.maxAnyTicks,s);for(let[t,n]of c.entries()){let r=o.videoTracks[t];r.rateProfile=await i.rateProfileOf(applyExact(r,e.tracks.get(n.number)))}return o}if(_!==null){let e=newScanState(a,r.size,[]),t=typeof _==`string`?_:_.attachEstimate(r,a,$,e,!0);note(typeof t==`string`?t:await settle(r,()=>scanSegment(r,e,u).then(t)))}return r.window=g.window===4096?K:n.readAhead.head,await probeScan(r,a,c,o.videoTracks,u,n,s),o.scan=`probe`,o}exports.CPU_MS_PER_BLOCK=te,exports.LARGE_FRAME_BYTES=32768,exports.MAX_CUES_BYTES=J,exports.MAX_TAIL_BYTES=q,exports.PROBE_BLOCKS=32,exports.PROBE_CLUSTERS=8,exports.SMALL_SCAN_WINDOW=K,exports.analyzeMatroska=analyzeMatroska,exports.codecNameOf=codecNameOf,exports.declaredRate=declaredRate,exports.estimateScan=estimateScan,exports.estimateWalkMs=estimateWalkMs,exports.mergeRunStats=mergeRunStats,exports.planExactScan=planExactScan;