View Source LiveExWebRTC.Publisher (live_ex_webrtc v0.4.0)

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

It:

  • renders:
    • audio and video device selects
    • audio and video stream configs
    • stream preview
    • transmission stats
  • on clicking "Start Streaming", creates WebRTC PeerConnection both on the client and server side
  • connects those two peer connections negotiatiing a single audio and video track
  • sends audio and video from selected devices to the live view process
  • publishes received audio and video packets to the configured PubSub

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

If LiveExWebRTC.Player is not used, you should subscribe to streams:audio:#{publisher_id} and streams:video:#{publisher_id} topics.

Keyframe requests should be sent on publishers:#{publisher_id} topic e.g.

PubSub.broadcast(LiveTwitch.PubSub, "publishers:my_publisher", {:live_ex_webrtc, :keyframe_req})

JavaScript Hook

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

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

Examples

defmodule LiveTwitchWeb.StreamerLive do
  use LiveTwitchWeb, :live_view

  alias LiveExWebRTC.Publisher

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

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

Summary

Functions

Attaches required hooks and creates t/0 struct.

Helper function for rendering Publisher 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.Publisher.live_render/1.

Options:

Helper function for rendering Publisher live view.

Attributes

  • socket (Phoenix.LiveView.Socket) (required) - Parent live view socket.
  • publisher (LiveExWebRTC.Publisher) (required) - Publisher struct. It is used to pass 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 Publisher struct.