| /* | |
| * 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 MODULES_VIDEO_CODING_RATE_CONTROL_SCENE_ANALYZER_H_ | |
| #define MODULES_VIDEO_CODING_RATE_CONTROL_SCENE_ANALYZER_H_ | |
| #include <cstdint> | |
| #include <optional> | |
| #include <vector> | |
| #include "api/video/video_frame_buffer.h" | |
| namespace webrtc { | |
| // Cheap pre-encode luma analysis for rate control. | |
| // | |
| // The luma plane is downscaled by `Options::downscale_factor` in each | |
| // dimension and compared with the one of the previous frame. A 64x64 block of | |
| // the frame is a square of `64 / downscale_factor` in the downscaled plane; | |
| // block SADs are scaled back to full resolution, so the thresholds of libaom's | |
| // `av1_rc_scene_detection_onepass_rt`, which this mirrors, apply. | |
| class SceneAnalyzer { | |
| public: | |
| struct Options { | |
| // Must divide 64. | |
| int downscale_factor = 8; | |
| // Pick one pixel per `downscale_factor` square instead of averaging it, | |
| // which reads 1/`downscale_factor` of the rows. | |
| bool point_sample = false; | |
| }; | |
| struct Stats { | |
| // Mean absolute difference per pixel between this frame and the previous | |
| // one, before encoding. | |
| double mean_abs_diff = 0.0; | |
| double spatial_variance = 0.0; | |
| bool scene_change = false; | |
| }; | |
| SceneAnalyzer() : SceneAnalyzer(Options{}) {} | |
| explicit SceneAnalyzer(const Options& options); | |
| SceneAnalyzer(const SceneAnalyzer&) = delete; | |
| SceneAnalyzer& operator=(const SceneAnalyzer&) = delete; | |
| // Returns nullopt for the first frame, after a resolution change, or if the | |
| // luma plane cannot be read. | |
| [[nodiscard]] std::optional<Stats> Analyze(VideoFrameBuffer& frame, | |
| bool is_screen = false); | |
| void Reset(); | |
| private: | |
| const Options options_; | |
| // Side length (in downscaled pixels) of a full-resolution 64x64 block. | |
| const int block_size_px_; | |
| std::vector<uint8_t> previous_; | |
| // Reusable scratch buffer swapped into `previous_` to avoid per-frame | |
| // allocations once dimensions stabilize. | |
| std::vector<uint8_t> current_; | |
| int src_width_px_ = 0; | |
| int src_height_px_ = 0; | |
| int frames_since_reset_ = 0; | |
| // Exponentially smoothed frame SAD per 64x64 block (3:1 decay). | |
| double avg_source_sad_per_64x64_ = 0.0; | |
| }; | |
| } // namespace webrtc | |
| #endif // MODULES_VIDEO_CODING_RATE_CONTROL_SCENE_ANALYZER_H_ |