// utils/h264Renderer.js
export function createH264WebCodecsRenderer(videoEl) {
    // 1) 生成一个可写的视频轨，绑定到 <video>.srcObject
    const trackGen = new MediaStreamTrackGenerator({ kind: 'video' });
    const writer = trackGen.writable.getWriter();
    const stream = new MediaStream([trackGen]);
    videoEl.srcObject = stream;

    // 简单的 Annex-B 关键帧判断（为了给 EncodedVideoChunk 标 type）
    function isKeyframeAnnexB(buf) {
        const u8 = new Uint8Array(buf);
        for (let i = 0; i + 4 < u8.length; i++) {
            // 00 00 01
            if (u8[i] === 0 && u8[i + 1] === 0 && u8[i + 2] === 1) {
                const nalType = u8[i + 3] & 0x1f;
                if (nalType === 5) return true; // IDR
            }
            // 00 00 00 01
            if (u8[i] === 0 && u8[i + 1] === 0 && u8[i + 2] === 0 && u8[i + 3] === 1) {
                const nalType = u8[i + 4] & 0x1f;
                if (nalType === 5) return true;
            }
        }
        return false;
    }

    // 2) 建立解码器：输出即写入 trackGen，再立刻释放帧
    const decoder = new VideoDecoder({
        output: async (frame) => {
            await writer.write(frame);
            frame.close();
        },
        error: (e) => console.error('VideoDecoder error:', e)
    });

    // H.264，Annex-B（SPS/PPS 从码流里来）
    decoder.configure({
        codec: 'avc1.64001f',          // High@3.1（占位即可）
        optimizeForLatency: true
    });

    // 用一个单调时间戳（微秒）。30fps ≈ 33333us
    let ts = 0;
    const stepUs = 33333;

    // 3) 返回一个“喂数据”的函数 & 清理函数
    return {
        push(buffer /* ArrayBuffer */) {
            const key = isKeyframeAnnexB(buffer);
            const chunk = new EncodedVideoChunk({
                type: key ? 'key' : 'delta',
                timestamp: ts,
                data: new Uint8Array(buffer) // 视图包裹，不拷贝
            });
            ts += stepUs;
            decoder.decode(chunk);
        },
        close() {
            try { writer.close(); } catch { }
            try { decoder.close(); } catch { }
            try { videoEl.srcObject = null; } catch { }
        }
    };
}
