Repository: pion/rtsp-bench
Branch: main
Commit: e2e65f4f616e
Files: 29
Total size: 50.7 KB
Directory structure:
gitextract_s0aj61ys/
├── .github/
│ ├── .ci.conf
│ ├── .gitignore
│ ├── fetch-scripts.sh
│ ├── install-hooks.sh
│ ├── pion-gopher-webrtc.png.license
│ ├── plot.png.license
│ └── workflows/
│ ├── api.yaml
│ ├── codeql-analysis.yml
│ ├── fuzz.yaml
│ ├── lint.yaml
│ ├── release.yml
│ ├── renovate-go-sum-fix.yaml
│ ├── reuse.yml
│ ├── test.yaml
│ └── tidy-check.yaml
├── .gitignore
├── .golangci.yml
├── .goreleaser.yml
├── .reuse/
│ └── dep5
├── LICENSE
├── LICENSES/
│ └── MIT.txt
├── README.md
├── client/
│ └── main.go
├── codecov.yml
├── go.mod
├── go.sum
├── renovate.json
└── server/
├── main.go
└── static/
└── index.html
================================================
FILE CONTENTS
================================================
================================================
FILE: .github/.ci.conf
================================================
# SPDX-FileCopyrightText: 2026 The Pion community <https://pion.ly>
# SPDX-License-Identifier: MIT
GO_MOD_VERSION_EXPECTED=1.24
SKIP_API_DIFF=true
================================================
FILE: .github/.gitignore
================================================
# SPDX-FileCopyrightText: 2026 The Pion community <https://pion.ly>
# SPDX-License-Identifier: MIT
.goassets
================================================
FILE: .github/fetch-scripts.sh
================================================
#!/bin/sh
#
# DO NOT EDIT THIS FILE
#
# It is automatically copied from https://github.com/pion/.goassets repository.
#
# If you want to update the shared CI config, send a PR to
# https://github.com/pion/.goassets instead of this repository.
#
# SPDX-FileCopyrightText: 2026 The Pion community <https://pion.ly>
# SPDX-License-Identifier: MIT
set -eu
SCRIPT_PATH="$(realpath "$(dirname "$0")")"
GOASSETS_PATH="${SCRIPT_PATH}/.goassets"
GOASSETS_REF=${GOASSETS_REF:-main}
if [ -d "${GOASSETS_PATH}" ]; then
if ! git -C "${GOASSETS_PATH}" diff --exit-code; then
echo "${GOASSETS_PATH} has uncommitted changes" >&2
exit 1
fi
git -C "${GOASSETS_PATH}" fetch origin
git -C "${GOASSETS_PATH}" checkout ${GOASSETS_REF}
git -C "${GOASSETS_PATH}" reset --hard origin/${GOASSETS_REF}
else
git clone -b ${GOASSETS_REF} https://github.com/pion/.goassets.git "${GOASSETS_PATH}"
fi
================================================
FILE: .github/install-hooks.sh
================================================
#!/bin/sh
#
# DO NOT EDIT THIS FILE
#
# It is automatically copied from https://github.com/pion/.goassets repository.
#
# If you want to update the shared CI config, send a PR to
# https://github.com/pion/.goassets instead of this repository.
#
# SPDX-FileCopyrightText: 2026 The Pion community <https://pion.ly>
# SPDX-License-Identifier: MIT
SCRIPT_PATH="$(realpath "$(dirname "$0")")"
. ${SCRIPT_PATH}/fetch-scripts.sh
cp "${GOASSETS_PATH}/hooks/commit-msg.sh" "${SCRIPT_PATH}/../.git/hooks/commit-msg"
cp "${GOASSETS_PATH}/hooks/pre-commit.sh" "${SCRIPT_PATH}/../.git/hooks/pre-commit"
================================================
FILE: .github/pion-gopher-webrtc.png.license
================================================
SPDX-FileCopyrightText: 2026 The Pion community <https://pion.ly>
SPDX-License-Identifier: MIT
================================================
FILE: .github/plot.png.license
================================================
SPDX-FileCopyrightText: 2026 The Pion community <https://pion.ly>
SPDX-License-Identifier: MIT
================================================
FILE: .github/workflows/api.yaml
================================================
#
# DO NOT EDIT THIS FILE
#
# It is automatically copied from https://github.com/pion/.goassets repository.
# If this repository should have package specific CI config,
# remove the repository name from .goassets/.github/workflows/assets-sync.yml.
#
# If you want to update the shared CI config, send a PR to
# https://github.com/pion/.goassets instead of this repository.
#
# SPDX-FileCopyrightText: 2026 The Pion community <https://pion.ly>
# SPDX-License-Identifier: MIT
name: API
on:
pull_request:
jobs:
check:
uses: pion/.goassets/.github/workflows/api.reusable.yml@main
================================================
FILE: .github/workflows/codeql-analysis.yml
================================================
#
# DO NOT EDIT THIS FILE
#
# It is automatically copied from https://github.com/pion/.goassets repository.
# If this repository should have package specific CI config,
# remove the repository name from .goassets/.github/workflows/assets-sync.yml.
#
# If you want to update the shared CI config, send a PR to
# https://github.com/pion/.goassets instead of this repository.
#
# SPDX-FileCopyrightText: 2026 The Pion community <https://pion.ly>
# SPDX-License-Identifier: MIT
name: CodeQL
on:
workflow_dispatch:
schedule:
- cron: '23 5 * * 0'
pull_request:
branches:
- main
paths:
- '**.go'
jobs:
analyze:
uses: pion/.goassets/.github/workflows/codeql-analysis.reusable.yml@main
================================================
FILE: .github/workflows/fuzz.yaml
================================================
#
# DO NOT EDIT THIS FILE
#
# It is automatically copied from https://github.com/pion/.goassets repository.
# If this repository should have package specific CI config,
# remove the repository name from .goassets/.github/workflows/assets-sync.yml.
#
# If you want to update the shared CI config, send a PR to
# https://github.com/pion/.goassets instead of this repository.
#
# SPDX-FileCopyrightText: 2026 The Pion community <https://pion.ly>
# SPDX-License-Identifier: MIT
name: Fuzz
on:
push:
branches:
- main
schedule:
- cron: "0 */8 * * *"
jobs:
fuzz:
uses: pion/.goassets/.github/workflows/fuzz.reusable.yml@main
with:
go-version: "1.25" # auto-update/latest-go-version
fuzz-time: "60s"
================================================
FILE: .github/workflows/lint.yaml
================================================
#
# DO NOT EDIT THIS FILE
#
# It is automatically copied from https://github.com/pion/.goassets repository.
# If this repository should have package specific CI config,
# remove the repository name from .goassets/.github/workflows/assets-sync.yml.
#
# If you want to update the shared CI config, send a PR to
# https://github.com/pion/.goassets instead of this repository.
#
# SPDX-FileCopyrightText: 2026 The Pion community <https://pion.ly>
# SPDX-License-Identifier: MIT
name: Lint
on:
pull_request:
jobs:
lint:
uses: pion/.goassets/.github/workflows/lint.reusable.yml@main
with:
golangci-lint-version: v2.10.1
================================================
FILE: .github/workflows/release.yml
================================================
#
# DO NOT EDIT THIS FILE
#
# It is automatically copied from https://github.com/pion/.goassets repository.
# If this repository should have package specific CI config,
# remove the repository name from .goassets/.github/workflows/assets-sync.yml.
#
# If you want to update the shared CI config, send a PR to
# https://github.com/pion/.goassets instead of this repository.
#
# SPDX-FileCopyrightText: 2026 The Pion community <https://pion.ly>
# SPDX-License-Identifier: MIT
name: Release
on:
push:
tags:
- 'v*'
jobs:
release:
uses: pion/.goassets/.github/workflows/release.reusable.yml@main
with:
go-version: "1.25" # auto-update/latest-go-version
================================================
FILE: .github/workflows/renovate-go-sum-fix.yaml
================================================
#
# DO NOT EDIT THIS FILE
#
# It is automatically copied from https://github.com/pion/.goassets repository.
# If this repository should have package specific CI config,
# remove the repository name from .goassets/.github/workflows/assets-sync.yml.
#
# If you want to update the shared CI config, send a PR to
# https://github.com/pion/.goassets instead of this repository.
#
# SPDX-FileCopyrightText: 2026 The Pion community <https://pion.ly>
# SPDX-License-Identifier: MIT
name: Fix go.sum
on:
push:
branches:
- renovate/*
jobs:
fix:
uses: pion/.goassets/.github/workflows/renovate-go-sum-fix.reusable.yml@main
secrets:
token: ${{ secrets.PIONBOT_PRIVATE_KEY }}
================================================
FILE: .github/workflows/reuse.yml
================================================
#
# DO NOT EDIT THIS FILE
#
# It is automatically copied from https://github.com/pion/.goassets repository.
# If this repository should have package specific CI config,
# remove the repository name from .goassets/.github/workflows/assets-sync.yml.
#
# If you want to update the shared CI config, send a PR to
# https://github.com/pion/.goassets instead of this repository.
#
# SPDX-FileCopyrightText: 2026 The Pion community <https://pion.ly>
# SPDX-License-Identifier: MIT
name: REUSE Compliance Check
on:
push:
pull_request:
jobs:
lint:
uses: pion/.goassets/.github/workflows/reuse.reusable.yml@main
================================================
FILE: .github/workflows/test.yaml
================================================
#
# DO NOT EDIT THIS FILE
#
# It is automatically copied from https://github.com/pion/.goassets repository.
# If this repository should have package specific CI config,
# remove the repository name from .goassets/.github/workflows/assets-sync.yml.
#
# If you want to update the shared CI config, send a PR to
# https://github.com/pion/.goassets instead of this repository.
#
# SPDX-FileCopyrightText: 2026 The Pion community <https://pion.ly>
# SPDX-License-Identifier: MIT
name: Test
on:
push:
branches:
- main
pull_request:
jobs:
test:
uses: pion/.goassets/.github/workflows/test.reusable.yml@main
strategy:
matrix:
go: ["1.25", "1.24"] # auto-update/supported-go-version-list
fail-fast: false
with:
go-version: ${{ matrix.go }}
secrets: inherit
test-i386:
uses: pion/.goassets/.github/workflows/test-i386.reusable.yml@main
strategy:
matrix:
go: ["1.25", "1.24"] # auto-update/supported-go-version-list
fail-fast: false
with:
go-version: ${{ matrix.go }}
test-windows:
uses: pion/.goassets/.github/workflows/test-windows.reusable.yml@main
strategy:
matrix:
go: ["1.25", "1.24"] # auto-update/supported-go-version-list
fail-fast: false
with:
go-version: ${{ matrix.go }}
test-macos:
uses: pion/.goassets/.github/workflows/test-macos.reusable.yml@main
strategy:
matrix:
go: ["1.25", "1.24"] # auto-update/supported-go-version-list
fail-fast: false
with:
go-version: ${{ matrix.go }}
test-wasm:
uses: pion/.goassets/.github/workflows/test-wasm.reusable.yml@main
with:
go-version: "1.25" # auto-update/latest-go-version
secrets: inherit
================================================
FILE: .github/workflows/tidy-check.yaml
================================================
#
# DO NOT EDIT THIS FILE
#
# It is automatically copied from https://github.com/pion/.goassets repository.
# If this repository should have package specific CI config,
# remove the repository name from .goassets/.github/workflows/assets-sync.yml.
#
# If you want to update the shared CI config, send a PR to
# https://github.com/pion/.goassets instead of this repository.
#
# SPDX-FileCopyrightText: 2026 The Pion community <https://pion.ly>
# SPDX-License-Identifier: MIT
name: Go mod tidy
on:
pull_request:
push:
branches:
- main
jobs:
tidy:
uses: pion/.goassets/.github/workflows/tidy-check.reusable.yml@main
with:
go-version: "1.25" # auto-update/latest-go-version
================================================
FILE: .gitignore
================================================
# SPDX-FileCopyrightText: 2026 The Pion community <https://pion.ly>
# SPDX-License-Identifier: MIT
### JetBrains IDE ###
#####################
.idea/
### Emacs Temporary Files ###
#############################
*~
### Folders ###
###############
bin/
vendor/
node_modules/
### Files ###
#############
*.ivf
*.ogg
tags
cover.out
*.sw[poe]
*.wasm
examples/sfu-ws/cert.pem
examples/sfu-ws/key.pem
wasm_exec.js
================================================
FILE: .golangci.yml
================================================
# SPDX-FileCopyrightText: 2026 The Pion community <https://pion.ly>
# SPDX-License-Identifier: MIT
version: "2"
linters:
enable:
- asciicheck # Simple linter to check that your code does not contain non-ASCII identifiers
- bidichk # Checks for dangerous unicode character sequences
- bodyclose # checks whether HTTP response body is closed successfully
- containedctx # containedctx is a linter that detects struct contained context.Context field
- contextcheck # check the function whether use a non-inherited context
- cyclop # checks function and package cyclomatic complexity
- decorder # check declaration order and count of types, constants, variables and functions
- dogsled # Checks assignments with too many blank identifiers (e.g. x, _, _, _, := f())
- dupl # Tool for code clone detection
- durationcheck # check for two durations multiplied together
- err113 # Golang linter to check the errors handling expressions
- errcheck # Errcheck is a program for checking for unchecked errors in go programs. These unchecked errors can be critical bugs in some cases
- errchkjson # Checks types passed to the json encoding functions. Reports unsupported types and optionally reports occations, where the check for the returned error can be omitted.
- errname # Checks that sentinel errors are prefixed with the `Err` and error types are suffixed with the `Error`.
- errorlint # errorlint is a linter for that can be used to find code that will cause problems with the error wrapping scheme introduced in Go 1.13.
- exhaustive # check exhaustiveness of enum switch statements
- forbidigo # Forbids identifiers
- forcetypeassert # finds forced type assertions
- gochecknoglobals # Checks that no globals are present in Go code
- gocognit # Computes and checks the cognitive complexity of functions
- goconst # Finds repeated strings that could be replaced by a constant
- gocritic # The most opinionated Go source code linter
- gocyclo # Computes and checks the cyclomatic complexity of functions
- godot # Check if comments end in a period
- godox # Tool for detection of FIXME, TODO and other comment keywords
- goheader # Checks is file header matches to pattern
- gomoddirectives # Manage the use of 'replace', 'retract', and 'excludes' directives in go.mod.
- goprintffuncname # Checks that printf-like functions are named with `f` at the end
- gosec # Inspects source code for security problems
- govet # Vet examines Go source code and reports suspicious constructs, such as Printf calls whose arguments do not align with the format string
- grouper # An analyzer to analyze expression groups.
- importas # Enforces consistent import aliases
- ineffassign # Detects when assignments to existing variables are not used
- lll # Reports long lines
- maintidx # maintidx measures the maintainability index of each function.
- makezero # Finds slice declarations with non-zero initial length
- misspell # Finds commonly misspelled English words in comments
- modernize # Replace and suggests simplifications to code
- nakedret # Finds naked returns in functions greater than a specified function length
- nestif # Reports deeply nested if statements
- nilerr # Finds the code that returns nil even if it checks that the error is not nil.
- nilnil # Checks that there is no simultaneous return of `nil` error and an invalid value.
- nlreturn # nlreturn checks for a new line before return and branch statements to increase code clarity
- noctx # noctx finds sending http request without context.Context
- predeclared # find code that shadows one of Go's predeclared identifiers
- revive # golint replacement, finds style mistakes
- staticcheck # Staticcheck is a go vet on steroids, applying a ton of static analysis checks
- tagliatelle # Checks the struct tags.
- thelper # thelper detects golang test helpers without t.Helper() call and checks the consistency of test helpers
- unconvert # Remove unnecessary type conversions
- unparam # Reports unused function parameters
- unused # Checks Go code for unused constants, variables, functions and types
- varnamelen # checks that the length of a variable's name matches its scope
- wastedassign # wastedassign finds wasted assignment statements
- whitespace # Tool for detection of leading and trailing whitespace
disable:
- depguard # Go linter that checks if package imports are in a list of acceptable packages
- funlen # Tool for detection of long functions
- gochecknoinits # Checks that no init functions are present in Go code
- gomodguard # Allow and block list linter for direct Go module dependencies. This is different from depguard where there are different block types for example version constraints and module recommendations.
- interfacebloat # A linter that checks length of interface.
- ireturn # Accept Interfaces, Return Concrete Types
- mnd # An analyzer to detect magic numbers
- nolintlint # Reports ill-formed or insufficient nolint directives
- paralleltest # paralleltest detects missing usage of t.Parallel() method in your Go test
- prealloc # Finds slice declarations that could potentially be preallocated
- promlinter # Check Prometheus metrics naming via promlint
- rowserrcheck # checks whether Err of rows is checked successfully
- sqlclosecheck # Checks that sql.Rows and sql.Stmt are closed.
- testpackage # linter that makes you use a separate _test package
- tparallel # tparallel detects inappropriate usage of t.Parallel() method in your Go test codes
- wrapcheck # Checks that errors returned from external packages are wrapped
- wsl # Whitespace Linter - Forces you to use empty lines!
settings:
staticcheck:
checks:
- all
- -QF1008 # "could remove embedded field", to keep it explicit!
- -QF1003 # "could use tagged switch on enum", Cases conflicts with exhaustive!
exhaustive:
default-signifies-exhaustive: true
forbidigo:
forbid:
- pattern: ^fmt.Print(f|ln)?$
- pattern: ^log.(Panic|Fatal|Print)(f|ln)?$
- pattern: ^os.Exit$
- pattern: ^panic$
- pattern: ^print(ln)?$
- pattern: ^testing.T.(Error|Errorf|Fatal|Fatalf|Fail|FailNow)$
pkg: ^testing$
msg: use testify/assert instead
analyze-types: true
gomodguard:
blocked:
modules:
- github.com/pkg/errors:
recommendations:
- errors
govet:
enable:
- shadow
revive:
rules:
# Prefer 'any' type alias over 'interface{}' for Go 1.18+ compatibility
- name: use-any
severity: warning
disabled: false
misspell:
locale: US
varnamelen:
max-distance: 12
min-name-length: 2
ignore-type-assert-ok: true
ignore-map-index-ok: true
ignore-chan-recv-ok: true
ignore-decls:
- i int
- n int
- w io.Writer
- r io.Reader
- b []byte
exclusions:
generated: lax
rules:
- linters:
- forbidigo
- gocognit
path: (examples|main\.go)
- linters:
- gocognit
path: _test\.go
- linters:
- forbidigo
path: cmd
formatters:
enable:
- gci # Gci control golang package import order and make it always deterministic.
- gofmt # Gofmt checks whether code was gofmt-ed. By default this tool runs with -s option to check for code simplification
- gofumpt # Gofumpt checks whether code was gofumpt-ed.
- goimports # Goimports does everything that gofmt does. Additionally it checks unused imports
exclusions:
generated: lax
issues:
max-issues-per-linter: 0
max-same-issues: 0
================================================
FILE: .goreleaser.yml
================================================
# SPDX-FileCopyrightText: 2026 The Pion community <https://pion.ly>
# SPDX-License-Identifier: MIT
builds:
- skip: true
================================================
FILE: .reuse/dep5
================================================
Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
Upstream-Name: Pion
Source: https://github.com/pion/
Files: README.md DESIGN.md **/README.md AUTHORS.txt renovate.json go.mod go.sum **/go.mod **/go.sum .eslintrc.json package.json examples.json sfu-ws/flutter/.gitignore sfu-ws/flutter/pubspec.yaml c-data-channels/webrtc.h examples/examples.json yarn.lock
Copyright: 2026 The Pion community <https://pion.ly>
License: MIT
Files: testdata/seed/* testdata/fuzz/* **/testdata/fuzz/* api/*.txt
Copyright: 2026 The Pion community <https://pion.ly>
License: CC0-1.0
================================================
FILE: LICENSE
================================================
MIT License
Copyright (c) 2026 The Pion community <https://pion.ly>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
================================================
FILE: LICENSES/MIT.txt
================================================
MIT License
Copyright (c) <year> <copyright holders>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
================================================
FILE: README.md
================================================
<h1 align="center">
<a href="https://pion.ly"><img src="./.github/pion-gopher-webrtc.png" alt="Pion WebRTC" height="250px"></a>
<br>
WebRTC Bench
<br>
</h1>
<h4 align="center">WebRTC Server that generates usage reports, Web/CLI Clients included!</h4>
<p align="center">
<a href="https://pion.ly"><img src="https://img.shields.io/badge/pion-webrtc-gray.svg?longCache=true&colorB=brightgreen" alt="Pion webrtc"></a>
<a href="https://discord.gg/PngbdqpFbt"><img src="https://img.shields.io/badge/join-us%20on%20discord-gray.svg?longCache=true&logo=discord&colorB=brightblue" alt="join us on Discord"></a> <a href="https://bsky.app/profile/pion.ly"><img src="https://img.shields.io/badge/follow-us%20on%20bluesky-gray.svg?longCache=true&logo=bluesky&colorB=brightblue" alt="Follow us on Bluesky"></a>
<br>
<a href="LICENSE"><img src="https://img.shields.io/badge/License-MIT-yellow.svg" alt="License: MIT"></a>
</p>
<br>
`webrtc-bench` is a WebRTC server that plays a video file from disk, and then re-distributes via WebRTC. It generates performance metrics including CPU usage, peer connection counts, and detailed latency measurements for connection setup phases.
This repo contains a CLI WebRTC Client that will connect and perform the load test. This is done via a REST API hosted on `:8080/doSignaling`. You can also watch the video/load test via the web UI at `:8080/`,
it connects via the same REST API as the CLI.
### Running
* `git clone https://github.com/pion/webrtc-bench.git`
* `cd webrtc-bench/server`
* `ffmpeg -i $INPUT_FILE -g 30 -b:v 2M input.ivf`
* `go run main.go`
You can then access the Web UI at [http://localhost:8080](http://localhost:8080). This requires a browser that supports H264, this repo doesn't do any error handling around signaling failures.
You can also use the provided WebRTC CLI
* `cd webrtc-bench/client`
* `go run main.go localhost:8080`
### Output Files
The benchmark generates three CSV files with performance data:
#### report.csv (Server)
System-level metrics collected every 3 seconds:
```
timestamp, peerConnectionCount, cpuUsage, droppedLatencyMeasurements
2020-12-15T13:59:23-08:00, 1, 17.878028, 0
2020-12-15T13:59:26-08:00, 0, 35.101254, 0
2020-12-15T13:59:29-08:00, 1, 12.565718, 0
```
#### server-latencies.csv (Server)
Detailed WebRTC connection setup timing from server perspective:
```
timestamp,type,latencyMs
2026-01-02T19:33:57.714Z,signaling_processing,13.391
2026-01-02T19:33:57.714Z,sdp_offer_processing,6.587
2026-01-02T19:33:57.714Z,sdp_answer_creation,0.365
2026-01-02T19:33:57.715Z,ice_gathering,0.255
2026-01-02T19:33:57.825Z,ice_connection,122.588
2026-01-02T19:33:57.979Z,dtls_handshake,153.612
```
**Server Metrics:**
- `signaling_processing`: Total signaling time (offer → answer)
- `sdp_offer_processing`: SDP offer parsing time
- `sdp_answer_creation`: SDP answer generation time
- `ice_gathering`: ICE candidate gathering time
- `ice_connection`: Time from connection start to ICE connected
- `dtls_handshake`: DTLS handshake completion time
#### client-latencies.csv (Client)
Connection setup timing from client perspective:
```
timestamp,type,latencyMs
2026-01-02T11:33:57.706Z,ice_gathering,5001.234
2026-01-02T11:33:57.706Z,signaling_rtt,72.456
2026-01-02T11:33:57.811Z,ice_connection,5183.789
2026-01-02T11:33:57.916Z,dtls_handshake,104.123
2026-01-02T11:33:57.916Z,media_ready,5287.912
```
**Client Metrics:**
- `ice_gathering`: ICE candidate gathering time
- `signaling_rtt`: Round-trip time for signaling exchange
- `ice_connection`: Total time to ICE connected
- `dtls_handshake`: DTLS handshake completion time
- `media_ready`: Total connection setup time
All latency measurements are recorded with sub-millisecond precision.
### Results
The following graph was generated from the `results.csv` that was generated by the server. The client was run from another EC2 instance in the same VPC.
The Y Axis is the CPU Usage, and the X Axis is the count of PeerConnections. This was run on a `m4.2xlarge (Intel(R) Xeon(R) CPU E5-2686 v4 @ 2.30GHz)`
<img src="./.github/plot.png" alt="Results Graph">
### FAQ
#### What codec/bitrate was being distributed
This is controlled by what video you use. You can go as high (or low) as you want.
#### What SRTP Cipher was used
SRTP_AEAD_AES_128_GCM
#### What Congestion Control/Feedback is used
None, on purpose.
Pion by design allows the user to specify what they want. We are distributing a video feed that is already encoded, and has a very small keyframe-interval so these things don't help us.
When setting up the PeerConnection you have full control of the RTP/RTCP pipelines, so users can add TWCC/NACK/FEC in a way that works for them.
#### I want to talk about cool WebRTC stuff!
Join the [Pion Discord](https://discord.gg/PngbdqpFbt)!
### Community
Pion has an active community on the [Discord](https://discord.gg/PngbdqpFbt).
Follow the [Pion Bluesky](https://bsky.app/profile/pion.ly) or [Pion Twitter](https://twitter.com/_pion) for project updates and important WebRTC news.
We are always looking to support **your projects**. Please reach out if you have something to build!
If you need commercial support or don't want to use public methods you can contact us at [team@pion.ly](mailto:team@pion.ly)
### License
MIT License - see [LICENSE](LICENSE) for full text
================================================
FILE: client/main.go
================================================
// SPDX-FileCopyrightText: 2026 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"os"
"time"
"github.com/pion/webrtc/v4"
)
type latencyMeasurement struct {
timestamp time.Time // When the operation completed (not when it started)
latencyMs float64 // Latency duration in milliseconds
metricType string // Measurement type (see latencyLogger for valid types)
}
// nolint: gochecknoglobals
var (
clientLatencies = make(chan latencyMeasurement, 10000)
)
type connectionMetrics struct {
// Timing milestones
connectionStart time.Time
offerCreated time.Time
iceGatheringStart time.Time
iceGatheringComplete time.Time
offerSent time.Time
answerReceived time.Time
iceConnected time.Time
dtlsComplete time.Time
mediaReady time.Time
}
// Generate latency measurements CSV with columns of timestamp, type, and latencyMs.
// The timestamp represents when the operation completed (not when it started).
//
// Valid measurement types:
// - "ice_gathering": Time spent gathering ICE candidates
// - "signaling_rtt": Round-trip time from offer sent to answer received
// - "ice_connection": Time from connection start to ICE connected
// - "dtls_handshake": Time from ICE connected to DTLS handshake complete
// - "media_ready": Total connection setup time from start to media ready
func latencyLogger() {
file, err := os.OpenFile("client-latencies.csv", os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o644) // nolint: gosec
if err != nil {
panic(err)
}
defer func() {
if err := file.Close(); err != nil {
panic(err)
}
}()
if _, err := file.WriteString("timestamp,type,latencyMs\n"); err != nil {
panic(err)
}
syncTicker := time.NewTicker(3 * time.Second)
defer syncTicker.Stop()
for {
select {
case measurement, ok := <-clientLatencies:
if !ok {
return
}
if _, err := fmt.Fprintf(file, "%s,%s,%f\n",
measurement.timestamp.Format(time.RFC3339Nano),
measurement.metricType,
measurement.latencyMs); err != nil {
panic(err)
}
case <-syncTicker.C:
if err := file.Sync(); err != nil {
panic(err)
}
}
}
}
func recordMetric(timestamp time.Time, metricType string, latencyMs float64) {
measurement := latencyMeasurement{
timestamp: timestamp,
latencyMs: latencyMs,
metricType: metricType,
}
select {
case clientLatencies <- measurement:
default:
// Channel full, drop measurement to avoid blocking
}
}
func recordConnectionMetrics(metrics *connectionMetrics) {
// Calculate latencies
iceGatheringLatency := float64(metrics.iceGatheringComplete.Sub(metrics.iceGatheringStart).Microseconds()) / 1000.0
signalingRTT := float64(metrics.answerReceived.Sub(metrics.offerSent).Microseconds()) / 1000.0
iceLatency := float64(metrics.iceConnected.Sub(metrics.connectionStart).Microseconds()) / 1000.0
dtlsLatency := float64(metrics.dtlsComplete.Sub(metrics.iceConnected).Microseconds()) / 1000.0
mediaReadyLatency := float64(metrics.mediaReady.Sub(metrics.connectionStart).Microseconds()) / 1000.0
// Record to CSV via channel
recordMetric(metrics.iceGatheringComplete, "ice_gathering", iceGatheringLatency)
recordMetric(metrics.answerReceived, "signaling_rtt", signalingRTT)
recordMetric(metrics.iceConnected, "ice_connection", iceLatency)
recordMetric(metrics.dtlsComplete, "dtls_handshake", dtlsLatency)
recordMetric(metrics.mediaReady, "media_ready", mediaReadyLatency)
}
func newPeerConnection() { // nolint: cyclop
metrics := &connectionMetrics{
connectionStart: time.Now(),
}
done := make(chan struct{})
peerConnection, err := webrtc.NewPeerConnection(webrtc.Configuration{})
if err != nil {
panic(err)
}
// Track ICE connection state changes
peerConnection.OnICEConnectionStateChange(func(state webrtc.ICEConnectionState) {
if state == webrtc.ICEConnectionStateConnected {
metrics.iceConnected = time.Now()
}
})
// Track when media is ready (ICE + DTLS complete)
peerConnection.OnConnectionStateChange(func(state webrtc.PeerConnectionState) {
if state == webrtc.PeerConnectionStateConnected {
metrics.dtlsComplete = time.Now()
metrics.mediaReady = time.Now()
// Record metrics after connection is established
recordConnectionMetrics(metrics)
close(done)
}
})
if _, err = peerConnection.AddTransceiverFromKind(webrtc.RTPCodecTypeVideo); err != nil {
panic(err)
}
gatherCompletePromise := webrtc.GatheringCompletePromise(peerConnection)
metrics.offerCreated = time.Now()
offer, err := peerConnection.CreateOffer(nil)
if err != nil {
panic(err)
} else if err = peerConnection.SetLocalDescription(offer); err != nil {
panic(err)
}
metrics.iceGatheringStart = time.Now()
<-gatherCompletePromise
metrics.iceGatheringComplete = time.Now()
offerJSON, err := json.Marshal(*peerConnection.LocalDescription())
if err != nil {
panic(err)
}
metrics.offerSent = time.Now()
// nolint:gosec,noctx
resp, err := http.Post(
fmt.Sprintf("http://%s/doSignaling", os.Args[1]),
"application/json",
bytes.NewReader(offerJSON),
)
if err != nil {
panic(err)
}
resp.Close = true
var answer webrtc.SessionDescription
if err = json.NewDecoder(resp.Body).Decode(&answer); err != nil {
panic(err)
}
metrics.answerReceived = time.Now()
if err = peerConnection.SetRemoteDescription(answer); err != nil {
panic(err)
}
if err = resp.Body.Close(); err != nil {
panic(err)
}
// Wait for connection to complete or timeout
select {
case <-done:
// Connection completed successfully
case <-time.After(5 * time.Second):
// Connection timeout - metrics may be incomplete
panic("connection timeout")
}
}
func main() {
if len(os.Args) != 2 {
panic("client expects server host+port")
}
// Start latency logger goroutine
go latencyLogger()
for range time.NewTicker(5 * time.Second).C {
for i := 0; i <= 10; i++ {
newPeerConnection()
}
}
}
================================================
FILE: codecov.yml
================================================
#
# DO NOT EDIT THIS FILE
#
# It is automatically copied from https://github.com/pion/.goassets repository.
#
# SPDX-FileCopyrightText: 2026 The Pion community <https://pion.ly>
# SPDX-License-Identifier: MIT
coverage:
status:
project:
default:
# Allow decreasing 2% of total coverage to avoid noise.
threshold: 2%
patch:
default:
target: 70%
only_pulls: true
ignore:
- "examples/*"
- "examples/**/*"
================================================
FILE: go.mod
================================================
module github.com/pion/webrtc-bench
go 1.24.0
require (
github.com/pion/webrtc/v4 v4.2.9
github.com/shirou/gopsutil/v4 v4.26.2
)
require (
github.com/ebitengine/purego v0.10.0 // indirect
github.com/go-ole/go-ole v1.2.6 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 // indirect
github.com/pion/datachannel v1.6.0 // indirect
github.com/pion/dtls/v3 v3.1.2 // indirect
github.com/pion/ice/v4 v4.2.1 // indirect
github.com/pion/interceptor v0.1.44 // indirect
github.com/pion/logging v0.2.4 // indirect
github.com/pion/mdns/v2 v2.1.0 // indirect
github.com/pion/randutil v0.1.0 // indirect
github.com/pion/rtcp v1.2.16 // indirect
github.com/pion/rtp v1.10.1 // indirect
github.com/pion/sctp v1.9.2 // indirect
github.com/pion/sdp/v3 v3.0.18 // indirect
github.com/pion/srtp/v3 v3.0.10 // indirect
github.com/pion/stun/v3 v3.1.1 // indirect
github.com/pion/transport/v4 v4.0.1 // indirect
github.com/pion/turn/v4 v4.1.4 // indirect
github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 // indirect
github.com/tklauser/go-sysconf v0.3.16 // indirect
github.com/tklauser/numcpus v0.11.0 // indirect
github.com/wlynxg/anet v0.0.5 // indirect
github.com/yusufpapurcu/wmi v1.2.4 // indirect
golang.org/x/crypto v0.48.0 // indirect
golang.org/x/net v0.50.0 // indirect
golang.org/x/sys v0.41.0 // indirect
golang.org/x/time v0.10.0 // indirect
)
================================================
FILE: go.sum
================================================
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/ebitengine/purego v0.10.0 h1:QIw4xfpWT6GWTzaW5XEKy3HXoqrJGx1ijYHzTF0/ISU=
github.com/ebitengine/purego v0.10.0/go.mod h1:iIjxzd6CiRiOG0UyXP+V1+jWqUXVjPKLAI0mRfJZTmQ=
github.com/go-ole/go-ole v1.2.6 h1:/Fpf6oFPoeFik9ty7siob0G6Ke8QvQEuVcuChpwXzpY=
github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0=
github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 h1:6E+4a0GO5zZEnZ81pIr0yLvtUWk2if982qA3F3QD6H4=
github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0/go.mod h1:zJYVVT2jmtg6P3p1VtQj7WsuWi/y4VnjVBn7F8KPB3I=
github.com/pion/datachannel v1.6.0 h1:XecBlj+cvsxhAMZWFfFcPyUaDZtd7IJvrXqlXD/53i0=
github.com/pion/datachannel v1.6.0/go.mod h1:ur+wzYF8mWdC+Mkis5Thosk+u/VOL287apDNEbFpsIk=
github.com/pion/dtls/v3 v3.1.2 h1:gqEdOUXLtCGW+afsBLO0LtDD8GnuBBjEy6HRtyofZTc=
github.com/pion/dtls/v3 v3.1.2/go.mod h1:Hw/igcX4pdY69z1Hgv5x7wJFrUkdgHwAn/Q/uo7YHRo=
github.com/pion/ice/v4 v4.2.1 h1:XPRYXaLiFq3LFDG7a7bMrmr3mFr27G/gtXN3v/TVfxY=
github.com/pion/ice/v4 v4.2.1/go.mod h1:2quLV1S5v1tAx3VvAJaH//KGitRXvo4RKlX6D3tnN+c=
github.com/pion/interceptor v0.1.44 h1:sNlZwM8dWXU9JQAkJh8xrarC0Etn8Oolcniukmuy0/I=
github.com/pion/interceptor v0.1.44/go.mod h1:4atVlBkcgXuUP+ykQF0qOCGU2j7pQzX2ofvPRFsY5RY=
github.com/pion/logging v0.2.4 h1:tTew+7cmQ+Mc1pTBLKH2puKsOvhm32dROumOZ655zB8=
github.com/pion/logging v0.2.4/go.mod h1:DffhXTKYdNZU+KtJ5pyQDjvOAh/GsNSyv1lbkFbe3so=
github.com/pion/mdns/v2 v2.1.0 h1:3IJ9+Xio6tWYjhN6WwuY142P/1jA0D5ERaIqawg/fOY=
github.com/pion/mdns/v2 v2.1.0/go.mod h1:pcez23GdynwcfRU1977qKU0mDxSeucttSHbCSfFOd9A=
github.com/pion/randutil v0.1.0 h1:CFG1UdESneORglEsnimhUjf33Rwjubwj6xfiOXBa3mA=
github.com/pion/randutil v0.1.0/go.mod h1:XcJrSMMbbMRhASFVOlj/5hQial/Y8oH/HVo7TBZq+j8=
github.com/pion/rtcp v1.2.16 h1:fk1B1dNW4hsI78XUCljZJlC4kZOPk67mNRuQ0fcEkSo=
github.com/pion/rtcp v1.2.16/go.mod h1:/as7VKfYbs5NIb4h6muQ35kQF/J0ZVNz2Z3xKoCBYOo=
github.com/pion/rtp v1.10.1 h1:xP1prZcCTUuhO2c83XtxyOHJteISg6o8iPsE2acaMtA=
github.com/pion/rtp v1.10.1/go.mod h1:rF5nS1GqbR7H/TCpKwylzeq6yDM+MM6k+On5EgeThEM=
github.com/pion/sctp v1.9.2 h1:HxsOzEV9pWoeggv7T5kewVkstFNcGvhMPx0GvUOUQXo=
github.com/pion/sctp v1.9.2/go.mod h1:OTOlsQ5EDQ6mQ0z4MUGXt2CgQmKyafBEXhUVqLRB6G8=
github.com/pion/sdp/v3 v3.0.18 h1:l0bAXazKHpepazVdp+tPYnrsy9dfh7ZbT8DxesH5ZnI=
github.com/pion/sdp/v3 v3.0.18/go.mod h1:ZREGo6A9ZygQ9XkqAj5xYCQtQpif0i6Pa81HOiAdqQ8=
github.com/pion/srtp/v3 v3.0.10 h1:tFirkpBb3XccP5VEXLi50GqXhv5SKPxqrdlhDCJlZrQ=
github.com/pion/srtp/v3 v3.0.10/go.mod h1:3mOTIB0cq9qlbn59V4ozvv9ClW/BSEbRp4cY0VtaR7M=
github.com/pion/stun/v3 v3.1.1 h1:CkQxveJ4xGQjulGSROXbXq94TAWu8gIX2dT+ePhUkqw=
github.com/pion/stun/v3 v3.1.1/go.mod h1:qC1DfmcCTQjl9PBaMa5wSn3x9IPmKxSdcCsxBcDBndM=
github.com/pion/transport/v3 v3.1.1 h1:Tr684+fnnKlhPceU+ICdrw6KKkTms+5qHMgw6bIkYOM=
github.com/pion/transport/v3 v3.1.1/go.mod h1:+c2eewC5WJQHiAA46fkMMzoYZSuGzA/7E2FPrOYHctQ=
github.com/pion/transport/v4 v4.0.1 h1:sdROELU6BZ63Ab7FrOLn13M6YdJLY20wldXW2Cu2k8o=
github.com/pion/transport/v4 v4.0.1/go.mod h1:nEuEA4AD5lPdcIegQDpVLgNoDGreqM/YqmEx3ovP4jM=
github.com/pion/turn/v4 v4.1.4 h1:EU11yMXKIsK43FhcUnjLlrhE4nboHZq+TXBIi3QpcxQ=
github.com/pion/turn/v4 v4.1.4/go.mod h1:ES1DXVFKnOhuDkqn9hn5VJlSWmZPaRJLyBXoOeO/BmQ=
github.com/pion/webrtc/v4 v4.2.9 h1:DZIh1HAhPIL3RvwEDFsmL5hfPSLEpxsQk9/Jir2vkJE=
github.com/pion/webrtc/v4 v4.2.9/go.mod h1:9EmLZve0H76eTzf8v2FmchZ6tcBXtDgpfTEu+drW6SY=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 h1:o4JXh1EVt9k/+g42oCprj/FisM4qX9L3sZB3upGN2ZU=
github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE=
github.com/shirou/gopsutil/v4 v4.26.2 h1:X8i6sicvUFih4BmYIGT1m2wwgw2VG9YgrDTi7cIRGUI=
github.com/shirou/gopsutil/v4 v4.26.2/go.mod h1:LZ6ewCSkBqUpvSOf+LsTGnRinC6iaNUNMGBtDkJBaLQ=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
github.com/tklauser/go-sysconf v0.3.16 h1:frioLaCQSsF5Cy1jgRBrzr6t502KIIwQ0MArYICU0nA=
github.com/tklauser/go-sysconf v0.3.16/go.mod h1:/qNL9xxDhc7tx3HSRsLWNnuzbVfh3e7gh/BmM179nYI=
github.com/tklauser/numcpus v0.11.0 h1:nSTwhKH5e1dMNsCdVBukSZrURJRoHbSEQjdEbY+9RXw=
github.com/tklauser/numcpus v0.11.0/go.mod h1:z+LwcLq54uWZTX0u/bGobaV34u6V7KNlTZejzM6/3MQ=
github.com/wlynxg/anet v0.0.5 h1:J3VJGi1gvo0JwZ/P1/Yc/8p63SoW98B5dHkYDmpgvvU=
github.com/wlynxg/anet v0.0.5/go.mod h1:eay5PRQr7fIVAMbTbchTnO9gG65Hg/uYGdc7mguHxoA=
github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0=
github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0=
golang.org/x/crypto v0.48.0 h1:/VRzVqiRSggnhY7gNRxPauEQ5Drw9haKdM0jqfcCFts=
golang.org/x/crypto v0.48.0/go.mod h1:r0kV5h3qnFPlQnBSrULhlsRfryS2pmewsg+XfMgkVos=
golang.org/x/net v0.50.0 h1:ucWh9eiCGyDR3vtzso0WMQinm2Dnt8cFMuQa9K33J60=
golang.org/x/net v0.50.0/go.mod h1:UgoSli3F/pBgdJBHCTc+tp3gmrU4XswgGRgtnwWTfyM=
golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201204225414-ed752295db88/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=
golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/time v0.10.0 h1:3usCWA8tQn0L8+hFJQNgzpWbd89begxN66o1Ojdn5L4=
golang.org/x/time v0.10.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
================================================
FILE: renovate.json
================================================
{
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
"extends": [
"github>pion/renovate-config"
]
}
================================================
FILE: server/main.go
================================================
// SPDX-FileCopyrightText: 2026 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
//go:build !js
package main
import (
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os"
"sync/atomic"
"time"
"github.com/pion/webrtc/v4"
"github.com/pion/webrtc/v4/pkg/media"
"github.com/pion/webrtc/v4/pkg/media/ivfreader"
"github.com/shirou/gopsutil/v4/cpu"
)
type latencyMeasurement struct {
timestamp time.Time // When the operation completed (not when it started)
latencyMs float64 // Latency duration in milliseconds
metricType string // Measurement type (see rawLatencyLogger for valid types)
}
// nolint: gochecknoglobals
var (
outboundVideoTrack *webrtc.TrackLocalStaticSample
peerConnectionCount int64
rawLatencies = make(chan latencyMeasurement, 10000)
droppedLatencyMeasurements int64
)
// Generate latency measurements CSV with columns of timestamp, type, and latencyMs.
// The timestamp represents when the operation completed (not when it started).
//
// Valid measurement types (prefixed by protocol layer):
// - "signaling_processing": Total server-side signaling processing time (offer to answer)
// - "sdp_offer_processing": Time to process incoming SDP offer (SetRemoteDescription)
// - "sdp_answer_creation": Time to create SDP answer (CreateAnswer)
// - "ice_gathering": Time spent gathering local ICE candidates
// - "ice_connection": Time from PeerConnection creation to ICE connected (includes signaling + network + client)
// - "dtls_handshake": Time from ICE connected to DTLS handshake complete
func rawLatencyLogger() {
file, err := os.OpenFile("server-latencies.csv", os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o644) // nolint: gosec
if err != nil {
panic(err)
}
defer func() {
if err := file.Close(); err != nil {
panic(err)
}
}()
if _, err := file.WriteString("timestamp,type,latencyMs\n"); err != nil {
panic(err)
}
syncTicker := time.NewTicker(3 * time.Second)
defer syncTicker.Stop()
for {
select {
case measurement, ok := <-rawLatencies:
if !ok {
return
}
if _, err := fmt.Fprintf(file, "%s,%s,%f\n",
measurement.timestamp.Format(time.RFC3339Nano),
measurement.metricType,
measurement.latencyMs); err != nil {
panic(err)
}
case <-syncTicker.C:
if err := file.Sync(); err != nil {
panic(err)
}
}
}
}
// Generate CSV with columns of timestamp, peerConnectionCount, cpuUsage, and droppedLatencyMeasurements.
func reportBuilder() {
file, err := os.OpenFile("report.csv", os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o644) // nolint: gosec
if err != nil {
panic(err)
}
if _, err := file.WriteString("timestamp, peerConnectionCount, cpuUsage, droppedLatencyMeasurements\n"); err != nil {
panic(err)
}
for range time.NewTicker(3 * time.Second).C {
usage, err := cpu.Percent(0, false)
if err != nil {
panic(err)
} else if len(usage) != 1 {
panic(fmt.Sprintf("CPU Usage results should have 1 sample, have %d", len(usage)))
}
if _, err = fmt.Fprintf(file, "%s, %d, %f, %d\n", time.Now().Format(time.RFC3339), atomic.LoadInt64(&peerConnectionCount), usage[0], atomic.LoadInt64(&droppedLatencyMeasurements)); err != nil { // nolint: lll
panic(err)
}
}
}
// HTTP Handler that accepts an Offer and returns an Answer
// adds outboundVideoTrack to PeerConnection.
func doSignaling(w http.ResponseWriter, r *http.Request) { // nolint: cyclop, varnamelen
signalingStartTime := time.Now()
defer func() {
latency := time.Since(signalingStartTime)
measurement := latencyMeasurement{
timestamp: time.Now(),
latencyMs: float64(latency.Microseconds()) / 1000.0,
metricType: "signaling_processing",
}
select {
case rawLatencies <- measurement:
default:
// Channel full, drop measurement to avoid blocking
atomic.AddInt64(&droppedLatencyMeasurements, 1)
}
}()
peerConnection, err := webrtc.NewPeerConnection(webrtc.Configuration{})
if err != nil {
panic(err)
}
// Track when PeerConnection is created for ICE connection latency measurement
peerConnectionCreatedTime := time.Now()
// Track when ICE connects for DTLS handshake latency measurement
var iceConnectedTime time.Time
peerConnection.OnICEConnectionStateChange(func(connectionState webrtc.ICEConnectionState) {
switch connectionState { // nolint: exhaustive
case webrtc.ICEConnectionStateDisconnected, webrtc.ICEConnectionStateFailed:
if closeErr := peerConnection.Close(); closeErr != nil {
panic(closeErr)
}
case webrtc.ICEConnectionStateClosed:
atomic.AddInt64(&peerConnectionCount, -1)
case webrtc.ICEConnectionStateConnected:
// Track when ICE connects for DTLS measurement
iceConnectedTime = time.Now()
// Measure ICE connection latency from PeerConnection creation to ICE connected.
// NOTE: This includes signaling processing time, network RTT for client to receive answer,
// client processing time, and ICE check exchanges. This is NOT a pure RTT measurement.
iceLatency := time.Since(peerConnectionCreatedTime)
iceMeasurement := latencyMeasurement{
timestamp: time.Now(),
latencyMs: float64(iceLatency.Microseconds()) / 1000.0,
metricType: "ice_connection",
}
select {
case rawLatencies <- iceMeasurement:
default:
// Channel full, drop measurement to avoid blocking
atomic.AddInt64(&droppedLatencyMeasurements, 1)
}
atomic.AddInt64(&peerConnectionCount, 1)
}
})
peerConnection.OnConnectionStateChange(func(connectionState webrtc.PeerConnectionState) {
if connectionState == webrtc.PeerConnectionStateConnected && !iceConnectedTime.IsZero() {
// Measure DTLS handshake latency (from ICE connected to PeerConnection connected)
dtlsLatency := time.Since(iceConnectedTime)
dtlsMeasurement := latencyMeasurement{
timestamp: time.Now(),
latencyMs: float64(dtlsLatency.Microseconds()) / 1000.0,
metricType: "dtls_handshake",
}
select {
case rawLatencies <- dtlsMeasurement:
default:
// Channel full, drop measurement to avoid blocking
atomic.AddInt64(&droppedLatencyMeasurements, 1)
}
}
})
if _, err = peerConnection.AddTrack(outboundVideoTrack); err != nil {
panic(err)
}
var offer webrtc.SessionDescription
if err = json.NewDecoder(r.Body).Decode(&offer); err != nil {
panic(err)
}
// Measure offer processing latency
offerProcessingStartTime := time.Now()
if err = peerConnection.SetRemoteDescription(offer); err != nil {
panic(err)
}
offerProcessingLatency := time.Since(offerProcessingStartTime)
offerProcessingMeasurement := latencyMeasurement{
timestamp: time.Now(),
latencyMs: float64(offerProcessingLatency.Microseconds()) / 1000.0,
metricType: "sdp_offer_processing",
}
select {
case rawLatencies <- offerProcessingMeasurement:
default:
// Channel full, drop measurement to avoid blocking
atomic.AddInt64(&droppedLatencyMeasurements, 1)
}
gatherCompletePromise := webrtc.GatheringCompletePromise(peerConnection)
// Measure answer creation latency
answerCreationStartTime := time.Now()
answer, err := peerConnection.CreateAnswer(nil)
if err != nil {
panic(err)
}
answerCreationLatency := time.Since(answerCreationStartTime)
answerCreationMeasurement := latencyMeasurement{
timestamp: time.Now(),
latencyMs: float64(answerCreationLatency.Microseconds()) / 1000.0,
metricType: "sdp_answer_creation",
}
select {
case rawLatencies <- answerCreationMeasurement:
default:
// Channel full, drop measurement to avoid blocking
atomic.AddInt64(&droppedLatencyMeasurements, 1)
}
if err = peerConnection.SetLocalDescription(answer); err != nil {
panic(err)
}
// Track when ICE gathering starts
iceGatheringStartTime := time.Now()
<-gatherCompletePromise
// Measure ICE gathering latency
iceGatheringLatency := time.Since(iceGatheringStartTime)
iceGatheringMeasurement := latencyMeasurement{
timestamp: time.Now(),
latencyMs: float64(iceGatheringLatency.Microseconds()) / 1000.0,
metricType: "ice_gathering",
}
select {
case rawLatencies <- iceGatheringMeasurement:
default:
// Channel full, drop measurement to avoid blocking
atomic.AddInt64(&droppedLatencyMeasurements, 1)
}
response, err := json.Marshal(*peerConnection.LocalDescription())
if err != nil {
panic(err)
}
w.Header().Set("Content-Type", "application/json")
if _, err := w.Write(response); err != nil {
panic(err)
}
}
func main() {
var err error
outboundVideoTrack, err = webrtc.NewTrackLocalStaticSample(webrtc.RTPCodecCapability{
MimeType: webrtc.MimeTypeVP8,
}, "pion", "pion")
if err != nil {
panic(err)
}
go func() {
for {
playVideo()
}
}()
go reportBuilder()
go rawLatencyLogger()
http.Handle("/", http.FileServer(http.Dir("./static")))
http.HandleFunc("/doSignaling", doSignaling)
fmt.Println("Open http://localhost:8080 to access this demo")
panic(http.ListenAndServe(":8080", nil)) // nolint: gosec
}
const videoFileName = "input.ivf"
func playVideo() {
file, err := os.Open(videoFileName)
if err != nil {
panic(err)
}
ivf, header, err := ivfreader.NewWith(file)
if err != nil {
panic(err)
}
ticker := time.NewTicker(
time.Millisecond * time.Duration((float32(header.TimebaseNumerator)/float32(header.TimebaseDenominator))*1000),
)
defer ticker.Stop()
for ; true; <-ticker.C {
frame, _, err := ivf.ParseNextFrame()
if errors.Is(err, io.EOF) {
return
}
if err != nil {
panic(err)
}
if err = outboundVideoTrack.WriteSample(media.Sample{Data: frame, Duration: time.Second}); err != nil {
panic(err)
}
}
}
================================================
FILE: server/static/index.html
================================================
<html lang="en">
<!--
SPDX-FileCopyrightText: 2026 The Pion community <https://pion.ly>
SPDX-License-Identifier: MIT
-->
<head>
<title>webrtc-bench</title>
</head>
<body>
<h3><a href="index.html">Video</a></h3>
<div id="remoteVideos"></div>
<br/>
<div>
<button onclick="window.doSignaling(true)"> ICE Restart (reconnect)</button>
</div>
<h3> Logs </h3>
<div id="logs"></div>
</body>
<script>
let pc = new RTCPeerConnection()
pc.addTransceiver('video')
let log = msg => {
document.getElementById('logs').innerHTML += msg + '<br>'
}
pc.oniceconnectionstatechange = () => log(pc.iceConnectionState)
pc.ontrack = function (event) {
let el = document.createElement(event.track.kind)
el.srcObject = event.streams[0]
el.autoplay = true
el.controls = true
document.getElementById('remoteVideos').appendChild(el)
}
window.doSignaling = iceRestart => {
pc.createOffer({iceRestart})
.then(offer => {
pc.setLocalDescription(offer)
return fetch(`/doSignaling`, {
method: 'post',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
},
body: JSON.stringify(offer)
})
})
.then(res => res.json())
.then(res => pc.setRemoteDescription(res))
.catch(alert)
}
window.doSignaling(false)
</script>
</html>
gitextract_s0aj61ys/
├── .github/
│ ├── .ci.conf
│ ├── .gitignore
│ ├── fetch-scripts.sh
│ ├── install-hooks.sh
│ ├── pion-gopher-webrtc.png.license
│ ├── plot.png.license
│ └── workflows/
│ ├── api.yaml
│ ├── codeql-analysis.yml
│ ├── fuzz.yaml
│ ├── lint.yaml
│ ├── release.yml
│ ├── renovate-go-sum-fix.yaml
│ ├── reuse.yml
│ ├── test.yaml
│ └── tidy-check.yaml
├── .gitignore
├── .golangci.yml
├── .goreleaser.yml
├── .reuse/
│ └── dep5
├── LICENSE
├── LICENSES/
│ └── MIT.txt
├── README.md
├── client/
│ └── main.go
├── codecov.yml
├── go.mod
├── go.sum
├── renovate.json
└── server/
├── main.go
└── static/
└── index.html
SYMBOL INDEX (14 symbols across 2 files)
FILE: client/main.go
type latencyMeasurement (line 17) | type latencyMeasurement struct
type connectionMetrics (line 28) | type connectionMetrics struct
function latencyLogger (line 50) | func latencyLogger() {
function recordMetric (line 88) | func recordMetric(timestamp time.Time, metricType string, latencyMs floa...
function recordConnectionMetrics (line 101) | func recordConnectionMetrics(metrics *connectionMetrics) {
function newPeerConnection (line 117) | func newPeerConnection() { // nolint: cyclop
function main (line 205) | func main() {
FILE: server/main.go
type latencyMeasurement (line 24) | type latencyMeasurement struct
function rawLatencyLogger (line 48) | func rawLatencyLogger() {
function reportBuilder (line 87) | func reportBuilder() {
function doSignaling (line 112) | func doSignaling(w http.ResponseWriter, r *http.Request) { // nolint: cy...
function main (line 272) | func main() {
constant videoFileName (line 297) | videoFileName = "input.ivf"
function playVideo (line 299) | func playVideo() {
Condensed preview — 29 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (56K chars).
[
{
"path": ".github/.ci.conf",
"chars": 148,
"preview": "# SPDX-FileCopyrightText: 2026 The Pion community <https://pion.ly>\n# SPDX-License-Identifier: MIT\n\nGO_MOD_VERSION_EXPEC"
},
{
"path": ".github/.gitignore",
"chars": 110,
"preview": "# SPDX-FileCopyrightText: 2026 The Pion community <https://pion.ly>\n# SPDX-License-Identifier: MIT\n\n.goassets\n"
},
{
"path": ".github/fetch-scripts.sh",
"chars": 894,
"preview": "#!/bin/sh\n\n#\n# DO NOT EDIT THIS FILE\n#\n# It is automatically copied from https://github.com/pion/.goassets repository.\n#"
},
{
"path": ".github/install-hooks.sh",
"chars": 594,
"preview": "#!/bin/sh\n\n#\n# DO NOT EDIT THIS FILE\n#\n# It is automatically copied from https://github.com/pion/.goassets repository.\n#"
},
{
"path": ".github/pion-gopher-webrtc.png.license",
"chars": 94,
"preview": "SPDX-FileCopyrightText: 2026 The Pion community <https://pion.ly>\nSPDX-License-Identifier: MIT"
},
{
"path": ".github/plot.png.license",
"chars": 94,
"preview": "SPDX-FileCopyrightText: 2026 The Pion community <https://pion.ly>\nSPDX-License-Identifier: MIT"
},
{
"path": ".github/workflows/api.yaml",
"chars": 586,
"preview": "#\n# DO NOT EDIT THIS FILE\n#\n# It is automatically copied from https://github.com/pion/.goassets repository.\n# If this re"
},
{
"path": ".github/workflows/codeql-analysis.yml",
"chars": 716,
"preview": "#\n# DO NOT EDIT THIS FILE\n#\n# It is automatically copied from https://github.com/pion/.goassets repository.\n# If this re"
},
{
"path": ".github/workflows/fuzz.yaml",
"chars": 734,
"preview": "#\n# DO NOT EDIT THIS FILE\n#\n# It is automatically copied from https://github.com/pion/.goassets repository.\n# If this re"
},
{
"path": ".github/workflows/lint.yaml",
"chars": 634,
"preview": "#\n# DO NOT EDIT THIS FILE\n#\n# It is automatically copied from https://github.com/pion/.goassets repository.\n# If this re"
},
{
"path": ".github/workflows/release.yml",
"chars": 678,
"preview": "#\n# DO NOT EDIT THIS FILE\n#\n# It is automatically copied from https://github.com/pion/.goassets repository.\n# If this re"
},
{
"path": ".github/workflows/renovate-go-sum-fix.yaml",
"chars": 693,
"preview": "#\n# DO NOT EDIT THIS FILE\n#\n# It is automatically copied from https://github.com/pion/.goassets repository.\n# If this re"
},
{
"path": ".github/workflows/reuse.yml",
"chars": 615,
"preview": "#\n# DO NOT EDIT THIS FILE\n#\n# It is automatically copied from https://github.com/pion/.goassets repository.\n# If this re"
},
{
"path": ".github/workflows/test.yaml",
"chars": 1739,
"preview": "#\n# DO NOT EDIT THIS FILE\n#\n# It is automatically copied from https://github.com/pion/.goassets repository.\n# If this re"
},
{
"path": ".github/workflows/tidy-check.yaml",
"chars": 702,
"preview": "#\n# DO NOT EDIT THIS FILE\n#\n# It is automatically copied from https://github.com/pion/.goassets repository.\n# If this re"
},
{
"path": ".gitignore",
"chars": 410,
"preview": "# SPDX-FileCopyrightText: 2026 The Pion community <https://pion.ly>\n# SPDX-License-Identifier: MIT\n\n### JetBrains IDE ##"
},
{
"path": ".golangci.yml",
"chars": 8499,
"preview": "# SPDX-FileCopyrightText: 2026 The Pion community <https://pion.ly>\n# SPDX-License-Identifier: MIT\n\nversion: \"2\"\nlinters"
},
{
"path": ".goreleaser.yml",
"chars": 121,
"preview": "# SPDX-FileCopyrightText: 2026 The Pion community <https://pion.ly>\n# SPDX-License-Identifier: MIT\n\nbuilds:\n- skip: true"
},
{
"path": ".reuse/dep5",
"chars": 588,
"preview": "Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/\nUpstream-Name: Pion\nSource: https://github.co"
},
{
"path": "LICENSE",
"chars": 1093,
"preview": "MIT License\n\nCopyright (c) 2026 The Pion community <https://pion.ly>\n\nPermission is hereby granted, free of charge, to a"
},
{
"path": "LICENSES/MIT.txt",
"chars": 1078,
"preview": "MIT License\n\nCopyright (c) <year> <copyright holders>\n\nPermission is hereby granted, free of charge, to any person obtai"
},
{
"path": "README.md",
"chars": 5337,
"preview": "<h1 align=\"center\">\n <a href=\"https://pion.ly\"><img src=\"./.github/pion-gopher-webrtc.png\" alt=\"Pion WebRTC\" height=\"25"
},
{
"path": "client/main.go",
"chars": 5988,
"preview": "// SPDX-FileCopyrightText: 2026 The Pion community <https://pion.ly>\n// SPDX-License-Identifier: MIT\n\npackage main\n\nimpo"
},
{
"path": "codecov.yml",
"chars": 461,
"preview": "#\n# DO NOT EDIT THIS FILE\n#\n# It is automatically copied from https://github.com/pion/.goassets repository.\n#\n# SPDX-Fil"
},
{
"path": "go.mod",
"chars": 1456,
"preview": "module github.com/pion/webrtc-bench\n\ngo 1.24.0\n\nrequire (\n\tgithub.com/pion/webrtc/v4 v4.2.9\n\tgithub.com/shirou/gopsutil/"
},
{
"path": "go.sum",
"chars": 6552,
"preview": "github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.m"
},
{
"path": "renovate.json",
"chars": 123,
"preview": "{\n \"$schema\": \"https://docs.renovatebot.com/renovate-schema.json\",\n \"extends\": [\n \"github>pion/renovate-config\"\n ]"
},
{
"path": "server/main.go",
"chars": 9589,
"preview": "// SPDX-FileCopyrightText: 2026 The Pion community <https://pion.ly>\n// SPDX-License-Identifier: MIT\n\n//go:build !js\n\npa"
},
{
"path": "server/static/index.html",
"chars": 1597,
"preview": "<html lang=\"en\">\n <!--\n SPDX-FileCopyrightText: 2026 The Pion community <https://pion.ly>\n SPDX-License"
}
]
About this extraction
This page contains the full source code of the pion/rtsp-bench GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 29 files (50.7 KB), approximately 16.2k tokens, and a symbol index with 14 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.