Live streams
One person presents live to everyone watching: the picture, a chat beside it, reactions, and the count of who watches. In WordPlusRealtimeCalls, on the same media servers as the browser: an app watches a stream a browser presents, and goes live itself.
How a stream starts, who is who, how your server runs it and how it ends: how live streams work. What people build with them: live streaming, interviews and questions on stage and members-only streams.
Who is who
Your server declares streams by pattern, as it declares rooms and calls (live streams in depth). Here the show of a shop is named show: and the show: show:mugs. The app asks the calls route of your server when it opens a stream, as for calls, and your rule answers with the place of the user in it. This rule decides:
- A show that does not exist opens for nobody.
- Its presenter is its host: goes live, brings guests on stage, keeps the chat and ends it.
- Everyone else watches, signed in or not. A visitor who is not signed in comes with no user, reads the chat and signs in to write.
- Viewers send reactions.
- Links in the chat come only from the host and those who keep the chat.
- Node
- PHP
- Python
realtime.streams( 'show:{id}', async ( user, { id } ) => {
// 1. A show that does not exist opens for nobody.
const show = await findShow( id );
if ( ! show ) return false;
// 2. Its presenter is its host.
if ( user === show.hostId ) return 'host';
// 3. Everyone else watches, signed in or not.
return 'viewer';
}, {
reactions: true, // 4. Viewers send reactions.
chat: { links: false }, // 5. Links only from those who keep the chat.
} );
$realtime->streams( 'show:{id}', function ( $user, array $p ) {
// 1. A show that does not exist opens for nobody.
$show = find_show( $p['id'] );
if ( null === $show ) {
return false;
}
// 2. Its presenter is its host.
if ( $user === $show->host_id ) {
return 'host';
}
// 3. Everyone else watches, signed in or not.
return 'viewer';
}, [
'reactions' => true, // 4. Viewers send reactions.
'chat' => [ 'links' => false ], // 5. Links only from those who keep the chat.
] );
def show_role(user, p):
# 1. A show that does not exist opens for nobody.
show = find_show(p["id"])
if show is None:
return False
# 2. Its presenter is its host.
if user == show.host_id:
return "host"
# 3. Everyone else watches, signed in or not.
return "viewer"
realtime.streams("show:{id}", show_role,
reactions=True, # 4. Viewers send reactions.
chat={"links": False}) # 5. Links only from those who keep the chat.
- The answer:
false, a role (hostorviewer), or the role with more:info(the name and https picture everyone sees, yourprofileby default),chat(writeorread),mod(truefor someone who keeps the chat without hosting),src(what the host may send:camera,microphone,screen) andquality(the best picture the host sends,720por1080p). - A visitor who is not signed in may only be a viewer. A rule that gives them more is refused with
no_user. - The settings of the stream, the third argument, are each a value or a function of the parts of its name:
stage(guests on stage, on unlessfalse),reactions,people(who sees who is watching,modsorall), andchat:offline(openorclosedwhile it is not live),linksandfresh(the chat emptied each time it goes live) (permissions).
Drawn ready
LiveStreamScreen of WordPlusRealtimeUI is the stream as the web player draws it, full screen: the picture, Live and how many watch over it, its title, the chat with a field to write in, and a heart for reactions, which float up the picture as everyone sends them.
import WordPlusRealtimeUI
let show = try await rt.calls.stream("show:mugs")
present(LiveStreamScreen(stream: show, title: "The new mugs"), animated: true)
- Closing it leaves the stream and dismisses the screen.
leavesOnClose = falsekeeps the stream for the app, andonClosedoes what the app wants in place of dismissing. - Its words are English by default, and yours by key in the language of the user:
LiveStreamScreen(stream:title:appearance: .init(strings: ["live": "Live", "watching": "%d schauen zu"])). The keys arelive,watching,starts_soon,ended,say_something,send,read_only,pinned,react,closeandnot_sent. - For viewers: the host goes live from the studio on the web, or with the calls of the stream below.
- In SwiftUI, wrap it in a
UIViewControllerRepresentableand show it withfullScreenCover, as the API demo does.
Watching
A screen of your own, on the stream itself:
import WordPlusRealtimeCalls
let show = try await rt.calls.stream("show:mugs")
let player = LiveStreamVideoView()
player.show(show) // the main picture of the stream as it changes, its sound plays by itself
show.onChange { // the state, the count, the chat, the pictures
stateLabel.text = show.state == .live ? "Live now" : "Not live"
countLabel.text = "\(show.viewers) watching"
}
show.onMessage { message in add(message.name, message.text) }
try await show.send("Hello!")
show.react("❤️")
show.leave()
- Reactions are any one emoji:
show.react("🔥"), or.heart,.clap,.laugh,.wowand.firefor the five the players offer.show.onReactionshears the ones sent since the last, by emoji, about every half second, andLiveStreamScreenfloats each up the picture. stateisidle,liveorended.mediais where the app is in the room of the stream:off,connecting,live,reconnecting.roleis the place your rule gave this user:host,guestorviewer.viewersandpeakcount those watching,startedAtis when it went live.- The main picture is the one the host chose: a shared screen, the picture from OBS, else the camera of the host.
show.tileshas each picture, andplayer.show(show, tile: identity)draws one of them. - The chat:
messages(the history, oldest first),pinned,canWrite,slow. Each message has the app user id of who wrote it, nil for a visitor. onEndedsays why the app is out of the stream:left,banned,kicked, or the code of what it could not go on with.
Going live
The app of the host shows its camera, then goes live:
try await show.preview() // the camera and microphone, in the same LiveStreamVideoView
try await show.setCamera(false) // or setMicrophone(_:)
try await show.goLive()
try await show.end()
- The camera and microphone need
NSCameraUsageDescriptionandNSMicrophoneUsageDescriptioninInfo.plist, as for calls. goLive()with nothing on turns the camera and microphone on first. A host may take an ended stream live again.- What a role may not do throws its code:
not_host,read_only,slow,timeout. - From OBS:
let (url, key) = try await show.ingest().ingest(renew: true)makes a new key and cuts off the old one. The picture from the encoder takes the place of the camera. - The app sends its camera and microphone. Sharing the screen into a stream is done from the studio on the web.
Guests on stage
A viewer raises a hand, the host invites them, and they come on stage beside the host with their camera and microphone, for everyone watching, on the web too. The screen drawn ready shows all of it. In a screen of your own:
// The app of a viewer:
try await show.hand(true) // show.hand(false) takes it down
show.onChange {
joinButton.isHidden = !show.invited // the host asks them on
stageBadge.isHidden = !show.onStage
}
try await show.joinStage() // on stage, the camera and microphone live
show.leaveStage()
// The app of the host:
show.onChange { drawHands(show.hands) } // [LiveStreamHand]: user, name, at, the oldest first
try await show.invite(show.hands[0].user!) // or anyone watching, by their user id
try await show.unstage("34") // off stage, back to watching
try await show.layout(.speaker) // .grid, .speaker, or .spotlight with a user
A guest sends the camera and microphone, the picture up to 720p. A visitor who is not signed in does not come on stage (anonymous), a stream whose settings say stage: false takes no hands (no_stage), and joinStage() with no invitation is not_invited.
Keeping the chat
The host, and anyone the rule made mod: deleteMessage(id), pin(id), unpin(), timeout(user, seconds:) (from a minute to a day, they go on watching), setSlow(seconds), clearChat(), kick(user) (out now, they may come back) and ban(user). isModerator says whether this user keeps the chat.
A message the chat does not take throws its code: read_only, slow, timeout, too_long, links, not_live.
The show card of the API demo opens the screen drawn ready on the show of Ann: the example app.
From your server
Your server runs a stream as its host does, with no app open: it lists the streams live now, reads one and who watches it, writes in its chat as the shop, times out, kicks or bans someone, turns reactions off, and ends the stream. Each change reaches the app at once: a message in onMessage, someone put out in their onEnded (kicked, banned), the end in state.
- Node
- PHP
- Python
await realtime.listStreams(); // [ { name, started_at, viewers } ], those live now
const show = realtime.stream( 'show:mugs' );
await show.say( 'Free shipping until midnight', { name: 'Mug Shop' } );
await show.timeout( 77, 600 ); // no writing for 10 minutes
await show.ban( 88 );
await show.end();
$realtime->listStreams();
$show = $realtime->stream( 'show:mugs' );
$show->say( 'Free shipping until midnight', 'Mug Shop' );
$show->timeout( 77, 600 );
$show->ban( 88 );
$show->end();
realtime.list_streams()
show = realtime.stream("show:mugs")
show.say("Free shipping until midnight", "Mug Shop")
show.timeout(77, 600)
show.ban(88)
show.end()
Everything your server can do with a stream, in each language: live streams from your server, and the guide of your stack (Next.js, Express, Laravel, PHP, Django, FastAPI, Flask).
Webhooks
Your server hears a stream go live and end, and each signed-in person who watched it, by webhook:
| Event | |
|---|---|
stream.live, stream.ended | { id, at, stream, started_at, ended_at }: the stream went live, or ended, the times in milliseconds |
stream.joined, stream.left | { id, at, stream, user, role, watch, joined_at }, and on leaving left_at and seconds: a signed-in person watching or on it while it was live. Visitors are not told |
These handlers do three things:
- As the show goes live, its followers hear of it.
- As it ends, your server keeps how long it ran.
- As someone stops watching, your server adds the seconds they watched while it was live.
- Node
- PHP
- Python
// 1. Live: tell its followers.
realtime.on( 'stream.live', ( { stream } ) => notifyFollowers( stream ) );
// 2. Ended: keep how long it ran.
realtime.on( 'stream.ended', ( { stream, started_at, ended_at } ) => saveShowLength( stream, started_at, ended_at ) );
// 3. Someone stopped watching: the seconds they watched.
realtime.on( 'stream.left', ( { stream, user, seconds } ) => addWatchTime( stream, user, seconds ) );
// 1. Live: tell its followers.
$realtime->on( 'stream.live', fn ( array $e ) => notify_followers( $e['stream'] ) );
// 2. Ended: keep how long it ran.
$realtime->on( 'stream.ended', fn ( array $e ) => save_show_length( $e['stream'], $e['started_at'], $e['ended_at'] ) );
// 3. Someone stopped watching: the seconds they watched.
$realtime->on( 'stream.left', fn ( array $e ) => add_watch_time( $e['stream'], $e['user'], $e['seconds'] ) );
# 1. Live: tell its followers.
realtime.on("stream.live", lambda e: notify_followers(e["stream"]))
# 2. Ended: keep how long it ran.
realtime.on("stream.ended", lambda e: save_show_length(e["stream"], e["started_at"], e["ended_at"]))
# 3. Someone stopped watching: the seconds they watched.
realtime.on("stream.left", lambda e: add_watch_time(e["stream"], e["user"], e["seconds"]))
What WordPlus Cloud sees
A live stream is not encrypted end to end. Its picture and chat are for everyone watching, so they are encrypted on the way, and the media servers of WordPlus Cloud see them, as a stream needs (encryption).
Refusals
rt.calls.stream(_:) and the actions of the host throw a CallError with its code:
| Code | |
|---|---|
forbidden | your rule said no, or no pattern matches the name |
no_user | your rule gave a visitor who is not signed in more than the place of a viewer |
not_included | the plan of your app does not include live streams |
banned | this user is banned from the stream |
no_hours | the account has used its credits this month, what it may borrow included: new viewers above the plan come in once credits are bought |
not_host | an action of the host from someone who is not the host |
publish_failed | the camera or microphone could not be sent into the stream |