mirror of
https://github.com/arcodange-org/mediabunny.git
synced 2026-10-10 01:03:45 +02:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f37dd21947 | ||
|
|
a15283eaa3 | ||
|
|
e18da824ce | ||
|
|
506ad0c798 | ||
|
|
c4398fb88c |
@@ -59,7 +59,28 @@ jobs:
|
||||
- name: Upload build artifacts
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: gh release upload ${{ github.event.release.tag_name }} dist/bundles/mediabunny.cjs dist/bundles/mediabunny.min.cjs dist/bundles/mediabunny.mjs dist/bundles/mediabunny.min.mjs dist/mediabunny.d.ts packages/mp3-encoder/dist/bundles/mediabunny-mp3-encoder.js packages/mp3-encoder/dist/bundles/mediabunny-mp3-encoder.min.js packages/mp3-encoder/dist/bundles/mediabunny-mp3-encoder.mjs packages/mp3-encoder/dist/bundles/mediabunny-mp3-encoder.min.mjs packages/mp3-encoder/dist/mediabunny-mp3-encoder.d.ts packages/ac3/dist/bundles/mediabunny-ac3.js packages/ac3/dist/bundles/mediabunny-ac3.min.js packages/ac3/dist/bundles/mediabunny-ac3.mjs packages/ac3/dist/bundles/mediabunny-ac3.min.mjs packages/ac3/dist/mediabunny-ac3.d.ts
|
||||
run: >
|
||||
gh release upload ${{ github.event.release.tag_name }}
|
||||
dist/bundles/mediabunny.cjs
|
||||
dist/bundles/mediabunny.min.cjs
|
||||
dist/bundles/mediabunny.mjs
|
||||
dist/bundles/mediabunny.min.mjs
|
||||
dist/mediabunny.d.ts
|
||||
packages/mp3-encoder/dist/bundles/mediabunny-mp3-encoder.js
|
||||
packages/mp3-encoder/dist/bundles/mediabunny-mp3-encoder.min.js
|
||||
packages/mp3-encoder/dist/bundles/mediabunny-mp3-encoder.mjs
|
||||
packages/mp3-encoder/dist/bundles/mediabunny-mp3-encoder.min.mjs
|
||||
packages/mp3-encoder/dist/mediabunny-mp3-encoder.d.ts
|
||||
packages/ac3/dist/bundles/mediabunny-ac3.js
|
||||
packages/ac3/dist/bundles/mediabunny-ac3.min.js
|
||||
packages/ac3/dist/bundles/mediabunny-ac3.mjs
|
||||
packages/ac3/dist/bundles/mediabunny-ac3.min.mjs
|
||||
packages/ac3/dist/mediabunny-ac3.d.ts
|
||||
packages/aac-encoder/dist/bundles/mediabunny-aac-encoder.js
|
||||
packages/aac-encoder/dist/bundles/mediabunny-aac-encoder.min.js
|
||||
packages/aac-encoder/dist/bundles/mediabunny-aac-encoder.mjs
|
||||
packages/aac-encoder/dist/bundles/mediabunny-aac-encoder.min.mjs
|
||||
packages/aac-encoder/dist/mediabunny-aac-encoder.d.ts
|
||||
|
||||
- name: Publish Mediabunny to npm
|
||||
run: npm publish --access public
|
||||
|
||||
+3
-1
@@ -7,4 +7,6 @@ node_modules
|
||||
*.tsbuildinfo
|
||||
|
||||
packages/mp3-encoder/dist
|
||||
packages/ac3/dist
|
||||
packages/ac3/dist
|
||||
packages/aac-encoder/dist
|
||||
packages/flac-encoder/dist
|
||||
@@ -93,7 +93,9 @@ export default withMermaid({
|
||||
text: 'Extensions',
|
||||
items: [
|
||||
{ text: 'mp3-encoder', link: '/guide/extensions/mp3-encoder' },
|
||||
{ text: 'aac-encoder', link: '/guide/extensions/aac-encoder' },
|
||||
{ text: 'ac3', link: '/guide/extensions/ac3' },
|
||||
{ text: 'flac-encoder', link: '/guide/extensions/flac-encoder' },
|
||||
],
|
||||
},
|
||||
],
|
||||
|
||||
@@ -20,5 +20,7 @@
|
||||
"Miscellaneous": "Whatever's left.",
|
||||
|
||||
"@mediabunny/mp3-encoder": "Adds MP3 encoder support to Mediabunny.",
|
||||
"@mediabunny/ac3": "Adds AC-3/E-AC-3 decoder and encoder support to Mediabunny."
|
||||
"@mediabunny/ac3": "Adds AC-3/E-AC-3 decoder and encoder support to Mediabunny.",
|
||||
"@mediabunny/aac-encoder": "Polyfills AAC encoder support to Mediabunny.",
|
||||
"@mediabunny/flac-encoder": "Adds FLAC encoder support to Mediabunny."
|
||||
}
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
# @mediabunny/aac-encoder
|
||||
|
||||
Some browsers lack support for AAC encoding in their WebCodecs implementations. This extension package provides a reliable AAC-LC encoder for use with Mediabunny. It is implemented using Mediabunny's [custom coder API](../supported-formats-and-codecs#custom-coders) and uses a fast, size-optimized WASM build of [FFmpeg](https://ffmpeg.org/)'s AAC encoder under the hood.
|
||||
|
||||
<a class="!no-underline inline-flex items-center gap-1.5" :no-icon="true" href="https://github.com/Vanilagy/mediabunny/blob/main/packages/aac-encoder/README.md">
|
||||
GitHub page
|
||||
<span class="vpi-arrow-right" />
|
||||
</a>
|
||||
|
||||
## Installation
|
||||
|
||||
This library peer-depends on Mediabunny. Install both using npm:
|
||||
```bash
|
||||
npm install mediabunny @mediabunny/aac-encoder
|
||||
```
|
||||
|
||||
Alternatively, directly include them using a script tag:
|
||||
```html
|
||||
<script src="mediabunny.js"></script>
|
||||
<script src="mediabunny-aac-encoder.js"></script>
|
||||
```
|
||||
|
||||
This will expose the global objects `Mediabunny` and `MediabunnyAacEncoder`. Use `mediabunny-aac-encoder.d.ts` to provide types for these globals. You can download the built distribution files from the [releases page](https://github.com/Vanilagy/mediabunny/releases).
|
||||
|
||||
## Usage
|
||||
|
||||
```ts
|
||||
import { registerAacEncoder } from '@mediabunny/aac-encoder';
|
||||
|
||||
registerAacEncoder();
|
||||
```
|
||||
That's it - Mediabunny now uses the registered AAC encoder automatically.
|
||||
|
||||
If you want to be more correct, check for native browser support first:
|
||||
```ts
|
||||
import { canEncodeAudio } from 'mediabunny';
|
||||
import { registerAacEncoder } from '@mediabunny/aac-encoder';
|
||||
|
||||
if (!(await canEncodeAudio('aac'))) {
|
||||
registerAacEncoder();
|
||||
}
|
||||
```
|
||||
|
||||
## Example
|
||||
|
||||
Here, we convert an input file to an MP4 with AAC audio:
|
||||
|
||||
```ts
|
||||
import {
|
||||
Input,
|
||||
ALL_FORMATS,
|
||||
BlobSource,
|
||||
Output,
|
||||
BufferTarget,
|
||||
Mp4OutputFormat,
|
||||
canEncodeAudio,
|
||||
Conversion,
|
||||
} from 'mediabunny';
|
||||
import { registerAacEncoder } from '@mediabunny/aac-encoder';
|
||||
|
||||
if (!(await canEncodeAudio('aac'))) {
|
||||
// Only register the custom encoder if there's no native support
|
||||
registerAacEncoder();
|
||||
}
|
||||
|
||||
const input = new Input({
|
||||
source: new BlobSource(file), // From a file picker, for example
|
||||
formats: ALL_FORMATS,
|
||||
});
|
||||
const output = new Output({
|
||||
format: new Mp4OutputFormat(),
|
||||
target: new BufferTarget(),
|
||||
});
|
||||
|
||||
const conversion = await Conversion.init({
|
||||
input,
|
||||
output,
|
||||
});
|
||||
await conversion.execute();
|
||||
|
||||
output.target.buffer; // => ArrayBuffer containing the MP4 file
|
||||
```
|
||||
@@ -0,0 +1,81 @@
|
||||
# @mediabunny/flac-encoder
|
||||
|
||||
No browser currently supports FLAC encoding in their WebCodecs implementations. This extension package provides a reliable FLAC encoder for use with Mediabunny. It is implemented using Mediabunny's [custom coder API](../supported-formats-and-codecs#custom-coders) and uses a fast, size-optimized WASM build of [libFLAC](https://github.com/xiph/flac) (the reference FLAC encoder) under the hood.
|
||||
|
||||
<a class="!no-underline inline-flex items-center gap-1.5" :no-icon="true" href="https://github.com/Vanilagy/mediabunny/blob/main/packages/flac-encoder/README.md">
|
||||
GitHub page
|
||||
<span class="vpi-arrow-right" />
|
||||
</a>
|
||||
|
||||
## Installation
|
||||
|
||||
This library peer-depends on Mediabunny. Install both using npm:
|
||||
```bash
|
||||
npm install mediabunny @mediabunny/flac-encoder
|
||||
```
|
||||
|
||||
Alternatively, directly include them using a script tag:
|
||||
```html
|
||||
<script src="mediabunny.js"></script>
|
||||
<script src="mediabunny-flac-encoder.js"></script>
|
||||
```
|
||||
|
||||
This will expose the global objects `Mediabunny` and `MediabunnyFlacEncoder`. Use `mediabunny-flac-encoder.d.ts` to provide types for these globals. You can download the built distribution files from the [releases page](https://github.com/Vanilagy/mediabunny/releases).
|
||||
|
||||
## Usage
|
||||
|
||||
```ts
|
||||
import { registerFlacEncoder } from '@mediabunny/flac-encoder';
|
||||
|
||||
registerFlacEncoder();
|
||||
```
|
||||
That's it - Mediabunny now uses the registered FLAC encoder automatically.
|
||||
|
||||
If you want to be more correct, check for native browser support first:
|
||||
```ts
|
||||
import { canEncodeAudio } from 'mediabunny';
|
||||
import { registerFlacEncoder } from '@mediabunny/flac-encoder';
|
||||
|
||||
if (!(await canEncodeAudio('flac'))) {
|
||||
registerFlacEncoder();
|
||||
}
|
||||
```
|
||||
|
||||
## Example
|
||||
|
||||
Here, we convert an input file to a FLAC file:
|
||||
|
||||
```ts
|
||||
import {
|
||||
Input,
|
||||
ALL_FORMATS,
|
||||
BlobSource,
|
||||
Output,
|
||||
BufferTarget,
|
||||
FlacOutputFormat,
|
||||
canEncodeAudio,
|
||||
Conversion,
|
||||
} from 'mediabunny';
|
||||
import { registerFlacEncoder } from '@mediabunny/flac-encoder';
|
||||
|
||||
if (!(await canEncodeAudio('flac'))) {
|
||||
registerFlacEncoder();
|
||||
}
|
||||
|
||||
const input = new Input({
|
||||
source: new BlobSource(file), // From a file picker, for example
|
||||
formats: ALL_FORMATS,
|
||||
});
|
||||
const output = new Output({
|
||||
format: new FlacOutputFormat(),
|
||||
target: new BufferTarget(),
|
||||
});
|
||||
|
||||
const conversion = await Conversion.init({
|
||||
input,
|
||||
output,
|
||||
});
|
||||
await conversion.execute();
|
||||
|
||||
output.target.buffer; // => ArrayBuffer containing the FLAC file
|
||||
```
|
||||
@@ -37,13 +37,13 @@ Mediabunny ships with built-in decoders and encoders for all audio PCM codecs, m
|
||||
|
||||
### Audio codecs
|
||||
|
||||
- `'aac'` - Advanced Audio Coding (AAC)
|
||||
- `'aac'` - Advanced Audio Coding (AAC) [^1]
|
||||
- `'opus'` - Opus
|
||||
- `'mp3'` - MP3
|
||||
- `'mp3'` - MP3 [^2]
|
||||
- `'vorbis'` - Vorbis
|
||||
- `'flac'` - Free Lossless Audio Codec (FLAC)
|
||||
- `'ac3'` - Dolby Digital (AC-3) [^1]
|
||||
- `'eac3'` - Dolby Digital Plus (E-AC-3) [^1]
|
||||
- `'ac3'` - Dolby Digital (AC-3) [^3]
|
||||
- `'eac3'` - Dolby Digital Plus (E-AC-3) [^3]
|
||||
- `'pcm-u8'` - 8-bit unsigned PCM
|
||||
- `'pcm-s8'` - 8-bit signed PCM
|
||||
- `'pcm-s16'` - 16-bit little-endian signed PCM
|
||||
@@ -59,8 +59,6 @@ Mediabunny ships with built-in decoders and encoders for all audio PCM codecs, m
|
||||
- `'ulaw'` - μ-law PCM
|
||||
- `'alaw'` - A-law PCM
|
||||
|
||||
[^1]: AC-3 and E-AC-3 are not natively supported by WebCodecs. To encode or decode these codecs, you can use the [`@mediabunny/ac3`](./extensions/ac3) extension package, or provide your own [custom coder](#custom-coders).
|
||||
|
||||
### Subtitle codecs
|
||||
|
||||
- `'webvtt'` - WebVTT
|
||||
@@ -69,7 +67,7 @@ Mediabunny ships with built-in decoders and encoders for all audio PCM codecs, m
|
||||
|
||||
Not all codecs can be used with all containers. The following table specifies the supported codec-container combinations:
|
||||
|
||||
| | .mp4 | .mov | .mkv | .webm[^2] | .ogg | .mp3 | .wav | .aac | .flac | .ts |
|
||||
| | .mp4 | .mov | .mkv | .webm[^4] | .ogg | .mp3 | .wav | .aac | .flac | .ts |
|
||||
|:--------------:|:--------:|:-----:|:-----:|:---------:|:-----:|:-----:|:-----:|:-----:|:-----:|:-----:|
|
||||
| `'avc'` | ✓ | ✓ | ✓ | | | | | | | ✓ |
|
||||
| `'hevc'` | ✓ | ✓ | ✓ | | | | | | | ✓ |
|
||||
@@ -97,11 +95,13 @@ Not all codecs can be used with all containers. The following table specifies th
|
||||
| `'pcm-f64be'` | ✓ | ✓ | | | | | | | | |
|
||||
| `'ulaw'` | | ✓ | | | | | ✓ | | | |
|
||||
| `'alaw'` | | ✓ | | | | | ✓ | | | |
|
||||
| `'webvtt'`[^3] | (✓) | | (✓) | (✓) | | | | | | |
|
||||
| `'webvtt'`[^5] | (✓) | | (✓) | (✓) | | | | | | |
|
||||
|
||||
|
||||
[^2]: WebM only supports a small subset of the codecs supported by Matroska. However, this library can technically read all codecs from a WebM that are supported by Matroska.
|
||||
[^3]: WebVTT can only be written, not read.
|
||||
[^1]: In some browsers, AAC encoding is not supported by WebCodecs. You can polyfill it with the [`@mediabunny/aac-encoder`](./extensions/aac-encoder) extension package, or provide your own [custom coder](#custom-coders).
|
||||
[^2]: MP3 encoding is not supported by WebCodecs. You can polyfill it with the [`@mediabunny/mp3-encoder`](./extensions/mp3-encoder) extension package, or provide your own [custom coder](#custom-coders).
|
||||
[^3]: AC-3 and E-AC-3 are not natively supported by WebCodecs. To encode or decode these codecs, you can use the [`@mediabunny/ac3`](./extensions/ac3) extension package, or provide your own [custom coder](#custom-coders).
|
||||
[^4]: WebM only supports a small subset of the codecs supported by Matroska. However, this library can technically read all codecs from a WebM that are supported by Matroska.
|
||||
[^5]: WebVTT can only be written, not read.
|
||||
|
||||
## Querying codec encodability
|
||||
|
||||
|
||||
@@ -40,6 +40,10 @@ export default tseslint.config(
|
||||
'packages/mp3-encoder/build',
|
||||
'packages/ac3/dist',
|
||||
'packages/ac3/build',
|
||||
'packages/aac-encoder/dist',
|
||||
'packages/aac-encoder/build',
|
||||
'packages/flac-encoder/dist',
|
||||
'packages/flac-encoder/build',
|
||||
'eslint.config.mjs',
|
||||
'docs/.vitepress/cache',
|
||||
'test/public',
|
||||
|
||||
Generated
+45
-7
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "mediabunny",
|
||||
"version": "1.35.1",
|
||||
"version": "1.37.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "mediabunny",
|
||||
"version": "1.35.1",
|
||||
"version": "1.37.0",
|
||||
"license": "MPL-2.0",
|
||||
"workspaces": [
|
||||
"packages/*"
|
||||
@@ -1413,10 +1413,18 @@
|
||||
"@jridgewell/sourcemap-codec": "^1.4.14"
|
||||
}
|
||||
},
|
||||
"node_modules/@mediabunny/aac-encoder": {
|
||||
"resolved": "packages/aac-encoder",
|
||||
"link": true
|
||||
},
|
||||
"node_modules/@mediabunny/ac3": {
|
||||
"resolved": "packages/ac3",
|
||||
"link": true
|
||||
},
|
||||
"node_modules/@mediabunny/flac-encoder": {
|
||||
"resolved": "packages/flac-encoder",
|
||||
"link": true
|
||||
},
|
||||
"node_modules/@mediabunny/mp3-encoder": {
|
||||
"resolved": "packages/mp3-encoder",
|
||||
"link": true
|
||||
@@ -7743,9 +7751,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/mediabunny": {
|
||||
"version": "1.35.0",
|
||||
"resolved": "https://registry.npmjs.org/mediabunny/-/mediabunny-1.35.0.tgz",
|
||||
"integrity": "sha512-nDCwdkK9aWDam1+L/VnK2EWzENj5WcPAAmm6HBTXQe5FZ/Mx7uSJewTKeA1JKXpkXvSsp+7UzTsx+G7HfcwOGA==",
|
||||
"version": "1.36.0",
|
||||
"resolved": "https://registry.npmjs.org/mediabunny/-/mediabunny-1.36.0.tgz",
|
||||
"integrity": "sha512-+RsDJ9O0JcrLenlgT0jzUA4+78UQhPDHnUax7QnfwOL4JMAitzp+6aV3WKUYaplb7wapvxpn/0k/S2UkAbAHWQ==",
|
||||
"license": "MPL-2.0",
|
||||
"peer": true,
|
||||
"workspaces": [
|
||||
@@ -12067,9 +12075,39 @@
|
||||
"url": "https://github.com/sponsors/wooorm"
|
||||
}
|
||||
},
|
||||
"packages/aac-encoder": {
|
||||
"name": "@mediabunny/aac-encoder",
|
||||
"version": "1.37.0",
|
||||
"license": "MPL-2.0",
|
||||
"devDependencies": {
|
||||
"@types/emscripten": "^1.40.1"
|
||||
},
|
||||
"funding": {
|
||||
"type": "individual",
|
||||
"url": "https://github.com/sponsors/Vanilagy"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"mediabunny": "^1.0.0"
|
||||
}
|
||||
},
|
||||
"packages/ac3": {
|
||||
"name": "@mediabunny/ac3",
|
||||
"version": "1.35.1",
|
||||
"version": "1.37.0",
|
||||
"license": "MPL-2.0",
|
||||
"devDependencies": {
|
||||
"@types/emscripten": "^1.40.1"
|
||||
},
|
||||
"funding": {
|
||||
"type": "individual",
|
||||
"url": "https://github.com/sponsors/Vanilagy"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"mediabunny": "^1.0.0"
|
||||
}
|
||||
},
|
||||
"packages/flac-encoder": {
|
||||
"name": "@mediabunny/flac-encoder",
|
||||
"version": "1.37.0",
|
||||
"license": "MPL-2.0",
|
||||
"devDependencies": {
|
||||
"@types/emscripten": "^1.40.1"
|
||||
@@ -12084,7 +12122,7 @@
|
||||
},
|
||||
"packages/mp3-encoder": {
|
||||
"name": "@mediabunny/mp3-encoder",
|
||||
"version": "1.35.1",
|
||||
"version": "1.37.0",
|
||||
"license": "MPL-2.0",
|
||||
"devDependencies": {
|
||||
"@types/emscripten": "^1.40.1"
|
||||
|
||||
+2
-2
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "mediabunny",
|
||||
"author": "Vanilagy",
|
||||
"version": "1.35.1",
|
||||
"version": "1.37.0",
|
||||
"description": "Pure TypeScript media toolkit for reading, writing, and converting media files, directly in the browser.",
|
||||
"type": "module",
|
||||
"workspaces": [
|
||||
@@ -41,7 +41,7 @@
|
||||
"docs:dev": "vitepress dev docs",
|
||||
"docs:build": "npm run build && npm run docs:generate && vitepress build docs && npm run examples:build && cp dist/mediabunny.d.ts dist-docs/",
|
||||
"docs:preview": "vitepress preview docs",
|
||||
"docs:generate": "tsx scripts/generate-api-docs.ts src/index.ts packages/mp3-encoder/src/index.ts packages/ac3/src/index.ts docs/api-config.json",
|
||||
"docs:generate": "tsx scripts/generate-api-docs.ts src/index.ts packages/mp3-encoder/src/index.ts packages/ac3/src/index.ts packages/aac-encoder/src/index.ts packages/flac-encoder/src/index.ts docs/api-config.json",
|
||||
"dev": "vite",
|
||||
"examples:build": "vite build",
|
||||
"fix-build-import-paths": "tsx scripts/add-import-extensions.ts",
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
build/* linguist-generated
|
||||
@@ -0,0 +1,373 @@
|
||||
Mozilla Public License Version 2.0
|
||||
==================================
|
||||
|
||||
1. Definitions
|
||||
--------------
|
||||
|
||||
1.1. "Contributor"
|
||||
means each individual or legal entity that creates, contributes to
|
||||
the creation of, or owns Covered Software.
|
||||
|
||||
1.2. "Contributor Version"
|
||||
means the combination of the Contributions of others (if any) used
|
||||
by a Contributor and that particular Contributor's Contribution.
|
||||
|
||||
1.3. "Contribution"
|
||||
means Covered Software of a particular Contributor.
|
||||
|
||||
1.4. "Covered Software"
|
||||
means Source Code Form to which the initial Contributor has attached
|
||||
the notice in Exhibit A, the Executable Form of such Source Code
|
||||
Form, and Modifications of such Source Code Form, in each case
|
||||
including portions thereof.
|
||||
|
||||
1.5. "Incompatible With Secondary Licenses"
|
||||
means
|
||||
|
||||
(a) that the initial Contributor has attached the notice described
|
||||
in Exhibit B to the Covered Software; or
|
||||
|
||||
(b) that the Covered Software was made available under the terms of
|
||||
version 1.1 or earlier of the License, but not also under the
|
||||
terms of a Secondary License.
|
||||
|
||||
1.6. "Executable Form"
|
||||
means any form of the work other than Source Code Form.
|
||||
|
||||
1.7. "Larger Work"
|
||||
means a work that combines Covered Software with other material, in
|
||||
a separate file or files, that is not Covered Software.
|
||||
|
||||
1.8. "License"
|
||||
means this document.
|
||||
|
||||
1.9. "Licensable"
|
||||
means having the right to grant, to the maximum extent possible,
|
||||
whether at the time of the initial grant or subsequently, any and
|
||||
all of the rights conveyed by this License.
|
||||
|
||||
1.10. "Modifications"
|
||||
means any of the following:
|
||||
|
||||
(a) any file in Source Code Form that results from an addition to,
|
||||
deletion from, or modification of the contents of Covered
|
||||
Software; or
|
||||
|
||||
(b) any new file in Source Code Form that contains any Covered
|
||||
Software.
|
||||
|
||||
1.11. "Patent Claims" of a Contributor
|
||||
means any patent claim(s), including without limitation, method,
|
||||
process, and apparatus claims, in any patent Licensable by such
|
||||
Contributor that would be infringed, but for the grant of the
|
||||
License, by the making, using, selling, offering for sale, having
|
||||
made, import, or transfer of either its Contributions or its
|
||||
Contributor Version.
|
||||
|
||||
1.12. "Secondary License"
|
||||
means either the GNU General Public License, Version 2.0, the GNU
|
||||
Lesser General Public License, Version 2.1, the GNU Affero General
|
||||
Public License, Version 3.0, or any later versions of those
|
||||
licenses.
|
||||
|
||||
1.13. "Source Code Form"
|
||||
means the form of the work preferred for making modifications.
|
||||
|
||||
1.14. "You" (or "Your")
|
||||
means an individual or a legal entity exercising rights under this
|
||||
License. For legal entities, "You" includes any entity that
|
||||
controls, is controlled by, or is under common control with You. For
|
||||
purposes of this definition, "control" means (a) the power, direct
|
||||
or indirect, to cause the direction or management of such entity,
|
||||
whether by contract or otherwise, or (b) ownership of more than
|
||||
fifty percent (50%) of the outstanding shares or beneficial
|
||||
ownership of such entity.
|
||||
|
||||
2. License Grants and Conditions
|
||||
--------------------------------
|
||||
|
||||
2.1. Grants
|
||||
|
||||
Each Contributor hereby grants You a world-wide, royalty-free,
|
||||
non-exclusive license:
|
||||
|
||||
(a) under intellectual property rights (other than patent or trademark)
|
||||
Licensable by such Contributor to use, reproduce, make available,
|
||||
modify, display, perform, distribute, and otherwise exploit its
|
||||
Contributions, either on an unmodified basis, with Modifications, or
|
||||
as part of a Larger Work; and
|
||||
|
||||
(b) under Patent Claims of such Contributor to make, use, sell, offer
|
||||
for sale, have made, import, and otherwise transfer either its
|
||||
Contributions or its Contributor Version.
|
||||
|
||||
2.2. Effective Date
|
||||
|
||||
The licenses granted in Section 2.1 with respect to any Contribution
|
||||
become effective for each Contribution on the date the Contributor first
|
||||
distributes such Contribution.
|
||||
|
||||
2.3. Limitations on Grant Scope
|
||||
|
||||
The licenses granted in this Section 2 are the only rights granted under
|
||||
this License. No additional rights or licenses will be implied from the
|
||||
distribution or licensing of Covered Software under this License.
|
||||
Notwithstanding Section 2.1(b) above, no patent license is granted by a
|
||||
Contributor:
|
||||
|
||||
(a) for any code that a Contributor has removed from Covered Software;
|
||||
or
|
||||
|
||||
(b) for infringements caused by: (i) Your and any other third party's
|
||||
modifications of Covered Software, or (ii) the combination of its
|
||||
Contributions with other software (except as part of its Contributor
|
||||
Version); or
|
||||
|
||||
(c) under Patent Claims infringed by Covered Software in the absence of
|
||||
its Contributions.
|
||||
|
||||
This License does not grant any rights in the trademarks, service marks,
|
||||
or logos of any Contributor (except as may be necessary to comply with
|
||||
the notice requirements in Section 3.4).
|
||||
|
||||
2.4. Subsequent Licenses
|
||||
|
||||
No Contributor makes additional grants as a result of Your choice to
|
||||
distribute the Covered Software under a subsequent version of this
|
||||
License (see Section 10.2) or under the terms of a Secondary License (if
|
||||
permitted under the terms of Section 3.3).
|
||||
|
||||
2.5. Representation
|
||||
|
||||
Each Contributor represents that the Contributor believes its
|
||||
Contributions are its original creation(s) or it has sufficient rights
|
||||
to grant the rights to its Contributions conveyed by this License.
|
||||
|
||||
2.6. Fair Use
|
||||
|
||||
This License is not intended to limit any rights You have under
|
||||
applicable copyright doctrines of fair use, fair dealing, or other
|
||||
equivalents.
|
||||
|
||||
2.7. Conditions
|
||||
|
||||
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
|
||||
in Section 2.1.
|
||||
|
||||
3. Responsibilities
|
||||
-------------------
|
||||
|
||||
3.1. Distribution of Source Form
|
||||
|
||||
All distribution of Covered Software in Source Code Form, including any
|
||||
Modifications that You create or to which You contribute, must be under
|
||||
the terms of this License. You must inform recipients that the Source
|
||||
Code Form of the Covered Software is governed by the terms of this
|
||||
License, and how they can obtain a copy of this License. You may not
|
||||
attempt to alter or restrict the recipients' rights in the Source Code
|
||||
Form.
|
||||
|
||||
3.2. Distribution of Executable Form
|
||||
|
||||
If You distribute Covered Software in Executable Form then:
|
||||
|
||||
(a) such Covered Software must also be made available in Source Code
|
||||
Form, as described in Section 3.1, and You must inform recipients of
|
||||
the Executable Form how they can obtain a copy of such Source Code
|
||||
Form by reasonable means in a timely manner, at a charge no more
|
||||
than the cost of distribution to the recipient; and
|
||||
|
||||
(b) You may distribute such Executable Form under the terms of this
|
||||
License, or sublicense it under different terms, provided that the
|
||||
license for the Executable Form does not attempt to limit or alter
|
||||
the recipients' rights in the Source Code Form under this License.
|
||||
|
||||
3.3. Distribution of a Larger Work
|
||||
|
||||
You may create and distribute a Larger Work under terms of Your choice,
|
||||
provided that You also comply with the requirements of this License for
|
||||
the Covered Software. If the Larger Work is a combination of Covered
|
||||
Software with a work governed by one or more Secondary Licenses, and the
|
||||
Covered Software is not Incompatible With Secondary Licenses, this
|
||||
License permits You to additionally distribute such Covered Software
|
||||
under the terms of such Secondary License(s), so that the recipient of
|
||||
the Larger Work may, at their option, further distribute the Covered
|
||||
Software under the terms of either this License or such Secondary
|
||||
License(s).
|
||||
|
||||
3.4. Notices
|
||||
|
||||
You may not remove or alter the substance of any license notices
|
||||
(including copyright notices, patent notices, disclaimers of warranty,
|
||||
or limitations of liability) contained within the Source Code Form of
|
||||
the Covered Software, except that You may alter any license notices to
|
||||
the extent required to remedy known factual inaccuracies.
|
||||
|
||||
3.5. Application of Additional Terms
|
||||
|
||||
You may choose to offer, and to charge a fee for, warranty, support,
|
||||
indemnity or liability obligations to one or more recipients of Covered
|
||||
Software. However, You may do so only on Your own behalf, and not on
|
||||
behalf of any Contributor. You must make it absolutely clear that any
|
||||
such warranty, support, indemnity, or liability obligation is offered by
|
||||
You alone, and You hereby agree to indemnify every Contributor for any
|
||||
liability incurred by such Contributor as a result of warranty, support,
|
||||
indemnity or liability terms You offer. You may include additional
|
||||
disclaimers of warranty and limitations of liability specific to any
|
||||
jurisdiction.
|
||||
|
||||
4. Inability to Comply Due to Statute or Regulation
|
||||
---------------------------------------------------
|
||||
|
||||
If it is impossible for You to comply with any of the terms of this
|
||||
License with respect to some or all of the Covered Software due to
|
||||
statute, judicial order, or regulation then You must: (a) comply with
|
||||
the terms of this License to the maximum extent possible; and (b)
|
||||
describe the limitations and the code they affect. Such description must
|
||||
be placed in a text file included with all distributions of the Covered
|
||||
Software under this License. Except to the extent prohibited by statute
|
||||
or regulation, such description must be sufficiently detailed for a
|
||||
recipient of ordinary skill to be able to understand it.
|
||||
|
||||
5. Termination
|
||||
--------------
|
||||
|
||||
5.1. The rights granted under this License will terminate automatically
|
||||
if You fail to comply with any of its terms. However, if You become
|
||||
compliant, then the rights granted under this License from a particular
|
||||
Contributor are reinstated (a) provisionally, unless and until such
|
||||
Contributor explicitly and finally terminates Your grants, and (b) on an
|
||||
ongoing basis, if such Contributor fails to notify You of the
|
||||
non-compliance by some reasonable means prior to 60 days after You have
|
||||
come back into compliance. Moreover, Your grants from a particular
|
||||
Contributor are reinstated on an ongoing basis if such Contributor
|
||||
notifies You of the non-compliance by some reasonable means, this is the
|
||||
first time You have received notice of non-compliance with this License
|
||||
from such Contributor, and You become compliant prior to 30 days after
|
||||
Your receipt of the notice.
|
||||
|
||||
5.2. If You initiate litigation against any entity by asserting a patent
|
||||
infringement claim (excluding declaratory judgment actions,
|
||||
counter-claims, and cross-claims) alleging that a Contributor Version
|
||||
directly or indirectly infringes any patent, then the rights granted to
|
||||
You by any and all Contributors for the Covered Software under Section
|
||||
2.1 of this License shall terminate.
|
||||
|
||||
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
|
||||
end user license agreements (excluding distributors and resellers) which
|
||||
have been validly granted by You or Your distributors under this License
|
||||
prior to termination shall survive termination.
|
||||
|
||||
************************************************************************
|
||||
* *
|
||||
* 6. Disclaimer of Warranty *
|
||||
* ------------------------- *
|
||||
* *
|
||||
* Covered Software is provided under this License on an "as is" *
|
||||
* basis, without warranty of any kind, either expressed, implied, or *
|
||||
* statutory, including, without limitation, warranties that the *
|
||||
* Covered Software is free of defects, merchantable, fit for a *
|
||||
* particular purpose or non-infringing. The entire risk as to the *
|
||||
* quality and performance of the Covered Software is with You. *
|
||||
* Should any Covered Software prove defective in any respect, You *
|
||||
* (not any Contributor) assume the cost of any necessary servicing, *
|
||||
* repair, or correction. This disclaimer of warranty constitutes an *
|
||||
* essential part of this License. No use of any Covered Software is *
|
||||
* authorized under this License except under this disclaimer. *
|
||||
* *
|
||||
************************************************************************
|
||||
|
||||
************************************************************************
|
||||
* *
|
||||
* 7. Limitation of Liability *
|
||||
* -------------------------- *
|
||||
* *
|
||||
* Under no circumstances and under no legal theory, whether tort *
|
||||
* (including negligence), contract, or otherwise, shall any *
|
||||
* Contributor, or anyone who distributes Covered Software as *
|
||||
* permitted above, be liable to You for any direct, indirect, *
|
||||
* special, incidental, or consequential damages of any character *
|
||||
* including, without limitation, damages for lost profits, loss of *
|
||||
* goodwill, work stoppage, computer failure or malfunction, or any *
|
||||
* and all other commercial damages or losses, even if such party *
|
||||
* shall have been informed of the possibility of such damages. This *
|
||||
* limitation of liability shall not apply to liability for death or *
|
||||
* personal injury resulting from such party's negligence to the *
|
||||
* extent applicable law prohibits such limitation. Some *
|
||||
* jurisdictions do not allow the exclusion or limitation of *
|
||||
* incidental or consequential damages, so this exclusion and *
|
||||
* limitation may not apply to You. *
|
||||
* *
|
||||
************************************************************************
|
||||
|
||||
8. Litigation
|
||||
-------------
|
||||
|
||||
Any litigation relating to this License may be brought only in the
|
||||
courts of a jurisdiction where the defendant maintains its principal
|
||||
place of business and such litigation shall be governed by laws of that
|
||||
jurisdiction, without reference to its conflict-of-law provisions.
|
||||
Nothing in this Section shall prevent a party's ability to bring
|
||||
cross-claims or counter-claims.
|
||||
|
||||
9. Miscellaneous
|
||||
----------------
|
||||
|
||||
This License represents the complete agreement concerning the subject
|
||||
matter hereof. If any provision of this License is held to be
|
||||
unenforceable, such provision shall be reformed only to the extent
|
||||
necessary to make it enforceable. Any law or regulation which provides
|
||||
that the language of a contract shall be construed against the drafter
|
||||
shall not be used to construe this License against a Contributor.
|
||||
|
||||
10. Versions of the License
|
||||
---------------------------
|
||||
|
||||
10.1. New Versions
|
||||
|
||||
Mozilla Foundation is the license steward. Except as provided in Section
|
||||
10.3, no one other than the license steward has the right to modify or
|
||||
publish new versions of this License. Each version will be given a
|
||||
distinguishing version number.
|
||||
|
||||
10.2. Effect of New Versions
|
||||
|
||||
You may distribute the Covered Software under the terms of the version
|
||||
of the License under which You originally received the Covered Software,
|
||||
or under the terms of any subsequent version published by the license
|
||||
steward.
|
||||
|
||||
10.3. Modified Versions
|
||||
|
||||
If you create software not governed by this License, and you want to
|
||||
create a new license for such software, you may create and use a
|
||||
modified version of this License if you rename the license and remove
|
||||
any references to the name of the license steward (except to note that
|
||||
such modified license differs from this License).
|
||||
|
||||
10.4. Distributing Source Code Form that is Incompatible With Secondary
|
||||
Licenses
|
||||
|
||||
If You choose to distribute Source Code Form that is Incompatible With
|
||||
Secondary Licenses under the terms of this version of the License, the
|
||||
notice described in Exhibit B of this License must be attached.
|
||||
|
||||
Exhibit A - Source Code Form License Notice
|
||||
-------------------------------------------
|
||||
|
||||
This Source Code Form is subject to the terms of the Mozilla Public
|
||||
License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||
|
||||
If it is not possible or desirable to put the notice in a particular
|
||||
file, then You may include the notice in a location (such as a LICENSE
|
||||
file in a relevant directory) where a recipient would be likely to look
|
||||
for such a notice.
|
||||
|
||||
You may add additional accurate notices of copyright ownership.
|
||||
|
||||
Exhibit B - "Incompatible With Secondary Licenses" Notice
|
||||
---------------------------------------------------------
|
||||
|
||||
This Source Code Form is "Incompatible With Secondary Licenses", as
|
||||
defined by the Mozilla Public License, v. 2.0.
|
||||
@@ -0,0 +1,156 @@
|
||||
# @mediabunny/aac-encoder
|
||||
|
||||
[](https://www.npmjs.com/package/@mediabunny/aac-encoder)
|
||||
[](https://bundlephobia.com/package/@mediabunny/aac-encoder)
|
||||
[](https://www.npmjs.com/package/@mediabunny/aac-encoder)
|
||||
[](https://discord.gg/hmpkyYuS4U)
|
||||
|
||||
<div align="center">
|
||||
<img src="../../docs/public/mediabunny-logo.svg" width="180" height="180">
|
||||
</div>
|
||||
|
||||
Some browsers lack support for AAC encoding in their WebCodecs implementations. This extension package provides a reliable AAC-LC encoder for use with [Mediabunny](https://github.com/Vanilagy/mediabunny). It is implemented using Mediabunny's [custom coder API](https://mediabunny.dev/guide/supported-formats-and-codecs#custom-coders) and uses a fast, size-optimized WASM build of [FFmpeg](https://ffmpeg.org/)'s AAC encoder under the hood.
|
||||
|
||||
> This package, like the rest of Mediabunny, is enabled by its [sponsors](https://mediabunny.dev/#sponsors) and their donations. If you've derived value from this package, please consider [leaving a donation](https://github.com/sponsors/Vanilagy)! 💘
|
||||
|
||||
## Installation
|
||||
|
||||
This library peer-depends on Mediabunny. Install both using npm:
|
||||
```bash
|
||||
npm install mediabunny @mediabunny/aac-encoder
|
||||
```
|
||||
|
||||
Alternatively, directly include them using a script tag:
|
||||
```html
|
||||
<script src="mediabunny.js"></script>
|
||||
<script src="mediabunny-aac-encoder.js"></script>
|
||||
```
|
||||
|
||||
This will expose the global objects `Mediabunny` and `MediabunnyAacEncoder`. Use `mediabunny-aac-encoder.d.ts` to provide types for these globals. You can download the built distribution files from the [releases page](https://github.com/Vanilagy/mediabunny/releases).
|
||||
|
||||
## Usage
|
||||
|
||||
```ts
|
||||
import { registerAacEncoder } from '@mediabunny/aac-encoder';
|
||||
|
||||
registerAacEncoder();
|
||||
```
|
||||
That's it - Mediabunny now uses the registered AAC encoder automatically.
|
||||
|
||||
If you want to be more correct, check for native browser support first:
|
||||
```ts
|
||||
import { canEncodeAudio } from 'mediabunny';
|
||||
import { registerAacEncoder } from '@mediabunny/aac-encoder';
|
||||
|
||||
if (!(await canEncodeAudio('aac'))) {
|
||||
registerAacEncoder();
|
||||
}
|
||||
```
|
||||
|
||||
## Example
|
||||
|
||||
Here, we convert an input file to an MP4 with AAC audio:
|
||||
|
||||
```ts
|
||||
import {
|
||||
Input,
|
||||
ALL_FORMATS,
|
||||
BlobSource,
|
||||
Output,
|
||||
BufferTarget,
|
||||
Mp4OutputFormat,
|
||||
canEncodeAudio,
|
||||
Conversion,
|
||||
} from 'mediabunny';
|
||||
import { registerAacEncoder } from '@mediabunny/aac-encoder';
|
||||
|
||||
if (!(await canEncodeAudio('aac'))) {
|
||||
// Only register the custom encoder if there's no native support
|
||||
registerAacEncoder();
|
||||
}
|
||||
|
||||
const input = new Input({
|
||||
source: new BlobSource(file), // From a file picker, for example
|
||||
formats: ALL_FORMATS,
|
||||
});
|
||||
const output = new Output({
|
||||
format: new Mp4OutputFormat(),
|
||||
target: new BufferTarget(),
|
||||
});
|
||||
|
||||
const conversion = await Conversion.init({
|
||||
input,
|
||||
output,
|
||||
});
|
||||
await conversion.execute();
|
||||
|
||||
output.target.buffer; // => ArrayBuffer containing the MP4 file
|
||||
```
|
||||
|
||||
For more ways of using Mediabunny, refer to its [guide](https://mediabunny.dev/guide/introduction).
|
||||
|
||||
## Building and development
|
||||
|
||||
For simplicity, all built WASM artifacts are included in the repo, since these rarely change. However, here are the instructions for building them from scratch:
|
||||
|
||||
[Install Emscripten](https://emscripten.org/docs/getting_started/downloads.html) and clone [FFmpeg](https://github.com/FFmpeg/FFmpeg). Then, from the Mediabunny root and with Emscripten sourced in:
|
||||
|
||||
```bash
|
||||
export FFMPEG_PATH=/path/to/ffmpeg
|
||||
export MEDIABUNNY_ROOT=$PWD
|
||||
|
||||
# Build FFmpeg
|
||||
cd $FFMPEG_PATH
|
||||
emmake make distclean
|
||||
emconfigure ./configure \
|
||||
--target-os=none \
|
||||
--arch=x86_32 \
|
||||
--enable-cross-compile \
|
||||
--disable-asm \
|
||||
--disable-x86asm \
|
||||
--disable-inline-asm \
|
||||
--disable-programs \
|
||||
--disable-doc \
|
||||
--disable-debug \
|
||||
--disable-all \
|
||||
--disable-everything \
|
||||
--disable-autodetect \
|
||||
--disable-pthreads \
|
||||
--disable-runtime-cpudetect \
|
||||
--enable-avcodec \
|
||||
--enable-encoder=aac \
|
||||
--cc="emcc" \
|
||||
--cxx=em++ \
|
||||
--ar=emar \
|
||||
--ranlib=emranlib \
|
||||
--extra-cflags="-DNDEBUG -Oz -flto -msimd128" \
|
||||
--extra-ldflags="-Oz -flto"
|
||||
emmake make
|
||||
|
||||
# Compile the bridge between JavaScript and FFmpeg's API
|
||||
cd $MEDIABUNNY_ROOT/packages/aac-encoder
|
||||
emcc src/bridge.c \
|
||||
$FFMPEG_PATH/libavcodec/libavcodec.a \
|
||||
$FFMPEG_PATH/libavutil/libavutil.a \
|
||||
-I$FFMPEG_PATH \
|
||||
-s MODULARIZE=1 \
|
||||
-s EXPORT_ES6=1 \
|
||||
-s SINGLE_FILE=1 \
|
||||
-s ALLOW_MEMORY_GROWTH=1 \
|
||||
-s ENVIRONMENT=web,worker \
|
||||
-s FILESYSTEM=0 \
|
||||
-s MALLOC=emmalloc \
|
||||
-s SUPPORT_LONGJMP=0 \
|
||||
-s EXPORTED_RUNTIME_METHODS=cwrap,HEAPU8 \
|
||||
-s EXPORTED_FUNCTIONS=_malloc,_free \
|
||||
-msimd128 \
|
||||
-flto \
|
||||
-Oz \
|
||||
-o build/aac.js
|
||||
```
|
||||
|
||||
This generates `build/aac.js`, which contains both the JavaScript "glue code" as well as the compiled WASM inlined.
|
||||
|
||||
### Building the package
|
||||
|
||||
Then, the complete JavaScript package can be built alongside the rest of Mediabunny by running `npm run build` in Mediabunny's root.
|
||||
@@ -0,0 +1,37 @@
|
||||
{
|
||||
"$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json",
|
||||
"mainEntryPointFilePath": "dist/modules/src/index.d.ts",
|
||||
"bundledPackages": [],
|
||||
"compiler": {},
|
||||
"apiReport": {
|
||||
"enabled": false
|
||||
},
|
||||
"docModel": {
|
||||
"enabled": false
|
||||
},
|
||||
"dtsRollup": {
|
||||
"enabled": true,
|
||||
"untrimmedFilePath": "dist/mediabunny-aac-encoder.d.ts"
|
||||
},
|
||||
"tsdocMetadata": {
|
||||
"enabled": false
|
||||
},
|
||||
"messages": {
|
||||
"compilerMessageReporting": {
|
||||
"default": {
|
||||
"logLevel": "warning"
|
||||
}
|
||||
},
|
||||
"extractorMessageReporting": {
|
||||
"default": {
|
||||
"logLevel": "warning"
|
||||
}
|
||||
},
|
||||
"tsdocMessageReporting": {
|
||||
"default": {
|
||||
"logLevel": "warning"
|
||||
}
|
||||
}
|
||||
},
|
||||
"newlineKind": "lf"
|
||||
}
|
||||
Generated
BIN
Binary file not shown.
@@ -0,0 +1,55 @@
|
||||
{
|
||||
"name": "@mediabunny/aac-encoder",
|
||||
"author": "Vanilagy",
|
||||
"version": "1.37.0",
|
||||
"description": "AAC encoder extension for Mediabunny, based on FFmpeg.",
|
||||
"main": "./dist/bundles/mediabunny-aac-encoder.mjs",
|
||||
"module": "./dist/bundles/mediabunny-aac-encoder.mjs",
|
||||
"types": "./dist/modules/src/index.d.ts",
|
||||
"exports": {
|
||||
"types": "./dist/modules/src/index.d.ts",
|
||||
"import": "./dist/bundles/mediabunny-aac-encoder.mjs",
|
||||
"require": "./dist/bundles/mediabunny-aac-encoder.mjs"
|
||||
},
|
||||
"files": [
|
||||
"README.md",
|
||||
"package.json",
|
||||
"LICENSE",
|
||||
"dist",
|
||||
"src"
|
||||
],
|
||||
"browser": {
|
||||
"worker_threads": false
|
||||
},
|
||||
"sideEffects": false,
|
||||
"license": "MPL-2.0",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/Vanilagy/mediabunny.git",
|
||||
"directory": "packages/aac-encoder"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/Vanilagy/mediabunny/issues"
|
||||
},
|
||||
"homepage": "https://mediabunny.dev/guide/extensions/aac-encoder",
|
||||
"funding": {
|
||||
"type": "individual",
|
||||
"url": "https://github.com/sponsors/Vanilagy"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"mediabunny": "^1.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/emscripten": "^1.40.1"
|
||||
},
|
||||
"keywords": [
|
||||
"aac",
|
||||
"encoding",
|
||||
"codec",
|
||||
"mediabunny",
|
||||
"ffmpeg",
|
||||
"browser",
|
||||
"wasm",
|
||||
"polyfill"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
/*!
|
||||
* Copyright (c) 2026-present, Vanilagy and contributors
|
||||
*
|
||||
* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||
*/
|
||||
|
||||
#include <emscripten.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include "libavcodec/avcodec.h"
|
||||
#include "libavutil/opt.h"
|
||||
#include "libavutil/channel_layout.h"
|
||||
#include "libavutil/log.h"
|
||||
|
||||
typedef struct {
|
||||
AVCodecContext *codec_ctx;
|
||||
AVPacket *packet;
|
||||
AVFrame *frame;
|
||||
float *input_buffer;
|
||||
int input_buffer_size;
|
||||
int encoded_pts;
|
||||
int encoded_duration;
|
||||
} EncoderContext;
|
||||
|
||||
EMSCRIPTEN_KEEPALIVE
|
||||
EncoderContext *init_encoder(int channels, int sample_rate, int bitrate) {
|
||||
av_log_set_level(AV_LOG_ERROR);
|
||||
|
||||
const AVCodec *codec = avcodec_find_encoder(AV_CODEC_ID_AAC);
|
||||
if (!codec) return NULL;
|
||||
|
||||
AVCodecContext *codec_ctx = avcodec_alloc_context3(codec);
|
||||
if (!codec_ctx) return NULL;
|
||||
|
||||
codec_ctx->sample_fmt = AV_SAMPLE_FMT_FLTP;
|
||||
codec_ctx->sample_rate = sample_rate;
|
||||
codec_ctx->bit_rate = bitrate;
|
||||
codec_ctx->time_base = (AVRational){1, sample_rate};
|
||||
|
||||
AVChannelLayout layout;
|
||||
av_channel_layout_default(&layout, channels);
|
||||
av_channel_layout_copy(&codec_ctx->ch_layout, &layout);
|
||||
av_channel_layout_uninit(&layout);
|
||||
|
||||
if (avcodec_open2(codec_ctx, codec, NULL) < 0) {
|
||||
avcodec_free_context(&codec_ctx);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
AVPacket *packet = av_packet_alloc();
|
||||
if (!packet) {
|
||||
avcodec_free_context(&codec_ctx);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
AVFrame *frame = av_frame_alloc();
|
||||
if (!frame) {
|
||||
av_packet_free(&packet);
|
||||
avcodec_free_context(&codec_ctx);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
frame->format = AV_SAMPLE_FMT_FLTP;
|
||||
frame->sample_rate = sample_rate;
|
||||
frame->nb_samples = codec_ctx->frame_size;
|
||||
av_channel_layout_copy(&frame->ch_layout, &codec_ctx->ch_layout);
|
||||
|
||||
if (av_frame_get_buffer(frame, 0) < 0) {
|
||||
av_frame_free(&frame);
|
||||
av_packet_free(&packet);
|
||||
avcodec_free_context(&codec_ctx);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
EncoderContext *ctx = malloc(sizeof(EncoderContext));
|
||||
if (!ctx) {
|
||||
av_frame_free(&frame);
|
||||
av_packet_free(&packet);
|
||||
avcodec_free_context(&codec_ctx);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
ctx->codec_ctx = codec_ctx;
|
||||
ctx->packet = packet;
|
||||
ctx->frame = frame;
|
||||
ctx->input_buffer = NULL;
|
||||
ctx->input_buffer_size = 0;
|
||||
ctx->encoded_pts = 0;
|
||||
ctx->encoded_duration = 0;
|
||||
|
||||
return ctx;
|
||||
}
|
||||
|
||||
EMSCRIPTEN_KEEPALIVE
|
||||
int get_encoder_frame_size(EncoderContext *ctx) {
|
||||
return ctx->codec_ctx->frame_size;
|
||||
}
|
||||
|
||||
EMSCRIPTEN_KEEPALIVE
|
||||
uint8_t *get_encoder_extradata(EncoderContext *ctx) {
|
||||
return ctx->codec_ctx->extradata;
|
||||
}
|
||||
|
||||
EMSCRIPTEN_KEEPALIVE
|
||||
int get_encoder_extradata_size(EncoderContext *ctx) {
|
||||
return ctx->codec_ctx->extradata_size;
|
||||
}
|
||||
|
||||
EMSCRIPTEN_KEEPALIVE
|
||||
float *get_encode_input_ptr(EncoderContext *ctx, int size) {
|
||||
if (ctx->input_buffer_size < size) {
|
||||
free(ctx->input_buffer);
|
||||
ctx->input_buffer = malloc(size);
|
||||
if (!ctx->input_buffer) {
|
||||
ctx->input_buffer_size = 0;
|
||||
return NULL;
|
||||
}
|
||||
ctx->input_buffer_size = size;
|
||||
}
|
||||
return ctx->input_buffer;
|
||||
}
|
||||
|
||||
EMSCRIPTEN_KEEPALIVE
|
||||
int send_frame(EncoderContext *ctx, int pts) {
|
||||
int channels = ctx->codec_ctx->ch_layout.nb_channels;
|
||||
int frame_size = ctx->frame->nb_samples;
|
||||
|
||||
ctx->frame->pts = pts;
|
||||
|
||||
// Deinterleave f32 input into the frame's f32-planar planes
|
||||
float *input = ctx->input_buffer;
|
||||
for (int ch = 0; ch < channels; ch++) {
|
||||
float *plane = (float *)ctx->frame->data[ch];
|
||||
for (int i = 0; i < frame_size; i++) {
|
||||
plane[i] = input[i * channels + ch];
|
||||
}
|
||||
}
|
||||
|
||||
return avcodec_send_frame(ctx->codec_ctx, ctx->frame);
|
||||
}
|
||||
|
||||
EMSCRIPTEN_KEEPALIVE
|
||||
int receive_packet(EncoderContext *ctx) {
|
||||
int ret = avcodec_receive_packet(ctx->codec_ctx, ctx->packet);
|
||||
if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
|
||||
return 0;
|
||||
}
|
||||
if (ret < 0) return ret;
|
||||
|
||||
ctx->encoded_pts = ctx->packet->pts;
|
||||
ctx->encoded_duration = ctx->packet->duration;
|
||||
|
||||
return ctx->packet->size;
|
||||
}
|
||||
|
||||
EMSCRIPTEN_KEEPALIVE
|
||||
void flush_encoder_start(EncoderContext *ctx) {
|
||||
avcodec_send_frame(ctx->codec_ctx, NULL);
|
||||
}
|
||||
|
||||
EMSCRIPTEN_KEEPALIVE
|
||||
void reset_encoder(EncoderContext *ctx) {
|
||||
avcodec_flush_buffers(ctx->codec_ctx);
|
||||
}
|
||||
|
||||
EMSCRIPTEN_KEEPALIVE
|
||||
uint8_t *get_encoded_data(EncoderContext *ctx) {
|
||||
return ctx->packet->data;
|
||||
}
|
||||
|
||||
EMSCRIPTEN_KEEPALIVE
|
||||
int get_encoded_pts(EncoderContext *ctx) {
|
||||
return ctx->encoded_pts;
|
||||
}
|
||||
|
||||
EMSCRIPTEN_KEEPALIVE
|
||||
int get_encoded_duration(EncoderContext *ctx) {
|
||||
return ctx->encoded_duration;
|
||||
}
|
||||
|
||||
EMSCRIPTEN_KEEPALIVE
|
||||
void close_encoder(EncoderContext *ctx) {
|
||||
free(ctx->input_buffer);
|
||||
av_frame_free(&ctx->frame);
|
||||
av_packet_free(&ctx->packet);
|
||||
avcodec_free_context(&ctx->codec_ctx);
|
||||
free(ctx);
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
/*!
|
||||
* Copyright (c) 2026-present, Vanilagy and contributors
|
||||
*
|
||||
* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||
*/
|
||||
|
||||
import createModule from '../build/aac';
|
||||
import type { PacketInfo, WorkerCommand, WorkerResponse, WorkerResponseData } from './shared';
|
||||
|
||||
type ExtendedEmscriptenModule = EmscriptenModule & {
|
||||
cwrap: typeof cwrap;
|
||||
};
|
||||
|
||||
let module: ExtendedEmscriptenModule;
|
||||
let modulePromise: Promise<ExtendedEmscriptenModule> | null = null;
|
||||
|
||||
let initEncoderFn: (channels: number, sampleRate: number, bitrate: number) => number;
|
||||
let getEncoderFrameSize: (ctx: number) => number;
|
||||
let getEncoderExtradata: (ctx: number) => number;
|
||||
let getEncoderExtradataSize: (ctx: number) => number;
|
||||
let getEncodeInputPtr: (ctx: number, size: number) => number;
|
||||
let sendFrameFn: (ctx: number, pts: number) => number;
|
||||
let receivePacketFn: (ctx: number) => number;
|
||||
let flushEncoderStartFn: (ctx: number) => void;
|
||||
let resetEncoderFn: (ctx: number) => void;
|
||||
let getEncodedData: (ctx: number) => number;
|
||||
let getEncodedPts: (ctx: number) => number;
|
||||
let getEncodedDuration: (ctx: number) => number;
|
||||
const ensureModule = async () => {
|
||||
if (!module) {
|
||||
if (modulePromise) {
|
||||
return modulePromise;
|
||||
}
|
||||
|
||||
modulePromise = createModule() as Promise<ExtendedEmscriptenModule>;
|
||||
module = await modulePromise;
|
||||
modulePromise = null;
|
||||
|
||||
initEncoderFn = module.cwrap('init_encoder', 'number', ['number', 'number', 'number']);
|
||||
getEncoderFrameSize = module.cwrap('get_encoder_frame_size', 'number', ['number']);
|
||||
getEncoderExtradata = module.cwrap('get_encoder_extradata', 'number', ['number']);
|
||||
getEncoderExtradataSize = module.cwrap('get_encoder_extradata_size', 'number', ['number']);
|
||||
getEncodeInputPtr = module.cwrap('get_encode_input_ptr', 'number', ['number', 'number']);
|
||||
sendFrameFn = module.cwrap('send_frame', 'number', ['number', 'number']);
|
||||
receivePacketFn = module.cwrap('receive_packet', 'number', ['number']);
|
||||
flushEncoderStartFn = module.cwrap('flush_encoder_start', null, ['number']);
|
||||
resetEncoderFn = module.cwrap('reset_encoder', null, ['number']);
|
||||
getEncodedData = module.cwrap('get_encoded_data', 'number', ['number']);
|
||||
getEncodedPts = module.cwrap('get_encoded_pts', 'number', ['number']);
|
||||
getEncodedDuration = module.cwrap('get_encoded_duration', 'number', ['number']);
|
||||
}
|
||||
};
|
||||
|
||||
const initEncoder = async (
|
||||
numberOfChannels: number,
|
||||
sampleRate: number,
|
||||
bitrate: number,
|
||||
) => {
|
||||
await ensureModule();
|
||||
|
||||
const ctx = initEncoderFn(numberOfChannels, sampleRate, bitrate);
|
||||
if (ctx === 0) {
|
||||
throw new Error('Failed to initialize AAC encoder.');
|
||||
}
|
||||
|
||||
const frameSize = getEncoderFrameSize(ctx);
|
||||
|
||||
const extradataPtr = getEncoderExtradata(ctx);
|
||||
const extradataSize = getEncoderExtradataSize(ctx);
|
||||
const extradata = module.HEAPU8.slice(extradataPtr, extradataPtr + extradataSize).buffer;
|
||||
|
||||
return { ctx, frameSize, extradata };
|
||||
};
|
||||
|
||||
const drainPackets = (ctx: number) => {
|
||||
const packets: PacketInfo[] = [];
|
||||
|
||||
let size: number;
|
||||
while ((size = receivePacketFn(ctx)) > 0) {
|
||||
const ptr = getEncodedData(ctx);
|
||||
const encodedData = module.HEAPU8.slice(ptr, ptr + size).buffer;
|
||||
const pts = getEncodedPts(ctx);
|
||||
const duration = getEncodedDuration(ctx);
|
||||
packets.push({ encodedData, pts, duration });
|
||||
}
|
||||
|
||||
return packets;
|
||||
};
|
||||
|
||||
const encode = (ctx: number, audioData: ArrayBuffer, timestamp: number) => {
|
||||
const audioBytes = new Uint8Array(audioData);
|
||||
|
||||
const inputPtr = getEncodeInputPtr(ctx, audioBytes.length);
|
||||
if (inputPtr === 0) {
|
||||
throw new Error('Failed to allocate encoder input buffer.');
|
||||
}
|
||||
module.HEAPU8.set(audioBytes, inputPtr);
|
||||
|
||||
const ret = sendFrameFn(ctx, timestamp);
|
||||
if (ret < 0) {
|
||||
throw new Error(`Encode failed with error code ${ret}.`);
|
||||
}
|
||||
|
||||
return drainPackets(ctx);
|
||||
};
|
||||
|
||||
const onMessage = (data: { id: number; command: WorkerCommand }) => {
|
||||
const { id, command } = data;
|
||||
|
||||
const handleCommand = async (): Promise<void> => {
|
||||
try {
|
||||
let result: WorkerResponseData;
|
||||
const transferables: Transferable[] = [];
|
||||
|
||||
switch (command.type) {
|
||||
case 'init': {
|
||||
const { ctx, frameSize, extradata } = await initEncoder(
|
||||
command.data.numberOfChannels,
|
||||
command.data.sampleRate,
|
||||
command.data.bitrate,
|
||||
);
|
||||
result = { type: command.type, ctx, frameSize, extradata };
|
||||
transferables.push(extradata);
|
||||
}; break;
|
||||
|
||||
case 'encode': {
|
||||
const packets = encode(
|
||||
command.data.ctx,
|
||||
command.data.audioData,
|
||||
command.data.timestamp,
|
||||
);
|
||||
for (const p of packets) {
|
||||
transferables.push(p.encodedData);
|
||||
}
|
||||
result = { type: command.type, packets };
|
||||
}; break;
|
||||
|
||||
case 'flush': {
|
||||
flushEncoderStartFn(command.data.ctx);
|
||||
const packets = drainPackets(command.data.ctx);
|
||||
for (const p of packets) {
|
||||
transferables.push(p.encodedData);
|
||||
}
|
||||
resetEncoderFn(command.data.ctx);
|
||||
result = { type: command.type, packets };
|
||||
}; break;
|
||||
}
|
||||
|
||||
const response: WorkerResponse = {
|
||||
id,
|
||||
success: true,
|
||||
data: result,
|
||||
};
|
||||
sendMessage(response, transferables);
|
||||
} catch (error: unknown) {
|
||||
const response: WorkerResponse = {
|
||||
id,
|
||||
success: false,
|
||||
error,
|
||||
};
|
||||
sendMessage(response);
|
||||
}
|
||||
};
|
||||
|
||||
void handleCommand();
|
||||
};
|
||||
|
||||
const sendMessage = (data: unknown, transferables?: Transferable[]) => {
|
||||
if (parentPort) {
|
||||
parentPort.postMessage(data, transferables ?? []);
|
||||
} else {
|
||||
self.postMessage(data, { transfer: transferables ?? [] });
|
||||
}
|
||||
};
|
||||
|
||||
let parentPort: {
|
||||
postMessage: (data: unknown, transferables?: Transferable[]) => void;
|
||||
on: (event: string, listener: (data: never) => void) => void;
|
||||
} | null = null;
|
||||
|
||||
if (typeof self === 'undefined') {
|
||||
const workerModule = 'worker_threads';
|
||||
// eslint-disable-next-line @stylistic/max-len
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-require-imports, @typescript-eslint/no-unsafe-member-access
|
||||
parentPort = require(workerModule).parentPort;
|
||||
}
|
||||
|
||||
if (parentPort) {
|
||||
parentPort.on('message', onMessage);
|
||||
} else {
|
||||
self.addEventListener('message', event => onMessage(event.data as { id: number; command: WorkerCommand }));
|
||||
}
|
||||
@@ -0,0 +1,305 @@
|
||||
/*!
|
||||
* Copyright (c) 2026-present, Vanilagy and contributors
|
||||
*
|
||||
* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||
*/
|
||||
|
||||
import {
|
||||
type AdtsHeaderTemplate,
|
||||
buildAdtsHeaderTemplate,
|
||||
parseAacAudioSpecificConfig,
|
||||
writeAdtsFrameLength,
|
||||
} from '../../../shared/aac-misc';
|
||||
import {
|
||||
CustomAudioEncoder,
|
||||
AudioCodec,
|
||||
AudioSample,
|
||||
EncodedPacket,
|
||||
registerEncoder,
|
||||
} from 'mediabunny';
|
||||
import type { PacketInfo, WorkerCommand, WorkerResponse, WorkerResponseData } from './shared';
|
||||
// @ts-expect-error An esbuild plugin handles this, TypeScript doesn't need to understand
|
||||
import createWorker from './encode.worker';
|
||||
|
||||
const AAC_SAMPLE_RATES = [
|
||||
96000, 88200, 64000, 48000, 44100, 32000,
|
||||
24000, 22050, 16000, 12000, 11025, 8000, 7350,
|
||||
];
|
||||
|
||||
class AacEncoder extends CustomAudioEncoder {
|
||||
private worker: Worker | null = null;
|
||||
private nextMessageId = 0;
|
||||
private pendingMessages = new Map<number, {
|
||||
resolve: (value: WorkerResponseData) => void;
|
||||
reject: (reason?: unknown) => void;
|
||||
}>();
|
||||
|
||||
private ctx = 0;
|
||||
private encoderFrameSize = 0;
|
||||
private sampleRate = 0;
|
||||
private numberOfChannels = 0;
|
||||
private chunkMetadata: EncodedAudioChunkMetadata = {};
|
||||
private useAdts = false;
|
||||
private adtsHeaderTemplate: AdtsHeaderTemplate | null = null;
|
||||
private description: Uint8Array | null = null;
|
||||
|
||||
// Accumulate interleaved f32 samples until we have a full frame
|
||||
private pendingBuffer = new Float32Array(2 ** 16);
|
||||
private pendingFrames = 0;
|
||||
private nextSampleTimestampInSamples: number | null = null;
|
||||
private nextPacketTimestampInSamples: number | null = null;
|
||||
|
||||
static override supports(codec: AudioCodec, config: AudioEncoderConfig): boolean {
|
||||
return codec === 'aac'
|
||||
&& config.numberOfChannels >= 1
|
||||
&& config.numberOfChannels <= 8
|
||||
&& AAC_SAMPLE_RATES.includes(config.sampleRate)
|
||||
&& config.bitrate !== undefined;
|
||||
}
|
||||
|
||||
async init() {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-call
|
||||
this.worker = (await createWorker()) as Worker;
|
||||
|
||||
const onMessage = (data: WorkerResponse) => {
|
||||
const pending = this.pendingMessages.get(data.id);
|
||||
assert(pending !== undefined);
|
||||
|
||||
this.pendingMessages.delete(data.id);
|
||||
if (data.success) {
|
||||
pending.resolve(data.data);
|
||||
} else {
|
||||
pending.reject(data.error);
|
||||
}
|
||||
};
|
||||
|
||||
if (this.worker.addEventListener) {
|
||||
this.worker.addEventListener('message', event => onMessage(event.data as WorkerResponse));
|
||||
} else {
|
||||
const nodeWorker = this.worker as unknown as {
|
||||
on: (event: string, listener: (data: never) => void) => void;
|
||||
};
|
||||
nodeWorker.on('message', onMessage);
|
||||
}
|
||||
|
||||
assert(this.config.bitrate !== undefined);
|
||||
this.sampleRate = this.config.sampleRate;
|
||||
this.numberOfChannels = this.config.numberOfChannels;
|
||||
|
||||
const result = await this.sendCommand({
|
||||
type: 'init',
|
||||
data: {
|
||||
numberOfChannels: this.config.numberOfChannels,
|
||||
sampleRate: this.config.sampleRate,
|
||||
bitrate: this.config.bitrate,
|
||||
},
|
||||
});
|
||||
|
||||
this.ctx = result.ctx;
|
||||
this.encoderFrameSize = result.frameSize;
|
||||
|
||||
// The ffmpeg encoder provides an AudioSpecificConfig as extradata after init
|
||||
const description = new Uint8Array(result.extradata);
|
||||
|
||||
const aacConfig = (this.config as { aac?: { format?: 'aac' | 'adts' } }).aac;
|
||||
this.useAdts = aacConfig?.format === 'adts';
|
||||
|
||||
if (this.useAdts) {
|
||||
const audioSpecificConfig = parseAacAudioSpecificConfig(description);
|
||||
this.adtsHeaderTemplate = buildAdtsHeaderTemplate(audioSpecificConfig);
|
||||
}
|
||||
|
||||
this.description = this.useAdts ? null : description;
|
||||
this.resetInternalState();
|
||||
}
|
||||
|
||||
private resetInternalState() {
|
||||
this.pendingFrames = 0;
|
||||
this.nextSampleTimestampInSamples = null;
|
||||
this.nextPacketTimestampInSamples = null;
|
||||
|
||||
this.chunkMetadata = {
|
||||
decoderConfig: {
|
||||
codec: 'mp4a.40.2',
|
||||
numberOfChannels: this.config.numberOfChannels,
|
||||
sampleRate: this.config.sampleRate,
|
||||
...(this.description ? { description: this.description } : {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async encode(audioSample: AudioSample) {
|
||||
if (this.nextSampleTimestampInSamples === null) {
|
||||
this.nextSampleTimestampInSamples = Math.round(audioSample.timestamp * this.sampleRate);
|
||||
this.nextPacketTimestampInSamples = this.nextSampleTimestampInSamples;
|
||||
}
|
||||
|
||||
const channels = this.numberOfChannels;
|
||||
const incomingFrames = audioSample.numberOfFrames;
|
||||
|
||||
// Extract interleaved f32 data
|
||||
const totalBytes = audioSample.allocationSize({ format: 'f32', planeIndex: 0 });
|
||||
const audioBytes = new Uint8Array(totalBytes);
|
||||
audioSample.copyTo(audioBytes, { format: 'f32', planeIndex: 0 });
|
||||
const incomingData = new Float32Array(audioBytes.buffer);
|
||||
|
||||
const requiredSamples = (this.pendingFrames + incomingFrames) * channels;
|
||||
if (requiredSamples > this.pendingBuffer.length) {
|
||||
let newSize = this.pendingBuffer.length;
|
||||
while (newSize < requiredSamples) {
|
||||
newSize *= 2;
|
||||
}
|
||||
const newBuffer = new Float32Array(newSize);
|
||||
newBuffer.set(this.pendingBuffer.subarray(0, this.pendingFrames * channels));
|
||||
this.pendingBuffer = newBuffer;
|
||||
}
|
||||
this.pendingBuffer.set(incomingData, this.pendingFrames * channels);
|
||||
this.pendingFrames += incomingFrames;
|
||||
|
||||
while (this.pendingFrames >= this.encoderFrameSize) {
|
||||
await this.encodeOneFrame();
|
||||
}
|
||||
}
|
||||
|
||||
async flush() {
|
||||
// Pad remaining samples with silence to fill a full frame
|
||||
if (this.pendingFrames > 0) {
|
||||
const channels = this.numberOfChannels;
|
||||
const frameSize = this.encoderFrameSize;
|
||||
const usedSamples = this.pendingFrames * channels;
|
||||
const frameSamples = frameSize * channels;
|
||||
|
||||
this.pendingBuffer.fill(0, usedSamples, frameSamples);
|
||||
this.pendingFrames = frameSize;
|
||||
|
||||
await this.encodeOneFrame();
|
||||
}
|
||||
|
||||
const result = await this.sendCommand({ type: 'flush', data: { ctx: this.ctx } });
|
||||
this.emitPackets(result.packets);
|
||||
|
||||
this.resetInternalState();
|
||||
}
|
||||
|
||||
close() {
|
||||
this.worker?.terminate();
|
||||
}
|
||||
|
||||
private async encodeOneFrame() {
|
||||
assert(this.nextSampleTimestampInSamples !== null);
|
||||
assert(this.nextPacketTimestampInSamples !== null);
|
||||
|
||||
const channels = this.numberOfChannels;
|
||||
const frameSize = this.encoderFrameSize;
|
||||
const frameSamples = frameSize * channels;
|
||||
|
||||
const frameData = this.pendingBuffer.slice(0, frameSamples);
|
||||
|
||||
// Shift remaining using copyWithin
|
||||
this.pendingFrames -= frameSize;
|
||||
if (this.pendingFrames > 0) {
|
||||
this.pendingBuffer.copyWithin(0, frameSamples, frameSamples + this.pendingFrames * channels);
|
||||
}
|
||||
|
||||
const audioData = frameData.buffer;
|
||||
const result = await this.sendCommand({
|
||||
type: 'encode',
|
||||
data: {
|
||||
ctx: this.ctx,
|
||||
audioData,
|
||||
timestamp: this.nextSampleTimestampInSamples,
|
||||
},
|
||||
}, [audioData]);
|
||||
|
||||
this.nextSampleTimestampInSamples += frameSize;
|
||||
|
||||
this.emitPackets(result.packets);
|
||||
}
|
||||
|
||||
private emitPackets(packets: PacketInfo[]) {
|
||||
assert(this.nextPacketTimestampInSamples !== null);
|
||||
|
||||
for (const p of packets) {
|
||||
let data = new Uint8Array(p.encodedData);
|
||||
|
||||
if (this.useAdts) {
|
||||
assert(this.adtsHeaderTemplate !== null);
|
||||
const { header, bitstream } = this.adtsHeaderTemplate;
|
||||
const frameLength = header.byteLength + data.byteLength;
|
||||
writeAdtsFrameLength(bitstream, frameLength);
|
||||
|
||||
const adtsFrame = new Uint8Array(frameLength);
|
||||
adtsFrame.set(header, 0);
|
||||
adtsFrame.set(data, header.byteLength);
|
||||
data = adtsFrame;
|
||||
}
|
||||
|
||||
const packet = new EncodedPacket(
|
||||
data,
|
||||
'key',
|
||||
this.nextPacketTimestampInSamples / this.sampleRate,
|
||||
p.duration / this.sampleRate,
|
||||
);
|
||||
|
||||
this.nextPacketTimestampInSamples += p.duration;
|
||||
|
||||
this.onPacket(
|
||||
packet,
|
||||
this.chunkMetadata,
|
||||
);
|
||||
|
||||
this.chunkMetadata = {};
|
||||
}
|
||||
}
|
||||
|
||||
private sendCommand<T extends string>(
|
||||
command: WorkerCommand & { type: T },
|
||||
transferables?: Transferable[],
|
||||
) {
|
||||
return new Promise<WorkerResponseData & { type: T }>((resolve, reject) => {
|
||||
const id = this.nextMessageId++;
|
||||
this.pendingMessages.set(id, {
|
||||
resolve: resolve as (value: WorkerResponseData) => void,
|
||||
reject,
|
||||
});
|
||||
|
||||
assert(this.worker);
|
||||
|
||||
if (transferables) {
|
||||
this.worker.postMessage({ id, command }, transferables);
|
||||
} else {
|
||||
this.worker.postMessage({ id, command });
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers the AAC encoder, which Mediabunny will then use automatically when applicable. Make sure to call this
|
||||
* function before starting any encoding task.
|
||||
*
|
||||
* Preferably, wrap the call in a condition to avoid overriding any native AAC encoder:
|
||||
*
|
||||
* ```ts
|
||||
* import { canEncodeAudio } from 'mediabunny';
|
||||
* import { registerAacEncoder } from '@mediabunny/aac-encoder';
|
||||
*
|
||||
* if (!(await canEncodeAudio('aac'))) {
|
||||
* registerAacEncoder();
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @group \@mediabunny/aac-encoder
|
||||
* @public
|
||||
*/
|
||||
export const registerAacEncoder = () => {
|
||||
registerEncoder(AacEncoder);
|
||||
};
|
||||
|
||||
function assert(x: unknown): asserts x {
|
||||
if (!x) {
|
||||
throw new Error('Assertion failed.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
/*!
|
||||
* Copyright (c) 2026-present, Vanilagy and contributors
|
||||
*
|
||||
* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||
*/
|
||||
|
||||
const AAC_ENCODER_LOADED_SYMBOL = Symbol.for('@mediabunny/aac-encoder loaded');
|
||||
if ((globalThis as Record<symbol, unknown>)[AAC_ENCODER_LOADED_SYMBOL]) {
|
||||
console.error(
|
||||
'[WARNING]\n@mediabunny/aac-encoder was loaded twice.'
|
||||
+ ' This will likely cause the encoder not to work correctly.'
|
||||
+ ' Check if multiple dependencies are importing different versions of @mediabunny/aac-encoder,'
|
||||
+ ' or if something is being bundled incorrectly.',
|
||||
);
|
||||
}
|
||||
(globalThis as Record<symbol, unknown>)[AAC_ENCODER_LOADED_SYMBOL] = true;
|
||||
|
||||
export { registerAacEncoder } from './encoder';
|
||||
@@ -0,0 +1,57 @@
|
||||
/*!
|
||||
* Copyright (c) 2026-present, Vanilagy and contributors
|
||||
*
|
||||
* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||
*/
|
||||
|
||||
export type WorkerCommand = {
|
||||
type: 'init';
|
||||
data: {
|
||||
numberOfChannels: number;
|
||||
sampleRate: number;
|
||||
bitrate: number;
|
||||
};
|
||||
} | {
|
||||
type: 'encode';
|
||||
data: {
|
||||
ctx: number;
|
||||
audioData: ArrayBuffer;
|
||||
timestamp: number;
|
||||
};
|
||||
} | {
|
||||
type: 'flush';
|
||||
data: {
|
||||
ctx: number;
|
||||
};
|
||||
};
|
||||
|
||||
export type PacketInfo = {
|
||||
encodedData: ArrayBuffer;
|
||||
pts: number;
|
||||
duration: number;
|
||||
};
|
||||
|
||||
export type WorkerResponseData = {
|
||||
type: 'init';
|
||||
ctx: number;
|
||||
frameSize: number;
|
||||
extradata: ArrayBuffer;
|
||||
} | {
|
||||
type: 'encode';
|
||||
packets: PacketInfo[];
|
||||
} | {
|
||||
type: 'flush';
|
||||
packets: PacketInfo[];
|
||||
};
|
||||
|
||||
export type WorkerResponse = {
|
||||
id: number;
|
||||
} & ({
|
||||
success: true;
|
||||
data: WorkerResponseData;
|
||||
} | {
|
||||
success: false;
|
||||
error: unknown;
|
||||
});
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"extends": "../../tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"composite": true,
|
||||
"outDir": "./dist/modules",
|
||||
"declaration": true,
|
||||
"declarationMap": true,
|
||||
"stripInternal": true,
|
||||
"noEmit": false,
|
||||
"moduleResolution": "nodenext",
|
||||
"module": "nodenext",
|
||||
"allowJs": true,
|
||||
"paths": {
|
||||
"mediabunny": ["../../src/index.ts"],
|
||||
},
|
||||
},
|
||||
"include": [
|
||||
"./src/**/*",
|
||||
"./build/**/*",
|
||||
],
|
||||
"references": [
|
||||
{ "path": "../../src" }
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"$schema": "https://developer.microsoft.com/json-schemas/tsdoc/v0/tsdoc.schema.json",
|
||||
"extends": ["../../tsdoc.json"]
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@mediabunny/ac3",
|
||||
"author": "Vanilagy",
|
||||
"version": "1.35.1",
|
||||
"version": "1.37.0",
|
||||
"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",
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
build/* linguist-generated
|
||||
@@ -0,0 +1,373 @@
|
||||
Mozilla Public License Version 2.0
|
||||
==================================
|
||||
|
||||
1. Definitions
|
||||
--------------
|
||||
|
||||
1.1. "Contributor"
|
||||
means each individual or legal entity that creates, contributes to
|
||||
the creation of, or owns Covered Software.
|
||||
|
||||
1.2. "Contributor Version"
|
||||
means the combination of the Contributions of others (if any) used
|
||||
by a Contributor and that particular Contributor's Contribution.
|
||||
|
||||
1.3. "Contribution"
|
||||
means Covered Software of a particular Contributor.
|
||||
|
||||
1.4. "Covered Software"
|
||||
means Source Code Form to which the initial Contributor has attached
|
||||
the notice in Exhibit A, the Executable Form of such Source Code
|
||||
Form, and Modifications of such Source Code Form, in each case
|
||||
including portions thereof.
|
||||
|
||||
1.5. "Incompatible With Secondary Licenses"
|
||||
means
|
||||
|
||||
(a) that the initial Contributor has attached the notice described
|
||||
in Exhibit B to the Covered Software; or
|
||||
|
||||
(b) that the Covered Software was made available under the terms of
|
||||
version 1.1 or earlier of the License, but not also under the
|
||||
terms of a Secondary License.
|
||||
|
||||
1.6. "Executable Form"
|
||||
means any form of the work other than Source Code Form.
|
||||
|
||||
1.7. "Larger Work"
|
||||
means a work that combines Covered Software with other material, in
|
||||
a separate file or files, that is not Covered Software.
|
||||
|
||||
1.8. "License"
|
||||
means this document.
|
||||
|
||||
1.9. "Licensable"
|
||||
means having the right to grant, to the maximum extent possible,
|
||||
whether at the time of the initial grant or subsequently, any and
|
||||
all of the rights conveyed by this License.
|
||||
|
||||
1.10. "Modifications"
|
||||
means any of the following:
|
||||
|
||||
(a) any file in Source Code Form that results from an addition to,
|
||||
deletion from, or modification of the contents of Covered
|
||||
Software; or
|
||||
|
||||
(b) any new file in Source Code Form that contains any Covered
|
||||
Software.
|
||||
|
||||
1.11. "Patent Claims" of a Contributor
|
||||
means any patent claim(s), including without limitation, method,
|
||||
process, and apparatus claims, in any patent Licensable by such
|
||||
Contributor that would be infringed, but for the grant of the
|
||||
License, by the making, using, selling, offering for sale, having
|
||||
made, import, or transfer of either its Contributions or its
|
||||
Contributor Version.
|
||||
|
||||
1.12. "Secondary License"
|
||||
means either the GNU General Public License, Version 2.0, the GNU
|
||||
Lesser General Public License, Version 2.1, the GNU Affero General
|
||||
Public License, Version 3.0, or any later versions of those
|
||||
licenses.
|
||||
|
||||
1.13. "Source Code Form"
|
||||
means the form of the work preferred for making modifications.
|
||||
|
||||
1.14. "You" (or "Your")
|
||||
means an individual or a legal entity exercising rights under this
|
||||
License. For legal entities, "You" includes any entity that
|
||||
controls, is controlled by, or is under common control with You. For
|
||||
purposes of this definition, "control" means (a) the power, direct
|
||||
or indirect, to cause the direction or management of such entity,
|
||||
whether by contract or otherwise, or (b) ownership of more than
|
||||
fifty percent (50%) of the outstanding shares or beneficial
|
||||
ownership of such entity.
|
||||
|
||||
2. License Grants and Conditions
|
||||
--------------------------------
|
||||
|
||||
2.1. Grants
|
||||
|
||||
Each Contributor hereby grants You a world-wide, royalty-free,
|
||||
non-exclusive license:
|
||||
|
||||
(a) under intellectual property rights (other than patent or trademark)
|
||||
Licensable by such Contributor to use, reproduce, make available,
|
||||
modify, display, perform, distribute, and otherwise exploit its
|
||||
Contributions, either on an unmodified basis, with Modifications, or
|
||||
as part of a Larger Work; and
|
||||
|
||||
(b) under Patent Claims of such Contributor to make, use, sell, offer
|
||||
for sale, have made, import, and otherwise transfer either its
|
||||
Contributions or its Contributor Version.
|
||||
|
||||
2.2. Effective Date
|
||||
|
||||
The licenses granted in Section 2.1 with respect to any Contribution
|
||||
become effective for each Contribution on the date the Contributor first
|
||||
distributes such Contribution.
|
||||
|
||||
2.3. Limitations on Grant Scope
|
||||
|
||||
The licenses granted in this Section 2 are the only rights granted under
|
||||
this License. No additional rights or licenses will be implied from the
|
||||
distribution or licensing of Covered Software under this License.
|
||||
Notwithstanding Section 2.1(b) above, no patent license is granted by a
|
||||
Contributor:
|
||||
|
||||
(a) for any code that a Contributor has removed from Covered Software;
|
||||
or
|
||||
|
||||
(b) for infringements caused by: (i) Your and any other third party's
|
||||
modifications of Covered Software, or (ii) the combination of its
|
||||
Contributions with other software (except as part of its Contributor
|
||||
Version); or
|
||||
|
||||
(c) under Patent Claims infringed by Covered Software in the absence of
|
||||
its Contributions.
|
||||
|
||||
This License does not grant any rights in the trademarks, service marks,
|
||||
or logos of any Contributor (except as may be necessary to comply with
|
||||
the notice requirements in Section 3.4).
|
||||
|
||||
2.4. Subsequent Licenses
|
||||
|
||||
No Contributor makes additional grants as a result of Your choice to
|
||||
distribute the Covered Software under a subsequent version of this
|
||||
License (see Section 10.2) or under the terms of a Secondary License (if
|
||||
permitted under the terms of Section 3.3).
|
||||
|
||||
2.5. Representation
|
||||
|
||||
Each Contributor represents that the Contributor believes its
|
||||
Contributions are its original creation(s) or it has sufficient rights
|
||||
to grant the rights to its Contributions conveyed by this License.
|
||||
|
||||
2.6. Fair Use
|
||||
|
||||
This License is not intended to limit any rights You have under
|
||||
applicable copyright doctrines of fair use, fair dealing, or other
|
||||
equivalents.
|
||||
|
||||
2.7. Conditions
|
||||
|
||||
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
|
||||
in Section 2.1.
|
||||
|
||||
3. Responsibilities
|
||||
-------------------
|
||||
|
||||
3.1. Distribution of Source Form
|
||||
|
||||
All distribution of Covered Software in Source Code Form, including any
|
||||
Modifications that You create or to which You contribute, must be under
|
||||
the terms of this License. You must inform recipients that the Source
|
||||
Code Form of the Covered Software is governed by the terms of this
|
||||
License, and how they can obtain a copy of this License. You may not
|
||||
attempt to alter or restrict the recipients' rights in the Source Code
|
||||
Form.
|
||||
|
||||
3.2. Distribution of Executable Form
|
||||
|
||||
If You distribute Covered Software in Executable Form then:
|
||||
|
||||
(a) such Covered Software must also be made available in Source Code
|
||||
Form, as described in Section 3.1, and You must inform recipients of
|
||||
the Executable Form how they can obtain a copy of such Source Code
|
||||
Form by reasonable means in a timely manner, at a charge no more
|
||||
than the cost of distribution to the recipient; and
|
||||
|
||||
(b) You may distribute such Executable Form under the terms of this
|
||||
License, or sublicense it under different terms, provided that the
|
||||
license for the Executable Form does not attempt to limit or alter
|
||||
the recipients' rights in the Source Code Form under this License.
|
||||
|
||||
3.3. Distribution of a Larger Work
|
||||
|
||||
You may create and distribute a Larger Work under terms of Your choice,
|
||||
provided that You also comply with the requirements of this License for
|
||||
the Covered Software. If the Larger Work is a combination of Covered
|
||||
Software with a work governed by one or more Secondary Licenses, and the
|
||||
Covered Software is not Incompatible With Secondary Licenses, this
|
||||
License permits You to additionally distribute such Covered Software
|
||||
under the terms of such Secondary License(s), so that the recipient of
|
||||
the Larger Work may, at their option, further distribute the Covered
|
||||
Software under the terms of either this License or such Secondary
|
||||
License(s).
|
||||
|
||||
3.4. Notices
|
||||
|
||||
You may not remove or alter the substance of any license notices
|
||||
(including copyright notices, patent notices, disclaimers of warranty,
|
||||
or limitations of liability) contained within the Source Code Form of
|
||||
the Covered Software, except that You may alter any license notices to
|
||||
the extent required to remedy known factual inaccuracies.
|
||||
|
||||
3.5. Application of Additional Terms
|
||||
|
||||
You may choose to offer, and to charge a fee for, warranty, support,
|
||||
indemnity or liability obligations to one or more recipients of Covered
|
||||
Software. However, You may do so only on Your own behalf, and not on
|
||||
behalf of any Contributor. You must make it absolutely clear that any
|
||||
such warranty, support, indemnity, or liability obligation is offered by
|
||||
You alone, and You hereby agree to indemnify every Contributor for any
|
||||
liability incurred by such Contributor as a result of warranty, support,
|
||||
indemnity or liability terms You offer. You may include additional
|
||||
disclaimers of warranty and limitations of liability specific to any
|
||||
jurisdiction.
|
||||
|
||||
4. Inability to Comply Due to Statute or Regulation
|
||||
---------------------------------------------------
|
||||
|
||||
If it is impossible for You to comply with any of the terms of this
|
||||
License with respect to some or all of the Covered Software due to
|
||||
statute, judicial order, or regulation then You must: (a) comply with
|
||||
the terms of this License to the maximum extent possible; and (b)
|
||||
describe the limitations and the code they affect. Such description must
|
||||
be placed in a text file included with all distributions of the Covered
|
||||
Software under this License. Except to the extent prohibited by statute
|
||||
or regulation, such description must be sufficiently detailed for a
|
||||
recipient of ordinary skill to be able to understand it.
|
||||
|
||||
5. Termination
|
||||
--------------
|
||||
|
||||
5.1. The rights granted under this License will terminate automatically
|
||||
if You fail to comply with any of its terms. However, if You become
|
||||
compliant, then the rights granted under this License from a particular
|
||||
Contributor are reinstated (a) provisionally, unless and until such
|
||||
Contributor explicitly and finally terminates Your grants, and (b) on an
|
||||
ongoing basis, if such Contributor fails to notify You of the
|
||||
non-compliance by some reasonable means prior to 60 days after You have
|
||||
come back into compliance. Moreover, Your grants from a particular
|
||||
Contributor are reinstated on an ongoing basis if such Contributor
|
||||
notifies You of the non-compliance by some reasonable means, this is the
|
||||
first time You have received notice of non-compliance with this License
|
||||
from such Contributor, and You become compliant prior to 30 days after
|
||||
Your receipt of the notice.
|
||||
|
||||
5.2. If You initiate litigation against any entity by asserting a patent
|
||||
infringement claim (excluding declaratory judgment actions,
|
||||
counter-claims, and cross-claims) alleging that a Contributor Version
|
||||
directly or indirectly infringes any patent, then the rights granted to
|
||||
You by any and all Contributors for the Covered Software under Section
|
||||
2.1 of this License shall terminate.
|
||||
|
||||
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
|
||||
end user license agreements (excluding distributors and resellers) which
|
||||
have been validly granted by You or Your distributors under this License
|
||||
prior to termination shall survive termination.
|
||||
|
||||
************************************************************************
|
||||
* *
|
||||
* 6. Disclaimer of Warranty *
|
||||
* ------------------------- *
|
||||
* *
|
||||
* Covered Software is provided under this License on an "as is" *
|
||||
* basis, without warranty of any kind, either expressed, implied, or *
|
||||
* statutory, including, without limitation, warranties that the *
|
||||
* Covered Software is free of defects, merchantable, fit for a *
|
||||
* particular purpose or non-infringing. The entire risk as to the *
|
||||
* quality and performance of the Covered Software is with You. *
|
||||
* Should any Covered Software prove defective in any respect, You *
|
||||
* (not any Contributor) assume the cost of any necessary servicing, *
|
||||
* repair, or correction. This disclaimer of warranty constitutes an *
|
||||
* essential part of this License. No use of any Covered Software is *
|
||||
* authorized under this License except under this disclaimer. *
|
||||
* *
|
||||
************************************************************************
|
||||
|
||||
************************************************************************
|
||||
* *
|
||||
* 7. Limitation of Liability *
|
||||
* -------------------------- *
|
||||
* *
|
||||
* Under no circumstances and under no legal theory, whether tort *
|
||||
* (including negligence), contract, or otherwise, shall any *
|
||||
* Contributor, or anyone who distributes Covered Software as *
|
||||
* permitted above, be liable to You for any direct, indirect, *
|
||||
* special, incidental, or consequential damages of any character *
|
||||
* including, without limitation, damages for lost profits, loss of *
|
||||
* goodwill, work stoppage, computer failure or malfunction, or any *
|
||||
* and all other commercial damages or losses, even if such party *
|
||||
* shall have been informed of the possibility of such damages. This *
|
||||
* limitation of liability shall not apply to liability for death or *
|
||||
* personal injury resulting from such party's negligence to the *
|
||||
* extent applicable law prohibits such limitation. Some *
|
||||
* jurisdictions do not allow the exclusion or limitation of *
|
||||
* incidental or consequential damages, so this exclusion and *
|
||||
* limitation may not apply to You. *
|
||||
* *
|
||||
************************************************************************
|
||||
|
||||
8. Litigation
|
||||
-------------
|
||||
|
||||
Any litigation relating to this License may be brought only in the
|
||||
courts of a jurisdiction where the defendant maintains its principal
|
||||
place of business and such litigation shall be governed by laws of that
|
||||
jurisdiction, without reference to its conflict-of-law provisions.
|
||||
Nothing in this Section shall prevent a party's ability to bring
|
||||
cross-claims or counter-claims.
|
||||
|
||||
9. Miscellaneous
|
||||
----------------
|
||||
|
||||
This License represents the complete agreement concerning the subject
|
||||
matter hereof. If any provision of this License is held to be
|
||||
unenforceable, such provision shall be reformed only to the extent
|
||||
necessary to make it enforceable. Any law or regulation which provides
|
||||
that the language of a contract shall be construed against the drafter
|
||||
shall not be used to construe this License against a Contributor.
|
||||
|
||||
10. Versions of the License
|
||||
---------------------------
|
||||
|
||||
10.1. New Versions
|
||||
|
||||
Mozilla Foundation is the license steward. Except as provided in Section
|
||||
10.3, no one other than the license steward has the right to modify or
|
||||
publish new versions of this License. Each version will be given a
|
||||
distinguishing version number.
|
||||
|
||||
10.2. Effect of New Versions
|
||||
|
||||
You may distribute the Covered Software under the terms of the version
|
||||
of the License under which You originally received the Covered Software,
|
||||
or under the terms of any subsequent version published by the license
|
||||
steward.
|
||||
|
||||
10.3. Modified Versions
|
||||
|
||||
If you create software not governed by this License, and you want to
|
||||
create a new license for such software, you may create and use a
|
||||
modified version of this License if you rename the license and remove
|
||||
any references to the name of the license steward (except to note that
|
||||
such modified license differs from this License).
|
||||
|
||||
10.4. Distributing Source Code Form that is Incompatible With Secondary
|
||||
Licenses
|
||||
|
||||
If You choose to distribute Source Code Form that is Incompatible With
|
||||
Secondary Licenses under the terms of this version of the License, the
|
||||
notice described in Exhibit B of this License must be attached.
|
||||
|
||||
Exhibit A - Source Code Form License Notice
|
||||
-------------------------------------------
|
||||
|
||||
This Source Code Form is subject to the terms of the Mozilla Public
|
||||
License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||
|
||||
If it is not possible or desirable to put the notice in a particular
|
||||
file, then You may include the notice in a location (such as a LICENSE
|
||||
file in a relevant directory) where a recipient would be likely to look
|
||||
for such a notice.
|
||||
|
||||
You may add additional accurate notices of copyright ownership.
|
||||
|
||||
Exhibit B - "Incompatible With Secondary Licenses" Notice
|
||||
---------------------------------------------------------
|
||||
|
||||
This Source Code Form is "Incompatible With Secondary Licenses", as
|
||||
defined by the Mozilla Public License, v. 2.0.
|
||||
@@ -0,0 +1,140 @@
|
||||
# @mediabunny/flac-encoder
|
||||
|
||||
[](https://www.npmjs.com/package/@mediabunny/flac-encoder)
|
||||
[](https://bundlephobia.com/package/@mediabunny/flac-encoder)
|
||||
[](https://www.npmjs.com/package/@mediabunny/flac-encoder)
|
||||
[](https://discord.gg/hmpkyYuS4U)
|
||||
|
||||
<div align="center">
|
||||
<img src="../../docs/public/mediabunny-logo.svg" width="180" height="180">
|
||||
</div>
|
||||
|
||||
No browser currently supports FLAC encoding in their WebCodecs implementations. This extension package provides a reliable FLAC encoder for use with [Mediabunny](https://github.com/Vanilagy/mediabunny). It is implemented using Mediabunny's [custom coder API](https://mediabunny.dev/guide/supported-formats-and-codecs#custom-coders) and uses a fast, size-optimized WASM build of [libFLAC](https://github.com/xiph/flac) under the hood.
|
||||
|
||||
> This package, like the rest of Mediabunny, is enabled by its [sponsors](https://mediabunny.dev/#sponsors) and their donations. If you've derived value from this package, please consider [leaving a donation](https://github.com/sponsors/Vanilagy)! 💘
|
||||
|
||||
## Installation
|
||||
|
||||
This library peer-depends on Mediabunny. Install both using npm:
|
||||
```bash
|
||||
npm install mediabunny @mediabunny/flac-encoder
|
||||
```
|
||||
|
||||
Alternatively, directly include them using a script tag:
|
||||
```html
|
||||
<script src="mediabunny.js"></script>
|
||||
<script src="mediabunny-flac-encoder.js"></script>
|
||||
```
|
||||
|
||||
This will expose the global objects `Mediabunny` and `MediabunnyFlacEncoder`. Use `mediabunny-flac-encoder.d.ts` to provide types for these globals. You can download the built distribution files from the [releases page](https://github.com/Vanilagy/mediabunny/releases).
|
||||
|
||||
## Usage
|
||||
|
||||
```ts
|
||||
import { registerFlacEncoder } from '@mediabunny/flac-encoder';
|
||||
|
||||
registerFlacEncoder();
|
||||
```
|
||||
That's it - Mediabunny now uses the registered FLAC encoder automatically.
|
||||
|
||||
If you want to be more correct, check for native browser support first:
|
||||
```ts
|
||||
import { canEncodeAudio } from 'mediabunny';
|
||||
import { registerFlacEncoder } from '@mediabunny/flac-encoder';
|
||||
|
||||
if (!(await canEncodeAudio('flac'))) {
|
||||
registerFlacEncoder();
|
||||
}
|
||||
```
|
||||
|
||||
## Example
|
||||
|
||||
Here, we convert an input file to a FLAC file:
|
||||
|
||||
```ts
|
||||
import {
|
||||
Input,
|
||||
ALL_FORMATS,
|
||||
BlobSource,
|
||||
Output,
|
||||
BufferTarget,
|
||||
FlacOutputFormat,
|
||||
canEncodeAudio,
|
||||
Conversion,
|
||||
} from 'mediabunny';
|
||||
import { registerFlacEncoder } from '@mediabunny/flac-encoder';
|
||||
|
||||
if (!(await canEncodeAudio('flac'))) {
|
||||
registerFlacEncoder();
|
||||
}
|
||||
|
||||
const input = new Input({
|
||||
source: new BlobSource(file), // From a file picker, for example
|
||||
formats: ALL_FORMATS,
|
||||
});
|
||||
const output = new Output({
|
||||
format: new FlacOutputFormat(),
|
||||
target: new BufferTarget(),
|
||||
});
|
||||
|
||||
const conversion = await Conversion.init({
|
||||
input,
|
||||
output,
|
||||
});
|
||||
await conversion.execute();
|
||||
|
||||
output.target.buffer; // => ArrayBuffer containing the FLAC file
|
||||
```
|
||||
|
||||
For more ways of using Mediabunny, refer to its [guide](https://mediabunny.dev/guide/introduction).
|
||||
|
||||
## Building and development
|
||||
|
||||
For simplicity, all built WASM artifacts are included in the repo, since these rarely change. However, here are the instructions for building them from scratch:
|
||||
|
||||
[Install Emscripten](https://emscripten.org/docs/getting_started/downloads.html), install CMake, and clone [libFLAC](https://github.com/xiph/flac). Then, from the Mediabunny root and with Emscripten sourced in:
|
||||
|
||||
```bash
|
||||
export FLAC_PATH=/path/to/flac
|
||||
export MEDIABUNNY_ROOT=$PWD
|
||||
|
||||
cd $FLAC_PATH
|
||||
mkdir -p build && cd build
|
||||
emcmake cmake .. \
|
||||
-DBUILD_PROGRAMS=OFF \
|
||||
-DBUILD_CXXLIBS=OFF \
|
||||
-DBUILD_EXAMPLES=OFF \
|
||||
-DBUILD_TESTING=OFF \
|
||||
-DWITH_OGG=OFF \
|
||||
-DBUILD_SHARED_LIBS=OFF \
|
||||
-DENABLE_MULTITHREADING=OFF \
|
||||
-DINSTALL_MANPAGES=OFF \
|
||||
-DCMAKE_C_FLAGS="-DNDEBUG -Oz -flto -msimd128"
|
||||
emmake make
|
||||
|
||||
# Compile the bridge between JavaScript and libFLAC's API
|
||||
cd $MEDIABUNNY_ROOT/packages/flac-encoder
|
||||
emcc src/bridge.c \
|
||||
$FLAC_PATH/build/src/libFLAC/libFLAC.a \
|
||||
-I$FLAC_PATH/include \
|
||||
-s MODULARIZE=1 \
|
||||
-s EXPORT_ES6=1 \
|
||||
-s SINGLE_FILE=1 \
|
||||
-s ALLOW_MEMORY_GROWTH=1 \
|
||||
-s ENVIRONMENT=web,worker \
|
||||
-s FILESYSTEM=0 \
|
||||
-s MALLOC=emmalloc \
|
||||
-s SUPPORT_LONGJMP=0 \
|
||||
-s EXPORTED_RUNTIME_METHODS=cwrap,HEAPU8 \
|
||||
-s EXPORTED_FUNCTIONS=_malloc,_free \
|
||||
-msimd128 \
|
||||
-flto \
|
||||
-Oz \
|
||||
-o build/flac.js
|
||||
```
|
||||
|
||||
This generates `build/flac.js`, which contains both the JavaScript "glue code" as well as the compiled WASM inlined.
|
||||
|
||||
### Building the package
|
||||
|
||||
Then, the complete JavaScript package can be built alongside the rest of Mediabunny by running `npm run build` in Mediabunny's root.
|
||||
@@ -0,0 +1,37 @@
|
||||
{
|
||||
"$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json",
|
||||
"mainEntryPointFilePath": "dist/modules/src/index.d.ts",
|
||||
"bundledPackages": [],
|
||||
"compiler": {},
|
||||
"apiReport": {
|
||||
"enabled": false
|
||||
},
|
||||
"docModel": {
|
||||
"enabled": false
|
||||
},
|
||||
"dtsRollup": {
|
||||
"enabled": true,
|
||||
"untrimmedFilePath": "dist/mediabunny-flac-encoder.d.ts"
|
||||
},
|
||||
"tsdocMetadata": {
|
||||
"enabled": false
|
||||
},
|
||||
"messages": {
|
||||
"compilerMessageReporting": {
|
||||
"default": {
|
||||
"logLevel": "warning"
|
||||
}
|
||||
},
|
||||
"extractorMessageReporting": {
|
||||
"default": {
|
||||
"logLevel": "warning"
|
||||
}
|
||||
},
|
||||
"tsdocMessageReporting": {
|
||||
"default": {
|
||||
"logLevel": "warning"
|
||||
}
|
||||
}
|
||||
},
|
||||
"newlineKind": "lf"
|
||||
}
|
||||
Generated
BIN
Binary file not shown.
@@ -0,0 +1,54 @@
|
||||
{
|
||||
"name": "@mediabunny/flac-encoder",
|
||||
"author": "Vanilagy",
|
||||
"version": "1.37.0",
|
||||
"description": "FLAC encoder extension for Mediabunny, based on libFLAC.",
|
||||
"main": "./dist/bundles/mediabunny-flac-encoder.mjs",
|
||||
"module": "./dist/bundles/mediabunny-flac-encoder.mjs",
|
||||
"types": "./dist/modules/src/index.d.ts",
|
||||
"exports": {
|
||||
"types": "./dist/modules/src/index.d.ts",
|
||||
"import": "./dist/bundles/mediabunny-flac-encoder.mjs",
|
||||
"require": "./dist/bundles/mediabunny-flac-encoder.mjs"
|
||||
},
|
||||
"files": [
|
||||
"README.md",
|
||||
"package.json",
|
||||
"LICENSE",
|
||||
"dist",
|
||||
"src"
|
||||
],
|
||||
"browser": {
|
||||
"worker_threads": false
|
||||
},
|
||||
"sideEffects": false,
|
||||
"license": "MPL-2.0",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/Vanilagy/mediabunny.git",
|
||||
"directory": "packages/flac-encoder"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/Vanilagy/mediabunny/issues"
|
||||
},
|
||||
"homepage": "https://mediabunny.dev/guide/extensions/flac-encoder",
|
||||
"funding": {
|
||||
"type": "individual",
|
||||
"url": "https://github.com/sponsors/Vanilagy"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"mediabunny": "^1.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/emscripten": "^1.40.1"
|
||||
},
|
||||
"keywords": [
|
||||
"flac",
|
||||
"encoding",
|
||||
"codec",
|
||||
"mediabunny",
|
||||
"lossless",
|
||||
"browser",
|
||||
"wasm"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
/*!
|
||||
* Copyright (c) 2026-present, Vanilagy and contributors
|
||||
*
|
||||
* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||
*/
|
||||
|
||||
#include <emscripten.h>
|
||||
#include <FLAC/stream_encoder.h>
|
||||
#include <stdbool.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#define BITS_PER_SAMPLE 16
|
||||
#define COMPRESSION_LEVEL 5
|
||||
|
||||
typedef struct {
|
||||
int size;
|
||||
int samples;
|
||||
} FrameInfo;
|
||||
|
||||
typedef struct {
|
||||
FLAC__StreamEncoder *encoder;
|
||||
|
||||
// Input buffer for interleaved int16 samples from JS
|
||||
int16_t *input_buffer;
|
||||
int input_buffer_size;
|
||||
|
||||
// Widened to int32 for libFLAC
|
||||
FLAC__int32 *int32_buffer;
|
||||
int int32_buffer_size;
|
||||
|
||||
// Contiguous output buffer for encoded frame data
|
||||
uint8_t *output_buffer;
|
||||
int output_size;
|
||||
int output_capacity;
|
||||
|
||||
// Per-frame metadata so JS can split the output buffer into individual packets
|
||||
FrameInfo *frames;
|
||||
int frame_count;
|
||||
int frames_capacity;
|
||||
|
||||
// Stream header captured during init (fLaC + metadata blocks)
|
||||
uint8_t *header_buffer;
|
||||
int header_size;
|
||||
int header_capacity;
|
||||
bool header_done;
|
||||
|
||||
int channels;
|
||||
} EncoderContext;
|
||||
|
||||
static void ensure_output_capacity(EncoderContext *ctx, int needed) {
|
||||
if (needed <= ctx->output_capacity) {
|
||||
return;
|
||||
}
|
||||
|
||||
int new_capacity = ctx->output_capacity;
|
||||
if (new_capacity < 4096) {
|
||||
new_capacity = 4096;
|
||||
}
|
||||
while (new_capacity < needed) {
|
||||
new_capacity *= 2;
|
||||
}
|
||||
|
||||
ctx->output_buffer = realloc(ctx->output_buffer, new_capacity);
|
||||
ctx->output_capacity = new_capacity;
|
||||
}
|
||||
|
||||
static FLAC__StreamEncoderWriteStatus write_callback(
|
||||
const FLAC__StreamEncoder *encoder,
|
||||
const FLAC__byte buffer[],
|
||||
size_t bytes,
|
||||
uint32_t samples,
|
||||
uint32_t current_frame,
|
||||
void *client_data
|
||||
) {
|
||||
EncoderContext *ctx = (EncoderContext *)client_data;
|
||||
|
||||
// samples == 0 means this is metadata (stream header)
|
||||
if (samples == 0) {
|
||||
if (!ctx->header_done) {
|
||||
int needed = ctx->header_size + bytes;
|
||||
if (needed > ctx->header_capacity) {
|
||||
int new_cap = ctx->header_capacity < 256 ? 256 : ctx->header_capacity;
|
||||
while (new_cap < needed) { new_cap *= 2; }
|
||||
ctx->header_buffer = realloc(ctx->header_buffer, new_cap);
|
||||
ctx->header_capacity = new_cap;
|
||||
}
|
||||
memcpy(ctx->header_buffer + ctx->header_size, buffer, bytes);
|
||||
ctx->header_size += bytes;
|
||||
}
|
||||
|
||||
return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
|
||||
}
|
||||
|
||||
ctx->header_done = true;
|
||||
|
||||
// Append encoded data
|
||||
ensure_output_capacity(ctx, ctx->output_size + bytes);
|
||||
memcpy(ctx->output_buffer + ctx->output_size, buffer, bytes);
|
||||
ctx->output_size += bytes;
|
||||
|
||||
// Record frame metadata
|
||||
if (ctx->frame_count >= ctx->frames_capacity) {
|
||||
int new_cap = ctx->frames_capacity < 16 ? 16 : ctx->frames_capacity * 2;
|
||||
ctx->frames = realloc(ctx->frames, new_cap * sizeof(FrameInfo));
|
||||
ctx->frames_capacity = new_cap;
|
||||
}
|
||||
ctx->frames[ctx->frame_count].size = bytes;
|
||||
ctx->frames[ctx->frame_count].samples = samples;
|
||||
ctx->frame_count++;
|
||||
|
||||
return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
|
||||
}
|
||||
|
||||
static void reset_output(EncoderContext *ctx) {
|
||||
ctx->output_size = 0;
|
||||
ctx->frame_count = 0;
|
||||
}
|
||||
|
||||
EMSCRIPTEN_KEEPALIVE
|
||||
int init_encoder(int channels, int sample_rate) {
|
||||
EncoderContext *ctx = calloc(1, sizeof(EncoderContext));
|
||||
if (!ctx) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
ctx->channels = channels;
|
||||
|
||||
ctx->encoder = FLAC__stream_encoder_new();
|
||||
if (!ctx->encoder) {
|
||||
free(ctx);
|
||||
return 0;
|
||||
}
|
||||
|
||||
FLAC__stream_encoder_set_channels(ctx->encoder, channels);
|
||||
FLAC__stream_encoder_set_sample_rate(ctx->encoder, sample_rate);
|
||||
FLAC__stream_encoder_set_bits_per_sample(ctx->encoder, BITS_PER_SAMPLE);
|
||||
FLAC__stream_encoder_set_compression_level(ctx->encoder, COMPRESSION_LEVEL);
|
||||
FLAC__stream_encoder_set_verify(ctx->encoder, false);
|
||||
|
||||
FLAC__StreamEncoderInitStatus status = FLAC__stream_encoder_init_stream(
|
||||
ctx->encoder,
|
||||
write_callback,
|
||||
NULL, // seek callback
|
||||
NULL, // tell callback
|
||||
NULL, // metadata callback
|
||||
ctx
|
||||
);
|
||||
|
||||
if (status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
|
||||
FLAC__stream_encoder_delete(ctx->encoder);
|
||||
free(ctx);
|
||||
return 0;
|
||||
}
|
||||
|
||||
return (int)ctx;
|
||||
}
|
||||
|
||||
EMSCRIPTEN_KEEPALIVE
|
||||
uint8_t *get_encode_input_ptr(int ctx_ptr, int size) {
|
||||
EncoderContext *ctx = (EncoderContext *)ctx_ptr;
|
||||
|
||||
if (size > ctx->input_buffer_size) {
|
||||
ctx->input_buffer = realloc(ctx->input_buffer, size);
|
||||
ctx->input_buffer_size = size;
|
||||
}
|
||||
|
||||
return (uint8_t *)ctx->input_buffer;
|
||||
}
|
||||
|
||||
EMSCRIPTEN_KEEPALIVE
|
||||
int send_samples(int ctx_ptr, int num_samples) {
|
||||
EncoderContext *ctx = (EncoderContext *)ctx_ptr;
|
||||
|
||||
// Widen int16 to int32 for libFLAC
|
||||
int total = num_samples * ctx->channels;
|
||||
if (total > ctx->int32_buffer_size) {
|
||||
ctx->int32_buffer = realloc(ctx->int32_buffer, total * sizeof(FLAC__int32));
|
||||
ctx->int32_buffer_size = total;
|
||||
}
|
||||
for (int i = 0; i < total; i++) {
|
||||
ctx->int32_buffer[i] = ctx->input_buffer[i];
|
||||
}
|
||||
|
||||
reset_output(ctx);
|
||||
|
||||
FLAC__bool ok = FLAC__stream_encoder_process_interleaved(ctx->encoder, ctx->int32_buffer, num_samples);
|
||||
return ok ? 0 : -1;
|
||||
}
|
||||
|
||||
EMSCRIPTEN_KEEPALIVE
|
||||
uint8_t *get_output_data(int ctx_ptr) {
|
||||
EncoderContext *ctx = (EncoderContext *)ctx_ptr;
|
||||
return ctx->output_buffer;
|
||||
}
|
||||
|
||||
EMSCRIPTEN_KEEPALIVE
|
||||
int get_frame_count(int ctx_ptr) {
|
||||
EncoderContext *ctx = (EncoderContext *)ctx_ptr;
|
||||
return ctx->frame_count;
|
||||
}
|
||||
|
||||
EMSCRIPTEN_KEEPALIVE
|
||||
int get_frame_size(int ctx_ptr, int index) {
|
||||
EncoderContext *ctx = (EncoderContext *)ctx_ptr;
|
||||
return ctx->frames[index].size;
|
||||
}
|
||||
|
||||
EMSCRIPTEN_KEEPALIVE
|
||||
int get_frame_samples(int ctx_ptr, int index) {
|
||||
EncoderContext *ctx = (EncoderContext *)ctx_ptr;
|
||||
return ctx->frames[index].samples;
|
||||
}
|
||||
|
||||
EMSCRIPTEN_KEEPALIVE
|
||||
uint8_t *get_header_data(int ctx_ptr) {
|
||||
EncoderContext *ctx = (EncoderContext *)ctx_ptr;
|
||||
return ctx->header_buffer;
|
||||
}
|
||||
|
||||
EMSCRIPTEN_KEEPALIVE
|
||||
int get_header_size(int ctx_ptr) {
|
||||
EncoderContext *ctx = (EncoderContext *)ctx_ptr;
|
||||
return ctx->header_size;
|
||||
}
|
||||
|
||||
EMSCRIPTEN_KEEPALIVE
|
||||
int finish_encoder(int ctx_ptr) {
|
||||
EncoderContext *ctx = (EncoderContext *)ctx_ptr;
|
||||
|
||||
reset_output(ctx);
|
||||
|
||||
FLAC__bool ok = FLAC__stream_encoder_finish(ctx->encoder);
|
||||
if (!ok) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
// finish() leaves the encoder uninitialized but retains configuration (channels, sample rate,
|
||||
// etc.), so we just re-init the stream to be ready for the next batch of samples.
|
||||
ctx->header_size = 0;
|
||||
ctx->header_done = false;
|
||||
|
||||
FLAC__StreamEncoderInitStatus status = FLAC__stream_encoder_init_stream(
|
||||
ctx->encoder,
|
||||
write_callback,
|
||||
NULL,
|
||||
NULL,
|
||||
NULL,
|
||||
ctx
|
||||
);
|
||||
|
||||
return status == FLAC__STREAM_ENCODER_INIT_STATUS_OK ? 0 : -1;
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
/*!
|
||||
* Copyright (c) 2026-present, Vanilagy and contributors
|
||||
*
|
||||
* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||
*/
|
||||
|
||||
import createModule from '../build/flac';
|
||||
import type { PacketInfo, WorkerCommand, WorkerResponse, WorkerResponseData } from './shared';
|
||||
|
||||
type ExtendedEmscriptenModule = EmscriptenModule & {
|
||||
cwrap: typeof cwrap;
|
||||
};
|
||||
|
||||
let module: ExtendedEmscriptenModule;
|
||||
let modulePromise: Promise<ExtendedEmscriptenModule> | null = null;
|
||||
|
||||
let initEncoderFn: (channels: number, sampleRate: number) => number;
|
||||
let getEncodeInputPtr: (ctx: number, size: number) => number;
|
||||
let sendSamplesFn: (ctx: number, numSamples: number) => number;
|
||||
let getOutputData: (ctx: number) => number;
|
||||
let getFrameCount: (ctx: number) => number;
|
||||
let getFrameSize: (ctx: number, index: number) => number;
|
||||
let getFrameSamples: (ctx: number, index: number) => number;
|
||||
let getHeaderData: (ctx: number) => number;
|
||||
let getHeaderSize: (ctx: number) => number;
|
||||
let finishEncoderFn: (ctx: number) => number;
|
||||
|
||||
const ensureModule = async () => {
|
||||
if (!module) {
|
||||
if (modulePromise) {
|
||||
return modulePromise;
|
||||
}
|
||||
|
||||
modulePromise = createModule() as Promise<ExtendedEmscriptenModule>;
|
||||
module = await modulePromise;
|
||||
modulePromise = null;
|
||||
|
||||
initEncoderFn = module.cwrap('init_encoder', 'number', ['number', 'number']);
|
||||
getEncodeInputPtr = module.cwrap('get_encode_input_ptr', 'number', ['number', 'number']);
|
||||
sendSamplesFn = module.cwrap('send_samples', 'number', ['number', 'number']);
|
||||
getOutputData = module.cwrap('get_output_data', 'number', ['number']);
|
||||
getFrameCount = module.cwrap('get_frame_count', 'number', ['number']);
|
||||
getFrameSize = module.cwrap('get_frame_size', 'number', ['number', 'number']);
|
||||
getFrameSamples = module.cwrap('get_frame_samples', 'number', ['number', 'number']);
|
||||
getHeaderData = module.cwrap('get_header_data', 'number', ['number']);
|
||||
getHeaderSize = module.cwrap('get_header_size', 'number', ['number']);
|
||||
finishEncoderFn = module.cwrap('finish_encoder', 'number', ['number']);
|
||||
}
|
||||
};
|
||||
|
||||
const initEncoder = async (numberOfChannels: number, sampleRate: number) => {
|
||||
await ensureModule();
|
||||
|
||||
const ctx = initEncoderFn(numberOfChannels, sampleRate);
|
||||
if (ctx === 0) {
|
||||
throw new Error('Failed to initialize FLAC encoder.');
|
||||
}
|
||||
|
||||
const headerPtr = getHeaderData(ctx);
|
||||
const headerSize = getHeaderSize(ctx);
|
||||
const header = module.HEAPU8.slice(headerPtr, headerPtr + headerSize).buffer;
|
||||
|
||||
return { ctx, header };
|
||||
};
|
||||
|
||||
const readPackets = (ctx: number) => {
|
||||
const packets: PacketInfo[] = [];
|
||||
const frameCount = getFrameCount(ctx);
|
||||
const outputPtr = getOutputData(ctx);
|
||||
|
||||
let offset = 0;
|
||||
for (let i = 0; i < frameCount; i++) {
|
||||
const size = getFrameSize(ctx, i);
|
||||
const samples = getFrameSamples(ctx, i);
|
||||
const encodedData = module.HEAPU8.slice(outputPtr + offset, outputPtr + offset + size).buffer;
|
||||
packets.push({ encodedData, samples });
|
||||
offset += size;
|
||||
}
|
||||
|
||||
return packets;
|
||||
};
|
||||
|
||||
const encode = (ctx: number, audioData: ArrayBuffer, numSamples: number) => {
|
||||
const audioBytes = new Uint8Array(audioData);
|
||||
|
||||
const inputPtr = getEncodeInputPtr(ctx, audioBytes.length);
|
||||
if (inputPtr === 0) {
|
||||
throw new Error('Failed to allocate encoder input buffer.');
|
||||
}
|
||||
module.HEAPU8.set(audioBytes, inputPtr);
|
||||
|
||||
const ret = sendSamplesFn(ctx, numSamples);
|
||||
if (ret < 0) {
|
||||
throw new Error(`Encode failed with error code ${ret}.`);
|
||||
}
|
||||
|
||||
return readPackets(ctx);
|
||||
};
|
||||
|
||||
const flush = (ctx: number) => {
|
||||
const ret = finishEncoderFn(ctx);
|
||||
if (ret < 0) {
|
||||
throw new Error('Flush failed.');
|
||||
}
|
||||
|
||||
return readPackets(ctx);
|
||||
};
|
||||
|
||||
const onMessage = (data: { id: number; command: WorkerCommand }) => {
|
||||
const { id, command } = data;
|
||||
|
||||
const handleCommand = async (): Promise<void> => {
|
||||
try {
|
||||
let result: WorkerResponseData;
|
||||
const transferables: Transferable[] = [];
|
||||
|
||||
switch (command.type) {
|
||||
case 'init': {
|
||||
const { ctx, header } = await initEncoder(
|
||||
command.data.numberOfChannels,
|
||||
command.data.sampleRate,
|
||||
);
|
||||
result = { type: command.type, ctx, header };
|
||||
transferables.push(header);
|
||||
}; break;
|
||||
|
||||
case 'encode': {
|
||||
const packets = encode(
|
||||
command.data.ctx,
|
||||
command.data.audioData,
|
||||
command.data.numSamples,
|
||||
);
|
||||
for (const p of packets) {
|
||||
transferables.push(p.encodedData);
|
||||
}
|
||||
result = { type: command.type, packets };
|
||||
}; break;
|
||||
|
||||
case 'flush': {
|
||||
const packets = flush(command.data.ctx);
|
||||
for (const p of packets) {
|
||||
transferables.push(p.encodedData);
|
||||
}
|
||||
result = { type: command.type, packets };
|
||||
}; break;
|
||||
}
|
||||
|
||||
const response: WorkerResponse = {
|
||||
id,
|
||||
success: true,
|
||||
data: result,
|
||||
};
|
||||
sendMessage(response, transferables);
|
||||
} catch (error: unknown) {
|
||||
const response: WorkerResponse = {
|
||||
id,
|
||||
success: false,
|
||||
error,
|
||||
};
|
||||
sendMessage(response);
|
||||
}
|
||||
};
|
||||
|
||||
void handleCommand();
|
||||
};
|
||||
|
||||
const sendMessage = (data: unknown, transferables?: Transferable[]) => {
|
||||
if (parentPort) {
|
||||
parentPort.postMessage(data, transferables ?? []);
|
||||
} else {
|
||||
self.postMessage(data, { transfer: transferables ?? [] });
|
||||
}
|
||||
};
|
||||
|
||||
let parentPort: {
|
||||
postMessage: (data: unknown, transferables?: Transferable[]) => void;
|
||||
on: (event: string, listener: (data: never) => void) => void;
|
||||
} | null = null;
|
||||
|
||||
if (typeof self === 'undefined') {
|
||||
const workerModule = 'worker_threads';
|
||||
// eslint-disable-next-line @stylistic/max-len
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-require-imports, @typescript-eslint/no-unsafe-member-access
|
||||
parentPort = require(workerModule).parentPort;
|
||||
}
|
||||
|
||||
if (parentPort) {
|
||||
parentPort.on('message', onMessage);
|
||||
} else {
|
||||
self.addEventListener('message', event => onMessage(event.data as { id: number; command: WorkerCommand }));
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
/*!
|
||||
* Copyright (c) 2026-present, Vanilagy and contributors
|
||||
*
|
||||
* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||
*/
|
||||
|
||||
import {
|
||||
CustomAudioEncoder,
|
||||
AudioCodec,
|
||||
AudioSample,
|
||||
EncodedPacket,
|
||||
registerEncoder,
|
||||
} from 'mediabunny';
|
||||
import type { PacketInfo, WorkerCommand, WorkerResponse, WorkerResponseData } from './shared';
|
||||
// @ts-expect-error An esbuild plugin handles this, TypeScript doesn't need to understand
|
||||
import createWorker from './encode.worker';
|
||||
|
||||
const FLAC_SAMPLE_RATES = [
|
||||
8000, 16000, 22050, 24000, 32000, 44100, 48000, 88200, 96000, 176400, 192000,
|
||||
];
|
||||
|
||||
class FlacEncoder extends CustomAudioEncoder {
|
||||
private worker: Worker | null = null;
|
||||
private nextMessageId = 0;
|
||||
private pendingMessages = new Map<number, {
|
||||
resolve: (value: WorkerResponseData) => void;
|
||||
reject: (reason?: unknown) => void;
|
||||
}>();
|
||||
|
||||
private ctx = 0;
|
||||
private chunkMetadata: EncodedAudioChunkMetadata = {};
|
||||
private description: Uint8Array | null = null;
|
||||
private nextTimestampInSamples: number | null = null;
|
||||
|
||||
static override supports(codec: AudioCodec, config: AudioEncoderConfig): boolean {
|
||||
return codec === 'flac'
|
||||
&& config.numberOfChannels >= 1
|
||||
&& config.numberOfChannels <= 8
|
||||
&& FLAC_SAMPLE_RATES.includes(config.sampleRate);
|
||||
}
|
||||
|
||||
async init() {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-call
|
||||
this.worker = (await createWorker()) as Worker;
|
||||
|
||||
const onMessage = (data: WorkerResponse) => {
|
||||
const pending = this.pendingMessages.get(data.id);
|
||||
assert(pending !== undefined);
|
||||
|
||||
this.pendingMessages.delete(data.id);
|
||||
if (data.success) {
|
||||
pending.resolve(data.data);
|
||||
} else {
|
||||
pending.reject(data.error);
|
||||
}
|
||||
};
|
||||
|
||||
if (this.worker.addEventListener) {
|
||||
this.worker.addEventListener('message', event => onMessage(event.data as WorkerResponse));
|
||||
} else {
|
||||
const nodeWorker = this.worker as unknown as {
|
||||
on: (event: string, listener: (data: never) => void) => void;
|
||||
};
|
||||
nodeWorker.on('message', onMessage);
|
||||
}
|
||||
|
||||
const result = await this.sendCommand({
|
||||
type: 'init',
|
||||
data: {
|
||||
numberOfChannels: this.config.numberOfChannels,
|
||||
sampleRate: this.config.sampleRate,
|
||||
},
|
||||
});
|
||||
|
||||
this.ctx = result.ctx;
|
||||
|
||||
this.description = new Uint8Array(result.header);
|
||||
this.resetInternalState();
|
||||
}
|
||||
|
||||
private resetInternalState() {
|
||||
this.nextTimestampInSamples = null;
|
||||
|
||||
this.chunkMetadata = {
|
||||
decoderConfig: {
|
||||
codec: 'flac',
|
||||
numberOfChannels: this.config.numberOfChannels,
|
||||
sampleRate: this.config.sampleRate,
|
||||
description: this.description!,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async encode(audioSample: AudioSample) {
|
||||
if (this.nextTimestampInSamples === null) {
|
||||
this.nextTimestampInSamples = Math.round(audioSample.timestamp * this.config.sampleRate);
|
||||
}
|
||||
|
||||
const totalBytes = audioSample.allocationSize({ format: 's16', planeIndex: 0 });
|
||||
const audioBytes = new Uint8Array(totalBytes);
|
||||
audioSample.copyTo(audioBytes, { format: 's16', planeIndex: 0 });
|
||||
|
||||
const audioData = audioBytes.buffer;
|
||||
const result = await this.sendCommand({
|
||||
type: 'encode',
|
||||
data: {
|
||||
ctx: this.ctx,
|
||||
audioData,
|
||||
numSamples: audioSample.numberOfFrames,
|
||||
},
|
||||
}, [audioData]);
|
||||
|
||||
this.emitPackets(result.packets);
|
||||
}
|
||||
|
||||
async flush() {
|
||||
const result = await this.sendCommand({ type: 'flush', data: { ctx: this.ctx } });
|
||||
this.emitPackets(result.packets);
|
||||
|
||||
this.resetInternalState();
|
||||
}
|
||||
|
||||
close() {
|
||||
this.worker?.terminate();
|
||||
}
|
||||
|
||||
private emitPackets(packets: PacketInfo[]) {
|
||||
assert(this.nextTimestampInSamples !== null);
|
||||
|
||||
for (const p of packets) {
|
||||
const data = new Uint8Array(p.encodedData);
|
||||
|
||||
const packet = new EncodedPacket(
|
||||
data,
|
||||
'key',
|
||||
this.nextTimestampInSamples / this.config.sampleRate,
|
||||
p.samples / this.config.sampleRate,
|
||||
);
|
||||
this.nextTimestampInSamples += p.samples;
|
||||
|
||||
this.onPacket(
|
||||
packet,
|
||||
this.chunkMetadata,
|
||||
);
|
||||
|
||||
this.chunkMetadata = {};
|
||||
}
|
||||
}
|
||||
|
||||
private sendCommand<T extends string>(
|
||||
command: WorkerCommand & { type: T },
|
||||
transferables?: Transferable[],
|
||||
) {
|
||||
return new Promise<WorkerResponseData & { type: T }>((resolve, reject) => {
|
||||
const id = this.nextMessageId++;
|
||||
this.pendingMessages.set(id, {
|
||||
resolve: resolve as (value: WorkerResponseData) => void,
|
||||
reject,
|
||||
});
|
||||
|
||||
assert(this.worker);
|
||||
|
||||
if (transferables) {
|
||||
this.worker.postMessage({ id, command }, transferables);
|
||||
} else {
|
||||
this.worker.postMessage({ id, command });
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers the FLAC encoder, which Mediabunny will then use automatically when applicable. Make sure to call this
|
||||
* function before starting any encoding task.
|
||||
*
|
||||
* Preferably, wrap the call in a condition to avoid overriding any native FLAC encoder:
|
||||
*
|
||||
* ```ts
|
||||
* import { canEncodeAudio } from 'mediabunny';
|
||||
* import { registerFlacEncoder } from '@mediabunny/flac-encoder';
|
||||
*
|
||||
* if (!(await canEncodeAudio('flac'))) {
|
||||
* registerFlacEncoder();
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @group \@mediabunny/flac-encoder
|
||||
* @public
|
||||
*/
|
||||
export const registerFlacEncoder = () => {
|
||||
registerEncoder(FlacEncoder);
|
||||
};
|
||||
|
||||
function assert(x: unknown): asserts x {
|
||||
if (!x) {
|
||||
throw new Error('Assertion failed.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
/*!
|
||||
* Copyright (c) 2026-present, Vanilagy and contributors
|
||||
*
|
||||
* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||
*/
|
||||
|
||||
const FLAC_ENCODER_LOADED_SYMBOL = Symbol.for('@mediabunny/flac-encoder loaded');
|
||||
if ((globalThis as Record<symbol, unknown>)[FLAC_ENCODER_LOADED_SYMBOL]) {
|
||||
console.error(
|
||||
'[WARNING]\n@mediabunny/flac-encoder was loaded twice.'
|
||||
+ ' This will likely cause the encoder not to work correctly.'
|
||||
+ ' Check if multiple dependencies are importing different versions of @mediabunny/flac-encoder,'
|
||||
+ ' or if something is being bundled incorrectly.',
|
||||
);
|
||||
}
|
||||
(globalThis as Record<symbol, unknown>)[FLAC_ENCODER_LOADED_SYMBOL] = true;
|
||||
|
||||
export { registerFlacEncoder } from './encoder';
|
||||
@@ -0,0 +1,54 @@
|
||||
/*!
|
||||
* Copyright (c) 2026-present, Vanilagy and contributors
|
||||
*
|
||||
* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||
*/
|
||||
|
||||
export type PacketInfo = {
|
||||
encodedData: ArrayBuffer;
|
||||
samples: number;
|
||||
};
|
||||
|
||||
export type WorkerCommand = {
|
||||
type: 'init';
|
||||
data: {
|
||||
numberOfChannels: number;
|
||||
sampleRate: number;
|
||||
};
|
||||
} | {
|
||||
type: 'encode';
|
||||
data: {
|
||||
ctx: number;
|
||||
audioData: ArrayBuffer;
|
||||
numSamples: number;
|
||||
};
|
||||
} | {
|
||||
type: 'flush';
|
||||
data: {
|
||||
ctx: number;
|
||||
};
|
||||
};
|
||||
|
||||
export type WorkerResponseData = {
|
||||
type: 'init';
|
||||
ctx: number;
|
||||
header: ArrayBuffer;
|
||||
} | {
|
||||
type: 'encode';
|
||||
packets: PacketInfo[];
|
||||
} | {
|
||||
type: 'flush';
|
||||
packets: PacketInfo[];
|
||||
};
|
||||
|
||||
export type WorkerResponse = {
|
||||
id: number;
|
||||
} & ({
|
||||
success: true;
|
||||
data: WorkerResponseData;
|
||||
} | {
|
||||
success: false;
|
||||
error: unknown;
|
||||
});
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"extends": "../../tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"composite": true,
|
||||
"outDir": "./dist/modules",
|
||||
"declaration": true,
|
||||
"declarationMap": true,
|
||||
"stripInternal": true,
|
||||
"noEmit": false,
|
||||
"moduleResolution": "nodenext",
|
||||
"module": "nodenext",
|
||||
"allowJs": true,
|
||||
"paths": {
|
||||
"mediabunny": ["../../src/index.ts"],
|
||||
},
|
||||
},
|
||||
"include": [
|
||||
"./src/**/*",
|
||||
"./build/**/*",
|
||||
],
|
||||
"references": [
|
||||
{ "path": "../../src" }
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"$schema": "https://developer.microsoft.com/json-schemas/tsdoc/v0/tsdoc.schema.json",
|
||||
"extends": ["../../tsdoc.json"]
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@mediabunny/mp3-encoder",
|
||||
"author": "Vanilagy",
|
||||
"version": "1.35.1",
|
||||
"version": "1.37.0",
|
||||
"description": "MP3 encoder extension for Mediabunny, based on LAME.",
|
||||
"main": "./dist/bundles/mediabunny-mp3-encoder.mjs",
|
||||
"module": "./dist/bundles/mediabunny-mp3-encoder.mjs",
|
||||
|
||||
@@ -17,7 +17,6 @@
|
||||
"include": [
|
||||
"./src/**/*",
|
||||
"./build/**/*",
|
||||
"../../shared/**/*",
|
||||
],
|
||||
"references": [
|
||||
{ "path": "../../src" }
|
||||
|
||||
+12
-1
@@ -7,6 +7,8 @@ set -e
|
||||
rm -rf dist
|
||||
rm -rf packages/mp3-encoder/dist
|
||||
rm -rf packages/ac3/dist
|
||||
rm -rf packages/aac-encoder/dist
|
||||
rm -rf packages/flac-encoder/dist
|
||||
|
||||
# Ensure license headers on all source files
|
||||
tsx scripts/ensure-license-headers.ts
|
||||
@@ -15,6 +17,8 @@ tsx scripts/ensure-license-headers.ts
|
||||
tsc -p src
|
||||
tsc -p packages/mp3-encoder
|
||||
tsc -p packages/ac3
|
||||
tsc -p packages/aac-encoder
|
||||
tsc -p packages/flac-encoder
|
||||
|
||||
# So that the resulting files use valid ESM imports with file extension. This only runs for the core Mediabunny as only
|
||||
# it ships the individual files to npm (for tree shaking, because it's large)
|
||||
@@ -27,11 +31,15 @@ tsx scripts/bundle.ts
|
||||
api-extractor run
|
||||
api-extractor run -c packages/mp3-encoder/api-extractor.json
|
||||
api-extractor run -c packages/ac3/api-extractor.json
|
||||
api-extractor run -c packages/aac-encoder/api-extractor.json
|
||||
api-extractor run -c packages/flac-encoder/api-extractor.json
|
||||
|
||||
# Checks that all symbols are documented
|
||||
tsx scripts/check-docblocks.ts dist/mediabunny.d.ts
|
||||
tsx scripts/check-docblocks.ts packages/mp3-encoder/dist/mediabunny-mp3-encoder.d.ts
|
||||
tsx scripts/check-docblocks.ts packages/ac3/dist/mediabunny-ac3.d.ts
|
||||
tsx scripts/check-docblocks.ts packages/aac-encoder/dist/mediabunny-aac-encoder.d.ts
|
||||
tsx scripts/check-docblocks.ts packages/flac-encoder/dist/mediabunny-flac-encoder.d.ts
|
||||
|
||||
# Checks that API docs are generatable
|
||||
npm run docs:generate -- --dry
|
||||
@@ -39,4 +47,7 @@ npm run docs:generate -- --dry
|
||||
# Appends stuff to the declaration files to register the global variables these libraries expose
|
||||
echo 'export as namespace Mediabunny;' >> dist/mediabunny.d.ts
|
||||
echo 'export as namespace MediabunnyMp3Encoder;' >> packages/mp3-encoder/dist/mediabunny-mp3-encoder.d.ts
|
||||
echo 'export as namespace MediabunnyAc3;' >> packages/ac3/dist/mediabunny-ac3.d.ts
|
||||
echo 'export as namespace MediabunnyAc3;' >> packages/ac3/dist/mediabunny-ac3.d.ts
|
||||
echo 'export as namespace MediabunnyAacEncoder;' >> packages/aac-encoder/dist/mediabunny-aac-encoder.d.ts
|
||||
echo 'export as namespace MediabunnyFlacEncoder;' >> packages/flac-encoder/dist/mediabunny-flac-encoder.d.ts
|
||||
|
||||
|
||||
@@ -144,10 +144,74 @@ const ac3Variants = await createVariants(
|
||||
},
|
||||
);
|
||||
|
||||
const aacEncoderVariants = await createVariants(
|
||||
'packages/aac-encoder/src/index.ts',
|
||||
'MediabunnyAacEncoder',
|
||||
'packages/aac-encoder/dist/bundles/mediabunny-aac-encoder',
|
||||
'js', // The bundles are purely for the browser, not for Node (due to the peer dependecy)
|
||||
{
|
||||
plugins: [
|
||||
PluginExternalGlobal.externalGlobalPlugin({
|
||||
mediabunny: 'Mediabunny',
|
||||
}),
|
||||
inlineWorkerPlugin({
|
||||
define: {
|
||||
'import.meta.url': '""',
|
||||
},
|
||||
legalComments: 'none',
|
||||
}),
|
||||
],
|
||||
},
|
||||
{
|
||||
external: ['mediabunny'],
|
||||
plugins: [
|
||||
inlineWorkerPlugin({
|
||||
define: {
|
||||
'import.meta.url': '""',
|
||||
},
|
||||
legalComments: 'none',
|
||||
}),
|
||||
],
|
||||
},
|
||||
);
|
||||
|
||||
const flacEncoderVariants = await createVariants(
|
||||
'packages/flac-encoder/src/index.ts',
|
||||
'MediabunnyFlacEncoder',
|
||||
'packages/flac-encoder/dist/bundles/mediabunny-flac-encoder',
|
||||
'js', // The bundles are purely for the browser, not for Node (due to the peer dependecy)
|
||||
{
|
||||
plugins: [
|
||||
PluginExternalGlobal.externalGlobalPlugin({
|
||||
mediabunny: 'Mediabunny',
|
||||
}),
|
||||
inlineWorkerPlugin({
|
||||
define: {
|
||||
'import.meta.url': '""',
|
||||
},
|
||||
legalComments: 'none',
|
||||
}),
|
||||
],
|
||||
},
|
||||
{
|
||||
external: ['mediabunny'],
|
||||
plugins: [
|
||||
inlineWorkerPlugin({
|
||||
define: {
|
||||
'import.meta.url': '""',
|
||||
},
|
||||
legalComments: 'none',
|
||||
}),
|
||||
],
|
||||
},
|
||||
);
|
||||
|
||||
const contexts = [
|
||||
...mediabunnyVariants,
|
||||
...mp3EncoderVariants,
|
||||
...ac3Variants,
|
||||
...aacEncoderVariants,
|
||||
...flacEncoderVariants,
|
||||
];
|
||||
|
||||
if (process.argv[2] === '--watch') {
|
||||
|
||||
+8
-1
@@ -4,11 +4,18 @@ set -e
|
||||
rm -rf dist/modules
|
||||
tsc -p src --stripInternal false
|
||||
|
||||
tsc -p packages/mp3-encoder --noEmit
|
||||
rm -rf packages/mp3-encoder/dist/modules
|
||||
tsc -p packages/mp3-encoder
|
||||
|
||||
rm -rf packages/ac3/dist/modules
|
||||
tsc -p packages/ac3
|
||||
|
||||
rm -rf packages/aac-encoder/dist/modules
|
||||
tsc -p packages/aac-encoder
|
||||
|
||||
rm -rf packages/flac-encoder/dist/modules
|
||||
tsc -p packages/flac-encoder
|
||||
|
||||
tsc -p tsconfig.vitest.json --noEmit
|
||||
|
||||
tsc -p scripts --noEmit
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
/*!
|
||||
* Copyright (c) 2026-present, Vanilagy and contributors
|
||||
*
|
||||
* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||
*/
|
||||
|
||||
import { Bitstream } from './bitstream';
|
||||
|
||||
export type AacAudioSpecificConfig = {
|
||||
objectType: number;
|
||||
frequencyIndex: number;
|
||||
sampleRate: number | null;
|
||||
channelConfiguration: number;
|
||||
numberOfChannels: number | null;
|
||||
};
|
||||
|
||||
export const aacFrequencyTable = [
|
||||
96000, 88200, 64000, 48000, 44100, 32000,
|
||||
24000, 22050, 16000, 12000, 11025, 8000, 7350,
|
||||
];
|
||||
|
||||
export const aacChannelMap = [-1, 1, 2, 3, 4, 5, 6, 8];
|
||||
|
||||
export const parseAacAudioSpecificConfig = (bytes: Uint8Array | null): AacAudioSpecificConfig => {
|
||||
if (!bytes || bytes.byteLength < 2) {
|
||||
throw new TypeError('AAC description must be at least 2 bytes long.');
|
||||
}
|
||||
|
||||
const bitstream = new Bitstream(bytes);
|
||||
|
||||
let objectType = bitstream.readBits(5);
|
||||
if (objectType === 31) {
|
||||
objectType = 32 + bitstream.readBits(6);
|
||||
}
|
||||
|
||||
const frequencyIndex = bitstream.readBits(4);
|
||||
let sampleRate: number | null = null;
|
||||
if (frequencyIndex === 15) {
|
||||
sampleRate = bitstream.readBits(24);
|
||||
} else {
|
||||
if (frequencyIndex < aacFrequencyTable.length) {
|
||||
sampleRate = aacFrequencyTable[frequencyIndex]!;
|
||||
}
|
||||
}
|
||||
|
||||
const channelConfiguration = bitstream.readBits(4);
|
||||
let numberOfChannels: number | null = null;
|
||||
if (channelConfiguration >= 1 && channelConfiguration <= 7) {
|
||||
numberOfChannels = aacChannelMap[channelConfiguration]!;
|
||||
}
|
||||
|
||||
return {
|
||||
objectType,
|
||||
frequencyIndex,
|
||||
sampleRate,
|
||||
channelConfiguration,
|
||||
numberOfChannels,
|
||||
};
|
||||
};
|
||||
|
||||
export const buildAacAudioSpecificConfig = (config: {
|
||||
objectType: number;
|
||||
sampleRate: number;
|
||||
numberOfChannels: number;
|
||||
}) => {
|
||||
let frequencyIndex = aacFrequencyTable.indexOf(config.sampleRate);
|
||||
let customSampleRate: number | null = null;
|
||||
|
||||
if (frequencyIndex === -1) {
|
||||
frequencyIndex = 15;
|
||||
customSampleRate = config.sampleRate;
|
||||
}
|
||||
|
||||
const channelConfiguration = aacChannelMap.indexOf(config.numberOfChannels);
|
||||
if (channelConfiguration === -1) {
|
||||
throw new TypeError(`Unsupported number of channels: ${config.numberOfChannels}`);
|
||||
}
|
||||
|
||||
let bitCount = 5 + 4 + 4;
|
||||
if (config.objectType >= 32) {
|
||||
bitCount += 6;
|
||||
}
|
||||
if (frequencyIndex === 15) {
|
||||
bitCount += 24;
|
||||
}
|
||||
|
||||
const byteCount = Math.ceil(bitCount / 8);
|
||||
const bytes = new Uint8Array(byteCount);
|
||||
const bitstream = new Bitstream(bytes);
|
||||
|
||||
if (config.objectType < 32) {
|
||||
bitstream.writeBits(5, config.objectType);
|
||||
} else {
|
||||
bitstream.writeBits(5, 31);
|
||||
bitstream.writeBits(6, config.objectType - 32);
|
||||
}
|
||||
|
||||
bitstream.writeBits(4, frequencyIndex);
|
||||
|
||||
if (frequencyIndex === 15) {
|
||||
bitstream.writeBits(24, customSampleRate!);
|
||||
}
|
||||
|
||||
bitstream.writeBits(4, channelConfiguration);
|
||||
|
||||
return bytes;
|
||||
};
|
||||
|
||||
export type AdtsHeaderTemplate = {
|
||||
header: Uint8Array;
|
||||
bitstream: Bitstream;
|
||||
};
|
||||
|
||||
export const buildAdtsHeaderTemplate = (config: AacAudioSpecificConfig): AdtsHeaderTemplate => {
|
||||
const header = new Uint8Array(7);
|
||||
const bitstream = new Bitstream(header);
|
||||
|
||||
const { objectType, frequencyIndex, channelConfiguration } = config;
|
||||
const profile = objectType - 1;
|
||||
|
||||
bitstream.writeBits(12, 0b1111_11111111); // Syncword
|
||||
bitstream.writeBits(1, 0); // MPEG Version
|
||||
bitstream.writeBits(2, 0); // Layer
|
||||
bitstream.writeBits(1, 1); // Protection absence
|
||||
bitstream.writeBits(2, profile); // Profile
|
||||
bitstream.writeBits(4, frequencyIndex); // MPEG-4 Sampling Frequency Index
|
||||
bitstream.writeBits(1, 0); // Private bit
|
||||
bitstream.writeBits(3, channelConfiguration); // MPEG-4 Channel Configuration
|
||||
bitstream.writeBits(1, 0); // Originality
|
||||
bitstream.writeBits(1, 0); // Home
|
||||
bitstream.writeBits(1, 0); // Copyright ID bit
|
||||
bitstream.writeBits(1, 0); // Copyright ID start
|
||||
bitstream.skipBits(13); // Frame length (to be filled per packet)
|
||||
bitstream.writeBits(11, 0x7ff); // Buffer fullness
|
||||
bitstream.writeBits(2, 0); // Number of AAC frames minus 1
|
||||
// Omit CRC check
|
||||
|
||||
return { header, bitstream };
|
||||
};
|
||||
|
||||
export const writeAdtsFrameLength = (bitstream: Bitstream, frameLength: number) => {
|
||||
bitstream.pos = 30;
|
||||
bitstream.writeBits(13, frameLength);
|
||||
};
|
||||
@@ -0,0 +1,85 @@
|
||||
/*!
|
||||
* Copyright (c) 2026-present, Vanilagy and contributors
|
||||
*
|
||||
* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||
*/
|
||||
|
||||
export class Bitstream {
|
||||
/** Current offset in bits. */
|
||||
pos = 0;
|
||||
|
||||
constructor(public bytes: Uint8Array) {}
|
||||
|
||||
seekToByte(byteOffset: number) {
|
||||
this.pos = 8 * byteOffset;
|
||||
}
|
||||
|
||||
private readBit() {
|
||||
const byteIndex = Math.floor(this.pos / 8);
|
||||
const byte = this.bytes[byteIndex] ?? 0;
|
||||
const bitIndex = 0b111 - (this.pos & 0b111);
|
||||
const bit = (byte & (1 << bitIndex)) >> bitIndex;
|
||||
|
||||
this.pos++;
|
||||
return bit;
|
||||
}
|
||||
|
||||
readBits(n: number) {
|
||||
if (n === 1) {
|
||||
return this.readBit();
|
||||
}
|
||||
|
||||
let result = 0;
|
||||
|
||||
for (let i = 0; i < n; i++) {
|
||||
result <<= 1;
|
||||
result |= this.readBit();
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
writeBits(n: number, value: number) {
|
||||
const end = this.pos + n;
|
||||
|
||||
for (let i = this.pos; i < end; i++) {
|
||||
const byteIndex = Math.floor(i / 8);
|
||||
let byte = this.bytes[byteIndex]!;
|
||||
const bitIndex = 0b111 - (i & 0b111);
|
||||
|
||||
byte &= ~(1 << bitIndex);
|
||||
byte |= ((value & (1 << (end - i - 1))) >> (end - i - 1)) << bitIndex;
|
||||
this.bytes[byteIndex] = byte;
|
||||
}
|
||||
|
||||
this.pos = end;
|
||||
};
|
||||
|
||||
readAlignedByte() {
|
||||
if (this.pos % 8 !== 0) {
|
||||
throw new Error('Bitstream is not byte-aligned.');
|
||||
}
|
||||
|
||||
const byteIndex = this.pos / 8;
|
||||
const byte = this.bytes[byteIndex] ?? 0;
|
||||
|
||||
this.pos += 8;
|
||||
return byte;
|
||||
}
|
||||
|
||||
skipBits(n: number) {
|
||||
this.pos += n;
|
||||
}
|
||||
|
||||
getBitsLeft() {
|
||||
return this.bytes.length * 8 - this.pos;
|
||||
}
|
||||
|
||||
clone() {
|
||||
const clone = new Bitstream(this.bytes);
|
||||
clone.pos = this.pos;
|
||||
return clone;
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,8 @@
|
||||
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||
*/
|
||||
|
||||
import { aacChannelMap, aacFrequencyTable, AudioCodec } from '../codec';
|
||||
import { aacChannelMap, aacFrequencyTable } from '../../shared/aac-misc';
|
||||
import { AudioCodec } from '../codec';
|
||||
import { Demuxer } from '../demuxer';
|
||||
import {
|
||||
ID3_V2_HEADER_SIZE,
|
||||
|
||||
@@ -1,47 +0,0 @@
|
||||
/*!
|
||||
* Copyright (c) 2026-present, Vanilagy and contributors
|
||||
*
|
||||
* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||
*/
|
||||
|
||||
import { AacAudioSpecificConfig } from '../codec';
|
||||
import { Bitstream } from '../misc';
|
||||
|
||||
export type AdtsHeaderTemplate = {
|
||||
header: Uint8Array;
|
||||
bitstream: Bitstream;
|
||||
};
|
||||
|
||||
export const buildAdtsHeaderTemplate = (config: AacAudioSpecificConfig): AdtsHeaderTemplate => {
|
||||
const header = new Uint8Array(7);
|
||||
const bitstream = new Bitstream(header);
|
||||
|
||||
const { objectType, frequencyIndex, channelConfiguration } = config;
|
||||
const profile = objectType - 1;
|
||||
|
||||
bitstream.writeBits(12, 0b1111_11111111); // Syncword
|
||||
bitstream.writeBits(1, 0); // MPEG Version
|
||||
bitstream.writeBits(2, 0); // Layer
|
||||
bitstream.writeBits(1, 1); // Protection absence
|
||||
bitstream.writeBits(2, profile); // Profile
|
||||
bitstream.writeBits(4, frequencyIndex); // MPEG-4 Sampling Frequency Index
|
||||
bitstream.writeBits(1, 0); // Private bit
|
||||
bitstream.writeBits(3, channelConfiguration); // MPEG-4 Channel Configuration
|
||||
bitstream.writeBits(1, 0); // Originality
|
||||
bitstream.writeBits(1, 0); // Home
|
||||
bitstream.writeBits(1, 0); // Copyright ID bit
|
||||
bitstream.writeBits(1, 0); // Copyright ID start
|
||||
bitstream.skipBits(13); // Frame length (to be filled per packet)
|
||||
bitstream.writeBits(11, 0x7ff); // Buffer fullness
|
||||
bitstream.writeBits(2, 0); // Number of AAC frames minus 1
|
||||
// Omit CRC check
|
||||
|
||||
return { header, bitstream };
|
||||
};
|
||||
|
||||
export const writeAdtsFrameLength = (bitstream: Bitstream, frameLength: number) => {
|
||||
bitstream.pos = 30;
|
||||
bitstream.writeBits(13, frameLength);
|
||||
};
|
||||
@@ -6,16 +6,17 @@
|
||||
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||
*/
|
||||
|
||||
import { parseAacAudioSpecificConfig, validateAudioChunkMetadata } from '../codec';
|
||||
import { buildAdtsHeaderTemplate, parseAacAudioSpecificConfig, writeAdtsFrameLength } from '../../shared/aac-misc';
|
||||
import { Bitstream } from '../../shared/bitstream';
|
||||
import { validateAudioChunkMetadata } from '../codec';
|
||||
import { Id3V2Writer } from '../id3';
|
||||
import { metadataTagsAreEmpty } from '../metadata';
|
||||
import { assert, Bitstream, toUint8Array } from '../misc';
|
||||
import { assert, toUint8Array } from '../misc';
|
||||
import { Muxer } from '../muxer';
|
||||
import { Output, OutputAudioTrack } from '../output';
|
||||
import { AdtsOutputFormat } from '../output-format';
|
||||
import { EncodedPacket } from '../packet';
|
||||
import { Writer } from '../writer';
|
||||
import { buildAdtsHeaderTemplate, writeAdtsFrameLength } from './adts-misc';
|
||||
|
||||
export class AdtsMuxer extends Muxer {
|
||||
private format: AdtsOutputFormat;
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||
*/
|
||||
|
||||
import { Bitstream } from '../misc';
|
||||
import { Bitstream } from '../../shared/bitstream';
|
||||
import { FileSlice, readBytes } from '../reader';
|
||||
|
||||
export const MIN_ADTS_FRAME_HEADER_SIZE = 7;
|
||||
|
||||
+1
-1
@@ -11,7 +11,6 @@ import {
|
||||
assert,
|
||||
assertNever,
|
||||
base64ToBytes,
|
||||
Bitstream,
|
||||
bytesToBase64,
|
||||
keyValueIterator,
|
||||
getUint24,
|
||||
@@ -30,6 +29,7 @@ import {
|
||||
import { PacketType } from './packet';
|
||||
import { MetadataTags } from './metadata';
|
||||
import { AC3_SAMPLE_RATES, EAC3_REDUCED_SAMPLE_RATES } from '../shared/ac3-misc';
|
||||
import { Bitstream } from '../shared/bitstream';
|
||||
|
||||
// References for AVC/HEVC code:
|
||||
// ISO 14496-15
|
||||
|
||||
+1
-101
@@ -6,6 +6,7 @@
|
||||
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||
*/
|
||||
|
||||
import { parseAacAudioSpecificConfig } from '../shared/aac-misc';
|
||||
import {
|
||||
Av1CodecInfo,
|
||||
AvcDecoderConfigurationRecord,
|
||||
@@ -13,7 +14,6 @@ import {
|
||||
Vp9CodecInfo,
|
||||
} from './codec-data';
|
||||
import {
|
||||
Bitstream,
|
||||
COLOR_PRIMARIES_MAP,
|
||||
MATRIX_COEFFICIENTS_MAP,
|
||||
TRANSFER_CHARACTERISTICS_MAP,
|
||||
@@ -590,106 +590,6 @@ export const extractAudioCodecString = (trackInfo: {
|
||||
throw new TypeError(`Unhandled codec '${codec}'.`);
|
||||
};
|
||||
|
||||
export type AacAudioSpecificConfig = {
|
||||
objectType: number;
|
||||
frequencyIndex: number;
|
||||
sampleRate: number | null;
|
||||
channelConfiguration: number;
|
||||
numberOfChannels: number | null;
|
||||
};
|
||||
|
||||
export const aacFrequencyTable = [
|
||||
96000, 88200, 64000, 48000, 44100, 32000,
|
||||
24000, 22050, 16000, 12000, 11025, 8000, 7350,
|
||||
];
|
||||
|
||||
export const aacChannelMap = [-1, 1, 2, 3, 4, 5, 6, 8];
|
||||
|
||||
export const parseAacAudioSpecificConfig = (bytes: Uint8Array | null): AacAudioSpecificConfig => {
|
||||
if (!bytes || bytes.byteLength < 2) {
|
||||
throw new TypeError('AAC description must be at least 2 bytes long.');
|
||||
}
|
||||
|
||||
const bitstream = new Bitstream(bytes);
|
||||
|
||||
let objectType = bitstream.readBits(5);
|
||||
if (objectType === 31) {
|
||||
objectType = 32 + bitstream.readBits(6);
|
||||
}
|
||||
|
||||
const frequencyIndex = bitstream.readBits(4);
|
||||
let sampleRate: number | null = null;
|
||||
if (frequencyIndex === 15) {
|
||||
sampleRate = bitstream.readBits(24);
|
||||
} else {
|
||||
if (frequencyIndex < aacFrequencyTable.length) {
|
||||
sampleRate = aacFrequencyTable[frequencyIndex]!;
|
||||
}
|
||||
}
|
||||
|
||||
const channelConfiguration = bitstream.readBits(4);
|
||||
let numberOfChannels: number | null = null;
|
||||
if (channelConfiguration >= 1 && channelConfiguration <= 7) {
|
||||
numberOfChannels = aacChannelMap[channelConfiguration]!;
|
||||
}
|
||||
|
||||
return {
|
||||
objectType,
|
||||
frequencyIndex,
|
||||
sampleRate,
|
||||
channelConfiguration,
|
||||
numberOfChannels,
|
||||
};
|
||||
};
|
||||
|
||||
export const buildAacAudioSpecificConfig = (config: {
|
||||
objectType: number;
|
||||
sampleRate: number;
|
||||
numberOfChannels: number;
|
||||
}) => {
|
||||
let frequencyIndex = aacFrequencyTable.indexOf(config.sampleRate);
|
||||
let customSampleRate: number | null = null;
|
||||
|
||||
if (frequencyIndex === -1) {
|
||||
frequencyIndex = 15;
|
||||
customSampleRate = config.sampleRate;
|
||||
}
|
||||
|
||||
const channelConfiguration = aacChannelMap.indexOf(config.numberOfChannels);
|
||||
if (channelConfiguration === -1) {
|
||||
throw new TypeError(`Unsupported number of channels: ${config.numberOfChannels}`);
|
||||
}
|
||||
|
||||
let bitCount = 5 + 4 + 4;
|
||||
if (config.objectType >= 32) {
|
||||
bitCount += 6;
|
||||
}
|
||||
if (frequencyIndex === 15) {
|
||||
bitCount += 24;
|
||||
}
|
||||
|
||||
const byteCount = Math.ceil(bitCount / 8);
|
||||
const bytes = new Uint8Array(byteCount);
|
||||
const bitstream = new Bitstream(bytes);
|
||||
|
||||
if (config.objectType < 32) {
|
||||
bitstream.writeBits(5, config.objectType);
|
||||
} else {
|
||||
bitstream.writeBits(5, 31);
|
||||
bitstream.writeBits(6, config.objectType - 32);
|
||||
}
|
||||
|
||||
bitstream.writeBits(4, frequencyIndex);
|
||||
|
||||
if (frequencyIndex === 15) {
|
||||
bitstream.writeBits(24, customSampleRate!);
|
||||
}
|
||||
|
||||
bitstream.writeBits(4, channelConfiguration);
|
||||
|
||||
return bytes;
|
||||
};
|
||||
|
||||
export const OPUS_SAMPLE_RATE = 48_000;
|
||||
|
||||
const PCM_CODEC_REGEX = /^pcm-([usf])(\d+)+(be)?$/;
|
||||
|
||||
@@ -774,12 +774,24 @@ export class Conversion {
|
||||
);
|
||||
}
|
||||
|
||||
if (codecs.includes('aac')) {
|
||||
elements.push(
|
||||
'\nThe @mediabunny/aac-encoder extension package provides support for encoding AAC.',
|
||||
);
|
||||
}
|
||||
|
||||
if (codecs.includes('ac3') || codecs.includes('eac3')) {
|
||||
elements.push(
|
||||
'\nThe @mediabunny/ac3 extension package provides support'
|
||||
+ ' for encoding and decoding AC-3/E-AC-3.',
|
||||
);
|
||||
}
|
||||
|
||||
if (codecs.includes('flac')) {
|
||||
elements.push(
|
||||
'\nThe @mediabunny/flac-encoder extension package provides support for encoding FLAC.',
|
||||
);
|
||||
}
|
||||
} else {
|
||||
elements.push('\nCheck the discardedTracks field for more info.');
|
||||
}
|
||||
|
||||
@@ -15,7 +15,6 @@ import {
|
||||
assert,
|
||||
AsyncMutex,
|
||||
binarySearchLessOrEqual,
|
||||
Bitstream,
|
||||
textDecoder,
|
||||
UNDETERMINED_LANGUAGE,
|
||||
} from '../misc';
|
||||
@@ -37,6 +36,7 @@ import {
|
||||
readSampleRate,
|
||||
getSampleRateOrUncommon,
|
||||
} from './flac-misc';
|
||||
import { Bitstream } from '../../shared/bitstream';
|
||||
|
||||
type FlacAudioInfo = {
|
||||
numberOfChannels: number;
|
||||
|
||||
@@ -6,7 +6,8 @@
|
||||
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||
*/
|
||||
|
||||
import { assert, assertNever, Bitstream } from '../misc';
|
||||
import { Bitstream } from '../../shared/bitstream';
|
||||
import { assert, assertNever } from '../misc';
|
||||
import { FileSlice, readBytes, readU16Be, readU8 } from '../reader';
|
||||
|
||||
type BlockSizeOrUncommon = number | 'uncommon-u16' | 'uncommon-u8';
|
||||
|
||||
+9
-13
@@ -10,7 +10,6 @@ import { validateAudioChunkMetadata } from '../codec';
|
||||
import { createVorbisComments, FlacBlockType } from '../codec-data';
|
||||
import {
|
||||
assert,
|
||||
Bitstream,
|
||||
textEncoder,
|
||||
toDataView,
|
||||
toUint8Array,
|
||||
@@ -27,6 +26,7 @@ import {
|
||||
getBlockSizeOrUncommon,
|
||||
readCodedNumber,
|
||||
} from './flac-misc';
|
||||
import { Bitstream } from '../../shared/bitstream';
|
||||
|
||||
const FLAC_HEADER = /* #__PURE__ */ new Uint8Array([0x66, 0x4c, 0x61, 0x43]); // 'fLaC'
|
||||
const STREAMINFO_SIZE = 38;
|
||||
@@ -207,12 +207,6 @@ export class FlacMuxer extends Muxer {
|
||||
): Promise<void> {
|
||||
const release = await this.mutex.acquire();
|
||||
|
||||
validateAudioChunkMetadata(meta);
|
||||
|
||||
assert(meta);
|
||||
assert(meta.decoderConfig);
|
||||
assert(meta.decoderConfig.description);
|
||||
|
||||
try {
|
||||
this.validateAndNormalizeTimestamp(
|
||||
track,
|
||||
@@ -221,14 +215,16 @@ export class FlacMuxer extends Muxer {
|
||||
);
|
||||
|
||||
if (this.sampleRate === null) {
|
||||
// It's the first packet
|
||||
validateAudioChunkMetadata(meta);
|
||||
|
||||
assert(meta);
|
||||
assert(meta.decoderConfig);
|
||||
assert(meta.decoderConfig.description);
|
||||
|
||||
this.sampleRate = meta.decoderConfig.sampleRate;
|
||||
}
|
||||
|
||||
if (this.channels === null) {
|
||||
this.channels = meta.decoderConfig.numberOfChannels;
|
||||
}
|
||||
|
||||
if (this.bitsPerSample === null) {
|
||||
const descriptionBitstream = new Bitstream(
|
||||
toUint8Array(meta.decoderConfig.description),
|
||||
);
|
||||
@@ -244,7 +240,7 @@ export class FlacMuxer extends Muxer {
|
||||
}
|
||||
|
||||
const slice = FileSlice.tempFromBytes(packet.data);
|
||||
readBytes(slice, 2);
|
||||
slice.skip(2);
|
||||
const bytes = readBytes(slice, 2);
|
||||
const bitstream = new Bitstream(bytes);
|
||||
const blockSizeOrUncommon = getBlockSizeOrUncommon(bitstream.readBits(4));
|
||||
|
||||
@@ -20,7 +20,6 @@ import {
|
||||
UNDETERMINED_LANGUAGE,
|
||||
assertNever,
|
||||
keyValueIterator,
|
||||
Bitstream,
|
||||
} from '../misc';
|
||||
import {
|
||||
AudioCodec,
|
||||
@@ -46,6 +45,7 @@ import {
|
||||
} from './isobmff-muxer';
|
||||
import { parseAc3SyncFrame, parseEac3SyncFrame, parseOpusIdentificationHeader } from '../codec-data';
|
||||
import { MetadataTags, RichImageData } from '../metadata';
|
||||
import { Bitstream } from '../../shared/bitstream';
|
||||
|
||||
export class IsobmffBoxWriter {
|
||||
private helper = new Uint8Array(8);
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||
*/
|
||||
|
||||
import { parseAacAudioSpecificConfig } from '../../shared/aac-misc';
|
||||
import {
|
||||
AacCodecInfo,
|
||||
AudioCodec,
|
||||
@@ -13,7 +14,6 @@ import {
|
||||
extractVideoCodecString,
|
||||
MediaCodec,
|
||||
OPUS_SAMPLE_RATE,
|
||||
parseAacAudioSpecificConfig,
|
||||
parsePcmCodec,
|
||||
PCM_AUDIO_CODECS,
|
||||
PcmAudioCodec,
|
||||
@@ -47,7 +47,6 @@ import {
|
||||
assert,
|
||||
binarySearchExact,
|
||||
binarySearchLessOrEqual,
|
||||
Bitstream,
|
||||
COLOR_PRIMARIES_MAP_INVERSE,
|
||||
findLastIndex,
|
||||
isIso639Dash2LanguageCode,
|
||||
@@ -92,6 +91,7 @@ import {
|
||||
} from '../reader';
|
||||
import { DEFAULT_TRACK_DISPOSITION, MetadataTags, RichImageData, TrackDisposition } from '../metadata';
|
||||
import { AC3_SAMPLE_RATES } from '../../shared/ac3-misc';
|
||||
import { Bitstream } from '../../shared/bitstream';
|
||||
|
||||
type InternalTrack = {
|
||||
id: number;
|
||||
|
||||
@@ -13,10 +13,8 @@ import { BufferTargetWriter, Writer } from '../writer';
|
||||
import { assert, computeRationalApproximation, last, promiseWithResolvers, Rational, simplifyRational } from '../misc';
|
||||
import { IsobmffOutputFormatOptions, IsobmffOutputFormat, MovOutputFormat } from '../output-format';
|
||||
import { inlineTimestampRegex, SubtitleConfig, SubtitleCue, SubtitleMetadata } from '../subtitles';
|
||||
import { aacChannelMap, aacFrequencyTable, buildAacAudioSpecificConfig } from '../../shared/aac-misc';
|
||||
import {
|
||||
aacChannelMap,
|
||||
aacFrequencyTable,
|
||||
buildAacAudioSpecificConfig,
|
||||
parsePcmCodec,
|
||||
PCM_AUDIO_CODECS,
|
||||
PcmAudioCodec,
|
||||
|
||||
@@ -6,8 +6,8 @@
|
||||
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||
*/
|
||||
|
||||
import { Bitstream } from '../../shared/bitstream';
|
||||
import {
|
||||
Bitstream,
|
||||
COLOR_PRIMARIES_MAP,
|
||||
MATRIX_COEFFICIENTS_MAP,
|
||||
TRANSFER_CHARACTERISTICS_MAP,
|
||||
@@ -49,10 +49,8 @@ import {
|
||||
inlineTimestampRegex,
|
||||
parseSubtitleTimestamp,
|
||||
} from '../subtitles';
|
||||
import { aacChannelMap, aacFrequencyTable, buildAacAudioSpecificConfig } from '../../shared/aac-misc';
|
||||
import {
|
||||
aacChannelMap,
|
||||
aacFrequencyTable,
|
||||
buildAacAudioSpecificConfig,
|
||||
OPUS_SAMPLE_RATE,
|
||||
PCM_AUDIO_CODECS,
|
||||
PcmAudioCodec,
|
||||
|
||||
+1
-2
@@ -6,11 +6,10 @@
|
||||
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||
*/
|
||||
|
||||
import { buildAacAudioSpecificConfig, parseAacAudioSpecificConfig } from '../shared/aac-misc';
|
||||
import {
|
||||
AUDIO_CODECS,
|
||||
AudioCodec,
|
||||
buildAacAudioSpecificConfig,
|
||||
parseAacAudioSpecificConfig,
|
||||
parsePcmCodec,
|
||||
PCM_AUDIO_CODECS,
|
||||
PcmAudioCodec,
|
||||
|
||||
+2
-79
@@ -6,6 +6,8 @@
|
||||
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||
*/
|
||||
|
||||
import { Bitstream } from '../shared/bitstream';
|
||||
|
||||
export function assert(x: unknown): asserts x {
|
||||
if (!x) {
|
||||
throw new Error('Assertion failed.');
|
||||
@@ -39,85 +41,6 @@ export const isU32 = (value: number) => {
|
||||
return value >= 0 && value < 2 ** 32;
|
||||
};
|
||||
|
||||
export class Bitstream {
|
||||
/** Current offset in bits. */
|
||||
pos = 0;
|
||||
|
||||
constructor(public bytes: Uint8Array) {}
|
||||
|
||||
seekToByte(byteOffset: number) {
|
||||
this.pos = 8 * byteOffset;
|
||||
}
|
||||
|
||||
private readBit() {
|
||||
const byteIndex = Math.floor(this.pos / 8);
|
||||
const byte = this.bytes[byteIndex] ?? 0;
|
||||
const bitIndex = 0b111 - (this.pos & 0b111);
|
||||
const bit = (byte & (1 << bitIndex)) >> bitIndex;
|
||||
|
||||
this.pos++;
|
||||
return bit;
|
||||
}
|
||||
|
||||
readBits(n: number) {
|
||||
if (n === 1) {
|
||||
return this.readBit();
|
||||
}
|
||||
|
||||
let result = 0;
|
||||
|
||||
for (let i = 0; i < n; i++) {
|
||||
result <<= 1;
|
||||
result |= this.readBit();
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
writeBits(n: number, value: number) {
|
||||
const end = this.pos + n;
|
||||
|
||||
for (let i = this.pos; i < end; i++) {
|
||||
const byteIndex = Math.floor(i / 8);
|
||||
let byte = this.bytes[byteIndex]!;
|
||||
const bitIndex = 0b111 - (i & 0b111);
|
||||
|
||||
byte &= ~(1 << bitIndex);
|
||||
byte |= ((value & (1 << (end - i - 1))) >> (end - i - 1)) << bitIndex;
|
||||
this.bytes[byteIndex] = byte;
|
||||
}
|
||||
|
||||
this.pos = end;
|
||||
};
|
||||
|
||||
readAlignedByte() {
|
||||
// Ensure we're byte-aligned
|
||||
if (this.pos % 8 !== 0) {
|
||||
throw new Error('Bitstream is not byte-aligned.');
|
||||
}
|
||||
|
||||
const byteIndex = this.pos / 8;
|
||||
const byte = this.bytes[byteIndex] ?? 0;
|
||||
|
||||
this.pos += 8;
|
||||
return byte;
|
||||
}
|
||||
|
||||
skipBits(n: number) {
|
||||
this.pos += n;
|
||||
}
|
||||
|
||||
getBitsLeft() {
|
||||
return this.bytes.length * 8 - this.pos;
|
||||
}
|
||||
|
||||
clone() {
|
||||
const clone = new Bitstream(this.bytes);
|
||||
clone.pos = this.pos;
|
||||
return clone;
|
||||
}
|
||||
}
|
||||
|
||||
/** Reads an exponential-Golomb universal code from a Bitstream. */
|
||||
export const readExpGolomb = (bitstream: Bitstream) => {
|
||||
let leadingZeroBits = 0;
|
||||
|
||||
@@ -8,10 +8,9 @@
|
||||
|
||||
import { SAMPLES_PER_AAC_FRAME } from '../adts/adts-demuxer';
|
||||
import { MAX_ADTS_FRAME_HEADER_SIZE, readAdtsFrameHeader } from '../adts/adts-reader';
|
||||
import { aacChannelMap, aacFrequencyTable } from '../../shared/aac-misc';
|
||||
import {
|
||||
aacChannelMap,
|
||||
AacCodecInfo,
|
||||
aacFrequencyTable,
|
||||
AudioCodec,
|
||||
extractAudioCodecString,
|
||||
extractVideoCodecString,
|
||||
@@ -54,7 +53,6 @@ import {
|
||||
assert,
|
||||
binarySearchExact,
|
||||
binarySearchLessOrEqual,
|
||||
Bitstream,
|
||||
COLOR_PRIMARIES_MAP_INVERSE,
|
||||
findLastIndex,
|
||||
floorToMultiple,
|
||||
@@ -71,6 +69,7 @@ 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';
|
||||
import { AC3_SAMPLE_RATES } from '../../shared/ac3-misc';
|
||||
import { Bitstream } from '../../shared/bitstream';
|
||||
|
||||
// Resources:
|
||||
// ISO/IEC 13818-1
|
||||
|
||||
@@ -6,8 +6,8 @@
|
||||
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||
*/
|
||||
|
||||
import { parseAacAudioSpecificConfig, validateAudioChunkMetadata, validateVideoChunkMetadata } from '../codec';
|
||||
import { buildAdtsHeaderTemplate, writeAdtsFrameLength } from '../adts/adts-misc';
|
||||
import { buildAdtsHeaderTemplate, parseAacAudioSpecificConfig, writeAdtsFrameLength } from '../../shared/aac-misc';
|
||||
import { validateAudioChunkMetadata, validateVideoChunkMetadata } from '../codec';
|
||||
import {
|
||||
AC3_REGISTRATION_DESCRIPTOR,
|
||||
AvcDecoderConfigurationRecord,
|
||||
@@ -23,7 +23,8 @@ import {
|
||||
iterateNalUnitsInAnnexB,
|
||||
iterateNalUnitsInLengthPrefixed,
|
||||
} from '../codec-data';
|
||||
import { assert, Bitstream, promiseWithResolvers, setUint24, toDataView, toUint8Array } from '../misc';
|
||||
import { Bitstream } from '../../shared/bitstream';
|
||||
import { assert, promiseWithResolvers, setUint24, toDataView, toUint8Array } from '../misc';
|
||||
import { Muxer } from '../muxer';
|
||||
import { Output, OutputAudioTrack, OutputTrack, OutputVideoTrack } from '../output';
|
||||
import { MpegTsOutputFormat } from '../output-format';
|
||||
|
||||
@@ -156,7 +156,6 @@ test('MPEG-TS muxing with AVC and AAC', async () => {
|
||||
|
||||
const secondVideoPacket = await videoSink.getNextPacket(firstVideoPacket);
|
||||
assert(secondVideoPacket);
|
||||
expect(secondVideoPacket.type).toBe('delta');
|
||||
|
||||
for await (const packet of videoSink.packets()) {
|
||||
expect(packet.data.slice(0, 4)).toEqual(new Uint8Array([0, 0, 0, 1])); // Annex B start code
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
import { expect, test } from 'vitest';
|
||||
import { Input } from '../../src/input.js';
|
||||
import { BufferSource } from '../../src/source.js';
|
||||
import { ALL_FORMATS } from '../../src/input-format.js';
|
||||
import { Output } from '../../src/output.js';
|
||||
import { BufferTarget } from '../../src/target.js';
|
||||
import { canEncode } from '../../src/encode.js';
|
||||
import { AudioSampleSource } from '../../src/media-source.js';
|
||||
import { EncodedPacketSink } from '../../src/media-sink.js';
|
||||
import { Mp4OutputFormat } from '../../src/output-format.js';
|
||||
import { AudioSample } from '../../src/sample.js';
|
||||
import { registerAacEncoder } from '@mediabunny/aac-encoder';
|
||||
|
||||
const createSineWave = (sampleRate: number, channels: number, durationSeconds: number) => {
|
||||
const totalFrames = sampleRate * durationSeconds;
|
||||
const data = new Float32Array(totalFrames * channels);
|
||||
|
||||
for (let i = 0; i < totalFrames; i++) {
|
||||
const value = Math.sin(2 * Math.PI * 440 * i / sampleRate);
|
||||
for (let ch = 0; ch < channels; ch++) {
|
||||
data[i * channels + ch] = value;
|
||||
}
|
||||
}
|
||||
|
||||
return data;
|
||||
};
|
||||
|
||||
test('Custom coder registration', async () => {
|
||||
expect(await canEncode('aac')).toBe(false);
|
||||
|
||||
registerAacEncoder();
|
||||
|
||||
expect(await canEncode('aac')).toBe(true);
|
||||
});
|
||||
|
||||
test('AAC encoding', async () => {
|
||||
registerAacEncoder();
|
||||
|
||||
const sampleRate = 48000;
|
||||
const channels = 2;
|
||||
const durationSeconds = 2;
|
||||
const data = createSineWave(sampleRate, channels, durationSeconds);
|
||||
|
||||
const output = new Output({
|
||||
format: new Mp4OutputFormat(),
|
||||
target: new BufferTarget(),
|
||||
});
|
||||
|
||||
const audioSource = new AudioSampleSource({ codec: 'aac', bitrate: 128000 });
|
||||
output.addAudioTrack(audioSource);
|
||||
|
||||
await output.start();
|
||||
await audioSource.add(new AudioSample({
|
||||
data,
|
||||
format: 'f32',
|
||||
numberOfChannels: channels,
|
||||
sampleRate,
|
||||
timestamp: 0,
|
||||
}));
|
||||
audioSource.close();
|
||||
await output.finalize();
|
||||
|
||||
using input = new Input({
|
||||
source: new BufferSource(output.target.buffer!),
|
||||
formats: ALL_FORMATS,
|
||||
});
|
||||
|
||||
const track = (await input.getPrimaryAudioTrack())!;
|
||||
expect(track.codec).toBe('aac');
|
||||
expect(track.sampleRate).toBe(sampleRate);
|
||||
expect(track.numberOfChannels).toBe(channels);
|
||||
|
||||
const sink = new EncodedPacketSink(track);
|
||||
let packetCount = 0;
|
||||
for await (const packet of sink.packets()) {
|
||||
expect(packet.type).toBe('key');
|
||||
packetCount++;
|
||||
}
|
||||
expect(packetCount).toBeGreaterThan(durationSeconds * sampleRate / 1024);
|
||||
|
||||
expect(await track.computeDuration()).toBeCloseTo(2, 1);
|
||||
});
|
||||
@@ -0,0 +1,83 @@
|
||||
import { expect, test } from 'vitest';
|
||||
import { Input } from '../../src/input.js';
|
||||
import { BufferSource } from '../../src/source.js';
|
||||
import { ALL_FORMATS } from '../../src/input-format.js';
|
||||
import { Output } from '../../src/output.js';
|
||||
import { BufferTarget } from '../../src/target.js';
|
||||
import { canEncode } from '../../src/encode.js';
|
||||
import { AudioSampleSource } from '../../src/media-source.js';
|
||||
import { EncodedPacketSink } from '../../src/media-sink.js';
|
||||
import { FlacOutputFormat } from '../../src/output-format.js';
|
||||
import { AudioSample } from '../../src/sample.js';
|
||||
import { registerFlacEncoder } from '@mediabunny/flac-encoder';
|
||||
|
||||
const createSineWave = (sampleRate: number, channels: number, durationSeconds: number) => {
|
||||
const totalFrames = sampleRate * durationSeconds;
|
||||
const data = new Float32Array(totalFrames * channels);
|
||||
|
||||
for (let i = 0; i < totalFrames; i++) {
|
||||
const value = Math.sin(2 * Math.PI * 440 * i / sampleRate);
|
||||
for (let ch = 0; ch < channels; ch++) {
|
||||
data[i * channels + ch] = value;
|
||||
}
|
||||
}
|
||||
|
||||
return data;
|
||||
};
|
||||
|
||||
test('Custom coder registration', async () => {
|
||||
expect(await canEncode('flac')).toBe(false);
|
||||
|
||||
registerFlacEncoder();
|
||||
|
||||
expect(await canEncode('flac')).toBe(true);
|
||||
});
|
||||
|
||||
test('FLAC encoding', async () => {
|
||||
registerFlacEncoder();
|
||||
|
||||
const sampleRate = 48000;
|
||||
const channels = 2;
|
||||
const durationSeconds = 2;
|
||||
const data = createSineWave(sampleRate, channels, durationSeconds);
|
||||
|
||||
const output = new Output({
|
||||
format: new FlacOutputFormat(),
|
||||
target: new BufferTarget(),
|
||||
});
|
||||
|
||||
const audioSource = new AudioSampleSource({ codec: 'flac', bitrate: 1 });
|
||||
output.addAudioTrack(audioSource);
|
||||
|
||||
await output.start();
|
||||
await audioSource.add(new AudioSample({
|
||||
data,
|
||||
format: 'f32',
|
||||
numberOfChannels: channels,
|
||||
sampleRate,
|
||||
timestamp: 0,
|
||||
}));
|
||||
audioSource.close();
|
||||
await output.finalize();
|
||||
|
||||
using input = new Input({
|
||||
source: new BufferSource(output.target.buffer!),
|
||||
formats: ALL_FORMATS,
|
||||
});
|
||||
|
||||
const track = (await input.getPrimaryAudioTrack())!;
|
||||
expect(track.codec).toBe('flac');
|
||||
expect(track.sampleRate).toBe(sampleRate);
|
||||
expect(track.numberOfChannels).toBe(channels);
|
||||
|
||||
const sink = new EncodedPacketSink(track);
|
||||
let packetCount = 0;
|
||||
for await (const packet of sink.packets()) {
|
||||
expect(packet.type).toBe('key');
|
||||
packetCount++;
|
||||
}
|
||||
// FLAC default block size is 4096, so ~24 packets for 2 seconds at 48kHz
|
||||
expect(packetCount).toBeGreaterThan(durationSeconds * sampleRate / 4096);
|
||||
|
||||
expect(await track.computeDuration()).toBeCloseTo(2, 1);
|
||||
});
|
||||
@@ -0,0 +1,83 @@
|
||||
import { expect, test } from 'vitest';
|
||||
import { Input } from '../../src/input.js';
|
||||
import { BufferSource } from '../../src/source.js';
|
||||
import { ALL_FORMATS } from '../../src/input-format.js';
|
||||
import { Output } from '../../src/output.js';
|
||||
import { BufferTarget } from '../../src/target.js';
|
||||
import { canEncode } from '../../src/encode.js';
|
||||
import { AudioSampleSource } from '../../src/media-source.js';
|
||||
import { EncodedPacketSink } from '../../src/media-sink.js';
|
||||
import { Mp3OutputFormat } from '../../src/output-format.js';
|
||||
import { AudioSample } from '../../src/sample.js';
|
||||
import { registerMp3Encoder } from '@mediabunny/mp3-encoder';
|
||||
|
||||
const createSineWave = (sampleRate: number, channels: number, durationSeconds: number) => {
|
||||
const totalFrames = sampleRate * durationSeconds;
|
||||
const data = new Float32Array(totalFrames * channels);
|
||||
|
||||
for (let i = 0; i < totalFrames; i++) {
|
||||
const value = Math.sin(2 * Math.PI * 440 * i / sampleRate);
|
||||
for (let ch = 0; ch < channels; ch++) {
|
||||
data[i * channels + ch] = value;
|
||||
}
|
||||
}
|
||||
|
||||
return data;
|
||||
};
|
||||
|
||||
test('Custom coder registration', async () => {
|
||||
expect(await canEncode('mp3')).toBe(false);
|
||||
|
||||
registerMp3Encoder();
|
||||
|
||||
expect(await canEncode('mp3')).toBe(true);
|
||||
});
|
||||
|
||||
test('MP3 encoding', async () => {
|
||||
registerMp3Encoder();
|
||||
|
||||
const sampleRate = 44100;
|
||||
const channels = 2;
|
||||
const durationSeconds = 2;
|
||||
const data = createSineWave(sampleRate, channels, durationSeconds);
|
||||
|
||||
const output = new Output({
|
||||
format: new Mp3OutputFormat(),
|
||||
target: new BufferTarget(),
|
||||
});
|
||||
|
||||
const audioSource = new AudioSampleSource({ codec: 'mp3', bitrate: 128_000 });
|
||||
output.addAudioTrack(audioSource);
|
||||
|
||||
await output.start();
|
||||
await audioSource.add(new AudioSample({
|
||||
data,
|
||||
format: 'f32',
|
||||
numberOfChannels: channels,
|
||||
sampleRate,
|
||||
timestamp: 0,
|
||||
}));
|
||||
audioSource.close();
|
||||
await output.finalize();
|
||||
|
||||
using input = new Input({
|
||||
source: new BufferSource(output.target.buffer!),
|
||||
formats: ALL_FORMATS,
|
||||
});
|
||||
|
||||
const track = (await input.getPrimaryAudioTrack())!;
|
||||
expect(track.codec).toBe('mp3');
|
||||
expect(track.sampleRate).toBe(sampleRate);
|
||||
expect(track.numberOfChannels).toBe(channels);
|
||||
|
||||
const sink = new EncodedPacketSink(track);
|
||||
let packetCount = 0;
|
||||
for await (const packet of sink.packets()) {
|
||||
expect(packet.type).toBe('key');
|
||||
packetCount++;
|
||||
}
|
||||
// MP3 frames are 1152 samples each, so ~77 packets for 2 seconds at 44.1kHz
|
||||
expect(packetCount).toBeGreaterThan(durationSeconds * sampleRate / 1152 - 2);
|
||||
|
||||
expect(await track.computeDuration()).toBeCloseTo(2, 0);
|
||||
});
|
||||
@@ -11,6 +11,7 @@
|
||||
"allowJs": true,
|
||||
"noEmit": true,
|
||||
},
|
||||
"include": [],
|
||||
"references": [
|
||||
{ "path": "./tsconfig.vite.json" },
|
||||
{ "path": "./tsconfig.vitest.json" }
|
||||
|
||||
@@ -8,6 +8,8 @@
|
||||
"paths": {
|
||||
"mediabunny": ["./src/index.ts"],
|
||||
"@mediabunny/ac3": ["./packages/ac3/src/index.ts"],
|
||||
"@mediabunny/aac-encoder": ["./packages/aac-encoder/src/index.ts"],
|
||||
"@mediabunny/flac-encoder": ["./packages/flac-encoder/src/index.ts"],
|
||||
},
|
||||
"types": ["vite/client"]
|
||||
},
|
||||
|
||||
+10
-1
@@ -8,9 +8,18 @@
|
||||
"paths": {
|
||||
"mediabunny": ["./src/index.ts"],
|
||||
"@mediabunny/ac3": ["./packages/ac3/src/index.ts"],
|
||||
"@mediabunny/aac-encoder": ["./packages/aac-encoder/src/index.ts"],
|
||||
"@mediabunny/flac-encoder": ["./packages/flac-encoder/src/index.ts"],
|
||||
"@mediabunny/mp3-encoder": ["./packages/mp3-encoder/src/index.ts"],
|
||||
},
|
||||
},
|
||||
"include": ["vitest.config.ts", "./test/**/*"],
|
||||
"exclude": ["./test/public/**/*"],
|
||||
"references": [{ "path": "./src" }, { "path": "./packages/ac3" }]
|
||||
"references": [
|
||||
{ "path": "./src" },
|
||||
{ "path": "./packages/ac3" },
|
||||
{ "path": "./packages/aac-encoder" },
|
||||
{ "path": "./packages/flac-encoder" },
|
||||
{ "path": "./packages/mp3-encoder" },
|
||||
]
|
||||
}
|
||||
|
||||
+5
-1
@@ -20,7 +20,11 @@ const rollupInput = Object.fromEntries(
|
||||
export default defineConfig({
|
||||
resolve: {
|
||||
alias: {
|
||||
mediabunny: path.resolve(__dirname, './dist/bundles/mediabunny.mjs'),
|
||||
'mediabunny': path.resolve(__dirname, './dist/bundles/mediabunny.mjs'),
|
||||
'@mediabunny/aac-encoder':
|
||||
path.resolve(__dirname, './packages/aac-encoder/dist/bundles/mediabunny-aac-encoder.mjs'),
|
||||
'@mediabunny/flac-encoder':
|
||||
path.resolve(__dirname, './packages/flac-encoder/dist/bundles/mediabunny-flac-encoder.mjs'),
|
||||
},
|
||||
},
|
||||
plugins: [
|
||||
|
||||
@@ -8,6 +8,12 @@ export default defineConfig({
|
||||
alias: {
|
||||
'mediabunny': path.resolve(__dirname, './src/index.ts'),
|
||||
'@mediabunny/ac3': path.resolve(__dirname, './packages/ac3/dist/bundles/mediabunny-ac3.mjs'),
|
||||
'@mediabunny/aac-encoder':
|
||||
path.resolve(__dirname, './packages/aac-encoder/dist/bundles/mediabunny-aac-encoder.mjs'),
|
||||
'@mediabunny/flac-encoder':
|
||||
path.resolve(__dirname, './packages/flac-encoder/dist/bundles/mediabunny-flac-encoder.mjs'),
|
||||
'@mediabunny/mp3-encoder':
|
||||
path.resolve(__dirname, './packages/mp3-encoder/dist/bundles/mediabunny-mp3-encoder.mjs'),
|
||||
},
|
||||
},
|
||||
test: {
|
||||
|
||||
Reference in New Issue
Block a user