| /* | |
| * Copyright (c) 2026 The WebRTC project authors. All Rights Reserved. | |
| * | |
| * Use of this source code is governed by a BSD-style license | |
| * that can be found in the LICENSE file in the root of the source | |
| * tree. An additional intellectual property rights grant can be found | |
| * in the file PATENTS. All contributing project authors may | |
| * be found in the AUTHORS file in the root of the source tree. | |
| */ | |
| #ifndef API_VIDEO_CODECS_VIDEO_RATE_CONTROLLER_H_ | |
| #define API_VIDEO_CODECS_VIDEO_RATE_CONTROLLER_H_ | |
| #include <cstdint> | |
| #include <memory> | |
| #include <optional> | |
| #include <variant> | |
| #include "absl/base/nullability.h" | |
| #include "api/units/data_rate.h" | |
| #include "api/units/data_size.h" | |
| #include "api/units/time_delta.h" | |
| #include "api/video/video_frame_buffer.h" | |
| #include "api/video_codecs/video_encoder_interface.h" | |
| namespace webrtc { | |
| // NOTE: This interface is for prototyping purposes only and may change without | |
| // prior notice. | |
| // | |
| // Picks the QP of each frame so that a single-spatial-layer stream encoded in | |
| // constant QP mode meets the bitrate it was given. For multi-spatial-layer | |
| // streams, use one `VideoRateController` instance per spatial layer. | |
| // | |
| // Lifecycle and concurrency: | |
| // - Implementations are NOT thread-safe. Callers must serialize all calls on a | |
| // given instance (e.g. from a single sequence/task queue or under an external | |
| // lock), even when the underlying encoder runs asynchronously. | |
| // - Multiple frames may be in flight concurrently (e.g. for pipelined hardware | |
| // encoders where `PlanFrame` for a later frame is called before | |
| // `OnFrameEncoded`/`OnFrameDropped` arrives for an earlier one). `PlanFrame` | |
| // calls must be issued in encode order with non-decreasing | |
| // `params.tu_settings.presentation_timestamp()`. | |
| // - Each `PlanFrame` call returns a `FramePlan` with a unique `PlanId` (`id`). | |
| // All subsequent `CheckEncodedFrame`, `ReplanFrame`, `OnFrameEncoded`, and | |
| // `OnFrameDropped` calls pass that `PlanId` to bind callbacks unambiguously | |
| // to the originating request. `ReplanFrame` preserves the same `PlanId`. | |
| // - Exactly one of `OnFrameEncoded` or `OnFrameDropped` must eventually be | |
| // called for every `PlanId` returned by `PlanFrame` (including `DropFrame` | |
| // plans), after which that `PlanId` is retired and must not be used again. | |
| class VideoRateController { | |
| public: | |
| using TemporalUnitSettings = VideoEncoderInterface::TemporalUnitSettings; | |
| using FrameEncodeSettings = VideoEncoderInterface::FrameEncodeSettings; | |
| using PlanId = int64_t; | |
| // Inputs to `PlanFrame`. Grouped in a struct so additional frame-level hints | |
| // (e.g. update area) can be added without changing the signature. | |
| struct FrameParams { | |
| // Non-cumulative target bitrate for `frame_settings.temporal_id()`, | |
| // following `FrameEncodeSettings::Cbr::target_bitrate`. Must be finite and | |
| // greater than zero. | |
| DataRate target_bitrate = DataRate::Zero(); | |
| // Nominal duration of the frame used to size its desired bit budget, | |
| // following `FrameEncodeSettings::Cbr::duration`. Must be finite and | |
| // greater than zero. | |
| TimeDelta duration = TimeDelta::Zero(); | |
| // Temporal unit metadata (e.g. `presentation_timestamp()` for draining | |
| // rate-control queues, and `content_hint()`). | |
| const TemporalUnitSettings& tu_settings; | |
| // Frame metadata (frame type, temporal id, resolution, reference structure, | |
| // etc.). `resolution()` must have positive width and height; | |
| // `rate_options()` and `frame_output()` are ignored. | |
| const FrameEncodeSettings& frame_settings; | |
| // Optional. Raw input frame buffer for controllers that inspect image | |
| // content (e.g. scene-change detection or block activity). Passing | |
| // `kNative` GPU-backed buffers may trigger per-frame | |
| // `ToI420ForInspection()` readbacks. | |
| VideoFrameBuffer* absl_nullable frame_buffer = nullptr; | |
| // Optional. Whether `PlanFrame` is allowed to return `DropFrame`. Set to | |
| // false for frames that must be encoded (e.g. keep-alive frames or tests). | |
| bool allow_drop = true; | |
| }; | |
| // Advises not to encode the frame (e.g. when the buffer/rate is | |
| // overshooting). Carries no QP and must always be retired via | |
| // `OnFrameDropped` (pass `allow_drop = false` when an encode is required). | |
| struct DropFrame {}; | |
| // Parameters for encoding the current frame in constant QP mode. | |
| struct EncodeFrame { | |
| // Frame-level QP to pass in `FrameEncodeSettings::Cqp::target_qp` (in the | |
| // codec's QP scale, e.g. [1, 255] for AV1). | |
| int qp = 0; | |
| // Nominal target bitstream size the controller planned `qp` to hit. | |
| // Informational; callers driving a CQP encoder do not need to enforce it. | |
| DataSize target_size = DataSize::Zero(); | |
| }; | |
| // Result of `PlanFrame` or `ReplanFrame`, binding a unique `PlanId` to either | |
| // a `DropFrame` recommendation or an `EncodeFrame` plan. | |
| struct FramePlan { | |
| // Unique identifier for this frame request, passed back to | |
| // `CheckEncodedFrame`, `ReplanFrame`, `OnFrameEncoded`, and | |
| // `OnFrameDropped`. Preserved across `ReplanFrame` retries. | |
| PlanId id = 0; | |
| std::variant<DropFrame, EncodeFrame> decision; | |
| }; | |
| // Result of an encode attempt reported back to the controller. | |
| struct EncodedFrameStats { | |
| // Actual bitstream size produced by the encoder. | |
| DataSize encoded_size = DataSize::Zero(); | |
| // Average QP reported by the encoder (`EncodedData::encoded_qp`), which may | |
| // deviate from `EncodeFrame::qp` (e.g. due to encoder rounding or the | |
| // caller clamping the planned QP to an application-enforced min/max QP | |
| // range to preserve a quality baseline, which can in turn cause overshoot | |
| // and subsequent frame drops). If unset, the controller assumes the last | |
| // planned `EncodeFrame::qp` was used. | |
| std::optional<int> qp; | |
| }; | |
| // What to do with an encode attempt of an in-flight frame, see | |
| // `CheckEncodedFrame`. | |
| enum class Verdict { | |
| kAccept, | |
| // Reject the attempt and call `ReplanFrame` for a retry plan. | |
| kReencode, | |
| // Discard the encode and report `OnFrameDropped`. | |
| kDrop, | |
| }; | |
| virtual ~VideoRateController() = default; | |
| // Starts planning the next frame of this spatial layer, draining queues by | |
| // the elapsed time up to `params.tu_settings.presentation_timestamp()`. | |
| [[nodiscard]] virtual FramePlan PlanFrame(const FrameParams& params) = 0; | |
| // Advises on an encode attempt for `id` before the caller commits to it. | |
| // Does not change the state. | |
| [[nodiscard]] virtual Verdict CheckEncodedFrame( | |
| PlanId id, | |
| const EncodedFrameStats& stats) const = 0; | |
| // Records a rejected encode attempt for `id` and returns an updated | |
| // `FramePlan` with the same `id` (either a retry `EncodeFrame` or `DropFrame` | |
| // if the controller advises giving up). May be called multiple times for the | |
| // same `id`. | |
| [[nodiscard]] virtual FramePlan ReplanFrame( | |
| PlanId id, | |
| const EncodedFrameStats& rejected_attempt) = 0; | |
| // Commits the accepted encode for `id` and retires `id`. | |
| virtual void OnFrameEncoded(PlanId id, const EncodedFrameStats& stats) = 0; | |
| // Commits that the frame for `id` was not encoded or its encode attempts were | |
| // discarded, and retires `id`. Pass `discarded_attempt` when discarding an | |
| // encode that was not already passed to `ReplanFrame` (e.g. after | |
| // `CheckEncodedFrame` returned `Verdict::kDrop`); pass `std::nullopt` for | |
| // pre-encode drops or after `ReplanFrame` already recorded the attempt. | |
| virtual void OnFrameDropped( | |
| PlanId id, | |
| std::optional<EncodedFrameStats> discarded_attempt) = 0; | |
| }; | |
| class VideoRateControllerFactory { | |
| public: | |
| virtual ~VideoRateControllerFactory() = default; | |
| [[nodiscard]] virtual absl_nonnull std::unique_ptr<VideoRateController> | |
| CreateRateController() const = 0; | |
| }; | |
| } // namespace webrtc | |
| #endif // API_VIDEO_CODECS_VIDEO_RATE_CONTROLLER_H_ |