caelum0x d56639a594
Some checks failed
build-images / web (push) Has been cancelled
vision2026-ci / Python SDK resource tests (push) Has been cancelled
build-images / api (push) Has been cancelled
build-images / worker-gpu (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (comfy-workflow-schema) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (effects-core) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (eventbus-types) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (growth-analytics) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (provider-adapter-kit) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (publishing-connectors) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (render-core) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (shot-template-schema) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (trends-schema) (push) Has been cancelled
vision2026-ci / Desktop engine crates (test + clippy + fmt) (push) Has been cancelled
codeql / Analyze (javascript-typescript) (push) Has been cancelled
codeql / Analyze (python) (push) Has been cancelled
perf / API hot-path micro-smoke (budgeted) (push) Has been cancelled
perf / Desktop engine crates (release build check) (push) Has been cancelled
vision2026-ci / API phase modules (ruff + pytest) (push) Has been cancelled
vision2026-ci / Alembic upgrade + drift check (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (caption-engine) (push) Has been cancelled
Menivor — open source release (MIT), free to use and fork
Paid, hosted product at menivor.com, now retired as a company project.
Fresh squashed history of the cleaned working tree (secret-scanned,
no .env, no customer data, no outreach logs). Built on
MoneyPrinterTurbo (MIT, harry0703) — see NOTICE.
2026-12-04 02:10:26 +03:00

447 lines
17 KiB
TypeScript

/**
* Pure calculators behind the free video tools: aspect ratio / resolution
* for TikTok, Reels and Shorts, and bitrate <-> file size. All units are
* explicit; no DOM, so the math is unit-tested.
*/
export interface PlatformSpec {
readonly key: string;
readonly name: string;
readonly ratio: string;
readonly width: number;
readonly height: number;
readonly note: string;
}
/** Recommended upload sizes (public platform help pages, 2026). */
export const PLATFORM_SPECS: readonly PlatformSpec[] = [
{ key: "tiktok", name: "TikTok", ratio: "9:16", width: 1080, height: 1920, note: "Full-screen vertical. Keep text out of the bottom fifth and the right edge." },
{ key: "reels", name: "Instagram Reels", ratio: "9:16", width: 1080, height: 1920, note: "Grid preview crops to 3:4, so keep the subject centred." },
{ key: "shorts", name: "YouTube Shorts", ratio: "9:16", width: 1080, height: 1920, note: "Vertical or square, up to 3 minutes." },
{ key: "ig-feed-portrait", name: "Instagram feed (portrait)", ratio: "4:5", width: 1080, height: 1350, note: "Tallest ratio the feed shows without cropping." },
{ key: "square", name: "Square post", ratio: "1:1", width: 1080, height: 1080, note: "Feeds on Instagram, Facebook and LinkedIn." },
{ key: "youtube", name: "YouTube (landscape)", ratio: "16:9", width: 1920, height: 1080, note: "Standard HD; 3840x2160 for 4K." },
];
function gcd(a: number, b: number): number {
let x = Math.abs(Math.round(a));
let y = Math.abs(Math.round(b));
while (y) {
[x, y] = [y, x % y];
}
return x || 1;
}
/** Reduce width x height to the simplest ratio, e.g. 1080x1920 -> "9:16". */
export function simplifyRatio(width: number, height: number): string {
if (!(width > 0) || !(height > 0)) return "";
const divisor = gcd(width, height);
return `${Math.round(width) / divisor}:${Math.round(height) / divisor}`;
}
/** Parse "9:16", "9x16" or "1.91:1" into a positive [w, h] pair. */
export function parseRatio(value: string): readonly [number, number] | null {
const match = /^\s*(\d+(?:\.\d+)?)\s*[:x/]\s*(\d+(?:\.\d+)?)\s*$/i.exec(value);
if (!match) return null;
const w = Number(match[1]);
const h = Number(match[2]);
return w > 0 && h > 0 ? [w, h] : null;
}
/** Round to the nearest even pixel (H.264/H.265 need even dimensions). */
export function toEven(value: number): number {
return Math.max(2, Math.round(value / 2) * 2);
}
/** Given a ratio and one side, compute the other side (even pixels). */
export function solveDimension(
ratio: readonly [number, number],
known: { readonly width?: number; readonly height?: number },
): { width: number; height: number } | null {
const [rw, rh] = ratio;
if (known.width && known.width > 0) {
return { width: toEven(known.width), height: toEven((known.width * rh) / rw) };
}
if (known.height && known.height > 0) {
return { width: toEven((known.height * rw) / rh), height: toEven(known.height) };
}
return null;
}
export interface FitResult {
/** Scaled source size inside the target frame. */
readonly width: number;
readonly height: number;
/** Bars (pad) or cropped pixels on each axis, total. */
readonly padX: number;
readonly padY: number;
readonly mode: "pad" | "crop";
}
/**
* Fit a source frame into a target frame. "pad" letterboxes (whole frame
* visible), "crop" fills the target and trims the overflow.
*/
export function fitFrame(
source: { readonly width: number; readonly height: number },
target: { readonly width: number; readonly height: number },
mode: "pad" | "crop",
): FitResult {
const scaleX = target.width / source.width;
const scaleY = target.height / source.height;
const scale = mode === "pad" ? Math.min(scaleX, scaleY) : Math.max(scaleX, scaleY);
const width = toEven(source.width * scale);
const height = toEven(source.height * scale);
return {
width,
height,
padX: Math.abs(target.width - width),
padY: Math.abs(target.height - height),
mode,
};
}
/** File size in megabytes (10^6 bytes) for a total bitrate and duration. */
export function fileSizeMB(videoKbps: number, audioKbps: number, durationSec: number): number {
const totalKbps = Math.max(0, videoKbps) + Math.max(0, audioKbps);
return (totalKbps * 1000 * Math.max(0, durationSec)) / 8 / 1_000_000;
}
/**
* Video bitrate (kbps) that hits a target file size, after reserving audio
* and ~2% container overhead. Never negative.
*/
export function videoBitrateForSize(
targetMB: number,
durationSec: number,
audioKbps: number,
overhead = 0.02,
): number {
if (!(durationSec > 0) || !(targetMB > 0)) return 0;
const totalKbps = (targetMB * 1_000_000 * 8 * (1 - overhead)) / durationSec / 1000;
return Math.max(0, Math.floor(totalKbps - Math.max(0, audioKbps)));
}
/** Parse "1:30", "01:02:03" or "90" into seconds. */
export function parseDuration(value: string): number | null {
const parts = value.trim().split(":").map((part) => part.trim());
if (parts.length === 0 || parts.length > 3 || parts.some((p) => !/^\d+(\.\d+)?$/.test(p))) {
return null;
}
return parts.reduce((total, part) => total * 60 + Number(part), 0);
}
export interface BitratePreset {
readonly label: string;
readonly width: number;
readonly height: number;
readonly fps: number;
/** Typical H.264 kbps range for upload-quality short video. */
readonly minKbps: number;
readonly maxKbps: number;
}
/** Common H.264 upload bitrates (YouTube's published recommendations, SDR). */
export const BITRATE_PRESETS: readonly BitratePreset[] = [
{ label: "1080x1920 vertical, 30 fps", width: 1080, height: 1920, fps: 30, minKbps: 8000, maxKbps: 12000 },
{ label: "1080x1920 vertical, 60 fps", width: 1080, height: 1920, fps: 60, minKbps: 12000, maxKbps: 15000 },
{ label: "720x1280 vertical, 30 fps", width: 720, height: 1280, fps: 30, minKbps: 5000, maxKbps: 7500 },
{ label: "1920x1080 landscape, 30 fps", width: 1920, height: 1080, fps: 30, minKbps: 8000, maxKbps: 12000 },
{ label: "3840x2160 (4K), 30 fps", width: 3840, height: 2160, fps: 30, minKbps: 35000, maxKbps: 45000 },
];
/** Bits per pixel per frame: a codec-agnostic quality sanity check. */
export function bitsPerPixel(kbps: number, width: number, height: number, fps: number): number {
if (!(width > 0 && height > 0 && fps > 0)) return 0;
return (kbps * 1000) / (width * height * fps);
}
export interface SpeakingPacePreset {
readonly label: string;
readonly wpm: number;
}
/** Common spoken-word pacing presets for script/voiceover timing. */
export const SPEAKING_PACE_PRESETS: readonly SpeakingPacePreset[] = [
{ label: "Slow, deliberate", wpm: 120 },
{ label: "Natural speaking pace", wpm: 150 },
{ label: "Fast, energetic", wpm: 170 },
];
/** Spoken word count for a duration in seconds at a given words-per-minute pace. */
export function wordsForDuration(durationSec: number, wpm: number): number {
if (!(durationSec > 0) || !(wpm > 0)) return 0;
return Math.round((durationSec / 60) * wpm);
}
/** Duration in seconds needed to speak a word count at a given words-per-minute pace. */
export function durationForWords(words: number, wpm: number): number {
if (!(words > 0) || !(wpm > 0)) return 0;
return Math.round((words / wpm) * 60);
}
export interface EngagementBenchmark {
readonly key: string;
readonly name: string;
/** Inclusive lower/upper bounds, in percent, for a "typical" (not top-performer) post. */
readonly typicalLowPct: number;
readonly typicalHighPct: number;
}
/**
* Typical (not top-performer) engagement-rate bands by platform, follower-normalised
* (engagements / followers). Sourced from publicly reported cross-platform benchmark
* studies, 2026; used only to label a result as below/within/above typical, never
* presented as a guaranteed outcome.
*/
export const ENGAGEMENT_BENCHMARKS: readonly EngagementBenchmark[] = [
{ key: "tiktok", name: "TikTok", typicalLowPct: 3, typicalHighPct: 9 },
{ key: "instagram", name: "Instagram", typicalLowPct: 1, typicalHighPct: 3 },
{ key: "youtube", name: "YouTube (Shorts)", typicalLowPct: 1, typicalHighPct: 5 },
{ key: "x", name: "X (Twitter)", typicalLowPct: 0.5, typicalHighPct: 1.5 },
{ key: "linkedin", name: "LinkedIn", typicalLowPct: 2, typicalHighPct: 5 },
{ key: "facebook", name: "Facebook", typicalLowPct: 0.5, typicalHighPct: 2 },
];
export function benchmarkFor(key: string): EngagementBenchmark | undefined {
return ENGAGEMENT_BENCHMARKS.find((b) => b.key === key);
}
/**
* Engagement rate as a percent of an audience size: (likes + comments + shares + saves)
* / audience * 100. `audience` is followers for an ER-by-followers read, or views/reach
* for an ER-by-views read — the caller picks which denominator to pass in. Returns 0 when
* the audience size is not a positive number, rather than Infinity or NaN.
*/
export function engagementRate(engagements: number, audience: number): number {
if (!(audience > 0) || !(engagements >= 0)) return 0;
return (engagements / audience) * 100;
}
export type EngagementTier = "below" | "within" | "above";
/** Classify a computed engagement-rate percent against a platform's typical band. */
export function engagementTier(ratePct: number, benchmark: EngagementBenchmark): EngagementTier {
if (ratePct < benchmark.typicalLowPct) return "below";
if (ratePct > benchmark.typicalHighPct) return "above";
return "within";
}
export type Weekday = "mon" | "tue" | "wed" | "thu" | "fri" | "sat" | "sun";
export const WEEKDAYS: readonly Weekday[] = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"];
export const WEEKDAY_LABELS: Record<Weekday, string> = {
mon: "Monday",
tue: "Tuesday",
wed: "Wednesday",
thu: "Thursday",
fri: "Friday",
sat: "Saturday",
sun: "Sunday",
};
export interface BestPostSlot {
readonly day: Weekday;
/** Hour of day, 0-23, in the anchor time zone (US Eastern Standard Time, UTC-5). */
readonly hour: number;
readonly note?: string;
}
export interface BestTimePlatform {
readonly key: string;
readonly name: string;
readonly slots: readonly BestPostSlot[];
}
/** Anchor zone every slot below is written in: US Eastern Standard Time. DST is not modelled. */
export const BEST_TIME_ANCHOR_OFFSET_HOURS = -5;
/**
* Typical best-performing posting hours per platform and weekday, in US Eastern
* Standard Time (the zone most publicly reported social scheduling studies use).
* Sourced from aggregate 2026 cross-platform posting-time research (Sprout Social,
* Hootsuite, Later, SocialPilot); presented as a starting point, not a guarantee —
* a creator's own audience-activity analytics always beats a generic benchmark.
*/
export const BEST_POST_TIMES: readonly BestTimePlatform[] = [
{
key: "tiktok",
name: "TikTok",
slots: [
{ day: "mon", hour: 6 }, { day: "mon", hour: 10 },
{ day: "tue", hour: 2 }, { day: "tue", hour: 9 },
{ day: "wed", hour: 7 }, { day: "wed", hour: 8 },
{ day: "thu", hour: 9 }, { day: "thu", hour: 12 },
{ day: "fri", hour: 5 }, { day: "fri", hour: 15 },
{ day: "sat", hour: 11 },
{ day: "sun", hour: 7 }, { day: "sun", hour: 20 },
],
},
{
key: "instagram",
name: "Instagram",
slots: [
{ day: "mon", hour: 11 },
{ day: "tue", hour: 11 }, { day: "tue", hour: 14 },
{ day: "wed", hour: 11 }, { day: "wed", hour: 13 },
{ day: "thu", hour: 11 },
{ day: "fri", hour: 11 },
{ day: "sat", hour: 10 },
{ day: "sun", hour: 10 }, { day: "sun", hour: 14 },
],
},
{
key: "youtube",
name: "YouTube (Shorts)",
slots: [
{ day: "mon", hour: 14 }, { day: "mon", hour: 16 },
{ day: "tue", hour: 14 },
{ day: "wed", hour: 14 },
{ day: "thu", hour: 12 }, { day: "thu", hour: 15 },
{ day: "fri", hour: 12 },
{ day: "sat", hour: 9 }, { day: "sat", hour: 11 },
{ day: "sun", hour: 9 }, { day: "sun", hour: 11 },
],
},
{
key: "linkedin",
name: "LinkedIn",
slots: [
{ day: "mon", hour: 9 }, { day: "mon", hour: 10 },
{ day: "tue", hour: 9 }, { day: "tue", hour: 12 },
{ day: "wed", hour: 9 }, { day: "wed", hour: 12 },
{ day: "thu", hour: 9 }, { day: "thu", hour: 13 },
{ day: "fri", hour: 9 },
{ day: "sat", note: "B2B audience is largely offline — skip if you can.", hour: NaN },
{ day: "sun", note: "B2B audience is largely offline — skip if you can.", hour: NaN },
],
},
{
key: "x",
name: "X (Twitter)",
slots: [
{ day: "mon", hour: 9 },
{ day: "tue", hour: 9 }, { day: "tue", hour: 12 },
{ day: "wed", hour: 9 }, { day: "wed", hour: 15 },
{ day: "thu", hour: 9 },
{ day: "fri", hour: 9 },
{ day: "sat", hour: 11 },
{ day: "sun", hour: 11 },
],
},
{
key: "facebook",
name: "Facebook",
slots: [
{ day: "mon", hour: 13 },
{ day: "tue", hour: 13 }, { day: "tue", hour: 15 },
{ day: "wed", hour: 11 }, { day: "wed", hour: 13 },
{ day: "thu", hour: 13 },
{ day: "fri", hour: 13 }, { day: "fri", hour: 15 },
{ day: "sat", hour: 12 },
{ day: "sun", hour: 12 },
],
},
];
export function bestTimesFor(key: string): BestTimePlatform | undefined {
return BEST_POST_TIMES.find((p) => p.key === key);
}
export interface TimezonePreset {
readonly key: string;
readonly label: string;
readonly offsetHours: number;
}
/** Common, named UTC offsets (standard time; half-hour zones use a .5 offset). */
export const TIMEZONE_PRESETS: readonly TimezonePreset[] = [
{ key: "pt", label: "Pacific Time (UTC-8)", offsetHours: -8 },
{ key: "mt", label: "Mountain Time (UTC-7)", offsetHours: -7 },
{ key: "ct", label: "Central Time (UTC-6)", offsetHours: -6 },
{ key: "et", label: "Eastern Time (UTC-5)", offsetHours: -5 },
{ key: "utc", label: "UTC", offsetHours: 0 },
{ key: "cet", label: "Central European Time (UTC+1)", offsetHours: 1 },
{ key: "eet", label: "Eastern European Time (UTC+2)", offsetHours: 2 },
{ key: "ist-ru", label: "Istanbul / Moscow (UTC+3)", offsetHours: 3 },
{ key: "gst", label: "Gulf Time (UTC+4)", offsetHours: 4 },
{ key: "ist-in", label: "India (UTC+5:30)", offsetHours: 5.5 },
{ key: "ict", label: "Indochina (UTC+7)", offsetHours: 7 },
{ key: "sgt", label: "Singapore / China (UTC+8)", offsetHours: 8 },
{ key: "jst", label: "Japan / Korea (UTC+9)", offsetHours: 9 },
{ key: "aet", label: "Sydney (UTC+10)", offsetHours: 10 },
];
export interface LocalizedPostSlot {
readonly day: Weekday;
/** Hour of day, 0-23, in the target time zone. */
readonly hour: number;
/** Days the local slot falls relative to the anchor day's label: -1, 0 or 1. */
readonly dayShift: -1 | 0 | 1;
readonly note?: string;
}
/** Shift a weekday label forward/back by whole days, wrapping Sun<->Mon. */
export function shiftWeekday(day: Weekday, shift: number): Weekday {
const index = WEEKDAYS.indexOf(day);
const next = ((index + shift) % WEEKDAYS.length + WEEKDAYS.length) % WEEKDAYS.length;
return WEEKDAYS[next] ?? day;
}
/**
* Convert one ET-anchored posting slot into the viewer's local time zone,
* carrying the weekday across midnight when the offset pushes it over.
*/
export function localizePostSlot(slot: BestPostSlot, targetOffsetHours: number): LocalizedPostSlot {
if (!Number.isFinite(slot.hour)) {
return { day: slot.day, hour: NaN, dayShift: 0, note: slot.note };
}
const diff = targetOffsetHours - BEST_TIME_ANCHOR_OFFSET_HOURS;
let hour = slot.hour + diff;
let dayShift = 0;
while (hour < 0) {
hour += 24;
dayShift -= 1;
}
while (hour >= 24) {
hour -= 24;
dayShift += 1;
}
return { day: shiftWeekday(slot.day, dayShift), hour, dayShift: dayShift as -1 | 0 | 1, note: slot.note };
}
/** Localize every slot for a platform and group the results back by local weekday. */
export function localizeBestTimes(
platform: BestTimePlatform,
targetOffsetHours: number,
): ReadonlyMap<Weekday, readonly LocalizedPostSlot[]> {
const grouped = new Map<Weekday, LocalizedPostSlot[]>();
for (const day of WEEKDAYS) grouped.set(day, []);
for (const slot of platform.slots) {
const localized = localizePostSlot(slot, targetOffsetHours);
const bucket = grouped.get(localized.day);
if (bucket && Number.isFinite(localized.hour)) bucket.push(localized);
else if (!Number.isFinite(localized.hour)) {
// Skip-days (e.g. LinkedIn weekends) keep their original label, not a
// timezone-shifted one, since there is no clock time to shift.
grouped.get(slot.day)?.push(localized);
}
}
for (const day of WEEKDAYS) {
grouped.get(day)?.sort((a, b) => a.hour - b.hour);
}
return grouped;
}
/** Format an hour (0-23, may be fractional) as "9:00 AM" / "12:30 PM". */
export function formatHour12(hour: number): string {
if (!Number.isFinite(hour)) return "-";
const normalized = ((hour % 24) + 24) % 24;
const wholeHour = Math.floor(normalized);
const minutes = Math.round((normalized - wholeHour) * 60);
const period = wholeHour >= 12 ? "PM" : "AM";
const displayHour = wholeHour % 12 === 0 ? 12 : wholeHour % 12;
return `${displayHour}:${String(minutes).padStart(2, "0")} ${period}`;
}