#diplacusis.py   testing script for earphones.     Sherwood 2026
import http.server
import webbrowser
import threading

PORT = 8080

HTML_CONTENT = """<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Musician's Diplacusis & Overlapping Piano</title>
    <style>
        body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; background: #121212; color: #e0e0e0; padding: 20px; text-align: center; }
        .card { background: #1e1e1e; padding: 20px; border-radius: 12px; max-width: 850px; margin: 0 auto 20px auto; box-shadow: 0 4px 15px rgba(0,0,0,0.5); }
        h1 { font-size: 1.5rem; margin-bottom: 10px; color: #fff; }
        p { color: #aaa; font-size: 0.9rem; }
        .controls { display: flex; justify-content: center; gap: 15px; margin: 15px 0; flex-wrap: wrap; }
        button { background: #333; color: white; border: 1px solid #555; padding: 10px 20px; border-radius: 6px; cursor: pointer; font-weight: bold; transition: 0.2s; }
        button:hover { background: #444; }
        button.active-left { background: #1976d2 !important; border-color: #64b5f6; }
        button.active-right { background: #c2185b !important; border-color: #f06292; }
        button.active-center { background: #388e3c !important; border-color: #81c784; }
        .slider-group { margin: 15px 0; text-align: left; background: #252525; padding: 12px; border-radius: 8px; }
        .slider-group label { display: block; margin-bottom: 5px; font-size: 0.85rem; color: #ccc; }
        input[type="range"] { width: 100%; cursor: pointer; }
        
        /* Piano Keyboard CSS */
        .piano-container {
            width: 100%;
            overflow-x: auto;
            white-space: nowrap;
            padding: 15px 0 30px 0;
            margin-top: 15px;
            background: #151515;
            border-radius: 8px;
            border: 1px solid #333;
        }
        .piano {
            display: inline-block;
            position: relative;
            height: 160px;
            user-select: none;
            cursor: pointer;
        }
        .key { display: inline-block; position: relative; border-radius: 0 0 5px 5px; box-sizing: border-box; }
        .white {
            background: #f0f0f0;
            color: #333;
            width: 40px;
            height: 160px;
            border: 1px solid #ccc;
            z-index: 1;
            margin-right: -1px;
        }
        .white:hover, .white.playing { background: #d0d0d0; }
        .white span { position: absolute; bottom: 8px; width: 100%; left: 0; text-align: center; font-size: 0.75rem; font-weight: bold; color: #555; pointer-events: none; }
        .black {
            background: #222;
            color: #fff;
            width: 28px;
            height: 100px;
            position: absolute;
            z-index: 2;
            border: 1px solid #000;
            margin-left: -14px;
        }
        .black:hover, .black.playing { background: #444; }
    </style>
</head>
<body>

    <div class="card">
        <h1>Diplacusis Tester for Earphones</h1>
        <p>Scroll horizontally to test any octave (C2-C6). Black notes overlap traditionally.</p>
        <p>Click on keyboard pitch; select one ear at a time (keyboard short cut: "1" or "3";  Space mutes</p>
        
        <div class="controls">
            <button id="btnLeft" onclick="setEar('left')">Left Ear Only [1]</button>
            <button id="btnBoth" onclick="setEar('center')" class="active-center">Both Ears [2]</button>
            <button id="btnRight" onclick="setEar('right')">Right Ear Only [3]</button>
            <button onclick="stopSound()" style="background:#b71c1c;">Stop [Space]</button>
        </div>

        <div class="slider-group">
            <label id="freqLabel">Frequency: 440.00 Hz (A4)</label>
            <input type="range" id="freqSlider" min="65" max="2000" step="0.1" value="440" oninput="updateFreq(this.value)">
        </div>

        <div class="slider-group">
            <label id="detuneLabel">Right Ear Fine Detune (Cents): 0</label>
            <input type="range" id="detuneSlider" min="-100" max="100" step="1" value="0" oninput="updateDetune(this.value)">
        </div>
    </div>

    <div class="card">
        <h3>Scrollable Traditional Keyboard (C2 to C6)</h3>
        <div class="piano-container">
            <div class="piano" id="pianoKeyboard"></div>
        </div>
        <p style="margin-top:10px; font-size:0.8rem;">Hotkeys: **1** (Left), **2** (Both), **3** (Right), **Space** (Mute)</p>
    </div>

<script>
    let audioCtx = null;
    let masterGain = null;
    let leftGain = null;
    let rightGain = null;
    let oscLeft = null;
    let oscRight = null;
    
    let currentFreq = 440;
    let currentDetune = 0;
    let currentEarMode = 'center';
    let isPlaying = false;

    function initAudio() {
        if (!audioCtx) {
            audioCtx = new (window.AudioContext || window.webkitAudioContext)();
            leftGain = audioCtx.createGain();
            rightGain = audioCtx.createGain();
            const channelMerger = audioCtx.createChannelMerger(2);
            leftGain.connect(channelMerger, 0, 0);
            rightGain.connect(channelMerger, 0, 1);
            masterGain = audioCtx.createGain();
            masterGain.gain.value = 0.15;
            channelMerger.connect(masterGain);
            masterGain.connect(audioCtx.destination);
        }
        if (audioCtx.state === 'suspended') {
            audioCtx.resume();
        }
    }

    function playTone(freq) {
        initAudio();
        stopSound();
        currentFreq = freq;
        document.getElementById('freqSlider').value = freq;
        document.getElementById('freqLabel').innerText = `Frequency: ${freq.toFixed(2)} Hz`;
        oscLeft = audioCtx.createOscillator();
        oscLeft.type = 'sine';
        oscLeft.frequency.value = freq;
        oscLeft.connect(leftGain);
        oscRight = audioCtx.createOscillator();
        oscRight.type = 'sine';
        oscRight.frequency.value = freq * Math.pow(2, currentDetune / 1200);
        oscRight.connect(rightGain);
        oscLeft.start();
        oscRight.start();
        isPlaying = true;
        applyEarMode();
    }

    function stopSound() {
        if (oscLeft) { try { oscLeft.stop(); } catch(e){} oscLeft = null; }
        if (oscRight) { try { oscRight.stop(); } catch(e){} oscRight = null; }
        isPlaying = false;
    }

    function setEar(mode) {
        currentEarMode = mode;
        document.getElementById('btnLeft').className = mode === 'left' ? 'active-left' : '';
        document.getElementById('btnBoth').className = mode === 'center' ? 'active-center' : '';
        document.getElementById('btnRight').className = mode === 'right' ? 'active-right' : '';
        applyEarMode();
    }

    function applyEarMode() {
        if (!leftGain || !rightGain) return;
        if (currentEarMode === 'left') {
            leftGain.gain.setValueAtTime(1, audioCtx.currentTime);
            rightGain.gain.setValueAtTime(0, audioCtx.currentTime);
        } else if (currentEarMode === 'right') {
            leftGain.gain.setValueAtTime(0, audioCtx.currentTime);
            rightGain.gain.setValueAtTime(1, audioCtx.currentTime);
        } else {
            leftGain.gain.setValueAtTime(1, audioCtx.currentTime);
            rightGain.gain.setValueAtTime(1, audioCtx.currentTime);
        }
    }

    function updateFreq(val) {
        currentFreq = parseFloat(val);
        document.getElementById('freqLabel').innerText = `Frequency: ${currentFreq.toFixed(2)} Hz`;
        if (isPlaying) {
            if (oscLeft) oscLeft.frequency.setValueAtTime(currentFreq, audioCtx.currentTime);
            if (oscRight) oscRight.frequency.setValueAtTime(currentFreq * Math.pow(2, currentDetune / 1200), audioCtx.currentTime);
        }
    }

    function updateDetune(val) {
        currentDetune = parseFloat(val);
        document.getElementById('detuneLabel').innerText = `Right Ear Fine Detune (Cents): ${currentDetune > 0 ? '+' : ''}${currentDetune}`;
        if (isPlaying && oscRight) {
            oscRight.frequency.setValueAtTime(currentFreq * Math.pow(2, currentDetune / 1200), audioCtx.currentTime);
        }
    }

    const noteNames = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"];
    const container = document.getElementById('pianoKeyboard');

    for (let midi = 36; midi <= 84; midi++) {
        const noteIndex = midi % 12;
        const octave = Math.floor(midi / 12) - 1;
        const name = noteNames[noteIndex] + octave;
        const freq = 440 * Math.pow(2, (midi - 69) / 12);
        
        const isBlack = name.includes("#");
        
        if (!isBlack) {
            const whiteKey = document.createElement('div');
            whiteKey.className = 'key white';
            const labelSpan = document.createElement('span');
            labelSpan.innerText = name;
            whiteKey.appendChild(labelSpan);
            whiteKey.onclick = () => playTone(freq);
            
            const nextMidi = midi + 1;
            const nextNoteIndex = nextMidi % 12;
            const nextName = noteNames[nextNoteIndex] + octave;
            
            if (nextName.includes("#") && nextMidi <= 84) {
                const blackKey = document.createElement('div');
                blackKey.className = 'key black';
                const blackFreq = 440 * Math.pow(2, (nextMidi - 69) / 12);
                blackKey.onclick = (e) => {
                    e.stopPropagation();
                    playTone(blackFreq);
                };
                whiteKey.appendChild(blackKey);
            }
            
            container.appendChild(whiteKey);
        }
        if (isBlack) continue;
    }

    window.addEventListener('keydown', (e) => {
        if (e.key === '1') setEar('left');
        if (e.key === '2') setEar('center');
        if (e.key === '3') setEar('right');
        if (e.code === 'Space') { e.preventDefault(); stopSound(); }
    });
</script>

</body>
</html>
"""

class MyHandler(http.server.SimpleHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.end_headers()
        self.wfile.write(HTML_CONTENT.encode("utf-8"))

def run_server():
    server = http.server.HTTPServer(('127.0.0.1', PORT), MyHandler)
    print(f"Diplacusis tester running at http://127.0.0.1:{PORT}")
    server.serve_forever()

if __name__ == '__main__':
    threading.Thread(target=run_server, daemon=True).start()
    webbrowser.open(f"http://127.0.0.1:{PORT}")
    input("Press Enter in this terminal to stop the server...\n")