mediainfo.js
repository·main·Indexed 21 days ago
https://github.com/buzz/mediainfo.jsA WebAssembly port of the MediaInfoLib C++ library for high-performance media metadata extraction in browsers and Node.js. It provides a JavaScript API via mediaInfoFactory to analyze video and audio files, supporting multiple output formats (object, JSON, XML, HTML, text) and a CLI for file inspection. The library includes specialized configurations for integration with Angular, Vite, React, and Webpack to handle the MediaInfoModule.wasm binary.
What's inside mediainfo.js
- mediainfo.js is a web-compatible version of the MediaInfoLib (originally written in C++), compiled to WebAssembly. It allows developers to extract media metadata in both browser environments and Node.js. It provides a high-performance way to inspect media files directly in the client or server-side JavaScript environments.
Configure Webpack for mediainfo.js WASM
mainWhen using
mediainfo.jswith Webpack, you must configure thewebpack.config.jsto ensure the WebAssembly (WASM) file is preserved with its original name and is discoverable via an alias. This prevents Webpack from renaming the file during the build process, which would break the internal loading mechanism of the library.// In webpack.config.js module.exports = { // 1. Preserve the original WASM filename assetModuleFilename: '[name][ext]', // 2. Make the WASM file discoverable via alias alias: { 'MediaInfoModule.wasm': wasmFilePath }, };Use mediainfo.js in a Vite + React project
mainTo use
mediainfo.jswith Vite and React, you should leverage Vite's asset pipeline to handle the WebAssembly (WASM) file. Instead of relying on relative paths that might break after bundling, import the WASM file as an asset URL using the?urlsuffix. This ensures Vite fingerprints the file and provides a reliable URL that can be passed to thelocateFileoption in themediaInfoFactoryconfiguration.import mediaInfoFactory from 'mediainfo.js' import mediaInfoWasmUrl from 'mediainfo.js/MediaInfoModule.wasm?url' await mediaInfoFactory({ locateFile: (path, prefix) => path === 'MediaInfoModule.wasm' ? mediaInfoWasmUrl : `${prefix}${path}`, })Configure MediaInfoModule.wasm assets in Angular
mainTo use
mediainfo.jsin an Angular project, you must ensure the WebAssembly module (MediaInfoModule.wasm) is included in your build assets. This allows the application to load the WASM binary at runtime. Add the following configuration to yourangular.jsonfile under theassetsarray of your build target:"assets": [ { "input": "node_modules/mediainfo.js/dist", "glob": "MediaInfoModule.wasm", "output": "" } ],Load the WASM file in React using locateFile
mainTo ensure
mediainfo.jscan find its required WebAssembly binary in a React application, you must provide alocateFilefunction to themediaInfoFactory. This function tells the library how to resolve the path to the.wasmfile. In a standard Webpack setup, you can override it to return the filename directly, allowing the alias configured in Webpack to handle the resolution.// In App.tsx const mediaInfo = await mediaInfoFactory({ locateFile: (filename) => filename, });Understand the BaseTrack @type and @typeorder properties
mainIn the
BaseTrackinterface, the@typeproperty identifies the category of the media track. Supported values are:GeneralVideoAudioTextImageMenuOther
The
@typeorderproperty (optional) provides a string indicating the sequence of tracks of the same type within the bitstream.Resolve Vite build warnings for MediaInfoModule.wasm
mainWhen usingmediainfo.jswith Vite, you may encounter a build warning related tonew URL('MediaInfoModule.wasm', import.meta.url)within the generated loader. This can be resolved by implementing a small transform plugin (e.g.,fixMediainfoWasmImportMetaUrl) in yourvite.config.tsto handle the import meta URL correctly.Configure MediaInfo output formats
mainWhen creating a
MediaInfoinstance via the factory, you can specify the outputformat. The availableFormatTypeoptions are:'object': Returns a parsed JavaScript object (MediaInfoResult). This is the default.'JSON': Returns a serialized JSON string.'XML': Returns a serialized XML string.'HTML': Returns a serialized HTML string.'text': Returns a serialized text string.
The
FORMAT_CHOICESconstant contains the string literals['JSON', 'XML', 'HTML', 'text']which correspond to the non-object formats.// The available format strings are: // 'JSON', 'XML', 'HTML', 'text'Configure MediaInfoFactoryOptions
mainWhen calling
mediaInfoFactory, you can pass aMediaInfoFactoryOptionsobject to customize the behavior of theMediaInfoinstance.Available options:
coverData(boolean): If true, output cover data as base64.chunkSize(number): The chunk size used byanalyzeDatain bytes.format(TFormat): The desired result format. Supported values areobject,JSON,XML,HTML, ortext.full(boolean): If true, provides full information display including all internal tags.locateFile(function): A function used to locate theMediaInfoModule.wasmfile. This is useful if the WASM file is hosted at a different URL than the default path. It follows the EmscriptenlocateFilepattern:(path: string, prefix: string) => string.
const options = { coverData: true, chunkSize: 1024 * 1024, format: 'JSON' as const, full: true, locateFile: (path: string, prefix: string) => `https://my-cdn.com/wasm/${path}` }; const mediaInfo = await mediaInfoFactory(options);How to use analyzeData with a callback
mainIf you prefer a callback-based approach over Promises,
analyzeDatasupports aResultCallbacksignature. The callback is invoked with(result, err), whereresultis the analyzed data (ornull) anderris an error object if the analysis fails.mediaInfo.analyzeData(size, readChunk, (result, err) => { if (err) { console.error('Analysis failed:', err); return; } console.log('Analysis result:', result); });Analyze media data using analyzeData()
mainThe
analyzeDatamethod is the primary way to process media files chunk by chunk. It is designed to work with large files by reading data in segments rather than loading the entire file into memory.It accepts two main arguments:
size: The total size of the buffer in bytes. This can be anumberor a function that returns aPromise<number>ornumber.readChunk: A function used to fetch the next segment of data. It receives thesizeto read and the currentoffset, and must return aUint8Arrayor aPromise<Uint8Array>.
The method returns a
Promisethat resolves with the analysis result (based on your configuredformat) or rejects if an error occurs. You can also provide a callback function instead of using the Promise.Note: You cannot start a new analysis while another is currently in progress on the same
MediaInfoinstance.// Example: Analyzing a file using a custom chunk reader const result = await mediaInfo.analyzeData( fileSize, async (size, offset) => { // Your logic to fetch a chunk from a File, Blob, or network const chunk = await fetchChunk(offset, size); return new Uint8Array(chunk); } );Initialize MediaInfo using mediaInfoFactory
mainUse
mediaInfoFactoryto create a newMediaInfoinstance. This function is asynchronous and handles the loading of the underlying WASM module. You can use it in two ways:- Promise-based: Call it with options to receive a
Promisethat resolves to aMediaInfoinstance. - Callback-based: Provide a success callback and an optional error callback.
By default, the output format is set to
objectunless specified otherwise in the options.import mediaInfoFactory from './mediaInfoFactory.js'; // Promise approach const mediaInfo = await mediaInfoFactory({ format: 'JSON' }); // Callback approach mediaInfoFactory( { format: 'XML' }, (instance) => { console.log('MediaInfo ready:', instance); }, (err) => { console.error('Failed to load MediaInfo:', err); } );- Promise-based: Call it with options to receive a