// src/workers/decoder.worker.js
let inflight = 0;
const MAX_INFLIGHT = 4;

// 可选：识别 'scrcpy_message' 头
const MAGIC = new TextEncoder().encode('scrcpy_message');
function startsWithHeader(buffer) {
    if (buffer.byteLength < MAGIC.length) return false;
    const head = new Uint8Array(buffer, 0, MAGIC.length);
    for (let i = 0; i < MAGIC.length; i++) if (head[i] !== MAGIC[i]) return false;
    return true;
}
function bufferTailToString(buffer, offset) {
    const view = new Uint8Array(buffer, offset);
    return new TextDecoder('utf-8').decode(view);
}

self.onmessage = (e) => {
    const { type, buffer, meta } = e.data || {};
    if (type !== 'video' || !buffer) return;

    // 控制消息永不丢
    if (startsWithHeader(buffer)) {
        const text = bufferTailToString(buffer, MAGIC.length);
        self.postMessage({ type: 'clipboard', text, meta });
        return;
    }

    // 真正的丢帧：在途已满就扔掉
    if (inflight >= MAX_INFLIGHT) {
        return; // 丢掉这帧
    }

    inflight++;
    try {
        const chunk = new Uint8Array(buffer);
        // console.log("进入视频帧")
        self.postMessage({ type: 'video', chunk, meta }, [chunk.buffer]);
    } finally {
        inflight--;
    }
};
