Compare commits

...
8 Commits
24 changed files with 285 additions and 129 deletions
+11 -7
View File
@@ -696,18 +696,18 @@ type FilePathSourceOptions = {
When using this source, make sure to manually [dispose of the Input](#disposing-inputs) when you are done with it to properly close the internal file handle held by this source.
:::
### `StreamSource`
### `CustomSource`
This is a general-purpose input source you can use to read data from anywhere.
For example, here we're reading a file from disk using the Node.js file system (although you should use [`FilePathSource`](#filepathsource) for that):
For example, here we're reading a file from disk using the Node.js file system (although you should use the existing [`FilePathSource`](#filepathsource) for that):
```ts
import { StreamSource } from 'mediabunny';
import { CustomSource } from 'mediabunny';
import { open } from 'node:fs/promises';
const fileHandle = await open('bigbuckbunny.mp4', 'r');
const source = new StreamSource({
const source = new CustomSource({
read: async (start, end) => {
const buffer = Buffer.alloc(end - start);
await fileHandle.read(buffer, 0, end - start, start);
@@ -720,9 +720,9 @@ const source = new StreamSource({
});
```
The options of `StreamSource` have the following type:
The options of `CustomSource` have the following type:
```ts
type StreamSourceOptions = {
type CustomSourceOptions = {
getSize: () => MaybePromise<number>;
read: (start: number, end: number) => MaybePromise<Uint8Array | ReadableStream<Uint8Array>>;
dispose?: () => unknown;
@@ -736,7 +736,7 @@ type MaybePromise<T> = T | Promise<T>;
- `getSize`\
Called when the size of the entire file is requested. Must return or resolve to the size in bytes. This function is guaranteed to be called before `read`.
- `read`\
Called when data is requested. Must return or resolve to the bytes from the specified byte range, or a stream that yields these bytes.
Called when data is requested. Must return or resolve to the bytes from the specified byte range, or a stream that yields these bytes. You are guaranteed that `0 <= start < end < fileSize`.
- `dispose`\
Called when the `Input` driven by this source is disposed.
- `maxCacheSize`\
@@ -747,6 +747,10 @@ type MaybePromise<T> = T | Promise<T>;
- `'fileSystem'`: File system-optimized prefetching: a small amount of data is prefetched bidirectionally, aligned with page boundaries.
- `'network'`: Network-optimized prefetching, or more generally, prefetching optimized for any high-latency environment: tries to minimize the amount of read calls and aggressively prefetches data when sequential access patterns are detected.
::: info
`CustomSource` was previously known as `StreamSource` and is still available under that alias, but usage of `StreamSource` is deprecated.
:::
### `ReadableStreamSource`
This is a source backed by a `ReadableStream` of `Uint8Array`, representing an append-only byte stream of unknown length. This is the source to use for incrementally streaming in input files that are still being constructed and whose size we don't yet know. You could also use it to stream in existing files, but other sources (such as [`BlobSource`](#blobsource) or [`FilePathSource`](#filepathsource)) are recommended instead because they offer random access.
+1
View File
@@ -148,6 +148,7 @@ const sponsors = {
{ image: 'https://avatars.githubusercontent.com/u/13042781', name: 'Anshul Bansal', url: 'https://github.com/akbansa' },
{ image: 'https://avatars.githubusercontent.com/u/43105172', name: 'zhmou', url: 'https://github.com/zhmou' },
{ image: 'https://avatars.githubusercontent.com/u/695166', name: 'Takenori Nakagawa', url: 'https://github.com/ww24' },
{ image: 'https://avatars.githubusercontent.com/u/43607012', name: 'Sturlen', url: 'https://github.com/Sturlen' },
],
};
</script>
+7 -7
View File
@@ -1,12 +1,12 @@
{
"name": "mediabunny",
"version": "1.45.2",
"version": "1.45.4",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "mediabunny",
"version": "1.45.2",
"version": "1.45.4",
"license": "MPL-2.0",
"workspaces": [
".",
@@ -12806,7 +12806,7 @@
},
"packages/aac-encoder": {
"name": "@mediabunny/aac-encoder",
"version": "1.45.2",
"version": "1.45.4",
"license": "MPL-2.0",
"devDependencies": {
"@types/emscripten": "^1.40.1"
@@ -12821,7 +12821,7 @@
},
"packages/ac3": {
"name": "@mediabunny/ac3",
"version": "1.45.2",
"version": "1.45.4",
"license": "MPL-2.0",
"devDependencies": {
"@types/emscripten": "^1.40.1"
@@ -12836,7 +12836,7 @@
},
"packages/flac-encoder": {
"name": "@mediabunny/flac-encoder",
"version": "1.45.2",
"version": "1.45.4",
"license": "MPL-2.0",
"devDependencies": {
"@types/emscripten": "^1.40.1"
@@ -12851,7 +12851,7 @@
},
"packages/mp3-encoder": {
"name": "@mediabunny/mp3-encoder",
"version": "1.45.2",
"version": "1.45.4",
"license": "MPL-2.0",
"devDependencies": {
"@types/emscripten": "^1.40.1"
@@ -12866,7 +12866,7 @@
},
"packages/server": {
"name": "@mediabunny/server",
"version": "1.45.2",
"version": "1.45.4",
"license": "MPL-2.0",
"dependencies": {
"node-av": "^5.2.4"
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "mediabunny",
"author": "Vanilagy",
"version": "1.45.2",
"version": "1.45.4",
"description": "Pure TypeScript media toolkit for reading, writing, and converting media files, directly in the browser.",
"type": "module",
"workspaces": [
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "@mediabunny/aac-encoder",
"author": "Vanilagy",
"version": "1.45.2",
"version": "1.45.4",
"description": "AAC encoder extension for Mediabunny, based on FFmpeg.",
"main": "./dist/bundles/mediabunny-aac-encoder.mjs",
"module": "./dist/bundles/mediabunny-aac-encoder.mjs",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "@mediabunny/ac3",
"author": "Vanilagy",
"version": "1.45.2",
"version": "1.45.4",
"description": "AC-3 and E-AC-3 (Dolby Digital) decoder and encoder extension for Mediabunny, based on FFmpeg.",
"main": "./dist/bundles/mediabunny-ac3.mjs",
"module": "./dist/bundles/mediabunny-ac3.mjs",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "@mediabunny/flac-encoder",
"author": "Vanilagy",
"version": "1.45.2",
"version": "1.45.4",
"description": "FLAC encoder extension for Mediabunny, based on libFLAC.",
"main": "./dist/bundles/mediabunny-flac-encoder.mjs",
"module": "./dist/bundles/mediabunny-flac-encoder.mjs",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "@mediabunny/mp3-encoder",
"author": "Vanilagy",
"version": "1.45.2",
"version": "1.45.4",
"description": "MP3 encoder extension for Mediabunny, based on LAME.",
"main": "./dist/bundles/mediabunny-mp3-encoder.mjs",
"module": "./dist/bundles/mediabunny-mp3-encoder.mjs",
+2 -2
View File
@@ -7,7 +7,7 @@
*/
import { CustomAudioEncoder, AudioCodec, AudioSample, EncodedPacket, registerEncoder } from 'mediabunny';
import { FRAME_HEADER_SIZE, readMp3FrameHeader, SAMPLING_RATES } from '../../../shared/mp3-misc';
import { MP3_FRAME_HEADER_SIZE, readMp3FrameHeader, SAMPLING_RATES } from '../../../shared/mp3-misc';
import type { WorkerCommand, WorkerResponse, WorkerResponseData } from './shared';
// @ts-expect-error An esbuild plugin handles this, TypeScript doesn't need to understand
import createWorker from './encode.worker';
@@ -160,7 +160,7 @@ class Mp3Encoder extends CustomAudioEncoder {
this.currentBufferOffset = requiredBufferSize;
let pos = 0;
while (pos <= this.currentBufferOffset - FRAME_HEADER_SIZE) {
while (pos <= this.currentBufferOffset - MP3_FRAME_HEADER_SIZE) {
const word = new DataView(this.buffer.buffer).getUint32(pos, false);
const header = readMp3FrameHeader(word, null).header;
if (!header) {
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "@mediabunny/server",
"author": "Vanilagy",
"version": "1.45.2",
"version": "1.45.4",
"description": "Adds full video and audio decoder and encoder support to Mediabunny for use in server-side environments (Node, Bun, Deno). Based on NodeAV.",
"main": "./dist/bundles/mediabunny-server.cjs",
"module": "./dist/bundles/mediabunny-server.mjs",
+64 -37
View File
@@ -83,12 +83,12 @@ const generateDocs = (entryFiles: string[], apiConfigFile: string, dry = false)
const declaration = exportSymbol.valueDeclaration || exportSymbol.declarations?.[0];
if (!declaration) return;
// Collect classes, interfaces, types, enums, variables (only if @public and not @deprecated)
// Collect classes, interfaces, types, enums, variables (only if @public)
if (ts.isClassDeclaration(declaration) || ts.isInterfaceDeclaration(declaration)
|| ts.isTypeAliasDeclaration(declaration) || ts.isEnumDeclaration(declaration)
|| ts.isVariableDeclaration(declaration)) {
const hasPublicTag = ts.getJSDocTags(declaration).some(tag => tag.tagName.text === 'public');
if (hasPublicTag && !hasDeprecatedTag(declaration)) {
if (hasPublicTag) {
exportedTypes.add(exportSymbol.getName());
}
}
@@ -98,9 +98,9 @@ const generateDocs = (entryFiles: string[], apiConfigFile: string, dry = false)
const aliasedSymbol = typeChecker.getAliasedSymbol(exportSymbol);
const aliasedDeclaration = aliasedSymbol.valueDeclaration || aliasedSymbol.declarations?.[0];
if (aliasedDeclaration) {
// Check if the aliased symbol has @public tag and is not deprecated
// Check if the aliased symbol has @public tag
const hasPublicTag = ts.getJSDocTags(aliasedDeclaration).some(tag => tag.tagName.text === 'public');
if (hasPublicTag && !hasDeprecatedTag(aliasedDeclaration)) {
if (hasPublicTag) {
exportedTypes.add(exportSymbol.getName());
}
@@ -139,10 +139,10 @@ const generateDocs = (entryFiles: string[], apiConfigFile: string, dry = false)
}
}
}
// Otherwise, add any symbol with @public tag and not @deprecated (we'll filter by type later)
// Otherwise, add any symbol with @public tag (we'll filter by type later)
else {
const hasPublicTag = ts.getJSDocTags(declaration).some(tag => tag.tagName.text === 'public');
if (hasPublicTag && !hasDeprecatedTag(declaration)) {
if (hasPublicTag) {
symbols.push(exportSymbol);
}
}
@@ -379,6 +379,34 @@ const generateDocs = (entryFiles: string[], apiConfigFile: string, dry = false)
});
};
// Helper to build a "> **Deprecated.** ..." notice from a node's @deprecated JSDoc tag.
// Returns an empty string if the node has no @deprecated tag.
const getDeprecationNotice = (node: ts.Node, currentTypeName?: string): string => {
const tag = ts.getJSDocTags(node).find(t => t.tagName.text === 'deprecated');
if (!tag) {
return '';
}
let text = '';
if (tag.comment) {
if (typeof tag.comment === 'string') {
text = processLinkTags(tag.comment.trim(), currentTypeName);
} else {
// comment is a NodeArray of JSDocComment elements (text + inline tags)
const raw = tag.comment.map((part) => {
if (ts.isJSDocLinkLike(part)) {
const linkName = part.name?.getText() ?? '';
const linkText = part.text?.trim() ?? '';
// Reconstruct as {@link Name text}
return `{@link ${linkName}${linkText ? ' ' + linkText : ''}}`;
}
return part.text ?? '';
}).join('');
text = processLinkTags(raw.trim(), currentTypeName);
}
}
return text ? `> **Deprecated.** ${text}\n\n` : '> **Deprecated.**\n\n';
};
// Helper to extract linked types from {@link} tags in text
const extractLinkedTypes = (text: string): string[] => {
if (!text) return [];
@@ -627,10 +655,11 @@ const generateDocs = (entryFiles: string[], apiConfigFile: string, dry = false)
const nodeKind = ts.SyntaxKind[declaration.kind];
const symbolName = (declaration as any).name?.getText() || exportSymbol.getName();
// Only process symbols with @public tag, and skip deprecated ones entirely
// Only process symbols with @public tag
const hasPublicTag = ts.getJSDocTags(declaration).some(tag => tag.tagName.text === 'public');
if (!hasPublicTag) return;
if (hasDeprecatedTag(declaration)) return;
if (!hasPublicTag) {
return;
}
// Check for @group tag (handle re-exports by looking at the original declaration)
let targetDeclaration = declaration;
@@ -714,7 +743,8 @@ const generateDocs = (entryFiles: string[], apiConfigFile: string, dry = false)
? `${variableName}(\n${params.join(',\n')},\n): ${returnType};`
: `${variableName}(): ${returnType};`;
let markdown = `${buildFrontmatter(description)}<script setup>\nimport { VPBadge } from 'vitepress/theme'\n</script>\n\n<VPBadge type="info" text="Function" />\n\n# ${variableName}\n\n\`\`\`ts\n${functionSig}\n\`\`\`${description ? `\n\n${description}` : ''}`;
const deprecationNotice = getDeprecationNotice(declaration, variableName);
let markdown = `${buildFrontmatter(description)}<script setup>\nimport { VPBadge } from 'vitepress/theme'\n</script>\n\n<VPBadge type="info" text="Function" />\n\n# ${variableName}\n\n${deprecationNotice}\`\`\`ts\n${functionSig}\n\`\`\`${description ? `\n\n${description}` : ''}`;
// Find referenced types in all parameters and return type
const allTypeStrings = params.map(p => p.replace(/\t.*?:\s*/, '')).concat([returnType]);
@@ -728,7 +758,8 @@ const generateDocs = (entryFiles: string[], apiConfigFile: string, dry = false)
}
} else {
// Handle regular variables
let markdown = `${buildFrontmatter(description)}<script setup>\nimport { VPBadge } from 'vitepress/theme'\n</script>\n\n<VPBadge type="info" text="Constant" />\n\n# ${variableName}\n\n${description ? `${description}\n\n` : ''}`;
const deprecationNotice = getDeprecationNotice(declaration, variableName);
let markdown = `${buildFrontmatter(description)}<script setup>\nimport { VPBadge } from 'vitepress/theme'\n</script>\n\n<VPBadge type="info" text="Constant" />\n\n# ${variableName}\n\n${deprecationNotice}${description ? `${description}\n\n` : ''}`;
const variableValue = declaration.initializer ? declaration.initializer.getText() : 'undefined';
const variableDefinition = `const ${variableName} = ${variableValue};`;
markdown += `\`\`\`ts\n${variableDefinition}\n\`\`\``;
@@ -971,33 +1002,10 @@ const generateDocs = (entryFiles: string[], apiConfigFile: string, dry = false)
const isDeprecatedMember = hasDeprecatedTag(member);
const getDeprecationNotice = () => {
const tag = ts.getJSDocTags(member).find(t => t.tagName.text === 'deprecated');
let text = '';
if (tag?.comment) {
if (typeof tag.comment === 'string') {
text = processLinkTags(tag.comment.trim(), className);
} else {
// comment is a NodeArray of JSDocComment elements (text + inline tags)
const raw = tag.comment.map((part) => {
if (ts.isJSDocLinkLike(part)) {
const linkName = part.name?.getText() ?? '';
const linkText = part.text?.trim() ?? '';
// Reconstruct as {@link Name text}
return `{@link ${linkName}${linkText ? ' ' + linkText : ''}}`;
}
return part.text ?? '';
}).join('');
text = processLinkTags(raw.trim(), className);
}
}
return text ? `> **Deprecated.** ${text}\n\n` : '> **Deprecated.**\n\n';
};
const addDeprecationNotice = (content: string) => {
// Insert the deprecation notice right after the heading line
const headingEnd = content.indexOf('\n');
return content.slice(0, headingEnd) + '\n\n' + getDeprecationNotice() + content.slice(headingEnd + 1);
return content.slice(0, headingEnd) + '\n\n' + getDeprecationNotice(member, className) + content.slice(headingEnd + 1);
};
const pushProperty = (content: string) => {
@@ -1529,7 +1537,8 @@ const generateDocs = (entryFiles: string[], apiConfigFile: string, dry = false)
markdown += `<VPBadge type="info" text="Interface" />\n\n`;
}
markdown += `# ${className}\n\n${description ? `${description}\n` : ''}${extendsClause}${implementsClause}`;
const deprecationNotice = getDeprecationNotice(declaration, className);
markdown += `# ${className}\n\n${deprecationNotice}${description ? `${description}\n` : ''}${extendsClause}${implementsClause}`;
// Add subclasses section for classes that have subclasses
if (ts.isClassDeclaration(declaration) && classHierarchy.has(className)) {
@@ -1900,7 +1909,25 @@ const extractJsDocDescription = (
descLines.push(line);
}
} else {
descLines = lines.filter(line => !line.trim().startsWith('@'));
// Skip @tag lines and their continuation lines (continuation ends at a blank line
// or the next @tag). Without this, multi-line tags like @deprecated bleed into the
// description.
descLines = [];
let inTagContinuation = false;
for (const line of lines) {
const trimmed = line.trim();
if (trimmed.startsWith('@')) {
inTagContinuation = true;
continue;
}
if (inTagContinuation) {
if (trimmed === '') {
inTagContinuation = false;
}
continue;
}
descLines.push(line);
}
}
const rawDesc = descLines.join('\n').trim();
+7 -2
View File
@@ -6,7 +6,7 @@
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
export const FRAME_HEADER_SIZE = 4;
export const MP3_FRAME_HEADER_SIZE = 4;
export const SAMPLING_RATES = [44100, 48000, 32000];
export const KILOBIT_RATES = [
// lowSamplingFrequency === 0
@@ -122,7 +122,8 @@ export const readMp3FrameHeader = (word: number, remainingBytes: number | null):
const layer = (secondByte >> 1) & 0x3;
const bitrateIndex = (thirdByte >> 4) & 0xf;
const frequencyIndex = ((thirdByte >> 2) & 0x3) % 3;
const frequencyIndex = ((thirdByte >> 2) & 0x3) % 3; // FFmpeg effectively does % 3 (but in a roundabout way)
const padding = (thirdByte >> 1) & 0x1;
const channel = (fourthByte >> 6) & 0x3;
@@ -212,3 +213,7 @@ export enum XingFlags {
FileSize = 1 << 1,
Toc = 1 << 2,
}
export const getMp3ChannelCount = (channel: number) => {
return channel === 3 ? 1 : 2;
};
+2 -2
View File
@@ -93,7 +93,7 @@ export const parseId3V1Tag = (slice: FileSlice, tags: MetadataTags) => {
const yearText = readId3V1String(slice, 4);
const year = Number.parseInt(yearText, 10);
if (Number.isInteger(year) && year > 0) {
tags.date ??= new Date(year, 0, 1);
tags.date ??= new Date(String(year)); // String so that it parses as UTC
}
const commentBytes = readBytes(slice, 30);
@@ -339,7 +339,7 @@ export const parseId3V2Tag = (slice: FileSlice, header: Id3V2Header, tags: Metad
const year = Number.parseInt(yearText, 10);
if (Number.isInteger(year)) {
tags.date ??= new Date(year, 0, 1);
tags.date ??= new Date(String(year)); // String so that it parses as UTC
}
}; break;
+4
View File
@@ -173,10 +173,14 @@ export {
type BlobSourceOptions,
BufferSource,
CustomPathedSource,
CustomSource,
type CustomSourceOptions,
FilePathSource,
type FilePathSourceOptions,
PathedSource,
// eslint-disable-next-line @typescript-eslint/no-deprecated
StreamSource,
// eslint-disable-next-line @typescript-eslint/no-deprecated
type StreamSourceOptions,
RangedSource,
ReadableStreamSource,
+6 -2
View File
@@ -22,7 +22,7 @@ import {
} from './matroska/ebml';
import { MatroskaDemuxer } from './matroska/matroska-demuxer';
import { Mp3Demuxer } from './mp3/mp3-demuxer';
import { FRAME_HEADER_SIZE, getXingOffset, INFO, XING } from '../shared/mp3-misc';
import { MP3_FRAME_HEADER_SIZE, getXingOffset, INFO, XING } from '../shared/mp3-misc';
import { ID3_V2_HEADER_SIZE, readId3V2Header } from './id3';
import { readNextMp3FrameHeader } from './mp3/mp3-reader';
import { OggDemuxer } from './ogg/ogg-demuxer';
@@ -330,7 +330,11 @@ export class Mp3InputFormat extends InputFormat {
// Fine, we found one frame header, but we're still not entirely sure this is MP3. Let's check if we can find
// another header right after it:
const secondResult = await readNextMp3FrameHeader(input._reader, currentPos, currentPos + FRAME_HEADER_SIZE);
const secondResult = await readNextMp3FrameHeader(
input._reader,
currentPos,
currentPos + MP3_FRAME_HEADER_SIZE,
);
if (!secondResult) {
return false;
}
-14
View File
@@ -45,17 +45,6 @@ polyfillSymbolDispose();
export const DEFAULT_SOURCE_CACHE_GROUP = 1;
export const ENCRYPTION_KEY_CACHE_GROUP = 2;
let inputFinalizationRegistry: FinalizationRegistry<SourceRef[]> | null = null;
if (typeof FinalizationRegistry !== 'undefined') {
inputFinalizationRegistry = new FinalizationRegistry((refs) => {
for (const ref of refs) {
if (!ref.freed) {
ref.free();
}
}
});
}
/**
* The options for creating an Input object.
* @group Input files & tracks
@@ -191,7 +180,6 @@ export class Input<S extends Source = Source> extends EventEmitter<InputEvents>
}
this._sourceRefs.push(this._rootRef);
inputFinalizationRegistry?.register(this, this._sourceRefs, this);
}
/** @internal */
@@ -539,8 +527,6 @@ export class Input<S extends Source = Source> extends EventEmitter<InputEvents>
}
this._sourceRefs.length = 0;
inputFinalizationRegistry?.unregister(this);
void this._demuxerPromise
?.then(demuxer => demuxer.dispose());
}
+23 -6
View File
@@ -46,7 +46,7 @@ import {
customVideoEncoders,
customAudioEncoders,
} from './custom-coder';
import { EncodedPacket, EncodedPacketSideData } from './packet';
import { EncodedPacket, EncodedPacketSideData, PacketType } from './packet';
import {
AudioSample,
audioSampleToInterleavedFormat,
@@ -63,6 +63,7 @@ import {
VideoEncodingConfig,
} from './encode';
import { AudioResampler } from './resample';
import { determineVideoPacketType } from './codec-data';
/**
* Base class for media sources. Media sources are used to add media samples to an output file.
@@ -224,6 +225,7 @@ class VideoEncoderWrapper {
private encoder: VideoEncoder | null = null;
private muxer: Muxer | null = null;
private lastMultipleOfKeyFrameInterval = -1;
private emittedEncoderPackets = 0;
// Tracks the input dimensions of the first frame
private codedWidth: number | null = null;
@@ -694,6 +696,7 @@ class VideoEncoderWrapper {
let packet = EncodedPacket.fromEncodedChunk(colorChunk, sideData);
// See if there's a relevant timing entry to refine the packet's timing data
const preciseTimingIndex = binarySearchLessOrEqual(
this.preciseTimings,
colorChunk.timestamp,
@@ -703,12 +706,24 @@ class VideoEncoderWrapper {
? this.preciseTimings[preciseTimingIndex]
: null;
// If there's a relevant timing entry, refine the packet's timing data to get better accuracy than
// microseconds
if (entry && entry.microsecondTimestamp === colorChunk.timestamp) {
let actualType: PacketType | null = null;
if (this.emittedEncoderPackets === 0 && packet.type === 'delta' && meta?.decoderConfig) {
// https://github.com/Vanilagy/mediabunny/issues/365
// We expect the first packet to be a key packet. If it's not, let's actually verify that it's
// not by getting the actual type.
actualType = determineVideoPacketType(
this.encodingConfig.codec,
meta.decoderConfig,
packet.data,
);
}
// Define the packet
if ((entry && entry.microsecondTimestamp === colorChunk.timestamp) || actualType !== null) {
packet = packet.clone({
timestamp: entry.timestampIsValid ? entry.timestamp : undefined,
duration: entry.durationIsValid ? entry.duration : undefined,
timestamp: entry?.timestampIsValid ? entry.timestamp : undefined,
duration: entry?.durationIsValid ? entry.duration : undefined,
type: actualType ?? undefined,
});
}
@@ -720,6 +735,8 @@ class VideoEncoderWrapper {
.catch((error) => {
this.error ??= error;
});
this.emittedEncoderPackets++;
};
const stack = new Error('Encoding error').stack;
+9 -10
View File
@@ -28,6 +28,7 @@ import {
XING,
XingFlags,
computeAverageMp3FrameSize,
getMp3ChannelCount,
} from '../../shared/mp3-misc';
import {
ID3_V1_TAG_SIZE,
@@ -108,7 +109,12 @@ export class Mp3Demuxer extends Demuxer {
}
}
const result = await readNextMp3FrameHeader(this.reader, this.lastLoadedPos, this.reader.fileSize);
const result = await readNextMp3FrameHeader(
this.reader,
this.lastLoadedPos,
this.reader.fileSize,
this.firstFrameHeader,
);
if (!result) {
this.lastSampleLoaded = true;
return;
@@ -157,13 +163,6 @@ export class Mp3Demuxer extends Demuxer {
this.firstFrameHeaderPos = result.startPos;
}
if (header.sampleRate !== this.firstFrameHeader.sampleRate) {
console.warn(
`MP3 changed sample rate mid-file: ${this.firstFrameHeader.sampleRate} Hz to ${header.sampleRate} Hz.`
+ ` Might be a bug, so please report this file.`,
);
}
const sampleDuration = header.audioSamplesInFrame / this.firstFrameHeader.sampleRate;
const sample: Sample = {
timestamp: this.nextTimestampInSamples / this.firstFrameHeader.sampleRate,
@@ -332,7 +331,7 @@ class Mp3AudioTrackBacking implements InputAudioTrackBacking {
getNumberOfChannels() {
assert(this.demuxer.firstFrameHeader);
return this.demuxer.firstFrameHeader.channel === 3 ? 1 : 2;
return getMp3ChannelCount(this.demuxer.firstFrameHeader.channel);
}
getSampleRate() {
@@ -351,7 +350,7 @@ class Mp3AudioTrackBacking implements InputAudioTrackBacking {
return {
codec: 'mp3',
numberOfChannels: this.demuxer.firstFrameHeader.channel === 3 ? 1 : 2,
numberOfChannels: getMp3ChannelCount(this.demuxer.firstFrameHeader.channel),
sampleRate: this.demuxer.firstFrameHeader.sampleRate,
};
}
+21 -6
View File
@@ -6,10 +6,15 @@
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
import { FRAME_HEADER_SIZE, Mp3FrameHeader, readMp3FrameHeader } from '../../shared/mp3-misc';
import { MP3_FRAME_HEADER_SIZE, getMp3ChannelCount, Mp3FrameHeader, readMp3FrameHeader } from '../../shared/mp3-misc';
import { Reader, readU32Be } from '../reader';
export const readNextMp3FrameHeader = async (reader: Reader, startPos: number, until: number | null): Promise<{
export const readNextMp3FrameHeader = async (
reader: Reader,
startPos: number,
until: number | null,
ref: Mp3FrameHeader | null = null,
): Promise<{
header: Mp3FrameHeader;
startPos: number;
} | null> => {
@@ -21,11 +26,11 @@ export const readNextMp3FrameHeader = async (reader: Reader, startPos: number, u
? Math.min(CHUNK_SIZE, until - currentPos)
: CHUNK_SIZE;
let slice = reader.requestSliceRange(currentPos, FRAME_HEADER_SIZE, maxLength);
let slice = reader.requestSliceRange(currentPos, MP3_FRAME_HEADER_SIZE, maxLength);
if (slice instanceof Promise) slice = await slice;
if (!slice || slice.length < FRAME_HEADER_SIZE) break;
if (!slice || slice.length < MP3_FRAME_HEADER_SIZE) break;
while (slice.remainingLength >= FRAME_HEADER_SIZE) {
while (slice.remainingLength >= MP3_FRAME_HEADER_SIZE) {
const posBeforeRead = slice.filePos;
const word = readU32Be(slice);
const remainingBytes = reader.fileSize !== null
@@ -33,7 +38,17 @@ export const readNextMp3FrameHeader = async (reader: Reader, startPos: number, u
: null;
const result = readMp3FrameHeader(word, remainingBytes);
if (result.header) {
if (
result.header
&& (!ref || (
// This condition helps us recover malformed streams
// https://stackoverflow.com/a/20884944
result.header.sampleRate === ref.sampleRate
&& result.header.mpegVersionId === ref.mpegVersionId
&& result.header.layer === ref.layer
&& getMp3ChannelCount(result.header.channel) === getMp3ChannelCount(ref.channel)
))
) {
return { header: result.header, startPos: currentPos };
}
+6 -2
View File
@@ -63,7 +63,11 @@ import {
TRANSFER_CHARACTERISTICS_MAP_INVERSE,
UNDETERMINED_LANGUAGE,
} from '../misc';
import { FRAME_HEADER_SIZE as MP3_FRAME_HEADER_SIZE, readMp3FrameHeader } from '../../shared/mp3-misc';
import {
MP3_FRAME_HEADER_SIZE,
getMp3ChannelCount,
readMp3FrameHeader,
} from '../../shared/mp3-misc';
import { EncodedPacket, PacketType, PLACEHOLDER_DATA } from '../packet';
import { FileSlice, readBytes, Reader, readU16Be, readU32Be, readU8 } from '../reader';
import { buildMpegTsMimeType, MpegTsStreamType, TIMESCALE, TS_PACKET_SIZE } from './mpeg-ts-misc';
@@ -629,7 +633,7 @@ export class MpegTsDemuxer extends Demuxer {
);
}
elementaryStream.info.numberOfChannels = result.header.channel === 3 ? 1 : 2;
elementaryStream.info.numberOfChannels = getMp3ChannelCount(result.header.channel);
elementaryStream.info.sampleRate = result.header.sampleRate;
} else if (elementaryStream.info.codec === 'ac3') {
const frameInfo = parseAc3SyncFrame(context.suppliedPacket.data);
+93 -24
View File
@@ -59,6 +59,13 @@ export type SourceEvents = {
};
};
let sourceFinalizationRegistry: FinalizationRegistry<() => unknown> | null = null;
if (typeof FinalizationRegistry !== 'undefined') {
sourceFinalizationRegistry = new FinalizationRegistry((cleanup) => {
cleanup();
});
}
/**
* The source base class, representing a resource from which bytes can be read.
* @group Input sources
@@ -85,10 +92,27 @@ export abstract class Source extends EventEmitter<SourceEvents> {
* @internal
*/
_usedForHls = false;
/**
* FinalizationRegistry for rogue refs to this source that didn't get freed. It lives on the Source itself so that
* in case the Source transitively points back to itself and forms a cycle (for example through a custom
* CustomSource callback) that we're not leaking memory.
* @internal
*/
_refFinalizationRegistry: FinalizationRegistry<Source> | null = null;
/** @internal */
private _sizePromise: Promise<number | null> | null = null;
constructor() {
super();
if (typeof FinalizationRegistry !== 'undefined') {
this._refFinalizationRegistry = new FinalizationRegistry((source) => {
source._decrementRefCount();
});
}
}
/**
* Resolves with the total size of the file in bytes. This function is memoized, meaning only the first call
* will retrieve the size.
@@ -171,6 +195,21 @@ export abstract class Source extends EventEmitter<SourceEvents> {
ref() {
return new SourceRef(this);
}
/** @internal */
_incrementRefCount() {
this._refCount++;
}
/** @internal */
_decrementRefCount() {
this._refCount--;
if (this._refCount === 0) {
this._dispose();
this._disposed = true;
}
}
}
/**
@@ -193,7 +232,9 @@ export class SourceRef<S extends Source = Source> implements Disposable {
throw new Error('Cannot ref a disposed source.');
}
source._refCount++;
source._incrementRefCount();
source._refFinalizationRegistry?.register(this, source, this);
this._source = source;
}
@@ -223,12 +264,8 @@ export class SourceRef<S extends Source = Source> implements Disposable {
const source = this.source;
assert(source._refCount > 0);
source._refCount--;
if (source._refCount === 0) {
source._dispose();
source._disposed = true;
}
source._decrementRefCount();
source._refFinalizationRegistry?.unregister(this);
this._freed = true;
this._source = null;
@@ -955,7 +992,7 @@ export type FilePathSourceOptions = {
*/
export class FilePathSource extends PathedSource {
/** @internal */
_streamSource: StreamSource;
_customSource: CustomSource;
/** @internal */
_fileHandle: FileHandle | null = null;
@@ -982,12 +1019,18 @@ export class FilePathSource extends PathedSource {
super(filePath, request => new FilePathSource(request.path, options));
// Let's back this source with a StreamSource, makes the implementation very simple
this._streamSource = new StreamSource({
// Let's back this source with a CustomSource, makes the implementation very simple
this._customSource = new CustomSource({
getSize: async () => {
this._fileHandle = await node.fs.open(filePath, 'r');
const fileHandle = await node.fs.open(filePath, 'r');
this._fileHandle = fileHandle;
const stats = await this._fileHandle.stat();
sourceFinalizationRegistry?.register(this, () => {
// If it's not closed, Node prints annoying warnings
void fileHandle.close();
}, this);
const stats = await fileHandle.stat();
return stats.size;
},
read: async (start, end) => {
@@ -1010,28 +1053,32 @@ export class FilePathSource extends PathedSource {
minReadPosition: number,
maxReadPosition: number,
): MaybePromise<ReadResult | null> {
return this._streamSource._read(start, end, minReadPosition, maxReadPosition);
return this._customSource._read(start, end, minReadPosition, maxReadPosition);
}
/** @internal */
_getFileSize(): number | null | undefined {
return this._streamSource._getFileSize();
return this._customSource._getFileSize();
}
/** @internal */
_dispose() {
this._streamSource._dispose();
void this._fileHandle?.close();
this._fileHandle = null;
this._customSource._dispose();
if (this._fileHandle) {
void this._fileHandle.close();
this._fileHandle = null;
sourceFinalizationRegistry?.unregister(this);
}
}
}
/**
* Options for defining a {@link StreamSource}.
* Options for defining a {@link CustomSource}.
* @group Input sources
* @public
*/
export type StreamSourceOptions = {
export type CustomSourceOptions = {
/**
* Called when the size of the entire file is requested. Must return or resolve to the size in bytes. This function
* is guaranteed to be called before `read`.
@@ -1041,6 +1088,8 @@ export type StreamSourceOptions = {
/**
* Called when data is requested. Must return or resolve to the bytes from the specified byte range, or a stream
* that yields these bytes.
*
* You are guaranteed that `0 <= start < end < fileSize`.
*/
read: (start: number, end: number) => MaybePromise<Uint8Array | ReadableStream<Uint8Array>>;
@@ -1067,18 +1116,19 @@ export type StreamSourceOptions = {
};
/**
* A general-purpose, callback-driven source that can get its data from anywhere.
* A general-purpose, callback-driven source that can get its data from anywhere. Use this source to implement your own
* custom source if the other sources don't cover your case.
* @group Input sources
* @public
*/
export class StreamSource extends Source {
export class CustomSource extends Source {
/** @internal */
_options: StreamSourceOptions;
_options: CustomSourceOptions;
/** @internal */
_orchestrator: ReadOrchestrator;
/** Creates a new {@link StreamSource} whose behavior is specified by `options`. */
constructor(options: StreamSourceOptions) {
/** Creates a new {@link CustomSource} whose behavior is specified by `options`. */
constructor(options: CustomSourceOptions) {
if (!options || typeof options !== 'object') {
throw new TypeError('options must be an object.');
}
@@ -1226,6 +1276,25 @@ export class StreamSource extends Source {
}
}
/**
* An alias for {@link CustomSource}.
* @deprecated This name is misleading and will be removed in a future release. Please use {@link CustomSource} instead.
*
* @group Input sources
* @public
*/
export const StreamSource = CustomSource;
/**
* An alias for {@link CustomSourceOptions}.
* @deprecated This name is misleading and will be removed in a future release. Please use
* {@link CustomSourceOptions} instead.
*
* @group Input sources
* @public
*/
export type StreamSourceOptions = CustomSourceOptions;
type ReadableStreamSourcePendingSlice = {
start: number;
end: number;
+21
View File
@@ -0,0 +1,21 @@
import { test } from 'vitest';
import { Input } from '../../src/input.js';
import { UrlSource } from '../../src/source.js';
import { ALL_FORMATS } from '../../src/input-format.js';
import { assert } from '../../src/misc.js';
import { AudioSampleSink } from '../../src/media-sink.js';
// "joined" in the sense that it was two separate MP3s that were spliced together (I think)
test('Can decode malformed joined MP3', async () => {
using input = new Input({
source: new UrlSource('/malformed-join.mp3'),
formats: ALL_FORMATS,
});
const audioTrack = await input.getPrimaryAudioTrack();
assert(audioTrack);
const sink = new AudioSampleSink(audioTrack);
// eslint-disable-next-line @typescript-eslint/no-unused-vars
for await (using sample of sink.samples());
});
+2 -2
View File
@@ -1,6 +1,6 @@
import { expect, test } from 'vitest';
import { Input } from '../../src/input.js';
import { FilePathSource, ReadableStreamSource, StreamSource } from '../../src/source.js';
import { FilePathSource, ReadableStreamSource, CustomSource } from '../../src/source.js';
import path from 'node:path';
import fs from 'node:fs';
import { Readable } from 'node:stream';
@@ -759,7 +759,7 @@ test('MPEG-TS partial reading', async () => {
let maxEnd = 0;
using input = new Input({
source: new StreamSource({
source: new CustomSource({
getSize: () => {
return buffer.byteLength;
},
Binary file not shown.