init
This commit is contained in:
134 files changed
+18678
No files matched your search
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"name": "@easy-stream/contracts",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"import": "./dist/index.js"
|
||||
}
|
||||
},
|
||||
"files": ["dist"],
|
||||
"scripts": {
|
||||
"build": "tsc -p tsconfig.json",
|
||||
"typecheck": "tsc -p tsconfig.json --noEmit",
|
||||
"test": "vitest run"
|
||||
},
|
||||
"dependencies": {
|
||||
"@sinclair/typebox": "^0.34.41"
|
||||
},
|
||||
"devDependencies": {
|
||||
"typescript": "^5.9.3",
|
||||
"vitest": "^3.2.4"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
import { Type, type Static } from '@sinclair/typebox';
|
||||
import { DateTimeSchema, EmailSchema, UuidSchema } from './common.js';
|
||||
|
||||
export const AdminLoginSchema = Type.Object(
|
||||
{
|
||||
email: EmailSchema,
|
||||
password: Type.String({ minLength: 12, maxLength: 1024 }),
|
||||
totp: Type.Optional(Type.String({ pattern: '^[0-9]{6}$' })),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
|
||||
export const AdminSessionResponseSchema = Type.Object(
|
||||
{
|
||||
admin: Type.Object(
|
||||
{ id: UuidSchema, email: EmailSchema },
|
||||
{ additionalProperties: false },
|
||||
),
|
||||
csrfToken: Type.String(),
|
||||
expiresAt: DateTimeSchema,
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
|
||||
export const StartScanSchema = Type.Object(
|
||||
{ full: Type.Optional(Type.Boolean({ default: false })) },
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
|
||||
export const PublicationParamsSchema = Type.Object(
|
||||
{ mediaItemId: UuidSchema },
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
|
||||
export const PublicationBodySchema = Type.Object(
|
||||
{ published: Type.Boolean() },
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
|
||||
export const JobStateSchema = Type.Union([
|
||||
Type.Literal('QUEUED'),
|
||||
Type.Literal('RUNNING'),
|
||||
Type.Literal('SUCCEEDED'),
|
||||
Type.Literal('FAILED'),
|
||||
Type.Literal('CANCELLED'),
|
||||
]);
|
||||
|
||||
export const JobSchema = Type.Object(
|
||||
{
|
||||
id: UuidSchema,
|
||||
type: Type.String(),
|
||||
state: JobStateSchema,
|
||||
progress: Type.Number({ minimum: 0, maximum: 1 }),
|
||||
error: Type.Union([Type.String(), Type.Null()]),
|
||||
createdAt: DateTimeSchema,
|
||||
updatedAt: DateTimeSchema,
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
|
||||
export const JobParamsSchema = Type.Object({ jobId: UuidSchema }, { additionalProperties: false });
|
||||
export const CacheParamsSchema = Type.Object(
|
||||
{ generationId: UuidSchema },
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
|
||||
export const CacheStatusSchema = Type.Object(
|
||||
{
|
||||
usedBytes: Type.Integer({ minimum: 0 }),
|
||||
maxBytes: Type.Integer({ minimum: 1 }),
|
||||
highWatermark: Type.Number({ minimum: 0, maximum: 1 }),
|
||||
lowWatermark: Type.Number({ minimum: 0, maximum: 1 }),
|
||||
activePackages: Type.Integer({ minimum: 0 }),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
|
||||
export const MetadataSearchQuerySchema = Type.Object(
|
||||
{
|
||||
q: Type.String({ minLength: 1, maxLength: 200 }),
|
||||
kind: Type.Union([Type.Literal('MOVIE'), Type.Literal('SERIES')]),
|
||||
year: Type.Optional(Type.Integer({ minimum: 1888, maximum: 2200 })),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
|
||||
export const MetadataCandidateSchema = Type.Object(
|
||||
{
|
||||
provider: Type.Literal('TMDB'),
|
||||
externalId: Type.Integer({ minimum: 1 }),
|
||||
kind: Type.Union([Type.Literal('MOVIE'), Type.Literal('SERIES')]),
|
||||
name: Type.Object(
|
||||
{ fa: Type.String(), en: Type.Optional(Type.String()) },
|
||||
{ additionalProperties: false },
|
||||
),
|
||||
synopsis: Type.Object(
|
||||
{ fa: Type.Optional(Type.String()), en: Type.Optional(Type.String()) },
|
||||
{ additionalProperties: false },
|
||||
),
|
||||
posterUrl: Type.Optional(Type.String()),
|
||||
backdropUrl: Type.Optional(Type.String()),
|
||||
year: Type.Optional(Type.Integer()),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
|
||||
export const MetadataSearchResponseSchema = Type.Object(
|
||||
{ items: Type.Array(MetadataCandidateSchema) },
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
|
||||
export const MetadataMatchParamsSchema = Type.Object(
|
||||
{ titleId: UuidSchema },
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
|
||||
export const MetadataMatchBodySchema = Type.Object(
|
||||
{
|
||||
provider: Type.Literal('TMDB'),
|
||||
externalId: Type.Integer({ minimum: 1 }),
|
||||
kind: Type.Union([Type.Literal('MOVIE'), Type.Literal('SERIES')]),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
|
||||
export type AdminLogin = Static<typeof AdminLoginSchema>;
|
||||
export type AdminSessionResponse = Static<typeof AdminSessionResponseSchema>;
|
||||
export type StartScan = Static<typeof StartScanSchema>;
|
||||
export type Job = Static<typeof JobSchema>;
|
||||
export type JobState = Static<typeof JobStateSchema>;
|
||||
export type CacheStatus = Static<typeof CacheStatusSchema>;
|
||||
export type MetadataSearchQuery = Static<typeof MetadataSearchQuerySchema>;
|
||||
export type MetadataCandidate = Static<typeof MetadataCandidateSchema>;
|
||||
export type MetadataMatchBody = Static<typeof MetadataMatchBodySchema>;
|
||||
@@ -0,0 +1,134 @@
|
||||
import { Type, type Static } from '@sinclair/typebox';
|
||||
import { DateTimeSchema, UuidSchema } from './common.js';
|
||||
|
||||
export const TitleKindSchema = Type.Union([Type.Literal('MOVIE'), Type.Literal('SERIES')]);
|
||||
export const MediaKindSchema = Type.Union([Type.Literal('MOVIE'), Type.Literal('EPISODE')]);
|
||||
|
||||
export const LocalizedTextSchema = Type.Object(
|
||||
{
|
||||
fa: Type.String(),
|
||||
en: Type.Optional(Type.String()),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
|
||||
export const OptionalLocalizedTextSchema = Type.Object(
|
||||
{
|
||||
fa: Type.Optional(Type.String()),
|
||||
en: Type.Optional(Type.String()),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
|
||||
export const CatalogCardSchema = Type.Object(
|
||||
{
|
||||
id: UuidSchema,
|
||||
slug: Type.String(),
|
||||
kind: TitleKindSchema,
|
||||
name: LocalizedTextSchema,
|
||||
posterUrl: Type.Optional(Type.String()),
|
||||
backdropUrl: Type.Optional(Type.String()),
|
||||
year: Type.Optional(Type.Integer()),
|
||||
playable: Type.Boolean(),
|
||||
resumeMediaItemId: Type.Optional(UuidSchema),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
|
||||
export const MediaItemSummarySchema = Type.Object(
|
||||
{
|
||||
id: UuidSchema,
|
||||
kind: MediaKindSchema,
|
||||
seasonNumber: Type.Optional(Type.Integer({ minimum: 0 })),
|
||||
episodeNumber: Type.Optional(Type.Integer({ minimum: 0 })),
|
||||
name: Type.Optional(OptionalLocalizedTextSchema),
|
||||
durationSeconds: Type.Number({ minimum: 0 }),
|
||||
compatibility: Type.Union([
|
||||
Type.Literal('COPY'),
|
||||
Type.Literal('AUDIO_TRANSCODE'),
|
||||
Type.Literal('VIDEO_TRANSCODE'),
|
||||
Type.Literal('HOLD_HDR'),
|
||||
Type.Literal('INVALID'),
|
||||
]),
|
||||
published: Type.Boolean(),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
|
||||
export const SeasonSummarySchema = Type.Object(
|
||||
{
|
||||
number: Type.Integer({ minimum: 0 }),
|
||||
episodeCount: Type.Integer({ minimum: 0 }),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
|
||||
export const TitleDetailSchema = Type.Object(
|
||||
{
|
||||
id: UuidSchema,
|
||||
slug: Type.String(),
|
||||
kind: TitleKindSchema,
|
||||
name: LocalizedTextSchema,
|
||||
posterUrl: Type.Optional(Type.String()),
|
||||
backdropUrl: Type.Optional(Type.String()),
|
||||
year: Type.Optional(Type.Integer()),
|
||||
playable: Type.Boolean(),
|
||||
resumeMediaItemId: Type.Optional(UuidSchema),
|
||||
synopsis: OptionalLocalizedTextSchema,
|
||||
seasons: Type.Optional(Type.Array(SeasonSummarySchema)),
|
||||
mediaItems: Type.Array(MediaItemSummarySchema),
|
||||
updatedAt: DateTimeSchema,
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
|
||||
export const CatalogQuerySchema = Type.Object(
|
||||
{
|
||||
cursor: Type.Optional(Type.String({ maxLength: 512 })),
|
||||
limit: Type.Optional(Type.Integer({ minimum: 1, maximum: 100, default: 24 })),
|
||||
kind: Type.Optional(TitleKindSchema),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
|
||||
export const SearchQuerySchema = Type.Object(
|
||||
{
|
||||
q: Type.String({ minLength: 1, maxLength: 200 }),
|
||||
limit: Type.Optional(Type.Integer({ minimum: 1, maximum: 50, default: 20 })),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
|
||||
export const CatalogResponseSchema = Type.Object(
|
||||
{
|
||||
items: Type.Array(CatalogCardSchema),
|
||||
nextCursor: Type.Optional(Type.String()),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
|
||||
export const SearchResponseSchema = Type.Object(
|
||||
{ items: Type.Array(CatalogCardSchema) },
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
|
||||
export const CatalogSnapshotSchema = Type.Object(
|
||||
{
|
||||
version: Type.Literal(1),
|
||||
generatedAt: DateTimeSchema,
|
||||
titles: Type.Array(TitleDetailSchema),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
|
||||
export type TitleKind = Static<typeof TitleKindSchema>;
|
||||
export type MediaKind = Static<typeof MediaKindSchema>;
|
||||
export type LocalizedText = Static<typeof LocalizedTextSchema>;
|
||||
export type OptionalLocalizedText = Static<typeof OptionalLocalizedTextSchema>;
|
||||
export type CatalogCard = Static<typeof CatalogCardSchema>;
|
||||
export type MediaItemSummary = Static<typeof MediaItemSummarySchema>;
|
||||
export type TitleDetail = Static<typeof TitleDetailSchema>;
|
||||
export type CatalogQuery = Static<typeof CatalogQuerySchema>;
|
||||
export type SearchQuery = Static<typeof SearchQuerySchema>;
|
||||
export type CatalogResponse = Static<typeof CatalogResponseSchema>;
|
||||
export type CatalogSnapshot = Static<typeof CatalogSnapshotSchema>;
|
||||
@@ -0,0 +1,42 @@
|
||||
import { Type, type Static } from '@sinclair/typebox';
|
||||
|
||||
export const UuidSchema = Type.String({
|
||||
pattern: '^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$',
|
||||
});
|
||||
export const DateTimeSchema = Type.String({
|
||||
pattern: '^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?(?:Z|[+-]\\d{2}:\\d{2})$',
|
||||
});
|
||||
export const EmailSchema = Type.String({
|
||||
maxLength: 320,
|
||||
pattern: '^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$',
|
||||
});
|
||||
|
||||
export const ErrorCodeSchema = Type.Union([
|
||||
Type.Literal('BAD_REQUEST'),
|
||||
Type.Literal('NOT_FOUND'),
|
||||
Type.Literal('UNAUTHORIZED'),
|
||||
Type.Literal('FORBIDDEN'),
|
||||
Type.Literal('CONFLICT'),
|
||||
Type.Literal('VALIDATION_ERROR'),
|
||||
Type.Literal('UNSUPPORTED_CLIENT'),
|
||||
Type.Literal('MEDIA_UNAVAILABLE'),
|
||||
Type.Literal('INTERNAL_ERROR'),
|
||||
]);
|
||||
|
||||
export const ErrorResponseSchema = Type.Object(
|
||||
{
|
||||
error: Type.Object(
|
||||
{
|
||||
code: ErrorCodeSchema,
|
||||
message: Type.String(),
|
||||
requestId: Type.String(),
|
||||
details: Type.Optional(Type.Unknown()),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
|
||||
export type ErrorCode = Static<typeof ErrorCodeSchema>;
|
||||
export type ErrorResponse = Static<typeof ErrorResponseSchema>;
|
||||
@@ -0,0 +1,98 @@
|
||||
import { Type, type Static } from '@sinclair/typebox';
|
||||
import { DateTimeSchema, UuidSchema } from './common.js';
|
||||
import { AudioTrackSchema, SubtitleTrackSchema } from './playback.js';
|
||||
|
||||
export const MediaCommandSchema = Type.Union([
|
||||
Type.Object(
|
||||
{
|
||||
type: Type.Literal('media.playback.requested'),
|
||||
sessionId: UuidSchema,
|
||||
mediaItemId: UuidSchema,
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
),
|
||||
Type.Object(
|
||||
{ type: Type.Literal('archive.scan.requested'), jobId: UuidSchema, full: Type.Boolean() },
|
||||
{ additionalProperties: false },
|
||||
),
|
||||
Type.Object(
|
||||
{
|
||||
type: Type.Literal('media.publication.changed'),
|
||||
mediaItemId: UuidSchema,
|
||||
published: Type.Boolean(),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
),
|
||||
Type.Object(
|
||||
{ type: Type.Literal('package.eviction.requested'), generationId: UuidSchema },
|
||||
{ additionalProperties: false },
|
||||
),
|
||||
Type.Object(
|
||||
{
|
||||
type: Type.Literal('cache.generation.accessed'),
|
||||
sessionId: UuidSchema,
|
||||
generationId: UuidSchema,
|
||||
accessedAt: DateTimeSchema,
|
||||
protectedUntil: DateTimeSchema,
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
),
|
||||
]);
|
||||
|
||||
/** Shared by the API lease writer and worker eviction reader. */
|
||||
export const CACHE_GENERATION_LEASES_KEY = 'easy-stream:cache-generation-leases:v1';
|
||||
|
||||
export const MediaPreparationResultSchema = Type.Object(
|
||||
{
|
||||
sessionId: UuidSchema,
|
||||
state: Type.Union([
|
||||
Type.Literal('PREPARING'),
|
||||
Type.Literal('READY'),
|
||||
Type.Literal('UNSUPPORTED_CLIENT'),
|
||||
Type.Literal('FAILED'),
|
||||
]),
|
||||
playable: Type.Boolean(),
|
||||
generationId: Type.Optional(UuidSchema),
|
||||
manifestPath: Type.Optional(Type.String({ pattern: '^/media/' })),
|
||||
reasonCode: Type.Optional(Type.String()),
|
||||
pollAfterMs: Type.Optional(Type.Integer({ minimum: 250, maximum: 30000 })),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
|
||||
export const PackageRegistryEntrySchema = Type.Object(
|
||||
{
|
||||
mediaItemId: UuidSchema,
|
||||
state: Type.Union([
|
||||
Type.Literal('PREPARING'),
|
||||
Type.Literal('READY'),
|
||||
Type.Literal('UNSUPPORTED_CLIENT'),
|
||||
Type.Literal('FAILED'),
|
||||
]),
|
||||
playable: Type.Boolean(),
|
||||
generationId: Type.Optional(UuidSchema),
|
||||
manifestPath: Type.Optional(Type.String({ pattern: '^/media/' })),
|
||||
reasonCode: Type.Optional(Type.String()),
|
||||
pollAfterMs: Type.Optional(Type.Integer({ minimum: 250, maximum: 30000 })),
|
||||
durationSeconds: Type.Optional(Type.Number({ minimum: 0 })),
|
||||
audioTracks: Type.Optional(Type.Array(AudioTrackSchema)),
|
||||
subtitleTracks: Type.Optional(Type.Array(SubtitleTrackSchema)),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
|
||||
export const PackageRegistrySchema = Type.Object(
|
||||
{
|
||||
version: Type.Literal(1),
|
||||
updatedAt: Type.String({
|
||||
pattern: '^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?(?:Z|[+-]\\d{2}:\\d{2})$',
|
||||
}),
|
||||
packages: Type.Array(PackageRegistryEntrySchema),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
|
||||
export type MediaCommand = Static<typeof MediaCommandSchema>;
|
||||
export type MediaPreparationResult = Static<typeof MediaPreparationResultSchema>;
|
||||
export type PackageRegistryEntry = Static<typeof PackageRegistryEntrySchema>;
|
||||
export type PackageRegistry = Static<typeof PackageRegistrySchema>;
|
||||
@@ -0,0 +1,5 @@
|
||||
export * from './admin.js';
|
||||
export * from './catalog.js';
|
||||
export * from './common.js';
|
||||
export * from './events.js';
|
||||
export * from './playback.js';
|
||||
@@ -0,0 +1,98 @@
|
||||
import { Type, type Static } from '@sinclair/typebox';
|
||||
import { DateTimeSchema, UuidSchema } from './common.js';
|
||||
|
||||
export const CompatibilityClassSchema = Type.Union([
|
||||
Type.Literal('COPY'),
|
||||
Type.Literal('AUDIO_TRANSCODE'),
|
||||
Type.Literal('VIDEO_TRANSCODE'),
|
||||
Type.Literal('HOLD_HDR'),
|
||||
Type.Literal('INVALID'),
|
||||
]);
|
||||
|
||||
export const PlaybackStateSchema = Type.Union([
|
||||
Type.Literal('PREPARING'),
|
||||
Type.Literal('READY'),
|
||||
Type.Literal('UNSUPPORTED_CLIENT'),
|
||||
Type.Literal('FAILED'),
|
||||
]);
|
||||
|
||||
export const SubtitleDeliverySchema = Type.Union([
|
||||
Type.Literal('ASS_JASSUB'),
|
||||
Type.Literal('WEBVTT'),
|
||||
Type.Literal('OFF'),
|
||||
]);
|
||||
|
||||
export const ClientCapabilitiesSchema = Type.Object(
|
||||
{
|
||||
mse: Type.Boolean(),
|
||||
nativeHls: Type.Boolean(),
|
||||
hlsJs: Type.Boolean(),
|
||||
assRenderer: Type.Boolean(),
|
||||
supportedCodecs: Type.Array(Type.String({ maxLength: 128 }), { maxItems: 32 }),
|
||||
userAgent: Type.Optional(Type.String({ maxLength: 512 })),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
|
||||
export const AudioTrackSchema = Type.Object(
|
||||
{
|
||||
id: UuidSchema,
|
||||
language: Type.String({ minLength: 2, maxLength: 35 }),
|
||||
label: Type.String({ maxLength: 100 }),
|
||||
default: Type.Boolean(),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
|
||||
export const SubtitleTrackSchema = Type.Object(
|
||||
{
|
||||
id: UuidSchema,
|
||||
language: Type.String({ minLength: 2, maxLength: 35 }),
|
||||
label: Type.String({ maxLength: 100 }),
|
||||
default: Type.Boolean(),
|
||||
forced: Type.Boolean(),
|
||||
assUrl: Type.Optional(Type.String()),
|
||||
vttUrl: Type.Optional(Type.String()),
|
||||
fontUrls: Type.Array(Type.String()),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
|
||||
export const CreatePlaybackSessionSchema = Type.Object(
|
||||
{
|
||||
mediaItemId: UuidSchema,
|
||||
clientCapabilities: ClientCapabilitiesSchema,
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
|
||||
export const PlaybackSessionSchema = Type.Object(
|
||||
{
|
||||
id: UuidSchema,
|
||||
mediaItemId: UuidSchema,
|
||||
state: PlaybackStateSchema,
|
||||
manifestUrl: Type.Optional(Type.String()),
|
||||
generationId: Type.Optional(UuidSchema),
|
||||
durationSeconds: Type.Optional(Type.Number({ minimum: 0 })),
|
||||
audioTracks: Type.Optional(Type.Array(AudioTrackSchema)),
|
||||
subtitleTracks: Type.Optional(Type.Array(SubtitleTrackSchema)),
|
||||
pollAfterMs: Type.Optional(Type.Integer({ minimum: 250, maximum: 30000 })),
|
||||
reasonCode: Type.Optional(Type.String()),
|
||||
expiresAt: DateTimeSchema,
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
|
||||
export const PlaybackSessionParamsSchema = Type.Object(
|
||||
{ id: UuidSchema },
|
||||
{ additionalProperties: false },
|
||||
);
|
||||
|
||||
export type CompatibilityClass = Static<typeof CompatibilityClassSchema>;
|
||||
export type PlaybackState = Static<typeof PlaybackStateSchema>;
|
||||
export type SubtitleDelivery = Static<typeof SubtitleDeliverySchema>;
|
||||
export type ClientCapabilities = Static<typeof ClientCapabilitiesSchema>;
|
||||
export type AudioTrack = Static<typeof AudioTrackSchema>;
|
||||
export type SubtitleTrack = Static<typeof SubtitleTrackSchema>;
|
||||
export type CreatePlaybackSession = Static<typeof CreatePlaybackSessionSchema>;
|
||||
export type PlaybackSession = Static<typeof PlaybackSessionSchema>;
|
||||
@@ -0,0 +1,38 @@
|
||||
import { Value } from '@sinclair/typebox/value';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { CreatePlaybackSessionSchema, MediaCommandSchema } from '../src/index.js';
|
||||
|
||||
describe('public contracts', () => {
|
||||
it('accepts a valid browser capability report', () => {
|
||||
expect(
|
||||
Value.Check(CreatePlaybackSessionSchema, {
|
||||
mediaItemId: '00000000-0000-4000-8000-000000000001',
|
||||
clientCapabilities: {
|
||||
mse: true,
|
||||
nativeHls: false,
|
||||
hlsJs: true,
|
||||
assRenderer: true,
|
||||
supportedCodecs: ['avc1.64001f', 'mp4a.40.2'],
|
||||
},
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('keeps worker commands discriminated and closed', () => {
|
||||
expect(
|
||||
Value.Check(MediaCommandSchema, {
|
||||
type: 'archive.scan.requested',
|
||||
jobId: '00000000-0000-4000-8000-000000000002',
|
||||
full: false,
|
||||
unexpected: true,
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(Value.Check(MediaCommandSchema, {
|
||||
type: 'cache.generation.accessed',
|
||||
sessionId: '00000000-0000-4000-8000-000000000001',
|
||||
generationId: '00000000-0000-4000-8000-000000000002',
|
||||
accessedAt: '2026-07-14T10:00:00.000Z',
|
||||
protectedUntil: '2026-07-14T14:00:00.000Z',
|
||||
})).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"rootDir": "src",
|
||||
"outDir": "dist",
|
||||
"tsBuildInfoFile": "dist/.tsbuildinfo"
|
||||
},
|
||||
"include": ["src/**/*.ts"]
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { defineConfig } from 'drizzle-kit';
|
||||
|
||||
if (!process.env.DATABASE_URL) {
|
||||
throw new Error('DATABASE_URL is required to run Drizzle commands');
|
||||
}
|
||||
|
||||
export default defineConfig({
|
||||
dialect: 'postgresql',
|
||||
schema: './src/schema.ts',
|
||||
out: './migrations',
|
||||
dbCredentials: { url: process.env.DATABASE_URL },
|
||||
strict: true,
|
||||
});
|
||||
@@ -0,0 +1,213 @@
|
||||
CREATE TYPE "title_kind" AS ENUM ('MOVIE', 'SERIES');
|
||||
CREATE TYPE "media_kind" AS ENUM ('MOVIE', 'EPISODE');
|
||||
CREATE TYPE "stream_kind" AS ENUM ('VIDEO', 'AUDIO');
|
||||
CREATE TYPE "compatibility_class" AS ENUM ('COPY', 'AUDIO_TRANSCODE', 'VIDEO_TRANSCODE', 'HOLD_HDR', 'INVALID');
|
||||
CREATE TYPE "package_state" AS ENUM ('QUEUED', 'BUILDING', 'READY', 'FAILED', 'EVICTED');
|
||||
CREATE TYPE "job_state" AS ENUM ('QUEUED', 'RUNNING', 'SUCCEEDED', 'FAILED', 'CANCELLED');
|
||||
CREATE TYPE "playback_state" AS ENUM ('PREPARING', 'READY', 'UNSUPPORTED_CLIENT', 'FAILED');
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "titles" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"slug" varchar(240) NOT NULL,
|
||||
"kind" "title_kind" NOT NULL,
|
||||
"name_fa" text,
|
||||
"name_en" text,
|
||||
"synopsis_fa" text,
|
||||
"synopsis_en" text,
|
||||
"poster_url" text,
|
||||
"backdrop_url" text,
|
||||
"release_year" integer,
|
||||
"tmdb_id" integer,
|
||||
"published" boolean DEFAULT false NOT NULL,
|
||||
"published_at" timestamp with time zone,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "media_items" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"title_id" uuid NOT NULL,
|
||||
"kind" "media_kind" NOT NULL,
|
||||
"season_number" integer,
|
||||
"episode_number" integer,
|
||||
"name_fa" text,
|
||||
"name_en" text,
|
||||
"duration_seconds" double precision,
|
||||
"compatibility" "compatibility_class" DEFAULT 'INVALID' NOT NULL,
|
||||
"compatibility_reason" text,
|
||||
"published" boolean DEFAULT false NOT NULL,
|
||||
"published_at" timestamp with time zone,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "source_files" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"media_item_id" uuid NOT NULL,
|
||||
"relative_path" text NOT NULL,
|
||||
"size_bytes" bigint NOT NULL,
|
||||
"modified_at_ns" bigint NOT NULL,
|
||||
"matroska_uid" varchar(128),
|
||||
"head_hash" varchar(128) NOT NULL,
|
||||
"tail_hash" varchar(128) NOT NULL,
|
||||
"fingerprint" varchar(128) NOT NULL,
|
||||
"probe_json" jsonb,
|
||||
"present" boolean DEFAULT true NOT NULL,
|
||||
"last_seen_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "media_streams" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"source_file_id" uuid NOT NULL,
|
||||
"stream_index" integer NOT NULL,
|
||||
"kind" "stream_kind" NOT NULL,
|
||||
"codec" varchar(64) NOT NULL,
|
||||
"codec_string" varchar(128),
|
||||
"language" varchar(35),
|
||||
"label" varchar(200),
|
||||
"is_default" boolean DEFAULT false NOT NULL,
|
||||
"channels" integer,
|
||||
"sample_rate" integer,
|
||||
"width" integer,
|
||||
"height" integer,
|
||||
"frame_rate" varchar(32),
|
||||
"bit_depth" integer,
|
||||
"pixel_format" varchar(64),
|
||||
"color_transfer" varchar(64),
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "subtitle_tracks" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"source_file_id" uuid NOT NULL,
|
||||
"stream_index" integer NOT NULL,
|
||||
"codec" varchar(64) NOT NULL,
|
||||
"source_language" varchar(35),
|
||||
"normalized_language" varchar(35) NOT NULL,
|
||||
"label" varchar(200) NOT NULL,
|
||||
"source_default" boolean DEFAULT false NOT NULL,
|
||||
"source_forced" boolean DEFAULT false NOT NULL,
|
||||
"is_default" boolean DEFAULT false NOT NULL,
|
||||
"is_forced" boolean DEFAULT false NOT NULL,
|
||||
"ass_path" text,
|
||||
"webvtt_path" text,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "font_attachments" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"source_file_id" uuid NOT NULL,
|
||||
"stream_index" integer NOT NULL,
|
||||
"sha256" varchar(64) NOT NULL,
|
||||
"mime_type" varchar(100) NOT NULL,
|
||||
"original_name" text NOT NULL,
|
||||
"storage_path" text,
|
||||
"approved" boolean DEFAULT false NOT NULL,
|
||||
"size_bytes" bigint NOT NULL,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "media_packages" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"media_item_id" uuid NOT NULL,
|
||||
"source_fingerprint" varchar(128) NOT NULL,
|
||||
"profile_version" varchar(64) NOT NULL,
|
||||
"state" "package_state" DEFAULT 'QUEUED' NOT NULL,
|
||||
"manifest_path" text,
|
||||
"size_bytes" bigint DEFAULT 0 NOT NULL,
|
||||
"cache_resident" boolean DEFAULT false NOT NULL,
|
||||
"pinned" boolean DEFAULT false NOT NULL,
|
||||
"last_accessed_at" timestamp with time zone,
|
||||
"error_code" varchar(100),
|
||||
"error_detail" text,
|
||||
"ready_at" timestamp with time zone,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "jobs" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"type" varchar(100) NOT NULL,
|
||||
"state" "job_state" DEFAULT 'QUEUED' NOT NULL,
|
||||
"progress" real DEFAULT 0 NOT NULL,
|
||||
"payload" jsonb DEFAULT '{}'::jsonb NOT NULL,
|
||||
"result" jsonb,
|
||||
"error" text,
|
||||
"attempts" integer DEFAULT 0 NOT NULL,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "admins" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"email" varchar(320) NOT NULL,
|
||||
"password_hash" text NOT NULL,
|
||||
"totp_secret_encrypted" text,
|
||||
"disabled" boolean DEFAULT false NOT NULL,
|
||||
"last_login_at" timestamp with time zone,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "admin_sessions" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"admin_id" uuid NOT NULL,
|
||||
"token_hash" varchar(64) NOT NULL,
|
||||
"csrf_token_hash" varchar(64) NOT NULL,
|
||||
"expires_at" timestamp with time zone NOT NULL,
|
||||
"revoked_at" timestamp with time zone,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "playback_sessions" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"media_item_id" uuid NOT NULL,
|
||||
"generation_id" uuid,
|
||||
"state" "playback_state" DEFAULT 'PREPARING' NOT NULL,
|
||||
"capabilities" jsonb NOT NULL,
|
||||
"reason_code" varchar(100),
|
||||
"poll_after_ms" integer,
|
||||
"response_json" jsonb DEFAULT '{}'::jsonb NOT NULL,
|
||||
"expires_at" timestamp with time zone NOT NULL,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE "media_items" ADD CONSTRAINT "media_items_title_id_titles_id_fk" FOREIGN KEY ("title_id") REFERENCES "titles"("id") ON DELETE cascade;
|
||||
ALTER TABLE "source_files" ADD CONSTRAINT "source_files_media_item_id_media_items_id_fk" FOREIGN KEY ("media_item_id") REFERENCES "media_items"("id") ON DELETE cascade;
|
||||
ALTER TABLE "media_streams" ADD CONSTRAINT "media_streams_source_file_id_source_files_id_fk" FOREIGN KEY ("source_file_id") REFERENCES "source_files"("id") ON DELETE cascade;
|
||||
ALTER TABLE "subtitle_tracks" ADD CONSTRAINT "subtitle_tracks_source_file_id_source_files_id_fk" FOREIGN KEY ("source_file_id") REFERENCES "source_files"("id") ON DELETE cascade;
|
||||
ALTER TABLE "font_attachments" ADD CONSTRAINT "font_attachments_source_file_id_source_files_id_fk" FOREIGN KEY ("source_file_id") REFERENCES "source_files"("id") ON DELETE cascade;
|
||||
ALTER TABLE "media_packages" ADD CONSTRAINT "media_packages_media_item_id_media_items_id_fk" FOREIGN KEY ("media_item_id") REFERENCES "media_items"("id") ON DELETE cascade;
|
||||
ALTER TABLE "admin_sessions" ADD CONSTRAINT "admin_sessions_admin_id_admins_id_fk" FOREIGN KEY ("admin_id") REFERENCES "admins"("id") ON DELETE cascade;
|
||||
ALTER TABLE "playback_sessions" ADD CONSTRAINT "playback_sessions_media_item_id_media_items_id_fk" FOREIGN KEY ("media_item_id") REFERENCES "media_items"("id") ON DELETE cascade;
|
||||
--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX "titles_slug_uidx" ON "titles" ("slug");
|
||||
CREATE INDEX "titles_published_idx" ON "titles" ("published", "published_at");
|
||||
CREATE INDEX "titles_tmdb_idx" ON "titles" ("tmdb_id");
|
||||
CREATE INDEX "media_items_title_idx" ON "media_items" ("title_id");
|
||||
CREATE UNIQUE INDEX "media_items_episode_uidx" ON "media_items" ("title_id", "season_number", "episode_number");
|
||||
CREATE INDEX "media_items_published_idx" ON "media_items" ("published");
|
||||
CREATE UNIQUE INDEX "source_files_path_uidx" ON "source_files" ("relative_path");
|
||||
CREATE UNIQUE INDEX "source_files_fingerprint_uidx" ON "source_files" ("fingerprint");
|
||||
CREATE INDEX "source_files_media_item_idx" ON "source_files" ("media_item_id");
|
||||
CREATE UNIQUE INDEX "media_streams_source_index_uidx" ON "media_streams" ("source_file_id", "stream_index");
|
||||
CREATE INDEX "media_streams_source_idx" ON "media_streams" ("source_file_id");
|
||||
CREATE UNIQUE INDEX "subtitle_tracks_source_index_uidx" ON "subtitle_tracks" ("source_file_id", "stream_index");
|
||||
CREATE INDEX "subtitle_tracks_source_idx" ON "subtitle_tracks" ("source_file_id");
|
||||
CREATE UNIQUE INDEX "font_attachments_source_index_uidx" ON "font_attachments" ("source_file_id", "stream_index");
|
||||
CREATE INDEX "font_attachments_hash_idx" ON "font_attachments" ("sha256");
|
||||
CREATE UNIQUE INDEX "media_packages_generation_uidx" ON "media_packages" ("media_item_id", "source_fingerprint", "profile_version");
|
||||
CREATE INDEX "media_packages_lru_idx" ON "media_packages" ("cache_resident", "pinned", "last_accessed_at");
|
||||
CREATE INDEX "jobs_state_created_idx" ON "jobs" ("state", "created_at");
|
||||
CREATE UNIQUE INDEX "admins_email_uidx" ON "admins" ("email");
|
||||
CREATE UNIQUE INDEX "admin_sessions_token_uidx" ON "admin_sessions" ("token_hash");
|
||||
CREATE INDEX "admin_sessions_admin_idx" ON "admin_sessions" ("admin_id");
|
||||
CREATE INDEX "playback_sessions_media_idx" ON "playback_sessions" ("media_item_id");
|
||||
CREATE INDEX "playback_sessions_generation_idx" ON "playback_sessions" ("generation_id");
|
||||
CREATE INDEX "playback_sessions_expires_idx" ON "playback_sessions" ("expires_at");
|
||||
@@ -0,0 +1,3 @@
|
||||
ALTER TABLE "playback_sessions" DROP CONSTRAINT IF EXISTS "playback_sessions_generation_id_media_packages_id_fk";
|
||||
--> statement-breakpoint
|
||||
CREATE INDEX IF NOT EXISTS "playback_sessions_generation_idx" ON "playback_sessions" ("generation_id");
|
||||
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"version": "7",
|
||||
"dialect": "postgresql",
|
||||
"entries": [
|
||||
{
|
||||
"idx": 0,
|
||||
"version": "7",
|
||||
"when": 1783987200000,
|
||||
"tag": "0000_initial",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 1,
|
||||
"version": "7",
|
||||
"when": 1784016000000,
|
||||
"tag": "0001_playback_generation_external",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
{
|
||||
"name": "@easy-stream/database",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"import": "./dist/index.js"
|
||||
},
|
||||
"./schema": {
|
||||
"types": "./dist/schema.d.ts",
|
||||
"import": "./dist/schema.js"
|
||||
}
|
||||
},
|
||||
"files": ["dist", "migrations"],
|
||||
"scripts": {
|
||||
"build": "tsc -p tsconfig.json",
|
||||
"typecheck": "tsc -p ../contracts/tsconfig.json && tsc -p tsconfig.json",
|
||||
"test": "tsc -p ../contracts/tsconfig.json && vitest run",
|
||||
"migrate": "drizzle-kit migrate",
|
||||
"generate": "drizzle-kit generate"
|
||||
},
|
||||
"dependencies": {
|
||||
"@easy-stream/contracts": "workspace:*",
|
||||
"@sinclair/typebox": "^0.34.41",
|
||||
"drizzle-orm": "^0.45.2",
|
||||
"postgres": "^3.4.7"
|
||||
},
|
||||
"devDependencies": {
|
||||
"drizzle-kit": "^0.31.10",
|
||||
"typescript": "^5.9.3",
|
||||
"vitest": "^3.2.4"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
import { CatalogSnapshotSchema, type CatalogSnapshot } from '@easy-stream/contracts';
|
||||
import { Value } from '@sinclair/typebox/value';
|
||||
import { sql } from 'drizzle-orm';
|
||||
import type { Database } from './client.js';
|
||||
import { mediaItems, titles } from './schema.js';
|
||||
|
||||
const UPSERT_BATCH_SIZE = 500;
|
||||
|
||||
export interface PreparedCatalogSync {
|
||||
scannedAt: Date;
|
||||
titleRows: Array<typeof titles.$inferInsert>;
|
||||
mediaItemRows: Array<typeof mediaItems.$inferInsert>;
|
||||
}
|
||||
|
||||
export interface CatalogSyncResult {
|
||||
titlesSeen: number;
|
||||
mediaItemsSeen: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates and converts the public scan snapshot into database insert rows. Keeping this
|
||||
* conversion separate also makes the scanner/database boundary testable without PostgreSQL.
|
||||
*/
|
||||
export function prepareCatalogSync(snapshot: unknown): PreparedCatalogSync {
|
||||
if (!Value.Check(CatalogSnapshotSchema, snapshot)) {
|
||||
const detail = [...Value.Errors(CatalogSnapshotSchema, snapshot)]
|
||||
.slice(0, 8)
|
||||
.map((error) => `${error.path || '/'} ${error.message}`)
|
||||
.join('; ');
|
||||
throw new Error(`Invalid catalog snapshot: ${detail}`);
|
||||
}
|
||||
|
||||
const catalog = snapshot as CatalogSnapshot;
|
||||
const scannedAt = new Date(catalog.generatedAt);
|
||||
const titleIds = new Set<string>();
|
||||
const slugs = new Set<string>();
|
||||
const mediaItemIds = new Set<string>();
|
||||
const titleRows: PreparedCatalogSync['titleRows'] = [];
|
||||
const mediaItemRows: PreparedCatalogSync['mediaItemRows'] = [];
|
||||
|
||||
for (const title of catalog.titles) {
|
||||
assertUnique(titleIds, title.id, 'title ID');
|
||||
assertUnique(slugs, title.slug, 'title slug');
|
||||
const published = title.mediaItems.some((item) => item.published);
|
||||
titleRows.push({
|
||||
id: title.id,
|
||||
slug: title.slug,
|
||||
kind: title.kind,
|
||||
nameFa: title.name.fa,
|
||||
nameEn: title.name.en ?? null,
|
||||
synopsisFa: title.synopsis.fa ?? null,
|
||||
synopsisEn: title.synopsis.en ?? null,
|
||||
posterUrl: title.posterUrl ?? null,
|
||||
backdropUrl: title.backdropUrl ?? null,
|
||||
releaseYear: title.year ?? null,
|
||||
published,
|
||||
publishedAt: published ? scannedAt : null,
|
||||
createdAt: scannedAt,
|
||||
updatedAt: scannedAt,
|
||||
});
|
||||
|
||||
for (const item of title.mediaItems) {
|
||||
assertUnique(mediaItemIds, item.id, 'media item ID');
|
||||
if ((title.kind === 'MOVIE') !== (item.kind === 'MOVIE')) {
|
||||
throw new Error(`Catalog media item ${item.id} has kind ${item.kind} under ${title.kind}`);
|
||||
}
|
||||
mediaItemRows.push({
|
||||
id: item.id,
|
||||
titleId: title.id,
|
||||
kind: item.kind,
|
||||
seasonNumber: item.seasonNumber ?? null,
|
||||
episodeNumber: item.episodeNumber ?? null,
|
||||
nameFa: item.name?.fa ?? null,
|
||||
nameEn: item.name?.en ?? null,
|
||||
durationSeconds: item.durationSeconds,
|
||||
compatibility: item.compatibility,
|
||||
published: item.published,
|
||||
publishedAt: item.published ? scannedAt : null,
|
||||
createdAt: scannedAt,
|
||||
updatedAt: scannedAt,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return { scannedAt, titleRows, mediaItemRows };
|
||||
}
|
||||
|
||||
/**
|
||||
* Safely imports scanner-owned catalog facts. Existing names, artwork, TMDB matches and all
|
||||
* publication fields are intentionally excluded from conflict updates so an archive rescan
|
||||
* cannot undo an administrator's choices. Rows absent from a snapshot are retained.
|
||||
*/
|
||||
export async function syncCatalogSnapshot(
|
||||
db: Database,
|
||||
snapshot: unknown,
|
||||
): Promise<CatalogSyncResult> {
|
||||
const prepared = prepareCatalogSync(snapshot);
|
||||
await db.transaction(async (transaction) => {
|
||||
// Prevent two worker processes from interleaving catalog snapshots.
|
||||
await transaction.execute(sql`select pg_advisory_xact_lock(hashtext('easy-stream.catalog-sync'))`);
|
||||
|
||||
for (const batch of batches(prepared.titleRows, UPSERT_BATCH_SIZE)) {
|
||||
await transaction
|
||||
.insert(titles)
|
||||
.values(batch)
|
||||
.onConflictDoUpdate({
|
||||
target: titles.id,
|
||||
set: {
|
||||
slug: sql`excluded.slug`,
|
||||
kind: sql`excluded.kind`,
|
||||
updatedAt: prepared.scannedAt,
|
||||
},
|
||||
setWhere: sql`${titles.slug} is distinct from excluded.slug or ${titles.kind} is distinct from excluded.kind`,
|
||||
});
|
||||
}
|
||||
|
||||
for (const batch of batches(prepared.mediaItemRows, UPSERT_BATCH_SIZE)) {
|
||||
await transaction
|
||||
.insert(mediaItems)
|
||||
.values(batch)
|
||||
.onConflictDoUpdate({
|
||||
target: mediaItems.id,
|
||||
set: {
|
||||
titleId: sql`excluded.title_id`,
|
||||
kind: sql`excluded.kind`,
|
||||
seasonNumber: sql`excluded.season_number`,
|
||||
episodeNumber: sql`excluded.episode_number`,
|
||||
durationSeconds: sql`excluded.duration_seconds`,
|
||||
compatibility: sql`excluded.compatibility`,
|
||||
updatedAt: prepared.scannedAt,
|
||||
},
|
||||
setWhere: sql`
|
||||
${mediaItems.titleId} is distinct from excluded.title_id
|
||||
or ${mediaItems.kind} is distinct from excluded.kind
|
||||
or ${mediaItems.seasonNumber} is distinct from excluded.season_number
|
||||
or ${mediaItems.episodeNumber} is distinct from excluded.episode_number
|
||||
or ${mediaItems.durationSeconds} is distinct from excluded.duration_seconds
|
||||
or ${mediaItems.compatibility} is distinct from excluded.compatibility
|
||||
`,
|
||||
});
|
||||
}
|
||||
});
|
||||
return {
|
||||
titlesSeen: prepared.titleRows.length,
|
||||
mediaItemsSeen: prepared.mediaItemRows.length,
|
||||
};
|
||||
}
|
||||
|
||||
function assertUnique(values: Set<string>, value: string, label: string): void {
|
||||
if (values.has(value)) throw new Error(`Catalog contains duplicate ${label}: ${value}`);
|
||||
values.add(value);
|
||||
}
|
||||
|
||||
function batches<T>(values: readonly T[], size: number): T[][] {
|
||||
const result: T[][] = [];
|
||||
for (let index = 0; index < values.length; index += size) {
|
||||
result.push(values.slice(index, index + size));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { drizzle } from 'drizzle-orm/postgres-js';
|
||||
import postgres from 'postgres';
|
||||
import * as schema from './schema.js';
|
||||
|
||||
export function createDatabase(connectionString: string, options?: { max?: number }) {
|
||||
const client = postgres(connectionString, {
|
||||
max: options?.max ?? 10,
|
||||
prepare: false,
|
||||
transform: { undefined: null },
|
||||
});
|
||||
|
||||
return {
|
||||
client,
|
||||
db: drizzle(client, { schema }),
|
||||
async close(): Promise<void> {
|
||||
await client.end({ timeout: 5 });
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export type Database = ReturnType<typeof createDatabase>['db'];
|
||||
@@ -0,0 +1,4 @@
|
||||
export * from './catalog-sync.js';
|
||||
export * from './client.js';
|
||||
export * from './job-status.js';
|
||||
export * from './schema.js';
|
||||
@@ -0,0 +1,56 @@
|
||||
import { and, eq, inArray, sql } from 'drizzle-orm';
|
||||
import type { Database } from './client.js';
|
||||
import { jobs } from './schema.js';
|
||||
|
||||
export async function markArchiveScanRunning(db: Database, jobId: string): Promise<boolean> {
|
||||
const [updated] = await db.update(jobs).set({
|
||||
state: 'RUNNING',
|
||||
progress: 0,
|
||||
error: null,
|
||||
attempts: sql`${jobs.attempts} + 1`,
|
||||
updatedAt: new Date(),
|
||||
}).where(and(
|
||||
eq(jobs.id, jobId),
|
||||
eq(jobs.type, 'ARCHIVE_SCAN'),
|
||||
// BullMQ may start a retry immediately after its failed event; accept either side of that
|
||||
// transition so automatic retries can move the same logical job back to RUNNING.
|
||||
inArray(jobs.state, ['QUEUED', 'RUNNING', 'FAILED']),
|
||||
)).returning({ id: jobs.id });
|
||||
return updated !== undefined;
|
||||
}
|
||||
|
||||
export async function markArchiveScanSucceeded(
|
||||
db: Database,
|
||||
jobId: string,
|
||||
result: Record<string, unknown>,
|
||||
): Promise<boolean> {
|
||||
const [updated] = await db.update(jobs).set({
|
||||
state: 'SUCCEEDED',
|
||||
progress: 1,
|
||||
result,
|
||||
error: null,
|
||||
updatedAt: new Date(),
|
||||
}).where(and(
|
||||
eq(jobs.id, jobId),
|
||||
eq(jobs.type, 'ARCHIVE_SCAN'),
|
||||
eq(jobs.state, 'RUNNING'),
|
||||
)).returning({ id: jobs.id });
|
||||
return updated !== undefined;
|
||||
}
|
||||
|
||||
export async function markArchiveScanFailed(
|
||||
db: Database,
|
||||
jobId: string,
|
||||
error: string,
|
||||
): Promise<boolean> {
|
||||
const [updated] = await db.update(jobs).set({
|
||||
state: 'FAILED',
|
||||
error: error.slice(0, 16_000),
|
||||
updatedAt: new Date(),
|
||||
}).where(and(
|
||||
eq(jobs.id, jobId),
|
||||
eq(jobs.type, 'ARCHIVE_SCAN'),
|
||||
inArray(jobs.state, ['QUEUED', 'RUNNING']),
|
||||
)).returning({ id: jobs.id });
|
||||
return updated !== undefined;
|
||||
}
|
||||
@@ -0,0 +1,324 @@
|
||||
import {
|
||||
bigint,
|
||||
boolean,
|
||||
doublePrecision,
|
||||
index,
|
||||
integer,
|
||||
jsonb,
|
||||
pgEnum,
|
||||
pgTable,
|
||||
real,
|
||||
text,
|
||||
timestamp,
|
||||
uniqueIndex,
|
||||
uuid,
|
||||
varchar,
|
||||
} from 'drizzle-orm/pg-core';
|
||||
|
||||
export const titleKind = pgEnum('title_kind', ['MOVIE', 'SERIES']);
|
||||
export const mediaKind = pgEnum('media_kind', ['MOVIE', 'EPISODE']);
|
||||
export const streamKind = pgEnum('stream_kind', ['VIDEO', 'AUDIO']);
|
||||
export const compatibilityClass = pgEnum('compatibility_class', [
|
||||
'COPY',
|
||||
'AUDIO_TRANSCODE',
|
||||
'VIDEO_TRANSCODE',
|
||||
'HOLD_HDR',
|
||||
'INVALID',
|
||||
]);
|
||||
export const packageState = pgEnum('package_state', [
|
||||
'QUEUED',
|
||||
'BUILDING',
|
||||
'READY',
|
||||
'FAILED',
|
||||
'EVICTED',
|
||||
]);
|
||||
export const jobState = pgEnum('job_state', [
|
||||
'QUEUED',
|
||||
'RUNNING',
|
||||
'SUCCEEDED',
|
||||
'FAILED',
|
||||
'CANCELLED',
|
||||
]);
|
||||
export const playbackState = pgEnum('playback_state', [
|
||||
'PREPARING',
|
||||
'READY',
|
||||
'UNSUPPORTED_CLIENT',
|
||||
'FAILED',
|
||||
]);
|
||||
|
||||
const timestamps = {
|
||||
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
|
||||
updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
|
||||
};
|
||||
|
||||
export const titles = pgTable(
|
||||
'titles',
|
||||
{
|
||||
id: uuid('id').primaryKey().defaultRandom(),
|
||||
slug: varchar('slug', { length: 240 }).notNull(),
|
||||
kind: titleKind('kind').notNull(),
|
||||
nameFa: text('name_fa'),
|
||||
nameEn: text('name_en'),
|
||||
synopsisFa: text('synopsis_fa'),
|
||||
synopsisEn: text('synopsis_en'),
|
||||
posterUrl: text('poster_url'),
|
||||
backdropUrl: text('backdrop_url'),
|
||||
releaseYear: integer('release_year'),
|
||||
tmdbId: integer('tmdb_id'),
|
||||
published: boolean('published').notNull().default(false),
|
||||
publishedAt: timestamp('published_at', { withTimezone: true }),
|
||||
...timestamps,
|
||||
},
|
||||
(table) => [
|
||||
uniqueIndex('titles_slug_uidx').on(table.slug),
|
||||
index('titles_published_idx').on(table.published, table.publishedAt),
|
||||
index('titles_tmdb_idx').on(table.tmdbId),
|
||||
],
|
||||
);
|
||||
|
||||
export const mediaItems = pgTable(
|
||||
'media_items',
|
||||
{
|
||||
id: uuid('id').primaryKey().defaultRandom(),
|
||||
titleId: uuid('title_id')
|
||||
.notNull()
|
||||
.references(() => titles.id, { onDelete: 'cascade' }),
|
||||
kind: mediaKind('kind').notNull(),
|
||||
seasonNumber: integer('season_number'),
|
||||
episodeNumber: integer('episode_number'),
|
||||
nameFa: text('name_fa'),
|
||||
nameEn: text('name_en'),
|
||||
durationSeconds: doublePrecision('duration_seconds'),
|
||||
compatibility: compatibilityClass('compatibility').notNull().default('INVALID'),
|
||||
compatibilityReason: text('compatibility_reason'),
|
||||
published: boolean('published').notNull().default(false),
|
||||
publishedAt: timestamp('published_at', { withTimezone: true }),
|
||||
...timestamps,
|
||||
},
|
||||
(table) => [
|
||||
index('media_items_title_idx').on(table.titleId),
|
||||
uniqueIndex('media_items_episode_uidx').on(
|
||||
table.titleId,
|
||||
table.seasonNumber,
|
||||
table.episodeNumber,
|
||||
),
|
||||
index('media_items_published_idx').on(table.published),
|
||||
],
|
||||
);
|
||||
|
||||
export const sourceFiles = pgTable(
|
||||
'source_files',
|
||||
{
|
||||
id: uuid('id').primaryKey().defaultRandom(),
|
||||
mediaItemId: uuid('media_item_id')
|
||||
.notNull()
|
||||
.references(() => mediaItems.id, { onDelete: 'cascade' }),
|
||||
relativePath: text('relative_path').notNull(),
|
||||
sizeBytes: bigint('size_bytes', { mode: 'number' }).notNull(),
|
||||
modifiedAtNs: bigint('modified_at_ns', { mode: 'bigint' }).notNull(),
|
||||
matroskaUid: varchar('matroska_uid', { length: 128 }),
|
||||
headHash: varchar('head_hash', { length: 128 }).notNull(),
|
||||
tailHash: varchar('tail_hash', { length: 128 }).notNull(),
|
||||
fingerprint: varchar('fingerprint', { length: 128 }).notNull(),
|
||||
probeJson: jsonb('probe_json').$type<Record<string, unknown>>(),
|
||||
present: boolean('present').notNull().default(true),
|
||||
lastSeenAt: timestamp('last_seen_at', { withTimezone: true }).notNull().defaultNow(),
|
||||
...timestamps,
|
||||
},
|
||||
(table) => [
|
||||
uniqueIndex('source_files_path_uidx').on(table.relativePath),
|
||||
uniqueIndex('source_files_fingerprint_uidx').on(table.fingerprint),
|
||||
index('source_files_media_item_idx').on(table.mediaItemId),
|
||||
],
|
||||
);
|
||||
|
||||
export const mediaStreams = pgTable(
|
||||
'media_streams',
|
||||
{
|
||||
id: uuid('id').primaryKey().defaultRandom(),
|
||||
sourceFileId: uuid('source_file_id')
|
||||
.notNull()
|
||||
.references(() => sourceFiles.id, { onDelete: 'cascade' }),
|
||||
streamIndex: integer('stream_index').notNull(),
|
||||
kind: streamKind('kind').notNull(),
|
||||
codec: varchar('codec', { length: 64 }).notNull(),
|
||||
codecString: varchar('codec_string', { length: 128 }),
|
||||
language: varchar('language', { length: 35 }),
|
||||
label: varchar('label', { length: 200 }),
|
||||
isDefault: boolean('is_default').notNull().default(false),
|
||||
channels: integer('channels'),
|
||||
sampleRate: integer('sample_rate'),
|
||||
width: integer('width'),
|
||||
height: integer('height'),
|
||||
frameRate: varchar('frame_rate', { length: 32 }),
|
||||
bitDepth: integer('bit_depth'),
|
||||
pixelFormat: varchar('pixel_format', { length: 64 }),
|
||||
colorTransfer: varchar('color_transfer', { length: 64 }),
|
||||
...timestamps,
|
||||
},
|
||||
(table) => [
|
||||
uniqueIndex('media_streams_source_index_uidx').on(table.sourceFileId, table.streamIndex),
|
||||
index('media_streams_source_idx').on(table.sourceFileId),
|
||||
],
|
||||
);
|
||||
|
||||
export const subtitleTracks = pgTable(
|
||||
'subtitle_tracks',
|
||||
{
|
||||
id: uuid('id').primaryKey().defaultRandom(),
|
||||
sourceFileId: uuid('source_file_id')
|
||||
.notNull()
|
||||
.references(() => sourceFiles.id, { onDelete: 'cascade' }),
|
||||
streamIndex: integer('stream_index').notNull(),
|
||||
codec: varchar('codec', { length: 64 }).notNull(),
|
||||
sourceLanguage: varchar('source_language', { length: 35 }),
|
||||
normalizedLanguage: varchar('normalized_language', { length: 35 }).notNull(),
|
||||
label: varchar('label', { length: 200 }).notNull(),
|
||||
sourceDefault: boolean('source_default').notNull().default(false),
|
||||
sourceForced: boolean('source_forced').notNull().default(false),
|
||||
isDefault: boolean('is_default').notNull().default(false),
|
||||
isForced: boolean('is_forced').notNull().default(false),
|
||||
assPath: text('ass_path'),
|
||||
webvttPath: text('webvtt_path'),
|
||||
...timestamps,
|
||||
},
|
||||
(table) => [
|
||||
uniqueIndex('subtitle_tracks_source_index_uidx').on(table.sourceFileId, table.streamIndex),
|
||||
index('subtitle_tracks_source_idx').on(table.sourceFileId),
|
||||
],
|
||||
);
|
||||
|
||||
export const fontAttachments = pgTable(
|
||||
'font_attachments',
|
||||
{
|
||||
id: uuid('id').primaryKey().defaultRandom(),
|
||||
sourceFileId: uuid('source_file_id')
|
||||
.notNull()
|
||||
.references(() => sourceFiles.id, { onDelete: 'cascade' }),
|
||||
streamIndex: integer('stream_index').notNull(),
|
||||
sha256: varchar('sha256', { length: 64 }).notNull(),
|
||||
mimeType: varchar('mime_type', { length: 100 }).notNull(),
|
||||
originalName: text('original_name').notNull(),
|
||||
storagePath: text('storage_path'),
|
||||
approved: boolean('approved').notNull().default(false),
|
||||
sizeBytes: bigint('size_bytes', { mode: 'number' }).notNull(),
|
||||
...timestamps,
|
||||
},
|
||||
(table) => [
|
||||
uniqueIndex('font_attachments_source_index_uidx').on(table.sourceFileId, table.streamIndex),
|
||||
index('font_attachments_hash_idx').on(table.sha256),
|
||||
],
|
||||
);
|
||||
|
||||
export const mediaPackages = pgTable(
|
||||
'media_packages',
|
||||
{
|
||||
id: uuid('id').primaryKey().defaultRandom(),
|
||||
mediaItemId: uuid('media_item_id')
|
||||
.notNull()
|
||||
.references(() => mediaItems.id, { onDelete: 'cascade' }),
|
||||
sourceFingerprint: varchar('source_fingerprint', { length: 128 }).notNull(),
|
||||
profileVersion: varchar('profile_version', { length: 64 }).notNull(),
|
||||
state: packageState('state').notNull().default('QUEUED'),
|
||||
manifestPath: text('manifest_path'),
|
||||
sizeBytes: bigint('size_bytes', { mode: 'number' }).notNull().default(0),
|
||||
cacheResident: boolean('cache_resident').notNull().default(false),
|
||||
pinned: boolean('pinned').notNull().default(false),
|
||||
lastAccessedAt: timestamp('last_accessed_at', { withTimezone: true }),
|
||||
errorCode: varchar('error_code', { length: 100 }),
|
||||
errorDetail: text('error_detail'),
|
||||
readyAt: timestamp('ready_at', { withTimezone: true }),
|
||||
...timestamps,
|
||||
},
|
||||
(table) => [
|
||||
uniqueIndex('media_packages_generation_uidx').on(
|
||||
table.mediaItemId,
|
||||
table.sourceFingerprint,
|
||||
table.profileVersion,
|
||||
),
|
||||
index('media_packages_lru_idx').on(table.cacheResident, table.pinned, table.lastAccessedAt),
|
||||
],
|
||||
);
|
||||
|
||||
export const jobs = pgTable(
|
||||
'jobs',
|
||||
{
|
||||
id: uuid('id').primaryKey().defaultRandom(),
|
||||
type: varchar('type', { length: 100 }).notNull(),
|
||||
state: jobState('state').notNull().default('QUEUED'),
|
||||
progress: real('progress').notNull().default(0),
|
||||
payload: jsonb('payload').$type<Record<string, unknown>>().notNull().default({}),
|
||||
result: jsonb('result').$type<Record<string, unknown>>(),
|
||||
error: text('error'),
|
||||
attempts: integer('attempts').notNull().default(0),
|
||||
...timestamps,
|
||||
},
|
||||
(table) => [index('jobs_state_created_idx').on(table.state, table.createdAt)],
|
||||
);
|
||||
|
||||
export const admins = pgTable(
|
||||
'admins',
|
||||
{
|
||||
id: uuid('id').primaryKey().defaultRandom(),
|
||||
email: varchar('email', { length: 320 }).notNull(),
|
||||
passwordHash: text('password_hash').notNull(),
|
||||
totpSecretEncrypted: text('totp_secret_encrypted'),
|
||||
disabled: boolean('disabled').notNull().default(false),
|
||||
lastLoginAt: timestamp('last_login_at', { withTimezone: true }),
|
||||
...timestamps,
|
||||
},
|
||||
(table) => [uniqueIndex('admins_email_uidx').on(table.email)],
|
||||
);
|
||||
|
||||
export const adminSessions = pgTable(
|
||||
'admin_sessions',
|
||||
{
|
||||
id: uuid('id').primaryKey().defaultRandom(),
|
||||
adminId: uuid('admin_id')
|
||||
.notNull()
|
||||
.references(() => admins.id, { onDelete: 'cascade' }),
|
||||
tokenHash: varchar('token_hash', { length: 64 }).notNull(),
|
||||
csrfTokenHash: varchar('csrf_token_hash', { length: 64 }).notNull(),
|
||||
expiresAt: timestamp('expires_at', { withTimezone: true }).notNull(),
|
||||
revokedAt: timestamp('revoked_at', { withTimezone: true }),
|
||||
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
|
||||
},
|
||||
(table) => [
|
||||
uniqueIndex('admin_sessions_token_uidx').on(table.tokenHash),
|
||||
index('admin_sessions_admin_idx').on(table.adminId),
|
||||
],
|
||||
);
|
||||
|
||||
export const playbackSessions = pgTable(
|
||||
'playback_sessions',
|
||||
{
|
||||
id: uuid('id').primaryKey().defaultRandom(),
|
||||
mediaItemId: uuid('media_item_id')
|
||||
.notNull()
|
||||
.references(() => mediaItems.id, { onDelete: 'cascade' }),
|
||||
// Packaging generation IDs are deterministic UUIDs owned by the media worker. They are
|
||||
// deliberately not media_packages.id, so this column must not reference that primary key.
|
||||
generationId: uuid('generation_id'),
|
||||
state: playbackState('state').notNull().default('PREPARING'),
|
||||
capabilities: jsonb('capabilities').$type<Record<string, unknown>>().notNull(),
|
||||
reasonCode: varchar('reason_code', { length: 100 }),
|
||||
pollAfterMs: integer('poll_after_ms'),
|
||||
responseJson: jsonb('response_json').$type<Record<string, unknown>>().notNull().default({}),
|
||||
expiresAt: timestamp('expires_at', { withTimezone: true }).notNull(),
|
||||
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
|
||||
updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
|
||||
},
|
||||
(table) => [
|
||||
index('playback_sessions_media_idx').on(table.mediaItemId),
|
||||
index('playback_sessions_generation_idx').on(table.generationId),
|
||||
index('playback_sessions_expires_idx').on(table.expiresAt),
|
||||
],
|
||||
);
|
||||
|
||||
export type TitleRow = typeof titles.$inferSelect;
|
||||
export type MediaItemRow = typeof mediaItems.$inferSelect;
|
||||
export type SourceFileRow = typeof sourceFiles.$inferSelect;
|
||||
export type MediaPackageRow = typeof mediaPackages.$inferSelect;
|
||||
export type AdminRow = typeof admins.$inferSelect;
|
||||
export type AdminSessionRow = typeof adminSessions.$inferSelect;
|
||||
export type PlaybackSessionRow = typeof playbackSessions.$inferSelect;
|
||||
@@ -0,0 +1,100 @@
|
||||
import type { CatalogSnapshot } from '@easy-stream/contracts';
|
||||
import { getTableConfig } from 'drizzle-orm/pg-core';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
prepareCatalogSync,
|
||||
syncCatalogSnapshot,
|
||||
type Database,
|
||||
} from '../src/index.js';
|
||||
import { mediaItems, playbackSessions, titles } from '../src/schema.js';
|
||||
|
||||
const snapshot: CatalogSnapshot = {
|
||||
version: 1,
|
||||
generatedAt: '2026-07-14T10:00:00.000Z',
|
||||
titles: [{
|
||||
id: '11111111-1111-5111-8111-111111111111',
|
||||
slug: 'sample-film',
|
||||
kind: 'MOVIE',
|
||||
name: { fa: 'فیلم نمونه', en: 'Sample Film' },
|
||||
playable: true,
|
||||
resumeMediaItemId: '22222222-2222-5222-8222-222222222222',
|
||||
synopsis: {},
|
||||
mediaItems: [{
|
||||
id: '22222222-2222-5222-8222-222222222222',
|
||||
kind: 'MOVIE',
|
||||
durationSeconds: 90,
|
||||
compatibility: 'COPY',
|
||||
published: true,
|
||||
}],
|
||||
updatedAt: '2026-07-14T10:00:00.000Z',
|
||||
}],
|
||||
};
|
||||
|
||||
describe('catalog snapshot synchronization', () => {
|
||||
it('validates and maps deterministic scanner IDs and initial publication', () => {
|
||||
const prepared = prepareCatalogSync(snapshot);
|
||||
expect(prepared.titleRows).toMatchObject([{
|
||||
id: snapshot.titles[0]?.id,
|
||||
nameFa: 'فیلم نمونه',
|
||||
nameEn: 'Sample Film',
|
||||
published: true,
|
||||
}]);
|
||||
expect(prepared.mediaItemRows).toMatchObject([{
|
||||
id: snapshot.titles[0]?.mediaItems[0]?.id,
|
||||
titleId: snapshot.titles[0]?.id,
|
||||
compatibility: 'COPY',
|
||||
published: true,
|
||||
}]);
|
||||
});
|
||||
|
||||
it('rejects ambiguous duplicate IDs before opening a transaction', () => {
|
||||
const duplicate = structuredClone(snapshot);
|
||||
duplicate.titles.push({ ...structuredClone(duplicate.titles[0]!), slug: 'another-slug' });
|
||||
expect(() => prepareCatalogSync(duplicate)).toThrow(/duplicate title ID/u);
|
||||
});
|
||||
|
||||
it('only updates scanner-owned fields on conflicts', async () => {
|
||||
const conflicts: Array<{ table: unknown; set: Record<string, unknown> }> = [];
|
||||
const transaction = {
|
||||
async execute() {},
|
||||
insert(table: unknown) {
|
||||
return {
|
||||
values() {
|
||||
return {
|
||||
async onConflictDoUpdate(config: { set: Record<string, unknown> }) {
|
||||
conflicts.push({ table, set: config.set });
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
const database = {
|
||||
async transaction<T>(action: (value: typeof transaction) => Promise<T>): Promise<T> {
|
||||
return action(transaction);
|
||||
},
|
||||
} as unknown as Database;
|
||||
|
||||
await syncCatalogSnapshot(database, snapshot);
|
||||
|
||||
expect(Object.keys(conflicts.find((entry) => entry.table === titles)!.set).sort())
|
||||
.toEqual(['kind', 'slug', 'updatedAt']);
|
||||
expect(Object.keys(conflicts.find((entry) => entry.table === mediaItems)!.set).sort())
|
||||
.toEqual([
|
||||
'compatibility',
|
||||
'durationSeconds',
|
||||
'episodeNumber',
|
||||
'kind',
|
||||
'seasonNumber',
|
||||
'titleId',
|
||||
'updatedAt',
|
||||
]);
|
||||
});
|
||||
|
||||
it('does not constrain a worker generation UUID to media_packages.id', () => {
|
||||
const configuration = getTableConfig(playbackSessions);
|
||||
const generationForeignKey = configuration.foreignKeys.some((foreignKey) =>
|
||||
foreignKey.reference().columns.includes(playbackSessions.generationId));
|
||||
expect(generationForeignKey).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"rootDir": "src",
|
||||
"outDir": "dist",
|
||||
"tsBuildInfoFile": "dist/.tsbuildinfo",
|
||||
"paths": {
|
||||
"@easy-stream/contracts": ["packages/contracts/dist/index.d.ts"]
|
||||
}
|
||||
},
|
||||
"include": ["src/**/*.ts"]
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"name": "@easy-stream/media",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"default": "./dist/index.js"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"build": "tsc -p tsconfig.json",
|
||||
"typecheck": "tsc -p tsconfig.json --noEmit",
|
||||
"test": "vitest run",
|
||||
"clean": "rm -rf dist"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^24.10.0",
|
||||
"typescript": "^5.9.3",
|
||||
"vitest": "^3.2.4"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,286 @@
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { lstat, opendir, readFile, realpath, rename, rm, stat, writeFile } from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import { assertWritableDestination, assertWritableRoot, isPathInside, UnsafePathError } from './paths.js';
|
||||
|
||||
const METADATA = '.cache-entry.json';
|
||||
let lifecycleTail: Promise<void> = Promise.resolve();
|
||||
|
||||
async function serializeLifecycle<T>(operation: () => Promise<T>): Promise<T> {
|
||||
const previous = lifecycleTail;
|
||||
let release!: () => void;
|
||||
lifecycleTail = new Promise<void>((resolve) => { release = resolve; });
|
||||
await previous;
|
||||
try {
|
||||
return await operation();
|
||||
} finally {
|
||||
release();
|
||||
}
|
||||
}
|
||||
|
||||
export interface CacheEntryMetadata {
|
||||
version: 1;
|
||||
key: string;
|
||||
bytes: number;
|
||||
lastAccessedAt: string;
|
||||
/** Do not evict before the latest playback grant expires. */
|
||||
protectedUntil?: string;
|
||||
active: boolean;
|
||||
building: boolean;
|
||||
pinned: boolean;
|
||||
}
|
||||
|
||||
async function readCacheMetadata(directory: string): Promise<CacheEntryMetadata> {
|
||||
const destination = path.join(directory, METADATA);
|
||||
const details = await lstat(destination);
|
||||
if (details.isSymbolicLink() || !details.isFile()) {
|
||||
throw new UnsafePathError(`Cache metadata is not a regular file: ${destination}`);
|
||||
}
|
||||
return JSON.parse(await readFile(destination, 'utf8')) as CacheEntryMetadata;
|
||||
}
|
||||
|
||||
async function assertSafeDeletion(root: string, directory: string): Promise<void> {
|
||||
await assertWritableRoot(root);
|
||||
await assertWritableDestination(root, directory);
|
||||
const details = await lstat(directory);
|
||||
if (details.isSymbolicLink() || !details.isDirectory()) {
|
||||
throw new UnsafePathError(`Cache deletion target is not a regular directory: ${directory}`);
|
||||
}
|
||||
const [canonicalRoot, canonicalDirectory] = await Promise.all([realpath(root), realpath(directory)]);
|
||||
if (!isPathInside(canonicalRoot, canonicalDirectory) || canonicalDirectory === canonicalRoot) {
|
||||
throw new UnsafePathError(`Refusing unsafe cache deletion: ${directory}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function directorySize(directory: string): Promise<number> {
|
||||
let total = 0;
|
||||
const handle = await opendir(directory);
|
||||
for await (const entry of handle) {
|
||||
const candidate = path.join(directory, entry.name);
|
||||
const details = await lstat(candidate);
|
||||
if (details.isSymbolicLink()) throw new Error(`Symlink found in media cache: ${candidate}`);
|
||||
if (details.isDirectory()) total += await directorySize(candidate);
|
||||
// Generation-local font hardlinks do not consume additional blocks while the global
|
||||
// content-addressed store owns another link. Cross-device copy fallbacks have nlink=1.
|
||||
else if (details.isFile()) total += details.nlink > 1 ? 0 : details.size;
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
export async function writeCacheMetadata(
|
||||
cacheRoot: string,
|
||||
entryDirectory: string,
|
||||
metadata: Omit<CacheEntryMetadata, 'version' | 'bytes'> & { bytes?: number },
|
||||
): Promise<CacheEntryMetadata> {
|
||||
const directory = await assertWritableDestination(cacheRoot, entryDirectory);
|
||||
const details = await stat(directory);
|
||||
if (!details.isDirectory()) throw new Error('Cache entry is not a directory');
|
||||
const value: CacheEntryMetadata = {
|
||||
version: 1,
|
||||
...metadata,
|
||||
bytes: metadata.bytes ?? await directorySize(directory),
|
||||
};
|
||||
const destination = path.join(directory, METADATA);
|
||||
try {
|
||||
const existing = await lstat(destination);
|
||||
if (existing.isSymbolicLink() || !existing.isFile()) {
|
||||
throw new UnsafePathError(`Cache metadata is not a regular file: ${destination}`);
|
||||
}
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
|
||||
}
|
||||
const temporary = `${destination}.${randomUUID()}.tmp`;
|
||||
try {
|
||||
await writeFile(temporary, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o640, flag: 'wx' });
|
||||
await rename(temporary, destination);
|
||||
} finally {
|
||||
await rm(temporary, { force: true });
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
export async function touchCacheEntry(cacheRoot: string, entryDirectory: string): Promise<void> {
|
||||
const directory = await assertWritableDestination(cacheRoot, entryDirectory);
|
||||
const value = await readCacheMetadata(directory);
|
||||
await writeCacheMetadata(cacheRoot, directory, { ...value, lastAccessedAt: new Date().toISOString() });
|
||||
}
|
||||
|
||||
export interface CacheTouchOptions {
|
||||
accessedAt?: string;
|
||||
protectedUntil?: string;
|
||||
}
|
||||
|
||||
/** Updates one cache generation without allowing a caller-controlled filesystem path. */
|
||||
export async function touchCacheGeneration(
|
||||
cacheRoot: string,
|
||||
generation: string,
|
||||
options: CacheTouchOptions = {},
|
||||
): Promise<boolean> {
|
||||
return await serializeLifecycle(async () => await touchCacheGenerationUnlocked(cacheRoot, generation, options));
|
||||
}
|
||||
|
||||
async function touchCacheGenerationUnlocked(
|
||||
cacheRoot: string,
|
||||
generation: string,
|
||||
options: CacheTouchOptions,
|
||||
): Promise<boolean> {
|
||||
if (!/^[a-z0-9][a-z0-9._-]{7,127}$/u.test(generation)) throw new Error('Invalid generation identifier');
|
||||
const accessedAt = options.accessedAt ?? new Date().toISOString();
|
||||
if (!Number.isFinite(Date.parse(accessedAt))) throw new Error('Invalid cache access timestamp');
|
||||
if (options.protectedUntil !== undefined && !Number.isFinite(Date.parse(options.protectedUntil))) {
|
||||
throw new Error('Invalid cache protection timestamp');
|
||||
}
|
||||
await assertWritableRoot(cacheRoot);
|
||||
const generationsRoot = path.join(path.resolve(cacheRoot), 'generations');
|
||||
const directory = await assertWritableDestination(generationsRoot, path.join(generationsRoot, generation));
|
||||
let value: CacheEntryMetadata;
|
||||
try {
|
||||
const details = await lstat(directory);
|
||||
if (details.isSymbolicLink() || !details.isDirectory()) throw new Error('Cache generation is not a regular directory');
|
||||
value = await readCacheMetadata(directory);
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false;
|
||||
throw error;
|
||||
}
|
||||
if (value.version !== 1 || value.key !== generation) throw new Error('Cache generation metadata does not match request');
|
||||
const existingAccess = Date.parse(value.lastAccessedAt);
|
||||
const requestedAccess = Date.parse(accessedAt);
|
||||
const existingProtection = Date.parse(value.protectedUntil ?? '');
|
||||
const requestedProtection = Date.parse(options.protectedUntil ?? '');
|
||||
await writeCacheMetadata(generationsRoot, directory, {
|
||||
...value,
|
||||
lastAccessedAt: new Date(Math.max(
|
||||
Number.isFinite(existingAccess) ? existingAccess : 0,
|
||||
requestedAccess,
|
||||
)).toISOString(),
|
||||
...(Number.isFinite(existingProtection) || Number.isFinite(requestedProtection)
|
||||
? {
|
||||
protectedUntil: new Date(Math.max(
|
||||
Number.isFinite(existingProtection) ? existingProtection : 0,
|
||||
Number.isFinite(requestedProtection) ? requestedProtection : 0,
|
||||
)).toISOString(),
|
||||
}
|
||||
: {}),
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
export interface EvictionOptions {
|
||||
capacityBytes: number;
|
||||
highWatermark?: number;
|
||||
lowWatermark?: number;
|
||||
protectedKeys?: ReadonlySet<string>;
|
||||
/** Bytes owned by the cache but stored outside the per-generation directories. */
|
||||
overheadBytes?: number;
|
||||
now?: Date;
|
||||
/** Grace window for newly built/touched entries while access events propagate. */
|
||||
minimumRetentionMs?: number;
|
||||
dryRun?: boolean;
|
||||
}
|
||||
|
||||
export interface EvictionResult {
|
||||
beforeBytes: number;
|
||||
afterBytes: number;
|
||||
evicted: string[];
|
||||
}
|
||||
|
||||
export async function evictCacheGeneration(cacheRoot: string, generation: string): Promise<boolean> {
|
||||
return await serializeLifecycle(async () => await evictCacheGenerationUnlocked(cacheRoot, generation));
|
||||
}
|
||||
|
||||
async function evictCacheGenerationUnlocked(cacheRoot: string, generation: string): Promise<boolean> {
|
||||
if (!/^[a-z0-9][a-z0-9._-]{7,127}$/u.test(generation)) throw new Error('Invalid generation identifier');
|
||||
await assertWritableRoot(cacheRoot);
|
||||
const generationsRoot = path.join(path.resolve(cacheRoot), 'generations');
|
||||
const directory = await assertWritableDestination(generationsRoot, path.join(generationsRoot, generation));
|
||||
let metadata: CacheEntryMetadata;
|
||||
try {
|
||||
const details = await lstat(directory);
|
||||
if (details.isSymbolicLink() || !details.isDirectory()) throw new Error('Cache generation is not a regular directory');
|
||||
metadata = await readCacheMetadata(directory);
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false;
|
||||
throw error;
|
||||
}
|
||||
if (metadata.version !== 1 || metadata.key !== generation) throw new Error('Cache generation metadata does not match request');
|
||||
if (metadata.active || metadata.building) throw new Error(`Cache generation is active: ${generation}`);
|
||||
if (metadata.pinned) throw new Error(`Cache generation is pinned: ${generation}`);
|
||||
if (isTimeProtected(metadata, Date.now())) throw new Error(`Cache generation has an active playback lease: ${generation}`);
|
||||
await assertSafeDeletion(generationsRoot, directory);
|
||||
await rm(directory, { recursive: true, force: false });
|
||||
return true;
|
||||
}
|
||||
|
||||
export async function evictCache(cacheRoot: string, options: EvictionOptions): Promise<EvictionResult> {
|
||||
return await serializeLifecycle(async () => await evictCacheUnlocked(cacheRoot, options));
|
||||
}
|
||||
|
||||
async function evictCacheUnlocked(cacheRoot: string, options: EvictionOptions): Promise<EvictionResult> {
|
||||
const root = path.resolve(cacheRoot);
|
||||
const high = options.highWatermark ?? 0.85;
|
||||
const low = options.lowWatermark ?? 0.75;
|
||||
if (!(options.capacityBytes > 0) || !(low >= 0 && low < high && high <= 1)) {
|
||||
throw new RangeError('Invalid cache capacity or watermarks');
|
||||
}
|
||||
const entries: Array<{ directory: string; metadata: CacheEntryMetadata }> = [];
|
||||
const overheadBytes = options.overheadBytes ?? 0;
|
||||
if (!Number.isFinite(overheadBytes) || overheadBytes < 0) throw new RangeError('Invalid cache overhead');
|
||||
const minimumRetentionMs = options.minimumRetentionMs ?? 0;
|
||||
if (!Number.isFinite(minimumRetentionMs) || minimumRetentionMs < 0) {
|
||||
throw new RangeError('Invalid cache retention window');
|
||||
}
|
||||
const now = (options.now ?? new Date()).getTime();
|
||||
let beforeBytes = overheadBytes;
|
||||
await assertWritableRoot(root);
|
||||
try {
|
||||
await lstat(root);
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
|
||||
return { beforeBytes, afterBytes: beforeBytes, evicted: [] };
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
const handle = await opendir(root);
|
||||
for await (const entry of handle) {
|
||||
if (entry.isSymbolicLink()) throw new UnsafePathError(`Symlink found in cache generations: ${path.join(root, entry.name)}`);
|
||||
if (!entry.isDirectory()) continue;
|
||||
const directory = path.join(root, entry.name);
|
||||
try {
|
||||
const metadata = await readCacheMetadata(directory);
|
||||
if (metadata.version !== 1 || metadata.key !== entry.name
|
||||
|| !Number.isFinite(metadata.bytes) || metadata.bytes < 0
|
||||
|| !Number.isFinite(Date.parse(metadata.lastAccessedAt))) continue;
|
||||
entries.push({ directory, metadata });
|
||||
beforeBytes += metadata.bytes;
|
||||
} catch (error) {
|
||||
if (error instanceof UnsafePathError) throw error;
|
||||
// Incomplete/unmanaged directories are never deleted by the LRU.
|
||||
}
|
||||
}
|
||||
if (beforeBytes <= options.capacityBytes * high) return { beforeBytes, afterBytes: beforeBytes, evicted: [] };
|
||||
entries.sort((left, right) => Date.parse(left.metadata.lastAccessedAt) - Date.parse(right.metadata.lastAccessedAt));
|
||||
const target = options.capacityBytes * low;
|
||||
let afterBytes = beforeBytes;
|
||||
const evicted: string[] = [];
|
||||
for (const entry of entries) {
|
||||
if (afterBytes <= target) break;
|
||||
const protectedEntry = entry.metadata.active || entry.metadata.building || entry.metadata.pinned
|
||||
|| isTimeProtected(entry.metadata, now)
|
||||
|| Date.parse(entry.metadata.lastAccessedAt) > now - minimumRetentionMs
|
||||
|| options.protectedKeys?.has(entry.metadata.key) === true;
|
||||
if (protectedEntry) continue;
|
||||
await assertSafeDeletion(root, entry.directory);
|
||||
if (options.dryRun !== true) await rm(entry.directory, { recursive: true, force: false });
|
||||
afterBytes -= entry.metadata.bytes;
|
||||
evicted.push(entry.metadata.key);
|
||||
}
|
||||
return { beforeBytes, afterBytes, evicted };
|
||||
}
|
||||
|
||||
function isTimeProtected(metadata: CacheEntryMetadata, now: number): boolean {
|
||||
if (metadata.protectedUntil === undefined) return false;
|
||||
const protectedUntil = Date.parse(metadata.protectedUntil);
|
||||
// Corrupt protection metadata fails closed: an operator can inspect/fix it rather than
|
||||
// evicting files that might still be in use.
|
||||
return !Number.isFinite(protectedUntil) || protectedUntil > now;
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
import { normalizeStreamLanguage } from './language.js';
|
||||
import type { Classification, MediaProbe, NormalizedTrack, ProbeStream } from './types.js';
|
||||
|
||||
function isHdr(stream: ProbeStream): boolean {
|
||||
const transfer = stream.color_transfer?.toLowerCase();
|
||||
const primaries = stream.color_primaries?.toLowerCase();
|
||||
if (transfer === 'smpte2084' || transfer === 'arib-std-b67' || primaries === 'bt2020') return true;
|
||||
return (stream.side_data_list ?? []).some((data) => {
|
||||
const encoded = JSON.stringify(data).toLowerCase();
|
||||
return encoded.includes('dolby vision') || encoded.includes('hdr10+') || encoded.includes('mastering display');
|
||||
});
|
||||
}
|
||||
|
||||
function isCopySafeVideo(stream: ProbeStream): boolean {
|
||||
const depth = Number.parseInt(stream.bits_per_raw_sample ?? '8', 10);
|
||||
const profile = stream.profile?.toLowerCase() ?? '';
|
||||
return stream.codec_name === 'h264'
|
||||
&& ['yuv420p', 'yuvj420p'].includes(stream.pix_fmt ?? '')
|
||||
&& (Number.isNaN(depth) || depth <= 8)
|
||||
&& !profile.includes('high 10')
|
||||
&& !profile.includes('high 4:2')
|
||||
&& (stream.field_order === undefined || ['progressive', 'unknown'].includes(stream.field_order));
|
||||
}
|
||||
|
||||
function isCopySafeAudio(stream: ProbeStream): boolean {
|
||||
const profile = stream.profile?.toLowerCase();
|
||||
return stream.codec_name === 'aac'
|
||||
&& (profile === undefined || profile === 'lc' || profile.includes('low complexity'))
|
||||
&& (stream.channels ?? 2) <= 6;
|
||||
}
|
||||
|
||||
export interface ClassificationOptions {
|
||||
maxCopySegmentDuration?: number;
|
||||
measuredMaxGopSeconds?: number;
|
||||
}
|
||||
|
||||
export function classifyMedia(probe: MediaProbe, options: ClassificationOptions = {}): Classification {
|
||||
const videos = probe.streams.filter((stream) => stream.codec_type === 'video' && stream.disposition?.attached_pic !== 1);
|
||||
const audios = probe.streams.filter((stream) => stream.codec_type === 'audio');
|
||||
const reasons: string[] = [];
|
||||
const duration = Number.parseFloat(probe.format.duration ?? 'NaN');
|
||||
if (videos.length === 0) reasons.push('NO_VIDEO');
|
||||
if (audios.length === 0) reasons.push('NO_AUDIO');
|
||||
if (!Number.isFinite(duration) || duration <= 0) reasons.push('INVALID_DURATION');
|
||||
if ((probe.format.probe_score ?? 100) < 25) reasons.push('LOW_PROBE_SCORE');
|
||||
const video = videos[0];
|
||||
if (video === undefined || audios.length === 0 || reasons.length > 0) {
|
||||
return { class: 'INVALID', reasons, audioStreamIndexes: audios.map((stream) => stream.index) };
|
||||
}
|
||||
if (isHdr(video)) {
|
||||
return { class: 'HOLD_HDR', reasons: ['HDR_UNSUPPORTED_V1'], videoStreamIndex: video.index, audioStreamIndexes: audios.map((stream) => stream.index) };
|
||||
}
|
||||
if (!isCopySafeVideo(video)) {
|
||||
return {
|
||||
class: 'VIDEO_TRANSCODE',
|
||||
reasons: [`VIDEO_CODEC_UNSUPPORTED:${video.codec_name ?? 'unknown'}`, `VIDEO_PIXEL_FORMAT:${video.pix_fmt ?? 'unknown'}`],
|
||||
videoStreamIndex: video.index,
|
||||
audioStreamIndexes: audios.map((stream) => stream.index),
|
||||
};
|
||||
}
|
||||
const maxGop = options.measuredMaxGopSeconds;
|
||||
if (maxGop !== undefined && maxGop > (options.maxCopySegmentDuration ?? 18)) {
|
||||
return {
|
||||
class: 'VIDEO_TRANSCODE',
|
||||
reasons: [`GOP_TOO_LONG:${maxGop.toFixed(3)}`],
|
||||
videoStreamIndex: video.index,
|
||||
audioStreamIndexes: audios.map((stream) => stream.index),
|
||||
};
|
||||
}
|
||||
const unsupportedAudio = audios.filter((stream) => !isCopySafeAudio(stream));
|
||||
if (unsupportedAudio.length > 0) {
|
||||
return {
|
||||
class: 'AUDIO_TRANSCODE',
|
||||
reasons: unsupportedAudio.map((stream) => `AUDIO_CODEC_UNSUPPORTED:${stream.index}:${stream.codec_name ?? 'unknown'}`),
|
||||
videoStreamIndex: video.index,
|
||||
audioStreamIndexes: audios.map((stream) => stream.index),
|
||||
};
|
||||
}
|
||||
return {
|
||||
class: 'COPY',
|
||||
reasons: [],
|
||||
videoStreamIndex: video.index,
|
||||
audioStreamIndexes: audios.map((stream) => stream.index),
|
||||
};
|
||||
}
|
||||
|
||||
export function normalizeTracks(probe: MediaProbe): NormalizedTrack[] {
|
||||
return probe.streams.flatMap((stream): NormalizedTrack[] => {
|
||||
if (!['video', 'audio', 'subtitle', 'attachment'].includes(stream.codec_type ?? '')) return [];
|
||||
const type = stream.codec_type as NormalizedTrack['type'];
|
||||
const language = normalizeStreamLanguage(stream);
|
||||
return [{
|
||||
index: stream.index,
|
||||
type,
|
||||
codec: stream.codec_name ?? 'unknown',
|
||||
language,
|
||||
...(stream.tags?.title === undefined ? {} : { label: stream.tags.title }),
|
||||
default: type === 'subtitle' ? language === 'fa' : stream.disposition?.default === 1,
|
||||
// Embedded flags are advisory; full-track ASS marked forced is common in this archive.
|
||||
forced: false,
|
||||
}];
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { rename, rm, stat, writeFile } from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import { probeMedia } from './ffprobe.js';
|
||||
import { fingerprintSource } from './fingerprint.js';
|
||||
import { assessFfmpegWarnings, buildMasterPlaylist, validateMediaPlaylist, type MasterAudio } from './hls.js';
|
||||
import { languageDisplayName, normalizeStreamLanguage } from './language.js';
|
||||
import { assertWritableDestination, ensureWritableDirectory, resolveInside } from './paths.js';
|
||||
import { runProcess } from './process.js';
|
||||
import type { Classification, MediaProbe, PackageResult, SourceFingerprint } from './types.js';
|
||||
|
||||
export interface CompatibilityEncodeOptions {
|
||||
archiveRoot: string;
|
||||
derivedRoot: string;
|
||||
sourcePath: string;
|
||||
fingerprint: SourceFingerprint;
|
||||
probe: MediaProbe;
|
||||
classification: Classification;
|
||||
generation: string;
|
||||
ffmpegPath?: string;
|
||||
ffprobePath?: string;
|
||||
segmentSeconds?: number;
|
||||
}
|
||||
|
||||
function frameRate(probe: MediaProbe, videoIndex: number): number {
|
||||
const stream = probe.streams.find((candidate) => candidate.index === videoIndex);
|
||||
const raw = stream?.avg_frame_rate ?? stream?.r_frame_rate ?? '24/1';
|
||||
const [numeratorRaw, denominatorRaw] = raw.split('/');
|
||||
const numerator = Number(numeratorRaw);
|
||||
const denominator = Number(denominatorRaw ?? 1);
|
||||
const value = numerator / denominator;
|
||||
return Number.isFinite(value) && value > 0 && value <= 240 ? value : 24;
|
||||
}
|
||||
|
||||
function renditions(probe: MediaProbe, indexes: readonly number[]): MasterAudio[] {
|
||||
return indexes.map((streamIndex, index) => {
|
||||
const stream = probe.streams.find((candidate) => candidate.index === streamIndex);
|
||||
if (stream === undefined) throw new Error(`Audio stream ${streamIndex} is missing`);
|
||||
const language = normalizeStreamLanguage(stream);
|
||||
return {
|
||||
streamIndex,
|
||||
language,
|
||||
name: languageDisplayName(language),
|
||||
uri: `audio-${streamIndex}-${language.replace(/[^a-z0-9-]/giu, '') || 'und'}/index.m3u8`,
|
||||
...(stream.channels === undefined ? {} : { channels: stream.channels }),
|
||||
default: index === 0,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export function buildCompatibilityEncodeArguments(
|
||||
source: string,
|
||||
output: string,
|
||||
probe: MediaProbe,
|
||||
classification: Classification,
|
||||
segmentSeconds = 6,
|
||||
): string[] {
|
||||
if (classification.class === 'HOLD_HDR') throw new Error('HDR_UNSUPPORTED_V1');
|
||||
if (classification.class === 'INVALID') throw new Error('INVALID_SOURCE');
|
||||
const videoIndex = classification.videoStreamIndex;
|
||||
if (videoIndex === undefined) throw new Error('No video stream selected');
|
||||
const audio = renditions(probe, classification.audioStreamIndexes);
|
||||
const gop = Math.max(1, Math.ceil(frameRate(probe, videoIndex) * segmentSeconds));
|
||||
const args = [
|
||||
'-hide_banner', '-loglevel', 'warning', '-nostdin', '-y',
|
||||
'-i', source,
|
||||
'-map', `0:${videoIndex}`,
|
||||
];
|
||||
for (const item of audio) args.push('-map', `0:${item.streamIndex}`);
|
||||
args.push(
|
||||
'-map_metadata', '-1', '-map_chapters', '-1', '-sn', '-dn',
|
||||
'-c:v', 'libx264', '-crf', '18', '-preset', 'medium',
|
||||
'-profile:v', 'high', '-pix_fmt', 'yuv420p', '-flags', '+cgop',
|
||||
'-g', String(gop), '-keyint_min', String(gop), '-sc_threshold', '0',
|
||||
'-force_key_frames', `expr:gte(t,n_forced*${segmentSeconds})`,
|
||||
);
|
||||
audio.forEach((item, index) => {
|
||||
args.push(`-c:a:${index}`, 'aac', `-b:a:${index}`, (item.channels ?? 2) > 2 ? '384k' : '192k');
|
||||
});
|
||||
const variants = [
|
||||
'v:0,agroup:audio,name:video',
|
||||
...audio.map((item, index) => `a:${index},agroup:audio,language:${item.language},default:${item.default ? 'yes' : 'no'},name:${path.dirname(item.uri)}`),
|
||||
].join(' ');
|
||||
args.push(
|
||||
'-f', 'hls', '-hls_time', String(segmentSeconds),
|
||||
'-hls_segment_type', 'fmp4', '-hls_playlist_type', 'vod',
|
||||
'-hls_flags', 'independent_segments+temp_file',
|
||||
'-master_pl_name', 'master.ffmpeg.m3u8', '-var_stream_map', variants,
|
||||
'-hls_fmp4_init_filename', 'init-%v.mp4',
|
||||
'-hls_segment_filename', path.join(output, '%v', 'segment-%06d.m4s'),
|
||||
path.join(output, '%v', 'index.m3u8'),
|
||||
);
|
||||
return args;
|
||||
}
|
||||
|
||||
function outputProbe(source: MediaProbe, videoIndex: number): MediaProbe {
|
||||
const { bit_rate: _ignoredBitrate, ...format } = source.format;
|
||||
return {
|
||||
...source,
|
||||
streams: source.streams.map((stream) => {
|
||||
if (stream.index === videoIndex) {
|
||||
const pixels = (stream.width ?? 1920) * (stream.height ?? 1080);
|
||||
return {
|
||||
...stream,
|
||||
codec_name: 'h264',
|
||||
profile: 'High',
|
||||
pix_fmt: 'yuv420p',
|
||||
bits_per_raw_sample: '8',
|
||||
mime_codec_string: 'avc1.640028',
|
||||
bit_rate: String(pixels > 1920 * 1080 ? 20_000_000 : 8_000_000),
|
||||
};
|
||||
}
|
||||
if (stream.codec_type === 'audio') return { ...stream, codec_name: 'aac', profile: 'LC', mime_codec_string: 'mp4a.40.2' };
|
||||
return stream;
|
||||
}),
|
||||
format,
|
||||
};
|
||||
}
|
||||
|
||||
async function validateEncodedCodecs(videoPlaylist: string, audioPlaylists: readonly string[], ffprobePath: string): Promise<void> {
|
||||
const video = await probeMedia(videoPlaylist, { ffprobePath, timeoutMs: 120_000 });
|
||||
if (!video.streams.some((stream) => stream.codec_type === 'video' && stream.codec_name === 'h264' && stream.pix_fmt === 'yuv420p')) {
|
||||
throw new Error('Compatibility output is not 8-bit H.264 yuv420p');
|
||||
}
|
||||
for (const playlist of audioPlaylists) {
|
||||
const audio = await probeMedia(playlist, { ffprobePath, timeoutMs: 120_000 });
|
||||
if (!audio.streams.some((stream) => stream.codec_type === 'audio' && stream.codec_name === 'aac')) {
|
||||
throw new Error('Compatibility audio output is not AAC');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function prepareCompatibilityHls(options: CompatibilityEncodeOptions): Promise<PackageResult> {
|
||||
if (options.classification.class === 'HOLD_HDR') throw new Error('HDR_UNSUPPORTED_V1');
|
||||
if (options.classification.class !== 'VIDEO_TRANSCODE') {
|
||||
throw new Error(`Compatibility video encode is not required for ${options.classification.class}`);
|
||||
}
|
||||
if (!/^[a-z0-9][a-z0-9._-]{7,127}$/u.test(options.generation)) throw new Error('Invalid generation identifier');
|
||||
const source = await resolveInside(options.archiveRoot, options.sourcePath);
|
||||
const videoIndex = options.classification.videoStreamIndex;
|
||||
if (videoIndex === undefined) throw new Error('No video stream selected');
|
||||
const audio = renditions(options.probe, options.classification.audioStreamIndexes);
|
||||
const generationsRoot = path.join(options.derivedRoot, 'generations');
|
||||
await ensureWritableDirectory(options.derivedRoot, generationsRoot);
|
||||
const finalDirectory = await assertWritableDestination(options.derivedRoot, path.join(generationsRoot, options.generation));
|
||||
try {
|
||||
if ((await stat(path.join(finalDirectory, 'master.m3u8'))).isFile()) {
|
||||
const videoPlaylist = await validateMediaPlaylist(path.join(finalDirectory, 'video', 'index.m3u8'), { requireEnded: true, maxTargetDuration: 7 });
|
||||
const audioPlaylists = await Promise.all(audio.map((item) => validateMediaPlaylist(path.join(finalDirectory, item.uri), { requireEnded: true, maxTargetDuration: 7 })));
|
||||
return { generation: options.generation, outputDirectory: finalDirectory, masterPlaylist: path.join(finalDirectory, 'master.m3u8'), videoPlaylist, audioPlaylists, knownAacRepairs: 0 };
|
||||
}
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
|
||||
}
|
||||
const staging = await assertWritableDestination(options.derivedRoot, path.join(options.derivedRoot, `.building-${options.generation}-${randomUUID()}`));
|
||||
await ensureWritableDirectory(options.derivedRoot, staging);
|
||||
let moved = false;
|
||||
try {
|
||||
const result = await runProcess(options.ffmpegPath ?? 'ffmpeg', buildCompatibilityEncodeArguments(
|
||||
source, staging, options.probe, options.classification, options.segmentSeconds ?? 6,
|
||||
), { timeoutMs: 7 * 24 * 60 * 60 * 1000, maxOutputBytes: 64 * 1024 * 1024 });
|
||||
const warnings = assessFfmpegWarnings(result.stderr);
|
||||
if (warnings.unknown.length > 0) throw new Error(`Unrecognized FFmpeg warning(s): ${warnings.unknown.slice(0, 5).join(' | ')}`);
|
||||
const videoStaging = path.join(staging, 'video', 'index.m3u8');
|
||||
const audioStaging = audio.map((item) => path.join(staging, item.uri));
|
||||
const [videoValidation, ...audioValidation] = await Promise.all([
|
||||
validateMediaPlaylist(videoStaging, { requireEnded: true, maxTargetDuration: 7 }),
|
||||
...audioStaging.map((playlist) => validateMediaPlaylist(playlist, { requireEnded: true, maxTargetDuration: 7 })),
|
||||
]);
|
||||
if (videoValidation === undefined) throw new Error('Encoded video playlist is missing');
|
||||
for (const item of audioValidation) {
|
||||
if (Math.abs(item.totalDuration - videoValidation.totalDuration) > 0.25) throw new Error('Encoded A/V durations differ by more than 250 ms');
|
||||
}
|
||||
await validateEncodedCodecs(videoStaging, audioStaging, options.ffprobePath ?? 'ffprobe');
|
||||
const after = await fingerprintSource(options.archiveRoot, source, options.fingerprint.edgeBytes);
|
||||
if (after.digest !== options.fingerprint.digest) throw new Error('Source changed during compatibility encoding');
|
||||
const master = buildMasterPlaylist(outputProbe(options.probe, videoIndex), videoIndex, 'video/index.m3u8', audio);
|
||||
await writeFile(path.join(staging, 'master.m3u8'), master, { encoding: 'utf8', mode: 0o640 });
|
||||
await rename(staging, finalDirectory);
|
||||
moved = true;
|
||||
const videoPlaylist = await validateMediaPlaylist(path.join(finalDirectory, 'video', 'index.m3u8'), { requireEnded: true, maxTargetDuration: 7 });
|
||||
const audioPlaylists = await Promise.all(audio.map((item) => validateMediaPlaylist(path.join(finalDirectory, item.uri), { requireEnded: true, maxTargetDuration: 7 })));
|
||||
return {
|
||||
generation: options.generation,
|
||||
outputDirectory: finalDirectory,
|
||||
masterPlaylist: path.join(finalDirectory, 'master.m3u8'),
|
||||
videoPlaylist,
|
||||
audioPlaylists,
|
||||
knownAacRepairs: warnings.knownAacRepairs,
|
||||
};
|
||||
} finally {
|
||||
if (!moved) await rm(staging, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import { runProcess, type RunProcessOptions } from './process.js';
|
||||
import type { MediaProbe, ProbeFormat, ProbeStream } from './types.js';
|
||||
|
||||
export interface ProbeOptions extends RunProcessOptions {
|
||||
ffprobePath?: string;
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function parseProbeJson(raw: string): MediaProbe {
|
||||
let value: unknown;
|
||||
try {
|
||||
value = JSON.parse(raw);
|
||||
} catch (error) {
|
||||
throw new Error(`ffprobe returned invalid JSON: ${error instanceof Error ? error.message : String(error)}`);
|
||||
}
|
||||
if (!isRecord(value) || !Array.isArray(value.streams) || !isRecord(value.format)) {
|
||||
throw new Error('ffprobe JSON is missing streams or format');
|
||||
}
|
||||
const streams = value.streams.filter(isRecord) as unknown as ProbeStream[];
|
||||
if (!streams.every((stream) => Number.isInteger(stream.index))) {
|
||||
throw new Error('ffprobe returned a stream without a numeric index');
|
||||
}
|
||||
return {
|
||||
streams,
|
||||
format: value.format as ProbeFormat,
|
||||
chapters: Array.isArray(value.chapters) ? value.chapters.filter(isRecord) : [],
|
||||
};
|
||||
}
|
||||
|
||||
export async function probeMedia(sourcePath: string, options: ProbeOptions = {}): Promise<MediaProbe> {
|
||||
const result = await runProcess(options.ffprobePath ?? 'ffprobe', [
|
||||
'-v', 'error',
|
||||
'-print_format', 'json',
|
||||
'-show_format',
|
||||
'-show_streams',
|
||||
'-show_chapters',
|
||||
sourcePath,
|
||||
], {
|
||||
timeoutMs: options.timeoutMs ?? 120_000,
|
||||
maxOutputBytes: options.maxOutputBytes ?? 64 * 1024 * 1024,
|
||||
...(options.cwd === undefined ? {} : { cwd: options.cwd }),
|
||||
...(options.env === undefined ? {} : { env: options.env }),
|
||||
...(options.signal === undefined ? {} : { signal: options.signal }),
|
||||
});
|
||||
return parseProbeJson(result.stdout);
|
||||
}
|
||||
|
||||
export { parseProbeJson };
|
||||
@@ -0,0 +1,61 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import { open, realpath, stat } from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import { isPathInside, UnsafePathError } from './paths.js';
|
||||
import type { SourceFingerprint } from './types.js';
|
||||
|
||||
const DEFAULT_EDGE_BYTES = 4 * 1024 * 1024;
|
||||
|
||||
export async function fingerprintSource(
|
||||
archiveRoot: string,
|
||||
sourcePath: string,
|
||||
edgeBytes = DEFAULT_EDGE_BYTES,
|
||||
): Promise<SourceFingerprint> {
|
||||
if (!Number.isSafeInteger(edgeBytes) || edgeBytes < 1 || edgeBytes > 64 * 1024 * 1024) {
|
||||
throw new RangeError('edgeBytes must be between 1 byte and 64 MiB');
|
||||
}
|
||||
const [root, source] = await Promise.all([realpath(archiveRoot), realpath(sourcePath)]);
|
||||
if (!isPathInside(root, source)) throw new UnsafePathError('Source is outside the archive root');
|
||||
|
||||
const before = await stat(source, { bigint: true });
|
||||
if (!before.isFile()) throw new UnsafePathError('Source is not a regular file');
|
||||
const size = before.size;
|
||||
const chunkSize = Number(size < BigInt(edgeBytes) ? size : BigInt(edgeBytes));
|
||||
const first = Buffer.alloc(chunkSize);
|
||||
const last = Buffer.alloc(chunkSize);
|
||||
const file = await open(source, 'r');
|
||||
try {
|
||||
await file.read(first, 0, chunkSize, 0);
|
||||
const lastOffset = size > BigInt(chunkSize) ? size - BigInt(chunkSize) : 0n;
|
||||
await file.read(last, 0, chunkSize, lastOffset);
|
||||
} finally {
|
||||
await file.close();
|
||||
}
|
||||
|
||||
const after = await stat(source, { bigint: true });
|
||||
if (after.size !== before.size || after.mtimeNs !== before.mtimeNs) {
|
||||
throw new Error('Source changed while it was being fingerprinted');
|
||||
}
|
||||
const relativePath = path.relative(root, source).split(path.sep).join('/');
|
||||
const hash = createHash('sha256');
|
||||
hash.update('easy-stream-source-fingerprint-v1\0');
|
||||
hash.update(relativePath);
|
||||
hash.update('\0');
|
||||
hash.update(size.toString());
|
||||
hash.update('\0');
|
||||
hash.update(before.mtimeNs.toString());
|
||||
hash.update('\0');
|
||||
hash.update(first);
|
||||
hash.update('\0');
|
||||
hash.update(last);
|
||||
|
||||
return {
|
||||
version: 1,
|
||||
algorithm: 'sha256',
|
||||
relativePath,
|
||||
size: size.toString(),
|
||||
mtimeNs: before.mtimeNs.toString(),
|
||||
edgeBytes: chunkSize,
|
||||
digest: hash.digest('hex'),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
import { createHash, randomUUID } from 'node:crypto';
|
||||
import { constants } from 'node:fs';
|
||||
import { access, copyFile, link, lstat, opendir, readFile, realpath, rm } from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import { assertWritableDestination, assertWritableRoot, ensureWritableDirectory, resolveInside, UnsafePathError } from './paths.js';
|
||||
import { runProcess } from './process.js';
|
||||
import type { ProcessResult, RunProcessOptions } from './process.js';
|
||||
import type { MediaProbe, ProbeStream, StoredFont } from './types.js';
|
||||
|
||||
const MAX_FONT_BYTES = 10 * 1024 * 1024;
|
||||
const MAX_FONT_COUNT = 128;
|
||||
const MAX_TOTAL_FONT_BYTES = 128 * 1024 * 1024;
|
||||
|
||||
function attachmentLooksLikeFont(stream: ProbeStream): boolean {
|
||||
const mime = stream.tags?.mimetype?.toLowerCase() ?? '';
|
||||
const name = stream.tags?.filename?.toLowerCase() ?? '';
|
||||
return stream.codec_type === 'attachment'
|
||||
&& (stream.codec_name === 'ttf' || stream.codec_name === 'otf'
|
||||
|| mime.includes('font') || mime.includes('truetype') || mime.includes('opentype')
|
||||
|| /\.(?:ttf|otf)$/iu.test(name));
|
||||
}
|
||||
|
||||
export function validateSfntFont(data: Buffer): 'ttf' | 'otf' {
|
||||
if (data.length < 12 || data.length > MAX_FONT_BYTES) throw new Error('Font size is outside accepted bounds');
|
||||
const signature = data.subarray(0, 4).toString('ascii');
|
||||
let format: 'ttf' | 'otf';
|
||||
if (data.readUInt32BE(0) === 0x00010000 || signature === 'true' || signature === 'typ1') format = 'ttf';
|
||||
else if (signature === 'OTTO') format = 'otf';
|
||||
else throw new Error(`Unsupported font signature ${JSON.stringify(signature)}`);
|
||||
const numTables = data.readUInt16BE(4);
|
||||
if (numTables < 1 || numTables > 256 || 12 + numTables * 16 > data.length) {
|
||||
throw new Error('Malformed SFNT table directory');
|
||||
}
|
||||
for (let index = 0; index < numTables; index += 1) {
|
||||
const record = 12 + index * 16;
|
||||
const offset = data.readUInt32BE(record + 8);
|
||||
const length = data.readUInt32BE(record + 12);
|
||||
if (offset > data.length || length > data.length || offset + length > data.length) {
|
||||
throw new Error('SFNT table points outside the attachment');
|
||||
}
|
||||
}
|
||||
return format;
|
||||
}
|
||||
|
||||
export interface FontExtractionOptions {
|
||||
archiveRoot: string;
|
||||
fontRoot: string;
|
||||
ffmpegPath?: string;
|
||||
sanitizerPath?: string;
|
||||
timeoutMs?: number;
|
||||
runner?: (binary: string, args: readonly string[], options?: RunProcessOptions) => Promise<ProcessResult>;
|
||||
}
|
||||
|
||||
export function fontDumpArguments(streamIndex: number, destination: string, source: string): string[] {
|
||||
return [
|
||||
'-hide_banner', '-loglevel', 'error', '-nostdin', '-y',
|
||||
`-dump_attachment:${streamIndex}`, destination,
|
||||
'-i', source,
|
||||
// Attachment dumping happens as the input header opens. Do not decode the movie.
|
||||
'-t', '0',
|
||||
'-f', 'null', '-',
|
||||
];
|
||||
}
|
||||
|
||||
export async function extractAndStoreFonts(
|
||||
sourcePath: string,
|
||||
probe: MediaProbe,
|
||||
options: FontExtractionOptions,
|
||||
): Promise<StoredFont[]> {
|
||||
const source = await resolveInside(options.archiveRoot, sourcePath);
|
||||
const staging = await ensureWritableDirectory(options.fontRoot, path.join(options.fontRoot, '.staging'), 0o700);
|
||||
const store = await ensureWritableDirectory(options.fontRoot, path.join(options.fontRoot, 'sha256'));
|
||||
const attachments = probe.streams.filter(attachmentLooksLikeFont);
|
||||
if (attachments.length > MAX_FONT_COUNT) throw new Error(`File has too many font attachments (${attachments.length})`);
|
||||
const declaredTotal = attachments.reduce((sum, stream) => sum + (stream.extradata_size ?? 0), 0);
|
||||
if (declaredTotal > MAX_TOTAL_FONT_BYTES) throw new Error('Declared font attachments exceed the total size limit');
|
||||
const output: StoredFont[] = [];
|
||||
const execute = options.runner ?? runProcess;
|
||||
|
||||
for (const attachment of attachments) {
|
||||
if ((attachment.extradata_size ?? 0) > MAX_FONT_BYTES) {
|
||||
throw new Error(`Font attachment ${attachment.index} exceeds ${MAX_FONT_BYTES} bytes`);
|
||||
}
|
||||
const temporary = path.join(staging, `${randomUUID()}.font`);
|
||||
try {
|
||||
await execute(
|
||||
options.ffmpegPath ?? 'ffmpeg',
|
||||
fontDumpArguments(attachment.index, temporary, source),
|
||||
{ timeoutMs: options.timeoutMs ?? 120_000 },
|
||||
);
|
||||
const data = await readFile(temporary);
|
||||
const format = validateSfntFont(data);
|
||||
if (options.sanitizerPath !== undefined) {
|
||||
await execute(options.sanitizerPath, [temporary], { timeoutMs: 30_000 });
|
||||
}
|
||||
const sha256 = createHash('sha256').update(data).digest('hex');
|
||||
const destination = path.join(store, `${sha256}.${format}`);
|
||||
try {
|
||||
await link(temporary, destination);
|
||||
} catch (error) {
|
||||
const code = (error as NodeJS.ErrnoException).code;
|
||||
if (code !== 'EEXIST') throw error;
|
||||
}
|
||||
const stored = await lstat(destination);
|
||||
if (stored.isSymbolicLink() || !stored.isFile()) {
|
||||
throw new UnsafePathError(`Stored font is not a regular file: ${destination}`);
|
||||
}
|
||||
await access(destination, constants.R_OK);
|
||||
output.push({
|
||||
streamIndex: attachment.index,
|
||||
sha256,
|
||||
path: destination,
|
||||
originalName: path.basename(attachment.tags?.filename ?? `attachment-${attachment.index}`),
|
||||
size: data.length,
|
||||
format,
|
||||
});
|
||||
} finally {
|
||||
await rm(temporary, { force: true });
|
||||
}
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
/** Publishes hash-named generation-local font links while retaining one global content store. */
|
||||
export async function publishGenerationFonts(
|
||||
fonts: readonly StoredFont[],
|
||||
mediaRoot: string,
|
||||
generationDirectory: string,
|
||||
): Promise<StoredFont[]> {
|
||||
await assertWritableRoot(mediaRoot);
|
||||
const root = await realpath(mediaRoot);
|
||||
const generation = await resolveInside(root, generationDirectory);
|
||||
const directory = await ensureWritableDirectory(root, path.join(generation, 'fonts'));
|
||||
const published: StoredFont[] = [];
|
||||
for (const font of fonts) {
|
||||
const source = await resolveInside(root, font.path);
|
||||
const destination = path.join(directory, `${font.sha256}.${font.format}`);
|
||||
try {
|
||||
await link(source, destination);
|
||||
} catch (error) {
|
||||
const code = (error as NodeJS.ErrnoException).code;
|
||||
if (code === 'EXDEV') {
|
||||
try {
|
||||
await copyFile(source, destination, constants.COPYFILE_EXCL);
|
||||
} catch (copyError) {
|
||||
if ((copyError as NodeJS.ErrnoException).code !== 'EEXIST') throw copyError;
|
||||
}
|
||||
} else if (code !== 'EEXIST') {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
const details = await lstat(destination);
|
||||
if (details.isSymbolicLink() || !details.isFile() || details.size !== font.size) {
|
||||
throw new Error(`Published font failed verification: ${font.sha256}`);
|
||||
}
|
||||
published.push({ ...font, path: destination });
|
||||
}
|
||||
return published;
|
||||
}
|
||||
|
||||
export interface FontPruneOptions {
|
||||
/** Avoid racing a package that extracted a font but has not published its hardlink yet. */
|
||||
minimumAgeMs?: number;
|
||||
now?: Date;
|
||||
}
|
||||
|
||||
export interface FontPruneResult {
|
||||
removed: string[];
|
||||
retainedBytes: number;
|
||||
}
|
||||
|
||||
/** Removes aged content-store files that have no generation hardlinks. */
|
||||
export async function pruneOrphanedFonts(
|
||||
mediaRoot: string,
|
||||
options: FontPruneOptions = {},
|
||||
): Promise<FontPruneResult> {
|
||||
const minimumAgeMs = options.minimumAgeMs ?? 60 * 60 * 1000;
|
||||
if (!Number.isFinite(minimumAgeMs) || minimumAgeMs < 0) throw new RangeError('Invalid font prune age');
|
||||
let root: string;
|
||||
try {
|
||||
await assertWritableRoot(mediaRoot);
|
||||
root = await realpath(mediaRoot);
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return { removed: [], retainedBytes: 0 };
|
||||
throw error;
|
||||
}
|
||||
let store: string;
|
||||
try {
|
||||
const storeCandidate = path.join(root, 'assets', 'fonts', 'sha256');
|
||||
await assertWritableDestination(root, storeCandidate);
|
||||
store = await resolveInside(root, storeCandidate);
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return { removed: [], retainedBytes: 0 };
|
||||
throw error;
|
||||
}
|
||||
let handle: Awaited<ReturnType<typeof opendir>>;
|
||||
try {
|
||||
handle = await opendir(store);
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return { removed: [], retainedBytes: 0 };
|
||||
throw error;
|
||||
}
|
||||
const cutoff = (options.now ?? new Date()).getTime() - minimumAgeMs;
|
||||
const removed: string[] = [];
|
||||
let retainedBytes = 0;
|
||||
for await (const entry of handle) {
|
||||
if (!/^[a-f0-9]{64}\.(?:ttf|otf)$/u.test(entry.name)) continue;
|
||||
const candidate = path.join(store, entry.name);
|
||||
const details = await lstat(candidate);
|
||||
if (details.isSymbolicLink()) throw new Error(`Symlink found in global font store: ${candidate}`);
|
||||
if (!details.isFile()) continue;
|
||||
if (details.nlink <= 1 && details.mtimeMs <= cutoff) {
|
||||
await rm(candidate, { force: false });
|
||||
removed.push(entry.name);
|
||||
} else {
|
||||
retainedBytes += details.size;
|
||||
}
|
||||
}
|
||||
return { removed, retainedBytes };
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
import { readFile, stat, writeFile, rename } from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import type { HlsPlaylistValidation, MediaProbe, ProbeStream } from './types.js';
|
||||
|
||||
const URI_PATTERN = /^(?![a-z][a-z0-9+.-]*:)(?!\/)(?!.*(?:^|\/)\.\.(?:\/|$))[^\0]+$/iu;
|
||||
|
||||
export interface ParsedMediaPlaylist {
|
||||
targetDuration: number;
|
||||
playlistType?: string;
|
||||
mapUri?: string;
|
||||
segments: Array<{ duration: number; uri: string }>;
|
||||
ended: boolean;
|
||||
}
|
||||
|
||||
function attribute(line: string, name: string): string | undefined {
|
||||
const match = line.match(new RegExp(`(?:^|,)${name}=(?:"([^"]*)"|([^,]*))`, 'u'));
|
||||
return match?.[1] ?? match?.[2];
|
||||
}
|
||||
|
||||
export function parseMediaPlaylist(content: string): ParsedMediaPlaylist {
|
||||
const lines = content.split(/\r?\n/u).map((line) => line.trim()).filter(Boolean);
|
||||
if (lines[0] !== '#EXTM3U') throw new Error('Playlist is missing EXTM3U');
|
||||
let targetDuration = 0;
|
||||
let playlistType: string | undefined;
|
||||
let mapUri: string | undefined;
|
||||
let pendingDuration: number | undefined;
|
||||
const segments: ParsedMediaPlaylist['segments'] = [];
|
||||
let ended = false;
|
||||
for (const line of lines.slice(1)) {
|
||||
if (line.startsWith('#EXT-X-TARGETDURATION:')) targetDuration = Number(line.slice(22));
|
||||
else if (line.startsWith('#EXT-X-PLAYLIST-TYPE:')) playlistType = line.slice(21);
|
||||
else if (line.startsWith('#EXT-X-MAP:')) mapUri = attribute(line.slice(11), 'URI');
|
||||
else if (line.startsWith('#EXTINF:')) pendingDuration = Number(line.slice(8).split(',')[0]);
|
||||
else if (line === '#EXT-X-ENDLIST') ended = true;
|
||||
else if (!line.startsWith('#')) {
|
||||
if (pendingDuration === undefined || !Number.isFinite(pendingDuration) || pendingDuration <= 0) {
|
||||
throw new Error(`Segment URI has no valid EXTINF: ${line}`);
|
||||
}
|
||||
segments.push({ duration: pendingDuration, uri: line });
|
||||
pendingDuration = undefined;
|
||||
}
|
||||
}
|
||||
if (!Number.isInteger(targetDuration) || targetDuration < 1) throw new Error('Invalid HLS target duration');
|
||||
if (mapUri === undefined) throw new Error('Fragmented MP4 playlist has no EXT-X-MAP');
|
||||
return { targetDuration, ...(playlistType === undefined ? {} : { playlistType }), mapUri, segments, ended };
|
||||
}
|
||||
|
||||
function assertSafeUri(uri: string): void {
|
||||
if (!URI_PATTERN.test(uri)) throw new Error(`Unsafe or external HLS URI: ${uri}`);
|
||||
}
|
||||
|
||||
export async function validateMediaPlaylist(
|
||||
playlistPath: string,
|
||||
options: { requireEnded?: boolean; maxTargetDuration?: number; minSegments?: number } = {},
|
||||
): Promise<HlsPlaylistValidation> {
|
||||
const content = await readFile(playlistPath, 'utf8');
|
||||
const parsed = parseMediaPlaylist(content);
|
||||
if (options.requireEnded === true && !parsed.ended) throw new Error(`${playlistPath} has no ENDLIST`);
|
||||
if (parsed.targetDuration > (options.maxTargetDuration ?? 18)) {
|
||||
throw new Error(`${playlistPath} target duration ${parsed.targetDuration} exceeds the compatibility limit`);
|
||||
}
|
||||
if (parsed.segments.length < (options.minSegments ?? 1)) throw new Error(`${playlistPath} has too few segments`);
|
||||
const directory = path.dirname(playlistPath);
|
||||
const mapUri = parsed.mapUri;
|
||||
if (mapUri === undefined) throw new Error('Fragmented MP4 playlist has no EXT-X-MAP');
|
||||
const referenced = [mapUri, ...parsed.segments.map((segment) => segment.uri)];
|
||||
for (const uri of referenced) {
|
||||
assertSafeUri(uri);
|
||||
const file = path.resolve(directory, uri);
|
||||
if (!file.startsWith(`${path.resolve(directory)}${path.sep}`)) throw new Error(`HLS URI escapes playlist directory: ${uri}`);
|
||||
const details = await stat(file);
|
||||
if (!details.isFile() || details.size === 0) throw new Error(`HLS resource is missing or empty: ${uri}`);
|
||||
}
|
||||
const durations = parsed.segments.map((segment) => segment.duration);
|
||||
return {
|
||||
path: playlistPath,
|
||||
segmentCount: durations.length,
|
||||
targetDuration: parsed.targetDuration,
|
||||
minDuration: Math.min(...durations),
|
||||
maxDuration: Math.max(...durations),
|
||||
totalDuration: durations.reduce((sum, duration) => sum + duration, 0),
|
||||
ended: parsed.ended,
|
||||
};
|
||||
}
|
||||
|
||||
export async function finalizeEventPlaylist(playlistPath: string): Promise<void> {
|
||||
const content = await readFile(playlistPath, 'utf8');
|
||||
const parsed = parseMediaPlaylist(content);
|
||||
if (!parsed.ended) throw new Error('Cannot finalize an incomplete EVENT playlist');
|
||||
const vod = content.replace('#EXT-X-PLAYLIST-TYPE:EVENT', '#EXT-X-PLAYLIST-TYPE:VOD');
|
||||
const temporary = `${playlistPath}.vod.tmp`;
|
||||
await writeFile(temporary, vod, { encoding: 'utf8', mode: 0o640 });
|
||||
await rename(temporary, playlistPath);
|
||||
}
|
||||
|
||||
function escapeAttribute(value: string): string {
|
||||
return value.replace(/["\r\n]/gu, '');
|
||||
}
|
||||
|
||||
function streamBitrate(stream: ProbeStream, fallback: number): number {
|
||||
const raw = stream.bit_rate ?? stream.tags?.BPS ?? stream.tags?.bps;
|
||||
const value = Number(raw);
|
||||
return Number.isFinite(value) && value > 0 ? value : fallback;
|
||||
}
|
||||
|
||||
export interface MasterAudio {
|
||||
streamIndex: number;
|
||||
language: string;
|
||||
name: string;
|
||||
uri: string;
|
||||
channels?: number;
|
||||
default: boolean;
|
||||
}
|
||||
|
||||
export function buildMasterPlaylist(
|
||||
probe: MediaProbe,
|
||||
videoStreamIndex: number,
|
||||
videoUri: string,
|
||||
audio: readonly MasterAudio[],
|
||||
): string {
|
||||
const video = probe.streams.find((stream) => stream.index === videoStreamIndex);
|
||||
if (video === undefined) throw new Error('Video stream is missing from probe');
|
||||
if (audio.length === 0) throw new Error('At least one audio rendition is required');
|
||||
const audioStreams = audio.map((item) => probe.streams.find((stream) => stream.index === item.streamIndex));
|
||||
const audioBandwidth = Math.max(...audioStreams.map((stream) => stream === undefined ? 384_000 : streamBitrate(stream, 384_000)));
|
||||
const containerBitrate = Number(probe.format.bit_rate);
|
||||
const conservativeVideoFallback = Number.isFinite(containerBitrate) && containerBitrate > audioBandwidth
|
||||
? containerBitrate - audioBandwidth
|
||||
: 8_000_000;
|
||||
const videoBandwidth = streamBitrate(video, conservativeVideoFallback);
|
||||
const bandwidth = Math.ceil((videoBandwidth + audioBandwidth) * 1.15);
|
||||
const average = videoBandwidth + audioBandwidth;
|
||||
const codecs = [video.mime_codec_string ?? 'avc1.640028', 'mp4a.40.2'].join(',');
|
||||
const resolution = video.width !== undefined && video.height !== undefined ? `,RESOLUTION=${video.width}x${video.height}` : '';
|
||||
const lines = ['#EXTM3U', '#EXT-X-VERSION:7', '#EXT-X-INDEPENDENT-SEGMENTS'];
|
||||
for (const item of audio) {
|
||||
assertSafeUri(item.uri);
|
||||
lines.push(
|
||||
`#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID="audio",NAME="${escapeAttribute(item.name)}",LANGUAGE="${escapeAttribute(item.language)}",AUTOSELECT=YES,DEFAULT=${item.default ? 'YES' : 'NO'}${item.channels === undefined ? '' : `,CHANNELS="${item.channels}"`},URI="${item.uri}"`,
|
||||
);
|
||||
}
|
||||
assertSafeUri(videoUri);
|
||||
lines.push(
|
||||
`#EXT-X-STREAM-INF:BANDWIDTH=${bandwidth},AVERAGE-BANDWIDTH=${average}${resolution},CODECS="${escapeAttribute(codecs)}",AUDIO="audio"`,
|
||||
videoUri,
|
||||
'',
|
||||
);
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
export interface WarningAssessment {
|
||||
knownAacRepairs: number;
|
||||
ignoredProbeWarnings: number;
|
||||
unknown: string[];
|
||||
}
|
||||
|
||||
/** Only the observed one-sample AAC rounding repair is accepted. */
|
||||
export function assessFfmpegWarnings(stderr: string): WarningAssessment {
|
||||
const lines = stderr.split(/\r?\n/u).map((line) => line.trim()).filter(Boolean);
|
||||
let knownAacRepairs = 0;
|
||||
let ignoredProbeWarnings = 0;
|
||||
const unknown: string[] = [];
|
||||
for (const line of lines) {
|
||||
const packet = line.match(/Packet duration:\s*(-?\d+)\s*\/\s*dts:/u);
|
||||
if (packet !== null) {
|
||||
if (Number(packet[1]) === -32) knownAacRepairs += 1;
|
||||
else unknown.push(line);
|
||||
continue;
|
||||
}
|
||||
if (line.includes('Could not find codec parameters for stream') && line.includes('Attachment: none')) {
|
||||
ignoredProbeWarnings += 1;
|
||||
continue;
|
||||
}
|
||||
if (line.startsWith('Consider increasing the value for the \'analyzeduration\'')) {
|
||||
ignoredProbeWarnings += 1;
|
||||
continue;
|
||||
}
|
||||
if (line === 'Bandwidth info not available, set audio and video bitrates') {
|
||||
ignoredProbeWarnings += 1;
|
||||
continue;
|
||||
}
|
||||
unknown.push(line);
|
||||
}
|
||||
return { knownAacRepairs, ignoredProbeWarnings, unknown };
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
export * from './cache.js';
|
||||
export * from './classify.js';
|
||||
export * from './encode.js';
|
||||
export * from './ffprobe.js';
|
||||
export * from './fingerprint.js';
|
||||
export * from './fonts.js';
|
||||
export * from './hls.js';
|
||||
export * from './language.js';
|
||||
export * from './packager.js';
|
||||
export * from './paths.js';
|
||||
export * from './process.js';
|
||||
export * from './single-flight.js';
|
||||
export * from './subtitles.js';
|
||||
export type * from './types.js';
|
||||
@@ -0,0 +1,63 @@
|
||||
import type { ProbeStream } from './types.js';
|
||||
|
||||
const LANGUAGE_ALIASES: Record<string, string> = {
|
||||
ara: 'ar', ar: 'ar',
|
||||
chi: 'zh', zho: 'zh', zh: 'zh',
|
||||
dut: 'nl', nld: 'nl', nl: 'nl',
|
||||
eng: 'en', en: 'en',
|
||||
fas: 'fa', per: 'fa', fa: 'fa', pes: 'fa',
|
||||
fre: 'fr', fra: 'fr', fr: 'fr',
|
||||
ger: 'de', deu: 'de', de: 'de',
|
||||
heb: 'he', he: 'he',
|
||||
hin: 'hi', hi: 'hi',
|
||||
ita: 'it', it: 'it',
|
||||
jpn: 'ja', ja: 'ja',
|
||||
kor: 'ko', ko: 'ko',
|
||||
por: 'pt', pt: 'pt',
|
||||
rus: 'ru', ru: 'ru',
|
||||
spa: 'es', es: 'es',
|
||||
tur: 'tr', tr: 'tr',
|
||||
und: 'und', unknown: 'und', qad: 'und',
|
||||
};
|
||||
|
||||
export function detectTextLanguage(text: string): string | undefined {
|
||||
const clean = text.replace(/\{[^}]*\}/g, '').replace(/\\[Nnh]/g, ' ');
|
||||
const arabicScript = (clean.match(/[\u0600-\u06ff]/gu) ?? []).length;
|
||||
const persianSpecific = (clean.match(/[پچژگکی]/gu) ?? []).length;
|
||||
const kana = (clean.match(/[\u3040-\u30ff]/gu) ?? []).length;
|
||||
const han = (clean.match(/[\u3400-\u9fff]/gu) ?? []).length;
|
||||
const cjk = kana + han;
|
||||
const hangul = (clean.match(/[\uac00-\ud7af]/gu) ?? []).length;
|
||||
const cyrillic = (clean.match(/[\u0400-\u04ff]/gu) ?? []).length;
|
||||
const latin = (clean.match(/[A-Za-z]/g) ?? []).length;
|
||||
const largest = Math.max(arabicScript, cjk, hangul, cyrillic, latin);
|
||||
if (largest < 12) return undefined;
|
||||
if (largest === arabicScript) return persianSpecific >= 2 ? 'fa' : 'ar';
|
||||
if (largest === cjk) return kana >= 2 ? 'ja' : 'zh';
|
||||
if (largest === hangul) return 'ko';
|
||||
if (largest === cyrillic) return 'ru';
|
||||
return 'en';
|
||||
}
|
||||
|
||||
export function normalizeLanguage(raw: string | undefined, content?: string): string {
|
||||
const value = raw?.trim().toLowerCase().replaceAll('_', '-');
|
||||
const primary = value?.split('-')[0];
|
||||
const normalized = primary === undefined ? undefined : LANGUAGE_ALIASES[primary];
|
||||
const detected = content === undefined ? undefined : detectTextLanguage(content);
|
||||
if (normalized === undefined || normalized === 'und') return detected ?? 'und';
|
||||
// Script evidence wins over unreliable private-use and plainly wrong archive tags.
|
||||
if (detected !== undefined && detected !== normalized) return detected;
|
||||
return normalized;
|
||||
}
|
||||
|
||||
export function normalizeStreamLanguage(stream: ProbeStream, content?: string): string {
|
||||
return normalizeLanguage(stream.tags?.language, content);
|
||||
}
|
||||
|
||||
export function languageDisplayName(language: string, locale = 'en'): string {
|
||||
try {
|
||||
return new Intl.DisplayNames([locale], { type: 'language' }).of(language) ?? language;
|
||||
} catch {
|
||||
return language;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,355 @@
|
||||
import { mkdir, readFile, rename, stat, writeFile } from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import { writeCacheMetadata } from './cache.js';
|
||||
import { probeMedia } from './ffprobe.js';
|
||||
import { fingerprintSource } from './fingerprint.js';
|
||||
import {
|
||||
assessFfmpegWarnings,
|
||||
buildMasterPlaylist,
|
||||
finalizeEventPlaylist,
|
||||
validateMediaPlaylist,
|
||||
type MasterAudio,
|
||||
} from './hls.js';
|
||||
import { languageDisplayName, normalizeStreamLanguage } from './language.js';
|
||||
import { assertWritableDestination, ensureWritableDirectory, resolveInside } from './paths.js';
|
||||
import { runProcess } from './process.js';
|
||||
import { SingleFlight } from './single-flight.js';
|
||||
import type { Classification, MediaProbe, PackageResult, SourceFingerprint } from './types.js';
|
||||
|
||||
const GENERATION_PATTERN = /^[a-z0-9][a-z0-9._-]{7,127}$/u;
|
||||
|
||||
export interface PackagingProgress {
|
||||
state: 'PREPARING' | 'READY' | 'FAILED';
|
||||
generation: string;
|
||||
outputDirectory: string;
|
||||
playable?: boolean;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export interface PackageHlsOptions {
|
||||
archiveRoot: string;
|
||||
cacheRoot: string;
|
||||
sourcePath: string;
|
||||
fingerprint: SourceFingerprint;
|
||||
probe: MediaProbe;
|
||||
classification: Classification;
|
||||
generation?: string;
|
||||
ffmpegPath?: string;
|
||||
ffprobePath?: string;
|
||||
segmentSeconds?: number;
|
||||
maxTargetDuration?: number;
|
||||
profileVersion?: string;
|
||||
progressIntervalMs?: number;
|
||||
activeBuildMaxAgeMs?: number;
|
||||
onProgress?: (progress: PackagingProgress) => void | Promise<void>;
|
||||
}
|
||||
|
||||
function buildGeneration(fingerprint: SourceFingerprint, profileVersion: string): string {
|
||||
const profile = profileVersion.toLowerCase().replace(/[^a-z0-9._-]/gu, '-').slice(0, 32);
|
||||
return `${profile}-${fingerprint.digest.slice(0, 32)}`;
|
||||
}
|
||||
|
||||
function audioRenditions(probe: MediaProbe, indexes: readonly number[]): MasterAudio[] {
|
||||
return indexes.map((streamIndex, index) => {
|
||||
const stream = probe.streams.find((candidate) => candidate.index === streamIndex);
|
||||
if (stream === undefined) throw new Error(`Audio stream ${streamIndex} is missing`);
|
||||
const language = normalizeStreamLanguage(stream);
|
||||
const safeLanguage = language.replace(/[^a-z0-9-]/giu, '').toLowerCase() || 'und';
|
||||
return {
|
||||
streamIndex,
|
||||
language,
|
||||
name: languageDisplayName(language),
|
||||
uri: `audio-${streamIndex}-${safeLanguage}/index.m3u8`,
|
||||
...(stream.channels === undefined ? {} : { channels: stream.channels }),
|
||||
default: index === 0,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function ffmpegArguments(
|
||||
source: string,
|
||||
output: string,
|
||||
videoIndex: number,
|
||||
audio: readonly MasterAudio[],
|
||||
classification: Classification,
|
||||
segmentSeconds: number,
|
||||
): string[] {
|
||||
const arguments_: string[] = [
|
||||
'-hide_banner', '-loglevel', 'warning', '-nostdin', '-y',
|
||||
'-i', source,
|
||||
'-map', `0:${videoIndex}`,
|
||||
];
|
||||
for (const item of audio) arguments_.push('-map', `0:${item.streamIndex}`);
|
||||
arguments_.push('-map_metadata', '-1', '-map_chapters', '-1', '-sn', '-dn', '-c:v', 'copy');
|
||||
if (classification.class === 'AUDIO_TRANSCODE') {
|
||||
audio.forEach((item, index) => {
|
||||
arguments_.push(`-c:a:${index}`, 'aac', `-b:a:${index}`, (item.channels ?? 2) > 2 ? '384k' : '192k');
|
||||
});
|
||||
} else {
|
||||
arguments_.push('-c:a', 'copy');
|
||||
}
|
||||
const variants = [
|
||||
'v:0,agroup:audio,name:video',
|
||||
...audio.map((item, index) => {
|
||||
const folder = path.dirname(item.uri);
|
||||
return `a:${index},agroup:audio,language:${item.language},default:${item.default ? 'yes' : 'no'},name:${folder}`;
|
||||
}),
|
||||
].join(' ');
|
||||
arguments_.push(
|
||||
'-f', 'hls',
|
||||
'-hls_time', String(segmentSeconds),
|
||||
'-hls_segment_type', 'fmp4',
|
||||
'-hls_playlist_type', 'event',
|
||||
'-hls_flags', 'independent_segments+temp_file',
|
||||
'-master_pl_name', 'master.live.m3u8',
|
||||
'-var_stream_map', variants,
|
||||
'-hls_fmp4_init_filename', 'init-%v.mp4',
|
||||
'-hls_segment_filename', path.join(output, '%v', 'segment-%06d.m4s'),
|
||||
path.join(output, '%v', 'index.m3u8'),
|
||||
);
|
||||
return arguments_;
|
||||
}
|
||||
|
||||
export class GenerationBuildActiveError extends Error {
|
||||
constructor(readonly generation: string) {
|
||||
super(`Generation is already being built: ${generation}`);
|
||||
this.name = 'GenerationBuildActiveError';
|
||||
}
|
||||
}
|
||||
|
||||
async function existingPackage(
|
||||
generation: string,
|
||||
outputDirectory: string,
|
||||
masterPlaylist: string,
|
||||
videoPlaylistPath: string,
|
||||
audioPlaylistPaths: readonly string[],
|
||||
ffprobePath: string,
|
||||
maxTargetDuration: number,
|
||||
): Promise<PackageResult | undefined> {
|
||||
try {
|
||||
const [videoPlaylist, ...audioPlaylists] = await Promise.all([
|
||||
validateMediaPlaylist(videoPlaylistPath, { requireEnded: true, maxTargetDuration }),
|
||||
...audioPlaylistPaths.map((playlist) => validateMediaPlaylist(playlist, { requireEnded: true, maxTargetDuration })),
|
||||
]);
|
||||
if (videoPlaylist === undefined) return undefined;
|
||||
const master = await readFile(masterPlaylist, 'utf8');
|
||||
if (!master.startsWith('#EXTM3U') || !master.includes('video/index.m3u8')) return undefined;
|
||||
await validateCodecs(videoPlaylistPath, audioPlaylistPaths, ffprobePath);
|
||||
return { generation, outputDirectory, masterPlaylist, videoPlaylist, audioPlaylists, knownAacRepairs: 0 };
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
async function validateCodecs(videoPlaylist: string, audioPlaylists: readonly string[], ffprobePath: string): Promise<void> {
|
||||
const video = await probeMedia(videoPlaylist, { ffprobePath, timeoutMs: 120_000 });
|
||||
if (!video.streams.some((stream) => stream.codec_type === 'video' && stream.codec_name === 'h264')) {
|
||||
throw new Error('Packaged video does not probe as H.264');
|
||||
}
|
||||
for (const playlist of audioPlaylists) {
|
||||
const audio = await probeMedia(playlist, { ffprobePath, timeoutMs: 120_000 });
|
||||
if (!audio.streams.some((stream) => stream.codec_type === 'audio' && stream.codec_name === 'aac')) {
|
||||
throw new Error(`Packaged audio does not probe as AAC: ${playlist}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function writeMaster(destination: string, content: string): Promise<void> {
|
||||
const temporary = `${destination}.tmp`;
|
||||
await writeFile(temporary, content, { encoding: 'utf8', mode: 0o640 });
|
||||
await rename(temporary, destination);
|
||||
}
|
||||
|
||||
function delay(milliseconds: number): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, milliseconds));
|
||||
}
|
||||
|
||||
export async function packageProgressiveHls(options: PackageHlsOptions): Promise<PackageResult> {
|
||||
if (!['COPY', 'AUDIO_TRANSCODE'].includes(options.classification.class)) {
|
||||
throw new Error(`Source cannot be JIT packaged: ${options.classification.class}`);
|
||||
}
|
||||
const source = await resolveInside(options.archiveRoot, options.sourcePath);
|
||||
const generation = options.generation ?? buildGeneration(options.fingerprint, options.profileVersion ?? 'cmaf-v1');
|
||||
if (!GENERATION_PATTERN.test(generation)) throw new Error('Invalid generation identifier');
|
||||
const generationsRoot = path.join(options.cacheRoot, 'generations');
|
||||
await ensureWritableDirectory(options.cacheRoot, generationsRoot);
|
||||
const outputDirectory = await assertWritableDestination(options.cacheRoot, path.join(generationsRoot, generation));
|
||||
const videoIndex = options.classification.videoStreamIndex;
|
||||
if (videoIndex === undefined) throw new Error('Classification selected no video stream');
|
||||
const audio = audioRenditions(options.probe, options.classification.audioStreamIndexes);
|
||||
const videoPlaylistPath = path.join(outputDirectory, 'video', 'index.m3u8');
|
||||
const audioPlaylistPaths = audio.map((item) => path.join(outputDirectory, item.uri));
|
||||
const masterPlaylist = path.join(outputDirectory, 'master.m3u8');
|
||||
const master = buildMasterPlaylist(options.probe, videoIndex, 'video/index.m3u8', audio);
|
||||
let outputExists = false;
|
||||
try {
|
||||
outputExists = (await stat(outputDirectory)).isDirectory();
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
|
||||
}
|
||||
if (outputExists) {
|
||||
const ready = await existingPackage(
|
||||
generation,
|
||||
outputDirectory,
|
||||
masterPlaylist,
|
||||
videoPlaylistPath,
|
||||
audioPlaylistPaths,
|
||||
options.ffprobePath ?? 'ffprobe',
|
||||
options.maxTargetDuration ?? 18,
|
||||
);
|
||||
if (ready !== undefined) {
|
||||
await options.onProgress?.({ state: 'READY', generation, outputDirectory, playable: true });
|
||||
return ready;
|
||||
}
|
||||
let building = false;
|
||||
let lastAccessedAt = 0;
|
||||
try {
|
||||
const metadata = JSON.parse(await readFile(path.join(outputDirectory, '.cache-entry.json'), 'utf8')) as {
|
||||
building?: boolean; lastAccessedAt?: string;
|
||||
};
|
||||
building = metadata.building === true;
|
||||
lastAccessedAt = Date.parse(metadata.lastAccessedAt ?? '');
|
||||
} catch {
|
||||
// An unrecognized partial directory is treated as a failed build and archived.
|
||||
}
|
||||
if (building && Number.isFinite(lastAccessedAt)
|
||||
&& Date.now() - lastAccessedAt < (options.activeBuildMaxAgeMs ?? 26 * 60 * 60 * 1000)) {
|
||||
throw new GenerationBuildActiveError(generation);
|
||||
}
|
||||
const failedName = `failed-${Date.now()}-${generation}`;
|
||||
const failedDirectory = path.join(generationsRoot, failedName);
|
||||
await rename(outputDirectory, failedDirectory);
|
||||
try {
|
||||
await writeCacheMetadata(generationsRoot, failedDirectory, {
|
||||
key: failedName,
|
||||
lastAccessedAt: new Date().toISOString(),
|
||||
active: false,
|
||||
building: false,
|
||||
pinned: false,
|
||||
});
|
||||
} catch {
|
||||
// The archived directory remains diagnostic-only even without cache metadata.
|
||||
}
|
||||
}
|
||||
try {
|
||||
await mkdir(outputDirectory, { recursive: false, mode: 0o750 });
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code === 'EEXIST') throw new GenerationBuildActiveError(generation);
|
||||
throw error;
|
||||
}
|
||||
// This stable URL exists before playable=true; it references atomically published EVENT playlists.
|
||||
await writeMaster(masterPlaylist, master);
|
||||
await writeCacheMetadata(generationsRoot, outputDirectory, {
|
||||
key: generation,
|
||||
lastAccessedAt: new Date().toISOString(),
|
||||
active: false,
|
||||
building: true,
|
||||
pinned: false,
|
||||
bytes: 0,
|
||||
});
|
||||
await options.onProgress?.({ state: 'PREPARING', generation, outputDirectory, playable: false });
|
||||
|
||||
let settled = false;
|
||||
let processResult: Awaited<ReturnType<typeof runProcess>> | undefined;
|
||||
let processError: unknown;
|
||||
const processPromise = runProcess(options.ffmpegPath ?? 'ffmpeg', ffmpegArguments(
|
||||
source,
|
||||
outputDirectory,
|
||||
videoIndex,
|
||||
audio,
|
||||
options.classification,
|
||||
options.segmentSeconds ?? 6,
|
||||
), { timeoutMs: 24 * 60 * 60 * 1000, maxOutputBytes: 64 * 1024 * 1024 }).then(
|
||||
(result) => { processResult = result; },
|
||||
(error: unknown) => { processError = error; },
|
||||
).finally(() => { settled = true; });
|
||||
|
||||
let playableReported = false;
|
||||
try {
|
||||
while (!settled && !playableReported) {
|
||||
await delay(options.progressIntervalMs ?? 250);
|
||||
try {
|
||||
await Promise.all([
|
||||
validateMediaPlaylist(videoPlaylistPath, { minSegments: 2, maxTargetDuration: options.maxTargetDuration ?? 18 }),
|
||||
...audioPlaylistPaths.map((playlist) => validateMediaPlaylist(playlist, { minSegments: 2, maxTargetDuration: options.maxTargetDuration ?? 18 })),
|
||||
]);
|
||||
playableReported = true;
|
||||
await options.onProgress?.({ state: 'PREPARING', generation, outputDirectory, playable: true });
|
||||
} catch {
|
||||
// The producer publishes manifests and segments atomically; absence here means not ready yet.
|
||||
}
|
||||
}
|
||||
await processPromise;
|
||||
if (processError !== undefined) throw processError;
|
||||
if (processResult === undefined) throw new Error('FFmpeg completed without a result');
|
||||
const afterFingerprint = await fingerprintSource(options.archiveRoot, source, options.fingerprint.edgeBytes);
|
||||
if (afterFingerprint.digest !== options.fingerprint.digest) throw new Error('Source changed during packaging');
|
||||
const warnings = assessFfmpegWarnings(processResult.stderr);
|
||||
if (warnings.unknown.length > 0) {
|
||||
throw new Error(`Unrecognized FFmpeg warning(s): ${warnings.unknown.slice(0, 5).join(' | ')}`);
|
||||
}
|
||||
const initial = await Promise.all([
|
||||
validateMediaPlaylist(videoPlaylistPath, { requireEnded: true, maxTargetDuration: options.maxTargetDuration ?? 18 }),
|
||||
...audioPlaylistPaths.map((playlist) => validateMediaPlaylist(playlist, { requireEnded: true, maxTargetDuration: options.maxTargetDuration ?? 18 })),
|
||||
]);
|
||||
const [videoInitial, ...audioInitial] = initial;
|
||||
if (videoInitial === undefined) throw new Error('Video playlist validation did not run');
|
||||
for (const item of audioInitial) {
|
||||
if (Math.abs(item.totalDuration - videoInitial.totalDuration) > 0.25) {
|
||||
throw new Error(`A/V duration differs by more than 250 ms (${videoInitial.totalDuration} vs ${item.totalDuration})`);
|
||||
}
|
||||
}
|
||||
await validateCodecs(videoPlaylistPath, audioPlaylistPaths, options.ffprobePath ?? 'ffprobe');
|
||||
await Promise.all([videoPlaylistPath, ...audioPlaylistPaths].map(finalizeEventPlaylist));
|
||||
const [videoPlaylist, ...audioPlaylists] = await Promise.all([
|
||||
validateMediaPlaylist(videoPlaylistPath, { requireEnded: true, maxTargetDuration: options.maxTargetDuration ?? 18 }),
|
||||
...audioPlaylistPaths.map((playlist) => validateMediaPlaylist(playlist, { requireEnded: true, maxTargetDuration: options.maxTargetDuration ?? 18 })),
|
||||
]);
|
||||
if (videoPlaylist === undefined) throw new Error('Final video playlist is missing');
|
||||
await writeCacheMetadata(generationsRoot, outputDirectory, {
|
||||
key: generation,
|
||||
lastAccessedAt: new Date().toISOString(),
|
||||
active: false,
|
||||
building: false,
|
||||
pinned: false,
|
||||
});
|
||||
await options.onProgress?.({ state: 'READY', generation, outputDirectory, playable: true });
|
||||
return { generation, outputDirectory, masterPlaylist, videoPlaylist, audioPlaylists, knownAacRepairs: warnings.knownAacRepairs };
|
||||
} catch (error) {
|
||||
try {
|
||||
const details = await stat(outputDirectory);
|
||||
if (details.isDirectory()) {
|
||||
await writeCacheMetadata(generationsRoot, outputDirectory, {
|
||||
key: generation,
|
||||
lastAccessedAt: new Date().toISOString(),
|
||||
active: false,
|
||||
building: false,
|
||||
pinned: false,
|
||||
});
|
||||
}
|
||||
} catch {
|
||||
// Preserve the original packaging error.
|
||||
}
|
||||
await options.onProgress?.({
|
||||
state: 'FAILED',
|
||||
generation,
|
||||
outputDirectory,
|
||||
playable: false,
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export class ProgressiveHlsPackager {
|
||||
readonly #singleFlight = new SingleFlight();
|
||||
|
||||
package(options: PackageHlsOptions): Promise<PackageResult> {
|
||||
const generation = options.generation ?? buildGeneration(options.fingerprint, options.profileVersion ?? 'cmaf-v1');
|
||||
return this.#singleFlight.run(generation, async () => await packageProgressiveHls({ ...options, generation }));
|
||||
}
|
||||
}
|
||||
|
||||
export async function readGeneratedMaster(outputDirectory: string): Promise<string> {
|
||||
return await readFile(path.join(outputDirectory, 'master.m3u8'), 'utf8');
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
import { lstat, mkdir, opendir, realpath, stat } from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
|
||||
export class UnsafePathError extends Error {
|
||||
constructor(message: string) {
|
||||
super(message);
|
||||
this.name = 'UnsafePathError';
|
||||
}
|
||||
}
|
||||
|
||||
function withSeparator(value: string): string {
|
||||
return value.endsWith(path.sep) ? value : `${value}${path.sep}`;
|
||||
}
|
||||
|
||||
export function isPathInside(root: string, candidate: string): boolean {
|
||||
const normalizedRoot = path.resolve(root);
|
||||
const normalizedCandidate = path.resolve(candidate);
|
||||
return normalizedCandidate === normalizedRoot || normalizedCandidate.startsWith(withSeparator(normalizedRoot));
|
||||
}
|
||||
|
||||
export async function resolveInside(root: string, candidate: string): Promise<string> {
|
||||
const realRoot = await realpath(root);
|
||||
const realCandidate = await realpath(candidate);
|
||||
if (!isPathInside(realRoot, realCandidate)) {
|
||||
throw new UnsafePathError(`Path escapes configured root: ${candidate}`);
|
||||
}
|
||||
return realCandidate;
|
||||
}
|
||||
|
||||
export async function assertWritableDestination(root: string, candidate: string): Promise<string> {
|
||||
const resolvedRoot = path.resolve(root);
|
||||
const resolvedCandidate = path.resolve(candidate);
|
||||
if (resolvedCandidate === resolvedRoot || !isPathInside(resolvedRoot, resolvedCandidate)) {
|
||||
throw new UnsafePathError(`Output must be a child of its configured root: ${candidate}`);
|
||||
}
|
||||
await assertWritableRoot(resolvedRoot);
|
||||
let canonicalRoot: string;
|
||||
try {
|
||||
canonicalRoot = await realpath(resolvedRoot);
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return resolvedCandidate;
|
||||
throw error;
|
||||
}
|
||||
let current = canonicalRoot;
|
||||
for (const component of path.relative(resolvedRoot, resolvedCandidate).split(path.sep)) {
|
||||
current = path.join(current, component);
|
||||
try {
|
||||
const details = await lstat(current);
|
||||
if (details.isSymbolicLink()) throw new UnsafePathError(`Symlink found in writable path: ${current}`);
|
||||
if (!details.isDirectory()) throw new UnsafePathError(`Writable path component is not a directory: ${current}`);
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code === 'ENOENT') break;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
return resolvedCandidate;
|
||||
}
|
||||
|
||||
/** Rejects a configured writable root that is itself a symlink. Missing roots are allowed. */
|
||||
export async function assertWritableRoot(root: string): Promise<string> {
|
||||
const resolvedRoot = path.resolve(root);
|
||||
try {
|
||||
const details = await lstat(resolvedRoot);
|
||||
if (details.isSymbolicLink()) throw new UnsafePathError(`Configured writable root is a symlink: ${resolvedRoot}`);
|
||||
if (!details.isDirectory()) throw new UnsafePathError(`Configured writable root is not a directory: ${resolvedRoot}`);
|
||||
await realpath(resolvedRoot);
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
|
||||
}
|
||||
return resolvedRoot;
|
||||
}
|
||||
|
||||
/** Creates a managed child directory one component at a time without following planted symlinks. */
|
||||
export async function ensureWritableDirectory(
|
||||
root: string,
|
||||
candidate: string,
|
||||
mode = 0o750,
|
||||
): Promise<string> {
|
||||
const resolvedRoot = path.resolve(root);
|
||||
const resolvedCandidate = path.resolve(candidate);
|
||||
if (resolvedCandidate === resolvedRoot || !isPathInside(resolvedRoot, resolvedCandidate)) {
|
||||
throw new UnsafePathError(`Output must be a child of its configured root: ${candidate}`);
|
||||
}
|
||||
await assertWritableRoot(resolvedRoot);
|
||||
try {
|
||||
await lstat(resolvedRoot);
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
|
||||
await mkdir(resolvedRoot, { recursive: true, mode });
|
||||
await assertWritableRoot(resolvedRoot);
|
||||
}
|
||||
const canonicalRoot = await realpath(resolvedRoot);
|
||||
let current = canonicalRoot;
|
||||
for (const component of path.relative(resolvedRoot, resolvedCandidate).split(path.sep)) {
|
||||
current = path.join(current, component);
|
||||
try {
|
||||
const details = await lstat(current);
|
||||
if (details.isSymbolicLink()) throw new UnsafePathError(`Symlink found in writable path: ${current}`);
|
||||
if (!details.isDirectory()) throw new UnsafePathError(`Writable path component is not a directory: ${current}`);
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
|
||||
try {
|
||||
await mkdir(current, { mode });
|
||||
} catch (mkdirError) {
|
||||
if ((mkdirError as NodeJS.ErrnoException).code !== 'EEXIST') throw mkdirError;
|
||||
}
|
||||
const details = await lstat(current);
|
||||
if (details.isSymbolicLink() || !details.isDirectory()) {
|
||||
throw new UnsafePathError(`Refusing unsafe writable directory: ${current}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Re-check the complete chain after creation so callers never receive a path whose
|
||||
// ancestor was replaced with a symlink while the components were being created.
|
||||
await assertWritableDestination(resolvedRoot, resolvedCandidate);
|
||||
return resolvedCandidate;
|
||||
}
|
||||
|
||||
export interface WalkArchiveOptions {
|
||||
extensions?: readonly string[];
|
||||
maxDepth?: number;
|
||||
}
|
||||
|
||||
/** Walks regular files only and never follows archive symlinks. */
|
||||
export async function* walkArchive(
|
||||
archiveRoot: string,
|
||||
options: WalkArchiveOptions = {},
|
||||
): AsyncGenerator<string> {
|
||||
const root = await realpath(archiveRoot);
|
||||
const rootStat = await stat(root);
|
||||
if (!rootStat.isDirectory()) throw new UnsafePathError(`Archive root is not a directory: ${root}`);
|
||||
const allowed = new Set((options.extensions ?? ['.mkv']).map((extension) => extension.toLowerCase()));
|
||||
const maxDepth = options.maxDepth ?? 32;
|
||||
|
||||
async function* visit(directory: string, depth: number): AsyncGenerator<string> {
|
||||
if (depth > maxDepth) throw new UnsafePathError(`Archive tree exceeds maximum depth ${maxDepth}`);
|
||||
const handle = await opendir(directory);
|
||||
for await (const entry of handle) {
|
||||
const candidate = path.join(directory, entry.name);
|
||||
if (entry.isSymbolicLink()) continue;
|
||||
if (entry.isDirectory()) {
|
||||
yield* visit(candidate, depth + 1);
|
||||
} else if (entry.isFile() && allowed.has(path.extname(entry.name).toLowerCase())) {
|
||||
const verified = await resolveInside(root, candidate);
|
||||
yield verified;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
yield* visit(root, 0);
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
import { spawn } from 'node:child_process';
|
||||
|
||||
export interface ProcessResult {
|
||||
code: number;
|
||||
stdout: string;
|
||||
stderr: string;
|
||||
}
|
||||
|
||||
export interface RunProcessOptions {
|
||||
cwd?: string;
|
||||
timeoutMs?: number;
|
||||
maxOutputBytes?: number;
|
||||
env?: NodeJS.ProcessEnv;
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
|
||||
export class ProcessFailure extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
readonly command: string,
|
||||
readonly result?: ProcessResult,
|
||||
) {
|
||||
super(message);
|
||||
this.name = 'ProcessFailure';
|
||||
}
|
||||
}
|
||||
|
||||
const MEDIA_PROCESS_ENV_KEYS = [
|
||||
'PATH',
|
||||
'HOME',
|
||||
'TMPDIR',
|
||||
'TMP',
|
||||
'TEMP',
|
||||
'LANG',
|
||||
'LC_ALL',
|
||||
'LD_LIBRARY_PATH',
|
||||
'DYLD_LIBRARY_PATH',
|
||||
'FONTCONFIG_FILE',
|
||||
'FONTCONFIG_PATH',
|
||||
'XDG_CACHE_HOME',
|
||||
'SSL_CERT_FILE',
|
||||
'SSL_CERT_DIR',
|
||||
// Required for child-process startup on Windows development hosts.
|
||||
'SystemRoot',
|
||||
'WINDIR',
|
||||
'PATHEXT',
|
||||
'COMSPEC',
|
||||
] as const;
|
||||
|
||||
/** Prevents FFmpeg/ffprobe from inheriting database, Redis, or application secrets. */
|
||||
export function mediaProcessEnvironment(
|
||||
source: NodeJS.ProcessEnv = process.env,
|
||||
): NodeJS.ProcessEnv {
|
||||
const environment: NodeJS.ProcessEnv = {};
|
||||
for (const key of MEDIA_PROCESS_ENV_KEYS) {
|
||||
const value = source[key];
|
||||
if (value !== undefined) environment[key] = value;
|
||||
}
|
||||
return environment;
|
||||
}
|
||||
|
||||
/** Runs a binary directly. Arguments never pass through a shell. */
|
||||
export async function runProcess(
|
||||
binary: string,
|
||||
args: readonly string[],
|
||||
options: RunProcessOptions = {},
|
||||
): Promise<ProcessResult> {
|
||||
const maxOutput = options.maxOutputBytes ?? 16 * 1024 * 1024;
|
||||
return await new Promise<ProcessResult>((resolve, reject) => {
|
||||
const child = spawn(binary, [...args], {
|
||||
cwd: options.cwd,
|
||||
env: options.env ?? mediaProcessEnvironment(),
|
||||
shell: false,
|
||||
windowsHide: true,
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
signal: options.signal,
|
||||
});
|
||||
|
||||
let stdout = '';
|
||||
let stderr = '';
|
||||
let stdoutBytes = 0;
|
||||
let stderrBytes = 0;
|
||||
let overflow = false;
|
||||
const append = (current: string, currentBytes: number, chunk: Buffer): [string, number] => {
|
||||
if (currentBytes + chunk.length > maxOutput) {
|
||||
overflow = true;
|
||||
child.kill('SIGKILL');
|
||||
return [current, currentBytes];
|
||||
}
|
||||
return [`${current}${chunk.toString('utf8')}`, currentBytes + chunk.length];
|
||||
};
|
||||
|
||||
child.stdout.on('data', (chunk: Buffer) => {
|
||||
[stdout, stdoutBytes] = append(stdout, stdoutBytes, chunk);
|
||||
});
|
||||
child.stderr.on('data', (chunk: Buffer) => {
|
||||
[stderr, stderrBytes] = append(stderr, stderrBytes, chunk);
|
||||
});
|
||||
child.once('error', (error) => reject(error));
|
||||
|
||||
const timer = options.timeoutMs === undefined
|
||||
? undefined
|
||||
: setTimeout(() => child.kill('SIGKILL'), options.timeoutMs);
|
||||
timer?.unref();
|
||||
|
||||
child.once('close', (code, signal) => {
|
||||
if (timer !== undefined) clearTimeout(timer);
|
||||
const result: ProcessResult = {
|
||||
code: code ?? -1,
|
||||
stdout,
|
||||
stderr,
|
||||
};
|
||||
if (overflow) {
|
||||
reject(new ProcessFailure(`Process output exceeded ${maxOutput} bytes`, binary, result));
|
||||
} else if (code !== 0) {
|
||||
reject(new ProcessFailure(`${binary} exited with ${String(code)} (${signal ?? 'no signal'})`, binary, result));
|
||||
} else {
|
||||
resolve(result);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
export interface DistributedLease {
|
||||
release(): Promise<void>;
|
||||
}
|
||||
|
||||
export interface DistributedLock {
|
||||
acquire(key: string, ttlMs: number): Promise<DistributedLease | undefined>;
|
||||
}
|
||||
|
||||
export class SingleFlight {
|
||||
readonly #running = new Map<string, Promise<unknown>>();
|
||||
|
||||
run<T>(key: string, operation: () => Promise<T>): Promise<T> {
|
||||
const existing = this.#running.get(key);
|
||||
if (existing !== undefined) return existing as Promise<T>;
|
||||
const promise = operation().finally(() => {
|
||||
if (this.#running.get(key) === promise) this.#running.delete(key);
|
||||
});
|
||||
this.#running.set(key, promise);
|
||||
return promise;
|
||||
}
|
||||
|
||||
has(key: string): boolean {
|
||||
return this.#running.has(key);
|
||||
}
|
||||
|
||||
get size(): number {
|
||||
return this.#running.size;
|
||||
}
|
||||
}
|
||||
|
||||
export async function withDistributedSingleFlight<T>(
|
||||
lock: DistributedLock,
|
||||
key: string,
|
||||
ttlMs: number,
|
||||
operation: () => Promise<T>,
|
||||
): Promise<T | undefined> {
|
||||
const lease = await lock.acquire(key, ttlMs);
|
||||
if (lease === undefined) return undefined;
|
||||
try {
|
||||
return await operation();
|
||||
} finally {
|
||||
await lease.release();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { readFile, rename } from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import { normalizeStreamLanguage } from './language.js';
|
||||
import { ensureWritableDirectory, resolveInside } from './paths.js';
|
||||
import { runProcess } from './process.js';
|
||||
import type { ExtractedSubtitle, MediaProbe } from './types.js';
|
||||
|
||||
const TEXT_SUBTITLE_CODECS = new Set(['ass', 'ssa', 'subrip', 'srt', 'webvtt', 'mov_text']);
|
||||
|
||||
export interface SubtitleExtractionOptions {
|
||||
archiveRoot: string;
|
||||
outputRoot: string;
|
||||
generation: string;
|
||||
ffmpegPath?: string;
|
||||
timeoutMs?: number;
|
||||
}
|
||||
|
||||
export function assDialogueText(ass: string): string {
|
||||
return ass
|
||||
.split(/\r?\n/u)
|
||||
.filter((line) => /^Dialogue\s*:/iu.test(line))
|
||||
.map((line) => line.split(',').slice(9).join(','))
|
||||
.join('\n');
|
||||
}
|
||||
|
||||
export function countAssCues(ass: string): number {
|
||||
return ass.split(/\r?\n/u).filter((line) => /^Dialogue\s*:/iu.test(line)).length;
|
||||
}
|
||||
|
||||
export interface SubtitleReadOptions {
|
||||
archiveRoot: string;
|
||||
ffmpegPath?: string;
|
||||
timeoutMs?: number;
|
||||
maxDurationSeconds?: number;
|
||||
}
|
||||
|
||||
export function subtitleAssArguments(
|
||||
source: string,
|
||||
streamIndex: number,
|
||||
maxDurationSeconds?: number,
|
||||
): string[] {
|
||||
if (!Number.isInteger(streamIndex) || streamIndex < 0) throw new RangeError('streamIndex must be non-negative');
|
||||
if (maxDurationSeconds !== undefined
|
||||
&& (!Number.isFinite(maxDurationSeconds) || maxDurationSeconds <= 0 || maxDurationSeconds > 86_400)) {
|
||||
throw new RangeError('maxDurationSeconds must be greater than 0 and at most 86400');
|
||||
}
|
||||
return [
|
||||
'-hide_banner', '-loglevel', 'error', '-nostdin',
|
||||
'-i', source,
|
||||
'-map', `0:${streamIndex}`,
|
||||
...(maxDurationSeconds === undefined ? [] : ['-t', String(maxDurationSeconds)]),
|
||||
'-c:s', 'ass',
|
||||
'-f', 'ass',
|
||||
'pipe:1',
|
||||
];
|
||||
}
|
||||
|
||||
export async function readSubtitleAsAss(
|
||||
sourcePath: string,
|
||||
streamIndex: number,
|
||||
options: SubtitleReadOptions,
|
||||
): Promise<string> {
|
||||
const source = await resolveInside(options.archiveRoot, sourcePath);
|
||||
const result = await runProcess(
|
||||
options.ffmpegPath ?? 'ffmpeg',
|
||||
subtitleAssArguments(source, streamIndex, options.maxDurationSeconds),
|
||||
{ timeoutMs: options.timeoutMs ?? 120_000, maxOutputBytes: 16 * 1024 * 1024 },
|
||||
);
|
||||
return result.stdout;
|
||||
}
|
||||
|
||||
async function atomicRename(temp: string, destination: string): Promise<void> {
|
||||
await rename(temp, destination);
|
||||
}
|
||||
|
||||
export async function extractSubtitleVariants(
|
||||
sourcePath: string,
|
||||
probe: MediaProbe,
|
||||
options: SubtitleExtractionOptions,
|
||||
): Promise<ExtractedSubtitle[]> {
|
||||
const source = await resolveInside(options.archiveRoot, sourcePath);
|
||||
const directory = await ensureWritableDirectory(
|
||||
options.outputRoot,
|
||||
path.join(options.outputRoot, options.generation, 'subtitles'),
|
||||
);
|
||||
const streams = probe.streams.filter(
|
||||
(stream) => stream.codec_type === 'subtitle' && TEXT_SUBTITLE_CODECS.has(stream.codec_name ?? ''),
|
||||
);
|
||||
const extracted: ExtractedSubtitle[] = [];
|
||||
|
||||
for (const stream of streams) {
|
||||
const token = randomUUID();
|
||||
const tempAss = path.join(directory, `.${stream.index}-${token}.ass`);
|
||||
const tempVtt = path.join(directory, `.${stream.index}-${token}.vtt`);
|
||||
await runProcess(options.ffmpegPath ?? 'ffmpeg', [
|
||||
'-hide_banner', '-loglevel', 'error', '-nostdin', '-y',
|
||||
'-i', source,
|
||||
'-map', `0:${stream.index}`,
|
||||
'-c:s', 'ass',
|
||||
tempAss,
|
||||
], { timeoutMs: options.timeoutMs ?? 120_000 });
|
||||
const ass = await readFile(tempAss, 'utf8');
|
||||
const language = normalizeStreamLanguage(stream, assDialogueText(ass));
|
||||
const stem = `${String(stream.index).padStart(3, '0')}-${language}`;
|
||||
const assPath = path.join(directory, `${stem}.ass`);
|
||||
const vttPath = path.join(directory, `${stem}.vtt`);
|
||||
await runProcess(options.ffmpegPath ?? 'ffmpeg', [
|
||||
'-hide_banner', '-loglevel', 'error', '-nostdin', '-y',
|
||||
'-i', tempAss,
|
||||
'-c:s', 'webvtt',
|
||||
tempVtt,
|
||||
], { timeoutMs: options.timeoutMs ?? 120_000 });
|
||||
await atomicRename(tempAss, assPath);
|
||||
await atomicRename(tempVtt, vttPath);
|
||||
extracted.push({
|
||||
streamIndex: stream.index,
|
||||
language,
|
||||
assPath,
|
||||
vttPath,
|
||||
cueCount: countAssCues(ass),
|
||||
default: language === 'fa',
|
||||
forced: false,
|
||||
});
|
||||
}
|
||||
return extracted;
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
export type CompatibilityClass =
|
||||
| 'COPY'
|
||||
| 'AUDIO_TRANSCODE'
|
||||
| 'VIDEO_TRANSCODE'
|
||||
| 'HOLD_HDR'
|
||||
| 'INVALID';
|
||||
|
||||
export interface ProbeDisposition {
|
||||
default?: number;
|
||||
forced?: number;
|
||||
attached_pic?: number;
|
||||
[key: string]: number | undefined;
|
||||
}
|
||||
|
||||
export interface ProbeStream {
|
||||
index: number;
|
||||
codec_name?: string;
|
||||
codec_long_name?: string;
|
||||
codec_type?: 'video' | 'audio' | 'subtitle' | 'attachment' | string;
|
||||
profile?: string;
|
||||
mime_codec_string?: string;
|
||||
bit_rate?: string;
|
||||
width?: number;
|
||||
height?: number;
|
||||
pix_fmt?: string;
|
||||
level?: number;
|
||||
field_order?: string;
|
||||
avg_frame_rate?: string;
|
||||
r_frame_rate?: string;
|
||||
bits_per_raw_sample?: string;
|
||||
sample_rate?: string;
|
||||
channels?: number;
|
||||
channel_layout?: string;
|
||||
color_transfer?: string;
|
||||
color_primaries?: string;
|
||||
color_space?: string;
|
||||
duration?: string;
|
||||
extradata_size?: number;
|
||||
disposition?: ProbeDisposition;
|
||||
tags?: Record<string, string | undefined>;
|
||||
side_data_list?: Array<Record<string, unknown>>;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface ProbeFormat {
|
||||
filename?: string;
|
||||
format_name?: string;
|
||||
duration?: string;
|
||||
size?: string;
|
||||
bit_rate?: string;
|
||||
probe_score?: number;
|
||||
tags?: Record<string, string | undefined>;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface MediaProbe {
|
||||
streams: ProbeStream[];
|
||||
format: ProbeFormat;
|
||||
chapters: Array<Record<string, unknown>>;
|
||||
}
|
||||
|
||||
export interface SourceFingerprint {
|
||||
version: 1;
|
||||
algorithm: 'sha256';
|
||||
relativePath: string;
|
||||
size: string;
|
||||
mtimeNs: string;
|
||||
edgeBytes: number;
|
||||
digest: string;
|
||||
}
|
||||
|
||||
export interface NormalizedTrack {
|
||||
index: number;
|
||||
type: 'video' | 'audio' | 'subtitle' | 'attachment';
|
||||
codec: string;
|
||||
language: string;
|
||||
label?: string;
|
||||
default: boolean;
|
||||
forced: boolean;
|
||||
}
|
||||
|
||||
export interface Classification {
|
||||
class: CompatibilityClass;
|
||||
reasons: string[];
|
||||
videoStreamIndex?: number;
|
||||
audioStreamIndexes: number[];
|
||||
}
|
||||
|
||||
export interface ExtractedSubtitle {
|
||||
streamIndex: number;
|
||||
language: string;
|
||||
assPath: string;
|
||||
vttPath: string;
|
||||
cueCount: number;
|
||||
default: boolean;
|
||||
forced: boolean;
|
||||
}
|
||||
|
||||
export interface StoredFont {
|
||||
streamIndex: number;
|
||||
sha256: string;
|
||||
path: string;
|
||||
originalName: string;
|
||||
size: number;
|
||||
format: 'ttf' | 'otf';
|
||||
}
|
||||
|
||||
export interface HlsPlaylistValidation {
|
||||
path: string;
|
||||
segmentCount: number;
|
||||
targetDuration: number;
|
||||
minDuration: number;
|
||||
maxDuration: number;
|
||||
totalDuration: number;
|
||||
ended: boolean;
|
||||
}
|
||||
|
||||
export interface PackageResult {
|
||||
generation: string;
|
||||
outputDirectory: string;
|
||||
masterPlaylist: string;
|
||||
videoPlaylist: HlsPlaylistValidation;
|
||||
audioPlaylists: HlsPlaylistValidation[];
|
||||
knownAacRepairs: number;
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
import { mkdtemp, mkdir, readFile, stat, symlink, writeFile } from 'node:fs/promises';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
evictCache,
|
||||
evictCacheGeneration,
|
||||
SingleFlight,
|
||||
touchCacheGeneration,
|
||||
writeCacheMetadata,
|
||||
} from '../src/index.js';
|
||||
|
||||
describe('single flight and cache pressure', () => {
|
||||
it('shares one running promise per generation', async () => {
|
||||
const flight = new SingleFlight();
|
||||
let calls = 0;
|
||||
const operation = async (): Promise<number> => {
|
||||
calls += 1;
|
||||
await new Promise((resolve) => setTimeout(resolve, 10));
|
||||
return 42;
|
||||
};
|
||||
const [left, right] = await Promise.all([flight.run('generation', operation), flight.run('generation', operation)]);
|
||||
expect([left, right]).toEqual([42, 42]);
|
||||
expect(calls).toBe(1);
|
||||
});
|
||||
|
||||
it('evicts oldest unprotected entries down to the low watermark', async () => {
|
||||
const root = await mkdtemp(path.join(os.tmpdir(), 'easy-stream-cache-'));
|
||||
for (const [key, date, pinned] of [['old', '2020-01-01T00:00:00.000Z', false], ['new', '2021-01-01T00:00:00.000Z', false], ['pin', '2019-01-01T00:00:00.000Z', true]] as const) {
|
||||
const directory = path.join(root, key);
|
||||
await mkdir(directory);
|
||||
await writeFile(path.join(directory, 'data'), Buffer.alloc(40));
|
||||
await writeCacheMetadata(root, directory, { key, lastAccessedAt: date, active: false, building: false, pinned, bytes: 40 });
|
||||
}
|
||||
const result = await evictCache(root, { capacityBytes: 100, highWatermark: 0.85, lowWatermark: 0.75 });
|
||||
expect(result.evicted).toEqual(['old', 'new']);
|
||||
expect(result.afterBytes).toBe(40);
|
||||
});
|
||||
|
||||
it('evicts only inactive, unpinned cache generations', async () => {
|
||||
const root = await mkdtemp(path.join(os.tmpdir(), 'easy-stream-generation-'));
|
||||
const generations = path.join(root, 'generations');
|
||||
const active = path.join(generations, 'active-generation');
|
||||
const ready = path.join(generations, 'ready-generation');
|
||||
await Promise.all([mkdir(active, { recursive: true }), mkdir(ready, { recursive: true })]);
|
||||
await Promise.all([writeFile(path.join(active, 'data'), 'active'), writeFile(path.join(ready, 'data'), 'ready')]);
|
||||
await writeCacheMetadata(generations, active, { key: 'active-generation', lastAccessedAt: new Date().toISOString(), active: true, building: false, pinned: false });
|
||||
await writeCacheMetadata(generations, ready, { key: 'ready-generation', lastAccessedAt: new Date().toISOString(), active: false, building: false, pinned: false });
|
||||
await expect(evictCacheGeneration(root, 'active-generation')).rejects.toThrow('active');
|
||||
expect(await evictCacheGeneration(root, 'ready-generation')).toBe(true);
|
||||
await expect(stat(ready)).rejects.toMatchObject({ code: 'ENOENT' });
|
||||
});
|
||||
|
||||
it('touches recency and keeps the longest playback protection window', async () => {
|
||||
const root = await mkdtemp(path.join(os.tmpdir(), 'easy-stream-generation-touch-'));
|
||||
const generations = path.join(root, 'generations');
|
||||
const generation = '11111111-1111-4111-8111-111111111111';
|
||||
const directory = path.join(generations, generation);
|
||||
await mkdir(directory, { recursive: true });
|
||||
await writeFile(path.join(directory, 'data'), 'ready');
|
||||
await writeCacheMetadata(generations, directory, {
|
||||
key: generation,
|
||||
lastAccessedAt: '2026-01-01T00:00:00.000Z',
|
||||
protectedUntil: '2999-07-14T10:00:00.000Z',
|
||||
active: false,
|
||||
building: false,
|
||||
pinned: false,
|
||||
});
|
||||
await touchCacheGeneration(root, generation, {
|
||||
accessedAt: '2026-07-14T09:00:00.000Z',
|
||||
protectedUntil: '2026-07-14T09:30:00.000Z',
|
||||
});
|
||||
const metadata = JSON.parse(await readFile(path.join(directory, '.cache-entry.json'), 'utf8'));
|
||||
expect(metadata).toMatchObject({
|
||||
lastAccessedAt: '2026-07-14T09:00:00.000Z',
|
||||
protectedUntil: '2999-07-14T10:00:00.000Z',
|
||||
});
|
||||
await expect(evictCacheGeneration(root, generation)).rejects.toThrow('playback lease');
|
||||
});
|
||||
|
||||
it('protects recently touched entries while evicting older pressure', async () => {
|
||||
const root = await mkdtemp(path.join(os.tmpdir(), 'easy-stream-cache-retention-'));
|
||||
for (const [key, date] of [
|
||||
['old-entry', '2026-07-14T00:00:00.000Z'],
|
||||
['recent-entry', '2026-07-14T09:59:00.000Z'],
|
||||
] as const) {
|
||||
const directory = path.join(root, key);
|
||||
await mkdir(directory);
|
||||
await writeFile(path.join(directory, 'data'), Buffer.alloc(60));
|
||||
await writeCacheMetadata(root, directory, {
|
||||
key,
|
||||
lastAccessedAt: date,
|
||||
active: false,
|
||||
building: false,
|
||||
pinned: false,
|
||||
bytes: 60,
|
||||
});
|
||||
}
|
||||
const result = await evictCache(root, {
|
||||
capacityBytes: 100,
|
||||
highWatermark: 0.85,
|
||||
lowWatermark: 0.75,
|
||||
minimumRetentionMs: 60 * 60 * 1000,
|
||||
now: new Date('2026-07-14T10:00:00.000Z'),
|
||||
});
|
||||
expect(result.evicted).toEqual(['old-entry']);
|
||||
expect(result.afterBytes).toBe(60);
|
||||
});
|
||||
|
||||
it('rejects a planted writable-path symlink without writing outside the cache', async () => {
|
||||
const base = await mkdtemp(path.join(os.tmpdir(), 'easy-stream-cache-write-link-'));
|
||||
const root = path.join(base, 'cache');
|
||||
const outside = path.join(base, 'outside');
|
||||
await Promise.all([mkdir(root), mkdir(outside)]);
|
||||
const marker = path.join(outside, 'marker');
|
||||
await writeFile(marker, 'untouched');
|
||||
await symlink(outside, path.join(root, 'linked-entry'));
|
||||
|
||||
await expect(writeCacheMetadata(root, path.join(root, 'linked-entry'), {
|
||||
key: 'linked-entry',
|
||||
lastAccessedAt: new Date().toISOString(),
|
||||
active: false,
|
||||
building: false,
|
||||
pinned: false,
|
||||
bytes: 1,
|
||||
})).rejects.toThrow(/Symlink found in writable path/u);
|
||||
|
||||
expect(await readFile(marker, 'utf8')).toBe('untouched');
|
||||
await expect(stat(path.join(outside, '.cache-entry.json'))).rejects.toMatchObject({ code: 'ENOENT' });
|
||||
});
|
||||
|
||||
it('rejects a planted generations symlink without deleting outside the cache', async () => {
|
||||
const base = await mkdtemp(path.join(os.tmpdir(), 'easy-stream-cache-delete-link-'));
|
||||
const root = path.join(base, 'cache');
|
||||
const outside = path.join(base, 'outside');
|
||||
const generation = '33333333-3333-4333-8333-333333333333';
|
||||
const outsideGeneration = path.join(outside, generation);
|
||||
await Promise.all([mkdir(root), mkdir(outsideGeneration, { recursive: true })]);
|
||||
const marker = path.join(outsideGeneration, 'marker');
|
||||
await writeFile(marker, 'untouched');
|
||||
await writeCacheMetadata(outside, outsideGeneration, {
|
||||
key: generation,
|
||||
lastAccessedAt: '2020-01-01T00:00:00.000Z',
|
||||
active: false,
|
||||
building: false,
|
||||
pinned: false,
|
||||
});
|
||||
await symlink(outside, path.join(root, 'generations'));
|
||||
|
||||
await expect(evictCacheGeneration(root, generation)).rejects.toThrow(/writable root is a symlink/u);
|
||||
expect(await readFile(marker, 'utf8')).toBe('untouched');
|
||||
await expect(stat(outsideGeneration)).resolves.toBeDefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,44 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { classifyMedia, detectTextLanguage, normalizeLanguage } from '../src/index.js';
|
||||
import { audio, probe, video } from './fixtures.js';
|
||||
|
||||
describe('media compatibility', () => {
|
||||
it('copy-packages browser-safe H.264 and AAC-LC', () => {
|
||||
expect(classifyMedia(probe())).toMatchObject({ class: 'COPY', videoStreamIndex: 0, audioStreamIndexes: [1] });
|
||||
});
|
||||
|
||||
it('selects audio-only transcoding for DTS', () => {
|
||||
expect(classifyMedia(probe([video(), audio({ codec_name: 'dts', profile: undefined })])).class)
|
||||
.toBe('AUDIO_TRANSCODE');
|
||||
});
|
||||
|
||||
it('selects video transcoding for HEVC SDR', () => {
|
||||
expect(classifyMedia(probe([video({ codec_name: 'hevc', pix_fmt: 'yuv420p10le' }), audio()])).class)
|
||||
.toBe('VIDEO_TRANSCODE');
|
||||
});
|
||||
|
||||
it('holds HDR independently of codec', () => {
|
||||
expect(classifyMedia(probe([video({ color_transfer: 'smpte2084', color_primaries: 'bt2020' }), audio()]))).toMatchObject({
|
||||
class: 'HOLD_HDR', reasons: ['HDR_UNSUPPORTED_V1'],
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects media without an audio stream', () => {
|
||||
expect(classifyMedia(probe([video()]))).toMatchObject({ class: 'INVALID', reasons: ['NO_AUDIO'] });
|
||||
});
|
||||
});
|
||||
|
||||
describe('language normalization', () => {
|
||||
it('maps ISO-639 aliases', () => {
|
||||
expect(normalizeLanguage('per')).toBe('fa');
|
||||
expect(normalizeLanguage('jpn')).toBe('ja');
|
||||
});
|
||||
|
||||
it('uses script evidence for private or wrong tags', () => {
|
||||
const english = 'This is enough English dialogue text for reliable script detection.';
|
||||
expect(normalizeLanguage('qad', english)).toBe('en');
|
||||
expect(normalizeLanguage('eng', 'این یک زیرنویس فارسی برای تشخیص زبان است')).toBe('fa');
|
||||
expect(detectTextLanguage('این یک زیرنویس فارسی برای تشخیص زبان است')).toBe('fa');
|
||||
expect(detectTextLanguage('هذا نص عربي واضح لاختبار اكتشاف لغة الترجمة العربية')).toBe('ar');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { buildCompatibilityEncodeArguments, classifyMedia } from '../src/index.js';
|
||||
import { audio, probe, video } from './fixtures.js';
|
||||
|
||||
describe('offline compatibility encode profile', () => {
|
||||
it('builds same-resolution H.264 CRF18 CMAF with bounded closed GOP and channel-aware AAC', () => {
|
||||
const media = probe([
|
||||
video({ codec_name: 'hevc', pix_fmt: 'yuv420p10le', avg_frame_rate: '24000/1001' }),
|
||||
audio({ index: 1, codec_name: 'dts', channels: 2 }),
|
||||
audio({ index: 2, codec_name: 'truehd', channels: 6, tags: { language: 'eng' } }),
|
||||
]);
|
||||
const classification = classifyMedia(media);
|
||||
const args = buildCompatibilityEncodeArguments('/archive/source.mkv', '/derived/build', media, classification);
|
||||
expect(args).toContain('libx264');
|
||||
expect(args.slice(args.indexOf('-crf'), args.indexOf('-crf') + 2)).toEqual(['-crf', '18']);
|
||||
expect(args.slice(args.indexOf('-pix_fmt'), args.indexOf('-pix_fmt') + 2)).toEqual(['-pix_fmt', 'yuv420p']);
|
||||
expect(args.slice(args.indexOf('-g'), args.indexOf('-g') + 2)).toEqual(['-g', '144']);
|
||||
expect(args).toContain('expr:gte(t,n_forced*6)');
|
||||
expect(args.slice(args.indexOf('-b:a:0'), args.indexOf('-b:a:0') + 2)).toEqual(['-b:a:0', '192k']);
|
||||
expect(args.slice(args.indexOf('-b:a:1'), args.indexOf('-b:a:1') + 2)).toEqual(['-b:a:1', '384k']);
|
||||
expect(args).toContain('vod');
|
||||
expect(args).toContain('fmp4');
|
||||
});
|
||||
|
||||
it('hard-refuses HDR input', () => {
|
||||
const media = probe([video({ codec_name: 'hevc', color_transfer: 'smpte2084' }), audio()]);
|
||||
expect(() => buildCompatibilityEncodeArguments('/a', '/b', media, classifyMedia(media))).toThrow('HDR_UNSUPPORTED_V1');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,44 @@
|
||||
import type { MediaProbe, ProbeStream } from '../src/index.js';
|
||||
|
||||
export function video(overrides: Partial<ProbeStream> = {}): ProbeStream {
|
||||
return {
|
||||
index: 0,
|
||||
codec_type: 'video',
|
||||
codec_name: 'h264',
|
||||
profile: 'High',
|
||||
mime_codec_string: 'avc1.64001f',
|
||||
width: 1280,
|
||||
height: 720,
|
||||
pix_fmt: 'yuv420p',
|
||||
bits_per_raw_sample: '8',
|
||||
field_order: 'progressive',
|
||||
tags: { BPS: '652016' },
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
export function audio(overrides: Partial<ProbeStream> = {}): ProbeStream {
|
||||
return {
|
||||
index: 1,
|
||||
codec_type: 'audio',
|
||||
codec_name: 'aac',
|
||||
profile: 'LC',
|
||||
channels: 2,
|
||||
sample_rate: '48000',
|
||||
tags: { language: 'jpn', BPS: '200416' },
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
export function probe(streams: ProbeStream[] = [video(), audio()]): MediaProbe {
|
||||
return {
|
||||
streams,
|
||||
format: {
|
||||
format_name: 'matroska,webm',
|
||||
duration: '1420.095',
|
||||
bit_rate: '899640',
|
||||
probe_score: 100,
|
||||
},
|
||||
chapters: [],
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
import { link, mkdtemp, mkdir, readFile, readdir, realpath, stat, writeFile } from 'node:fs/promises';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
extractAndStoreFonts,
|
||||
fontDumpArguments,
|
||||
pruneOrphanedFonts,
|
||||
publishGenerationFonts,
|
||||
validateSfntFont,
|
||||
} from '../src/index.js';
|
||||
import { probe } from './fixtures.js';
|
||||
|
||||
function minimalSfnt(): Buffer {
|
||||
const data = Buffer.alloc(28);
|
||||
data.writeUInt32BE(0x00010000, 0);
|
||||
data.writeUInt16BE(1, 4);
|
||||
data.write('head', 12, 'ascii');
|
||||
data.writeUInt32BE(28, 20);
|
||||
data.writeUInt32BE(0, 24);
|
||||
return data;
|
||||
}
|
||||
|
||||
describe('font attachment safety', () => {
|
||||
it('validates the SFNT directory rather than trusting an extension', () => {
|
||||
expect(validateSfntFont(minimalSfnt())).toBe('ttf');
|
||||
expect(() => validateSfntFont(Buffer.from('not a font'))).toThrow();
|
||||
});
|
||||
|
||||
it('builds a header-only FFmpeg dump command', () => {
|
||||
const args = fontDumpArguments(4, '/cache/font', '/archive/movie.mkv');
|
||||
expect(args).toContain('-dump_attachment:4');
|
||||
expect(args.slice(args.indexOf('-i') + 2)).toContain('-t');
|
||||
expect(args[args.indexOf('-t') + 1]).toBe('0');
|
||||
});
|
||||
|
||||
it('cleans staging data when extracted font validation fails', async () => {
|
||||
const base = await mkdtemp(path.join(os.tmpdir(), 'easy-stream-font-'));
|
||||
const archive = path.join(base, 'archive');
|
||||
const fontRoot = path.join(base, 'fonts');
|
||||
await mkdir(archive);
|
||||
const source = path.join(archive, 'movie.mkv');
|
||||
await writeFile(source, 'archive');
|
||||
const mediaProbe = probe([{ index: 4, codec_type: 'attachment', codec_name: 'ttf', extradata_size: 10, tags: { filename: 'bad.ttf' } }]);
|
||||
await expect(extractAndStoreFonts(source, mediaProbe, {
|
||||
archiveRoot: archive,
|
||||
fontRoot,
|
||||
async runner(_binary, args) {
|
||||
const destination = args[args.indexOf('-dump_attachment:4') + 1];
|
||||
if (destination === undefined) throw new Error('Missing mock destination');
|
||||
await writeFile(destination, 'invalid');
|
||||
return { code: 0, stdout: '', stderr: '' };
|
||||
},
|
||||
})).rejects.toThrow('Font size');
|
||||
expect(await readdir(path.join(fontRoot, '.staging'))).toEqual([]);
|
||||
});
|
||||
|
||||
it('publishes deduplicated fonts under the signed generation path', async () => {
|
||||
const root = await mkdtemp(path.join(os.tmpdir(), 'easy-stream-font-publish-'));
|
||||
const sourceDirectory = path.join(root, 'assets', 'fonts', 'sha256');
|
||||
const generation = path.join(root, 'generations', '11111111-1111-4111-8111-111111111111');
|
||||
await Promise.all([mkdir(sourceDirectory, { recursive: true }), mkdir(generation, { recursive: true })]);
|
||||
const data = minimalSfnt();
|
||||
const sha256 = 'a'.repeat(64);
|
||||
const source = path.join(sourceDirectory, `${sha256}.ttf`);
|
||||
await writeFile(source, data);
|
||||
const font = { streamIndex: 4, sha256, path: source, originalName: 'source.ttf', size: data.length, format: 'ttf' as const };
|
||||
const first = await publishGenerationFonts([font], root, generation);
|
||||
const second = await publishGenerationFonts([font], root, generation);
|
||||
expect(first[0]?.path).toBe(path.join(await realpath(generation), 'fonts', `${sha256}.ttf`));
|
||||
expect(second[0]?.path).toBe(first[0]?.path);
|
||||
expect(await readFile(first[0]!.path)).toEqual(data);
|
||||
});
|
||||
|
||||
it('prunes only global fonts with no generation hardlinks', async () => {
|
||||
const root = await mkdtemp(path.join(os.tmpdir(), 'easy-stream-font-prune-'));
|
||||
const store = path.join(root, 'assets', 'fonts', 'sha256');
|
||||
const generationFonts = path.join(root, 'generations', 'generation-id', 'fonts');
|
||||
await Promise.all([mkdir(store, { recursive: true }), mkdir(generationFonts, { recursive: true })]);
|
||||
const orphan = `${'a'.repeat(64)}.ttf`;
|
||||
const retained = `${'b'.repeat(64)}.otf`;
|
||||
await Promise.all([
|
||||
writeFile(path.join(store, orphan), minimalSfnt()),
|
||||
writeFile(path.join(store, retained), minimalSfnt()),
|
||||
]);
|
||||
await link(path.join(store, retained), path.join(generationFonts, retained));
|
||||
const result = await pruneOrphanedFonts(root, { minimumAgeMs: 0, now: new Date(Date.now() + 1000) });
|
||||
expect(result.removed).toEqual([orphan]);
|
||||
expect(result.retainedBytes).toBe(minimalSfnt().length);
|
||||
await expect(stat(path.join(store, orphan))).rejects.toMatchObject({ code: 'ENOENT' });
|
||||
expect((await stat(path.join(store, retained))).nlink).toBe(2);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,71 @@
|
||||
import { mkdtemp, mkdir, readFile, writeFile } from 'node:fs/promises';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
assessFfmpegWarnings,
|
||||
buildMasterPlaylist,
|
||||
finalizeEventPlaylist,
|
||||
parseMediaPlaylist,
|
||||
validateMediaPlaylist,
|
||||
} from '../src/index.js';
|
||||
import { audio, probe, video } from './fixtures.js';
|
||||
|
||||
async function playlistFixture(): Promise<string> {
|
||||
const directory = await mkdtemp(path.join(os.tmpdir(), 'easy-stream-hls-'));
|
||||
await Promise.all([
|
||||
writeFile(path.join(directory, 'init.mp4'), 'init'),
|
||||
writeFile(path.join(directory, 'segment-000.m4s'), 'one'),
|
||||
writeFile(path.join(directory, 'segment-001.m4s'), 'two'),
|
||||
]);
|
||||
const playlist = path.join(directory, 'index.m3u8');
|
||||
await writeFile(playlist, [
|
||||
'#EXTM3U', '#EXT-X-VERSION:7', '#EXT-X-TARGETDURATION:10', '#EXT-X-PLAYLIST-TYPE:EVENT',
|
||||
'#EXT-X-MAP:URI="init.mp4"', '#EXTINF:9.2,', 'segment-000.m4s', '#EXTINF:4.0,',
|
||||
'segment-001.m4s', '#EXT-X-ENDLIST', '',
|
||||
].join('\n'));
|
||||
return playlist;
|
||||
}
|
||||
|
||||
describe('HLS validation', () => {
|
||||
it('checks all local fMP4 references and finalizes EVENT to VOD atomically', async () => {
|
||||
const playlist = await playlistFixture();
|
||||
const result = await validateMediaPlaylist(playlist, { requireEnded: true, minSegments: 2, maxTargetDuration: 18 });
|
||||
expect(result).toMatchObject({ segmentCount: 2, maxDuration: 9.2, totalDuration: 13.2 });
|
||||
await finalizeEventPlaylist(playlist);
|
||||
expect(await readFile(playlist, 'utf8')).toContain('#EXT-X-PLAYLIST-TYPE:VOD');
|
||||
});
|
||||
|
||||
it('rejects traversal and remote segment URIs', async () => {
|
||||
const directory = await mkdtemp(path.join(os.tmpdir(), 'easy-stream-hls-unsafe-'));
|
||||
await writeFile(path.join(directory, 'init.mp4'), 'init');
|
||||
const traversal = path.join(directory, 'traversal.m3u8');
|
||||
await writeFile(traversal, '#EXTM3U\n#EXT-X-TARGETDURATION:6\n#EXT-X-MAP:URI="init.mp4"\n#EXTINF:5,\n../secret.m4s');
|
||||
await expect(validateMediaPlaylist(traversal)).rejects.toThrow('Unsafe or external HLS URI');
|
||||
const remote = path.join(directory, 'remote.m3u8');
|
||||
await writeFile(remote, '#EXTM3U\n#EXT-X-TARGETDURATION:6\n#EXT-X-MAP:URI="init.mp4"\n#EXTINF:5,\nhttps://evil.invalid/a.m4s');
|
||||
await expect(validateMediaPlaylist(remote)).rejects.toThrow('Unsafe or external HLS URI');
|
||||
});
|
||||
|
||||
it('permits only the bounded -32 AAC rounding warning', () => {
|
||||
const known = assessFfmpegWarnings('[mp4 @ a] Packet duration: -32 / dts: 580456 in stream 0 is out of range');
|
||||
expect(known).toMatchObject({ knownAacRepairs: 1, unknown: [] });
|
||||
expect(assessFfmpegWarnings('[mp4 @ a] Packet duration: -64 / dts: 10 in stream 0 is out of range').unknown)
|
||||
.toHaveLength(1);
|
||||
expect(assessFfmpegWarnings('Non-monotonous DTS').unknown).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('uses declared/container bitrate and a conservative video fallback', () => {
|
||||
const declared = buildMasterPlaylist(probe(), 0, 'video/index.m3u8', [{
|
||||
streamIndex: 1, language: 'ja', name: 'Japanese', uri: 'audio/index.m3u8', default: true,
|
||||
}]);
|
||||
expect(declared).toContain('AVERAGE-BANDWIDTH=852432');
|
||||
const missing = probe([video({ tags: {}, bit_rate: undefined }), audio({ tags: {}, bit_rate: undefined })]);
|
||||
missing.format.bit_rate = undefined;
|
||||
const conservative = buildMasterPlaylist(missing, 0, 'video/index.m3u8', [{
|
||||
streamIndex: 1, language: 'ja', name: 'Japanese', uri: 'audio/index.m3u8', default: true,
|
||||
}]);
|
||||
const bandwidth = Number(conservative.match(/BANDWIDTH=(\d+)/u)?.[1]);
|
||||
expect(bandwidth).toBeGreaterThan(8_000_000);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,34 @@
|
||||
import { mkdtemp, mkdir, realpath, symlink, writeFile } from 'node:fs/promises';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { fingerprintSource, isPathInside, walkArchive } from '../src/index.js';
|
||||
|
||||
describe('archive boundaries', () => {
|
||||
it('walks regular MKV files without following symlinks', async () => {
|
||||
const base = await mkdtemp(path.join(os.tmpdir(), 'easy-stream-walk-'));
|
||||
const root = path.join(base, 'archive');
|
||||
const outside = path.join(base, 'outside');
|
||||
await Promise.all([mkdir(path.join(root, 'series'), { recursive: true }), mkdir(outside)]);
|
||||
await writeFile(path.join(root, 'series', 'one.mkv'), 'safe');
|
||||
await writeFile(path.join(outside, 'secret.mkv'), 'secret');
|
||||
await symlink(path.join(outside, 'secret.mkv'), path.join(root, 'linked.mkv'));
|
||||
const files: string[] = [];
|
||||
for await (const file of walkArchive(root)) files.push(file);
|
||||
expect(files).toEqual([await realpath(path.join(root, 'series', 'one.mkv'))]);
|
||||
expect(isPathInside(root, path.join(root, 'series', 'one.mkv'))).toBe(true);
|
||||
expect(isPathInside(root, path.join(outside, 'secret.mkv'))).toBe(false);
|
||||
});
|
||||
|
||||
it('fingerprints path, stat and both file edges', async () => {
|
||||
const root = await mkdtemp(path.join(os.tmpdir(), 'easy-stream-fingerprint-'));
|
||||
const source = path.join(root, 'movie.mkv');
|
||||
await writeFile(source, 'HEAD-middle-TAIL');
|
||||
const first = await fingerprintSource(root, source, 4);
|
||||
const same = await fingerprintSource(root, source, 4);
|
||||
expect(same.digest).toBe(first.digest);
|
||||
await writeFile(source, 'HEAd-middle-TAIL');
|
||||
const changed = await fingerprintSource(root, source, 4);
|
||||
expect(changed.digest).not.toBe(first.digest);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,17 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { mediaProcessEnvironment } from '../src/index.js';
|
||||
|
||||
describe('media child process environment', () => {
|
||||
it('keeps runtime paths but strips application secrets', () => {
|
||||
expect(mediaProcessEnvironment({
|
||||
PATH: '/usr/bin',
|
||||
LD_LIBRARY_PATH: '/opt/ffmpeg/lib',
|
||||
DATABASE_URL: 'postgres://secret',
|
||||
REDIS_URL: 'redis://secret',
|
||||
PLAYBACK_SIGNING_SECRET: 'secret',
|
||||
})).toEqual({
|
||||
PATH: '/usr/bin',
|
||||
LD_LIBRARY_PATH: '/opt/ffmpeg/lib',
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,17 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { subtitleAssArguments } from '../src/index.js';
|
||||
|
||||
describe('bounded subtitle inspection', () => {
|
||||
it('adds a numeric output duration only when requested', () => {
|
||||
const bounded = subtitleAssArguments('/archive/movie.mkv', 3, 600);
|
||||
expect(bounded.slice(bounded.indexOf('-t'), bounded.indexOf('-t') + 2)).toEqual(['-t', '600']);
|
||||
expect(bounded).toContain('0:3');
|
||||
expect(subtitleAssArguments('/archive/movie.mkv', 3)).not.toContain('-t');
|
||||
});
|
||||
|
||||
it('rejects invalid stream and duration values before invoking FFmpeg', () => {
|
||||
expect(() => subtitleAssArguments('/archive/movie.mkv', -1, 600)).toThrow('streamIndex');
|
||||
expect(() => subtitleAssArguments('/archive/movie.mkv', 2, Number.POSITIVE_INFINITY)).toThrow('maxDurationSeconds');
|
||||
expect(() => subtitleAssArguments('/archive/movie.mkv', 2, 86_401)).toThrow('maxDurationSeconds');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"rootDir": "src",
|
||||
"outDir": "dist",
|
||||
"types": ["node"]
|
||||
},
|
||||
"include": ["src/**/*.ts"],
|
||||
"exclude": ["src/**/*.test.ts"]
|
||||
}
|
||||
Reference in new issue
Block a user