### Quick Example: Convert and Resize Image Source: https://github.com/nklisch/ffmpeg-kit/blob/main/docs/operations/image.md A quick example demonstrating how to convert an image to WebP format, resize it to a specific width, and save the output. This is a common starting point for image manipulation tasks. ```typescript import { ffmpeg } from "ffmpeg-kit"; // Convert image format await ffmpeg.image() .input("photo.jpg") .convert("webp") .resize({ width: 800 }) .output("photo.webp") .execute(); ``` -------------------------------- ### Quick GIF Creation Example Source: https://github.com/nklisch/ffmpeg-kit/blob/main/docs/operations/gif.md A basic example demonstrating how to create a GIF from a video file with specified trim start, duration, size, and FPS. It includes palette optimization for better quality. ```typescript import { ffmpeg } from "ffmpeg-kit"; await ffmpeg.gif() .input("video.mp4") .trimStart(10) .duration(3) .size({ width: 480 }) .fps(15) .optimizePalette() .output("clip.gif") .execute(); ``` -------------------------------- ### QSV Input Arguments Example Source: https://github.com/nklisch/ffmpeg-kit/blob/main/docs/designs/completed/phase-4-hardware-encoding.md Example of input arguments for QSV hardware acceleration. ```typescript // qsv: ["-hwaccel", "qsv", "-hwaccel_output_format", "qsv"] ``` -------------------------------- ### Quick Audio Processing Example Source: https://github.com/nklisch/ffmpeg-kit/blob/main/docs/operations/audio.md A quick example demonstrating audio normalization, fade in/out, and output. Ensure 'ffmpeg-kit' is imported. ```typescript import { ffmpeg } from "ffmpeg-kit"; await ffmpeg.audio() .input("podcast.wav") .normalize({ targetLUFS: -16 }) .fadeIn(1) .fadeOut(2) .output("normalized.wav") .execute(); ``` -------------------------------- ### Install ffmpeg-kit using npm, pnpm, or yarn Source: https://github.com/nklisch/ffmpeg-kit/blob/main/docs/designs/completed/design-docs-site.md Demonstrates how to install the ffmpeg-kit package using different package managers. ```bash npm install ffmpeg-kit ``` ```bash pnpm add ffmpeg-kit ``` ```bash yarn add ffmpeg-kit ``` -------------------------------- ### Quick Export Video Example Source: https://github.com/nklisch/ffmpeg-kit/blob/main/docs/operations/export.md A basic example demonstrating how to export a video using a predefined preset and the faststart option for web streaming. ```typescript import { ffmpeg } from "ffmpeg-kit"; await ffmpeg.exportVideo() .input("raw.mp4") .preset("youtube_1080p") .faststart() .output("youtube.mp4") .execute(); ``` -------------------------------- ### Install ffmpeg-kit Source: https://github.com/nklisch/ffmpeg-kit/blob/main/README.md Install the ffmpeg-kit package using npm. Requires Node.js >= 22 and FFmpeg/ffprobe installed on PATH. ```bash npm install ffmpeg-kit ``` -------------------------------- ### Start Development Server Source: https://github.com/nklisch/ffmpeg-kit/blob/main/docs/designs/completed/design-docs-site.md Starts the VitePress development server for local testing and visual verification of documentation pages. ```bash pnpm docs:dev ``` -------------------------------- ### Vulkan Input Arguments Example Source: https://github.com/nklisch/ffmpeg-kit/blob/main/docs/designs/completed/phase-4-hardware-encoding.md Example of input arguments for Vulkan hardware acceleration. ```typescript // vulkan: ["-hwaccel", "vulkan"] ``` -------------------------------- ### Install FFmpegKit with yarn Source: https://github.com/nklisch/ffmpeg-kit/blob/main/docs/guide/getting-started.md Install the ffmpeg-kit package using yarn. ```bash yarn add ffmpeg-kit ``` -------------------------------- ### Quick Concat Example Source: https://github.com/nklisch/ffmpeg-kit/blob/main/docs/operations/concat.md A basic example demonstrating how to concatenate three video clips into a single output file. ```typescript import { ffmpeg } from "ffmpeg-kit"; await ffmpeg.concat() .addClip("clip1.mp4") .addClip("clip2.mp4") .addClip("clip3.mp4") .output("joined.mp4") .execute(); ``` -------------------------------- ### Verify Guide Page Existence Source: https://github.com/nklisch/ffmpeg-kit/blob/main/docs/designs/completed/design-docs-site.md Checks if a specific guide page HTML file exists in the build output directory. ```bash ls docs/.vitepress/dist/guide/getting-started.html ``` -------------------------------- ### VAAPI Input Arguments Example Source: https://github.com/nklisch/ffmpeg-kit/blob/main/docs/designs/completed/phase-4-hardware-encoding.md Example of input arguments for VAAPI hardware acceleration. ```typescript // vaapi: ["-hwaccel", "vaapi", "-hwaccel_device", "/dev/dri/renderD128", "-hwaccel_output_format", "vaapi"] ``` -------------------------------- ### CPU Input Arguments Example Source: https://github.com/nklisch/ffmpeg-kit/blob/main/docs/designs/completed/phase-4-hardware-encoding.md Example of input arguments for CPU mode (no hardware acceleration). ```typescript // cpu: [] ``` -------------------------------- ### npm Installation Command Source: https://github.com/nklisch/ffmpeg-kit/blob/main/docs/designs/completed/phase-12-polish-publish.md Installs the ffmpeg-kit package using npm. This is the standard command for adding the SDK to a Node.js project. ```bash npm install ffmpeg-kit ``` -------------------------------- ### Quick Example: Add Watermark Source: https://github.com/nklisch/ffmpeg-kit/blob/main/docs/operations/overlay.md A quick example demonstrating how to add a watermark to a video. Ensure you have the base video and watermark image files available. ```typescript import { ffmpeg } from "ffmpeg-kit"; await ffmpeg.overlay() .base("video.mp4") .watermark({ input: "logo.png", position: "top-right", opacity: 0.8 }) .output("watermarked.mp4") .execute(); ``` -------------------------------- ### NVIDIA Input Arguments Example Source: https://github.com/nklisch/ffmpeg-kit/blob/main/docs/designs/completed/phase-4-hardware-encoding.md Example of input arguments for NVIDIA hardware acceleration. ```typescript // nvidia: ["-hwaccel", "cuda", "-hwaccel_output_format", "cuda"] ``` -------------------------------- ### Install FFmpegKit with pnpm Source: https://github.com/nklisch/ffmpeg-kit/blob/main/docs/guide/getting-started.md Install the ffmpeg-kit package using pnpm. ```bash pnpm add ffmpeg-kit ``` -------------------------------- ### Quick Example: Extract Frame Source: https://github.com/nklisch/ffmpeg-kit/blob/main/docs/operations/extract.md A quick example demonstrating how to extract a frame at a specific timestamp, set its size, format, and output path. ```typescript import { ffmpeg } from "ffmpeg-kit"; const result = await ffmpeg.extract() .input("video.mp4") .timestamp(5) .size({ width: 640 }) .format("jpg") .output("thumb.jpg") .execute(); console.log(result.outputPath); // "thumb.jpg" console.log(result.width, result.height); // 640, 360 ``` -------------------------------- ### Apply a Preset for YouTube Source: https://github.com/nklisch/ffmpeg-kit/blob/main/docs/guide/presets.md Use the `.preset()` method to apply predefined settings for common delivery targets like YouTube. This example applies the 'youtube_1080p' preset. ```typescript await ffmpeg.exportVideo() .input("raw.mp4") .preset("youtube_1080p") .faststart() .output("youtube.mp4") .execute(); ``` -------------------------------- ### Quick Start: Scale and Trim Source: https://github.com/nklisch/ffmpeg-kit/blob/main/README.md Scale a video to a specific width and trim a segment starting from a given time. The output is a new video file. ```typescript // Scale and trim await ffmpeg.transform() .input("video.mp4") .scale({ width: 1280 }) .trimStart(10) .duration(30) .output("clip.mp4") .execute(); ``` -------------------------------- ### YouTube Upload Export Example Source: https://github.com/nklisch/ffmpeg-kit/blob/main/docs/operations/export.md An example of exporting a video specifically for YouTube upload, utilizing a preset, faststart, and auto hardware acceleration. ```typescript await ffmpeg.exportVideo() .input("raw.mp4") .preset("youtube_1080p") .faststart() .hwAccel("auto") .output("youtube.mp4") .execute(); ``` -------------------------------- ### FFmpeg Command Construction for Text Overlays Source: https://github.com/nklisch/ffmpeg-kit/blob/main/docs/designs/completed/phase-7-export-overlay-text.md This example shows the typical construction of an FFmpeg command when applying text filters. Audio is stream-copied to preserve it. ```bash -y -i inputPath -vf "drawtext=...[,drawtext=...]" DEFAULT_VIDEO_CODEC_ARGS -c:a copy output ``` -------------------------------- ### Example: H.264 CPU Encoder Arguments Source: https://github.com/nklisch/ffmpeg-kit/blob/main/docs/designs/completed/phase-4-hardware-encoding.md Generates FFmpeg arguments for H.264 encoding using the libx264 codec. This example demonstrates mapping CRF and preset values to command-line flags. ```typescript encoderConfigToArgs({ codec: "libx264", crf: 23, preset: "medium" }) ``` -------------------------------- ### Video Resizing Implementation Example Source: https://github.com/nklisch/ffmpeg-kit/blob/main/docs/designs/completed/phase-10-convenience-layer.md Demonstrates the `resize` convenience function for changing the dimensions of a video. It uses the `transform` builder and the `scale` filter. ```typescript transform().input(input).scale({ width, height }).output(output).execute() ``` -------------------------------- ### Example: AAC Audio Encoder Arguments Source: https://github.com/nklisch/ffmpeg-kit/blob/main/docs/designs/completed/phase-4-hardware-encoding.md Generates FFmpeg arguments for AAC audio encoding. This example shows how to specify the codec and bitrate for audio streams. ```typescript audioEncoderConfigToArgs({ codec: "aac", bitrate: "192k" }) ``` -------------------------------- ### Fluent Builder Pattern Example Source: https://github.com/nklisch/ffmpeg-kit/blob/main/docs/guide/architecture.md Demonstrates the fluent builder pattern for FFmpegKit operations, from factory function to terminal execution. ```typescript // factory → configure → execute const result = await ffmpeg.extract() .input("video.mp4") // configure .timestamp(5) // configure .size({ width: 640 }) // configure .output("thumb.jpg") // configure .execute(); // terminal ``` -------------------------------- ### Create FFmpeg Instance with Custom Configuration Source: https://github.com/nklisch/ffmpeg-kit/blob/main/docs/ARCH.md Demonstrates how to create a new FFmpeg instance with specific configuration options like paths, timeouts, and logging levels. Each instance maintains its own state. ```typescript import { createFFmpeg } from '@ffmpeg-sdk/core'; // Each instance has its own config, cache, and session tracking const ffmpeg = createFFmpeg({ ffmpegPath: '/usr/bin/ffmpeg', // default: auto-detect from PATH ffprobePath: '/usr/bin/ffprobe', tempDir: '/tmp/ffmpeg-sdk', defaultTimeout: 600_000, defaultHwAccel: 'auto', logLevel: 'error', probeCacheSize: 100, probeCacheTtl: 300_000, }); ``` -------------------------------- ### Trim Video Segment Source: https://github.com/nklisch/ffmpeg-kit/blob/main/docs/operations/transform.md This example shows how to extract a specific segment from a longer video by defining the start and end times. ```typescript await ffmpeg.transform() .input("long-video.mp4") .trimStart("00:01:00") .trimEnd("00:02:30") .output("segment.mp4") .execute(); ``` -------------------------------- ### Quick Start: Probe File Source: https://github.com/nklisch/ffmpeg-kit/blob/main/README.md Probe a media file to get information such as duration. The probe output object contains detailed format information. ```typescript // Probe a file const info = await ffmpeg.probe("video.mp4"); console.log(info.format.duration); ``` -------------------------------- ### Short Reaction Clip GIF Source: https://github.com/nklisch/ffmpeg-kit/blob/main/docs/operations/gif.md Generates a short GIF clip from a video, suitable for reaction memes. This example specifies a precise start time, duration, dimensions, and frame rate, along with palette optimization. ```typescript await ffmpeg.gif() .input("video.mp4") .trimStart(5.5) .duration(2) .size({ width: 320 }) .fps(12) .optimizePalette() .output("reaction.gif") .execute(); ``` -------------------------------- ### Validate Installation Source: https://github.com/nklisch/ffmpeg-kit/blob/main/docs/INTERFACE.md Validates the FFmpeg installation. ```APIDOC ## VALIDATE INSTALLATION ### Description Validates that the FFmpeg binary is installed and accessible. ### Method `validateInstallation()` ### Request Example ```typescript await ffmpeg.validateInstallation(); ``` ``` -------------------------------- ### Create Custom FFmpeg Instance Source: https://github.com/nklisch/ffmpeg-kit/blob/main/README.md Demonstrates how to create a custom FFmpeg instance with specific paths for executables, a temporary directory, default timeout, hardware acceleration setting, and log level. ```typescript import { createFFmpeg } from "ffmpeg-kit"; const ff = createFFmpeg({ ffmpegPath: "/usr/local/bin/ffmpeg", ffprobePath: "/usr/local/bin/ffprobe", tempDir: "/tmp/my-app", defaultTimeout: 300_000, defaultHwAccel: "cpu", logLevel: "warning", }); ``` -------------------------------- ### Build Documentation Source: https://github.com/nklisch/ffmpeg-kit/blob/main/docs/designs/completed/design-docs-site.md Ensures a clean build of the documentation site with no warnings. ```bash pnpm docs:build ``` -------------------------------- ### Compression Implementation Example Source: https://github.com/nklisch/ffmpeg-kit/blob/main/docs/designs/completed/phase-10-convenience-layer.md Shows the implementation of the `compress` convenience function, utilizing the `qualityTier` option to reduce file size. This is useful for creating smaller media files. ```typescript exportVideo().input(input).qualityTier(quality ?? 'standard').output(output).execute() ``` -------------------------------- ### validateInstallation() Source: https://github.com/nklisch/ffmpeg-kit/blob/main/docs/api/core.md Validates that FFmpeg and ffprobe binaries are available and returns their versions. Throws an error if either binary is missing. ```APIDOC ## `validateInstallation()` ### Description Validates that FFmpeg and ffprobe binaries are available on the system and returns their respective paths and versions. This function is crucial for ensuring the FFmpegKit environment is correctly set up. ### Method Signature ```typescript function validateInstallation(options?: { ffmpegPath?: string; ffprobePath?: string; }): Promise<{ ffmpeg: { path: string; version: string }; ffprobe: { path: string; version: string }; }>; ``` ### Parameters #### `options` (object) - Optional An object that can optionally specify the paths to the FFmpeg and ffprobe binaries. - **`ffmpegPath`** (string) - The explicit path to the FFmpeg binary. - **`ffprobePath`** (string) - The explicit path to the ffprobe binary. ### Returns - **Promise** - A promise that resolves with an object containing information about the FFmpeg and ffprobe installations, including their paths and versions. - **`ffmpeg`** (object) - **`path`** (string) - The path to the FFmpeg binary. - **`version`** (string) - The version of the FFmpeg binary. - **`ffprobe`** (object) - **`path`** (string) - The path to the ffprobe binary. - **`version`** (string) - The version of the ffprobe binary. ### Throws - Throws an error if either the FFmpeg or ffprobe binary is missing or cannot be found. ### Example ```typescript import { validateInstallation } from "ffmpeg-kit"; const info = await validateInstallation(); console.log(info.ffmpeg.version); // "7.1.0" console.log(info.ffprobe.version); // "7.1.0" ``` ``` -------------------------------- ### Operation Page Template Source: https://github.com/nklisch/ffmpeg-kit/blob/main/docs/designs/completed/design-docs-site.md Template for individual operation documentation pages, including quick examples, API details, and use-case examples. ```markdown # {Operation Name} {One-line description.} ## Quick Example ```typescript {Minimal working example} ``` ## API ### `.method(param)` {Description, parameter types, default value.} | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | ... | ... | ... | ... | ## Examples ### {Use Case 1} ```typescript {Complete example} ``` ### {Use Case 2} ```typescript {Complete example} ``` ## Result Type ```typescript interface {Operation}Result { ... } ``` ## Related - [{Related operation}](/operations/{name}) - [{Relevant guide}](/guide/{name}) ``` -------------------------------- ### Fade Out Filter Construction Source: https://github.com/nklisch/ffmpeg-kit/blob/main/docs/designs/completed/design-phase-6.md Constructs a fade-out filter with duration, start time, and curve parameters. The start time is auto-calculated if not provided. ```text afade=t=out:d={duration}:st={startAt}:curve={curve} ``` -------------------------------- ### Use Default FFmpeg Instance Source: https://github.com/nklisch/ffmpeg-kit/blob/main/docs/ARCH.md Shows how to import and use the default FFmpeg instance, which automatically detects paths. ```typescript import { ffmpeg } from '@ffmpeg-sdk/core'; ``` -------------------------------- ### DASH Argument Generation Examples Source: https://github.com/nklisch/ffmpeg-kit/blob/main/docs/designs/completed/phase-8-subtitle-image-streaming-gif.md Illustrates how to generate specific DASH arguments using the DASH builder, covering default adaptation sets, segment duration, template/timeline usage, and single file output. ```javascript dash().input(v).output(o).toArgs() produces "-f dash" with default adaptation sets ``` ```javascript dash().input(v).segmentDuration(4).output(o).toArgs() produces "-seg_duration 4" ``` ```javascript dash().input(v).useTemplate(true).useTimeline(true).output(o).toArgs() produces "-use_template 1 -use_timeline 1" ``` ```javascript dash().input(v).singleFile(true).output(o).toArgs() produces "-single_file 1" ``` -------------------------------- ### Basic Batch Processing Example Source: https://github.com/nklisch/ffmpeg-kit/blob/main/docs/guide/batch.md Processes a list of video files, scaling each to 720p width concurrently. It logs the number of succeeded and failed items, and any errors encountered. ```typescript import { ffmpeg } from "ffmpeg-kit"; const result = await ffmpeg.batch({ items: ["a.mp4", "b.mp4", "c.mp4"], concurrency: 2, process: async (item) => { await ffmpeg.transform() .input(item) .scale({ width: 720 }) .output(item.replace(".mp4", "-720p.mp4")) .execute(); }, }); console.log(result.succeeded); // number of items that succeeded console.log(result.failed); // number of items that failed console.log(result.errors); // Map ``` -------------------------------- ### Pipeline with Multiple Steps and Placeholders Source: https://github.com/nklisch/ffmpeg-kit/blob/main/docs/guide/pipeline.md Illustrates a more complex pipeline involving normalization and audio processing, utilizing both `$tmp` for temporary files and `$prev` to reference previous step outputs. Ensure necessary functions like 'audio' are available. ```typescript await ffmpeg.pipeline() .step("normalize", (deps) => transform(deps).input("video.mp4").scale({ width: 1920 }).output("$tmp")) .step("audio", (deps) => audio(deps).input("$prev").normalize({ targetLUFS: -16 }).output("$tmp")) .step("export", (deps) => exportVideo(deps).input("$prev").preset("youtube_1080p").output("final.mp4")) .execute(); ``` -------------------------------- ### Validate FFmpeg Installation Source: https://github.com/nklisch/ffmpeg-kit/blob/main/docs/INTERFACE.md Checks if the FFmpeg binary is installed and accessible in the system's PATH using ffmpeg.validateInstallation. Ensures the SDK can execute FFmpeg commands. ```typescript await ffmpeg.validateInstallation(); ``` -------------------------------- ### Perform First Release Source: https://github.com/nklisch/ffmpeg-kit/blob/main/SETUP.md Use this command to bump the version, tag the release, and push changes. The CI will then publish to npm. ```bash pnpm release patch ``` -------------------------------- ### Validate FFmpeg Installation Source: https://github.com/nklisch/ffmpeg-kit/blob/main/docs/guide/instances.md Validates the FFmpeg installation by checking the versions of ffmpeg and ffprobe binaries and listing available codecs. It's recommended to call this at app startup. ```typescript import { validateInstallation } from "ffmpeg-kit"; const info = await validateInstallation({ ffmpegPath: "/usr/local/bin/ffmpeg", ffprobePath: "/usr/local/bin/ffprobe", }); console.log(info.ffmpegVersion); // "7.1.0" console.log(info.ffprobeVersion); // "7.1.0" console.log(info.codecs); // available codec list ``` -------------------------------- ### Waveform Rendering Example Source: https://github.com/nklisch/ffmpeg-kit/blob/main/docs/operations/waveform.md Renders a waveform on an HTML canvas using the extracted amplitude samples. This example demonstrates how to map sample data to canvas coordinates for visualization. ```typescript const result = await ffmpeg.waveform({ input: "podcast.mp3", fps: 20 }); // Canvas-based rendering example const canvas = document.querySelector("canvas"); const ctx = canvas.getContext("2d"); const { samples, duration } = result; const width = canvas.width; const height = canvas.height; const midY = height / 2; const stepX = width / samples.length; ctx.beginPath(); for (let i = 0; i < samples.length; i++) { const x = i * stepX; const amplitude = Math.abs(samples[i]) * midY; ctx.fillRect(x, midY - amplitude, stepX - 1, amplitude * 2); } ``` -------------------------------- ### Add Multiple Text Overlays to Video Source: https://github.com/nklisch/ffmpeg-kit/blob/main/docs/operations/text.md This example shows how to apply multiple text overlays to a video simultaneously. It includes a 'LIVE' indicator and a speaker name with different styling and positioning. ```typescript await ffmpeg.text() .input("video.mp4") .addText({ text: "LIVE", anchor: "top-right", margin: 20, style: { fontSize: 24, fontColor: "red", bold: true }, }) .addText({ text: "Speaker Name", anchor: "bottom-left", margin: 30, style: { fontSize: 32, fontColor: "white", box: true, boxColor: "black@0.6" }, }) .output("broadcast.mp4") .execute(); ``` -------------------------------- ### Set Trim Start and Duration for GIF Source: https://github.com/nklisch/ffmpeg-kit/blob/main/docs/designs/completed/phase-8-subtitle-image-streaming-gif.md Control the start time and duration of the GIF using `trimStart()` and `duration()`. This allows for precise segment selection from the input video. ```kotlin gif().input(v).trimStart(2).duration(3).output(o).toArgs() ``` -------------------------------- ### Create FFmpeg SDK Instance Source: https://github.com/nklisch/ffmpeg-kit/blob/main/docs/designs/completed/design-phase-11.md Creates an FFmpeg SDK instance with per-instance configuration. This allows for isolated settings for each SDK instance, including probe cache, hardware detection cache, and binary path configuration. ```typescript import { tmpdir } from "node:os"; import { join } from "node:path"; import { execute } from "./core/execute.ts"; import { probe, getDuration, getVideoStream, getAudioStream } from "./core/probe.ts"; import { validateInstallation } from "./core/validate.ts"; import { detectHardware } from "./hardware/detect.ts"; import { parseTimecode } from "./util/timecode.ts"; import { Cache } from "./util/cache.ts"; import { filter, chain, filterGraph } from "./filters/graph.ts"; import { extract } from "./operations/extract.ts"; import { transform } from "./operations/transform.ts"; import { audio } from "./operations/audio.ts"; import { concat } from "./operations/concat.ts"; import { exportVideo } from "./operations/export.ts"; import { overlay } from "./operations/overlay.ts"; import { text } from "./operations/text.ts"; import { subtitle } from "./operations/subtitle.ts"; import { image } from "./operations/image.ts"; import { hls, dash } from "./operations/streaming.ts"; import { gif } from "./operations/gif.ts"; import { pipeline } from "./convenience/pipeline.ts"; import { batch } from "./convenience/batch.ts"; import { smartTranscode } from "./convenience/smart.ts"; import { thumbnailSheet } from "./convenience/thumbnail-sheet.ts"; import { waveform } from "./convenience/waveform.ts"; import { detectSilence, trimSilence, splitOnSilence } from "./convenience/silence.ts"; import { estimateSize } from "./convenience/estimate.ts"; import { normalizeMedia } from "./convenience/normalize-media.ts"; import { remux, compress, extractAudio, imageToVideo, resize } from "./convenience/quick.ts"; import type { FFmpegConfig, FFmpegSDK, BuilderDeps } from "./types/sdk.ts"; import type { ProbeResult } from "./types/probe.ts"; import type { HardwareCapabilities } from "./hardware/detect.ts"; function createDeps(config?: FFmpegConfig): BuilderDeps { const ffmpegPath = config?.ffmpegPath ?? "ffmpeg"; const ffprobePath = config?.ffprobePath ?? "ffprobe"; const defaultTimeout = config?.defaultTimeout ?? 600_000; const logLevel = config?.logLevel ?? "error"; const tempDir = config?.tempDir ?? join(tmpdir(), "ffmpeg-kit"); const defaultHwAccel = config?.defaultHwAccel ?? "auto"; const probeCacheSize = config?.probeCacheSize ?? 100; const probeCacheTtl = config?.probeCacheTtl ?? 300_000; const probeCache = new Cache({ maxSize: Math.max(probeCacheSize, 1), ttlMs: probeCacheSize > 0 ? probeCacheTtl : 0, }); return { execute: (args, options) => execute( args, { timeout: defaultTimeout, logLevel, ...options }, { ffmpegPath }, ), probe: (inputPath, options) => probe(inputPath, options, { ffprobePath, cacheInstance: probeCache }), tempDir, defaultHwAccel, }; } /** * Create an FFmpeg SDK instance with per-instance configuration. * Each instance has its own probe cache, hardware detection cache, * and binary path configuration. */ export function createFFmpeg(config?: FFmpegConfig): FFmpegSDK { const deps = createDeps(config); const ffmpegPath = config?.ffmpegPath ?? "ffmpeg"; const ffprobePath = config?.ffprobePath ?? "ffprobe"; // Per-instance hardware detection cache const hwRef: { current: Promise | null } = { current: null }; // Per-instance probe cache ref (extract from deps.probe closure for clearing) // We create a new cache object in createDeps, so we hold a reference here. const probeCacheSize = config?.probeCacheSize ?? 100; const probeCacheTtl = config?.probeCacheTtl ?? 300_000; const probeCache = new Cache({ maxSize: Math.max(probeCacheSize, 1), ttlMs: probeCacheSize > 0 ? probeCacheTtl : 0, }); // Rebuild deps with our probeCache reference so we can clear it const finalDeps: BuilderDeps = { execute: deps.execute, probe: (inputPath, options) => probe(inputPath, options, { ffprobePath, cacheInstance: probeCache }), tempDir: deps.tempDir, defaultHwAccel: deps.defaultHwAccel, }; const sdk: FFmpegSDK = { // ── Core ── execute: finalDeps.execute, probe: finalDeps.probe, getDuration: async (path) => { const result = await finalDeps.probe(path); return result.format.duration ?? 0; }, getVideoStream: async (path) => { const result = await finalDeps.probe(path); return (result.streams.find((s) => s.type === "video") as import("./types/probe.ts").VideoStreamInfo) ?? null; }, getAudioStream: async (path) => { const result = await finalDeps.probe(path); return (result.streams.find((s) => s.type === "audio") as import("./types/probe.ts").AudioStreamInfo) ?? null; }, validateInstallation: () => validateInstallation({ ffmpegPath, ffprobePath }), clearProbeCache: () => { probeCache.clear(); hwRef.current = null; }, parseTimecode, ``` -------------------------------- ### Compare Helper vs Builder for Compression Source: https://github.com/nklisch/ffmpeg-kit/blob/main/docs/operations/quick.md Illustrates the difference between using a quick helper function for compression and the more detailed builder approach for greater control over export parameters. ```typescript // Helper — simple and fine for most cases await ffmpeg.compress("input.mp4", "output.mp4", { crf: 26 }); // Builder — when you need more control await ffmpeg.exportVideo() .input("input.mp4") .videoCodec("h264") .crf(26) .audioBitrate("192k") .pixelFormat("yuv420p") .faststart() .hwAccel("auto") .output("output.mp4") .execute(); ``` -------------------------------- ### Example of inconsistent builder return 'return builder' Source: https://github.com/nklisch/ffmpeg-kit/blob/main/docs/designs/completed/refactor-plan-2.md This example illustrates the 'return builder;' pattern that is being replaced for consistency. This pattern was used in several builder files before the standardization effort. ```typescript return builder; ``` -------------------------------- ### Trim Video Start and Duration Source: https://github.com/nklisch/ffmpeg-kit/blob/main/docs/designs/completed/phase-5-extract-transform.md Trims the video from a specified start time for a given duration. The `-ss` flag is placed before `-i` for faster seeking, and `-t` specifies the duration. ```javascript transform().input("v.mp4").trimStart(5).output("o.mp4").toArgs() ``` ```javascript transform().input("v.mp4").trimStart(5).duration(3).output("o.mp4").toArgs() ``` -------------------------------- ### FFmpegKit Build and Test Commands Source: https://github.com/nklisch/ffmpeg-kit/blob/main/docs/designs/completed/phase-8-subtitle-image-streaming-gif.md This bash script provides a comprehensive checklist for building and testing the FFmpegKit project. It includes commands for building the project, type checking, linting, generating fixtures, running builder tests, and executing end-to-end tests for various functionalities including GIFs. ```bash # Build succeeds pnpm build # Type check passes pnpm typecheck # Lint passes pnpm check # Generate new fixtures cd __tests__/fixtures && bash generate.sh # Run builder tests pnpm vitest run __tests__/builder/subtitle.test.ts pnpm vitest run __tests__/builder/image.test.ts pnpm vitest run __tests__/builder/streaming.test.ts pnpm vitest run __tests__/builder/gif.test.ts # Run E2E tests pnpm vitest run __tests__/integration/subtitle.e2e.test.ts pnpm vitest run __tests__/integration/image.e2e.test.ts pnpm vitest run __tests__/integration/streaming.e2e.test.ts pnpm vitest run __tests__/integration/gif.e2e.test.ts # Run all tests 3x for flakiness check pnpm test && pnpm test && pnpm test ``` -------------------------------- ### Build and Test Commands Source: https://github.com/nklisch/ffmpeg-kit/blob/main/docs/designs/completed/phase-4-hardware-encoding.md Provides bash commands for building, type checking, linting, and running unit and end-to-end tests for the project. Includes a command to run the full test suite multiple times to check for flakiness. ```bash # Build compiles with no errors pnpm build # Typecheck passes pnpm typecheck # Lint passes pnpm lint # All unit tests pass pnpm test:unit # All E2E tests pass (requires ffmpeg) pnpm test:e2e # Run full test suite 3x to verify no flakiness pnpm test && pnpm test && pnpm test ``` -------------------------------- ### Validate FFmpeg and FFprobe Installation Source: https://github.com/nklisch/ffmpeg-kit/blob/main/docs/designs/completed/phase-3-core-layer.md Validates that FFmpeg and FFprobe binaries are installed and accessible in the system's PATH or via provided paths. It checks their versions by executing `ffmpeg -version` and `ffprobe -version`. Throws an error if either binary is not found. ```typescript export interface InstallationInfo { ffmpeg: { path: string; version: string }; ffprobe: { path: string; version: string }; } /** * Validate that ffmpeg and ffprobe are installed and available. * * - Finds binaries in PATH (or uses provided paths) * - Runs `ffmpeg -version` and `ffprobe -version` to get version strings * - Throws FFmpegError with BINARY_NOT_FOUND if either is missing */ export function validateInstallation(config?: { ffmpegPath?: string; ffprobePath?: string; }): Promise; /** * Parse the version string from `ffmpeg -version` output. * e.g. "ffmpeg version 7.1.1 Copyright ..." → "7.1.1" * e.g. "ffmpeg version N-123456-g..." → "N-123456-g..." */ export function parseVersionString(output: string): string; ``` -------------------------------- ### Create Custom FFmpeg Instance Source: https://github.com/nklisch/ffmpeg-kit/blob/main/docs/designs/completed/phase-12-polish-publish.md Create a custom FFmpeg instance with specific configurations like FFmpeg path, temporary directory, timeout, and hardware acceleration. ```typescript import { createFFmpeg } from "ffmpeg-kit"; const ff = createFFmpeg({ ffmpegPath: "/usr/local/bin/ffmpeg", tempDir: "/tmp/my-app", defaultTimeout: 300_000, defaultHwAccel: "cpu", }); ``` -------------------------------- ### Trim Audio Source: https://github.com/nklisch/ffmpeg-kit/blob/main/docs/operations/audio.md Trims the audio to a specific start and end time. ```APIDOC ## .trim(options) ### Description Trims the audio to a specified duration. ### Method (Implicitly called within the audio chain) ### Parameters #### Request Body - **start** (number) - Required - Start time in seconds. - **end** (number) - Required - End time in seconds. ``` -------------------------------- ### getDefaultAudioCodec Source: https://github.com/nklisch/ffmpeg-kit/blob/main/docs/designs/completed/phase-4-hardware-encoding.md Get the default audio codec for a given container format. ```APIDOC ## getDefaultAudioCodec ### Description Returns the default audio codec for a specified container format. For example, "mp4" defaults to "aac", and "webm" defaults to "libopus". ### Method Signature `getDefaultAudioCodec(format: string): AudioCodec` ### Parameters #### Path Parameters - **format** (string) - Required - The container format (e.g., "mp4", "webm", "mkv"). ### Returns - **AudioCodec** - The default audio codec for the given container format. ``` -------------------------------- ### getCpuEncoder Source: https://github.com/nklisch/ffmpeg-kit/blob/main/docs/designs/completed/phase-4-hardware-encoding.md Get the CPU (software) encoder for a given codec family. ```APIDOC ## getCpuEncoder ### Description Retrieves the CPU (software) encoder for a specified codec family. ### Method Signature `getCpuEncoder(family: CodecFamily): VideoCodec` ### Parameters #### Path Parameters - **family** (CodecFamily) - Required - The codec family (e.g., "h264", "hevc"). ### Returns - **VideoCodec** - The name of the CPU encoder for the given codec family. ``` -------------------------------- ### Guaranteed Success with 'auto' Hardware Acceleration Source: https://github.com/nklisch/ffmpeg-kit/blob/main/docs/guide/hardware.md This example demonstrates how to use 'auto' hardware acceleration, which guarantees success by falling back to CPU if GPU encoding fails. ```typescript // This always succeeds on any machine — GPU if available, CPU otherwise const result = await ffmpeg.exportVideo() .input("video.mp4") .hwAccel("auto") .output("output.mp4") .execute(); ``` -------------------------------- ### Image to Video Implementation Example Source: https://github.com/nklisch/ffmpeg-kit/blob/main/docs/designs/completed/phase-10-convenience-layer.md Details the implementation of `imageToVideo`, which converts a still image into a video. It allows setting the duration and frame rate, and returns specific result fields. ```typescript image().input(input).toVideo({ duration: duration ?? 5, fps: fps ?? 30 }).output(output).execute() ``` -------------------------------- ### Get Media Duration Source: https://github.com/nklisch/ffmpeg-kit/blob/main/docs/INTERFACE.md Quickly retrieves the duration of a media file in seconds. ```APIDOC ## getDuration(inputPath: string) ### Description Quickly retrieves the duration of a media file in seconds. ### Parameters #### Path Parameters - **inputPath** (string) - Required - The path to the media file. ### Response #### Success Response - **duration** (number) - The duration of the media file in seconds. ### Response Example ```json 10.5 ``` ``` -------------------------------- ### Create a FilterGraphBuilder Source: https://github.com/nklisch/ffmpeg-kit/blob/main/docs/designs/completed/phase-9-filter-graph.md Instantiates a new FilterGraphBuilder object to start constructing filter graphs. ```typescript import { filterGraph } from "@ffmpeg-kits/core"; const builder = filterGraph(); ``` -------------------------------- ### Generate Test Fixture Source: https://github.com/nklisch/ffmpeg-kit/blob/main/docs/TESTING.md Generates a 5-second video and audio fixture using H.264 and AAC codecs. Ensure the total fixture size stays under 5 MB and is deterministically generatable. ```bash ffmpeg -f lavfi -i testsrc2=size=1920x1080:rate=30:duration=5 \ -f lavfi -i sine=frequency=440:duration=5:sample_rate=48000 \ -c:v libx264 -preset ultrafast -crf 23 -pix_fmt yuv420p \ -c:a aac -b:a 128k \ video-h264.mp4 ``` -------------------------------- ### Basic Text Overlay with Styling Source: https://github.com/nklisch/ffmpeg-kit/blob/main/docs/operations/text.md A quick example demonstrating the basic usage of adding a text overlay with specific text content, anchor point, margin, and styling including a background box with transparency. ```typescript import { ffmpeg } from "ffmpeg-kit"; await ffmpeg.text() .input("video.mp4") .addText({ text: "Hello World", anchor: "bottom-center", margin: 40, style: { fontSize: 48, fontColor: "white", box: true, boxColor: "black@0.5" }, startTime: 1, endTime: 5, }) .output("titled.mp4") .execute(); ``` -------------------------------- ### Get Current Platform Function Source: https://github.com/nklisch/ffmpeg-kit/blob/main/docs/designs/completed/phase-3-core-layer.md Declares a function to retrieve the current operating system platform. ```typescript /** Get the current platform */ export function getPlatform(): Platform; ``` -------------------------------- ### Create Multiple FFmpegKit Instances Source: https://github.com/nklisch/ffmpeg-kit/blob/main/docs/guide/instances.md Illustrates creating separate FFmpegKit instances for different use cases, such as a fast instance for thumbnails and a high-performance instance for exports. ```typescript // Fast instance for thumbnails const thumbnailFF = createFFmpeg({ defaultTimeout: 30_000, logLevel: "quiet", }); // Full-quality instance for exports const exportFF = createFFmpeg({ defaultTimeout: 3_600_000, // 1 hour defaultHwAccel: "auto", }); ``` -------------------------------- ### SilenceRange Interface Source: https://github.com/nklisch/ffmpeg-kit/blob/main/docs/designs/completed/phase-10-convenience-layer.md Represents a detected range of silence, specifying the start and end times and the duration of the silence. ```typescript /** Result from silence detection */ export interface SilenceRange { start: number; end: number; duration: number; } ``` -------------------------------- ### Create Custom FFmpegKit Instance Source: https://github.com/nklisch/ffmpeg-kit/blob/main/docs/guide/instances.md Instantiate FFmpegKit with custom paths, timeout, hardware acceleration, and log level. Use the created instance like the default singleton. ```typescript import { createFFmpeg } from "ffmpeg-kit"; const ff = createFFmpeg({ ffmpegPath: "/usr/local/bin/ffmpeg", ffprobePath: "/usr/local/bin/ffprobe", tempDir: "/tmp/my-app", defaultTimeout: 300_000, // 5 minutes (default: 10 minutes) defaultHwAccel: "auto", // default hardware acceleration mode logLevel: "warning", // ffmpeg log verbosity }); // Use exactly like the default ffmpeg singleton await ff.extract() .input("video.mp4") .timestamp(5) .output("frame.png") .execute(); ``` -------------------------------- ### VitePress Theme Import Source: https://github.com/nklisch/ffmpeg-kit/blob/main/docs/designs/completed/design-docs-site.md Imports the default VitePress theme and custom styles. This is a basic setup for the theme. ```typescript import DefaultTheme from "vitepress/theme"; import "./style.css"; export default DefaultTheme; ``` -------------------------------- ### Run End-to-End Tests Source: https://github.com/nklisch/ffmpeg-kit/blob/main/docs/designs/completed/phase-3-core-layer.md Execute end-to-end integration tests using pnpm. These tests require FFmpeg to be installed. ```bash pnpm test -- __tests__/integration/execute.e2e.test.ts ``` ```bash pnpm test -- __tests__/integration/probe.e2e.test.ts ``` ```bash pnpm test -- __tests__/integration/validate.e2e.test.ts ``` -------------------------------- ### FFmpegKit Build and Test Commands Source: https://github.com/nklisch/ffmpeg-kit/blob/main/docs/designs/completed/phase-5-extract-transform.md Provides essential bash commands for building FFmpegKit, running type checks, generating fixtures, executing builder and E2E tests, and linting the project. ```bash # Build pnpm build # Type check pnpm typecheck # Generate new fixture cd __tests__/fixtures && bash generate.sh # Run builder tests (Tier 1) pnpm vitest run __tests__/builder/extract.test.ts pnpm vitest run __tests__/builder/transform.test.ts # Run E2E tests (Tier 2) pnpm vitest run __tests__/integration/extract.e2e.test.ts pnpm vitest run __tests__/integration/transform.e2e.test.ts # Run all tests pnpm test # Lint pnpm check ``` -------------------------------- ### CreateFFmpegOptions Source: https://github.com/nklisch/ffmpeg-kit/blob/main/docs/api/types.md Options used when creating an FFmpeg instance, specifying paths, temporary directories, and default settings. ```APIDOC ## CreateFFmpegOptions ### Description Options for `createFFmpeg()`. These options configure the FFmpeg instance upon creation. ### Type Definition ```typescript interface CreateFFmpegOptions { ffmpegPath?: string; ffprobePath?: string; tempDir?: string; defaultTimeout?: number; defaultHwAccel?: HwAccelMode; logLevel?: FFmpegLogLevel; } ``` ### Fields - **ffmpegPath** (string, optional): Path to the FFmpeg executable. - **ffprobePath** (string, optional): Path to the FFprobe executable. - **tempDir** (string, optional): Directory for temporary files. - **defaultTimeout** (number, optional): Default timeout in milliseconds for operations. - **defaultHwAccel** (HwAccelMode, optional): Default hardware acceleration mode. - **logLevel** (FFmpegLogLevel, optional): Default logging level. ``` -------------------------------- ### Run Unit Tests Source: https://github.com/nklisch/ffmpeg-kit/blob/main/docs/designs/completed/phase-3-core-layer.md Execute specific unit tests using pnpm. These tests do not require FFmpeg to be installed. ```bash pnpm test -- __tests__/unit/timecode.test.ts ``` ```bash pnpm test -- __tests__/unit/cache.test.ts ``` ```bash pnpm test -- __tests__/unit/args.test.ts ``` ```bash pnpm test -- __tests__/unit/execute.test.ts ``` ```bash pnpm test -- __tests__/unit/validate.test.ts ``` -------------------------------- ### HLS Argument Generation Examples Source: https://github.com/nklisch/ffmpeg-kit/blob/main/docs/designs/completed/phase-8-subtitle-image-streaming-gif.md Demonstrates how to generate specific HLS arguments using the HLS builder, covering segment duration, segment type, playlist type, flags, codecs, bitrate, list size, and base URL. ```javascript hls().input(v).output(o).toArgs() produces "-f hls -hls_time 2 -hls_list_size 0" ``` ```javascript hls().input(v).segmentDuration(4).output(o).toArgs() produces "-hls_time 4" ``` ```javascript hls().input(v).segmentType('fmp4').output(o).toArgs() produces "-hls_segment_type fmp4 -hls_fmp4_init_filename init.mp4" ``` ```javascript hls().input(v).playlistType('vod').output(o).toArgs() produces "-hls_playlist_type vod" ``` ```javascript hls().input(v).flags(['independent_segments', 'program_date_time']).output(o).toArgs() produces "-hls_flags independent_segments+program_date_time" ``` ```javascript hls().input(v).videoCodec('libx264').crf(23).audioCodec('aac').audioBitrate('192k').output(o).toArgs() produces correct codec args ``` ```javascript hls().input(v).listSize(5).output(o).toArgs() produces "-hls_list_size 5" ``` ```javascript hls().input(v).baseUrl('https://cdn.example.com/').output(o).toArgs() produces "-hls_base_url" ``` -------------------------------- ### SilenceRegion Source: https://github.com/nklisch/ffmpeg-kit/blob/main/docs/api/types.md Defines a region of silence within an audio or video stream, including start and end times and duration. ```APIDOC ## SilenceRegion ### Description Defines a region of silence within an audio or video stream, specifying its start time, end time, and duration. ### Type Definition ```typescript interface SilenceRegion { start: number; end: number; duration: number; } ``` ### Fields - **start** (number): The start time of the silence region in seconds. - **end** (number): The end time of the silence region in seconds. - **duration** (number): The total duration of the silence region in seconds. ``` -------------------------------- ### Get Audio Stream Info Source: https://github.com/nklisch/ffmpeg-kit/blob/main/docs/INTERFACE.md Retrieves detailed information about the first audio stream found in a media file. ```APIDOC ## getAudioStream(inputPath: string) ### Description Retrieves detailed information about the first audio stream found in a media file. ### Parameters #### Path Parameters - **inputPath** (string) - Required - The path to the media file. ### Response #### Success Response - **AudioStreamInfo** - An object containing detailed audio stream properties, or null if no audio stream is found. ### Response Example ```json { "type": "audio", "index": 1, "codec": "aac", "codecLongName": "AAC (Advanced Audio Coding)", "profile": "LC", "sampleRate": 44100, "channels": 2, "channelLayout": "stereo", "sampleFormat": "fltp", "bitrate": 128000, "duration": 10.5, "disposition": { "default": true, "dub": false, "original": false, "comment": false, "lyrics": false, "karaoke": false, "forced": false, "hearingImpaired": false, "visualImpaired": false, "attachedPic": false }, "tags": { "language": "eng", "handler_name": "SoundHandler" } } ``` ```