live video(cam) streaming in mpeg-ts format

I’m trying to stream my webcam in mpeg-ts format using ffmpeg, it works good with single user, when send user connects it starts another ffmpeg process. how can i share single ffmpeg process output to all connected user like multicast

def live_cam(conn, _params) do                
    conn = put_resp_header(conn, "content-type", "video/MP2T")
    conn = send_chunked(conn, 200)
    ffmpeg_args = ["-y", "-nostdin", "-hide_banner", "-loglevel", "0", "-f", "v4l2", "-framerate", "25", "-video_size", "1280x720", "-input_format", "mjpeg", "-i", "/dev/video1",
						"-c", "libx264", "-movflags", "faststart", "-f", "mpegts", "-"]        
    port = Port.open({:spawn_executable, "/usr/local/bin/ffmpeg"}, [{:args, ffmpeg_args}, :stream, :binary, :exit_status, :hide, :use_stdio, :stderr_to_stdout])
    
    
    handle_output(port, conn)        
    conn
end

defp handle_output(port, conn) do
    receive do
      {^port, {:data, data}} ->                        
        chunk(conn, data)
        handle_output(port, conn)
      {^port, {:exit_status, status}} ->            
        status        
    end
end

Registry should do the job, need to wrap each connection in a Task or GenServer, when you get output from ffmpeg, use Registry.dispatch/4 to send to all connections, like a PubSub. This design also allows for multiple cameras.

3 Likes