• Stars
    star
    164
  • Rank 221,912 (Top 5 %)
  • Language
    Go
  • License
    Apache License 2.0
  • Created about 3 years ago
  • Updated 2 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
6,715
star
2

client-sdk-js

LiveKit browser client SDK (javascript)
TypeScript
273
star
3

client-sdk-flutter

Flutter Client SDK for LiveKit
Dart
197
star
4

livekit-react

React component and library for LiveKit
TypeScript
166
star
5

livekit-cli

Command line interface to LiveKit
Go
154
star
6

client-sdk-swift

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

client-sdk-android

LiveKit SDK for Android
Kotlin
138
star
8

egress

Export and record WebRTC sessions and tracks
Go
137
star
9

rust-sdks

LiveKit real-time SDK and server API for Rust
Rust
119
star
10

agents

Build real-time multimodal AI applications 🤖🎙️📹
Python
111
star
11

components-js

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

server-sdk-js

JS Server SDK to LiveKit
TypeScript
100
star
13

client-sdk-react-native

TypeScript
80
star
14

protocol

LiveKit protocol. Protobuf definitions for LiveKit's signaling protocol
Go
58
star
15

ingress

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

sip

SIP to WebRTC bridge for LiveKit
Go
46
star
17

client-sdk-unity-web

Client SDK for Unity WebGL
C#
42
star
18

python-sdks

LiveKit real-time SDK and server API for Python
Python
38
star
19

livekit-helm

LiveKit Helm charts
Smarty
36
star
20

livekit-recorder

Go
31
star
21

livekit-server-sdk-python

LiveKit Server SDK for Python
Python
25
star
22

server-sdk-kotlin

Kotlin
24
star
23

track-processors-js

TypeScript
23
star
24

client-example-swift

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

server-sdk-ruby

LiveKit Server SDK for Ruby
Ruby
20
star
26

client-sdk-unity

C#
20
star
27

psrpc

Go
17
star
28

meet

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

client-unity-demo

Demo for LiveKit Unity SDK
C#
11
star
30

client-sdk-cpp

C++
11
star
31

WebRTC-swift

Swift package for WebRTC
Objective-C
10
star
32

agents-playground

TypeScript
9
star
33

deploy

Resources for deploying LiveKit
Go
8
star
34

livekit-docs

JavaScript
8
star
35

chrometester

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

nats-test

benchmarking app that emulates our usage patterns
Go
7
star
37

mediatransportutil

Media transport utilities
Go
5
star
38

webrtc-vmaf

VMAF benchmarking tool for WebRTC codecs
Python
4
star
39

client-example-collection-swift

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

webrtc-chrome

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

rtcscore-go

Library to calculate Mean Opinion Score(MOS)
Go
2
star
42

ios-test-apps

Swift
1
star
43

gstreamer

C
1
star
44

mageutil

Go
1
star
45

components-android

Kotlin
1
star
46

gst-plugins

Go
1
star