Skip to content

Commit ee1a0ec

Browse files
authored
[ Release ] : v0.4.0 (#28)
For more details PR : #26
1 parent e6dbfc7 commit ee1a0ec

24 files changed

Lines changed: 357 additions & 76 deletions

‎.env.example‎

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -40,16 +40,31 @@ DOMAIN_SUBDOMAIN_NAME=https://vod-cdn.{SUBDOMAIN}.{DOMAIN}.com
4040
# FFmpeg uses this for demuxing, filtering, and muxing threads.
4141
FFMPEG_THREADS=0
4242

43-
# x265 (HEVC/Dolby Vision) thread pool size. Set to your vCPU count for max utilization.
44-
# This is the BIGGEST performance lever — pools=none previously disabled ALL threading.
45-
# Example: 32-core machine → X265_POOL_SIZE=32
46-
X265_POOL_SIZE=32
47-
4843
# x265 frame-level parallelism. How many frames encode simultaneously.
4944
# 4 is optimal for most machines. Higher values use more RAM but increase throughput.
5045
# Rule of thumb: 2-6 depending on available RAM (each frame buffer ~50-200MB for 4K).
5146
X265_FRAME_THREADS=4
5247

48+
# x265 lookahead threads. 0 = auto-detect (recommended, uses half of frame-threads).
49+
# Previously hardcoded to 1, which bottlenecked the rate-control analysis.
50+
X265_LOOKAHEAD_THREADS=0
51+
52+
# x265 rate-control lookahead depth (frames). Higher = better bitrate distribution.
53+
# Increased from 20 to 40 for improved VBR quality at the cost of slightly more RAM.
54+
X265_RC_LOOKAHEAD=40
55+
56+
# x264 rate-control lookahead depth (frames). Higher = better VBR quality.
57+
# Increased from 40 to 60 for improved bitrate distribution.
58+
X264_RC_LOOKAHEAD=60
59+
60+
# FFmpeg 8.1: Input thread queue sizing. Prevents "Thread message queue blocking" stalls.
61+
# Higher values help with high-bitrate 4K sources. Default 512 covers most cases.
62+
THREAD_QUEUE_SIZE=512
63+
64+
# Maximum muxer queue size. FFmpeg 8.1 runs each muxer in its own thread.
65+
# Higher values prevent the muxer thread from blocking the encoder.
66+
MAX_MUXING_QUEUE_SIZE=4096
67+
5368
# Developer Override: Force the system to use ONLY one group of profiles.
5469
# Values: 'avc_sdr', 'hvc_sdr', 'hvc_pq', 'dvh_pq', 'ALL'
5570
TEST_VIDEO_PROFILE=ALL

‎Dockerfile‎

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,6 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
4040
build-essential \
4141
pkg-config \
4242
nasm \
43-
yasm \
4443
wget \
4544
git \
4645
cmake \
@@ -72,7 +71,7 @@ RUN git clone --depth 1 https://github.com/Netflix/vmaf.git /tmp/vmaf && \
7271
# -----------------------------------------------------------------------------
7372
# 3. Download FFmpeg Source Code
7473
# -----------------------------------------------------------------------------
75-
ARG FFMPEG_VERSION=7.1
74+
ARG FFMPEG_VERSION=8.1
7675
RUN wget -q https://ffmpeg.org/releases/ffmpeg-${FFMPEG_VERSION}.tar.bz2 && \
7776
tar xjf ffmpeg-${FFMPEG_VERSION}.tar.bz2 && \
7877
rm ffmpeg-${FFMPEG_VERSION}.tar.bz2
@@ -90,7 +89,9 @@ RUN PKG_CONFIG_PATH=/usr/local/lib/aarch64-linux-gnu/pkgconfig:/usr/local/lib/x8
9089
--enable-gpl \
9190
--enable-nonfree \
9291
--enable-version3 \
92+
--enable-pthreads \
9393
--enable-swresample \
94+
--enable-swscale \
9495
--enable-libsoxr \
9596
--enable-libopus \
9697
--enable-libx264 \
@@ -108,7 +109,6 @@ RUN PKG_CONFIG_PATH=/usr/local/lib/aarch64-linux-gnu/pkgconfig:/usr/local/lib/x8
108109
--disable-doc \
109110
--disable-debug \
110111
--disable-ffplay \
111-
--disable-autodetect \
112112
--disable-sdl2 \
113113
--disable-libxcb \
114114
--disable-libxcb-shm \
@@ -125,7 +125,7 @@ RUN PKG_CONFIG_PATH=/usr/local/lib/aarch64-linux-gnu/pkgconfig:/usr/local/lib/x8
125125
--disable-nvdec \
126126
--disable-indevs \
127127
--disable-outdevs \
128-
--extra-cflags="-O2" \
128+
--extra-cflags="-O3 -march=x86-64-v3 -pipe -fomit-frame-pointer" \
129129
&& make -j$(nproc) \
130130
&& make install \
131131
&& strip /usr/local/bin/ffmpeg /usr/local/bin/ffprobe
@@ -160,7 +160,7 @@ RUN pnpm run build
160160

161161
# =============================================================================
162162
# Stage 3 — Production Runtime
163-
# Final optimized image containing the compiled Node.js application, the custom
163+
# Final image containing the compiled Node.js application, the custom
164164
# FFmpeg binary, and minimal shared runtime libraries.
165165
# =============================================================================
166166
FROM ubuntu:24.04
@@ -170,11 +170,11 @@ ENV DEBIAN_FRONTEND=noninteractive
170170
# -----------------------------------------------------------------------------
171171
# Metadata & OCI Labels
172172
# -----------------------------------------------------------------------------
173-
ARG VERSION=0.3.2
173+
ARG VERSION=0.4.0
174174
ARG BUILD_DATE=unknown
175175

176176
LABEL org.opencontainers.image.title="ffmpeg-queue-worker-node" \
177-
org.opencontainers.image.description="FFmpeg 7.1 & Node.js Video Job Worker" \
177+
org.opencontainers.image.description="FFmpeg 8.1 & Node.js Video Job Worker" \
178178
org.opencontainers.image.version="${VERSION}" \
179179
org.opencontainers.image.created="${BUILD_DATE}" \
180180
org.opencontainers.image.authors="Maulik M. Kadeval" \

‎package.json‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "worker",
3-
"version": "0.3.2",
3+
"version": "0.4.0",
44
"description": "FFmpeg Worker Service (TypeScript)",
55
"repository": {
66
"type": "git",
@@ -13,6 +13,8 @@
1313
"build": "rm -rf dist && tsc && find src -name '*.json' | while read f; do mkdir -p dist/$(dirname ${f#src/}) && cp $f dist/${f#src/}; done",
1414
"dev:local:format": "prettier --write \"src/**/*.{ts,json}\"",
1515
"dev:local:build:docker": "docker build -t worker-local-dev .",
16+
"dev:local:build:docker:arm64": "docker build --platform linux/arm64 -t worker-local-dev .",
17+
"dev:local:build:docker:amd64": "docker build --platform linux/amd64 -t worker-local-dev .",
1618
"dev:local:test:job": "tsx --env-file=.env test/queue-job.test.local.ts",
1719
"dev:local:run:docker": "docker run --env-file .env worker-local-dev",
1820
"dev:local:e2e": "pnpm run dev:local:format && pnpm run dev:local:build:docker && pnpm run dev:local:test:job && pnpm run dev:local:run:docker"

‎src/application/video.process.ts‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ import { pino } from 'pino';
1616
const logger = pino({ name: 'ProcessVideo' });
1717

1818
/**
19-
* Orchestrates the core video processing pipeline: Download -> Probe -> Transcode -> Upload.
19+
* Orchestrates the domain lifecycle of a video ingest job: Network -> Probe -> Encode -> Storage.
2020
*/
2121
export class ProcessVideo implements ProcessVideoUseCase {
2222
constructor(
@@ -25,6 +25,17 @@ export class ProcessVideo implements ProcessVideoUseCase {
2525
private readonly db: VideoRepository,
2626
) {}
2727

28+
/**
29+
* Executes the sequential pipeline required to convert an arbitrary media source to HLS.
30+
*
31+
* - Streams the raw source over HTTP directly to local NVMe via `node:stream/promises` to avoid RAM saturation.
32+
* - Invokes `ffprobe` to determine target mapping bounds (`sourceWidth`, `sourceHeight`).
33+
* - Updates the database (PostgreSQL) incrementally based on status transitions to prevent worker lock loss.
34+
*
35+
* @param job - Required DTO mapping `videoId` to an inbound `sourceUrl`.
36+
* @param onProgress - BullMQ callback exposing fractional `Math.round()` percentage integers back to Redis.
37+
* @throws {WorkerError} Forwards non-zero FFmpeg exits or network IO disconnects back to BullMQ for retry evaluation.
38+
*/
2839
async execute(job: JobData, onProgress?: ProgressCallback): Promise<void> {
2940
const { videoId, sourceUrl, webhookUrl } = job;
3041
logger.info({ videoId, sourceUrl, webhookUrl }, 'Starting video processing pipeline');

‎src/config/env.ts‎

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,11 @@
11
/**
2-
* Runtime configuration validated via Zod schema.
3-
* Designed to fail-fast: if any required variable is missing or malformed, the process crashes
4-
* immediately before attempting to bind ports or connect to the database.
2+
* Configuration loaded from environment variables using Zod.
3+
* The application will crash on startup if any required values are missing or incorrect.
54
*/
65
import { z } from 'zod';
76

87
/**
9-
* Strips literal quotes injected by `.env` loaders to prevent DSN/connection string parsing errors.
8+
* Removes extra quotation marks from environment variables.
109
*/
1110
const unquotedString = z.string().transform((s) => s.replace(/^["'](.*?)["']$/, '$1'));
1211

@@ -31,6 +30,7 @@ const envSchema = z.object({
3130
AZURE_UPLOAD_RETRIES: z.coerce.number().default(3),
3231
AZURE_STORAGE_CONNECTION_STRING: unquotedString.optional(),
3332
AZURE_STORAGE_ACCOUNT_URL: unquotedString.optional(),
33+
AZURE_MANAGED_IDENTITY_CLIENT_ID: unquotedString.optional(),
3434
AZURE_STORAGE_CONTAINER_NAME: unquotedString.pipe(
3535
z.string().min(1, 'AZURE_STORAGE_CONTAINER_NAME is required'),
3636
),
@@ -42,12 +42,18 @@ const envSchema = z.object({
4242
DOMAIN_SUBDOMAIN_NAME: unquotedString.optional(),
4343

4444
FFMPEG_THREADS: z.coerce.number().default(0),
45-
X265_POOL_SIZE: z.coerce.number().default(32),
46-
X265_FRAME_THREADS: z.coerce.number().default(4),
45+
X265_FRAME_THREADS: z.coerce.number().default(2),
46+
X265_LOOKAHEAD_THREADS: z.coerce.number().default(0),
47+
X265_RC_LOOKAHEAD: z.coerce.number().default(40),
48+
49+
THREAD_QUEUE_SIZE: z.coerce.number().default(512),
50+
MAX_MUXING_QUEUE_SIZE: z.coerce.number().default(4096),
51+
52+
X264_RC_LOOKAHEAD: z.coerce.number().default(60),
4753
});
4854

4955
/**
50-
* Validated application configuration. Extracted directly from `process.env`.
51-
* @throws {ZodError} If validation fails during module load.
56+
* The validated application settings, used throughout the app.
57+
* @throws {ZodError} If any environment variable rules are broken.
5258
*/
5359
export const config: z.infer<typeof envSchema> = envSchema.parse(process.env);

‎src/domain/errors.ts‎

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
/**
2-
* Base custom exception for all domain errors. Wraps the underlying `.cause` for traceability.
3-
* Features a `retryable` flag that signals to the queue wrapper whether to re-queue the job
4-
* (e.g., transient network issue) or fail it permanently (e.g., validation failure).
2+
* Derived exception class enforcing `{ retryable: boolean }` properties.
3+
* Designed explicitly so the BullMQ execution loop can discriminate between `EIO` / network transient faults
4+
* versus deterministic decoder/syntax panics which will never succeed.
55
*/
66
export class WorkerError extends Error {
77
public readonly retryable: boolean;
@@ -13,24 +13,38 @@ export class WorkerError extends Error {
1313
}
1414
}
1515

16+
/**
17+
* Maps to HTTP 404/403 closures when resolving `sourceUrl` blobs into `import { pipeline }`.
18+
*/
1619
export class SourceNotFoundError extends WorkerError {
1720
constructor(url: string, cause?: Error) {
1821
super(`Source video not found: ${url}`, false, { cause });
1922
}
2023
}
2124

25+
/**
26+
* Thrown strictly when `ffprobe` JSON parsing misses `codec_type === 'video'` segments,
27+
* preventing OOM exceptions across downstream multiplex mapping arrays.
28+
*/
2229
export class ValidationError extends WorkerError {
2330
constructor(message: string) {
2431
super(message, false);
2532
}
2633
}
2734

35+
/**
36+
* Thrown dynamically upon `code !== 0` closures from spawned `ffmpeg` PIDs.
37+
* Allows `retryable=true` scaling to bypass transient OS thread allocation panics.
38+
*/
2839
export class TranscodeError extends WorkerError {
2940
constructor(message: string, cause?: Error) {
3041
super(message, true, { cause });
3142
}
3243
}
3344

45+
/**
46+
* Bounds Azure/S3 multipart SDK connection strings resetting during `BlockBlobClient.upload()`.
47+
*/
3448
export class UploadError extends WorkerError {
3549
constructor(message: string, cause?: Error) {
3650
super(message, true, { cause });

‎src/domain/job.interface.ts‎

Lines changed: 45 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,17 @@
1+
/**
2+
* Explicit schema interfaces required across the ingestion boundaries (worker -> pg -> storage).
3+
*/
14
export interface JobData {
25
videoId: string;
36
sourceUrl: string;
47
userId: string;
8+
/** Resolves a callback POST upon zero-exit codes enabling loose-coupled status meshes. */
59
webhookUrl?: string;
610
}
711

12+
/**
13+
* Indexed mapping bound to libavformat streams array for track persistence.
14+
*/
815
export interface AudioStreamInfo {
916
index: number;
1017
codec: string;
@@ -13,6 +20,9 @@ export interface AudioStreamInfo {
1320
title: string;
1421
}
1522

23+
/**
24+
* Maps raw `ffprobe` JSON outputs into explicitly-typed constraints.
25+
*/
1626
export interface ProbeResult {
1727
duration: number;
1828
width: number;
@@ -26,19 +36,30 @@ export interface ProbeResult {
2636
videoRange: string;
2737
}
2838

39+
/**
40+
* Output artifact references mapped directly into CDN manifest namespaces.
41+
*/
2942
export interface VideoRendition {
3043
resolution: string;
3144
width: number;
3245
height: number;
3346
bitrate: number;
47+
/** Pre-built HTTP relative-blob URL mapping directly to EXT-X-STREAM-INF payloads. */
3448
url: string;
3549
}
3650

51+
/**
52+
* Final memory resolution passed back up to the master BullMQ job processor.
53+
*/
3754
export interface TranscodeResult {
55+
/** Virtualized tmpfs / NVMe root mapping the segmented output arrays. */
3856
outputDir: string;
3957
renditions: VideoRendition[];
4058
}
4159

60+
/**
61+
* Tracks row-level states in PostgreSQL to handle pre-emption and idempotency locks.
62+
*/
4263
export type JobStatus =
4364
| 'queued'
4465
| 'processing'
@@ -47,6 +68,9 @@ export type JobStatus =
4768
| 'completed'
4869
| 'failed';
4970

71+
/**
72+
* Implements the atomic transactions expected off `pg` client handles.
73+
*/
5074
export interface VideoRepository {
5175
updateStatus(
5276
videoId: string,
@@ -59,21 +83,33 @@ export interface VideoRepository {
5983
}
6084

6185
/**
62-
* Dependency-inversion interface for blob storage providers (e.g., Azure Blob Storage, AWS S3).
86+
* Maps the internal Node disk blocks outwards to object blob spaces via multipart SDK uploads.
6387
*/
6488
export interface StorageProvider {
89+
/**
90+
* Iterates the segment manifests onto Azure/AWS, injecting exact `video/mp4` and `application/vnd.apple.mpegurl` headers.
91+
* @returns Fully qualified FQDN for the resulting master array.
92+
*/
6593
uploadHLS(folderPath: string, videoId: string, onProgress?: ProgressCallback): Promise<string>;
6694
}
6795

96+
/**
97+
* Progress delegate invoked off chunk offsets per internal `ffprobe` loop bindings.
98+
*/
6899
export type ProgressCallback = (data: { variant: string; percent: number }) => void;
69100

70101
/**
71-
* Domain boundary around the native FFmpeg system binary.
72-
* Implementors must guarantee that `cleanup()` removes all trailing artifacts from the OS.
102+
* Abstract boundary wrapping child_process execution of the native OS ffmpeg binary.
73103
*/
74104
export interface TranscodeProvider {
105+
/**
106+
* Synchronous `spawn` intercept for the inbound libavformat properties array.
107+
*/
75108
probe(sourceUrl: string): Promise<ProbeResult>;
76109

110+
/**
111+
* Pushes bounded stream definitions through the libx265 / libx264 cores.
112+
*/
77113
transcodeHLS(
78114
sourceUrl: string,
79115
videoId: string,
@@ -86,9 +122,15 @@ export interface TranscodeProvider {
86122
videoRange?: string,
87123
): Promise<TranscodeResult>;
88124

125+
/**
126+
* Empties the `tmpfs` blocks post-execution, strictly avoiding disk bloat errors.
127+
*/
89128
cleanup(videoId: string): Promise<void>;
90129
}
91130

131+
/**
132+
* Dependency-injected service orchestrating the state/execute lifecycle of worker units.
133+
*/
92134
export interface ProcessVideoUseCase {
93135
execute(job: JobData, onProgress?: ProgressCallback): Promise<void>;
94136
}

‎src/infrastructure/db/db.ts‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,13 @@ import type {
1010
const logger = pino({ name: 'PostgresVideoRepository' });
1111

1212
/**
13-
* PostgreSQL adapter for persisting video state and metadata.
13+
* Provides database connection pooling for PostgreSQL using `pg`.
1414
*
1515
* @remarks
16-
* - Manages its own connection pool. Must call `close()` during graceful shutdown to prevent connection leaks.
17-
* - Upserts are used for metadata (`ON CONFLICT (video_id) DO UPDATE`) to safely support job retries (idempotency).
18-
* - `updateStatus` serves as a sanity check: it intentionally throws if the video ID vanishes mid-process.
16+
* - Enforces minimum timeout definitions (`idleTimeoutMillis`, `connectionTimeoutMillis`) to
17+
* prevent zombie DB locks if pg/Azure networks lag.
18+
* - Resolves race conditions across distributed workers by utilizing `ON CONFLICT ... DO UPDATE` upserts.
19+
* - Verifies row existence before state progression transitions to prevent missing target errors.
1920
*/
2021
export class PostgresVideoRepository implements VideoRepository {
2122
private readonly pool: pg.Pool;

0 commit comments

Comments
 (0)