Skip to content

Commit 7e76bea

Browse files
TokenSource API examples (#18)
Add one example per token source type (literal, endpoint, sandbox, custom, caching) that connects to a room, plus a shared common.h for the logging delegate and connect/observe session loop.
1 parent fff0172 commit 7e76bea

10 files changed

Lines changed: 812 additions & 11 deletions

‎CMakeLists.txt‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ set(CMAKE_POSITION_INDEPENDENT_CODE ON)
2121
# Make "include(LiveKitSDK)" search in ./cmake
2222
list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake")
2323

24-
set(LIVEKIT_SDK_VERSION "latest" CACHE STRING "LiveKit C++ SDK version (e.g. 0.2.0 or latest)")
24+
set(LIVEKIT_SDK_VERSION "latest" CACHE STRING "LiveKit C++ SDK version (e.g. 1.3.0 or latest)")
2525
set(LIVEKIT_LOCAL_SDK_DIR "" CACHE PATH "Path to a local LiveKit SDK install prefix (skips download)")
2626

2727
if(LIVEKIT_LOCAL_SDK_DIR)
@@ -82,6 +82,7 @@ endfunction()
8282
include(ExampleDeps)
8383

8484
add_subdirectory(basic_room)
85+
add_subdirectory(token_source)
8586
add_subdirectory(simple_room)
8687
add_subdirectory(simple_rpc)
8788
add_subdirectory(simple_data_stream)

‎README.md‎

Lines changed: 40 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,36 @@
11
# cpp-example-collection
2+
23
This repository contains a collection of small, self-contained examples for the
34
[LiveKit C++ SDK](https://github.com/livekit/client-sdk-cpp).
45

56
The goal of these examples is to demonstrate common usage patterns of the
67
LiveKit C++ SDK (connecting to a room, publishing tracks, RPC, data streams,
78
etc.) without requiring users to build the SDK from source.
89

10+
## Examples
11+
12+
| Example | Description |
13+
| --- | --- |
14+
| [`basic_room`](basic_room/) | Connects to a room and publishes synthetic audio and video tracks. |
15+
| [`frame_metadata`](frame_metadata/) | Publishes and consumes video frames with frame metadata such as IDs, timestamps, and user data. |
16+
| [`hello_livekit/receiver`](hello_livekit/receiver/) | Subscribes to the sender example's video and data tracks. |
17+
| [`hello_livekit/sender`](hello_livekit/sender/) | Publishes synthetic video and data for a paired receiver example. |
18+
| [`logging_levels/basic_usage`](logging_levels/basic_usage/) | Demonstrates SDK log-level filtering and log callbacks. |
19+
| [`logging_levels/custom_sinks`](logging_levels/custom_sinks/) | Shows custom SDK log sinks such as file, JSON, and ROS-style output. |
20+
| [`ping_pong/ping`](ping_pong/ping/) | Sends ping messages over a data track and records response latency. |
21+
| [`ping_pong/pong`](ping_pong/pong/) | Listens for ping messages and publishes matching pong responses. |
22+
| [`platform_audio`](platform_audio/) | Demonstrates microphone capture and speaker playout with platform audio devices. |
23+
| [`simple_data_stream`](simple_data_stream/) | Sends and receives text and byte streams over LiveKit data streams. |
24+
| [`simple_room`](simple_room/) | Connects to a room, publishes local media, and subscribes to remote media. |
25+
| [`simple_rpc`](simple_rpc/) | Demonstrates LiveKit RPC calls between participants. |
26+
| [`token_source`](token_source/) | Shows ways to supply connection credentials through LiveKit token sources. |
927

1028
## How the SDK is provided
1129

1230
These examples **automatically download a prebuilt LiveKit C++ SDK release**
1331
from GitHub at CMake configure time.
1432

15-
This is handled by the cmake helper: [LiveKitSDK.cmake ](https://github.com/livekit-examples/cpp-example-collection/cmake/LiveKitSDK.cmake)
33+
This is handled by the CMake helper: [`LiveKitSDK.cmake`](https://github.com/livekit-examples/cpp-example-collection/blob/main/cmake/LiveKitSDK.cmake).
1634

1735
## Selecting a LiveKit SDK version
1836

@@ -23,59 +41,71 @@ You can pin a specific SDK version using the `LIVEKIT_SDK_VERSION` CMake option.
2341
### Examples
2442

2543
Use the latest release:
44+
2645
```bash
2746
cmake -S . -B build
28-
# Or use a specific version (recommended for reproducibility):
29-
cmake -S . -B build -DLIVEKIT_SDK_VERSION=0.2.0
47+
```
48+
49+
Use a specific version:
50+
51+
```bash
52+
cmake -S . -B build -DLIVEKIT_SDK_VERSION=1.3.0
3053
```
3154

3255
Reconfigure to change versions:
56+
3357
```bash
3458
rm -rf build
35-
cmake -S . -B build -DLIVEKIT_SDK_VERSION=0.3.1
59+
cmake -S . -B build -DLIVEKIT_SDK_VERSION=1.3.0
3660
```
3761

3862
Build against a local SDK:
63+
3964
```bash
4065
rm -rf build
4166
# install the SDK into $HOME/livekit-sdk-install (or any other directory)
42-
cmake --install <sdk-build-dir> --prefix $HOME/livekit-sdk-install
67+
cmake --install <sdk-build-dir> --prefix "$HOME/livekit-sdk-install"
4368

4469
# build the examples against the local SDK
45-
cmake -S . -B build -DLIVEKIT_LOCAL_SDK_DIR=$HOME/livekit-sdk-install
70+
cmake -S . -B build -DLIVEKIT_LOCAL_SDK_DIR="$HOME/livekit-sdk-install"
4671
```
4772

48-
4973
### Building the examples
74+
5075
#### macOS / Linux
76+
5177
```bash
52-
cmake -S . -B build # add -DLIVEKIT_SDK_VERSION=0.2.0 if using a specific version
78+
cmake -S . -B build
5379
cmake --build build
5480
```
5581

5682
#### Windows (Visual Studio generator)
83+
5784
```powershell
58-
cmake -S . -B build # add -DLIVEKIT_SDK_VERSION=0.2.0 if using a specific version
85+
cmake -S . -B build
5986
cmake --build build --config Release
6087
```
6188

62-
The Livekit Release SDK is downloaded into **build/_deps/livekit-sdk/**
89+
The LiveKit Release SDK is downloaded into **build/_deps/livekit-sdk/**
6390

6491
### Running the examples
6592

6693
After building, example binaries are located under:
94+
6795
```bash
6896
build/<example-name>/
6997
```
7098

7199
For example:
100+
72101
```bash
73102
./build/basic_room/basic_room --url <ws-url> --token <token>
74103
```
75104

76105
### Supported platforms
77106

78107
Prebuilt SDKs are downloaded automatically for:
108+
79109
* Windows: x64
80110
* macOS: x64, arm64 (Apple Silicon)
81111
* Linux: x64

‎token_source/CMakeLists.txt‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
# Copyright 2026 LiveKit, Inc.
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
# One executable per token source type. Each shares token_source_common.h for
16+
# the logging delegate and the connect/observe session loop.
17+
18+
# Resolve the SDK lib directory so -llivekit_ffi is found at link time.
19+
get_filename_component(_lk_cmake_dir "${LiveKit_DIR}" DIRECTORY) # .../lib/cmake
20+
get_filename_component(_lk_lib_dir "${_lk_cmake_dir}" DIRECTORY) # .../lib
21+
22+
set(_token_source_examples
23+
token_source_literal token_source_literal.cpp
24+
token_source_endpoint token_source_endpoint.cpp
25+
token_source_sandbox token_source_sandbox.cpp
26+
token_source_custom token_source_custom.cpp
27+
token_source_caching token_source_caching.cpp
28+
)
29+
30+
list(LENGTH _token_source_examples _count)
31+
math(EXPR _last "${_count} - 1")
32+
foreach(_i RANGE 0 ${_last} 2)
33+
list(GET _token_source_examples ${_i} _target)
34+
math(EXPR _src_idx "${_i} + 1")
35+
list(GET _token_source_examples ${_src_idx} _src)
36+
37+
add_executable(${_target} ${_src})
38+
target_include_directories(${_target} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
39+
target_link_libraries(${_target} PRIVATE ${LIVEKIT_CORE_TARGET})
40+
target_link_directories(${_target} PRIVATE "${_lk_lib_dir}")
41+
42+
livekit_copy_windows_runtime_dlls(${_target})
43+
endforeach()
44+
45+
unset(_token_source_examples)

‎token_source/README.md‎

Lines changed: 125 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,125 @@
1+
# Token Source Examples
2+
3+
These examples show the different ways to obtain the credentials
4+
(**WebSocket URL** + **participant JWT**) the SDK needs to join a room. Each
5+
example builds its own executable, constructs a single kind of
6+
[`TokenSource`](https://github.com/livekit/client-sdk-cpp/blob/main/include/livekit/token_source.h),
7+
connects to a room, logs participant join/leave for a few seconds, then
8+
disconnects.
9+
10+
> Token sources are for the **initial connection only**. Once connected, the
11+
> LiveKit server refreshes the session token internally — your token source is
12+
> not called again unless you connect again. See the SDK's
13+
> [authentication docs](https://github.com/livekit/client-sdk-cpp/blob/main/docs/authentication.md).
14+
15+
## Types
16+
17+
| Type | Example | When to use |
18+
| --- | --- | --- |
19+
| `LiteralTokenSource` | `token_source_literal.cpp` | You already have a URL + JWT (minted out of band, e.g. `lk token create`). The SDK consumes them as-is. |
20+
| `EndpointTokenSource` | `token_source_endpoint.cpp` | Recommended for production. The SDK POSTs request options to your backend token endpoint, which returns the URL + a fresh JWT. API keys stay server-side. |
21+
| `SandboxTokenSource` | `token_source_sandbox.cpp` | Local development only. Uses LiveKit Cloud's sandbox token server. **Not for production.** |
22+
| `CustomTokenSource` | `token_source_custom.cpp` | You have an internal auth/token system. Plug in your own async callback that returns credentials. |
23+
| `CachingTokenSource` | `token_source_caching.cpp` | A decorator that adds JWT-aware caching around any configurable source (endpoint/sandbox/custom) to cut down on fetch calls. |
24+
25+
`LiteralTokenSource` is *fixed* (no per-call options); the others are
26+
*configurable* and accept
27+
[`TokenRequestOptions`](https://github.com/livekit/client-sdk-cpp/blob/main/include/livekit/token_source.h)
28+
(room name, participant identity, agent dispatch, ...).
29+
30+
## Configuring the Examples
31+
32+
All inputs come from environment variables, so no secrets or sandbox IDs are committed to source.
33+
34+
| Variable | Used by | Notes |
35+
| --- | --- | --- |
36+
| `LIVEKIT_URL` | literal, custom | WebSocket URL, e.g. `ws://localhost:7880`. |
37+
| `LIVEKIT_TOKEN` | literal, custom | Participant JWT. |
38+
| `LIVEKIT_TOKEN_ENDPOINT` | endpoint, caching | Token endpoint URL. Default `http://127.0.0.1:3000/createToken`. |
39+
| `LIVEKIT_TOKEN_ENDPOINT_METHOD` | endpoint, caching | Optional HTTP method (default `POST`). |
40+
| `LIVEKIT_TOKEN_ENDPOINT_HEADERS` | endpoint, caching | Optional newline-separated `Name: Value` headers. |
41+
| `LIVEKIT_SANDBOX_ID` | sandbox | Required. Sandbox ID from LiveKit Cloud. |
42+
| `LIVEKIT_AGENT_NAME` | sandbox | Optional agent to dispatch into the room. |
43+
| `LIVEKIT_AGENT_METADATA` | sandbox | Optional metadata for the dispatched agent. |
44+
45+
These examples require LiveKit C++ SDK **v1.3.0** or newer. Build them with the
46+
rest of the repo — see the root [README](../README.md#building-the-examples).
47+
48+
## Running the Examples
49+
50+
### Prerequisites
51+
52+
#### LiveKit Server
53+
54+
Start a development server via:
55+
56+
```bash
57+
livekit-server --dev
58+
```
59+
60+
#### Token Sources
61+
62+
For literal and custom, generate a development token with the
63+
[LiveKit CLI](https://docs.livekit.io/home/cli/cli-setup/) (a dev server started
64+
with `livekit-server --dev` uses `devkey` / `secret`):
65+
66+
```bash
67+
export LIVEKIT_TOKEN=$(lk token create \
68+
--api-key devkey --api-secret secret \
69+
-i my-participant --join --room my-room \
70+
--valid-for 24h --token-only)
71+
```
72+
73+
For the endpoint and caching examples, run a local token server such as
74+
[token-server-node](https://github.com/livekit-examples/token-server-node). This can be run via:
75+
76+
```bash
77+
cd <path-to>/token-server-node
78+
LIVEKIT_URL=ws://localhost:7880 LIVEKIT_API_KEY=devkey LIVEKIT_API_SECRET=secret PORT=3000 pnpm start
79+
```
80+
81+
For sandbox, create a **Token Server** sandbox in [LiveKit Cloud](https://cloud.livekit.io)
82+
(Sandbox → create from the token-server template), then copy the sandbox ID
83+
(`token-server-xxxxxx`). See the
84+
[sandbox token server docs](https://docs.livekit.io/frontends/build/authentication/sandbox-token-server/)
85+
for setup details. Do not use this in production.
86+
87+
```bash
88+
export LIVEKIT_SANDBOX_ID=token-server-xxxxxx
89+
# optional: dispatch a registered agent into the room with metadata
90+
# export LIVEKIT_AGENT_NAME=my-agent
91+
# export LIVEKIT_AGENT_METADATA='{"greeting": "hello from cpp"}'
92+
```
93+
94+
### Executing
95+
96+
The built binaries live under `build/token_source/`:
97+
98+
```bash
99+
# Literal: bring your own URL + token
100+
export LIVEKIT_URL=ws://localhost:7880
101+
export LIVEKIT_TOKEN=<participant-jwt>
102+
./build/token_source/token_source_literal
103+
```
104+
105+
```bash
106+
# Endpoint / caching: point at your token endpoint
107+
export LIVEKIT_TOKEN_ENDPOINT=http://127.0.0.1:3000/createToken
108+
./build/token_source/token_source_endpoint
109+
./build/token_source/token_source_caching
110+
```
111+
112+
```bash
113+
# Sandbox: development-only, ID from the environment
114+
export LIVEKIT_SANDBOX_ID=<your-sandbox-id>
115+
export LIVEKIT_AGENT_NAME=<your-agent-name> # optional
116+
export LIVEKIT_AGENT_METADATA=<your-agent-metadata> # optional
117+
./build/token_source/token_source_sandbox
118+
```
119+
120+
```bash
121+
# Custom: callback returns credentials (this example reads the env)
122+
export LIVEKIT_URL=ws://localhost:7880
123+
export LIVEKIT_TOKEN=<participant-jwt>
124+
./build/token_source/token_source_custom
125+
```
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
/*
2+
* Copyright 2026 LiveKit, Inc.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
// Caching token source: a decorator that adds JWT-aware caching to any
18+
// configurable token source (endpoint, sandbox, or custom).
19+
//
20+
// Repeated fetches for the same request options reuse the cached token until it
21+
// nears expiry or you call invalidate() to drop the cached credentials, cutting
22+
// down calls to your backend. This example wraps an EndpointTokenSource.
23+
//
24+
// Environment:
25+
// LIVEKIT_TOKEN_ENDPOINT Token endpoint URL
26+
// (default http://127.0.0.1:3000/createToken)
27+
// LIVEKIT_TOKEN_ENDPOINT_METHOD Optional HTTP method (default POST)
28+
// LIVEKIT_TOKEN_ENDPOINT_HEADERS Optional newline-separated "Name: Value" headers
29+
30+
#include <livekit/livekit.h>
31+
#include <livekit/token_source.h>
32+
33+
#include <iostream>
34+
#include <string>
35+
#include <utility>
36+
37+
#include "token_source_common.h"
38+
39+
namespace {
40+
41+
using namespace token_source_example;
42+
43+
bool cachingTokenSourceConnect() {
44+
std::string endpoint_url = getenvOrEmpty("LIVEKIT_TOKEN_ENDPOINT");
45+
if (endpoint_url.empty()) {
46+
endpoint_url = "http://127.0.0.1:3000/createToken";
47+
}
48+
49+
std::cout << "Caching token source wrapping endpoint: " << endpoint_url << "\n";
50+
51+
// Build the inner source, then wrap it. CachingTokenSource::create takes
52+
// ownership of the inner source via unique_ptr.
53+
auto inner = livekit::EndpointTokenSource::create(endpoint_url, endpointOptionsFromEnv());
54+
auto token_source = livekit::CachingTokenSource::create(std::move(inner));
55+
56+
livekit::TokenRequestOptions request_options;
57+
request_options.participant_identity = "robot-a";
58+
const auto credentials = token_source->fetch(request_options).get();
59+
if (!credentials) {
60+
std::cerr << "Failed to fetch credentials: " << credentials.error().message << "\n";
61+
return false;
62+
}
63+
64+
livekit::Room room;
65+
ParticipantLogDelegate delegate;
66+
room.setDelegate(&delegate);
67+
if (!room.connect(credentials.value().server_url, credentials.value().participant_token, livekit::RoomOptions())) {
68+
std::cerr << "Failed to connect to room\n";
69+
return false;
70+
}
71+
std::cout << "Connected to room: " << room.roomInfo().name << " (caching token source)\n";
72+
73+
return runConnectedSession(room);
74+
}
75+
76+
} // namespace
77+
78+
int main() {
79+
livekit::initialize(livekit::LogLevel::Info);
80+
const bool ok = cachingTokenSourceConnect();
81+
livekit::shutdown();
82+
return ok ? 0 : 1;
83+
}

0 commit comments

Comments
 (0)