title: FFMPEG - how to stream video directly to HLS
body: <p>We need to get video file/data as a stream from the user or from a caller to our API and while processing it we need to generate live stream using HLS</p>
  <p>FFMPEG support creating live stream in HLS format with the following command</p>
  <pre><code> String cmd[] = new String[]{
                  &quot;ffmpeg&quot;,
                  &quot;-re&quot;,
                  &quot;-i&quot;, src,
                  &quot;-c:v:0&quot;, &quot;copy&quot;,
                  &quot;-b:v:1&quot;, &quot;512k&quot;,
                  &quot;-b:a:0&quot;, &quot;64k&quot;,
                  &quot;-b:a:1&quot;, &quot;32k&quot;,
                  &quot;-map&quot;, &quot;0:v&quot;,
                  &quot;-map&quot;, &quot;0:a&quot;,
                  &quot;-map&quot;, &quot;0:v&quot;,
                  &quot;-map&quot;, &quot;0:a&quot;,
                  &quot;-f&quot;, &quot;hls&quot;,
                  &quot;-var_stream_map&quot;, &quot;v:0,a:0 v:1,a:1&quot;,
                  &quot;-hls_time&quot;, &quot;5&quot;,
                  &quot;-hls_segment_filename&quot;, folder+&quot;/stream_%v/data%02d.ts&quot;,
                  &quot;-hls_list_size&quot;, &quot;5&quot;,
                  &quot;-hls_delete_threshold&quot;, &quot;2&quot;,
                  &quot;-hls_flags&quot;, &quot;delete_segments&quot;,
                  &quot;-master_pl_name&quot;, &quot;playlist.m3u8&quot;,
                  folder+&quot;/stream_%v/sub-playlist.m3u8&quot;};
    
  </code></pre>
  <p>where the source can be</p>
  <ol>
  <li>A file on disk  /path/file.mp4</li>
  <li>A UDP url  udp://localhost:port</li>
  </ol>
  <p>We are getting the bytes that we need to encode in a function like this:</p>
  <pre><code>handleFileStream(HttpServletRequest request)
  </code></pre>
  <p>and then we can loop the input stream and send it to FFMPEG using UDP</p>
  <pre><code>ServletInputStream inputStream = request.getInputStream();
  byte[] buffer = new byte[8 * 1024];
  int bytesRead;
   while ((bytesRead = inputStream.read(buffer)) != -1) {
       DatagramPacket packet = new DatagramPacket(buffer, bytesRead, address, udpCurPort);
       socket.send(packet);               
   }
  </code></pre>
  <p>but this method has 2 problems that we can see</p>
  <ol>
  <li><p>we need to communicate with FFMPEG with udp and we need a new port for each conversion and we assume that we will have multiple conversions running simultaneously</p>
  </li>
  <li><p>we see that ffmpeg creates the HLS play list only at the end of the stream , and we what the stream to be created during the stream process</p>
  </li>
  </ol>
  <p>Is there a better way to pass streaming bytes to FFMPEG?</p>
  <p>We are running inside a java environment and we launch FFMPEG like this:</p>
  <pre><code>Runtime rt = Runtime.getRuntime();
  Process pr = rt.exec(cmd);
  </code></pre>