AXCWG 3 maanden geleden
bovenliggende
commit
fb3f3caad9
9 gewijzigde bestanden met toevoegingen van 996 en 56 verwijderingen
  1. 28 0
      c0.js
  2. 48 53
      main.js
  3. 0 0
      ogg/index.cjs
  4. 0 0
      ogg/index.cjs.map
  5. 831 0
      ogg/index.es.js
  6. 0 0
      ogg/index.es.js.map
  7. 42 3
      package-lock.json
  8. 4 0
      package.json
  9. 43 0
      pitched.js

+ 28 - 0
c0.js

@@ -0,0 +1,28 @@
+import {parentPort} from "worker_threads";
+import Kali from "@descript/kali";
+import {workerData} from "worker_threads";
+try{
+
+    let decodeAudio = await import('audio-decode')
+    let decoders = decodeAudio.decoders;
+    await decoders.mp3();
+
+    let decoded = await decoders.mp3(
+        workerData.binary
+    )
+
+
+
+    let kali = new Kali(1)
+    let samplerate = decoded.sampleRate / workerData.pitch
+    kali.setup(samplerate, workerData.pitch, true)
+    kali.input(decoded.getChannelData(workerData.channel))
+    kali.process()
+    let output = new Float32Array(samplerate * decoded.duration)
+    kali.output(output);
+    parentPort.postMessage({output, samplerate})
+}catch(err){
+    console.log(err)
+}
+
+

+ 48 - 53
main.js

@@ -1,14 +1,21 @@
-let argv = require('minimist')(process.argv.slice(2));
-const fs = require('fs');
-const express = require('express');
+import {Worker} from 'worker_threads'
+import Minimist from 'minimist'
+
+let argv = Minimist(process.argv.slice(2));
+import fs from 'fs';
+import express from 'express';
+import ffmpeg from 'fluent-ffmpeg';
+
 const app = express();
-const mysql = require('mysql2')
-const SendSeekable = require('send-seekable');
+import mysql from 'mysql2';
+import SendSeekable from 'send-seekable'
+
 const pool = mysql.createPool({
     keepAliveInitialDelay: 0, enableKeepAlive: true,
 })
-require('cnchar');
-require('sort-array');
+import 'cnchar'
+import 'sort-array'
+
 const Kind = {
     0: "去和声伴奏",
     1: "和声伴奏",
@@ -27,22 +34,26 @@ const db = mysql.createConnection({
     enableKeepAlive: true,
     keepAliveInitialDelay: 0,
 })
-const nodemailer = require('nodemailer')
-let Queue = require('js-queue');
+import nodemailer from 'nodemailer'
+import Queue from 'js-queue'
+
+
+import webp from 'webp-converter'
+
+import sortArray from "sort-array";
+
+import pkg from 'opencc'
+const {OpenCC} = pkg
+
+import https from "node:https";
+
+import nrc from "node-run-cmd";
+
+import bodyParser from "body-parser";
 
-const webp = require('webp-converter')
 webp.grant_permission()
 let queue = new Queue();
 queue.autoRun = false;
-
-const bodyParser = require("body-parser");
-const nrc = require('node-run-cmd')
-const https = require("node:https");
-const {OpenCC} = require("opencc");
-const {HttpsProxyAgent} = require("https-proxy-agent");
-const sortArray = require("sort-array");
-const Kali = require("@descript/kali");
-const WavEncoder = require("wav-encoder");
 const converters2t = new OpenCC('s2t.json')
 const convertert2s = new OpenCC('t2s.json')
 app.use(bodyParser.json({"limit": "200mb"}));
@@ -529,52 +540,36 @@ app.get('/:uuid', async function (req, res) {
     let uuid = req.params.uuid;
     let pitch = req.query.pitch;
 
-    async function Provider() {
+    async function Provider(b) {
 
         try {
 
             /** @type {ArrayBuffer}*/
-            if(!pitch){
+            if (!pitch) {
                 res.contentType("audio/mp3");
                 res.header("Access-Control-Allow-Origin", "*");
                 res.header("Access-Control-Allow-Headers", "Content-Type");
                 res.header('Content-Disposition', `attachment; filename="${encodeURI(availCache[uuid].song_name)}.mp3"`);
                 res.sendSeekable(availCache[uuid].databinary)
-            }else{
-                let decodeAudio = await import('audio-decode')
-                let decoders = decodeAudio.decoders;
-                await decoders.mp3();
-                let decoded = await decoders.mp3(availCache[uuid].databinary)
-                fs.writeFileSync('./test', decoded.getChannelData(0))
-                let Kali = require('@descript/kali')
-                let kali = new Kali(1)
-                let samplerate = decoded.sampleRate / pitch
-                kali.setup(samplerate, pitch, true)
-                kali.input(decoded.getChannelData(0))
-
-                kali.process()
-                let output = new Float32Array(samplerate * decoded.duration)
-                kali.output(output);
-
-
-                const WavEncoder = require('wav-encoder')
-                const prep = {
-                    sampleRate: samplerate,
-                    channelData: [
-                        output
-                    ]
-                }
-                let wavBuffer = await WavEncoder.encode(prep)
+            } else {
 
+                const worker = new Worker('./pitched.js', {
+                    workerData: {
+                        binary: availCache[uuid].databinary, pitch: pitch
+                    }
+                })
+
+
+                worker.on("message", message => {
+                    res.contentType("audio/wav");
+                    res.header("Access-Control-Allow-Origin", "*");
+                    res.header("Access-Control-Allow-Headers", "Content-Type");
+                    res.header("Access-Control-Allow-Origin", "*");
+                    res.sendSeekable(Buffer.from(message))
+                })
 
 
 
-                res.contentType("audio/wav");
-                res.header("Access-Control-Allow-Origin", "*");
-                res.header("Access-Control-Allow-Headers", "Content-Type");
-                res.header("Access-Control-Allow-Origin", "*");
-                res.header('Content-Disposition', `attachment; filename="${encodeURI(availCache[uuid].song_name)}.wav"`);
-                res.sendSeekable(Buffer.from(wavBuffer))
             }
 
 
@@ -593,7 +588,7 @@ app.get('/:uuid', async function (req, res) {
         await Provider();
 
     } else {
-        db.execute("SELECT song_name, databinary FROM instrunet_entry WHERE uuid = ?", [uuid], (err, rows)=>{
+        db.execute("SELECT song_name, databinary FROM instrunet_entry WHERE uuid = ?", [uuid], (err, rows) => {
             availCache[uuid] = rows[0]
             Provider()
         })

File diff suppressed because it is too large
+ 0 - 0
ogg/index.cjs


File diff suppressed because it is too large
+ 0 - 0
ogg/index.cjs.map


+ 831 - 0
ogg/index.es.js

@@ -0,0 +1,831 @@
+var n = typeof n < "u" ? n : {}, Y = Object.assign({}, n), $ = (e, t) => {
+  throw t;
+}, le = !0, ce = !1, ue = !1, de = !1;
+if (n.ENVIRONMENT)
+  throw new Error("Module.ENVIRONMENT has been deprecated. To force the environment, use the ENVIRONMENT compile-time option (for example, -sENVIRONMENT=web or -sENVIRONMENT=node)");
+var _ = "";
+function fe(e) {
+  return n.locateFile ? n.locateFile(e, _) : _ + e;
+}
+if (typeof document < "u" && document.currentScript && (_ = document.currentScript.src), _.indexOf("blob:") !== 0 ? _ = _.substr(0, _.replace(/[?#].*/, "").lastIndexOf("/") + 1) : _ = "", !(typeof window == "object" || typeof importScripts == "function"))
+  throw new Error("not compiled for this environment (did you build to HTML and try to run it not on the web, or set ENVIRONMENT to something - like node - and run it someplace else - like on the web?)");
+n.print || console.log.bind(console);
+var u = n.printErr || console.error.bind(console);
+Object.assign(n, Y);
+Y = null;
+Ve();
+n.arguments && n.arguments;
+y("arguments", "arguments_");
+n.thisProgram && n.thisProgram;
+y("thisProgram", "thisProgram");
+n.quit && ($ = n.quit);
+y("quit", "quit_");
+o(typeof n.memoryInitializerPrefixURL > "u", "Module.memoryInitializerPrefixURL option was removed, use Module.locateFile instead");
+o(typeof n.pthreadMainPrefixURL > "u", "Module.pthreadMainPrefixURL option was removed, use Module.locateFile instead");
+o(typeof n.cdInitializerPrefixURL > "u", "Module.cdInitializerPrefixURL option was removed, use Module.locateFile instead");
+o(typeof n.filePackagePrefixURL > "u", "Module.filePackagePrefixURL option was removed, use Module.locateFile instead");
+o(typeof n.read > "u", "Module.read option was removed (modify read_ in JS)");
+o(typeof n.readAsync > "u", "Module.readAsync option was removed (modify readAsync in JS)");
+o(typeof n.readBinary > "u", "Module.readBinary option was removed (modify readBinary in JS)");
+o(typeof n.setWindowTitle > "u", "Module.setWindowTitle option was removed (modify emscripten_set_window_title in JS)");
+o(typeof n.TOTAL_MEMORY > "u", "Module.TOTAL_MEMORY has been renamed Module.INITIAL_MEMORY");
+y("asm", "wasmExports");
+y("read", "read_");
+y("readAsync", "readAsync");
+y("readBinary", "readBinary");
+y("setWindowTitle", "setWindowTitle");
+o(!ce, "worker environment detected but not enabled at build time.  Add 'worker' to `-sENVIRONMENT` to enable.");
+o(!ue, "node environment detected but not enabled at build time.  Add 'node' to `-sENVIRONMENT` to enable.");
+o(!de, "shell environment detected but not enabled at build time.  Add 'shell' to `-sENVIRONMENT` to enable.");
+var I;
+n.wasmBinary && (I = n.wasmBinary);
+y("wasmBinary", "wasmBinary");
+typeof WebAssembly != "object" && p("no native wasm support detected");
+var P, C = !1;
+function o(e, t) {
+  e || p("Assertion failed" + (t ? ": " + t : ""));
+}
+var V, R, v;
+function me() {
+  var e = P.buffer;
+  n.HEAP8 = V = new Int8Array(e), n.HEAP16 = new Int16Array(e), n.HEAPU8 = R = new Uint8Array(e), n.HEAPU16 = new Uint16Array(e), n.HEAP32 = new Int32Array(e), n.HEAPU32 = v = new Uint32Array(e), n.HEAPF32 = new Float32Array(e), n.HEAPF64 = new Float64Array(e);
+}
+o(!n.STACK_SIZE, "STACK_SIZE can no longer be set at runtime.  Use -sSTACK_SIZE at link time");
+o(
+  typeof Int32Array < "u" && typeof Float64Array < "u" && Int32Array.prototype.subarray != null && Int32Array.prototype.set != null,
+  "JS engine does not provide full typed array support"
+);
+o(!n.wasmMemory, "Use of `wasmMemory` detected.  Use -sIMPORTED_MEMORY to define wasmMemory externally");
+o(!n.INITIAL_MEMORY, "Detected runtime INITIAL_MEMORY setting.  Use -sIMPORTED_MEMORY to define wasmMemory dynamically");
+function pe() {
+  var e = N();
+  o((e & 3) == 0), e == 0 && (e += 4), v[e >> 2] = 34821223, v[e + 4 >> 2] = 2310721022, v[0] = 1668509029;
+}
+function x() {
+  if (!C) {
+    var e = N();
+    e == 0 && (e += 4);
+    var t = v[e >> 2], r = v[e + 4 >> 2];
+    (t != 34821223 || r != 2310721022) && p(`Stack overflow! Stack cookie has been overwritten at ${A(e)}, expected hex dwords 0x89BACDFE and 0x2135467, but received ${A(r)} ${A(t)}`), v[0] != 1668509029 && p("Runtime error: The application has corrupted its heap memory area (address zero)!");
+  }
+}
+(function() {
+  var e = new Int16Array(1), t = new Int8Array(e.buffer);
+  if (e[0] = 25459, t[0] !== 115 || t[1] !== 99)
+    throw "Runtime error: expected the system to be little-endian! (Run with -sSUPPORT_BIG_ENDIAN to bypass)";
+})();
+var j = [], J = [], K = [], U = !1;
+function ge() {
+  if (n.preRun)
+    for (typeof n.preRun == "function" && (n.preRun = [n.preRun]); n.preRun.length; )
+      he(n.preRun.shift());
+  D(j);
+}
+function ye() {
+  o(!U), U = !0, x(), D(J);
+}
+function _e() {
+  if (x(), n.postRun)
+    for (typeof n.postRun == "function" && (n.postRun = [n.postRun]); n.postRun.length; )
+      Te(n.postRun.shift());
+  D(K);
+}
+function he(e) {
+  j.unshift(e);
+}
+function Ee(e) {
+  J.unshift(e);
+}
+function Te(e) {
+  K.unshift(e);
+}
+o(Math.imul, "This browser does not support Math.imul(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill");
+o(Math.fround, "This browser does not support Math.fround(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill");
+o(Math.clz32, "This browser does not support Math.clz32(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill");
+o(Math.trunc, "This browser does not support Math.trunc(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill");
+var b = 0, E = null, S = null, F = {};
+function ve(e) {
+  var t;
+  b++, (t = n.monitorRunDependencies) == null || t.call(n, b), e ? (o(!F[e]), F[e] = 1, E === null && typeof setInterval < "u" && (E = setInterval(() => {
+    if (C) {
+      clearInterval(E), E = null;
+      return;
+    }
+    var r = !1;
+    for (var i in F)
+      r || (r = !0, u("still waiting on run dependencies:")), u(`dependency: ${i}`);
+    r && u("(end of list)");
+  }, 1e4))) : u("warning: run dependency added without ID");
+}
+function be(e) {
+  var r;
+  if (b--, (r = n.monitorRunDependencies) == null || r.call(n, b), e ? (o(F[e]), delete F[e]) : u("warning: run dependency removed without ID"), b == 0 && (E !== null && (clearInterval(E), E = null), S)) {
+    var t = S;
+    S = null, t();
+  }
+}
+function p(e) {
+  var r;
+  (r = n.onAbort) == null || r.call(n, e), e = "Aborted(" + e + ")", u(e), C = !0;
+  var t = new WebAssembly.RuntimeError(e);
+  throw t;
+}
+var f = {
+  error() {
+    p("Filesystem support (FS) was not included. The problem is that you are using files from JS, but files were not used from C/C++, so filesystem support was not auto-included. You can force-include filesystem support with -sFORCE_FILESYSTEM");
+  },
+  init() {
+    f.error();
+  },
+  createDataFile() {
+    f.error();
+  },
+  createPreloadedFile() {
+    f.error();
+  },
+  createLazyFile() {
+    f.error();
+  },
+  open() {
+    f.error();
+  },
+  mkdev() {
+    f.error();
+  },
+  registerDevice() {
+    f.error();
+  },
+  analyzePath() {
+    f.error();
+  },
+  ErrnoError() {
+    f.error();
+  }
+};
+n.FS_createDataFile = f.createDataFile;
+n.FS_createPreloadedFile = f.createPreloadedFile;
+var we = "data:application/octet-stream;base64,", q = (e) => e.startsWith(we), Se = (e) => e.startsWith("file://");
+function g(e) {
+  return function() {
+    o(U, `native function \`${e}\` called before runtime initialization`);
+    var t = T[e];
+    return o(t, `exported native function \`${e}\` not found`), t.apply(null, arguments);
+  };
+}
+var h;
+h = "middle-layer.wasm";
+q(h) || (h = fe(h));
+function G(e) {
+  if (e == h && I)
+    return new Uint8Array(I);
+  throw "both async and sync fetching of the wasm failed";
+}
+function Fe(e) {
+  return !I && le && typeof fetch == "function" ? fetch(e, { credentials: "same-origin" }).then((t) => {
+    if (!t.ok)
+      throw "failed to load wasm binary file at '" + e + "'";
+    return t.arrayBuffer();
+  }).catch(() => G(e)) : Promise.resolve().then(() => G(e));
+}
+function W(e, t, r) {
+  return Fe(e).then((i) => WebAssembly.instantiate(i, t)).then((i) => i).then(r, (i) => {
+    u(`failed to asynchronously prepare wasm: ${i}`), Se(h) && u(`warning: Loading from a file URI (${h}) is not supported in most browsers. See https://emscripten.org/docs/getting_started/FAQ.html#how-do-i-run-a-local-webserver-for-testing-why-does-my-program-stall-in-downloading-or-preparing`), p(i);
+  });
+}
+function Ae(e, t, r, i) {
+  return !e && typeof WebAssembly.instantiateStreaming == "function" && !q(t) && typeof fetch == "function" ? fetch(t, { credentials: "same-origin" }).then((a) => {
+    var c = WebAssembly.instantiateStreaming(a, r);
+    return c.then(
+      i,
+      function(s) {
+        return u(`wasm streaming compile failed: ${s}`), u("falling back to ArrayBuffer instantiation"), W(t, r, i);
+      }
+    );
+  }) : W(t, r, i);
+}
+function Ie() {
+  var e = {
+    env: z,
+    wasi_snapshot_preview1: z
+  };
+  function t(a, c) {
+    return T = a.exports, P = T.memory, o(P, "memory not found in wasm exports"), me(), Ee(T.__wasm_call_ctors), be("wasm-instantiate"), T;
+  }
+  ve("wasm-instantiate");
+  var r = n;
+  function i(a) {
+    o(n === r, "the Module object should not be replaced during async compilation - perhaps the order of HTML elements is wrong?"), r = null, t(a.instance);
+  }
+  if (n.instantiateWasm)
+    try {
+      return n.instantiateWasm(e, t);
+    } catch (a) {
+      return u(`Module.instantiateWasm callback failed with error: ${a}`), !1;
+    }
+  return Ae(I, h, e, i), {};
+}
+function y(e, t, r = !0) {
+  Object.getOwnPropertyDescriptor(n, e) || Object.defineProperty(n, e, {
+    configurable: !0,
+    get() {
+      let i = r ? " (the initial value can be provided on Module, but after startup the value is only looked for on a local variable of that name)" : "";
+      p(`\`Module.${e}\` has been replaced by \`${t}\`` + i);
+    }
+  });
+}
+function Ce(e) {
+  Object.getOwnPropertyDescriptor(n, e) && p(`\`Module.${e}\` was supplied but \`${e}\` not included in INCOMING_MODULE_JS_API`);
+}
+function Z(e) {
+  return e === "FS_createPath" || e === "FS_createDataFile" || e === "FS_createPreloadedFile" || e === "FS_unlink" || e === "addRunDependency" || // The old FS has some functionality that WasmFS lacks.
+  e === "FS_createLazyFile" || e === "FS_createDevice" || e === "removeRunDependency";
+}
+function X(e, t) {
+  typeof globalThis < "u" && Object.defineProperty(globalThis, e, {
+    configurable: !0,
+    get() {
+      m(`\`${e}\` is not longer defined by emscripten. ${t}`);
+    }
+  });
+}
+X("buffer", "Please use HEAP8.buffer or wasmMemory.buffer");
+X("asm", "Please use wasmExports instead");
+function Re(e) {
+  typeof globalThis < "u" && !Object.getOwnPropertyDescriptor(globalThis, e) && Object.defineProperty(globalThis, e, {
+    configurable: !0,
+    get() {
+      var t = `\`${e}\` is a library symbol and not included by default; add it to your library.js __deps or to DEFAULT_LIBRARY_FUNCS_TO_INCLUDE on the command line`, r = e;
+      r.startsWith("_") || (r = "$" + e), t += ` (e.g. -sDEFAULT_LIBRARY_FUNCS_TO_INCLUDE='${r}')`, Z(e) && (t += ". Alternatively, forcing filesystem support (-sFORCE_FILESYSTEM) can export this for you"), m(t);
+    }
+  }), Q(e);
+}
+function Q(e) {
+  Object.getOwnPropertyDescriptor(n, e) || Object.defineProperty(n, e, {
+    configurable: !0,
+    get() {
+      var t = `'${e}' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the Emscripten FAQ)`;
+      Z(e) && (t += ". Alternatively, forcing filesystem support (-sFORCE_FILESYSTEM) can export this for you"), p(t);
+    }
+  });
+}
+function Oe(e) {
+  this.name = "ExitStatus", this.message = `Program terminated with exit(${e})`, this.status = e;
+}
+var D = (e) => {
+  for (; e.length > 0; )
+    e.shift()(n);
+}, Me = n.noExitRuntime || !0, A = (e) => (o(typeof e == "number"), e >>>= 0, "0x" + e.toString(16).padStart(8, "0")), m = (e) => {
+  m.shown || (m.shown = {}), m.shown[e] || (m.shown[e] = 1, u(e));
+}, Le = () => Date.now(), Pe = (e, t, r) => R.copyWithin(e, t, t + r), Ue = (e) => {
+  p(`Cannot enlarge memory arrays to size ${e} bytes (OOM). Either (1) compile with -sINITIAL_MEMORY=X with X higher than the current value ${V.length}, (2) compile with -sALLOW_MEMORY_GROWTH which allows increasing the size at runtime, or (3) if you want malloc to return NULL (0) instead of this abort, compile with -sABORTING_MALLOC=0`);
+}, xe = (e) => {
+  R.length, e >>>= 0, Ue(e);
+}, ee = 0, te = () => Me || ee > 0, H = typeof TextDecoder < "u" ? new TextDecoder("utf8") : void 0, De = (e, t, r) => {
+  for (var i = t + r, a = t; e[a] && !(a >= i); )
+    ++a;
+  if (a - t > 16 && e.buffer && H)
+    return H.decode(e.subarray(t, a));
+  for (var c = ""; t < a; ) {
+    var s = e[t++];
+    if (!(s & 128)) {
+      c += String.fromCharCode(s);
+      continue;
+    }
+    var l = e[t++] & 63;
+    if ((s & 224) == 192) {
+      c += String.fromCharCode((s & 31) << 6 | l);
+      continue;
+    }
+    var d = e[t++] & 63;
+    if ((s & 240) == 224 ? s = (s & 15) << 12 | l << 6 | d : ((s & 248) != 240 && m("Invalid UTF-8 leading byte " + A(s) + " encountered when deserializing a UTF-8 string in wasm memory to a JS string!"), s = (s & 7) << 18 | l << 12 | d << 6 | e[t++] & 63), s < 65536)
+      c += String.fromCharCode(s);
+    else {
+      var w = s - 65536;
+      c += String.fromCharCode(55296 | w >> 10, 56320 | w & 1023);
+    }
+  }
+  return c;
+}, Ne = (e, t) => (o(typeof e == "number", `UTF8ToString expects a number (got ${typeof e})`), e ? De(R, e, t) : ""), ke = (e) => {
+  var t;
+  te() || ((t = n.onExit) == null || t.call(n, e), C = !0), $(e, new Oe(e));
+}, Be = (e, t) => {
+  if (Xe(), te() && !t) {
+    var r = `program exited (with status: ${e}), but keepRuntimeAlive() is set (counter=${ee}) due to an async operation, so halting execution but not exiting the runtime or preventing further async execution (you can use emscripten_force_exit, if you want to force a true shutdown)`;
+    u(r);
+  }
+  ke(e);
+}, Ge = Be, We = (e) => {
+  for (var t = 0, r = 0; r < e.length; ++r) {
+    var i = e.charCodeAt(r);
+    i <= 127 ? t++ : i <= 2047 ? t += 2 : i >= 55296 && i <= 57343 ? (t += 4, ++r) : t += 3;
+  }
+  return t;
+}, He = (e, t, r, i) => {
+  if (o(typeof e == "string", `stringToUTF8Array expects a string (got ${typeof e})`), !(i > 0))
+    return 0;
+  for (var a = r, c = r + i - 1, s = 0; s < e.length; ++s) {
+    var l = e.charCodeAt(s);
+    if (l >= 55296 && l <= 57343) {
+      var d = e.charCodeAt(++s);
+      l = 65536 + ((l & 1023) << 10) | d & 1023;
+    }
+    if (l <= 127) {
+      if (r >= c)
+        break;
+      t[r++] = l;
+    } else if (l <= 2047) {
+      if (r + 1 >= c)
+        break;
+      t[r++] = 192 | l >> 6, t[r++] = 128 | l & 63;
+    } else if (l <= 65535) {
+      if (r + 2 >= c)
+        break;
+      t[r++] = 224 | l >> 12, t[r++] = 128 | l >> 6 & 63, t[r++] = 128 | l & 63;
+    } else {
+      if (r + 3 >= c)
+        break;
+      l > 1114111 && m("Invalid Unicode code point " + A(l) + " encountered when serializing a JS string to a UTF-8 string in wasm memory! (Valid unicode code points should be in range 0-0x10FFFF)."), t[r++] = 240 | l >> 18, t[r++] = 128 | l >> 12 & 63, t[r++] = 128 | l >> 6 & 63, t[r++] = 128 | l & 63;
+    }
+  }
+  return t[r] = 0, r - a;
+}, ze = (e, t, r) => (o(typeof r == "number", "stringToUTF8(str, outPtr, maxBytesToWrite) is missing the third parameter that specifies the length of the output buffer!"), He(e, R, t, r)), Ye = (e) => {
+  var t = We(e) + 1, r = je(t);
+  return r && ze(e, r, t), r;
+}, $e = Ye;
+function Ve() {
+  Ce("fetchSettings");
+}
+var z = {
+  /** @export */
+  emscripten_date_now: Le,
+  /** @export */
+  emscripten_memcpy_js: Pe,
+  /** @export */
+  emscripten_resize_heap: xe,
+  /** @export */
+  exit: Ge
+}, T = Ie(), je = n._malloc = g("malloc");
+n._free = g("free");
+n._initEncoder = g("initEncoder");
+n._clearEncoder = g("clearEncoder");
+n._createAnalysisBuffer = g("createAnalysisBuffer");
+n._processEncoding = g("processEncoding");
+n._getEncodedDataLen = g("getEncodedDataLen");
+n._transferEncodedData = g("transferEncodedData");
+n._decodeComments = g("decodeComments");
+var Je = n._fflush = g("fflush"), ne = () => (ne = T.emscripten_stack_init)(), N = () => (N = T.emscripten_stack_get_end)();
+n.UTF8ToString = Ne;
+n.allocateUTF8 = $e;
+var Ke = [
+  "writeI53ToI64",
+  "writeI53ToI64Clamped",
+  "writeI53ToI64Signaling",
+  "writeI53ToU64Clamped",
+  "writeI53ToU64Signaling",
+  "readI53FromI64",
+  "readI53FromU64",
+  "convertI32PairToI53",
+  "convertI32PairToI53Checked",
+  "convertU32PairToI53",
+  "zeroMemory",
+  "growMemory",
+  "isLeapYear",
+  "ydayFromDate",
+  "arraySum",
+  "addDays",
+  "setErrNo",
+  "inetPton4",
+  "inetNtop4",
+  "inetPton6",
+  "inetNtop6",
+  "readSockaddr",
+  "writeSockaddr",
+  "getHostByName",
+  "initRandomFill",
+  "randomFill",
+  "getCallstack",
+  "emscriptenLog",
+  "convertPCtoSourceLocation",
+  "readEmAsmArgs",
+  "jstoi_q",
+  "jstoi_s",
+  "getExecutableName",
+  "listenOnce",
+  "autoResumeAudioContext",
+  "dynCallLegacy",
+  "getDynCaller",
+  "dynCall",
+  "handleException",
+  "runtimeKeepalivePush",
+  "runtimeKeepalivePop",
+  "callUserCallback",
+  "maybeExit",
+  "asmjsMangle",
+  "asyncLoad",
+  "alignMemory",
+  "mmapAlloc",
+  "handleAllocatorInit",
+  "HandleAllocator",
+  "getNativeTypeSize",
+  "STACK_SIZE",
+  "STACK_ALIGN",
+  "POINTER_SIZE",
+  "ASSERTIONS",
+  "getCFunc",
+  "ccall",
+  "cwrap",
+  "uleb128Encode",
+  "sigToWasmTypes",
+  "generateFuncType",
+  "convertJsFunctionToWasm",
+  "getEmptyTableSlot",
+  "updateTableMap",
+  "getFunctionAddress",
+  "addFunction",
+  "removeFunction",
+  "reallyNegative",
+  "unSign",
+  "strLen",
+  "reSign",
+  "formatString",
+  "intArrayFromString",
+  "intArrayToString",
+  "AsciiToString",
+  "stringToAscii",
+  "UTF16ToString",
+  "stringToUTF16",
+  "lengthBytesUTF16",
+  "UTF32ToString",
+  "stringToUTF32",
+  "lengthBytesUTF32",
+  "stringToUTF8OnStack",
+  "writeArrayToMemory",
+  "registerKeyEventCallback",
+  "maybeCStringToJsString",
+  "findEventTarget",
+  "findCanvasEventTarget",
+  "getBoundingClientRect",
+  "fillMouseEventData",
+  "registerMouseEventCallback",
+  "registerWheelEventCallback",
+  "registerUiEventCallback",
+  "registerFocusEventCallback",
+  "fillDeviceOrientationEventData",
+  "registerDeviceOrientationEventCallback",
+  "fillDeviceMotionEventData",
+  "registerDeviceMotionEventCallback",
+  "screenOrientation",
+  "fillOrientationChangeEventData",
+  "registerOrientationChangeEventCallback",
+  "fillFullscreenChangeEventData",
+  "registerFullscreenChangeEventCallback",
+  "JSEvents_requestFullscreen",
+  "JSEvents_resizeCanvasForFullscreen",
+  "registerRestoreOldStyle",
+  "hideEverythingExceptGivenElement",
+  "restoreHiddenElements",
+  "setLetterbox",
+  "softFullscreenResizeWebGLRenderTarget",
+  "doRequestFullscreen",
+  "fillPointerlockChangeEventData",
+  "registerPointerlockChangeEventCallback",
+  "registerPointerlockErrorEventCallback",
+  "requestPointerLock",
+  "fillVisibilityChangeEventData",
+  "registerVisibilityChangeEventCallback",
+  "registerTouchEventCallback",
+  "fillGamepadEventData",
+  "registerGamepadEventCallback",
+  "disableGamepadApiIfItThrows",
+  "registerBeforeUnloadEventCallback",
+  "fillBatteryEventData",
+  "battery",
+  "registerBatteryEventCallback",
+  "setCanvasElementSize",
+  "getCanvasElementSize",
+  "demangle",
+  "demangleAll",
+  "jsStackTrace",
+  "stackTrace",
+  "getEnvStrings",
+  "checkWasiClock",
+  "flush_NO_FILESYSTEM",
+  "wasiRightsToMuslOFlags",
+  "wasiOFlagsToMuslOFlags",
+  "createDyncallWrapper",
+  "safeSetTimeout",
+  "setImmediateWrapped",
+  "clearImmediateWrapped",
+  "polyfillSetImmediate",
+  "getPromise",
+  "makePromise",
+  "idsToPromises",
+  "makePromiseCallback",
+  "ExceptionInfo",
+  "findMatchingCatch",
+  "Browser_asyncPrepareDataCounter",
+  "setMainLoop",
+  "getSocketFromFD",
+  "getSocketAddress",
+  "FS_createPreloadedFile",
+  "FS_modeStringToFlags",
+  "FS_getMode",
+  "FS_stdin_getChar",
+  "FS_createDataFile",
+  "FS_unlink",
+  "FS_mkdirTree",
+  "_setNetworkCallback",
+  "heapObjectForWebGLType",
+  "heapAccessShiftForWebGLHeap",
+  "webgl_enable_ANGLE_instanced_arrays",
+  "webgl_enable_OES_vertex_array_object",
+  "webgl_enable_WEBGL_draw_buffers",
+  "webgl_enable_WEBGL_multi_draw",
+  "emscriptenWebGLGet",
+  "computeUnpackAlignedImageSize",
+  "colorChannelsInGlTextureFormat",
+  "emscriptenWebGLGetTexPixelData",
+  "__glGenObject",
+  "emscriptenWebGLGetUniform",
+  "webglGetUniformLocation",
+  "webglPrepareUniformLocationsBeforeFirstUse",
+  "webglGetLeftBracePos",
+  "emscriptenWebGLGetVertexAttrib",
+  "__glGetActiveAttribOrUniform",
+  "writeGLArray",
+  "registerWebGlEventCallback",
+  "runAndAbortIfError",
+  "SDL_unicode",
+  "SDL_ttfContext",
+  "SDL_audio",
+  "ALLOC_NORMAL",
+  "ALLOC_STACK",
+  "allocate",
+  "writeStringToMemory",
+  "writeAsciiToMemory"
+];
+Ke.forEach(Re);
+var qe = [
+  "run",
+  "addOnPreRun",
+  "addOnInit",
+  "addOnPreMain",
+  "addOnExit",
+  "addOnPostRun",
+  "addRunDependency",
+  "removeRunDependency",
+  "FS_createFolder",
+  "FS_createPath",
+  "FS_createLazyFile",
+  "FS_createLink",
+  "FS_createDevice",
+  "FS_readFile",
+  "out",
+  "err",
+  "callMain",
+  "abort",
+  "wasmMemory",
+  "wasmExports",
+  "stackAlloc",
+  "stackSave",
+  "stackRestore",
+  "getTempRet0",
+  "setTempRet0",
+  "writeStackCookie",
+  "checkStackCookie",
+  "ptrToString",
+  "exitJS",
+  "getHeapMax",
+  "abortOnCannotGrowMemory",
+  "ENV",
+  "MONTH_DAYS_REGULAR",
+  "MONTH_DAYS_LEAP",
+  "MONTH_DAYS_REGULAR_CUMULATIVE",
+  "MONTH_DAYS_LEAP_CUMULATIVE",
+  "ERRNO_CODES",
+  "ERRNO_MESSAGES",
+  "DNS",
+  "Protocols",
+  "Sockets",
+  "timers",
+  "warnOnce",
+  "UNWIND_CACHE",
+  "readEmAsmArgsArray",
+  "keepRuntimeAlive",
+  "wasmTable",
+  "noExitRuntime",
+  "freeTableIndexes",
+  "functionsInTableMap",
+  "setValue",
+  "getValue",
+  "PATH",
+  "PATH_FS",
+  "UTF8Decoder",
+  "UTF8ArrayToString",
+  "stringToUTF8Array",
+  "stringToUTF8",
+  "lengthBytesUTF8",
+  "UTF16Decoder",
+  "stringToNewUTF8",
+  "JSEvents",
+  "specialHTMLTargets",
+  "currentFullscreenStrategy",
+  "restoreOldWindowedStyle",
+  "ExitStatus",
+  "promiseMap",
+  "uncaughtExceptionCount",
+  "exceptionLast",
+  "exceptionCaught",
+  "Browser",
+  "wget",
+  "SYSCALLS",
+  "preloadPlugins",
+  "FS_stdin_getChar_buffer",
+  "FS",
+  "MEMFS",
+  "TTY",
+  "PIPEFS",
+  "SOCKFS",
+  "tempFixedLengthArray",
+  "miniTempWebGLFloatBuffers",
+  "miniTempWebGLIntBuffers",
+  "GL",
+  "emscripten_webgl_power_preferences",
+  "AL",
+  "GLUT",
+  "EGL",
+  "GLEW",
+  "IDBStore",
+  "SDL",
+  "SDL_gfx",
+  "allocateUTF8OnStack"
+];
+qe.forEach(Q);
+var L;
+S = function e() {
+  L || re(), L || (S = e);
+};
+function Ze() {
+  ne(), pe();
+}
+function re() {
+  if (b > 0 || (Ze(), ge(), b > 0))
+    return;
+  function e() {
+    L || (L = !0, n.calledRun = !0, !C && (ye(), n.onRuntimeInitialized && n.onRuntimeInitialized(), o(!n._main, 'compiled without a main, but one is present. if you added it from JS, use Module["onRuntimeInitialized"]'), _e()));
+  }
+  n.setStatus ? (n.setStatus("Running..."), setTimeout(function() {
+    setTimeout(function() {
+      n.setStatus("");
+    }, 1), e();
+  }, 1)) : e(), x();
+}
+function Xe() {
+  var e = u, t = !1;
+  u = (r) => {
+    t = !0;
+  };
+  try {
+    Je(0);
+  } catch {
+  }
+  u = e, t && (m("stdio streams had content in them that was not flushed. you should set EXIT_RUNTIME to 1 (see the Emscripten FAQ), or make sure to emit a newline when you printf etc."), m("(this may also be due to not including full filesystem support - try building with -sFORCE_FILESYSTEM)"));
+}
+if (n.preInit)
+  for (typeof n.preInit == "function" && (n.preInit = [n.preInit]); n.preInit.length > 0; )
+    n.preInit.pop()();
+re();
+n.preRun = () => n._isInitialized = !1;
+n.postRun = () => n._isInitialized = !0;
+n.ANALYSIS_SAMPLE_COUNT = 8192;
+function Qe(e, t) {
+  if (!e.length)
+    return null;
+  e.forEach((a) => {
+    if (a.name.indexOf("=") !== -1)
+      throw Error(`Tag name "${a.name}" contains reserved character "="`);
+    if (a.name.indexOf("	") !== -1)
+      throw Error(`Tag name "${a.name}" contains reserved character (tab)`);
+    if (a.value.indexOf("	") !== -1)
+      throw Error(`Tag value "${a.value}" contains reserved character (tab)`);
+  });
+  const i = e.map((a) => `${a.name}=${a.value}`).join("	");
+  return t.allocateUTF8(i);
+}
+function et(e, t) {
+  if (e === null)
+    return [];
+  const r = t.UTF8ToString(e);
+  return r === "" ? [] : r.split("	").map((a) => {
+    const c = a.indexOf("=");
+    return c === -1 ? { name: a, value: "" } : {
+      name: a.slice(0, c),
+      value: a.slice(c + 1)
+    };
+  });
+}
+const M = {
+  quality: 0.5,
+  tags: []
+}, { _clearEncoder: tt, _createAnalysisBuffer: nt, _decodeComments: rt, _initEncoder: it, _processEncoding: at, _getEncodedDataLen: ot, _transferEncodedData: st, ANALYSIS_SAMPLE_COUNT: lt } = n;
+let O = null;
+async function ie() {
+  if (!n._isInitialized) {
+    if (n._isInitialized === void 0)
+      throw Error("Unexpected behavior from middle-layer.js import.");
+    return O !== null ? await O : (O = new Promise((e) => {
+      n.onRuntimeInitialized = e();
+    }), O);
+  }
+}
+function ct(e, t, r) {
+  const i = e.numberOfChannels, a = e.sampleRate;
+  return it(i, a, t, r);
+}
+function ut(e) {
+  const t = e.numberOfChannels, r = [];
+  for (let i = 0; i < t; ++i)
+    r[i] = e.getChannelData(i);
+  return r;
+}
+function ae(e, t) {
+  at(e, t);
+  const r = ot(e);
+  if (r === 0)
+    return new Uint8Array(0);
+  const i = st(e);
+  return new Uint8Array(n.HEAPU8.subarray(i, i + r));
+}
+function dt(e, t, r, i, a) {
+  if (a === null)
+    throw Error("Unexpected");
+  const c = r + i;
+  for (let s = 0; s < t.length; ++s) {
+    const l = t[s], d = n.HEAPU32[a + s] >> 2;
+    n.HEAPF32.set(l.subarray(r, c), d);
+  }
+  return ae(e, i);
+}
+function ft() {
+  return new Promise((e) => setTimeout(e, 0));
+}
+function mt(e) {
+  return ae(e, 0);
+}
+function pt(e) {
+  if (e === M)
+    return M;
+  const t = { ...M }, r = e;
+  for (const i in e)
+    r[i] !== void 0 && (t[i] = r[i]);
+  return t;
+}
+async function oe(e, t) {
+  return await (t ?? new AudioContext()).decodeAudioData(e);
+}
+function gt(e) {
+  let t = null, r = null;
+  try {
+    const i = new Uint8Array(e);
+    return t = n._malloc(i.length), n.HEAPU8.set(i, t), r = rt(t, i.length), et(r, n);
+  } finally {
+    r !== null && n._free(r), t !== null && n._free(t);
+  }
+}
+async function yt(e, t = M) {
+  let r = null;
+  const i = [], a = pt(t);
+  let c = null;
+  try {
+    await ie(), c = Qe(a.tags, n);
+    const s = e.length;
+    r = ct(e, a.quality, c);
+    const l = ut(e);
+    let d = 0;
+    if (r === null)
+      throw Error("Unexpected");
+    for (; d < s; ) {
+      const se = nt(r) >> 2, k = Math.min(lt, s - d), B = dt(r, l, d, k, se);
+      B.length && i.push(B), d += k, await ft();
+    }
+    const w = mt(r);
+    return w.length && i.push(w), new Blob(i, { type: "audio/ogg" });
+  } finally {
+    r !== null && tt(r), c !== null && n._free(c);
+  }
+}
+async function _t(e, t) {
+  const r = await e.arrayBuffer();
+  return await oe(r, t);
+}
+async function ht(e, t) {
+  await ie();
+  const r = await e.arrayBuffer(), i = gt(r);
+  return [await oe(r, t), i];
+}
+export {
+  _t as decodeOggBlob,
+  ht as decodeOggBlobWithTags,
+  yt as encodeAudioBuffer
+};
+//# sourceMappingURL=index.es.js.map

File diff suppressed because it is too large
+ 0 - 0
ogg/index.es.js.map


+ 42 - 3
package-lock.json

@@ -10,10 +10,13 @@
       "license": "MIT",
       "dependencies": {
         "@descript/kali": "^0.0.7",
+        "@nikhilbadveli/custom-ogg-encoder": "^1.0.1",
+        "audio-buffer": "^5.0.0",
         "audio-decode": "^2.2.2",
         "body-parser": "^1.20.3",
         "cnchar": "^3.2.6",
         "express": "^4.21.1",
+        "fluent-ffmpeg": "^2.1.3",
         "html-entities": "^2.5.2",
         "https": "^1.0.0",
         "https-proxy-agent": "^7.0.6",
@@ -146,6 +149,12 @@
         "set-blocking": "^2.0.0"
       }
     },
+    "node_modules/@nikhilbadveli/custom-ogg-encoder": {
+      "version": "1.0.1",
+      "resolved": "https://registry.npmjs.org/@nikhilbadveli/custom-ogg-encoder/-/custom-ogg-encoder-1.0.1.tgz",
+      "integrity": "sha512-Ophhr+DJFwJNmZN+6RJ+G1triSAgL5BaWFvMIn38UvTa4gdiv9mW90DkY+0QKE1OdptRq76BzGRhonydHLlKvA==",
+      "license": "MIT"
+    },
     "node_modules/@npmcli/fs": {
       "version": "1.1.1",
       "resolved": "https://registry.npmjs.org/@npmcli/fs/-/fs-1.1.1.tgz",
@@ -376,10 +385,16 @@
       "integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==",
       "license": "MIT"
     },
+    "node_modules/async": {
+      "version": "0.2.10",
+      "resolved": "https://registry.npmjs.org/async/-/async-0.2.10.tgz",
+      "integrity": "sha512-eAkdoKxU6/LkKDBzLpT+t6Ff5EtfSF4wx1WfJiPEEV7WNLnDaRXk0oVysiEPm262roaachGexwUv94WhSgN5TQ=="
+    },
     "node_modules/audio-buffer": {
       "version": "5.0.0",
       "resolved": "https://registry.npmjs.org/audio-buffer/-/audio-buffer-5.0.0.tgz",
-      "integrity": "sha512-gsDyj1wwUp8u7NBB+eW6yhLb9ICf+0eBmDX8NGaAS00w8/fLqFdxUlL5Ge/U8kB64DlQhdonxYC59dXy1J7H/w=="
+      "integrity": "sha512-gsDyj1wwUp8u7NBB+eW6yhLb9ICf+0eBmDX8NGaAS00w8/fLqFdxUlL5Ge/U8kB64DlQhdonxYC59dXy1J7H/w==",
+      "license": "MIT"
     },
     "node_modules/audio-decode": {
       "version": "2.2.2",
@@ -1011,6 +1026,31 @@
       "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==",
       "license": "MIT"
     },
+    "node_modules/fluent-ffmpeg": {
+      "version": "2.1.3",
+      "resolved": "https://registry.npmjs.org/fluent-ffmpeg/-/fluent-ffmpeg-2.1.3.tgz",
+      "integrity": "sha512-Be3narBNt2s6bsaqP6Jzq91heDgOEaDCJAXcE3qcma/EJBSy5FB4cvO31XBInuAuKBx8Kptf8dkhjK0IOru39Q==",
+      "license": "MIT",
+      "dependencies": {
+        "async": "^0.2.9",
+        "which": "^1.1.1"
+      },
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/fluent-ffmpeg/node_modules/which": {
+      "version": "1.3.1",
+      "resolved": "https://registry.npmjs.org/which/-/which-1.3.1.tgz",
+      "integrity": "sha512-HxJdYWq1MTIQbJ3nw0cqssHoTNU267KlrDuGZ1WYlxDStUtKUhOaJmh112/TZmHxxUfuJqPXSOm7tDyas0OSIQ==",
+      "license": "ISC",
+      "dependencies": {
+        "isexe": "^2.0.0"
+      },
+      "bin": {
+        "which": "bin/which"
+      }
+    },
     "node_modules/forwarded": {
       "version": "0.2.0",
       "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz",
@@ -1445,8 +1485,7 @@
       "version": "2.0.0",
       "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",
       "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",
-      "license": "ISC",
-      "optional": true
+      "license": "ISC"
     },
     "node_modules/js-queue": {
       "version": "2.0.2",

+ 4 - 0
package.json

@@ -1,4 +1,5 @@
 {
+  "type": "module",
   "name": "instrunet_backend",
   "version": "1.0.0",
   "main": "main.js",
@@ -13,10 +14,13 @@
   "description": "",
   "dependencies": {
     "@descript/kali": "^0.0.7",
+    "@nikhilbadveli/custom-ogg-encoder": "^1.0.1",
+    "audio-buffer": "^5.0.0",
     "audio-decode": "^2.2.2",
     "body-parser": "^1.20.3",
     "cnchar": "^3.2.6",
     "express": "^4.21.1",
+    "fluent-ffmpeg": "^2.1.3",
     "html-entities": "^2.5.2",
     "https": "^1.0.0",
     "https-proxy-agent": "^7.0.6",

+ 43 - 0
pitched.js

@@ -0,0 +1,43 @@
+import {parentPort, workerData, Worker} from "worker_threads";
+import WavEncoder from "wav-encoder";
+
+
+// TODO: Possible optimization in the future.
+function createWorker(c){
+    return new Promise((resolve, reject) => {
+        const c0 = new Worker('./c0.js', {
+            workerData: {
+                pitch: Number(workerData.pitch),
+                binary: workerData.binary,
+                channel: c
+            }
+        })
+
+        c0.on("message", (worker) => {
+            resolve(worker);
+        })
+        c0.on("error", (err) => {
+            console.error(err);
+            reject(err);
+        })
+    })
+}
+
+try{
+
+
+
+    const res = await Promise.all([createWorker(0), createWorker(1)]);
+
+    const prep = {
+        sampleRate: res[0].samplerate,
+        channelData: [
+            res[0].output, res[1].output
+        ]
+    }
+    let wavBuffer = await WavEncoder.encode(prep)
+    parentPort.postMessage(wavBuffer)
+}catch(e){
+    console.error(e)
+}
+

Some files were not shown because too many files changed in this diff