• Stars
    star
    189
  • Rank 204,649 (Top 5 %)
  • Language
    Go
  • License
    Apache License 2.0
  • Created over 3 years ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Client and server SDK for Golang
The LiveKit icon, the name of the repository and some sample code in the background.

LiveKit Go SDK

Use this SDK to manage LiveKit rooms and create access tokens from your Go backend.

Installation

go get github.com/livekit/server-sdk-go

Note: since v1.0 release, this package requires Go 1.18+ in order to build.

Token creation

import (
	"time"

	lksdk "github.com/livekit/server-sdk-go"
	"github.com/livekit/protocol/auth"
)

func getJoinToken(apiKey, apiSecret, room, identity string) (string, error) {
	at := auth.NewAccessToken(apiKey, apiSecret)
	grant := &auth.VideoGrant{
		RoomJoin: true,
		Room:     room,
	}
	at.AddGrant(grant).
		SetIdentity(identity).
		SetValidFor(time.Hour)

	return at.ToJWT()
}

RoomService API

RoomService gives you complete control over rooms and participants within them. It includes selective track subscriptions as well as moderation capabilities.

import (
	lksdk "github.com/livekit/server-sdk-go"
	livekit "github.com/livekit/protocol/livekit"
)

func main() {
	host := "host"
	apiKey := "key"
	apiSecret := "secret"

	roomName := "myroom"
	identity := "participantIdentity"

    roomClient := lksdk.NewRoomServiceClient(host, apiKey, apiSecret)

    // create a new room
    room, _ := roomClient.CreateRoom(context.Background(), &livekit.CreateRoomRequest{
		Name: roomName,
	})

    // list rooms
    res, _ := roomClient.ListRooms(context.Background(), &livekit.ListRoomsRequest{})

    // terminate a room and cause participants to leave
    roomClient.DeleteRoom(context.Background(), &livekit.DeleteRoomRequest{
		Room: roomId,
	})

    // list participants in a room
    res, _ := roomClient.ListParticipants(context.Background(), &livekit.ListParticipantsRequest{
		Room: roomName,
	})

    // disconnect a participant from room
    roomClient.RemoveParticipant(context.Background(), &livekit.RoomParticipantIdentity{
		Room:     roomName,
		Identity: identity,
	})

    // mute/unmute participant's tracks
    roomClient.MutePublishedTrack(context.Background(), &livekit.MuteRoomTrackRequest{
		Room:     roomName,
		Identity: identity,
		TrackSid: "track_sid",
		Muted:    true,
	})
}

Interacting as a participant

The Participant SDK gives you access programmatic access as a client enabling you to publish and record audio/video/data to the room.

import (
  lksdk "github.com/livekit/server-sdk-go"
)

func main() {
  host := "<host>"
  apiKey := "api-key"
  apiSecret := "api-secret"
  roomName := "myroom"
  identity := "botuser"
  roomCB := &lksdk.RoomCallback{
	ParticipantCallback: lksdk.ParticipantCallback{
	  OnTrackSubscribed: trackSubscribed
  	},
  }
  room, err := lksdk.ConnectToRoom(host, lksdk.ConnectInfo{
  	APIKey:              apiKey,
  	APISecret:           apiSecret,
  	RoomName:            roomName,
  	ParticipantIdentity: identity,
  }, roomCB)
  if err != nil {
  	panic(err)
  }

  ...
  room.Disconnect()
}

func trackSubscribed(track *webrtc.TrackRemote, publication *lksdk.RemoteTrackPublication, rp *lksdk.RemoteParticipant) {

}

Publishing tracks to Room

With the Go SDK, you can publish existing files encoded in H.264, VP8, and Opus to the room.

First, you will need to encode media into the right format.

VP8 / Opus

ffmpeg -i <input.mp4> \
  -c:v libvpx -keyint_min 120 -qmax 50 -maxrate 2M -b:v 1M <output.ivf> \
  -c:a libopus -page_duration 20000 -vn <output.ogg>

The above encodes VP8 at average 1Mbps / max 2Mbps with a minimum keyframe interval of 120.

H.264 / Opus

ffmpeg -i <input.mp4> \
  -c:v libx264 -bsf:v h264_mp4toannexb -b:v 2M -profile baseline -pix_fmt yuv420p \
    -x264-params keyint=120 -max_delay 0 -bf 0 <output.h264> \
  -c:a libopus -page_duration 20000 -vn <output.ogg>

The above encodes H264 with CBS of 2Mbps with a minimum keyframe interval of 120.

Publish from file

file := "video.ivf"
videoWidth := 1920
videoHeight := 1080
track, err := lksdk.NewLocalFileTrack(file,
	// control FPS to ensure synchronization
	lksdk.ReaderTrackWithFrameDuration(33 * time.Millisecond),
	lksdk.ReaderTrackWithOnWriteComplete(func() { fmt.Println("track finished") }),
)
if err != nil {
    return err
}
if _, err = room.LocalParticipant.PublishTrack(track, &lksdk.TrackPublicationOptions{
	Name: file,
	Width: videoWidth,
	Height: videoHeight,
}); err != nil {
    return err
}

Publish from io.ReadCloser implementation

// - `in` implements io.ReadCloser, such as buffer or file
// - `mime` has to be one of webrtc.MimeType...
track, err := lksdk.NewLocalReaderTrack(in, mime,
	lksdk.ReaderTrackWithFrameDuration(33 * time.Millisecond),
	lksdk.ReaderTrackWithOnWriteComplete(func() { fmt.Println("track finished") }),
)
if err != nil {
	return err
}
if _, err = room.LocalParticipant.PublishTrack(track, &lksdk.TrackPublicationOptions{}); err != nil {
    return err
}

For a full working example, refer to join.go in livekit-cli.

Publish from other sources

In order to publish from non-file sources, you will have to implement your own SampleProvider, that could provide frames of data with a NextSample method.

The SDK takes care of sending the samples to the room.

Receiving webhooks

The Go SDK helps you to verify and decode webhook callbacks to ensure their authenticity. See webhooks guide for configuration.

import (
	"github.com/livekit/protocol/auth"
	"github.com/livekit/protocol/livekit"
	"github.com/livekit/protocol/webhook"
)

var authProvider = auth.NewSimpleKeyProvider(
	apiKey, apiSecret,
)

func ServeHTTP(w http.ResponseWriter, r *http.Request) {
  // event is a livekit.WebhookEvent{} object
	event, err := webhook.ReceiveWebhookEvent(r, authProvider)
	if err != nil {
		// could not validate, handle error
		return
	}

	// consume WebhookEvent
}


LiveKit Ecosystem
Client SDKsComponents · JavaScript · iOS/macOS · Android · Flutter · React Native · Rust · Python · Unity (web) · Unity (beta)
Server SDKsNode.js · Golang · Ruby · Java/Kotlin · PHP (community) · Python (community)
ServicesLivekit server · Egress · Ingress
ResourcesDocs · Example apps · Cloud · Self-hosting · CLI

More Repositories

1

livekit

End-to-end stack for WebRTC. SFU media server and SDKs.
Go
9,214
star
2

agents

Build real-time multimodal AI applications 🤖🎙️📹
Python
750
star
3

client-sdk-js

LiveKit browser client SDK (javascript)
TypeScript
329
star
4

client-sdk-flutter

Flutter Client SDK for LiveKit
Dart
238
star
5

livekit-cli

Command line interface to LiveKit
Go
199
star
6

client-sdk-swift

LiveKit Swift Client SDK. Easily build live audio or video experiences into your mobile app, game or website.
Swift
182
star
7

rust-sdks

LiveKit real-time and server SDKs for Rust
Rust
173
star
8

client-sdk-android

LiveKit SDK for Android
Kotlin
169
star
9

livekit-react

React component and library for LiveKit
TypeScript
169
star
10

egress

Export and record WebRTC sessions and tracks
Go
166
star
11

components-js

Official open source React components and examples for building with LiveKit.
TypeScript
145
star
12

node-sdks

LiveKit real-time and server SDKs for Node.JS
TypeScript
124
star
13

client-sdk-react-native

TypeScript
98
star
14

python-sdks

LiveKit real-time and server SDKs for Python
Python
80
star
15

sip

SIP to WebRTC bridge for LiveKit
Go
76
star
16

protocol

LiveKit protocol. Protobuf definitions for LiveKit's signaling protocol
Go
69
star
17

ingress

Ingest streams (RTMP/WHIP) or files (HLS, MP4) to LiveKit WebRTC
Go
68
star
18

agents-playground

TypeScript
61
star
19

client-sdk-unity-web

Client SDK for Unity WebGL
C#
50
star
20

livekit-helm

LiveKit Helm charts
Smarty
47
star
21

livekit-recorder

Go
32
star
22

client-sdk-unity

C#
31
star
23

track-processors-js

TypeScript
29
star
24

server-sdk-kotlin

Kotlin
28
star
25

livekit-server-sdk-python

LiveKit Server SDK for Python
Python
25
star
26

psrpc

Go
22
star
27

client-example-swift

Example app for LiveKit Swift SDK 👉 https://github.com/livekit/client-sdk-swift
Swift
21
star
28

server-sdk-ruby

LiveKit Server SDK for Ruby
Ruby
21
star
29

meet

Open source video conferencing app built on LiveKit Components, LiveKit Cloud, and Next.js.
TypeScript
16
star
30

client-unity-demo

Demo for LiveKit Unity SDK
C#
11
star
31

client-sdk-cpp

C++
11
star
32

WebRTC-swift

Swift package for WebRTC
Objective-C
10
star
33

livekit-docs

JavaScript
10
star
34

deploy

Resources for deploying LiveKit
Go
9
star
35

webrtc-vmaf

VMAF benchmarking tool for WebRTC codecs
Python
9
star
36

chrometester

A livekit tester to simulate a subscriber in a room, uses headless Chromium
JavaScript
8
star
37

gstreamer-publisher

Command-line app that publishes any GStreamer pipeline to LiveKit
Go
8
star
38

nats-test

benchmarking app that emulates our usage patterns
Go
7
star
39

mediatransportutil

Media transport utilities
Go
6
star
40

rtcscore-go

Library to calculate Mean Opinion Score(MOS)
Go
4
star
41

components-swift

Swift
4
star
42

signal-proxy

Go
3
star
43

client-example-collection-swift

A collection of small examples for the LiveKit Swift SDK 👉 https://github.com/livekit/client-sdk-swift
Swift
3
star
44

webrtc-chrome

Fork of Google's WebRTC repo, with LiveKit patches.
C++
3
star
45

components-android

Kotlin
3
star
46

gst-plugins

Go
3
star
47

client-sdk-react-native-expo-plugin

TypeScript
2
star
48

webrtc-xcframework

Ruby
2
star
49

mageutil

Go
2
star
50

ios-test-apps

Swift
1
star
51

gstreamer

C
1
star
52

websocket-bridge

Send and Receive Media to LiveKit via WebSocket
Go
1
star