### FFmpeg-Static Installation Flow Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/INDEX.md Details the steps involved in the npm installation of ffmpeg-static, including binary download and setup. ```text npm install ffmpeg-static ↓ npm lifecycle hook → node install.js ├─ Detect platform ├─ Download binary (GitHub releases) ├─ Decompress (.gz) ├─ Set permissions ├─ Download metadata └─ Exit (0 = success, 1 = failure) ↓ Binary stored in node_modules/ffmpeg-static/ ``` -------------------------------- ### Install 32-bit Binary on 64-bit System Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/configuration.md Install a 32-bit ffmpeg binary on a 64-bit system by specifying the architecture during installation. ```bash npm install ffmpeg-static --npm_config_arch=ia32 ``` -------------------------------- ### Installation Flow Diagram Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/source-structure.md Illustrates the sequence of operations when installing the ffmpeg-static package via npm. ```text npm install ffmpeg-static ↓ npm lifecycle hook "install" ↓ node install.js ├─ Validate platform/arch ├─ Check pre-existing binary ├─ Setup proxy (if configured) ├─ Setup cache ├─ Download ffmpeg binary (from GitHub releases) ├─ Set permissions (POSIX) ├─ Download README (optional) ├─ Download LICENSE (optional) └─ Exit (status 0 or 1) ``` -------------------------------- ### Example Download URLs Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/installation-process.md Provides example URLs for downloading the FFmpeg binary, README, and LICENSE files for the 'linux-x64' platform. ```text https://github.com/eugeneware/ffmpeg-static/releases/download/b4.4/linux-x64.gz https://github.com/eugeneware/ffmpeg-static/releases/download/b4.4/linux-x64.README https://github.com/eugeneware/ffmpeg-static/releases/download/b4.4/linux-x64.LICENSE ``` -------------------------------- ### Supported Binaries Usage Example Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/types.md Example demonstrating how to check if the current platform and architecture are supported by the ffmpeg-static module using the binaries mapping. ```javascript const binaries = { darwin: ['x64', 'arm64'], freebsd: ['x64'], linux: ['x64', 'ia32', 'arm64', 'arm'], win32: ['x64', 'ia32'] }; const platform = process.platform; // e.g., 'linux' const arch = process.arch; // e.g., 'x64' const isSupported = binaries[platform] && binaries[platform].indexOf(arch) !== -1; console.log(isSupported); // true or false ``` -------------------------------- ### Proxy Setup for Installation Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/INDEX.md Configure npm to use a proxy server for downloading packages, such as ffmpeg-static, by setting HTTP_PROXY and HTTPS_PROXY environment variables. ```bash HTTP_PROXY=... npm install ffmpeg-static ``` -------------------------------- ### Example ffmpeg-static Download URLs Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/api-reference.md Examples of constructed download URLs for various platforms and architectures. ```text https://github.com/eugeneware/ffmpeg-static/releases/download/b4.4/darwin-x64.gz ``` ```text https://github.com/eugeneware/ffmpeg-static/releases/download/b4.4/linux-arm64.gz ``` ```text https://github.com/eugeneware/ffmpeg-static/releases/download/b4.4/win32-x64.gz ``` -------------------------------- ### Install ffmpeg-static Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/README.md Install the ffmpeg-static package using npm. This command downloads the appropriate FFmpeg binary for your OS during installation. ```bash npm install ffmpeg-static ``` -------------------------------- ### Inspect Installed Files Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/errors.md After installation, list the contents of the ffmpeg-static directory in node_modules to verify the binary and associated files. ```bash ls -la node_modules/ffmpeg-static/ ``` -------------------------------- ### Use FFmpeg with child_process Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/INDEX.md Execute the ffmpeg binary using Node.js's child_process module. This example spawns a process to get the ffmpeg version. ```javascript const ffmpegPath = require('ffmpeg-static'); const { spawn } = require('child_process'); const ffmpeg = spawn(ffmpegPath, ['-version']); ffmpeg.stdout.on('data', (data) => console.log(data.toString())); ``` -------------------------------- ### ffmpeg-static Installation Flow Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/source-structure.md Illustrates the sequence of operations performed by the npm install script for ffmpeg-static, including platform detection, proxy configuration, and binary download. ```text User: npm install ffmpeg-static ↓ npm reads "install" script from package.json ↓ npm executes: node install.js ↓ [Platform Detection] - Check npm_config_platform / npm_config_arch - Fall back to os.platform() / os.arch() - Validate against supported binaries mapping ↓ [Early Exit Check] - If binary exists at target path → exit 0 (skip download) ↓ [Proxy Detection] - Check HTTP_PROXY, HTTPS_PROXY env vars - Create HttpsProxyAgent if needed ↓ [Cache Setup] - Use env-paths to find OS cache directory - Setup FileCache with URL normalization ↓ [Release Configuration] - Read binary-release-tag from package.json - Use FFMPEG_BINARY_RELEASE env var if set ↓ [Construct URLs] - baseUrl = github.com/releases/download/{release} - downloadUrl = {baseUrl}/{platform}-{arch}.gz - readmeUrl = {baseUrl}/{platform}-{arch}.README - licenseUrl = {baseUrl}/{platform}-{arch}.LICENSE ↓ [Download Binary] - HTTP GET to downloadUrl - Use proxy agent if configured - Use cache if available - Decompress if .gz - Write to ffmpegPath - Show progress bar ↓ [Set Permissions] - chmod 0o755 on POSIX systems ↓ [Download Metadata] - Attempt README download (warn on 404) - Attempt LICENSE download (warn on 404) ↓ Exit 0 (success) ``` -------------------------------- ### Example ffmpeg binary paths Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/installation-process.md Illustrates the expected file paths for the ffmpeg binary on different operating systems and user directories. ```text /home/user/project/node_modules/ffmpeg-static/ffmpeg /Users/user/project/node_modules/ffmpeg-static/ffmpeg C:\Users\user\project\node_modules\ffmpeg-static\ffmpeg.exe ``` -------------------------------- ### Install from Different Release Tag Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/configuration.md Install ffmpeg-static from a specific release tag by setting the FFMPEG_BINARY_RELEASE environment variable before running npm install. ```bash FFMPEG_BINARY_RELEASE=b4.3 npm install ffmpeg-static ``` -------------------------------- ### Enable Verbose Output Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/errors.md Use console.info, console.error, and console.warn to log installation information. Capture these logs using shell redirection. ```javascript console.info('ffmpeg is installed already.'); console.error(err); console.warn('Failed to download the ffmpeg README.'); ``` ```bash npm install ffmpeg-static 2>&1 | tee install.log ``` -------------------------------- ### npm install script for ffmpeg-static Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/installation-process.md This script defines the 'install' lifecycle hook in package.json, which triggers the execution of 'install.js' during npm package installation. ```json { "scripts": { "install": "node install.js" } } ``` -------------------------------- ### Handle Installation Failure for Unsupported Architecture Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/errors.md This code snippet is used during the installation phase to check if ffmpegPath is null, indicating a failure to find a suitable binary for the architecture. It then exits with an error message. ```javascript if (!ffmpegPath) { exitOnError('ffmpeg-static install failed: No binary found for architecture') } ``` -------------------------------- ### Provide Custom Binary Path for Installation Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/errors.md Set the FFMPEG_BIN environment variable to a custom path before installing ffmpeg-static. This is useful if you have ffmpeg installed in a non-standard location. ```bash export FFMPEG_BIN=/usr/local/bin/ffmpeg npm install ffmpeg-static ``` -------------------------------- ### FFmpeg Path Usage Example Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/types.md Demonstrates how to safely use the ffmpeg-static module export by checking if the returned path is a string. ```javascript const ffmpegPath = require('ffmpeg-static'); if (typeof ffmpegPath === 'string') { // ffmpegPath is safe to use console.log('Binary path:', ffmpegPath); } else { // ffmpegPath is null console.error('ffmpeg not available'); } ``` -------------------------------- ### Use npm Registry Cache for Installation Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/errors.md Clean the npm cache forcefully and then install ffmpeg-static. This can resolve issues related to corrupted cache entries. ```bash npm cache clean --force npm install ffmpeg-static ``` -------------------------------- ### Install ffmpeg-static for Different Platform Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/usage-examples.md Cross-compile the ffmpeg-static package for a different platform during installation. This is useful for CI/CD pipelines or deploying to diverse environments. ```bash npm install ffmpeg-static --npm_config_platform=linux --npm_config_arch=arm64 ``` -------------------------------- ### Cross-compile Binaries on macOS Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/configuration.md Install binaries for a different platform and architecture than the host system by setting both npm_config_platform and npm_config_arch during npm install. ```bash # Install Linux binaries while on macOS npm install ffmpeg-static --npm_config_platform=linux --npm_config_arch=x64 ``` -------------------------------- ### Construct Download URL Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/api-reference.md Illustrates how the base URL and download URL are constructed using release information and platform/architecture details. This logic is used internally by the install script. ```javascript const baseUrl = `https://github.com/eugeneware/ffmpeg-static/releases/download/${release}`; const downloadUrl = `${baseUrl}/${platform}-${arch}.gz`; ``` -------------------------------- ### URL Normalization Examples Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/types.md Illustrates how different types of URLs are transformed by the normalization process, focusing on S3 specific parameters. ```javascript Input: 'https://example.com/file?param=1' Output: 'https://example.com/file?param=1' ``` ```javascript Input: 'https://bucket.s3.amazonaws.com/file?X-Amz-Algorithm=AWS4&other_param=123' Output: 'https://bucket.s3.amazonaws.com/file?other_param=123' ``` ```javascript Input: 'https://release-assets.s3.amazonaws.com/file.gz?X-Amz-Signature=abc&actor_id=1' Output: 'https://release-assets.s3.amazonaws.com/file.gz?actor_id=1' ``` -------------------------------- ### Download README File Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/installation-process.md Downloads the README file for the ffmpeg binary. Handles 404 errors by logging a warning and continuing, while other errors cause installation failure. ```javascript .then(() => downloadFile(readmeUrl, `${ffmpegPath}.README`)) .catch(exitOnErrorOrWarnWith('Failed to download the ffmpeg README.')) ``` -------------------------------- ### Configure Platform and Architecture via CLI Flags Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/configuration.md Specify the target platform and architecture directly when installing ffmpeg-static using npm CLI flags. ```bash npm install ffmpeg-static --npm_config_platform=linux --npm_config_arch=x64 ``` -------------------------------- ### Configure Platform and Architecture via Environment Variables Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/configuration.md Set the target platform and architecture for ffmpeg-static by defining environment variables before running the npm install command. ```bash npm_config_platform=linux npm_config_arch=x64 npm install ffmpeg-static ``` -------------------------------- ### Stream Pipeline Usage Example Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/types.md Demonstrates how to construct and use a stream pipeline with Node.js's stream.pipeline function, conditionally including a decompression step for gzipped URLs. ```javascript const streams = isGzUrl(url) ? [response.body, createGunzip(), file] : [response.body, file]; pipeline( ...streams, (err) => { if (err) reject(err); else resolve(); } ); ``` -------------------------------- ### Cross-compiling with npm config overrides Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/api-reference.md Use npm configuration flags (`--npm_config_platform` and `--npm_config_arch`) during installation to force ffmpeg-static to download binaries for a different platform or architecture than the one the package is being installed on. ```bash # Download linux x64 binary when running on macOS npm install ffmpeg-static --npm_config_platform=linux --npm_config_arch=x64 ``` -------------------------------- ### Typical Progress Bar Implementation Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/types.md An example of how to implement the `ProgressCallback` to update a progress bar. This function initializes a `ProgressBar` instance if it doesn't exist and then ticks it with the received bytes. ```javascript function onProgress(deltaBytes, totalBytes) { if (totalBytes === null) return; if (!progressBar) { progressBar = new ProgressBar(`Downloading ffmpeg ${releaseName} [:bar] :percent :etas `, { complete: "|", incomplete: " ", width: 20, total: totalBytes }); } progressBar.tick(deltaBytes); } ``` -------------------------------- ### Clear Cache and Retry Installation Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/errors.md Use these commands to clear the npm cache for ffmpeg-static and then reinstall. This is often the first step in resolving installation issues. ```bash # macOS rm -rf ~/Library/Caches/ffmpeg-static # Linux rm -rf ~/.cache/ffmpeg-static # Windows rmdir %APPDATA%\ffmpeg-static\cache /s npm install ffmpeg-static ``` -------------------------------- ### Override Platform for Installation Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/configuration.md Use the npm_config_platform environment variable during installation to force the download of binaries for a specific platform, useful for cross-compiling. ```bash npm install ffmpeg-static --npm_config_platform=linux ``` -------------------------------- ### Example Download Error Objects Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/types.md Illustrates different `DownloadError` objects that can be thrown. These examples show variations for HTTP errors (like 404 or 500), network timeouts, and missing status codes or URLs. ```javascript // HTTP 404 - Not Found { statusCode: 404, url: 'https://github.com/.../releases/download/b4.4/unsupported-arch.gz', message: 'Download failed.' } ``` ```javascript // Network timeout { statusCode: undefined, url: undefined, message: 'Socket timeout' } ``` ```javascript // HTTP 500 - Server Error { statusCode: 500, url: 'https://github.com/eugeneware/ffmpeg-static/releases/download/b4.4/linux-x64.gz', message: 'Download failed.' } ``` -------------------------------- ### Download LICENSE File Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/installation-process.md Downloads the LICENSE file for the ffmpeg binary. Handles 404 errors by logging a warning and continuing, while other errors cause installation failure. ```javascript .then(() => downloadFile(licenseUrl, `${ffmpegPath}.LICENSE`)) .catch(exitOnErrorOrWarnWith('Failed to download the ffmpeg LICENSE.')) ``` -------------------------------- ### Configure Corporate Proxy Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/configuration.md Set both HTTP_PROXY and HTTPS_PROXY environment variables to use a corporate proxy for both HTTP and HTTPS downloads during installation. ```bash export HTTP_PROXY=http://proxy.corp.internal:8080 export HTTPS_PROXY=http://proxy.corp.internal:8080 npm install ffmpeg-static ``` -------------------------------- ### Set FFMPEG_BIN Environment Variable Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/errors.md Example of setting the FFMPEG_BIN environment variable to point to a custom ffmpeg binary, which can be used as a solution for unsupported platforms. ```bash export FFMPEG_BIN=/usr/local/bin/ffmpeg ``` -------------------------------- ### Get FFmpeg Binary Path Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/README.md Require the 'ffmpeg-static' module to get the absolute path to the statically linked FFmpeg binary on your local filesystem. This path can then be used to execute FFmpeg commands. ```javascript var pathToFfmpeg = require('ffmpeg-static'); console.log(pathToFfmpeg); ``` -------------------------------- ### Get ffmpeg-static Module Export Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/INDEX.md Retrieve the absolute path to the ffmpeg binary. Returns null if the platform is unsupported. ```javascript const ffmpegPath = require('ffmpeg-static'); // Returns: string (absolute path) | null (unsupported platform) ``` -------------------------------- ### Require ffmpeg-static Path Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/INDEX.md Require the ffmpeg-static module to get the path to the binary. Check if the path is null, which indicates an unsupported platform. ```javascript const ffmpegPath = require('ffmpeg-static'); if (!ffmpegPath) { /* error */ } ``` -------------------------------- ### Programmatic ffmpeg Installation Verification Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/installation-process.md Verifies the ffmpeg installation using Node.js. It checks for the availability of the ffmpeg path, confirms the binary is executable using fs.accessSync, and tests its functionality by spawning a process to run 'ffmpeg -version'. ```javascript const ffmpegPath = require('ffmpeg-static'); const fs = require('fs'); const {spawnSync} = require('child_process'); if (!ffmpegPath) { console.error('ffmpeg not available for this platform'); process.exit(1); } fs.accessSync(ffmpegPath, fs.constants.X_OK); console.log('ffmpeg is executable'); const result = spawnSync(ffmpegPath, ['-version']); if (result.status === 0) { console.log('ffmpeg is working'); } ``` -------------------------------- ### Custom Progress Callback Example Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/types.md Demonstrates a custom progress callback function that logs the download progress percentage or the downloaded bytes if the total size is unknown. It's used with the `downloadFile` function. ```javascript const { downloadFile } = require('ffmpeg-static/install.js'); const customProgress = (deltaBytes, totalBytes) => { if (totalBytes === null) { console.log(`Downloaded: ${deltaBytes} bytes (total unknown)`); } else { const percent = ((deltaBytes / totalBytes) * 100).toFixed(2); console.log(`Progress: ${percent}% (${deltaBytes}/${totalBytes} bytes)`); } }; await downloadFile(url, destination, customProgress); ``` -------------------------------- ### Setup HTTPS Proxy Agent Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/installation-process.md If a proxy URL is detected, this code sets up an HTTPSProxyAgent. The proxy URL is parsed to extract connection details. ```javascript if (proxyUrl) { const HttpsProxyAgent = require('https-proxy-agent') const {hostname, port, protocol} = new URL(proxyUrl) agent = new HttpsProxyAgent({hostname, port, protocol}) } ``` -------------------------------- ### Get FFmpeg Binary Path Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/INDEX.md Retrieve the filesystem path to the ffmpeg binary. Check if the path is available before proceeding, as it may not be available for all platforms. ```javascript const ffmpegPath = require('ffmpeg-static'); if (!ffmpegPath) { console.error('ffmpeg not available for this platform'); process.exit(1); } console.log('FFmpeg binary at:', ffmpegPath); ``` -------------------------------- ### Handle Metadata Download Errors in ffmpeg-static Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/errors.md This snippet shows how to catch errors during the download of README and LICENSE files. It differentiates between 404 errors (logged as warnings) and other errors (which cause the installation to exit). ```javascript .catch(exitOnErrorOrWarnWith('Failed to download the ffmpeg README.')) .then(() => downloadFile(licenseUrl, `${ffmpegPath}.LICENSE`)) .catch(exitOnErrorOrWarnWith('Failed to download the ffmpeg LICENSE.')) ``` ```javascript const exitOnErrorOrWarnWith = (msg) => (err) => { if (err.statusCode === 404) console.warn(msg) else exitOnError(err) } ``` -------------------------------- ### Check if ffmpeg is Already Installed Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/configuration.md Checks if the ffmpeg binary file exists at the specified path. If it exists, the script exits successfully without downloading. ```javascript if (fs.statSync(ffmpegPath).isFile()) { console.info('ffmpeg is installed already.'); process.exit(0); } ``` -------------------------------- ### Basic ffmpeg-static Usage Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/api-reference.md Retrieve the absolute filesystem path to the ffmpeg binary. Use this path when invoking ffmpeg, for example, with Node.js's child_process module. ```javascript const ffmpegPath = require('ffmpeg-static'); if (ffmpegPath) { console.log('ffmpeg binary path:', ffmpegPath); // e.g., /path/to/node_modules/ffmpeg-static/ffmpeg } else { console.error('ffmpeg binary not available for this platform'); } ``` -------------------------------- ### Set Proxy Environment Variable Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/api-reference.md Example of how to set the HTTPS_PROXY environment variable in your shell to configure proxy settings for npm package installations. ```bash export HTTPS_PROXY=http://proxy.company.com:8080 npm install ffmpeg-static ``` -------------------------------- ### Verify ffmpeg Binary Existence (POSIX) Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/installation-process.md Checks if the ffmpeg binary file exists in the expected location within the node_modules directory. This is a basic check to ensure the file was installed. ```bash # Check the binary exists ls -l node_modules/ffmpeg-static/ffmpeg ``` -------------------------------- ### FFmpeg-Static Architecture Overview Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/INDEX.md Illustrates the flow from a user application requiring the ffmpeg-static module to the execution of the FFmpeg binary. ```text User Application ↓ require('ffmpeg-static') ↓ index.js ├─ Detects platform/arch ├─ Validates support └─ Returns binary path (string | null) ↓ Application uses path with spawn/exec ↓ ffmpeg binary executes (statically linked) ``` -------------------------------- ### Execute ffmpeg Command Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/source-structure.md Demonstrates how to use the ffmpeg binary path obtained from 'ffmpeg-static' to execute ffmpeg commands for media conversion. Includes basic error handling. ```javascript const path = require('path'); const child_process = require('child_process'); const ffmpegPath = require('ffmpeg-static'); const inputFile = process.argv[2]; const outputFile = process.argv[3]; if (!inputFile || !outputFile) { console.error('Usage: node example.js '); process.exit(1); } const command = [ '-i', inputFile, '-c:a', 'libmp3lame', '-q:a', '2', outputFile ].map(arg => `"${arg}"`).join(' '); child_process.exec(`"${ffmpegPath}" ${command}`, (error, stdout, stderr) => { if (error) { console.error(`exec error: ${error}`); return; } console.log(`stdout: ${stdout}`); console.error(`stderr: ${stderr}`); }); ``` -------------------------------- ### Using ffmpeg-static with child_process Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/api-reference.md Demonstrates how to use the retrieved ffmpeg binary path with Node.js's `child_process.spawnSync` to execute ffmpeg commands, such as checking the version. ```javascript const ffmpegPath = require('ffmpeg-static'); const { spawnSync } = require('child_process'); if (ffmpegPath) { const result = spawnSync(ffmpegPath, ['-version']); console.log('ffmpeg version check:', result.stdout.toString()); } ``` -------------------------------- ### Override Architecture for Installation Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/configuration.md Use the npm_config_arch environment variable during installation to force the download of binaries for a specific architecture. ```bash npm install ffmpeg-static --npm_config_arch=arm64 ``` -------------------------------- ### Main Entry Point in package.json Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/source-structure.md Specifies the main JavaScript file and other files to be included in the package. ```json { "main": "index.js", "files": ["index.js", "install.js", "example.js"] } ``` -------------------------------- ### Initialize ffmpeg-cli-wrapper Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/INDEX.md Initialize the ffmpeg-cli-wrapper by passing the ffmpegPath to its constructor. ```javascript const ffmpegWrapper = require('ffmpeg-cli-wrapper'); const wrapper = new ffmpegWrapper({ ffmpegPath: ffmpegPath }); ``` -------------------------------- ### Execute ffmpeg Command using ffmpeg-static Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/INDEX.md Shows how to execute an ffmpeg command using the path obtained from ffmpeg-static. Ensure ffmpegPath is not null before spawning. ```javascript const {spawn} = require('child_process'); const ffmpegPath = require('ffmpeg-static'); if (ffmpegPath) { const ffmpeg = spawn(ffmpegPath, ['-version']); } ``` -------------------------------- ### Download URL Pattern for ffmpeg-static Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/api-reference.md Use this pattern to construct download URLs for ffmpeg-static binaries. Replace {release} with the version tag and {platform}-{arch} with the target system. ```text https://github.com/eugeneware/ffmpeg-static/releases/download/{release}/{platform}-{arch}.gz ``` -------------------------------- ### Accessing ffmpeg-static Configuration Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/types.md Demonstrates how to access the 'binary-release-tag' and 'binary-release-name' from the package.json configuration, with fallback to environment variables. ```javascript const pkg = require('./package.json'); const release = process.env.FFMPEG_BINARY_RELEASE || pkg['ffmpeg-static']['binary-release-tag']; const releaseName = pkg['ffmpeg-static']['binary-release-name'] || release; ``` -------------------------------- ### Test S3 URL Normalization with Assertions Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/errors.md These assertions verify the correct normalization of S3 URLs within the install script. Failures indicate a bug in the script itself and will cause the installation to exit with an error. ```javascript strictEqual( normalizeS3Url('https://example.org/foo?bar'), 'https://example.org/foo?bar' ) strictEqual( normalizeS3Url('https://github-production-release-asset-2e65be.s3.amazonaws.com/...?X-Amz-Algorithm=...&other_param=...'), 'https://github-production-release-asset-2e65be.s3.amazonaws.com/...?other_param=...' ) ``` -------------------------------- ### Handle Download Errors in Consumer Code Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/errors.md Demonstrates how to catch and handle download errors when running install.js directly. It provides specific error handling for different HTTP status codes. ```javascript const {downloadFile} = require('ffmpeg-static/install.js'); downloadFile(url, dest) .catch(err => { if (err.statusCode === 404) { console.error('Binary not found for this release/platform'); } else if (err.statusCode >= 500) { console.error('Download server error; please try again later'); } else { console.error('Download failed:', err.message); } }); ``` -------------------------------- ### Get Video Duration with FFmpeg Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/usage-examples.md Extracts the duration of a media file using ffmpeg-static. Ensure ffmpeg is available in your environment. ```javascript const ffmpegPath = require('ffmpeg-static'); const {spawnSync} = require('child_process'); function getVideoDuration(filePath) { if (!ffmpegPath) { throw new Error('ffmpeg not available'); } const result = spawnSync(ffmpegPath, ['-v', 'error', '-show_entries', 'format=duration', '-of', 'default=noprint_wrappers=1:nokey=1:noprint_wrappers=1', filePath]); if (result.error || result.status !== 0) { throw new Error('Failed to get video duration'); } const duration = parseFloat(result.stdout.toString().trim()); return duration; } // Usage try { const duration = getVideoDuration('video.mp4'); console.log(`Duration: ${duration} seconds`); } catch (err) { console.error(err.message); } ``` -------------------------------- ### npm Lifecycle Scripts in package.json Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/source-structure.md Defines scripts executed during npm package management operations like installation, testing, and linting. ```json { "scripts": { "install": "node install.js", "test": "node test.js", "lint": "eslint .", "prepublishOnly": "npm run lint && npm run install && npm test" } } ``` -------------------------------- ### Integrate with fluent-ffmpeg Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/usage-examples.md Use ffmpeg-static as the ffmpeg backend for fluent-ffmpeg. Ensure ffmpegPath is available before setting it. ```javascript const ffmpegPath = require('ffmpeg-static'); const ffmpeg = require('fluent-ffmpeg'); if (ffmpegPath) { ffmpeg.setFfmpegPath(ffmpegPath); } ffmpeg('input.mp4') .output('output.webm') .on('end', () => console.log('Conversion complete')) .on('error', (err) => console.error(err.message)) .run(); ``` -------------------------------- ### Integrate with ffmpeg-cli-wrapper Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/usage-examples.md Use ffmpeg-static with ffmpeg-cli-wrapper. Exits if ffmpeg is not available. ```javascript const ffmpegPath = require('ffmpeg-static'); const Command = require('ffmpeg-cli-wrapper').Command; if (!ffmpegPath) { console.error('ffmpeg not available'); process.exit(1); } const cmd = new Command(ffmpegPath); cmd.input('input.mp4') .output('output.mp4') .option('-c:v', 'libx264') .execute() .then(() => console.log('Done')) .catch(err => console.error(err)); ``` -------------------------------- ### Get ffmpeg-static Binary Path Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/usage-examples.md Retrieves the absolute path to the ffmpeg binary. Returns null if the binary is not available for the current platform. ```javascript const ffmpegPath = require('ffmpeg-static'); console.log(ffmpegPath); // Output: /path/to/node_modules/ffmpeg-static/ffmpeg // or: null (if unsupported platform) ``` -------------------------------- ### ffmpeg-static Runtime Flow Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/source-structure.md Details the runtime behavior of the ffmpeg-static package, explaining how it locates the ffmpeg binary based on environment variables and platform detection. ```text require('ffmpeg-static') ↓ [Check FFMPEG_BIN] - If set → return FFMPEG_BIN value ↓ [Detect Platform/Arch] - Check npm_config_platform / npm_config_arch - Fall back to os.platform() / os.arch() ↓ [Validate Support] - Check if [platform][arch] in supported binaries - If invalid → return null - If valid → continue ↓ [Compute Path] - path.join(__dirname, 'ffmpeg' | 'ffmpeg.exe') ↓ Return path (string) or null ``` -------------------------------- ### Execute ffmpeg with spawn Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/INDEX.md Execute ffmpeg using the spawn function from Node.js child_process, passing the ffmpegPath and arguments. ```javascript const { spawn } = require('child_process'); spawn(ffmpegPath, args) ``` -------------------------------- ### Graceful Degradation for Unavailable ffmpeg Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/usage-examples.md Provide alternative behavior when ffmpeg is unavailable by checking ffmpegPath. This example skips video processing if ffmpeg is not found. ```javascript const ffmpegPath = require('ffmpeg-static'); function processVideo(inputFile, outputFile) { if (!ffmpegPath) { console.warn('ffmpeg not available, skipping video processing'); return Promise.resolve(); } // Process with ffmpeg return runFfmpeg(inputFile, outputFile); } ``` -------------------------------- ### Exit on Error Function Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/installation-process.md A fatal error handler that logs the error to the console and exits the process with a non-zero status code. Use for critical installation failures. ```javascript const exitOnError = (err) => { console.error(err) process.exit(1) } ``` -------------------------------- ### Runtime Flow Diagram Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/source-structure.md Describes how the ffmpeg-static package is used at runtime within an application. ```text require('ffmpeg-static') ↓ index.js executes ├─ Check FFMPEG_BIN env var ├─ Detect platform/arch ├─ Validate against supported binaries └─ Return path (string) or null ↓ Application code uses returned path ├─ spawn(ffmpegPath, ...) ├─ exec(ffmpegPath, ...) └─ etc. ``` -------------------------------- ### Configure Platform and Architecture via .npmrc Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/configuration.md Set the target platform and architecture for ffmpeg-static by creating or editing the .npmrc file in your project or home directory. ```ini npm_config_platform=linux npm_config_arch=x64 ``` -------------------------------- ### Main Module Export Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/api-reference.md The main module export of `ffmpeg-static` provides the absolute filesystem path to the statically-linked ffmpeg binary for the current platform. It returns `null` if the platform is unsupported. ```APIDOC ## Main Module Export ### Description Provides the absolute filesystem path to the statically-linked ffmpeg binary for the current platform. Returns `null` if the platform/architecture is not supported. ### Export Type ```javascript string | null ``` ### Behavior 1. If `FFMPEG_BIN` environment variable is set, its value is returned directly. 2. Otherwise, the current platform and architecture are detected. 3. If the detected platform/architecture is supported, the path to the binary is computed. 4. If unsupported, `null` is returned. ### Usage Examples **Basic usage — retrieve binary path:** ```javascript const ffmpegPath = require('ffmpeg-static'); if (ffmpegPath) { console.log('ffmpeg binary path:', ffmpegPath); } else { console.error('ffmpeg binary not available for this platform'); } ``` **Using with child_process:** ```javascript const ffmpegPath = require('ffmpeg-static'); const { spawnSync } = require('child_process'); if (ffmpegPath) { const result = spawnSync(ffmpegPath, ['-version']); console.log('ffmpeg version check:', result.stdout.toString()); } ``` **Overriding with FFMPEG_BIN:** ```bash # Use a custom ffmpeg binary export FFMPEG_BIN=/usr/local/bin/ffmpeg node app.js ``` **Using with npm config to cross-compile:** ```bash # Download linux x64 binary when running on macOS npm install ffmpeg-static --npm_config_platform=linux --npm_config_arch=x64 ``` ``` -------------------------------- ### Supported platform and architecture combinations Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/installation-process.md Defines the mapping of supported operating systems to their respective architectures for which ffmpeg binaries are available. ```javascript var binaries = { darwin: ['x64', 'arm64'], freebsd: ['x64'], linux: ['x64', 'ia32', 'arm64', 'arm'], win32: ['x64', 'ia32'] } ``` -------------------------------- ### Exit on Error or Warn Function Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/installation-process.md A flexible error handler for optional file downloads. Logs 404 errors as warnings but calls `exitOnError` for any other error, stopping the installation. ```javascript const exitOnErrorOrWarnWith = (msg) => (err) => { if (err.statusCode === 404) console.warn(msg) else exitOnError(err) } ``` -------------------------------- ### Supported Binaries Mapping Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/api-reference.md This object shows the platform-architecture combinations for which ffmpeg-static provides pre-built binaries. It's used internally for detection. ```javascript { darwin: ['x64', 'arm64'], freebsd: ['x64'], linux: ['x64', 'ia32', 'arm64', 'arm'], win32: ['x64', 'ia32'] } ``` -------------------------------- ### Test Flow Diagram Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/source-structure.md Outlines the steps performed when running npm test for the ffmpeg-static package. ```text npm test ↓ node test.js ├─ Check binary path is absolute ├─ Check binary file exists ├─ Check binary is executable ├─ Check binary runs (--help) └─ Exit with TAP output ``` -------------------------------- ### Test ffmpeg Binary Execution Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/errors.md Use 'child_process.spawnSync' to run 'ffmpeg -version' and check for execution errors. This confirms the binary is functional before integrating it into your application. ```javascript const {spawnSync} = require('child_process'); const ffmpegPath = require('ffmpeg-static'); const result = spawnSync(ffmpegPath, ['-version']); if (result.error) { console.error('ffmpeg execution failed:', result.error); process.exit(1); } ``` -------------------------------- ### Get ffmpeg-static Binary Path Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/source-structure.md Require the 'ffmpeg-static' module to obtain the absolute path to the pre-compiled ffmpeg binary. This path can then be used with Node.js's child_process module. ```javascript const ffmpegPath = require('ffmpeg-static'); console.log(ffmpegPath); ``` -------------------------------- ### Convert Video Format Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/usage-examples.md Converts an input video file to a different codec and container format. Ensure ffmpeg-static is installed and accessible. The function overwrites the output file if it exists. ```javascript const ffmpegPath = require('ffmpeg-static'); const {spawn} = require('child_process'); const fs = require('fs'); function convertVideo(inputFile, outputFile, codec) { if (!ffmpegPath) { return Promise.reject(new Error('ffmpeg not available')); } return new Promise((resolve, reject) => { const ffmpeg = spawn(ffmpegPath, [ '-i', inputFile, '-c:v', codec, '-y', // Overwrite output file outputFile ]); let stderr = ''; ffmpeg.stderr.on('data', (data) => { stderr += data.toString(); }); ffmpeg.on('close', (code) => { if (code === 0) { resolve(); } else { reject(new Error(`ffmpeg failed with code ${code}: ${stderr}`)); } }); ffmpeg.on('error', reject); }); } // Usage convertVideo('input.mp4', 'output.webm', 'libvpx') .then(() => console.log('Conversion complete')) .catch(err => console.error('Conversion failed:', err.message)); ``` -------------------------------- ### Initialize File Cache Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/api-reference.md Sets up a file-based cache for HTTP requests using a specified cache directory. Cache keys are normalized to ensure consistent caching behavior. ```javascript const cache = new FileCache(envPaths(pkg.name).cache); cache.getCacheKey = (url) => { return FileCache.prototype.getCacheKey(normalizeS3Url(url)); }; ``` -------------------------------- ### Get Video Codec and Resolution Info with FFmpeg Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/usage-examples.md Retrieves codec name, width, and height for the first video stream of a media file using ffmpeg-static. Requires ffmpeg to be accessible. ```javascript const ffmpegPath = require('ffmpeg-static'); const {spawnSync} = require('child_process'); function getVideoInfo(filePath) { if (!ffmpegPath) { throw new Error('ffmpeg not available'); } const result = spawnSync(ffmpegPath, [ '-v', 'error', '-select_streams', 'v:0', '-show_entries', 'stream=codec_name,width,height', '-of', 'csv=p=0', filePath ]); if (result.error || result.status !== 0) { throw new Error('Failed to get video info'); } const [codec, width, height] = result.stdout.toString().trim().split(','); return { codec, width: parseInt(width), height: parseInt(height) }; } // Usage try { const info = getVideoInfo('video.mp4'); console.log(`Codec: ${info.codec}, Resolution: ${info.width}x${info.height}`); } catch (err) { console.error(err.message); } ``` -------------------------------- ### Check Cache Directory Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/errors.md Inspect the download cache directory for ffmpeg-static. The path varies by operating system. ```bash # macOS ls -la ~/Library/Caches/ffmpeg-static/ ``` ```bash # Linux ls -la ~/.cache/ffmpeg-static/ ``` ```powershell # Windows (PowerShell) dir $env:APPDATA\ffmpeg-static\cache ``` -------------------------------- ### Check Unsupported Platform/Architecture Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/errors.md This code checks if the current platform and architecture are supported by the ffmpeg-static binaries. If not, it sets ffmpegPath to null. ```javascript if (!binaries[platform] || binaries[platform].indexOf(arch) === -1) { ffmpegPath = null } ``` -------------------------------- ### Set ffmpeg Binary Release Tag Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/configuration.md Specify a custom Git release tag for downloading ffmpeg binaries using the FFMPEG_BINARY_RELEASE environment variable during installation. This allows pinning to specific ffmpeg versions. ```bash export FFMPEG_BINARY_RELEASE=b4.4 npm install ffmpeg-static ``` -------------------------------- ### Specify Binary Release Tag and Name in package.json Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/configuration.md Configure the specific binary release tag and display name for ffmpeg-static within your project's package.json file. ```json { "ffmpeg-static": { "binary-release-tag": "b4.4", "binary-release-name": "4.4" } } ``` -------------------------------- ### Execute ffmpeg Command with child_process.exec Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/usage-examples.md Executes an ffmpeg command using child_process.exec. Ensure the ffmpeg binary is available and handle potential errors. ```javascript const ffmpegPath = require('ffmpeg-static'); const {exec} = require('child_process'); if (!ffmpegPath) { console.error('ffmpeg not available'); process.exit(1); } exec(`${ffmpegPath} -version`, (error, stdout, stderr) => { if (error) { console.error('ffmpeg error:', error.message); return; } console.log('ffmpeg version info:'); console.log(stdout); }); ``` -------------------------------- ### Construct Download URLs Source: https://github.com/descriptinc/ffmpeg-ffprobe-static/blob/master/_autodocs/installation-process.md Constructs the base URL for downloading FFmpeg binaries and specific URLs for the binary, README, and LICENSE files based on the release version and target platform/architecture. ```javascript const baseUrl = `https://github.com/eugeneware/ffmpeg-static/releases/download/${release}` const downloadUrl = `${baseUrl}/${platform}-${arch}.gz` const readmeUrl = `${baseUrl}/${platform}-${arch}.README` const licenseUrl = `${baseUrl}/${platform}-${arch}.LICENSE` ```