h4 commited on
Commit
983d306
·
verified ·
1 Parent(s): 91e9fa5

Upload index.html with huggingface_hub

Browse files
Files changed (1) hide show
  1. index.html +484 -0
index.html ADDED
@@ -0,0 +1,484 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width,initial-scale=1">
6
+ <title>retro-sync — 71-Shard NFT</title>
7
+ <style>
8
+ *{box-sizing:border-box;margin:0;padding:0}
9
+ body{font-family:monospace;background:#0a0a0a;color:#0f0;padding:1em;max-width:960px;margin:0 auto}
10
+ h1{color:#0ff;font-size:1.3em;margin-bottom:.2em}
11
+ h2{color:#0ff;font-size:.95em;margin:1em 0 .3em;border-bottom:1px solid #333;padding-bottom:.2em}
12
+ textarea,input[type=text]{width:100%;background:#111;color:#0f0;border:1px solid #333;padding:.4em;font-family:monospace;font-size:.85em;resize:vertical}
13
+ textarea{height:4em}
14
+ button{background:#222;color:#0ff;border:1px solid #0ff;padding:.3em .7em;cursor:pointer;font-family:monospace;font-size:.8em;margin:.2em .2em .2em 0}
15
+ button:hover{background:#0ff;color:#000}
16
+ .row{display:flex;gap:.4em;flex-wrap:wrap;margin:.3em 0;align-items:center}
17
+ .out{background:#111;border:1px solid #333;padding:.4em;margin:.3em 0;word-break:break-all;min-height:1.5em;font-size:.8em;max-height:200px;overflow:auto}
18
+ .grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(70px,1fr));gap:3px;margin:.5em 0}
19
+ .tile{border:1px solid #333;text-align:center;font-size:9px;padding:2px;cursor:pointer;position:relative;min-height:70px}
20
+ .tile img{width:100%;image-rendering:pixelated;image-rendering:crisp-edges}
21
+ .tile.found{border-color:#0f0;background:#0f01}
22
+ .tile.prime{border-color:#ff0}
23
+ .tile.prime.found{border-color:#0f0}
24
+ .tile:hover{background:#0ff1}
25
+ .tile img{width:100%;display:block;image-rendering:pixelated}
26
+ .tile .lbl{color:#888}
27
+ .status{color:#888;font-size:.8em}
28
+ canvas{border:1px solid #333;margin:.3em 0;max-width:100%}
29
+ audio{width:100%;margin:.3em 0}
30
+ .cid{color:#ff0;font-size:.8em}
31
+ </style>
32
+ </head>
33
+ <body>
34
+ <h1>retro-sync — 71-Shard NFT</h1>
35
+ <p class="status">6-layer stego · WASM decoder · Groth16/BN254 · Cl(15,0,0)
36
+ <span id="progress" style="color:#0ff">0/71</span>
37
+ <span id="wasm-status" style="color:#f00">⏳ loading WASM…</span>
38
+ </p>
39
+
40
+ <h2>📡 Load Shards</h2>
41
+ <textarea id="urls" placeholder="Paste image URLs (one per line), or a base URL like:
42
+ https://example.com/retro-sync
43
+ (will auto-append /tiles/01.png ... /tiles/71.png and /shards/01.json ... /shards/71.json)"></textarea>
44
+ <div class="row">
45
+ <button onclick="loadFromURLs()">⬇ Fetch URLs</button>
46
+ <button onclick="loadFromFile()">📂 Load Image</button>
47
+ <input type="file" id="file-input" accept="image/*" multiple style="display:none">
48
+ <button onclick="loadFromPaste()">📋 Paste Image</button>
49
+ <button onclick="loadPreset('local')">📍 Local</button>
50
+ <button onclick="loadPreset('space')">HF Space</button>
51
+ <button onclick="loadPreset('dataset')">HF Dataset</button>
52
+ <button onclick="loadPreset('archive')">Archive.org</button>
53
+ <button onclick="loadPreset('gh')">GitHub Pages</button>
54
+ </div>
55
+ <div class="out" id="log"></div>
56
+
57
+ <h2>🧩 Collection</h2>
58
+ <div class="grid" id="grid"></div>
59
+
60
+ <h2>🔍 Decode</h2>
61
+ <div class="row">
62
+ <button onclick="decodeSelected()">Decode Selected</button>
63
+ <button onclick="decodeAll()">Decode All Collected</button>
64
+ <button onclick="reconstruct()">🎵 Reconstruct WAV</button>
65
+ <button onclick="shareLog()">📋 Share Log</button>
66
+ </div>
67
+ <canvas id="canvas" width="512" height="512"></canvas>
68
+ <div class="out" id="decode-out"></div>
69
+
70
+ <h2>🎵 Player</h2>
71
+ <div id="player"></div>
72
+
73
+ <h2>📦 Shard Data</h2>
74
+ <div class="out" id="shard-out" style="white-space:pre-wrap"></div>
75
+
76
+ <script type="module">
77
+ import init, { decode_tile, reconstruct_payload, extract_segment } from './pkg/stego.js';
78
+
79
+ let wasmReady = false;
80
+ init().then(() => {
81
+ wasmReady = true;
82
+ document.getElementById('wasm-status').textContent = '✅ WASM ready';
83
+ document.getElementById('wasm-status').style.color = '#0f0';
84
+ log('🔧 stego WASM loaded');
85
+ }).catch(e => {
86
+ document.getElementById('wasm-status').textContent = '❌ WASM failed';
87
+ log('⚠ WASM load failed: ' + e.message);
88
+ });
89
+
90
+ const PRIMES = new Set([2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71]);
91
+ const TILE_CAP = 512 * 512 * 6 / 8; // 196608
92
+
93
+ const tiles = {};
94
+ const shardJSON = {};
95
+ const tileBytes = {}; // idx → Uint8Array from WASM decode
96
+ let selected = null;
97
+
98
+ const $ = id => document.getElementById(id);
99
+ function log(msg) {
100
+ $('log').textContent = msg + '\n' + $('log').textContent.slice(0, 4000);
101
+ }
102
+ window.log = log;
103
+
104
+ function shareLog() {
105
+ const text = $('log').textContent + '\n---\n' + $('decode-out').textContent;
106
+ navigator.clipboard.writeText(text).then(() => log('📋 Log copied to clipboard'));
107
+ }
108
+ window.shareLog = shareLog;
109
+
110
+ const PRESETS = {
111
+ local: location.origin + location.pathname.replace(/\/[^/]*$/, ''),
112
+ space: 'https://huggingface.co/spaces/introspector/retro-sync/resolve/main',
113
+ dataset: 'https://huggingface.co/datasets/introspector/retro-sync/resolve/main',
114
+ archive: 'https://archive.org/download/retro-sync',
115
+ gh: 'https://meta-introspector.github.io/retro-sync',
116
+ };
117
+
118
+ function loadPreset(key) { $('urls').value = PRESETS[key] || ''; loadFromURLs(); }
119
+ window.loadPreset = loadPreset;
120
+
121
+ function initFromParams() {
122
+ const p = new URLSearchParams(location.search);
123
+ const base = p.get('base') || p.get('src') || p.get('url');
124
+ const dataset = p.get('dataset');
125
+ const rdfa = p.get('rdfa');
126
+
127
+ if (base) { $('urls').value = base; loadFromURLs(); return true; }
128
+
129
+ // HF dataset: ?dataset=user/repo or ?dataset=user/repo/path
130
+ if (dataset) {
131
+ const parts = dataset.split('/');
132
+ const repo = parts.slice(0, 2).join('/');
133
+ const path = parts.slice(2).join('/') || '';
134
+ const hfBase = `https://huggingface.co/datasets/${repo}/resolve/main/${path}`;
135
+ $('urls').value = hfBase;
136
+ log(`📦 Loading HF dataset: ${dataset}`);
137
+ loadFromURLs();
138
+ return true;
139
+ }
140
+
141
+ // eRDFa shard URL: ?rdfa=https://example.com/shard.cbor
142
+ if (rdfa) {
143
+ log(`🔗 Loading eRDFa shard: ${rdfa}`);
144
+ fetch(rdfa).then(r => r.arrayBuffer()).then(buf => {
145
+ log(`📋 eRDFa shard: ${buf.byteLength} bytes`);
146
+ // Try to extract base URL from shard metadata
147
+ const text = new TextDecoder().decode(new Uint8Array(buf).slice(0, 200));
148
+ const m = text.match(/https?:\/\/[^\s"]+/);
149
+ if (m) { $('urls').value = m[0]; loadFromURLs(); }
150
+ }).catch(e => log(`⚠ eRDFa load failed: ${e.message}`));
151
+ return true;
152
+ }
153
+
154
+ return false;
155
+ }
156
+
157
+ async function loadFromURLs() {
158
+ let text = $('urls').value.trim();
159
+ if (!text) {
160
+ // Auto-detect: try local path first
161
+ text = window.location.origin + window.location.pathname.replace(/\/[^/]*$/, '');
162
+ $('urls').value = text;
163
+ log('Auto-detecting local tiles...');
164
+ }
165
+ const lines = text.split('\n').map(l => l.trim()).filter(Boolean);
166
+
167
+ if (lines.length === 1 && !lines[0].match(/\.(png|jpg|json)$/i)) {
168
+ const base = lines[0].replace(/\/+$/, '');
169
+ log(`Base URL: ${base} — fetching 71 tiles...`);
170
+ let loaded = 0;
171
+ let failed = 0;
172
+ for (let i = 1; i <= 71; i++) {
173
+ const pad = String(i).padStart(2, '0');
174
+ const tileUrl = `${base}/tiles/${pad}.png`;
175
+ if (i === 1) log(`First tile: ${tileUrl}`);
176
+ loadTileFromURL(tileUrl, i);
177
+ fetchShard(`${base}/nft71/${pad}.json`, i).then(() => {
178
+ loaded++; $('progress').textContent = `${loaded}/71`;
179
+ }).catch(() => {});
180
+ }
181
+ return;
182
+ }
183
+
184
+ for (const url of lines) {
185
+ const m = url.match(/(\d{1,2})\.(png|jpg|jpeg|json)/i);
186
+ if (m) {
187
+ const idx = parseInt(m[1]);
188
+ if (m[2] === 'json') fetchShard(url, idx);
189
+ else loadTileFromURL(url, idx);
190
+ } else { log(`⚠ Can't parse index from: ${url}`); }
191
+ }
192
+ }
193
+ window.loadFromURLs = loadFromURLs;
194
+
195
+ function loadTileFromURL(url, idx) {
196
+ const img = new Image();
197
+ img.crossOrigin = 'anonymous';
198
+ img.onload = () => { tiles[idx] = {img, pixels: null, url}; log(`✅ tile ${idx}`); renderGrid(); };
199
+ img.onerror = () => log(`⚠ tile ${idx} failed: ${url}`);
200
+ img.src = url;
201
+ }
202
+
203
+ async function fetchShard(url, idx) {
204
+ try { const r = await fetch(url); if (r.ok) shardJSON[idx] = await r.json(); } catch(e) {}
205
+ }
206
+
207
+ $('file-input').onchange = e => {
208
+ for (const file of e.target.files) {
209
+ const m = file.name.match(/(\d{1,2})/);
210
+ const idx = m ? parseInt(m[1]) : Object.keys(tiles).length + 1;
211
+ const img = new Image();
212
+ img.onload = () => { tiles[idx] = {img, pixels: null, url: file.name}; log(`✅ loaded ${file.name} as tile ${idx}`); renderGrid(); };
213
+ img.src = URL.createObjectURL(file);
214
+ }
215
+ };
216
+ function loadFromFile() { $('file-input').click(); }
217
+ window.loadFromFile = loadFromFile;
218
+
219
+ async function loadFromPaste() {
220
+ try {
221
+ const items = await navigator.clipboard.read();
222
+ for (const item of items) {
223
+ for (const type of item.types) {
224
+ if (type.startsWith('image/')) {
225
+ const blob = await item.getType(type);
226
+ const idx = Object.keys(tiles).length + 1;
227
+ const img = new Image();
228
+ img.onload = () => { tiles[idx] = {img, pixels: null, url: 'clipboard'}; log(`✅ pasted as tile ${idx}`); renderGrid(); };
229
+ img.src = URL.createObjectURL(blob);
230
+ return;
231
+ }
232
+ }
233
+ }
234
+ log('⚠ No image in clipboard');
235
+ } catch(e) { log('⚠ Clipboard: ' + e.message); }
236
+ }
237
+ window.loadFromPaste = loadFromPaste;
238
+
239
+ function renderGrid() {
240
+ let html = '';
241
+ for (let i = 1; i <= 71; i++) {
242
+ const t = tiles[i];
243
+ const prime = PRIMES.has(i);
244
+ const cls = [t ? 'found' : '', prime ? 'prime' : ''].join(' ');
245
+ const sel = selected === i ? 'outline:2px solid #0ff;' : '';
246
+ if (t) {
247
+ html += `<div class="tile ${cls}" style="${sel}" onclick="selectTile(${i})">
248
+ <img src="${t.img.src}"><div class="lbl">${prime?'★':'·'}${i}</div></div>`;
249
+ } else {
250
+ html += `<div class="tile ${cls}" style="${sel}" onclick="selectTile(${i})">
251
+ <div style="padding:15px 0">${prime?'★':'·'}${i}</div><div class="lbl">—</div></div>`;
252
+ }
253
+ }
254
+ $('grid').innerHTML = html;
255
+ }
256
+
257
+ function getPixels(idx) {
258
+ const t = tiles[idx];
259
+ if (!t) return null;
260
+ if (t.pixels) return t.pixels;
261
+ const c = document.createElement('canvas');
262
+ c.width = t.img.width; c.height = t.img.height;
263
+ c.getContext('2d').drawImage(t.img, 0, 0);
264
+ t.pixels = c.getContext('2d').getImageData(0, 0, c.width, c.height).data;
265
+ return t.pixels;
266
+ }
267
+
268
+ function selectTile(idx) {
269
+ selected = idx;
270
+ renderGrid();
271
+ const t = tiles[idx];
272
+ if (t) {
273
+ const canvas = $('canvas');
274
+ canvas.width = t.img.width; canvas.height = t.img.height;
275
+ canvas.getContext('2d').drawImage(t.img, 0, 0);
276
+ }
277
+ if (shardJSON[idx]) {
278
+ $('shard-out').textContent = JSON.stringify(shardJSON[idx], null, 2).slice(0, 3000);
279
+ } else {
280
+ $('shard-out').textContent = `Shard ${idx} — no JSON loaded`;
281
+ }
282
+ }
283
+ window.selectTile = selectTile;
284
+
285
+ function decodeSelected() {
286
+ if (!wasmReady) { log('⚠ WASM not loaded yet'); return; }
287
+ if (!selected || !tiles[selected]) { log('Select a tile first'); return; }
288
+ const rgba = getPixels(selected);
289
+ if (!rgba) return;
290
+
291
+ const bytes = decode_tile(new Uint8Array(rgba));
292
+ tileBytes[selected] = bytes;
293
+
294
+ const nonZero = bytes.filter(b => b !== 0).length;
295
+ const hex = Array.from(bytes.slice(0, 32)).map(b => b.toString(16).padStart(2, '0')).join(' ');
296
+ const magic = String.fromCharCode(bytes[0], bytes[1], bytes[2], bytes[3]);
297
+ $('decode-out').textContent = `Tile ${selected} — ${bytes.length}B extracted (${nonZero} non-zero)\nFirst 4: "${magic}"\nHex: ${hex}…`;
298
+ log(`✅ decoded tile ${selected}: ${nonZero} non-zero bytes`);
299
+ }
300
+ window.decodeSelected = decodeSelected;
301
+
302
+ function decodeAll() {
303
+ if (!wasmReady) { log('⚠ WASM not loaded yet'); return; }
304
+ let count = 0;
305
+ for (let i = 1; i <= 71; i++) {
306
+ if (!tiles[i]) continue;
307
+ const rgba = getPixels(i);
308
+ if (!rgba) continue;
309
+ tileBytes[i] = decode_tile(new Uint8Array(rgba));
310
+ count++;
311
+ }
312
+ log(`✅ decoded ${count} tiles via WASM`);
313
+ $('decode-out').textContent = `${count} tiles decoded. Click "Reconstruct WAV" to assemble.`;
314
+ }
315
+ window.decodeAll = decodeAll;
316
+
317
+ function reconstruct() {
318
+ if (!wasmReady) { log('⚠ WASM not loaded yet'); return; }
319
+ const n = Object.keys(tiles).length;
320
+ if (n < 71) log(`⚠ Have ${n}/71 tiles`);
321
+
322
+ log('Decoding all tiles via WASM...');
323
+ // Decode any missing tiles
324
+ for (let i = 1; i <= 71; i++) {
325
+ if (tileBytes[i]) continue;
326
+ const rgba = getPixels(i);
327
+ if (rgba) tileBytes[i] = decode_tile(new Uint8Array(rgba));
328
+ }
329
+
330
+ // Concatenate all tile bytes in order
331
+ const total = TILE_CAP * 71;
332
+ const allBytes = new Uint8Array(total);
333
+ for (let i = 1; i <= 71; i++) {
334
+ if (tileBytes[i]) allBytes.set(tileBytes[i], (i - 1) * TILE_CAP);
335
+ }
336
+
337
+ // Use WASM to parse NFT7
338
+ const info = reconstruct_payload(allBytes);
339
+ const parsed = JSON.parse(info);
340
+
341
+ if (parsed.error) {
342
+ log(`⚠ ${parsed.error}`);
343
+ $('decode-out').textContent = `Error: ${parsed.error}\nFirst 32 bytes: ${parsed.first32}`;
344
+ return;
345
+ }
346
+
347
+ let out = `🎵 NFT7 decoded — ${parsed.segments.length} segments:\n`;
348
+ for (const s of parsed.segments) out += ` ${s.name}: ${s.size.toLocaleString()} B sha256:${s.sha256.slice(0,16)}…\n`;
349
+ $('decode-out').textContent = out;
350
+ log(`🎵 ${parsed.segments.length} segments reconstructed`);
351
+
352
+ const MIME = {wav:'audio/wav', midi:'audio/midi', pdf:'application/pdf',
353
+ source:'text/plain', lilypond:'text/x-lilypond', data:'text/plain', witnesses:'application/json'};
354
+ const EXT = {wav:'.wav', midi:'.midi', pdf:'.pdf',
355
+ source:'.txt', lilypond:'.ly', data:'.txt', witnesses:'.json'};
356
+
357
+ let html = `<p style="color:#0ff">retro-sync — ${parsed.segments.length} files from ${n} tiles</p>`;
358
+
359
+ // Parse witnesses for verification
360
+ let witnesses = [];
361
+ try {
362
+ const wData = extract_segment(allBytes, 'witnesses');
363
+ const wText = new TextDecoder().decode(wData);
364
+ // witnesses are concatenated JSON objects — split on }{ boundary
365
+ witnesses = wText.split(/\}\s*\{/).map((s,i,a) =>
366
+ JSON.parse((i>0?'{':'') + s + (i<a.length-1?'}':''))
367
+ );
368
+ } catch(e) {}
369
+
370
+ // Show witness chain
371
+ if (witnesses.length) {
372
+ html += `<div style="margin:8px 0;padding:6px;background:#111;border:1px solid #333">`;
373
+ html += `<div style="color:#0ff;margin-bottom:4px">🔗 Witness Chain (${witnesses.length} steps)</div>`;
374
+ for (const w of witnesses) {
375
+ if (w.output_hash) {
376
+ html += `<div style="font-size:.75em;color:#8b949e">`;
377
+ html += `${w.step}: <span style="color:#ff0">${w.output_hash.slice(0,16)}…</span> `;
378
+ html += `${w.output_file||''} ${w.output_bytes?'('+w.output_bytes.toLocaleString()+'B)':''} `;
379
+ html += `<span style="color:#666">${w.tool||''} ${w.tool_version||''}</span></div>`;
380
+ } else if (w.chain_hash) {
381
+ html += `<div style="font-size:.75em;color:#0f0">`;
382
+ html += `${w.step}: commitment <span style="color:#ff0">${w.chain_hash.slice(0,32)}…</span></div>`;
383
+ } else if (w.sha256) {
384
+ html += `<div style="font-size:.75em;color:#8b949e">`;
385
+ html += `${w.step}: source <span style="color:#ff0">${w.sha256.slice(0,16)}…</span> ${w.file||''}</div>`;
386
+ }
387
+ }
388
+ html += `</div>`;
389
+ }
390
+
391
+ // Download + preview for each segment
392
+ for (const s of parsed.segments) {
393
+ const data = extract_segment(allBytes, s.name);
394
+ const blob = new Blob([data], {type: MIME[s.name] || 'application/octet-stream'});
395
+ const url = URL.createObjectURL(blob);
396
+ const ext = EXT[s.name] || '.bin';
397
+ const sz = s.size > 1048576 ? (s.size/1048576).toFixed(1)+' MB' : (s.size/1024).toFixed(1)+' KB';
398
+ html += `<div style="margin:4px 0">`;
399
+ html += `<a href="${url}" download="segment${ext}" style="color:#0f0">⬇ ${s.name}${ext}</a> `;
400
+ html += `<span style="color:#888">${sz}</span> `;
401
+ html += `<span style="color:#ff0;font-size:.7em">sha256:${s.sha256.slice(0,16)}…</span>`;
402
+ if (s.name === 'wav') {
403
+ html += `<br><audio controls src="${url}" style="width:100%;margin:2px 0"></audio>`;
404
+ } else if (s.name === 'pdf') {
405
+ html += ` <a href="${url}" target="_blank" style="color:#58a6ff">📄 view</a>`;
406
+ } else if (s.name === 'midi_bundle') {
407
+ // Split bundle into individual MIDIs at MThd boundaries
408
+ const arr = new Uint8Array(data);
409
+ const midis = [];
410
+ for (let j = 0; j < arr.length - 4; j++) {
411
+ if (arr[j]===0x4D && arr[j+1]===0x54 && arr[j+2]===0x68 && arr[j+3]===0x64) midis.push(j);
412
+ }
413
+ html += `<div style="margin:4px 0;color:#0ff">${midis.length} MIDIs in bundle</div>`;
414
+ for (let m = 0; m < midis.length; m++) {
415
+ const start = midis[m];
416
+ const end = m+1 < midis.length ? midis[m+1] : arr.length;
417
+ const midiData = arr.slice(start, end);
418
+ const midiBlob = new Blob([midiData], {type:'audio/midi'});
419
+ const midiUrl = URL.createObjectURL(midiBlob);
420
+ html += `<div style="margin:2px 0">`;
421
+ html += `<a href="${midiUrl}" download="invention_${m+1}.mid" style="color:#0f0">⬇ #${m+1}</a> `;
422
+ html += `<span style="color:#888">${(end-start/1024).toFixed(1)}KB</span> `;
423
+ html += `<button onclick="playMidi(this,'${midiUrl}')" style="font-size:10px">▶ Play</button>`;
424
+ html += `</div>`;
425
+ }
426
+ } else if (s.name === 'midi') {
427
+ html += ` <span style="color:#888">🎹 MIDI</span>`;
428
+ } else if (['source','lilypond','data','witnesses'].includes(s.name)) {
429
+ const text = new TextDecoder().decode(data);
430
+ html += `<pre style="color:#0f0;font-size:.7em;max-height:80px;overflow:auto;margin:2px 0;padding:3px;background:#111;border:1px solid #222">${text.replace(/</g,'&lt;').slice(0,2000)}</pre>`;
431
+ }
432
+ html += `</div>`;
433
+ }
434
+ $('player').innerHTML = html;
435
+ }
436
+ window.reconstruct = reconstruct;
437
+
438
+ // MIDI player via Tone.js + @tonejs/midi
439
+ let toneLoaded = false;
440
+ async function loadTone() {
441
+ if (toneLoaded) return;
442
+ const s1 = document.createElement('script');
443
+ s1.src = 'https://cdn.jsdelivr.net/npm/tone@14/build/Tone.min.js';
444
+ document.head.appendChild(s1);
445
+ const s2 = document.createElement('script');
446
+ s2.src = 'https://cdn.jsdelivr.net/npm/@tonejs/midi@2/build/Midi.js';
447
+ document.head.appendChild(s2);
448
+ await new Promise(r => { s2.onload = r; setTimeout(r, 3000); });
449
+ toneLoaded = true;
450
+ }
451
+
452
+ let currentSynth = null;
453
+ async function playMidi(btn, url) {
454
+ await loadTone();
455
+ if (currentSynth) { currentSynth.dispose(); currentSynth = null; btn.textContent = '▶ Play'; }
456
+ btn.textContent = '⏳';
457
+ try {
458
+ const resp = await fetch(url);
459
+ const buf = await resp.arrayBuffer();
460
+ const midi = new Midi(buf);
461
+ await Tone.start();
462
+ const synth = new Tone.PolySynth(Tone.Synth, {maxPolyphony: 16}).toDestination();
463
+ currentSynth = synth;
464
+ const now = Tone.now();
465
+ for (const track of midi.tracks) {
466
+ for (const note of track.notes) {
467
+ synth.triggerAttackRelease(note.name, note.duration, now + note.time, note.velocity);
468
+ }
469
+ }
470
+ btn.textContent = '⏹ Stop';
471
+ btn.onclick = () => { synth.dispose(); currentSynth = null; btn.textContent = '▶ Play'; btn.onclick = () => playMidi(btn, url); };
472
+ } catch(e) { log('⚠ MIDI play error: ' + e.message); btn.textContent = '▶ Play'; }
473
+ }
474
+ window.playMidi = playMidi;
475
+
476
+ renderGrid();
477
+ log('🚀 Page loaded, checking params...');
478
+ if (!initFromParams()) {
479
+ log('📍 No URL params, loading local preset...');
480
+ loadPreset('local');
481
+ }
482
+ </script>
483
+ </body>
484
+ </html>