UNPKG

frame-hop

Version:

Frame slicing for windowed signal processing

40 lines (37 loc) 1.15 kB
"use strict" // Slices a stream of frames into a stream of overlapping windows // The size of each frame is the same as the size o function createHopStream(frame_size, hop_size, onFrame, max_data_size) { if(hop_size > frame_size) { throw new Error("Hop size must be smaller than frame size") } max_data_size = max_data_size || frame_size var buffer = new Float32Array(2*frame_size + max_data_size) var ptr = 0 var frame_slices = [] for(var j=0; j+frame_size<=buffer.length; j+=hop_size) { frame_slices.push(buffer.subarray(j, j+frame_size)) } return function processHopData(data) { var i, j, k buffer.set(data, ptr) ptr += data.length for(i=0, j=0; j+frame_size<=ptr; ++i, j+=hop_size) { onFrame(frame_slices[i]) } for(k=0; j<ptr; ) { buffer.set(frame_slices[i], k) var nhops = Math.ceil((k+frame_size) / hop_size)|0 var nptr = nhops * hop_size if(nptr !== k+frame_size) { nhops -= 1 nptr -= hop_size } i += nhops j += (nptr - k) k = nptr } ptr += k - j } } module.exports = createHopStream