(
sendPacket: (packet: Uint8Array) => void,
)
| 32 | } |
| 33 | |
| 34 | export function createOpusPacketizer( |
| 35 | sendPacket: (packet: Uint8Array) => void, |
| 36 | ) { |
| 37 | const enc = createOpusEncoder(); |
| 38 | let pending = Buffer.alloc(0); |
| 39 | let closed = false; |
| 40 | |
| 41 | const push = (pcm: Uint8Array) => { |
| 42 | if (closed) return; |
| 43 | if (!pcm || pcm.length === 0) return; |
| 44 | |
| 45 | pending = Buffer.concat([pending, Buffer.from(pcm)]); |
| 46 | |
| 47 | while (pending.length >= FRAME_SIZE) { |
| 48 | const frame = pending.subarray(0, FRAME_SIZE); |
| 49 | pending = pending.subarray(FRAME_SIZE); |
| 50 | try { |
| 51 | const packet = enc.encode(frame); |
| 52 | sendPacket(packet); |
| 53 | } catch (err) { |
| 54 | console.error("Opus encode failed:", err); |
| 55 | } |
| 56 | } |
| 57 | }; |
| 58 | |
| 59 | const flush = (padFinalFrame = false) => { |
| 60 | if (closed) return; |
| 61 | if (pending.length === 0) return; |
| 62 | |
| 63 | if (!padFinalFrame) { |
| 64 | pending = Buffer.alloc(0); |
| 65 | return; |
| 66 | } |
| 67 | |
| 68 | const padded = Buffer.alloc(FRAME_SIZE); |
| 69 | pending.copy(padded, 0, 0, pending.length); |
| 70 | pending = Buffer.alloc(0); |
| 71 | |
| 72 | try { |
| 73 | const packet = enc.encode(padded); |
| 74 | sendPacket(packet); |
| 75 | } catch (err) { |
| 76 | console.error("Opus encode failed:", err); |
| 77 | } |
| 78 | }; |
| 79 | |
| 80 | const reset = () => { |
| 81 | pending = Buffer.alloc(0); |
| 82 | }; |
| 83 | |
| 84 | const close = () => { |
| 85 | closed = true; |
| 86 | pending = Buffer.alloc(0); |
| 87 | }; |
| 88 | |
| 89 | const bufferedBytes = () => pending.length; |
| 90 | |
| 91 | return { push, flush, reset, close, bufferedBytes }; |
no test coverage detected