Files

3517 lines
300 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 Juan Ignacio Antonucci (Juan Jiant)
// JIANT Studio (index.html): one page for JIANT FM and JIANT BYTE. What it does itself: finds the FM-1 and says which
// firmware it runs (INFO: BYTE's engines include MATH), shows its screen big (78 SCREEN / 79 SCREEN_DATA, as the editor's
// mirror) or the emulator's, and records audio (the FM-1's USB audio: stereo, or the 8 channels of USB > STEMS; or the
// emulator's output) and MIDI. The installer, the editor and the emulator are the sites' own pages in frames (one origin:
// /JIANT/ and /JIANT-BYTE/ on juanjiant-bit.github.io), dressed in the firmware's look.
// Install safety: the BroadcastChannel "jiant-midi" (as every MIDI page of both sites): while an installer writes, this
// page lets the FM-1 go (link closed, screen off) and says "released"; the editor and the emulator in the frames do the
// same on their own.
import { scrDecode, scrEncode, wavFile, zipStored, midiFile, SCR } from "./studio-lib.js";
import { Daw } from "./daw.js";
import { Player, anim } from "./learn.js";
import { Ecosystem, Levels } from "./radio-vis.js";
import { capture as anCapture, text as anText } from "./analysis.js";
import { checker as cvChecker, classify as cvClassify, convert as cvConvert, putObject as cvPut, replaceInFile as cvReplace, projectName as cvName } from "./convert.js";
import { Vis as VisEngine, Live as VisLive, forDrawing as visRecipe, VI_NAMES, VD_NAMES, VB_NAMES, VP_NAMES } from "./visgen.js";
import { makeTable, toI16, pack as wtPack, unpack as wtUnpack, parseInfo as parseWtInfo, render as wtRender, wav as wtWav, WT, FRAMES, LEN, CHUNKS } from "./wavetable.js";
import { AudioEditor } from "./audioedit.js";
import { mathLib, compile as fmCompile, preview as fmPreview, wave as fmWave, keepText as fmKeep, textOf as fmTextOf } from "./fmformula.js";
import { captureBackup, restoreBackup, readBackup, songsNotRestored, BACKUP_IDS, bkU32, bkR32, bkCrc, bkPack, bkUnpack, bkManifestAll } from "./fm1backup.js";
const $ = (id) => document.getElementById(id);
const QS = new URLSearchParams(location.search);
const MOCK = QS.get("mock") === "1";
let mockSel = 0; // (the simulated FM-1's selected track)
/* ------------------------------------------------------------------------------------------------- the words */
const TEXT = {
es: {
lvNow: "· En pantalla:", lvLayer: "capa", lvLayerWhat: "Estás manteniendo %s: las teclas y perillas hacen otra cosa mientras lo sostenés.", lvPressed: "apretado", lvButton: "Apretaste %s.",
lvChip: "● En vivo", lvLead: "Tocá tu FM-1 y mirá acá: cada perilla que girás, el motor que elegís, los pasos y el play se explican solos, mientras pasan.",
lvStartBtn: "Seguir mi FM-1", lvStopBtn: "Dejar de seguir", lvOff: "Conectá la FM-1 (Inicio › Buscar) o prendé el emulador, y tocá «Seguir mi FM-1».",
lvNoDev: "No hay FM-1 conectada ni emulador prendido.", lvWaiting: "Siguiendo %s: tocá algo…", lvTouch: "Siguiendo: girá una perilla, cambiá de sonido o dale play.",
lvTrack: "Pista", lvGlobal: "Global", lvSound: "Sonido", lvPreset: "preset", lvStep: "Paso", lvBar: "compás",
lvUnknown: "Un parámetro de esta página.", lvReload: "Cambiaste de sonido: el motor y su preset en la pista elegida.", lvStepWhat: "Editaste un paso de la secuencia de esta pista.",
lvPlay: "La música está sonando: el secuenciador avanza paso a paso.", lvStop: "Se detuvo la reproducción.", lvPunch: "Mantené FX y tocá teclas: un efecto suena solo mientras lo sostenés.",
lvPunchOn: "un efecto activo", lvPunchOff: "ninguno", lvMutate: "MUTATE cambió el patrón de esta pista.", lvPage: "La página que está en pantalla y sus perillas.", lvMore: "Ver en la guía:",
tourOpen: "Guía rápida", tourNext: "Siguiente", tourPrev: "Anterior", tourSkip: "Saltear", tourDone: "Listo",
tourWelcomeT: "Bienvenido a JIANT Studio", tourWelcome: "Todo para tu FM-1 en una página: instalar el firmware, editarlo, ver su pantalla en grande, tocar el emulador, grabar, guardar tus proyectos y aprender cómo funciona. Te muestro dónde está cada cosa.",
tourWelcomeH: "Son unos pasos; podés saltearlo y volver cuando quieras con el botón ? de arriba.",
tourFwT: "JIANT FM o JIANT BYTE", tourFw: "Elegí el firmware: FM (síntesis) o BYTE (fórmulas). Studio cambia sus herramientas, sus manuales y su estética según cuál elijas.", tourFwH: "Si conectás una FM-1, Studio lo detecta y lo elige solo.",
tourTargetT: "FM-1 o Emulador", tourTarget: "¿Con qué trabajás? Con tu FM-1 por USB, o con el emulador: el firmware real corriendo en el navegador.", tourTargetH: "El editor, la pantalla, grabar y la guía en vivo usan lo que elijas acá.",
tourDevT: "Tu FM-1", tourDev: "Acá ves si hay una FM-1 conectada y qué firmware y versión tiene.", tourDevH: "Verde: conectada. Si algo no responde, desconectá y volvé a buscar.",
tourFindT: "Buscar la FM-1", tourFind: "Conectá la FM-1 con un cable USB de datos y tocá Buscar: Studio la encuentra por MIDI.", tourFindH: "Funciona en Chrome o Edge (computadora) y Chrome en Android.",
tourV_installT: "Instalar", tourV_install: "Instala o actualiza el firmware, con un backup antes. Primero leés las advertencias y aceptás; después son tres pasos.", tourV_installH: "Mientras instala, todo lo demás suelta la FM-1 para no interrumpirla.",
tourV_editorT: "Editor", tourV_editor: "Cada sonido y ajuste de la FM-1 en la pantalla: motores, presets, perillas, secuencias, proyectos.", tourV_editorH: "Lo que cambiás acá cambia en el aparato al instante, y al revés.",
tourV_screenT: "Pantalla", tourV_screen: "La pantalla de la FM-1 en grande, en vivo, incluso en el celular a pantalla completa.", tourV_screenH: "Tocá Mostrar; se gira sola en horizontal o vertical.",
tourV_emuT: "Emulador", tourV_emu: "El firmware real en el navegador, para tocar con el mouse, el teclado de la computadora o un teclado MIDI.", tourV_emuH: "Tiene pantalla completa; elegí qué entrada MIDI lo toca.",
tourV_recT: "Grabar", tourV_rec: "Graba el master o cada pista por separado (stems), en WAV y MIDI, con pistas como en un DAW.", tourV_recH: "De la FM-1 por USB (modo STEMS) o directamente del emulador.",
tourV_projT: "Proyectos", tourV_proj: "Tus ranuras de proyecto A–D y los backups a mano, guardados en este navegador.", tourV_projH: "Hacé un backup antes de instalar o probar algo nuevo.",
tourV_learnT: "Cómo funciona", tourV_learn: "Cada motor, secuenciador, efecto, modulador y generador, explicado con animaciones. Y En vivo: tocás la FM-1 y Studio te explica qué moviste.", tourV_learnH: "Empezá por el Índice o por ● En vivo.",
tourV_docsT: "Manuales", tourV_docs: "El manual interactivo, el manual completo y las hojas de ayuda de cada firmware.", tourV_docsH: "Las hojas de ayuda se pueden imprimir.",
tourV_rescueT: "Rescate", tourV_rescue: "Si una FM-1 no enciende o no aparece por USB, una placa RP2040 la puede revivir: un tutorial paso a paso.", tourV_rescueH: "Solo para FM-1 que no prenden; si prende, usá Instalar.",
tourV_portsT: "Otros aparatos", tourV_ports: "JIANT en el SMK-37 y la MPC Sample, con su emulador y su manual, y los plugins que vienen.", tourV_portsH: "Probalos en el navegador sin tener el aparato.",
tourLangT: "Idioma", tourLang: "Cambiá entre español e inglés.",
tourEndT: "Listo", tourEnd: "Esta guía vuelve cuando quieras con este botón.", tourEndH: "Para empezar: conectá tu FM-1 y tocá Buscar, o elegí Emulador y prendelo.",
siteLink: "El sitio de %s: qué es, sus pantallas y su historia →", vLearn: "Cómo funciona", lrIndex: "Índice", lrIndexLead: "Todo, de un vistazo: tocá cualquier elemento para abrir su página. Con ← y → pasás al siguiente.", lrTitleFm: "JIANT FM por dentro", lrTitleByte: "JIANT BYTE por dentro", lrTry: "Probarlo en el emulador", lrWhere: "En la FM-1: ", lrSince: "desde %s", lrNone: "Esta guía todavía se está escribiendo.",
vRescue: "Rescate", rsTitle: "Rescatar un FM-1", rsBeta: "experimental · sin probar en hardware",
rsLead: "Para un FM-1 que no enciende o que la computadora no ve por USB (hard brick). Una placa RP2040 de pocos dólares hace todo sola: se conecta al USB-C del FM-1 con tres cables y le vuelve a escribir el firmware. Sin Python ni terminal: Studio arma el archivo para la placa.",
rsFirstT: "Antes de empezar", rsFirst: "Si el FM-1 enciende y la computadora lo ve (aunque esté trabado o suene raro), no hace falta esto: usá Instalar, que lo actualiza por USB.", rsToInstall: "Ir a Instalar",
rs1: "Lo que necesitás", rsNeedBoard: "Una placa RP2040: Waveshare RP2040-Zero, Seeed XIAO RP2040 o Raspberry Pi Pico (o una parecida).",
rsNeedUsb: "Un cable USB-C que puedas cortar (o un conector USB-C macho con cables), para llegar a sus hilos: verde (D+), blanco (D−), negro (GND) y rojo (5 V, que no se usa).",
rsNeedWires: "Soldador o cables dupont para unir esos tres hilos a la placa.", rsNeedBatt: "El FM-1 con la batería cargada.", rsNeedPc: "Una computadora con Chrome, Edge o Firefox (o un cargador USB para el paso 6).",
rs2: "Tu placa y los cables", rsCable: "Cable cortado: verde = D+, blanco = D−, negro = GND, rojo = 5 V. El rojo queda sin conectar (aislalo con cinta). Si la placa no logra hablar con el FM-1, probá cambiar verde y blanco entre sí.",
rsWireZero: "RP2040-Zero: verde → pin 0, blanco → pin 1, negro → GND. Su LED es de colores (la tabla del paso 6).",
rsWireXiao: "XIAO RP2040: verde → D6, blanco → D7, negro → GND. Su LED es de colores (la tabla del paso 6).",
rsWirePico: "Raspberry Pi Pico (y las tipo Pico): verde → GP0 (pin 1), blanco → GP1 (pin 2), negro → GND (pin 3). Su LED es de un solo color: parpadeo lento = esperando, rápido = error, fijo = listo.",
rs3: "El firmware que va a recibir", rsFwFile: "Otro archivo…", rsFwHelp: "Lo más simple: JIANT FM o JIANT BYTE, el paquete publicado, que Studio baja solo. También sirve el FM-1.fwsc de la V15 oficial de M-VAVE (no la V16: no entra). Si tu FM-1 venía con la V16, usá JIANT. Nada sale de tu navegador.",
rsFwGet: "Bajando el paquete publicado de %s…", rsFwOk: "Comprobado: %s", rsFwBad: "No sirve: %s", rsLdGet: "Bajando el loader de JieLi (jl-uboot-tool, MIT)…", rsLdOk: "Loader de JieLi comprobado", rsLdBad: "No se pudo bajar el loader de JieLi: %s. Reintentá en un rato.",
rs4: "Crear el archivo para la placa", rsMakeHelp: "Junta el firmware de rescate de tu placa, el firmware elegido y el loader en un solo fm1-rescue.uf2, y lo descarga.", rsMake: "Crear fm1-rescue.uf2", rsMade: "Listo: fm1-rescue.uf2 descargado (%s, %n KB)", rsNeedFw: "Falta el firmware (paso 3).",
rs5: "Grabar la placa", rs6: "Conectar y rescatar", rs7: "Después",
rsAfter: "Apagá el FM-1, sacá los cables y encendelo: arranca con el firmware elegido. Desde ahí lo podés actualizar o cambiar como siempre, con Instalar. Tus ajustes, sonidos y canciones no se tocan.",
rsLedT: "Qué dice el LED",
rsAndroidT: "Sin computadora: la app FM-1 Rescue", rsAndroid: "Hace lo mismo desde un teléfono Android: graba la placa por OTG y muestra el avance del rescate. Todavía es una versión de prueba: se baja de GitHub (Actions › android › Artifacts › fm1-rescue) con una cuenta iniciada.",
rsAndroidHow: "Cómo se usa", rsAndroidApk: "Bajar el APK", rsMore: "Cómo funciona",
rsSafe: "Solo se escribe la zona del firmware (0x4000–0x92FFF), sector por sector, cada uno releído y comparado; la cabecera de arranque y tus datos no se tocan. Sin firmware dentro, la placa queda como un FM-1 Transporter común. Basado en FM-1 Transporter (Hügelton Instruments), MvaveFM1Unbricker (Quixotic7), jl-uboot-tool (kagaimiq) y la guía de GoodPerson42. Usalo con la batería cargada y bajo tu responsabilidad: todavía no se probó en un FM-1 real.",
rdLiked: "¿Qué te gustó? (opcional)", rdDisliked: "¿Qué no te gustó? (opcional)", rdNext: "Siguiente", rdpDrums: "Batería", rdpBass: "Bajo", rdpChords: "Acordes", rdpLead: "Lead", rdpArp: "Arp", rdpSound: "Sonido/mezcla",
rdStarting: "Prendiendo…", rdEmuOn: "Prendiendo el emulador…",
emuVer: "Versión", emuVerPinned: "La de este sitio (recomendada)", emuVerPublic: "pública", emuVerBeta: "Beta (lo último, para probar)", emuVerConfirm: "Cambiar de versión reinicia el emulador (cada versión guarda su propia memoria). ¿Seguir?",
gPlay: "Tocar", gMake: "Crear", gLearn: "Aprender", gDevice: "Equipo",
pathFm1E: "Tengo un FM-1", pathFm1: "Conectarlo y usarlo", pathFm1T: "Instalar JIANT, editar los sonidos, guardar proyectos, grabar y mirar su pantalla.",
pathTryE: "No tengo uno", pathTry: "Probarlo sin equipo", pathTryT: "La radio y el emulador: el FM-1 entero en el navegador, sonando ya.",
pathLearnE: "Quiero aprender", pathLearn: "Cómo funciona", pathLearnT: "Cada motor, secuenciador y efecto, animado, y los manuales.",
cNone: "Sin equipo conectado.", cFm1: "FM-1 conectado: %s", cBusy: "El FM-1 está ocupado (instalando o en otra pestaña).", cLooking: "Buscando el FM-1…",
cEmuOn: "Usando el emulador (encendido).", cEmuOff: "Usando el emulador (apagado).", cFind: "Buscar mi FM-1", cUseEmu: "Usar el emulador", cUseFm1: "Usar mi FM-1", cOpenEmu: "Abrir el emulador",
pjTitle: "Biblioteca de proyectos", pjRead: "Leer los proyectos", pjAsk: "Leé los proyectos del FM-1: sus nombres y qué partes A–D tienen.", pjHelp: "Escribí un nombre y tocá Enter: cambia en el FM-1 al instante. Antes de pisar o borrar, se baja una copia de lo que había.",
pjOld: "El FM-1 no respondió: la biblioteca necesita JIANT FM V10.8.54 o posterior, o una versión de JIANT BYTE que la tenga (en camino).", pjUnnamed: "sin nombre", pjName: "Nombre del proyecto", pjOpen: "ABIERTO",
pjCopy: "Copiar a…", pjMove: "Mover a…", pjEmpty: "Vacío", pjShare: "Compartir", pjDownload: "Descargar", pjGFile: "ARCHIVO", pjGCopy: "COPIAR A", pjGMove: "MOVER A", pjGParts: "NOMBRE DE LAS PARTES", pjGName: "NOMBRE", pjSaveName: "Guardar", pjMore: "Más herramientas: proyectos A–D y proyectos viejos", pjTap: "Tocá un proyecto para ver qué podés hacer con él.", pjEmptyHelp: "Este lugar está vacío: importá un proyecto desde un archivo.", pjBusyNow: "Trabajando…", pjExport: "Exportar", pjImport: "Importar acá", pjDelete: "Borrar", pjParts: "Nombrar partes",
pjCopyTo: "¿A qué proyecto copiar el %s? (1–6)", pjMoveTo: "¿A qué proyecto mover el %s? (1–6)", pjBadTarget: "Ese destino no sirve: elegí otro proyecto, del 1 al 6.",
pjOverwrite: "El proyecto %s («%n») tiene contenido y se va a pisar. Antes se baja una copia. ¿Seguir?", pjDelConfirm: "¿Borrar el proyecto %s («%n»)? Antes se baja una copia.",
pjSaving: "Guardando una copia…", pjWriting: "Escribiendo la parte %s…", pjDone: "Listo.", pjRenamed: "Nombre cambiado: %s", pjBadFile: "Ese archivo no es un proyecto exportado de Studio.",
pjPartWhich: "¿Qué parte querés nombrar? (B, C o D; la A es el nombre del proyecto)", pjPartName: "Nombre de la parte %s (hasta 12)",
pjRc1: "El FM-1 no lo permitió (el proyecto abierto no se puede pisar ni mover, o la parte está vacía).", pjRc2: "Falló la memoria del FM-1: el destino quedó como estaba.", pjRc3: "Está sonando: pará la música (STOP) y probá de nuevo.", pjRc4: "El destino tiene un proyecto.",
cvTitle: "Proyectos viejos (antes de V10.7)", cvHelp: "Si el FM-1 dice «OLD PROJECT: OPEN IN STUDIO», acá se actualizan: Studio guarda primero todo en este navegador, encuentra los proyectos viejos y convierte solo esos.",
cvDevice: "Revisar y convertir el FM-1", cvFile: "Convertir un archivo de backup…", cvChecking: "Buscando proyectos viejos…", cvNoChecker: "No se pudo cargar el firmware para revisarlos; probá de nuevo.",
cvNone: "No hay proyectos viejos: todo abre con este firmware.", cvFound: "Proyectos viejos: %s (sin convertir).", cvConfirm: "Hay %n proyecto(s) viejo(s): %s.\nYa quedó un backup completo en este navegador. ¿Convertirlos y escribirlos en el FM-1?",
cvConverting: "Convirtiendo %s…", cvDone: "Listo: %s convertidos. Abrilos en el FM-1 (SAVE › PROJECTS).", cvFileDone: "Listo: %s convertidos; se bajó el archivo nuevo.", cvFail: "No se pudo convertir: %s", cvBefore: "Antes de convertir",
vVis: "Visuales", visTitle: "Visuales que viven de la música", visLead: "El generador de visuales de JIANT BYTE en grande, para una pantalla o un proyector: cada canción arma su receta (ingredientes de las pantallas de BYTE, mezclados y deformados) y todo reacciona a los golpes, al bajo y a los acordes. Funciona con BYTE por USB, con el emulador o con cualquier aparato MIDI.",
visSrc: "Fuente", visSrcUsb: "%s por USB (la receta del equipo)", visSrcEmu: "El emulador", visStart: "▶ Empezar", visStop: "Parar", visPal: "PALETA", visNew: "Otra receta",
visNoEmu: "Prendé el emulador (pestaña Emulador) y volvé a empezar.", visOld: "El equipo no respondió: los visuales por USB necesitan JIANT BYTE con VIS.", visNone: "VIS no disponible en esta versión de JIANT BYTE. Probá con el emulador o con cualquier aparato MIDI.", visNoneEmu: "VIS no disponible en esta versión de JIANT BYTE: Studio dibuja con lo que suena el emulador.",
tourV_visT: "Visuales", tourV_vis: "Visuales generativos que se mueven con la música, para proyectar.", tourV_visH: "Con BYTE, el emulador o cualquier MIDI.",
vPe: "Proyecto", peTitle: "El proyecto entero", peLead: "Todo el proyecto en grande: SONG, SEQ, SONIDO, MOD · MIX y GEN. Guardalo en un archivo, mandalo al FM-1 o traelo. Funciona con el FM-1 por USB y con el emulador.",
peUnnamed: "SIN NOMBRE", peImport: "Abrir .%s", peExport: "Guardar .%s", peSend: "Enviar al FM-1", peFetch: "Traer del FM-1", peSound: "SONIDO",
peSoon_song: "SONG llega con el firmware que guarda las secciones de cada canción (mutes, patrón, FILL, mutación y automatización): las secciones sobre las 6 pistas, para arrastrar y estirar.",
peSoon_seq: "SEQ llega con el largo de nota, la probabilidad y el micro-timing en el firmware: un piano roll por pista.",
peSoon_mod: "MOD · MIX llega en la próxima entrega: la matriz completa con montos ±200 %, niveles, paneo, envíos y efectos.",
peSoon_gen: "GEN llega cuando el emulador pueda regenerar una pista o una sección: género, semilla, MOOD, ENERGY, y lo que cambiaste respecto del original.",
peNoDev: "Conectá el FM-1 o prendé el emulador.", peAsk: "Leé las pistas del proyecto que está sonando.", peRead: "Leer el proyecto", peReading: "Leyendo…", peFail: "No se pudo completar", peTrackParams: "Pista (comunes)", peGenEmu: "GEN se maneja con el emulador: prendelo en la pestaña Emulador y elegilo arriba.", peGenOld: "Este emulador no tiene el generador para Studio todavía.", peGenNow: "LO QUE HIZO EL GENERADOR", peGenNew: "Nueva pieza", peGenTrack: "Regenerar solo la pista:", peGenSection: "Regenerar solo la sección:", peGenHelp: "Regenerar una pista o una sección deja el resto como está (la sección A rehace la pieza entera). Lo que generó queda guardado como original: al guardar el proyecto, el archivo lleva el original y tus cambios.", peGenHelpNoState: "Este emulador no devuelve el estado del generador: se puede regenerar, pero el archivo no puede llevar el original.", peGenBack: "Volver al original", peGenBackConfirm: "¿Volver a la pieza que generó el generador? Se pierden los cambios hechos con GEN.", peGenBackDone: "Volviste al original.", peGenChanged: "Cambiaste la pieza respecto del original.", peGenSame: "Es la pieza original.", peSeqPick: "Elegí una pista para leer sus pasos.", peSeqRefused: "El FM-1 no aceptó el cambio (¿está sonando la cadena de canción?).", peSeqHelp: "Clic en una celda: agrega o saca una nota (hasta 4 por paso). VEL, PROB y µTIME: clic a la altura que querés. µTIME (−32..+31 sesentaicuatroavos) es solo de la web: el FM-1 lo toca igual.", peSeqHelpOld: "Clic en una celda: agrega o saca una nota. VEL y PROB: clic a la altura que querés. El micro-timing, el largo y los componentes llegan con un firmware que los exponga.", peModMatrix: "MATRIZ MOD", peModMix: "MEZCLA (NIVEL DE CADA PISTA)", peModFx: "EFECTOS Y MASTER", peSongRead: "Leer la canción", peSongAsk: "Lee las secciones de las canciones del FM-1.", peSongOld: "El índice de canciones de este firmware es de otra versión: actualizá JIANT BYTE.", peSongN: "Proyecto", peSongEmpty: "Este proyecto no tiene filas de canción todavía.", peSongSec: "SECCIÓN", peSongCell: "Clic: mute · clic derecho: variación", peSongHelp: "Cada columna es una fila de la canción (su parte A–D y sus compases). Clic en una celda: mute de esa pista en esa fila; clic derecho: su variación (FILL, REV, OCT…). La letra en la celda es el patrón A–D de esa pista.", peSongApply: "Aplicar al FM-1", peSongUndo: "Deshacer", peSongConfirm: "Se escribe el índice de canciones del FM-1 (las filas, mutes y variaciones de los 6 proyectos). ¿Seguir?", peSongDone: "Canción aplicada.", peFmTitle: "FÓRMULA PROPIA (MATH USER)", peFmFamily: "Familia", peFmChaos: "Caos", peFmGen: "Generar", peFmPlay: "▶ Escuchar", peFmStop: "■ Parar", peFmSend: "Mandar a la pista", peFmClear: "Borrar del equipo", peFmNoLib: "No se pudo cargar el compilador de fórmulas del editor de JIANT FM.", peFmOld: "Este firmware no recibe fórmulas propias: hace falta JIANT FM V10.8.75 o posterior.", peFmHelp: "Escribí una fórmula de t (un bytebeat como t*(t>>5|t>>8), o con sin(w) un floatbeat), o tocá Generar. Escuchala y mandala: la pista pasa a ALGO USER.", peFmUnknown: "La pista tiene una fórmula propia (%n bytes) que no se escribió en este navegador: escribí una nueva para reemplazarla.", peFmErr: "Error:", peFmRefused: "El equipo no aceptó la fórmula.", peFmSent: "Fórmula mandada a %s (ALGO USER). Guardá el proyecto para conservarla.", peFmCleared: "Fórmula borrada.", peFormula: "FÓRMULA DE LA PISTA", peFormulaSend: "Mandar la fórmula", peFormulaOk: "Fórmula enviada.", peFormulaCut: "Enviada, pero cortada a 255 caracteres.", peOnlyChanged: "Ver solo las que cambiaron (las otras están en su valor de fábrica)",
peSaved: "Archivo guardado.", peLoaded: "Abierto: %s. Tocá «Enviar al FM-1» para cargarlo.", peBadFile: "Ese archivo no es un proyecto de Studio.", peNoFile: "Primero abrí un archivo de proyecto.",
peSendConfirm: "Se va a reemplazar la música de %n por «%s». Antes queda un backup completo en este navegador. ¿Seguir?", peSending: "Enviando… ", peSent: "Listo: el proyecto está en el FM-1.", peBefore: "Antes de enviar un proyecto",
tourV_peT: "Proyecto", tourV_pe: "El proyecto entero en grande: guardarlo, enviarlo y editar todo el sonido.", tourV_peH: "Hoy anda SONIDO; el resto llega con el firmware.",
vAn: "Análisis", anTitle: "Análisis: los datos exactos", anLead: "Lee del FM-1 o del emulador todo lo que tiene: cada pista con su motor, preset, nivel y cada parámetro con su nombre y valor (y cuáles cambiaron), los globales y los efectos, los pasos, la canción y el generador. Con el emulador escucha además unos segundos: nivel, picos, cuánto sostiene cada pista y su espectro. Bajá el archivo o copiá el resumen y pasalo tal cual.",
anGo: "Analizar", anSteps: "Incluir los pasos", anAudio: "Escuchar 8 s del emulador", anFrom: "De: %s (elige la pista de a una un instante y vuelve a la tuya)", anNoDev: "Conectá el FM-1 o prendé el emulador.",
anDone: "Listo.", anFail: "No se pudo leer todo", anJson: "Bajar el archivo (JSON)", anCopy: "Copiar el resumen", anCopied: "Resumen copiado.", anNoCopy: "No se pudo copiar: seleccioná el texto.",
tourV_anT: "Análisis", tourV_an: "Los datos exactos del equipo o del emulador en un archivo, para mandar cuando algo suena raro.", tourV_anH: "Con el emulador también mide cómo suena cada pista.",
rdUndo: "Volver al sonido anterior",
vRadio: "Radio", rdTitle: "Sintonizá la radio JIANT", rdAsk: "Ayudame a mejorarla calificando las canciones", rdAskLive: "Ayudame a mejorarla: calificá esta canción", rdLead: "Piezas nuevas del generador, una tras otra, y un ecosistema que vive de la música: cada pista mueve a sus seres. Decí si te gusta cada pieza; con tus votos el generador mejora. Subí el volumen.",
rdStart: "Empezar", rdStop: "Parar", rdGenre: "Género", rdMood: "MOOD", rdSeed: "semilla", rdThanks: "Votos: %n · ¡gracias!",
rdNoEmu: "No se pudo prender el emulador: probá de nuevo, o prendelo en la pestaña Emulador.", rdOld: "El emulador publicado todavía no tiene RADIO para esta página: llega con su próxima versión.",
rdPrivacy: "Tu voto guarda solo los datos de la pieza (versión, género, semilla) y si te gustó; nada personal. Sirve para mejorar el generador.",
tourV_radioT: "Radio", tourV_radio: "Escuchá piezas del generador en el emulador y votá cuáles te gustan.", tourV_radioH: "👍 o 👎 pasa a la siguiente; ⏭ salta sin votar.",
vWt: "Wavetables", wtTitle: "Tus wavetables para WAVE", wtLead: "Cualquier sonido (un archivo o el micrófono) se vuelve una tabla de 8 cuadros para el motor WAVE de JIANT BYTE: Studio busca el período de cada parte del sonido, toma un ciclo, lo alinea con el anterior y lo normaliza. Escuchala, bajala como WAV o mandala a una ranura USER del equipo.",
wtFile: "Cargar audio", wtMic: "Grabar con el micrófono", wtMicStop: "Parar", wtMicName: "MIC", wtRecording: "Grabando (hasta 8 s): un sonido sostenido o una frase que cambie de color. Tocá Parar.",
wtNoMic: "No se pudo abrir el micrófono (el navegador no dio permiso).", wtMade: "%s → 8 cuadros de 128 muestras.", wtSilent: "Ese audio está en silencio.", wtBad: "No pude leer ese archivo de audio.",
wtFrames: "Los 8 cuadros", wtFramesHelp: "WAVE barre del cuadro 1 al 8 con su perilla de posición; tocá un cuadro para verlo al frente.", wtPlay: "Escuchar el barrido", wtWav: "Bajar WAV",
wtSlots: "Ranuras USER del equipo", wtReadSlots: "Leer ranuras", wtSlot: "Ranura", wtName: "Nombre", wtSend: "Mandar al equipo", wtLoad: "Traer del equipo", wtEmpty: "vacía",
wtByteOnly: "Las wavetables de usuario son de JIANT BYTE: elegí BYTE arriba.", wtNoDev: "Conectá el FM-1 con JIANT BYTE (o prendé el emulador) para mandarla.", wtAsk: "Leé las ranuras para ver qué tiene el equipo.",
wtSlotsHelp: "Las ranuras USER de %s; la tabla suena apenas llega y queda guardada al terminar.", wtSent: "Listo: %n en %s.", wtLoaded: "%s traída del equipo.", wtOld: "El equipo no respondió: hace falta una versión de JIANT BYTE con wavetables de usuario. Actualizalo desde Instalar.",
wtBusy: "El equipo está guardando: probá de nuevo en un momento.", wtSlotBad: "Esa ranura no existe en el equipo.",
tourV_wtT: "Wavetables", tourV_wt: "Convertí cualquier sonido en una wavetable para WAVE de JIANT BYTE y mandala al equipo.", tourV_wtH: "Funciona mejor con sonidos sostenidos: una voz, una cuerda, un drone.",
vProj: "Proyectos", projTitle: "Proyectos y backups",
projLead: "Tus proyectos y backups. Un backup guarda todo (la música actual, las canciones con sus secciones, los sonidos de usuario y los ajustes) en este navegador y, si querés, en un archivo. Restaurarlo lo devuelve al aparato tal cual. Funciona con la FM-1 conectada o con el emulador.",
bkNow: "Hacer backup ahora", bkImport: "Importar archivo…", bkAlsoFile: "Descargar también el archivo", bkLibTitle: "Backups", bkLibHelp: "Guardados en este navegador (no se suben a ningún lado). Descargá los importantes: si se borran los datos del navegador, se pierden.",
bkEmpty: "Todavía no hay backups. «Hacer backup ahora» guarda el primero.", bkDownload: "Descargar", bkRestore: "Restaurar", bkDelete: "Borrar",
bkWorking: "Haciendo el backup… ", bkRestoring: "Restaurando… ", bkDone: "Backup guardado: %s", bkRestored: "Backup restaurado en %s", bkRestoredBut: "Restaurado; estas canciones no entraron en este firmware: %s",
bkFail: "No se pudo: %s", bkNoDev: "Conectá la FM-1 (Inicio › Buscar) o prendé el emulador.", bkConfirm: "¿Restaurar «%s» en %s? Reemplaza la música actual, las canciones, los sonidos de usuario y los ajustes. No desconectes el USB.",
bkDelConfirm: "¿Borrar «%s» de este navegador?", bkOther: "Backup de otro firmware: se restaura con su propio editor", bkImported: "Importado: %s", bkBadFile: "Ese archivo no es un backup de JIANT",
bkMusic: "música actual", bkSongs: "%n canciones", bkSections: "%n secciones", bkTarget: "el emulador",
slotsTitle: "Proyectos A–D", slotsHelp: "Las cuatro ranuras de proyecto del aparato. Cargar trae el proyecto a la música actual; Guardar escribe la música actual en la ranura.",
slotsRead: "Leer ranuras", slotUsed: "con proyecto", slotEmpty: "vacía", slotUnknown: "sin leer", slotLoad: "Cargar", slotSave: "Guardar acá",
slotLoadConfirm: "¿Cargar el proyecto %s? Reemplaza la música actual (guardala antes si la querés).", slotSaveConfirm: "¿Guardar la música actual en %s? Reemplaza el proyecto que tiene.",
slotLoaded: "Proyecto %s cargado", slotSaved: "Música actual guardada en %s",
vDocs: "Manuales", docsLeadFm: "Todo para aprender JIANT FM: el manual interactivo (tocá cualquier control del FM-1 y mirá qué hace), el manual completo y las dos hojas de ayuda para tener a mano.",
docsLeadByte: "Todo para aprender JIANT BYTE: el manual interactivo, el manual completo y sus hojas de ayuda. Lo que todavía no está publicado dice «en camino».",
docInter: "Manual interactivo", docInterText: "El FM-1 dibujado: tocá un control y mirá qué hace solo, mantenido y en combinación, con la pantalla a la que lleva. Tutorial paso a paso, buscador de comandos y recetas.",
docInterTextByte: "El panel de JIANT BYTE: cada control, sus capas y combinaciones, las fórmulas y los motores, con la pantalla a la que lleva.",
docOpenHere: "Abrir acá", docNewTab: "Abrir en otra pestaña", docFull: "Manual completo", docFullText: "Cada botón, perilla y mensaje con el nombre que muestra el aparato; índice que sigue la lectura. Para leer o imprimir.",
docCtl: "Hoja de ayuda · Controles", docCtlText: "Las seis reglas de navegación, cada botón, capa, combinación y página en una hoja.",
docSnd: "Hoja de ayuda · Sonido", docSndText: "Los motores, sus parámetros y los efectos en una hoja.", docView: "Ver", docPdf: "PDF", docPng: "Imagen",
docSoon: "en camino", docNew: "Lo nuevo", docNewText: "Qué cambió en la última versión, con capturas.", docMap: "Mapa de navegación", docMapText: "Cada sección, sus grupos y páginas en el orden en que se recorren.",
docPorts: "Manuales de otros aparatos", docPortsText: "SMK-37, MPC Sample, el plugin de MPC y el plugin VST3 · AU · LV2.",
other: "English", vPorts: "Otros equipos", vHome: "Inicio", vInstall: "Instalar", vEditor: "Editor", vScreen: "Pantalla en vivo", vEmu: "Emulador", vRec: "Grabar",
tFm1: "FM-1", tEmu: "Emulador", target: "Destino",
eyebrow: "Un firmware libre para la M-VAVE FM-1",
vidCap: "La presentación: todas las funciones nuevas, una por una, en el emulador.",
leadFm: "Síntesis, secuencias, mutación y escena en vivo. Instalalo, editalo, mirá su pantalla en grande y grabá, todo desde acá.",
leadByte: "Bytebeat y floatbeat: cada sonido, batería y animación es una fórmula del tiempo. Instalalo, editalo y grabá desde acá.",
needBrowser: "Chrome o Edge", needCable: "Un cable USB de datos", needPhone: "Celular Android con USB-C (OTG)",
s1Title: "Conectá la FM-1", s1Text: "Enchufala directo a esta computadora o celular, sin hub, y prendela. Cuando el navegador pida usar dispositivos MIDI, elegí Permitir.",
find: "Buscar FM-1", forget: "Soltar la FM-1",
s2Title: "Instalá o actualizá", s2Text: "Elegí el firmware. Antes de escribir, el instalador hace un backup y todas las demás herramientas sueltan la FM-1 solas.",
fmPitch: "Seis pistas vivas, once motores, secuenciador de 64 pasos, canciones, generador y efectos.",
bytePitch: "Fórmulas como voces: MATH, WAVE y DRUM-X con fórmulas. LIFE: las pistas se escuchan entre sí.",
s3Title: "Usala", s3Text: "Todo con la misma conexión. Arriba elegís si trabajás con la FM-1 por USB o con el emulador.",
toolEditor: "Sonidos, pasos, pistas, proyectos y backups desde la computadora.",
toolScreen: "La pantalla de la FM-1 en grande, a pantalla completa en el celular.",
toolEmu: "La FM-1 en el navegador, con sonido. Tocala con un teclado MIDI.",
toolRec: "Master o stems en WAV, y lo que tocaste en MIDI.",
hSafeQ: "¿Es seguro tener el editor o el emulador abiertos mientras instalo?",
hSafeA: "Sí. Cuando el instalador empieza a escribir, avisa a todas las pestañas y marcos de JIANT FM y JIANT BYTE: el editor se desconecta, la pantalla se apaga y el emulador deja de escuchar MIDI, y el instalador espera a que cada uno confirme antes de mandar el primer byte. Nadie se vuelve a conectar hasta que termina. Cerrá otros programas de música que usen la FM-1 (un DAW, otro editor): esos no se enteran.",
hStopQ: "Si la instalación se cortó", hStopA: "La FM-1 queda en modo actualización: volvé a enchufarla (o prendela) en esta misma página y la instalación sigue desde donde quedó.",
hDeadQ: "Si la FM-1 no arranca", hDeadA: "Abrí Instalar: el instalador la encuentra en modo actualización y la recupera. Si ni así responde, hace falta un FM-1-transporter (está explicado en el instalador).",
hPhoneQ: "¿Funciona en el celular?", hPhoneA: "En Android con Chrome, enchufando la FM-1 al USB-C del teléfono (un cable o adaptador OTG). En iPhone no: Safari no tiene Web MIDI.",
devNone: "sin FM-1", devLooking: "buscando…", devGone: "FM-1 desconectada", devBusy: "instalando en otra pestaña", devMock: "(simulada)",
found: "Encontrada: ", foundNot: "No aparece ninguna FM-1 con JIANT. Si tiene otro firmware o el oficial, instalá JIANT FM o JIANT BYTE desde el paso 2.",
noMidi: "Este navegador no tiene Web MIDI: usá Chrome o Edge (en iPhone no hay).", denied: "El navegador no dio permiso para MIDI.",
nowBusy: "Un instalador está escribiendo: la FM-1 quedó libre para él.",
instTitleFm: "JIANT FM", instTitleByte: "JIANT BYTE",
instSafe: "Mientras el instalador escribe, el editor, la pantalla y el emulador de esta página (y de otras pestañas) sueltan la FM-1 y esperan. No desenchufes ni apagues la FM-1 hasta que termine.",
edTarget: "Destino: ", edEmuNote: "Editando el emulador: el editor habla con la FM-1 del navegador (pestaña Emulador). Prendelo ahí primero.",
scrTitle: "La pantalla, en grande", scrStart: "Mostrar", scrStop: "Detener", scrFull: "Pantalla completa", scrExitFull: "Salir",
scrSharp: "Píxeles nítidos", scrWaitFm1: "Conectá la FM-1 (Inicio) y tocá Mostrar.", scrWaitEmu: "Prendé el emulador en la pestaña Emulador y tocá Mostrar.",
scrNo: "Este firmware no tiene espejo de pantalla: actualizá JIANT FM o JIANT BYTE.",
scrNoFw: "Tu FM-1 tiene %s, que todavía no trae el espejo de pantalla: llega con la próxima versión del firmware. Mientras tanto, elegí Emulador arriba y mirá la pantalla del emulador.",
scrNoShort: "sin espejo de pantalla (llega en la próxima versión)",
scrHelpFm1: "La FM-1 manda solo lo que cambia: una pantalla quieta no cuesta nada. Mientras se ve acá, la interfaz de la FM-1 puede ir un poco más lenta en páginas muy animadas; el sonido no cambia.",
scrHelpEmu: "La pantalla del emulador, cuadro a cuadro.",
scrOrient: "La pantalla de la FM-1 es cuadrada (240 × 240). En vertical ocupa todo el ancho; en horizontal, todo el alto, con los controles al costado. A pantalla completa queda centrada y lo más grande posible en las dos posiciones: girá el celular como te quede cómodo.",
scrRate: " KB/s", scrFps: " cuadros/s", scrWaiting: "esperando la imagen…",
emuMidi: "MIDI que toca el emulador", emuMidiAll: "Todas las entradas", emuMidiNone: "Ninguna", emuMidiOff: "(prendé el emulador)",
recGuideT: "Paso a paso: grabar el emulador en la compu y bajar la pista", recG1: "Arriba elegí «Emulador» (en vez de FM-1) y abrí la pestaña EMULADOR: tocá Prender. Ya suena en la compu, sin la FM-1.", recG2: "Hacé tu música en el emulador: el mouse o el teclado de la compu tocan los botones (Z–' y Q–O son las teclas).", recG3: "Pasá a esta pestaña, GRABAR. En Entrada elegí «Emulador JIANT · master (estéreo)» para una sola pista, o «· stems (8 canales)» para cada pista por separado.", recG4: "Tocá Grabar, dale PLAY en el emulador y, cuando termines, Detener. La toma aparece abajo, en Tomas.", recG5: "Bajala: «WAV master» es la mezcla en un archivo; «Stems (ZIP)» trae un WAV por pista, alineados, para tu DAW; «MIDI» las notas.", recG6: "En tu DAW (Ableton, Reaper, FL…): arrastrá los WAV a pistas nuevas, todos desde el compás 1. Ya quedan sincronizados.", emuOpts: "Opciones: versión y MIDI", leadMore: "Leer más", spListen: "ESCUCHAR", spListenS: "radio, visuales", spListenL: "Escuchar y mirar", spCreate: "CREAR", spCreateS: "emulador, sonido", spCreateL: "Hacer música", spRec: "GRABAR", spRecS: "tomas, stems", spRecL: "Grabar y llevarte el audio", spManage: "GESTIONAR", spManageS: "proyectos, backups", spManageL: "Ordenar lo que hiciste", spDevice: "APARATO", spDeviceS: "conectar, instalar", spDeviceL: "El FM-1: conexión, entrar y salir", spLearn: "APRENDER", spLearnS: "guías, manuales", spLearnL: "Entender JIANT", spConnFm1: "Usar el FM-1 (USB)", spConnEmu: "Usar el emulador", spBackup: "Backup ahora", spExportProj: "Exportar proyecto", spImport: "Importar archivo", spExportAudio: "Exportar audio", spStems: "Stems de una canción", spStemsD: "Cada pista de un backup en su WAV, exactas, también en el celular.", spHomeT: "Inicio", vEd: "Editor de audio", edTitle: "Editor de audio", edLead: "Tus tomas y tus archivos en pistas, como en un DAW: cortá, recortá, mové, poné fundidos, subí la ganancia, normalizá, invertí y duplicá, con deshacer. Después bajá la mezcla en WAV o cada pista en un ZIP. Todo pasa en el navegador.", edAdd: "Agregar la toma", edFile: "Importar audio", edEdit: "Editar", tourV_ed: "Tus tomas y archivos en pistas: cortar, recortar, fundidos, ganancia, normalizar, y exportar la mezcla o cada pista.", tourV_edT: "Editor de audio", ed_split: "CORTAR", ed_dup: "DUPLICAR", ed_rev: "INVERTIR", ed_norm: "NORMALIZAR", ed_del: "BORRAR", ed_snap: "IMÁN", ed_expMix: "Bajar la mezcla (WAV)", ed_expTracks: "Cada pista (ZIP)", ed_empty: "Todavía no hay pistas. Grabá una toma (GRABAR) y tocá «Agregar la toma», o importá un archivo de audio.", ed_added: "Agregado: %s", ed_pick: "Elegí un clip (tocalo).", ed_pickHelp: "Tocá un clip para elegirlo: arrastralo para moverlo, sus bordes para recortarlo. La regla de arriba mueve la posición. Teclas: espacio, S cortar, D duplicar, Supr borrar, Ctrl+Z deshacer.", ed_splitHere: "Poné la posición dentro del clip para cortarlo ahí.", ed_undone: "Deshecho.", ed_gain: "GANANCIA", ed_fin: "FUNDIDO ENTRA", ed_fout: "FUNDIDO SALE", ed_rendering: "Mezclando…", ed_exported: "Listo: está en tus descargas.", recArrive: "llegan %n canales", recFewerAndroid: "Llegan %got canales y la FM-1 manda %need. Es un límite de Chrome en Android con este teléfono: el sistema sí recibe todas las pistas por USB (una app nativa las graba), pero Chrome le pasa a la página solo %got. Para cada pista por separado en el celular: la app JIANT Probe graba los stems en vivo, o «Stems de una canción» (abajo) arma cada pista exacta desde un backup. En una computadora con Chrome o Edge llegan todas.", stNoRenderer: "El emulador publicado no tiene el armador de stems: avisale a Juan. Mientras tanto, grabá en vivo con «Emulador JIANT · stems».", recTitle: "Grabar", recAudio: "Audio", recInput: "Entrada", recStart: "Grabar", recStop: "Detener",
recProfile: "Modo USB de la FM-1 (MENU › SYSTEM › USB)", profAuto: "Detectar por los canales que llegan",
profMaster: "AUDIO · STEREO · IN+OUT: el master (2 canales)", profStems: "STEMS: 8 canales (T1–T6, FX L R)",
profStemsIn: "STEMS+IN: 10 canales (T1–T6, FX L R, VOX, DRY)",
profHelp_auto: "Studio mira cuántos canales llegan y los nombra: 2 el master, 8 STEMS, 10 STEMS+IN. Después de cambiar el modo en la FM-1, desenchufala y enchufala.",
profHelp_master: "En la FM-1: MENU › SYSTEM › USB › AUDIO (o STEREO, o IN+OUT) y reenchufá. Llega el master estéreo, como suena.",
profHelp_stems: "En la FM-1: MENU › SYSTEM › USB › STEMS y reenchufá. Cada pista en mono antes del master (sin limitador ni MASTER) y la vuelta de efectos en estéreo: su suma es la mezcla. USB LEVEL en −6 dB o menos deja margen.",
profHelp_stemsin: "En la FM-1: MENU › SYSTEM › USB › STEMS+IN y reenchufá. Como STEMS más dos canales de voz: VOX (la voz como la mezcló la última pista) y DRY (la voz como llegó); lo que suena en este dispositivo entra a la FM-1 como voz.",
recMonitor: "Probar entrada", recMonitorStop: "Cerrar entrada", recPlay: "▶ Escuchar la toma", recPlayStop: "■ Parar",
recDawEmpty: "Tocá Probar entrada: aparece un carril por cada canal que llega, con su nivel. Grabar dibuja cada pista mientras suena.",
recFewerLong: "Llegan %got canales y el modo de la FM-1 manda %need. Fijate que en Entrada esté elegida la FM-1 (en Android suele llamarse «USB audio»), no «Predeterminado», que es el micrófono del teléfono. Si aun así llegan menos: los stems de una canción desde un backup (abajo) son exactos y sin límite. Si estás en una computadora: después de cambiar el modo USB de la FM-1, desenchufala y volvé a enchufarla, y recargá esta página. En Windows, además: Configuración de sonido › Más opciones › Grabación › la FM-1 › Propiedades › Opciones avanzadas: elegí el formato de 8 canales.",
laneTrack: "pista, mono", lane_L: "master izquierdo", lane_R: "master derecho", lane_FXL: "efectos, izquierda", lane_FXR: "efectos, derecha",
lane_VOX: "la voz mezclada", lane_DRY: "la voz como llegó", recMute: "Silenciar", recSolo: "Solo",
stWhat: "Qué", stLive: "La sección que suena (8 compases)", stGo: "Stems desde la FM-1", stFile: "…o desde un backup",
stReading: "Leyendo el backup de la FM-1… ", stRender: "Armando los stems: ", stDone: "Listo: el ZIP con cada pista está en tus descargas, y cada WAV abajo, en Tomas.", stNeedDev: "Conectá la FM-1 (Inicio) o prendé el emulador, o elegí un archivo de backup.",
recSaved: "Toma guardada: está abajo, en Tomas.",
recSrcFm1: "La FM-1 por USB es una entrada de audio: estéreo (USB > AUDIO), u 8 canales en USB > STEMS (las 6 pistas y los efectos por separado). Elegila acá.",
recSrcEmu: "Graba la salida del emulador (prendelo en la pestaña Emulador).",
recEmuStems: "Emulador JIANT · stems (8 canales)", recEmuMaster: "Emulador JIANT · master (estéreo)", recEmuMidi: "Emulador JIANT · MIDI OUT",
recEmuOff: "Prendé el emulador en la pestaña Emulador (Prender) y volvé.", recEmuOld: "El emulador publicado todavía no entrega stems ni MIDI: llegan con su próxima versión. Mientras tanto: «master (estéreo)».", recEmuStemsHelp: "Del emulador, como USB STEMS: cada pista sola (T1–T6) y la vuelta de efectos (FX L R), antes del master; se graban juntas y se exportan como WAV por pista, el ZIP y la mezcla.",
recEmuMidiHelp: "Las notas que manda MIDI OUT del emulador (MENU › CONTROL › MIDI OUT: KEYS las teclas, ALL también el secuenciador y el arpegiador).",
recNoDev: "No hay entradas de audio (dale permiso al micrófono para verlas).", recAsk: "Pedir permiso de audio",
recMidi: "MIDI", recMidiHelp: "Mientras grabás, también se guarda lo que entra por MIDI: lo que tocás en la FM-1 (MENU > MIDI OUT) o en un teclado.",
recMidiIn: "Entrada MIDI", recMidiNone: "(ninguna)",
recStems: "Stems de una canción", recStemsHelp: "Exactos y sin límite de canales, también en el celular: Studio lee la canción de la FM-1 por USB (o un archivo de backup) y la toca en el emulador una vez por pista. Cada pista en su WAV, alineadas al sample.",
recStemsGo: "Abrir el emulador",
recTakes: "Tomas", recNone: "Todavía no grabaste nada.", recWav: "WAV master", recStemsZip: "Stems (ZIP)", recMid: "MIDI",
recChannels: " canales", recNotes: " notas",
portsTitle: "JIANT FM en otros aparatos",
portsLead: "El mismo firmware, de las mismas fuentes, en otras máquinas: una canción suena igual en todas. En las CPU grandes suma los motores SAMPLE y GRAIN, DRUM-X con samples y 8 voces por pista. Todos gratis y GPL-3.0; algunos todavía buscan quién los pruebe.",
shotSmk: "el panel del SMK-37 con JIANT en el emulador", shotMpc: "la MPC Sample con JIANT en el emulador",
shotDaw: "el editor del plugin: pantalla en vivo y pistas", shotDawSound: "el editor del plugin: el sonido",
shotDawSamples: "el editor del plugin: el explorador de samples", portsManuals: "Manuales",
portsHow: "Cómo funcionan", portTry: "Probar en el navegador", portDownload: "Descargar", portManual: "Manual", portInstall: "Cómo instalar",
portSource: "Código", portBuild: "Compilar", smkInstaller: "Instalador",
stOk: "funciona", stSoon: "próximamente", portSoonBuy: "Próximamente a la venta", stPreview: "preview: buscamos testers", stDev: "en desarrollo", stCi: "compilado en CI",
pSmkTitle: "M-VAVE SMK-37 Pro / Elite", pSmkText: "JIANT directo en el chip del SMK-37 (el mismo AC791N que la FM-1): 37 teclas, 16 pads RGB, 8 encoders y 4 faders como panel. Usa el mismo editor web.",
pSmk1: "Pads con color por pista", pSmk2: "El mismo editor y los mismos sonidos que la FM-1",
pMpcTitle: "Akai MPC Sample", pMpcText: "JIANT como el instrumento entero de la MPC Sample: su pantalla, sus pads, botones y perillas como el panel de la FM-1, arrancando desde la microSD.",
pMpc1: "SAMPLE, GRAIN y DRUM-X con samples", pMpc2: "16 slots de samples de 60 s, grabación desde la entrada",
pPlugMpcTitle: "Plugin para MPC", pPlugMpcText: "JIANT FM como instrumento dentro de las MPC standalone (MPC OS 3.10.1 o más nuevo) y de hosts VST2 de escritorio.",
pPlugMpc1: "ARM32, ARM64 y escritorio", pPlugMpc2: "Pasa el simulador de host del SDK; falta probarlo en una MPC",
pDawTitle: "VST3 · AU · LV2 · app", pDawText: "Para tu DAW o el iPad (AUM, GarageBand, Logic, Cubasis…), con un editor hecho para DAW: la pantalla en vivo, las seis pistas, los presets y parámetros de cada sonido, y un navegador de samples con arrastrar y soltar.",
pDaw1: "Hasta 8 JIANT en una sesión, cada uno el suyo", pDaw2: "La app standalone responde al editor web (con un cable MIDI virtual)",
pDaw3: "VST3 (macOS, Windows, Linux), AU y AUv3 (macOS, iPadOS), LV2 (Linux), standalone",
foot: "JIANT Studio, de Juan Jiant",
},
en: {
lvNow: "· On screen:", lvLayer: "layer", lvLayerWhat: "You are holding %s: the keys and knobs do something else while you hold it.", lvPressed: "pressed", lvButton: "You pressed %s.",
lvChip: "● Live", lvLead: "Play your FM-1 and watch here: every knob you turn, the engine you pick, the steps and play explain themselves as they happen.",
lvStartBtn: "Follow my FM-1", lvStopBtn: "Stop following", lvOff: "Connect the FM-1 (Home › Find) or switch the emulator on, and press “Follow my FM-1”.",
lvNoDev: "No FM-1 connected and no emulator on.", lvWaiting: "Following %s: touch something…", lvTouch: "Following: turn a knob, change the sound or press play.",
lvTrack: "Track", lvGlobal: "Global", lvSound: "Sound", lvPreset: "preset", lvStep: "Step", lvBar: "bar",
lvUnknown: "A parameter of this page.", lvReload: "You changed the sound: the engine and its preset on the selected track.", lvStepWhat: "You edited a step of this track's sequence.",
lvPlay: "The music is playing: the sequencer moves step by step.", lvStop: "Playback stopped.", lvPunch: "Hold FX and play keys: an effect sounds only while you hold it.",
lvPunchOn: "an effect on", lvPunchOff: "none", lvMutate: "MUTATE changed this track's pattern.", lvPage: "The page on screen and its knobs.", lvMore: "See it in the guide:",
tourOpen: "Quick tour", tourNext: "Next", tourPrev: "Back", tourSkip: "Skip", tourDone: "Done",
tourWelcomeT: "Welcome to JIANT Studio", tourWelcome: "Everything for your FM-1 in one page: install the firmware, edit it, see its screen big, play the emulator, record, keep your projects and learn how it works. Here is where each thing is.",
tourWelcomeH: "A few steps; skip it and come back whenever you want with the ? button at the top.",
tourFwT: "JIANT FM or JIANT BYTE", tourFw: "Pick the firmware: FM (synthesis) or BYTE (formulas). Studio changes its tools, manuals and look to match.", tourFwH: "Connect an FM-1 and Studio picks it by itself.",
tourTargetT: "FM-1 or Emulator", tourTarget: "What are you working with? Your FM-1 over USB, or the emulator: the real firmware running in the browser.", tourTargetH: "The editor, the screen, recording and the live guide use what you pick here.",
tourDevT: "Your FM-1", tourDev: "Here you see whether an FM-1 is connected, and its firmware and version.", tourDevH: "Green: connected. If something does not answer, forget it and find it again.",
tourFindT: "Find the FM-1", tourFind: "Connect the FM-1 with a USB data cable and press Find: Studio finds it over MIDI.", tourFindH: "Works in Chrome or Edge (computer) and Chrome on Android.",
tourV_installT: "Install", tourV_install: "Installs or updates the firmware, with a backup first. First you read the warnings and accept; then three steps.", tourV_installH: "While it installs, everything else lets go of the FM-1 so nothing interrupts it.",
tourV_editorT: "Editor", tourV_editor: "Every sound and setting of the FM-1 on screen: engines, presets, knobs, sequences, projects.", tourV_editorH: "What you change here changes on the device at once, and the other way round.",
tourV_screenT: "Screen", tourV_screen: "The FM-1's screen, big and live, even full screen on your phone.", tourV_screenH: "Press Show; it turns by itself, landscape or portrait.",
tourV_emuT: "Emulator", tourV_emu: "The real firmware in the browser, played with the mouse, the computer keyboard or a MIDI keyboard.", tourV_emuH: "It goes full screen; choose which MIDI input plays it.",
tourV_recT: "Record", tourV_rec: "Records the master or each track apart (stems), as WAV and MIDI, with tracks as in a DAW.", tourV_recH: "From the FM-1 over USB (STEMS mode) or straight from the emulator.",
tourV_projT: "Projects", tourV_proj: "Your project slots A–D and backups by hand, kept in this browser.", tourV_projH: "Back up before installing or trying something new.",
tourV_learnT: "How it works", tourV_learn: "Every engine, sequencer, effect, modulator and generator, explained with animations. And Live: play the FM-1 and Studio tells you what you moved.", tourV_learnH: "Start with the Index or ● Live.",
tourV_docsT: "Manuals", tourV_docs: "The interactive manual, the full manual and the cheat sheets of each firmware.", tourV_docsH: "The cheat sheets print well.",
tourV_rescueT: "Rescue", tourV_rescue: "If an FM-1 does not turn on or show over USB, an RP2040 board can bring it back: a step-by-step tutorial.", tourV_rescueH: "Only for FM-1s that do not start; if it starts, use Install.",
tourV_portsT: "Other devices", tourV_ports: "JIANT on the SMK-37 and the MPC Sample, with their emulators and manuals, and the plugins coming.", tourV_portsH: "Try them in the browser without the device.",
tourLangT: "Language", tourLang: "Switch between Spanish and English.",
tourEndT: "Done", tourEnd: "This tour comes back whenever you want with this button.", tourEndH: "To start: connect your FM-1 and press Find, or pick Emulator and switch it on.",
siteLink: "%s's site: what it is, its screens and its story →", vLearn: "How it works", lrIndex: "Index", lrIndexLead: "Everything at a glance: tap any element to open its page. ← and → go to the next one.", lrTitleFm: "Inside JIANT FM", lrTitleByte: "Inside JIANT BYTE", lrTry: "Try it in the emulator", lrWhere: "On the FM-1: ", lrSince: "since %s", lrNone: "This guide is still being written.",
vRescue: "Rescue", rsTitle: "Rescue an FM-1", rsBeta: "experimental · not tried on hardware yet",
rsLead: "For an FM-1 that does not turn on, or that the computer does not see over USB (hard brick). A few-dollar RP2040 board does it all by itself: wired to the FM-1's USB-C with three wires, it writes the firmware again. No Python, no terminal: Studio makes the board's file.",
rsFirstT: "Before you start", rsFirst: "If the FM-1 turns on and the computer sees it (even stuck or sounding wrong), you do not need this: use Install, which updates it over USB.", rsToInstall: "Go to Install",
rs1: "What you need", rsNeedBoard: "An RP2040 board: Waveshare RP2040-Zero, Seeed XIAO RP2040 or Raspberry Pi Pico (or a similar one).",
rsNeedUsb: "A USB-C cable you can cut (or a USB-C plug with wires), to reach its wires: green (D+), white (D−), black (GND) and red (5 V, unused).",
rsNeedWires: "A soldering iron or dupont wires to join those three wires to the board.", rsNeedBatt: "The FM-1 with its battery charged.", rsNeedPc: "A computer with Chrome, Edge or Firefox (or a USB charger for step 6).",
rs2: "Your board and the wires", rsCable: "A cut cable: green = D+, white = D−, black = GND, red = 5 V. The red one stays unconnected (tape it). If the board cannot talk to the FM-1, try swapping green and white.",
rsWireZero: "RP2040-Zero: green → pin 0, white → pin 1, black → GND. Its LED is in colours (the table in step 6).",
rsWireXiao: "XIAO RP2040: green → D6, white → D7, black → GND. Its LED is in colours (the table in step 6).",
rsWirePico: "Raspberry Pi Pico (and Pico-style boards): green → GP0 (pin 1), white → GP1 (pin 2), black → GND (pin 3). Its LED has one colour: slow blink = waiting, fast = error, steady = done.",
rs3: "The firmware it will get", rsFwFile: "Another file…", rsFwHelp: "Simplest: JIANT FM or JIANT BYTE, the published package, which Studio downloads by itself. M-VAVE's official V15 FM-1.fwsc works too (not V16: it does not fit). If your FM-1 came with V16, use JIANT. Nothing leaves your browser.",
rsFwGet: "Downloading the published %s package…", rsFwOk: "Checked: %s", rsFwBad: "Not usable: %s", rsLdGet: "Downloading JieLi's loader (jl-uboot-tool, MIT)…", rsLdOk: "JieLi's loader checked", rsLdBad: "JieLi's loader could not be downloaded: %s. Try again in a while.",
rs4: "Make the board's file", rsMakeHelp: "Puts your board's rescue firmware, the chosen firmware and the loader into one fm1-rescue.uf2, and downloads it.", rsMake: "Make fm1-rescue.uf2", rsMade: "Done: fm1-rescue.uf2 downloaded (%s, %n KB)", rsNeedFw: "The firmware is missing (step 3).",
rs5: "Flash the board", rs6: "Connect and rescue", rs7: "Afterwards",
rsAfter: "Switch the FM-1 off, remove the wires and switch it on: it boots the chosen firmware. From there you can update or change it as always, with Install. Your settings, sounds and songs are not touched.",
rsLedT: "What the LED says",
rsAndroidT: "No computer: the FM-1 Rescue app", rsAndroid: "Does the same from an Android phone: flashes the board over OTG and shows the rescue's progress. Still a test version: it downloads from GitHub (Actions › android › Artifacts › fm1-rescue) while signed in.",
rsAndroidHow: "How to use it", rsAndroidApk: "Get the APK", rsMore: "How it works",
rsSafe: "Only the firmware area (0x4000–0x92FFF) is written, sector by sector, each read back and compared; the boot head and your data are not touched. Without a firmware inside, the board is a plain FM-1 Transporter. Built on FM-1 Transporter (Hügelton Instruments), MvaveFM1Unbricker (Quixotic7), jl-uboot-tool (kagaimiq) and GoodPerson42's guide. Use it with a charged battery and at your own risk: it has not been tried on a real FM-1 yet.",
rdLiked: "What did you like? (optional)", rdDisliked: "What didn't you like? (optional)", rdNext: "Next", rdpDrums: "Drums", rdpBass: "Bass", rdpChords: "Chords", rdpLead: "Lead", rdpArp: "Arp", rdpSound: "Sound/mix",
rdStarting: "Starting…", rdEmuOn: "Switching the emulator on…",
emuVer: "Version", emuVerPinned: "This site's (recommended)", emuVerPublic: "public", emuVerBeta: "Beta (the latest, to try)", emuVerConfirm: "Changing the version restarts the emulator (each version keeps its own memory). Go on?",
gPlay: "Play", gMake: "Make", gLearn: "Learn", gDevice: "Device",
pathFm1E: "I have an FM-1", pathFm1: "Connect it and use it", pathFm1T: "Install JIANT, edit the sounds, keep projects, record and watch its screen.",
pathTryE: "I don't have one", pathTry: "Try it without one", pathTryT: "The radio and the emulator: the whole FM-1 in the browser, playing now.",
pathLearnE: "I want to learn", pathLearn: "How it works", pathLearnT: "Every engine, sequencer and effect, animated, and the manuals.",
cNone: "No device connected.", cFm1: "FM-1 connected: %s", cBusy: "The FM-1 is busy (installing or in another tab).", cLooking: "Looking for the FM-1…",
cEmuOn: "Using the emulator (on).", cEmuOff: "Using the emulator (off).", cFind: "Find my FM-1", cUseEmu: "Use the emulator", cUseFm1: "Use my FM-1", cOpenEmu: "Open the emulator",
pjTitle: "Project library", pjRead: "Read the projects", pjAsk: "Read the FM-1's projects: their names and which parts A–D they hold.", pjHelp: "Type a name and press Enter: it changes on the FM-1 at once. Before anything is overwritten or deleted, a copy of it is downloaded.",
pjOld: "The FM-1 did not answer: the library needs JIANT FM V10.8.54 or later, or a JIANT BYTE version with it (on its way).", pjUnnamed: "untitled", pjName: "Project name", pjOpen: "OPEN",
pjCopy: "Copy to…", pjMove: "Move to…", pjEmpty: "Empty", pjShare: "Share", pjDownload: "Download", pjGFile: "FILE", pjGCopy: "COPY TO", pjGMove: "MOVE TO", pjGParts: "THE PARTS' NAMES", pjGName: "NAME", pjSaveName: "Save", pjMore: "More tools: projects A–D and old projects", pjTap: "Tap a project to see what you can do with it.", pjEmptyHelp: "This place is empty: import a project from a file.", pjBusyNow: "Working…", pjExport: "Export", pjImport: "Import here", pjDelete: "Delete", pjParts: "Name parts",
pjCopyTo: "Copy project %s to which project? (1–6)", pjMoveTo: "Move project %s to which project? (1–6)", pjBadTarget: "That target does not work: pick another project, 1 to 6.",
pjOverwrite: "Project %s (“%n”) holds music and will be overwritten. A copy is downloaded first. Go on?", pjDelConfirm: "Delete project %s (“%n”)? A copy is downloaded first.",
pjSaving: "Saving a copy…", pjWriting: "Writing part %s…", pjDone: "Done.", pjRenamed: "Renamed: %s", pjBadFile: "That file is not a project exported from Studio.",
pjPartWhich: "Which part to name? (B, C or D; A is the project's name)", pjPartName: "Name of part %s (up to 12)",
pjRc1: "The FM-1 did not allow it (the open project cannot be overwritten or moved, or the part is empty).", pjRc2: "The FM-1's memory failed: the target is as it was.", pjRc3: "It is playing: stop the music (STOP) and try again.", pjRc4: "The target holds a project.",
cvTitle: "Old projects (before V10.7)", cvHelp: "If the FM-1 says “OLD PROJECT: OPEN IN STUDIO”, they are brought up to date here: Studio first keeps everything in this browser, finds the old projects and converts only those.",
cvDevice: "Check and convert the FM-1", cvFile: "Convert a backup file…", cvChecking: "Looking for old projects…", cvNoChecker: "The firmware to check them could not be loaded; try again.",
cvNone: "No old projects: everything opens with this firmware.", cvFound: "Old projects: %s (not converted).", cvConfirm: "There are %n old project(s): %s.\nA full backup is already kept in this browser. Convert them and write them to the FM-1?",
cvConverting: "Converting %s…", cvDone: "Done: %s converted. Open them on the FM-1 (SAVE › PROJECTS).", cvFileDone: "Done: %s converted; the new file was downloaded.", cvFail: "Could not convert: %s", cvBefore: "Before converting",
vVis: "Visuals", visTitle: "Visuals that live on the music", visLead: "JIANT BYTE's visual generator, big, for a screen or a projector: each song makes its recipe (ingredients from BYTE's screens, mixed and bent) and everything reacts to the hits, the bass and the chords. Works with BYTE over USB, the emulator or any MIDI device.",
visSrc: "Source", visSrcUsb: "%s over USB (the device's recipe)", visSrcEmu: "The emulator", visStart: "▶ Start", visStop: "Stop", visPal: "PALETTE", visNew: "Another recipe",
visNoEmu: "Switch the emulator on (Emulator tab) and start again.", visOld: "The device did not answer: visuals over USB need JIANT BYTE with VIS.", visNone: "VIS is not available in this JIANT BYTE version. Try the emulator or any MIDI device.", visNoneEmu: "VIS is not available in this JIANT BYTE version: Studio draws from what the emulator plays.",
tourV_visT: "Visuals", tourV_vis: "Generative visuals moving with the music, to project.", tourV_visH: "With BYTE, the emulator or any MIDI device.",
vPe: "Project", peTitle: "The whole project", peLead: "The whole project, big: SONG, SEQ, SOUND, MOD · MIX and GEN. Keep it in a file, send it to the FM-1 or fetch it. Works with the FM-1 over USB and with the emulator.",
peUnnamed: "UNTITLED", peImport: "Open .%s", peExport: "Save .%s", peSend: "Send to the FM-1", peFetch: "Fetch from the FM-1", peSound: "SOUND",
peSoon_song: "SONG arrives with the firmware that keeps each song's sections (mutes, pattern, FILL, mutation and automation): the sections over the 6 tracks, to drag and stretch.",
peSoon_seq: "SEQ arrives with note length, probability and micro-timing in the firmware: a piano roll per track.",
peSoon_mod: "MOD · MIX arrives in the next delivery: the full matrix with ±200 % amounts, levels, pan, sends and effects.",
peSoon_gen: "GEN arrives when the emulator can regenerate one track or one section: genre, seed, MOOD, ENERGY, and what you changed from the original.",
peNoDev: "Connect the FM-1 or switch the emulator on.", peAsk: "Read the tracks of the project playing.", peRead: "Read the project", peReading: "Reading…", peFail: "Could not complete", peTrackParams: "Track (common)", peGenEmu: "GEN works with the emulator: switch it on in the Emulator tab and pick it above.", peGenOld: "This emulator does not have the generator for Studio yet.", peGenNow: "WHAT THE GENERATOR MADE", peGenNew: "New piece", peGenTrack: "Regenerate only the track:", peGenSection: "Regenerate only the section:", peGenHelp: "Regenerating a track or a section leaves the rest as it is (section A remakes the whole piece). What it made is kept as the original: when you save the project, the file carries the original and your changes.", peGenHelpNoState: "This emulator does not return the generator's state: you can regenerate, but the file cannot carry the original.", peGenBack: "Back to the original", peGenBackConfirm: "Go back to the piece the generator made? Changes made with GEN are lost.", peGenBackDone: "Back to the original.", peGenChanged: "You changed the piece from the original.", peGenSame: "This is the original piece.", peSeqPick: "Pick a track to read its steps.", peSeqRefused: "The FM-1 did not take the change (is the song chain playing?).", peSeqHelp: "Click a cell: add or remove a note (up to 4 a step). VEL, PROB and µTIME: click at the height you want. µTIME (−32..+31 64ths) is web-only: the FM-1 plays it all the same.", peSeqHelpOld: "Click a cell: add or remove a note. VEL and PROB: click at the height you want. Micro-timing, length and components come with a firmware that exposes them.", peModMatrix: "MOD MATRIX", peModMix: "MIX (EACH TRACK'S LEVEL)", peModFx: "EFFECTS AND MASTER", peSongRead: "Read the song", peSongAsk: "Reads the sections of the FM-1's songs.", peSongOld: "This firmware's song index is another version: update JIANT BYTE.", peSongN: "Project", peSongEmpty: "This project has no song rows yet.", peSongSec: "SECTION", peSongCell: "Click: mute · right click: variation", peSongHelp: "Each column is a song row (its part A–D and its bars). Click a cell: mute that track in that row; right click: its variation (FILL, REV, OCT…). The letter in the cell is that track's pattern A–D.", peSongApply: "Apply to the FM-1", peSongUndo: "Undo", peSongConfirm: "The FM-1's song index is written (the rows, mutes and variations of all 6 projects). Go on?", peSongDone: "Song applied.", peFmTitle: "YOUR OWN FORMULA (MATH USER)", peFmFamily: "Family", peFmChaos: "Chaos", peFmGen: "Generate", peFmPlay: "▶ Listen", peFmStop: "■ Stop", peFmSend: "Send to the track", peFmClear: "Clear from the device", peFmNoLib: "Could not load the JIANT FM editor's formula compiler.", peFmOld: "This firmware takes no formulas of one's own: it needs JIANT FM V10.8.75 or later.", peFmHelp: "Type a formula of t (a bytebeat such as t*(t>>5|t>>8), or with sin(w) a floatbeat), or press Generate. Listen to it and send it: the track becomes ALGO USER.", peFmUnknown: "The track holds a formula of its own (%n bytes) not written in this browser: type a new one to replace it.", peFmErr: "Error:", peFmRefused: "The device did not take the formula.", peFmSent: "Formula sent to %s (ALGO USER). Save the project to keep it.", peFmCleared: "Formula cleared.", peFormula: "THE TRACK'S FORMULA", peFormulaSend: "Send the formula", peFormulaOk: "Formula sent.", peFormulaCut: "Sent, but cut at 255 characters.", peOnlyChanged: "Show only the changed ones (the rest are at their defaults)",
peSaved: "File saved.", peLoaded: "Opened: %s. Press “Send to the FM-1” to load it.", peBadFile: "That file is not a Studio project.", peNoFile: "Open a project file first.",
peSendConfirm: "The music on %n will be replaced by “%s”. A full backup is kept in this browser first. Go on?", peSending: "Sending… ", peSent: "Done: the project is on the FM-1.", peBefore: "Before sending a project",
tourV_peT: "Project", tourV_pe: "The whole project, big: keep it, send it and edit all of its sound.", tourV_peH: "SOUND works today; the rest comes with the firmware.",
vAn: "Analysis", anTitle: "Analysis: the exact data", anLead: "Reads everything the FM-1 or the emulator holds: each track with its engine, preset, level and every parameter by name and value (and which ones changed), the globals and effects, the steps, the song and the generator. From the emulator it also listens for a few seconds: level, peaks, how long each track sustains and its spectrum. Download the file or copy the summary and pass it on as it is.",
anGo: "Analyze", anSteps: "Include the steps", anAudio: "Listen to 8 s of the emulator", anFrom: "From: %s (selects each track for an instant and goes back to yours)", anNoDev: "Connect the FM-1 or switch the emulator on.",
anDone: "Done.", anFail: "Not everything could be read", anJson: "Download the file (JSON)", anCopy: "Copy the summary", anCopied: "Summary copied.", anNoCopy: "Could not copy: select the text.",
tourV_anT: "Analysis", tourV_an: "The device's or the emulator's exact data in a file, to send when something sounds wrong.", tourV_anH: "From the emulator it also measures how each track sounds.",
rdUndo: "Back to the previous sound",
vRadio: "Radio", rdTitle: "Tune in to JIANT radio", rdAsk: "Help me make it better by rating the songs", rdAskLive: "Help me make it better: rate this song", rdLead: "New pieces from the generator, one after another, and an ecosystem that lives on the music: each track moves its beings. Say whether you like each piece; your votes make the generator better. Turn the volume up.",
rdStart: "Start", rdStop: "Stop", rdGenre: "Genre", rdMood: "MOOD", rdSeed: "seed", rdThanks: "Votes: %n · thank you!",
rdNoEmu: "The emulator could not be switched on: try again, or switch it on in the Emulator tab.", rdOld: "The published emulator does not have RADIO for this page yet: it comes with its next version.",
rdPrivacy: "Your vote keeps only the piece's data (version, genre, seed) and whether you liked it; nothing personal. It helps improve the generator.",
tourV_radioT: "Radio", tourV_radio: "Listen to the generator's pieces on the emulator and vote for the ones you like.", tourV_radioH: "👍 or 👎 moves to the next one; ⏭ skips without a vote.",
vWt: "Wavetables", wtTitle: "Your wavetables for WAVE", wtLead: "Any sound (a file or the microphone) becomes an 8-frame table for JIANT BYTE's WAVE engine: Studio finds the period of each part of the sound, takes one cycle, aligns it with the one before and normalizes it. Hear it, download it as a WAV or send it to one of the device's USER slots.",
wtFile: "Load audio", wtMic: "Record from the microphone", wtMicStop: "Stop", wtMicName: "MIC", wtRecording: "Recording (up to 8 s): a held sound or a phrase that changes colour. Press Stop.",
wtNoMic: "The microphone could not be opened (the browser gave no permission).", wtMade: "%s → 8 frames of 128 samples.", wtSilent: "That audio is silent.", wtBad: "That audio file could not be read.",
wtFrames: "The 8 frames", wtFramesHelp: "WAVE sweeps from frame 1 to 8 with its position knob; tap a frame to bring it to the front.", wtPlay: "Hear the sweep", wtWav: "Download WAV",
wtSlots: "The device's USER slots", wtReadSlots: "Read slots", wtSlot: "Slot", wtName: "Name", wtSend: "Send to the device", wtLoad: "Get from the device", wtEmpty: "empty",
wtByteOnly: "User wavetables are JIANT BYTE's: pick BYTE above.", wtNoDev: "Connect the FM-1 with JIANT BYTE (or switch the emulator on) to send it.", wtAsk: "Read the slots to see what the device holds.",
wtSlotsHelp: "%s's USER slots; the table sounds as soon as it arrives and is saved when it is done.", wtSent: "Done: %n in %s.", wtLoaded: "%s fetched from the device.", wtOld: "The device did not answer: this needs a JIANT BYTE version with user wavetables. Update it from Install.",
wtBusy: "The device is saving: try again in a moment.", wtSlotBad: "That slot does not exist on the device.",
tourV_wtT: "Wavetables", tourV_wt: "Turn any sound into a wavetable for JIANT BYTE's WAVE and send it to the device.", tourV_wtH: "Works best with held sounds: a voice, a string, a drone.",
vProj: "Projects", projTitle: "Projects and backups",
projLead: "Your projects and backups. A backup keeps everything (the current music, the songs and their sections, the user sounds and the settings) in this browser and, if you want, in a file. Restoring it puts it back on the device as it was. Works with the FM-1 connected or with the emulator.",
bkNow: "Back up now", bkImport: "Import a file…", bkAlsoFile: "Also download the file", bkLibTitle: "Backups", bkLibHelp: "Kept in this browser (nothing is uploaded). Download the ones that matter: clearing the browser's data loses them.",
bkEmpty: "No backups yet. “Back up now” keeps the first.", bkDownload: "Download", bkRestore: "Restore", bkDelete: "Delete",
bkWorking: "Backing up… ", bkRestoring: "Restoring… ", bkDone: "Backup kept: %s", bkRestored: "Backup restored on %s", bkRestoredBut: "Restored; these songs did not fit this firmware: %s",
bkFail: "Could not: %s", bkNoDev: "Connect the FM-1 (Home › Find) or switch the emulator on.", bkConfirm: "Restore “%s” on %s? It replaces the current music, the songs, the user sounds and the settings. Keep USB connected.",
bkDelConfirm: "Delete “%s” from this browser?", bkOther: "Another firmware's backup: restore it with its own editor", bkImported: "Imported: %s", bkBadFile: "That file is not a JIANT backup",
bkMusic: "current music", bkSongs: "%n songs", bkSections: "%n sections", bkTarget: "the emulator",
slotsTitle: "Projects A–D", slotsHelp: "The device's four project slots. Load brings a project into the current music; Save writes the current music into the slot.",
slotsRead: "Read the slots", slotUsed: "holds a project", slotEmpty: "empty", slotUnknown: "not read", slotLoad: "Load", slotSave: "Save here",
slotLoadConfirm: "Load project %s? It replaces the current music (save it first if you want it).", slotSaveConfirm: "Save the current music into %s? It replaces the project there.",
slotLoaded: "Project %s loaded", slotSaved: "Current music saved into %s",
vDocs: "Manuals", docsLeadFm: "Everything to learn JIANT FM: the interactive manual (touch any control of the FM-1 and see what it does), the full manual and the two cheat sheets to keep at hand.",
docsLeadByte: "Everything to learn JIANT BYTE: the interactive manual, the full manual and its cheat sheets. What is not published yet says “on its way”.",
docInter: "Interactive manual", docInterText: "The FM-1 drawn: touch a control to see what it does alone, held and in combination, with the screen it leads to. A step-by-step tutorial, a command search and recipes.",
docInterTextByte: "JIANT BYTE's panel: every control, its layers and combos, the formulas and the engines, with the screen it leads to.",
docOpenHere: "Open here", docNewTab: "Open in a new tab", docFull: "Full manual", docFullText: "Every button, knob and message named as the device shows it; contents that follow your reading. To read or print.",
docCtl: "Cheat sheet · Controls", docCtlText: "The six navigation rules, every button, layer, combo and page on one sheet.",
docSnd: "Cheat sheet · Sound", docSndText: "The engines, their parameters and the effects on one sheet.", docView: "View", docPdf: "PDF", docPng: "Image",
docSoon: "on its way", docNew: "What's new", docNewText: "What changed in the latest version, with screenshots.", docMap: "Navigation map", docMapText: "Every section, its groups and pages in the order you walk them.",
docPorts: "Manuals for other devices", docPortsText: "SMK-37, MPC Sample, the MPC plugin and the VST3 · AU · LV2 plugin.",
other: "Español", vPorts: "Other devices", vHome: "Home", vInstall: "Install", vEditor: "Editor", vScreen: "Live screen", vEmu: "Emulator", vRec: "Record",
tFm1: "FM-1", tEmu: "Emulator", target: "Target",
eyebrow: "A free firmware for the M-VAVE FM-1",
vidCap: "The presentation: every new feature, one by one, on the emulator.",
leadFm: "Synthesis, sequencing, mutation and performance. Install it, edit it, see its screen big and record, all from here.",
leadByte: "Bytebeat and floatbeat: every sound, drum and animation is a formula of time. Install it, edit it and record from here.",
needBrowser: "Chrome or Edge", needCable: "A USB data cable", needPhone: "Android phone with USB-C (OTG)",
s1Title: "Connect the FM-1", s1Text: "Plug it straight into this computer or phone, without a hub, and switch it on. When the browser asks to use MIDI devices, choose Allow.",
find: "Find FM-1", forget: "Let the FM-1 go",
s2Title: "Install or update", s2Text: "Pick the firmware. Before writing, the installer makes a backup and every other tool lets the FM-1 go by itself.",
fmPitch: "Six living tracks, eleven engines, a 64-step sequencer, songs, a generator and effects.",
bytePitch: "Formulas as voices: MATH, WAVE and DRUM-X with formulas. LIFE: the tracks hear each other.",
s3Title: "Use it", s3Text: "All over one connection. Up top you choose the FM-1 over USB or the emulator.",
toolEditor: "Sounds, steps, tracks, projects and backups from the computer.",
toolScreen: "The FM-1's screen big, full screen on a phone.",
toolEmu: "The FM-1 in the browser, with sound. Play it from a MIDI keyboard.",
toolRec: "Master or stems as WAV, and what you played as MIDI.",
hSafeQ: "Is it safe to keep the editor or the emulator open while installing?",
hSafeA: "Yes. When the installer starts writing it tells every JIANT FM and JIANT BYTE tab and frame: the editor disconnects, the screen stops and the emulator stops listening to MIDI, and the installer waits until each one confirms before the first byte goes out. Nothing reconnects until it has finished. Close other music software using the FM-1 (a DAW, another editor): those are not told.",
hStopQ: "If an installation stopped", hStopA: "The FM-1 stays in update mode: plug it back in (or switch it on) on this same page and the install carries on where it stopped.",
hDeadQ: "If the FM-1 won't start", hDeadA: "Open Install: the installer finds it in update mode and recovers it. If it still does not answer, an FM-1-transporter is needed (explained in the installer).",
hPhoneQ: "Does it work on a phone?", hPhoneA: "On Android with Chrome, with the FM-1 plugged into the phone's USB-C (an OTG cable or adapter). Not on iPhone: Safari has no Web MIDI.",
devNone: "no FM-1", devLooking: "looking…", devGone: "FM-1 unplugged", devBusy: "installing in another tab", devMock: "(simulated)",
found: "Found: ", foundNot: "No FM-1 with JIANT answers. If it runs other or official firmware, install JIANT FM or JIANT BYTE in step 2.",
noMidi: "This browser has no Web MIDI: use Chrome or Edge (none on iPhone).", denied: "The browser did not allow MIDI.",
nowBusy: "An installer is writing: the FM-1 was let go for it.",
instTitleFm: "JIANT FM", instTitleByte: "JIANT BYTE",
instSafe: "While the installer writes, the editor, the screen and the emulator on this page (and in other tabs) let the FM-1 go and wait. Do not unplug or switch off the FM-1 until it has finished.",
edTarget: "Target: ", edEmuNote: "Editing the emulator: the editor talks to the FM-1 in the browser (Emulator tab). Switch it on there first.",
scrTitle: "The screen, big", scrStart: "Show", scrStop: "Stop", scrFull: "Full screen", scrExitFull: "Exit",
scrSharp: "Sharp pixels", scrWaitFm1: "Connect the FM-1 (Home) and press Show.", scrWaitEmu: "Switch the emulator on in the Emulator tab and press Show.",
scrNo: "This firmware has no screen mirror: update JIANT FM or JIANT BYTE.",
scrNoFw: "Your FM-1 runs %s, which has no screen mirror yet: it comes with the next firmware release. Meanwhile pick Emulator up top and see the emulator's screen.",
scrNoShort: "no screen mirror (comes in the next release)",
scrHelpFm1: "The FM-1 sends only what changes: a screen at rest costs nothing. While it shows here the FM-1's UI may run a little slower on very animated pages; the sound does not change.",
scrHelpEmu: "The emulator's screen, frame by frame.",
scrOrient: "The FM-1's screen is square (240 × 240). In portrait it fills the width; in landscape, the height, with the controls beside it. Full screen keeps it centred and as big as it gets either way: turn the phone as you like.",
scrRate: " KB/s", scrFps: " frames/s", scrWaiting: "waiting for the picture…",
emuMidi: "MIDI that plays the emulator", emuMidiAll: "Every input", emuMidiNone: "None", emuMidiOff: "(switch the emulator on)",
recGuideT: "Step by step: record the emulator on a computer and download the track", recG1: "At the top pick «Emulator» (instead of FM-1) and open the EMULATOR tab: press Switch on. It plays on the computer, no FM-1 needed.", recG2: "Make your music in the emulator: the mouse or the computer keyboard plays the buttons (Z–' and Q–O are the keys).", recG3: "Come to this tab, RECORD. In Input pick «JIANT emulator · master (stereo)» for one track, or «· stems (8 channels)» for each track apart.", recG4: "Press Record, press PLAY in the emulator and, when you are done, Stop. The take appears below, in Takes.", recG5: "Download it: «WAV master» is the mix in one file; «Stems (ZIP)» has one WAV per track, aligned, for your DAW; «MIDI» the notes.", recG6: "In your DAW (Ableton, Reaper, FL…): drag the WAVs onto new tracks, all from bar 1. They are already in sync.", emuOpts: "Options: version and MIDI", leadMore: "Read more", spListen: "LISTEN", spListenS: "radio, visuals", spListenL: "Listen and watch", spCreate: "CREATE", spCreateS: "emulator, sound", spCreateL: "Make music", spRec: "RECORD", spRecS: "takes, stems", spRecL: "Record and take the audio with you", spManage: "MANAGE", spManageS: "projects, backups", spManageL: "Keep what you made in order", spDevice: "DEVICE", spDeviceS: "connect, install", spDeviceL: "The FM-1: connection, in and out", spLearn: "LEARN", spLearnS: "guides, manuals", spLearnL: "Understand JIANT", spConnFm1: "Use the FM-1 (USB)", spConnEmu: "Use the emulator", spBackup: "Back up now", spExportProj: "Export the project", spImport: "Import a file", spExportAudio: "Export audio", spStems: "A song's stems", spStemsD: "Each track of a backup in its own WAV, exact, on a phone too.", spHomeT: "Home", vEd: "Audio editor", edTitle: "Audio editor", edLead: "Your takes and files on tracks, as in a DAW: cut, trim, move, fade, raise the gain, normalize, reverse and duplicate, with undo. Then download the mix as a WAV or each track in a ZIP. It all happens in the browser.", edAdd: "Add the take", edFile: "Import audio", edEdit: "Edit", tourV_ed: "Your takes and files on tracks: cut, trim, fades, gain, normalize, and export the mix or each track.", tourV_edT: "Audio editor", ed_split: "CUT", ed_dup: "DUPLICATE", ed_rev: "REVERSE", ed_norm: "NORMALIZE", ed_del: "DELETE", ed_snap: "SNAP", ed_expMix: "Download the mix (WAV)", ed_expTracks: "Each track (ZIP)", ed_empty: "No tracks yet. Record a take (RECORD) and press «Add the take», or import an audio file.", ed_added: "Added: %s", ed_pick: "Pick a clip (tap it).", ed_pickHelp: "Tap a clip to pick it: drag it to move it, its edges to trim it. The ruler on top moves the position. Keys: space, S cut, D duplicate, Del delete, Ctrl+Z undo.", ed_splitHere: "Put the position inside the clip to cut it there.", ed_undone: "Undone.", ed_gain: "GAIN", ed_fin: "FADE IN", ed_fout: "FADE OUT", ed_rendering: "Mixing…", ed_exported: "Done: it is in your downloads.", recArrive: "%n channels arrive", recFewerAndroid: "%got channels come in and the FM-1 sends %need. It is a limit of Chrome on Android with this phone: the system does receive every track over USB (a native app records them), but Chrome hands only %got to the page. For each track apart on the phone: the JIANT Probe app records the stems live, or «A song's stems» (below) makes each track exact from a backup. On a computer with Chrome or Edge they all come in.", stNoRenderer: "The published emulator lacks its stems renderer: tell Juan. Meanwhile, record live with «JIANT emulator · stems».", recTitle: "Record", recAudio: "Audio", recInput: "Input", recStart: "Record", recStop: "Stop",
recProfile: "The FM-1's USB mode (MENU › SYSTEM › USB)", profAuto: "Detect by the channels that come in",
profMaster: "AUDIO · STEREO · IN+OUT: the master (2 channels)", profStems: "STEMS: 8 channels (T1–T6, FX L R)",
profStemsIn: "STEMS+IN: 10 channels (T1–T6, FX L R, VOX, DRY)",
profHelp_auto: "Studio counts the channels that come in and names them: 2 the master, 8 STEMS, 10 STEMS+IN. After changing the mode on the FM-1, unplug it and plug it in again.",
profHelp_master: "On the FM-1: MENU › SYSTEM › USB › AUDIO (or STEREO, or IN+OUT), then plug it in again. The stereo master comes in, as it sounds.",
profHelp_stems: "On the FM-1: MENU › SYSTEM › USB › STEMS, then plug it in again. Each track mono before the master (no limiter, no MASTER knob) and the effects' return in stereo: their sum is the mix. USB LEVEL at −6 dB or lower leaves headroom.",
profHelp_stemsin: "On the FM-1: MENU › SYSTEM › USB › STEMS+IN, then plug it in again. STEMS plus two voice channels: VOX (the voice as the last track mixed it) and DRY (the voice as it came); what this device plays goes into the FM-1 as the voice.",
recMonitor: "Test the input", recMonitorStop: "Close the input", recPlay: "▶ Play the take", recPlayStop: "■ Stop",
recDawEmpty: "Press Test the input: a lane shows for each channel that comes in, with its level. Record draws each track as it plays.",
recFewerLong: "%got channels come in and the FM-1's mode sends %need. Check that Input is the FM-1 (on Android it is often called «USB audio»), not «Default», which is the phone's microphone. If fewer still come in: a song's stems from a backup (below) are exact and unlimited. On a computer: after changing the FM-1's USB mode, unplug it, plug it back and reload this page. On Windows, also: Sound settings › More sound settings › Recording › the FM-1 › Properties › Advanced: pick the 8-channel format.",
laneTrack: "track, mono", lane_L: "master left", lane_R: "master right", lane_FXL: "effects, left", lane_FXR: "effects, right",
lane_VOX: "the voice as mixed", lane_DRY: "the voice as it came", recMute: "Mute", recSolo: "Solo",
stWhat: "What", stLive: "The section playing (8 bars)", stGo: "Stems from the FM-1", stFile: "…or from a backup",
stReading: "Reading the FM-1's backup… ", stRender: "Making the stems: ", stDone: "Done: the ZIP with each track is in your downloads, and each WAV below, in Takes.", stNeedDev: "Connect the FM-1 (Home) or switch the emulator on, or pick a backup file.",
recSaved: "Take saved: it is below, under Takes.",
recSrcFm1: "The FM-1 over USB is an audio input: stereo (USB > AUDIO), or 8 channels in USB > STEMS (the 6 tracks and the effects apart). Pick it here.",
recSrcEmu: "Records the emulator's output (switch it on in the Emulator tab).",
recEmuStems: "JIANT emulator · stems (8 channels)", recEmuMaster: "JIANT emulator · master (stereo)", recEmuMidi: "JIANT emulator · MIDI OUT",
recEmuOff: "Switch the emulator on in the Emulator tab (Switch on) and come back.", recEmuOld: "The published emulator does not give stems or MIDI yet: they come with its next version. Meanwhile: “master (stereo)”.", recEmuStemsHelp: "From the emulator, as USB STEMS: each track alone (T1–T6) and the effects' return (FX L R), before the master; recorded together, exported as a WAV per track, the ZIP and the mix.",
recEmuMidiHelp: "The notes the emulator's MIDI OUT sends (MENU › CONTROL › MIDI OUT: KEYS the keys, ALL the sequencer and the arpeggiator too).",
recNoDev: "No audio inputs (allow the microphone to list them).", recAsk: "Ask for audio permission",
recMidi: "MIDI", recMidiHelp: "While recording, what comes in over MIDI is kept too: what you play on the FM-1 (MENU > MIDI OUT) or on a keyboard.",
recMidiIn: "MIDI input", recMidiNone: "(none)",
recStems: "A song's stems", recStemsHelp: "Exact and with no channel limit, on a phone too: Studio reads the song from the FM-1 over USB (or a backup file) and plays it in the emulator once a track. Each track its own WAV, sample-aligned.",
recStemsGo: "Open the emulator",
recTakes: "Takes", recNone: "Nothing recorded yet.", recWav: "WAV master", recStemsZip: "Stems (ZIP)", recMid: "MIDI",
recChannels: " channels", recNotes: " notes",
portsTitle: "JIANT FM on other devices",
portsLead: "The same firmware from the same sources on other machines: a song sounds the same on every one. On the bigger CPUs it adds the SAMPLE and GRAIN engines, DRUM-X with samples and 8 voices a track. All free and GPL-3.0; some are still looking for testers.",
shotSmk: "the SMK-37's panel running JIANT in the emulator", shotMpc: "the MPC Sample running JIANT in the emulator",
shotDaw: "the plugin's editor: the live screen and tracks", shotDawSound: "the plugin's editor: the sound",
shotDawSamples: "the plugin's editor: the sample browser", portsManuals: "Manuals",
portsHow: "How they work", portTry: "Try it in the browser", portDownload: "Download", portManual: "Manual", portInstall: "How to install",
portSource: "Source", portBuild: "Build", smkInstaller: "Installer",
stOk: "works", stSoon: "coming soon", portSoonBuy: "Coming soon, for sale", stPreview: "preview: testers wanted", stDev: "in development", stCi: "built by CI",
pSmkTitle: "M-VAVE SMK-37 Pro / Elite", pSmkText: "JIANT bare metal on the SMK-37's chip (the FM-1's AC791N): 37 keys, 16 RGB pads, 8 encoders and 4 faders as its panel. The same web editor.",
pSmk1: "Pads lit in each track's colour", pSmk2: "The FM-1's editor and sounds",
pMpcTitle: "Akai MPC Sample", pMpcText: "JIANT as the MPC Sample's whole instrument: its screen, its pads, buttons and knobs as the FM-1's panel, started from the microSD card.",
pMpc1: "SAMPLE, GRAIN and DRUM-X with samples", pMpc2: "16 sample slots of 60 s, recording from the input",
pPlugMpcTitle: "MPC plugin", pPlugMpcText: "JIANT FM as an instrument inside the MPC standalones (MPC OS 3.10.1 or newer) and desktop VST2 hosts.",
pPlugMpc1: "ARM32, ARM64 and desktop", pPlugMpc2: "Passes the SDK's host simulator; not yet tried on an MPC",
pDawTitle: "VST3 · AU · LV2 · app", pDawText: "For your DAW or the iPad (AUM, GarageBand, Logic, Cubasis…), with an editor made for a DAW: the live screen, the six tracks, each sound's presets and parameters, and a sample browser with drag and drop.",
pDaw1: "Up to 8 JIANTs in one session, each its own", pDaw2: "The standalone app answers the web editor (through a virtual MIDI cable)",
pDaw3: "VST3 (macOS, Windows, Linux), AU and AUv3 (macOS, iPadOS), LV2 (Linux), standalone",
foot: "JIANT Studio, by Juan Jiant",
},
};
let lang = (() => { try { const l = localStorage.getItem("jiant.studio.lang"); if (TEXT[l]) return l; } catch (_) {} return /^es/i.test(navigator.language || "") ? "es" : "en"; })();
const t = (k) => TEXT[lang][k] ?? TEXT.en[k] ?? k;
function applyLang() {
document.documentElement.lang = lang;
document.querySelectorAll("[data-t]").forEach((e) => { e.textContent = t(e.dataset.t); });
requestAnimationFrame(clampLeads);
document.querySelectorAll("[data-t-label]").forEach((e) => e.setAttribute("aria-label", t(e.dataset.tLabel)));
$("lang").textContent = t("other");
render();
}
$("lang").addEventListener("click", () => { lang = lang === "es" ? "en" : "es"; try { localStorage.setItem("jiant.studio.lang", lang); } catch (_) {} applyLang(); });
/* ------------------------------------------------------------------------------------- where the tools live */
/* The sites: /JIANT/ (JIANT FM) and /JIANT-BYTE/ (JIANT BYTE) under one origin; this page is /JIANT/studio/. Anywhere else
* (a copy on disk) the tools come from the published sites (then they cannot hear this page: another origin). */
const ROOT = (() => { const m = location.pathname.match(/^(.*?)\/JIANT\//); return location.protocol.startsWith("http") && m ? m[1] : null; })();
const SITE = ROOT !== null ? `${ROOT}/` : "https://juanjiant-bit.github.io/";
const TOOLS = {
fm: { base: `${SITE}JIANT/`, installer: "webapp/installer/", editor: "webapp/editor/", emu: "emu/" },
byte: { base: `${SITE}JIANT-BYTE/`, installer: "webapp/installer/", editor: "webapp/editor/", emu: "emu/" },
};
const toolUrl = (fw, tool, q = "") => TOOLS[fw].base + TOOLS[fw][tool] + q;
/* ------------------------------------------------------------------------------------------------ the state */
const state = {
view: "home", fw: QS.get("fw") === "byte" ? "byte" : "fm", target: QS.get("target") === "emu" ? "emu" : "fm1",
dev: null, // {link, input, output, version, kind ("fm" | "byte"), engines}
looking: false, busy: false, // busy: an installer writes (jiant-midi)
found: "", // the last result line
};
try { const f = localStorage.getItem("jiant.studio.fw"); if (!QS.get("fw") && (f === "fm" || f === "byte")) state.fw = f; } catch (_) {}
/* ------------------------------------------------------------------------------------- the USB link (SysEx) */
const HDR = [0x7D, 0x46, 0x4C];
const CMD = { INFO: 1, PING: 25, SCREEN: 78, SCREEN_DATA: 79 };
/* the pushes the live guide reads (EDITOR_PROTOCOL.md, WATCH): CHANGED 23, RELOAD 24, STEP_CHANGED 26, TRACK_CHANGED 32,
TRANSPORT 40, PUNCH 41, MUTATE 42, and (when the firmware has it) UI 43 */
const LIVE_PUSH = new Set([23, 24, 26, 32, 40, 41, 42, 43]);
const frame = (cmd, args = []) => [0xF0, ...HDR, cmd & 0x7F, ...args, 0xF7];
function unframe(d) {
if (!d || d.length < 6 || d[0] !== 0xF0 || d[d.length - 1] !== 0xF7 || d[1] !== HDR[0] || d[2] !== HDR[1] || d[3] !== HDR[2]) return null;
return { cmd: d[4], a: Array.from(d.subarray ? d.subarray(5, d.length - 1) : d.slice(5, -1)) };
}
/* one request at a time, each matched by its command (the device answers in order); pushes (79) to onPush */
class Link {
constructor(output, onPush) { this.output = output; this.onPush = onPush; this.q = []; this.cur = null; this.lastSent = 0; this.closed = false; }
request(cmd, args = [], timeout = 600, match = null) {
if (this.closed) return Promise.reject(new Error("closed"));
return new Promise((res, rej) => { this.q.push({ cmd, args, res, rej, timeout, match }); this.pump(); });
}
pump() {
if (this.cur || !this.q.length || this.closed) return;
const c = this.cur = this.q.shift();
try { this.output.send(frame(c.cmd, c.args)); this.lastSent = Date.now(); } catch (e) { this.finish(null, e); return; }
c.timer = setTimeout(() => this.finish(null, new Error("timeout")), c.timeout);
}
finish(a, err) {
const c = this.cur;
if (!c) return;
clearTimeout(c.timer); this.cur = null;
if (err) c.rej(err); else c.res(a);
this.pump();
}
receive(data) {
const f = unframe(data);
if (!f) return;
if (f.cmd === CMD.SCREEN_DATA) { this.onPush(f); return; }
if (f.cmd === 98 || f.cmd === 99) { visPush(f, this); return; } // (VIS: JIANT BYTE's visual state)
if (LIVE_PUSH.has(f.cmd)) { livePush(f, this); return; } // (the live guide: what moved on the FM-1)
if (this.cur && f.cmd === this.cur.cmd && (f.cmd !== CMD.SCREEN || f.a[0] === this.cur.args[0]) && (!this.cur.match || this.cur.match(f.a))) this.finish(f.a);
}
close() { this.closed = true; for (const c of [this.cur, ...this.q].filter(Boolean)) { clearTimeout(c.timer); c.rej(new Error("closed")); } this.cur = null; this.q = []; }
}
/* INFO: version string, NENGINES, P_COUNT, G_COUNT, NSTEP, P_E0, then the engines' names. JIANT BYTE's include MATH */
function parseInfo(a) {
let i = 0;
const str = () => { let s = ""; while (i < a.length && a[i]) s += String.fromCharCode(a[i++]); i++; return s; };
const version = str(), n = a[i], pe0 = a[i + 4], pcount = a[i + 1], gcount = a[i + 2], nstep = a[i + 3]; i += 5;
const engines = [];
for (let k = 0; k < n && i < a.length; k++) engines.push(str());
/* JIANT BYTE names itself ("JIANT BYTE v0.16"); JIANT FM does not ("JIANT V10.8.24"). (Not by its engines: JIANT FM has
MATH too since V10.8.21) */
return { version, engines, pe0, pcount, gcount, nstep, kind: /\bBYTE\b/i.test(version) ? "byte" : "fm", jiant: /^(JIANT|FELUCCA)\b/i.test(version) };
}
const PORT_RE = /felucca|jiant|skiff|fm[ _-]*1|smk[ _-]*37|m[ _-]*vave|cuvave|composite|sinco|usb[ _-]*midi|usb audio/i;
let access = null;
async function midiAccess() {
if (access) return access;
if (MOCK) return (access = mockAccess());
if (!navigator.requestMIDIAccess) throw Object.assign(new Error("nomidi"), { code: "noMidi" });
try { access = await navigator.requestMIDIAccess({ sysex: true }); }
catch (e) { throw Object.assign(new Error("denied"), { code: "denied" }); }
access.onstatechange = (e) => {
const p = e.port;
if (state.dev && p && p.state === "disconnected" && (p.id === state.dev.input.id || p.id === state.dev.output.id)) { letGo(); state.found = t("devGone"); render(); }
renderMidiInputs();
};
return access;
}
async function find() {
if (state.looking || state.busy) return;
state.looking = true; state.found = ""; render();
try {
const acc = await midiAccess();
const live = (m) => [...m.values()].filter((p) => p.state !== "disconnected");
let ins = live(acc.inputs).filter((p) => PORT_RE.test(p.name || "")), outs = live(acc.outputs).filter((p) => PORT_RE.test(p.name || ""));
if (!ins.length || !outs.length) { ins = live(acc.inputs); outs = live(acc.outputs); }
const pairs = ins.flatMap((input) => outs.map((output) => ({ input, output, s: input.name === output.name ? 1 : 0 }))).sort((x, y) => y.s - x.s);
for (const { input, output } of pairs) {
const link = new Link(output, onScreenData);
input.onmidimessage = (e) => link.receive(e.data);
try {
const info = parseInfo(await link.request(CMD.INFO, [], 900));
if (!info.jiant) throw new Error("not JIANT");
letGo();
/* does it mirror its screen? (78 SCREEN, op 0: firmware before the mirror sends no reply) */
let screen = null; // (null: it did not say; Show tries anyway)
for (let k = 0; k < 2 && screen === null; k++) {
try { const a = await link.request(CMD.SCREEN, [0], 1200); screen = a[1] === 0; } catch (_) {}
}
state.dev = { link, input, output, ...info, screen };
if (state.fw !== info.kind) setFw(info.kind);
state.found = t("found") + `${devName(state.dev)}${MOCK ? " " + t("devMock") : ""}` + (state.dev.screen === false ? " · " + t("scrNoShort") : "");
return;
} catch (_) { link.close(); input.onmidimessage = null; }
}
state.found = t("foundNot");
} catch (e) { state.found = t(e.code || "foundNot"); }
finally { state.looking = false; render(); }
}
/* "JIANT BYTE v0.16", "JIANT FM V10.8.21": the firmware's name once (its INFO says "JIANT BYTE v0.16" or "JIANT V10.8.21") */
/* on a phone a view's lead shows three lines, the rest behind "more"; on a computer it opens the emulator's options */
function clampLeads() {
const phone = matchMedia("(max-width: 640px)").matches;
const eo = document.getElementById("emuopt"); if (eo && !phone) eo.open = true;
document.querySelectorAll(".view:not([hidden]) p.lead").forEach((p) => {
const nx = p.nextElementSibling, had = nx && nx.classList.contains("leadmore");
if (had) nx.remove();
p.classList.remove("clamp"); if (!phone || p.dataset.open) return;
p.classList.add("clamp");
if (p.scrollHeight <= p.clientHeight + 2) { p.classList.remove("clamp"); return; }
const b = document.createElement("button"); b.type = "button"; b.className = "leadmore"; b.textContent = t("leadMore");
b.onclick = () => { p.dataset.open = "1"; p.classList.remove("clamp"); b.remove(); };
p.after(b);
});
}
addEventListener("resize", () => requestAnimationFrame(clampLeads));
const devName = (d) => `${d.kind === "byte" ? "JIANT BYTE" : "JIANT FM"} ${d.version.replace(/^(JIANT|FELUCCA)\s+/i, "").replace(/^(BYTE|FM)\s+/i, "")}`;
const tp = (k) => (state.fw === "byte" ? t(k).replace(/el FM-1|the FM-1/g, (m) => m.slice(0, -4) + "JIANT BYTE").replace(/FM-1/g, "JIANT BYTE") : t(k)); // the project editor's texts name the device that is connected
function letGo() {
const d = state.dev;
if (!d) return;
screenStop(false);
d.link.close();
d.input.onmidimessage = midiTap; // (the recorder keeps listening to what the FM-1 plays)
state.dev = null;
}
$("find").addEventListener("click", find);
$("forget").addEventListener("click", () => { letGo(); state.found = ""; render(); });
/* -------------------------------------------------------------------- install safety: the jiant-midi channel */
let busyUntil = 0, busyTimer = 0, midiBc = null;
try {
const bc = midiBc = new BroadcastChannel("jiant-midi");
bc.onmessage = (e) => {
const m = e.data || {};
if (m.type === "who") bc.postMessage({ type: "studio", connected: !!state.dev });
if (m.type !== "installer") return;
clearTimeout(busyTimer);
if (m.busy) {
busyUntil = Date.now() + 60000; state.busy = true;
letGo(); monitorStop();
state.found = t("nowBusy");
bc.postMessage({ type: "released", who: "studio" });
busyTimer = setTimeout(() => { state.busy = false; render(); }, 60000);
} else { state.busy = false; busyUntil = 0; }
render();
};
} catch (_) {}
/* ------------------------------------------------------------------------------------- views, firmware, target */
/* the views' strip: its edges and arrows where it scrolls, the wheel sideways, the current one brought into view */
{
const nv = document.querySelector("nav.views"), row = $("viewsrow");
const edges = () => { row.classList.toggle("l", nv.scrollLeft > 4); row.classList.toggle("r", nv.scrollLeft + nv.clientWidth < nv.scrollWidth - 4); };
nv.addEventListener("scroll", edges, { passive: true }); window.addEventListener("resize", edges);
nv.addEventListener("wheel", (e) => { if (Math.abs(e.deltaY) > Math.abs(e.deltaX) && nv.scrollWidth > nv.clientWidth) { nv.scrollLeft += e.deltaY; e.preventDefault(); } }, { passive: false });
$("navl").onclick = () => { nv.scrollLeft -= nv.clientWidth * 0.7; };
$("navr").onclick = () => { nv.scrollLeft += nv.clientWidth * 0.7; };
window.navShow = () => { const b = nv.querySelector('[aria-current="page"]'); if (b) nv.scrollTo({ left: b.offsetLeft - (nv.clientWidth - b.offsetWidth) / 2, behavior: "smooth" }); edges(); };
setTimeout(edges, 50);
}
const VIEWS = ["home", "install", "editor", "screen", "emu", "rec", "ed", "proj", "pe", "wt", "radio", "an", "vis", "learn", "docs", "rescue", "ports"];
function go(view, push = true) {
if (!VIEWS.includes(view)) view = "home";
state.view = view;
for (const v of VIEWS) $("v-" + v).hidden = v !== view;
const dock = view === "radio"; // Radio: the emulator beside it (above on a phone)
document.body.classList.toggle("radiodock", dock);
if (dock) { $("v-emu").hidden = false; loadFrame("emu"); }
if (push && !(view === "learn" && /^#learn\//.test(location.hash))) history.replaceState(null, "", location.pathname + location.search + "#" + view);
showFrames();
render();
window.navShow && window.navShow(); requestAnimationFrame(clampLeads);
window.scrollTo({ top: 0 });
}
document.addEventListener("click", (e) => {
const g = e.target.closest("[data-go]");
if (g) { e.preventDefault(); go(g.dataset.go); return; }
const f = e.target.closest("[data-fw]");
if (f) { setFw(f.dataset.fw); return; }
const i = e.target.closest("[data-install]");
if (i) { setFw(i.dataset.install); go("install"); return; }
const tg = e.target.closest("[data-target]");
if (tg) { setTarget(tg.dataset.target); }
});
function setFw(fw) {
if (fw !== "fm" && fw !== "byte") return;
const changed = fw !== state.fw;
state.fw = fw;
try { localStorage.setItem("jiant.studio.fw", fw); } catch (_) {}
document.documentElement.dataset.skin = fw;
document.querySelector('meta[name="theme-color"]').content = fw === "byte" ? "#000000" : "#050409";
if (changed) for (const k of Object.keys(frames)) frames[k].fw = null; // the tools of the other firmware: loaded anew
showFrames();
render();
}
function setTarget(target) {
state.target = target === "emu" ? "emu" : "fm1";
if (frames.editor.fw) frames.editor.fw = null; // the editor anew, for the other target
screenStop(false);
showFrames();
render();
}
/* ------------------------------------------------------------------------- the tools in frames, in our look */
const frames = {
install: { el: $("f-install"), fw: null, tool: "installer" },
editor: { el: $("f-editor"), fw: null, tool: "editor" },
emu: { el: $("f-emu"), fw: null, tool: "emu" },
};
const VIEW_FRAME = { install: "install", editor: "editor", emu: "emu" };
function showFrames() {
const k = VIEW_FRAME[state.view];
// the emulator stays loaded once it was (it keeps playing; the screen and the recorder read it)
if (k) loadFrame(k);
if (state.view === "screen" && state.target === "emu") loadFrame("emu");
}
const BETA_PATH = { fm: "preview/emu/", byte: "emu/beta/" }; // each firmware's beta emulator, beside its public one
function loadFrame(k) {
const f = frames[k];
if (f.fw === state.fw && f.el.src) return;
f.fw = state.fw;
const q = k === "editor" && state.target === "emu" ? "?emu=1" : MOCK && k === "editor" ? "?mock=1" : "";
f.el.src = k === "emu" && state.emuVer ? (state.emuVer === "beta" ? `${TOOLS[state.fw].base}${BETA_PATH[state.fw]}` : `${TOOLS[state.fw].base}emu-v/${state.emuVer}/`) : toolUrl(state.fw, f.tool, q); // another version: its own page (emu-v)
}
for (const [k, f] of Object.entries(frames)) f.el.addEventListener("load", () => { dress(f.el); if (k === "editor") editorLoaded(); });
/* the firmware's look inside a tool's frame (same origin only): its colour tokens and type, over the page's own */
const DRESS = {
fm: `:root,:root:not([data-theme="light"]){--bg:#050409;--fg:#efe6c8;--dim:#a39bb6;--line:rgba(239,230,200,.18)}
body{background:#050409;color:#efe6c8;font-family:"Instrument Sans",system-ui,sans-serif}`,
byte: `:root,:root:not([data-theme="light"]){--bg:#000;--fg:#f2f0f7;--dim:#9d94b8;--line:rgba(167,123,255,.35);
--jiant-panel:#0b0912;--jiant-field:#05040a;--jiant-cyan:#a77bff;--jiant-yellow:#ffb21a;--jiant-mag:#ff3b3b;--jiant-orange:#ff7a1a;
--jiant-display:"Silkscreen",monospace;--jiant-body:"IBM Plex Mono",monospace;--jiant-mono:"VT323",monospace;
--jiant-heat:linear-gradient(90deg,#ff3b3b,#ff7a1a 40%,#ffb21a 60%,#a77bff)}
body{background:#000;color:#f2f0f7;font-family:"IBM Plex Mono",monospace}
h1,h2,.jiant-wordmark{font-family:"Silkscreen",monospace}`,
};
/* inside Studio a tool's own wordmark, links to the other tools, support line and footer are Studio's already */
const EMBEDDED = `h1.jiant-wordmark,.jiant-wordmark,p.kofi,.kofi,body>main>footer,body>footer,main>p.dim:first-of-type{display:none!important}
main{padding-top:8px!important} a{color:inherit}`;
function dress(iframe) {
try {
const d = iframe.contentDocument;
if (!d || !d.head) return;
let s = d.getElementById("studio-skin");
if (!s) {
s = d.createElement("style"); s.id = "studio-skin"; d.head.append(s);
const l = d.createElement("link"); l.rel = "stylesheet";
l.href = "https://fonts.googleapis.com/css2?family=Michroma&family=IBM+Plex+Mono:wght@400;500;600&family=Instrument+Sans:wght@400;500;600&family=Silkscreen&family=VT323&display=swap";
d.head.append(l);
}
s.textContent = DRESS[state.fw] + EMBEDDED;
d.documentElement.dataset.skin = state.fw; // (the editor's own design layer, editor.html #jiant-skin: the firmware's look)
} catch (_) { /* another origin: its own look */ }
}
function editorLoaded() {
// the FM-1 found here, or the emulator running: the editor (just loaded, so not connected) connects at once, as its own
// button would
if (state.busy || (state.target === "fm1" ? !state.dev : !emuOn())) return;
try { const b = frames.editor.el.contentDocument.getElementById("connect"); if (b && !b.disabled) b.click(); } catch (_) {}
}
/* ------------------------------------------------------------------------------------------------ the screen */
const scr = { on: false, src: null, ctx: $("scr").getContext("2d"), img: null, lut: null, fb: new Uint16Array(SCR.W * SCR.H),
dirty: null, raf: 0, timer: 0, bytes: 0, frames: 0, t0: 0, rate: 0, fps: 0, got: false, lock: null, copy: 0 };
scr.img = scr.ctx.createImageData(SCR.W, SCR.H);
scr.lut = (() => { const l = new Uint32Array(65536); for (let c = 0; c < 65536; c++) l[c] = 0xFF000000 | ((c & 31) * 255 / 31 | 0) << 16 | (((c >> 5) & 63) * 255 / 63 | 0) << 8 | (((c >> 11) & 31) * 255 / 31 | 0); return l; })();
function onScreenData(f) {
if (!scr.on || scr.src !== "fm1") return;
const box = scrDecode(f.a, scr.fb);
if (!box) return;
scr.bytes += f.a.length + 6;
if (!scr.got) { scr.got = true; $("scrwait").hidden = true; } // (the first picture: the waiting line goes)
const d = scr.dirty;
scr.dirty = !d ? box : { x: Math.min(d.x, box.x), y: Math.min(d.y, box.y),
w: Math.max(d.x + d.w, box.x + box.w) - Math.min(d.x, box.x), h: Math.max(d.y + d.h, box.y + box.h) - Math.min(d.y, box.y) };
if (!scr.raf) scr.raf = requestAnimationFrame(paint);
}
function paint() {
scr.raf = 0;
const d = scr.dirty;
if (!d) return;
scr.dirty = null; scr.frames++;
const px = new Uint32Array(scr.img.data.buffer);
for (let y = d.y; y < d.y + d.h; y++) for (let i = y * SCR.W + d.x, e = i + d.w; i < e; i++) px[i] = scr.lut[scr.fb[i]];
scr.ctx.putImageData(scr.img, 0, 0, d.x, d.y, d.w, d.h);
}
function emuCanvas() {
try { return frames.emu.el.contentDocument && frames.emu.el.contentDocument.getElementById("screen"); } catch (_) { return null; }
}
async function screenStart() {
if (scr.on) return;
scr.src = state.target; scr.got = false; scr.bytes = 0; scr.frames = 0; scr.t0 = Date.now();
scr.fb.fill(0); scr.ctx.fillStyle = "#000"; scr.ctx.fillRect(0, 0, SCR.W, SCR.H);
if (scr.src === "emu") {
loadFrame("emu");
scr.on = true;
const step = () => {
if (!scr.on) return;
const c = emuCanvas();
if (c && c.width) { scr.ctx.drawImage(c, 0, 0, SCR.W, SCR.H); if (!scr.got) { scr.got = true; $("scrwait").hidden = true; } scr.frames++; }
scr.copy = requestAnimationFrame(step);
};
step();
} else {
const d = state.dev;
if (!d) { render(); return; }
scr.on = true;
try {
const a = await d.link.request(CMD.SCREEN, [1]);
if (a[1] || !a[2]) { scr.on = false; $("scrstat").textContent = t("scrNo"); render(); return; }
} catch (e) { scr.on = false; $("scrstat").textContent = t("scrNo"); render(); return; }
clearInterval(scr.timer);
scr.timer = setInterval(async () => {
if (!scr.on || !state.dev || document.hidden) return;
try { const a = await state.dev.link.request(CMD.SCREEN, [2]); if (scr.on && !a[2]) await state.dev.link.request(CMD.SCREEN, [1]); } catch (_) {}
}, 1000);
}
wake();
render();
}
function screenStop(tell = true) {
if (!scr.on) return;
scr.on = false;
clearInterval(scr.timer); cancelAnimationFrame(scr.copy);
if (tell && scr.src === "fm1" && state.dev) state.dev.link.request(CMD.SCREEN, [4]).catch(() => {});
if (scr.lock) { scr.lock.release().catch(() => {}); scr.lock = null; }
render();
}
async function wake() {
try { if (scr.on && !scr.lock && navigator.wakeLock && !document.hidden) { scr.lock = await navigator.wakeLock.request("screen"); scr.lock.addEventListener("release", () => { scr.lock = null; }); } } catch (_) {}
}
document.addEventListener("visibilitychange", () => {
if (document.hidden || !scr.on) return;
wake();
if (scr.src === "fm1" && state.dev) state.dev.link.request(CMD.SCREEN, [3]).catch(() => {}); // (it may have stopped meanwhile)
});
setInterval(() => {
if (!scr.on) return;
const dt = (Date.now() - scr.t0) / 1000;
if (dt >= 1) { scr.rate = scr.bytes / dt; scr.fps = scr.frames / dt; scr.bytes = 0; scr.frames = 0; scr.t0 = Date.now(); }
if (state.view === "screen") $("scrstat").textContent = !scr.got ? t("scrWaiting") :
scr.src === "fm1" ? `${(scr.rate / 1024).toFixed(1)}${t("scrRate")} · ${scr.fps.toFixed(0)}${t("scrFps")}` : `${scr.fps.toFixed(0)}${t("scrFps")}`;
}, 500);
const fullscreen = () => {
const s = $("stage");
if (document.fullscreenElement || document.webkitFullscreenElement) (document.exitFullscreen || document.webkitExitFullscreen).call(document);
else (s.requestFullscreen || s.webkitRequestFullscreen).call(s)?.catch?.(() => {});
};
/* Show: the screen on, and full screen at once (the same tap: browsers allow full screen only from one); Exit leaves full
* screen with the picture still here, Stop ends it */
$("scrgo").addEventListener("click", () => {
if (scr.on) { screenStop(); return; }
if (state.target === "emu" || (state.dev && state.dev.screen === true)) fullscreen(); // (unsure: the page first, Full screen after) // (only a picture that will come goes full screen)
screenStart();
});
$("scrfull").addEventListener("click", async () => { if (!scr.on) await screenStart(); fullscreen(); });
$("fsexit").addEventListener("click", fullscreen);
const sharp = () => {
const on = $("stage").classList.toggle("smooth") === false;
$("scrsharp").setAttribute("aria-pressed", String(on));
try { localStorage.setItem("jiant.studio.smooth", on ? "0" : "1"); } catch (_) {}
};
$("scrsharp").addEventListener("click", sharp); $("fssharp").addEventListener("click", sharp);
try { if (localStorage.getItem("jiant.studio.smooth") === "1") { $("stage").classList.add("smooth"); $("scrsharp").setAttribute("aria-pressed", "false"); } } catch (_) {}
let fade = 0;
const showBar = () => { $("fsbar").classList.remove("faded"); clearTimeout(fade); fade = setTimeout(() => $("fsbar").classList.add("faded"), 2500); };
$("stage").addEventListener("pointerdown", showBar);
document.addEventListener("fullscreenchange", () => { if (document.fullscreenElement) showBar(); });
if (QS.has("screen")) { state.view = "screen"; }
/* ------------------------------------------------------------------------------------------------ recording */
/* JIANT's USB audio profiles (MENU > SYSTEM > USB, then unplug and plug again): what each sends to the computer or the
* phone, channel by channel (docs/MANUAL.md "Stems", "USB audio in", "Stems with a voice"; android/README.md) */
const PROFILES = {
master: { ch: 2, lanes: [["L", 0, -1], ["R", 0, 1]] },
stems: { ch: 8, lanes: [["T1", 1], ["T2", 2], ["T3", 3], ["T4", 4], ["T5", 5], ["T6", 6], ["FX L", 7, -1], ["FX R", 7, 1]] },
stemsin: { ch: 10, lanes: [["T1", 1], ["T2", 2], ["T3", 3], ["T4", 4], ["T5", 5], ["T6", 6], ["FX L", 7, -1], ["FX R", 7, 1], ["VOX", 8], ["DRY", 9]] },
};
const LANE_COLORS = { fm: ["#efe6c8", "#9d97ff", "#d39bff", "#ff9fd2", "#ff9a8a", "#ffc07a", "#fff3a8", "#3fe0e6", "#7be0a8", "#a39bb6"],
byte: ["#f2f0f7", "#ff7a1a", "#a77bff", "#ff3b3b", "#6bc8ff", "#ffd23f", "#f2f0f7", "#ff6fae", "#6bff9e", "#9d94b8"] };
const rec = { on: false, mon: false, stream: null, ac: null, node: null, chunks: [], ch: 2, rate: 44100, t0: 0, midi: [], takes: [], clock: 0,
profile: "master", engines: [] };
const daw = new Daw($("daw"), { get mute() { return t("recMute"); }, get solo() { return t("recSolo"); } });
const profileOf = (ch) => { const p = $("recprof").value; return p !== "auto" ? p : ch >= 10 ? "stemsin" : ch >= 8 ? "stems" : "master"; };
/* the six tracks' engines, for the lanes' names (27 TRACK: selected, NTRK, then per track engine, preset, level v14,
mute, armed) */
async function trackNames(emu = false) {
const d = state.dev, L = emu ? projLink() : d && state.target === "fm1" ? { link: d.link } : null;
if (!L) return [];
try {
const engines = emu ? parseInfo(await L.link.request(CMD.INFO, [], 900)).engines : d.engines;
const a = await L.link.request(27, [], 600), n = a[1] | 0;
return Array.from({ length: n }, (_, k) => engines[a[2 + k * 6]] || "");
} catch (_) { return []; }
}
function lanesFor(profile, ch) {
const P = PROFILES[profile], col = LANE_COLORS[state.fw];
const lanes = P.lanes.slice(0, Math.max(ch, 1)).map(([name, c, pan], i) => {
const e = /^T\d$/.test(name) ? rec.engines[+name[1] - 1] : "", eng = e && e !== "-" ? e : "";
return { name: eng ? `${name} · ${eng}` : name, sub: /^T\d$/.test(name) ? t("laneTrack") : t("lane_" + name.replace(" ", "")), color: col[c] || col[0], pan: pan || 0 };
});
for (let i = lanes.length; i < ch; i++) lanes.push({ name: `CH ${i + 1}`, sub: "", color: col[9], pan: 0 });
return lanes;
}
function profileHelp() {
const p = $("recprof").value, d = $("recdev").value;
$("profhelp").textContent = d === "emu-stems" ? t("recEmuStemsHelp") + ($("midisrc").value === "emu-midi" ? " " + t("recEmuMidiHelp") : "") :
d === "emu" ? t("recSrcEmu") : t("profHelp_" + p);
}
$("recprof").addEventListener("change", () => { profileHelp(); if (rec.mon && !rec.on) monitorStop(); });
/* the input open and shown in the lanes (levels only) until Record, which keeps what comes in */
/* the emulator's tap (emu/index.html jiantEmu.tap): its stems as the input (8 channels, STEMS' lanes) and/or its MIDI
OUT, each at its sample (rec.at0: the take's first sample) */
const emuApi = () => { try { const e = frames.emu.el.contentWindow.jiantEmu; return e && e.on() && e.tap ? e : null; } catch (_) { return null; } };
const emuWhyNot = () => t(emuOn() ? "recEmuOld" : "recEmuOff");
function onTap(m) {
if (rec.src === "emu-stems") {
if (rec.on) { if (rec.at0 == null) rec.at0 = m.at; rec.chunks.push(m.planes); daw.live(m.planes, rec.rate); }
else daw.meters(m.planes.map((p) => { let v = 0; for (let i = 0; i < p.length; i += 8) { const a = Math.abs(p[i]); if (a > v) v = a; } return v; }));
}
if (rec.on && rec.emuMidi) for (const e of m.midi) {
if (e.data[0] < 0x80 || e.data[0] >= 0xF0) continue;
const t0 = rec.at0 != null ? (e.at - rec.at0) / 44.1 : performance.now() - rec.t0;
if (t0 >= 0) rec.midi.push({ t: t0, data: e.data });
}
}
async function monitorStart() {
if (rec.mon || state.busy) return true;
let stream;
if ($("recdev").value === "emu-stems") {
loadFrame("emu");
const e = emuApi();
if (!e) { $("recstat").textContent = emuWhyNot(); return false; }
rec.tapStop = e.tap(onTap);
rec.engines = state.target === "emu" ? await trackNames(true) : [];
Object.assign(rec, { mon: true, src: "emu-stems", stream: null, ac: null, node: null, ch: 8, rate: 44100, profile: "stems" });
daw.setLanes(lanesFor("stems", 8));
$("recstat").textContent = `8${t("recChannels")} · 44100 Hz`;
$("recwarn").hidden = true;
render();
return true;
}
rec.src = $("recdev").value;
const want = PROFILES[$("recprof").value === "auto" ? "stemsin" : $("recprof").value].ch;
try {
if (rec.src === "emu") {
loadFrame("emu");
const w = frames.emu.el.contentWindow;
stream = w && w.jiantEmu && w.jiantEmu.stream && w.jiantEmu.stream();
if (!stream) { $("recstat").textContent = t("recSrcEmu"); return false; }
} else {
const id = $("recdev").value;
if (MOCK && id === "mock-stems") stream = "mock";
else {
if (!id || id === "ask") { await renderAudioInputs(true); if ($("recdev").value && $("recdev").value !== "ask") return monitorStart(); return false; }
const base = { deviceId: { exact: id }, echoCancellation: false, noiseSuppression: false, autoGainControl: false, sampleRate: { ideal: 44100 } };
try { stream = await navigator.mediaDevices.getUserMedia({ audio: { ...base, channelCount: want > 2 ? { min: 2, ideal: want } : { exact: 2 } } }); }
catch (_) { stream = await navigator.mediaDevices.getUserMedia({ audio: { ...base, channelCount: { ideal: want } } }); }
}
}
} catch (e) { $("recstat").textContent = e.message; return false; }
/* the FM-1's STEMS / STEMS+IN run at 44100 Hz only: the context at that rate too, so the browser has nothing to convert
(the emulator's stream keeps its own rate) */
/* ?recold=1: the recorder exactly as it was until 30/11 (the context at the browser's rate, as many lanes as the
browser's settings say), for an A/B on a device where the new one does worse */
const OLD = QS.get("recold") === "1";
let ac; try { ac = new AudioContext(rec.src === "emu" || OLD ? { latencyHint: "playback" } : { latencyHint: "playback", sampleRate: 44100 }); } catch (_) { ac = new AudioContext({ latencyHint: "playback" }); }
const src = stream === "mock" ? mockStems(ac) : ac.createMediaStreamSource(stream);
const ch = stream === "mock" ? 10 : Math.max(1, Math.min(16, stream.getAudioTracks()[0]?.getSettings?.().channelCount || src.channelCount || 2));
await ac.audioWorklet.addModule("recorder-worklet.js");
/* "max": the worklet gets every channel the stream has, whatever the browser's settings say (some report none, or 2);
it says how many arrive and the lanes follow */
const node = new AudioWorkletNode(ac, "studio-recorder", { numberOfInputs: 1, numberOfOutputs: 0, channelCount: ch, channelCountMode: stream === "mock" || OLD ? "explicit" : "max", channelInterpretation: "discrete" });
if (stream !== "mock" && rec.src !== "emu") { // what the browser says it opened: shown under the transport
const tr = stream.getAudioTracks()[0], st = (tr && tr.getSettings && tr.getSettings()) || {};
rec.diag = `${OLD ? "[recold] " : ""}${tr ? tr.label : "?"} · settings: ${st.channelCount ?? "—"} ch, ${st.sampleRate ?? "—"} Hz · context ${ac.sampleRate} Hz`;
} else rec.diag = "";
src.connect(node);
rec.engines = await trackNames();
const profile = rec.src === "emu" ? "master" : profileOf(ch);
Object.assign(rec, { mon: true, stream, ac, node, ch, rate: ac.sampleRate, profile });
daw.setLanes(lanesFor(profile, ch));
node.port.onmessage = (e) => {
if (e.data.channels && rec.diag && !rec.diagN) { rec.diagN = e.data.channels; const d = $("recdiag"); if (d) d.textContent = `${rec.diag} · ${t("recArrive").replace("%n", e.data.channels)}`; }
if (!OLD && e.data.channels && e.data.channels !== rec.ch && rec.src !== "emu" && !rec.on) { // the real count: lanes and the warning again
rec.ch = e.data.channels; rec.profile = profileOf(rec.ch); daw.setLanes(lanesFor(rec.profile, rec.ch)); chWarn(rec.ch, rec.profile);
return;
}
const c = e.data.chunk;
if (!c) return;
if (rec.on) { rec.chunks.push(c); daw.live(c, rec.rate); }
else daw.meters(c.map((p) => { let m = 0; for (let i = 0; i < p.length; i += 8) { const v = Math.abs(p[i]); if (v > m) m = v; } return m; }));
};
rec.diagN = 0; { const d = $("recdiag"); if (d) d.textContent = rec.diag || ""; }
chWarn(ch, profile);
render();
return true;
}
function chWarn(got, profile) {
const need = PROFILES[profile].ch;
$("recstat").textContent = `${got}${t("recChannels")} · ${rec.rate} Hz`;
const warn = $("recwarn");
warn.hidden = !(rec.src !== "emu" && (got < need || ($("recprof").value !== "auto" && got < PROFILES[$("recprof").value].ch)));
warn.textContent = t(/Android/i.test(navigator.userAgent) ? "recFewerAndroid" : "recFewerLong").replace("%got", got).replace("%need", PROFILES[$("recprof").value === "auto" ? profile : $("recprof").value].ch);
}
function monitorStop() {
if (!rec.mon) return;
if (rec.on) recStop();
rec.mon = false;
if (rec.tapStop) { rec.tapStop(); rec.tapStop = null; }
if (rec.stream && rec.src !== "emu" && rec.stream !== "mock") rec.stream.getTracks().forEach((x) => x.stop());
if (rec.ac) rec.ac.close().catch(() => {});
render();
}
$("recmon").addEventListener("click", () => (rec.mon ? monitorStop() : monitorStart()));
async function recStart() {
if (rec.on || state.busy) return;
if (!rec.mon && !(await monitorStart())) return;
daw.stop();
daw.setLanes(lanesFor(rec.profile, rec.ch));
Object.assign(rec, { on: true, chunks: [], t0: performance.now(), midi: [], at0: null, emuMidi: false });
const mid = $("midisrc").value;
if (mid === "emu-midi") { // the emulator's MIDI OUT: by its tap (the stems' own, or one of its own)
rec.emuMidi = true;
if (!rec.tapStop) { const e = emuApi(); if (e) rec.tapStop = e.tap(onTap); else $("recstat").textContent = emuWhyNot(); }
} else if (mid && access) {
const inp = access.inputs.get(mid);
if (inp) {
midiTapInput = inp;
if (state.dev && state.dev.input.id === inp.id) { const prev = inp.onmidimessage; inp.onmidimessage = (e) => { midiTap(e); prev && prev(e); }; }
else inp.addEventListener("midimessage", midiTap);
}
}
rec.clock = setInterval(() => {
const s = Math.floor((performance.now() - rec.t0) / 1000);
$("recclock").textContent = `${String(Math.floor(s / 60)).padStart(2, "0")}:${String(s % 60).padStart(2, "0")}`;
}, 200);
render();
}
function recStop() {
if (!rec.on) return;
rec.on = false;
clearInterval(rec.clock);
try { rec.node.port.postMessage("flush"); } catch (_) {}
setTimeout(() => {
if (midiTapInput) { midiTapInput.removeEventListener("midimessage", midiTap); midiTapInput = null; }
if (rec.tapStop && rec.src !== "emu-stems") { rec.tapStop(); rec.tapStop = null; } // (a tap for its MIDI only)
const take = makeTake();
if (take) daw.show(take.planes, rec.rate);
$("recclock").textContent = "00:00";
$("recstat").textContent = t("recSaved");
render();
}, 200); // (the worklet's last chunk)
}
$("recgo").addEventListener("click", () => (rec.on ? recStop() : recStart()));
$("recplay").addEventListener("click", () => (daw.playing ? daw.stop() : daw.play()));
daw.onState = () => render();
/* ---- a song's stems from a backup (the FM-1's, read over USB, or a file): the emulator's own renderer (emu/stems.js,
in a Worker) plays it once a track; the result shown in the lanes as a take */
async function stemsFrom(archiveOrNull) {
let base = TOOLS[state.fw].base + "emu/"; const say = (x) => { $("ststat").textContent = x; };
try {
/* a public emulator without its stems renderer (stems.js): the preview's, whole (its renderer, wasm and backup reader) */
const has = async (b) => { try { return (await fetch(b + "stems.js", { cache: "no-cache" })).ok; } catch (_) { return false; } };
if (!(await has(base))) { const alt = TOOLS[state.fw].base + (state.fw === "fm" ? "preview/emu/" : "emu/beta/"); if (await has(alt)) base = alt; else { say(t("stNoRenderer")); return; } }
const BK = await import(base + "fm1backup.js");
let archive = archiveOrNull;
if (!archive) { // the FM-1 over USB, or the emulator when it is the target
const L = projLink();
if (!L || state.busy) { say(t("stNeedDev")); return; }
archive = await BK.captureBackup((r, o) => L.link.request(r[0], r[1], (o && o.timeout) || 2000), state.dev && state.target !== "emu" ? state.dev.version : L.name,
(done, total) => say(t("stReading") + Math.round(done / Math.max(1, total) * 100) + " %"));
}
const backup = BK.readBackup(archive), wasm = await (await fetch(base + "felucca.wasm")).arrayBuffer();
const v = $("stsong").value, opts = v === "live" ? { mode: "live", bars: 8 } : { mode: "song", song: +v };
const out = await new Promise((res, rej) => {
const w = new Worker(base + "stems.js", { type: "module" });
w.onmessage = (e) => { const m = e.data; if (m.type === "progress") say(t("stRender") + `${m.step} / ${m.steps}`); else { w.terminate(); m.type === "done" ? res(m) : rej(new Error(m.message)); } };
w.onerror = (e) => { w.terminate(); rej(new Error(e.message || "stems")); };
w.postMessage({ wasm, backup, opts }, [wasm]);
});
const files = unzipStored(new Uint8Array(out.zip)), col = LANE_COLORS[state.fw], planes = [], lanes = [];
for (const f of files) {
const { l, r, rate } = readWav(f.data), m = new Float32Array(l.length);
for (let i = 0; i < l.length; i++) m[i] = (l[i] + r[i]) * 0.5;
const k = /^T(\d)/.exec(f.name), n = k ? +k[1] : 0;
planes.push(m); lanes.push({ name: f.name.replace(".wav", ""), sub: k ? t("laneTrack").replace(", mono", "") : "MIX", color: k ? col[n] : col[0], pan: 0 });
rec.rate = rate;
}
const name = `${state.fw === "byte" ? "JIANT-BYTE" : "JIANT-FM"}-${v === "live" ? "live" : "song" + (+v + 1)}-stems`;
const take = { name, secs: out.seconds, planes, rate: rec.rate, lanes, files: [{ label: t("recStemsZip"), name: name + ".zip", blob: new Blob([out.zip], { type: "application/zip" }) },
...files.map((f) => ({ label: f.name.replace(".wav", ""), name: `${name}-${f.name}`, blob: new Blob([f.data], { type: "audio/wav" }), small: true }))] };
rec.takes.unshift(take);
daw.setLanes(lanes); daw.show(planes, rec.rate);
download(take.files[0].blob, take.files[0].name); // the ZIP straight to the downloads (each WAV is in Takes too)
say(t("stDone"));
render();
setTimeout(() => { const k = $("takes"); if (k) k.scrollIntoView({ behavior: "smooth", block: "center" }); }, 60);
} catch (e) { say(String(e.message || e)); }
}
$("stgo").addEventListener("click", () => stemsFrom(null));
$("stfile").addEventListener("change", async () => { const f = $("stfile").files[0]; if (f) stemsFrom(JSON.parse(await f.text())); $("stfile").value = ""; });
/* the renderer's ZIP is stored (no compression) and its WAVs 16-bit stereo: read back without a library */
function unzipStored(z) {
const out = [], dv = new DataView(z.buffer, z.byteOffset, z.byteLength);
for (let o = 0; o + 30 <= z.length && dv.getUint32(o, true) === 0x04034B50;) {
const size = dv.getUint32(o + 18, true), nl = dv.getUint16(o + 26, true), xl = dv.getUint16(o + 28, true);
const name = new TextDecoder().decode(z.subarray(o + 30, o + 30 + nl)), start = o + 30 + nl + xl;
out.push({ name, data: z.slice(start, start + size) }); o = start + size;
}
return out;
}
function readWav(b) {
const dv = new DataView(b.buffer, b.byteOffset, b.byteLength), ch = dv.getUint16(22, true), rate = dv.getUint32(24, true);
let o = 12; while (o + 8 <= b.length && String.fromCharCode(...b.subarray(o, o + 4)) !== "data") o += 8 + dv.getUint32(o + 4, true);
const n = Math.floor(dv.getUint32(o + 4, true) / (2 * ch)), l = new Float32Array(n), r = new Float32Array(n);
for (let i = 0, p = o + 8; i < n; i++, p += 2 * ch) { l[i] = dv.getInt16(p, true) / 32768; r[i] = ch > 1 ? dv.getInt16(p + 2, true) / 32768 : l[i]; }
return { l, r, rate };
}
function makeTake() {
const n = rec.chunks.reduce((s, c) => s + c[0].length, 0);
if (!n && !rec.midi.length) return null;
const ch = rec.ch, planes = Array.from({ length: ch }, () => new Float32Array(n));
let o = 0;
for (const c of rec.chunks) { for (let k = 0; k < ch; k++) planes[k].set(c[k] || c[0], o); o += c[0].length; }
const stamp = new Date().toISOString().replace(/[:T]/g, "-").slice(0, 19);
const name = `${state.fw === "byte" ? "JIANT-BYTE" : "JIANT-FM"}-${state.target === "emu" ? "emu" : "fm1"}-${stamp}`;
const lanes = lanesFor(rec.profile, ch);
const take = { name, secs: n / rec.rate, files: [], planes, rate: rec.rate, lanes };
if (n) {
if (rec.profile !== "master" && ch >= 8) { // STEMS / STEMS+IN: each track, the effects, the voice; their sum
const sum = [new Float32Array(n), new Float32Array(n)];
for (let i = 0; i < n; i++) {
let c = 0; for (let k = 0; k < 6; k++) c += planes[k][i] * 0.5;
if (ch >= 10) c += planes[8][i] * 0.5; // (VOX: the voice as the track mixed it, not in its stem)
sum[0][i] = c + planes[6][i]; sum[1][i] = c + planes[7][i];
}
const file = (l) => l.name.replace(/[^A-Za-z0-9]+/g, "-").replace(/-+$/, "");
const entries = [];
for (let k = 0; k < Math.min(6, ch); k++) entries.push({ name: `${name}/${file(lanes[k])}.wav`, data: wavFile([planes[k]], rec.rate) });
entries.push({ name: `${name}/FX.wav`, data: wavFile([planes[6], planes[7]], rec.rate) });
if (ch >= 10) { entries.push({ name: `${name}/VOX.wav`, data: wavFile([planes[8]], rec.rate) }); entries.push({ name: `${name}/DRY.wav`, data: wavFile([planes[9]], rec.rate) }); }
entries.push({ name: `${name}/MIX.wav`, data: wavFile(sum, rec.rate) });
take.files.push({ label: t("recStemsZip"), name: `${name}-stems.zip`, blob: new Blob([zipStored(entries)], { type: "application/zip" }) });
take.files.push({ label: t("recWav"), name: `${name}.wav`, blob: new Blob([wavFile(sum, rec.rate)], { type: "audio/wav" }) });
for (const e of entries.slice(0, -1)) take.files.push({ label: e.name.split("/")[1].replace(".wav", ""), name: e.name.replace("/", "-"), blob: new Blob([e.data], { type: "audio/wav" }), small: true });
} else {
take.files.push({ label: t("recWav"), name: `${name}.wav`, blob: new Blob([wavFile(planes.slice(0, 2), rec.rate)], { type: "audio/wav" }) });
}
}
if (rec.midi.length) {
take.files.push({ label: `${t("recMid")} (${rec.midi.filter((m) => (m.data[0] & 0xF0) === 0x90 && m.data[2]).length}${t("recNotes")})`, name: `${name}.mid`,
blob: new Blob([midiFile(rec.midi)], { type: "audio/midi" }) });
}
rec.takes.unshift(take);
rec.chunks = [];
return take;
}
let midiTapInput = null;
function midiTap(e) {
const d = e.data;
if (!rec.on || !d || !d.length || d[0] < 0x80 || d[0] >= 0xF0) return;
rec.midi.push({ t: performance.now() - rec.t0, data: Array.from(d) });
}
async function renderAudioInputs(ask = false) {
const sel = $("recdev"), was = sel.value;
if (rec.mon) return; // (the input in use stays as it is)
sel.disabled = false;
const emuOpts = () => [new Option(t("recEmuStems"), "emu-stems"), new Option(t("recEmuMaster"), "emu")];
if (state.target === "emu") {
sel.replaceChildren(...emuOpts());
sel.value = was === "emu" ? "emu" : "emu-stems";
return;
}
try {
if (ask) (await navigator.mediaDevices.getUserMedia({ audio: true })).getTracks().forEach((x) => x.stop());
const ins = (await navigator.mediaDevices.enumerateDevices()).filter((d) => d.kind === "audioinput");
const opts = ins.map((d, i) => new Option(d.label || `${t("recInput")} ${i + 1}`, d.deviceId));
if (!opts.length || !ins.some((d) => d.label)) opts.push(new Option(t("recAsk"), "ask"));
if (MOCK) opts.unshift(new Option("JIANT FM (simulated: STEMS+IN, 10 ch)", "mock-stems"));
sel.replaceChildren(...opts, ...emuOpts());
/* the FM-1: by its name, else (Android names any USB interface "USB audio" or so) the USB input; chosen over the
phone's or computer's own default unless the person picked another one themselves */
const fm1 = MOCK ? { deviceId: "mock-stems" } : ins.find((d) => /fm-?1|jiant|felucca|m-?vave/i.test(d.label)) || ins.find((d) => /usb/i.test(d.label) && !/webcam|camera|c[aá]mara/i.test(d.label));
const keep = [...sel.options].some((o) => o.value === was) && was !== "ask" && !(fm1 && (was === "default" || !rec.picked));
sel.value = keep ? was : fm1 ? fm1.deviceId : sel.options[0].value;
} catch (_) { sel.replaceChildren(new Option(t("recNoDev"), "")); }
}
if (navigator.mediaDevices && navigator.mediaDevices.addEventListener) navigator.mediaDevices.addEventListener("devicechange", () => { if (state.view === "rec") renderAudioInputs(); });
$("recdev").addEventListener("change", () => { rec.picked = $("recdev").value !== "ask"; if ($("recdev").value === "ask") renderAudioInputs(true); profileHelp(); });
$("midisrc").addEventListener("change", profileHelp);
function renderMidiInputs() {
const sel = $("midisrc"), was = sel.value;
const ins = access ? [...access.inputs.values()].filter((p) => p.state !== "disconnected") : [];
sel.replaceChildren(new Option(t("recMidiNone"), ""), new Option(t("recEmuMidi"), "emu-midi"), ...ins.map((p) => new Option(p.name || p.id, p.id)));
const fm1 = ins.find((p) => PORT_RE.test(p.name || ""));
sel.value = was && [...sel.options].some((o) => o.value === was) ? was : state.target === "emu" ? "emu-midi" : fm1 ? fm1.id : "";
}
$("midisrc").addEventListener("focus", async () => { if (!access && !MOCK) { try { await midiAccess(); } catch (_) {} renderMidiInputs(); } });
function renderTakes() {
const box = $("takes");
if (!rec.takes.length) { box.replaceChildren(Object.assign(document.createElement("p"), { className: "small dim", textContent: t("recNone") })); return; }
box.replaceChildren(...rec.takes.map((tk) => {
const row = document.createElement("div"); row.className = "take";
const nm = document.createElement("span"); nm.className = "name"; nm.textContent = `${tk.name} · ${tk.secs.toFixed(1)} s`;
const edb = document.createElement("button"); edb.type = "button"; edb.className = "btn"; edb.textContent = t("edEdit");
edb.onclick = () => { go("ed"); edOpen(tk); };
if (tk.planes && tk.planes.length && tk.planes[0].length) row.append(edb);
row.append(nm, ...tk.files.map((f) => {
const a = document.createElement("a"); a.className = "btn ghost"; a.textContent = f.label; a.download = f.name;
a.href = f.url || (f.url = URL.createObjectURL(f.blob)); return a;
}));
return row;
}));
}
/* ------------------------------------------------------------------------------------------------ the audio editor */
let aed = null;
function edMake() {
if (aed) return aed;
const W = {}; for (const k of ["split", "dup", "rev", "norm", "del", "snap", "expMix", "expTracks", "empty", "added", "pick", "pickHelp", "splitHere", "undone", "gain", "fin", "fout", "rendering", "exported"]) W[k] = t("ed_" + k);
aed = new AudioEditor($("aed"), W, { wav: wavFile, zip: zipStored });
return aed;
}
function edOpen(tk) { if (!tk || !tk.planes || !tk.planes[0] || !tk.planes[0].length) return; edMake().addTake({ name: tk.name, rate: tk.rate || rec.rate, planes: tk.planes, lanes: tk.lanes }); }
function renderEd() {
edMake();
const sel = $("edtake"), cur = sel.value;
const ok = rec.takes.filter((tk) => tk.planes && tk.planes[0] && tk.planes[0].length);
sel.replaceChildren(...(ok.length ? ok.map((tk, i) => { const o = document.createElement("option"); o.value = String(i); o.textContent = `${tk.name} · ${tk.secs.toFixed(1)} s`; return o; })
: [Object.assign(document.createElement("option"), { value: "", textContent: t("recNone") })]));
if (cur && sel.querySelector(`option[value="${cur}"]`)) sel.value = cur;
$("edadd").disabled = !ok.length;
$("edadd").onclick = () => { const tk = ok[+sel.value]; if (tk) edOpen(tk); };
}
$("edfile").onclick = () => $("edfilein").click();
$("edfilein").onchange = async () => { const fs = [...$("edfilein").files]; $("edfilein").value = ""; for (const f of fs) { try { await edMake().addFile(f); } catch (e) { edMake().say(String(e.message || e)); } } };
/* -------------------------------------------------------------------------------------------- other devices */
/* JIANT FM's ports (ports/README.md): each one's state, what it is, and its links: the emulator (emu/devices.html, the
* same origin: shown here in a frame), the download (the releases), its manual. The words are TEXT's (p<Name>...) */
const GH = "https://github.com/juanjiant-bit/JIANT/blob/main/", RELEASES = "https://github.com/juanjiant-bit/JIANT/releases";
const MAN = "../docs/guide/"; // the manuals in HTML (tools/gen_manual_html.py), this site's
const OUTLINE = { // a device's outline where there is no picture (the pads, the keys)
smk: '<svg viewBox="0 0 320 120" fill="none" stroke="currentColor" stroke-width="2"><rect x="4" y="4" width="312" height="112" rx="10"/><rect x="16" y="14" width="44" height="34" rx="3"/>' +
Array.from({ length: 8 }, (_, i) => `<rect x="${72 + i * 26}" y="16" width="20" height="13" rx="2"/><rect x="${72 + i * 26}" y="34" width="20" height="13" rx="2"/>`).join("") +
Array.from({ length: 22 }, (_, i) => `<rect x="${16 + i * 13.3}" y="62" width="11" height="46" rx="2"/>`).join("") + "</svg>",
mpc: '<svg viewBox="0 0 240 150" fill="none" stroke="currentColor" stroke-width="2"><rect x="4" y="4" width="232" height="142" rx="12"/><rect x="16" y="16" width="86" height="54" rx="4"/>' +
Array.from({ length: 16 }, (_, i) => `<rect x="${118 + (i % 4) * 28}" y="${16 + Math.floor(i / 4) * 31}" width="24" height="27" rx="4"/>`).join("") +
'<circle cx="30" cy="96" r="10"/><circle cx="60" cy="96" r="10"/><circle cx="90" cy="96" r="10"/><rect x="18" y="118" width="84" height="8" rx="4"/></svg>',
plug: '<svg viewBox="0 0 240 150" fill="none" stroke="currentColor" stroke-width="2"><rect x="4" y="4" width="232" height="142" rx="8"/><path d="M4 26h232"/><circle cx="16" cy="15" r="3"/><circle cx="28" cy="15" r="3"/>' +
'<rect x="18" y="40" width="60" height="92" rx="3"/><rect x="88" y="40" width="64" height="64" rx="3"/><circle cx="178" cy="54" r="12"/><circle cx="210" cy="54" r="12"/><rect x="164" y="80" width="60" height="52" rx="3"/></svg>',
};
const PORTS = [
// shots: the port running (its emulator's panel in the browser, the plugin's editor), the first one on the card
{ id: "smk37", name: "pSmkTitle", text: "pSmkText", points: ["pSmk1", "pSmk2"], state: ["stDev", "soon"], pic: OUTLINE.smk,
shots: [["img/smk37.webp", "shotSmk"]],
links: [["portTry", "#try:smk37"], ["portManual", MAN + "smk37.html"], ["portBuild", GH + "docs/SMK37.md"], ["smkInstaller", "smk37/index.html"]] },
{ id: "mpc", name: "pMpcTitle", text: "pMpcText", points: ["pMpc1", "pMpc2"], state: ["stPreview", "soon"], pic: OUTLINE.mpc,
shots: [["img/mpc.webp", "shotMpc"]], whole: true, // (the unit stands upright: all of it shown)
links: [["portTry", "#try:mpc"], ["portManual", MAN + "mpc-sample.html"], ["portDownload", RELEASES], ["portInstall", MAN + "mpc-sample.html#release"]] },
// (the plugins: coming soon, for sale; no download here)
{ id: "mpcplug", name: "pPlugMpcTitle", text: "pPlugMpcText", points: ["pPlugMpc1"], state: ["stSoon", "soon"], pic: OUTLINE.mpc,
links: [["portManual", MAN + "ports.html#the-mpc-plugin"], ["portSoonBuy", null]] },
{ id: "daw", name: "pDawTitle", text: "pDawText", points: ["pDaw1", "pDaw2", "pDaw3"], state: ["stSoon", "soon"],
shots: [["img/plugin.webp", "shotDaw"], ["img/plugin-sound.webp", "shotDawSound"], ["img/plugin-samples.webp", "shotDawSamples"]],
links: [["portManual", MAN + "plugin.html"], ["portSoonBuy", null]] },
];
let docsFor = "";
function renderPorts() {
const el = (tag, cls, text) => { const e = document.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e; };
$("portlist").replaceChildren(...PORTS.map((p) => {
const card = el("article", "card port");
const pic = el("div", "pic");
let thumbs = null;
if (p.shots) {
// the shot (a tap: larger), and under it a thumbnail each when there are more
const im = new Image(); im.loading = "lazy"; if (p.whole) im.style.objectFit = "contain";
const show = (k) => { im.src = p.shots[k][0]; im.alt = t(p.shots[k][1]); pic.dataset.k = k;
if (thumbs) [...thumbs.children].forEach((b, i) => b.setAttribute("aria-pressed", String(i === k))); };
const open = el("button", "picopen"); open.type = "button"; open.append(im);
open.addEventListener("click", () => openShot(p, +pic.dataset.k || 0));
pic.append(open);
if (p.shots.length > 1) {
thumbs = el("div", "thumbs");
thumbs.append(...p.shots.map(([src, cap], k) => {
const b = el("button"); b.type = "button"; b.title = t(cap);
const ti = new Image(); ti.src = src; ti.alt = ""; ti.loading = "lazy"; b.append(ti);
b.addEventListener("click", () => show(k));
return b;
}));
}
show(0);
} else { pic.innerHTML = p.pic; pic.setAttribute("aria-hidden", "true"); }
const meta = el("div", "meta"); meta.append(el("span", "state " + p.state[1], t(p.state[0])));
const ul = el("ul"); ul.append(...p.points.map((k) => el("li", null, t(k))));
const links = el("div", "links");
links.append(...p.links.map(([k, href], i) => {
if (!href) return el("span", "btn ghost na", t(k));
const a = el("a", "btn" + (i ? " ghost" : ""), t(k)); a.href = href;
if (href.startsWith("#try:")) a.addEventListener("click", (e) => { e.preventDefault(); tryDevice(href.slice(5), t(p.name)); });
else { a.target = "_blank"; a.rel = "noopener"; }
return a;
}));
card.append(pic, ...(thumbs ? [thumbs] : []), el("h2", null, t(p.name)), meta, el("p", null, t(p.text)), ul, links);
return card;
}));
}
/* a port's shots, large: a dialog, its caption, ← → between them */
function openShot(p, k) {
const dlg = $("shotdlg"), img = $("shotimg"), cap = $("shotcap");
const show = () => { img.src = p.shots[k][0]; img.alt = p.title || t(p.shots[k][1]); cap.textContent = p.title || `${t(p.name)} · ${t(p.shots[k][1])}`;
$("shotprev").hidden = $("shotnext").hidden = p.shots.length < 2; };
dlg._step = (d) => { k = (k + d + p.shots.length) % p.shots.length; show(); };
show();
dlg.showModal();
}
$("shotprev").addEventListener("click", () => $("shotdlg")._step(-1));
$("shotnext").addEventListener("click", () => $("shotdlg")._step(1));
$("shotclose").addEventListener("click", () => $("shotdlg").close());
$("shotdlg").addEventListener("click", (e) => { if (e.target === $("shotdlg")) $("shotdlg").close(); });
$("shotdlg").addEventListener("keydown", (e) => { if (e.key === "ArrowLeft") $("shotdlg")._step(-1); else if (e.key === "ArrowRight") $("shotdlg")._step(1); });
/* the device's emulator (the JIANT FM site's emu/devices.html, its panel picked by the hash) in the frame below */
function tryDevice(dev, name) {
const f = $("f-devices"), url = `${TOOLS.fm.base}emu/devices.html#${dev}`;
$("devtry").hidden = false; $("devtrytitle").textContent = `${t("portTry")} · ${name}`;
if (f.src !== new URL(url, location.href).href) f.src = url;
$("devtry").scrollIntoView({ behavior: "smooth", block: "start" });
}
$("f-devices").addEventListener("load", () => {
const f = $("f-devices");
dress(f);
try { // inside Studio: straight to the devices and their panel (its own bar, title, plugins note and footer are Studio's)
const d = f.contentDocument, st = d.createElement("style");
st.textContent = "main>header.top,main>section:first-of-type,section.plugins,main>footer,body>footer{display:none!important}";
d.head.append(st);
// the frame as tall as the page in it: the whole device and its screen larger, no scrolling inside
const fit = () => { f.style.height = `${Math.max(480, Math.ceil(d.body.getBoundingClientRect().bottom + f.contentWindow.scrollY) + 16)}px`; };
new f.contentWindow.ResizeObserver(fit).observe(d.body); fit();
} catch (_) {}
});
$("devtryclose").addEventListener("click", () => { $("devtry").hidden = true; $("f-devices").src = "about:blank"; });
/* ------------------------------------------------------------------------------------- projects and backups */
/* By hand: the device's project slots A-D (9 PROJECT: 0 load, 1 save, 2 query) and complete backups (65-67, fm1backup.js:
* the installer's and the editor's), from the FM-1 or the emulator (its editor handler answers the same). Backups are
* kept in this browser (IndexedDB) and, if asked, downloaded; restoring one tells the other tools on jiant-midi to let go
* of the FM-1 first (as the installer does) */
const proj = { slots: [null, null, null, null], working: false, list: [], emuLink: null };
const SLOT = ["A", "B", "C", "D"];
function projLink() {
if (state.target === "fm1") return state.dev ? { link: state.dev.link, name: devName(state.dev) } : null;
if (!emuOn()) return null;
if (!proj.emuLink || proj.emuLink.closed) {
const m = emuMidi(), input = [...m.inputs.values()][0], output = [...m.outputs.values()][0];
const link = proj.emuLink = new Link(output, () => {});
input.addEventListener("midimessage", (e) => link.receive(e.data));
}
return { link: proj.emuLink, name: t("bkTarget") };
}
/* fm1backup.js's request ([cmd, args], {timeout, retries, match}) over a Link */
const bkRequest = (link) => async ([cmd, args], o = {}) => {
for (let k = 0; ; k++) {
try { return await link.request(cmd, args, o.timeout || 1200, o.match || null); }
catch (e) { if (e.message !== "timeout" || k >= (o.retries || 0)) throw new Error(e.message === "timeout" ? "timeout" : e.message); }
}
};
/* the library: IndexedDB (a memory list where it is not allowed) */
const bkDb = (() => {
let db = null, mem = [], memId = 1;
const open = () => db || (db = new Promise((res) => {
try {
const r = indexedDB.open("jiant-studio", 1);
r.onupgradeneeded = () => r.result.createObjectStore("backups", { keyPath: "id", autoIncrement: true });
r.onsuccess = () => res(r.result); r.onerror = () => res(null);
} catch (_) { res(null); }
}));
const tx = async (mode, f) => { const d = await open(); if (!d) return null;
return new Promise((res, rej) => { const st = d.transaction("backups", mode).objectStore("backups"), r = f(st); r.onsuccess = () => res(r.result); r.onerror = () => rej(r.error); }); };
return {
async all() { const a = await tx("readonly", (st) => st.getAll()); return (a || mem).slice().sort((x, y) => y.created.localeCompare(x.created)); },
async put(b) { const id = await tx("readwrite", (st) => st.put(b)); if (id == null) { if (!b.id) b.id = memId++; mem = mem.filter((x) => x.id !== b.id).concat(b); return b.id; } return id; },
async del(id) { const r = await tx("readwrite", (st) => st.delete(id)); if (r === null) mem = mem.filter((x) => x.id !== id); },
};
})();
/* what a backup holds, in a line: the current music, the songs (6 x 4 sections from id 40), its size */
function bkSummary(file) {
const objs = file.objects || [], size = objs.reduce((n, o) => n + (o.size || 0), 0);
const songs = new Map();
for (const o of objs) if (o.id >= 40 && o.size) { const n = ((o.id - 40) >> 2) + 1; songs.set(n, (songs.get(n) || 0) + 1); }
const secs = [...songs.values()].reduce((a, b) => a + b, 0);
const parts = [];
if (objs.find((o) => o.id === 0 && o.size)) parts.push(t("bkMusic"));
if (songs.size) parts.push(`${t("bkSongs").replace("%n", songs.size)} (${t("bkSections").replace("%n", secs)})`);
parts.push(`${(size / 1024).toFixed(1)} KB`);
return parts.join(" · ");
}
const bkJiant = (file) => { try { readBackup(file); return true; } catch (_) { return false; } };
const stamp = (d) => d.toLocaleString(lang === "es" ? "es-AR" : "en-GB", { day: "2-digit", month: "2-digit", year: "numeric", hour: "2-digit", minute: "2-digit" });
const fileName = (b) => `${(b.name || "backup").replace(/[^\w.-]+/g, "_")}.json`;
function download(blob, name) { const a = document.createElement("a"); a.href = URL.createObjectURL(blob); a.download = name; document.body.append(a); a.click(); a.remove(); setTimeout(() => URL.revokeObjectURL(a.href), 4000); }
function projSay(s) { $("projstat").textContent = s; }
function progress(done, total) { $("bkprog").hidden = !total; $("bkbar").style.width = total ? `${Math.round(done / total * 100)}%` : "0"; }
/* the other tools let go (the editor in its frame, other tabs), the screen stops, then f; then they may come back */
async function exclusive(f) {
proj.working = true; renderProj();
try { midiBc && midiBc.postMessage({ type: "installer", busy: true }); } catch (_) {}
screenStop();
await new Promise((r) => setTimeout(r, 400));
try { return await f(); }
finally {
try { midiBc && midiBc.postMessage({ type: "installer", busy: false }); } catch (_) {}
proj.working = false; progress(0, 0); renderProj();
}
}
async function backupNow() {
const L = projLink();
if (!L) { projSay(t("bkNoDev")); return; }
await exclusive(async () => {
try {
projSay(t("bkWorking"));
const fw = state.target === "emu" ? `${state.fw === "byte" ? "JIANT BYTE" : "JIANT FM"} (emulator)` : L.name;
let file;
try { file = await captureBackup(bkRequest(L.link), fw, (d, n) => { progress(d, n); projSay(t("bkWorking") + `${Math.round(d / n * 100)} %`); }); }
catch (e) { // (another firmware's list of objects: kept whole, restored with its own editor)
if (!/manifest|archive object/i.test(e.message)) throw e;
file = await captureBackup(bkRequest(L.link), fw, (d, n) => progress(d, n), { complete: true });
}
const now = new Date(), b = { name: `${fw} · ${stamp(now)}`, created: now.toISOString(), fw: state.fw, firmware: fw, summary: bkSummary(file), file };
b.id = await bkDb.put(b);
if ($("bkdl").checked) download(new Blob([JSON.stringify(file)], { type: "application/json" }), fileName(b));
projSay(t("bkDone").replace("%s", b.name));
} catch (e) { projSay(t("bkFail").replace("%s", e.message)); }
await loadList();
});
}
/* ---- old projects (before V10.7): found with today's firmware, converted with emu-convert (convert.js) */
const cvSay = (x) => { $("cvstat").textContent = x; };
const cvUrls = () => [`${TOOLS.fm.base}emu/felucca.wasm`, `${TOOLS.fm.base}preview/emu/felucca.wasm`];
async function cvFind(objects) {
cvSay(t("cvChecking"));
const ex = await cvChecker(cvUrls());
if (!ex) throw new Error(t("cvNoChecker"));
return cvClassify(ex, objects).filter((r) => r.state === "old");
}
$("cvgo").onclick = async () => {
const L = projLink(); if (!L) { cvSay(t("bkNoDev")); return; }
await exclusive(async () => {
try {
cvSay(t("bkWorking"));
const fw = L.name, file = await captureBackup(bkRequest(L.link), fw, (d, n) => { progress(d, n); cvSay(t("bkWorking") + `${Math.round(d / n * 100)} %`); });
const now = new Date(), b = { name: `${t("cvBefore")} · ${fw} · ${stamp(now)}`, created: now.toISOString(), fw: state.fw, firmware: fw, summary: bkSummary(file), file };
b.id = await bkDb.put(b); // everything as it was, kept in this browser first
const objects = readBackup(file).objects, old = await cvFind(objects);
if (!old.length) { cvSay(t("cvNone")); return; }
const names = old.map((r) => cvName(r.id)).join(", ");
if (!confirm(t("cvConfirm").replace("%n", old.length).replace("%s", names))) { cvSay(t("cvFound").replace("%s", names)); return; }
const req = bkRequest(L.link);
for (const [i, r] of old.entries()) {
cvSay(t("cvConverting").replace("%s", cvName(r.id)) + ` ${i + 1}/${old.length}`);
await cvPut(req, r.id, await cvConvert(`${TOOLS.fm.base}emu-convert/felucca.wasm`, objects.find((o) => o.id === r.id).bytes));
}
cvSay(t("cvDone").replace("%s", names));
} catch (e) { cvSay(t("cvFail").replace("%s", e.message)); }
await loadList();
});
};
$("cvfilebtn").onclick = () => $("cvfile").click();
$("cvfile").onchange = async () => {
const f = $("cvfile").files[0]; $("cvfile").value = ""; if (!f) return;
try {
const file = JSON.parse(await f.text()), objects = readBackup(file).objects, old = await cvFind(objects);
if (!old.length) { cvSay(t("cvNone")); return; }
for (const r of old) cvReplace(file, r.id, await cvConvert(`${TOOLS.fm.base}emu-convert/felucca.wasm`, objects.find((o) => o.id === r.id).bytes));
download(new Blob([JSON.stringify(file)], { type: "application/json" }), f.name.replace(/\.json$/i, "") + "-converted.json");
cvSay(t("cvFileDone").replace("%s", old.map((r) => cvName(r.id)).join(", ")));
} catch (e) { cvSay(t("cvFail").replace("%s", e.message)); }
};
/* ---- the project library (JIANT FM V10.8.54: PROJ_LIST 95, PROJ_NAME 96, PROJ_OP 97): the FM-1's projects by name, their
parts A..D, renamed live, copied, moved, deleted, exported and imported one by one (their parts as backup objects
40 + 4n + k); before anything is overwritten or deleted, a copy of it is downloaded */
const pj = { list: null, busy: false };
const pjSay = (x) => { $("pjstat").textContent = x; };
const PJ_RC = ["", "pjRc1", "pjRc2", "pjRc3", "pjRc4"];
async function pjRead() {
const L = projLink(); if (!L) { pjSay(t("bkNoDev")); return; }
try {
const a = await L.link.request(95, [], 1500);
if (a[0]) throw new Error(t(PJ_RC[a[0]] || "pjRc1"));
const n = a[1], list = [];
for (let i = 0; i < n; i++) { const b = 2 + i * 15; list.push({ n: a[b], parts: a[b + 1], open: !!(a[b + 2] & 1), gen: !!(a[b + 2] & 2), name: String.fromCharCode(...a.slice(b + 3, b + 15).filter((c) => c)) }); }
pj.list = list; pjSay("");
} catch (e) { pj.list = null; pjSay(e.message === "timeout" ? t("pjOld") : e.message); }
renderPj();
}
/* a project's four parts as backup objects (their sizes from the backup list) */
async function pjExport(p, quiet) {
const L = projLink(), req = bkRequest(L.link);
const man = bkManifestAll(await req([65, []], { timeout: 8000, retries: 1 })), objs = [];
for (let k = 0; k < 4; k++) {
const o = man.find((m) => m.id === 40 + 4 * p.n + k);
if (!o || !o.size) { objs.push({ k, size: 0, data: "" }); continue; }
const bytes = new Uint8Array(o.size);
for (let off = 0; off < o.size; off += 256) {
const size = Math.min(256, o.size - off), match = (r) => r[0] === o.id && (() => { try { return bkR32(r, 2) === off; } catch (_) { return false; } })();
const a = await req([66, [o.id, ...bkU32(off), size & 127, size >>> 7]], { timeout: 2500, retries: 2, match });
if (a[1]) throw new Error(t("pjRc2"));
bytes.set(bkUnpack(a.slice(9), size), off);
}
let s = ""; for (const b of bytes) s += String.fromCharCode(b);
objs.push({ k, size: o.size, crc: bkCrc(bytes), data: btoa(s) });
}
const file = { format: "jiant-project", version: 1, firmware: L.name, created: new Date().toISOString(), name: p.name, parts: objs };
const fname = `${quiet === true ? "before-" : ""}jiant-project-${p.n + 1}-${(p.name || "untitled").replace(/[^\w-]+/g, "_")}.json`, blob = new Blob([JSON.stringify(file)], { type: "application/json" });
if (quiet === "share") { const f = new File([blob], fname.replace(/^share-/, ""), { type: "application/json" }); try { await navigator.share({ files: [f], title: p.name || fname }); return file; } catch (e) { if (e && e.name === "AbortError") return file; } }
download(blob, fname.replace(/^share-/, ""));
return file;
}
async function pjDo(f) {
if (pj.busy) return; pj.busy = true; renderPj();
try { await exclusive(f); } catch (e) { pjSay(e.message); }
pj.busy = false; await pjRead();
}
function pjTarget(p, k) {
const v = prompt(t(k).replace("%s", p.n + 1)); if (!v) return null;
const to = (parseInt(v, 10) || 0) - 1, q = pj.list && pj.list.find((x) => x.n === to);
if (!q || to === p.n) { pjSay(t("pjBadTarget")); return null; }
return q;
}
async function pjOp(op, p, q) {
const L = projLink();
if (q && q.parts && !confirm(t("pjOverwrite").replace("%s", q.n + 1).replace("%n", q.name || "—"))) return;
if (op === 2 && !confirm(t("pjDelConfirm").replace("%s", p.n + 1).replace("%n", p.name || "—"))) return;
await pjDo(async () => {
const victim = op === 2 ? p : q && q.parts ? q : null;
if (victim) { pjSay(t("pjSaving")); await pjExport(victim, true); } // a copy of what goes, first
const a = await L.link.request(97, [op, p.n, q ? q.n : 0, q && q.parts ? 1 : 0], 6000);
pjSay(a[3] ? t(PJ_RC[a[3]] || "pjRc1") : t("pjDone"));
});
}
async function pjImport(p) {
$("pjfile").onchange = async () => {
const f = $("pjfile").files[0]; $("pjfile").value = ""; if (!f) return;
let file; try { file = JSON.parse(await f.text()); if (!(file.format === "jiant-project" || (file.format === "jiant-fm-project" && Array.isArray(file.parts)))) throw 0; } catch (_) { pjSay(t("pjBadFile")); return; }
if (p.open) { pjSay(t("pjRc1")); return; }
if (p.parts && !confirm(t("pjOverwrite").replace("%s", p.n + 1).replace("%n", p.name || "—"))) return;
await pjDo(async () => {
if (p.parts) { pjSay(t("pjSaving")); await pjExport(p, true); }
const req = bkRequest(projLink().link);
for (const o of file.parts) {
if (!o.size) continue;
const bytes = Uint8Array.from(atob(o.data), (c) => c.charCodeAt(0));
pjSay(t("pjWriting").replace("%s", "ABCD"[o.k]));
await cvPut(req, 40 + 4 * p.n + o.k, bytes);
}
pjSay(t("pjDone"));
});
};
$("pjfile").click();
}
function renderPj() {
if (!$("pjgrid")) return;
const can = !!projLink() && !state.busy && !proj.working && !pj.busy;
$("pjcard").hidden = false; $("pjread").disabled = !can;
$("pjhelp").textContent = t(pj.list ? "pjTap" : projLink() ? "pjAsk" : "bkNoDev");
const el = (tag, cls, text) => { const e = document.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e; };
const btn = (k, cls, f, dis) => { const b = el("button", "btn" + (cls ? " " + cls : ""), t(k)); b.type = "button"; b.disabled = !can || !!dis; b.onclick = f; return b; };
const clean = (v) => v.toUpperCase().replace(/[^ -~]/g, "").slice(0, 12);
const rename = async (p, k, v) => {
const a = await projLink().link.request(96, [p.n, k, ...[...v].map((ch) => ch.charCodeAt(0))], 2000).catch(() => null);
pjSay(a && !a[2] ? t("pjRenamed").replace("%s", k ? `${p.n + 1}${"ABCD"[k]} ${v}` : v || "—") : t(PJ_RC[a ? a[2] : 1] || "pjRc1"));
if (!k) pjRead();
};
const group = (title, ...kids) => { const g = el("div", "pjg"); g.append(el("p", "pjgt", title)); const r = el("div", "pjrow"); r.append(...kids); g.append(r); return g; };
const targets = (p, op) => (pj.list || []).filter((q) => q.n !== p.n).map((q) => {
const b = el("button", "pjto" + (q.parts ? " used" : ""), String(q.n + 1)); b.type = "button"; b.title = q.name || t(q.parts ? "pjUnnamed" : "pjEmpty");
b.disabled = !can || !p.parts || (op === 1 && (p.open || q.open)); b.onclick = () => pjOp(op, p, q); return b;
});
$("pjgrid").replaceChildren(...(pj.list || []).map((p) => {
const empty = !p.parts, isOpen = pj.sel === p.n;
const c = el("div", "pj" + (p.open ? " open" : "") + (empty ? " empty" : "") + (isOpen ? " sel" : ""));
const head = el("button", "pjhead"); head.type = "button"; head.setAttribute("aria-expanded", String(isOpen));
head.onclick = () => { pj.sel = isOpen ? null : p.n; renderPj(); };
const info = el("span", "pjinfo"), parts = el("span", "parts");
for (let k = 0; k < 4; k++) parts.append(el("i", p.parts & (1 << k) ? "on" : "", "ABCD"[k]));
info.append(el("b", "pjname", empty ? t("pjEmpty") : p.name || t("pjUnnamed")), parts);
head.append(el("span", "num", String(p.n + 1)), info);
if (p.open) head.append(el("span", "tag", t("pjOpen"))); if (p.gen) head.append(el("span", "tag", "GEN"));
head.append(el("span", "chev", isOpen ? "–" : "+"));
c.append(head);
if (isOpen) {
const body = el("div", "pjbody");
if (empty) body.append(el("p", "dim", t("pjEmptyHelp")), group(t("pjGFile"), btn("pjImport", "", () => pjImport(p), p.open)));
else {
const name = el("input"), save = btn("pjSaveName", "ghost", () => rename(p, 0, clean(name.value)));
name.maxLength = 12; name.value = p.name; name.placeholder = t("pjUnnamed"); name.disabled = !can; name.setAttribute("aria-label", t("pjName"));
name.setAttribute("autocapitalize", "characters"); name.setAttribute("autocomplete", "off"); name.spellcheck = false;
name.onkeydown = (e) => { if (e.key === "Enter") save.click(); };
const ex = (mode) => () => pjDo(async () => { pjSay(t("pjSaving")); await pjExport(p, mode); pjSay(t("pjDone")); });
const fileBtns = [btn(navigator.canShare ? "pjShare" : "pjDownload", "", ex(navigator.canShare ? "share" : false))];
if (navigator.canShare) fileBtns.push(btn("pjDownload", "ghost", ex(false)));
fileBtns.push(btn("pjImport", "ghost", () => pjImport(p), p.open));
const partRow = []; for (let k = 1; k < 4; k++) if (p.parts & (1 << k)) {
const w = el("label", "pjpart"), i = el("input"); i.maxLength = 12; i.placeholder = `${p.n + 1}${"ABCD"[k]}`; i.disabled = !can; i.spellcheck = false; i.setAttribute("autocapitalize", "characters");
i.onchange = () => rename(p, k, clean(i.value)); w.append(el("span", null, "ABCD"[k]), i); partRow.push(w);
}
body.append(group(t("pjGName"), name, save), group(t("pjGFile"), ...fileBtns), group(t("pjGCopy"), ...targets(p, 0)));
if (!p.open) body.append(group(t("pjGMove"), ...targets(p, 1)));
if (partRow.length) body.append(group(t("pjGParts"), ...partRow));
const del = btn("pjDelete", "danger", () => pjOp(2, p), p.open); const dz = el("div", "pjdel"); dz.append(del); body.append(dz);
}
c.append(body);
}
return c;
}));
$("pjgrid").classList.toggle("busy", !!pj.busy);
if (pj.busy && !$("pjstat").textContent) pjSay(t("pjBusyNow"));
}
$("pjread").onclick = () => pjRead();
async function restore(b) {
const L = projLink();
if (!L) { projSay(t("bkNoDev")); return; }
if (!confirm(t("bkConfirm").replace("%s", b.name).replace("%s", L.name))) return;
await exclusive(async () => {
try {
projSay(t("bkRestoring"));
const r = await restoreBackup(bkRequest(L.link), b.file, (d, n) => { progress(d, n); projSay(t("bkRestoring") + `${Math.round(d / n * 100)} %`); });
const lost = songsNotRestored(r.notRestored);
projSay(lost.length ? t("bkRestoredBut").replace("%s", lost.join(", ")) : t("bkRestored").replace("%s", L.name));
} catch (e) { projSay(t("bkFail").replace("%s", e.message)); }
});
}
async function loadList() { proj.list = await bkDb.all(); renderProj(); }
$("bkgo").addEventListener("click", backupNow);
$("bkimport").addEventListener("click", () => $("bkfile").click());
$("bkfile").addEventListener("change", async () => {
const f = $("bkfile").files[0]; $("bkfile").value = "";
if (!f) return;
try {
const file = JSON.parse(await f.text());
if (!file || file.format !== "felucca-backup" || !Array.isArray(file.objects)) throw new Error(t("bkBadFile"));
const b = { name: f.name.replace(/\.json$/i, ""), created: file.created || new Date().toISOString(), fw: /BYTE/i.test(file.firmware || "") ? "byte" : "fm",
firmware: file.firmware || "", summary: bkSummary(file), file };
await bkDb.put(b); projSay(t("bkImported").replace("%s", b.name));
} catch (e) { projSay(t("bkFail").replace("%s", e.message)); }
loadList();
});
/* the slots: read on demand (a query each), Load and Save after asking */
async function readSlots() {
const L = projLink();
if (!L) { projSay(t("bkNoDev")); return; }
for (let k = 0; k < 4; k++) {
try { const a = await L.link.request(9, [2, k], 1500, (r) => r[1] === k); proj.slots[k] = !!a[2]; } catch (_) { proj.slots[k] = null; }
}
renderProj();
}
async function slotDo(k, op) {
const L = projLink();
if (!L) { projSay(t("bkNoDev")); return; }
if (!confirm(t(op ? "slotSaveConfirm" : "slotLoadConfirm").replace("%s", SLOT[k]))) return;
await exclusive(async () => {
try {
const a = await L.link.request(9, [op, k], op ? 6000 : 3000, (r) => r[0] === op && r[1] === k);
if (op === 0 && !a[2]) throw new Error(t("slotEmpty"));
projSay(t(op ? "slotSaved" : "slotLoaded").replace("%s", SLOT[k]));
if (op) proj.slots[k] = true;
} catch (e) { projSay(t("bkFail").replace("%s", e.message)); }
});
}
$("slotsread").addEventListener("click", readSlots);
function renderProj() {
if (!$("v-proj")) return;
const can = !!projLink() && !state.busy && !proj.working;
$("bkgo").disabled = !can; $("slotsread").disabled = !can; $("bkimport").disabled = proj.working;
$("slotshelp").textContent = t("slotsHelp");
const el = (tag, cls, text) => { const e = document.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e; };
const btn = (k, cls, f, dis) => { const b = el("button", "btn" + (cls ? " " + cls : ""), t(k)); b.type = "button"; b.disabled = !!dis; b.addEventListener("click", f); return b; };
$("slots").replaceChildren(...SLOT.map((n, k) => {
const v = proj.slots[k], c = el("div", "slot" + (v ? " used" : ""));
const row = el("div", "row");
row.append(btn("slotLoad", "", () => slotDo(k, 0), !can || v === false), btn("slotSave", "ghost", () => slotDo(k, 1), !can));
c.append(el("b", null, n), el("span", "st", t(v == null ? "slotUnknown" : v ? "slotUsed" : "slotEmpty")), row);
return c;
}));
const list = proj.list.filter((b) => (b.fw || "fm") === state.fw);
$("bklist").replaceChildren(...(list.length ? list.map((b) => {
const r = el("div", "bkrow"), name = el("input"); name.value = b.name; name.setAttribute("aria-label", "name");
name.addEventListener("change", () => { b.name = name.value.trim() || b.name; bkDb.put(b); });
const left = el("div"); left.append(name, el("div", "when", `${stamp(new Date(b.created))} · ${b.firmware || ""}`));
const ok = bkJiant(b.file);
const acts = el("div", "acts");
acts.append(btn("bkDownload", "ghost", () => download(new Blob([JSON.stringify(b.file)], { type: "application/json" }), fileName(b))),
btn("bkRestore", "", () => restore(b), !can || !ok), btn("bkDelete", "ghost", async () => { if (confirm(t("bkDelConfirm").replace("%s", b.name))) { await bkDb.del(b.id); loadList(); } }));
r.append(left, el("div", "what", ok ? b.summary : `${b.summary} · ${t("bkOther")}`), acts);
return r;
}) : [el("p", "bkempty", t("bkEmpty"))]));
}
/* ------------------------------------------------------------------------------------------- wavetables (BYTE) */
/* any sound (a file or the microphone) -> WAVE's USER table, 8 frames x 128 (wavetable.js); heard as a sweep, saved as a
* WAV, sent to a USER slot of JIANT BYTE over USB (protocol 1.5: WT_INFO 90, WT_WRITE 91 in chunks with an ack, WT_COMMIT
* 92; WT_READ 93 back). The FM-1 or the emulator, as Projects */
const wt = { frames: null, sel: 0, info: null, rec: null, working: false };
const wtSay = (x) => { $("wtstat").textContent = x; };
function wtDraw() {
$("wtcard").hidden = !wt.frames; renderWtDev();
if (!wt.frames) return;
const css = getComputedStyle(document.documentElement), fg = css.getPropertyValue("--accent").trim() || "#fff", dim = css.getPropertyValue("--dim").trim() || "#888";
const box = $("wtframes");
if (box.children.length !== FRAMES) box.replaceChildren(...Array.from({ length: FRAMES }, (_, i) => { const c = document.createElement("canvas"); c.width = c.height = 128; c.onclick = () => { wt.sel = i; wtDraw(); }; return c; }));
[...box.children].forEach((c, i) => {
const g = c.getContext("2d"); g.clearRect(0, 0, 128, 128); c.classList.toggle("on", i === wt.sel);
g.strokeStyle = dim; g.beginPath(); g.moveTo(0, 64); g.lineTo(128, 64); g.stroke();
g.strokeStyle = fg; g.lineWidth = 2; g.beginPath(); wt.frames[i].forEach((v, k) => (k ? g.lineTo : g.moveTo).call(g, k, 64 - v * 56)); g.stroke();
});
const cv = $("wtsweep"), g = cv.getContext("2d"), W = cv.width, H = cv.height; g.clearRect(0, 0, W, H);
for (let i = FRAMES - 1; i >= 0; i--) { // the frames back to front, each a step up and right
const ox = 40 + i * 70, oy = H - 40 - i * 20, sx = (W - 40 - 7 * 70 - 40) / LEN;
g.globalAlpha = i === wt.sel ? 1 : 0.35 + 0.08 * (FRAMES - i); g.strokeStyle = i === wt.sel ? fg : dim; g.lineWidth = i === wt.sel ? 2.5 : 1.2;
g.beginPath(); wt.frames[i].forEach((v, k) => (k ? g.lineTo : g.moveTo).call(g, ox + k * sx, oy - v * 34)); g.stroke();
}
g.globalAlpha = 1;
}
function wtSet(frames, msg) { wt.frames = frames; if (MOCK) window.__wtFrames = frames; wt.sel = 0; wtSay(msg); wtDraw(); }
async function wtFromBuffer(buf, name) {
try {
const ac = new (window.OfflineAudioContext || window.webkitOfflineAudioContext)(1, 1, 44100);
const a = await ac.decodeAudioData(buf), x = new Float32Array(a.length);
for (let c = 0; c < a.numberOfChannels; c++) { const d = a.getChannelData(c); for (let i = 0; i < x.length; i++) x[i] += d[i] / a.numberOfChannels; }
wtSet(makeTable(x, a.sampleRate), t("wtMade").replace("%s", name));
if (!$("wtname").value) $("wtname").value = name.replace(/\.[^.]+$/, "").toUpperCase().replace(/[^A-Z0-9 ]/g, "").slice(0, 8);
} catch (e) { wtSay(e.message === "silent" ? t("wtSilent") : t("wtBad")); }
}
$("wtfilebtn").onclick = () => $("wtfile").click();
$("wtfile").onchange = async () => { const f = $("wtfile").files[0]; if (f) await wtFromBuffer(await f.arrayBuffer(), f.name); $("wtfile").value = ""; };
$("wtmic").onclick = async () => {
if (wt.rec) { wt.rec.stop(); return; }
try {
const s = await navigator.mediaDevices.getUserMedia({ audio: { echoCancellation: false, noiseSuppression: false, autoGainControl: false } });
const r = wt.rec = new MediaRecorder(s), parts = [];
r.ondataavailable = (e) => parts.push(e.data);
r.onstop = async () => { s.getTracks().forEach((k) => k.stop()); wt.rec = null; $("wtmic").textContent = t("wtMic"); await wtFromBuffer(await new Blob(parts).arrayBuffer(), t("wtMicName")); };
r.start(); $("wtmic").textContent = t("wtMicStop"); wtSay(t("wtRecording"));
setTimeout(() => { if (wt.rec === r) r.stop(); }, 8000);
} catch (_) { wtSay(t("wtNoMic")); }
};
$("wtplay").onclick = () => {
if (!wt.frames) return;
const ac = new AudioContext(), x = wtRender(wt.frames, ac.sampleRate), b = ac.createBuffer(1, x.length, ac.sampleRate);
b.copyToChannel(x, 0); const s = ac.createBufferSource(); s.buffer = b; s.connect(ac.destination); s.onended = () => ac.close(); s.start();
};
$("wtwav").onclick = () => { if (!wt.frames) return; const a = document.createElement("a"); a.href = URL.createObjectURL(wtWav(wt.frames)); a.download = `${($("wtname").value || "WAVETABLE").trim()}.wav`; a.click(); setTimeout(() => URL.revokeObjectURL(a.href), 4000); };
/* the device: its USER slots */
function wtLink() { return state.fw === "byte" ? projLink() : null; }
function renderWtDev() {
if (!$("wtdevcard")) return;
const L = wtLink();
$("wtdevcard").hidden = !wt.frames && !wt.info;
$("wtslotshelp").textContent = state.fw !== "byte" ? t("wtByteOnly") : !L ? t("wtNoDev") : wt.info ? t("wtSlotsHelp").replace("%s", L.name) : t("wtAsk");
const sel = $("wtslot"), cur = sel.value;
const n = wt.info ? wt.info.n : 8;
sel.replaceChildren(...Array.from({ length: n }, (_, i) => { const o = document.createElement("option"); o.value = i; o.textContent = `USER ${i + 1}${wt.info && wt.info.used[i] ? " · " + (wt.info.names[i] || "—") : wt.info ? " · " + t("wtEmpty") : ""}`; return o; }));
if (cur) sel.value = cur;
for (const id of ["wtsend", "wtload", "wtread"]) $(id).disabled = !L || wt.working;
$("wtsend").disabled ||= !wt.frames;
}
async function wtInfo(L) { wt.info = parseWtInfo(await L.link.request(WT.INFO, [], 900)); }
$("wtread").onclick = async () => { const L = wtLink(); if (!L) return; try { await wtInfo(L); wtSay(""); } catch (_) { wtSay(t("wtOld")); } renderWtDev(); };
$("wtsend").onclick = async () => {
const L = wtLink(); if (!L || !wt.frames) return;
const slot = +$("wtslot").value, name = ($("wtname").value || "USER").toUpperCase().slice(0, 8);
wt.working = true; renderWtDev(); $("wtprog").hidden = false;
try {
for (let f = 0; f < FRAMES; f++) {
const i16 = toI16(wt.frames[f]);
for (let c = 0; c < CHUNKS; c++) {
const a = await L.link.request(WT.WRITE, [slot, f, c, ...wtPack(i16, c)], 900, (r) => r[0] === slot && r[1] === f && r[2] === c);
if (a[3]) throw new Error(t(a[3] === 2 ? "wtBusy" : "wtSlotBad"));
$("wtbar").style.width = `${Math.round(((f * CHUNKS + c + 1) / (FRAMES * CHUNKS)) * 100)}%`;
}
}
const r = await L.link.request(WT.COMMIT, [slot, ...[...name].map((ch) => ch.charCodeAt(0) & 127), 0], 3000, (r) => r[0] === slot);
if (r[1]) throw new Error(t("wtBusy"));
wtSay(t("wtSent").replace("%s", `USER ${slot + 1}`).replace("%n", name));
try { await wtInfo(L); } catch (_) {}
} catch (e) { wtSay(e.message === "timeout" ? t("wtOld") : e.message); }
wt.working = false; $("wtprog").hidden = true; renderWtDev();
};
$("wtload").onclick = async () => {
const L = wtLink(); if (!L) return;
const slot = +$("wtslot").value; wt.working = true; renderWtDev();
try {
const frames = [];
for (let f = 0; f < FRAMES; f++) {
const s = [];
for (let c = 0; c < CHUNKS; c++) s.push(...wtUnpack((await L.link.request(WT.READ, [slot, f, c], 900, (r) => r[0] === slot && r[1] === f && r[2] === c)).slice(3)));
frames.push(Float32Array.from(s, (v) => v / 32000));
}
if (wt.info && wt.info.names[slot]) $("wtname").value = wt.info.names[slot];
wtSet(frames, t("wtLoaded").replace("%s", `USER ${slot + 1}`));
} catch (_) { wtSay(t("wtOld")); }
wt.working = false; renderWtDev();
};
/* ------------------------------------------------------------------------------------------------ radio (votes) */
/* The generator heard by real ears: the public emulator with GEN on RADIO (a new piece when one ends), the piece told
* (genre, mood, form), 👍 / 👎 (a vote, then the next) or ⏭ (the next, no vote). A vote is the piece's data only
* (device, version, genre, seed, mood, energy, form, seconds heard, ±1, a random id of this browser) into Juan's Supabase
* (insert only; 409 = voted already, taken as done); offline, kept and sent later. The generator through jiantEmu.gen
* (web/emu worklet.js: the firmware's web_gen_info / web_gen_genre / web_gen_cmd) */
const RD_URL = "https://tjscbsiofkxshzckmmhk.supabase.co/rest/v1/votes", RD_KEY = "sb_publishable_An299mMM1UZte-5dkjnojg_Cl_Lk6tM";
const RD_FORMS = ["LOOP", "PARTS", "SONG", "MY LOOP"]; // (3 MY LOOP: JIANT BYTE's)
const rdInfo = (i) => Array.isArray(i) ? i : i ? [i.radio, i.genre, i.seed, i.mood, i.energy, i.form, i.n ?? i.piece, i.playing] : null; // (BYTE's shell: an object)
const rdGenre = (g) => g === -1 ? "EXPLORE" : g === -2 ? "RANDOM" : rd.genres[g] || String(g);
const rd = { pending: null, askT: 0, on: false, timer: 0, info: null, genres: [], piece: -1, since: 0, version: "", votes: 0, queue: [], retry: 0 };
function rdClient() {
let c = null;
try { c = localStorage.getItem("jiant.studio.radio.client"); } catch (_) {}
if (!c) { c = "c" + Array.from(crypto.getRandomValues(new Uint8Array(12)), (b) => b.toString(16).padStart(2, "0")).join(""); try { localStorage.setItem("jiant.studio.radio.client", c); } catch (_) {} }
return c.slice(0, 40);
}
/* the generator: the emulator's (or, with ?mock=1, a pretend one for the tests) */
const rdMock = MOCK && { s: [1, 0, 1234, 0, 64, 2, 1, 1], gen(cmd, arg, g) {
const s = this.s; if (cmd === 10) this.rs = arg; if (cmd === 11) this.rs = null; if (cmd === 0) s[0] = arg ? 1 : 0; if (cmd === 1) { s[6]++; s[2] = (s[2] * 7 + 13) % 99991; this.rs = null; } if (cmd === 2) s[1] = Math.max(0, arg); if (cmd === 3) s[3] = arg; if (cmd === 4) s[7] = arg;
return Promise.resolve({ ok: true, info: [...s], genres: g ? ["HOUSE", "TECHNO", "IDM GLITCH", "DREAM POP"] : null, resound: true, rs: this.rs ?? null, rc: 0 });
} };
function rdGen() {
if (rdMock) return rdMock;
try {
const e = frames.emu.el.contentWindow.jiantEmu;
if (!e || !e.on() || !e.gen) return null;
return { gen: async (c, a, g) => { const r = (await e.gen(c, a, g)) || {}; return { ...r, ok: r.ok ?? !!r.info }; } }; // (BYTE's shell: no ok, info an object)
} catch (_) { return null; }
}
function rdLink() {
if (!emuOn()) return null;
if (!proj.emuLink || proj.emuLink.closed) { const m = emuMidi(), input = [...m.inputs.values()][0], output = [...m.outputs.values()][0]; const link = proj.emuLink = new Link(output, () => {}); input.addEventListener("midimessage", (e) => link.receive(e.data)); }
return proj.emuLink;
}
const rdSay = (x) => { $("rdstat").textContent = x; };
function renderRadio() {
if (!$("rdgo")) return;
rdVis();
$("rdgo").textContent = rd.starting ? t("rdStarting") : "▶ " + t("rdStart"); $("rdgo").disabled = !!rd.starting;
$("rdfwtag").textContent = state.fw === "byte" ? "BYTE" : "FM";
const live = rd.on && !!rd.info;
$("rdcard").hidden = !live; $("rdintro").hidden = live;
if (!rd.info) return;
const [, g, seed, mood, energy, form] = rd.info;
$("rdnow").textContent = rdGenre(g);
if (rd.vis) rd.vis.setInfo({ genre: rdGenre(g), seed, mood, form: RD_FORMS[form] });
$("rdmeta").textContent = `${t("rdMood")} ${mood > 0 ? "+" : ""}${mood} · ${RD_FORMS[form] || "?"} · ${t("rdSeed")} ${seed} · ${rd.version || ""}`;
$("rdcount").textContent = rd.votes ? t("rdThanks").replace("%n", rd.votes) : "";
for (const id of ["rdup", "rddown", "rdskip"]) $(id).disabled = !rd.on;
$("rdsound").hidden = !rd.canResound; $("rdundo").hidden = rd.rs == null;
}
/* the ecosystem: alive while the Radio tab shows; the emulator's stems feed it (each track its species) */
function rdVis() {
if (!rd.vis) rd.vis = new Ecosystem($("rdvis"), state.fw);
rd.vis.setSkin(state.fw);
if (state.view === "radio" && !document.hidden) rd.vis.start(); else rd.vis.stop();
}
function rdFeed() {
clearInterval(rd.fake); if (rd.untap) { rd.untap(); rd.untap = null; }
if (rdMock) { let k = 0; rd.fake = setInterval(() => { k++; rd.vis && rd.vis.feed(Array.from({ length: 6 }, (_, i) => (k + i * 3) % 8 === 0 ? 1 : 0.2 + 0.2 * Math.sin(k / 5 + i))); }, 100); return; }
try {
const e = frames.emu.el.contentWindow.jiantEmu, L = new Levels();
if (e && e.tap) rd.untap = e.tap((m) => { if (rd.vis && m.planes) rd.vis.feed(L.of(m.planes)); });
} catch (_) {}
}
document.addEventListener("visibilitychange", () => rd.vis && rdVis());
/* switched on from its own button beside the radio: the radio follows */
setInterval(() => { if (state.view === "radio" && !rd.on && !rd.starting && !rdMock && emuOn()) rdStart(); }, 1000);
/* the emulator switched on from here (its page in the hidden Emulator tab; the click carries this one's gesture) */
async function rdEmu() {
loadFrame("emu");
const wait = async (f, ms) => { const t0 = Date.now(); while (Date.now() - t0 < ms) { try { const v = f(); if (v) return v; } catch (_) {} await new Promise((r) => setTimeout(r, 200)); } return null; };
const doc = await wait(() => { const d = frames.emu.el.contentDocument; return d && d.getElementById("go") && frames.emu.el.contentWindow.jiantEmu ? d : null; }, 20000);
if (!doc) return false;
if (!emuOn()) { doc.getElementById("go").click(); rdSay(t("rdEmuOn")); }
return !!(await wait(() => emuOn(), 30000));
}
async function rdPoll() {
const G = rdGen(); if (!G || !rd.on) return;
const r = await G.gen(null, 0, !rd.genres.length);
if (!r.ok) { rdSay(t("rdOld")); return; }
if (r.genres && r.genres.length) { rd.genres = r.genres; $("rdgenre").replaceChildren(...[["-2", "RANDOM"], ["-1", "EXPLORE"], ...r.genres.map((n, i) => [String(i), n])].map(([v, n]) => { const o = document.createElement("option"); o.value = v; o.textContent = n; return o; })); }
rd.info = rdInfo(r.info); rd.rs = r.rs ?? null; rd.canResound = !!r.resound;
if (document.activeElement !== $("rdgenre") && rd.info) $("rdgenre").value = String(rd.info[1]);
if (rd.info[6] !== rd.piece) { rd.piece = rd.info[6]; rd.since = Date.now(); }
if (!rd.info[0] && rd.on) G.gen(0, 1); // RADIO back on (the device's own keys can turn it off)
rdSay(""); renderRadio();
}
async function rdStart() {
rd.starting = true; rdSay(""); renderRadio();
try {
if (!rdMock && !(await rdEmu())) { rdSay(t("rdNoEmu")); return; }
const G = rdGen();
if (!G) { rdSay(t("rdOld")); return; }
try { const L = rdLink(); if (L) rd.version = parseInfo(await L.request(CMD.INFO, [], 900)).version.replace(/^\S+\s+/, ""); } catch (_) {}
if (rdMock) rd.version = "V10.8.44";
const r = await G.gen(0, 1, true);
if (!r.ok) { rdSay(t("rdOld")); return; }
rd.on = true;
await G.gen(1, 0); // a piece of its own first (RADIO on has nothing yet to play)
await G.gen(4, 1);
clearInterval(rd.timer); rd.timer = setInterval(rdPoll, 1000);
rdFeed();
await rdPoll();
} finally { rd.starting = false; renderRadio(); }
}
function rdStop() { rd.on = false; clearInterval(rd.timer); clearInterval(rd.fake); if (rd.untap) { rd.untap(); rd.untap = null; } const G = rdGen(); if (G) G.gen(4, 0); renderRadio(); }
async function rdSend(row) {
const post = (b) => fetch(RD_URL, { method: "POST", headers: { apikey: RD_KEY, "Content-Type": "application/json", Prefer: "return=minimal" }, body: JSON.stringify(b) });
try {
let r = await post(row);
if (r.status === 400 && ("parts" in row || "resound" in row)) { const { parts, resound, ...rest } = row; r = await post(rest); } // no `parts` / `resound` column yet: the vote without them
return r.ok || r.status === 409; // 409: this piece voted already from this browser
} catch (_) { return false; }
}
async function rdFlush() {
while (rd.queue.length) { if (!(await rdSend(rd.queue[0]))) return; rd.queue.shift(); }
clearInterval(rd.retry); rd.retry = 0;
}
/* a vote: the optional "what did (not) you like" row (parts: drums 1, bass 2, chords 4, lead 8, arp 16, sound 32), then
one insert and the next piece; Next, or 4 s untouched */
const RD_PARTS = ["rdpDrums", "rdpBass", "rdpChords", "rdpLead", "rdpArp", "rdpSound"];
function rdAsk(vote) {
const G = rdGen(); if (!G || !rd.on || !rd.info) return;
if (rd.vis) rd.vis.event(["down", "up"][+(vote > 0)]);
const [, g, seed, mood, energy, form] = rd.info;
rd.pending = { device: state.fw === "byte" ? "BYTE" : "FM", version: rd.version, genre: rdGenre(g), seed, mood, energy,
form: RD_FORMS[form] || "SONG", listened_s: Math.round((Date.now() - rd.since) / 1000), vote, client: rdClient(), parts: 0, ...(rd.rs != null ? { resound: rd.rs } : {}) };
$("rdpartsq").textContent = t(vote > 0 ? "rdLiked" : "rdDisliked");
$("rdparts").replaceChildren(...RD_PARTS.map((k, i) => { const b = document.createElement("button"); b.type = "button"; b.className = "btn ghost rdchip"; b.textContent = t(k); b.setAttribute("aria-pressed", "false");
b.onclick = () => { rd.pending.parts ^= 1 << i; b.setAttribute("aria-pressed", String(!!(rd.pending.parts & (1 << i)))); rdArm(); }; return b; }));
$("rdask").hidden = false; $("rdvote").hidden = true; rdArm();
}
function rdArm() { clearTimeout(rd.askT); rd.askT = setTimeout(() => rdNext(), 4000); }
async function rdNext() {
const G = rdGen(); clearTimeout(rd.askT);
$("rdask").hidden = true; $("rdvote").hidden = false;
if (rd.pending) {
rd.queue.push(rd.pending); rd.pending = null; rd.votes++;
rdFlush().then(() => { if (rd.queue.length && !rd.retry) rd.retry = setInterval(rdFlush, 30000); });
}
if (rd.vis) rd.vis.event("next");
if (G && rd.on) { await G.gen(1, 0); await rdPoll(); }
}
$("rdsound").onclick = async () => { // another sound: the same notes, every track revoiced by its role
const G = rdGen(); if (!G || !rd.on) return;
if (rd.vis) rd.vis.event("next");
await G.gen(10, Math.floor(Math.random() * 10000)); await rdPoll();
};
$("rdundo").onclick = async () => { const G = rdGen(); if (!G) return; await G.gen(11, 0); await rdPoll(); };
$("rdgo").onclick = () => rdStart(); $("rdstop").onclick = () => rdStop();
$("rdfull").onclick = () => { const st = $("rdstage"); document.fullscreenElement ? document.exitFullscreen() : st.requestFullscreen && st.requestFullscreen().catch(() => {}); };
$("rdup").onclick = () => rdAsk(1); $("rddown").onclick = () => rdAsk(-1); $("rdskip").onclick = () => { rd.pending = null; rdNext(); }; $("rdnext").onclick = () => rdNext();
$("rdgenre").onchange = async () => { const G = rdGen(); if (G) { await G.gen(2, +$("rdgenre").value); await G.gen(1, 0); await rdPoll(); } };
$("rdmood").onchange = async () => { const G = rdGen(); if (G) { await G.gen(3, +$("rdmood").value); await rdPoll(); } };
/* ------------------------------------------------------------------------------------------------- analysis */
/* the exact state (and, from the emulator, how it sounds) in one file to hand over (analysis.js) */
const an = { data: null, busy: false };
const anSay = (x) => { $("anstat").textContent = x; };
function renderAn() {
if (!$("ango")) return;
const L = projLink(), emu = emuApi();
$("anwho").textContent = L ? t("anFrom").replace("%s", L.name) : t("anNoDev");
$("ango").disabled = !L || an.busy; $("anaudio").disabled = !emu; if (!emu) $("anaudio").checked = false;
$("anout").hidden = !an.data;
}
$("ango").onclick = async () => {
const L = projLink(); if (!L || an.busy) return;
an.busy = true; an.data = null; renderAn(); $("anprog").hidden = false;
const e = emuApi();
try {
an.data = await anCapture((c, a, to, m) => L.link.request(c, a, to, m), {
source: L.name, steps: $("ansteps").checked,
audio: $("anaudio").checked && e ? (f) => e.tap(f) : null, secs: 8,
gen: e && e.gen ? async () => { const r = await e.gen(null, 0, true); const i = rdInfo(r && r.info); return i ? { radio: !!i[0], genre: i[1] >= 0 && r.genres ? r.genres[i[1]] : i[1], seed: i[2], mood: i[3], energy: i[4], form: RD_FORMS[i[5]], piece: i[6] } : null; } : null,
}, (x, f) => { anSay(x); $("anbar").style.width = `${Math.round(f * 100)}%`; });
$("anpre").textContent = anText(an.data); anSay(t("anDone"));
} catch (err) { anSay(t("anFail") + (err && err.message ? ` (${err.message})` : "")); }
an.busy = false; $("anprog").hidden = true; renderAn();
};
$("anjson").onclick = () => {
if (!an.data) return;
const a = document.createElement("a"), stamp = an.data.made.replace(/[:.]/g, "-").slice(0, 19);
a.href = URL.createObjectURL(new Blob([JSON.stringify(an.data, null, 1)], { type: "application/json" }));
a.download = `jiant-analysis-${state.fw}-${(an.data.firmware || "").replace(/\s+/g, "_")}-${stamp}.json`; a.click(); setTimeout(() => URL.revokeObjectURL(a.href), 4000);
};
$("ancopy").onclick = async () => { try { await navigator.clipboard.writeText($("anpre").textContent); anSay(t("anCopied")); } catch (_) { anSay(t("anNoCopy")); } };
/* ------------------------------------------------------------------------------------------------ VIS (visuals) */
/* JIANT BYTE's visual generator drawn big (visgen.js): one recipe and drawing, three sources filling the same state:
* JIANT BYTE over USB (WATCH's second byte bit 0: VIS_SONG 98 when the song changes, VIS_TICK 99 25 times a second),
* the emulator (jiantEmu.vis(); JIANT FM's: its generator and its stems), or any MIDI device (Studio reads it) */
const vis = { on: false, src: "", eng: null, live: null, song: null, R: null, knobs: {}, raf: 0, poll: 0, untap: null, midi: null, link: null, rec: 0, lastSong: "" };
const visSay = (x) => { $("visstat").textContent = x; };
function visSong(o) { // { seed, recipe, genre, energy, engines, section, palette?, mix?, deform?, react? }
const key = [o.seed, o.recipe, o.genre, o.energy, o.engines].join(",");
if (key !== vis.lastSong || !vis.R) {
vis.lastSong = key; vis.song = o; vis.cuts = {}; vis.cut = null; vis.R = visRecipe(o.seed >>> 0, o.genre | 0, o.energy | 0, o.engines | 0, ((o.recipe | 0) + vis.rec) & 255);
vis.live = new VisLive(); vis.eng.set(vis.live, vis.R);
if (!vis.knobs.user) { $("vismix").value = Math.round(vis.R.mix * 100); $("visreact").value = Math.round(vis.R.react * 100); }
const C = vis.R.c;
$("visrec").textContent = `#${(o.seed >>> 0).toString(16).toUpperCase()} · ${VI_NAMES[C.content]} / ${VI_NAMES[C.skel[0]]}${C.over[0] !== 255 ? " + " + VI_NAMES[C.over[0]] : ""} · ${C.def[0].filter((d) => d !== 255).map((d) => VD_NAMES[d]).join(" ")} · ${VB_NAMES[C.blend]} · ${VP_NAMES[C.pal]}`;
}
if (o.section != null && vis.live) vis.live.tick({ section: o.section });
}
/* cuts (VISGEN.md "Cuts"): a set of eight recipes per song (recipe bytes + 0..7); a kick moves one on, a snare three,
a new section back to the first; the one drawn j = (pos * (2 sec + 1) + sec) & 7; at most a cut every 150 ms */
function visTick(t) {
if (!vis.live) return;
vis.live.tick(t);
const c = vis.cut || (vis.cut = { pos: 0, at: 0, sec: 0, j: 0 }), now = performance.now();
if (t.section != null && t.section !== c.sec) { c.sec = t.section & 3; c.pos = 0; }
else if (t.hits && now - c.at > 150) { if (t.hits & 18) c.pos += 3; else if (t.hits & 1) c.pos += 1; } // (18: a snare, or bit 4 a timbre change)
const j = (c.pos * (2 * c.sec + 1) + c.sec) & 7;
if (j !== c.j && vis.song) {
c.j = j; c.at = now;
const o = vis.song; vis.cuts = vis.cuts || {};
const key = `${vis.lastSong}:${j}`, R = vis.cuts[key] || (vis.cuts[key] = visRecipe(o.seed >>> 0, o.genre | 0, o.energy | 0, o.engines | 0, ((o.recipe | 0) + vis.rec + j) & 255));
vis.eng.rec = R;
}
}
/* JIANT BYTE over USB */
function visPush(f, link) {
if (!vis.on || link !== vis.link) return;
const a = f.a;
if (f.cmd === 98) visSong({ seed: a[0] | a[1] << 7 | a[2] << 14, recipe: a[3] | a[4] << 7, genre: a[5], energy: a[6], engines: a[7] | a[8] << 7, section: a[9] });
else visTick({ levels: a.slice(0, 6).map((v) => v / 127), hits: a[6], root: a[7], quality: a[8], step: a[9], playing: true });
}
/* the emulator: jiantEmu.vis() when it has it (JIANT BYTE's), else (JIANT FM's) its generator and its stems */
async function visEmu() {
const e = (() => { try { return frames.emu.el.contentWindow.jiantEmu; } catch (_) { return null; } })();
if (!e || !e.on()) { visSay(t("visNoEmu")); return; }
let hasVis = !!e.vis;
if (hasVis) { try { const v = await e.vis(); hasVis = !!(v && typeof v === "object" && "seed" in v); } catch (_) { hasVis = false; } } // (BYTE v1.0: "This engine has no VIS.")
if (!hasVis && state.fw === "byte") visSay(t("visNoneEmu"));
if (hasVis) {
vis.poll = setInterval(async () => { const v = await e.vis().catch(() => null); if (!v) return; visSong(v); visTick({ levels: (v.levels || []).map((x) => x / 127), hits: v.hits, root: v.root, quality: v.quality, step: v.step, section: v.section, playing: !!v.playing }); }, 40);
return;
}
const L = new Levels(); let step = 0, prev = new Float32Array(6);
vis.untap = e.tap && e.tap((m) => {
if (!m.planes) return;
const lv = L.of(m.planes); let hits = 0;
if (lv[0] - prev[0] > .25) hits |= 1; if (lv[2] - prev[2] > .3) hits |= 2; if (lv[3] - prev[3] > .3) hits |= 4;
prev = lv; step = (step + 1) & 63;
visTick({ levels: Array.from(lv), hits, step, playing: true });
});
const gen = async () => { const r = e.gen ? await e.gen(null, 0).catch(() => null) : null, i = r && rdInfo(r.info); visSong({ seed: i ? i[2] : 1, recipe: 0, genre: i && i[1] >= 0 ? i[1] : 27, energy: i ? i[4] : 50, engines: 0x90 }); };
gen(); vis.poll = setInterval(gen, 2000);
}
/* any MIDI device: channel 10 (GM) the drums, low notes the bass, three notes at once a chord, the clock the steps,
CC 1 MIX and CC 74 DEFORM; a recipe from this session (Another recipe for a new one) */
function visMidi(input) {
const st = { lv: new Float32Array(6), hits: 0, root: null, q: 0, held: new Map(), clocks: 0, step: 0, notes: 0, chans: new Set(), t0: Date.now() };
const seed = (Date.now() / 1000 | 0) & 0x1FFFFF;
const tickT = setInterval(() => {
const energy = Math.min(100, 30 + st.notes * 3); st.notes *= .9;
const mask = (st.chans.has(9) ? 0x10 : 0) | (st.chans.size > 2 ? 0x80 : 0) | 0x01;
visSong({ seed, recipe: 0, genre: 27, energy: energy | 0, engines: mask, section: (st.step >> 7) & 3 });
visTick({ levels: Array.from(st.lv), hits: st.hits, root: st.root, quality: st.q, step: st.step & 63, playing: true });
st.hits = 0; for (let i = 0; i < 6; i++) st.lv[i] *= .85;
}, 40);
const on = (e) => {
const [s, d1, d2] = e.data, ty = s & 0xF0, ch = s & 15;
if (s === 0xF8) { if (++st.clocks % 6 === 0) st.step++; return; }
if (s === 0xFA) { st.step = 0; st.clocks = 0; return; }
if (ty === 0xB0) { if (d1 === 1) { $("vismix").value = Math.round(d2 / 1.27); vis.knobs.user = true; } if (d1 === 74) $("visdef").value = Math.round(d2 / 1.27); return; }
if (ty === 0x90 && d2) {
st.notes++; st.chans.add(ch);
if (ch === 9) { st.hits |= d1 === 35 || d1 === 36 ? 1 : d1 === 38 || d1 === 40 || d1 === 39 ? 2 : d1 === 42 || d1 === 44 || d1 === 46 ? 4 : 8; st.lv[0] = Math.max(st.lv[0], d2 / 127); }
else { const slot = 1 + (ch % 5); st.lv[slot] = Math.max(st.lv[slot], d2 / 127); if (d1 < 48) st.lv[1] = Math.max(st.lv[1], d2 / 127); }
st.held.set(d1, Date.now());
const now = [...st.held.entries()].filter(([, at]) => Date.now() - at < 60).map(([n]) => n).sort((a, b) => a - b);
if (now.length >= 3) { const r = now[0] % 12, iv = new Set(now.map((n) => (n - now[0]) % 12)); st.root = r; st.q = iv.has(4) ? (iv.has(8) ? 3 : 0) : iv.has(3) ? (iv.has(6) ? 2 : 1) : iv.has(5) ? 4 : 0; }
} else if (ty === 0x80 || (ty === 0x90 && !d2)) st.held.delete(d1);
};
input.addEventListener("midimessage", on);
vis.midi = () => { clearInterval(tickT); input.removeEventListener("midimessage", on); };
}
async function visSources() {
const sel = $("vissrc"), cur = sel.value, opts = [];
if (state.fw === "byte" && state.dev) opts.push(["usb", t("visSrcUsb").replace("%s", devName(state.dev))]);
opts.push(["emu", t("visSrcEmu")]);
try { const a = await midiAccess(); for (const i of a.inputs.values()) if (!PORT_RE.test(i.name || "") || state.fw !== "byte") opts.push(["midi:" + i.id, "MIDI · " + i.name]); } catch (_) {}
sel.replaceChildren(...opts.map(([v, n]) => { const o = document.createElement("option"); o.value = v; o.textContent = n; return o; }));
if (opts.some(([v]) => v === cur)) sel.value = cur;
}
function visStop() {
vis.on = false; clearInterval(vis.poll); cancelAnimationFrame(vis.raf);
if (vis.untap) { vis.untap(); vis.untap = null; } if (vis.midi) { vis.midi(); vis.midi = null; }
if (vis.link) { vis.link.request(22, [0, 0], 600).catch(() => {}); vis.link = null; }
$("visgo").textContent = t("visStart"); visSay("");
}
async function visStart() {
visStop();
const cv = $("viscv"), W = 960, H = 540; cv.width = W; cv.height = H;
vis.eng = new VisEngine(W, H); vis.R = null; vis.lastSong = ""; vis.on = true; vis.knobs.user = false;
visSong({ seed: 1, recipe: 0, genre: 27, energy: 50, engines: 0 });
const src = $("vissrc").value;
if (src === "usb" && state.dev) {
vis.link = state.dev.link;
try { const a = await vis.link.request(22, [0, 1], 900); if (!(a.length > 1 && a[1] & 1)) { visSay(t("visNone")); vis.link.request(22, [0, 0], 600).catch(() => {}); vis.link = null; } else vis.poll = setInterval(() => vis.link && vis.link.request(CMD.PING, [], 600).catch(() => {}), 1000); } // (BYTE cuts a WATCH 3 s without a request) // (WATCH's second byte 0: this firmware has no VIS)
catch (_) { visSay(t("visOld")); }
}
else if (src === "emu") await visEmu();
else if (src.startsWith("midi:")) { const a = await midiAccess(); const i = a.inputs.get(src.slice(5)); if (i) visMidi(i); }
$("visgo").textContent = t("visStop");
const g = cv.getContext("2d");
const loop = (now) => {
if (!vis.on) return; vis.raf = requestAnimationFrame(loop);
if (state.view !== "vis" && !document.fullscreenElement) return;
const K = { mix: $("vismix").value / 100, def: $("visdef").value / 100, pal: +$("vispal").value, react: $("visreact").value / 100 };
vis.eng.frame(now, K); g.drawImage(vis.eng.out, 0, 0);
};
vis.raf = requestAnimationFrame(loop);
}
$("visgo").onclick = () => (vis.on ? visStop() : visStart());
$("visnew").onclick = () => { vis.rec = (vis.rec + 1) & 255; vis.lastSong = ""; };
$("visfull").onclick = () => { const st = $("visstage"); document.fullscreenElement ? document.exitFullscreen() : st.requestFullscreen && st.requestFullscreen().catch(() => {}); };
for (const id of ["vismix", "visreact"]) $(id).addEventListener("input", () => { vis.knobs.user = true; });
$("vispal").replaceChildren(...VP_NAMES.map((n, i) => { const o = document.createElement("option"); o.value = i; o.textContent = n; return o; }));
/* ------------------------------------------------------------------------------------------- project editor */
/* the whole project (the approved mock-up: SONG SEQ SOUND MOD·MIX GEN): a file (.b1t3 on JIANT BYTE, .jfm on JIANT
* FM) holding the device's objects (BACKUP 65-67, as a full backup) with the project's name and the generator's state;
* sent to the FM-1 or fetched from it (a copy of what was there kept in this browser first); SOUND live: every
* parameter of each track by name (TRACK 27, TRACK_DUMP 29, DESC 5 with that track selected for a moment), set as it
* moves (TRACK_PARAM 31). SONG, SEQ, MOD·MIX and GEN come as the firmware adds what they need */
const pe = { tab: "sound", trk: 0, info: null, tracks: [], params: {}, desc: {}, busy: false, name: "" };
const PE_TABS = [["song", "SONG"], ["seq", "SEQ"], ["sound", "peSound"], ["mod", "MOD · MIX"], ["gen", "GEN"]];
const peSay = (x) => { $("pestat").textContent = x; };
function peExt() { return state.fw === "byte" ? "b1t3" : "jfm"; }
function renderPe() {
peDress();
if (!$("pebody")) return;
const L = projLink();
$("pename").value = pe.name || ""; $("pename").placeholder = tp("peUnnamed");
$("petags").textContent = pe.info ? `${pe.info.version}${pe.gen ? " · " + pe.gen : ""}` : L ? L.name : t("bkNoDev");
for (const id of ["peexport", "pesend", "pefetch"]) $(id).disabled = !L || pe.busy;
$("peexport").textContent = tp("peExport").replace("%s", peExt()); $("peimport").textContent = tp("peImport").replace("%s", peExt());
$("petabs").replaceChildren(...PE_TABS.map(([k, n]) => { const b = document.createElement("button"); b.type = "button"; b.textContent = TEXT[lang][n] ? t(n) : n; b.setAttribute("aria-pressed", String(pe.tab === k)); b.onclick = () => { pe.tab = k; renderPe(); }; return b; }));
const body = $("pebody");
if (pe.tab === "song" && state.fw === "byte") { peSong(body, L); return; }
if (pe.tab === "seq") { peSeq(body, L); return; }
if (pe.tab === "mod") { peMod(body, L); return; }
if (pe.tab === "gen") { peGen(body); return; }
if (pe.tab !== "sound") { body.innerHTML = ""; const p = document.createElement("p"); p.className = "dim"; p.textContent = tp("peSoon_" + pe.tab); body.append(p); return; }
peSound(body, L);
}
function peDress() { document.querySelectorAll('#v-pe [data-t^="pe"]').forEach((e) => { e.textContent = tp(e.dataset.t); }); }
async function peLoad(L) { // the tracks, and each one's parameters by name
const a = await L.link.request(1, [], 900); pe.info = parseInfo(a);
const ia = a, nm = []; let i = 0; while (ia[i]) i++; i++;
pe.pcount = ia[i + 1]; pe.pe0 = ia[i + 4];
const T = await L.link.request(27, [], 900), sel = T[0], n = T[1];
pe.tracks = Array.from({ length: n }, (_, k) => ({ engine: pe.info.engines[T[2 + k * 6]] || "?", preset: T[3 + k * 6] }));
pe.sel = sel;
}
async function peTrack(L, k) {
peSay(tp("peReading"));
pe.busy = true;
try {
const common = pe.desc.common || (pe.desc.common = {});
if (!Object.keys(common).length) for (let id = 0; id < pe.pe0; id++) { try { common[id] = parseDesc(await L.link.request(5, [0, id], 800)); } catch (_) {} }
await L.link.request(27, [k], 900);
const eng = {}; for (let id = pe.pe0; id < pe.pcount; id++) { try { eng[id] = parseDesc(await L.link.request(5, [0, id], 800)); } catch (_) {} }
const D = await L.link.request(29, [k], 900), vals = {};
for (let id = 0; id < pe.pcount; id++) vals[id] = v14(D, 3 + id * 2);
const spec = await peSpecials(L, k);
pe.params[k] = { eng, vals, spec };
} finally { try { await L.link.request(27, [pe.sel], 900); } catch (_) {} pe.busy = false; }
peSay("");
}
/* a track's special ids (INFO caps bit 4; FM 1.4, BYTE v1.1b4): values beside the parameters, no P_* slot. FM: id
P_COUNT + k, DESC 0 id, TRACK_PARAM track id. BYTE: the page id less 0x80, DESC 2 w, TRACK_PARAM 64 + track w.
Firmware without them does not answer: a short timeout, and the first silence ends the probe */
const PE_SPEC = { fm: [0, 1, 2, 3], byte: [0x50, 0x51, 0x52, 0x53, 0x6d, 0x6e, 0x6f] };
const peSpecArgs = (k, id) => (state.fw === "byte" ? [64 + k, id] : [k, id]);
async function peSpecials(L, k) {
if (pe.desc.noSpec) return {};
const ids = state.fw === "byte" ? PE_SPEC.byte : PE_SPEC.fm.map((j) => pe.pcount + j), out = {};
const descs = pe.desc.spec || (pe.desc.spec = {});
for (const id of ids) {
try {
if (!descs[id]) descs[id] = parseDesc(await L.link.request(5, [state.fw === "byte" ? 2 : 0, id], 500));
const a = await L.link.request(31, peSpecArgs(k, id), 500, (r) => r[1] === id);
out[id] = { d: descs[id], v: v14(a, 2) };
} catch (_) { if (!Object.keys(out).length && !Object.keys(descs).length) pe.desc.noSpec = true; break; }
}
return out;
}
function peSound(body, L) {
body.replaceChildren();
const el = (tag, cls, text) => { const e = document.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e; };
if (!L) { body.append(el("p", "dim", tp("peNoDev"))); return; }
if (!pe.tracks.length) { const b = el("button", "btn", tp("peRead")); b.type = "button"; b.onclick = async () => { try { await peLoad(L); await peTrack(L, pe.trk); } catch (e) { peSay(tp("peFail")); } renderPe(); }; body.append(el("p", "dim", tp("peAsk")), b); return; }
const bar = el("div", "petrk");
pe.tracks.forEach((tr, k) => { const b = el("button", "btn" + (k === pe.trk ? "" : " ghost"), `T${k + 1} · ${tr.engine}`); b.type = "button"; b.onclick = async () => { pe.trk = k; if (!pe.params[k]) await peTrack(L, k); renderPe(); }; bar.append(b); });
body.append(bar);
const P = pe.params[pe.trk]; if (!P) { body.append(el("p", "dim", tp("peReading"))); return; }
const knob = (id, d, spec) => {
const v = spec ? P.spec[id].v : P.vals[id], box = el("div", "pek" + (v !== d.def ? " chg" : "")), lab = el("label"), out = el("b"), show = (x) => { out.textContent = d.names && d.names.length ? (d.names[x - d.min] ?? x) : `${x}${d.unit ? " " + d.unit : ""}`; };
lab.append(document.createTextNode(d.label), out); show(v);
let ctl;
if (d.names && d.names.length && d.max - d.min < 40) { ctl = el("select"); d.names.forEach((n, i) => { const o = el("option", null, n); o.value = d.min + i; ctl.append(o); }); ctl.value = v; }
else { ctl = el("input"); ctl.type = "range"; ctl.min = d.min; ctl.max = d.max; ctl.value = v; }
ctl.setAttribute("aria-label", d.label);
let tm = 0;
ctl.addEventListener("input", () => {
const x = +ctl.value; show(x); if (spec) P.spec[id].v = x; else P.vals[id] = x; box.classList.toggle("chg", x !== d.def);
clearTimeout(tm); tm = setTimeout(() => L.link.request(31, [...(spec ? peSpecArgs(pe.trk, id) : [pe.trk, id]), (x + 8192) & 127, (x + 8192) >> 7], 800).catch(() => peSay(tp("peFail"))), 30);
});
box.append(lab, ctl); return box;
};
const group = (title, ids, src) => { const g = el("div", "pegrid"); for (const id of ids) { const d = src[id]; if (d && d.label && d.label !== "-") g.append(knob(id, d)); } if (g.children.length) body.append(el("p", "pegrp", title), g); };
if (state.fw === "byte") { // BYTE: the track's formula (39 LYRIC: read, written live)
const box = el("div"), ta = el("textarea"), send = el("button", "btn", tp("peFormulaSend")), msg = el("span", "dim");
ta.rows = 3; ta.spellcheck = false; ta.maxLength = 255; ta.style.cssText = "width:100%;font:15px/1.4 var(--mono);background:var(--field);color:var(--fg);border:var(--border) solid var(--line);padding:8px";
ta.setAttribute("aria-label", tp("peFormula")); send.type = "button";
if (P.formula == null) { L.link.request(39, [pe.trk], 900, (r) => r[0] === pe.trk).then((a) => { P.formula = String.fromCharCode(...a.slice(2).filter((c) => c)); renderPe(); }).catch(() => { P.formula = ""; }); }
ta.value = P.formula || "";
send.onclick = async () => {
const v = ta.value.replace(/[^ -~]/g, "").slice(0, 255);
try { const a = await L.link.request(39, [pe.trk, ...[...v].map((c) => c.charCodeAt(0)), 0], 1500, (r) => r[0] === pe.trk); P.formula = v; msg.textContent = a[1] === 1 ? tp("peFormulaCut") : tp("peFormulaOk"); }
catch (_) { msg.textContent = tp("peFail"); }
};
ta.addEventListener("keydown", (e) => { if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) send.click(); });
const row = el("div", "emuctl"); row.append(send, msg);
box.append(el("p", "pegrp", tp("peFormula")), ta, row); body.append(box);
}
if (state.fw === "fm" && /MATH/i.test(pe.tracks[pe.trk].engine || "")) peFmFormula(body, L, P, el);
const C = pe.desc.common, only = el("label", "chk"), cb = el("input");
cb.type = "checkbox"; cb.checked = !!pe.onlyChanged; cb.onchange = () => { pe.onlyChanged = cb.checked; renderPe(); };
only.append(cb, document.createTextNode(" " + tp("peOnlyChanged"))); body.append(only);
group(`${pe.tracks[pe.trk].engine}`, Object.keys(P.eng).map(Number), P.eng);
const S = P.spec || {}, sg = (title, ids) => { const g = el("div", "pegrid"); for (const id of ids) if (S[id] && S[id].d.label && (!pe.onlyChanged || S[id].v !== S[id].d.def)) g.append(knob(id, S[id].d, true)); if (g.children.length) body.append(el("p", "pegrp", title), g); };
const sk = Object.keys(S).map(Number);
sg("FX › OTT", sk.filter((id) => state.fw === "byte" ? id >= 0x50 && id <= 0x53 : id >= pe.pcount));
sg("EDIT · NOISE · CRUSH · LIFE", sk.filter((id) => state.fw === "byte" && id >= 0x6d));
group(tp("peTrackParams"), Object.keys(C).map(Number).filter((id) => !pe.onlyChanged || (C[id] && P.vals[id] !== C[id].def)), C);
}
/* ---- JIANT FM's MATH USER (V10.8.75, FORMULA 100): the track's own formula, typed or generated, heard here, sent and
read back; then ALGO USER (-4) and WAVE 5 (INT, a bytebeat) or 6 (FIX, a floatbeat) on the track. Older firmware
does not answer FORMULA: the box says so */
async function peFmFormula(body, L, P, el) {
const box = el("div"), ta = el("textarea"), msg = el("p", "dim"), cv = el("canvas"), row = el("div", "emuctl");
const gen = el("button", "btn ghost", tp("peFmGen")), play = el("button", "btn ghost", tp("peFmPlay")), send = el("button", "btn", tp("peFmSend")), clr = el("button", "btn ghost", tp("peFmClear"));
[gen, play, send, clr].forEach((b) => { b.type = "button"; });
ta.rows = 3; ta.spellcheck = false; ta.maxLength = 400; ta.setAttribute("autocomplete", "off"); ta.setAttribute("autocorrect", "off"); ta.setAttribute("autocapitalize", "off");
ta.style.cssText = "width:100%;font:15px/1.4 var(--mono);background:var(--field);color:var(--fg);border:var(--border) solid var(--line);padding:8px;box-sizing:border-box";
cv.width = 600; cv.height = 90; cv.style.cssText = "width:100%;height:70px;background:var(--panel);border:var(--border) solid var(--line);margin-top:8px";
const fam = el("select"), chaos = el("input"), gopt = el("div", "emuctl");
chaos.type = "range"; chaos.min = 0; chaos.max = 100; chaos.value = pe.fmChaos ?? 40; chaos.setAttribute("aria-label", "CAOS");
fam.setAttribute("aria-label", tp("peFmFamily"));
row.append(gen, play, send, clr);
box.append(el("p", "pegrp", tp("peFmTitle")), gopt, ta, cv, msg, row); body.append(box);
const M = await mathLib(toolUrl("fm", "editor")).catch(() => null);
if (!M) { msg.textContent = tp("peFmNoLib"); [gen, play, send, clr].forEach((b) => { b.disabled = true; }); return; }
const FAM = M.mathGenerate.FAMILIES || null; // (the editor's generator with families and chaos, when published)
if (FAM) {
const L2 = (f) => (f.labels && (f.labels[lang] || f.labels.en)) || f.id;
fam.replaceChildren(...[{ id: "any", labels: { es: "Cualquiera", en: "Any" } }, ...FAM.filter((f) => f.id !== "any")].map((f) => { const o = el("option", null, L2(f)); o.value = f.id; return o; }));
fam.value = pe.fmFamily || "any"; fam.onchange = () => { pe.fmFamily = fam.value; };
chaos.oninput = () => { pe.fmChaos = +chaos.value; cl.textContent = `${tp("peFmChaos")} ${chaos.value}`; };
const cl = el("span", "dim", `${tp("peFmChaos")} ${chaos.value}`);
gopt.append(fam, cl, chaos);
}
const k = pe.trk;
if (P.fmf === undefined) { // what the track holds: FORMULA query (none on older firmware)
try { const a = await L.link.request(100, [k, 0], 900, (r) => r[0] === k); const n = a[2] | 0, code = M.FVM.unpack7(Array.from(a.slice(3))).slice(0, n); P.fmf = n ? (fmTextOf(code) ?? "") : ""; P.fmfOld = false; P.fmfDev = n; }
catch (_) { P.fmf = ""; P.fmfOld = true; }
}
if (P.fmfOld) { msg.textContent = tp("peFmOld"); [send, clr].forEach((b) => { b.disabled = true; }); }
ta.value = P.fmf || "";
let c = null, stop = null;
const check = () => {
const src = ta.value.trim(); P.fmf = ta.value;
const g = cv.getContext("2d"); g.clearRect(0, 0, cv.width, cv.height);
if (!src) { c = null; msg.textContent = P.fmfDev && !P.fmf ? tp("peFmUnknown").replace("%n", P.fmfDev) : P.fmfOld ? tp("peFmOld") : tp("peFmHelp"); send.disabled = true; return; }
c = fmCompile(M, src);
if (!c.ok) { msg.textContent = `${tp("peFmErr")} ${c.error} (${c.pos + 1}): ${src.slice(Math.max(0, c.pos - 10), c.pos)}▸${src.slice(c.pos, c.pos + 10)}`; send.disabled = true; return; }
msg.textContent = `${c.fix ? "FLOAT" : "BYTE"} · ${c.size}/${c.max} B` + (P.fmfOld ? " · " + tp("peFmOld") : ""); send.disabled = P.fmfOld;
const w = fmWave(c, cv.width); g.strokeStyle = getComputedStyle(document.documentElement).getPropertyValue("--accent") || "#a77bff"; g.lineWidth = 2; g.beginPath();
w.forEach((v, x) => { const y = cv.height - v / 255 * cv.height; x ? g.lineTo(x, y) : g.moveTo(x, y); }); g.stroke();
};
ta.addEventListener("input", check); check();
gen.onclick = () => {
const seed = (Math.random() * 1e9) >>> 0;
if (FAM) { const g = M.mathGenerate(seed, { family: fam.value, chaos: +chaos.value }); ta.value = g.src; }
else ta.value = M.mathGenerate(seed);
check();
};
play.onclick = () => { if (stop) { stop(); stop = null; play.textContent = tp("peFmPlay"); return; } if (!c || !c.ok) return; stop = fmPreview(c, 4); play.textContent = tp("peFmStop"); setTimeout(() => { if (stop) { stop = null; play.textContent = tp("peFmPlay"); } }, 4000); };
send.onclick = async () => {
if (!c || !c.ok) return;
try {
const r = await L.link.request(100, [k, 1, ...M.FVM.pack7(c.code)], 1500, (x) => x[0] === k);
const back = M.FVM.unpack7(Array.from(r.slice(3))).slice(0, r[2] | 0);
if (r[1] || back.join() !== c.code.join()) { peSay(tp("peFmRefused")); return; }
fmKeep(c.code, ta.value.trim());
const set = (id, v) => L.link.request(31, [k, id, (v + 8192) & 127, (v + 8192) >> 7], 800);
await set(pe.pe0 + 1, c.fix ? 6 : 5); await set(pe.pe0 + 2, -4);
P.fmfDev = c.size; peSay(tp("peFmSent").replace("%s", `T${k + 1}`));
} catch (_) { peSay(tp("peFail")); }
};
clr.onclick = async () => { try { await L.link.request(100, [k, 2], 900, (x) => x[0] === k); ta.value = ""; P.fmfDev = 0; check(); peSay(tp("peFmCleared")); } catch (_) { peSay(tp("peFail")); } };
}
/* ---- a control for a described parameter (DESC): a slider or a list; set calls back as it moves */
function peCtl(d, v, set) {
const el = (tag, cls, text) => { const e = document.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e; };
const box = el("div", "pek" + (v !== d.def ? " chg" : "")), lab = el("label"), out = el("b");
const show = (x) => { out.textContent = d.names && d.names.length ? (d.names[x - d.min] ?? x) : /^AMT/.test(d.label) ? `${Math.round(x * 100 / 64)} %` : `${x}${d.unit ? " " + d.unit : ""}`; };
lab.append(document.createTextNode(d.label), out); show(v);
let ctl;
if (d.names && d.names.length && d.max - d.min < 64) { ctl = el("select"); d.names.forEach((n, i) => { const o = el("option", null, n); o.value = d.min + i; ctl.append(o); }); ctl.value = v; }
else { ctl = el("input"); ctl.type = "range"; ctl.min = d.min; ctl.max = d.max; ctl.value = v; }
ctl.setAttribute("aria-label", d.label);
let tm = 0; ctl.addEventListener("input", () => { const x = +ctl.value; show(x); box.classList.toggle("chg", x !== d.def); clearTimeout(tm); tm = setTimeout(() => set(x), 30); });
box.append(lab, ctl); return box;
}
/* ---- SEQ: a track's steps as a piano roll (TRACK_STEP track index 2: the whole step, JIANT BYTE 1.6 caps bit 1;
without it the plain step): notes, then velocity, probability and (whole step) micro-timing as bars to click */
async function peSeqRead(L, k) {
const n = (pe.info && pe.info.nstep) || 64, steps = [];
let whole = true;
for (let i = 0; i < n; i++) {
let a = null;
if (whole) try { a = await L.link.request(30, [k, i, 2], 700, (r) => r[0] === k && r[1] === i); } catch (_) { whole = false; }
if (!a) a = await L.link.request(30, [k, i], 700, (r) => r[0] === k && r[1] === i);
steps.push(a); peSay(`${tp("peReading")} ${i + 1}/${n}`);
}
pe.seq = { k, steps, whole: whole && steps[0].length >= 43 }; peSay("");
}
function peSeq(body, L) {
body.replaceChildren();
const el = (tag, cls, text) => { const e = document.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e; };
if (!L) { body.append(el("p", "dim", tp("peNoDev"))); return; }
if (!pe.tracks.length) { body.append(el("p", "dim", tp("peAsk"))); const b = el("button", "btn", tp("peRead")); b.type = "button"; b.onclick = async () => { try { await peLoad(L); } catch (_) { peSay(tp("peFail")); } renderPe(); }; body.append(b); return; }
const bar = el("div", "petrk");
pe.tracks.forEach((tr, k) => { const b = el("button", "btn" + (pe.seq && pe.seq.k === k ? "" : " ghost"), `T${k + 1} · ${tr.engine}`); b.type = "button"; b.onclick = async () => { try { await exclusive(() => peSeqRead(L, k)); } catch (e) { peSay(tp("peFail")); } renderPe(); }; bar.append(b); });
body.append(bar);
const Q = pe.seq; if (!Q) { body.append(el("p", "dim", tp("peSeqPick"))); return; }
const notes = Q.steps.flatMap((a) => a.slice(3, 3 + a[2])), lo = Math.max(0, Math.min(48, ...notes) - 2), hi = Math.min(127, Math.max(lo + 12, ...notes) + 2), N = Q.steps.length;
const NN = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"];
const write = async (i) => {
const a = Q.steps[i], len = Q.whole && !a.slice(27, 43).some((v, j) => j % 2 === 1 && v > 1) ? 43 : 23; // (a legacy LENGTH 255: the 20 bytes left as they are)
try { const r = await L.link.request(30, a.slice(0, len), 900, (x) => x[0] === Q.k && x[1] === i); Q.steps[i] = len === 43 ? r : [...r.slice(0, 23), ...a.slice(23)]; }
catch (_) { peSay(tp("peSeqRefused")); }
};
/* the roll: its own horizontal scroll (the page never widens), the notes' names held at the left, black keys darker,
a line each beat and a stronger one each bar, the bar numbers on top; the lanes under it */
const CW = N > 32 ? 16 : 22, RH = 16, black = (p) => [1, 3, 6, 8, 10].includes(p % 12);
const wrap = el("div", "proll"), grid = el("div", "prgrid");
grid.style.gridTemplateColumns = `46px repeat(${N}, ${CW}px)`;
grid.append(el("div", "prlab prtop", ""));
for (let i = 0; i < N; i++) grid.append(el("div", "prbar" + (i % 16 === 0 ? " b" : ""), i % 16 === 0 ? String(i / 16 + 1) : i % 4 === 0 ? "·" : ""));
const edge = (i) => (i % 16 === 0 ? " bar" : i % 4 === 0 ? " beat" : "");
for (let p = hi; p >= lo; p--) {
grid.append(el("div", "prlab" + (black(p) ? " bk" : "") + (p % 12 === 0 ? " c" : ""), NN[p % 12] + (Math.floor(p / 12) - 1)));
for (let i = 0; i < N; i++) {
const a = Q.steps[i], on = a.slice(3, 3 + a[2]).includes(p), c = el("button", "prc" + (black(p) ? " bk" : "") + edge(i) + (on ? " on" : ""));
c.type = "button"; c.style.height = `${RH}px`;
c.setAttribute("aria-label", `${NN[p % 12]}${Math.floor(p / 12) - 1} · ${i + 1}`); c.setAttribute("aria-pressed", String(on));
c.onclick = async () => {
const ns = a.slice(3, 3 + a[2]);
const next = on ? ns.filter((x) => x !== p) : ns.length < 4 ? [...ns, p] : ns;
a[2] = next.length; for (let j = 0; j < 4; j++) a[3 + j] = next[j] || 0; if (!on) a[7] = 0;
await write(i); renderPe();
};
grid.append(c);
}
}
const lane = (name, get, set, max, web, center) => {
grid.append(el("div", "prlab prlane", name));
for (let i = 0; i < N; i++) {
const a = Q.steps[i], v = get(a), c = el("div", "prl" + edge(i)), f = el("i");
if (center) { const h = Math.abs(v - 32) / 32 * 50; f.style.cssText = `height:${h}%;${v >= 32 ? "bottom:50%" : "top:50%"}`; }
else f.style.height = `${Math.round(v / max * 100)}%`;
if (web) f.className = "web"; c.append(f); c.title = `${name} ${i + 1}: ${center ? v - 32 : v}`;
c.onclick = async (e) => { const r = c.getBoundingClientRect(), x = Math.round((1 - (e.clientY - r.top) / r.height) * max); set(a, Math.max(0, Math.min(max, x))); await write(i); renderPe(); };
grid.append(c);
}
};
lane("VEL", (a) => a[9], (a, x) => { a[9] = x; }, 127);
lane("PROB", (a) => Math.min(100, a[13] ?? 100), (a, x) => { a[13] = x; }, 100);
if (Q.whole) lane("µTIME", (a) => a[23], (a, x) => { a[23] = x; }, 63, true, true);
wrap.append(grid); body.append(wrap, el("p", "dim", tp(Q.whole ? "peSeqHelp" : "peSeqHelpOld")));
}
/* ---- MOD · MIX: the track's matrix (its SRC/DEST/AMT slots, AMT ±200 % where the firmware has it), the six tracks'
levels and mutes (TRACK_MIX 28) and the global effects and master (DUMP, DESC scope 1) */
async function peMod(body, L) {
body.replaceChildren();
const el = (tag, cls, text) => { const e = document.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e; };
if (!L) { body.append(el("p", "dim", tp("peNoDev"))); return; }
if (!pe.tracks.length || !pe.params[pe.trk]) { body.append(el("p", "dim", tp("peAsk"))); const b = el("button", "btn", tp("peRead")); b.type = "button"; b.onclick = async () => { try { await peLoad(L); await peTrack(L, pe.trk); } catch (_) { peSay(tp("peFail")); } renderPe(); }; body.append(b); return; }
const P = pe.params[pe.trk], C = pe.desc.common, k = pe.trk;
body.append(el("p", "pegrp", `${tp("peModMatrix")} · T${k + 1} ${pe.tracks[k].engine}`));
const slots = {}; for (const [id, d] of Object.entries(C)) { const m = /^(SRC|DEST|AMT)(\d)$/.exec(d.label || ""); if (m) (slots[m[2]] = slots[m[2]] || {})[m[1]] = +id; }
const g = el("div", "pegrid");
for (const n of Object.keys(slots).sort()) for (const f of ["SRC", "DEST", "AMT"]) { const id = slots[n][f]; if (id == null) continue; g.append(peCtl(C[id], P.vals[id], (x) => { P.vals[id] = x; L.link.request(31, [k, id, (x + 8192) & 127, (x + 8192) >> 7], 800).catch(() => peSay(tp("peFail"))); })); }
body.append(g);
body.append(el("p", "pegrp", tp("peModMix")));
const mg = el("div", "pegrid");
for (let tk = 0; tk < pe.tracks.length; tk++) {
let mx; try { mx = await L.link.request(28, [tk], 800, (r) => r[0] === tk); } catch (_) { continue; }
const lv = v14(mx, 1), mute = mx[3];
mg.append(peCtl({ label: `T${tk + 1} ${pe.tracks[tk].engine}${mute ? " (MUTE)" : ""}`, min: 0, max: 127, def: 100, unit: "", names: [] }, lv, (x) => L.link.request(28, [tk, (x + 8192) & 127, (x + 8192) >> 7, mute], 800).catch(() => {})));
}
body.append(mg);
body.append(el("p", "pegrp", tp("peModFx")));
if (!pe.globals) {
const G = await L.link.request(4, [], 1500), gd = {};
for (let id = 0; id < pe.info.gcount; id++) { try { const d = parseDesc(await L.link.request(5, [1, id], 800)); if (d.label && d.label !== "-") gd[id] = { d, v: v14(G, 2 + (pe.pcount + id) * 2) }; } catch (_) {} }
pe.globals = gd;
}
const fg = el("div", "pegrid");
for (const [id, { d, v }] of Object.entries(pe.globals)) fg.append(peCtl(d, v, (x) => { pe.globals[id].v = x; L.link.request(3, [1, +id, (x + 8192) & 127, (x + 8192) >> 7], 800).catch(() => peSay(tp("peFail"))); }));
body.append(fg);
}
/* ---- GEN (the emulator's generator: jiantEmu.gen; JIANT BYTE's answers carry its whole state, web_gen_state's 19
ints): what made the piece, a new one, one track or one section again (cmd 5 / 6, a salt in the high bits), back to the
original; the project file keeps the original's state beside what was changed */
async function peGen(body) {
body.replaceChildren();
const el = (tag, cls, text) => { const e = document.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e; };
const e = emuApi();
if (!e || !e.gen) { body.append(el("p", "dim", tp("peGenEmu"))); return; }
const r = await e.gen(null, 0, true).catch(() => null), i = r && rdInfo(r.info);
if (!i) { body.append(el("p", "dim", tp("peGenOld"))); return; }
if (r.genres) pe.genres = r.genres;
if (r.state && !pe.genOrig) pe.genOrig = r.state.slice();
pe.genNow = r.state || null;
const G = pe.genres || [], name = (g) => (g === -1 ? "EXPLORE" : g === -2 ? "RANDOM" : G[g] || String(g));
/* BYTE v1.1b4's 44 ints: [19] the regenerations' count (−1: more than 8), then that many {kind, index, salt}; the
entries past them are leftovers, not compared */
const genUsed = (st) => (st.length > 19 ? st.slice(0, 20 + 3 * Math.max(0, Math.min(8, st[19] < 0 ? 8 : st[19]))) : st);
const changed = pe.genOrig && pe.genNow && (() => { const a = genUsed(pe.genOrig), b = genUsed(pe.genNow); return a.length !== b.length || a.some((v, k) => v !== b[k]); })();
body.append(el("p", "pegrp", tp("peGenNow")), el("p", "", `${name(i[1])} · ${t("rdSeed")} ${i[2]} · MOOD ${i[3] > 0 ? "+" : ""}${i[3]} · ENERGY ${i[4]} · ${RD_FORMS[i[5]] || "?"}`));
const act = async (cmd, arg) => { await e.gen(cmd, arg); renderPe(); };
const row = el("div", "emuctl"), gsel = el("select"), mood = el("input"), nb = el("button", "btn", tp("peGenNew"));
[["-2", "RANDOM"], ["-1", "EXPLORE"], ...G.map((n, k) => [String(k), n])].forEach(([v, n]) => { const o = el("option", null, n); o.value = v; gsel.append(o); }); gsel.value = String(i[1]);
gsel.onchange = () => act(2, +gsel.value);
mood.type = "range"; mood.min = -50; mood.max = 50; mood.value = i[3]; mood.setAttribute("aria-label", "MOOD"); mood.onchange = () => act(3, +mood.value);
nb.type = "button"; nb.onclick = async () => { await e.gen(1, 0); const x = await e.gen(null, 0); pe.genOrig = x && x.state ? x.state.slice() : null; renderPe(); };
row.append(gsel, el("span", "dim", "MOOD"), mood, nb); body.append(row);
const salt = () => (Math.random() * 7 + 1) << 4;
const trk = el("div", "emuctl"); trk.append(el("span", "dim", tp("peGenTrack")));
for (let k = 0; k < 6; k++) { const b = el("button", "btn ghost", `T${k + 1}`); b.type = "button"; b.onclick = () => act(5, k | salt()); trk.append(b); }
const sec = el("div", "emuctl"); sec.append(el("span", "dim", tp("peGenSection")));
for (let k = 0; k < 4; k++) { const b = el("button", "btn ghost", "ABCD"[k]); b.type = "button"; b.onclick = () => act(6, k | salt()); sec.append(b); }
body.append(trk, sec, el("p", "dim", t(r.state ? "peGenHelp" : "peGenHelpNoState")));
if (pe.genOrig) {
const o = el("div", "emuctl"), back = el("button", "btn ghost", tp("peGenBack"));
back.type = "button"; back.disabled = !changed;
back.onclick = async () => { if (!confirm(tp("peGenBackConfirm"))) return; const x = await e.gen(null, 0, false, { state: pe.genOrig, regen: true }); peSay(x && x.rc ? tp("peFail") : tp("peGenBackDone")); renderPe(); };
o.append(el("span", changed ? "" : "dim", t(changed ? "peGenChanged" : "peGenSame")), back); body.append(o);
}
}
/* ---- SONG (JIANT BYTE): the song index (backup object 10, v4, 2344 B: rows[n] at 8 + 36n, scene[n][r] at 296 + 128n
+ 8r, tsrc at 1320 + 64n + 4r, tvar at 1832 + 64n + 4r) read and written whole; the playing song's sections over the
six tracks: bars, mutes, each cell's pattern and variation */
const TVAR = ["", "MUTE", "THIN", "FILL", "HALF", "REV", "SHIFT", "OCT+", "OCT-", "VAR1", "VAR2", "VAR3", "VAR4"];
async function peGetObj(req, id) {
const man = bkManifestAll(await req([65, []], { timeout: 8000, retries: 1 })), o = man.find((m) => m.id === id);
if (!o || !o.size) return new Uint8Array(0);
const bytes = new Uint8Array(o.size);
for (let off = 0; off < o.size; off += 256) {
const size = Math.min(256, o.size - off), match = (r) => r[0] === id && (() => { try { return bkR32(r, 2) === off; } catch (_) { return false; } })();
const a = await req([66, [id, ...bkU32(off), size & 127, size >>> 7]], { timeout: 2500, retries: 2, match });
if (a[1]) throw new Error(`get ${a[1]}`);
bytes.set(bkUnpack(a.slice(9), size), off);
}
return bytes;
}
function peSong(body, L) {
body.replaceChildren();
const el = (tag, cls, text) => { const e = document.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e; };
if (!L) { body.append(el("p", "dim", tp("peNoDev"))); return; }
const S = pe.song;
if (!S) {
const b = el("button", "btn", tp("peSongRead")); b.type = "button";
b.onclick = async () => { peSay(tp("peReading")); try { await exclusive(async () => { const d = await peGetObj(bkRequest(L.link), 10); pe.song = { d, orig: d.slice() }; }); peSay(""); } catch (e) { peSay(tp("peFail") + ` (${e.message})`); } renderPe(); };
body.append(el("p", "dim", tp("peSongAsk")), b); return;
}
const d = S.d, dv = new DataView(d.buffer);
if (d.length < 2344 || dv.getUint32(0, true) !== 0x474E4F53 || d[4] !== 4) { body.append(el("p", "dim", tp("peSongOld"))); return; }
const n = S.n ?? d[5], rb = 8 + 36 * n, count = d[rb];
const sel = el("select"); for (let k = 0; k < 6; k++) { const o = el("option", null, `${tp("peSongN")} ${k + 1}`); o.value = k; sel.append(o); } sel.value = n; sel.onchange = () => { S.n = +sel.value; renderPe(); };
const top = el("div", "emuctl"); top.append(sel); body.append(top);
if (!count) { body.append(el("p", "dim", tp("peSongEmpty"))); }
const bars = Array.from({ length: count }, (_, r) => d[rb + 4 + r * 2 + 1] || 1), total = bars.reduce((a, b) => a + b, 0) || 1;
const wrap = el("div", "sc"), grid = el("div", "grid");
grid.style.cssText = `display:grid;gap:2px;grid-template-columns:70px ${bars.map((b) => `minmax(${Math.max(36, b * 6)}px,${b}fr)`).join(" ")};min-width:${Math.max(560, total * 8)}px`;
grid.append(el("div", "lab", tp("peSongSec")));
bars.forEach((b, r) => {
const h = el("div", "sec"), slot = d[rb + 4 + r * 2], inp = el("input");
h.style.cssText = `background:${["#ffb21a", "#a77bff", "#3fe0e6", "#ff38b4"][slot & 3]};color:#000;padding:4px 6px;font:11px var(--display);display:flex;gap:4px;align-items:center`;
inp.type = "number"; inp.min = 1; inp.max = 64; inp.value = b; inp.style.cssText = "width:3.2em;font:12px var(--mono);background:rgba(0,0,0,.25);border:0;color:#000";
inp.setAttribute("aria-label", `bars ${r + 1}`);
inp.onchange = () => { d[rb + 4 + r * 2 + 1] = Math.max(1, Math.min(64, +inp.value | 0)); S.dirty = true; renderPe(); };
h.append(document.createTextNode("ABCD"[slot & 3]), inp); grid.append(h);
});
const TC = ["#ff38b4", "#3fe0e6", "#6bff9e", "#a77bff", "#ffb21a", "#ff7a1a"];
for (let tk = 0; tk < 6; tk++) {
grid.append(Object.assign(el("div", "lab", `T${tk + 1}`), { style: `color:${TC[tk]}` }));
for (let r = 0; r < count; r++) {
const so = 296 + 128 * n + 8 * r, muted = tk < 4 ? (d[so + 1] >> tk) & 1 : (d[so] >> (tk - 3)) & 1;
const src = (dv.getUint32(1320 + 64 * n + 4 * r, true) >>> (tk * 3)) & 7, va = (dv.getUint32(1832 + 64 * n + 4 * r, true) >>> (tk * 4)) & 15;
const c = el("button", "cell", `${src ? "ABCD"[src - 1] : ""} ${TVAR[va] || ""}`.trim());
c.type = "button"; c.title = tp("peSongCell");
c.style.cssText = `height:30px;border:0;font:10px var(--mono);color:#000;background:${muted ? "#1b1628" : TC[tk] + "cc"};cursor:pointer;min-height:0;padding:0 3px`;
c.onclick = () => { // a mute on or off (the row then holds a scene)
if (tk < 4) d[so + 1] ^= 1 << tk; else d[so] ^= 1 << (tk - 3);
d[so] |= 1; S.dirty = true; renderPe();
};
c.oncontextmenu = (e) => { // the cell's variation, one on
e.preventDefault(); const o = 1832 + 64 * n + 4 * r, v = dv.getUint32(o, true), cur = (v >>> (tk * 4)) & 15;
dv.setUint32(o, ((v & ~(15 << (tk * 4))) | (((cur + 1) % 13) << (tk * 4))) >>> 0, true); S.dirty = true; renderPe();
};
grid.append(c);
}
}
wrap.append(grid); body.append(wrap, el("p", "dim", tp("peSongHelp")));
const acts = el("div", "emuctl"), apply = el("button", "btn", tp("peSongApply")), undo = el("button", "btn ghost", tp("peSongUndo"));
apply.type = undo.type = "button"; apply.disabled = !S.dirty;
apply.onclick = async () => {
if (!confirm(tp("peSongConfirm"))) return;
try { await exclusive(async () => { await cvPut(bkRequest(L.link), 10, d); }); S.orig = d.slice(); S.dirty = false; peSay(tp("peSongDone")); }
catch (e) { peSay(tp("peFail") + ` (${e.message})`); }
renderPe();
};
undo.onclick = () => { S.d = S.orig.slice(); S.dirty = false; renderPe(); };
acts.append(apply, undo); body.append(acts);
}
/* the project file: the device's objects (a full backup) with the name and the generator */
async function peCapture(L) {
return captureBackup(bkRequest(L.link), L.name, (d, n) => { $("peprog").hidden = false; $("pebar").style.width = `${Math.round(d / n * 100)}%`; peSay(t("bkWorking") + `${Math.round(d / n * 100)} %`); });
}
$("peexport").onclick = async () => {
const L = projLink(); if (!L) return;
await exclusive(async () => {
try {
const backup = await peCapture(L), e = emuApi(), g = e && e.gen ? await e.gen(null, 0).catch(() => null) : null, gi = g && rdInfo(g.info);
const file = { format: state.fw === "byte" ? "jiant-b1t3" : "jiant-fm-project", version: 1, firmware: L.name, created: new Date().toISOString(), name: $("pename").value || tp("peUnnamed"),
gen: gi ? { genre: gi[1], seed: gi[2], mood: gi[3], energy: gi[4], form: gi[5], state: g.state || null, original: pe.genOrig || null } : null, web: {}, backup };
download(new Blob([JSON.stringify(file)], { type: "application/json" }), `${(file.name || "project").replace(/[^\w-]+/g, "_")}.${peExt()}`);
peSay(tp("peSaved"));
} catch (err) { peSay(tp("peFail") + ` (${err.message})`); }
$("peprog").hidden = true;
});
};
$("peimport").onclick = () => $("pefile").click();
$("pefile").onchange = async () => {
const f = $("pefile").files[0]; $("pefile").value = ""; if (!f) return;
try { const file = JSON.parse(await f.text()); if (!file.backup) throw new Error("format"); readBackup(file.backup); pe.file = file; pe.name = file.name || ""; peSay(tp("peLoaded").replace("%s", file.name || f.name)); }
catch (_) { peSay(tp("peBadFile")); }
renderPe();
};
$("pesend").onclick = async () => {
const L = projLink(); if (!L || !pe.file) { peSay(tp("peNoFile")); return; }
if (!confirm(tp("peSendConfirm").replace("%s", pe.file.name || "").replace("%n", L.name))) return;
await exclusive(async () => {
try {
const before = await peCapture(L), now = new Date();
await bkDb.put({ name: `${tp("peBefore")} · ${L.name} · ${stamp(now)}`, created: now.toISOString(), fw: state.fw, firmware: L.name, summary: bkSummary(before), file: before });
await restoreBackup(bkRequest(L.link), pe.file.backup, (d, n) => { $("pebar").style.width = `${Math.round(d / n * 100)}%`; peSay(tp("peSending") + `${Math.round(d / n * 100)} %`); });
pe.params = {}; pe.tracks = []; peSay(tp("peSent"));
} catch (err) { peSay(tp("peFail") + ` (${err.message})`); }
$("peprog").hidden = true; renderPe();
});
};
$("pefetch").onclick = async () => { pe.params = {}; pe.tracks = []; pe.desc = {}; const L = projLink(); if (!L) return; try { await peLoad(L); await peTrack(L, pe.trk); } catch (_) { peSay(tp("peFail")); } renderPe(); };
$("pename").addEventListener("input", () => { pe.name = $("pename").value; });
/* ------------------------------------------------------------------------------------------- how it works */
/* each firmware's ideas (learn-fm.json, learn-byte.json): sectors (the concept, the engines, the sequencers, the
* effects, the modulators, the generators, the songs), each item its statement, how it works, where it is on the
* FM-1 and its animation (learn.js) */
const lr = { data: {}, fw: null, sec: -1, item: 0, player: null, want: null }; // sec -1: the index
/* #learn/<sector>/<item>: a page of its own (kept for when the data is there) */
function lrRoute(hash) {
const m = /^#learn\/([\w-]+)(?:\/([\w-]+))?/.exec(hash || "");
if (!m) return false;
lr.want = { sec: m[1], item: m[2] || null };
return true;
}
const lrSecs = () => ((lr.data[state.fw] || {}).sectors || []).filter((x) => x.items && x.items.length);
function lrOpen(si, ii) {
lr.sec = si; lr.item = ii;
const S = lrSecs()[si];
const h = si < 0 || !S ? "#learn" : `#learn/${S.id}/${S.items[ii].id}`;
if (location.hash !== h) history.replaceState(null, "", location.pathname + location.search + h);
renderLearn();
}
async function lrLoad(fw) {
if (!lr.data[fw]) {
try { const r = await fetch(`learn-${fw}.json`, { cache: "no-cache" }); lr.data[fw] = r.ok ? await r.json() : { sectors: [] }; }
catch (_) { lr.data[fw] = { sectors: [] }; }
}
return lr.data[fw];
}
const L = (o) => (o && typeof o === "object" ? o[lang] || o.es || o.en || "" : o || "");
async function renderLearn() {
const fw = state.fw, D = await lrLoad(fw);
if (lr.fw !== fw) { lr.fw = fw; lr.sec = -1; lr.item = 0; }
if (lr.want && lr.want.sec === "live") { lr.sec = -2; lr.want = null; }
if (lr.want) { // a link to a page: its sector and item
const secs0 = (D.sectors || []).filter((x) => x.items && x.items.length), si = secs0.findIndex((x) => x.id === lr.want.sec);
if (si >= 0) { lr.sec = si; lr.item = Math.max(0, secs0[si].items.findIndex((x) => x.id === lr.want.item)); }
lr.want = null;
}
$("lrtitle").textContent = t(fw === "byte" ? "lrTitleByte" : "lrTitleFm");
$("lrintro").textContent = L(D.intro) || t("lrNone");
const secs = (D.sectors || []).filter((x) => x.items && x.items.length);
const chip = (label, n, on, f) => { const b = document.createElement("button"); b.type = "button"; b.setAttribute("aria-pressed", String(on)); b.append(label);
if (n != null) { const c = document.createElement("b"); c.textContent = n; b.append(c); } b.addEventListener("click", f); return b; };
$("lrsec").replaceChildren(chip(t("lvChip"), null, lr.sec === -2, () => { lr.sec = -2; history.replaceState(null, "", location.pathname + location.search + "#learn/live"); renderLearn(); }),
chip(t("lrIndex"), secs.reduce((a, x) => a + x.items.length, 0), lr.sec === -1, () => lrOpen(-1, 0)),
...secs.map((x, i) => chip(L(x.name), x.items.length, i === lr.sec, () => lrOpen(i, 0))));
const S = secs[lr.sec];
$("lrlive").hidden = lr.sec !== -2;
$("lrcard").hidden = !S; $("lritems").hidden = !S; $("lrindex").hidden = !!S || !secs.length || lr.sec === -2;
if (lr.sec === -2) { $("lrlead").textContent = t("lvLead"); await liveGloss(fw); renderLive(); return; }
if (!S) { $("lrlead").textContent = secs.length ? t("lrIndexLead") : ""; lrIndex(secs); return; }
$("lrlead").textContent = L(S.lead);
$("lritems").replaceChildren(...S.items.map((it, i) => {
const b = document.createElement("button"); b.type = "button"; b.setAttribute("role", "option"); b.setAttribute("aria-selected", String(i === lr.item));
const n = document.createElement("b"), g = document.createElement("span"); n.textContent = it.name; g.textContent = L(it.tag); b.append(n, g);
b.addEventListener("click", () => { lrOpen(lr.sec, i); if (matchMedia("(max-width: 820px)").matches) $("lrcard").scrollIntoView({ behavior: "smooth", block: "start" }); });
return b;
}));
const it = S.items[Math.min(lr.item, S.items.length - 1)];
$("lrname").textContent = it.name; $("lrtag").textContent = L(it.tag);
$("lrstate").textContent = L(it.statement);
const how = (it.how && (it.how[lang] || it.how.es || it.how.en)) || [];
$("lrhow").replaceChildren(...how.map((h) => Object.assign(document.createElement("li"), { textContent: h })));
const where = L(it.where); $("lrwhere").hidden = !where; $("lrwhere").textContent = where ? t("lrWhere") + where + (it.since ? ` · ${t("lrSince").replace("%s", it.since)}` : "") : "";
$("lrpos").textContent = `${lr.item + 1} / ${S.items.length}`;
lr.player = lr.player || new Player($("lrcanvas"));
lr.player.show(it.anim && it.anim.kind, it.anim && it.anim.params);
const sel = $("lritems").children[lr.item]; if (sel && sel.scrollIntoView) sel.scrollIntoView({ block: "nearest", inline: "nearest" });
}
function lrStep(d) {
const secs = lrSecs(), S = secs[lr.sec];
if (!S) return;
let si = lr.sec, ii = lr.item + d;
if (ii < 0) { si = (si - 1 + secs.length) % secs.length; ii = secs[si].items.length - 1; }
else if (ii >= S.items.length) { si = (si + 1) % secs.length; ii = 0; }
lrOpen(si, ii);
}
/* the index: every sector, every item a tile (its animation still, its name and line); a tap opens its page */
let lrIndexFor = "";
function lrIndex(secs) {
const key = state.fw + lang + document.documentElement.dataset.skin;
if (lrIndexFor === key) return;
lrIndexFor = key;
const el = (tag, cls, text) => { const e = document.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e; };
const tiles = [];
$("lrindex").replaceChildren(...secs.map((S, si) => {
const sec = el("section", "lrisec");
sec.append(el("h2", null, L(S.name)), el("p", "dim", L(S.lead)));
const grid = el("div", "lrigrid");
grid.append(...S.items.map((it, ii) => {
const b = el("button", "lritile"); b.type = "button";
const cv = el("canvas"); tiles.push([cv, it.anim || {}]);
b.append(cv, el("b", null, it.name), el("span", null, L(it.tag)));
b.addEventListener("click", () => { lrOpen(si, ii); window.scrollTo({ top: $("v-learn").offsetTop - 10, behavior: "smooth" }); });
return b;
}));
sec.append(grid);
return sec;
}));
// their stills, drawn once each as they come into sight
const io = "IntersectionObserver" in window ? new IntersectionObserver((es) => es.forEach((e) => { if (e.isIntersecting) { io.unobserve(e.target); e.target._draw(); } })) : null;
for (const [cv, a] of tiles) {
cv._draw = () => lrStill(cv, a.kind, a.params);
io ? io.observe(cv) : cv._draw();
}
}
function lrStill(cv, kind, params) {
const r = cv.getBoundingClientRect(), d = Math.min(2, devicePixelRatio || 1), W = Math.max(1, r.width), H = Math.max(1, r.height);
cv.width = Math.round(W * d); cv.height = Math.round(H * d);
const c = cv.getContext("2d"), VW = 520, k = W / VW; // (drawn at the card's size, then scaled down: the same picture)
c.setTransform(d * k, 0, 0, d * k, 0, 0);
const s = getComputedStyle(cv), v = (n, f) => s.getPropertyValue(n).trim() || f;
try { anim(kind)(c, 1.3, VW, H / k, params || {}, { fg: v("--fg", "#efe6c8"), dim: v("--dim", "#a39bb6"), acc: v("--accent", "#ff7a1a"), a2: v("--accent-2", "#ff9a8a"), bg: v("--bg", "#000") }); } catch (_) {}
}
$("lrprev").addEventListener("click", () => lrStep(-1));
$("lrback").addEventListener("click", () => lrOpen(-1, 0));
$("lrnext").addEventListener("click", () => lrStep(1));
document.addEventListener("keydown", (e) => { if (state.view !== "learn" || /input|select|textarea/i.test(e.target.tagName)) return; if (e.key === "ArrowRight") lrStep(1); else if (e.key === "ArrowLeft") lrStep(-1); });
/* ---------------------------------------------------------------------------------------- the quick tour */
/* The first time Studio opens (and from the ? button): each part in turn, lit while the rest dims, a card telling what
* it is, what it does and how to use it; Next / Back / Skip, the arrow keys, Esc. Remembered in this browser */
const TOUR = [
{ k: "Welcome" },
{ k: "Fw", sel: "#fwseg" },
{ k: "Target", sel: "#targetseg" },
{ k: "Dev", sel: "#devchip", view: "home" },
{ k: "Find", sel: "#find", view: "home" },
...["install", "editor", "screen", "emu", "rec", "proj", "pe", "wt", "radio", "an", "vis", "learn", "docs", "rescue", "ports"].map((v) => ({ k: "V_" + v, sel: `nav.views [data-go="${v}"]`, view: v })),
{ k: "Lang", sel: "#lang" },
{ k: "End", sel: "#tourbtn" },
];
const tour = { i: 0, on: false };
const TOUR_KEY = "jiant.studio.tour.1";
function tourShow(i) {
const dir = i < tour.i ? -1 : 1;
tour.i = Math.max(0, Math.min(TOUR.length - 1, i));
const hid = (x) => x.sel && (() => { const el = document.querySelector(x.sel); return el && el.hidden; })();
while (hid(TOUR[tour.i]) && tour.i + dir >= 0 && tour.i + dir < TOUR.length) tour.i += dir; // a part this firmware has not (Wavetables on FM)
const st = TOUR[tour.i];
if (st.view && state.view !== st.view) go(st.view);
$("tour").hidden = false; tour.on = true;
$("tourstep").textContent = `${tour.i + 1} / ${TOUR.length}`;
$("tourtitle").textContent = t("tour" + st.k + "T"); $("tourwhat").textContent = t("tour" + st.k);
const how = TEXT[lang]["tour" + st.k + "H"]; $("tourhow").textContent = how || ""; $("tourhow").hidden = !how;
$("tourprev").disabled = tour.i === 0; $("tournext").textContent = t(tour.i === TOUR.length - 1 ? "tourDone" : "tourNext");
$("tourdots").replaceChildren(...TOUR.map((_, k) => Object.assign(document.createElement("i"), { className: k === tour.i ? "on" : "" })));
const el = st.sel && document.querySelector(st.sel);
const hole = $("tourhole"), card = $("tourcard");
if (el && el.getClientRects().length) {
el.scrollIntoView({ block: "nearest", inline: "center" });
requestAnimationFrame(() => {
const r = el.getBoundingClientRect(), pad = 6;
Object.assign(hole.style, { left: `${r.left - pad}px`, top: `${r.top - pad}px`, width: `${r.width + 2 * pad}px`, height: `${r.height + 2 * pad}px`, display: "" });
const cw = card.offsetWidth, ch = card.offsetHeight, below = r.bottom + 14 + ch < innerHeight;
card.style.top = `${below ? r.bottom + 14 : Math.max(12, r.top - 14 - ch)}px`;
card.style.left = `${Math.max(12, Math.min(innerWidth - cw - 12, r.left + r.width / 2 - cw / 2))}px`;
});
} else {
hole.style.display = "none";
requestAnimationFrame(() => { card.style.top = `${Math.max(12, (innerHeight - card.offsetHeight) / 2)}px`; card.style.left = `${(innerWidth - card.offsetWidth) / 2}px`; });
}
$("tournext").focus();
}
function tourEnd() { $("tour").hidden = true; tour.on = false; try { localStorage.setItem(TOUR_KEY, "1"); } catch (_) {} }
$("tournext").addEventListener("click", () => (tour.i === TOUR.length - 1 ? tourEnd() : tourShow(tour.i + 1)));
$("tourprev").addEventListener("click", () => tourShow(tour.i - 1));
$("tourskip").addEventListener("click", tourEnd);
$("tourbtn").addEventListener("click", () => tourShow(0));
document.addEventListener("keydown", (e) => {
if (!tour.on) return;
if (e.key === "Escape") tourEnd(); else if (e.key === "ArrowRight") $("tournext").click(); else if (e.key === "ArrowLeft") tourShow(tour.i - 1); else return;
e.preventDefault(); e.stopPropagation();
}, true);
addEventListener("resize", () => { if (tour.on) tourShow(tour.i); });
/* -------------------------------------------------------------------------------- how it works: live */
/* Following the FM-1 (or the emulator): WATCH 31 and a PING a second keep its pushes coming; a knob turned (CHANGED)
* is named by its DESC (cached per engine) and explained by the firmware's glossary (live-fm.json, live-byte.json:
* the label's meaning, by engine where it differs), with the guide's related element (its animation); RELOAD (engine,
* preset, track), STEP_CHANGED, TRACK_CHANGED, TRANSPORT, PUNCH and MUTATE are told too, and UI (43, page and buttons)
* when the firmware sends it. The last ones in a list */
/* the UI push's numbers (EDITOR_PROTOCOL.md: push 43, the same in JIANT FM and JIANT BYTE) */
const UI_SECTIONS = ["HOME", "EDIT", "SEQ", "FX", "GLO", "ENV", "LFO", "SCL", "ARP", "SAVE"];
const UI_LAYERS = ["", "FX", "GLO", "SCL", "EDIT", "SEQ", "REC", "SAVE", "MACRO"];
const UI_BUTTONS = ["FX", "SCL", "ENV", "LFO", "EDIT", "GLO", "HOME", "SAVE", "ARP", "SEQ", "PLAY", "REC", "OCT−", "OCT+"];
const live = { on: false, link: null, timer: 0, desc: new Map(), engine: -1, engines: [], track: 0, gloss: {}, log: [], last: null, player: null, shown: null, status: "" };
const v14 = (a, i) => (a[i] | (a[i + 1] << 7)) - 8192;
function readStr(a, i) { let s = ""; while (i < a.length && a[i]) s += String.fromCharCode(a[i++]); return [s, i + 1]; }
function parseDesc(a) {
const o = { scope: a[0], id: a[1], fmt: a[2], min: v14(a, 3), max: v14(a, 5), def: v14(a, 7) };
let i = 9; [o.label, i] = readStr(a, i); [o.unit, i] = readStr(a, i);
o.names = [];
if (o.fmt === 8) for (let k = 0; k <= o.max - o.min && k < 32 && i < a.length; k++) { let n; [n, i] = readStr(a, i); o.names.push(n); }
return o;
}
async function liveGloss(fw) {
if (!live.gloss[fw]) { try { const r = await fetch(`live-${fw}.json`, { cache: "no-cache" }); live.gloss[fw] = r.ok ? await r.json() : {}; } catch (_) { live.gloss[fw] = {}; } }
return live.gloss[fw];
}
function liveSource() {
if (state.target === "fm1") return state.dev ? { link: state.dev.link, name: devName(state.dev), engines: state.dev.engines } : null;
const L = projLink(); return L ? { link: L.link, name: t("bkTarget"), engines: null } : null;
}
async function liveStart() {
const S = liveSource();
if (!S) { live.status = t("lvNoDev"); renderLive(); return; }
live.on = true; live.link = S.link; live.desc.clear(); live.status = t("lvWaiting").replace("%s", S.name); renderLive();
try {
const info = parseInfo(await S.link.request(CMD.INFO, [], 900));
live.engines = S.engines || info.engines; live.pe0 = info.pe0;
await S.link.request(22, [63], 900); // WATCH: every push this firmware has (bit 5: UI, 43)
const d = await S.link.request(4, [], 1500); // DUMP: the selected track's engine
live.engine = d[0];
} catch (_) {}
await lrLoad(state.fw); await liveGloss(state.fw);
clearInterval(live.timer);
let tick = 0; // (a PING a second; WATCH again every 5 s: another tool's WATCH 0 ends it)
live.timer = setInterval(() => { if (!live.on || state.busy) return; live.link.request(++tick % 5 ? CMD.PING : 22, tick % 5 ? [] : [63], 600).catch(() => {}); }, 1000);
renderLive();
}
function liveStop() {
live.on = false; clearInterval(live.timer);
try { if (live.link) live.link.request(22, [0], 600).catch(() => {}); } catch (_) {}
live.status = ""; renderLive();
}
const engName = (e) => { const n = live.engines && live.engines[e]; return n && n !== "-" ? n : ""; };
/* a push, as it comes in (from Link.receive) */
async function livePush(f, link) {
if (!live.on || link !== live.link) return;
const a = f.a;
if (f.cmd === 23 || f.cmd === 32) { // a parameter: this track's (CHANGED) or another's (TRACK_CHANGED)
const other = f.cmd === 32, scope = other ? 0 : a[0], id = a[1], v = v14(a, 2);
const key = `${scope}:${id}:${scope ? "" : live.engine}`;
let d = live.desc.get(key);
if (!d) {
try { d = parseDesc(await link.request(5, [scope, id], 800)); live.desc.set(key, d); }
catch (_) { d = { label: `#${id}`, min: 0, max: 127, names: [], unit: "" }; }
}
liveShow({ kind: "param", d, v, scope, track: other ? a[0] : null });
} else if (f.cmd === 24) { // RELOAD: engine, preset (, the selected track)
live.engine = a[0]; if (a.length > 2) live.track = a[2];
for (const k of [...live.desc.keys()]) if (k.startsWith("0:")) live.desc.delete(k);
liveShow({ kind: "reload", engine: a[0], preset: a[1], track: a[2] });
} else if (f.cmd === 26) liveShow({ kind: "step", index: a[0] });
else if (f.cmd === 40) liveShow({ kind: "transport", playing: a[0], beat: a[1], bar: a[2] | (a[3] << 7) }, true);
else if (f.cmd === 41) liveShow({ kind: "punch", bits: a[0] | a[1] << 7 | a[2] << 14 | a[3] << 21 });
else if (f.cmd === 42) liveShow({ kind: "mutate", track: a[0] });
else if (f.cmd === 43) { // UI (when the firmware sends it): section, page, layer, button, knobs
let i = 1, page; const knobs = [];
[page, i] = readStr(a, i);
const layer = a[i], button = a[i + 1]; i += 2;
for (let k = 0; k < 4 && i < a.length; k++) { let s1; [s1, i] = readStr(a, i); knobs.push(s1); }
// (a button's press or release: told as such; a page or layer change: the page)
const pressed = button != null && button !== 127 ? { b: button & 63, up: !!(button & 64) } : null;
const changed = !live.ui || live.ui.page !== page || live.ui.section !== a[0] || live.ui.layer !== layer;
live.ui = { section: a[0], page, layer, knobs };
if (changed) liveShow({ kind: "ui", section: a[0], page, layer, knobs });
else if (pressed && !pressed.up) liveShow({ kind: "button", button: pressed.b, page });
}
}
/* the guide's element whose id or name matches a word (an engine, FILTER, DELAY…) */
function lrFind(word, sector) {
if (!word) return null;
const w = String(word).toLowerCase(), D = lr.data[state.fw];
if (!D) return null;
const secs = (D.sectors || []).filter((x) => !sector || x.id === sector), all = [];
for (const sec of secs) for (const it of sec.items) all.push([sec, it]);
const hit = (f) => { const r = all.find(([, it]) => f(it)); return r ? `${r[0].id}/${r[1].id}` : null; };
return hit((it) => it.id === w) // an id first, in every sector (slicer: FX's, not audio in's)
|| hit((it) => it.name.toLowerCase() === w)
|| hit((it) => it.id.startsWith(w + "-")) // DRUM: drum-x
|| hit((it) => it.name.toLowerCase().split(/[^a-z0-9-]+/).includes(w));
}
function lrItem(path) {
const [sid, iid] = String(path).split("/"), D = lr.data[state.fw];
const sec = D && (D.sectors || []).find((x) => x.id === sid);
return sec && sec.items.find((i) => i.id === iid);
}
/* what an event says: a title, a line, the value, its explanation (what, how) and the guide's element to show */
function liveExplain(e) {
const G = live.gloss[state.fw] || {}, eng = engName(live.engine), L2 = (o) => (o ? o[lang] || o.es || o.en : null);
if (e.kind === "param") {
const d = e.d, engParam = e.scope === 0 && e.track == null && (state.fw !== "fm" || !live.pe0 || d.id >= live.pe0); // FM: an engine's own knob (INFO's pe0) (a common one with the same label keeps the general text)
/* a label the device uses on more than one page (REV, DLY: SENDS and FX > GATE): "PAGE/LABEL" in labels first, the
page as the UI push (43) named it last */
const pg = live.ui && live.ui.page, E = engParam && G.engines && G.engines[eng];
const g = (pg && E && E[`${pg}/${d.label}`]) || (pg && G.labels && G.labels[`${pg}/${d.label}`]) || (E && E[d.label]) || (G.labels && G.labels[d.label]) || null; // the page's own text first (an engine's page, then any page), then the engine's, then the general one
const span = d.max - d.min || 1, frac = Math.max(0, Math.min(1, (e.v - d.min) / span));
const val = d.names && d.names.length ? d.names[e.v - d.min] || e.v : `${e.v}${d.unit ? " " + d.unit : ""}`;
const where = e.track != null ? `${t("lvTrack")} ${e.track + 1}` : e.scope ? t("lvGlobal") : `${t("lvTrack")} ${live.track + 1}${eng ? " · " + eng : ""}`;
const gx = g ? L2(g) : null;
let learn = g && g.learn ? (lrFind(g.learn) || null) : null;
if (!learn) learn = lrFind(d.label) || lrFind(eng, "engines") || lrFind(eng);
return { title: d.label, line: where, value: String(val), frac, what: gx ? gx.what : t("lvUnknown"), how: gx ? gx.how : "", learn };
}
if (e.kind === "reload") { const en = engName(e.engine); return { title: en || t("lvSound"), line: `${t("lvTrack")} ${(e.track ?? live.track) + 1} · ${t("lvPreset")} ${e.preset + 1}`, what: t("lvReload"), how: "", learn: lrFind(en, "engines") || lrFind(en) }; }
if (e.kind === "step") return { title: `${t("lvStep")} ${e.index + 1}`, line: `${t("lvTrack")} ${live.track + 1}`, what: t("lvStepWhat"), how: "", learn: lrFind("seq") || lrFind("step") };
if (e.kind === "transport") return { title: e.playing ? "PLAY" : "STOP", line: e.playing ? `${t("lvBar")} ${e.bar + 1} · ${e.beat + 1}` : "", what: t(e.playing ? "lvPlay" : "lvStop"), how: "", learn: lrFind("song") };
if (e.kind === "punch") return { title: "FX PUNCH-IN", line: e.bits ? t("lvPunchOn") : t("lvPunchOff"), what: t("lvPunch"), how: "", learn: lrFind("punch") };
if (e.kind === "mutate") return { title: "MUTATE", line: `${t("lvTrack")} ${e.track + 1}`, what: t("lvMutate"), how: "", learn: lrFind("mutate") };
if (e.kind === "ui") {
const sec = UI_SECTIONS[e.section] || "", lay = e.layer ? UI_LAYERS[e.layer] || "" : "";
const knobs = (e.knobs || []).map((k, i) => (k ? `K${i + 1} ${k}` : "")).filter(Boolean).join(" · ");
return { title: e.page || sec || "—", line: [sec !== e.page ? sec : "", lay ? `${t("lvLayer")} ${lay}` : "", knobs].filter(Boolean).join(" · "),
what: lay ? t("lvLayerWhat").replace("%s", lay) : t("lvPage"), how: "", learn: lrFind(e.page) || lrFind(lay) || lrFind(sec) };
}
if (e.kind === "button") {
const n = UI_BUTTONS[e.button] || "?";
return { title: n, line: `${t("lvPressed")} · ${e.page || ""}`, what: t("lvButton").replace("%s", n), how: "", learn: lrFind(n) };
}
return { title: "?", line: "", what: "", how: "" };
}
function liveShow(e, quiet) {
const x = liveExplain(e);
if (!(quiet && live.last && live.last.kind === e.kind)) {
const same = live.log[0] && live.log[0].title === x.title && live.log[0].line === x.line;
if (same) live.log[0] = x; else { live.log.unshift(x); if (live.log.length > 12) live.log.length = 12; }
}
live.last = { kind: e.kind, x }; live.status = "";
renderLive();
}
function renderLive() {
if (!$("lrlive") || state.view !== "learn" || lr.sec !== -2) return;
$("lvgo").textContent = t(live.on ? "lvStopBtn" : "lvStartBtn");
const here = live.on && live.ui ? ` ${t("lvNow")} ${[UI_SECTIONS[live.ui.section], live.ui.page].filter((x, i, A) => x && A.indexOf(x) === i).join(" › ")}${live.ui.layer ? ` (${t("lvLayer")} ${UI_LAYERS[live.ui.layer] || ""})` : ""}` : "";
$("lvstat").textContent = (live.status || (live.on ? t("lvTouch") : t("lvOff"))) + here;
const x = live.last && live.last.x;
$("lvcard").hidden = !x;
if (x) {
$("lvtitle").textContent = x.title; $("lvline").textContent = x.line || "";
$("lvval").hidden = x.value == null; $("lvvaltext").textContent = x.value ?? ""; $("lvbar").style.width = `${Math.round((x.frac ?? 0) * 100)}%`;
$("lvwhat").textContent = x.what || ""; $("lvhow").textContent = x.how || ""; $("lvhow").hidden = !x.how;
const it = x.learn && lrItem(x.learn);
$("lvmore").hidden = !it; $("lvstage").hidden = !it;
if (it) {
$("lvmore").textContent = `${t("lvMore")} ${it.name} →`; $("lvmore").href = `#learn/${x.learn}`;
live.player = live.player || new Player($("lvcanvas"));
if (live.shown !== x.learn) { live.shown = x.learn; live.player.show(it.anim && it.anim.kind, it.anim && it.anim.params); }
}
}
$("lvlog").replaceChildren(...live.log.map((l) => {
const li = document.createElement("li"), b = document.createElement("b");
b.textContent = l.title; li.append(b, ` ${l.line || ""}${l.value != null ? " · " + l.value : ""}`);
return li;
}));
}
$("lvgo").addEventListener("click", () => (live.on ? liveStop() : liveStart()));
/* ------------------------------------------------------------------------------------------------- rescue */
/* FM-1 Rescue (rescue/, android/rescue): an RP2040 wired to the FM-1's USB-C puts it in the JieLi ROM's boot mode
* and writes the firmware area again. Here: the tutorial, the board's wiring drawn, and its .uf2 made in the browser
* (rescue/builder.js: the board's base firmware + the chosen package + JieLi's loader, each checked) */
const RS_STEPS = {
es: { flash: ["Mantené apretado <b>BOOT</b> en la placa y conectala a la computadora. Aparece una unidad <code>RPI-RP2</code>.",
"Arrastrá <code>fm1-rescue.uf2</code> a esa unidad. Se cierra sola cuando termina.",
"Desconectá la placa de la computadora."],
go: ["Con el FM-1 <b>apagado</b>, conectá los tres cables a la placa (como en el paso 2) y el USB-C al FM-1.",
"Conectá la placa a la computadora o a un cargador USB. El LED parpadea en <b>amarillo</b>: espera.",
"<b>Encendé el FM-1.</b> El LED pasa a azul mientras trabaja: entre 1 y 3 minutos. No desconectes nada.",
"<b>Verde fijo</b> = listo y verificado. Si parpadea en rojo: apagá el FM-1, reconectá la placa y volvé a encenderlo."] },
en: { flash: ["Hold <b>BOOT</b> on the board and plug it into the computer. An <code>RPI-RP2</code> drive appears.",
"Drag <code>fm1-rescue.uf2</code> onto that drive. It closes by itself when done.",
"Unplug the board from the computer."],
go: ["With the FM-1 <b>off</b>, connect the three wires to the board (as in step 2) and the USB-C to the FM-1.",
"Plug the board into the computer or a USB charger. The LED blinks <b>yellow</b>: waiting.",
"<b>Switch the FM-1 on.</b> The LED turns blue while it works: 1 to 3 minutes. Do not unplug anything.",
"<b>Steady green</b> = done and verified. Blinking red: switch the FM-1 off, re-plug the board, switch it on again."] },
};
const RS_LEDS = { // [colour, second colour, blink, es, en]
list: [["#e5c100", "", "blink", ["Amarillo, parpadea", "Esperando: encendé el FM-1 (tiene que estar apagado antes)."], ["Yellow, blinking", "Waiting: switch the FM-1 on (it must be off before)."]],
["#e5c100", "", "", ["Amarillo, fijo", "El FM-1 respondió: entrando en modo de arranque."], ["Yellow, steady", "The FM-1 answered: entering boot mode."]],
["#2f6fe0", "", "blink", ["Azul, parpadea", "Leyendo y escribiendo. No desconectes nada."], ["Blue, blinking", "Reading and writing. Do not unplug anything."]],
["#2e8b57", "", "", ["Verde, fijo", "Terminado y verificado."], ["Green, steady", "Done and verified."]],
["#e0443a", "", "fast", ["Rojo, parpadea rápido", "Error: apagá el FM-1, reconectá la placa y encendelo. Si sigue: revisá los cables (probá cambiar verde y blanco) y la batería."], ["Red, fast blinking", "Error: switch the FM-1 off, re-plug the board, switch it on. If it stays: check the wires (try swapping green and white) and the battery."]],
["#9b4dca", "", "", ["Violeta, fijo", "El FM-1 está encendido con un firmware que no acepta el modo de arranque: apagalo, reconectá la placa y encendelo."], ["Purple, steady", "The FM-1 runs a firmware that refuses boot mode: switch it off, re-plug the board, switch it on."]],
["#e0443a", "#2f6fe0", "alt", ["Rojo y azul, alternando", "El .uf2 está dañado: crealo otra vez."], ["Red and blue, alternating", "The .uf2 is damaged: make it again."]]],
};
/* a board and its three wires to the FM-1's USB-C plug, drawn (SVG): the pads named as printed on the board */
const RS_BOARDS = {
zero: { name: "RP2040-Zero", pads: ["0", "1", "GND"], text: "rsWireZero" },
xiao: { name: "XIAO RP2040", pads: ["D6", "D7", "GND"], text: "rsWireXiao" },
pico: { name: "Raspberry Pi Pico", pads: ["GP0 · 1", "GP1 · 2", "GND · 3"], text: "rsWirePico" },
};
function rsWiring(b) {
const B = RS_BOARDS[b], W = [["#3fbf5f", "D+"], ["#f2f0ea", "D−"], ["#111", "GND"]];
const pad = (i) => 104 + i * 46;
let g = `<svg viewBox="0 0 560 260" role="img" aria-label="${B.name}: ${B.pads.join(", ")}" font-family="IBM Plex Mono, monospace">`;
g += `<rect x="20" y="40" width="200" height="180" rx="14" fill="#16131f" stroke="currentColor" stroke-opacity=".35"/>`;
g += `<rect x="6" y="110" width="28" height="40" rx="6" fill="#2a2633" stroke="currentColor" stroke-opacity=".35"/><text x="20" y="100" font-size="11" text-anchor="middle" fill="currentColor" opacity=".6">USB</text>`;
g += `<text x="120" y="68" font-size="15" text-anchor="middle" fill="currentColor">${B.name}</text>`;
g += `<rect x="60" y="86" width="40" height="40" rx="5" fill="#2a2633"/><text x="80" y="111" font-size="10" text-anchor="middle" fill="currentColor" opacity=".6">RP2040</text>`;
B.pads.forEach((n, i) => {
g += `<circle cx="200" cy="${pad(i)}" r="9" fill="#c9a74a" stroke="#000" stroke-opacity=".4"/>`;
g += `<text x="186" y="${pad(i) + 4}" font-size="12" text-anchor="end" fill="currentColor">${n}</text>`;
const d = `M200 ${pad(i)} C 300 ${pad(i)}, 330 ${100 + i * 30}, 420 ${100 + i * 30}`;
g += `<path d="${d}" fill="none" stroke="currentColor" stroke-opacity=".45" stroke-width="9" stroke-linecap="round"/>`; // (an edge: black shows on dark)
g += `<path d="${d}" fill="none" stroke="${W[i][0]}" stroke-width="6" stroke-linecap="round"/>`;
g += `<text x="300" y="${(pad(i) + 100 + i * 30) / 2 - 8}" font-size="11" fill="currentColor" opacity=".8">${W[i][1]}</text>`;
});
g += `<path d="M420 190 C 395 190, 380 205, 350 215" fill="none" stroke="#d13a3a" stroke-width="6" stroke-linecap="round" stroke-dasharray="2 9"/>`;
g += `<text x="356" y="238" font-size="11" fill="currentColor" opacity=".7">5 V ✕</text>`;
g += `<rect x="420" y="80" width="60" height="124" rx="10" fill="#2a2633" stroke="currentColor" stroke-opacity=".35"/>`;
g += `<rect x="480" y="122" width="40" height="40" rx="10" fill="#3a3544" stroke="currentColor" stroke-opacity=".5"/>`;
g += `<text x="450" y="70" font-size="12" text-anchor="middle" fill="currentColor">USB-C</text><text x="500" y="186" font-size="12" text-anchor="middle" fill="currentColor">FM-1</text>`;
return g + "</svg>";
}
const rs = { board: "zero", fw: null, fwName: "", loader: null, lib: null, src: "fm", busy: false };
const rsLib = () => rs.lib || (rs.lib = import("./rescue/builder.js"));
function rsSay(id, text, cls = "") { const e = $(id); e.textContent = text; e.className = "rsst" + (cls ? " " + cls : ""); }
async function rsLoader() {
if (rs.loader) return rs.loader;
const L = await rsLib();
rsSay("rsldst", t("rsLdGet"));
try {
const r = await fetch(L.LOADER_URL);
if (!r.ok) throw new Error("HTTP " + r.status);
rs.loader = await L.checkLoader(new Uint8Array(await r.arrayBuffer()));
rsSay("rsldst", t("rsLdOk"), "ok");
} catch (e) { rsSay("rsldst", t("rsLdBad").replace("%s", e.message), "err"); }
return rs.loader;
}
async function rsUse(bytes, name) {
const L = await rsLib();
try { const v = await L.checkPackage(bytes); rs.fw = bytes; rs.fwName = `${name} · ${v.official ? "V15" : v.identity}`; rsSay("rsfwst", t("rsFwOk").replace("%s", rs.fwName), "ok"); }
catch (e) { rs.fw = null; rsSay("rsfwst", t("rsFwBad").replace("%s", e.message), "err"); }
rsRender();
}
/* the published package of a firmware: its site's firmware/versions.json, the first (the installer's) */
async function rsPublished(fw) {
const name = fw === "byte" ? "JIANT BYTE" : "JIANT FM", base = `${TOOLS[fw].base}firmware/`;
rs.fw = null; rsSay("rsfwst", t("rsFwGet").replace("%s", name)); rsRender();
try {
const v = await (await fetch(base + "versions.json", { cache: "no-cache" })).json();
const e = v.find((x) => !x.status || x.status === "public") || v[0];
const r = await fetch(base + e.file);
if (!r.ok) throw new Error("HTTP " + r.status);
await rsUse(new Uint8Array(await r.arrayBuffer()), `${name} ${e.version}`);
} catch (e) { rsSay("rsfwst", t("rsFwBad").replace("%s", e.message), "err"); }
}
async function rsMake() {
if (!rs.fw) { rsSay("rsmakest", t("rsNeedFw"), "err"); return; }
rs.busy = true; rsRender();
try {
const L = await rsLib(), loader = await rsLoader();
if (!loader) throw new Error(t("rsLdBad").replace("%s", "—"));
const base = new Uint8Array(await (await fetch(`rescue/base/fm1-rescue-base-${rs.board}.uf2`)).arrayBuffer());
const { uf2 } = await L.buildRescueUf2({ baseUf2: base, fwsc: rs.fw, loader });
download(new Blob([uf2], { type: "application/octet-stream" }), "fm1-rescue.uf2");
rs.made = uf2.length;
rsSay("rsmakest", t("rsMade").replace("%s", `${RS_BOARDS[rs.board].name}, ${rs.fwName}`).replace("%n", Math.round(uf2.length / 1024)), "ok");
} catch (e) { rsSay("rsmakest", t("rsFwBad").replace("%s", e.message), "err"); }
rs.busy = false; rsRender();
}
let rsStarted = false;
function rsRender() {
if (!$("v-rescue")) return;
document.querySelectorAll("#rsboard [data-board]").forEach((b) => b.setAttribute("aria-pressed", String(b.dataset.board === rs.board)));
document.querySelectorAll("#rsfw [data-fwsrc]").forEach((b) => b.setAttribute("aria-pressed", String(b.dataset.fwsrc === rs.src)));
$("rswire").innerHTML = rsWiring(rs.board);
$("rswiretext").textContent = t(RS_BOARDS[rs.board].text);
const S = RS_STEPS[lang] || RS_STEPS.en;
$("rsflash").innerHTML = S.flash.map((x) => `<li>${x}</li>`).join("");
$("rsgo").innerHTML = S.go.map((x) => `<li>${x}</li>`).join("");
$("rsleds").replaceChildren(...RS_LEDS.list.map(([c, c2, k, es, en]) => {
const r = document.createElement("div"), i = document.createElement("i"), a = document.createElement("b"), d = document.createElement("span");
r.className = "led"; i.className = k; i.style.setProperty("--c", c); if (c2) i.style.setProperty("--c2", c2);
const [x, y] = lang === "es" ? es : en; a.textContent = x; d.textContent = y; r.append(i, a, d); return r;
}));
$("rsmake").disabled = rs.busy || !rs.fw;
const done = { board: true, fw: !!rs.fw, make: !!rs.made };
document.querySelectorAll("#rsteps .rstep").forEach((li) => li.classList.toggle("done", !!done[li.dataset.k]));
if (!rsStarted && state.view === "rescue") { rsStarted = true; rsPublished(rs.src === "byte" ? "byte" : "fm"); rsLoader(); }
}
$("rsboard").addEventListener("click", (e) => { const b = e.target.closest("[data-board]"); if (b) { rs.board = b.dataset.board; rsRender(); } });
$("rsfw").addEventListener("click", (e) => {
const b = e.target.closest("[data-fwsrc]"); if (!b) return;
rs.src = b.dataset.fwsrc;
if (rs.src === "file") $("rsfile").click(); else rsPublished(rs.src);
rsRender();
});
$("rsfile").addEventListener("change", async () => { const f = $("rsfile").files[0]; $("rsfile").value = ""; if (f) rsUse(new Uint8Array(await f.arrayBuffer()), f.name); });
$("rsmake").addEventListener("click", rsMake);
/* ------------------------------------------------------------------------------------------------ manuals */
/* each firmware's manuals on its own site (same origin): the interactive manual (here, in a frame, or a tab), the full
* manual in HTML (tools/gen_manual_html.py), the two cheat sheets (picture and PDF) and, for JIANT FM, what's new, the
* map and the other devices' manuals. What a site does not have yet (a HEAD that fails) says "on its way" */
const DOCS = {
fm: { inter: "manual/", full: { es: "docs/guide/manual.es.html", en: "docs/guide/manual.html" },
ctl: "docs/cheatsheet-controls", snd: "docs/cheatsheet-sound",
extra: [["docNew", "docNewText", { es: "docs/guide/whats-new-v10.8.21.es.html", en: "docs/guide/whats-new-v10.8.21.html" }, null],
["docMap", "docMapText", { es: "docs/navigation-map.es.png", en: "docs/navigation-map.png" }, "docs/navigation-map.png"],
["docPorts", "docPortsText", { es: "docs/guide/smk37.html", en: "docs/guide/smk37.html" }, "studio/img/smk37.webp"]] },
byte: { inter: "manual/", full: { es: "docs/guide/manual.es.html" }, ctl: "docs/cheatsheet-byte-controls", snd: "docs/cheatsheet-byte-sound", extra: [] },
};
const docHas = new Map(); // url -> Promise<bool>
const has = (url) => {
if (MOCK) return Promise.resolve(true);
// (a GET let go once its answer starts: any server answers it, a HEAD not always)
if (!docHas.has(url)) { const c = new AbortController();
docHas.set(url, fetch(url, { cache: "no-cache", signal: c.signal }).then((r) => { c.abort(); return r.ok; }, () => false)); }
return docHas.get(url);
};
function renderDocs() {
const fw = state.fw, D = DOCS[fw], base = TOOLS[fw].base, name = fw === "byte" ? "JIANT BYTE" : "JIANT FM";
$("docstitle").textContent = name;
$("docslead").textContent = t(fw === "byte" ? "docsLeadByte" : "docsLeadFm");
const el = (tag, cls, text) => { const e = document.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e; };
const link = (text, href, go) => { const a = el("a", "btn" + (go ? "" : " ghost"), text); a.href = href; a.target = "_blank"; a.rel = "noopener"; return a; };
// a card: its picture (an image that opens large, or a word), title, text, its links once the site has them
const card = (o) => {
const c = el("article", "card doc" + (o.wide ? " wide" : ""));
const pic = el("div", "pic" + (o.img ? "" : " glyph"));
if (o.img) {
const b = el("button"); b.type = "button"; const im = new Image(); im.loading = "lazy"; im.alt = o.title; b.append(im);
b.addEventListener("click", () => openShot({ name: "", shots: [[o.big || o.img, ""]] , title: o.title }, 0));
pic.append(b);
has(o.img).then((ok) => { if (ok) im.src = o.img; else { pic.className = "pic glyph"; pic.replaceChildren(name); } });
} else pic.textContent = o.glyph || name;
const links = el("div", "links");
c.append(pic, el("h2", null, o.title), el("p", null, o.text), links);
has(o.check).then((ok) => links.replaceChildren(...(ok ? o.links() : [el("span", "soon", t("docSoon"))])));
return c;
};
const full = D.full[lang] || D.full.es || D.full.en;
const cards = [
card({ wide: true, title: t("docInter"), text: t(fw === "byte" ? "docInterTextByte" : "docInterText"), glyph: `${name} · ${t("docInter")}`,
img: fw === "fm" ? "img/manual-fm.webp" : null, check: base + D.inter, links: () => {
const here = el("button", "btn", t("docOpenHere")); here.type = "button";
here.addEventListener("click", () => openManual(base + D.inter, `${name} · ${t("docInter")}`));
return [here, link(t("docNewTab"), base + D.inter)];
} }),
card({ title: t("docFull"), text: t("docFullText"), glyph: name, check: base + full,
links: () => Object.entries(D.full).map(([l, h], i) => link(Object.keys(D.full).length > 1 ? (l === "es" ? "Español" : "English") : t("docNewTab"), base + h, l === lang || (i === 0 && !D.full[lang]))) }),
...[["docCtl", "docCtlText", D.ctl], ["docSnd", "docSndText", D.snd]].map(([k, tx, f]) =>
card({ title: t(k), text: t(tx), img: base + f + ".png", check: base + f + ".png",
links: () => { const v = el("button", "btn", t("docView")); v.type = "button";
v.addEventListener("click", () => openShot({ name: "", shots: [[base + f + ".png", ""]], title: t(k) }, 0));
return [v, link(t("docPdf"), base + f + ".pdf"), link(t("docPng"), base + f + ".png")]; } })),
...D.extra.map(([k, tx, hrefs, img]) => card({ title: t(k), text: t(tx), img: img && base + img, glyph: t(k), check: base + (hrefs[lang] || hrefs.en),
links: () => [link(t("docNewTab"), base + (hrefs[lang] || hrefs.en), true)] })),
];
$("doclist").replaceChildren(...cards);
}
/* the interactive manual inside Studio, in its frame under the cards */
function openManual(url, title) {
const f = $("f-manual");
$("mantry").hidden = false; $("mantrytitle").textContent = title; $("mannew").href = url;
if (f.src !== new URL(url, location.href).href) f.src = url;
$("mantry").scrollIntoView({ behavior: "smooth", block: "start" });
}
$("manclose").addEventListener("click", () => { $("mantry").hidden = true; $("f-manual").src = "about:blank"; });
/* ------------------------------------------------------------------------------------------- the whole page */
/* the connection line under the bar: what Studio is talking to, and the next thing to do */
/* the emulator's version: the pinned one, or one the installer offers, each its own page from the same commit
(the FM session's emu-v: index.json [{ version, sha7, public, ok }], /emu-v/<sha7>/) */
async function emuVersions() {
const sel = $("emuver"); if (!sel) return;
if (sel.dataset.fw === state.fw) return; sel.dataset.fw = state.fw;
let list = null; try { const r = await fetch(`${TOOLS[state.fw].base}emu-v/index.json`, { cache: "no-cache" }); if (r.ok) list = (await r.json()).filter((v) => v.ok); } catch (_) {}
let beta = false; try { const r = await fetch(`${TOOLS[state.fw].base}${BETA_PATH[state.fw]}index.html`, { cache: "no-cache" }); beta = r.ok; } catch (_) {} // (a firmware's beta emulator beside the public one)
list = Array.isArray(list) ? list : [];
$("emuverbox").hidden = !list.length && !beta;
const o = (v, txt) => { const e = document.createElement("option"); e.value = v; e.textContent = txt; return e; };
sel.replaceChildren(o("", t("emuVerPinned")), ...(beta ? [o("beta", t("emuVerBeta"))] : []), ...list.map((v) => o(v.sha7, v.version + (v.public ? ` · ${t("emuVerPublic")}` : ""))));
sel.value = state.emuVer || "";
}
$("emuver").onchange = () => {
if (!confirm(t("emuVerConfirm"))) { $("emuver").value = state.emuVer || ""; return; }
state.emuVer = $("emuver").value; frames.emu.el.removeAttribute("src"); frames.emu.fw = null; loadFrame("emu");
};
function renderConn() {
const d = state.dev, emu = state.target === "emu", on = emuOn();
const dot = $("conndot"), acts = [];
if (emu) { dot.className = "dot" + (on ? " ok" : ""); $("conntext").textContent = t(on ? "cEmuOn" : "cEmuOff"); if (!on) acts.push(["cOpenEmu", () => go("emu")]); acts.push(["cUseFm1", () => setTarget("fm1")]); }
else if (state.busy) { dot.className = "dot warn"; $("conntext").textContent = t("cBusy"); }
else if (state.looking) { dot.className = "dot warn"; $("conntext").textContent = t("cLooking"); }
else if (d) { dot.className = "dot ok"; $("conntext").textContent = t("cFm1").replace("%s", devName(d)); }
else { dot.className = "dot"; $("conntext").textContent = t("cNone"); acts.push(["cFind", () => $("find").click()], ["cUseEmu", () => setTarget("emu")]); }
$("connacts").replaceChildren(...acts.map(([k, f]) => { const b = document.createElement("button"); b.type = "button"; b.textContent = t(k); b.onclick = f; return b; }));
}
document.addEventListener("click", (e) => { const p = e.target.closest("[data-path]"); if (p) { e.preventDefault(); setTarget("fm1"); $("step1").scrollIntoView({ behavior: "smooth", block: "center" }); $("find").focus({ preventScroll: true }); } });
/* (videos) the presentation of the firmware picked, in the page's language when there is one, on the home page */
const HOME_VIDEOS = { fm: { en: "video/jiant-fm-en.mp4" }, byte: { en: `${SITE}JIANT-BYTE/docs/video/jiant-byte-en.mp4` } }; // (BYTE's from its own site)
function homeVideo() {
const set = HOME_VIDEOS[state.fw] || {}, src = set[lang] || set.en || set.es, fig = $("homevideo"), v = $("hvid");
fig.hidden = !src; $("hvidcap").textContent = t("vidCap");
if (!src || v.dataset.src === src) return;
v.dataset.src = src; v.src = src; v.poster = src.replace(/\.mp4$/, ".jpg");
v.replaceChildren(); const tr = document.createElement("track");
tr.kind = "subtitles"; tr.src = src.replace(/\.mp4$/, ".vtt"); tr.srclang = src.match(/-(\w\w)\.mp4$/)[1]; tr.label = tr.srclang.toUpperCase(); v.append(tr);
}
function render() {
const d = state.dev, fwName = state.fw === "byte" ? "BYTE" : "FM";
$("brandfw").textContent = fwName; $("herofw").textContent = fwName;
$("herolead").textContent = t(state.fw === "byte" ? "leadByte" : "leadFm");
homeVideo();
$("sitelink").href = TOOLS[state.fw].base; $("sitelink").textContent = t("siteLink").replace("%s", state.fw === "byte" ? "JIANT BYTE" : "JIANT FM");
document.querySelectorAll("[data-fw]").forEach((b) => b.setAttribute("aria-pressed", String(b.dataset.fw === state.fw)));
document.querySelectorAll("[data-install]").forEach((b) => b.setAttribute("aria-pressed", String(b.dataset.install === state.fw)));
document.querySelectorAll("[data-target]").forEach((b) => b.setAttribute("aria-pressed", String(b.dataset.target === state.target)));
document.querySelectorAll("nav.views button").forEach((b) => b.setAttribute("aria-current", b.dataset.go === state.view ? "page" : "false"));
if (window.__spReady) renderSpaces();
renderConn(); if (state.view === "emu") emuVersions();
// the device chip
const dot = $("devdot");
dot.className = "dot" + (state.busy ? " warn" : d ? " ok" : "");
$("devtext").textContent = state.busy ? t("devBusy") : state.looking ? t("devLooking") :
d ? devName(d) : t("devNone");
$("find").disabled = state.looking || state.busy; $("forget").hidden = !d;
$("findres").textContent = state.found;
$("step1").classList.toggle("now", !d); $("step3").classList.toggle("now", !!d);
// install
$("insttitle").textContent = t(state.fw === "byte" ? "instTitleByte" : "instTitleFm");
// editor
$("edtitle").textContent = state.fw === "byte" ? "JIANT BYTE" : "JIANT FM";
$("edtarget").textContent = t("edTarget") + t(state.target === "emu" ? "tEmu" : "tFm1");
$("ednote").hidden = state.target !== "emu"; $("ednote").textContent = t("edEmuNote");
// emulator
$("emutitle").textContent = state.fw === "byte" ? "JIANT BYTE" : "JIANT FM";
// screen
$("scrgo").textContent = t(scr.on ? "scrStop" : "scrStart");
const noMirror = state.target === "fm1" && d && d.screen === false;
$("scrgo").disabled = state.busy || (!scr.on && state.target === "fm1" && (!d || noMirror));
$("scrfull").disabled = noMirror;
$("scrwait").hidden = scr.on && scr.got;
$("scrwait").textContent = scr.on ? t("scrWaiting") : noMirror ? t("scrNoFw").replace("%s", devName(d)) :
t(state.target === "emu" ? "scrWaitEmu" : "scrWaitFm1");
$("scrhelp").textContent = t(state.target === "emu" ? "scrHelpEmu" : "scrHelpFm1");
$("scr").setAttribute("aria-label", t("scrTitle"));
if (!scr.on && state.view !== "screen") $("scrstat").textContent = "";
$("scrfull").hidden = !(document.fullscreenEnabled || document.webkitFullscreenEnabled);
// record
$("recgo").textContent = t(rec.on ? "recStop" : "recStart");
$("recgo").classList.toggle("recording", rec.on);
$("recgo").disabled = state.busy;
$("recmon").textContent = t(rec.mon ? "recMonitorStop" : "recMonitor");
$("recmon").disabled = rec.on || state.busy;
$("recplay").textContent = t(daw.playing ? "recPlayStop" : "recPlay");
$("recplay").disabled = rec.on || !daw.planes;
$("recprof").disabled = rec.mon || /^emu/.test($("recdev").value);
if (state.view === "rec") profileHelp();
if (state.view === "rec" && !rec.on) { renderAudioInputs(); renderMidiInputs(); }
renderTakes();
if (state.view === "ports") renderPorts();
if (state.view === "ed") renderEd();
if (state.view === "proj") { renderProj(); if (!pj.list && !pj.busy && projLink()) pjRead(); renderPj(); $("cvcard").hidden = state.fw !== "fm"; }
if (state.view === "wt") renderWtDev();
if (state.view === "an") renderAn();
if (state.view === "pe") renderPe();
if (state.view === "vis") { visSources(); if (!vis.on) $("visgo").textContent = t("visStart"); }
if (state.view === "radio" || rd.vis) renderRadio();
document.querySelector('nav.views [data-go="wt"]').hidden = state.fw !== "byte";
if (state.view === "learn") renderLearn();
if (state.view === "rescue") { if (!rsStarted) rs.src = state.fw; rsRender(); }
if (state.view === "docs" && docsFor !== state.fw + lang) { docsFor = state.fw + lang; renderDocs(); }
}
/* ------------------------------------------------- the editor and the emulator joined (target: Emulator) */
/* A MIDIAccess-like pair of ports for the editor's frame (editor.html ?emu=1): what the editor sends goes to the emulator's
* own editor handler (emu/index.html jiantEmu.sysex -> worklet.js -> editor-api.h), its replies and pushes come back */
function emuMidi() {
const emu = () => { try { return frames.emu.el.contentWindow.jiantEmu; } catch (_) { return null; } };
loadFrame("emu");
const input = { id: "emu-in", name: "JIANT (emulator)", type: "input", state: "connected", manufacturer: "JIANT", onmidimessage: null,
_l: new Set(), addEventListener(_, f) { this._l.add(f); }, removeEventListener(_, f) { this._l.delete(f); },
open() { return Promise.resolve(this); }, close() { return Promise.resolve(this); } };
let off = null;
const hook = () => {
const e = emu();
if (!e || off) return;
off = e.listen((bytes) => { const ev = { data: Uint8Array.from(bytes) }; input.onmidimessage && input.onmidimessage(ev); input._l.forEach((f) => f(ev)); });
};
const output = { id: "emu-out", name: "JIANT (emulator)", type: "output", state: "connected", manufacturer: "JIANT",
open() { return Promise.resolve(this); }, close() { return Promise.resolve(this); },
send(d) { hook(); const e = emu(); if (e && e.on()) e.sysex(Array.from(d)); } };
hook();
return { inputs: new Map([[input.id, input]]), outputs: new Map([[output.id, output]]), onstatechange: null, sysexEnabled: true };
}
/* which MIDI inputs play the emulator (emu/index.html jiantEmu.midiInput): every one, none, or one port */
function renderEmuMidi() {
const sel = $("emumidi");
let e = null;
try { e = frames.emu.el.contentWindow.jiantEmu; } catch (_) {}
if (!e || !e.on()) { sel.replaceChildren(new Option(t("emuMidiOff"), "")); sel.disabled = true; return; }
sel.disabled = false;
sel.replaceChildren(new Option(t("emuMidiAll"), "all"), new Option(t("emuMidiNone"), "none"), ...e.midiInputs().map((p) => new Option(p.name, p.id)));
sel.value = e.midiInput();
}
$("emumidi").addEventListener("change", () => { try { frames.emu.el.contentWindow.jiantEmu.midiInput($("emumidi").value); } catch (_) {} });
$("emumidi").addEventListener("pointerdown", renderEmuMidi);
setInterval(() => { if (state.view === "emu" && document.activeElement !== $("emumidi")) renderEmuMidi(); }, 1500);
/* the emulator's whole panel in its frame: the device as wide as the frame lets it be with all of it in sight (its own
* page makes it as wide as the page, taller than the frame); refitted on any resize, in or out of full screen */
function fitEmu() {
try {
const w = frames.emu.el.contentWindow, d = w.document, dev = d.getElementById("device");
if (!dev) return;
const ar = (dev.style.aspectRatio || "1000 / 624").split("/").map(Number), r = ar[0] / ar[1];
const main = dev.parentElement, cs = w.getComputedStyle(main);
const padX = parseFloat(cs.paddingLeft) + parseFloat(cs.paddingRight);
const top = dev.getBoundingClientRect().top + w.scrollY;
const h = Math.max(240, w.innerHeight - top - 12), wid = Math.min(main.clientWidth - padX, h * r);
main.style.maxWidth = "none";
Object.assign(dev.style, { width: `${Math.floor(wid)}px`, marginLeft: "auto", marginRight: "auto" });
} catch (_) {}
}
frames.emu.el.addEventListener("load", () => {
fitEmu();
try {
const w = frames.emu.el.contentWindow;
w.addEventListener("resize", fitEmu);
// (its layout, wide or tall, rebuilt: the aspect changes)
new w.MutationObserver(fitEmu).observe(w.document.getElementById("device"), { attributes: true, attributeFilter: ["style"] });
} catch (_) {}
});
/* full screen: the browser's own (the frame's box) where it has it; else (iPhone) the box over the whole page */
const emuFullOn = () => $("emubox").classList.contains("max") || document.fullscreenElement === $("emubox") || document.webkitFullscreenElement === $("emubox");
function emuFull(on) {
const b = $("emubox");
if (on) {
loadFrame("emu");
const req = b.requestFullscreen || b.webkitRequestFullscreen;
const p = req ? req.call(b) : null;
if (p && p.catch) p.catch(() => b.classList.add("max")); else if (!req) b.classList.add("max");
} else {
b.classList.remove("max");
if (document.fullscreenElement || document.webkitFullscreenElement) (document.exitFullscreen || document.webkitExitFullscreen).call(document);
}
setTimeout(fitEmu, 300);
}
$("emufull").addEventListener("click", () => emuFull(!emuFullOn()));
$("emuexit").addEventListener("click", () => emuFull(false));
document.addEventListener("keydown", (e) => { if (e.key === "Escape" && $("emubox").classList.contains("max")) emuFull(false); });
const emuOn = () => { try { const e = frames.emu.el.contentWindow.jiantEmu; return !!(e && e.on()); } catch (_) { return false; } };
/* ?mock=1: STEMS+IN's 10 channels made up (each its own pitch and pulse), in the recorder's own context: a node */
function mockStems(ac) {
const merge = ac.createChannelMerger(10);
for (let k = 0; k < 10; k++) {
const o = ac.createOscillator(), g = ac.createGain(), lfo = ac.createOscillator(), lg = ac.createGain();
o.type = ["square", "sawtooth", "triangle", "sine"][k % 4]; o.frequency.value = 55 * (k + 2);
lfo.frequency.value = 0.7 + k * 0.45; lg.gain.value = 0.18; g.gain.value = 0.2;
lfo.connect(lg).connect(g.gain); o.connect(g).connect(merge, 0, k); o.start(); lfo.start();
}
return merge;
}
/* ------------------------------------------------------------------------------- ?mock=1: a simulated FM-1 */
function mockAccess() {
const fb = new Uint16Array(SCR.W * SCR.H), rgb = (r, g, b) => (r >> 3) << 11 | (g >> 2) << 5 | b >> 3;
const rect = (x, y, w, h, c) => { for (let j = y; j < y + h; j++) fb.fill(c, j * SCR.W + x, j * SCR.W + x + w); };
const kind = QS.get("fw") === "byte" ? "byte" : "fm";
let on = false, last = 0, step = 0, tick = 0;
const input = { id: "mock-in", name: "JIANT", type: "input", state: "connected", onmidimessage: null,
_l: new Set(), addEventListener(_, f) { this._l.add(f); }, removeEventListener(_, f) { this._l.delete(f); } };
const deliver = (bytes) => setTimeout(() => { const ev = { data: Uint8Array.from(bytes) }; input.onmidimessage && input.onmidimessage(ev); input._l.forEach((f) => f(ev)); }, 2);
const draw = () => {
const bg = kind === "byte" ? rgb(0, 0, 0) : rgb(20, 18, 28), acc = kind === "byte" ? rgb(167, 123, 255) : rgb(236, 110, 80);
rect(0, 0, 240, 240, bg); rect(0, 0, 240, 24, rgb(40, 36, 52)); rect(8, 8, 70, 8, rgb(230, 230, 230)); rect(196, 8, 36, 8, acc);
rect(8, 34, 52, 44, acc); rect(64, 34, 52, 44, rgb(60, 56, 80)); rect(120, 34, 52, 44, rgb(60, 56, 80)); rect(176, 34, 56, 44, rgb(60, 56, 80));
for (let i = 0; i < 120; i++) fb[(120 + Math.round(30 * Math.sin(i / 9))) * 240 + 60 + i] = acc;
};
// its projects (A and C saved) and its archive (backups: the current music, the settings, the song index, two songs)
const slots = [true, false, true, false];
let mockWatch = 0;
const arch = new Map(BACKUP_IDS.map((id) => {
const n = { 0: 520, 1: 140, 10: 64, 40: 300, 41: 300, 44: 280 }[id] || 0;
return [id, Uint8Array.from({ length: n }, (_, i) => (i * 7 + id * 13) & 255)];
}));
const puts = new Map();
const output = { id: "mock-out", name: "JIANT", type: "output", state: "connected", send(d) {
const f = unframe(Uint8Array.from(d));
if (!f) return;
last = Date.now();
if (f.cmd === 22) { // WATCH: then a knob turning (CUT), now and then a sound change
clearInterval(mockWatch);
if (f.a[0]) { let k = 0; mockWatch = setInterval(() => {
k++;
if (k % 12 === 0) deliver(frame(24, [(k / 12) % 2 ? 2 : 0, k % 5, 0]));
else if (k % 12 === 6) { const s0 = (x) => [...x].map((c) => c.charCodeAt(0)).concat(0);
deliver(frame(43, [1, ...s0(k % 24 === 6 ? "FILTER" : "OSC"), 0, 127, ...s0("CUT"), ...s0("RES"), ...s0("ENV"), ...s0("TYPE")])); }
else { const v = 40 + Math.round(40 * Math.sin(k / 3)) + 8192; deliver(frame(23, [0, 20, v & 127, v >> 7])); }
}, 250); }
deliver(frame(22, [f.a[0] ? 31 : 0])); return;
}
const e14 = (v) => [(v + 8192) & 127, (v + 8192) >> 7];
if (f.cmd === 4) { deliver(frame(4, [0, 0, ...Array.from({ length: 140 }, (_, i) => e14(i % 7 ? 64 : 0)).flat()])); return; } // DUMP: the engine, the preset, 100 + 40 values
if (f.cmd === 29) { deliver(frame(29, [f.a[0], 0, f.a[0], ...Array.from({ length: 100 }, (_, i) => e14(i === 3 ? 90 : 64)).flat()])); return; } // TRACK_DUMP
if (f.cmd === 31) { deliver(frame(31, f.a.slice(0, 4))); return; } // TRACK_PARAM: set, echoed
if (f.cmd === 30) { const [t, i] = f.a, on = i % 4 === 0; deliver(frame(30, [t, i, on ? 1 : 0, on ? 36 + t : 0, 0, 0, 0, 2, 0, 100])); return; } // TRACK_STEP
if (f.cmd === 95) { const P = window.__pj = window.__pj || [["NIGHT", 15, 1], ["", 3, 0], ["", 0, 0], ["DUB", 1, 2], ["", 0, 0], ["", 0, 0]];
deliver(frame(95, [0, 6, ...P.flatMap(([nm, parts, fl], n) => [n, parts, fl, ...Array.from({ length: 12 }, (_, i) => nm.charCodeAt(i) || 0)])])); return; }
if (f.cmd === 96) { const P = window.__pj; if (f.a[1] === 0) P[f.a[0]][0] = String.fromCharCode(...f.a.slice(2, f.a.indexOf(0, 2) < 0 ? undefined : f.a.indexOf(0, 2))); deliver(frame(96, [f.a[0], f.a[1], 0])); return; }
if (f.cmd === 97) { const P = window.__pj, [op, a, b, force] = f.a; let rc = 0;
if (op !== 2 && (P[b][2] & 1 || (op === 1 && P[a][2] & 1))) rc = 1; else if (op !== 2 && P[b][1] && !force) rc = 4;
else if (op === 2) P[a] = ["", 0, 0]; else { P[b] = [P[a][0], P[a][1], 0]; if (op === 1) P[a] = ["", 0, 0]; }
deliver(frame(97, [op, a, b, rc])); return; }
if (f.cmd === 33) { deliver(frame(33, [0, 0, 2, 0, 0, 0, 0, 1, 1, 2])); return; } // SONG: A x1, B x2
if (f.cmd === 5) { // DESC: CUT on any id
const s = (x) => [...x].map((c) => c.charCodeAt(0)).concat(0), e = (v) => [(v + 8192) & 127, (v + 8192) >> 7];
deliver(frame(5, [f.a[0], f.a[1], 0, ...e(0), ...e(127), ...e(64), ...s("CUT"), ...s("")])); return;
}
if (f.cmd === CMD.PING) { deliver(frame(CMD.PING, [])); return; }
if (f.cmd === 9) { // PROJECT: 0 load, 1 save, 2 query
const [op, k] = f.a;
if (op === 1) slots[k] = true;
setTimeout(() => deliver(frame(9, [op, k, slots[k] ? 1 : 0])), op === 1 ? 300 : 20);
return;
}
if (f.cmd === 65) { // BACKUP_LIST
deliver(frame(65, [1, 0, arch.size, ...[...arch].flatMap(([id, b]) => [id, ...bkU32(b.length), ...bkU32(b.length ? bkCrc(b) : 0)])]));
return;
}
if (f.cmd === 66) { // BACKUP_GET: id, offset, count
const id = f.a[0], off = bkR32(f.a, 1), n = f.a[6] | f.a[7] << 7, b = arch.get(id);
deliver(frame(66, [id, 0, ...bkU32(off), n & 127, n >> 7, ...bkPack(b.subarray(off, off + n))]));
return;
}
if (f.cmd === 67) { // BACKUP_PUT: begin, data, commit
const [op, id] = f.a;
if (op === 0) puts.set(id, new Uint8Array(bkR32(f.a, 2)));
else if (op === 1) { const off = bkR32(f.a, 2), body = f.a.slice(7), n = Math.min(256, puts.get(id).length - off); puts.get(id).set(bkUnpack(body, n), off); }
else if (op === 2) arch.set(id, puts.get(id));
deliver(frame(67, [op, id, 0]));
return;
}
if (kind === "byte" && f.cmd >= 90 && f.cmd <= 93) { // user wavetables (protocol 1.5): 8 slots
const W = window.__wt = window.__wt || { names: Array(8).fill(""), data: Array.from({ length: 8 }, () => Array.from({ length: 8 }, () => new Array(96).fill(0))) }, a = f.a;
if (f.cmd === 90) { const used = W.names.reduce((m, n, i) => m | (n ? 1 << (i % 7) : 0), 0); deliver(frame(90, [8, 8, 128, used & 127, W.names[7] ? 1 : 0, ...W.names.flatMap((n) => [...n].map((c) => c.charCodeAt(0)).concat(0))])); }
if (f.cmd === 91) { if (a[0] > 7) { deliver(frame(91, [a[0], a[1], a[2], 1])); return; } W.data[a[0]][a[1] * 4 + a[2]] = a.slice(3); deliver(frame(91, [a[0], a[1], a[2], 0])); }
if (f.cmd === 92) { W.names[a[0]] = String.fromCharCode(...a.slice(1, a.indexOf(0, 1))); deliver(frame(92, [a[0], 0])); }
if (f.cmd === 93) deliver(frame(93, [a[0], a[1], a[2], ...(W.data[a[0]][a[1] * 4 + a[2]] || new Array(96).fill(0))]));
return;
}
if (f.cmd === CMD.INFO) {
const s = (x) => [...x].map((c) => c.charCodeAt(0)).concat(0);
const eng = kind === "byte" ? ["ANALOG", "-", "PHASE", "MATH", "WAVE", "DRUM"] : ["ANALOG", "-", "PHASE", "MATH", "DRUM", "FM6"]; // (FM has MATH too)
deliver(frame(CMD.INFO, [...s(kind === "byte" ? (QS.has("nomirror") ? "JIANT BYTE v0.16" : "JIANT BYTE v0.17") : "JIANT V10.8.24"), eng.length, 100, 40, 64, 10, ...eng.flatMap(s)]));
} else if (f.cmd === 27) { // TRACK: six tracks, their engines (indexes into INFO's list)
if (f.a.length) mockSel = f.a[0];
deliver(frame(27, [mockSel, 6, ...[4, 0, 2, 3, 5, 1].flatMap((e) => [e, 0, 0, 64, 0, 0])]));
} else if (f.cmd === CMD.SCREEN && !QS.has("nomirror")) { // (?nomirror: firmware from before the mirror: no reply)
const op = f.a[0] | 0;
if (op === 1 || (op === 3 && on)) { on = true; draw(); for (const a of scrEncode(fb, 0, 0, 240, 240)) deliver(frame(CMD.SCREEN_DATA, a)); }
if (op === 4) on = false;
deliver(frame(CMD.SCREEN, [op, 0, on ? 1 : 0, 240 & 127, 240 >> 7, 240 & 127, 240 >> 7]));
}
} };
setInterval(() => { // the playhead's row moving, and a note now and then
if (on && Date.now() - last < 4000) {
const y = 200, row = fb.subarray(y * 240, (y + 12) * 240);
row.fill(rgb(20, 18, 28)); for (let j = 0; j < 12; j++) row.fill(rgb(255, 210, 63), j * 240 + 8 + (step % 16) * 14, j * 240 + 20 + (step % 16) * 14);
step++;
for (const a of scrEncode(fb.subarray(y * 240), 0, y, 240, 12)) deliver(frame(CMD.SCREEN_DATA, a));
} else on = false;
if (++tick % 4 === 0) { const n = 48 + (tick % 12); deliver([0x90, n, 100]); setTimeout(() => deliver([0x80, n, 0]), 200); }
}, 125);
return { inputs: new Map([[input.id, input]]), outputs: new Map([[output.id, output]]), onstatechange: null, sysexEnabled: true };
}
/* ------------------------------------------------------------------------------------------------- the start */
document.documentElement.dataset.skin = state.fw;
const fromHash = (location.hash || "").replace(/^#/, "").split("?")[0].split("/")[0];
lrRoute(location.hash);
applyLang();
go(QS.get("view") || (VIEWS.includes(fromHash) ? fromHash : state.view), false);
/* ------------------------------------------------------------------------------------------------ the six spaces */
const SPACES = [
{ k: "Listen", v: ["radio", "vis", "screen"], ic: '<path d="M4 13a8 8 0 0 1 16 0v5h-3v-5M4 13v5h3v-5"/>' },
{ k: "Create", v: ["emu", "pe", "editor", "wt"], ic: '<path d="M4 20l4-1 11-11-3-3L5 16l-1 4zM14 6l3 3"/>' },
{ k: "Rec", v: ["rec", "ed"], ic: '<circle cx="12" cy="12" r="7"/><circle cx="12" cy="12" r="2.6"/>' },
{ k: "Manage", v: ["proj"], ic: '<path d="M4 6h6l2 2h8v10H4z"/>' },
{ k: "Device", v: ["install", "an", "rescue", "ports"], ic: '<rect x="4" y="6" width="16" height="12" rx="1"/><path d="M8 10h3M8 14h8"/>' },
{ k: "Learn", v: ["learn", "docs"], ic: '<path d="M4 7l8-3 8 3-8 3-8-3zM6 9v6c3 2 9 2 12 0V9"/>' },
];
const spaceOf = (v) => SPACES.findIndex((s) => s.v.includes(v));
const spLast = {};
const VNAME = { radio: "vRadio", home: "vHome", emu: "vEmu", screen: "vScreen", rec: "vRec", ed: "vEd", vis: "vVis", editor: "vEditor", pe: "vPe", proj: "vProj", wt: "vWt", learn: "vLearn", docs: "vDocs", install: "vInstall", an: "vAn", rescue: "vRescue", ports: "vPorts" };
function renderSpaces() {
if (!$("spaces")) return; // (the tab strip as before: the spaces only as sheets)
const cur = spaceOf(state.view);
$("spaces").replaceChildren(...SPACES.map((s, i) => {
const b = document.createElement("button"); b.type = "button"; b.className = "spbtn"; b.dataset.space = i; b.setAttribute("aria-pressed", String(i === cur));
b.innerHTML = `<svg viewBox="0 0 24 24">${s.ic}</svg><b></b><i></i>`; b.querySelector("b").textContent = t("sp" + s.k); b.querySelector("i").textContent = t("sp" + s.k + "S");
b.onclick = () => { if (i !== cur) { const v = spLast[i] && s.v.includes(spLast[i]) ? spLast[i] : visibleViews(s)[0]; go(v); } openSheet(i); };
return b;
}));
$("viewsrow").classList.toggle("home", cur < 0);
document.querySelectorAll("nav.views [data-go]").forEach((b) => b.classList.toggle("offspace", cur < 0 || !SPACES[cur].v.includes(b.dataset.go)));
if (cur >= 0) spLast[cur] = state.view;
}
const visibleViews = (s) => s.v.filter((v) => { const b = document.querySelector(`nav.views [data-go="${v}"]`); return !b || !b.hidden; });
let sheetAt = -1;
function openSheet(i) {
const s = SPACES[i], el = (tag, cls, text) => { const e = document.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e; };
sheetAt = i; $("sheett").textContent = t("sp" + s.k); $("sheets").textContent = t("sp" + s.k + "L");
const rows = [];
if (s.k === "Device") {
const c = el("div", "conncard"), st = el("div", "cst"), dot = el("span", "dot" + (state.dev || emuOn() ? " ok" : ""));
st.append(dot, document.createTextNode(state.target === "emu" ? t(emuOn() ? "cEmuOn" : "cEmuOff") : state.dev ? devName(state.dev) : t("bkNoDev")));
const a = el("div", "cacts"), bt = (k, f, ghost) => { const b = el("button", "btn" + (ghost ? " ghost" : ""), t(k)); b.type = "button"; b.onclick = () => { closeSheet(); f(); }; return b; };
a.append(bt(state.target === "emu" ? "spConnFm1" : "spConnEmu", () => { const to = state.target === "emu" ? "fm1" : "emu"; setTarget(to); }),
bt("spBackup", () => { go("proj"); setTimeout(() => $("bkgo").click(), 50); }, true), bt("spExportProj", () => go("pe"), true),
bt("spImport", () => { go("proj"); setTimeout(() => $("bkimport").click(), 50); }, true), bt("spExportAudio", () => go("rec"), true));
c.append(st, a); rows.push(c);
}
const item = (n, title, desc, f, cur) => { const r = el("button", "fnrow"); r.type = "button"; if (cur) r.setAttribute("aria-current", "true");
const mid = el("div"); mid.append(el("strong", null, title), el("p", null, desc)); r.append(el("span", "fk", String(n).padStart(2, "0")), mid, el("span", "fg", "›"));
r.onclick = () => { closeSheet(); f(); }; return r; };
let n = 0;
for (const v of visibleViews(s)) rows.push(item(++n, t(VNAME[v]), t("tourV_" + v), () => go(v), v === state.view));
if (s.k === "Rec") rows.push(item(++n, t("spStems"), t("spStemsD"), () => { go("rec"); setTimeout(() => { const x = $("stsong"); if (x) x.scrollIntoView({ behavior: "smooth", block: "center" }); }, 80); }));
$("sheetbody").replaceChildren(...rows);
$("sheet").hidden = false; $("scrim").hidden = false; scopes.sheet = true;
const f = $("sheetbody").querySelector('[aria-current="true"]') || $("sheetbody").querySelector(".fnrow"); if (f) f.focus({ preventScroll: true });
}
function closeSheet() { $("sheet").hidden = true; $("scrim").hidden = true; scopes.sheet = false; sheetAt = -1; }
$("scrim").onclick = closeSheet; $("sheetx").onclick = closeSheet;
document.addEventListener("keydown", (e) => { if (e.key === "Escape" && !$("sheet").hidden) closeSheet(); });
$("devchip").addEventListener("click", () => openSheet(SPACES.findIndex((s) => s.k === "Device")));
window.studioGo = (v) => go(v);
window.__spReady = true; renderSpaces();
{ /* on a phone the spaces sit at the bottom of the screen: out of the header (its sticky layer would hold them) */
const mq = matchMedia("(max-width: 640px)"), sp = $("spaces"), home = $("viewsrow");
const place = () => { if (!sp) return; if (mq.matches) { if (sp.parentElement !== document.body) document.body.append(sp); } else if (sp.nextElementSibling !== home) home.before(sp); };
mq.addEventListener("change", place); place();
}
/* the heat scopes: a bytebeat drawn as it plays (the header's, and the sheet's behind its title), in the heat colours */
const scopes = { sheet: false };
{
const F = [(t) => t * (t >> 5 | t >> 8), (t) => t * ((t >> 9 | t >> 13) & 25 & t >> 6), (t) => (t >> 6 | t | t >> (t >> 16)) * 10 + ((t >> 11) & 7), (t) => t * (t >> 11 & t >> 8 & 123 & t >> 3), (t) => (t * 5 & t >> 7) | (t * 3 & t >> 10)];
const RM = matchMedia("(prefers-reduced-motion: reduce)").matches;
let T = 0, fi = 0, last = 0;
const grad = (g, w) => { const gr = g.createLinearGradient(0, 0, w, 0); [["#3b6cff", 0], ["#9d6bff", .25], ["#ff4a7a", .5], ["#ff8a1f", .75], ["#ffe14d", 1]].forEach(([c, p]) => gr.addColorStop(p, c)); return gr; };
const draw = (cv, t0, lw) => {
if (!cv || !cv.offsetParent) return; const g = cv.getContext("2d"), W = cv.width, H = cv.height, f = F[fi];
g.clearRect(0, 0, W, H); g.strokeStyle = grad(g, W); g.lineWidth = lw; g.lineJoin = "round"; g.beginPath();
for (let x = 0; x < W; x += 2) { const v = (f(t0 + x * 3) & 255) / 255, y = H * .12 + (1 - v) * H * .76; x ? g.lineTo(x, y) : g.moveTo(x, y); }
g.stroke();
};
const tick = (ms) => {
if (!document.hidden && ms - last > 33) { last = ms; T += 1400; if (T > 400000) { T = 0; fi = (fi + 1) % F.length; } draw($("heatscope"), T, 1.5); if (scopes.sheet) draw($("sheetscope"), T * 2, 2.5); }
if (!RM) requestAnimationFrame(tick);
};
if (RM) { draw($("heatscope"), 9000, 1.5); } else requestAnimationFrame(tick);
}
window.addEventListener("hashchange", () => {
const h = location.hash.replace(/^#/, "").split("/")[0];
if (lrRoute(location.hash) && state.view === "learn") { renderLearn(); return; }
if (VIEWS.includes(h) && h !== state.view) go(h, false);
});
if (MOCK || QS.has("screen")) find().then(() => { if (QS.has("screen") && state.dev) { screenStart(); } });
/* (for the tests) */
loadList();
try { if (!localStorage.getItem(TOUR_KEY) && !MOCK && !QS.has("notour") && !location.hash) setTimeout(() => tourShow(0), 700); } catch (_) {}
window.jiantStudio = { tourShow, tourEnd, proj, bkDb, emuMidi, state, find, letGo, screenStart, screenStop, recStart, recStop, setFw, setTarget, go, rec, scr };