RTMPKit
Published on · Updated · 28 min
When you start a live stream on Twitch, YouTube or Facebook, your broadcasting software sends the audio and video feed to a server using a protocol created by Macromedia in 2002, which became the de facto standard for live streaming: RTMP. Real-Time Messaging Protocol.
The concept: a client connects to the server, performs a three-step handshake (C0/C1/C2), negotiates parameters via AMF0 commands, then sends audio and video data encapsulated in FLV tags, all multiplexed over chunk streams. Behind this apparent simplicity lie real subtleties — chunk size management, relative and absolute timestamps, sequence headers for each codec, and since 2023 Enhanced RTMP v2 which adds FourCC negotiation for modern codecs (HEVC, AV1, VP9, Opus).
While building the Atelier Socle streaming ecosystem — HLSKit for HTTP Live Streaming, IcecastKit for Icecast/SHOUTcast — the RTMP piece was missing. Not an FFmpeg binding, not a bridged C library — a proper native Swift publish client, with Swift 6.2 structured concurrency, presets for major platforms, and a SwiftNIO-based transport.
I looked. Nothing existed in pure Swift with Enhanced RTMP v2 support. RTMPKit was born from that need.
With version 0.2.0 — RTMP Broadcast Platform — RTMPKit goes beyond a simple publish client. The library becomes a full broadcast platform: 10 platform presets (Twitch, YouTube, Facebook, Kick, Instagram, TikTok, Rumble, LinkedIn, Trovo, Twitter/Periscope), a programmatic platform registry, adaptive bitrate with congestion detection, simultaneous multi-destination publishing, RTMP authentication (simple, token, Adobe challenge/response), FLV codec auto-detection, stream recording in FLV, bandwidth probing with quality recommendations, connection scoring with trend analysis, dynamic metadata (text, cue points, captions), full AMF3 support, Prometheus and StatsD export — and most importantly a full RTMP ingest server capable of accepting incoming connections with stream key validation, multi-destination relay, DVR, IP security and rate limiting. 2205 tests, 94.01% coverage.
0.3.0 hardens the infrastructure and improves server compatibility. Three manual codec configuration record builders are added — buildAVCDecoderConfigurationRecord (SPS+PPS → ISO 14496-15 §5.3.3.1), buildHEVCDecoderConfigurationRecord (VPS+SPS+PPS → ISO 14496-15 §8.3.3.1) and buildAACAudioSpecificConfig (ISO 14496-3 §1.6.2.1) — for cases where you build FLV tags manually. Audio/video interleaving by timestamp (AVInterleaver) ensures correct RTMP message send order, preventing A/V desync on the receiver side. The Enhanced RTMP v2 byte0 layout is fixed ([isExHeader:1][FrameType:3][PacketType:4]), the HEVC SPS offset correctly skips the 2-byte NALU header, and onBWDone/onBWCheck commands are ignored for SRS and Wowza compatibility. On the performance side, TCP_NODELAY is enabled by default, TCP buffers are configurable, and chunk compression (fmt1/fmt2 per Adobe RTMP §5.3.1) reduces overhead on multi-chunk messages. Quality monitoring and ABR logic are moved off the critical send path. 2243 tests, interop validated with MediaMTX and SRS v6.
What RTMPKit does
RTMPKit is both an RTMP publish client and an ingest server in pure Swift. On the publishing side, it handles the entire lifecycle of a live stream — connection, handshake, codec negotiation, sending audio and video frames as FLV, real-time statistics, auto-reconnection. On the server side, it accepts incoming connections, validates stream keys, relays to multiple destinations, and records in DVR. All with strict Sendable conformance end to end.
Full RTMP 1.0 — Handshake (C0/C1/C2), chunk stream multiplexing, AMF0 commands, FLV packaging
Enhanced RTMP v2 — FourCC negotiation for HEVC, AV1, VP9, Opus, FLAC, AC-3 and E-AC-3 with auto-detection from FLV files
FLV packaging — Audio tags (AAC sequence headers, raw frames), video tags (AVC NALUs, keyframes), script data
10 platform presets — One-line configuration for Twitch, YouTube, Facebook, Kick, Instagram, TikTok, Rumble, LinkedIn, Trovo and Twitter/Periscope
Platform registry — Programmatic discovery with case-insensitive lookup, TLS-required filtering, and dynamic configuration
Adaptive bitrate — Conservative, responsive and aggressive ABR policies with EWMA bandwidth estimation, RTT tracking, congestion detection and frame dropping
Multi-destination publishing — Simultaneous streaming to N servers with per-destination state, fault isolation, hot add/remove, and configurable failure policies
RTMP authentication — Simple (query string), token with expiration, and Adobe MD5 challenge/response (Wowza)
FLV codec auto-detection — HEVC, AV1, VP9 and Opus automatically detected from FLV files; Enhanced RTMP v2 enabled transparently
Stream recording — Live stream recording to FLV with segmentation, pause/resume and size limits
Bandwidth probing — Bandwidth measurement, RTT jitter, packet loss, and quality preset recommendations across 6 tiers
Connection quality scoring — Composite grades (excellent/good/fair/poor/critical) with 5 weighted dimensions and trend analysis
Dynamic metadata —
@setDataFrame/onMetaDataduring streaming, timed text, cue points with rich parameters, and multi-standard captionsAMF3 support — Full AMF3 encoding and decoding for all 18 type markers with 3 reference tables (string/object/traits)
Prometheus and StatsD metrics — Publisher and server metrics export to monitoring systems with periodic or on-demand snapshots
RTMP ingest server — Accepts incoming RTMP connections with stream key validation (allow-list, closure), relay to multiple destinations, and DVR recording
Server security — IP blocklist/allowlist, temporary bans, per-IP rate limiting, and configurable security policies (open/standard/strict)
Auto-reconnection — Exponential backoff with configurable jitter, retry limits, and four presets (
.default,.aggressive,.conservative,.none)Real-time monitoring —
AsyncStreamevent bus, ConnectionMonitor with sliding-window bitrate, dropped frame tracking, and RTT measurementTransport dependency injection — Replace the NIO transport with a mock for testing without a real RTMP server
Cross-platform — macOS 14+, iOS 17+, tvOS 17+, watchOS 10+, visionOS 1+, and Linux (Swift 6.2+)
CLI tool —
rtmp-clifor publishing, recording, probing, server management, and diagnosticsSwift 6.2 strict concurrency — Actors for stateful types,
Sendableeverywhere,async/awaitthroughout, zero@unchecked Sendableornonisolated(unsafe)Zero core dependencies — The
RTMPKittarget depends only on SwiftNIO for the transport layer. No other third-party dependencies
Quick start
Connect to Twitch, send audio/video data, and disconnect gracefully:
Installation
Via Swift Package Manager, by adding the dependency to your Package.swift:
Then add it to your target:
Platform support
| Platform | Minimum version |
|---|---|
macOS | 14+ |
iOS | 17+ |
tvOS | 17+ |
watchOS | 10+ |
visionOS | 1+ |
Linux | Swift 6.2 (Ubuntu 22.04+) |
Implemented standards
| Standard | Reference |
|---|---|
RTMP 1.0 | |
Enhanced RTMP v2 | |
AMF0 | |
AMF3 | |
FLV File Format |
Platform presets
RTMPKit provides presets for 10 streaming platforms. Each preset automatically configures the ingest URL, TLS, chunk size and Enhanced RTMP support — a single line is all you need to start broadcasting:
Platform registry
The StreamingPlatformRegistry enables programmatic discovery and configuration for all 10 platforms. Case-insensitive lookup, TLS filtering, and full iteration:
Custom configuration
For any RTMP server, with full control over chunk size, Enhanced RTMP, reconnect policy, and transport configuration:
Enhanced RTMP v2
Enhanced RTMP is enabled by default. After connecting, you can check which codecs were negotiated with the server:
Build enhanced video and audio tags for modern codecs:
FLV codec auto-detection
FLVCodecProbe inspects an FLV file and identifies the video and audio codecs used. If the file contains HEVC, AV1, VP9 or Opus, Enhanced RTMP v2 is enabled transparently without any manual intervention:
Multi-destination publishing
The MultiPublisher broadcasts simultaneously to N platforms with independent per-destination state. Each connection is isolated — if Twitch goes down, YouTube and Facebook keep running. You can add or remove destinations while streaming, and configure failure policies (for example: stop everything if 2 destinations fail):
Adaptive bitrate
RTMPKit monitors network conditions and continuously adjusts bitrate recommendations. Three ABR policies are available, each with different thresholds and reaction speeds. Frame dropping is handled intelligently — B-frames are sacrificed first, then P-frames, I-frames are never dropped:
RTMP authentication
RTMPKit handles three authentication mechanisms. Simple authentication appends credentials to the URL. Token authentication supports expiration with a typed error if the token is expired. Adobe authentication (used by Wowza) implements the MD5 challenge/response in two rounds automatically:
Stream recording
The StreamRecorder writes the live stream to FLV on disk. Segmentation can be by duration or total size. The recorder supports pause and resume, and can be driven directly from the publisher:
Bandwidth probing
The BandwidthProbe measures connection quality before starting a stream. It evaluates bandwidth, RTT jitter, signal quality, and produces a human-readable summary. The QualityPresetSelector converts these measurements into a platform-appropriate quality preset, across a 6-tier scale (360p30 to 1080p60):
Connection quality scoring
The ConnectionQualityMonitor continuously computes a composite quality score based on 5 weighted dimensions. Scores are emitted via an AsyncStream and each report includes a trend analysis (improving, stable, degrading):
Dynamic metadata
RTMPKit handles real-time stream metadata via @setDataFrame/onMetaData. Beyond standard metadata (resolution, bitrate, framerate), the library supports timed text, cue points with rich parameters (duration, sponsor...), and captions. Custom fields survive the AMF0 roundtrip:
Prometheus and StatsD metrics
RTMPKit exports streaming metrics in Prometheus (text/OpenMetrics) and StatsD (UDP datagrams) formats. Export can be periodic or on-demand via snapshot. Labels (platform, environment) are configurable:
RTMP ingest server
RTMPKit includes a full RTMP ingest server capable of accepting incoming connections from any RTMP-compatible software (OBS, FFmpeg, Wirecast...). The server validates stream keys (by allow-list or dynamic closure), can relay the stream to multiple destinations simultaneously, and records in DVR. A comprehensive security system handles IP blocklists, temporary bans, rate limiting, and offers three preconfigured policies (open, standard, strict):
The relay forwards a received stream to multiple RTMP destinations simultaneously — turning the ingest server into a redistribution hub:
DVR records incoming streams to disk. Auto-DVR mode automatically records all received streams without per-stream configuration:
Server security relies on IP blocklists/allowlists, temporary bans, and per-IP rate limiting. Three preconfigured policies cover the most common use cases:
Real-time monitoring
The AsyncStream event bus covers all publisher events — state changes, server messages, statistics, ABR recommendations, quality alerts, recording events and errors:
Connection statistics
Access real-time statistics at any point — bytes sent, total frames, current bitrate, uptime, and drop rate:
Auto-reconnection
Four reconnection presets are available, plus fully custom policies with jitter:
Transport dependency injection
The network transport is injectable — you can replace the real NIO transport with a mock to test your publish logic without network access:
Codec Configuration Builders (0.3.0)
0.3.0 adds three static methods for manually building codec configuration records — useful when feeding RTMPKit from an external capture pipeline (e.g. swift-capture-kit) instead of using the high-level helpers.
Interleaving & Performance (0.3.0)
The AVInterleaver reorders audio and video messages by timestamp before sending over the network. A small buffer (8 entries by default) accumulates messages from both types and flushes once both streams have advanced past the earliest timestamp. Result: packets arrive in correct temporal order on the receiver side, even if the encoder produces audio and video with a few-frame offset.
On the transport side, TCP_NODELAY is enabled by default (configurable via RTMPConfiguration.tcpNoDelay) to reduce send latency. TCP buffer sizes (receive and send) are configurable. RTMP chunk compression (fmt1/fmt2 per Adobe RTMP Spec §5.3.1) reduces header overhead on multi-chunk messages — only fields that change between consecutive chunks are sent. Non-monotonic timestamps are handled with a fmt0 fallback for B-frame sequences.
Quality monitoring and ABR logic are moved off the critical send path (fire-and-forget), reducing latency impact on frame sending.
Architecture

The library is organized into 20 modules, from the low-level handshake to the full ingest server:
CLI tool
rtmp-cli covers all command-line use cases: publishing with presets or multi-destination, FLV recording, bandwidth probing, local ingest server management, connection testing and diagnostics.
| Command | Description |
|---|---|
publish | Stream an FLV file to one or more RTMP servers |
test-connection | Test connectivity, handshake, and measure latency |
info | Query server information, capabilities, and Enhanced RTMP support |
probe | Measure bandwidth and connection quality |
record | Publish an FLV file and record the stream to disk |
server | Start a local RTMP ingest server |
Ecosystem
RTMPKit is part of the Atelier Socle streaming ecosystem:
PodcastFeedMaker — Podcast RSS feed generation
HLSKit — HTTP Live Streaming
IcecastKit — Icecast/SHOUTcast streaming
RTMPKit (this library) — RTMP streaming
SRTKit — SRT streaming
CaptureKit — Unified media capture
Links
GitHub - atelier-socle/swift-rtmp-kit: Pure Swift RTMP broadcast platform — publish, ingest, adaptive bitrate, multi-destination, recording, AMF3, Enhanced RTMP (HEVC/AV1). Zero dependencies. macOS · iOS · Linux
Pure Swift RTMP broadcast platform — publish, ingest, adaptive bitrate, multi-destination, recording, AMF3, Enhanced RTMP (HEVC/AV1). Zero dependencie…