// ==UserScript==
// @name GPTative Synthesizer - Strict Code Block Sheet Parser - Fixed & Enhanced
// @version 3.1
// @description Parses strictly formatted musical sheets inside markdown code blocks during chat generation and synthesizes audio with Web Audio API. Respects autoplay policies and robustly handles generation state.
// @match *://yuntian-deng-chatgpt.hf.space/*
// @grant none
// @run-at document-idle
// ==/UserScript==
(() => {
"use strict";
// ============ Constants & Config ============
// Important tags delimiting the sheet inside code blocks
const BEGIN_TAG = "[BEGIN MUSICAL SHEET]";
const END_TAG = "[END MUSICAL SHEET]";
// Audio / Playback parameters
const TEMPO_BPM = 90;
const BEAT_DURATION = 60 / TEMPO_BPM; // in seconds
const FADE_TIME = 0.035; // seconds for smooth fade-in/out of notes
const REST_SYMBOL = "∅";
// Base frequency for A4 tuning (standard 440Hz or alternative 432Hz)
const BASE_A4_FREQ = 432;
// Mapping rhythmic durations symbols to seconds
const DURATION_MAP = {
"♩": 1 * BEAT_DURATION, // quarter note
"♪": 0.5 * BEAT_DURATION, // eighth note
"♬": 0.25 * BEAT_DURATION // sixteenth note
};
// Dynamics (volume multipliers)
const DYNAMICS = {
pp: 0.2,
p: 0.4,
mp: 0.6,
mf: 0.75,
f: 1.0,
ff: 1.3
};
// Note name to semitone offset from A (A = 0)
const NOTE_SEMITONE_OFFSETS = {
"C": -9,
"C#": -8, "Db": -8,
"D": -7,
"D#": -6, "Eb": -6,
"E": -5,
"F": -4,
"F#": -3, "Gb": -3,
"G": -2,
"G#": -1, "Ab": -1,
"A": 0,
"A#": 1, "Bb": 1,
"B": 2
};
// ============ State Variables ============
let isGenerating = false; // true when bot is generating
let isError = false; // true if error detected in chat
let isPlaying = false; // true when playback active
let currentSheet = null; // text content of the currently playing sheet
// Audio API nodes & management
let audioCtx = null;
let osc = null;
let gainNode = null;
let vibratoLFO = null;
let playTimeout = null;
let currentTimeouts = [];
/**
* Clear all scheduled timeouts for playing notes.
*/
function clearAllTimeouts() {
currentTimeouts.forEach(id => clearTimeout(id));
currentTimeouts = [];
}
// ============ Audio Context Init ============
function initAudioCtx() {
if (!audioCtx) {
const AudioContextClass = window.AudioContext || window.webkitAudioContext;
audioCtx = new AudioContextClass();
}
}
/**
* Ensures AudioContext is resumed (required for autoplay policy).
* Returns a Promise.
*/
async function ensureAudioCtxResumed() {
initAudioCtx();
if (audioCtx.state === "suspended") {
try {
await audioCtx.resume();
console.log("[GPTative] AudioContext resumed");
} catch (e) {
console.warn("[GPTative] AudioContext resume failed:", e);
}
}
}
// ============ Utility Functions ============
/**
* Converts note string to frequency in Hz.
* @param {string} noteName Example: C, D#, Gb...
* @param {number} octave Octave number (default 4 if missing)
* @returns {number} frequency in Hz
*/
function noteToFrequency(noteName, octave = 4) {
let semitoneOffset = NOTE_SEMITONE_OFFSETS[noteName];
if (semitoneOffset === undefined) return null;
let semitonesFromA4 = semitoneOffset + (octave - 4) * 12;
return BASE_A4_FREQ * Math.pow(2, semitonesFromA4 / 12);
}
/**
* Parses a single token representing a note with optional octave, duration, dynamic.
* Format example: C4♩[mf]
* @param {string} token
* @returns {object|null} Parsed note event or null if invalid
*/
function parseNoteToken(token) {
// Regex breakdown:
// 1: note letter A-G or a-g
// 2: optional accidental #, ♯, b, ♭
// 3: optional octave digit (0-9)
// 4: duration symbol one of ♩♪♬
// 5: optional dynamics inside square brackets [mf], [pp], etc.
const re = /^([A-Ga-g])([#♯b♭]?)(\d?)([♩♪♬])(\[(pp|p|mp|mf|f|ff)\])?$/;
const match = token.match(re);
if (!match) return null;
let [, note, accidental, octaveStr, durationSym, , dynamics] = match;
note = note.toUpperCase();
// Normalize accidentals to sharps or flats as standard
if (accidental === "♯") accidental = "#";
if (accidental === "♭") accidental = "b";
let noteName = note + (accidental || "");
let octave = octaveStr !== "" ? parseInt(octaveStr, 10) : 4;
let duration = durationSym;
let dynamic = dynamics ? dynamics.toLowerCase() : "mf";
if (!(noteName in NOTE_SEMITONE_OFFSETS)) {
console.warn(`[GPTative] Invalid note name: ${noteName}`);
return null;
}
if (!(dynamic in DYNAMICS)) {
console.warn(`[GPTative] Unknown dynamic: ${dynamic}, defaulting to mf`);
dynamic = "mf";
}
return {
noteName,
octave,
duration,
dynamic
};
}
/**
* Sanitizes and splits a line of music tokens into discrete tokens,
* properly handling rests, measures, and multiple tokens separated by spaces.
* @param {string} line
* @returns {string[]} tokens
*/
function sanitizeAndSplitTokens(line) {
// Remove unwanted symbols, replace "Rest" by rest symbol ∅
line = line.replace(/[𝄞𝄢𝄫𝄫]/g, " "); // Common musical symbols to spaces
line = line.replace(/Rest/gi, REST_SYMBOL);
// Normalize multiple whitespaces
line = line.replace(/\s+/g, " ").trim();
// Insert spaces around measure bar (|) to separate tokens correctly
line = line.replace(/\|/g, " | ");
// Split on spaces
const rawTokens = line.split(" ").filter(t => t.length > 0);
const tokens = [];
rawTokens.forEach(token => {
if (token === "|") {
tokens.push(token);
return;
}
if (token === REST_SYMBOL || token === `${REST_SYMBOL}♩` || token === `${REST_SYMBOL}♪` || token === `${REST_SYMBOL}♬`) {
// Normalize rest duration symbol if any
if(token.length === 1) tokens.push(REST_SYMBOL);
else tokens.push(token);
return;
}
// Notes tokens - there may be compound tokens stuck together, try to extract all matches
// Examples: C4♩[mf], D#5♪, E♬, F4♩, etc.
const noteRegex = /([A-Ga-g][#♯b♭]?\d?[♩♪♬](\[(pp|p|mp|mf|f|ff)\])?)/g;
let m;
while ((m = noteRegex.exec(token)) !== null) {
tokens.push(m[1]);
}
});
return tokens;
}
// ============ Generations & Parsing ============
/**
* Extracts the latest fully wrapped musical sheet strictly contained inside
* a markdown code block with the required BEGIN and END tags.
* It scans from the latest code blocks backward.
* @returns {string|null} extracted sheet text or null if none found
*/
function extractStrictSheetFromCodeBlocks() {
// Select all <pre> and <code> blocks (where code blocks content usually live)
const codeBlocks = Array.from(document.querySelectorAll("pre, code"));
for (let i = codeBlocks.length - 1; i >= 0; i--) {
const block = codeBlocks[i];
// Only consider blocks that appear as code blocks (heuristic)
if (!block.textContent) continue;
const text = block.textContent;
const beginIdx = text.indexOf(BEGIN_TAG);
const endIdx = text.indexOf(END_TAG);
if (beginIdx !== -1 && endIdx !== -1 && endIdx > beginIdx) {
const sheet = text.substring(beginIdx + BEGIN_TAG.length, endIdx).trim();
if (sheet.length > 0) {
return sheet;
}
}
}
return null;
}
/**
* Parses a full musical sheet string into an array of events for playback.
* @param {string} sheetText Raw musical sheet content between BEGIN and END tags
* @returns {Array<{time:number, freq:number|null, duration:number, gain:number}>} Array of note/rest events
*/
function parseSheet(sheetText) {
// Split into lines, exclude metadata lines (lines with colon ':')
const allLines = sheetText.split("\n").map(l => l.trim());
// Extract musical content lines only (exclude metadata lines)
let musicLines = allLines.filter(line => line.length > 0 && !line.includes(":"));
// Accumulate tokens from all music lines
const tokens = [];
musicLines.forEach(line => {
tokens.push(...sanitizeAndSplitTokens(line));
});
// Parse tokens into note/rest events with timing and gain
let currentTime = 0;
let currentDynamic = "mf"; // Default dynamic
const events = [];
for (const token of tokens) {
if (token === "|") {
// Measure bar - no time increment, optional place for alignment if needed
continue;
}
// Change dynamic if token is only dynamic marker, e.g. [mf]
const dynMatch = token.match(/^\[(pp|p|mp|mf|f|ff)\]$/i);
if (dynMatch) {
currentDynamic = dynMatch[1].toLowerCase();
continue;
}
// Rest token
if (token === REST_SYMBOL || token.startsWith(REST_SYMBOL)) {
// Determine duration from rest token suffix if any eg. '∅♩' means quarter rest
let restDur = BEAT_DURATION;
const durSymMatch = token.match(/[♩♪♬]/);
if (durSymMatch) {
restDur = DURATION_MAP[durSymMatch[0]] || BEAT_DURATION;
}
events.push({
time: currentTime,
freq: null,
duration: restDur,
gain: 0
});
currentTime += restDur;
continue;
}
// Otherwise, parse note token
const noteInfo = parseNoteToken(token);
if (!noteInfo) {
console.warn("[GPTative] Skipping invalid token:", token);
continue;
}
// Calculate frequency from note info
const freq = noteToFrequency(noteInfo.noteName, noteInfo.octave);
if (!freq || freq <= 0 || !isFinite(freq)) {
console.warn("[GPTative] Invalid frequency for token:", token);
continue;
}
// Map duration symbol to seconds
const dur = DURATION_MAP[noteInfo.duration] || BEAT_DURATION;
// Map dynamic to gain multiplier
const gainVal = DYNAMICS[noteInfo.dynamic] || DYNAMICS[currentDynamic] || 0.75;
// Create event
events.push({
time: currentTime,
freq,
duration: dur,
gain: gainVal
});
currentTime += dur;
}
return events;
}
// ============ Playback Engine ============
/**
* Initializes oscillator, gain and vibrato
* and connects to audio destination.
*/
function initOscillator() {
if (!audioCtx) initAudioCtx();
if (osc) return; // already created
osc = audioCtx.createOscillator();
gainNode = audioCtx.createGain();
gainNode.gain.value = 0;
// Vibrato LFO (5Hz vibrato with ±10Hz freq modulation)
vibratoLFO = audioCtx.createOscillator();
vibratoLFO.frequency.value = 5; // 5Hz vibrato rate
const vibratoGain = audioCtx.createGain();
vibratoGain.gain.value = 10; // ±10 Hz vibrato depth
// Connect vibrato: vibratoLFO -> vibratoGain -> osc.frequency
vibratoLFO.connect(vibratoGain);
vibratoGain.connect(osc.frequency);
osc.type = "triangle";
osc.connect(gainNode);
gainNode.connect(audioCtx.destination);
osc.start();
vibratoLFO.start();
console.log("[GPTative] Oscillator & vibrato initialized and started");
}
/**
* Stops and disposes oscillator and gain nodes gracefully
*/
function stopOscillator() {
if (!osc) return;
// Fade out gain smoothly before stopping
gainNode.gain.cancelScheduledValues(audioCtx.currentTime);
gainNode.gain.setTargetAtTime(0, audioCtx.currentTime, FADE_TIME);
// Stop oscillators after fade time
setTimeout(() => {
try {
osc.stop();
vibratoLFO.stop();
} catch (_) {}
osc.disconnect();
gainNode.disconnect();
vibratoLFO.disconnect();
osc = null;
gainNode = null;
vibratoLFO = null;
console.log("[GPTative] Oscillator & vibrato stopped and cleaned up");
}, FADE_TIME * 1000);
}
/**
* Plays given note/rest events sequentially.
* Uses scheduled timeouts for note timing.
* @param {Array} events - Array of {time, freq, duration, gain}
*/
function playEvents(events) {
if (!events.length) return;
initOscillator();
let currIndex = 0;
/**
* Plays a single event at index currIndex
*/
function playNext() {
if (currIndex >= events.length) {
isPlaying = false;
stopOscillator();
return;
}
const ev = events[currIndex++];
if (ev.freq === null) {
// Rest: fade gain to zero (if not already)
if (gainNode) {
gainNode.gain.cancelScheduledValues(audioCtx.currentTime);
gainNode.gain.setTargetAtTime(0, audioCtx.currentTime, FADE_TIME);
}
// Schedule next note after rest duration
const id = setTimeout(playNext, ev.duration * 1000);
currentTimeouts.push(id);
return;
}
// Play note frequency with gain and fades
try {
osc.frequency.setTargetAtTime(ev.freq, audioCtx.currentTime, 0.01);
gainNode.gain.cancelScheduledValues(audioCtx.currentTime);
gainNode.gain.setValueAtTime(0, audioCtx.currentTime);
gainNode.gain.linearRampToValueAtTime(ev.gain, audioCtx.currentTime + FADE_TIME);
gainNode.gain.setTargetAtTime(0, audioCtx.currentTime + ev.duration - FADE_TIME, FADE_TIME);
} catch (e) {
console.warn("[GPTative] Audio param scheduling failed:", e);
}
// Schedule next note after current note duration
const id = setTimeout(playNext, ev.duration * 1000);
currentTimeouts.push(id);
}
isPlaying = true;
playNext();
}
/**
* Stops the current playback immediately and cleans all timeouts/audio nodes.
*/
function stopCurrentPlayback() {
if (!isPlaying) return;
clearAllTimeouts();
isPlaying = false;
stopOscillator();
}
// ============ Generation and Playback Control ============
/**
* Checks chat DOM to determine if bot is generating.
*/
function updateGeneratingState() {
// Query generation overlay elements from app UI indicators
const genOverlay = document.querySelector(".wrap.default.full.svelte-ls20lj.generating");
const currentlyGenerating = !!genOverlay;
if (currentlyGenerating !== isGenerating) {
isGenerating = currentlyGenerating;
console.log("[GPTative] Generating state updated:", isGenerating);
}
}
/**
* Checks for error state presence (optional).
*/
function updateErrorState() {
const errorStatus = document.querySelector(".clear-status.svelte-ls20lj .error");
const errorToast = document.querySelector(".toast-body.error.svelte-15qa81b");
const errorActive = !!errorStatus || !!errorToast;
if (errorActive !== isError) {
isError = errorActive;
console.log("[GPTative] Error state updated:", isError);
}
}
/**
* Main control loop that detects new sheets, manages playback lifecycle.
*/
async function controlLoop() {
updateGeneratingState();
updateErrorState();
if (isError) {
if (isPlaying) {
stopCurrentPlayback();
currentSheet = null;
}
return;
}
if (!isGenerating) {
if (isPlaying) {
stopCurrentPlayback();
currentSheet = null;
}
return;
}
// Extract current musical sheet from latest code blocks
const sheetText = extractStrictSheetFromCodeBlocks();
if (!sheetText) {
// No sheet found - stop playing if currently playing
if (isPlaying) {
stopCurrentPlayback();
currentSheet = null;
}
return;
}
// New sheet detected, play it
if (sheetText !== currentSheet) {
currentSheet = sheetText;
// Parse sheet into playable events
const events = parseSheet(sheetText);
if (isPlaying) {
stopCurrentPlayback();
}
// Make sure AudioContext resumed on user interaction
await ensureAudioCtxResumed();
if (events.length > 0) {
console.log(`[GPTative] Playing new sheet with ${events.length} events`);
playEvents(events);
} else {
console.warn("[GPTative] No playable note events found");
}
}
// else: same sheet playing, no action needed
}
// ============ Mutation Observer for Chat Updates ============
/**
* Set up mutation observer on chat container or fallback document.body
*/
function setupMutationObserver() {
// The main chat container selector (adjust if UI changes)
const chatContainerSelector = ".bubble-wrap.svelte-gjtrl6";
const chatWrap = document.querySelector(chatContainerSelector);
const observerTarget = chatWrap || document.body;
const mutationObserver = new MutationObserver(() => {
// Debounce control loop calls
if (controlLoopTimeout) clearTimeout(controlLoopTimeout);
controlLoopTimeout = setTimeout(controlLoop, 150);
});
mutationObserver.observe(observerTarget, {
childList: true,
subtree: true,
attributes: true,
attributeFilter: ["class", "style"]
});
}
let controlLoopTimeout = null;
// ============ Initialization ============
/**
* Registers user interaction to resume AudioContext (due to browser autoplay policy)
*/
function setupUserInteractionForAudio() {
window.addEventListener("click", async () => {
if (audioCtx && audioCtx.state === "suspended") {
try {
await audioCtx.resume();
console.log("[GPTative] AudioContext resumed via user gesture");
} catch (e) {
console.warn("[GPTative] Failed to resume AudioContext on user interaction", e);
}
}
}, { once: true }); // only once needed
}
/**
* Start all observers and polling
*/
function startController() {
setupMutationObserver();
setupUserInteractionForAudio();
// Fallback polling in case mutation observer misses something
setInterval(controlLoop, 1500);
console.log("[GPTative] Synthesizer userscript initialized and running.");
}
// Run initialization now
startController();
})();
// ==UserScript==
// @name GPTative Synthesizer - Strict Code Block Sheet Parser - Fixed & Enhanced - Full Sheet Play After Generation Complete
// @version 3.2
// @description Parses strictly formatted musical sheets inside markdown code blocks and plays them ONLY after full sheet is fully generated (wrapped by BEGIN and END tags). Respects autoplay policies and robustly handles generation state and prevents playing partial streaming content.
// @match *://yuntian-deng-chatgpt.hf.space/*
// @grant none
// @run-at document-idle
// ==/UserScript==
(() => {
"use strict";
// ============ Constants & Config ============
const BEGIN_TAG = "[BEGIN MUSICAL SHEET]";
const END_TAG = "[END MUSICAL SHEET]";
// Audio / Playback parameters
const TEMPO_BPM = 90;
const BEAT_DURATION = 60 / TEMPO_BPM; // in seconds
const FADE_TIME = 0.035; // seconds for smooth fade-in/out of notes
const REST_SYMBOL = "∅";
// Base frequency for A4 tuning (standard 440Hz or alternative 432Hz)
const BASE_A4_FREQ = 432;
// Mapping rhythmic durations symbols to seconds
const DURATION_MAP = {
"♩": 1 * BEAT_DURATION, // quarter note
"♪": 0.5 * BEAT_DURATION, // eighth note
"♬": 0.25 * BEAT_DURATION // sixteenth note
};
// Dynamics (volume multipliers)
const DYNAMICS = {
pp: 0.2,
p: 0.4,
mp: 0.6,
mf: 0.75,
f: 1.0,
ff: 1.3
};
// Note name to semitone offset from A (A = 0)
const NOTE_SEMITONE_OFFSETS = {
"C": -9,
"C#": -8, "Db": -8,
"D": -7,
"D#": -6, "Eb": -6,
"E": -5,
"F": -4,
"F#": -3, "Gb": -3,
"G": -2,
"G#": -1, "Ab": -1,
"A": 0,
"A#": 1, "Bb": 1,
"B": 2
};
// ============ State Variables ============
let isGenerating = false; // true when bot is generating
let isError = false; // true if error detected in chat
let isPlaying = false; // true when playback active
let bufferedSheet = null; // text content of the currently buffered full sheet
let lastPlayedSheet = null; // text content of last fully played sheet
// Audio API nodes & management
let audioCtx = null;
let osc = null;
let gainNode = null;
let vibratoLFO = null;
let currentTimeouts = [];
/**
* Clear all scheduled timeouts for playing notes.
*/
function clearAllTimeouts() {
currentTimeouts.forEach(id => clearTimeout(id));
currentTimeouts = [];
}
// ============ Audio Context Init ============
function initAudioCtx() {
if (!audioCtx) {
const AudioContextClass = window.AudioContext || window.webkitAudioContext;
audioCtx = new AudioContextClass();
}
}
/**
* Ensures AudioContext is resumed (required for autoplay policy).
* Returns a Promise.
*/
async function ensureAudioCtxResumed() {
initAudioCtx();
if (audioCtx.state === "suspended") {
try {
await audioCtx.resume();
console.log("[GPTative] AudioContext resumed");
} catch (e) {
console.warn("[GPTative] AudioContext resume failed:", e);
}
}
}
// ============ Utility Functions ============
/**
* Converts note string to frequency in Hz.
* @param {string} noteName Example: C, D#, Gb...
* @param {number} octave Octave number (default 4 if missing)
* @returns {number} frequency in Hz
*/
function noteToFrequency(noteName, octave = 4) {
let semitoneOffset = NOTE_SEMITONE_OFFSETS[noteName];
if (semitoneOffset === undefined) return null;
let semitonesFromA4 = semitoneOffset + (octave - 4) * 12;
return BASE_A4_FREQ * Math.pow(2, semitonesFromA4 / 12);
}
/**
* Parses a single token representing a note with optional octave, duration, dynamic.
* Format example: C4♩[mf]
* @param {string} token
* @returns {object|null} Parsed note event or null if invalid
*/
function parseNoteToken(token) {
// Regex breakdown:
// 1: note letter A-G or a-g
// 2: optional accidental #, ♯, b, ♭
// 3: optional octave digit (0-9)
// 4: duration symbol one of ♩♪♬
// 5: optional dynamics inside square brackets [mf], [pp], etc.
const re = /^([A-Ga-g])([#♯b♭]?)(\d?)([♩♪♬])(\[(pp|p|mp|mf|f|ff)\])?$/;
const match = token.match(re);
if (!match) return null;
let [, note, accidental, octaveStr, durationSym, , dynamics] = match;
note = note.toUpperCase();
// Normalize accidentals to sharps or flats as standard
if (accidental === "♯") accidental = "#";
if (accidental === "♭") accidental = "b";
let noteName = note + (accidental || "");
let octave = octaveStr !== "" ? parseInt(octaveStr, 10) : 4;
let duration = durationSym;
let dynamic = dynamics ? dynamics.toLowerCase() : "mf";
if (!(noteName in NOTE_SEMITONE_OFFSETS)) {
console.warn(`[GPTative] Invalid note name: ${noteName}`);
return null;
}
if (!(dynamic in DYNAMICS)) {
console.warn(`[GPTative] Unknown dynamic: ${dynamic}, defaulting to mf`);
dynamic = "mf";
}
return {
noteName,
octave,
duration,
dynamic
};
}
/**
* Sanitizes and splits a line of music tokens into discrete tokens,
* properly handling rests, measures, and multiple tokens separated by spaces.
* @param {string} line
* @returns {string[]} tokens
*/
function sanitizeAndSplitTokens(line) {
// Remove unwanted symbols, replace "Rest" by rest symbol ∅
line = line.replace(/[𝄞𝄢𝄫𝄫]/g, " "); // Common musical symbols to spaces
line = line.replace(/Rest/gi, REST_SYMBOL);
// Normalize multiple whitespaces
line = line.replace(/\s+/g, " ").trim();
// Insert spaces around measure bar (|) to separate tokens correctly
line = line.replace(/\|/g, " | ");
// Split on spaces
const rawTokens = line.split(" ").filter(t => t.length > 0);
const tokens = [];
rawTokens.forEach(token => {
if (token === "|") {
tokens.push(token);
return;
}
if (token === REST_SYMBOL || token === `${REST_SYMBOL}♩` || token === `${REST_SYMBOL}♪` || token === `${REST_SYMBOL}♬`) {
// Normalize rest duration symbol if any
if(token.length === 1) tokens.push(REST_SYMBOL);
else tokens.push(token);
return;
}
// Notes tokens - there may be compound tokens stuck together, try to extract all matches
// Examples: C4♩[mf], D#5♪, E♬, F4♩, etc.
const noteRegex = /([A-Ga-g][#♯b♭]?\d?[♩♪♬](\[(pp|p|mp|mf|f|ff)\])?)/g;
let m;
while ((m = noteRegex.exec(token)) !== null) {
tokens.push(m[1]);
}
});
return tokens;
}
// ============ Sheet Extraction (Full Sheet Only) ============
/**
* Extracts the latest full musical sheet strictly contained inside
* a markdown code block with required BEGIN and END tags.
* It returns the sheet content only if both BEGIN and END tags exist,
* ensuring full sheet is available (not partial streaming content).
* Scans code blocks from newest to oldest.
* @returns {string|null} extracted full sheet or null if none found
*/
function extractFullyWrappedSheetFromCodeBlocks() {
// Select all <pre> and <code> blocks (where code blocks content usually live)
// Since chat apps render code blocks in various ways, both tags considered
const codeBlocks = Array.from(document.querySelectorAll("pre, code"));
for (let i = codeBlocks.length - 1; i >= 0; i--) {
const block = codeBlocks[i];
if (!block.textContent) continue;
const text = block.textContent;
// Checks: there must be exactly one BEGIN and one END tag and in order
const beginIdx = text.indexOf(BEGIN_TAG);
const endIdx = text.indexOf(END_TAG);
// We require END tag after BEGIN tag, no partial sheet
if (beginIdx !== -1 && endIdx !== -1 && endIdx > beginIdx) {
const sheet = text.substring(beginIdx + BEGIN_TAG.length, endIdx).trim();
if (sheet.length > 0) {
return sheet;
}
}
}
return null;
}
// ============ Parsing Sheet to Events ============
/**
* Parses a full musical sheet string into an array of events for playback.
* @param {string} sheetText Raw musical sheet content between BEGIN and END tags
* @returns {Array<{time:number, freq:number|null, duration:number, gain:number}>} Array of note/rest events
*/
function parseSheet(sheetText) {
// Split into lines, exclude metadata lines (lines with colon ':')
const allLines = sheetText.split("\n").map(l => l.trim());
// Extract musical content lines only (exclude metadata lines)
let musicLines = allLines.filter(line => line.length > 0 && !line.includes(":"));
// Accumulate tokens from all music lines
const tokens = [];
musicLines.forEach(line => {
tokens.push(...sanitizeAndSplitTokens(line));
});
// Parse tokens into note/rest events with timing and gain
let currentTime = 0;
let currentDynamic = "mf"; // Default dynamic
const events = [];
for (const token of tokens) {
if (token === "|") {
// Measure bar - no time increment, optional place for alignment if needed
continue;
}
// Change dynamic if token is only dynamic marker, e.g. [mf]
const dynMatch = token.match(/^\[(pp|p|mp|mf|f|ff)\]$/i);
if (dynMatch) {
currentDynamic = dynMatch[1].toLowerCase();
continue;
}
// Rest token
if (token === REST_SYMBOL || token.startsWith(REST_SYMBOL)) {
// Determine duration from rest token suffix if any eg. '∅♩' means quarter rest
let restDur = BEAT_DURATION;
const durSymMatch = token.match(/[♩♪♬]/);
if (durSymMatch) {
restDur = DURATION_MAP[durSymMatch[0]] || BEAT_DURATION;
}
events.push({
time: currentTime,
freq: null,
duration: restDur,
gain: 0
});
currentTime += restDur;
continue;
}
// Otherwise, parse note token
const noteInfo = parseNoteToken(token);
if (!noteInfo) {
console.warn("[GPTative] Skipping invalid token:", token);
continue;
}
// Calculate frequency from note info
const freq = noteToFrequency(noteInfo.noteName, noteInfo.octave);
if (!freq || freq <= 0 || !isFinite(freq)) {
console.warn("[GPTative] Invalid frequency for token:", token);
continue;
}
// Map duration symbol to seconds
const dur = DURATION_MAP[noteInfo.duration] || BEAT_DURATION;
// Map dynamic to gain multiplier
const gainVal = DYNAMICS[noteInfo.dynamic] || DYNAMICS[currentDynamic] || 0.75;
// Create event
events.push({
time: currentTime,
freq,
duration: dur,
gain: gainVal
});
currentTime += dur;
}
return events;
}
// ============ Playback Engine ============
/**
* Initializes oscillator, gain and vibrato
* and connects to audio destination.
*/
function initOscillator() {
if (!audioCtx) initAudioCtx();
if (osc) return; // already created
osc = audioCtx.createOscillator();
gainNode = audioCtx.createGain();
gainNode.gain.value = 0;
// Vibrato LFO (5Hz vibrato with ±10Hz freq modulation)
vibratoLFO = audioCtx.createOscillator();
vibratoLFO.frequency.value = 5; // 5Hz vibrato rate
const vibratoGain = audioCtx.createGain();
vibratoGain.gain.value = 10; // ±10 Hz vibrato depth
// Connect vibrato: vibratoLFO -> vibratoGain -> osc.frequency
vibratoLFO.connect(vibratoGain);
vibratoGain.connect(osc.frequency);
osc.type = "triangle";
osc.connect(gainNode);
gainNode.connect(audioCtx.destination);
osc.start();
vibratoLFO.start();
console.log("[GPTative] Oscillator & vibrato initialized and started");
}
/**
* Stops and disposes oscillator and gain nodes gracefully
*/
function stopOscillator() {
if (!osc) return;
// Fade out gain smoothly before stopping
gainNode.gain.cancelScheduledValues(audioCtx.currentTime);
gainNode.gain.setTargetAtTime(0, audioCtx.currentTime, FADE_TIME);
// Stop oscillators after fade time
setTimeout(() => {
try {
osc.stop();
vibratoLFO.stop();
} catch (_) {}
osc.disconnect();
gainNode.disconnect();
vibratoLFO.disconnect();
osc = null;
gainNode = null;
vibratoLFO = null;
console.log("[GPTative] Oscillator & vibrato stopped and cleaned up");
}, FADE_TIME * 1000);
}
/**
* Plays given note/rest events sequentially.
* Uses scheduled timeouts for note timing.
* @param {Array} events - Array of {time, freq, duration, gain}
*/
function playEvents(events) {
if (!events.length) return;
initOscillator();
let currIndex = 0;
/**
* Plays a single event at index currIndex
*/
function playNext() {
if (currIndex >= events.length) {
isPlaying = false;
stopOscillator();
return;
}
const ev = events[currIndex++];
if (ev.freq === null) {
// Rest: fade gain to zero (if not already)
if (gainNode) {
gainNode.gain.cancelScheduledValues(audioCtx.currentTime);
gainNode.gain.setTargetAtTime(0, audioCtx.currentTime, FADE_TIME);
}
// Schedule next note after rest duration
const id = setTimeout(playNext, ev.duration * 1000);
currentTimeouts.push(id);
return;
}
// Play note frequency with gain and fades
try {
osc.frequency.setTargetAtTime(ev.freq, audioCtx.currentTime, 0.01);
gainNode.gain.cancelScheduledValues(audioCtx.currentTime);
gainNode.gain.setValueAtTime(0, audioCtx.currentTime);
gainNode.gain.linearRampToValueAtTime(ev.gain, audioCtx.currentTime + FADE_TIME);
gainNode.gain.setTargetAtTime(0, audioCtx.currentTime + ev.duration - FADE_TIME, FADE_TIME);
} catch (e) {
console.warn("[GPTative] Audio param scheduling failed:", e);
}
// Schedule next note after current note duration
const id = setTimeout(playNext, ev.duration * 1000);
currentTimeouts.push(id);
}
isPlaying = true;
playNext();
}
/**
* Stops the current playback immediately and cleans all timeouts/audio nodes.
*/
function stopCurrentPlayback() {
if (!isPlaying) return;
clearAllTimeouts();
isPlaying = false;
stopOscillator();
}
// ============ Generation and Playback Control ============
/**
* Checks chat DOM to determine if bot is generating.
*/
function updateGeneratingState() {
// Query generation overlay elements from app UI indicators
// Heuristic: presence of spinner, overlay, or other generating indication
const genOverlay = document.querySelector(".wrap.default.full.svelte-ls20lj.generating");
const currentlyGenerating = !!genOverlay;
if (currentlyGenerating !== isGenerating) {
isGenerating = currentlyGenerating;
console.log("[GPTative] Generating state updated:", isGenerating);
}
}
/**
* Checks for error state presence (optional).
*/
function updateErrorState() {
const errorStatus = document.querySelector(".clear-status.svelte-ls20lj .error");
const errorToast = document.querySelector(".toast-body.error.svelte-15qa81b");
const errorActive = !!errorStatus || !!errorToast;
if (errorActive !== isError) {
isError = errorActive;
console.log("[GPTative] Error state updated:", isError);
}
}
/**
* Core control loop that:
* - Waits for generation to finish
* - Only after generation ends searches for fully wrapped musical sheet
* - Plays sheet only if full and not already played
*/
async function controlLoop() {
updateGeneratingState();
updateErrorState();
if (isError) {
if (isPlaying) {
stopCurrentPlayback();
bufferedSheet = null;
lastPlayedSheet = null;
}
return;
}
// Wait and do NOT play while generation is ongoing
if (isGenerating) {
// Clear any buffered sheet while generating (to avoid partial data)
bufferedSheet = null;
return;
}
// Now generation is NOT ongoing => we assume full message is available
// Extract full sheet only if fully wrapped
const sheetText = extractFullyWrappedSheetFromCodeBlocks();
if (!sheetText) {
// No full sheet found, stop playing if playing and clear buffered state
if (isPlaying) {
stopCurrentPlayback();
}
bufferedSheet = null;
lastPlayedSheet = null;
return;
}
// If the sheet is fully different from last played, buffer it for play
if (sheetText !== lastPlayedSheet) {
// Buffer the new full sheet, to avoid playing partial updates
if (sheetText !== bufferedSheet) {
bufferedSheet = sheetText;
return; // Wait for next run for stable sheet (double-check no regeneration)
}
// bufferedSheet equals sheetText means stable full sheet after generation ended
// Proceed to parse and play the sheet
// Parse sheet into playable events
const events = parseSheet(bufferedSheet);
if (isPlaying) {
stopCurrentPlayback();
}
// Ensure AudioContext resumed on user interaction
await ensureAudioCtxResumed();
if (events.length > 0) {
console.log(`[GPTative] Playing new fully received sheet with ${events.length} events`);
playEvents(events);
lastPlayedSheet = bufferedSheet;
bufferedSheet = null; // clear buffer after play start
} else {
console.warn("[GPTative] No playable note events found");
// Reset states if no events can play
lastPlayedSheet = null;
bufferedSheet = null;
}
}
// else: sheetText === lastPlayedSheet; already playing or played; do nothing
}
// ============ Mutation Observer for Chat Updates ============
/**
* Set up mutation observer on chat container or fallback document.body
*/
function setupMutationObserver() {
// The main chat container selector (adjust if UI changes)
const chatContainerSelector = ".bubble-wrap.svelte-gjtrl6";
const chatWrap = document.querySelector(chatContainerSelector);
const observerTarget = chatWrap || document.body;
const mutationObserver = new MutationObserver(() => {
// Debounce control loop calls
if (controlLoopTimeout) clearTimeout(controlLoopTimeout);
controlLoopTimeout = setTimeout(controlLoop, 250);
});
mutationObserver.observe(observerTarget, {
childList: true,
subtree: true,
attributes: true,
attributeFilter: ["class", "style"]
});
}
let controlLoopTimeout = null;
// ============ Initialization ============
/**
* Registers user interaction to resume AudioContext (due to browser autoplay policy)
*/
function setupUserInteractionForAudio() {
// Only need once, before first playback attempt
window.addEventListener("click", async () => {
if (audioCtx && audioCtx.state === "suspended") {
try {
await audioCtx.resume();
console.log("[GPTative] AudioContext resumed via user gesture");
} catch (e) {
console.warn("[GPTative] Failed to resume AudioContext on user interaction", e);
}
}
}, { once: true }); // only once needed
}
/**
* Start all observers and polling
*/
function startController() {
setupMutationObserver();
setupUserInteractionForAudio();
// Fallback polling in case mutation observer misses something
setInterval(controlLoop, 1500);
console.log("[GPTative] Synthesizer userscript (full sheet play after generation) initialized and running.");
}
// Run initialization now
startController();
})();