@handy-common-utils/media-utils
v1.10.4
Published
A pure-JS, no-FFmpeg media info parser and audio stream extractor which works with popular formats and codecs and runs well in both browser and Node.js environments.
Maintainers
Readme
@handy-common-utils/media-utils
A pure-JS, no-FFmpeg media info parser and audio stream extractor which works with popular formats and codecs. It runs well in both browser and Node.js environments.
Getting Media Information
This library provides a unified interface to extract media information (duration, video/audio streams, codecs, etc.) from various media formats. It can use its own lightweight in-house parsers or several 3rd party parsers (mp4box, codem-isoboxer, @remotion/media-parser). Those 3rd party parsers are optional dependencies of this library.
Key Features
- Unified API: Get consistent
MediaInfoobject regardless of the parser used. - Browser & Node.js: Works in both environments (file system helpers are Node.js only).
- Smart Fallback: The
automode tries parsers in this order:media-utils(this library): Fast, lightweight, for raw AAC/MP3/WAV/OGG/WMA audio files as well as MKV/WebM/ASF/WMV containers.mp4box: mp4box, handles only MP4/MOV containers.isoboxer: codem-isoboxer, handles only MP4/MOV containers.remotion: @remotion/media-parser, handles some popular containers.
Verified Combinations for getMediaInfo by parser
| Format | Codecs (Video/Audio) | auto | media-utils | mp4box | isoboxer | remotion |
| :------------------ | :------------------- | :----: | :-----------: | :------: | :--------: | :--------: |
| MP4 | H.264 / AAC | ✅ | ❌ | ✅ | ✅ | ✅ |
| MP4 | H.264 / MP3 | ✅ | ❌ | ✅ | ✅ | ✅ |
| MOV | H.264 / AAC | ✅ | ❌ | ✅ | ✅ | ✅ |
| MOV | H.264 / MP3 | ✅ | ❌ | ✅ | ✅ | ❌ |
| WebM | VP8 / Vorbis | ✅ | ✅ | ❌ | ❌ | ✅ |
| WebM | VP9 / Opus | ✅ | ✅ | ❌ | ❌ | ✅ |
| WebM | VP9 / Vorbis | ✅ | ✅ | ❌ | ❌ | ✅ |
| WebM | AV1 / Opus | ✅ | ✅ | ❌ | ❌ | ❌ |
| MKV | MSMPEG4v2 / MP3 | ✅ | ✅ | ❌ | ❌ | ❌ |
| MKV | H.264 / AAC | ✅ | ✅ | ❌ | ❌ | ✅ |
| MKV | H.264 / MP3 | ✅ | ✅ | ❌ | ❌ | ✅ |
| MKV (streaming) | THEORA / Vorbis | ✅ | ✅ | ❌ | ❌ | ❌ |
| WMV | WMV2 / WMAv2 | ✅ | ✅ | ❌ | ❌ | ❌ |
| AVI | MJPEG / PCM | ✅ | ✅ | ❌ | ❌ | ❌ |
| AVI | H.264 / PCM | ✅ | ✅ | ❌ | ❌ | ❌ |
| MPEG TS | MPEG2 / MP2 | ✅ | ✅ | ❌ | ❌ | ❌ |
| MPEG TS | MPEG2 / MP3 | ✅ | ✅ | ❌ | ❌ | ❌ |
| MPEG TS | MPEG2 / AAC | ✅ | ✅ | ❌ | ❌ | ❌ |
| AAC | AAC | ✅ | ✅ | ❌ | ❌ | ✅ |
| MP3 | MP3 | ✅ | ✅ | ❌ | ❌ | ✅ |
| OGG | Opus | ✅ | ✅ | ❌ | ❌ | ❌ |
| OGG | Vorbis | ✅ | ✅ | ❌ | ❌ | ❌ |
| WAV | PCM | ✅ | ✅ | ❌ | ❌ | ❌ |
| WMA | WMAv2 | ✅ | ✅ | ❌ | ❌ | ❌ |
Note: For streaming MKV, no stream details are available.
Optional Dependencies
If you don't have those optional dependencies in use already, the recommendation is to install mp4box together with this package.
npm install @handy-common-utils/media-utils mp4boxThis library will pick optional dependencies automatically if they are installed.
Example
import { getMediaInfoFromFile } from '@handy-common-utils/media-utils';
// Automatically choose the best parser (default behavior)
// If no parser is specified, 'auto' mode will try available parsers in order
const info = await getMediaInfoFromFile('path/to/video.mp4');
console.log(`Duration: ${info.durationInSeconds}s`);
console.log(`Video: ${info.videoStreams[0]?.codec}`);
console.log(`Audio: ${info.audioStreams[0]?.codec}`);
// Force a specific parser
const infoMp4Box = await getMediaInfoFromFile('path/to/video.mp4', { useParser: 'mp4box' });Extracting Audio Stream
You can extract audio streams from video files (MP4, MOV, MKV/WebM, ASF/WMV, AVI, MPEG-TS) without re-encoding. This is fast and preserves original quality.
Verified Combinations for extractAudio
| Source Format | Source Codecs (Video/Audio) | Extracted Format | Supported | | :------------ | :-------------------------- | :--------------- | :-------: | | MP4 | H.264 / AAC | AAC | ✅ | | MP4 | H.264 / MP3 | MP3 | ✅ | | MOV | H.264 / AAC | AAC | ✅ | | MOV | H.264 / MP3 | MP3 | ✅ | | WebM | VP9 / Opus | OGG (Opus) | ✅ | | WebM | VP9 / Vorbis | OGG (Vorbis) | ✅ | | MKV | H.264 / AAC | AAC | ✅ | | MKV | MSMPEG4v2 / MP3 | MP3 | ✅ | | AVI | MJPEG / PCM | WAV | ✅ | | AVI | H.264 / PCM | WAV | ✅ | | WMV | WMV2 / WMAv2 | WMA | ✅ | | MPEG TS | MPEG2 / MP2 | MP2 | ✅ | | MPEG TS | MPEG2 / MP3 | MP3 | ✅ | | MPEG TS | MPEG2 / AAC | AAC | ✅ |
Dependencies
extractAudio requires mp4box to be installed.
npm install @handy-common-utils/media-utils mp4boxExample
import { extractAudioFromFileToFile } from '@handy-common-utils/media-utils';
// Extract the first audio track to a new file
// If neither trackId nor streamIndex is specified, the first audio stream/track will be extracted
await extractAudioFromFileToFile('input-video.mp4', 'output-audio.aac');
// Advanced usage with streams and options
import { extractAudio, createReadableStreamFromFile } from '@handy-common-utils/media-utils';
import fs from 'node:fs';
import { Writable } from 'node:stream';
const inputStream = await createReadableStreamFromFile('input.mov');
const outputStream = Writable.toWeb(fs.createWriteStream('output.mp3'));
await extractAudio(inputStream, outputStream, {
trackId: 2, // Optional: specify track ID (takes precedence over streamIndex)
// streamIndex: 0, // Optional: specify the index in all audio streams (0-based)
});Logging
This library supports logging control via options and environment variables.
Options
Both getMediaInfo and extractAudio accept options to control logging:
quiet: (boolean) Iftrue, suppresses all console output. Defaults totrue.debug: (boolean) Iftrue, enables debug logging. Defaults tofalse.
This example shows how debug logging can be enabled:
await getMediaInfoFromFile('video.mp4', { quiet: false, debug: true });Please note that if quiet is true, debug logging is always disabled even if debug is set to true.
Environment Variables
You can override the logging behavior using environment variables. These variables take precedence over the options passed to functions.
MEDIA_UTILS_LOG_QUIET: Set to 'true' or 'false' to control quiet mode.MEDIA_UTILS_LOG_DEBUG: Set to 'true' or 'false' to control debug logging.
MEDIA_UTILS_LOG_QUIET=false MEDIA_UTILS_LOG_DEBUG=true node my-script.jsUtility Functions
This library exports several utility functions to help you work with media streams in Node.js environments.
createReadableStreamFromFile(filePath: string)
Creates a Web ReadableStream from a Node.js file path. This is useful when you need to convert a file into a stream for processing.
Note: This function only works in Node.js, not in browsers.
import { createReadableStreamFromFile } from '@handy-common-utils/media-utils';
const stream = await createReadableStreamFromFile('path/to/media.mp4');
// Use the stream with getMediaInfo or extractAudioImportant: The caller is responsible for properly consuming or cancelling the returned stream to ensure the underlying file handle is released. If the stream is not fully consumed, call stream.cancel() to clean up resources.
readFromStreamToFile(stream: ReadableStream<Uint8Array>, filePath: string)
Reads a Web ReadableStream and writes it to a file. This is useful for saving processed streams back to disk.
Note: This function only works in Node.js, not in browsers.
import { readFromStreamToFile } from '@handy-common-utils/media-utils';
// Assuming you have a ReadableStream from some processing
await readFromStreamToFile(myStream, 'path/to/output.mp4');The function automatically creates the output directory if it doesn't exist.
API
@handy-common-utils/media-utils
Modules
| Module | Description | | ------ | ------ | | extract-audio | - | | get-media-info | - | | index | - | | media-info | - | | utils | - |
Extract Audio
extract-audio
Interfaces
| Interface | Description | | ------ | ------ | | ExtractAudioOptions | - |
Functions
| Function | Description | | ------ | ------ | | extractAudio | Extract raw audio data from the input | | extractAudioFromFile | Extract raw audio data from a file This function works in Node.js environment but not in browser. | | extractAudioFromFileToFile | Extract raw audio data from a file and write to an output file This function works in Node.js environment but not in browser. |
Functions
Function: extractAudio()
extractAudio(
input,output,optionsInput?):Promise<void>
Extract raw audio data from the input
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| input | ReadableStream<Uint8Array<ArrayBufferLike>> | The input data provided through a readable stream |
| output | WritableStream<Uint8Array<ArrayBufferLike>> | The output stream to write extracted audio to |
| optionsInput? | ExtractAudioOptions | Options for the extraction process |
Returns
Promise<void>
Promise that resolves when extraction is complete
Function: extractAudioFromFile()
extractAudioFromFile(
filePath,output,options?):Promise<void>
Extract raw audio data from a file This function works in Node.js environment but not in browser.
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| filePath | string | The path to the media file |
| output | WritableStream<Uint8Array<ArrayBufferLike>> | The output stream to write extracted audio to |
| options? | ExtractAudioOptions | Options for the extraction process |
Returns
Promise<void>
Function: extractAudioFromFileToFile()
extractAudioFromFileToFile(
inputFilePath,outputFilePath,options?):Promise<void>
Extract raw audio data from a file and write to an output file This function works in Node.js environment but not in browser.
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| inputFilePath | string | The path to the input media file |
| outputFilePath | string | The path to the output audio file |
| options? | ExtractAudioOptions | Options for the extraction process |
Returns
Promise<void>
Interfaces
Interface: ExtractAudioOptions
Extends
Properties
| Property | Type | Description | Inherited from |
| ------ | ------ | ------ | ------ |
| debug? | boolean | Whether to enable debug logging. Default value is false. | - |
| onProgress? | (progress) => void | Optional callback to receive progress updates (0-100). | - |
| quiet? | boolean | Whether to suppress console output. Default value is true. | - |
| streamIndex? | number | The index of the stream/track to extract audio from. If this option is provided, trackId is ignored. If trackId is not provided and this option is not specified, the first audio stream/track will be extracted. | - |
| trackId? | number | The ID of the track to extract audio from If this option is provided, streamIndex is ignored. If both trackId and streamIndex are not provided, the first audio stream/track will be extracted. | - |
| useParser? | "mp4box" | "remotion" | "isoboxer" | "media-utils" | "auto" | Which parser library/package to use The default is 'auto', which will try to use mp4box first and fallback to remotion if mp4box fails. | ParserRelatedOptions.useParser |
Get Media Info
get-media-info
Type Aliases
| Type Alias | Description | | ------ | ------ | | GetMediaInfoOptions | - |
Functions
| Function | Description | | ------ | ------ | | getMediaInfo | Get media information from a stream | | getMediaInfoFromFile | Get media information from a file path. This function works in Node.js environment but not in browser. |
Functions
Function: getMediaInfo()
getMediaInfo(
stream,optionsInput?):Promise<MediaInfo&object>
Get media information from a stream
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| stream | ReadableStream<Uint8Array<ArrayBufferLike>> | The input Web ReadableStream (not Node Readable). To convert a Node Readable to Web ReadableStream, use Readable.toWeb(nodeReadable). |
| optionsInput? | GetMediaInfoOptions | Options for the parser |
Returns
Promise<MediaInfo & object>
The media information
Function: getMediaInfoFromFile()
getMediaInfoFromFile(
filePath,options?):Promise<MediaInfo>
Get media information from a file path. This function works in Node.js environment but not in browser.
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| filePath | string | The path to the media file |
| options? | GetMediaInfoOptions | Options for the parser |
Returns
Promise<MediaInfo>
The media information
Type Aliases
Type Alias: GetMediaInfoOptions
GetMediaInfoOptions =
ParserRelatedOptions&object
Type Declaration
| Name | Type | Description |
| ------ | ------ | ------ |
| debug? | boolean | Whether to enable debug logging. Default value is false. |
| quiet? | boolean | Whether to suppress console output. Default value is true. |
Index
index
References
allAudioCodecs
Re-exports allAudioCodecs
allContainers
Re-exports allContainers
allVideoCodecs
Re-exports allVideoCodecs
AudioCodecDetails
Re-exports AudioCodecDetails
AudioCodecType
Re-exports AudioCodecType
AudioStreamInfo
Re-exports AudioStreamInfo
ContainerDetails
Re-exports ContainerDetails
ContainerType
Re-exports ContainerType
createReadableStreamFromFile
Re-exports createReadableStreamFromFile
ensureBufferData
Re-exports ensureBufferData
extractAudio
Re-exports extractAudio
extractAudioFromFile
Re-exports extractAudioFromFile
extractAudioFromFileToFile
Re-exports extractAudioFromFileToFile
ExtractAudioOptions
Re-exports ExtractAudioOptions
findAudioCodec
Re-exports findAudioCodec
findContainer
Re-exports findContainer
findVideoCodec
Re-exports findVideoCodec
getGlobalLogger
Re-exports getGlobalLogger
getMediaInfo
Re-exports getMediaInfo
getMediaInfoFromFile
Re-exports getMediaInfoFromFile
GetMediaInfoOptions
Re-exports GetMediaInfoOptions
isPCM
Re-exports isPCM
isWMA
Re-exports isWMA
MediaInfo
Re-exports MediaInfo
ParserRelatedOptions
Re-exports ParserRelatedOptions
ParsingError
Re-exports ParsingError
readBeginning
Re-exports readBeginning
readFromStreamToFile
Re-exports readFromStreamToFile
setupGlobalLogger
Re-exports setupGlobalLogger
toAudioCodec
Re-exports toAudioCodec
toContainer
Re-exports toContainer
toVideoCodec
Re-exports toVideoCodec
UnsupportedFormatError
Re-exports UnsupportedFormatError
VideoCodecDetails
Re-exports VideoCodecDetails
VideoCodecType
Re-exports VideoCodecType
VideoStreamInfo
Re-exports VideoStreamInfo
Media Info
media-info
Classes
| Class | Description | | ------ | ------ | | AudioCodecDetails | - | | ContainerDetails | - | | VideoCodecDetails | - |
Interfaces
| Interface | Description | | ------ | ------ | | AudioStreamInfo | - | | MediaInfo | - | | VideoStreamInfo | - |
Type Aliases
| Type Alias | Description | | ------ | ------ | | AudioCodecType | - | | ContainerType | - | | VideoCodecType | - |
Functions
| Function | Description | | ------ | ------ | | allAudioCodecs | Get all audio codecs with their details | | allContainers | Get all containers with their details | | allVideoCodecs | Get all video codecs with their details | | findAudioCodec | Find the matching audio codec for a given code | | findContainer | Find the matching container for a given code | | findVideoCodec | Find the matching video codec for a given code | | isPCM | Check if the audio codec is a PCM (including ADPCM) codec | | isWMA | Check if the audio codec is a WMA codec | | toAudioCodec | Find the matching audio codec for a given code | | toContainer | Find the matching container for a given code | | toVideoCodec | Find the matching video codec for a given code |
Classes
Class: AudioCodecDetails<T>
Type Parameters
| Type Parameter |
| ------ |
| T extends string |
Constructors
Constructor
new AudioCodecDetails<
T>(code,defaultContainer,aliases):AudioCodecDetails<T>
####### Parameters
| Parameter | Type |
| ------ | ------ |
| code | T |
| defaultContainer | "unknown" | "mp4" | "mov" | "m4a" | "webm" | "mkv" | "avi" | "mpegts" | "wma" | "asf" | "ogg" | "aac" | "mp3" | "flac" | "wav" | "ac3" | "mp2" | "mp1" | "dts" |
| aliases | (string | RegExp)[] |
####### Returns
AudioCodecDetails<T>
Properties
| Property | Modifier | Type |
| ------ | ------ | ------ |
| aliases | readonly | (string | RegExp)[] |
| code | readonly | T |
| defaultContainer | readonly | "unknown" | "mp4" | "mov" | "m4a" | "webm" | "mkv" | "avi" | "mpegts" | "wma" | "asf" | "ogg" | "aac" | "mp3" | "flac" | "wav" | "ac3" | "mp2" | "mp1" | "dts" |
Class: ContainerDetails<T>
Type Parameters
| Type Parameter |
| ------ |
| T extends string |
Constructors
Constructor
new ContainerDetails<
T>(code,fileExtension,aliases):ContainerDetails<T>
####### Parameters
| Parameter | Type |
| ------ | ------ |
| code | T |
| fileExtension | string |
| aliases | (string | RegExp)[] |
####### Returns
ContainerDetails<T>
Properties
| Property | Modifier | Type |
| ------ | ------ | ------ |
| aliases | readonly | (string | RegExp)[] |
| code | readonly | T |
| fileExtension | readonly | string |
Class: VideoCodecDetails<T>
Type Parameters
| Type Parameter |
| ------ |
| T extends string |
Constructors
Constructor
new VideoCodecDetails<
T>(code,aliases):VideoCodecDetails<T>
####### Parameters
| Parameter | Type |
| ------ | ------ |
| code | T |
| aliases | (string | RegExp)[] |
####### Returns
VideoCodecDetails<T>
Properties
| Property | Modifier | Type |
| ------ | ------ | ------ |
| aliases | readonly | (string | RegExp)[] |
| code | readonly | T |
Functions
Function: allAudioCodecs()
allAudioCodecs():
AudioCodecDetails<"unknown"|"aac"|"mp3"|"flac"|"ac3"|"mp2"|"mp1"|"dts"|"opus"|"aac_latm"|"wmav1"|"wmav2"|"wmapro"|"wmalossless"|"vorbis"|"pcm_u8"|"pcm_s16le"|"pcm_s24le"|"pcm_s32le"|"pcm_s16be"|"pcm_s24be"|"pcm_s32be"|"pcm_f32le"|"pcm_alaw"|"pcm_mulaw"|"alac"|"adpcm_ms"|"adpcm_ima_wav"|"eac3">[]
Get all audio codecs with their details
Returns
AudioCodecDetails<"unknown" | "aac" | "mp3" | "flac" | "ac3" | "mp2" | "mp1" | "dts" | "opus" | "aac_latm" | "wmav1" | "wmav2" | "wmapro" | "wmalossless" | "vorbis" | "pcm_u8" | "pcm_s16le" | "pcm_s24le" | "pcm_s32le" | "pcm_s16be" | "pcm_s24be" | "pcm_s32be" | "pcm_f32le" | "pcm_alaw" | "pcm_mulaw" | "alac" | "adpcm_ms" | "adpcm_ima_wav" | "eac3">[]
Array of audio codec details
Function: allContainers()
allContainers():
ContainerDetails<"unknown"|"mp4"|"mov"|"m4a"|"webm"|"mkv"|"avi"|"mpegts"|"wma"|"asf"|"ogg"|"aac"|"mp3"|"flac"|"wav"|"ac3"|"mp2"|"mp1"|"dts">[]
Get all containers with their details
Returns
ContainerDetails<"unknown" | "mp4" | "mov" | "m4a" | "webm" | "mkv" | "avi" | "mpegts" | "wma" | "asf" | "ogg" | "aac" | "mp3" | "flac" | "wav" | "ac3" | "mp2" | "mp1" | "dts">[]
Array of container details
Function: allVideoCodecs()
allVideoCodecs():
VideoCodecDetails<"unknown"|"h264"|"hevc"|"vp8"|"vp9"|"wmv2"|"av1"|"prores"|"mpeg4"|"mpeg2video"|"theora"|"mjpeg"|"msmpeg4v2"|"mpeg1video">[]
Get all video codecs with their details
Returns
VideoCodecDetails<"unknown" | "h264" | "hevc" | "vp8" | "vp9" | "wmv2" | "av1" | "prores" | "mpeg4" | "mpeg2video" | "theora" | "mjpeg" | "msmpeg4v2" | "mpeg1video">[]
Array of video codec details
Function: findAudioCodec()
findAudioCodec(
code):AudioCodecDetails<"unknown"|"aac"|"mp3"|"flac"|"ac3"|"mp2"|"mp1"|"dts"|"opus"|"aac_latm"|"wmav1"|"wmav2"|"wmapro"|"wmalossless"|"vorbis"|"pcm_u8"|"pcm_s16le"|"pcm_s24le"|"pcm_s32le"|"pcm_s16be"|"pcm_s24be"|"pcm_s32be"|"pcm_f32le"|"pcm_alaw"|"pcm_mulaw"|"alac"|"adpcm_ms"|"adpcm_ima_wav"|"eac3"> |undefined
Find the matching audio codec for a given code
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| code | string | null | undefined | A code which could be a codec identifier (e.g., "mp4a.40.2", "opus", "mp3") or anything else |
Returns
AudioCodecDetails<"unknown" | "aac" | "mp3" | "flac" | "ac3" | "mp2" | "mp1" | "dts" | "opus" | "aac_latm" | "wmav1" | "wmav2" | "wmapro" | "wmalossless" | "vorbis" | "pcm_u8" | "pcm_s16le" | "pcm_s24le" | "pcm_s32le" | "pcm_s16be" | "pcm_s24be" | "pcm_s32be" | "pcm_f32le" | "pcm_alaw" | "pcm_mulaw" | "alac" | "adpcm_ms" | "adpcm_ima_wav" | "eac3"> | undefined
Details of the audio codec found, or undefined if no matching codec can be found.
Function: findContainer()
findContainer(
code):ContainerDetails<"unknown"|"mp4"|"mov"|"m4a"|"webm"|"mkv"|"avi"|"mpegts"|"wma"|"asf"|"ogg"|"aac"|"mp3"|"flac"|"wav"|"ac3"|"mp2"|"mp1"|"dts"> |undefined
Find the matching container for a given code
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| code | string | null | undefined | A code which could be a MP4 brand identifier (e.g., "isom", "iso2", "mp41") or anything else |
Returns
ContainerDetails<"unknown" | "mp4" | "mov" | "m4a" | "webm" | "mkv" | "avi" | "mpegts" | "wma" | "asf" | "ogg" | "aac" | "mp3" | "flac" | "wav" | "ac3" | "mp2" | "mp1" | "dts"> | undefined
Details of the container found, or undefined if no matching container can be found.
Function: findVideoCodec()
findVideoCodec(
code):VideoCodecDetails<"unknown"|"h264"|"hevc"|"vp8"|"vp9"|"wmv2"|"av1"|"prores"|"mpeg4"|"mpeg2video"|"theora"|"mjpeg"|"msmpeg4v2"|"mpeg1video"> |undefined
Find the matching video codec for a given code
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| code | string | null | undefined | A code which could be a codec identifier (e.g., "avc", "hevc", "vp09") or anything else |
Returns
VideoCodecDetails<"unknown" | "h264" | "hevc" | "vp8" | "vp9" | "wmv2" | "av1" | "prores" | "mpeg4" | "mpeg2video" | "theora" | "mjpeg" | "msmpeg4v2" | "mpeg1video"> | undefined
Details of the video codec found, or undefined if no matching codec can be found.
Function: isPCM()
isPCM(
audioCodec):boolean
Check if the audio codec is a PCM (including ADPCM) codec
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| audioCodec | string | null | undefined | The audio codec to check |
Returns
boolean
True if the audio codec is a PCM codec, false otherwise
Function: isWMA()
isWMA(
audioCodec):boolean
Check if the audio codec is a WMA codec
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| audioCodec | string | null | undefined | The audio codec to check |
Returns
boolean
True if the audio codec is a WMA codec, false otherwise
Function: toAudioCodec()
toAudioCodec(
code):AudioCodecDetails<"unknown"|"aac"|"mp3"|"flac"|"ac3"|"mp2"|"mp1"|"dts"|"opus"|"aac_latm"|"wmav1"|"wmav2"|"wmapro"|"wmalossless"|"vorbis"|"pcm_u8"|"pcm_s16le"|"pcm_s24le"|"pcm_s32le"|"pcm_s16be"|"pcm_s24be"|"pcm_s32be"|"pcm_f32le"|"pcm_alaw"|"pcm_mulaw"|"alac"|"adpcm_ms"|"adpcm_ima_wav"|"eac3">
Find the matching audio codec for a given code
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| code | string | null | undefined | A code which could be a codec identifier (e.g., "mp4a.40.2", "opus", "mp3") or anything else |
Returns
AudioCodecDetails<"unknown" | "aac" | "mp3" | "flac" | "ac3" | "mp2" | "mp1" | "dts" | "opus" | "aac_latm" | "wmav1" | "wmav2" | "wmapro" | "wmalossless" | "vorbis" | "pcm_u8" | "pcm_s16le" | "pcm_s24le" | "pcm_s32le" | "pcm_s16be" | "pcm_s24be" | "pcm_s32be" | "pcm_f32le" | "pcm_alaw" | "pcm_mulaw" | "alac" | "adpcm_ms" | "adpcm_ima_wav" | "eac3">
Details of the audio codec found, or throws an error if no matching codec can be found.
Function: toContainer()
toContainer(
code):ContainerDetails<"unknown"|"mp4"|"mov"|"m4a"|"webm"|"mkv"|"avi"|"mpegts"|"wma"|"asf"|"ogg"|"aac"|"mp3"|"flac"|"wav"|"ac3"|"mp2"|"mp1"|"dts">
Find the matching container for a given code
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| code | string | string[] | null | undefined | A code or an array of MP4 brand identifiers (e.g., ["isom", "iso2", "mp41"]) |
Returns
ContainerDetails<"unknown" | "mp4" | "mov" | "m4a" | "webm" | "mkv" | "avi" | "mpegts" | "wma" | "asf" | "ogg" | "aac" | "mp3" | "flac" | "wav" | "ac3" | "mp2" | "mp1" | "dts">
Details of the container found, or throws an error if no matching container can be found.
Function: toVideoCodec()
toVideoCodec(
code):VideoCodecDetails<"unknown"|"h264"|"hevc"|"vp8"|"vp9"|"wmv2"|"av1"|"prores"|"mpeg4"|"mpeg2video"|"theora"|"mjpeg"|"msmpeg4v2"|"mpeg1video">
Find the matching video codec for a given code
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| code | string | null | undefined | A code which could be a codec identifier (e.g., "avc", "hevc", "vp09") or anything else |
Returns
VideoCodecDetails<"unknown" | "h264" | "hevc" | "vp8" | "vp9" | "wmv2" | "av1" | "prores" | "mpeg4" | "mpeg2video" | "theora" | "mjpeg" | "msmpeg4v2" | "mpeg1video">
Details of the video codec found, or throws an error if no matching codec can be found.
Interfaces
Interface: AudioStreamInfo
Properties
| Property | Type | Description |
| ------ | ------ | ------ |
| audioType? | string | Such like Music, Effects, Visual impaired / Audio description, Hearing impaired |
| bitrate? | number | - |
| bitsPerSample? | number | - |
| channelCount? | number | - |
| codec | "unknown" | "aac" | "mp3" | "flac" | "ac3" | "mp2" | "mp1" | "dts" | "opus" | "aac_latm" | "wmav1" | "wmav2" | "wmapro" | "wmalossless" | "vorbis" | "pcm_u8" | "pcm_s16le" | "pcm_s24le" | "pcm_s32le" | "pcm_s16be" | "pcm_s24be" | "pcm_s32be" | "pcm_f32le" | "pcm_alaw" | "pcm_mulaw" | "alac" | "adpcm_ms" | "adpcm_ima_wav" | "eac3" | - |
| codecDetail? | string | Parser-specific codec information |
| codecDetails? | object | Codec-specific details (stream-level properties) For ADPCM codecs (MS ADPCM, IMA ADPCM, etc.), these properties are constant for the entire audio stream and stored once in the container's format header: - WAV: in the fmt chunk - AVI: in the stream format chunk (strf) - MKV (A_MS/ACM): inside the CodecPrivate WAVEFORMATEX These values do NOT change per block/frame. |
| codecDetails.asvc? | number | - |
| codecDetails.blockAlign? | number | Block align (nBlockAlign) — STREAM LEVEL The size (in bytes) of each encoded ADPCM block. Must remain constant for the whole stream. - Containers expect every read operation to start on a block boundary - ADPCM decoding requires knowing block size ahead of time - Every ADPCM block in the stream must be exactly blockAlign bytes Not stored per block — the block itself does not announce its own length. |
| codecDetails.bsmod? | number | - |
| codecDetails.componentType? | number | - |
| codecDetails.formatTag? | number | Format tag (wFormatTag) — STREAM LEVEL Identifies the codec type: - 0x0001 = PCM - 0x0002 = MS ADPCM - 0x0011 = IMA ADPCM - etc. Stored once in the container's format header, not in each block. |
| codecDetails.layer? | number | Something like layer I, II, III |
| codecDetails.mainId? | number | - |
| codecDetails.padding? | number | - |
| codecDetails.samplesPerBlock? | number | Samples per block — STREAM LEVEL Tells the decoder how many PCM samples will come out of each compressed block. Derived from the codec and blockAlign. Needed because ADPCM uses: - Warm-up samples - 4-bit deltas Also constant for the entire stream. Not stored per block. The block itself contains: - Predictor index - Delta (step size) - Warm-up samples - 4-bit deltas ...but NOT samples-per-block (that's known from the stream header). |
| durationInSeconds? | number | - |
| id | number | - |
| language? | string | Usually it is ISO-639 string |
| level? | string | - |
| profile? | string | - |
| sampleRate? | number | - |
| surroundMode? | string | DTS surround mode |
Interface: MediaInfo
Properties
| Property | Type | Description |
| ------ | ------ | ------ |
| audioStreams | AudioStreamInfo[] | - |
| container | "unknown" | "mp4" | "mov" | "m4a" | "webm" | "mkv" | "avi" | "mpegts" | "wma" | "asf" | "ogg" | "aac" | "mp3" | "flac" | "wav" | "ac3" | "mp2" | "mp1" | "dts" | - |
| containerDetail? | string | Parser-specific container information |
| durationInSeconds? | number | - |
| mimeType? | string | - |
| parser | "mp4box" | "remotion" | "isoboxer" | "media-utils" | "auto" | - |
| videoStreams | VideoStreamInfo[] | - |
Interface: VideoStreamInfo
Properties
| Property | Type | Description |
| ------ | ------ | ------ |
| bitrate? | number | - |
| codec | "unknown" | "h264" | "hevc" | "vp8" | "vp9" | "wmv2" | "av1" | "prores" | "mpeg4" | "mpeg2video" | "theora" | "mjpeg" | "msmpeg4v2" | "mpeg1video" | - |
| codecDetail? | string | Parser-specific codec information |
| durationInSeconds? | number | - |
| fps? | number | - |
| height? | number | - |
| id | number | - |
| level? | string | - |
| profile? | string | - |
| width? | number | - |
Type Aliases
Type Alias: AudioCodecType
AudioCodecType = keyof typeof
audioCodecs
Type Alias: ContainerType
ContainerType = keyof typeof
containers
Type Alias: VideoCodecType
VideoCodecType = keyof typeof
videoCodecs
Utils
utils
Classes
| Class | Description | | ------ | ------ | | UnsupportedFormatError | Error thrown when a parser encounters an unsupported file format or invalid data. |
Interfaces
| Interface | Description | | ------ | ------ | | ParserRelatedOptions | - | | ParsingError | - |
Functions
| Function | Description | | ------ | ------ | | createReadableStreamFromFile | Creates a Web ReadableStream from a Node.js file path. This function works in Node.js environment but not in browser. | | ensureBufferData | Ensures that the buffer has enough data by reading from the stream if necessary. This function manages buffer compaction and appending new data. | | getGlobalLogger | Returns the global logger for the library. If the logger has not been set, it will be initialized default settings which discards all logs. Please note that environment variables MEDIA_UTILS_LOG_QUIET and MEDIA_UTILS_LOG_DEBUG can be used to override the logging behavior. | | readBeginning | Reads the beginning of a stream up to a specified size. This function handles reading, buffering, and closing the reader. | | readFromStreamToFile | Reads a Web ReadableStream and writes it to a file. This function works in Node.js environment but not in browser. | | setupGlobalLogger | Set the global logger for the library to a new console logger. Please note that environment variables MEDIA_UTILS_LOG_QUIET and MEDIA_UTILS_LOG_DEBUG can be used to override the logging behavior. |
Classes
Class: UnsupportedFormatError
Error thrown when a parser encounters an unsupported file format or invalid data.
Extends
Error
Implements
Constructors
Constructor
new UnsupportedFormatError(
message):UnsupportedFormatError
####### Parameters
| Parameter | Type |
| ------ | ------ |
| message | string |
####### Returns
UnsupportedFormatError
####### Overrides
Error.constructor
Properties
| Property | Modifier | Type | Default value |
| ------ | ------ | ------ | ------ |
| isUnsupportedFormatError | readonly | true | true |
Functions
Function: createReadableStreamFromFile()
createReadableStreamFromFile(
filePath):Promise<ReadableStream<Uint8Array<ArrayBufferLike>>>
Creates a Web ReadableStream from a Node.js file path. This function works in Node.js environment but not in browser.
Important: The caller is responsible for properly consuming or cancelling
the returned stream to ensure the underlying file handle is released.
If the stream is not fully consumed, call stream.cancel() to clean up resources.
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| filePath | string | The path to the file |
Returns
Promise<ReadableStream<Uint8Array<ArrayBufferLike>>>
A (web) ReadableStream of Uint8Array chunks
Function: ensureBufferData()
ensureBufferData(
reader,buffer?,bufferOffset?,size?):Promise<{buffer:Uint8Array;bufferOffset:number;done:boolean; }>
Ensures that the buffer has enough data by reading from the stream if necessary. This function manages buffer compaction and appending new data.
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| reader | ReadableStreamDefaultReader<Uint8Array<ArrayBufferLike>> | The ReadableStreamDefaultReader to read from |
| buffer? | Uint8Array<ArrayBufferLike> | The current data buffer (optional, defaults to empty buffer) |
| bufferOffset? | number | The current offset in the buffer (optional, defaults to 0) |
| size? | number | The minimum required size of data available in the buffer (buffer.length - bufferOffset) |
Returns
Promise<{ buffer: Uint8Array; bufferOffset: number; done: boolean; }>
An object containing the updated buffer, bufferOffset, and a boolean indicating if the stream has ended
Function: getGlobalLogger()
getGlobalLogger():
LineLogger
Returns the global logger for the library. If the logger has not been set, it will be initialized default settings which discards all logs. Please note that environment variables MEDIA_UTILS_LOG_QUIET and MEDIA_UTILS_LOG_DEBUG can be used to override the logging behavior.
Returns
LineLogger
The global logger for the library.
Function: readBeginning()
readBeginning(
reader,size):Promise<Uint8Array<ArrayBufferLike>>
Reads the beginning of a stream up to a specified size. This function handles reading, buffering, and closing the reader.
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| reader | ReadableStreamDefaultReader<Uint8Array<ArrayBufferLike>> | The ReadableStreamDefaultReader to read from |
| size | number | The amount of data to read (optional, defaults to 64KB) |
Returns
Promise<Uint8Array<ArrayBufferLike>>
The read data as a Uint8Array
Function: readFromStreamToFile()
readFromStreamToFile(
stream,filePath):Promise<void>
Reads a Web ReadableStream and writes it to a file. This function works in Node.js environment but not in browser.
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| stream | ReadableStream<Uint8Array<ArrayBufferLike>> | The readable stream to read from |
| filePath | string | The path to the file to write to |
Returns
Promise<void>
Function: setupGlobalLogger()
setupGlobalLogger(
flags):LineLogger
Set the global logger for the library to a new console logger. Please note that environment variables MEDIA_UTILS_LOG_QUIET and MEDIA_UTILS_LOG_DEBUG can be used to override the logging behavior.
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| flags | { debug?: boolean; quiet?: boolean; } | null | undefined | The flags to pass to the console logger. |
Returns
LineLogger
The global logger for the library.
Interfaces
Interface: ParserRelatedOptions
Extended by
Properties
| Property | Type | Description |
| ------ | ------ | ------ |
| useParser? | "mp4box" | "remotion" | "isoboxer" | "media-utils" | "auto" | Which parser library/package to use The default is 'auto', which will try to use mp4box first and fallback to remotion if mp4box fails. |
Interface: ParsingError
Properties
| Property | Type |
| ------ | ------ |
| isUnsupportedFormatError? | boolean |
