Skip to content

feat(stream): add RTT-based adaptive bitrate (MACCA) - #6181

Open
cesarpmorais wants to merge 1 commit into
SunshineStream:masterfrom
cesarpmorais:feat/macca-adaptive-bitrate
Open

cesarpmorais wants to merge 1 commit into
SunshineStream:masterfrom
cesarpmorais:feat/macca-adaptive-bitrate

Conversation

@cesarpmorais

@cesarpmorais cesarpmorais commented Nov 23, 2026 •

Copy link
Copy Markdown

Description

This PR adds an opt-in adaptive bitrate mode, bitrate_mode = adaptive. The default stays fixed, so nothing changes unless a user turns it on.

The controller is MACCA (Multi-state AIMD with Cubic Convergence Adaptation), from our paper accepted at SBESC 2026. There we evaluated it against fixed bitrate and a baseline AIMD controller on a Sunshine/Moonlight testbed.

MACCA only uses the ENet round-trip time Sunshine already measures on the control stream. It works with any Moonlight client and adds nothing to the protocol. When the bandwidth to the client drops, packets queue up and the RTT rises; MACCA lowers the bitrate before that queue turns into stutter or a disconnect, and raises it again once the path is clear:

  • Decrease: if the RTT stays above abr_rtt_threshold_ms (100 ms) for abr_hysteresis_ms (2 s), the bitrate is multiplied by abr_beta (0.7). While congestion lasts, it decreases again after each further window, down to abr_min_kbps. Shorter spikes are ignored.
  • Recovery: once the RTT stays below the threshold minus abr_margin_ms (20 ms) for abr_stable_time_ms (1 s), the bitrate follows the CUBIC curve from the last decrease. It rises fast at first, levels off near the rate held before the cut after abr_cubic_recovery_ms (15 s), then probes above it.
  • Fast convergence: if a decrease comes before the previous recovery finished, the next recovery aims lower, closer to the bandwidth actually available (abr_fast_convergence, on by default).
  • Limits: at most one change per second, and never above what Moonlight requested, max_bitrate or abr_max_kbps.

The defaults are the parameters we evaluated. In our Linux testbed (VA-API, Celeste, six tc bandwidth-degradation scenarios), compared with the baseline AIMD controller, MACCA:

  • had the lowest peak RTT in 5 of 6 scenarios (up to −43%);
  • had the lowest total stall time in 5 of 6 scenarios (up to −61%);
  • traded this for a higher median RTT (12–23 ms instead of 4–5 ms), because it keeps probing for capacity.

Compared with fixed bitrate, both adaptive controllers cut stall time by 90–100%.

Usage

bitrate_mode = adaptive

That's all that is needed; it can also be set in the Web UI under Audio/Video → Bitrate Mode. The tuning options appear there when Adaptive is selected. All options are read when a stream starts:

Option Default Meaning
abr_rtt_threshold_ms 100 RTT above this is congestion. Raise it above the usual RTT on high-latency (e.g. internet) paths.
abr_margin_ms 20 The RTT must be this far below the threshold to count as clear; in between, the bitrate is held.
abr_hysteresis_ms 2000 How long congestion must last before each decrease.
abr_stable_time_ms 1000 How long the path must stay clear before each increase.
abr_beta 0.7 Factor applied on each decrease.
abr_cubic_recovery_ms 15000 Time to return to the rate held before the last decrease.
abr_fast_convergence enabled Aim lower after a decrease that interrupts a recovery.
abr_min_kbps 1000 Bitrate floor. With VideoToolbox, see the known issue below.
abr_max_kbps 0 Bitrate ceiling; 0 uses the bitrate requested by Moonlight, which is never exceeded.

With min_log_level = debug, each change is logged as Adaptive bitrate: target … kbps (RTT … ms). docs/configuration.md documents all options, and docs/troubleshooting.md covers the VideoToolbox issue.

Encoder support

  • FFmpeg-based encoders (VA-API, AMF, QuickSync, software): FFmpeg does not reliably apply a new bitrate on an open context, so the codec context is rebuilt at the new bitrate. The rebuild reuses the session's hardware frame pool and forces an IDR frame. This is the path we evaluated (VA-API).
  • VideoToolbox: the bitrate is changed in place through kVTCompressionPropertyKey_AverageBitRate, plus DataRateLimits when the session uses standard rate control.
  • Native NVENC: set_bitrate returns false, so the stream keeps a fixed bitrate. Runtime reconfiguration for NVENC is what feat(stream): add adaptive NVENC bitrate control #5460 implements.

Known issue: VideoToolbox drops frames at low bitrates (also with fixed bitrate)

While testing on macOS (Apple M5, macOS 26.6.2, HEVC 1080p60, high-motion video), we found that VideoToolbox's low-latency rate control drops frames when the bitrate is too low for the content. Sunshine treats a dropped frame as fatal and recreates the encoder, so every frame is sent as an IDR frame at about 30 fps, and the stream stutters. The log repeats VideoToolbox dropped a frame / Creating encoder [hevc_vt] on every frame.

This is not caused by this PR. With bitrate_mode = fixed and Moonlight set to 4 Mbps (2708 kbps negotiated), the same content produced 1296 dropped frames in 44 s, every frame an IDR, while the RTT stayed at 5–8 ms. Adaptive mode makes it more likely to hit, though: under congestion it can lower the bitrate into that range. In our run, the drops started when MACCA reached 4558 kbps and stopped once its recovery passed ~5150 kbps.

This PR documents it rather than working around it:

  • docs/troubleshooting.md has a new macOS entry ("Stream stutters at low bitrates with VideoToolbox"), and the docs and UI text for bitrate_mode and abr_min_kbps point to it;
  • the advice is to keep abr_min_kbps above that level on macOS, e.g. abr_min_kbps = 6000 for 1080p60.

A real fix belongs in the VideoToolbox encoder, separately from this PR: for example, falling back to standard rate control instead of recreating the session in a loop. I'm happy to open an issue for it.

Relation to #5460

#5460 adapts the bitrate from packet loss and FEC reports, for native NVENC on Windows. This PR uses RTT only and works across encoders. The two signals are complementary, and #5460's NVENC reconfiguration would also give this controller NVENC support.

Changes

  • src/bitrate_controller.{h,cpp}: the controller. It is policy only, with no I/O.
  • src/stream.cpp: make_bitrate_controller creates one controller per session when adaptive mode is on. The control thread publishes the peer's ENet RTT to an atomic, so the video thread never touches the ENet peer. The video thread feeds the controller one sample per sent frame and raises a bitrate_change mail event when the target changes.
  • src/video.{h,cpp}, src/platform/common.h, src/platform/macos/vt_encoder.mm:
    • encode_session_t::set_bitrate, and handling of the event in both encode loops.
    • The last bitrate the encoder accepted is kept across encoder reinitializations (display changes, recovery) and applied to the new encoder, so the encoder doesn't jump back to the negotiated bitrate while the controller holds a lower one.
    • On the avcodec path, the codec context creation moves out of make_avcodec_encode_session into build_avcodec_ctx, so it can be rebuilt at a new bitrate. To keep it within the quality gate's complexity limits, it is split into small helpers (select_avcodec_profile, set_avcodec_gop, make_avcodec_hw_device, attach_avcodec_hw_frames, make_avcodec_options, set_avcodec_rate_control, configure_avcodec_ctx), with the encoder inputs grouped in avcodec_ctx_inputs_t. The settings applied are unchanged. One side fix: the options dictionary is now freed after avcodec_open2; it leaked before.
  • src/config.{h,cpp}: the bitrate_mode and abr_* options, with range checks. An unknown bitrate_mode falls back to fixed with a warning.
  • Docs (configuration.md, troubleshooting.md), Web UI (Audio/Video → Bitrate Mode) and en.json.
  • tests/software_encode_test_utils.h: the CPU test display and BGRA frame used by test_legacy_codec_roundtrip.cpp, now shared with the new test_video_bitrate.cpp instead of being duplicated.

Screenshot

Issues Fixed or Closed

Roadmap Issues

Testing

Automated (macOS 26.6.2, Apple M5, BUILD_WERROR=ON; formatted with clang-format 23.1.0):

  • New tests/unit/test_bitrate_controller.cpp: hysteresis, ignored short spikes, cascaded decreases and the floor, fast convergence on and off, the cubic recovery values, probing up to the ceiling, the dead band between the thresholds, one decision per interval, ceilings, and no overflow long after a decrease.
  • New tests/unit/test_video_bitrate.cpp:
    • a real MPEG-2 software encode session changes bitrate mid-stream (clamped to max_bitrate), restarts with an IDR frame, and every frame still decodes;
    • pending changes are applied, and remembered only when accepted;
    • the last bitrate is restored on a new encoder.
  • tests/unit/platform/macos/test_vt_encoder.mm: a VideoToolbox H.264 session accepts runtime bitrate changes (skipped without a hardware encoder; it ran on the M5).
  • tests/unit/test_stream.cpp: the controller is only created in adaptive mode, starts at the negotiated bitrate or max_bitrate, and uses the configured parameters.
  • ConfigPersistenceTest.ParsesAdaptiveBitrateOptions covers parsing and the rejection of invalid values. test_config_consistency covers the new options in the docs, the UI defaults and en.json.
  • The software-encoder round-trip tests (MPEG-2, H.263+) exercise the refactored codec setup. Hardware FFmpeg encoders (VA-API, AMF, QuickSync) could not be run on this Mac.
  • Results: Web UI tests 219/219 pass. Full C++ suite: 853 pass. The only failures are suites that need screen-recording, microphone or input permissions the build shell did not have; none touch this change.

Manual, macOS → Moonlight Android on the local network (VideoToolbox HEVC 1080p60, Moonlight slider 25 Mbps → 18988 kbps negotiated, high-motion video). The bandwidth to the client was capped at 8 Mbit/s for 30 s with dummynet:

Phase Target (kbps) RTT
Before the cap 18988 5–8 ms
Cap reached 18988 382 ms
Decreases, ~2 s apart 13291 → 9303 → 6512 → 4558 → 3190 413 → 457 → 55 ms
Recovery, one step per second 3281 → … → 11129 6–23 ms

The controller behaved as designed: the RTT went from 457 ms back under 25 ms within 4 s of the last decrease. Peak RTT 470 ms, median 8 ms, no stalls. Below ~5 Mbps the VideoToolbox frame-drop issue described above appeared (it reproduces with fixed bitrate too).

Earlier evaluation: the same controller logic, before this port, was evaluated on Linux with VA-API and tc bandwidth caps (six scenarios, against fixed bitrate and a baseline AIMD). All 787 rate changes logged in those runs match the controller's rules.

Not tested: Windows, and FFmpeg hardware encoders other than VA-API on current master.

Type of Change

  • feat: New feature (non-breaking change which adds functionality)
  • fix: Bug fix (non-breaking change which fixes an issue)
  • docs: Documentation only changes
  • style: Changes that do not affect the meaning of the code (white-space, formatting, missing semicolons, etc.)
  • refactor: Code change that neither fixes a bug nor adds a feature
  • perf: Code change that improves performance
  • test: Adding missing tests or correcting existing tests
  • build: Changes that affect the build system or external dependencies
  • ci: Changes to CI configuration files and scripts
  • chore: Other changes that don't modify src or test files
  • revert: Reverts a previous commit
  • BREAKING CHANGE: Introduces a breaking change (can be combined with any type above)

Checklist

  • Code follows the style guidelines of this project
  • Code has been self-reviewed
  • Code has been commented, particularly in hard-to-understand areas
  • Code docstring/documentation-blocks for new or existing methods/components have been added or updated
  • Tests have been added or updated for new or modified functionality, including regression tests for bug fixes

AI Usage

See our AI usage policy.

  • AI tools were used while preparing this PR

Claude Code ported the controller from our research branch onto current master, wrote the unit tests and docs, checked the logged rate changes from our campaign against the controller's rules, and helped run and analyze the macOS tests.

This pull request was generated by Claude Code (Claude Opus 5.5), medium thinking level

🤖 Generated with Claude Code

@cesarpmorais

Copy link
Copy Markdown
Author

This pull request was generated by Claude Code (Claude Opus 5.5), medium thinking level

@cesarpmorais
cesarpmorais force-pushed the feat/macca-adaptive-bitrate branch from c694f1f to 7a185bf Compare November 23, 2026 15:32
Add an opt-in `bitrate_mode = adaptive` that adjusts the encoder bitrate
from the client's ENet round-trip time, with no client changes.

The controller cuts the bitrate by beta after sustained congestion and
recovers along a CUBIC curve, with fast convergence, at most one decision
per second. Its parameters are exposed as `abr_*` options, defaulting to
the values evaluated in the MACCA paper (SBESC 2026).

The control thread publishes the RTT through an atomic, and the last
bitrate the encoder accepted is restored after encoder reinitialization.
FFmpeg-based encoders rebuild the codec context at the new bitrate,
reusing the hardware frame pool; VideoToolbox changes it in place.
Native NVENC keeps a fixed bitrate for now.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@cesarpmorais
cesarpmorais force-pushed the feat/macca-adaptive-bitrate branch from 7a185bf to 8cbce28 Compare November 23, 2026 15:44
@sonarqubecloud

Copy link
Copy Markdown

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant