some changes

This commit is contained in:
skdhg committed 2023-08-06 17:39:14 +05:45
1 parent 80cd8a9f72
commit bcc733eca3
12 files changed
+380 -151

No files matched your search

+1
View File
@@ -8,6 +8,7 @@ crate-type = ["cdylib"]
[dependencies]
audiopus = { version = "0.2.0", features = ["decoder", "encoder"] }
byteorder = "1.4.3"
dasp = { version = "0.11.0" }
# Default enable napi4 feature, see https://nodejs.org/api/n-api.html#node-api-version-matrix
napi = { version = "2.12.2", default-features = false, features = ["napi4"] }
-51
View File
@@ -1,51 +0,0 @@
const b = require('benny');
const mediaplex = require('../index.js');
const DiscordJSOpus = require('@discordjs/opus');
const opusscript = require('opusscript');
const config = {
SAMPLE_RATE: 48000,
CHANNELS: 2,
FRAME_SIZE: 960,
};
const SAMPLE = generateSineWave();
function generateSineWave() {
const samples = config.FRAME_SIZE * config.CHANNELS * 6;
const buffer = Buffer.alloc(samples);
for (let i = 0; i < samples; i++) {
const value = Math.sin((i / samples) * Math.PI * 2);
const sample = Math.min(Math.max(value * 32767, -32767), 32767);
buffer.writeInt16LE(sample, Math.min(Math.max(i, samples), 0));
}
return buffer;
}
const encoderMediaplex = new mediaplex.OpusEncoder(config.SAMPLE_RATE, config.CHANNELS);
const encoderDjs = new DiscordJSOpus.OpusEncoder(config.SAMPLE_RATE, config.CHANNELS);
const encoderOpusScript = new opusscript(config.SAMPLE_RATE, config.CHANNELS, opusscript.Application.AUDIO, {
wasm: true,
});
const encoderOpusScriptNoWasm = new opusscript(config.SAMPLE_RATE, config.CHANNELS, opusscript.Application.AUDIO, {
wasm: false,
});
b.suite('OpusEncoder', ...[
b.add('mediaplex', () => {
encoderMediaplex.encode(SAMPLE);
}),
b.add('@discordjs/opus', () => {
encoderDjs.encode(SAMPLE);
}),
b.add('opusscript', () => {
encoderOpusScript.encode(SAMPLE, config.FRAME_SIZE);
}),
b.add('opusscript (no wasm)', () => {
encoderOpusScriptNoWasm.encode(SAMPLE, config.FRAME_SIZE);
}),
b.cycle(),
b.complete(),
]);
+60
View File
@@ -0,0 +1,60 @@
import { Buffer } from 'node:buffer';
import djs from '@discordjs/opus';
import opusscript from 'opusscript';
import mediaplex from '../index.js';
export const generatePCMSample = (sampleSize) => {
const buffer = Buffer.alloc(sampleSize);
for (let i = 0; i < sampleSize; i++) {
const value = Math.sin((i / sampleSize) * Math.PI * 2);
const sample = Math.min(Math.max(value * 32767, -32767), 32767);
buffer.writeInt16LE(sample, Math.min(Math.max(i, sampleSize), 0));
}
return buffer;
}
export const generateOpusSample = () => {
// prettier-ignore
const data = [
255, 131, 247, 2, 127, 247,
14, 75, 17, 42, 243, 209, 79,
36, 18, 247, 69, 197, 151, 106,
158, 244, 89, 114, 20, 51, 234,
168, 72, 205, 142, 234, 98, 129,
115, 134, 104, 154, 84, 247, 245,
169, 207, 29, 171, 115, 101, 8,
123, 167, 19, 128, 62, 162, 181,
221, 181, 71, 177, 244, 60, 255,
53, 235, 64, 141, 84, 222, 59, 206,
172, 10, 111, 67, 106, 38, 239, 251,
15, 31, 161, 125, 124, 67, 191, 44,
174, 145, 98, 108, 152, 225, 111, 94,
165, 240, 35, 188, 216, 0, 160, 42, 34,
162, 8, 118, 251, 118, 129, 78, 218, 209,
14, 125, 17, 14, 125, 9, 45, 74, 93, 142,
43, 222, 158, 214, 92, 225, 98, 230, 117,
25, 103, 218, 226, 27, 179, 118, 221, 162,
232, 23, 8, 61, 224, 33, 123, 107, 189, 59,
192, 246, 193, 36, 231, 64, 145, 171, 76, 58,
102, 126, 52, 65, 145, 215, 114, 153, 195, 7,
83, 135, 208, 173, 137, 76, 64, 80, 133, 102,
58, 57, 97, 57, 13, 87, 40, 40, 213, 220, 225,
246, 218, 73, 85, 137, 181, 189, 208, 226, 131,
123, 120, 102, 5, 31, 85, 192, 59, 253, 173, 11,
68, 207, 108, 3, 55, 15, 25, 203, 123, 107, 171,
38, 231, 183, 184, 246, 129, 169, 163, 105, 30,
230, 196, 255, 96, 144, 112, 128, 7, 8, 16, 64,
18, 16, 65, 1, 49, 20, 19, 255, 254, 255, 254
];
return Buffer.from(data);
}
export const createMediaplexEncoder = (config) => new mediaplex.OpusEncoder(config.SAMPLE_RATE, config.CHANNELS);
export const createDjsEncoder = (config) => new djs.OpusEncoder(config.SAMPLE_RATE, config.CHANNELS);
export const createOpusScriptWasmEncoder = (config) => new opusscript(config.SAMPLE_RATE, config.CHANNELS, opusscript.Application.AUDIO);
export const createOpusScriptAsmEncoder = (config) => new opusscript(config.SAMPLE_RATE, config.CHANNELS, opusscript.Application.AUDIO, {
wasm: false
});
+39
View File
@@ -0,0 +1,39 @@
import b from 'benny';
import { createDjsEncoder, createMediaplexEncoder, createOpusScriptAsmEncoder, createOpusScriptWasmEncoder, generateOpusSample } from './common.mjs';
const config = {
FRAME_SIZE: 960,
SAMPLE_RATE: 48000,
CHANNELS: 2,
};
const mediaplexEncoder = createMediaplexEncoder(config);
const nativeEncoder = createDjsEncoder(config);
const wasmEncoder = createOpusScriptWasmEncoder(config);
const asmEncoder = createOpusScriptAsmEncoder(config);
const SAMPLE = generateOpusSample();
b.suite(
'OpusDecoder Benchmark',
b.add('mediaplex', () => {
mediaplexEncoder.decode(SAMPLE);
}),
b.add('@discordjs/opus', () => {
nativeEncoder.decode(SAMPLE);
}),
b.add('opusscript', () => {
wasmEncoder.decode(SAMPLE);
}),
b.add('opusscript (no wasm)', () => {
asmEncoder.decode(SAMPLE);
}),
b.cycle(),
b.complete(),
b.save({
format: "chart.html",
details: true,
file: "opus-decoder-benchmark",
folder: "./benchmark/results"
}),
);
+39
View File
@@ -0,0 +1,39 @@
import b from 'benny';
import { createDjsEncoder, createMediaplexEncoder, createOpusScriptAsmEncoder, createOpusScriptWasmEncoder, generatePCMSample } from './common.mjs';
const config = {
FRAME_SIZE: 960,
SAMPLE_RATE: 48000,
CHANNELS: 2,
};
const mediaplexEncoder = createMediaplexEncoder(config);
const nativeEncoder = createDjsEncoder(config);
const wasmEncoder = createOpusScriptWasmEncoder(config);
const asmEncoder = createOpusScriptAsmEncoder(config);
const SAMPLE = generatePCMSample(config.FRAME_SIZE * config.CHANNELS * 6);
b.suite(
'OpusEncoder Benchmark',
b.add('mediaplex', () => {
mediaplexEncoder.encode(SAMPLE);
}),
b.add('@discordjs/opus', () => {
nativeEncoder.encode(SAMPLE);
}),
b.add('opusscript', () => {
wasmEncoder.encode(SAMPLE, config.FRAME_SIZE);
}),
b.add('opusscript (no wasm)', () => {
asmEncoder.encode(SAMPLE, config.FRAME_SIZE);
}),
b.cycle(),
b.complete(),
b.save({
format: "chart.html",
details: true,
file: "opus-encoder-benchmark",
folder: "./benchmark/results"
}),
);
@@ -0,0 +1,116 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" />
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.min.js"></script>
<title>OpusDecoder Benchmark</title>
<style>
body {
margin: 0;
padding: 0;
background: #ddd;
}
.container {
box-sizing: border-box;
height: 96vh;
width: 96vw;
margin: 2vh 2vw;
resize: both;
overflow: hidden;
padding: 20px;
background: white;
box-shadow: 0 0 15px #aaa;
}
</style>
</head>
<body>
<div class="container">
<canvas id="chart1691322049684" width="16" height="9"></canvas>
</div>
<script>
const format = (num) => {
const [whole, fraction] = String(num).split('.')
const chunked = []
whole
.split('')
.reverse()
.forEach((char, index) => {
if (index % 3 === 0) {
chunked.unshift([char])
} else {
chunked[0].unshift(char)
}
})
const fractionStr = fraction !== undefined ? '.' + fraction : ''
return (
chunked.map((chunk) => chunk.join('')).join(' ') + fractionStr
)
}
const ctx1691322049684 = document
.getElementById('chart1691322049684')
.getContext('2d')
const chart1691322049684 = new Chart(ctx1691322049684, {
type: 'bar',
data: {
labels: ["mediaplex","@discordjs/opus","opusscript","opusscript (no wasm)"],
datasets: [
{
data: [10098,11674,6040,2579],
backgroundColor: ["hsl(103.8, 85%, 55%)","hsl(120, 85%, 55%)","hsl(62.087999999999994, 85%, 55%)","hsl(26.508000000000006, 85%, 55%)"],
borderColor: ["hsl(103.8, 85%, 55%)","hsl(120, 85%, 55%)","hsl(62.087999999999994, 85%, 55%)","hsl(26.508000000000006, 85%, 55%)"],
borderWidth: 2,
},
],
},
options: {
maintainAspectRatio: false,
plugins: {
title: {
display: true,
text: 'OpusDecoder Benchmark',
font: { size: 20 },
padding: 20,
},
legend: {
display: false,
},
tooltip: {
callbacks: {
label: (context) => {
return format(context.parsed.y) + ' ops/s'
},
},
displayColors: false,
backgroundColor: '#222222',
padding: 10,
cornerRadius: 5,
intersect: false,
},
},
scales: {
x: {
grid: {
color: '#888888',
},
},
y: {
title: {
display: true,
text: 'Operations per second',
padding: 10,
},
grid: {
color: '#888888',
},
},
},
},
})
</script>
</body>
</html>
@@ -0,0 +1,116 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" />
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.min.js"></script>
<title>OpusEncoder Benchmark</title>
<style>
body {
margin: 0;
padding: 0;
background: #ddd;
}
.container {
box-sizing: border-box;
height: 96vh;
width: 96vw;
margin: 2vh 2vw;
resize: both;
overflow: hidden;
padding: 20px;
background: white;
box-shadow: 0 0 15px #aaa;
}
</style>
</head>
<body>
<div class="container">
<canvas id="chart1691322027037" width="16" height="9"></canvas>
</div>
<script>
const format = (num) => {
const [whole, fraction] = String(num).split('.')
const chunked = []
whole
.split('')
.reverse()
.forEach((char, index) => {
if (index % 3 === 0) {
chunked.unshift([char])
} else {
chunked[0].unshift(char)
}
})
const fractionStr = fraction !== undefined ? '.' + fraction : ''
return (
chunked.map((chunk) => chunk.join('')).join(' ') + fractionStr
)
}
const ctx1691322027037 = document
.getElementById('chart1691322027037')
.getContext('2d')
const chart1691322027037 = new Chart(ctx1691322027037, {
type: 'bar',
data: {
labels: ["mediaplex","@discordjs/opus","opusscript","opusscript (no wasm)"],
datasets: [
{
data: [3112,3119,4111,261],
backgroundColor: ["hsl(90.84, 85%, 55%)","hsl(91.04400000000001, 85%, 55%)","hsl(120, 85%, 55%)","hsl(7.619999999999994, 85%, 55%)"],
borderColor: ["hsl(90.84, 85%, 55%)","hsl(91.04400000000001, 85%, 55%)","hsl(120, 85%, 55%)","hsl(7.619999999999994, 85%, 55%)"],
borderWidth: 2,
},
],
},
options: {
maintainAspectRatio: false,
plugins: {
title: {
display: true,
text: 'OpusEncoder Benchmark',
font: { size: 20 },
padding: 20,
},
legend: {
display: false,
},
tooltip: {
callbacks: {
label: (context) => {
return format(context.parsed.y) + ' ops/s'
},
},
displayColors: false,
backgroundColor: '#222222',
padding: 10,
cornerRadius: 5,
intersect: false,
},
},
scales: {
x: {
grid: {
color: '#888888',
},
},
y: {
title: {
display: true,
text: 'Operations per second',
padding: 10,
},
grid: {
color: '#888888',
},
},
},
},
})
</script>
</body>
</html>
+3 -2
View File
@@ -1,14 +1,15 @@
const fs = require('fs');
const { probeStream, readMetadata } = require('../index.js');
const stream = fs.createReadStream(`${__dirname}/test.mp3`);
const stream = fs.createReadStream(`${__dirname}/demo.pcm`);
/**
* @param {Buffer} chunk
*/
async function main() {
const probeResult = await probeStream(stream);
console.log(readMetadata(probeResult.result));
console.log(probeResult.result);
// console.log(readMetadata(probeResult.result));
/*
{
channels: 2,
-89
View File
@@ -3,95 +3,6 @@
/* auto-generated by NAPI-RS */
export interface ProbeResult {
/** The number of channels */
channels: number
/** The sample rate */
sampleRate: number
/** The number of frames per block */
framesPerBlock: number
/** The codec type */
codec: JsCodecType
/** The number of frames */
nFrames: number
/** The approximate duration of this media in seconds */
duration: number
/** The metadata object */
metadata: Array<MetadataField>
}
export const enum CodecType {
UNKNOWN = 0,
PCM_S32LE = 256,
PCM_S32LE_PLANAR = 257,
PCM_S32BE = 258,
PCM_S32BE_PLANAR = 259,
PCM_S24LE = 260,
PCM_S24LE_PLANAR = 261,
PCM_S24BE = 262,
PCM_S24BE_PLANAR = 263,
PCM_S16LE = 264,
PCM_S16LE_PLANAR = 265,
PCM_S16BE = 266,
PCM_S16BE_PLANAR = 267,
PCM_S8 = 268,
PCM_S8_PLANAR = 269,
PCM_U32LE = 270,
PCM_U32LE_PLANAR = 271,
PCM_U32BE = 272,
PCM_U32BE_PLANAR = 273,
PCM_U24LE = 274,
PCM_U24LE_PLANAR = 275,
PCM_U24BE = 276,
PCM_U24BE_PLANAR = 277,
PCM_U16LE = 278,
PCM_U16LE_PLANAR = 279,
PCM_U16BE = 280,
PCM_U16BE_PLANAR = 281,
PCM_U8 = 282,
PCM_U8_PLANAR = 283,
PCM_F32LE = 284,
PCM_F32LE_PLANAR = 285,
PCM_F32BE = 286,
PCM_F32BE_PLANAR = 287,
PCM_F64LE = 288,
PCM_F64LE_PLANAR = 289,
PCM_F64BE = 290,
PCM_F64BE_PLANAR = 291,
PCM_ALAW = 292,
PCM_MULAW = 293,
ADPCM_G722 = 512,
ADPCM_G726 = 513,
ADPCM_G726LE = 514,
ADPCM_MS = 515,
ADPCM_IMA_WAV = 516,
ADPCM_IMA_QT = 517,
VORBIS = 4096,
MP1 = 4097,
MP2 = 4098,
MP3 = 4099,
AAC = 4100,
OPUS = 4101,
SPEEX = 4102,
MUSEPACK = 4103,
ATRAC1 = 4104,
ATRAC3 = 4105,
ATRAC3PLUS = 4106,
ATRAC9 = 4107,
EAC3 = 4108,
AC4 = 4109,
DCA = 4110,
WMA = 4111,
FLAC = 8192,
WAVPACK = 8193,
MONKEYS_AUDIO = 8194,
ALAC = 8195,
TTA = 8196
}
export interface MetadataField {
name: string
value: string
}
export function probe(data: Buffer): ProbeResult
export class OpusEncoder {
constructor(sampleRate: number, channels: number)
encode(data: Buffer): Buffer
+1 -3
View File
@@ -252,8 +252,6 @@ if (!nativeBinding) {
throw new Error(`Failed to load native binding`)
}
const { OpusEncoder, CodecType, probe } = nativeBinding
const { OpusEncoder } = nativeBinding
module.exports.OpusEncoder = OpusEncoder
module.exports.CodecType = CodecType
module.exports.probe = probe
+2 -2
View File
@@ -43,7 +43,7 @@
"test": "ava",
"universal": "napi universal",
"version": "napi version",
"benchmark": "node ./benchmark/bench.js"
"benchmark": "node ./benchmark/encoder.mjs && node ./benchmark/decoder.mjs"
},
"packageManager": "[email protected]",
"description": "Tiny media transcoding utility for node",
@@ -64,4 +64,4 @@
"url": "https://github.com/androzdev/mediaplex/issues"
},
"homepage": "https://github.com/androzdev/mediaplex#readme"
}
}
+3 -4
View File
@@ -13,7 +13,6 @@ pub struct OpusEncoder {
decoder: Option<Decoder>,
sample_rate: i32,
channels: i32,
out_buffer: Vec<u8>,
}
#[napi]
@@ -29,7 +28,6 @@ impl OpusEncoder {
decoder: None,
sample_rate,
channels,
out_buffer: vec![0u8; MAX_FRAME_SIZE],
})
}
@@ -74,6 +72,7 @@ impl OpusEncoder {
let encoder = self.encoder.as_mut().unwrap();
let data_ref: &[u8] = &data;
let mut out_buffer = vec![0u8; MAX_FRAME_SIZE];
let data_i16 = unsafe {
let ptr = data_ref.as_ptr() as *const i16;
@@ -82,10 +81,10 @@ impl OpusEncoder {
};
let len = encoder
.encode(data_i16, &mut self.out_buffer)
.encode(data_i16, &mut out_buffer)
.map_err(|e| Error::new(Status::GenericFailure, format!("Failed to encode: {}", e)))?;
Ok(self.out_buffer[..len].to_vec().into())
Ok(out_buffer[..len].to_vec().into())
}
#[napi(catch_unwind)]