### Deno Installation and Import Source: https://github.com/globaltechinfo/mediaforge/blob/main/README.md Shows how to install and import the mediaforge library in Deno using JSR. Ensure necessary runtime permissions are granted. ```typescript import { ffmpeg } from "jsr:@globaltech/mediaforge"; ``` -------------------------------- ### Install Mediaforge Source: https://context7.com/globaltechinfo/mediaforge/llms.txt Install the mediaforge package using npm, pnpm, yarn, or bun. ```bash npm install mediaforge ``` ```bash pnpm add mediaforge ``` ```bash yarn add mediaforge ``` ```bash bun add mediaforge ``` -------------------------------- ### Install MediaForge Package Source: https://github.com/globaltechinfo/mediaforge/wiki/Home Install the mediaforge npm package using npm. This command installs the library but requires FFmpeg to be installed separately on your system. ```bash npm install mediaforge ``` -------------------------------- ### Deno Installation and Import (npm compat) Source: https://github.com/globaltechinfo/mediaforge/blob/main/README.md Demonstrates importing the mediaforge library in Deno using npm compatibility mode. ```typescript import { ffmpeg } from "npm:mediaforge"; ``` -------------------------------- ### Show MediaForge Version Source: https://github.com/globaltechinfo/mediaforge/blob/main/README.md Displays the installed version of the MediaForge tool. ```bash mediaforge version ``` -------------------------------- ### Show MediaForge Version via CLI Source: https://github.com/globaltechinfo/mediaforge/wiki/Home Display the installed version of the MediaForge CLI tool. ```bash # Show version mediaforge version ``` -------------------------------- ### Probe Media File via CLI Source: https://github.com/globaltechinfo/mediaforge/wiki/Home Use the `mediaforge probe` command to get detailed information about a media file directly from the command line. ```bash # Probe a file mediaforge probe video.mp4 ``` -------------------------------- ### Importing and Basic FFmpeg Usage in TypeScript Source: https://github.com/globaltechinfo/mediaforge/blob/main/README.md Demonstrates how to import the ffmpeg function from the mediaforge library for both ESM and CJS environments. Shows a basic transcoding example with common video and audio settings. ```typescript import { ffmpeg } from 'mediaforge'; // ESM ✅ // or const { ffmpeg } = require('mediaforge'); // CJS ✅ await ffmpeg('input.mp4') .output('output.mp4') .videoCodec('libx264') .videoBitrate('2M') .audioCodec('aac') .audioBitrate('128k') .run(); ``` -------------------------------- ### Hardware Acceleration with VAAPI Source: https://github.com/globaltechinfo/mediaforge/blob/main/README.md Enable VAAPI (Intel/AMD on Linux) hardware acceleration. Specify the device path and use `vaapiToArgs` for encoding parameters. This example demonstrates encoding to H.264 using VAAPI. ```typescript import { ffmpeg } from 'mediaforge'; import { nvencToArgs, vaapiToArgs } from 'mediaforge'; // VAAPI (Intel/AMD on Linux) await ffmpeg('input.mp4') .hwAccel('vaapi', { device: '/dev/dri/renderD128' }) .output('output.mp4') .addOutputOption(...vaapiToArgs({}, 'h264_vaapi')) .run(); ``` -------------------------------- ### Transcoding Video with FFmpeg Source: https://github.com/globaltechinfo/mediaforge/blob/main/README.md Example of transcoding a video file using mediaforge, specifying video and audio codecs, bitrate, and output preset. Includes adding custom FFmpeg options. ```typescript import { ffmpeg } from 'mediaforge'; // Transcode video await ffmpeg('input.mp4') .output('output.mp4') .videoCodec('libx264') .crf(22) .addOutputOption('-preset', 'fast') .audioCodec('aac') .audioBitrate('128k') .run(); ``` -------------------------------- ### Generate Multiple Outputs in One Pass Source: https://github.com/globaltechinfo/mediaforge/wiki/Home This example shows how to create multiple output files with different settings (e.g., different resolutions and codecs) from a single input file in one FFmpeg process. ```typescript import { ffmpeg } from 'mediaforge'; // Multiple outputs in one pass await ffmpeg('input.mp4') .output('preview.mp4') .size('640x360') .videoCodec('libx264') .output('hq.mp4') .size('1920x1080') .videoCodec('libx264') .run(); ``` -------------------------------- ### Basic FFmpeg Transcoding with MediaForge Source: https://github.com/globaltechinfo/mediaforge/wiki/Home Use this snippet to transcode a video file to a different format with specified video and audio codecs and bitrates. Ensure FFmpeg is installed and accessible. ```typescript import { ffmpeg } from 'mediaforge'; await ffmpeg('input.mp4') .output('output.mp4') .videoCodec('libx264') .videoBitrate('2M') .audioCodec('aac') .audioBitrate('128k') .run(); ``` -------------------------------- ### Handle Progress Events Source: https://github.com/globaltechinfo/mediaforge/blob/main/README.md Enable progress reporting with `enableProgress()` and listen to events like 'start', 'progress', 'stderr', 'end', and 'error' on the spawned process emitter. ```typescript import { ffmpeg } from 'mediaforge'; const proc = ffmpeg('input.mp4') .output('output.mp4') .videoCodec('libx264') .enableProgress() .spawn({ parseProgress: true }); proc.emitter.on('start', (args) => console.log('Started:', args)); proc.emitter.on('progress', (info) => { console.log(`${info.percent?.toFixed(1)}% — fps: ${info.fps} — speed: ${info.speed}x`); }); proc.emitter.on('stderr', (line) => { /* raw stderr line */ }); proc.emitter.on('end', () => console.log('Done')); proc.emitter.on('error', (err) => console.error(err)); await new Promise((res, rej) => { proc.emitter.on('end', res); proc.emitter.on('error', rej); }); ``` -------------------------------- ### CLI File Probing Source: https://github.com/globaltechinfo/mediaforge/blob/main/README.md Use the `probe` command via the CLI to quickly get information about a media file. ```bash # Probe a file mediaforge probe video.mp4 ``` -------------------------------- ### Hardware Acceleration with NVENC Source: https://github.com/globaltechinfo/mediaforge/blob/main/README.md Configure NVENC (NVIDIA) hardware acceleration for video encoding. Use `hwAccel('cuda')` and `nvencToArgs` to specify encoding parameters like preset and quality. This example encodes to H.264 using NVENC. ```typescript import { ffmpeg } from 'mediaforge'; import { nvencToArgs, vaapiToArgs } from 'mediaforge'; // NVENC (NVIDIA) await ffmpeg('input.mp4') .hwAccel('cuda') .output('output.mp4') .addOutputOption(...nvencToArgs({ preset: 'p4', cq: 23 }, 'h264_nvenc')) .run(); ``` -------------------------------- ### Named Encoding Presets Source: https://context7.com/globaltechinfo/mediaforge/llms.txt Utilize production-ready codec configurations for common use cases by getting and applying named presets. ```APIDOC ## getPreset / applyPreset - Named Encoding Presets Use production-ready codec configurations for common use cases. ### List Available Presets ```typescript import { listPresets } from 'mediaforge'; console.log(listPresets()); // Expected output: ['web', 'web-hq', 'mobile', 'archive', 'podcast', 'hls-input', 'gif', 'discord', 'instagram', 'prores', 'dnxhd'] ``` ### Get and Apply Preset as Separate Argument Arrays ```typescript import { ffmpeg, getPreset } from 'mediaforge'; const p = getPreset('web'); await ffmpeg('input.mp4') .output('output.mp4') .addOutputOption(...p.videoArgs) .addOutputOption(...p.audioArgs) .addOutputOption(...p.extraArgs) .run(); ``` ### Apply Preset as a Flat Array ```typescript import { ffmpeg, applyPreset } from 'mediaforge'; await ffmpeg('input.mp4') .output('output.mp4') .addOutputOption(...applyPreset('web')) .run(); ``` ### Available Presets: - **'web'**: H.264 + AAC, browser-safe, fast seek. - **'web-hq'**: H.264 CRF 18 + AAC 192k, slow preset. - **'mobile'**: H.264 baseline + AAC, small file. - **'archive'**: Lossless H.264 (CRF 0) + FLAC. - **'podcast'**: Audio only, mono AAC 96k. - **'discord'**: Discord-friendly H.264 + AAC. - **'instagram'**: Instagram-compatible H.264 + AAC. - **'prores'**: ProRes 422 HQ + PCM for editing. - **'dnxhd'**: DNxHD 115 + PCM for editing. ``` -------------------------------- ### Get FFmpeg Chapter List Source: https://context7.com/globaltechinfo/mediaforge/llms.txt Retrieve a list of chapters from a media file using the `getChapterList` function, which returns chapter titles and their start/end times in seconds. ```typescript import { probe, getChapterList } from 'mediaforge'; const info = probe('video.mp4'); console.log(getChapterList(info)); // [{ title, startSec, endSec }] ``` -------------------------------- ### Build Complex Video Filter Chain Source: https://context7.com/globaltechinfo/mediaforge/llms.txt Utilize filter chain helpers to programmatically build complex video filter graphs. Use `chain.toString()` to get the final filter string for use with `ffmpeg`. ```typescript const chain = videoFilterChain(); scale(chain, { width: 1280, height: 720 }); crop(chain, { width: 640, height: 480, x: 100, y: 50 }); fade(chain, { type: 'in', start_time: 0, duration: 1 }); // Use chain.toString() to get filter string ``` -------------------------------- ### List MediaForge Capabilities via CLI Source: https://github.com/globaltechinfo/mediaforge/wiki/Home Query available codecs, filters, formats, and hardware acceleration methods using `mediaforge caps`. ```bash # List capabilities mediaforge caps --codecs mediaforge caps --filters mediaforge caps --formats mediaforge caps --hwaccels ``` -------------------------------- ### Deno Runtime Permissions Source: https://github.com/globaltechinfo/mediaforge/blob/main/README.md Illustrates the required command-line flags for running Deno scripts that utilize mediaforge, specifically for file access and process execution. ```bash deno run --allow-run --allow-write --allow-read my-script.ts ``` -------------------------------- ### List MediaForge Capabilities Source: https://github.com/globaltechinfo/mediaforge/blob/main/README.md Use these commands to list available codecs, filters, and formats supported by MediaForge. ```bash mediaforge caps --codecs ``` ```bash mediaforge caps --filters ``` ```bash mediaforge caps --formats ``` ```bash mediaforge caps --hwaccels ``` -------------------------------- ### Summarize FFmpeg Media Streams Source: https://context7.com/globaltechinfo/mediaforge/llms.txt Use `summarizeVideoStream` and `summarizeAudioStream` to get a concise, human-readable summary of stream properties. ```typescript import { probe, getVideoStreams, getAudioStreams, summarizeVideoStream, summarizeAudioStream, } from 'mediaforge'; const info = probe('video.mp4'); const videoStreams = getVideoStreams(info); const audioStreams = getAudioStreams(info); // Summarize streams for display const videoSummary = summarizeVideoStream(videoStreams[0]); // { codec: 'h264', width: 1920, height: 1080, fps: 30, bitrate: 4000000 } const audioSummary = summarizeAudioStream(audioStreams[0]); // { codec: 'aac', sampleRate: 48000, channels: 2, channelLayout: 'stereo' } ``` -------------------------------- ### Get FFmpeg Media Stream Information Source: https://context7.com/globaltechinfo/mediaforge/llms.txt Utilize helper functions like `getVideoStreams` and `getAudioStreams` to extract and work with specific media streams from FFprobe results. ```typescript import { probe, getVideoStreams, getAudioStreams, } from 'mediaforge'; const info = probe('video.mp4'); // Get stream helpers const videoStreams = getVideoStreams(info); const audioStreams = getAudioStreams(info); ``` -------------------------------- ### Create Streaming Packages Source: https://context7.com/globaltechinfo/mediaforge/llms.txt Generate HLS and DASH manifests and segments for adaptive bitrate streaming. ```typescript import { hlsPackage, adaptiveHls, dashPackage } from 'mediaforge'; // Single-bitrate HLS await hlsPackage({ input: 'input.mp4', outputDir: './hls-output', segmentDuration: 6, hlsVersion: 3, videoCodec: 'libx264', videoBitrate: '2M', audioBitrate: '128k', }).run(); // Multi-bitrate adaptive HLS await adaptiveHls({ input: 'input.mp4', outputDir: './hls-output', variants: [ { label: '1080p', resolution: '1920x1080', videoBitrate: '4M', audioBitrate: '192k' }, { label: '720p', resolution: '1280x720', videoBitrate: '2M', audioBitrate: '128k' }, { label: '480p', resolution: '854x480', videoBitrate: '800k', audioBitrate: '96k' }, ], }).run(); // DASH packaging await dashPackage({ input: 'input.mp4', output: './dash/manifest.mpd', segmentDuration: 4, videoCodec: 'libx264', videoBitrate: '2M', }).run(); ``` -------------------------------- ### Check Codec Availability and Select Best Codec Source: https://github.com/globaltechinfo/mediaforge/blob/main/README.md Demonstrates how to check if a specific codec is available for encoding and how to automatically select the best available video codec based on a prioritized list. ```typescript import { guardCodec, guardFeatureVersion, selectBestCodec } from 'mediaforge'; import { FFmpegBuilder } from 'mediaforge'; const builder = new FFmpegBuilder(); // Check codec availability const result = builder.checkCodec('libx264', 'encode'); if (!result.available) console.warn(result.reason); // Auto-select best codec const codec = await builder.selectVideoCodec([ { codec: 'h264_nvenc', featureKey: 'nvenc' }, { codec: 'h264_vaapi' }, { codec: 'libx264' }, // fallback ]); ``` -------------------------------- ### Apply Named Presets for Codec Configurations Source: https://github.com/globaltechinfo/mediaforge/blob/main/README.md Use named presets like 'web' or 'archive' to quickly apply production-ready codec settings. Presets can be applied as separate video and audio argument arrays or as a single flat array. Use `listPresets()` to see all available options. ```typescript import { getPreset, applyPreset, listPresets } from 'mediaforge'; // Get preset as separate arg arrays const p = getPreset('web'); await ffmpeg('input.mp4') .output('output.mp4') .addOutputOption(...p.videoArgs) .addOutputOption(...p.audioArgs) .run(); // Or as flat array await ffmpeg('input.mp4') .output('output.mp4') .addOutputOption(...applyPreset('web')) .run(); // List all available presets console.log(listPresets()); ``` -------------------------------- ### Transcode Media via CLI Source: https://github.com/globaltechinfo/mediaforge/wiki/Home Perform media transcoding using the `mediaforge` CLI tool. Specify input/output files, video/audio codecs, and bitrates. ```bash # Transcode mediaforge -i input.mp4 -c:v libx264 -b:v 2M -c:a aac output.mp4 ``` -------------------------------- ### DASH Packaging Source: https://github.com/globaltechinfo/mediaforge/blob/main/README.md Create a DASH (Dynamic Adaptive Streaming over HTTP) manifest and segments. Specify input file, output manifest path, segment duration, video codec, and bitrate. The library handles FFmpeg flag ordering for compatibility. ```typescript import { hlsPackage, adaptiveHls, dashPackage } from 'mediaforge'; // DASH await dashPackage({ input: 'input.mp4', output: 'output/manifest.mpd', segmentDuration: 4, videoCodec: 'libx264', videoBitrate: '2M', }).run(); ``` -------------------------------- ### Auto-Select Best Hardware Acceleration Source: https://github.com/globaltechinfo/mediaforge/blob/main/README.md Automatically select the best available hardware acceleration (e.g., CUDA, VAAPI, VideoToolbox) using `FFmpegBuilder.selectHwaccel()`. The selected acceleration is then applied using `hwAccel()`. ```typescript import { ffmpeg } from 'mediaforge'; import { nvencToArgs, vaapiToArgs } from 'mediaforge'; // Auto-select best available hardware const builder = new FFmpegBuilder('input.mp4'); const bestHw = builder.selectHwaccel(['cuda', 'vaapi', 'videotoolbox']); if (bestHw) builder.hwAccel(bestHw); ``` -------------------------------- ### Basic Transcoding with FFmpeg Builder Source: https://context7.com/globaltechinfo/mediaforge/llms.txt Use the ffmpeg builder to transcode a video file, specifying video and audio codecs and bitrates. Call .run() for synchronous execution. ```typescript import { ffmpeg } from 'mediaforge'; // Basic transcoding with video and audio codec settings await ffmpeg('input.mp4') .output('output.mp4') .videoCodec('libx264') .videoBitrate('2M') .crf(22) .audioCodec('aac') .audioBitrate('128k') .run(); ``` -------------------------------- ### Configure Hardware Acceleration Source: https://github.com/globaltechinfo/mediaforge/wiki/Home Enable hardware-accelerated encoding using NVENC or VAAPI, or auto-select the best available option. ```ts import { ffmpeg } from 'mediaforge'; import { nvencToArgs, vaapiToArgs } from 'mediaforge'; // NVENC (NVIDIA) await ffmpeg('input.mp4') .hwAccel('cuda') .output('output.mp4') .addOutputOption(...nvencToArgs({ preset: 'p4', cq: 23 }, 'h264_nvenc')) .run(); // VAAPI (Intel/AMD on Linux) await ffmpeg('input.mp4') .hwAccel('vaapi', { device: '/dev/dri/renderD128' }) .output('output.mp4') .addOutputOption(...vaapiToArgs({}, 'h264_vaapi')) .run(); // Auto-select best available hardware const builder = new FFmpegBuilder('input.mp4'); const bestHw = builder.selectHwaccel(['cuda', 'vaapi', 'videotoolbox']); if (bestHw) builder.hwAccel(bestHw); ``` -------------------------------- ### Apply Simple Video Filter with Builder Source: https://context7.com/globaltechinfo/mediaforge/llms.txt Use the fluent builder to apply a single video filter like scaling. Ensure the input and output file paths are correctly specified. ```typescript import { ffmpeg, scale, crop, overlay, drawtext, fade } from 'mediaforge'; import { videoFilterChain } from 'mediaforge'; // Simple filter via builder await ffmpeg('input.mp4') .output('output.mp4') .videoFilter('scale=1280:720') .run(); ``` -------------------------------- ### Generate Audio Visualizations Source: https://context7.com/globaltechinfo/mediaforge/llms.txt Create static waveform images or dynamic spectrum videos from media files. ```typescript import { generateWaveform, generateSpectrum } from 'mediaforge'; // Waveform image from audio await generateWaveform({ input: 'audio.mp3', output: 'waveform.png', width: 1920, height: 240, color: '#00aaff', backgroundColor: '#1a1a2e', mode: 'line', // 'line' | 'point' | 'p2p' | 'cline' scale: 'lin', // 'lin' | 'log' }); // Real-time spectrum visualizer video await generateSpectrum({ input: 'podcast.mp3', output: 'spectrum.mp4', width: 1280, height: 720, color: 'fire', fps: 25, }); ``` -------------------------------- ### Asynchronous FFprobe Source: https://github.com/globaltechinfo/mediaforge/wiki/Home Perform an asynchronous probe of media file information using `probeAsync`. This is recommended for non-blocking operations. ```typescript import { probeAsync } from 'mediaforge'; // Async probe const info = await probeAsync('video.mp4'); ``` -------------------------------- ### Fluent Builder API Source: https://github.com/globaltechinfo/mediaforge/wiki/Home The core API for constructing FFmpeg commands using a chainable builder pattern. ```APIDOC ## Fluent Builder API ### Description The Fluent Builder API allows for the construction of complex FFmpeg commands by chaining methods. Each method returns the builder instance, allowing for sequential configuration of inputs, outputs, codecs, and filters. ### Methods - **.input(path, opts?)** - Adds an input file. - **.output(path, opts?)** - Adds an output file. Must be called before codec or filter options. - **.videoCodec(codec)** - Sets the video codec (e.g., libx264, libx265, copy). - **.videoBitrate(rate)** - Sets the video bitrate (e.g., 2M, 4000k). - **.audioCodec(codec)** - Sets the audio codec (e.g., aac, libopus, copy). - **.audioBitrate(rate)** - Sets the audio bitrate (e.g., 128k, 192k). - **.size(wxh)** - Sets the output resolution (e.g., 1280x720). - **.crf(value)** - Sets the Constant Rate Factor for quality. - **.run(opts?)** - Executes the constructed command and returns a Promise. ### Request Example ```ts await ffmpeg('input.mp4') .output('output.mp4') .videoCodec('libx264') .crf(22) .audioCodec('aac') .run(); ``` ``` -------------------------------- ### Asynchronous FFprobe Media Analysis Source: https://context7.com/globaltechinfo/mediaforge/llms.txt Use the `probeAsync` function for non-blocking media file analysis, suitable for server environments. It returns a Promise resolving to the media information. ```typescript import { probeAsync } from 'mediaforge'; // Async probe for server environments const asyncInfo = await probeAsync('video.mp4'); ``` -------------------------------- ### Hardware Acceleration Source: https://context7.com/globaltechinfo/mediaforge/llms.txt Enable GPU-accelerated encoding with NVENC, VAAPI, VideoToolbox, and QSV. ```APIDOC ## Hardware Acceleration Enable GPU-accelerated encoding with NVENC, VAAPI, VideoToolbox, and QSV. ### NVIDIA NVENC ```typescript import { ffmpeg, nvencToArgs } from 'mediaforge'; await ffmpeg('input.mp4') .hwAccel('cuda') .output('output.mp4') .addOutputOption(...nvencToArgs({ preset: 'p4', cq: 23 }, 'h264_nvenc')) .run(); ``` ### Intel/AMD VAAPI (Linux) ```typescript import { ffmpeg, vaapiToArgs } from 'mediaforge'; await ffmpeg('input.mp4') .hwAccel('vaapi', { device: '/dev/dri/renderD128' }) .output('output.mp4') .addOutputOption(...vaapiToArgs({}, 'h264_vaapi')) .run(); ``` ### Auto-select Best Available Hardware ```typescript import { FFmpegBuilder } from 'mediaforge'; const builder = new FFmpegBuilder('input.mp4'); const bestHw = builder.selectHwaccel(['cuda', 'vaapi', 'videotoolbox']); if (bestHw) builder.hwAccel(bestHw); // Select best codec with fallback const codec = await builder.selectVideoCodec([ { codec: 'h264_nvenc', featureKey: 'nvenc' }, { codec: 'h264_vaapi' }, { codec: 'libx264' }, // CPU fallback ]); builder.output('out.mp4').videoCodec(codec ?? 'libx264'); await builder.run(); ``` ``` -------------------------------- ### Bun Usage Source: https://github.com/globaltechinfo/mediaforge/blob/main/README.md Use MediaForge in Bun projects with the same API as Node.js by importing directly from the 'mediaforge' package. ```typescript // Bun — same API as Node.js import { ffmpeg } from "mediaforge"; await ffmpeg("input.mp4") .output("output.mp4") .videoCodec("libx264") .run(); ``` -------------------------------- ### Audio Visualization Source: https://context7.com/globaltechinfo/mediaforge/llms.txt Generate waveform images and spectrum visualizer videos from audio/video files. ```APIDOC ## generateWaveform / generateSpectrum - Audio Visualization Generate waveform images and spectrum visualizer videos from audio/video files. ### Generate Waveform Image ```typescript import { generateWaveform } from 'mediaforge'; await generateWaveform({ input: 'audio.mp3', output: 'waveform.png', width: 1920, height: 240, color: '#00aaff', backgroundColor: '#1a1a2e', mode: 'line', // 'line' | 'point' | 'p2p' | 'cline' scale: 'lin', // 'lin' | 'log' }); ``` ### Generate Spectrum Visualizer Video ```typescript import { generateSpectrum } from 'mediaforge'; await generateSpectrum({ input: 'podcast.mp3', output: 'spectrum.mp4', width: 1280, height: 720, color: 'fire', fps: 25, }); ``` ``` -------------------------------- ### ffmpeg - Core Fluent Builder API Source: https://context7.com/globaltechinfo/mediaforge/llms.txt The primary entry point for configuring and executing FFmpeg operations such as transcoding, streaming, and metadata manipulation. ```APIDOC ## ffmpeg(input) ### Description Creates a chainable builder for configuring inputs, outputs, codecs, and filters. Use .run() for synchronous execution or .spawn() for event-based control. ### Parameters - **input** (string) - Required - The path to the input media file. ### Methods - **output(path)**: Sets the output file path. - **videoCodec(codec)**: Sets the video codec (e.g., 'libx264'). - **videoBitrate(bitrate)**: Sets the video bitrate. - **crf(value)**: Sets the Constant Rate Factor. - **audioCodec(codec)**: Sets the audio codec. - **audioBitrate(bitrate)**: Sets the audio bitrate. - **size(dimensions)**: Sets the output resolution (e.g., '640x360'). - **noVideo()**: Disables video stream in output. - **seekInput(time)**: Sets the input seek time. - **inputDuration(seconds)**: Sets the duration limit for the input. - **run()**: Executes the FFmpeg command synchronously. ``` -------------------------------- ### probe / probeAsync - FFprobe Integration Source: https://context7.com/globaltechinfo/mediaforge/llms.txt Functions to analyze media files and retrieve detailed stream, format, and codec information. ```APIDOC ## probe(input) / probeAsync(input) ### Description Analyzes media files using FFprobe to return typed information about streams, formats, and duration. ### Parameters - **input** (string) - Required - The path to the media file. ### Helpers - **getVideoStreams(info)**: Extracts video streams from probe data. - **getAudioStreams(info)**: Extracts audio streams from probe data. - **getMediaDuration(info)**: Returns the media duration in seconds. - **summarizeVideoStream(stream)**: Returns a summary object of video stream properties. - **summarizeAudioStream(stream)**: Returns a summary object of audio stream properties. - **isHdr(info)**: Checks if the media is HDR. - **isInterlaced(info)**: Checks if the media is interlaced. - **getChapterList(info)**: Returns a list of chapters. ``` -------------------------------- ### Configure Hardware Acceleration Source: https://context7.com/globaltechinfo/mediaforge/llms.txt Utilize GPU-based encoding via NVENC, VAAPI, or auto-detection builders to optimize performance. ```typescript import { ffmpeg, nvencToArgs, vaapiToArgs } from 'mediaforge'; import { FFmpegBuilder } from 'mediaforge'; // NVIDIA NVENC await ffmpeg('input.mp4') .hwAccel('cuda') .output('output.mp4') .addOutputOption(...nvencToArgs({ preset: 'p4', cq: 23 }, 'h264_nvenc')) .run(); // Intel/AMD VAAPI (Linux) await ffmpeg('input.mp4') .hwAccel('vaapi', { device: '/dev/dri/renderD128' }) .output('output.mp4') .addOutputOption(...vaapiToArgs({}, 'h264_vaapi')) .run(); // Auto-select best available hardware const builder = new FFmpegBuilder('input.mp4'); const bestHw = builder.selectHwaccel(['cuda', 'vaapi', 'videotoolbox']); if (bestHw) builder.hwAccel(bestHw); // Select best codec with fallback const codec = await builder.selectVideoCodec([ { codec: 'h264_nvenc', featureKey: 'nvenc' }, { codec: 'h264_vaapi' }, { codec: 'libx264' }, // CPU fallback ]); builder.output('out.mp4').videoCodec(codec ?? 'libx264'); await builder.run(); ``` -------------------------------- ### Deno Usage with JSR Source: https://github.com/globaltechinfo/mediaforge/blob/main/README.md Import MediaForge modules from JSR for Deno projects. Ensure necessary permissions are granted for running external processes and file access. ```typescript // Deno — import from JSR import { ffmpeg, probe, screenshots } from "jsr:@globaltech/mediaforge"; // Transcode (requires --allow-run=ffmpeg --allow-read --allow-write) await ffmpeg("input.mp4") .output("output.mp4") .videoCodec("libx264") .audioBitrate("128k") .run(); // Probe a file const info = probe("video.mp4"); console.log(info.format?.duration); // Screenshots const { files } = await screenshots({ input: "video.mp4", folder: "./thumbs", count: 5 }); ``` ```bash deno run --allow-run=ffmpeg,ffprobe --allow-read --allow-write your-script.ts ``` -------------------------------- ### Multiple Outputs in One FFmpeg Pass Source: https://github.com/globaltechinfo/mediaforge/blob/main/README.md Shows how to configure mediaforge to generate multiple output files with different settings (e.g., resolutions, codecs) from a single input file in one FFmpeg process. ```typescript // Multiple outputs in one pass await ffmpeg('input.mp4') .output('preview.mp4') .size('640x360') .videoCodec('libx264') .output('hq.mp4') .size('1920x1080') .videoCodec('libx264') .run(); ``` -------------------------------- ### Apply Encoding Presets with MediaForge Source: https://context7.com/globaltechinfo/mediaforge/llms.txt Use predefined codec configurations for common output formats. Presets can be retrieved as argument arrays or applied directly to the output. ```typescript import { ffmpeg, getPreset, applyPreset, listPresets } from 'mediaforge'; // List available presets console.log(listPresets()); // ['web', 'web-hq', 'mobile', 'archive', 'podcast', 'hls-input', 'gif', 'discord', 'instagram', 'prores', 'dnxhd'] // Get preset as separate arg arrays const p = getPreset('web'); await ffmpeg('input.mp4') .output('output.mp4') .addOutputOption(...p.videoArgs) .addOutputOption(...p.audioArgs) .addOutputOption(...p.extraArgs) .run(); // Or apply preset as flat array await ffmpeg('input.mp4') .output('output.mp4') .addOutputOption(...applyPreset('web')) .run(); // Available presets: // 'web' - H.264 + AAC, browser-safe, fast seek // 'web-hq' - H.264 CRF 18 + AAC 192k, slow preset // 'mobile' - H.264 baseline + AAC, small file // 'archive' - Lossless H.264 (CRF 0) + FLAC // 'podcast' - Audio only, mono AAC 96k // 'discord' - Discord-friendly H.264 + AAC // 'instagram' - Instagram-compatible H.264 + AAC // 'prores' - ProRes 422 HQ + PCM for editing // 'dnxhd' - DNxHD 115 + PCM for editing ``` -------------------------------- ### Multiple Outputs in Single FFmpeg Pass Source: https://context7.com/globaltechinfo/mediaforge/llms.txt Configure multiple output files with different settings in a single FFmpeg command using the fluent builder API. ```typescript import { ffmpeg } from 'mediaforge'; // Multiple outputs in a single pass await ffmpeg('input.mp4') .output('preview.mp4') .size('640x360') .videoCodec('libx264') .output('hq.mp4') .size('1920x1080') .videoCodec('libx264') .run(); ``` -------------------------------- ### Probe Media File Information Source: https://github.com/globaltechinfo/mediaforge/blob/main/README.md Use `probe` for synchronous or `probeAsync` for asynchronous media file analysis. Helper functions are available to extract specific details like streams, duration, and summaries. ```typescript import { probe, probeAsync, ProbeError, getVideoStreams, getAudioStreams, getDefaultVideoStream, getDefaultAudioStream, getMediaDuration, durationToMicroseconds, summarizeVideoStream, summarizeAudioStream, parseFrameRate, parseDuration, parseBitrate, isHdr, isInterlaced, getChapterList, findStreamByLanguage, formatDuration, } from 'mediaforge'; // Synchronous probe const info = probe('video.mp4'); console.log(info.format?.duration); // "120.042000" console.log(info.streams[0]?.codec_name); // "h264" // Async probe const info = await probeAsync('video.mp4'); // Helpers const videoStreams = getVideoStreams(info); const audioStreams = getAudioStreams(info); const duration = getMediaDuration(info); // seconds const us = durationToMicroseconds(duration!); // microseconds const videoSummary = summarizeVideoStream(getDefaultVideoStream(info)!); // { codec: 'h264', width: 1920, height: 1080, fps: 30, bitrate: 4000000, ... } console.log(isHdr(info)); // true/false console.log(isInterlaced(info)); // true/false console.log(getChapterList(info)); // [{ title, startSec, endSec }] const engAudio = findStreamByLanguage(info, 'eng', 'audio'); ``` -------------------------------- ### Extracting Audio Only with FFmpeg Source: https://github.com/globaltechinfo/mediaforge/blob/main/README.md Demonstrates how to use mediaforge to extract only the audio stream from a video file, disabling video output and specifying audio codec and bitrate. ```typescript // Extract audio only await ffmpeg('video.mp4') .output('audio.mp3') .noVideo() .audioCodec('libmp3lame') .audioBitrate('192k') .run(); ``` -------------------------------- ### CLI Transcoding Source: https://github.com/globaltechinfo/mediaforge/blob/main/README.md Transcode media files using the command-line interface by specifying input, output, and codec options. ```bash # Transcode mediaforge -i input.mp4 -c:v libx264 -b:v 2M -c:a aac output.mp4 ``` -------------------------------- ### Utilize FFprobe Helper Functions Source: https://github.com/globaltechinfo/mediaforge/wiki/Home Extract specific media information using helper functions like `getVideoStreams`, `getAudioStreams`, `getMediaDuration`, and `summarizeVideoStream`. ```typescript import { getVideoStreams, getAudioStreams, getDefaultVideoStream, getDefaultAudioStream, getMediaDuration, durationToMicroseconds, summarizeVideoStream, summarizeAudioStream, parseFrameRate, parseDuration, parseBitrate, isHdr, isInterlaced, getChapterList, findStreamByLanguage, } from 'mediaforge'; // Helpers const videoStreams = getVideoStreams(info); const audioStreams = getAudioStreams(info); const duration = getMediaDuration(info); // seconds const us = durationToMicroseconds(duration!); // microseconds const videoSummary = summarizeVideoStream(getDefaultVideoStream(info)!); // { codec: 'h264', width: 1920, height: 1080, fps: 30, bitrate: 4000000, ... } console.log(isHdr(info)); // true/false console.log(isInterlaced(info)); // true/false console.log(getChapterList(info)); // [{ title, startSec, endSec }] const engAudio = findStreamByLanguage(info, 'eng', 'audio'); ``` -------------------------------- ### Pipe and Stream Media I/O Source: https://github.com/globaltechinfo/mediaforge/blob/main/README.md Handle media streams using pipeThrough, streamOutput, or streamToFile. Automatic flags are injected for MP4/MOV formats to ensure streamability. ```ts import { pipeThrough, streamOutput, streamToFile } from 'mediaforge'; import fs from 'fs'; // Pipe: readable stream → ffmpeg → writable stream // When outputFormat is 'mp4' or 'mov', the library automatically injects // -movflags frag_keyframe+empty_moov+default_base_moof so the output is // streamable without seeking. You do not need to set this manually. const proc = pipeThrough({ inputFormat: 'webm', outputArgs: ['-c:v', 'libx264', '-c:a', 'aac'], outputFormat: 'mp4', }); fs.createReadStream('input.webm').pipe(proc.stdin!); proc.stdout.pipe(fs.createWriteStream('output.mp4')); await new Promise((res, rej) => { proc.emitter.on('end', res); proc.emitter.on('error', rej); }); // Stream output to HTTP response import http from 'http'; http.createServer((req, res) => { res.setHeader('Content-Type', 'video/mp4'); streamOutput({ input: 'movie.mp4', outputFormat: 'mp4', outputArgs: ['-c', 'copy', '-movflags', 'frag_keyframe+empty_moov'], }).pipe(res); }).listen(3000); // Pipe incoming HTTP upload directly to file await streamToFile({ stream: req, // Node.js IncomingMessage inputFormat: 'webm', output: './uploads/video.mp4', outputArgs: ['-c:v', 'libx264', '-c:a', 'aac'], }); ``` -------------------------------- ### Streaming Packages API Source: https://context7.com/globaltechinfo/mediaforge/llms.txt APIs for creating HLS and DASH streaming packages for adaptive bitrate delivery. ```APIDOC ## POST /hlsPackage ### Description Creates a single-bitrate HLS streaming package. ### Method POST ### Endpoint /hlsPackage ### Parameters #### Request Body - **input** (string) - Required - Path to the input media file. - **outputDir** (string) - Required - Directory to save the HLS segments and manifest. - **segmentDuration** (number) - Optional - Duration of each HLS segment in seconds. Defaults to 6. - **hlsVersion** (number) - Optional - HLS protocol version. Defaults to 3. - **videoCodec** (string) - Optional - Video codec to use for encoding. Defaults to 'libx264'. - **videoBitrate** (string) - Optional - Target video bitrate (e.g., '2M'). - **audioBitrate** (string) - Optional - Target audio bitrate (e.g., '128k'). ### Request Example ```json { "input": "input.mp4", "outputDir": "./hls-output", "segmentDuration": 6, "hlsVersion": 3, "videoCodec": "libx264", "videoBitrate": "2M", "audioBitrate": "128k" } ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message. #### Response Example ```json { "message": "HLS package created successfully." } ``` ## POST /adaptiveHls ### Description Creates a multi-bitrate adaptive HLS streaming package. ### Method POST ### Endpoint /adaptiveHls ### Parameters #### Request Body - **input** (string) - Required - Path to the input media file. - **outputDir** (string) - Required - Directory to save the HLS segments and manifest. - **variants** (array) - Required - An array of variant stream configurations. - **label** (string) - Required - A human-readable label for the variant (e.g., '1080p'). - **resolution** (string) - Required - The resolution of the variant (e.g., '1920x1080'). - **videoBitrate** (string) - Required - Target video bitrate for this variant (e.g., '4M'). - **audioBitrate** (string) - Required - Target audio bitrate for this variant (e.g., '192k'). ### Request Example ```json { "input": "input.mp4", "outputDir": "./hls-output", "variants": [ { "label": "1080p", "resolution": "1920x1080", "videoBitrate": "4M", "audioBitrate": "192k" }, { "label": "720p", "resolution": "1280x720", "videoBitrate": "2M", "audioBitrate": "128k" }, { "label": "480p", "resolution": "854x480", "videoBitrate": "800k", "audioBitrate": "96k" } ] } ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message. #### Response Example ```json { "message": "Adaptive HLS package created successfully." } ``` ## POST /dashPackage ### Description Creates a DASH (Dynamic Adaptive Streaming over HTTP) streaming package. ### Method POST ### Endpoint /dashPackage ### Parameters #### Request Body - **input** (string) - Required - Path to the input media file. - **output** (string) - Required - Path for the output DASH manifest file (e.g., 'manifest.mpd'). - **segmentDuration** (number) - Optional - Duration of each DASH segment in seconds. Defaults to 4. - **videoCodec** (string) - Optional - Video codec to use for encoding. Defaults to 'libx264'. - **videoBitrate** (string) - Optional - Target video bitrate (e.g., '2M'). ### Request Example ```json { "input": "input.mp4", "output": "./dash/manifest.mpd", "segmentDuration": 4, "videoCodec": "libx264", "videoBitrate": "2M" } ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message. #### Response Example ```json { "message": "DASH package created successfully." } ``` ``` -------------------------------- ### Single-Bitrate HLS Packaging Source: https://github.com/globaltechinfo/mediaforge/blob/main/README.md Create a single-bitrate HLS stream from an input file. Specify output directory, segment duration, HLS version, and video/audio bitrates. Ensure `hlsVersion` and other `hls_*` flags follow `-f hls` for FFmpeg 7.x compatibility. ```typescript import { hlsPackage, adaptiveHls, dashPackage } from 'mediaforge'; // Single-bitrate HLS await hlsPackage({ input: 'input.mp4', outputDir: './hls-output', segmentDuration: 6, hlsVersion: 3, // 3 | 4 | 5 | 6 | 7 — default: 3 videoCodec: 'libx264', videoBitrate: '2M', audioBitrate: '128k', }).run(); ``` -------------------------------- ### Package HLS and DASH Source: https://github.com/globaltechinfo/mediaforge/wiki/Home Generate adaptive streaming manifests and segments for HLS and DASH delivery. ```ts import { hlsPackage, adaptiveHls, dashPackage } from 'mediaforge'; // Single-bitrate HLS await hlsPackage({ input: 'input.mp4', outputDir: './hls-output', segmentDuration: 6, videoCodec: 'libx264', videoBitrate: '2M', audioBitrate: '128k', }).run(); // Adaptive HLS (multiple bitrates) await adaptiveHls({ input: 'input.mp4', outputDir: './hls-output', variants: [ { label: '1080p', resolution: '1920x1080', videoBitrate: '4M', audioBitrate: '192k' }, { label: '720p', resolution: '1280x720', videoBitrate: '2M', audioBitrate: '128k' }, { label: '360p', resolution: '854x480', videoBitrate: '800k', audioBitrate: '96k' }, ], }).run(); // DASH await dashPackage({ input: 'input.mp4', output: 'output/manifest.mpd', segmentDuration: 4, videoCodec: 'libx264', videoBitrate: '2M', }).run(); ``` -------------------------------- ### Build Audio Filter Chain with Helpers Source: https://context7.com/globaltechinfo/mediaforge/llms.txt Construct audio filter chains using helper functions for filters like loudnorm, equalizer, and bass. The `chain.toString()` method retrieves the filter string. ```typescript const chain = audioFilterChain(); loudnorm(chain, { i: -16, lra: 11, tp: -1.5 }); equalizer(chain, { frequency: 1000, width: 1, gain: 3 }); bass(chain, { gain: 6, frequency: 100 }); highpass(chain, 80); // Remove rumble below 80Hz // Use chain.toString() to get filter string ``` -------------------------------- ### Synchronous FFprobe Source: https://github.com/globaltechinfo/mediaforge/wiki/Home Perform a synchronous probe of media file information. Access format details and stream information directly from the returned object. ```typescript import { probe } from 'mediaforge'; // Synchronous probe const info = probe('video.mp4'); console.log(info.format?.duration); // "120.042000" console.log(info.streams[0]?.codec_name); // "h264" ``` -------------------------------- ### Monitor FFmpeg Progress Events Source: https://github.com/globaltechinfo/mediaforge/wiki/Home Enable and listen to progress events from FFmpeg using `enableProgress` and the `emitter`. Parse progress information for real-time feedback. ```typescript import { ffmpeg } from 'mediaforge'; const proc = ffmpeg('input.mp4') .output('output.mp4') .videoCodec('libx264') .enableProgress() .spawn({ parseProgress: true }); proc.emitter.on('start', (args) => console.log('Started:', args)); proc.emitter.on('progress', (info) => { console.log(`${info.percent?.toFixed(1)}% — fps: ${info.fps} — speed: ${info.speed}x`); }); proc.emitter.on('stderr', (line) => { /* raw stderr line */ }); proc.emitter.on('end', () => console.log('Done')); proc.emitter.on('error', (err) => console.error(err)); await new Promise((res, rej) => { proc.emitter.on('end', res); proc.emitter.on('error', rej); }); ```