{"id":15710,"library":"mp4box","title":"MP4Box.js","description":"MP4Box.js is a robust JavaScript library designed for comprehensive processing of MP4 files, including parsing, segmentation, and sample extraction. It enables advanced functionalities directly within web browsers or Node.js environments, making it a critical tool for working with the Media Source Extensions (MSE) API for adaptive streaming. The current stable version is 2.3.0, with a history of frequent minor and patch releases, indicating active development and maintenance. Key differentiators include its progressive parsing capabilities, cross-platform support, and its direct inspiration from the well-established GPAC MP4Box tool, providing a powerful and familiar API for developers handling MP4 media.","status":"active","version":"2.3.0","language":"javascript","source_language":"en","source_url":"git://github.com/gpac/mp4box.js","tags":["javascript","mp4","HTML 5 media","Media Source Extension","streaming","typescript"],"install":[{"cmd":"npm install mp4box","lang":"bash","label":"npm"},{"cmd":"yarn add mp4box","lang":"bash","label":"yarn"},{"cmd":"pnpm add mp4box","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"The library exports a default object/namespace which contains the `createFile` factory and other utilities. The `require('mp4box')` syntax in the README is for CommonJS environments; use `import MP4Box from 'mp4box'` for modern ESM.","wrong":"import { MP4Box } from 'mp4box';","symbol":"MP4Box (default export)","correct":"import MP4Box from 'mp4box';"},{"note":"`createFile` is a method of the default `MP4Box` export, not a direct named export from the module. It acts as a factory to create an `MP4File` instance.","wrong":"import { createFile } from 'mp4box';","symbol":"createFile","correct":"const mp4boxfile = MP4Box.createFile();"},{"note":"For TypeScript projects, explicitly import types like `MP4File` (the interface for the object returned by `createFile()`), `MP4Info` (the structure passed to `onReady`), or `MP4Track` using `import type` for better clarity and bundler optimization.","symbol":"TypeScript Types (MP4File, MP4Info)","correct":"import type { MP4File, MP4Info, MP4Track } from 'mp4box';"}],"quickstart":{"code":"import MP4Box from 'mp4box';\n\nconst mp4boxfile = MP4Box.createFile();\nmp4boxfile.onError = function(e) {\n  console.error('MP4Box error:', e);\n};\nmp4boxfile.onMoovStart = function () {\n  console.log('Starting to receive File Information (moov box)');\n};\nmp4boxfile.onReady = function(info) {\n  console.log('Received File Information:', info);\n  // Example: Log track details\n  info.tracks.forEach(track => {\n    console.log(`Track ID: ${track.id}, Type: ${track.movie_type}, Codec: ${track.codec}, Duration: ${track.duration/track.timescale}s`);\n  });\n};\n\n// Simulate appending data (e.g., from a fetched MP4 file)\nasync function loadMp4Data() {\n  // In a real scenario, 'url' would be the path to your MP4 file\n  const url = 'https://raw.githubusercontent.com/gpac/mp4box.js/master/test/initial-media/mp4/frag_raw.mp4';\n  const response = await fetch(url);\n  const reader = response.body.getReader();\n  let offset = 0;\n  while (true) {\n    const { done, value } = await reader.read();\n    if (done) {\n      mp4boxfile.flush(); // Signal end of file\n      break;\n    }\n    const buffer = value.buffer; // value is a Uint8Array, get its underlying ArrayBuffer\n    buffer.fileStart = offset; // Important for MP4Box to track byte ranges\n    mp4boxfile.appendBuffer(buffer);\n    offset += buffer.byteLength;\n  }\n}\n\nloadMp4Data();","lang":"typescript","description":"This quickstart demonstrates how to progressively parse an MP4 file by fetching data chunks and appending them to an `MP4File` instance. It sets up `onMoovStart` and `onReady` callbacks to log file metadata as it becomes available. The example fetches a small MP4 from GitHub to simulate real-world usage."},"warnings":[{"fix":"Review your code for direct dependencies on `MP4BoxStream`. Adapt to use `DataStream` or other new APIs as per the v2.0.0 release notes and updated documentation. Most users interacting via `appendBuffer` should not be directly affected, but custom extensions might need updates.","message":"Version 2.0.0 introduced significant internal changes, including the replacement of `MP4BoxStream` with `DataStream`. This impacts custom implementations that might have directly interacted with the stream abstraction.","severity":"breaking","affected_versions":">=2.0.0"},{"fix":"Always use `import MP4Box from 'mp4box';` for ESM-enabled projects. Avoid `require()` in environments where ESM is the default or preferred module system to prevent errors like `ReferenceError: require is not defined`.","message":"The library's examples and default export behavior (especially with `require('mp4box')`) can be confusing for modern JavaScript projects. While it provides CommonJS compatibility, the preferred and most robust way to use `mp4box.js` in current Node.js and browser environments is via ESM `import` statements.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Ensure that `buffer.fileStart = currentOffset;` is set before calling `appendBuffer()`. If omitted, parsing errors or incorrect metadata extraction will occur, especially with fragmented or progressively loaded files.","message":"When appending data using `mp4boxfile.appendBuffer(buffer)`, it is crucial to set the `fileStart` property on the `ArrayBuffer` or `TypedArray` you provide. This property, indicating the byte offset of the buffer within the original file, is essential for `MP4Box.js` to correctly parse box offsets and structure.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-21T00:00:00.000Z","next_check":"2026-07-20T00:00:00.000Z","problems":[{"fix":"Change your import statement to `import MP4Box from 'mp4box';`.","cause":"Attempting to use `require('mp4box')` in an ECMAScript Module (ESM) context (e.g., in a `.mjs` file or a Node.js project with `\"type\": \"module\"` in package.json).","error":"ReferenceError: require is not defined"},{"fix":"Use the correct default import: `import MP4Box from 'mp4box';`.","cause":"Incorrectly importing the `MP4Box` object using named imports (e.g., `import { MP4Box } from 'mp4box';`) when it is exported as a default.","error":"TypeError: MP4Box.createFile is not a function"},{"fix":"Before calling `mp4boxfile.appendBuffer(buffer);`, ensure you set `buffer.fileStart = currentByteOffset;` where `currentByteOffset` is the starting position of that buffer's data in the complete file.","cause":"The `ArrayBuffer` passed to `appendBuffer` is missing the `fileStart` property, which indicates the byte offset of the buffer's data within the original file.","error":"Cannot read properties of undefined (reading 'fileStart') or similar parsing errors after appendBuffer"}],"ecosystem":"npm"}