Q: How to read stream data as chunk? I try to lean, how to read chunk of stream data. It almost works, it likes i misunderstanding implement allocate buffer size in pause event of stdout. the video that i use is https://www.youtube.com/watch?v=oiNkumxPVzU. 480p. ffmpeg freeze to encode at 03:53, no error, just freeze likes missing require bytes. the video length exactly is 03:55.
const { spawn } = require('child_process');
const path = require('path');

const decArgs = [
    '-i', path.join(__dirname + '/public/future.mkv'),
    '-an',
    '-pix_fmt', 'rgb32',
    '-f', 'rawvideo',
    '-'
];

const decode = spawn('ffmpeg', decArgs, {
    stdio: [
        'ignore',
        'pipe',
        'ignore'
    ] 
});

// Encode section
const width = 854;
const height = 480;
const channels = 4;
const fps = 29.97002997002997.toString();
const colorsLength = width*height*channels;


const encArgs = [
    '-pix_fmt', 'rgb32',
    '-f', 'rawvideo',
    '-s', `${width}x${height}`,
    '-r', fps,
    '-i', '-',
    '-c:v', 'libx264',
    '-preset', 'ultrafast',
    '-crf', '30',
    '-pix_fmt', 'yuv420p',
    '-r', fps,
    '-y',
    path.join(__dirname + '/public/output.mp4')
];

const encode = spawn('ffmpeg', encArgs, {
    stdio: [
        'pipe',
        'ignore',
        'pipe'
    ]
});

// colors RGBA
let buffer = Buffer.alloc(0);
decode.stdout.on('data', data => {
    const allocSize = buffer.length + data.length;
    buffer = Buffer.concat([buffer, data], allocSize);
    
    if (buffer.length > colorsLength) decode.stdout.pause();
});

decode.stdout.on('pause', () => {
    // Create new buffer with size of colors length
    const bufferData = Buffer.alloc(colorsLength);
    buffer.copy(bufferData, 0, 0, colorsLength);
    // after manipulate the buffer send it to encode
    encode.stdin.write(bufferData);
    
    // Create new buffer to take out left buffer. cause stream length cant be predict.
    const leftBuffer = Buffer.alloc(buffer.length - bufferData.length);
    buffer.copy(leftBuffer, 0, buffer.length - bufferData.length, buffer.length);
    buffer = leftBuffer;

    decode.stdout.resume()
});

decode.stdout.on('end', () => {
    if (buffer.length) encode.stdin.write(buffer);
})

encode.stderr.on('data', data => {
    console.log(data.toString())
})

