Skip to content

handy-common-utils/media-utils

Repository files navigation

@handy-common-utils/media-utils

A pure-JavaScript library for efficiently parsing media information and extracting audio streams. It works with all popular formats and codecs directly in the browser and Node.js, without relying on external binaries like FFmpeg or WASM.

Version Downloads/week CI

Why Use @handy-common-utils/media-utils?

  • Pure JavaScript: No reliance on FFmpeg, WASM, or any 3rd party media parsing or processing tools or packages.
  • Universal Compatibility: Fully compatible with both Node.js and Browser environments.
  • Wide Format Support: Supports all popular container formats (MP4, MKV, WebM, MOV, AVI, WMV, MPEG-TS, etc.) and audio/video codecs.
  • Convenient API: Easily process data from Web Streams, Node.js Streams, and Node.js file systems.
  • Fast Audio Extraction: Extract audio streams from video files without re-encoding to preserve quality and speed.

Installation

npm install @handy-common-utils/media-utils

Getting Media Information

Use getMediaInfo() to extract crucial metadata like duration, stream details (video/audio), and codec information from any supported media format. All popular container formats and audio/video codecs are supported.

getMediaInfo() works with Web Streams. If you'd like to use Node.js Stream or Node.js file system, try Readable.toWeb() or getMediaInfoFromFile().

Example: Quick Start

import { getMediaInfoFromFile } from '@handy-common-utils/media-utils';

// Read from a file path (Node.js only)
const info = await getMediaInfoFromFile('path/to/video.mp4');

console.log(JSON.stringify(info, null, 2));
//   {
//     parser: 'media-utils',
//     container: 'mp4',
//     containerDetail: 'mp42, isom, mp42',
//     durationInSeconds: 734,
//     videoStreams: [
//       {
//         id: 1,
//         codec: 'h264',
//         codecDetail: 'avc1.64001f',
//         width: 1280,
//         height: 534,
//         fps: 24,
//         bitrate: 1830000,
//         durationInSeconds: 734,
//       },
//     ],
//     audioStreams: [
//       {
//         id: 2,
//         codec: 'aac',
//         codecDetail: 'mp4a.40.02',
//         profile: 'LC',
//         channelCount: 2,
//         sampleRate: 44100,
//         bitrate: 192000,
//         durationInSeconds: 734,
//       },
//     ],
//   }

Verified Combinations

This table lists the combinations verified by our test suite.

Format/Container Video Codec Audio Codec(s) File Remark Supported
aac aac
asf/wma wmav2
asf/wmv wmv2 wmav2
avi h264 adpcm_ms
avi h264 mp3
avi h264 pcm_s16le
avi h264 pcm_u8
avi mjpeg pcm_s16le
avi mpeg4 ac3 5 channels
mkv h264 aac, aac
mkv h264 aac
mkv h264 mp3
mkv msmpeg4v2 mp3
mkv streaming
mov h264 aac
mov h264 mp3
mov h264 pcm_s16le
mov h264 pcm_s32be
mp3 mp3
mp4 h264 aac
mp4 h264 mp3
mpegts h264 aac
mpegts mpeg2video mp2
mxf h264 pcm_s24le
mxf mpeg2video pcm_s16le
ogg opus
ogg vorbis
wav pcm_s16le
webm av1 opus
webm vp8 vorbis
webm vp9 opus
webm vp9 vorbis

Note: For streaming MKV, no stream details are available.

Integration with Third-Party Parsers (Optional)

While @handy-common-utils/media-utils provides built-in support for all popular formats, it can also automatically integrate with other well-known Javascript parsers as a fallback or for specific needs.

  • media-utils (built-in): This is the recommended default, all popular formats are supported.
  • mp4box: mp4box, handles only MP4/MOV containers.
  • isoboxer: codem-isoboxer, handles only MP4/MOV containers.
  • remotion: @remotion/media-parser, handles more formats

If you install any of these packages, getMediaInfo() will use them as a fallback mechanism.

To force a specific parser, use the useParser option:

// Force mp4box parser (must be installed separately)
const infoMp4Box = await getMediaInfoFromFile('path/to/video.mp4', { useParser: 'mp4box' });

// Use built-in parser and fall back to others ('auto' is the default if not specified)
const infoAuto = await getMediaInfoFromFile('path/to/video.mp4', { useParser: 'auto' });

Extracting Audio Stream

The extractAudio() function allows you to extract an audio stream from a video container (MP4, MOV, MKV, AVI, etc.) without re-encoding. This process is extremely fast and preserves the original audio quality and codec.

extractAudio() works with Web Streams. If you'd like to use Node.js Stream or Node.js file system, try Readable.toWeb(), Writable.toWeb, extractAudioFromFile() or extractAudioFromFileToFile().

Example: Extracting to File

import { extractAudioFromFileToFile } from '@handy-common-utils/media-utils';

// Extracts the first audio stream and writes it to a new file.
// The output format is automatically determined by the extracted audio codec.
await extractAudioFromFileToFile('input-video.mp4', 'output-audio.aac');

Verified Extraction Combinations

Format/Container Video Codec Audio Codec(s) File Remark Supported Extracted Audio
asf/wmv wmv2 wmav2 wmav2 in asf
avi h264 adpcm_ms adpcm_ms in wav
avi h264 mp3 mp3 in mp3
avi h264 pcm_s16le pcm_s16le in wav
avi h264 pcm_u8 pcm_u8 in wav
avi mjpeg pcm_s16le pcm_s16le in wav
mkv h264 aac aac in aac
mkv h264 mp3 mp3 in mp3
mkv msmpeg4v2 mp3 mp3 in mp3
mov h264 aac aac in aac
mov h264 mp3 mp3 in mp3
mov h264 pcm_s16le pcm_s16le in wav
mov h264 pcm_s32be pcm_s32le in wav
mp4 h264 aac aac in aac
mp4 h264 mp3 mp3 in mp3
mpegts h264 aac aac in aac
mpegts h264 mp3 mp3 in mp3
mpegts mpeg2video mp2 mp2 in mp3
mxf h264 pcm_s24le pcm_s24le in wav
mxf mpeg2video pcm_s16le pcm_s16le in wav
webm vp9 opus opus in ogg
webm vp9 vorbis vorbis in ogg

Advanced Usage: Stream-to-Stream

You can use the core extractAudio() function for greater control over input and output streams:

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');
// Use a Node.js Writable Stream, converted to a Web WritableStream
const outputStream = Writable.toWeb(fs.createWriteStream('output.mp3'));

await extractAudio(inputStream, outputStream, {
  // Optional: Specify which track to extract (trackId takes precedence)
  trackId: 2,
  // streamIndex: 0,
});

Errors

In case the input is corrupted or the format or codec is not recognisable, UnsupportedFormatError would be thrown.

Logging Control

Log messages are single line text strings printed to console. The verbosity of the logging can be controlled through function options and environment variables.

Unless explicitly configured, nothing would be logged (quiet is true by default).

Options

Both getMediaInfo and extractAudio accept logging options:

  • quiet (boolean): Suppresses all console output. Default: true.
  • debug (boolean): Enables detailed debug logging. Default: false.
// Enable debug logs for troubleshooting
await getMediaInfoFromFile('video.mp4', { quiet: false, debug: true });

Note: If quiet is true, debug logging is automatically disabled.

Environment Variables

Environment variables take precedence over function options.

  • 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.js

Utility Functions (Node.js Only)

These functions are provided to help integrate Node.js filesystem operations with the library's Web Stream-based API.

createReadableStreamFromFile(filePath: string)

Creates a Web ReadableStream from a Node.js file path.

import { createReadableStreamFromFile } from '@handy-common-utils/media-utils';

const stream = await createReadableStreamFromFile('path/to/media.mp4');
// Now the stream can be passed to getMediaInfo or extractAudio

Important: The caller is responsible for consuming or explicitly cancelling the stream (stream.cancel()) to release the underlying file handle if the stream is not fully consumed. The good news is, getMediaInfo and extractAudio always does that.

readFromStreamToFile(stream: ReadableStream<Uint8Array>, filePath: string)

Reads a Web ReadableStream and writes its content to a file. The output directory is automatically created if it doesn't exist.

import { readFromStreamToFile } from '@handy-common-utils/media-utils';

// Assuming you have a ReadableStream from some processing
await readFromStreamToFile(myStream, 'path/to/output.mp4');

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? "auto" | "mp4box" | "remotion" | "isoboxer" | "media-utils" 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 -
GetMediaInfoResult -

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<GetMediaInfoResult>

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<GetMediaInfoResult>

The media information

Function: getMediaInfoFromFile()

getMediaInfoFromFile(filePath, options?): Promise<GetMediaInfoResult>

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<GetMediaInfoResult>

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.

Type Alias: GetMediaInfoResult

GetMediaInfoResult = MediaInfo & object

Type Declaration
Name Type Description
bytesRead? number Number of bytes read from the stream. In most cases, the parser does not need to read the whole stream.
parser Exclude<GetMediaInfoOptions["useParser"], undefined> -

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


createWritableStreamFromFile

Re-exports createWritableStreamFromFile


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


GetMediaInfoResult

Re-exports GetMediaInfoResult


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" | "mxf" | "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" | "mxf" | "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" | "mxf" | "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" | "mxf" | "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" | "mxf" | "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" | "mxf" | "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" | "mxf" | "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" | "mxf" | "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.essenceTrackNumber? number In an MXF file, the video and audio data (the "essence") are stored in packets called KLVs. Every essence KLV starts with a 16-byte Universal Label (UL) that acts as a header. The essenceTrackNumber is a 4-byte value (e.g., 0x15010000 or 0x16010000) that is embedded inside those 16-byte headers to identify which stream the data belongs to. - Prefix 0x15: Usually indicates Video essence. - Prefix 0x16: Usually indicates Sound essence. - The suffix: Differentiates between multiple tracks of the same type (e.g., 0x1601 for the first audio track, 0x1602 for the second).
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" | "mxf" | "wma" | "asf" | "ogg" | "aac" | "mp3" | "flac" | "wav" | "ac3" | "mp2" | "mp1" | "dts" -
containerDetail? string Parser-specific container information
durationInSeconds? number -
mimeType? string -
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
codecDetails? object -
codecDetails.essenceTrackNumber? number In an MXF file, the video and audio data (the "essence") are stored in packets called KLVs. Every essence KLV starts with a 16-byte Universal Label (UL) that acts as a header. The essenceTrackNumber is a 4-byte value (e.g., 0x15010000 or 0x16010000) that is embedded inside those 16-byte headers to identify which stream the data belongs to. - Prefix 0x15: Usually indicates Video essence. - Prefix 0x16: Usually indicates Sound essence. - The suffix: Differentiates between multiple tracks of the same type (e.g., 0x1601 for the first audio track, 0x1602 for the second).
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.
createWritableStreamFromFile Creates a Web WritableStream 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: createWritableStreamFromFile()

createWritableStreamFromFile(filePath): Promise<WritableStream<Uint8Array<ArrayBufferLike>>>

Creates a Web WritableStream 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<WritableStream<Uint8Array<ArrayBufferLike>>>

A (web) WritableStream of Uint8Array chunks

Function: ensureBufferData()

ensureBufferData(reader, buffer?, bufferOffset?, size?): Promise<{ buffer: Uint8Array; bufferOffset: number; bytesRead: 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; bytesRead: 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? "auto" | "mp4box" | "remotion" | "isoboxer" | "media-utils" 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

About

A pure-JS, no-FFmpeg media info parser and audio stream extractor which works with popular formats and codecs

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors

Languages