Implement module player
Ported and heavily modified from Puniko's FoundKey branch.
This commit is contained in:
parent
37f08826d1
commit
c6d1adc4b2
9 changed files with 914 additions and 2 deletions
3
.gitignore
vendored
3
.gitignore
vendored
|
@ -8,6 +8,9 @@ packages/backend/.idea/backend.iml
|
|||
packages/backend/.idea/modules.xml
|
||||
packages/backend/.idea/vcs.xml
|
||||
|
||||
# vimlocal
|
||||
.vimlocal
|
||||
|
||||
# Node.js
|
||||
node_modules
|
||||
report.*.json
|
||||
|
|
8
COPYING
8
COPYING
|
@ -18,3 +18,11 @@ https://github.com/transmute-industries/RsaSignature2017/blob/master/LICENSE
|
|||
Machine learning model for sensitive images by Infinite Red, Inc.
|
||||
License: MIT
|
||||
https://github.com/infinitered/nsfwjs/blob/master/LICENSE
|
||||
|
||||
Chiptune2.js by Simon Gündling
|
||||
License: MIT
|
||||
https://github.com/deskjet/chiptune2.js#license
|
||||
|
||||
libopenmpt (as part of openmpt) by OpenMPT
|
||||
License: BSD 3-Clause
|
||||
https://github.com/OpenMPT/openmpt/blob/master/LICENSE
|
||||
|
|
|
@ -430,7 +430,7 @@ router.get("/notes/:note", async (ctx, next) => {
|
|||
ctx.set("Cache-Control", "public, max-age=15");
|
||||
ctx.set(
|
||||
"Content-Security-Policy",
|
||||
"default-src 'self' 'unsafe-inline'; img-src *; frame-ancestors *",
|
||||
"default-src 'self' 'unsafe-inline' 'unsafe-eval'; connect-src *; font-src 'self' data:; img-src *; media-src *; worker-src 'self'; frame-ancestors *",
|
||||
);
|
||||
|
||||
return;
|
||||
|
|
1
packages/client/assets/libopenmpt.js
Normal file
1
packages/client/assets/libopenmpt.js
Normal file
File diff suppressed because one or more lines are too long
BIN
packages/client/assets/libopenmpt.wasm
Executable file
BIN
packages/client/assets/libopenmpt.wasm
Executable file
Binary file not shown.
|
@ -30,6 +30,11 @@
|
|||
:image="media"
|
||||
:raw="raw"
|
||||
/>
|
||||
<XModPlayer
|
||||
v-else-if="isModule(media)"
|
||||
:key="media.id"
|
||||
:module="media"
|
||||
/>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
|
@ -45,8 +50,13 @@ import "photoswipe/style.css";
|
|||
import XBanner from "@/components/MkMediaBanner.vue";
|
||||
import XImage from "@/components/MkMediaImage.vue";
|
||||
import XVideo from "@/components/MkMediaVideo.vue";
|
||||
import XModPlayer from "@/components/MkModPlayer.vue";
|
||||
import * as os from "@/os";
|
||||
import { FILE_TYPE_BROWSERSAFE } from "@/const";
|
||||
import {
|
||||
FILE_TYPE_BROWSERSAFE,
|
||||
FILE_TYPE_TRACKER_MODULES,
|
||||
FILE_EXT_TRACKER_MODULES,
|
||||
} from "@/const";
|
||||
import { defaultStore } from "@/store";
|
||||
|
||||
const props = defineProps<{
|
||||
|
@ -181,11 +191,24 @@ onMounted(() => {
|
|||
const previewable = (file: misskey.entities.DriveFile): boolean => {
|
||||
if (file.type === "image/svg+xml") return true; // svgのwebpublic/thumbnailはpngなのでtrue
|
||||
// FILE_TYPE_BROWSERSAFEに適合しないものはブラウザで表示するのに不適切
|
||||
if (isModule(file)) return true;
|
||||
return (
|
||||
(file.type.startsWith("video") || file.type.startsWith("image")) &&
|
||||
FILE_TYPE_BROWSERSAFE.includes(file.type)
|
||||
);
|
||||
};
|
||||
|
||||
const isModule = (file: misskey.entities.DriveFile): boolean => {
|
||||
return (
|
||||
FILE_TYPE_TRACKER_MODULES.some((type) => {
|
||||
return file.type === type;
|
||||
}) ||
|
||||
FILE_EXT_TRACKER_MODULES.some((ext) => {
|
||||
return file.name.toLowerCase().endsWith("." + ext);
|
||||
})
|
||||
);
|
||||
};
|
||||
|
||||
const previewableCount = props.mediaList.filter((media) =>
|
||||
previewable(media)
|
||||
).length;
|
||||
|
|
551
packages/client/src/components/MkModPlayer.vue
Normal file
551
packages/client/src/components/MkModPlayer.vue
Normal file
|
@ -0,0 +1,551 @@
|
|||
<template>
|
||||
<div class="mod-player-disabled" v-if="!available">
|
||||
<MkLoading />
|
||||
</div>
|
||||
<div class="mod-player-disabled" v-else-if="hide" @click="toggleVisible()">
|
||||
<div>
|
||||
<b
|
||||
><i class="ph-warning ph-bold ph-lg"></i>
|
||||
{{ i18n.ts.sensitive }}</b
|
||||
>
|
||||
<span>{{ i18n.ts.clickToShow }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mod-player-enabled" v-else>
|
||||
<div class="pattern-display">
|
||||
<div class="mod-pattern" ref="modPattern" v-if="patternShow">
|
||||
<span
|
||||
v-for="(row, i) in patData[currentPattern]"
|
||||
ref="initRow"
|
||||
v-bind:class="{ modRowActive: isRowActive(i) }"
|
||||
>
|
||||
<span v-bind:class="{ modColQuarter: i % 4 === 0 }">{{
|
||||
indexText(i)
|
||||
}}</span>
|
||||
<span class="mod-row-inner">{{ getRowText(row) }}</span>
|
||||
</span>
|
||||
</div>
|
||||
<div class="mod-pattern" v-else @click="showPattern()">
|
||||
<span class="modRowActive" ref="initRow">
|
||||
<span class="modColQuarter">00</span>
|
||||
<span class="mod-row-inner">|C-41Cv14XEF</span>
|
||||
</span>
|
||||
<br />
|
||||
<p>Click to show module patterns</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="controls">
|
||||
<button class="play" @click="playPause()">
|
||||
<i class="ph-pause ph-fill ph-lg" v-if="playing"></i>
|
||||
<i class="ph-play ph-fill ph-lg" v-else></i>
|
||||
</button>
|
||||
<button class="stop" @click="stop()">
|
||||
<i class="ph-stop ph-fill ph-lg"></i>
|
||||
</button>
|
||||
<input
|
||||
class="progress"
|
||||
type="range"
|
||||
min="0"
|
||||
max="1"
|
||||
v-model="position"
|
||||
step="0.1"
|
||||
ref="progress"
|
||||
@mousedown="initSeek()"
|
||||
@mouseup="performSeek()"
|
||||
/>
|
||||
<input
|
||||
type="range"
|
||||
min="0"
|
||||
max="1"
|
||||
v-model="player.context.gain.value"
|
||||
step="0.1"
|
||||
/>
|
||||
<a
|
||||
class="download"
|
||||
:title="i18n.ts.download"
|
||||
:href="module.url"
|
||||
target="_blank"
|
||||
>
|
||||
<i class="ph-download-simple ph-fill ph-lg"></i>
|
||||
</a>
|
||||
</div>
|
||||
<i class="ph-eye-slash ph-bold ph-lg" @click="toggleVisible()"></i>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import { ref, shallowRef, nextTick, onDeactivated, onMounted } from "vue";
|
||||
import * as calckey from "calckey-js";
|
||||
import { i18n } from "@/i18n";
|
||||
import { defaultStore } from "@/store";
|
||||
import { ChiptuneJsPlayer, ChiptuneJsConfig } from "@/scripts/chiptune2";
|
||||
|
||||
const props = defineProps<{
|
||||
module: calckey.entities.DriveFile;
|
||||
}>();
|
||||
|
||||
interface ModRow {
|
||||
notes: string[];
|
||||
insts: string[];
|
||||
vols: string[];
|
||||
fxs: string[];
|
||||
ops: string[];
|
||||
}
|
||||
|
||||
const available = ref(false);
|
||||
const player = shallowRef(new ChiptuneJsPlayer(new ChiptuneJsConfig()));
|
||||
const loaded = !!window.libopenmpt;
|
||||
|
||||
onMounted(() => {
|
||||
if (loaded) {
|
||||
available.value = true;
|
||||
player.value
|
||||
.load(props.module.url)
|
||||
.then((result: null) => {
|
||||
buffer = result;
|
||||
})
|
||||
.catch((error: any) => {
|
||||
console.error(error);
|
||||
});
|
||||
} else {
|
||||
document.head
|
||||
.appendChild(
|
||||
Object.assign(document.createElement("script"), {
|
||||
async: true,
|
||||
src: "/client-assets/libopenmpt.js",
|
||||
})
|
||||
)
|
||||
.addEventListener("load", () => {
|
||||
available.value = true;
|
||||
window.libopenmpt = window.Module;
|
||||
player.value
|
||||
.load(props.module.url)
|
||||
.then((result: null) => {
|
||||
buffer = result;
|
||||
})
|
||||
.catch((error: any) => {
|
||||
console.error(error);
|
||||
});
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
let hide = ref(
|
||||
defaultStore.state.nsfw === "force"
|
||||
? true
|
||||
: props.module.isSensitive && defaultStore.state.nsfw !== "ignore"
|
||||
);
|
||||
let playing = ref(false);
|
||||
let patternShow = ref(false);
|
||||
const initRow = shallowRef<HTMLSpanElement>();
|
||||
let modPattern = ref<HTMLDivElement>();
|
||||
let progress = ref<HTMLProgressElement>();
|
||||
let position = ref(0);
|
||||
let patData = shallowRef([] as ModRow[][]);
|
||||
let currentPattern = ref(0);
|
||||
let nbChannels = ref(0);
|
||||
|
||||
let currentRow = 0;
|
||||
let rowHeight = 0;
|
||||
let buffer = null;
|
||||
let isSeeking = false;
|
||||
|
||||
function showPattern() {
|
||||
patternShow.value = !patternShow.value;
|
||||
nextTick(() => {
|
||||
if (playing.value) display();
|
||||
else stop();
|
||||
});
|
||||
}
|
||||
|
||||
function getRowText(row: ModRow) {
|
||||
let text = "";
|
||||
for (let i = 0; i < row.notes.length; i++) {
|
||||
text = text.concat(
|
||||
"|",
|
||||
row.notes[i],
|
||||
row.insts[i],
|
||||
row.vols[i],
|
||||
row.fxs[i],
|
||||
row.ops[i]
|
||||
);
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
function playPause() {
|
||||
player.value.addHandler("onRowChange", (i: { index: number }) => {
|
||||
currentRow = i.index;
|
||||
currentPattern.value = player.value.getPattern();
|
||||
progress.value.max = player.value.duration();
|
||||
if (!isSeeking) {
|
||||
position.value = player.value.position() % player.value.duration();
|
||||
}
|
||||
requestAnimationFrame(display);
|
||||
});
|
||||
|
||||
player.value.addHandler("onEnded", () => {
|
||||
stop();
|
||||
});
|
||||
|
||||
if (player.value.currentPlayingNode === null) {
|
||||
player.value.play(buffer);
|
||||
player.value.seek(position.value);
|
||||
playing.value = true;
|
||||
} else {
|
||||
player.value.togglePause();
|
||||
playing.value = !player.value.currentPlayingNode.paused;
|
||||
}
|
||||
}
|
||||
|
||||
function stop(noDisplayUpdate = false) {
|
||||
player.value.stop();
|
||||
playing.value = false;
|
||||
if (!noDisplayUpdate) {
|
||||
try {
|
||||
player.value.play(buffer);
|
||||
display(0, true);
|
||||
} catch (e) {
|
||||
console.warn(e);
|
||||
}
|
||||
}
|
||||
player.value.stop();
|
||||
position.value = 0;
|
||||
currentRow = 0;
|
||||
player.value.clearHandlers();
|
||||
}
|
||||
|
||||
function initSeek() {
|
||||
isSeeking = true;
|
||||
}
|
||||
|
||||
function performSeek() {
|
||||
player.value.seek(position.value);
|
||||
display();
|
||||
isSeeking = false;
|
||||
}
|
||||
|
||||
function toggleVisible() {
|
||||
hide.value = !hide.value;
|
||||
nextTick(() => {
|
||||
stop(hide.value);
|
||||
});
|
||||
}
|
||||
|
||||
function isRowActive(i: number) {
|
||||
if (i === currentRow) {
|
||||
if (modPattern.value) {
|
||||
if (rowHeight === 0 && initRow.value)
|
||||
rowHeight = initRow.value[0].getBoundingClientRect().height;
|
||||
modPattern.value.scrollTop = currentRow * rowHeight;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
function indexText(i: number) {
|
||||
let rowText = parseInt(i).toString(16);
|
||||
if (rowText.length === 1) {
|
||||
rowText = "0" + rowText;
|
||||
}
|
||||
return rowText;
|
||||
}
|
||||
|
||||
function getRow(pattern: number, rowOffset: number) {
|
||||
let notes: string[] = [],
|
||||
insts: string[] = [],
|
||||
vols: string[] = [],
|
||||
fxs: string[] = [],
|
||||
ops: string[] = [];
|
||||
|
||||
for (let channel = 0; channel < nbChannels.value; channel++) {
|
||||
const part = player.value.getPatternRowChannel(
|
||||
pattern,
|
||||
rowOffset,
|
||||
channel
|
||||
);
|
||||
|
||||
notes.push(part.substring(0, 3));
|
||||
insts.push(part.substring(4, 6));
|
||||
vols.push(part.substring(6, 9));
|
||||
fxs.push(part.substring(10, 11));
|
||||
ops.push(part.substring(11, 13));
|
||||
}
|
||||
|
||||
return {
|
||||
nbChannels: nbChannels.value,
|
||||
notes,
|
||||
insts,
|
||||
vols,
|
||||
fxs,
|
||||
ops,
|
||||
};
|
||||
}
|
||||
|
||||
function display(_time = 0, reset = false) {
|
||||
if (!patternShow.value) return;
|
||||
|
||||
if (reset) {
|
||||
const pattern = player.value.getPattern();
|
||||
currentPattern.value = pattern;
|
||||
}
|
||||
|
||||
if (patData.value.length === 0) {
|
||||
const nbPatterns = player.value.getNumPatterns();
|
||||
const pattern = player.value.getPattern();
|
||||
|
||||
currentPattern.value = pattern;
|
||||
|
||||
if (player.value.currentPlayingNode) {
|
||||
nbChannels.value = player.value.currentPlayingNode.nbChannels;
|
||||
}
|
||||
|
||||
const patternsArray: ModRow[][] = [];
|
||||
|
||||
for (let patOffset = 0; patOffset < nbPatterns; patOffset++) {
|
||||
const rowsArray: ModRow[] = [];
|
||||
const nbRows = player.value.getPatternNumRows(patOffset);
|
||||
for (let rowOffset = 0; rowOffset < nbRows; rowOffset++) {
|
||||
rowsArray.push(getRow(patOffset, rowOffset));
|
||||
}
|
||||
patternsArray.push(rowsArray);
|
||||
}
|
||||
|
||||
patData.value = Object.freeze(patternsArray);
|
||||
}
|
||||
}
|
||||
|
||||
onDeactivated(() => {
|
||||
stop();
|
||||
});
|
||||
</script>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
.mod-player-enabled {
|
||||
position: relative;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
|
||||
> i {
|
||||
display: block;
|
||||
position: absolute;
|
||||
border-radius: 6px;
|
||||
background-color: var(--fg);
|
||||
color: var(--accentLighten);
|
||||
font-size: 14px;
|
||||
opacity: 0.5;
|
||||
padding: 3px 6px;
|
||||
text-align: center;
|
||||
cursor: pointer;
|
||||
top: 12px;
|
||||
right: 12px;
|
||||
}
|
||||
|
||||
> .pattern-display {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
overflow: hidden;
|
||||
color: #ffffff;
|
||||
background-color: black;
|
||||
text-align: center;
|
||||
font: 12px monospace;
|
||||
white-space: pre;
|
||||
user-select: none;
|
||||
|
||||
> .mod-pattern {
|
||||
display: grid;
|
||||
overflow-y: hidden;
|
||||
height: 0;
|
||||
padding-top: 25%;
|
||||
padding-bottom: 25%;
|
||||
content-visibility: auto;
|
||||
|
||||
> .modRowActive {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
> span {
|
||||
opacity: 0.5;
|
||||
|
||||
> .modColQuarter {
|
||||
color: #ffff00;
|
||||
}
|
||||
|
||||
> .mod-row-inner {
|
||||
background: repeating-linear-gradient(
|
||||
to right,
|
||||
white 0 4ch,
|
||||
#80e0ff 4ch 6ch,
|
||||
#80ff80 6ch 9ch,
|
||||
#ff80e0 9ch 10ch,
|
||||
#ffe080 10ch 12ch
|
||||
);
|
||||
background-clip: text;
|
||||
-webkit-background-clip: text;
|
||||
-webkit-text-fill-color: transparent;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
> .controls {
|
||||
display: flex;
|
||||
width: 100%;
|
||||
background-color: var(--panelHighlight);
|
||||
|
||||
> * {
|
||||
padding: 4px 8px;
|
||||
}
|
||||
|
||||
> button,
|
||||
a {
|
||||
border: none;
|
||||
background-color: transparent;
|
||||
color: var(--navFg);
|
||||
cursor: pointer;
|
||||
|
||||
&:hover {
|
||||
background-color: var(--accentedBg);
|
||||
}
|
||||
}
|
||||
|
||||
> input[type="range"] {
|
||||
height: 21px;
|
||||
-webkit-appearance: none;
|
||||
width: 90px;
|
||||
padding: 0;
|
||||
margin: 4px 8px;
|
||||
overflow-x: hidden;
|
||||
|
||||
&:focus {
|
||||
outline: none;
|
||||
|
||||
&::-webkit-slider-runnable-track {
|
||||
background: var(--bg);
|
||||
}
|
||||
|
||||
&::-ms-fill-lower,
|
||||
&::-ms-fill-upper {
|
||||
background: var(--bg);
|
||||
}
|
||||
}
|
||||
|
||||
&::-webkit-slider-runnable-track {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
cursor: pointer;
|
||||
border-radius: 0;
|
||||
animate: 0.2s;
|
||||
background: var(--bg);
|
||||
border: 1px solid var(--fg);
|
||||
overflow-x: hidden;
|
||||
}
|
||||
|
||||
&::-webkit-slider-thumb {
|
||||
border: none;
|
||||
height: 100%;
|
||||
width: 14px;
|
||||
border-radius: 0;
|
||||
background: var(--accentLighten);
|
||||
cursor: pointer;
|
||||
-webkit-appearance: none;
|
||||
box-shadow: calc(-100vw - 14px) 0 0 100vw var(--accent);
|
||||
clip-path: polygon(
|
||||
1px 0,
|
||||
100% 0,
|
||||
100% 100%,
|
||||
1px 100%,
|
||||
1px calc(50% + 10.5px),
|
||||
-100vw calc(50% + 10.5px),
|
||||
-100vw calc(50% - 10.5px),
|
||||
0 calc(50% - 10.5px)
|
||||
);
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
&::-moz-range-track {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
cursor: pointer;
|
||||
border-radius: 0;
|
||||
animate: 0.2s;
|
||||
background: var(--bg);
|
||||
border: 1px solid var(--fg);
|
||||
}
|
||||
|
||||
&::-moz-range-progress {
|
||||
cursor: pointer;
|
||||
height: 100%;
|
||||
background: var(--accent);
|
||||
}
|
||||
|
||||
&::-moz-range-thumb {
|
||||
border: none;
|
||||
height: 100%;
|
||||
border-radius: 0;
|
||||
width: 14px;
|
||||
background: var(--accentLighten);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
&::-ms-track {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
cursor: pointer;
|
||||
border-radius: 0;
|
||||
animate: 0.2s;
|
||||
background: transparent;
|
||||
border-color: transparent;
|
||||
color: transparent;
|
||||
}
|
||||
|
||||
&::-ms-fill-lower {
|
||||
background: var(--accent);
|
||||
border: 1px solid var(--fg);
|
||||
border-radius: 0;
|
||||
}
|
||||
|
||||
&::-ms-fill-upper {
|
||||
background: var(--bg);
|
||||
border: 1px solid var(--fg);
|
||||
border-radius: 0;
|
||||
}
|
||||
|
||||
&::-ms-thumb {
|
||||
margin-top: 1px;
|
||||
border: none;
|
||||
height: 100%;
|
||||
width: 14px;
|
||||
border-radius: 0;
|
||||
background: var(--accentLighten);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
&.progress {
|
||||
flex-grow: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.mod-player-disabled {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
background: #111;
|
||||
color: #fff;
|
||||
|
||||
> div {
|
||||
display: table-cell;
|
||||
text-align: center;
|
||||
font-size: 12px;
|
||||
|
||||
> b {
|
||||
display: block;
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
|
@ -38,6 +38,55 @@ export const FILE_TYPE_BROWSERSAFE = [
|
|||
"audio/x-flac",
|
||||
"audio/vnd.wave",
|
||||
];
|
||||
|
||||
export const FILE_TYPE_TRACKER_MODULES = [
|
||||
"audio/mod",
|
||||
"audio/x-mod",
|
||||
"audio/s3m",
|
||||
"audio/x-s3m",
|
||||
"audio/xm",
|
||||
"audio/x-xm",
|
||||
"audio/it",
|
||||
"audio/x-it"
|
||||
];
|
||||
|
||||
export const FILE_EXT_TRACKER_MODULES = [
|
||||
'mod',
|
||||
's3m',
|
||||
'xm',
|
||||
'it',
|
||||
'mptm',
|
||||
'stm',
|
||||
'nst',
|
||||
'm15',
|
||||
'stk',
|
||||
'wow',
|
||||
'ult',
|
||||
'669',
|
||||
'mtm',
|
||||
'med',
|
||||
'far',
|
||||
'mdl',
|
||||
'ams',
|
||||
'dsm',
|
||||
'amf',
|
||||
'okt',
|
||||
'dmf',
|
||||
'ptm',
|
||||
'psm',
|
||||
'mt2',
|
||||
'dbm',
|
||||
'digi',
|
||||
'imf',
|
||||
'j2b',
|
||||
'gdm',
|
||||
'umx',
|
||||
'plm',
|
||||
'mo3',
|
||||
'xpk',
|
||||
'ppm',
|
||||
'mmcmp'
|
||||
];
|
||||
/*
|
||||
https://github.com/sindresorhus/file-type/blob/main/supported.js
|
||||
https://github.com/sindresorhus/file-type/blob/main/core.js
|
||||
|
|
277
packages/client/src/scripts/chiptune2.ts
Normal file
277
packages/client/src/scripts/chiptune2.ts
Normal file
|
@ -0,0 +1,277 @@
|
|||
/* global libopenmpt UTF8ToString writeAsciiToMemory */
|
||||
|
||||
const ChiptuneAudioContext = window.AudioContext || window.webkitAudioContext;
|
||||
|
||||
export function ChiptuneJsConfig (repeatCount?: number, context?: AudioContext) {
|
||||
this.repeatCount = repeatCount;
|
||||
this.context = context;
|
||||
}
|
||||
|
||||
ChiptuneJsConfig.prototype.constructor = ChiptuneJsConfig;
|
||||
|
||||
export function ChiptuneJsPlayer (config: object) {
|
||||
this.config = config;
|
||||
this.audioContext = config.context || new ChiptuneAudioContext();
|
||||
this.context = this.audioContext.createGain();
|
||||
this.currentPlayingNode = null;
|
||||
this.handlers = [];
|
||||
this.touchLocked = true;
|
||||
this.volume = 1;
|
||||
}
|
||||
|
||||
ChiptuneJsPlayer.prototype.constructor = ChiptuneJsPlayer;
|
||||
|
||||
ChiptuneJsPlayer.prototype.fireEvent = function (eventName: string, response) {
|
||||
const handlers = this.handlers;
|
||||
if (handlers.length > 0) {
|
||||
for(const handler of handlers) {
|
||||
if (handler.eventName === eventName) {
|
||||
handler.handler(response);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
ChiptuneJsPlayer.prototype.addHandler = function (eventName: string, handler: Function) {
|
||||
this.handlers.push({ eventName, handler });
|
||||
};
|
||||
|
||||
ChiptuneJsPlayer.prototype.clearHandlers = function () {
|
||||
this.handlers = [];
|
||||
};
|
||||
|
||||
ChiptuneJsPlayer.prototype.onEnded = function (handler: Function) {
|
||||
this.addHandler('onEnded', handler);
|
||||
};
|
||||
|
||||
ChiptuneJsPlayer.prototype.onError = function (handler: Function) {
|
||||
this.addHandler('onError', handler);
|
||||
};
|
||||
|
||||
ChiptuneJsPlayer.prototype.duration = function () {
|
||||
return libopenmpt._openmpt_module_get_duration_seconds(this.currentPlayingNode.modulePtr);
|
||||
};
|
||||
|
||||
ChiptuneJsPlayer.prototype.position = function () {
|
||||
return libopenmpt._openmpt_module_get_position_seconds(this.currentPlayingNode.modulePtr);
|
||||
};
|
||||
|
||||
ChiptuneJsPlayer.prototype.seek = function (position: number) {
|
||||
if (this.currentPlayingNode) {
|
||||
libopenmpt._openmpt_module_set_position_seconds(this.currentPlayingNode.modulePtr, position);
|
||||
}
|
||||
};
|
||||
|
||||
ChiptuneJsPlayer.prototype.metadata = function () {
|
||||
const data = {};
|
||||
const keys = UTF8ToString(libopenmpt._openmpt_module_get_metadata_keys(this.currentPlayingNode.modulePtr)).split(';');
|
||||
let keyNameBuffer = 0;
|
||||
for (const key of keys) {
|
||||
keyNameBuffer = libopenmpt._malloc(key.length + 1);
|
||||
writeAsciiToMemory(key, keyNameBuffer);
|
||||
data[key] = UTF8ToString(libopenmpt._openmpt_module_get_metadata(this.currentPlayingNode.modulePtr, keyNameBuffer));
|
||||
libopenmpt._free(keyNameBuffer);
|
||||
}
|
||||
return data;
|
||||
};
|
||||
|
||||
ChiptuneJsPlayer.prototype.unlock = function () {
|
||||
const context = this.audioContext;
|
||||
const buffer = context.createBuffer(1, 1, 22050);
|
||||
const unlockSource = context.createBufferSource();
|
||||
unlockSource.buffer = buffer;
|
||||
unlockSource.connect(this.context);
|
||||
this.context.connect(context.destination);
|
||||
unlockSource.start(0);
|
||||
this.touchLocked = false;
|
||||
};
|
||||
|
||||
ChiptuneJsPlayer.prototype.load = function (input) {
|
||||
return new Promise((resolve, reject) => {
|
||||
if(this.touchLocked) {
|
||||
this.unlock();
|
||||
}
|
||||
const player = this;
|
||||
if (input instanceof File) {
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => {
|
||||
resolve(reader.result);
|
||||
};
|
||||
reader.readAsArrayBuffer(input);
|
||||
} else {
|
||||
window.fetch(input).then((response) => {
|
||||
response.arrayBuffer().then((arrayBuffer) => {
|
||||
resolve(arrayBuffer);
|
||||
}).catch((error) => {
|
||||
reject(error);
|
||||
});
|
||||
}).catch((error) => {
|
||||
reject(error);
|
||||
});
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
ChiptuneJsPlayer.prototype.play = function (buffer: ArrayBuffer) {
|
||||
this.unlock();
|
||||
this.stop();
|
||||
const processNode = this.createLibopenmptNode(buffer, this.buffer);
|
||||
if (processNode === null) {
|
||||
return;
|
||||
}
|
||||
libopenmpt._openmpt_module_set_repeat_count(processNode.modulePtr, this.config.repeatCount || 0);
|
||||
this.currentPlayingNode = processNode;
|
||||
processNode.connect(this.context);
|
||||
this.context.connect(this.audioContext.destination);
|
||||
};
|
||||
|
||||
ChiptuneJsPlayer.prototype.stop = function () {
|
||||
if (this.currentPlayingNode != null) {
|
||||
this.currentPlayingNode.disconnect();
|
||||
this.currentPlayingNode.cleanup();
|
||||
this.currentPlayingNode = null;
|
||||
}
|
||||
};
|
||||
|
||||
ChiptuneJsPlayer.prototype.togglePause = function () {
|
||||
if (this.currentPlayingNode != null) {
|
||||
this.currentPlayingNode.togglePause();
|
||||
}
|
||||
};
|
||||
|
||||
ChiptuneJsPlayer.prototype.getPattern = function () {
|
||||
if (this.currentPlayingNode && this.currentPlayingNode.modulePtr) {
|
||||
return libopenmpt._openmpt_module_get_current_pattern(this.currentPlayingNode.modulePtr);
|
||||
}
|
||||
return 0;
|
||||
};
|
||||
|
||||
ChiptuneJsPlayer.prototype.getRow = function () {
|
||||
if (this.currentPlayingNode && this.currentPlayingNode.modulePtr) {
|
||||
return libopenmpt._openmpt_module_get_current_row(this.currentPlayingNode.modulePtr);
|
||||
}
|
||||
return 0;
|
||||
};
|
||||
|
||||
ChiptuneJsPlayer.prototype.getNumPatterns = function () {
|
||||
if (this.currentPlayingNode && this.currentPlayingNode.modulePtr) {
|
||||
return libopenmpt._openmpt_module_get_num_patterns(this.currentPlayingNode.modulePtr);
|
||||
}
|
||||
return 0;
|
||||
};
|
||||
|
||||
ChiptuneJsPlayer.prototype.getPatternNumRows = function (pattern: number) {
|
||||
if (this.currentPlayingNode && this.currentPlayingNode.modulePtr) {
|
||||
return libopenmpt._openmpt_module_get_pattern_num_rows(this.currentPlayingNode.modulePtr, pattern);
|
||||
}
|
||||
return 0;
|
||||
};
|
||||
|
||||
ChiptuneJsPlayer.prototype.getPatternRowChannel = function (pattern: number, row: number, channel: number) {
|
||||
if (this.currentPlayingNode && this.currentPlayingNode.modulePtr) {
|
||||
return UTF8ToString(libopenmpt._openmpt_module_format_pattern_row_channel(this.currentPlayingNode.modulePtr, pattern, row, channel, 0, true));
|
||||
}
|
||||
return '';
|
||||
};
|
||||
|
||||
ChiptuneJsPlayer.prototype.createLibopenmptNode = function (buffer, config: object) {
|
||||
const maxFramesPerChunk = 4096;
|
||||
const processNode = this.audioContext.createScriptProcessor(2048, 0, 2);
|
||||
processNode.config = config;
|
||||
processNode.player = this;
|
||||
const byteArray = new Int8Array(buffer);
|
||||
const ptrToFile = libopenmpt._malloc(byteArray.byteLength);
|
||||
libopenmpt.HEAPU8.set(byteArray, ptrToFile);
|
||||
processNode.modulePtr = libopenmpt._openmpt_module_create_from_memory(ptrToFile, byteArray.byteLength, 0, 0, 0);
|
||||
processNode.nbChannels = libopenmpt._openmpt_module_get_num_channels(processNode.modulePtr);
|
||||
processNode.patternIndex = -1;
|
||||
processNode.paused = false;
|
||||
processNode.leftBufferPtr = libopenmpt._malloc(4 * maxFramesPerChunk);
|
||||
processNode.rightBufferPtr = libopenmpt._malloc(4 * maxFramesPerChunk);
|
||||
processNode.cleanup = function () {
|
||||
if (this.modulePtr !== 0) {
|
||||
libopenmpt._openmpt_module_destroy(this.modulePtr);
|
||||
this.modulePtr = 0;
|
||||
}
|
||||
if (this.leftBufferPtr !== 0) {
|
||||
libopenmpt._free(this.leftBufferPtr);
|
||||
this.leftBufferPtr = 0;
|
||||
}
|
||||
if (this.rightBufferPtr !== 0) {
|
||||
libopenmpt._free(this.rightBufferPtr);
|
||||
this.rightBufferPtr = 0;
|
||||
}
|
||||
};
|
||||
processNode.stop = function () {
|
||||
this.disconnect();
|
||||
this.cleanup();
|
||||
};
|
||||
processNode.pause = function () {
|
||||
this.paused = true;
|
||||
};
|
||||
processNode.unpause = function () {
|
||||
this.paused = false;
|
||||
};
|
||||
processNode.togglePause = function () {
|
||||
this.paused = !this.paused;
|
||||
};
|
||||
processNode.onaudioprocess = function (e) {
|
||||
const outputL = e.outputBuffer.getChannelData(0);
|
||||
const outputR = e.outputBuffer.getChannelData(1);
|
||||
let framesToRender = outputL.length;
|
||||
if (this.ModulePtr === 0) {
|
||||
for (let i = 0; i < framesToRender; ++i) {
|
||||
outputL[i] = 0;
|
||||
outputR[i] = 0;
|
||||
}
|
||||
this.disconnect();
|
||||
this.cleanup();
|
||||
return;
|
||||
}
|
||||
if (this.paused) {
|
||||
for (let i = 0; i < framesToRender; ++i) {
|
||||
outputL[i] = 0;
|
||||
outputR[i] = 0;
|
||||
}
|
||||
return;
|
||||
}
|
||||
let framesRendered = 0;
|
||||
let ended = false;
|
||||
let error = false;
|
||||
|
||||
const currentPattern = libopenmpt._openmpt_module_get_current_pattern(this.modulePtr);
|
||||
const currentRow = libopenmpt._openmpt_module_get_current_row(this.modulePtr);
|
||||
if (currentPattern !== this.patternIndex) {
|
||||
processNode.player.fireEvent('onPatternChange');
|
||||
}
|
||||
processNode.player.fireEvent('onRowChange', { index: currentRow });
|
||||
|
||||
while (framesToRender > 0) {
|
||||
const framesPerChunk = Math.min(framesToRender, maxFramesPerChunk);
|
||||
const actualFramesPerChunk = libopenmpt._openmpt_module_read_float_stereo(this.modulePtr, this.context.sampleRate, framesPerChunk, this.leftBufferPtr, this.rightBufferPtr);
|
||||
if (actualFramesPerChunk === 0) {
|
||||
ended = true;
|
||||
// modulePtr will be 0 on openmpt: error: openmpt_module_read_float_stereo: ERROR: module * not valid or other openmpt error
|
||||
error = !this.modulePtr;
|
||||
}
|
||||
const rawAudioLeft = libopenmpt.HEAPF32.subarray(this.leftBufferPtr / 4, this.leftBufferPtr / 4 + actualFramesPerChunk);
|
||||
const rawAudioRight = libopenmpt.HEAPF32.subarray(this.rightBufferPtr / 4, this.rightBufferPtr / 4 + actualFramesPerChunk);
|
||||
for (let i = 0; i < actualFramesPerChunk; ++i) {
|
||||
outputL[framesRendered + i] = rawAudioLeft[i];
|
||||
outputR[framesRendered + i] = rawAudioRight[i];
|
||||
}
|
||||
for (let i = actualFramesPerChunk; i < framesPerChunk; ++i) {
|
||||
outputL[framesRendered + i] = 0;
|
||||
outputR[framesRendered + i] = 0;
|
||||
}
|
||||
framesToRender -= framesPerChunk;
|
||||
framesRendered += framesPerChunk;
|
||||
}
|
||||
if (ended) {
|
||||
this.disconnect();
|
||||
this.cleanup();
|
||||
error ? processNode.player.fireEvent('onError', { type: 'openmpt' }) : processNode.player.fireEvent('onEnded');
|
||||
}
|
||||
};
|
||||
return processNode;
|
||||
};
|
Loading…
Reference in a new issue