title: NodeJS - How to pipe same video stream to multiple clients?
body: <p>We have a situation trying to serve a video stream.</p>
  
  <p>Since HTML5 video tag does not support udp to multicast, we are trying to re-use an already converted ffmpeg stream and send it to more than one response. But that does not work. </p>
  
  <p>The first response gets the stream alright, but the second one does not.
  It seems that the stream cannot be piped out to another response, neither can it be cloned.</p>
  
  <p>Has anyone done that before? Any ideas?</p>
  
  <p>Thanks in advance!</p>
  
  <p>Here's the code:</p>
  
  <pre><code>var request = require('request');
  var http = require('http');
  var child_process = require("child_process");
  var n = 1;
  var stdouts = {};
  
  http.createServer(function (req, resp) {
  
  console.log("***** url ["+req.url+"], call "+n);
  
  if (req.url != "/favicon.ico" &amp;&amp; req.url != "/")
  {
  var params = req.url.substring(1).split("/");
  
  switch (params[0])
  {
    case "VIEW":
      if (params[1] == "C2FLOOR1" || params[1] == "C2FLOOR2" || params[1] == "C2PORFUN" || params[1] == "C2TESTCAM")
        var camera = "rtsp://192.168.16.19:554/Inter/Cameras/Stream?Camera="+params[1];
      else
        var camera = "http://192.168.16.19:8609/Inter/Cameras/GetStream?Camera="+params[1];
  
      // Write header
      resp.writeHead(200, {'Content-Type': 'video/ogg', 'Connection': 'keep-alive'});
  
      if (stdouts.hasOwnProperty(params[1]))
      {
        console.log("Getting stream already created for camera "+params[1]);
  
        var newStdout = Object.create(stdouts[params[1]]);
  
        newStdout.pipe(resp);
      }
      else
      {
          // Start ffmpeg
          var ffmpeg = child_process.spawn("ffmpeg",[
          "-i",camera,
          "-vcodec","libtheora",
          "-qscale:v","7",        // video quality
          "-f","ogg",             // File format
          "-g","1",               // GOP (Group Of Pictures) size
          "-"                     // Output to STDOUT
          ]);
  
          stdouts[params[1]] = ffmpeg.stdout;
  
          // Pipe the video output to the client response
          ffmpeg.stdout.pipe(resp);
  
      console.log("Initializing camera at "+camera);
      }
  
      // Kill the subprocesses when client disconnects
  /*
      resp.on("close",function(){
        ffmpegs[params[1]].kill();
        console.log("FIM!");
      });
  */
      break;
  }
  }
  else
  {
  resp.writeHeader(200, {"Content-Type": "text/html"});
  resp.write("WRONG CALL");
  resp.end();
  }
  n++;
  
  }).listen(8088);
  
  console.log('Server running at port 8088');
  </code></pre>