diff --git a/editor/src/I18nManager.js b/editor/src/I18nManager.js index a6b2de3f..547c1646 100644 --- a/editor/src/I18nManager.js +++ b/editor/src/I18nManager.js @@ -20147,6 +20147,25 @@ Object.assign(RR_TEXT_TRANSLATIONS['id'], { "How long this track rises from sile Object.assign(RR_TEXT_TRANSLATIONS['vi'], { "How long this track rises from silence as it starts.": "Thời gian bản nhạc này lớn dần từ im lặng khi bắt đầu.", "How long this track fades away, and how early the next entry starts under it. 0 plays it to its end.": "Thời gian bản nhạc này nhỏ dần, và mục tiếp theo bắt đầu sớm bao lâu bên dưới nó. 0 phát đến hết.", "How long each track rises from silence as it starts.": "Thời gian mỗi bản nhạc lớn dần từ im lặng khi bắt đầu.", "How long each track fades away, and how early the next one starts under it. 0 plays every track to its end.": "Thời gian mỗi bản nhạc nhỏ dần, và bản tiếp theo bắt đầu sớm bao lâu bên dưới nó. 0 phát mỗi bản đến hết.", "A fade-out starts what follows early, under the ending track; a fade-in lets the new one rise.": "Nhỏ dần cho phần tiếp theo bắt đầu sớm dưới bản đang kết thúc; lớn dần để âm thanh mới dâng lên." }); Object.assign(RR_TEXT_TRANSLATIONS['th'], { "How long this track rises from silence as it starts.": "ระยะเวลาที่แทร็กนี้ค่อยๆ ดังขึ้นจากความเงียบเมื่อเริ่ม", "How long this track fades away, and how early the next entry starts under it. 0 plays it to its end.": "ระยะเวลาที่แทร็กนี้ค่อยๆ เบาลง และรายการถัดไปเริ่มก่อนใต้แทร็กนี้เร็วแค่ไหน 0 จะเล่นจนจบ", "How long each track rises from silence as it starts.": "ระยะเวลาที่แต่ละแทร็กค่อยๆ ดังขึ้นจากความเงียบเมื่อเริ่ม", "How long each track fades away, and how early the next one starts under it. 0 plays every track to its end.": "ระยะเวลาที่แต่ละแทร็กค่อยๆ เบาลง และแทร็กถัดไปเริ่มก่อนใต้แทร็กนั้นเร็วแค่ไหน 0 จะเล่นทุกแทร็กจนจบ", "A fade-out starts what follows early, under the ending track; a fade-in lets the new one rise.": "การเฟดออกทำให้ส่วนถัดไปเริ่มก่อนใต้แทร็กที่กำลังจบ ส่วนการเฟดอินให้เสียงใหม่ค่อยๆ ดังขึ้น" }); +// BGM sequence palette pools: a track's own tail, an entry's draw weight, and +// a layer that may repeat. A machine-assisted first pass; worth a native review. +Object.assign(RR_TEXT_TRANSLATIONS['ja'], { "Draw weight": "抽選の重み", "This entry’s share of a random draw against the rest of the pool. 2 is drawn twice as often as 1; 0 is never drawn. Random order only.": "プール内の他の項目に対する、ランダム抽選でのこの項目の割合です。2 は 1 の2倍選ばれ、0 は選ばれません。順序がランダムのときのみ有効です。", "Tail (s)": "テール(秒)", "How many seconds before this track ends the next draw starts, this one fading away under it. Empty uses the palette’s fade-out; 0 plays it to its end.": "このトラックが終わる何秒前に次の抽選を開始し、その下でこのトラックをフェードアウトさせるかです。空欄ならパレットのフェードアウトを使い、0 なら最後まで再生します。", "Allow repeats": "繰り返しを許可", "A random draw may pick the entry that just played. Random order only.": "ランダム抽選で、直前に再生した項目を選べるようにします。順序がランダムのときのみ有効です。" }); +Object.assign(RR_TEXT_TRANSLATIONS['zh-Hant'], { "Draw weight": "抽選權重", "This entry’s share of a random draw against the rest of the pool. 2 is drawn twice as often as 1; 0 is never drawn. Random order only.": "此項目在隨機抽選中相對於池中其他項目的比重。2 被抽中的機率是 1 的兩倍;0 永不被抽中。僅適用於隨機順序。", "Tail (s)": "尾段(秒)", "How many seconds before this track ends the next draw starts, this one fading away under it. Empty uses the palette’s fade-out; 0 plays it to its end.": "在此曲目結束前幾秒開始下一次抽選,並讓此曲目在其下淡出。留空則使用調色盤的淡出;0 則播放到結尾。", "Allow repeats": "允許重複", "A random draw may pick the entry that just played. Random order only.": "隨機抽選可以選到剛播放過的項目。僅適用於隨機順序。" }); +Object.assign(RR_TEXT_TRANSLATIONS['zh-Hans'], { "Draw weight": "抽选权重", "This entry’s share of a random draw against the rest of the pool. 2 is drawn twice as often as 1; 0 is never drawn. Random order only.": "此项目在随机抽选中相对于池中其他项目的比重。2 被抽中的概率是 1 的两倍;0 永不被抽中。仅适用于随机顺序。", "Tail (s)": "尾段(秒)", "How many seconds before this track ends the next draw starts, this one fading away under it. Empty uses the palette’s fade-out; 0 plays it to its end.": "在此曲目结束前几秒开始下一次抽选,并让此曲目在其下淡出。留空则使用调色板的淡出;0 则播放到结尾。", "Allow repeats": "允许重复", "A random draw may pick the entry that just played. Random order only.": "随机抽选可以选到刚播放过的项目。仅适用于随机顺序。" }); +Object.assign(RR_TEXT_TRANSLATIONS['ko'], { "Draw weight": "추첨 가중치", "This entry’s share of a random draw against the rest of the pool. 2 is drawn twice as often as 1; 0 is never drawn. Random order only.": "풀의 다른 항목에 대한 이 항목의 무작위 추첨 비중입니다. 2는 1보다 두 배 자주 뽑히고, 0은 뽑히지 않습니다. 순서가 무작위일 때만 적용됩니다.", "Tail (s)": "테일(초)", "How many seconds before this track ends the next draw starts, this one fading away under it. Empty uses the palette’s fade-out; 0 plays it to its end.": "이 트랙이 끝나기 몇 초 전에 다음 추첨을 시작하고, 그 아래에서 이 트랙을 페이드아웃할지 정합니다. 비워 두면 팔레트의 페이드아웃을 쓰고, 0이면 끝까지 재생합니다.", "Allow repeats": "반복 허용", "A random draw may pick the entry that just played. Random order only.": "무작위 추첨이 방금 재생한 항목을 고를 수 있습니다. 순서가 무작위일 때만 적용됩니다." }); +Object.assign(RR_TEXT_TRANSLATIONS['es'], { "Draw weight": "Peso de sorteo", "This entry’s share of a random draw against the rest of the pool. 2 is drawn twice as often as 1; 0 is never drawn. Random order only.": "La parte de esta entrada en un sorteo aleatorio frente al resto del grupo. 2 sale el doble que 1; 0 nunca sale. Solo con orden aleatorio.", "Tail (s)": "Cola (s)", "How many seconds before this track ends the next draw starts, this one fading away under it. Empty uses the palette’s fade-out; 0 plays it to its end.": "Cuántos segundos antes de que termine esta pista empieza el siguiente sorteo, mientras esta se desvanece por debajo. Vacío usa el fundido de la paleta; 0 la reproduce hasta el final.", "Allow repeats": "Permitir repeticiones", "A random draw may pick the entry that just played. Random order only.": "Un sorteo aleatorio puede elegir la entrada que acaba de sonar. Solo con orden aleatorio." }); +Object.assign(RR_TEXT_TRANSLATIONS['pt'], { "Draw weight": "Peso do sorteio", "This entry’s share of a random draw against the rest of the pool. 2 is drawn twice as often as 1; 0 is never drawn. Random order only.": "A parte desta entrada num sorteio aleatório em relação ao resto do conjunto. 2 sai duas vezes mais que 1; 0 nunca sai. Apenas na ordem aleatória.", "Tail (s)": "Cauda (s)", "How many seconds before this track ends the next draw starts, this one fading away under it. Empty uses the palette’s fade-out; 0 plays it to its end.": "Quantos segundos antes do fim desta faixa começa o próximo sorteio, com esta a desvanecer por baixo. Vazio usa o fade-out da paleta; 0 toca-a até ao fim.", "Allow repeats": "Permitir repetições", "A random draw may pick the entry that just played. Random order only.": "Um sorteio aleatório pode escolher a entrada que acabou de tocar. Apenas na ordem aleatória." }); +Object.assign(RR_TEXT_TRANSLATIONS['fr'], { "Draw weight": "Poids de tirage", "This entry’s share of a random draw against the rest of the pool. 2 is drawn twice as often as 1; 0 is never drawn. Random order only.": "La part de cette entrée dans un tirage aléatoire face au reste du groupe. 2 est tiré deux fois plus souvent que 1 ; 0 n’est jamais tiré. Ordre aléatoire uniquement.", "Tail (s)": "Traîne (s)", "How many seconds before this track ends the next draw starts, this one fading away under it. Empty uses the palette’s fade-out; 0 plays it to its end.": "Combien de secondes avant la fin de cette piste le tirage suivant commence, celle-ci s’estompant en dessous. Vide utilise le fondu de la palette ; 0 la joue jusqu’au bout.", "Allow repeats": "Autoriser les répétitions", "A random draw may pick the entry that just played. Random order only.": "Un tirage aléatoire peut choisir l’entrée qui vient de jouer. Ordre aléatoire uniquement." }); +Object.assign(RR_TEXT_TRANSLATIONS['it'], { "Draw weight": "Peso di estrazione", "This entry’s share of a random draw against the rest of the pool. 2 is drawn twice as often as 1; 0 is never drawn. Random order only.": "La quota di questa voce in un’estrazione casuale rispetto al resto del gruppo. 2 esce il doppio di 1; 0 non esce mai. Solo con ordine casuale.", "Tail (s)": "Coda (s)", "How many seconds before this track ends the next draw starts, this one fading away under it. Empty uses the palette’s fade-out; 0 plays it to its end.": "Quanti secondi prima della fine di questa traccia parte l’estrazione successiva, mentre questa sfuma sotto. Vuoto usa la dissolvenza della tavolozza; 0 la suona fino alla fine.", "Allow repeats": "Consenti ripetizioni", "A random draw may pick the entry that just played. Random order only.": "Un’estrazione casuale può scegliere la voce appena suonata. Solo con ordine casuale." }); +Object.assign(RR_TEXT_TRANSLATIONS['de'], { "Draw weight": "Ziehungsgewicht", "This entry’s share of a random draw against the rest of the pool. 2 is drawn twice as often as 1; 0 is never drawn. Random order only.": "Der Anteil dieses Eintrags an einer Zufallsziehung gegenüber dem Rest des Pools. 2 wird doppelt so oft gezogen wie 1; 0 nie. Nur bei zufälliger Reihenfolge.", "Tail (s)": "Ausklang (s)", "How many seconds before this track ends the next draw starts, this one fading away under it. Empty uses the palette’s fade-out; 0 plays it to its end.": "Wie viele Sekunden vor dem Ende dieses Titels die nächste Ziehung beginnt, während dieser darunter ausblendet. Leer nutzt das Ausblenden der Palette; 0 spielt ihn bis zum Ende.", "Allow repeats": "Wiederholungen erlauben", "A random draw may pick the entry that just played. Random order only.": "Eine Zufallsziehung darf den Eintrag wählen, der gerade lief. Nur bei zufälliger Reihenfolge." }); +Object.assign(RR_TEXT_TRANSLATIONS['ru'], { "Draw weight": "Вес выбора", "This entry’s share of a random draw against the rest of the pool. 2 is drawn twice as often as 1; 0 is never drawn. Random order only.": "Доля этой записи при случайном выборе относительно остального набора. 2 выпадает вдвое чаще, чем 1; 0 не выпадает никогда. Только при случайном порядке.", "Tail (s)": "Хвост (с)", "How many seconds before this track ends the next draw starts, this one fading away under it. Empty uses the palette’s fade-out; 0 plays it to its end.": "За сколько секунд до конца этого трека начинается следующий выбор, а этот затухает под ним. Пусто — затухание палитры; 0 — играть до конца.", "Allow repeats": "Разрешить повторы", "A random draw may pick the entry that just played. Random order only.": "Случайный выбор может взять запись, которая только что звучала. Только при случайном порядке." }); +Object.assign(RR_TEXT_TRANSLATIONS['pl'], { "Draw weight": "Waga losowania", "This entry’s share of a random draw against the rest of the pool. 2 is drawn twice as often as 1; 0 is never drawn. Random order only.": "Udział tej pozycji w losowaniu względem reszty puli. 2 wypada dwa razy częściej niż 1; 0 nigdy. Tylko przy losowej kolejności.", "Tail (s)": "Ogon (s)", "How many seconds before this track ends the next draw starts, this one fading away under it. Empty uses the palette’s fade-out; 0 plays it to its end.": "Ile sekund przed końcem tego utworu zaczyna się następne losowanie, a ten wycisza się pod nim. Puste używa wyciszenia palety; 0 gra go do końca.", "Allow repeats": "Zezwalaj na powtórzenia", "A random draw may pick the entry that just played. Random order only.": "Losowanie może wybrać pozycję, która właśnie grała. Tylko przy losowej kolejności." }); +Object.assign(RR_TEXT_TRANSLATIONS['el'], { "Draw weight": "Βάρος κλήρωσης", "This entry’s share of a random draw against the rest of the pool. 2 is drawn twice as often as 1; 0 is never drawn. Random order only.": "Το μερίδιο αυτής της καταχώρισης σε μια τυχαία κλήρωση έναντι της υπόλοιπης ομάδας. Το 2 βγαίνει διπλάσιες φορές από το 1· το 0 δεν βγαίνει ποτέ. Μόνο με τυχαία σειρά.", "Tail (s)": "Ουρά (δ)", "How many seconds before this track ends the next draw starts, this one fading away under it. Empty uses the palette’s fade-out; 0 plays it to its end.": "Πόσα δευτερόλεπτα πριν τελειώσει αυτό το κομμάτι ξεκινά η επόμενη κλήρωση, ενώ αυτό σβήνει από κάτω. Κενό χρησιμοποιεί το σβήσιμο της παλέτας· το 0 το παίζει ως το τέλος.", "Allow repeats": "Να επιτρέπονται επαναλήψεις", "A random draw may pick the entry that just played. Random order only.": "Μια τυχαία κλήρωση μπορεί να επιλέξει την καταχώριση που μόλις έπαιξε. Μόνο με τυχαία σειρά." }); +Object.assign(RR_TEXT_TRANSLATIONS['tr'], { "Draw weight": "Çekiliş ağırlığı", "This entry’s share of a random draw against the rest of the pool. 2 is drawn twice as often as 1; 0 is never drawn. Random order only.": "Bu girdinin rastgele çekilişte havuzun geri kalanına göre payı. 2, 1’in iki katı sık çıkar; 0 hiç çıkmaz. Yalnızca rastgele sırada.", "Tail (s)": "Kuyruk (sn)", "How many seconds before this track ends the next draw starts, this one fading away under it. Empty uses the palette’s fade-out; 0 plays it to its end.": "Bu parça bitmeden kaç saniye önce sonraki çekilişin başlayacağı ve bunun altında sönümleneceği. Boş, paletin sönümlemesini kullanır; 0 sonuna kadar çalar.", "Allow repeats": "Tekrara izin ver", "A random draw may pick the entry that just played. Random order only.": "Rastgele çekiliş az önce çalan girdiyi seçebilir. Yalnızca rastgele sırada." }); +Object.assign(RR_TEXT_TRANSLATIONS['ar'], { "Draw weight": "وزن السحب", "This entry’s share of a random draw against the rest of the pool. 2 is drawn twice as often as 1; 0 is never drawn. Random order only.": "حصة هذا العنصر في السحب العشوائي مقارنة ببقية المجموعة. 2 يُسحب ضعف 1؛ و0 لا يُسحب أبدًا. في الترتيب العشوائي فقط.", "Tail (s)": "الذيل (ث)", "How many seconds before this track ends the next draw starts, this one fading away under it. Empty uses the palette’s fade-out; 0 plays it to its end.": "كم ثانية قبل نهاية هذا المقطع يبدأ السحب التالي، بينما يتلاشى هذا المقطع تحته. الفراغ يستخدم تلاشي اللوحة؛ و0 يشغّله حتى نهايته.", "Allow repeats": "السماح بالتكرار", "A random draw may pick the entry that just played. Random order only.": "يمكن للسحب العشوائي اختيار العنصر الذي شُغّل للتو. في الترتيب العشوائي فقط." }); +Object.assign(RR_TEXT_TRANSLATIONS['id'], { "Draw weight": "Bobot undian", "This entry’s share of a random draw against the rest of the pool. 2 is drawn twice as often as 1; 0 is never drawn. Random order only.": "Bagian entri ini dalam undian acak dibanding sisa kumpulan. 2 terpilih dua kali lebih sering dari 1; 0 tidak pernah terpilih. Hanya untuk urutan acak.", "Tail (s)": "Ekor (dtk)", "How many seconds before this track ends the next draw starts, this one fading away under it. Empty uses the palette’s fade-out; 0 plays it to its end.": "Berapa detik sebelum trek ini berakhir undian berikutnya dimulai, sementara trek ini memudar di bawahnya. Kosong memakai fade-out palet; 0 memutarnya sampai akhir.", "Allow repeats": "Izinkan pengulangan", "A random draw may pick the entry that just played. Random order only.": "Undian acak boleh memilih entri yang baru saja diputar. Hanya untuk urutan acak." }); +Object.assign(RR_TEXT_TRANSLATIONS['vi'], { "Draw weight": "Trọng số bốc", "This entry’s share of a random draw against the rest of the pool. 2 is drawn twice as often as 1; 0 is never drawn. Random order only.": "Tỷ lệ của mục này trong lần bốc ngẫu nhiên so với phần còn lại của nhóm. 2 được bốc gấp đôi 1; 0 không bao giờ được bốc. Chỉ với thứ tự ngẫu nhiên.", "Tail (s)": "Đuôi (giây)", "How many seconds before this track ends the next draw starts, this one fading away under it. Empty uses the palette’s fade-out; 0 plays it to its end.": "Bao nhiêu giây trước khi bản nhạc này kết thúc thì lần bốc kế tiếp bắt đầu, còn bản này giảm dần bên dưới. Để trống dùng giảm dần của bảng phối; 0 phát đến hết.", "Allow repeats": "Cho phép lặp lại", "A random draw may pick the entry that just played. Random order only.": "Lần bốc ngẫu nhiên có thể chọn mục vừa phát. Chỉ với thứ tự ngẫu nhiên." }); +Object.assign(RR_TEXT_TRANSLATIONS['th'], { "Draw weight": "น้ำหนักการสุ่ม", "This entry’s share of a random draw against the rest of the pool. 2 is drawn twice as often as 1; 0 is never drawn. Random order only.": "สัดส่วนของรายการนี้ในการสุ่มเทียบกับรายการอื่นในกลุ่ม 2 ถูกสุ่มได้บ่อยเป็นสองเท่าของ 1 ส่วน 0 ไม่ถูกสุ่มเลย ใช้กับลำดับแบบสุ่มเท่านั้น", "Tail (s)": "หาง (วินาที)", "How many seconds before this track ends the next draw starts, this one fading away under it. Empty uses the palette’s fade-out; 0 plays it to its end.": "จำนวนวินาทีก่อนแทร็กนี้จบที่การสุ่มครั้งถัดไปจะเริ่ม โดยแทร็กนี้ค่อย ๆ เบาลงอยู่ข้างใต้ เว้นว่างไว้จะใช้เฟดเอาต์ของพาเลต ส่วน 0 จะเล่นจนจบ", "Allow repeats": "อนุญาตให้ซ้ำ", "A random draw may pick the entry that just played. Random order only.": "การสุ่มอาจเลือกรายการที่เพิ่งเล่นไปได้ ใช้กับลำดับแบบสุ่มเท่านั้น" }); // State slip elements (Database > States, General), and the Multi-Element // Rule shown beside them with Element Status Core. A machine-assisted first // pass; worth a native review. diff --git a/editor/src/utils/BgmSequenceEditor.js b/editor/src/utils/BgmSequenceEditor.js index f0a1e5ea..1ec48616 100644 --- a/editor/src/utils/BgmSequenceEditor.js +++ b/editor/src/utils/BgmSequenceEditor.js @@ -7,8 +7,11 @@ * Entries play in order and repeat: * { type: 'track', name, volume, pitch, pan, fadeIn } (any entry may set `once`) * { type: 'silence', duration } - * { type: 'palette', duration, fadeIn, fadeOut, single, layers: [{ volume, pitch, pan, order, pool }] } - * where a pool holds tracks (`{ type: 'track', name, volume }`) and silences. + * { type: 'palette', duration, fadeIn, fadeOut, single, layers: [{ volume, pitch, pan, order, repeats?, pool }] } + * where a pool holds tracks (`{ type: 'track', name, volume, tail?, weight? }`) + * and silences (`{ type: 'silence', duration, weight? }`). The optional keys are + * written only when they differ from what their absence means: no `tail` uses + * the palette's fade-out, no `weight` is 1, no `repeats` keeps the no-repeat draw. * * The model functions are static so a save can normalize and validate what * the form holds without the DOM; the instance renders one container and @@ -94,19 +97,46 @@ class RRBgmSequenceEditor { }; } + /** A pool item's share of a random draw, to two decimals; 1 when blank or unreadable. */ + static weight(value) { + if (value === null || value === undefined || value === '') return 1; + const parsed = Number(value); + if (!Number.isFinite(parsed) || parsed < 0) return 1; + return Math.min(1000, Math.round(parsed * 100) / 100); + } + + /** A pool track's own tail in seconds, or null for the palette's fade-out. 0 is a real value. */ + static tail(value) { + if (value === null || value === undefined || value === '') return null; + const parsed = Number(value); + if (!Number.isFinite(parsed) || parsed < 0) return null; + return Math.min(600, Math.round(parsed * 10) / 10); + } + static poolEntry(raw) { if (!raw || typeof raw !== 'object') return null; - if (raw.type === 'silence') return { type: 'silence', duration: RRBgmSequenceEditor.seconds(raw.duration) }; - return { type: 'track', name: typeof raw.name === 'string' ? raw.name : '', - volume: RRBgmSequenceEditor.number(raw.volume, 100, 0, 100) }; + let item; + if (raw.type === 'silence') { + item = { type: 'silence', duration: RRBgmSequenceEditor.seconds(raw.duration) }; + } else { + item = { type: 'track', name: typeof raw.name === 'string' ? raw.name : '', + volume: RRBgmSequenceEditor.number(raw.volume, 100, 0, 100) }; + const tail = RRBgmSequenceEditor.tail(raw.tail); + if (tail !== null) item.tail = tail; + } + const weight = RRBgmSequenceEditor.weight(raw.weight); + if (weight !== 1) item.weight = weight; + return item; } static layer(raw) { const source = raw && typeof raw === 'object' ? raw : {}; - return Object.assign(RRBgmSequenceEditor.levels(source), { - order: source.order === 'sequential' || source.order === 'shuffle' ? source.order : 'random', - pool: (Array.isArray(source.pool) ? source.pool : []).map(RRBgmSequenceEditor.poolEntry).filter(Boolean) + const layer = Object.assign(RRBgmSequenceEditor.levels(source), { + order: source.order === 'sequential' || source.order === 'shuffle' ? source.order : 'random' }); + if (source.repeats === true) layer.repeats = true; + layer.pool = (Array.isArray(source.pool) ? source.pool : []).map(RRBgmSequenceEditor.poolEntry).filter(Boolean); + return layer; } static entry(raw) { @@ -429,12 +459,23 @@ class RRBgmSequenceEditor { } const layers = entry.layers.map((layer, l) => { const lp = `${path}.layers.${l}`; + const weightField = (ip, item) => ``; const pool = layer.pool.map((item, i) => { const ip = `${lp}.pool.${i}`; - const body = item.type === 'silence' - ? `${this.escape(this.tt('Silence'))} ${this.numberInput(`${ip}.duration`, item.duration, 0, 3600, 0.5, 60)} ${this.escape(this.tt('s'))}` - : `${nameBox(ip, item.name, null)}`; - return `
${body}${this.smallButton('remove', ip, '×', this.tt('Remove'))}
`; + if (item.type === 'silence') { + return `
` + + `${this.escape(this.tt('Silence'))} ${this.numberInput(`${ip}.duration`, item.duration, 0, 3600, 0.5, 60)} ${this.escape(this.tt('s'))}` + + `${weightField(ip, item)}${this.smallButton('remove', ip, '×', this.tt('Remove'))}
`; + } + // The name needs the row's width, so the two draw settings take + // a line of their own under it, as a layer's controls do. + return `
+
${nameBox(ip, item.name, null)}${this.smallButton('remove', ip, '×', this.tt('Remove'))}
+
+ + ${weightField(ip, item)} +
+
`; }).join(''); // Four controls plus the remove button do not fit the column, the // same way the palette's timings did not: the title line keeps the @@ -450,6 +491,7 @@ class RRBgmSequenceEditor { + ${pool}
@@ -596,6 +638,21 @@ class RRBgmSequenceEditor { else if (key === 'pan') node[key] = RRBgmSequenceEditor.number(input.value, 0, -100, 100); else if (key === 'order') node[key] = input.value === 'sequential' || input.value === 'shuffle' ? input.value : 'random'; else if (key === 'once' || key === 'single') { node[key] = !!input.checked; this.edited(); return; } + else if (key === 'repeats') { + // Left off the layer when unticked, as normalize() writes it. + if (input.checked) node.repeats = true; + else delete node.repeats; + this.edited(); + return; + } else if (key === 'tail') { + // Empty is its own value -- the palette's fade-out -- and 0 is another. + const tail = RRBgmSequenceEditor.tail(input.value); + if (tail === null) delete node.tail; + else node.tail = tail; + input.value = tail === null ? '' : tail; + this.edited(); + return; + } else if (key === 'weight') node[key] = RRBgmSequenceEditor.weight(input.value); input.value = node[key]; this.edited(); } diff --git a/editor/tests/bgm-palette-clock.test.cjs b/editor/tests/bgm-palette-clock.test.cjs new file mode 100644 index 00000000..302caf93 --- /dev/null +++ b/editor/tests/bgm-palette-clock.test.cjs @@ -0,0 +1,324 @@ +const assert = require('node:assert/strict'); +const { runtimeSource } = require('./helpers/runtime-source.cjs'); +const fs = require('node:fs'); +const path = require('node:path'); +const test = require('node:test'); +const { ModelOfflineAudioContext } = require('./helpers/offline-audio-model.cjs'); +const { RATE, scenarios, compare, paletteRuntime, HANDOVER_LAYERS } = require('./helpers/palette-clock-scenarios.cjs'); + +// BGM palettes on the audio clock: layers start together, every hand-over is +// written on the context clock ahead of time, and the frame loop only keeps +// the books. Rendered offline at 48 kHz through the real AudioManager and +// WebAudio over a model OfflineAudioContext (helpers/offline-audio-model.cjs), +// and held frame by frame to the palette rules written out directly +// (helpers/palette-clock-scenarios.cjs). tests/smoke/palette-clock-offline runs +// the same scenarios on Chromium's own OfflineAudioContext. + +const repoRoot = path.resolve(__dirname, '..', '..'); +const core = runtimeSource('reactor_core.js'); +const managers = fs.readFileSync(path.join(repoRoot, 'runtime', 'reactor_managers.js'), 'utf8'); +const slice = (source, from, to) => { + const start = source.indexOf(from); + const end = source.indexOf(to, start); + assert.ok(start >= 0 && end > start, 'expected ' + from + ' before ' + to); + return source.slice(start, end); +}; +const sources = { + webAudio: slice(core, 'function WebAudio() {', 'function Video() {'), + audioManager: slice(managers, 'function AudioManager() {', 'function SoundManager() {') +}; +const TOLERANCE = 1e-5; + +const results = new Map(); +async function rendered(scenario) { + if (!results.has(scenario.name)) { + const context = new ModelOfflineAudioContext(2, scenario.frames, RATE); + results.set(scenario.name, await scenario.run({ context, sources })); + } + return results.get(scenario.name); +} + +for (const scenario of scenarios) { + test(scenario.name, async () => { + const result = await rendered(scenario); + const { worst, at } = compare(result.rendered, result.expected); + assert.ok(worst < TOLERANCE, `rendered differs from the palette rules by ${worst} at frame ${at}`); + assert.ok(result.expected[0].some(v => Math.abs(v) > 0.05), 'the expected mix is not silent'); + // The same output one frame early or late is nowhere near: this is what + // makes the comparison a statement about frames. + for (const shift of [-1, 1]) { + const off = compare(result.rendered, result.expected, shift); + assert.ok(off.worst > 0.01, `a one-frame shift (${shift}) would differ by only ${off.worst}`); + } + // Every track the runtime committed went to the frame the rules give it. + const placed = result.marks.placed.map(list => list.map(draw => draw.file + '@' + draw.frame)); + // (Draws committed past the end of the render are ahead of what was mixed.) + for (const commit of result.marks.commits.filter(c => c.frame < scenario.frames)) { + assert.ok(placed[commit.layer].includes(commit.name + '@' + commit.frame), + `layer ${commit.layer} committed ${commit.name} at frame ${commit.frame}, not a frame the rules give it`); + } + }); +} + +test('the first draws are decoded before any layer sounds, and all start on one frame', async () => { + const result = await rendered(scenarios[0]); + const { start, commits } = result.marks; + const first = commits.filter(c => c.frame === start); + assert.deepEqual(first.map(c => c.layer).sort(), [0, 1], 'both layers began on the palette start frame'); + // 30 ms decode, then the 50 ms start lead. + assert.ok(start / RATE >= 0.03 + 0.05, 'nothing started before the first draws had decoded'); + const got = result.rendered.getChannelData(0); + for (let f = 0; f < start; f++) assert.equal(got[f], 0, 'silent until the start frame, frame ' + f); + assert.notEqual(got[start + 1], 0); +}); + +test('a draw is committed to the clock long before its frame: decoded while the one before it plays', async () => { + const result = await rendered(scenarios[0]); + const later = result.marks.commits.filter(c => c.frame > result.marks.start); + assert.ok(later.length >= 10, 'many hand-overs were rendered: ' + later.length); + for (const commit of later) { + const lead = commit.frame / RATE - commit.at; + assert.ok(lead > 0.05, `${commit.name} at frame ${commit.frame} was committed only ${lead.toFixed(3)} s ahead`); + } +}); + +test('the frame loop\'s rate and stalls change nothing that is heard', async () => { + const smooth = await rendered(scenarios[0]); + const rough = await rendered(scenarios[1]); + assert.equal(rough.marks.start, smooth.marks.start, 'the same start frame: the first decode is what starts a palette'); + const a = smooth.rendered.getChannelData(0); + const b = rough.rendered.getChannelData(1 - 1); + let worst = 0; + for (let f = 0; f < a.length; f++) worst = Math.max(worst, Math.abs(a[f] - b[f])); + assert.equal(worst, 0, 'bit for bit the same output with updates every 50 ms and a 100 ms stall'); +}); + +test('the palette end: nothing starts after it, and the next entry follows its fade-out', async () => { + const result = await rendered(scenarios[2]); + const { end, commits, advancedAt } = result.marks; + assert.ok(commits.every(c => c.frame < end), 'no draw was committed at or past the end frame'); + assert.ok(advancedAt >= end / RATE + 0.05, 'the silence that follows began after the fade-out'); + const got = result.rendered.getChannelData(0); + const quiet = Math.ceil((end / RATE + 0.05) * RATE) + 1; + // The tail that began before the end rings on past it, by its own ramp. + const crossing = result.marks.placed[1].find(d => d.releaseAt < end && d.releaseAt + d.span * RATE > end); + assert.ok(crossing, 'the scenario has a tail crossing the end'); + const tailEnd = Math.ceil(crossing.cutTime * RATE); + for (let f = Math.max(quiet, tailEnd); f < got.length; f++) assert.equal(got[f], 0, 'silent after the fade, frame ' + f); +}); + +test('a late draw is late only in what was missed: it enters part-way and the next draw keeps its frame', async () => { + const result = await rendered(scenarios[3]); + const { lateB, enterFrame, commits } = result.marks; + assert.ok(enterFrame > lateB.frame + 0.1 * RATE, 'the first B decoded well after its frame'); + const after = commits.filter(c => c.frame > lateB.frame); + assert.ok(after.length >= 2, 'the layer went on past the late draw'); + const placed = result.marks.placed[0]; + const b = placed.find(d => d.file === 'B' && d.frame === lateB.frame); + const next = placed[placed.indexOf(b) + 1]; + assert.equal(after[0].frame, next.frame, 'the draw after it is on the frame it would have had anyway'); +}); + +test('Fade Out BGM: the sequence goes quiet within its fade and is let go', async () => { + const result = await rendered(scenarios[4]); + const { fadeAt, fade, stoppedAt } = result.marks; + assert.ok(fadeAt > 0 && stoppedAt >= fadeAt + fade, 'stopped once the fade was done'); + const got = result.rendered.getChannelData(0); + for (let f = Math.ceil((fadeAt + fade) * RATE); f < got.length; f++) assert.equal(got[f], 0, 'silent after the fade, frame ' + f); +}); + +/** + * The runtime over a model context whose clock the test moves by hand: no + * render, so it is quick, and the books can be read at any moment. + */ +function manual(entries, decodeDelay = 0.03) { + const context = new ModelOfflineAudioContext(2, RATE, RATE); + const runtime = paletteRuntime({ context, sources }, entries, decodeDelay); + const at = t => { + context.currentTime = t; + runtime.loads.due(t); + }; + const settle = async () => { for (let i = 0; i < 8; i++) await Promise.resolve(); }; + const step = async t => { + at(t); + await settle(); + runtime.AudioManager.updateBgmSequence(); + await settle(); + }; + return Object.assign(runtime, { context, at, settle, step }); +} + +const paletteWith = fields => Object.assign({ type: 'palette', duration: 0, fadeIn: 0, fadeOut: 0.04, layers: HANDOVER_LAYERS }, fields); + +test('palettes take the clock path only with an audio context and the scheduled API', () => { + const { AudioManager, WebAudio } = manual([paletteWith({})]); + assert.equal(AudioManager._bgmSequenceUsesClock(), true); + const playAt = WebAudio.prototype.playAt; + WebAudio.prototype.playAt = undefined; + assert.equal(AudioManager._bgmSequenceUsesClock(), false, 'a WebAudio without playAt keeps the frame path'); + WebAudio.prototype.playAt = playAt; + const context = WebAudio._context; + WebAudio._context = null; + assert.equal(AudioManager._bgmSequenceUsesClock(), false, 'no audio context, no clock'); + WebAudio._context = context; +}); + +test('the next draw loads while the current one plays, and is ducked and levelled like it', async () => { + const rt = manual([paletteWith({})]); + const { AudioManager } = rt; + AudioManager.playBgm(rt.bgm); + const state = AudioManager._bgmSequence; + assert.equal(state.palette.clock, true); + assert.equal(state.palette.started, false, 'waiting for the first draws'); + assert.equal(state.buffers.length, 2, 'both first draws are loading'); + await rt.step(0.04); + assert.equal(state.palette.started, true); + const start = state.palette.startTime; + await rt.step(start + 0.001); + const layer = state.palette.layers[0]; + assert.equal(layer.buffer.name, 'A', 'layer one is sounding A'); + assert.equal(layer.queue.length, 1, 'and has B queued behind it'); + const next = layer.queue[0]; + assert.equal(next.buffer.name, 'B'); + assert.equal(next.committed, false, 'still decoding'); + AudioManager.playMe({ name: '', volume: 90, pitch: 100, pan: 0 }); + AudioManager._meBuffer = { destroy() {}, isPlaying: () => true, isError: () => false }; + AudioManager._duckBgmSequence(AudioManager.BGM_SEQUENCE_ME_DUCK); + assert.equal(next.buffer.volume, 0.25, 'a queued draw is ducked with the rest'); + AudioManager._duckBgmSequence(1); + AudioManager._meBuffer = null; + AudioManager.bgmVolume = 50; + assert.equal(next.buffer.volume, 0.5, 'and follows the BGM volume option'); + assert.equal(layer.buffer.volume, 0.5); + AudioManager.bgmVolume = 100; + await rt.step(start + 0.05); + assert.equal(next.committed, true, 'committed once decoded'); + assert.equal(next.buffer._rrStartAt, rt.WebAudio.frameTime(next.frame, RATE), 'to its own frame'); + assert.ok(next.frame / RATE - rt.context.currentTime > 0.3, 'a third of a second before it is due'); + AudioManager.stopBgm(); + assert.equal(AudioManager._bgmSequence, null); + assert.ok(state.buffers.every(b => b._rrRetired), 'stop lets go of the queued draws too'); +}); + +test('a replay fade-in asked while the first draws load is the one they open with', async () => { + const rt = manual([paletteWith({ fadeIn: 0.01 })]); + const { AudioManager } = rt; + AudioManager.playBgm(rt.bgm); + AudioManager.fadeInBgm(2); + await rt.step(0.04); + const palette = AudioManager._bgmSequence.palette; + const buffer = AudioManager._bgmSequence.buffers[0]; + const gain = buffer._fadeGainNode.gain; + const t = palette.startTime; + assert.equal(gain.valueAt(t), 0, 'shut on the start frame'); + assert.ok(Math.abs(gain.valueAt(t + 0.2) - 0.1) < 1e-9, 'a tenth of the way up 0.2 s into its two seconds, not its own 0.01 s'); + // A Fade In BGM while sounding keeps the hand-over it has to make. + await rt.step(t + 0.1); + AudioManager.fadeInBgm(0.05); + const release = buffer._rrReleaseAt; + assert.ok(Math.abs(gain.valueAt(t + 0.1 + 0.05) - 1) < 1e-9, 'up by the end of the new fade'); + assert.ok(gain.valueAt(release + buffer._rrReleaseFade - 1e-4) < 0.01, 'and still down to silence by its release end'); +}); + +test('a single-shot palette moves on from its draw\'s hand-over frame, the other layers fading from that frame', async () => { + const entries = [ + { type: 'palette', single: true, duration: 0, fadeIn: 0, fadeOut: 0.04, layers: [ + { volume: 100, pitch: 100, pan: 0, pool: [{ type: 'track', name: 'C', tail: 0.05 }] }, + { volume: 100, pitch: 100, pan: 0, pool: [{ type: 'track', name: 'A', tail: 0 }] } + ] }, + { type: 'silence', duration: 5 } + ]; + const rt = manual(entries); + const { AudioManager } = rt; + AudioManager.playBgm(rt.bgm); + const state = AudioManager._bgmSequence; + await rt.step(0.04); + const palette = state.palette; + const handOver = rt.WebAudio.frameTime(palette.startFrame + Math.round(0.2 * RATE), RATE); + await rt.step(palette.startTime + 0.01); + const other = palette.layers[1].buffer; + assert.equal(other.name, 'A'); + assert.equal(palette.layers[0].queue.length, 0, 'a single-shot draws nothing more'); + await rt.step(handOver + 0.012); + assert.equal(state.index, 1, 'moved on'); + assert.equal(other._rrReleaseAt, handOver, 'the other layer fades from the hand-over frame, not from the frame that noticed'); + assert.equal(other._rrReleaseFade, 0.05); +}); + +test('a palette ending into an entry that fades in hands over on its end frame', async () => { + const entries = [paletteWith({ duration: 0.5 }), { type: 'track', name: 'D', fadeIn: 0.2 }]; + const rt = manual(entries); + const { AudioManager } = rt; + AudioManager.playBgm(rt.bgm); + const state = AudioManager._bgmSequence; + await rt.step(0.04); + const palette = state.palette; + const end = rt.WebAudio.frameTime(palette.endFrame, RATE); + for (let t = palette.startTime; t < end; t += 1 / 60) await rt.step(t); + const sounding = palette.layers.map(layer => layer.buffer).filter(Boolean); + assert.ok(sounding.length >= 1); + for (const buffer of sounding) assert.equal(buffer._rrReleaseAt, end, buffer.name + ' fades from the end frame'); + await rt.step(end + 0.01); + assert.equal(state.index, 1, 'the track entry has begun'); + assert.equal(state.palette, null); + for (const buffer of sounding) assert.ok(state.retiring.some(item => item.buffer === buffer), buffer.name + ' rides out its fade'); +}); + +test('a weighted random layer on the clock still follows its weights and never repeats a pick', async () => { + const layers = [{ volume: 100, pitch: 100, pan: 0, pool: [ + { type: 'track', name: 'D', weight: 3 }, { type: 'track', name: 'C', weight: 1 }, { type: 'track', name: 'B', weight: 0 } + ] }]; + const rt = manual([{ type: 'palette', duration: 0, fadeIn: 0, fadeOut: 0, layers }], 0.001); + const { AudioManager } = rt; + AudioManager.playBgm(rt.bgm); + const names = []; + const layer = () => AudioManager._bgmSequence.palette.layers[0]; + for (let t = 0.002; t < 40; t += 0.05) { + await rt.step(t); + if (layer().buffer && names[names.length - 1] !== layer().buffer) names.push(layer().buffer); + } + const picks = names.map(b => b.name); + assert.ok(picks.length > 100, 'many draws: ' + picks.length); + for (let i = 1; i < picks.length; i++) assert.notEqual(picks[i], picks[i - 1], 'no repeat at ' + i); + assert.ok(!picks.includes('B'), 'a weight of 0 is never drawn while others can be'); +}); + +test('an entry marked once is skipped on later passes, with its palette on the clock', async () => { + const entries = [ + { type: 'palette', once: true, duration: 0.3, fadeIn: 0, fadeOut: 0, layers: [ + { volume: 100, pitch: 100, pan: 0, pool: [{ type: 'track', name: 'C' }] }] }, + { type: 'palette', duration: 0.3, fadeIn: 0, fadeOut: 0, layers: [ + { volume: 100, pitch: 100, pan: 0, pool: [{ type: 'track', name: 'D' }] }] } + ]; + const rt = manual(entries, 0.001); + const { AudioManager } = rt; + AudioManager.playBgm(rt.bgm); + const heard = []; + let seen = null; + for (let t = 0.002; t < 3; t += 1 / 60) { + await rt.step(t); + const state = AudioManager._bgmSequence; + if (state && state.palette && state.palette !== seen) { + seen = state.palette; + heard.push(state.index); + } + } + assert.ok(heard.length >= 5, 'several passes: ' + heard.join(',')); + assert.deepEqual(heard, [0].concat(heard.slice(1).map(() => 1)), 'the once-entry played on the first pass only'); +}); + +test('the clock path leaves no timer, listener or buffer behind once the sequence stops', async () => { + const rt = manual([paletteWith({})]); + const { AudioManager } = rt; + AudioManager.playBgm(rt.bgm); + await rt.step(0.04); + await rt.step(0.2); + const state = AudioManager._bgmSequence; + const all = state.buffers.slice(); + AudioManager.stopBgm(); + for (const buffer of all) { + assert.equal(buffer._sourceNodes.length, 0, buffer.name + ' has no sources left'); + assert.equal(buffer._loadListeners.length, 0); + } + assert.equal(rt.loads.pending.filter(load => load.generation === load.audio._loadGeneration).length, 0, 'no decode is waited for'); +}); diff --git a/editor/tests/bgm-sequence-editor.test.cjs b/editor/tests/bgm-sequence-editor.test.cjs index d394aaf7..db53784e 100644 --- a/editor/tests/bgm-sequence-editor.test.cjs +++ b/editor/tests/bgm-sequence-editor.test.cjs @@ -149,7 +149,7 @@ test('every control round-trips, because an unhandled key silently reverts', () // fadeIn branch reached a running editor. Sweep every control the form // renders, not just the ones a test happened to think of. const wanted = { duration: 3, fadeIn: 3, fadeOut: 3, volume: 70, pitch: 120, pan: -20, - once: true, single: true, order: 'shuffle' }; + once: true, single: true, order: 'shuffle', tail: 4.4, weight: 0.8, repeats: true }; const found = []; editor.container.innerHTML.replace(/<(input|select)[^>]*>/g, tag => { const path = (tag.match(/data-path="([^"]+)"/) || [])[1]; @@ -172,6 +172,53 @@ test('every control round-trips, because an unhandled key silently reverts', () } }); +test('a pool keeps a track’s tail, an entry’s draw weight and a layer’s repeats only where they say something', () => { + const E = loadEditorClass(); + const layer = plain(E.layer({ order: 'random', repeats: true, pool: [ + { type: 'track', name: 'Melody_01', tail: '4.44', weight: '0.5' }, + { type: 'track', name: 'Air_01', tail: 0 }, + { type: 'track', name: 'Plain', tail: '', weight: 1 }, + { type: 'track', name: 'Odd', tail: -2, weight: 'x' }, + { type: 'silence', duration: 14.4, weight: 0.8 }, + { type: 'silence', duration: 20, weight: 0 } + ] })); + assert.equal(layer.repeats, true); + assert.deepEqual(layer.pool, [ + { type: 'track', name: 'Melody_01', volume: 100, tail: 4.4, weight: 0.5 }, + { type: 'track', name: 'Air_01', volume: 100, tail: 0 }, + { type: 'track', name: 'Plain', volume: 100 }, + { type: 'track', name: 'Odd', volume: 100 }, + { type: 'silence', duration: 14.4, weight: 0.8 }, + { type: 'silence', duration: 20, weight: 0 } + ], 'a tail of 0 is kept (it plays the track out); no tail and weight 1 are left off'); + assert.equal('repeats' in plain(E.layer({ repeats: false })), false, 'an unticked layer carries no key'); + assert.equal('repeats' in plain(E.layer({ repeats: 'yes' })), false, 'only true switches it on'); +}); + +test('an emptied tail field goes back to the palette’s fade-out, and 0 stays 0', () => { + const E = loadEditorClass(); + const handlers = {}; + const container = { innerHTML: '', addEventListener: (type, fn) => { handlers[type] = fn; }, contains: () => true }; + const editor = new E({ container, tt: t => t, t: () => 'levels', pickTrack: () => Promise.resolve(null) }); + editor.load({ enabled: true, entries: [{ type: 'palette', duration: 0, fadeOut: 4.8, layers: [ + { pool: [{ type: 'track', name: 'A', tail: 4.4 }] }] }] }); + const path = 'entries.0.layers.0.pool.0.tail'; + assert.match(container.innerHTML, new RegExp(`data-path="${path.replace(/\./g, '\\.')}" value="4.4"`)); + const input = { dataset: { path }, value: '' }; + handlers.change({ target: input }); + assert.equal('tail' in editor.value().entries[0].layers[0].pool[0], false, 'empty is no tail at all'); + assert.equal(input.value, '', 'and the field stays empty rather than reading 0'); + handlers.change({ target: Object.assign(input, { value: '0' }) }); + assert.equal(editor.value().entries[0].layers[0].pool[0].tail, 0); + assert.equal(input.value, 0); + handlers.change({ target: { dataset: { path: 'entries.0.layers.0.repeats' }, checked: true } }); + assert.equal(editor.value().entries[0].layers[0].repeats, true); + handlers.change({ target: { dataset: { path: 'entries.0.layers.0.repeats' }, checked: false } }); + assert.equal('repeats' in editor.value().entries[0].layers[0], false); + editor.load(editor.value()); + assert.match(container.innerHTML, new RegExp(`data-path="${path.replace(/\./g, '\\.')}" value="0"`), 'a 0 tail renders as 0, not empty'); +}); + test('Map Properties carries every field the map already has and writes the sequence beside them', async () => { const map = { id: 3, name: 'Woods', width: 20, height: 15, data: [1, 2], events: [null], pluginField: { kept: true }, _transient: 1, bgm: { name: 'Old' } }; const sequence = { enabled: true, entries: [{ type: 'track', name: 'A', fadeIn: 0, fadeOut: 0, once: false, volume: 80, pitch: 100, pan: 0 }, { type: 'silence', duration: 2, once: false }] }; diff --git a/editor/tests/bgm-sequence-runtime.test.cjs b/editor/tests/bgm-sequence-runtime.test.cjs index 46aa0264..665741be 100644 --- a/editor/tests/bgm-sequence-runtime.test.cjs +++ b/editor/tests/bgm-sequence-runtime.test.cjs @@ -916,3 +916,130 @@ test('a library key whose entry is gone plays the track it stood in for, and nev assert.equal(created.length, 1); assert.equal(AudioManager._bgmBuffer.name, 'Battle1'); }); + +/** A one-palette map; the palette's own fields over a duration-0, fade-free default. */ +const paletteMap = (layers, palette = {}) => ({ bgm: { name: '', volume: 90, pitch: 100, pan: 0 }, bgmSequence: { enabled: true, entries: [ + Object.assign({ type: 'palette', duration: 0, fadeIn: 0, fadeOut: 0 }, palette, { layers }) +] } }); + +/** Runs `fn` with Math.random answering from `rolls` in turn. */ +function withRolls(rolls, fn) { + const real = Math.random; + let i = 0; + Math.random = () => rolls[i++ % rolls.length]; + try { return fn(); } finally { Math.random = real; } +} + +test('a pool track with its own tail hands over that early, whatever the palette fade-out', () => { + // The shape adaptive scores are written in: a 28.4s file holding 24s of + // music and a 4.4s tail, beside segments whose tail is 4.8s. + const map = paletteMap([{ volume: 100, pitch: 100, pan: 0, order: 'sequential', pool: [ + { type: 'track', name: 'Melody_01', tail: 4.4 }, + { type: 'track', name: 'Melody_02' } + ] }], { fadeOut: 4.8 }); + const { AudioManager, context, created, live, tick } = loadAudioManager({ map }); + context.WebAudio.trackSeconds = 28.4; + AudioManager.playBgm(AudioManager.mapBgmObject(map, 1)); + assert.equal(created[0].name, 'Melody_01'); + tick(23.9); + assert.equal(created.length, 1, 'the palette fade-out of 4.8s would have handed over at 23.6s'); + tick(0.1); + assert.equal(created.length, 2, 'handed over at 24.0s, the end of its music'); + assert.equal(created[1].name, 'Melody_02'); + assert.equal(created[0].fadedOut, 4.4, 'the outgoing track fades over its own tail'); + assert.deepEqual(live(), ['Melody_01', 'Melody_02'], 'its tail rings on under the next segment'); + tick(4.4); + assert.deepEqual(live(), ['Melody_02']); + + // Melody_02 names no tail, so the palette's fade-out decides it: 4.4s in + // already, it hands over at 33.6 - 4.8 = 28.8s. + created[1]._totalTime = 33.6; + tick(24.3); + assert.equal(created.length, 2); + tick(0.1); + assert.equal(created.length, 3, 'a track without a tail hands over by the palette fade-out'); + assert.equal(created[1].fadedOut, 4.8); +}); + +test('a tail of 0 plays a one-shot to its end, though the palette fades the rest', () => { + const map = paletteMap([{ volume: 100, pitch: 100, pan: 0, order: 'sequential', pool: [ + { type: 'track', name: 'Air_01', tail: 0 }, + { type: 'track', name: 'Air_02', tail: 0 } + ] }], { fadeOut: 4.8 }); + const { AudioManager, context, created, live, tick } = loadAudioManager({ map }); + context.WebAudio.trackSeconds = 14.4; + AudioManager.playBgm(AudioManager.mapBgmObject(map, 1)); + tick(14.3); + assert.equal(created.length, 1, 'no early hand-over'); + assert.equal(created[0].fadedOut, null, 'and no fade'); + created[0].end(); + assert.deepEqual(live(), ['Air_02'], 'the next draw starts when the file ends'); +}); + +test('a single-shot palette moves on by the tail of the track that ends', () => { + const map = { bgm: { name: '', volume: 90, pitch: 100, pan: 0 }, bgmSequence: { enabled: true, entries: [ + { type: 'palette', single: true, duration: 0, fadeIn: 0, fadeOut: 4.8, layers: [ + { volume: 100, pitch: 100, pan: 0, pool: [{ type: 'track', name: 'Seg', tail: 2 }] }] }, + { type: 'track', name: 'Next', fadeIn: 1 } + ] } }; + const { AudioManager, context, created, tick } = loadAudioManager({ map }); + context.WebAudio.trackSeconds = 30; + AudioManager.playBgm(AudioManager.mapBgmObject(map, 1)); + tick(27.9); + assert.equal(created.length, 1); + tick(0.1); + assert.equal(created[1].name, 'Next', 'moved on 2s before the end, not 4.8s'); + assert.equal(created[0].fadedOut, 2); +}); + +test('a random draw follows the pool weights and still never repeats the entry just played', () => { + const map = paletteMap([{ volume: 100, pitch: 100, pan: 0, pool: [ + { type: 'track', name: 'A', weight: 3 }, + { type: 'track', name: 'B' }, + { type: 'silence', duration: 5, weight: 0 } + ] }]); + const { AudioManager } = loadAudioManager({ map }); + const layer = { pool: map.bgmSequence.entries[0].layers[0].pool, order: 'random', repeats: false, last: -1 }; + const pick = roll => withRolls([roll], () => AudioManager._pickBgmSequencePoolEntry(layer)); + // Weights 3 : 1 : 0 over a total of 4. + assert.equal(pick(0), 0); + assert.equal(pick(0.74), 0, 'A takes the first three quarters'); + assert.equal(pick(0.76), 1, 'B the last quarter'); + assert.equal(pick(0.9999), 1, 'a zero weight is never drawn, even at the top of the range'); + layer.last = 0; + assert.equal(pick(0), 1, 'A just played, so the whole draw goes to B'); + assert.equal(pick(0.99), 1); +}); + +test('a layer allowing repeats may draw the entry it just played', () => { + const pool = [{ type: 'track', name: 'A' }, { type: 'track', name: 'B' }]; + const map = paletteMap([{ volume: 100, pitch: 100, pan: 0, pool }]); + const { AudioManager } = loadAudioManager({ map }); + const layer = { pool, order: 'random', repeats: true, last: 0 }; + assert.equal(withRolls([0.1], () => AudioManager._pickBgmSequencePoolEntry(layer)), 0, 'A again'); + assert.equal(withRolls([0.9], () => AudioManager._pickBgmSequencePoolEntry(layer)), 1); + // And through the palette: the layer's flag arrives from the stored shape. + map.bgmSequence.entries[0].layers[0].repeats = true; + AudioManager.playBgm(AudioManager.mapBgmObject(map, 1)); + assert.equal(AudioManager._bgmSequence.palette.layers[0].repeats, true); +}); + +test('weights that are all zero fall back to an even draw instead of silence', () => { + const pool = [{ type: 'track', name: 'A', weight: 0 }, { type: 'track', name: 'B', weight: 0 }, { type: 'track', name: 'C', weight: 0 }]; + const map = paletteMap([{ volume: 100, pitch: 100, pan: 0, pool }]); + const { AudioManager } = loadAudioManager({ map }); + const layer = { pool, order: 'random', repeats: false, last: 1 }; + assert.equal(withRolls([0.1], () => AudioManager._pickBgmSequencePoolEntry(layer)), 0); + assert.equal(withRolls([0.9], () => AudioManager._pickBgmSequencePoolEntry(layer)), 2, 'B, just played, still sits out'); +}); + +test('an unweighted pool still draws evenly among the entries it may pick', () => { + const pool = [{ type: 'track', name: 'A' }, { type: 'track', name: 'B' }, { type: 'track', name: 'C' }, { type: 'track', name: 'D' }]; + const map = paletteMap([{ volume: 100, pitch: 100, pan: 0, pool }]); + const { AudioManager } = loadAudioManager({ map }); + const layer = { pool, order: 'random', repeats: false, last: 2 }; + const counts = [0, 0, 0, 0]; + const steps = 3000; + for (let i = 0; i < steps; i++) counts[withRolls([(i + 0.5) / steps], () => AudioManager._pickBgmSequencePoolEntry(layer))]++; + assert.deepEqual(counts, [1000, 1000, 0, 1000], 'a third each, C sitting out'); +}); diff --git a/editor/tests/helpers/offline-audio-model.cjs b/editor/tests/helpers/offline-audio-model.cjs index 596660a6..1ed05dd6 100644 --- a/editor/tests/helpers/offline-audio-model.cjs +++ b/editor/tests/helpers/offline-audio-model.cjs @@ -41,7 +41,13 @@ class ModelParam { return this; } setValueAtTime(value, time) { return this._insert({ type: 'set', value, time }); } - linearRampToValueAtTime(value, time) { return this._insert({ type: 'ramp', value, time }); } + linearRampToValueAtTime(value, time) { + // A ramp with no event before it starts when it is written, from the + // value then (the spec, and Chromium): not from time 0. + const now = this._context.currentTime; + const lone = !this._events.some(event => event.time < time); + return this._insert({ type: 'ramp', value, time, from: lone ? { time: now, value: this.valueAt(now) } : null }); + } setValueCurveAtTime(values, time, duration) { const curve = Float32Array.from(values); if (curve.length < 2) throw new RangeError('a curve needs two values'); @@ -54,8 +60,14 @@ class ModelParam { cancelAndHoldAtTime(time) { const held = this.valueAt(time); const pending = this._events.find(event => event.time >= time); - this._events = this._events.filter(event => event.time < time && !(event.type === 'curve' && event.time + event.duration > time)); - this._insert({ type: pending && pending.type === 'ramp' ? 'ramp' : 'set', value: held, time }); + const curve = this._events.find(event => event.type === 'curve' && event.time < time && event.time + event.duration > time); + this._events = this._events.filter(event => event.time < time && event !== curve); + // As the spec has it, and Chromium does it: an event is put in only for + // a ramp under way (it becomes a ramp ending here) or a curve cut short. + // Otherwise nothing is, and a ramp written next starts from the event + // before -- not from `time`. + if (pending && pending.type === 'ramp') this._insert({ type: 'ramp', value: held, time }); + else if (curve) this._insert({ type: 'set', value: held, time }); return this; } /** The value at context time t, by the spec's automation rules. */ @@ -68,9 +80,10 @@ class ModelParam { else { next = event; break; } } if (next && next.type === 'ramp') { - const t0 = previous ? (previous.type === 'curve' ? previous.time + previous.duration : previous.time) : 0; - const v0 = previous ? previous.value : this._default; + const t0 = previous ? (previous.type === 'curve' ? previous.time + previous.duration : previous.time) : next.from ? next.from.time : 0; + const v0 = previous ? previous.value : next.from ? next.from.value : this._default; if (next.time <= t0) return next.value; + if (t < t0) return v0; return v0 + ((next.value - v0) * (t - t0)) / (next.time - t0); } if (!previous) return this._default; diff --git a/editor/tests/helpers/palette-clock-scenarios.cjs b/editor/tests/helpers/palette-clock-scenarios.cjs new file mode 100644 index 00000000..42ec644e --- /dev/null +++ b/editor/tests/helpers/palette-clock-scenarios.cjs @@ -0,0 +1,340 @@ +'use strict'; +// BGM palettes on the audio clock: scenarios shared by +// tests/bgm-palette-clock.test.cjs (node, over tests/helpers/offline-audio-model.cjs) +// and tests/smoke/palette-clock-offline (NW.js, over Chromium's own +// OfflineAudioContext). Each one plays a palette through the real AudioManager +// and WebAudio, rendered at 48 kHz, with files that take a while to decode and +// a frame loop stepping at its own rate, and returns what was rendered beside +// what the palette rules say it should be, frame by frame. +// +// mixPalette() is the reference: the palette's hand-over rules written out +// directly, every draw placed on the frame the rules give it. Tone plus noise +// moves by about 0.1 between neighbouring frames, so output that matches the +// reference to 1e-5 has every join on its frame. + +const { RATE, tone, buildRuntime, silent } = require('./plan-player-scenarios.cjs'); + +const LEAD = 1 / 1048576; +/** WebAudio.frameTime, restated: the reference must not borrow the code it checks. */ +const frameTime = frame => (frame > 0 ? (frame - LEAD) / RATE : frame / RATE); + +const FILES = { + A: tone(19200, 2, 61), // 0.40 s + B: tone(14400, 2, 62), // 0.30 s + C: tone(12000, 2, 63), // 0.25 s + D: tone(9600, 2, 64) // 0.20 s +}; + +/** One library entry holding `entries`, and the BGM object that plays it. */ +function library(entries) { + return { + system: { reactorMusicSequences: [null, { id: 1, name: 'Test', sequence: { enabled: true, entries } }] }, + bgm: { name: '', volume: 100, pitch: 100, pan: 0, sequence: 'library:1' } + }; +} + +/** + * The runtime over `context`, every file decoding `decodeDelay` seconds after + * it was asked for (or a function of the url giving the delay). Track commits are recorded as { layer, name, frame, at }, + * `at` being the context time the commit ran. + */ +function paletteRuntime({ context, sources }, entries, decodeDelay = 0.03) { + const fixtures = {}; + for (const name of Object.keys(FILES)) fixtures['audio/bgm/' + name + '.ogg'] = FILES[name]; + const { system, bgm } = library(entries); + const runtime = buildRuntime(sources, context, fixtures, { globals: { $dataSystem: system }, decodeDelay }); + const { AudioManager } = runtime; + const commits = []; + const commit = AudioManager._commitBgmSequenceDraw; + AudioManager._commitBgmSequenceDraw = function(state, palette, layer, draw) { + commits.push({ layer: palette.layers.indexOf(layer), name: draw.buffer.name, frame: draw.frame, at: context.currentTime }); + return commit.apply(this, arguments); + }; + return Object.assign(runtime, { commits, bgm }); +} + +const settle = async () => { + for (let i = 0; i < 8; i++) await Promise.resolve(); +}; + +/** + * Renders `frames` while files decode (checked every `decodeEvery` s) and the + * frame loop runs updateBgmSequence every `updateEvery` s, except inside + * `stall` ([from, to] seconds). `act(now, runtime)` runs at every update. + */ +async function drive(context, runtime, { frames, updateEvery = 1 / 60, decodeEvery = 0.005, stall = null, act = null }) { + const { AudioManager, loads, timers } = runtime; + const quantum = 128; + const steps = new Map(); + const mark = (t, kind) => { + const frame = Math.ceil((t * RATE) / quantum) * quantum; + if (frame >= frames) return; + const step = steps.get(frame) || { decode: false, update: false }; + step[kind] = true; + steps.set(frame, step); + }; + for (let t = decodeEvery; t < frames / RATE; t += decodeEvery) mark(t, 'decode'); + for (let t = updateEvery; t < frames / RATE; t += updateEvery) { + if (stall && t >= stall[0] && t < stall[1]) continue; + mark(t, 'update'); + } + for (const [frame, step] of steps) { + context.suspend(frame / RATE).then(async () => { + const now = context.currentTime; + loads.due(now); + await settle(); + for (const timer of timers) { + if (timer.cleared || timer.ran || timer.at + timer.ms / 1000 > now) continue; + timer.ran = true; + timer.fn(); + } + if (step.update) { + AudioManager.updateBgmSequence(); + if (act) act(now, runtime); + await settle(); + } + context.resume(); + }); + } + AudioManager.playBgm(runtime.bgm); + return context.startRendering(); +} + +/** + * The palette rules, mixed directly. `layers` lists each layer's draws in the + * order they are made ({ file, tail } or { silence }), as many as the render + * needs; `start` is the frame they all begin on and `end` the palette's end + * frame (Infinity without a duration). Returns the mix and, per layer, the + * draws as placed: { file, frame, handOver, releaseAt, span, cut }. + * `adjust(draw)` may change a placed draw before it is mixed. + */ +function mixPalette({ start, end = Infinity, fadeIn = 0, fadeOut = 0, layers, frames, adjust = null }) { + const out = silent(frames); + const placed = layers.map(draws => { + const list = []; + let cursor = start; + for (const draw of draws) { + if (!(cursor < end) || cursor >= frames) break; + if (draw.silence !== undefined) { + cursor += Math.round(draw.silence * RATE); + continue; + } + const data = FILES[draw.file]; + const length = data[0].length; + const fade = Number.isFinite(draw.tail) ? draw.tail : fadeOut; + let handOver = cursor + length; + let span = 0; + if (fade > 0 && length / RATE > fade) { + handOver = cursor + Math.round((length / RATE - fade) * RATE); + span = fade; + } + let releaseAt = handOver; + if (end <= handOver) { + releaseAt = end; + span = fadeOut; + } + list.push({ file: draw.file, frame: cursor, handOver, releaseAt, span, fadeIn, enter: cursor, cutTime: frameTime(releaseAt) + span }); + cursor = handOver; + } + return list; + }); + for (const list of placed) { + for (const draw of list) { + if (adjust) adjust(draw); + if (draw.removed) continue; + const data = FILES[draw.file]; + const startTime = frameTime(draw.frame); + const releaseTime = frameTime(draw.releaseAt); + const fadeInLevel = t => (draw.fadeIn > 0 ? Math.min(1, Math.max(0, (t - startTime) / draw.fadeIn)) : 1); + const envelope = t => { + if (draw.hold && t >= draw.hold.at) { + const held = draw.hold.level; + return Math.max(0, held * (1 - (t - draw.hold.at) / draw.hold.span)); + } + if (t < releaseTime || !(draw.span > 0)) return fadeInLevel(t); + return Math.max(0, fadeInLevel(releaseTime) * (1 - (t - releaseTime) / draw.span)); + }; + draw.envelope = envelope; + const last = Math.min(draw.frame + data[0].length, Math.ceil(draw.cutTime * RATE), frames); + for (let f = Math.max(draw.enter, 0); f < last; f++) { + const g = envelope(f / RATE); + for (let c = 0; c < 2; c++) out[c][f] += data[c][f - draw.frame] * g; + } + } + } + return { mix: out, placed }; +} + +/** `count` draws walking a pool in order, as a sequential layer makes them. */ +const walk = (pool, count) => Array.from({ length: count }, (_, i) => pool[i % pool.length]); + +const scenarios = []; + +const HANDOVER_LAYERS = [ + { volume: 100, pitch: 100, pan: 0, order: 'sequential', pool: [{ type: 'track', name: 'A', tail: 0.02 }, { type: 'track', name: 'B' }] }, + { volume: 100, pitch: 100, pan: 0, order: 'sequential', pool: [ + { type: 'track', name: 'C', tail: 0 }, { type: 'silence', duration: 0.015 }, { type: 'track', name: 'D', tail: 0 } + ] } +]; +const HANDOVER_DRAWS = [ + walk([{ file: 'A', tail: 0.02 }, { file: 'B' }], 12), + walk([{ file: 'C', tail: 0 }, { silence: 0.015 }, { file: 'D', tail: 0 }], 18) +]; +const handoverPalette = () => ({ type: 'palette', duration: 0, fadeIn: 0.01, fadeOut: 0.04, layers: HANDOVER_LAYERS }); + +async function renderHandovers(env, frames, timing) { + const runtime = paletteRuntime(env, [handoverPalette()]); + let start = null; + const rendered = await drive(env.context, runtime, Object.assign({ frames }, timing, { + act: (now, rt) => { + const palette = rt.AudioManager._bgmSequence && rt.AudioManager._bgmSequence.palette; + if (palette && palette.started && start === null) start = palette.startFrame; + } + })); + const { mix, placed } = mixPalette({ start, fadeIn: 0.01, fadeOut: 0.04, layers: HANDOVER_DRAWS, frames }); + return { rendered, expected: mix, marks: { start, placed, commits: runtime.commits, firstDecode: 0.03 } }; +} + +scenarios.push({ + name: 'layers start together and every hand-over lands on its frame: by tail, by fade-out, end to end, across a silence', + frames: 96000, + async run(env) { + return renderHandovers(env, this.frames, { updateEvery: 1 / 60 }); + } +}); + +scenarios.push({ + name: 'a slow, stalling frame loop moves no join', + frames: 96000, + async run(env) { + return renderHandovers(env, this.frames, { updateEvery: 0.05, stall: [0.6, 0.7] }); + } +}); + +scenarios.push({ + name: 'the palette ends on its frame: every layer fades from it, a tail crossing it keeps its own ramp, nothing starts after it', + frames: 48000, + async run(env) { + const palette = { + type: 'palette', duration: 0.7, fadeIn: 0, fadeOut: 0.05, + layers: [ + HANDOVER_LAYERS[0], + { volume: 100, pitch: 100, pan: 0, pool: [{ type: 'track', name: 'C', tail: 0.12 }] } + ] + }; + const runtime = paletteRuntime(env, [palette, { type: 'silence', duration: 0.5 }]); + let start = null; + const marks = {}; + const rendered = await drive(env.context, runtime, { + frames: this.frames, + act: (now, rt) => { + const state = rt.AudioManager._bgmSequence; + if (state && state.palette && state.palette.started && start === null) start = state.palette.startFrame; + if (state && state.index === 1 && !marks.advancedAt) marks.advancedAt = now; + } + }); + const end = start + Math.round(0.7 * RATE); + const { mix, placed } = mixPalette({ + start, end, fadeOut: 0.05, frames: this.frames, + layers: [walk([{ file: 'A', tail: 0.02 }, { file: 'B' }], 6), walk([{ file: 'C', tail: 0.12 }], 8)] + }); + Object.assign(marks, { start, end, placed, commits: runtime.commits }); + return { rendered, expected: mix, marks }; + } +}); + +scenarios.push({ + name: 'a draw decoded after its frame enters part-way, in its place, and the next one is still on time', + frames: 72000, + async run(env) { + const layers = [HANDOVER_LAYERS[0]]; + const palette = { type: 'palette', duration: 0, fadeIn: 0.01, fadeOut: 0.04, layers }; + // The first B takes half a second to decode, longer than A has left. + let slow = true; + const delay = url => { + if (slow && url.endsWith('/B.ogg')) { + slow = false; + return 0.5; + } + return 0.03; + }; + const runtime = paletteRuntime(env, [palette], delay); + let start = null; + const rendered = await drive(env.context, runtime, { + frames: this.frames, + act: (now, rt) => { + const state = rt.AudioManager._bgmSequence; + if (state && state.palette && state.palette.started && start === null) start = state.palette.startFrame; + } + }); + const lateB = runtime.commits.find(c => c.name === 'B'); + const enterFrame = Math.round(lateB.at * RATE); + const { mix, placed } = mixPalette({ + start, fadeIn: 0.01, fadeOut: 0.04, frames: this.frames, layers: [walk([{ file: 'A', tail: 0.02 }, { file: 'B' }], 8)], + adjust: draw => { + if (draw.file === 'B' && draw.frame === lateB.frame) draw.enter = enterFrame; + } + }); + return { rendered, expected: mix, marks: { start, placed, commits: runtime.commits, lateB, enterFrame } }; + } +}); + +scenarios.push({ + name: 'Fade Out BGM during a hand-over ramps everything down without cutting a tail or starting the next draw', + frames: 72000, + async run(env) { + const runtime = paletteRuntime(env, [handoverPalette()]); + let start = null; + const marks = { fadeAt: null }; + const FADE = 0.1; + const rendered = await drive(env.context, runtime, { + frames: this.frames, + act: (now, rt) => { + const state = rt.AudioManager._bgmSequence; + if (state && state.palette && state.palette.started && start === null) start = state.palette.startFrame; + // Just after layer one's second hand-over: B's tail and A's fade-in are both under way. + if (start !== null && marks.fadeAt === null && now * RATE >= start + Math.round(0.38 * RATE) + Math.round(0.26 * RATE) + 100) { + marks.fadeAt = now; + rt.AudioManager.fadeOutBgm(FADE); + } + if (marks.fadeAt !== null && !rt.AudioManager._bgmSequence && !marks.stoppedAt) marks.stoppedAt = now; + } + }); + const fadeAt = marks.fadeAt; + const { mix, placed } = mixPalette({ + start, fadeIn: 0.01, fadeOut: 0.04, layers: HANDOVER_DRAWS, frames: this.frames, + adjust: draw => { + const startTime = frameTime(draw.frame); + const releaseTime = frameTime(draw.releaseAt); + if (startTime > fadeAt) { + draw.removed = true; + } else if (releaseTime > fadeAt) { + // Held where it is and ramped to silence: its own fade-in + // level at that moment, since its release had not begun. + const level = draw.fadeIn > 0 ? Math.min(1, Math.max(0, (fadeAt - startTime) / draw.fadeIn)) : 1; + draw.hold = { at: fadeAt, level, span: FADE }; + draw.cutTime = fadeAt + FADE; + } + } + }); + Object.assign(marks, { start, placed, commits: runtime.commits, fade: FADE }); + return { rendered, expected: mix, marks }; + } +}); + +/** Largest difference between what was rendered and what was expected, and where. */ +function compare(rendered, expected, shift = 0) { + let worst = 0; + let at = -1; + for (let c = 0; c < 2; c++) { + const got = rendered.getChannelData(c); + for (let f = 0; f < got.length; f++) { + const want = f - shift >= 0 && f - shift < expected[c].length ? expected[c][f - shift] : 0; + const d = Math.abs(got[f] - want); + if (d > worst) { worst = d; at = f; } + } + } + return { worst, at }; +} + +module.exports = { RATE, FILES, scenarios, compare, mixPalette, paletteRuntime, drive, library, walk, frameTime, HANDOVER_LAYERS }; diff --git a/editor/tests/helpers/plan-player-scenarios.cjs b/editor/tests/helpers/plan-player-scenarios.cjs index dd4eb109..4dc222a0 100644 --- a/editor/tests/helpers/plan-player-scenarios.cjs +++ b/editor/tests/helpers/plan-player-scenarios.cjs @@ -111,16 +111,21 @@ function clip(fields) { /** * The runtime's WebAudio and AudioManager, built from their source over * `context`, with every audio file read from `fixtures` (url -> channels) - * instead of the disk. Nothing global is touched: timers are recorded, not run. + * instead of the disk. Nothing global is touched: timers are recorded, not run + * (each with the context time it was set at; clearTimeout marks it cleared). + * options.globals replaces any of the globals below; options.decodeDelay (or a + * function of the url giving one) makes a file decode that many context + * seconds after it was asked for, once the caller runs loads.due(now), instead + * of at once. */ -function buildRuntime(sources, context, fixtures = {}) { +function buildRuntime(sources, context, fixtures = {}, options = {}) { const timers = []; const globals = { Utils: { encodeURI: s => s, hasEncryptedAudio: () => false, isLocal: () => true, canPlayOgg: () => true }, Graphics: { frameCount: 0 }, console, - setTimeout: (fn, ms) => timers.push({ fn, ms }), - clearTimeout: () => {}, + setTimeout: (fn, ms) => timers.push({ fn, ms, at: context.currentTime, id: timers.length + 1 }), + clearTimeout: id => { const timer = timers[id - 1]; if (timer) timer.cleared = true; }, setInterval: undefined, clearInterval: () => {}, XMLHttpRequest: undefined, @@ -130,6 +135,7 @@ function buildRuntime(sources, context, fixtures = {}) { $dataSystem: null, $gameTroop: undefined }; + Object.assign(globals, options.globals || {}); const names = Object.keys(globals); // eslint-disable-next-line no-new-func const factory = new Function(...names, sources.webAudio + '\n' + sources.audioManager + '\nreturn { WebAudio: WebAudio, AudioManager: AudioManager };'); @@ -138,12 +144,32 @@ function buildRuntime(sources, context, fixtures = {}) { WebAudio._masterVolume = 1; WebAudio._masterGainNode = context.createGain(); WebAudio._masterGainNode.connect(context.destination); + const pending = []; + const loads = { + pending, + /** Decodes every file whose delay is up, and runs its load listeners as _onDecode would. */ + due(now) { + for (let i = 0; i < pending.length; i++) { + const load = pending[i]; + if (load.at > now) continue; + pending.splice(i--, 1); + if (load.generation !== load.audio._loadGeneration) continue; + fill(load.audio, context, load.data); + load.audio._onLoad(); + } + } + }; WebAudio.prototype._startLoading = function() { const data = fixtures[this._url]; if (!data) { this._isError = true; return; } + const delay = typeof options.decodeDelay === 'function' ? options.decodeDelay(this._url) : options.decodeDelay; + if (delay > 0) { + pending.push({ audio: this, data, at: context.currentTime + delay, generation: this._loadGeneration }); + return; + } fill(this, context, data); }; const decoded = (data, chunks) => { @@ -152,7 +178,7 @@ function buildRuntime(sources, context, fixtures = {}) { fill(audio, context, data, chunks); return audio; }; - return { WebAudio, AudioManager, timers, decoded }; + return { WebAudio, AudioManager, timers, decoded, loads }; } /** Puts decoded audio into a WebAudio, split into chunks of the given lengths. */ @@ -516,4 +542,4 @@ function compare(rendered, expected) { return { worst, at }; } -module.exports = { RATE, scenarios, compare, mixPlan, tone, clip, buildRuntime, LOOP_PLAN, LINE_PLAN }; +module.exports = { RATE, scenarios, compare, mixPlan, tone, clip, buildRuntime, silent, LOOP_PLAN, LINE_PLAN }; diff --git a/editor/tests/smoke/palette-clock-offline/index.html b/editor/tests/smoke/palette-clock-offline/index.html new file mode 100644 index 00000000..cd39a008 --- /dev/null +++ b/editor/tests/smoke/palette-clock-offline/index.html @@ -0,0 +1,51 @@ + + + + diff --git a/editor/tests/smoke/palette-clock-offline/package.json b/editor/tests/smoke/palette-clock-offline/package.json new file mode 100644 index 00000000..8f284ce4 --- /dev/null +++ b/editor/tests/smoke/palette-clock-offline/package.json @@ -0,0 +1,5 @@ +{ + "name": "palette-clock-offline", + "main": "index.html", + "window": { "show": false } +} diff --git a/runtime/reactor_core_io.js b/runtime/reactor_core_io.js index e4d56777..98a82b4e 100644 --- a/runtime/reactor_core_io.js +++ b/runtime/reactor_core_io.js @@ -903,6 +903,7 @@ WebAudio.prototype.playAt = function(when, offset, options) { this._removeNodes(); this._createPannerNode(); this._createGainNode(); + this._fadeInSpan = null; const region = loop && typeof loop === "object" ? loop : null; const voice = this.scheduleVoice({ destination: this._fadeGainNode, @@ -940,6 +941,67 @@ WebAudio.prototype.stopAt = function(time) { this._createScheduledEndTimer(time); }; +/** + * fadeIn(), on the clock: the fade stage is shut until context time `time` and + * opens over `duration` seconds from there. Call it after playAt, which is what + * builds the stage. A time already past opens from the level the fade would + * have reached by now. + * + * @param {number} time - Context time the fade starts. + * @param {number} duration - Seconds it takes. + */ +WebAudio.prototype.fadeInAt = function(time, duration) { + if (!this._fadeGainNode) return; + const gain = this._fadeGainNode.gain; + const span = Math.max(0, duration || 0); + const from = Math.max(time, WebAudio._currentTime()); + const level = span > 0 ? Math.min(1, Math.max(0, (from - time) / span)) : 1; + gain.cancelScheduledValues(from); + gain.setValueAtTime(level, from); + if (level < 1) gain.linearRampToValueAtTime(1, time + span); + this._fadeInSpan = { start: time, end: time + span }; +}; + +/** + * fadeOut(), on the clock: from context time `time` the fade stage falls to + * silence over `duration` seconds, from whatever level it is at then, a fade-in + * part-way included. Unlike fadeOut() it leaves the object playing; stopAt is + * what ends it. A time already past falls from the level now, still reaching + * silence when the fade would have. + * + * @param {number} time - Context time the fade starts. + * @param {number} duration - Seconds it takes. + */ +WebAudio.prototype.fadeOutAt = function(time, duration) { + if (!this._fadeGainNode) return; + const gain = this._fadeGainNode.gain; + const now = WebAudio._currentTime(); + const from = Math.max(time, now); + const end = time + Math.max(0, duration || 0); + // The level to fall from. Now, it is what the stage is sounding; later, it + // is worked out from the last fadeInAt, the only other automation the + // stage carries on this path (playAt builds it open). + const span = this._fadeInSpan; + const rising = span && from > span.start && from < span.end; + let level = from > now ? 1 : gain.value; + if (from > now && span) level = rising ? (from - span.start) / (span.end - span.start) : from <= span.start ? 0 : 1; + if (gain.cancelAndHoldAtTime) { + gain.cancelAndHoldAtTime(from); + } else { + gain.cancelScheduledValues(from); + // Without cancelAndHoldAtTime (Firefox) a fade-in under way would + // lose its ramp: end it where it would have been by then. + if (rising && from > now) gain.linearRampToValueAtTime(level, from); + } + // Always written: cancelAndHoldAtTime inserts an event only when a ramp is + // under way, so without one a ramp would start from the event before -- + // measured in Chromium, a fade from a stage set to 1 at frame 0 falls from + // frame 0, not from `time`. + gain.setValueAtTime(level, from); + if (end > from) gain.linearRampToValueAtTime(0, end); + else gain.setValueAtTime(0, from); +}; + WebAudio.prototype._createScheduledEndTimer = function(time) { this._removeEndTimer(); const delay = time - WebAudio._currentTime() + WebAudio.END_TIMER_SLACK; diff --git a/runtime/reactor_main.js b/runtime/reactor_main.js index afa0af4c..74a98ac3 100644 --- a/runtime/reactor_main.js +++ b/runtime/reactor_main.js @@ -1,10 +1,10 @@ //============================================================================= // reactor_main.js — RPG Reactor runtime entry point // RPG Reactor runtime version: 0.99.8 -// RPG Reactor runtime revision: 20261129.7 +// RPG Reactor runtime revision: 20261130.2 // The same stamp, reachable from the F12 console: which engine is this // window actually running? Type RPG_REACTOR_RUNTIME_REVISION to see. -globalThis.RPG_REACTOR_RUNTIME_REVISION = "20261129.7"; +globalThis.RPG_REACTOR_RUNTIME_REVISION = "20261130.2"; //============================================================================= const scriptUrls = [ diff --git a/runtime/reactor_managers.js b/runtime/reactor_managers.js index c64187d6..68bb00c0 100644 --- a/runtime/reactor_managers.js +++ b/runtime/reactor_managers.js @@ -1811,9 +1811,7 @@ AudioManager.fadeOutBgm = function(duration) { AudioManager.fadeInBgm = function(duration) { if (this._bgmPlan) this._fadeInBgmPlan(duration); - if (this._bgmSequence) { - for (const buffer of this._bgmSequenceBuffers()) buffer.fadeIn(duration); - } + if (this._bgmSequence) this._fadeInBgmSequence(duration); if (this._bgmBuffer && this._currentBgm) { this._bgmBuffer.fadeIn(duration); } @@ -2225,6 +2223,11 @@ AudioManager.throwLoadError = function(webAudio) { // before the next entry. A layer whose track reaches its end first hands // over to its next draw the same way, so with `duration: 0` a pool plays // through in full, crossfading track to track. +// A pool item may carry `weight` (default 1), its share of a random +// draw against the rest of the pool; and a track may carry `tail`, the +// seconds of it that ring on under the next draw, which overrides the +// palette's `fadeOut` for that hand-over (0 plays it to its end). A layer +// with `repeats: true` lets a random draw pick the entry it just played. // Any entry may set `once: true` to play only on the sequence's first pass; // later passes skip it, which is how an opening statement plays once over a // bed that then repeats without it. @@ -2232,6 +2235,17 @@ AudioManager.throwLoadError = function(webAudio) { // LOOPSTART/LOOPLENGTH tags are inert; a sequence that is one plain track // is the ordinary BGM path, tags honoured. // +// A palette plays on the audio context's clock. Its layers' first draws are +// decoded before any of them sounds, and then all start on one frame. Each +// draw is decoded while the one before it plays, and is started on the frame +// that draw hands over (its end, less its tail or the palette's fade-out); the +// outgoing fade, and the palette's own end after `duration`, are written on +// the clock too. Nothing about where a join falls depends on the frame loop, +// which only keeps the books (and starts what follows the palette). A WebAudio +// without the scheduled API (a plugin's replacement, or no audio context) +// keeps the older timing: each draw starts when its file has loaded, and +// hands over at the first frame past its point. +// // The sequence lives beside the BGM slot, not in it: _bgmBuffer and // _currentBgm stay null while one plays, and every BGM entry point above // checks _bgmSequence. It reports into the saved-BGM shape as the map's @@ -2254,6 +2268,8 @@ AudioManager.throwLoadError = function(webAudio) { AudioManager._bgmSequence = null; AudioManager._pendingBgmSequence = null; AudioManager.BGM_SEQUENCE_ME_DUCK = 0.25; +/** Seconds between a palette's last first draw decoding and all its layers starting together. */ +AudioManager.BGM_SEQUENCE_START_LEAD = 0.05; /** The BGM object a map plays: its fallback track, marked with the sequence when it has one. */ AudioManager.mapBgmObject = function(map, mapId) { @@ -2443,8 +2459,8 @@ AudioManager._bgmSequenceBuffers = function() { return this._bgmSequence ? this._bgmSequence.buffers.filter(buffer => buffer && !buffer._rrRetired) : []; }; -/** Starts one non-looping track for the sequence; `onEnd` runs when it plays out. */ -AudioManager._startBgmSequenceTrack = function(state, audio, onEnd, fadeIn) { +/** Makes, without playing, one track for the sequence; `onEnd` runs when it plays out. */ +AudioManager._createBgmSequenceTrack = function(state, audio, onEnd) { const buffer = this.createBuffer("bgm/", audio.name); this.updateBufferParameters(buffer, this._bgmVolume, audio); buffer._rrBaseVolume = buffer.volume; @@ -2455,6 +2471,12 @@ AudioManager._startBgmSequenceTrack = function(state, audio, onEnd, fadeIn) { buffer._rrRetired = true; onEnd(); }); + return buffer; +}; + +/** Starts one non-looping track for the sequence; `onEnd` runs when it plays out. */ +AudioManager._startBgmSequenceTrack = function(state, audio, onEnd, fadeIn) { + const buffer = this._createBgmSequenceTrack(state, audio, onEnd); buffer.play(false, 0); // After play: the fade stage does not exist until the nodes do. A buffer // still loading defers both, and in the order they were asked for. @@ -2474,7 +2496,7 @@ AudioManager._destroyBgmSequenceBuffer = function(buffer) { * playing, ramping down, until the sweep in updateBgmSequence destroys it -- * which is what lets the next entry start over the top of this one. */ -AudioManager._retireBgmSequenceBuffer = function(state, buffer, fade) { +AudioManager._retireBgmSequenceBuffer = function(state, buffer, fade, at) { if (!buffer) return; if (!(fade > 0)) { this._destroyBgmSequenceBuffer(buffer); @@ -2485,10 +2507,41 @@ AudioManager._retireBgmSequenceBuffer = function(state, buffer, fade) { // would stretch a tail that is halfway through. if (buffer._rrRetired) return; buffer._rrRetired = true; + if (buffer._rrClock) { + // On the clock: from `at` (the frame the hand-over was due), not from + // whichever frame noticed. Usually it is already written that way. + // A release already written for that time or earlier stands: a tail + // that began before this point keeps its own ramp. + const from = Number.isFinite(at) ? at : WebAudio._currentTime(); + if (!(buffer._rrStartAt < from)) { + // Never heard by then: there is nothing to fade. + buffer.destroy(); + return; + } + if (!(buffer._rrReleaseAt <= from)) this._releaseBgmSequenceBuffer(buffer, from, fade); + state.retiring.push({ buffer: buffer, doneAt: buffer._rrReleaseEnd }); + return; + } buffer.fadeOut(fade); state.retiring.push({ buffer: buffer, doneAt: WebAudio._currentTime() + fade }); }; +/** + * Writes a clock track's release: from context time `at` it fades to silence + * over `fade` seconds and is then cut, or is cut at `at` with no fade. A track + * whose file ends first simply ends. + */ +AudioManager._releaseBgmSequenceBuffer = function(buffer, at, fade) { + const span = Math.max(0, fade || 0); + const natural = buffer._rrStartAt + (buffer._totalTime || 0) / (buffer._pitch || 1); + if (span > 0 && at < natural) buffer.fadeOutAt(at, span); + const cut = at + span; + if (cut < natural) buffer.stopAt(cut); + buffer._rrReleaseAt = at; + buffer._rrReleaseFade = span; + buffer._rrReleaseEnd = Math.min(cut, natural); +}; + AudioManager._sweepBgmSequenceRetiring = function(state, now) { if (!state.retiring || !state.retiring.length) return; state.retiring = state.retiring.filter(item => { @@ -2524,10 +2577,10 @@ AudioManager._pruneBgmSequenceBuffers = function(state) { state.buffers = state.buffers.filter(buffer => buffer && !buffer._rrRetired); }; -AudioManager._advanceBgmSequence = function(fadeOut) { +AudioManager._advanceBgmSequence = function(fadeOut, at) { const state = this._bgmSequence; if (!state || state.stopping) return; - this._endBgmSequencePalette(state, fadeOut); + this._endBgmSequencePalette(state, fadeOut, at); this._pruneBgmSequenceBuffers(state); const total = state.entries.length; // Walk forward past anything the sequence has already used up. Bounded by @@ -2576,8 +2629,10 @@ AudioManager._startBgmSequencePalette = function(state, entry, now) { pool: (Array.isArray(layer.pool) ? layer.pool : []).filter(item => item && typeof item === "object"), trim: 100, order: layer.order === "sequential" || layer.order === "shuffle" ? layer.order : "random", + repeats: layer.repeats === true, bag: null, buffer: null, + tail: null, silentUntil: 0, last: -1 })).filter(layer => layer.pool.length > 0); @@ -2607,9 +2662,307 @@ AudioManager._startBgmSequencePalette = function(state, entry, now) { state.due = now + duration; return; } + if (this._bgmSequenceUsesClock()) { + this._startBgmSequenceClockPalette(state, state.palette); + return; + } for (const layer of layers) this._startBgmSequenceLayer(state, layer); }; +//----------------------------------------------------------------------------- +// Palettes on the clock +// +// Each layer keeps a short queue of draws ahead of the one sounding: the next +// track (loading, then committed to the clock once decoded), and any silences +// before it, which commit at once since their length is known. A draw's +// `frame` is the context frame it starts on and `endFrame` the frame it hands +// over on; both are whole frames of the context's own rate, so a join lands +// on its frame however the frame loop runs. The loop moves a draw from the +// queue to `layer.buffer` once its frame has come, which is when the draw +// after it is chosen and starts loading. + +/** Whether palettes play on the clock: an audio context, and a WebAudio with the scheduled API. */ +AudioManager._bgmSequenceUsesClock = function() { + if (typeof WebAudio === "undefined" || !WebAudio._context || !WebAudio.prototype) return false; + const proto = WebAudio.prototype; + return ["playAt", "stopAt", "fadeInAt", "fadeOutAt", "isDecoded", "addDecodeListener"].every(name => typeof proto[name] === "function"); +}; + +/** The context's frames per second. */ +AudioManager._bgmSequenceRate = function() { + return WebAudio._context.sampleRate; +}; + +/** The context time frame `frame` sounds at. */ +AudioManager._bgmSequenceFrameTime = function(frame) { + return WebAudio.frameTime(frame, this._bgmSequenceRate()); +}; + +/** Chooses every layer's first draw and starts loading it; they sound together once all are decoded. */ +AudioManager._startBgmSequenceClockPalette = function(state, palette) { + palette.clock = true; + palette.started = false; + palette.startFrame = 0; + palette.endFrame = Infinity; + palette.openFade = null; + for (const layer of palette.layers) { + layer.queue = []; + layer.endFrame = 0; + layer.releaseFade = 0; + layer.spent = false; + } + // Every queue exists before any draw does: a file already decoded calls + // back at once, and the start must still see the layers yet to draw. + for (const layer of palette.layers) this._drawBgmSequenceLayer(state, palette, layer, null); + this._tryStartBgmSequenceClockPalette(state, palette); +}; + +/** + * Picks a layer's next draw, to start on context frame `frame` (null for a + * first draw, whose frame is set when the palette starts), and queues it. A + * track starts loading and commits itself to the clock once decoded. + */ +AudioManager._drawBgmSequenceLayer = function(state, palette, layer, frame) { + const index = this._pickBgmSequencePoolEntry(layer); + const previous = layer.last; + layer.last = index; + const item = layer.pool[index]; + const draw = { + index: index, + previous: previous, + frame: frame, + endFrame: null, + silence: null, + buffer: null, + committed: false, + tail: null, + trim: 100, + releaseFade: 0, + fadeIn: palette.fadeIn + }; + layer.queue.push(draw); + if (item.type === "silence" || !item.name) { + draw.silence = Math.max(0, Number(item.duration) || 0); + if (frame !== null) this._commitBgmSequenceSilence(draw, frame); + return draw; + } + // As _startBgmSequenceLayer: the item's own volume trims it against the + // rest of the pool, and its own tail decides how early it hands over. + draw.trim = Number.isFinite(item.volume) ? item.volume : 100; + draw.tail = this._bgmSequencePoolTail(item); + const audio = { + name: item.name, + volume: layer.volume * draw.trim / 100, + pitch: layer.pitch, + pan: layer.pan + }; + const buffer = this._createBgmSequenceTrack(state, audio, () => { + this._destroyBgmSequenceBuffer(buffer); + if (layer.buffer === buffer) layer.buffer = null; + this._pruneBgmSequenceBuffers(state); + }); + buffer._rrClock = true; + buffer._rrAudio = audio; + draw.buffer = buffer; + state.buffers.push(buffer); + buffer.addDecodeListener(() => this._onBgmSequenceDrawDecoded(state, palette, layer, draw)); + return draw; +}; + +AudioManager._commitBgmSequenceSilence = function(draw, frame) { + draw.frame = frame; + draw.endFrame = frame + Math.round(draw.silence * this._bgmSequenceRate()); + draw.committed = true; +}; + +AudioManager._onBgmSequenceDrawDecoded = function(state, palette, layer, draw) { + if (this._bgmSequence !== state || state.palette !== palette || state.stopping) return; + if (draw.committed || !draw.buffer || draw.buffer._rrRetired || layer.queue.indexOf(draw) < 0) return; + if (!palette.started) { + this._tryStartBgmSequenceClockPalette(state, palette); + } else { + this._commitBgmSequenceDraw(state, palette, layer, draw); + } +}; + +/** + * Starts the palette once every layer's first draw is decoded: all of them on + * one frame, BGM_SEQUENCE_START_LEAD from now. A draw whose file failed to load + * does not hold the others back; its layer stays quiet, as it would have. + */ +AudioManager._tryStartBgmSequenceClockPalette = function(state, palette) { + if (this._bgmSequence !== state || state.palette !== palette || palette.started || state.stopping) return; + for (const layer of palette.layers) { + const draw = layer.queue[0]; + if (!draw || (draw.buffer && !draw.buffer.isDecoded() && !draw.buffer.isError())) return; + } + const rate = this._bgmSequenceRate(); + const start = Math.ceil((WebAudio._currentTime() + this.BGM_SEQUENCE_START_LEAD) * rate); + const duration = palette.duration; + palette.started = true; + palette.startFrame = start; + palette.startTime = this._bgmSequenceFrameTime(start); + palette.endFrame = duration > 0 ? start + Math.round(duration * rate) : Infinity; + // A fade-in asked of the whole sequence while it loaded (a replay after a + // battle) is the one the first draws open with, as it always has been. + const fadeIn = palette.openFade !== null ? palette.openFade : palette.fadeIn; + for (const layer of palette.layers) { + layer.endFrame = start; + const draw = layer.queue[0]; + if (!draw) continue; + draw.fadeIn = fadeIn; + if (draw.silence !== null) { + this._commitBgmSequenceSilence(draw, start); + } else { + draw.frame = start; + if (draw.buffer.isDecoded()) this._commitBgmSequenceDraw(state, palette, layer, draw); + } + } + for (const layer of palette.layers) this._planBgmSequenceLayer(state, palette, layer); +}; + +/** + * Starts a decoded draw on its frame, and writes its hand-over: from `endFrame` + * (the end of the file, less its tail or the palette's fade-out) it fades over + * that much and is cut. A palette ending first ends it instead, over the + * palette's fade-out. A draw decoded after its frame enters as far in as the + * time gone, so it is late in nothing but the part that was missed. + */ +AudioManager._commitBgmSequenceDraw = function(state, palette, layer, draw) { + const buffer = draw.buffer; + const rate = this._bgmSequenceRate(); + const when = this._bgmSequenceFrameTime(draw.frame); + buffer.playAt(when, 0); + buffer._rrStartAt = when; + draw.committed = true; + if (draw.fadeIn > 0) buffer.fadeInAt(when, draw.fadeIn); + const pitch = buffer._pitch || 1; + const total = buffer._totalTime || 0; + const fade = this._bgmSequenceLayerFade({ tail: draw.tail }, palette); + let handOver = draw.frame + Math.round((total * rate) / pitch); + draw.releaseFade = 0; + // A track shorter than its own crossfade plays out, as on the frame path. + if (fade > 0 && total > fade) { + handOver = draw.frame + Math.round(((total - fade) * rate) / pitch); + draw.releaseFade = fade; + } + draw.endFrame = handOver; + if (palette.endFrame <= handOver) { + this._releaseBgmSequenceBuffer(buffer, this._bgmSequenceFrameTime(palette.endFrame), palette.fadeOut); + } else { + this._releaseBgmSequenceBuffer(buffer, this._bgmSequenceFrameTime(handOver), draw.releaseFade); + } +}; + +/** + * Queues the draws that follow the last one, for as long as they are silences + * (whose length is known) and the palette has not ended by then: a track is + * the last thing queued, since its length is only known once it is decoded. + */ +AudioManager._planBgmSequenceLayer = function(state, palette, layer) { + if (palette.single) return; + for (let guard = 0; guard < 4; guard++) { + const last = layer.queue[layer.queue.length - 1]; + if (last && !(last.silence !== null && last.committed)) return; + const frame = last ? last.endFrame : layer.endFrame; + if (!Number.isFinite(frame) || !(frame < palette.endFrame)) return; + this._drawBgmSequenceLayer(state, palette, layer, frame); + } +}; + +/** Moves a layer on to each queued draw whose frame has come: the outgoing one keeps its tail. */ +AudioManager._updateBgmSequenceClockLayer = function(state, palette, layer, now) { + for (let guard = 0; guard < 16; guard++) { + const draw = layer.queue[0]; + if (!draw || !draw.committed || now < this._bgmSequenceFrameTime(draw.frame)) return; + layer.queue.shift(); + const outgoing = layer.buffer; + if (outgoing && !outgoing._rrRetired) { + // Its release is already on the clock; this is only the books. + outgoing._rrRetired = true; + state.retiring.push({ buffer: outgoing, doneAt: outgoing._rrReleaseEnd }); + } + layer.buffer = draw.buffer; + layer.tail = draw.tail; + layer.trim = draw.trim; + layer.endFrame = draw.endFrame; + layer.releaseFade = draw.buffer ? draw.releaseFade : 0; + layer.silentUntil = draw.silence !== null ? this._bgmSequenceFrameTime(draw.endFrame) : 0; + this._pruneBgmSequenceBuffers(state); + this._planBgmSequenceLayer(state, palette, layer); + } +}; + +/** The frame-loop step for a palette on the clock: the books, a single-shot's end, and the palette's own. */ +AudioManager._updateBgmSequenceClockPalette = function(state, palette, now) { + if (!palette.started) { + // Also how a first draw that failed to load stops holding the rest back. + this._tryStartBgmSequenceClockPalette(state, palette); + if (!palette.started) return; + } + if (palette.fading) { + if (now >= palette.fadeDoneAt) this._advanceBgmSequence(); + return; + } + for (const layer of palette.layers) { + this._updateBgmSequenceClockLayer(state, palette, layer, now); + if (!palette.single || layer.spent || layer.queue.length) continue; + const end = this._bgmSequenceFrameTime(layer.endFrame); + if (now < end) continue; + // Single-shot: the end of the one draw is the end of the entry, so it + // crossfades into what follows, from its own hand-over frame. + layer.spent = true; + if (layer.buffer && layer.releaseFade > 0) { + this._advanceBgmSequence(layer.releaseFade, end); + return; + } + layer.buffer = null; + layer.silentUntil = 0; + if (palette.layers.every(item => item.spent)) { + this._advanceBgmSequence(palette.fadeOut); + return; + } + } + if (palette.endFrame < Infinity && now >= this._bgmSequenceFrameTime(palette.endFrame)) { + const at = this._bgmSequenceFrameTime(palette.endFrame); + // The layers' fades from `at` are already on the clock (see + // _commitBgmSequenceDraw); what is left is when the next entry begins. + const next = this._nextBgmSequenceEntry(state); + if (this._bgmSequenceFadeIn(next) > 0) { + this._advanceBgmSequence(palette.fadeOut, at); + return; + } + palette.fading = true; + palette.fadeDoneAt = at + palette.fadeOut; + for (const layer of palette.layers) { + if (layer.buffer) layer.buffer._rrRetired = true; + } + } +}; + +/** + * Lets go of a layer's queued draws as its palette ends at context time `at`. + * One already sounding (the frame loop had not reached it yet) ends with the + * layer; the rest were never heard, so their picks are given back. + */ +AudioManager._dropBgmSequenceQueue = function(state, layer, fadeOut, at) { + const queue = layer.queue || []; + layer.queue = []; + for (let i = queue.length - 1; i >= 0; i--) { + const draw = queue[i]; + const sounding = draw.buffer && draw.committed && draw.buffer._rrStartAt < at; + if (sounding) { + this._retireBgmSequenceBuffer(state, draw.buffer, fadeOut, at); + continue; + } + if (draw.buffer) this._destroyBgmSequenceBuffer(draw.buffer); + if (draw.frame === null || this._bgmSequenceFrameTime(draw.frame) >= at) { + if (layer.order === "shuffle" && Array.isArray(layer.bag)) layer.bag.push(draw.index); + layer.last = draw.previous; + } + } +}; + /** The next pool entry: in order, dealt from a shuffled bag, or drawn at random. */ AudioManager._pickBgmSequencePoolEntry = function(layer) { const pool = layer.pool; @@ -2636,9 +2989,45 @@ AudioManager._pickBgmSequencePoolEntry = function(layer) { } return layer.bag.pop(); } - let index = Math.floor(Math.random() * pool.length); - if (index === layer.last) index = (index + 1 + Math.floor(Math.random() * (pool.length - 1))) % pool.length; - return index; + // Random: each entry's weight is its share of the draw. The entry just + // played sits out unless the layer allows repeats. With every weight left + // at 1 this is the even draw among the others that it has always been. + const sitsOut = index => index === layer.last && !layer.repeats; + const weights = pool.map((item, index) => (sitsOut(index) ? 0 : this._bgmSequencePoolWeight(item))); + let total = weights.reduce((sum, weight) => sum + weight, 0); + if (!(total > 0)) { + // Every candidate weighs nothing: draw evenly among them rather than + // falling silent, still keeping the no-repeat rule. + for (let i = 0; i < weights.length; i++) weights[i] = sitsOut(i) ? 0 : 1; + total = weights.reduce((sum, weight) => sum + weight, 0); + } + let roll = Math.random() * total; + for (let i = 0; i < weights.length; i++) { + if (!(weights[i] > 0)) continue; + if (roll < weights[i]) return i; + roll -= weights[i]; + } + // Rounding left the roll past the end: the last entry that could be drawn. + for (let i = weights.length - 1; i >= 0; i--) if (weights[i] > 0) return i; + return 0; +}; + +/** A pool item's share of a random draw: its `weight`, or 1. */ +AudioManager._bgmSequencePoolWeight = function(item) { + const weight = item ? Number(item.weight) : NaN; + return Number.isFinite(weight) && weight >= 0 ? weight : 1; +}; + +/** The tail a pool track names for itself, or null to use the palette's fade-out. */ +AudioManager._bgmSequencePoolTail = function(item) { + if (!item || item.tail === null || item.tail === undefined || item.tail === "") return null; + const tail = Number(item.tail); + return Number.isFinite(tail) && tail >= 0 ? tail : null; +}; + +/** How early a layer's current track hands over: its own tail, else the palette's fade-out. */ +AudioManager._bgmSequenceLayerFade = function(layer, palette) { + return layer && Number.isFinite(layer.tail) ? layer.tail : palette.fadeOut; }; AudioManager._startBgmSequenceLayer = function(state, layer) { @@ -2648,6 +3037,7 @@ AudioManager._startBgmSequenceLayer = function(state, layer) { layer.last = index; const item = layer.pool[index]; layer.buffer = null; + layer.tail = null; if (item.type === "silence" || !item.name) { layer.silentUntil = WebAudio._currentTime() + Math.max(0, Number(item.duration) || 0); return; @@ -2656,6 +3046,10 @@ AudioManager._startBgmSequenceLayer = function(state, layer) { // A pool draws from wherever its tracks came from, and two sources rarely // agree on level. The item's own volume trims it against the rest. layer.trim = Number.isFinite(item.volume) ? item.volume : 100; + // A track that names its own tail hands over that early, whatever the + // palette's fade-out: segments written to overlap by different amounts, + // and one-shots that must ring to their end, can share a layer's pool. + layer.tail = this._bgmSequencePoolTail(item); const audio = { name: item.name, volume: layer.volume * layer.trim / 100, @@ -2679,11 +3073,12 @@ AudioManager._startBgmSequenceLayer = function(state, layer) { */ AudioManager._bgmSequenceLayerIsEnding = function(layer, palette) { const buffer = layer.buffer; - if (!buffer || buffer._rrRetired || !(palette.fadeOut > 0)) return false; + const fade = this._bgmSequenceLayerFade(layer, palette); + if (!buffer || buffer._rrRetired || !(fade > 0)) return false; if (!buffer.isPlaying || !buffer.isPlaying()) return false; const total = buffer._totalTime; // A track shorter than its own crossfade would hand over before it is heard. - if (!(total > palette.fadeOut)) return false; + if (!(total > fade)) return false; // play() marks a buffer playing while it is still decoding, and _startTime // is only set once playback really begins; reading it before that would // hand over a track nobody has heard. @@ -2693,7 +3088,7 @@ AudioManager._bgmSequenceLayerIsEnding = function(layer, palette) { // whose loop region is shorter than itself would wrap before reaching its // end and never hand over at all. const played = (WebAudio._currentTime() - buffer._startTime) * (buffer._pitch || 1); - return played >= total - palette.fadeOut; + return played >= total - fade; }; /** Moves a single-shot palette on once every layer has had its one turn. */ @@ -2704,9 +3099,13 @@ AudioManager._advanceIfPaletteSpent = function(state) { if (!busy) this._advanceBgmSequence(palette.fadeOut); }; -AudioManager._endBgmSequencePalette = function(state, fadeOut) { +AudioManager._endBgmSequencePalette = function(state, fadeOut, at) { const palette = state.palette; if (!palette) return; + if (palette.clock) { + const end = Number.isFinite(at) ? at : WebAudio._currentTime(); + for (const layer of palette.layers) this._dropBgmSequenceQueue(state, layer, fadeOut, end); + } // Carried into the next draw of this same entry: without it the no-repeat // guard resets every cycle and a layer can hand over to the track it is // already playing -- inaudible when the palette faded to silence first, @@ -2714,7 +3113,7 @@ AudioManager._endBgmSequencePalette = function(state, fadeOut) { state.lastPicks = { index: state.index, picks: palette.layers.map(layer => ({ last: layer.last, bag: layer.bag })) }; state.palette = null; for (const layer of palette.layers) { - if (layer.buffer) this._retireBgmSequenceBuffer(state, layer.buffer, fadeOut); + if (layer.buffer) this._retireBgmSequenceBuffer(state, layer.buffer, fadeOut, at); layer.buffer = null; } this._pruneBgmSequenceBuffers(state); @@ -2731,6 +3130,10 @@ AudioManager.updateBgmSequence = function() { return; } const palette = state.palette; + if (palette && palette.clock) { + this._updateBgmSequenceClockPalette(state, palette, now); + return; + } if (palette) { if (palette.fading) { if (now >= palette.fadeDoneAt) this._advanceBgmSequence(); @@ -2744,11 +3147,12 @@ AudioManager.updateBgmSequence = function() { } else if (layer.buffer && this._bgmSequenceLayerIsEnding(layer, palette)) { // Single-shot: the end of the one track is the end of the entry, // so it crossfades into what follows rather than drawing again. - if (palette.single) { this._advanceBgmSequence(palette.fadeOut); return; } + const fade = this._bgmSequenceLayerFade(layer, palette); + if (palette.single) { this._advanceBgmSequence(fade); return; } // Retiring first matters twice: the stop listener bails on a // retired buffer, so the track playing itself out cannot start a // second draw on top of the one starting here. - this._retireBgmSequenceBuffer(state, layer.buffer, palette.fadeOut); + this._retireBgmSequenceBuffer(state, layer.buffer, fade); layer.buffer = null; this._startBgmSequenceLayer(state, layer); } @@ -2801,10 +3205,41 @@ AudioManager._fadeOutBgmSequence = function(duration) { if (!state || state.stopping) return; state.stopping = true; state.due = WebAudio._currentTime() + Math.max(0, duration || 0); + const now = WebAudio._currentTime(); for (const buffer of state.buffers) { if (!buffer || buffer._rrRetired) continue; buffer._rrRetired = true; - buffer.fadeOut(duration); + if (!buffer._rrClock) { + buffer.fadeOut(duration); + } else if (buffer._rrStartAt <= now) { + // Rewritten rather than ramped over: the hand-over it was due to + // make would otherwise cut it mid-fade. + this._releaseBgmSequenceBuffer(buffer, now, duration); + } else { + // Loading, or waiting for its frame: it was never going to be heard. + buffer.destroy(); + } + } +}; + +/** Fade In BGM over a sequence: what is sounding swells in, keeping any hand-over it has to make. */ +AudioManager._fadeInBgmSequence = function(duration) { + const state = this._bgmSequence; + if (!state) return; + const palette = state.palette; + if (palette && palette.clock && !palette.started) { + // Asked while the first draws load: they open with this fade instead. + palette.openFade = duration; + return; + } + const now = WebAudio._currentTime(); + for (const buffer of this._bgmSequenceBuffers()) { + if (!buffer._rrClock) { + buffer.fadeIn(duration); + } else if (buffer._rrStartAt <= now) { + buffer.fadeInAt(now, duration); + if (buffer._rrReleaseAt > now) buffer.fadeOutAt(buffer._rrReleaseAt, buffer._rrReleaseFade); + } } }; @@ -2824,7 +3259,10 @@ AudioManager._refreshBgmSequenceVolumes = function() { const entry = state.entries[state.index]; for (const buffer of this._bgmSequenceBuffers()) { let audio = null; - if (state.palette) { + if (buffer._rrAudio) { + // A palette draw on the clock carries its own level, queued ones included. + audio = buffer._rrAudio; + } else if (state.palette) { const layer = state.palette.layers.find(item => item.buffer === buffer); if (layer) { const trim = Number.isFinite(layer.trim) ? layer.trim : 100; diff --git a/template/Demo/js/reactor_core_io.js b/template/Demo/js/reactor_core_io.js index e4d56777..98a82b4e 100644 --- a/template/Demo/js/reactor_core_io.js +++ b/template/Demo/js/reactor_core_io.js @@ -903,6 +903,7 @@ WebAudio.prototype.playAt = function(when, offset, options) { this._removeNodes(); this._createPannerNode(); this._createGainNode(); + this._fadeInSpan = null; const region = loop && typeof loop === "object" ? loop : null; const voice = this.scheduleVoice({ destination: this._fadeGainNode, @@ -940,6 +941,67 @@ WebAudio.prototype.stopAt = function(time) { this._createScheduledEndTimer(time); }; +/** + * fadeIn(), on the clock: the fade stage is shut until context time `time` and + * opens over `duration` seconds from there. Call it after playAt, which is what + * builds the stage. A time already past opens from the level the fade would + * have reached by now. + * + * @param {number} time - Context time the fade starts. + * @param {number} duration - Seconds it takes. + */ +WebAudio.prototype.fadeInAt = function(time, duration) { + if (!this._fadeGainNode) return; + const gain = this._fadeGainNode.gain; + const span = Math.max(0, duration || 0); + const from = Math.max(time, WebAudio._currentTime()); + const level = span > 0 ? Math.min(1, Math.max(0, (from - time) / span)) : 1; + gain.cancelScheduledValues(from); + gain.setValueAtTime(level, from); + if (level < 1) gain.linearRampToValueAtTime(1, time + span); + this._fadeInSpan = { start: time, end: time + span }; +}; + +/** + * fadeOut(), on the clock: from context time `time` the fade stage falls to + * silence over `duration` seconds, from whatever level it is at then, a fade-in + * part-way included. Unlike fadeOut() it leaves the object playing; stopAt is + * what ends it. A time already past falls from the level now, still reaching + * silence when the fade would have. + * + * @param {number} time - Context time the fade starts. + * @param {number} duration - Seconds it takes. + */ +WebAudio.prototype.fadeOutAt = function(time, duration) { + if (!this._fadeGainNode) return; + const gain = this._fadeGainNode.gain; + const now = WebAudio._currentTime(); + const from = Math.max(time, now); + const end = time + Math.max(0, duration || 0); + // The level to fall from. Now, it is what the stage is sounding; later, it + // is worked out from the last fadeInAt, the only other automation the + // stage carries on this path (playAt builds it open). + const span = this._fadeInSpan; + const rising = span && from > span.start && from < span.end; + let level = from > now ? 1 : gain.value; + if (from > now && span) level = rising ? (from - span.start) / (span.end - span.start) : from <= span.start ? 0 : 1; + if (gain.cancelAndHoldAtTime) { + gain.cancelAndHoldAtTime(from); + } else { + gain.cancelScheduledValues(from); + // Without cancelAndHoldAtTime (Firefox) a fade-in under way would + // lose its ramp: end it where it would have been by then. + if (rising && from > now) gain.linearRampToValueAtTime(level, from); + } + // Always written: cancelAndHoldAtTime inserts an event only when a ramp is + // under way, so without one a ramp would start from the event before -- + // measured in Chromium, a fade from a stage set to 1 at frame 0 falls from + // frame 0, not from `time`. + gain.setValueAtTime(level, from); + if (end > from) gain.linearRampToValueAtTime(0, end); + else gain.setValueAtTime(0, from); +}; + WebAudio.prototype._createScheduledEndTimer = function(time) { this._removeEndTimer(); const delay = time - WebAudio._currentTime() + WebAudio.END_TIMER_SLACK; diff --git a/template/Demo/js/reactor_main.js b/template/Demo/js/reactor_main.js index afa0af4c..74a98ac3 100644 --- a/template/Demo/js/reactor_main.js +++ b/template/Demo/js/reactor_main.js @@ -1,10 +1,10 @@ //============================================================================= // reactor_main.js — RPG Reactor runtime entry point // RPG Reactor runtime version: 0.99.8 -// RPG Reactor runtime revision: 20261129.7 +// RPG Reactor runtime revision: 20261130.2 // The same stamp, reachable from the F12 console: which engine is this // window actually running? Type RPG_REACTOR_RUNTIME_REVISION to see. -globalThis.RPG_REACTOR_RUNTIME_REVISION = "20261129.7"; +globalThis.RPG_REACTOR_RUNTIME_REVISION = "20261130.2"; //============================================================================= const scriptUrls = [ diff --git a/template/Demo/js/reactor_managers.js b/template/Demo/js/reactor_managers.js index c64187d6..68bb00c0 100644 --- a/template/Demo/js/reactor_managers.js +++ b/template/Demo/js/reactor_managers.js @@ -1811,9 +1811,7 @@ AudioManager.fadeOutBgm = function(duration) { AudioManager.fadeInBgm = function(duration) { if (this._bgmPlan) this._fadeInBgmPlan(duration); - if (this._bgmSequence) { - for (const buffer of this._bgmSequenceBuffers()) buffer.fadeIn(duration); - } + if (this._bgmSequence) this._fadeInBgmSequence(duration); if (this._bgmBuffer && this._currentBgm) { this._bgmBuffer.fadeIn(duration); } @@ -2225,6 +2223,11 @@ AudioManager.throwLoadError = function(webAudio) { // before the next entry. A layer whose track reaches its end first hands // over to its next draw the same way, so with `duration: 0` a pool plays // through in full, crossfading track to track. +// A pool item may carry `weight` (default 1), its share of a random +// draw against the rest of the pool; and a track may carry `tail`, the +// seconds of it that ring on under the next draw, which overrides the +// palette's `fadeOut` for that hand-over (0 plays it to its end). A layer +// with `repeats: true` lets a random draw pick the entry it just played. // Any entry may set `once: true` to play only on the sequence's first pass; // later passes skip it, which is how an opening statement plays once over a // bed that then repeats without it. @@ -2232,6 +2235,17 @@ AudioManager.throwLoadError = function(webAudio) { // LOOPSTART/LOOPLENGTH tags are inert; a sequence that is one plain track // is the ordinary BGM path, tags honoured. // +// A palette plays on the audio context's clock. Its layers' first draws are +// decoded before any of them sounds, and then all start on one frame. Each +// draw is decoded while the one before it plays, and is started on the frame +// that draw hands over (its end, less its tail or the palette's fade-out); the +// outgoing fade, and the palette's own end after `duration`, are written on +// the clock too. Nothing about where a join falls depends on the frame loop, +// which only keeps the books (and starts what follows the palette). A WebAudio +// without the scheduled API (a plugin's replacement, or no audio context) +// keeps the older timing: each draw starts when its file has loaded, and +// hands over at the first frame past its point. +// // The sequence lives beside the BGM slot, not in it: _bgmBuffer and // _currentBgm stay null while one plays, and every BGM entry point above // checks _bgmSequence. It reports into the saved-BGM shape as the map's @@ -2254,6 +2268,8 @@ AudioManager.throwLoadError = function(webAudio) { AudioManager._bgmSequence = null; AudioManager._pendingBgmSequence = null; AudioManager.BGM_SEQUENCE_ME_DUCK = 0.25; +/** Seconds between a palette's last first draw decoding and all its layers starting together. */ +AudioManager.BGM_SEQUENCE_START_LEAD = 0.05; /** The BGM object a map plays: its fallback track, marked with the sequence when it has one. */ AudioManager.mapBgmObject = function(map, mapId) { @@ -2443,8 +2459,8 @@ AudioManager._bgmSequenceBuffers = function() { return this._bgmSequence ? this._bgmSequence.buffers.filter(buffer => buffer && !buffer._rrRetired) : []; }; -/** Starts one non-looping track for the sequence; `onEnd` runs when it plays out. */ -AudioManager._startBgmSequenceTrack = function(state, audio, onEnd, fadeIn) { +/** Makes, without playing, one track for the sequence; `onEnd` runs when it plays out. */ +AudioManager._createBgmSequenceTrack = function(state, audio, onEnd) { const buffer = this.createBuffer("bgm/", audio.name); this.updateBufferParameters(buffer, this._bgmVolume, audio); buffer._rrBaseVolume = buffer.volume; @@ -2455,6 +2471,12 @@ AudioManager._startBgmSequenceTrack = function(state, audio, onEnd, fadeIn) { buffer._rrRetired = true; onEnd(); }); + return buffer; +}; + +/** Starts one non-looping track for the sequence; `onEnd` runs when it plays out. */ +AudioManager._startBgmSequenceTrack = function(state, audio, onEnd, fadeIn) { + const buffer = this._createBgmSequenceTrack(state, audio, onEnd); buffer.play(false, 0); // After play: the fade stage does not exist until the nodes do. A buffer // still loading defers both, and in the order they were asked for. @@ -2474,7 +2496,7 @@ AudioManager._destroyBgmSequenceBuffer = function(buffer) { * playing, ramping down, until the sweep in updateBgmSequence destroys it -- * which is what lets the next entry start over the top of this one. */ -AudioManager._retireBgmSequenceBuffer = function(state, buffer, fade) { +AudioManager._retireBgmSequenceBuffer = function(state, buffer, fade, at) { if (!buffer) return; if (!(fade > 0)) { this._destroyBgmSequenceBuffer(buffer); @@ -2485,10 +2507,41 @@ AudioManager._retireBgmSequenceBuffer = function(state, buffer, fade) { // would stretch a tail that is halfway through. if (buffer._rrRetired) return; buffer._rrRetired = true; + if (buffer._rrClock) { + // On the clock: from `at` (the frame the hand-over was due), not from + // whichever frame noticed. Usually it is already written that way. + // A release already written for that time or earlier stands: a tail + // that began before this point keeps its own ramp. + const from = Number.isFinite(at) ? at : WebAudio._currentTime(); + if (!(buffer._rrStartAt < from)) { + // Never heard by then: there is nothing to fade. + buffer.destroy(); + return; + } + if (!(buffer._rrReleaseAt <= from)) this._releaseBgmSequenceBuffer(buffer, from, fade); + state.retiring.push({ buffer: buffer, doneAt: buffer._rrReleaseEnd }); + return; + } buffer.fadeOut(fade); state.retiring.push({ buffer: buffer, doneAt: WebAudio._currentTime() + fade }); }; +/** + * Writes a clock track's release: from context time `at` it fades to silence + * over `fade` seconds and is then cut, or is cut at `at` with no fade. A track + * whose file ends first simply ends. + */ +AudioManager._releaseBgmSequenceBuffer = function(buffer, at, fade) { + const span = Math.max(0, fade || 0); + const natural = buffer._rrStartAt + (buffer._totalTime || 0) / (buffer._pitch || 1); + if (span > 0 && at < natural) buffer.fadeOutAt(at, span); + const cut = at + span; + if (cut < natural) buffer.stopAt(cut); + buffer._rrReleaseAt = at; + buffer._rrReleaseFade = span; + buffer._rrReleaseEnd = Math.min(cut, natural); +}; + AudioManager._sweepBgmSequenceRetiring = function(state, now) { if (!state.retiring || !state.retiring.length) return; state.retiring = state.retiring.filter(item => { @@ -2524,10 +2577,10 @@ AudioManager._pruneBgmSequenceBuffers = function(state) { state.buffers = state.buffers.filter(buffer => buffer && !buffer._rrRetired); }; -AudioManager._advanceBgmSequence = function(fadeOut) { +AudioManager._advanceBgmSequence = function(fadeOut, at) { const state = this._bgmSequence; if (!state || state.stopping) return; - this._endBgmSequencePalette(state, fadeOut); + this._endBgmSequencePalette(state, fadeOut, at); this._pruneBgmSequenceBuffers(state); const total = state.entries.length; // Walk forward past anything the sequence has already used up. Bounded by @@ -2576,8 +2629,10 @@ AudioManager._startBgmSequencePalette = function(state, entry, now) { pool: (Array.isArray(layer.pool) ? layer.pool : []).filter(item => item && typeof item === "object"), trim: 100, order: layer.order === "sequential" || layer.order === "shuffle" ? layer.order : "random", + repeats: layer.repeats === true, bag: null, buffer: null, + tail: null, silentUntil: 0, last: -1 })).filter(layer => layer.pool.length > 0); @@ -2607,9 +2662,307 @@ AudioManager._startBgmSequencePalette = function(state, entry, now) { state.due = now + duration; return; } + if (this._bgmSequenceUsesClock()) { + this._startBgmSequenceClockPalette(state, state.palette); + return; + } for (const layer of layers) this._startBgmSequenceLayer(state, layer); }; +//----------------------------------------------------------------------------- +// Palettes on the clock +// +// Each layer keeps a short queue of draws ahead of the one sounding: the next +// track (loading, then committed to the clock once decoded), and any silences +// before it, which commit at once since their length is known. A draw's +// `frame` is the context frame it starts on and `endFrame` the frame it hands +// over on; both are whole frames of the context's own rate, so a join lands +// on its frame however the frame loop runs. The loop moves a draw from the +// queue to `layer.buffer` once its frame has come, which is when the draw +// after it is chosen and starts loading. + +/** Whether palettes play on the clock: an audio context, and a WebAudio with the scheduled API. */ +AudioManager._bgmSequenceUsesClock = function() { + if (typeof WebAudio === "undefined" || !WebAudio._context || !WebAudio.prototype) return false; + const proto = WebAudio.prototype; + return ["playAt", "stopAt", "fadeInAt", "fadeOutAt", "isDecoded", "addDecodeListener"].every(name => typeof proto[name] === "function"); +}; + +/** The context's frames per second. */ +AudioManager._bgmSequenceRate = function() { + return WebAudio._context.sampleRate; +}; + +/** The context time frame `frame` sounds at. */ +AudioManager._bgmSequenceFrameTime = function(frame) { + return WebAudio.frameTime(frame, this._bgmSequenceRate()); +}; + +/** Chooses every layer's first draw and starts loading it; they sound together once all are decoded. */ +AudioManager._startBgmSequenceClockPalette = function(state, palette) { + palette.clock = true; + palette.started = false; + palette.startFrame = 0; + palette.endFrame = Infinity; + palette.openFade = null; + for (const layer of palette.layers) { + layer.queue = []; + layer.endFrame = 0; + layer.releaseFade = 0; + layer.spent = false; + } + // Every queue exists before any draw does: a file already decoded calls + // back at once, and the start must still see the layers yet to draw. + for (const layer of palette.layers) this._drawBgmSequenceLayer(state, palette, layer, null); + this._tryStartBgmSequenceClockPalette(state, palette); +}; + +/** + * Picks a layer's next draw, to start on context frame `frame` (null for a + * first draw, whose frame is set when the palette starts), and queues it. A + * track starts loading and commits itself to the clock once decoded. + */ +AudioManager._drawBgmSequenceLayer = function(state, palette, layer, frame) { + const index = this._pickBgmSequencePoolEntry(layer); + const previous = layer.last; + layer.last = index; + const item = layer.pool[index]; + const draw = { + index: index, + previous: previous, + frame: frame, + endFrame: null, + silence: null, + buffer: null, + committed: false, + tail: null, + trim: 100, + releaseFade: 0, + fadeIn: palette.fadeIn + }; + layer.queue.push(draw); + if (item.type === "silence" || !item.name) { + draw.silence = Math.max(0, Number(item.duration) || 0); + if (frame !== null) this._commitBgmSequenceSilence(draw, frame); + return draw; + } + // As _startBgmSequenceLayer: the item's own volume trims it against the + // rest of the pool, and its own tail decides how early it hands over. + draw.trim = Number.isFinite(item.volume) ? item.volume : 100; + draw.tail = this._bgmSequencePoolTail(item); + const audio = { + name: item.name, + volume: layer.volume * draw.trim / 100, + pitch: layer.pitch, + pan: layer.pan + }; + const buffer = this._createBgmSequenceTrack(state, audio, () => { + this._destroyBgmSequenceBuffer(buffer); + if (layer.buffer === buffer) layer.buffer = null; + this._pruneBgmSequenceBuffers(state); + }); + buffer._rrClock = true; + buffer._rrAudio = audio; + draw.buffer = buffer; + state.buffers.push(buffer); + buffer.addDecodeListener(() => this._onBgmSequenceDrawDecoded(state, palette, layer, draw)); + return draw; +}; + +AudioManager._commitBgmSequenceSilence = function(draw, frame) { + draw.frame = frame; + draw.endFrame = frame + Math.round(draw.silence * this._bgmSequenceRate()); + draw.committed = true; +}; + +AudioManager._onBgmSequenceDrawDecoded = function(state, palette, layer, draw) { + if (this._bgmSequence !== state || state.palette !== palette || state.stopping) return; + if (draw.committed || !draw.buffer || draw.buffer._rrRetired || layer.queue.indexOf(draw) < 0) return; + if (!palette.started) { + this._tryStartBgmSequenceClockPalette(state, palette); + } else { + this._commitBgmSequenceDraw(state, palette, layer, draw); + } +}; + +/** + * Starts the palette once every layer's first draw is decoded: all of them on + * one frame, BGM_SEQUENCE_START_LEAD from now. A draw whose file failed to load + * does not hold the others back; its layer stays quiet, as it would have. + */ +AudioManager._tryStartBgmSequenceClockPalette = function(state, palette) { + if (this._bgmSequence !== state || state.palette !== palette || palette.started || state.stopping) return; + for (const layer of palette.layers) { + const draw = layer.queue[0]; + if (!draw || (draw.buffer && !draw.buffer.isDecoded() && !draw.buffer.isError())) return; + } + const rate = this._bgmSequenceRate(); + const start = Math.ceil((WebAudio._currentTime() + this.BGM_SEQUENCE_START_LEAD) * rate); + const duration = palette.duration; + palette.started = true; + palette.startFrame = start; + palette.startTime = this._bgmSequenceFrameTime(start); + palette.endFrame = duration > 0 ? start + Math.round(duration * rate) : Infinity; + // A fade-in asked of the whole sequence while it loaded (a replay after a + // battle) is the one the first draws open with, as it always has been. + const fadeIn = palette.openFade !== null ? palette.openFade : palette.fadeIn; + for (const layer of palette.layers) { + layer.endFrame = start; + const draw = layer.queue[0]; + if (!draw) continue; + draw.fadeIn = fadeIn; + if (draw.silence !== null) { + this._commitBgmSequenceSilence(draw, start); + } else { + draw.frame = start; + if (draw.buffer.isDecoded()) this._commitBgmSequenceDraw(state, palette, layer, draw); + } + } + for (const layer of palette.layers) this._planBgmSequenceLayer(state, palette, layer); +}; + +/** + * Starts a decoded draw on its frame, and writes its hand-over: from `endFrame` + * (the end of the file, less its tail or the palette's fade-out) it fades over + * that much and is cut. A palette ending first ends it instead, over the + * palette's fade-out. A draw decoded after its frame enters as far in as the + * time gone, so it is late in nothing but the part that was missed. + */ +AudioManager._commitBgmSequenceDraw = function(state, palette, layer, draw) { + const buffer = draw.buffer; + const rate = this._bgmSequenceRate(); + const when = this._bgmSequenceFrameTime(draw.frame); + buffer.playAt(when, 0); + buffer._rrStartAt = when; + draw.committed = true; + if (draw.fadeIn > 0) buffer.fadeInAt(when, draw.fadeIn); + const pitch = buffer._pitch || 1; + const total = buffer._totalTime || 0; + const fade = this._bgmSequenceLayerFade({ tail: draw.tail }, palette); + let handOver = draw.frame + Math.round((total * rate) / pitch); + draw.releaseFade = 0; + // A track shorter than its own crossfade plays out, as on the frame path. + if (fade > 0 && total > fade) { + handOver = draw.frame + Math.round(((total - fade) * rate) / pitch); + draw.releaseFade = fade; + } + draw.endFrame = handOver; + if (palette.endFrame <= handOver) { + this._releaseBgmSequenceBuffer(buffer, this._bgmSequenceFrameTime(palette.endFrame), palette.fadeOut); + } else { + this._releaseBgmSequenceBuffer(buffer, this._bgmSequenceFrameTime(handOver), draw.releaseFade); + } +}; + +/** + * Queues the draws that follow the last one, for as long as they are silences + * (whose length is known) and the palette has not ended by then: a track is + * the last thing queued, since its length is only known once it is decoded. + */ +AudioManager._planBgmSequenceLayer = function(state, palette, layer) { + if (palette.single) return; + for (let guard = 0; guard < 4; guard++) { + const last = layer.queue[layer.queue.length - 1]; + if (last && !(last.silence !== null && last.committed)) return; + const frame = last ? last.endFrame : layer.endFrame; + if (!Number.isFinite(frame) || !(frame < palette.endFrame)) return; + this._drawBgmSequenceLayer(state, palette, layer, frame); + } +}; + +/** Moves a layer on to each queued draw whose frame has come: the outgoing one keeps its tail. */ +AudioManager._updateBgmSequenceClockLayer = function(state, palette, layer, now) { + for (let guard = 0; guard < 16; guard++) { + const draw = layer.queue[0]; + if (!draw || !draw.committed || now < this._bgmSequenceFrameTime(draw.frame)) return; + layer.queue.shift(); + const outgoing = layer.buffer; + if (outgoing && !outgoing._rrRetired) { + // Its release is already on the clock; this is only the books. + outgoing._rrRetired = true; + state.retiring.push({ buffer: outgoing, doneAt: outgoing._rrReleaseEnd }); + } + layer.buffer = draw.buffer; + layer.tail = draw.tail; + layer.trim = draw.trim; + layer.endFrame = draw.endFrame; + layer.releaseFade = draw.buffer ? draw.releaseFade : 0; + layer.silentUntil = draw.silence !== null ? this._bgmSequenceFrameTime(draw.endFrame) : 0; + this._pruneBgmSequenceBuffers(state); + this._planBgmSequenceLayer(state, palette, layer); + } +}; + +/** The frame-loop step for a palette on the clock: the books, a single-shot's end, and the palette's own. */ +AudioManager._updateBgmSequenceClockPalette = function(state, palette, now) { + if (!palette.started) { + // Also how a first draw that failed to load stops holding the rest back. + this._tryStartBgmSequenceClockPalette(state, palette); + if (!palette.started) return; + } + if (palette.fading) { + if (now >= palette.fadeDoneAt) this._advanceBgmSequence(); + return; + } + for (const layer of palette.layers) { + this._updateBgmSequenceClockLayer(state, palette, layer, now); + if (!palette.single || layer.spent || layer.queue.length) continue; + const end = this._bgmSequenceFrameTime(layer.endFrame); + if (now < end) continue; + // Single-shot: the end of the one draw is the end of the entry, so it + // crossfades into what follows, from its own hand-over frame. + layer.spent = true; + if (layer.buffer && layer.releaseFade > 0) { + this._advanceBgmSequence(layer.releaseFade, end); + return; + } + layer.buffer = null; + layer.silentUntil = 0; + if (palette.layers.every(item => item.spent)) { + this._advanceBgmSequence(palette.fadeOut); + return; + } + } + if (palette.endFrame < Infinity && now >= this._bgmSequenceFrameTime(palette.endFrame)) { + const at = this._bgmSequenceFrameTime(palette.endFrame); + // The layers' fades from `at` are already on the clock (see + // _commitBgmSequenceDraw); what is left is when the next entry begins. + const next = this._nextBgmSequenceEntry(state); + if (this._bgmSequenceFadeIn(next) > 0) { + this._advanceBgmSequence(palette.fadeOut, at); + return; + } + palette.fading = true; + palette.fadeDoneAt = at + palette.fadeOut; + for (const layer of palette.layers) { + if (layer.buffer) layer.buffer._rrRetired = true; + } + } +}; + +/** + * Lets go of a layer's queued draws as its palette ends at context time `at`. + * One already sounding (the frame loop had not reached it yet) ends with the + * layer; the rest were never heard, so their picks are given back. + */ +AudioManager._dropBgmSequenceQueue = function(state, layer, fadeOut, at) { + const queue = layer.queue || []; + layer.queue = []; + for (let i = queue.length - 1; i >= 0; i--) { + const draw = queue[i]; + const sounding = draw.buffer && draw.committed && draw.buffer._rrStartAt < at; + if (sounding) { + this._retireBgmSequenceBuffer(state, draw.buffer, fadeOut, at); + continue; + } + if (draw.buffer) this._destroyBgmSequenceBuffer(draw.buffer); + if (draw.frame === null || this._bgmSequenceFrameTime(draw.frame) >= at) { + if (layer.order === "shuffle" && Array.isArray(layer.bag)) layer.bag.push(draw.index); + layer.last = draw.previous; + } + } +}; + /** The next pool entry: in order, dealt from a shuffled bag, or drawn at random. */ AudioManager._pickBgmSequencePoolEntry = function(layer) { const pool = layer.pool; @@ -2636,9 +2989,45 @@ AudioManager._pickBgmSequencePoolEntry = function(layer) { } return layer.bag.pop(); } - let index = Math.floor(Math.random() * pool.length); - if (index === layer.last) index = (index + 1 + Math.floor(Math.random() * (pool.length - 1))) % pool.length; - return index; + // Random: each entry's weight is its share of the draw. The entry just + // played sits out unless the layer allows repeats. With every weight left + // at 1 this is the even draw among the others that it has always been. + const sitsOut = index => index === layer.last && !layer.repeats; + const weights = pool.map((item, index) => (sitsOut(index) ? 0 : this._bgmSequencePoolWeight(item))); + let total = weights.reduce((sum, weight) => sum + weight, 0); + if (!(total > 0)) { + // Every candidate weighs nothing: draw evenly among them rather than + // falling silent, still keeping the no-repeat rule. + for (let i = 0; i < weights.length; i++) weights[i] = sitsOut(i) ? 0 : 1; + total = weights.reduce((sum, weight) => sum + weight, 0); + } + let roll = Math.random() * total; + for (let i = 0; i < weights.length; i++) { + if (!(weights[i] > 0)) continue; + if (roll < weights[i]) return i; + roll -= weights[i]; + } + // Rounding left the roll past the end: the last entry that could be drawn. + for (let i = weights.length - 1; i >= 0; i--) if (weights[i] > 0) return i; + return 0; +}; + +/** A pool item's share of a random draw: its `weight`, or 1. */ +AudioManager._bgmSequencePoolWeight = function(item) { + const weight = item ? Number(item.weight) : NaN; + return Number.isFinite(weight) && weight >= 0 ? weight : 1; +}; + +/** The tail a pool track names for itself, or null to use the palette's fade-out. */ +AudioManager._bgmSequencePoolTail = function(item) { + if (!item || item.tail === null || item.tail === undefined || item.tail === "") return null; + const tail = Number(item.tail); + return Number.isFinite(tail) && tail >= 0 ? tail : null; +}; + +/** How early a layer's current track hands over: its own tail, else the palette's fade-out. */ +AudioManager._bgmSequenceLayerFade = function(layer, palette) { + return layer && Number.isFinite(layer.tail) ? layer.tail : palette.fadeOut; }; AudioManager._startBgmSequenceLayer = function(state, layer) { @@ -2648,6 +3037,7 @@ AudioManager._startBgmSequenceLayer = function(state, layer) { layer.last = index; const item = layer.pool[index]; layer.buffer = null; + layer.tail = null; if (item.type === "silence" || !item.name) { layer.silentUntil = WebAudio._currentTime() + Math.max(0, Number(item.duration) || 0); return; @@ -2656,6 +3046,10 @@ AudioManager._startBgmSequenceLayer = function(state, layer) { // A pool draws from wherever its tracks came from, and two sources rarely // agree on level. The item's own volume trims it against the rest. layer.trim = Number.isFinite(item.volume) ? item.volume : 100; + // A track that names its own tail hands over that early, whatever the + // palette's fade-out: segments written to overlap by different amounts, + // and one-shots that must ring to their end, can share a layer's pool. + layer.tail = this._bgmSequencePoolTail(item); const audio = { name: item.name, volume: layer.volume * layer.trim / 100, @@ -2679,11 +3073,12 @@ AudioManager._startBgmSequenceLayer = function(state, layer) { */ AudioManager._bgmSequenceLayerIsEnding = function(layer, palette) { const buffer = layer.buffer; - if (!buffer || buffer._rrRetired || !(palette.fadeOut > 0)) return false; + const fade = this._bgmSequenceLayerFade(layer, palette); + if (!buffer || buffer._rrRetired || !(fade > 0)) return false; if (!buffer.isPlaying || !buffer.isPlaying()) return false; const total = buffer._totalTime; // A track shorter than its own crossfade would hand over before it is heard. - if (!(total > palette.fadeOut)) return false; + if (!(total > fade)) return false; // play() marks a buffer playing while it is still decoding, and _startTime // is only set once playback really begins; reading it before that would // hand over a track nobody has heard. @@ -2693,7 +3088,7 @@ AudioManager._bgmSequenceLayerIsEnding = function(layer, palette) { // whose loop region is shorter than itself would wrap before reaching its // end and never hand over at all. const played = (WebAudio._currentTime() - buffer._startTime) * (buffer._pitch || 1); - return played >= total - palette.fadeOut; + return played >= total - fade; }; /** Moves a single-shot palette on once every layer has had its one turn. */ @@ -2704,9 +3099,13 @@ AudioManager._advanceIfPaletteSpent = function(state) { if (!busy) this._advanceBgmSequence(palette.fadeOut); }; -AudioManager._endBgmSequencePalette = function(state, fadeOut) { +AudioManager._endBgmSequencePalette = function(state, fadeOut, at) { const palette = state.palette; if (!palette) return; + if (palette.clock) { + const end = Number.isFinite(at) ? at : WebAudio._currentTime(); + for (const layer of palette.layers) this._dropBgmSequenceQueue(state, layer, fadeOut, end); + } // Carried into the next draw of this same entry: without it the no-repeat // guard resets every cycle and a layer can hand over to the track it is // already playing -- inaudible when the palette faded to silence first, @@ -2714,7 +3113,7 @@ AudioManager._endBgmSequencePalette = function(state, fadeOut) { state.lastPicks = { index: state.index, picks: palette.layers.map(layer => ({ last: layer.last, bag: layer.bag })) }; state.palette = null; for (const layer of palette.layers) { - if (layer.buffer) this._retireBgmSequenceBuffer(state, layer.buffer, fadeOut); + if (layer.buffer) this._retireBgmSequenceBuffer(state, layer.buffer, fadeOut, at); layer.buffer = null; } this._pruneBgmSequenceBuffers(state); @@ -2731,6 +3130,10 @@ AudioManager.updateBgmSequence = function() { return; } const palette = state.palette; + if (palette && palette.clock) { + this._updateBgmSequenceClockPalette(state, palette, now); + return; + } if (palette) { if (palette.fading) { if (now >= palette.fadeDoneAt) this._advanceBgmSequence(); @@ -2744,11 +3147,12 @@ AudioManager.updateBgmSequence = function() { } else if (layer.buffer && this._bgmSequenceLayerIsEnding(layer, palette)) { // Single-shot: the end of the one track is the end of the entry, // so it crossfades into what follows rather than drawing again. - if (palette.single) { this._advanceBgmSequence(palette.fadeOut); return; } + const fade = this._bgmSequenceLayerFade(layer, palette); + if (palette.single) { this._advanceBgmSequence(fade); return; } // Retiring first matters twice: the stop listener bails on a // retired buffer, so the track playing itself out cannot start a // second draw on top of the one starting here. - this._retireBgmSequenceBuffer(state, layer.buffer, palette.fadeOut); + this._retireBgmSequenceBuffer(state, layer.buffer, fade); layer.buffer = null; this._startBgmSequenceLayer(state, layer); } @@ -2801,10 +3205,41 @@ AudioManager._fadeOutBgmSequence = function(duration) { if (!state || state.stopping) return; state.stopping = true; state.due = WebAudio._currentTime() + Math.max(0, duration || 0); + const now = WebAudio._currentTime(); for (const buffer of state.buffers) { if (!buffer || buffer._rrRetired) continue; buffer._rrRetired = true; - buffer.fadeOut(duration); + if (!buffer._rrClock) { + buffer.fadeOut(duration); + } else if (buffer._rrStartAt <= now) { + // Rewritten rather than ramped over: the hand-over it was due to + // make would otherwise cut it mid-fade. + this._releaseBgmSequenceBuffer(buffer, now, duration); + } else { + // Loading, or waiting for its frame: it was never going to be heard. + buffer.destroy(); + } + } +}; + +/** Fade In BGM over a sequence: what is sounding swells in, keeping any hand-over it has to make. */ +AudioManager._fadeInBgmSequence = function(duration) { + const state = this._bgmSequence; + if (!state) return; + const palette = state.palette; + if (palette && palette.clock && !palette.started) { + // Asked while the first draws load: they open with this fade instead. + palette.openFade = duration; + return; + } + const now = WebAudio._currentTime(); + for (const buffer of this._bgmSequenceBuffers()) { + if (!buffer._rrClock) { + buffer.fadeIn(duration); + } else if (buffer._rrStartAt <= now) { + buffer.fadeInAt(now, duration); + if (buffer._rrReleaseAt > now) buffer.fadeOutAt(buffer._rrReleaseAt, buffer._rrReleaseFade); + } } }; @@ -2824,7 +3259,10 @@ AudioManager._refreshBgmSequenceVolumes = function() { const entry = state.entries[state.index]; for (const buffer of this._bgmSequenceBuffers()) { let audio = null; - if (state.palette) { + if (buffer._rrAudio) { + // A palette draw on the clock carries its own level, queued ones included. + audio = buffer._rrAudio; + } else if (state.palette) { const layer = state.palette.layers.find(item => item.buffer === buffer); if (layer) { const trim = Number.isFinite(layer.trim) ? layer.trim : 100;