View Source LiveExWebRTC.Player (live_ex_webrtc v0.3.0)

Component for sending and playing audio and video via WebRTC from a Phoenix app to a browser (browser subscribes).

It:

  • renders a single HTMLVideoElement
  • creates WebRTC PeerConnection both on the server and client side
  • connects those two peer connections negotiating a single audio and a single video track
  • attaches audio and video on the client side to the HTMLVideoElement
  • subscribes to the configured PubSub where it expects audio and video packets and sends them to the client side.

When LiveExWebRTC.Publisher is used, audio an video packets are delivered automatically, assuming both components are configured with the same PubSub.

If LiveExWebRTC.Publisher is not used, you should send packets to the streams:audio:#{publisher_id} and streams:video:#{publisher_id} topics.

Keyframe requests are sent under publishers:#{publisher_id} topic.

JavaScript Hook

Player live view requires JavaScript hook to be registered under Player name. The hook can be created using createPlayerHook function. For example:

import { createPlayerHook } from "live_ex_webrtc";
let Hooks = {};
const iceServers = [{ urls: "stun:stun.l.google.com:19302" }];
Hooks.Player = createPlayerHook(iceServers);
let liveSocket = new LiveSocket("/live", Socket, {
  // ...
  hooks: Hooks
});

Examples

defmodule LiveTwitchWeb.StreamViewerLive do
  use LiveTwitchWeb, :live_view

  alias LiveExWebRTC.Player

  @impl true
  def render(assigns) do
  ~H"""
  <Player.live_render socket={@socket} player={@player} />
  """
  end

  @impl true
  def mount(_params, _session, socket) do
    socket = Player.attach(socket, id: "player", publisher_id: "publisher", pubsub: LiveTwitch.PubSub)
    {:ok, socket}
  end
end

Summary

Functions

Attaches required hooks and creates t/0 struct.

Helper function for rendering Player live view.

Types

@type on_connected() :: (publisher_id :: String.t() -> any())
@type on_packet() ::
  (publisher_id :: String.t(),
   packet_type :: :audio | :video,
   packet :: ExRTP.Packet.t(),
   socket :: Phoenix.LiveView.Socket.t() ->
     packet :: ExRTP.Packet.t())
@type t() :: struct()

Functions

Attaches required hooks and creates t/0 struct.

Created struct is saved in socket's assigns and has to be passed to LiveExWebRTC.Player.live_render/1.

Options:

Helper function for rendering Player live view.

Attributes

  • socket (Phoenix.LiveView.Socket) (required) - Parent live view socket.

  • player (LiveExWebRTC.Player) (required) - Player struct. It is used to pass player id and publisher id to the newly created live view via live view session. This data is then used to do a handshake between parent live view and child live view during which child live view receives the whole Player struct.

  • class (:string) - CSS/Tailwind classes for styling HTMLVideoElement. Defaults to nil.