voelin-media: RTMP output for the Stream Studio through libavformat
The RTMP output was a seam that refused every rtmp:// URL. Broadcast services (Twitch, YouTube, nginx-rtmp) take RTMP, so the studio could only reach the few that speak WHIP. The connection is libavformat's own rtmp:// and rtmps:// protocols, loaded at runtime with the rest of FFmpeg and never linked. Its RTMP writer takes an FLV byte stream and sends each tag as a message, so the FLV is ours (onMetaData, AVC and AAC sequence headers, a tag per frame) and no muxer struct (AVFormatContext, AVStream, codec parameters, which all moved between releases) is used: five avio functions and AVIOInterruptCB. Write errors only land in AVIOContext.error, which moved too (120 bytes in libavformat 58, 84 in 63); it is found at load by flushing a context whose write callback fails with a sentinel. Video is the studio's H.264 of one layer as encoded; other codecs are refused with the reason. Audio is the studio's Opus decoded and encoded as AAC-LC by FFmpeg's own codecs on the output's thread. The encoder's sample format has no AVOption, so AVCodecContext.sample_fmt is located from its neighbours' option offsets like hw_frames_ctx; its 1024-sample frames are a reference to the first decoded frame (FFmpeg filled in the channel layout, whose field moved) with only the leading fields pointed at our planes. The stream key comes from the URL or the token (sent as the play path) and never shows in the output's name. The first connection is made when the output is added, so a wrong address fails there; later failures are reconnected with backoff (1 s doubling to 30 s), each new connection starting at a keyframe it asks for, and the stats show why it is down. EndStream unpublishes; a dead network is cut off after three seconds. Tested against FFmpeg's own RTMP server (ffmpeg -listen 1): a studio stream through the hardware H.264 encoder and a 440 Hz tone arrives as h264 320x180 and aac 48 kHz stereo per ffprobe, starts at a keyframe, decodes, and comes back after the server is replaced; the unit tests also pass against FFmpeg 4.4.8. voelinctl studio run gets --rtmp. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
b8a111df1f
commit
2a1279ee7b
17 files changed
+2038
-78
No files matched your search
+54
-2
@@ -30,6 +30,7 @@ video, recording, a replay buffer, WHIP) is described in
|
||||
| `EncoderReport { ffmpeg, zero_copy, encoders: Vec<EncoderInfo> }` | for the UI: FFmpeg's release and path (or why none), whether DMA-BUF import works, and per backend `name`, `api`, `codec`, `hardware`, `status` (self-test result or why it cannot be used) and `rank` under the current preference |
|
||||
| `EncoderBackend` | `Libvpx`, `OpenH264`, `Ffmpeg("h264_vaapi")`, `Hardware("mediacodec")`; `name()` is the settings spelling |
|
||||
| `ffmpeg::{Ffmpeg, probe, FfmpegEncoder, BACKENDS}` | FFmpeg loaded at runtime (feature `ffmpeg`), see [FFmpeg encoders](#ffmpeg-encoders-loaded-at-runtime) |
|
||||
| `ffmpeg::avio::Connection`, `ffmpeg::audio::AacEncoder` | bytes written through libavformat's protocols (`rtmp://`, `rtmps://`) with their write errors and an abort flag; the studio's Opus as AAC through FFmpeg's own codecs. See [RTMP output](#rtmp-output) |
|
||||
| `ffmpeg::{GpuConverter, GpuLayer}` | an RGB DMA-BUF converted to NV12 and scaled for every simulcast layer on the GPU (`convert(&DmaBufRef, &[GpuLayer], out)`), `modifiers()` it imports; see zero-copy under [FFmpeg encoders](#ffmpeg-encoders-loaded-at-runtime) |
|
||||
| `ScreenCapture` | `sources()`, `start_sink(&SourceId, &CaptureOptions, Box<dyn FrameSink>)` (frames borrowed from the capture buffer, on the backend's thread), `start(..)` (copies into a queue), `stop()`; async: the portal asks the user |
|
||||
| `FrameSink` | `max_fps()` (may change while capturing), `wants(timestamp)` (asked before anything is mapped or copied), `frame(FrameRef) -> bool`; `accepts_dmabuf()`, `dmabuf(&DmaBufRef) -> Option<bool>` (a frame still in GPU memory, offered before it is mapped) and `dmabuf_modifiers()` (tiled layouts the sink imports) |
|
||||
@@ -289,8 +290,8 @@ the software encoders above are used as before.
|
||||
`/usr/local/lib`) and MacPorts (`/opt/local/lib`) (macOS). No version is
|
||||
refused. libavutil's functions come from the libavutil libavcodec itself
|
||||
loaded (through its handle; on Windows the already loaded DLL), so the two
|
||||
always match; libavformat of the same major is opened if present (for RTMP
|
||||
output later). `VOELIN_FFMPEG=0` disables FFmpeg. Only functions are
|
||||
always match; libavformat of the same major is opened if present (for
|
||||
[RTMP output](#rtmp-output)). `VOELIN_FFMPEG=0` disables FFmpeg. Only functions are
|
||||
looked up by name (`sys.rs`); FFmpeg's warnings and errors go to
|
||||
`tracing` (target `ffmpeg`) and into the self-test's failure reasons.
|
||||
- ABI across major versions: every codec setting goes through AVOptions
|
||||
@@ -469,6 +470,56 @@ the software encoders above are used as before.
|
||||
(no compression metadata); the portal offers it ahead of LINEAR (see
|
||||
[Capture](#capture)). See [the measurements](#zero-copy-measured).
|
||||
|
||||
### RTMP output
|
||||
|
||||
The studio's RTMP output ([studio.md](studio.md#outputs-studiooutput))
|
||||
goes through the same runtime-loaded FFmpeg, libavformat included, and
|
||||
links nothing.
|
||||
|
||||
- Connection (`ffmpeg/avio.rs`): `avio_open2` with libavformat's own
|
||||
`rtmp://` / `rtmps://` protocols (handshake, `connect`, `publish`, TLS),
|
||||
`avio_write`, `avio_flush`, `avio_closep` (unpublish). Five functions and
|
||||
`AVIOInterruptCB` (two fields, unchanged since libavformat 53): every
|
||||
blocking call polls an abort flag, so a stop or a stuck network never
|
||||
holds a thread for longer than FFmpeg's 100 ms poll once it is set;
|
||||
`rw_timeout` (10 s) bounds a connect or a send to a server that stopped
|
||||
answering. Protocol options go in as an `AVDictionary` (`rtmp_app`,
|
||||
`rtmp_playpath` for a key given apart, `tcp_nodelay`).
|
||||
- What it sends is FLV (`studio/output/flv.rs`): libavformat's RTMP writer
|
||||
reads an FLV byte stream and sends each tag as an RTMP message, so the
|
||||
FLV is written by us like the recordings' Matroska and no muxer
|
||||
(`AVFormatContext`, `AVStream`, codec parameters, all of which moved
|
||||
between releases) is ever used.
|
||||
- Write errors: `avio_write` and `avio_flush` return nothing; a failed
|
||||
write is only stored in `AVIOContext.error`, which moved (120 bytes in
|
||||
libavformat 58, 84 in 63). It is found at load by search
|
||||
(`layout::avio_error`): a context of our own whose write callback fails
|
||||
with a sentinel value is flushed, and the one `int` of its first 200
|
||||
bytes that changed to the sentinel is the field. Checked against the
|
||||
`offsetof` of FFmpeg 4.4.8 and 9.0.1.
|
||||
- Audio (`ffmpeg/audio.rs`): RTMP services take AAC, so the studio's Opus
|
||||
is decoded by FFmpeg's `opus` decoder and encoded by its native `aac`
|
||||
encoder (AAC-LC, 48 kHz stereo, 160 kbit/s; `AudioSpecificConfig`
|
||||
`11 90`). An audio encoder needs its sample format before it opens, and
|
||||
`AVCodecContext.sample_fmt` has no AVOption: it is located like
|
||||
`hw_frames_ctx`, from the option offsets of its neighbours (after
|
||||
`sample_rate` directly from libavcodec 61 with `ch_layout` after it;
|
||||
after `channels` up to 60), and checked to be `NONE` in a new context.
|
||||
The encoder takes 1024-sample frames and Opus gives 960, so the samples
|
||||
are queued and cut into frames of our own; such a frame needs its
|
||||
channel layout, whose field also moved (`ch_layout` from libavutil 57,
|
||||
`channels` and `channel_layout` before), and `avcodec_send_frame` copies
|
||||
frames with `av_frame_ref`, which refuses one without a layout unless its
|
||||
buffers are reference-counted. So the encoder's input frame is a
|
||||
reference to the first frame the decoder made (FFmpeg filled in layout,
|
||||
rate, format and buffer references), with only its leading fields
|
||||
(`data`, `linesize`, `nb_samples`, unchanged since libavutil 51) and
|
||||
`pts` pointed at our planes; the decoded buffers it keeps are never read.
|
||||
The AAC frames carry the Opus packets' clock (less the encoder's 1024
|
||||
samples of priming), and a gap in the studio's audio restarts it.
|
||||
- Without libavformat, or when a check fails, `LibraryInfo::rtmp` says why
|
||||
and adding an RTMP output fails with that reason.
|
||||
|
||||
Installing FFmpeg (runtime libraries only, no `-dev` packages):
|
||||
|
||||
| OS | |
|
||||
@@ -917,6 +968,7 @@ has not run on Windows yet.
|
||||
| Portal / PipeWire error paths (no bus, bus without portal, no daemon) | unit tests, manual probe | tested |
|
||||
| Portal capture (shared memory and DMA-BUF), PipeWire video and audio streams | `voelinctl stream bench --source portal` on a 2560x1440 Wayland desktop | tested: it delivered no frames at all (the DMA-BUF mapping length), and the DMA-BUF path cost 19.5 cores where shared memory costs 0.41. Both fixed; 1440p60 now runs on 0.55 cores (see the table above). Portal audio is still untested |
|
||||
| Windows Graphics Capture, WASAPI | – | type-checked for `x86_64-pc-windows-gnu` only |
|
||||
| RTMP through libavformat: write errors from `AVIOContext.error`, an abort ending a stuck connect, `AVCodecContext.sample_fmt`, Opus → AAC, FLV tags, a studio stream to FFmpeg's own RTMP server read back by ffprobe, a reconnect | `ffmpeg::avio`, `ffmpeg::audio`, `ffmpeg::tests`, `studio::output::{flv, rtmp}` tests, `voelin-core/tests/studio.rs` (see [studio.md](studio.md#status)) | tested with FFmpeg 9.0.1 and 4.4.8 (`VOELIN_FFMPEG_DIR`); no public service tried. FFmpeg 4.4.8 also showed that the existing `hw_frames_ctx` check refuses its layout there (VA-API off, as designed for a failed check) |
|
||||
| FFmpeg loader: sonames, missing FFmpeg, layout checks on a real release | `ffmpeg::sys` / `ffmpeg` unit tests; mirrors compared with offsets compiled from the 4.4-9.0 headers | tested (FFmpeg 6.1.1 on Ubuntu 24.04; FFmpeg 9.0.1 / libavutil 61 / libavcodec 63 on Arch, every offset compared with that release's own headers) |
|
||||
| FFmpeg software encoders → our decoders: x264 → OpenH264, SVT-AV1 / rav1e / libaom → dav1d (PSNR > 28 dB, keyframes at start and on request, timestamps, bitrate change, size change, odd sizes, Constrained High / Baseline) | `tests/ffmpeg.rs` (`VOELIN_OPENH264_LIB`, `--features av1`) | tested |
|
||||
| Self-test failures (NVENC without CUDA, Quick Sync without a session, VA-API without a render node, encoders not in the build) | `tests/ffmpeg.rs`, `voelinctl stream encoders` | tested: each fails alone with FFmpeg's reason |
|
||||
|
||||
+36
-8
@@ -3,7 +3,8 @@
|
||||
The Stream Studio composites scenes of sources (screens, windows, cameras,
|
||||
images, text, colours) into one picture that becomes the video of our stream,
|
||||
and keeps or forwards what the stream's encoders make: a recording, a replay
|
||||
buffer to save clips from after the fact, and WHIP to a broadcast service. It
|
||||
buffer to save clips from after the fact, and WHIP or RTMP to a broadcast
|
||||
service. It
|
||||
is the engine behind the Studio screen of the UI (scenes and sources, a live
|
||||
preview, LIVE / timer, the audio mixer, Record Clip, Go Live / End Stream,
|
||||
Share Window / Share Screen, a camera with background blur); this page is
|
||||
@@ -21,7 +22,7 @@ sources (a thread each) ─ Feed (latest wins) ┐
|
||||
Streamer::start_studio: convert → layers → encoders ─────┼─ MediaSink (the live stream, when attached)
|
||||
audio sources → mixer → Opus ────┘
|
||||
│ every packet of the stream codec, attached or not
|
||||
└─ Studio::write_packet ─ replay buffer, recording, WHIP outputs
|
||||
└─ Studio::write_packet ─ replay buffer, recording, WHIP and RTMP outputs
|
||||
```
|
||||
|
||||
Everything is changeable while it runs, and nothing is capped: any number of
|
||||
@@ -165,9 +166,31 @@ fails is removed and reported, and the rest go on.
|
||||
that reaches the service: no STUN or TURN yet. It asks for a keyframe when
|
||||
it starts, when ICE comes up, when the service sends a PLI and after its
|
||||
queue overflowed.
|
||||
- **RTMP** (`rtmp::Rtmp`): the seam only. It is meant to go through the
|
||||
FFmpeg libraries loaded at runtime (libavformat's muxer side is not in the
|
||||
loader yet); until then adding an `rtmp://` output fails with that reason.
|
||||
- **RTMP and RTMPS** (`rtmp::Rtmp`, feature `ffmpeg`): through libavformat
|
||||
loaded at runtime, never linked ([media.md](media.md#rtmp-output)). Its
|
||||
`rtmp://` and `rtmps://` protocols do the handshake, `connect`, `publish`
|
||||
and TLS and take an FLV byte stream; the FLV is ours (`flv`: `onMetaData`,
|
||||
AVC and AAC sequence headers, then one tag per frame), as the recordings'
|
||||
Matroska is, so no libavformat struct is touched. Video is the studio's
|
||||
H.264 of the output's layer as encoded; another stream codec is refused
|
||||
with the reason (classic RTMP carries H.264; Enhanced RTMP's HEVC, AV1,
|
||||
VP9 and Opus are not written). Audio is the studio's Opus decoded and
|
||||
encoded as AAC-LC (160 kbit/s, 48 kHz stereo) by FFmpeg's own `opus`
|
||||
decoder and `aac` encoder, on the output's thread. The stream key is the
|
||||
last part of the URL's path (`rtmp://host/app/key`) or the output's token
|
||||
(sent as the play path, the URL's path as the application); the output's
|
||||
name never shows it. The first connection is made when the output is
|
||||
added, so a wrong address or key fails there; a connection that fails
|
||||
later (the service restarting, the network) is made again after 1, 2, 4,
|
||||
... up to 30 seconds for as long as the output exists, each new one
|
||||
starting at a keyframe it asks for, while the stats show why it is down.
|
||||
A thread of its own runs the connection behind a bounded queue (about two
|
||||
seconds): a slow upload drops packets rather than holding up an encoder,
|
||||
and video resumes at the next keyframe. Audio goes out in time order with
|
||||
the video (it waits for the video of its time, at most a second), and the
|
||||
audio of the first keyframe's moment, which comes before the keyframe,
|
||||
is kept as a recording keeps it. `EndStream` unpublishes and closes; a
|
||||
network that does not answer is cut off after three seconds.
|
||||
|
||||
Recording and the replay buffer need no live stream: a studio's streamer
|
||||
encodes from the start (see below).
|
||||
@@ -191,8 +214,8 @@ channel; late subscribers miss what came before).
|
||||
| `SetPreview { width, height, fps }` | the preview tap's size and rate (default 480x270 at 15 fps) |
|
||||
| `StartRecording { path }` / `StopRecording` | `.webm` or `.mkv` |
|
||||
| `SetReplay { seconds, memory_mb }` / `SaveClip { path }` | the replay buffer (0 seconds: off) |
|
||||
| `AddOutput(OutputSpec::Record { path } \| Url { url, token })` / `RemoveOutput { id }` | more recordings, WHIP (`http(s)://`), RTMP (refused for now) |
|
||||
| `GoLive` / `EndStream` | the studio's state for the header (LIVE, timer); `EndStream` also closes the outputs that push (WHIP push from when they are added). The TeamSpeak stream itself is started and attached as usual |
|
||||
| `AddOutput(OutputSpec::Record { path } \| Url { url, token })` / `RemoveOutput { id }` | more recordings, WHIP (`http(s)://`, `token`: the bearer token), RTMP (`rtmp(s)://`, `token`: the stream key unless the URL ends with it) |
|
||||
| `GoLive` / `EndStream` | the studio's state for the header (LIVE, timer); `EndStream` also closes the outputs that push (WHIP and RTMP push from when they are added). The TeamSpeak stream itself is started and attached as usual |
|
||||
|
||||
| Event | |
|
||||
|---|---|
|
||||
@@ -251,6 +274,9 @@ voelinctl studio run scenes.json --seconds 10 --switch-to 2 \
|
||||
--preview preview.png --record rec.webm --clip clip.mkv --replay 30 --tone 440 --codec vp8
|
||||
# Push to a WHIP endpoint (token also from VOELIN_WHIP_TOKEN).
|
||||
voelinctl studio run scenes.json --seconds 60 --whip https://ingest.example/whip --token ...
|
||||
# Push over RTMP(S) (H.264; the key in the URL or in --token).
|
||||
voelinctl studio run scenes.json --seconds 60 --codec h264 --tone 440 \
|
||||
--rtmp rtmps://live.example/app --token <stream key>
|
||||
# The compositor alone: compose time and heap allocations per frame.
|
||||
voelinctl studio bench --sources 4 --res 1920x1080 --fps 60
|
||||
voelinctl studio cameras
|
||||
@@ -292,4 +318,6 @@ two threads) takes about 3 ms at its own rate (15 fps by default).
|
||||
| Screen, window and portal sources | the existing capture backends ([media.md](media.md#capture)) | as tested there; not run inside the studio here |
|
||||
| Background blur, image and colour backdrops on the oval mask | `segment::tests` | tested; **no person segmentation model** (see above) |
|
||||
| Windows and Android cameras | – | not implemented: `camera::list()` has only the test pattern there |
|
||||
| RTMP | – | the seam only (refuses with its reason) |
|
||||
| RTMP: the FLV tags (sizes, times past 24 bits, AVC from Annex B, `onMetaData` in AMF0), URL and key handling (the name hides the key), codecs other than H.264 and dead servers refused | `flv::tests`, `rtmp::tests` | tested |
|
||||
| RTMP: write errors seen (`AVIOContext.error`, found at load), an abort ends a stuck connect, the sample format field of the AAC encoder, Opus → AAC (frames back to back from the packets' clock, priming, a gap restarts the clock) | `ffmpeg::avio::tests`, `ffmpeg::audio::tests`, `ffmpeg::tests` | tested with FFmpeg 9.0.1 (libavformat 63: `error` at 84, `sample_fmt` at 348) and FFmpeg 4.4.8 (58: 120 and 408) |
|
||||
| RTMP end to end: a studio stream (H.264 through the hardware encoder, a 440 Hz tone) pushed to FFmpeg's own RTMP server (`ffmpeg -listen 1`) with the key apart from the URL; the server killed and another started on its port; `EndStream` | `voelin-core/tests/studio.rs` `a_studio_stream_goes_out_over_rtmp_and_comes_back_after_the_server_did` | tested: ffprobe reads `h264` 320x180 and `aac` 48000 Hz stereo in both servers' files, each starting at a keyframe, every picture decodes (red), the audio decodes to 440 Hz; the key arrived as the stream name; the second server finished its file and exited by itself. No public service (Twitch, YouTube) tried; RTMPS only through FFmpeg's TLS, untried here |
|
||||
Reference in new issue
Block a user