Search code examples
node.jsffmpegstreampipechild-process

Use both stdio and stout in the same child process


I am using ffmpeg to combine the audio/video 2 streams and pipe them to express. Here is my code:

var ffmpeg = cp.spawn('ffmpeg', [
        // Set inputs
        '-i', 'pipe:4',
        '-i', 'pipe:5',
        // Map audio & video from streams
        '-map', '0:v',
        '-map', '1:a',
        // Keep encoding
        '-c', 'copy',
        '-movflags', 'frag_keyframe+empty_moov',
        '-f', 'mp4',
        // Define output file
        'pipe:1',
      ], {
        stdio: [
          /* Standard: stdin, stdout, stderr */
          'inherit', 'inherit', 'inherit',
          /* Custom: pipe:3, pipe:4, pipe:5 */
          'pipe', 'pipe', 'pipe',
        ],
      });
      video.pipe(ffmpeg.stdio[4]);
      audio.pipe(ffmpeg.stdio[5]);
      res.header('Content-Disposition', 'attachment; filename="video.mp4"');
      ffmpeg.stdout.pipe(res);

But the code gives an error saying that ffmpeg.stout is null. After a bit of research, I found out that you can't have the stdio options array, or else stout will be null. Any way to fix this?


Solution

  • After almost two weeks, I found the answer. When I was looking at the docs, it said:

    If the child was not spawned with stdio[1] set to 'pipe', then this will not be set.

    I realized all I had to do was change the middle inherit to pipe:

            stdio: [
              /* Standard: stdin, stdout, stderr */
              'inherit', 'pipe', 'inherit',
              /* Custom: pipe:3, pipe:4, pipe:5 */
              'pipe', 'pipe', 'pipe',
            ],
    

    Thanks anyways.