title: FFmpeg live streaming webm video to multiple http clients over Nodejs
body: <p>I am trying to share a live stream of my screen over an ExpressJS server.
  I cannot save ffmpeg output to a file or start more than one ffmpeg instance for performance reason.
  My current solution is to pipe ffmpeg's stdout and stream it to each connected client.</p>
  
  <p><strong>index.js</strong></p>
  
  <pre><code>const express = require('express');
  const app = express();
  const request = require('request');
  const FFmpeg = require('./FFmpeg');
  
  const APP_PORT = 3500;
  
  app.get('/stream', function (req, res) {
    const recorder = FFmpeg.getInstance();
  
    res.writeHead(200, {
      "content-type": "video/webm",
    });
    recorder.stdout.on('data', res.write);
    req.on('close', FFmpeg.killInstance);
  });
  
  app.listen(APP_PORT, function () {
    console.log(`App is listening on port ${APP_PORT}!`)
  });
  </code></pre>
  
  <p><strong>FFmpeg.js</strong></p>
  
  <pre><code>const spawn = require('child_process').spawn;
  const ffmpegPath = 'ffmpeg';
  const ffmpegOptions = [
    '-loglevel', 'panic',
    '-y',
    '-f',
    'alsa',
    '-ac',
    '2',
    '-i',
    'pulse',
    '-f',
    'x11grab',
    '-r',
    '25',
    '-i',
    ':0.0+0,0',
    '-acodec',
    'libvorbis',
    '-preset',
    'ultrafast',
    '-vf',
    'scale=320:-1',
    "-vcodec", "libvpx-vp9",
    '-f', 'webm',
    'pipe:1',
  ];
  
  module.exports = {
    start,
    getInstance,
    killInstance,
  };
  
  let instance = null;
  let connections = 0;
  
  function killInstance() {
    connections -= 1;
    if (connections &lt; 1) {
      instance.kill();
      instance = null;
    }
  };
  
  function getInstance() {
    connections += 1;
    if (!instance) instance = start();
    return instance;
  };
  
  function start() {
    return spawn(ffmpegPath, ffmpegOptions);
  };
  </code></pre>
  
  <p>It is working well for one client, but I cannot manage to stream to several clients at the same time (might be related to missing keyframes).</p>