| 6 | * tree. An additional intellectual property rights grant can be found |
| 7 | * in the file PATENTS. All contributing project authors may |
| 8 | * be found in the AUTHORS file in the root of the source tree. |
| 9 | */ |
| 10 |
| 11 | #include "video/frame_cadence_adapter.h" |
| 12 |
| 13 | #include <algorithm> |
| 14 | #include <atomic> |
| 15 | #include <deque> |
| 16 | #include <memory> |
| 17 | #include <utility> |
| 18 | #include <vector> |
| 19 |
| 20 | #include "absl/algorithm/container.h" |
| 21 | #include "absl/base/attributes.h" |
| 22 | #include "absl/cleanup/cleanup.h" |
| 23 | #include "api/sequence_checker.h" |
| 24 | #include "api/task_queue/pending_task_safety_flag.h" |
| 25 | #include "api/task_queue/task_queue_base.h" |
| 26 | #include "api/units/time_delta.h" |
| 27 | #include "api/units/timestamp.h" |
| 28 | #include "api/video/video_frame.h" |
| 29 | #include "rtc_base/checks.h" |
| 30 | #include "rtc_base/logging.h" |
| 31 | #include "rtc_base/race_checker.h" |
| 32 | #include "rtc_base/rate_statistics.h" |
| 33 | #include "rtc_base/synchronization/mutex.h" |
| 34 | #include "rtc_base/system/no_unique_address.h" |
| 35 | #include "rtc_base/system/unused.h" |
| 36 | #include "rtc_base/task_utils/repeating_task.h" |
| 37 | #include "rtc_base/thread_annotations.h" |
| 38 | #include "rtc_base/time_utils.h" |
| 39 | #include "rtc_base/trace_event.h" |
| 40 | #include "system_wrappers/include/clock.h" |
| 41 | #include "system_wrappers/include/metrics.h" |
| 42 | #include "system_wrappers/include/ntp_time.h" |
| 43 |
| 44 | namespace webrtc { |
| 45 | namespace { |
| 46 |
| 47 | // Abstracts concrete modes of the cadence adapter. |
| 48 | class AdapterMode { |
| 49 | public: |
| 50 | virtual ~AdapterMode() = default; |
| 51 |
| 52 | // Called on the worker thread for every frame that enters. |
| 53 | virtual void OnFrame(Timestamp post_time, |
| 54 | bool queue_overload, |
| 55 | const VideoFrame& frame) = 0; |
| 56 |
| 57 | // Returns the currently estimated input framerate. |
| 58 | virtual absl::optional<uint32_t> GetInputFrameRateFps() = 0; |
| 59 |
| 60 | // Updates the frame rate. |
| 61 | virtual void UpdateFrameRate() = 0; |
| 62 | }; |
| 63 |
| 64 | // Implements a pass-through adapter. Single-threaded. |
| 65 | class PassthroughAdapterMode : public AdapterMode { |
| 66 | public: |
| 67 | PassthroughAdapterMode(Clock* clock, |
| 68 | FrameCadenceAdapterInterface::Callback* callback) |
| 69 | : clock_(clock), callback_(callback) { |
| 70 | sequence_checker_.Detach(); |
| 71 | } |
| 72 |
| 73 | // Adapter overrides. |
| 74 | void OnFrame(Timestamp post_time, |
| 75 | bool queue_overload, |
| 76 | const VideoFrame& frame) override { |
| 77 | RTC_DCHECK_RUN_ON(&sequence_checker_); |
| 78 | callback_->OnFrame(post_time, queue_overload, frame); |
| 79 | } |
| 80 |
| 81 | absl::optional<uint32_t> GetInputFrameRateFps() override { |
| 82 | RTC_DCHECK_RUN_ON(&sequence_checker_); |
| 83 | return input_framerate_.Rate(clock_->TimeInMilliseconds()); |
| 84 | } |
| 85 |
| 86 | void UpdateFrameRate() override { |
| 87 | RTC_DCHECK_RUN_ON(&sequence_checker_); |
| 88 | input_framerate_.Update(1, clock_->TimeInMilliseconds()); |
| 89 | } |
| 90 |
| 91 | private: |
| 92 | Clock* const clock_; |
| 93 | FrameCadenceAdapterInterface::Callback* const callback_; |
| 94 | RTC_NO_UNIQUE_ADDRESS SequenceChecker sequence_checker_; |
| 95 | // Input frame rate statistics for use when not in zero-hertz mode. |
| 96 | RateStatistics input_framerate_ RTC_GUARDED_BY(sequence_checker_){ |
| 97 | FrameCadenceAdapterInterface::kFrameRateAveragingWindowSizeMs, 1000}; |
| 98 | }; |
| 99 |
| 100 | // Implements a frame cadence adapter supporting zero-hertz input. |
| 101 | class ZeroHertzAdapterMode : public AdapterMode { |
| 102 | public: |
| 103 | ZeroHertzAdapterMode(TaskQueueBase* queue, |
| 104 | Clock* clock, |
| 105 | FrameCadenceAdapterInterface::Callback* callback, |
| 106 | double max_fps, |
| 107 | std::atomic<int>& frames_scheduled_for_processing, |
| 108 | bool zero_hertz_queue_overload); |
| 109 | ~ZeroHertzAdapterMode() { refresh_frame_requester_.Stop(); } |
| 110 |
| 111 | // Reconfigures according to parameters. |
| 112 | // All spatial layer trackers are initialized as unconverged by this method. |
| 113 | void ReconfigureParameters( |
| 114 | const FrameCadenceAdapterInterface::ZeroHertzModeParams& params); |
| 115 |
| 116 | // Updates spatial layer quality convergence status. |
| 117 | void UpdateLayerQualityConvergence(size_t spatial_index, |
| 118 | bool quality_converged); |
| 119 |
| 120 | // Updates spatial layer enabled status. |
| 121 | void UpdateLayerStatus(size_t spatial_index, bool enabled); |
| 122 |
| 123 | // Adapter overrides. |
| 124 | void OnFrame(Timestamp post_time, |
| 125 | bool queue_overload, |
| 126 | const VideoFrame& frame) override; |
| 127 | absl::optional<uint32_t> GetInputFrameRateFps() override; |
| 128 | void UpdateFrameRate() override {} |
| 129 |
| 130 | // Notified on dropped frames. |
| 131 | void OnDiscardedFrame(); |
| 132 |
| 133 | // Conditionally requests a refresh frame via |
| 134 | // Callback::RequestRefreshFrame. |
| 135 | void ProcessKeyFrameRequest(); |
| 136 |
| 137 | // Updates the restrictions of max frame rate for the video source. |
| 138 | // Always called during construction using latest `restricted_frame_delay_`. |
| 139 | void UpdateVideoSourceRestrictions(absl::optional<double> max_frame_rate); |
| 140 |
| 141 | private: |
| 142 | // The tracking state of each spatial layer. Used for determining when to |
| 143 | // stop repeating frames. |
| 144 | struct SpatialLayerTracker { |
| 145 | // If unset, the layer is disabled. Otherwise carries the quality |
| 146 | // convergence status of the layer. |
| 147 | absl::optional<bool> quality_converged; |
| 148 | }; |
| 149 | // The state of a scheduled repeat. |
| 150 | struct ScheduledRepeat { |
| 151 | ScheduledRepeat(Timestamp origin, |
| 152 | int64_t origin_timestamp_us, |
| 153 | int64_t origin_ntp_time_ms) |
| 154 | : scheduled(origin), |
| 155 | idle(false), |
| 156 | origin(origin), |
| 157 | origin_timestamp_us(origin_timestamp_us), |
| 158 | origin_ntp_time_ms(origin_ntp_time_ms) {} |
| 159 | // The instant when the repeat was scheduled. |
| 160 | Timestamp scheduled; |
| 161 | // True if the repeat was scheduled as an idle repeat (long), false |
| 162 | // otherwise. |
| 163 | bool idle; |
| 164 | // The moment we decided to start repeating. |
| 165 | Timestamp origin; |
| 166 | // The timestamp_us of the frame when we started repeating. |
| 167 | int64_t origin_timestamp_us; |
| 168 | // The ntp_times_ms of the frame when we started repeating. |
| 169 | int64_t origin_ntp_time_ms; |
| 170 | }; |
| 171 |
| 172 | // Returns true if all spatial layers can be considered to be converged in |
| 173 | // terms of quality. |
| 174 | // Convergence means QP has dropped to a low-enough level to warrant ceasing |
| 175 | // to send identical frames at high frequency. |
| 176 | bool HasQualityConverged() const RTC_RUN_ON(sequence_checker_); |
| 177 | // Resets quality convergence information. HasQualityConverged() returns false |
| 178 | // after this call. |
| 179 | void ResetQualityConvergenceInfo() RTC_RUN_ON(sequence_checker_); |
| 180 | // Processes incoming frames on a delayed cadence. |
| 181 | void ProcessOnDelayedCadence(Timestamp post_time) |
| 182 | RTC_RUN_ON(sequence_checker_); |
| 183 | // Schedules a later repeat with delay depending on state of layer trackers |
| 184 | // and if UpdateVideoSourceRestrictions has been called or not. |
| 185 | // If true is passed in `idle_repeat`, the repeat is going to be |
| 186 | // kZeroHertzIdleRepeatRatePeriod. Otherwise it'll be the maximum value of |
| 187 | // `frame_delay` or `restricted_frame_delay_` if it has been set. |
| 188 | void ScheduleRepeat(int frame_id, bool idle_repeat) |
| 189 | RTC_RUN_ON(sequence_checker_); |
| 190 | // Repeats a frame in the absence of incoming frames. Slows down when quality |
| 191 | // convergence is attained, and stops the cadence terminally when new frames |
| 192 | // have arrived. |
| 193 | void ProcessRepeatedFrameOnDelayedCadence(int frame_id) |
| 194 | RTC_RUN_ON(sequence_checker_); |
| 195 | // Sends a frame, updating the timestamp to the current time. Also updates |
| 196 | // `queue_overload_count_` based on the time it takes to encode a frame and |
| 197 | // the amount of received frames while encoding. The `queue_overload` |
| 198 | // parameter in the OnFrame callback will be true while |
| 199 | // `queue_overload_count_` is larger than zero to allow the client to drop |
| 200 | // frames and thereby mitigate delay buildups. |
| 201 | // Repeated frames are sent with `post_time` set to absl::nullopt. |
| 202 | void SendFrameNow(absl::optional<Timestamp> post_time, |
| 203 | const VideoFrame& frame) RTC_RUN_ON(sequence_checker_); |
| 204 | // Returns the repeat duration depending on if it's an idle repeat or not. |
| 205 | TimeDelta RepeatDuration(bool idle_repeat) const |
| 206 | RTC_RUN_ON(sequence_checker_); |
| 207 | // Returns the frame duration taking potential restrictions into account. |
| 208 | TimeDelta FrameDuration() const RTC_RUN_ON(sequence_checker_); |
| 209 | // Unless timer already running, starts repeatedly requesting refresh frames |
| 210 | // after a grace_period. If a frame appears before the grace_period has |
| 211 | // passed, the request is cancelled. |
| 212 | void MaybeStartRefreshFrameRequester() RTC_RUN_ON(sequence_checker_); |
| 213 |
| 214 | TaskQueueBase* const queue_; |
| 215 | Clock* const clock_; |
| 216 | FrameCadenceAdapterInterface::Callback* const callback_; |
| 217 |
| 218 | // The configured max_fps. |
| 219 | // TODO(crbug.com/1255737): support max_fps updates. |
| 220 | const double max_fps_; |
| 221 |
| 222 | // Number of frames that are currently scheduled for processing on the |
| 223 | // `queue_`. |
| 224 | const std::atomic<int>& frames_scheduled_for_processing_; |
| 225 |
| 226 | // Can be used as kill-switch for the queue overload mechanism. |
| 227 | const bool zero_hertz_queue_overload_enabled_; |
| 228 |
| 229 | // How much the incoming frame sequence is delayed by. |
| 230 | const TimeDelta frame_delay_ = TimeDelta::Seconds(1) / max_fps_; |
| 231 |
| 232 | RTC_NO_UNIQUE_ADDRESS SequenceChecker sequence_checker_; |
| 233 | // A queue of incoming frames and repeated frames. |
| 234 | std::deque<VideoFrame> queued_frames_ RTC_GUARDED_BY(sequence_checker_); |
| 235 | // The current frame ID to use when starting to repeat frames. This is used |
| 236 | // for cancelling deferred repeated frame processing happening. |
| 237 | int current_frame_id_ RTC_GUARDED_BY(sequence_checker_) = 0; |
| 238 | // Has content when we are repeating frames. |
| 239 | absl::optional<ScheduledRepeat> scheduled_repeat_ |
| 240 | RTC_GUARDED_BY(sequence_checker_); |
| 241 | // Convergent state of each of the configured simulcast layers. |
| 242 | std::vector<SpatialLayerTracker> layer_trackers_ |
| 243 | RTC_GUARDED_BY(sequence_checker_); |
| 244 | // Repeating task handle used for requesting refresh frames until arrival, as |
| 245 | // they can be dropped in various places in the capture pipeline. |
| 246 | RepeatingTaskHandle refresh_frame_requester_ |
| 247 | RTC_GUARDED_BY(sequence_checker_); |
| 248 | // Can be set by UpdateVideoSourceRestrictions when the video source restricts |
| 249 | // the max frame rate. |
| 250 | absl::optional<TimeDelta> restricted_frame_delay_ |
| 251 | RTC_GUARDED_BY(sequence_checker_); |
| 252 | // Set in OnSendFrame to reflect how many future frames will be forwarded with |
| 253 | // the `queue_overload` flag set to true. |
| 254 | int queue_overload_count_ RTC_GUARDED_BY(sequence_checker_) = 0; |
| 255 |
| 256 | ScopedTaskSafety safety_; |
| 257 | }; |
| 258 |
| 259 | // Implements a frame cadence adapter supporting VSync aligned encoding. |
| 260 | class VSyncEncodeAdapterMode : public AdapterMode { |
| 261 | public: |
| 262 | VSyncEncodeAdapterMode( |
| 263 | Clock* clock, |
| 264 | TaskQueueBase* queue, |
| 265 | rtc::scoped_refptr<PendingTaskSafetyFlag> queue_safety_flag, |
| 266 | Metronome* metronome, |
| 267 | TaskQueueBase* worker_queue, |
| 268 | FrameCadenceAdapterInterface::Callback* callback) |
| 269 | : clock_(clock), |
| 270 | queue_(queue), |
| 271 | queue_safety_flag_(queue_safety_flag), |
| 272 | callback_(callback), |
| 273 | metronome_(metronome), |
| 274 | worker_queue_(worker_queue) { |
| 275 | queue_sequence_checker_.Detach(); |
| 276 | worker_sequence_checker_.Detach(); |
| 277 | } |
| 278 |
| 279 | // Adapter overrides. |
| 280 | void OnFrame(Timestamp post_time, |
| 281 | bool queue_overload, |
| 282 | const VideoFrame& frame) override; |
| 283 |
| 284 | absl::optional<uint32_t> GetInputFrameRateFps() override { |
| 285 | RTC_DCHECK_RUN_ON(&queue_sequence_checker_); |
| 286 | return input_framerate_.Rate(clock_->TimeInMilliseconds()); |
| 287 | } |
| 288 |
| 289 | void UpdateFrameRate() override { |
| 290 | RTC_DCHECK_RUN_ON(&queue_sequence_checker_); |
| 291 | input_framerate_.Update(1, clock_->TimeInMilliseconds()); |
| 292 | } |
| 293 |
| 294 | void EncodeAllEnqueuedFrames(); |
| 295 |
| 296 | private: |
| 297 | // Holds input frames coming from the client ready to be encoded. |
| 298 | struct InputFrameRef { |
| 299 | InputFrameRef(const VideoFrame& video_frame, Timestamp time_when_posted_us) |
| 300 | : time_when_posted_us(time_when_posted_us), |
| 301 | video_frame(std::move(video_frame)) {} |
| 302 | Timestamp time_when_posted_us; |
| 303 | const VideoFrame video_frame; |
| 304 | }; |
| 305 |
| 306 | Clock* const clock_; |
| 307 | TaskQueueBase* queue_; |
| 308 | RTC_NO_UNIQUE_ADDRESS SequenceChecker queue_sequence_checker_; |
| 309 | rtc::scoped_refptr<PendingTaskSafetyFlag> queue_safety_flag_; |
| 310 | // Input frame rate statistics for use when not in zero-hertz mode. |
| 311 | RateStatistics input_framerate_ RTC_GUARDED_BY(queue_sequence_checker_){ |
| 312 | FrameCadenceAdapterInterface::kFrameRateAveragingWindowSizeMs, 1000}; |
| 313 | FrameCadenceAdapterInterface::Callback* const callback_; |
| 314 |
| 315 | Metronome* metronome_; |
| 316 | TaskQueueBase* const worker_queue_; |
| 317 | RTC_NO_UNIQUE_ADDRESS SequenceChecker worker_sequence_checker_; |
| 318 | // `worker_safety_` protects tasks on the worker queue related to `metronome_` |
| 319 | // since metronome usage must happen on worker thread. |
| 320 | ScopedTaskSafetyDetached worker_safety_; |
| 321 | Timestamp expected_next_tick_ RTC_GUARDED_BY(worker_sequence_checker_) = |
| 322 | Timestamp::PlusInfinity(); |
| 323 | // Vector of input frames to be encoded. |
| 324 | std::vector<InputFrameRef> input_queue_ |
| 325 | RTC_GUARDED_BY(worker_sequence_checker_); |
| 326 | }; |
| 327 |
| 328 | class FrameCadenceAdapterImpl : public FrameCadenceAdapterInterface { |
| 329 | public: |
| 330 | FrameCadenceAdapterImpl(Clock* clock, |
| 331 | TaskQueueBase* queue, |
| 332 | Metronome* metronome, |
| 333 | TaskQueueBase* worker_queue, |
| 334 | const FieldTrialsView& field_trials); |
| 335 | ~FrameCadenceAdapterImpl(); |
| 336 |
| 337 | // FrameCadenceAdapterInterface overrides. |
| 338 | void Initialize(Callback* callback) override; |
| 339 | void SetZeroHertzModeEnabled( |
| 340 | absl::optional<ZeroHertzModeParams> params) override; |
| 341 | absl::optional<uint32_t> GetInputFrameRateFps() override; |
| 342 | void UpdateFrameRate() override; |
| 343 | void UpdateLayerQualityConvergence(size_t spatial_index, |
| 344 | bool quality_converged) override; |
| 345 | void UpdateLayerStatus(size_t spatial_index, bool enabled) override; |
| 346 | void UpdateVideoSourceRestrictions( |
| 347 | absl::optional<double> max_frame_rate) override; |
| 348 | void ProcessKeyFrameRequest() override; |
| 349 |
| 350 | // VideoFrameSink overrides. |
| 351 | void OnFrame(const VideoFrame& frame) override; |
| 352 | void OnDiscardedFrame() override; |
| 353 | void OnConstraintsChanged( |
| 354 | const VideoTrackSourceConstraints& constraints) override; |
| 355 |
| 356 | private: |
| 357 | // Called from OnFrame in both pass-through and zero-hertz mode. |
| 358 | void OnFrameOnMainQueue(Timestamp post_time, |
| 359 | bool queue_overload, |
| 360 | const VideoFrame& frame) RTC_RUN_ON(queue_); |
| 361 |
| 362 | // Returns true under all of the following conditions: |
| 363 | // - constraints min fps set to 0 |
| 364 | // - constraints max fps set and greater than 0, |
| 365 | // - field trial enabled |
| 366 | // - zero-hertz mode enabled |
| 367 | bool IsZeroHertzScreenshareEnabled() const RTC_RUN_ON(queue_); |
| 368 |
| 369 | // Configures current adapter on non-ZeroHertz mode, called when Initialize or |
| 370 | // MaybeReconfigureAdapters. |
| 371 | void ConfigureCurrentAdapterWithoutZeroHertz(); |
| 372 |
| 373 | // Handles adapter creation on configuration changes. |
| 374 | void MaybeReconfigureAdapters(bool was_zero_hertz_enabled) RTC_RUN_ON(queue_); |
| 375 |
| 376 | Clock* const clock_; |
| 377 | TaskQueueBase* const queue_; |
| 378 |
| 379 | // True if we support frame entry for screenshare with a minimum frequency of |
| 380 | // 0 Hz. |
| 381 | const bool zero_hertz_screenshare_enabled_; |
| 382 |
| 383 | // Kill-switch for the queue overload mechanism in zero-hertz mode. |
| 384 | const bool frame_cadence_adapter_zero_hertz_queue_overload_enabled_; |
| 385 |
| 386 | // The three possible modes we're under. |
| 387 | absl::optional<PassthroughAdapterMode> passthrough_adapter_; |
| 388 | absl::optional<ZeroHertzAdapterMode> zero_hertz_adapter_; |
| 389 | // The `vsync_encode_adapter_` must be destroyed on the worker queue since |
| 390 | // VSync metronome needs to happen on worker thread. |
| 391 | std::unique_ptr<VSyncEncodeAdapterMode> vsync_encode_adapter_; |
| 392 | // If set, zero-hertz mode has been enabled. |
| 393 | absl::optional<ZeroHertzModeParams> zero_hertz_params_; |
| 394 | // Cache for the current adapter mode. |
| 395 | AdapterMode* current_adapter_mode_ = nullptr; |
| 396 |
| 397 | // VSync encoding is used when this valid. |
| 398 | Metronome* const metronome_; |
| 399 | TaskQueueBase* const worker_queue_; |
| 400 |
| 401 | // Timestamp for statistics reporting. |
| 402 | absl::optional<Timestamp> zero_hertz_adapter_created_timestamp_ |
| 403 | RTC_GUARDED_BY(queue_); |
| 404 |
| 405 | // Set up during Initialize. |
| 406 | Callback* callback_ = nullptr; |
| 407 |
| 408 | // The source's constraints. |
| 409 | absl::optional<VideoTrackSourceConstraints> source_constraints_ |
| 410 | RTC_GUARDED_BY(queue_); |
| 411 |
| 412 | // Stores the latest restriction in max frame rate set by |
| 413 | // UpdateVideoSourceRestrictions. Ensures that a previously set restriction |
| 414 | // can be maintained during reconstructions of the adapter. |
| 415 | absl::optional<double> restricted_max_frame_rate_ RTC_GUARDED_BY(queue_); |
| 416 |
| 417 | // Race checker for incoming frames. This is the network thread in chromium, |
| 418 | // but may vary from test contexts. |
| 419 | rtc::RaceChecker incoming_frame_race_checker_; |
| 420 |
| 421 | // Number of frames that are currently scheduled for processing on the |
| 422 | // `queue_`. |
| 423 | std::atomic<int> frames_scheduled_for_processing_{0}; |
| 424 |
| 425 | ScopedTaskSafetyDetached safety_; |
| 426 | }; |
| 427 |
| 428 | ZeroHertzAdapterMode::ZeroHertzAdapterMode( |
| 429 | TaskQueueBase* queue, |
| 430 | Clock* clock, |
| 431 | FrameCadenceAdapterInterface::Callback* callback, |
| 432 | double max_fps, |
| 433 | std::atomic<int>& frames_scheduled_for_processing, |
| 434 | bool zero_hertz_queue_overload_enabled) |
| 435 | : queue_(queue), |
| 436 | clock_(clock), |
| 437 | callback_(callback), |
| 438 | max_fps_(max_fps), |
| 439 | frames_scheduled_for_processing_(frames_scheduled_for_processing), |
| 440 | zero_hertz_queue_overload_enabled_(zero_hertz_queue_overload_enabled) { |
| 441 | sequence_checker_.Detach(); |
| 442 | MaybeStartRefreshFrameRequester(); |
| 443 | } |
| 444 |
| 445 | void ZeroHertzAdapterMode::ReconfigureParameters( |
| 446 | const FrameCadenceAdapterInterface::ZeroHertzModeParams& params) { |
| 447 | RTC_DCHECK_RUN_ON(&sequence_checker_); |
| 448 | RTC_DLOG(LS_INFO) << __func__ << " this " << this << " num_simulcast_layers " |
| 449 | << params.num_simulcast_layers; |
| 450 |
| 451 | // Start as unconverged. |
| 452 | layer_trackers_.clear(); |
| 453 | layer_trackers_.resize(params.num_simulcast_layers, |
| 454 | SpatialLayerTracker{false}); |
| 455 | } |
| 456 |
| 457 | void ZeroHertzAdapterMode::UpdateLayerQualityConvergence( |
| 458 | size_t spatial_index, |
| 459 | bool quality_converged) { |
| 460 | RTC_DCHECK_RUN_ON(&sequence_checker_); |
| 461 | TRACE_EVENT_INSTANT2(TRACE_DISABLED_BY_DEFAULT("webrtc"), __func__, |
| 462 | "spatial_index", spatial_index, "converged", |
| 463 | quality_converged); |
| 464 | if (spatial_index >= layer_trackers_.size()) |
| 465 | return; |
| 466 | if (layer_trackers_[spatial_index].quality_converged.has_value()) |
| 467 | layer_trackers_[spatial_index].quality_converged = quality_converged; |
| 468 | } |
| 469 |
| 470 | void ZeroHertzAdapterMode::UpdateLayerStatus(size_t spatial_index, |
| 471 | bool enabled) { |
| 472 | RTC_DCHECK_RUN_ON(&sequence_checker_); |
| 473 | TRACE_EVENT_INSTANT2(TRACE_DISABLED_BY_DEFAULT("webrtc"), __func__, |
| 474 | "spatial_index", spatial_index, "enabled", enabled); |
| 475 | if (spatial_index >= layer_trackers_.size()) |
| 476 | return; |
| 477 | if (enabled) { |
| 478 | if (!layer_trackers_[spatial_index].quality_converged.has_value()) { |
| 479 | // Assume quality has not converged until hearing otherwise. |
| 480 | layer_trackers_[spatial_index].quality_converged = false; |
| 481 | } |
| 482 | } else { |
| 483 | layer_trackers_[spatial_index].quality_converged = absl::nullopt; |
| 484 | } |
| 485 | } |
| 486 |
| 487 | void ZeroHertzAdapterMode::OnFrame(Timestamp post_time, |
| 488 | bool queue_overload, |
| 489 | const VideoFrame& frame) { |
| 490 | RTC_DCHECK_RUN_ON(&sequence_checker_); |
| 491 | TRACE_EVENT0("webrtc", "ZeroHertzAdapterMode::OnFrame"); |
| 492 | refresh_frame_requester_.Stop(); |
| 493 |
| 494 | // Assume all enabled layers are unconverged after frame entry. |
| 495 | ResetQualityConvergenceInfo(); |
| 496 |
| 497 | // Remove stored repeating frame if needed. |
| 498 | if (scheduled_repeat_.has_value()) { |
| 499 | RTC_DCHECK(queued_frames_.size() == 1); |
| 500 | RTC_DLOG(LS_VERBOSE) << __func__ << " this " << this |
| 501 | << " cancel repeat and restart with original"; |
| 502 | queued_frames_.pop_front(); |
| 503 | } |
| 504 |
| 505 | // Store the frame in the queue and schedule deferred processing. |
| 506 | queued_frames_.push_back(frame); |
| 507 | current_frame_id_++; |
| 508 | scheduled_repeat_ = absl::nullopt; |
| 509 | TimeDelta time_spent_since_post = clock_->CurrentTime() - post_time; |
| 510 | queue_->PostDelayedHighPrecisionTask( |
| 511 | SafeTask(safety_.flag(), |
| 512 | [this, post_time] { |
| 513 | RTC_DCHECK_RUN_ON(&sequence_checker_); |
| 514 | ProcessOnDelayedCadence(post_time); |
| 515 | }), |
| 516 | std::max(frame_delay_ - time_spent_since_post, TimeDelta::Zero())); |
| 517 | } |
| 518 |
| 519 | void ZeroHertzAdapterMode::OnDiscardedFrame() { |
| 520 | RTC_DCHECK_RUN_ON(&sequence_checker_); |
| 521 | TRACE_EVENT0("webrtc", __func__); |
| 522 |
| 523 | // Under zero hertz source delivery, a discarded frame ending a sequence of |
| 524 | // frames which happened to contain important information can be seen as a |
| 525 | // capture freeze. Avoid this by starting requesting refresh frames after a |
| 526 | // grace period. |
| 527 | MaybeStartRefreshFrameRequester(); |
| 528 | } |
| 529 |
| 530 | absl::optional<uint32_t> ZeroHertzAdapterMode::GetInputFrameRateFps() { |
| 531 | RTC_DCHECK_RUN_ON(&sequence_checker_); |
| 532 | return max_fps_; |
| 533 | } |
| 534 |
| 535 | void ZeroHertzAdapterMode::UpdateVideoSourceRestrictions( |
| 536 | absl::optional<double> max_frame_rate) { |
| 537 | RTC_DCHECK_RUN_ON(&sequence_checker_); |
| 538 | TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("webrtc"), __func__, |
| 539 | "max_frame_rate", max_frame_rate.value_or(-1)); |
| 540 | if (max_frame_rate.value_or(0) > 0) { |
| 541 | // Set new, validated (> 0) and restricted frame rate. |
| 542 | restricted_frame_delay_ = TimeDelta::Seconds(1) / *max_frame_rate; |
| 543 | } else { |
| 544 | // Source reports that the frame rate is now unrestricted. |
| 545 | restricted_frame_delay_ = absl::nullopt; |
| 546 | } |
| 547 | } |
| 548 |
| 549 | void ZeroHertzAdapterMode::ProcessKeyFrameRequest() { |
| 550 | RTC_DCHECK_RUN_ON(&sequence_checker_); |
| 551 | TRACE_EVENT_INSTANT0("webrtc", __func__); |
| 552 | // If we're new and don't have a frame, there's no need to request refresh |
| 553 | // frames as this was being triggered for us when zero-hz mode was set up. |
| 554 | // |
| 555 | // The next frame encoded will be a key frame. Reset quality convergence so we |
| 556 | // don't get idle repeats shortly after, because key frames need a lot of |
| 557 | // refinement frames. |
| 558 | ResetQualityConvergenceInfo(); |
| 559 |
| 560 | // If we're not repeating, or we're repeating with short duration, we will |
| 561 | // very soon send out a frame and don't need a refresh frame. |
| 562 | if (!scheduled_repeat_.has_value() || !scheduled_repeat_->idle) { |
| 563 | RTC_LOG(LS_INFO) << __func__ << " this " << this |
| 564 | << " not requesting refresh frame because of recently " |
| 565 | "incoming frame or short repeating."; |
| 566 | return; |
| 567 | } |
| 568 |
| 569 | // If the repeat is scheduled within a short (i.e. frame_delay_) interval, we |
| 570 | // will very soon send out a frame and don't need a refresh frame. |
| 571 | Timestamp now = clock_->CurrentTime(); |
| 572 | if (scheduled_repeat_->scheduled + RepeatDuration(/*idle_repeat=*/true) - |
| 573 | now <= |
| 574 | frame_delay_) { |
| 575 | RTC_LOG(LS_INFO) << __func__ << " this " << this |
| 576 | << " not requesting refresh frame because of soon " |
| 577 | "happening idle repeat"; |
| 578 | return; |
| 579 | } |
| 580 |
| 581 | // Cancel the current repeat and reschedule a short repeat now. No need for a |
| 582 | // new refresh frame. |
| 583 | RTC_LOG(LS_INFO) << __func__ << " this " << this |
| 584 | << " not requesting refresh frame and scheduling a short " |
| 585 | "repeat due to key frame request"; |
| 586 | ScheduleRepeat(++current_frame_id_, /*idle_repeat=*/false); |
| 587 | return; |
| 588 | } |
| 589 |
| 590 | bool ZeroHertzAdapterMode::HasQualityConverged() const { |
| 591 | RTC_DCHECK_RUN_ON(&sequence_checker_); |
| 592 | // 1. Define ourselves as unconverged with no spatial layers configured. This |
| 593 | // is to keep short repeating until the layer configuration comes. |
| 594 | // 2. Unset layers implicitly imply that they're converged to support |
| 595 | // disabling layers when they're not needed. |
| 596 | const bool quality_converged = |
| 597 | !layer_trackers_.empty() && |
| 598 | absl::c_all_of(layer_trackers_, [](const SpatialLayerTracker& tracker) { |
| 599 | return tracker.quality_converged.value_or(true); |
| 600 | }); |
| 601 | return quality_converged; |
| 602 | } |
| 603 |
| 604 | void ZeroHertzAdapterMode::ResetQualityConvergenceInfo() { |
| 605 | RTC_DCHECK_RUN_ON(&sequence_checker_); |
| 606 | RTC_DLOG(LS_INFO) << __func__ << " this " << this; |
| 607 | for (auto& layer_tracker : layer_trackers_) { |
| 608 | if (layer_tracker.quality_converged.has_value()) |
| 609 | layer_tracker.quality_converged = false; |
| 610 | } |
| 611 | } |
| 612 |
| 613 | void ZeroHertzAdapterMode::ProcessOnDelayedCadence(Timestamp post_time) { |
| 614 | RTC_DCHECK_RUN_ON(&sequence_checker_); |
| 615 | RTC_DCHECK(!queued_frames_.empty()); |
| 616 | TRACE_EVENT0("webrtc", __func__); |
| 617 |
| 618 | // Avoid sending the front frame for encoding (which could take a long time) |
| 619 | // until we schedule a repeat. |
| 620 | VideoFrame front_frame = queued_frames_.front(); |
| 621 |
| 622 | // If there were two or more frames stored, we do not have to schedule repeats |
| 623 | // of the front frame. |
| 624 | if (queued_frames_.size() > 1) { |
| 625 | queued_frames_.pop_front(); |
| 626 | } else { |
| 627 | // There's only one frame to send. Schedule a repeat sequence, which is |
| 628 | // cancelled by `current_frame_id_` getting incremented should new frames |
| 629 | // arrive. |
| 630 | ScheduleRepeat(current_frame_id_, HasQualityConverged()); |
| 631 | } |
| 632 | SendFrameNow(post_time, front_frame); |
| 633 | } |
| 634 |
| 635 | void ZeroHertzAdapterMode::ScheduleRepeat(int frame_id, bool idle_repeat) { |
| 636 | RTC_DCHECK_RUN_ON(&sequence_checker_); |
| 637 | Timestamp now = clock_->CurrentTime(); |
| 638 | if (!scheduled_repeat_.has_value()) { |
| 639 | scheduled_repeat_.emplace(now, queued_frames_.front().timestamp_us(), |
| 640 | queued_frames_.front().ntp_time_ms()); |
| 641 | } |
| 642 | scheduled_repeat_->scheduled = now; |
| 643 | scheduled_repeat_->idle = idle_repeat; |
| 644 |
| 645 | TimeDelta repeat_delay = RepeatDuration(idle_repeat); |
| 646 | queue_->PostDelayedHighPrecisionTask( |
| 647 | SafeTask(safety_.flag(), |
| 648 | [this, frame_id] { |
| 649 | RTC_DCHECK_RUN_ON(&sequence_checker_); |
| 650 | ProcessRepeatedFrameOnDelayedCadence(frame_id); |
| 651 | }), |
| 652 | repeat_delay); |
| 653 | } |
| 654 |
| 655 | void ZeroHertzAdapterMode::ProcessRepeatedFrameOnDelayedCadence(int frame_id) { |
| 656 | RTC_DCHECK_RUN_ON(&sequence_checker_); |
| 657 | TRACE_EVENT0("webrtc", __func__); |
| 658 | RTC_DCHECK(!queued_frames_.empty()); |
| 659 |
| 660 | // Cancel this invocation if new frames turned up. |
| 661 | if (frame_id != current_frame_id_) |
| 662 | return; |
| 663 | RTC_DCHECK(scheduled_repeat_.has_value()); |
| 664 |
| 665 | VideoFrame& frame = queued_frames_.front(); |
| 666 |
| 667 | // Since this is a repeated frame, nothing changed compared to before. |
| 668 | VideoFrame::UpdateRect empty_update_rect; |
| 669 | empty_update_rect.MakeEmptyUpdate(); |
| 670 | frame.set_update_rect(empty_update_rect); |
| 671 |
| 672 | // Adjust timestamps of the frame of the repeat, accounting for the actual |
| 673 | // delay since we started repeating. |
| 674 | // |
| 675 | // NOTE: No need to update the RTP timestamp as the VideoStreamEncoder |
| 676 | // overwrites it based on its chosen NTP timestamp source. |
| 677 | TimeDelta total_delay = clock_->CurrentTime() - scheduled_repeat_->origin; |
| 678 | if (frame.timestamp_us() > 0) { |
| 679 | frame.set_timestamp_us(scheduled_repeat_->origin_timestamp_us + |
| 680 | total_delay.us()); |
| 681 | } |
| 682 | if (frame.ntp_time_ms()) { |
| 683 | frame.set_ntp_time_ms(scheduled_repeat_->origin_ntp_time_ms + |
| 684 | total_delay.ms()); |
| 685 | } |
| 686 |
| 687 | // Schedule another repeat before sending the frame off which could take time. |
| 688 | ScheduleRepeat(frame_id, HasQualityConverged()); |
| 689 | SendFrameNow(absl::nullopt, frame); |
| 690 | } |
| 691 |
| 692 | void ZeroHertzAdapterMode::SendFrameNow(absl::optional<Timestamp> post_time, |
| 693 | const VideoFrame& frame) { |
| 694 | RTC_DCHECK_RUN_ON(&sequence_checker_); |
| 695 | TRACE_EVENT0("webrtc", __func__); |
| 696 |
| 697 | Timestamp encode_start_time = clock_->CurrentTime(); |
| 698 | if (post_time.has_value()) { |
| 699 | TimeDelta delay = (encode_start_time - *post_time); |
| 700 | RTC_HISTOGRAM_COUNTS_10000("WebRTC.Screenshare.ZeroHz.DelayMs", delay.ms()); |
| 701 | } |
| 702 |
| 703 | // Forward the frame and set `queue_overload` if is has been detected that it |
| 704 | // is not possible to deliver frames at the expected rate due to slow |
| 705 | // encoding. |
| 706 | callback_->OnFrame(/*post_time=*/encode_start_time, queue_overload_count_ > 0, |
| 707 | frame); |
| 708 |
| 709 | // WebRTC-ZeroHertzQueueOverload kill-switch. |
| 710 | if (!zero_hertz_queue_overload_enabled_) |
| 711 | return; |
| 712 |
| 713 | // `queue_overload_count_` determines for how many future frames the |
| 714 | // `queue_overload` flag will be set and it is only increased if: |
| 715 | // o We are not already in an overload state. |
| 716 | // o New frames have been scheduled for processing on the queue while encoding |
| 717 | // took place in OnFrame. |
| 718 | // o The duration of OnFrame is longer than the current frame duration. |
| 719 | // If all these conditions are fulfilled, `queue_overload_count_` is set to |
| 720 | // `frames_scheduled_for_processing_` and any pending repeat is canceled since |
| 721 | // new frames are available and the repeat is not needed. |
| 722 | // If the adapter is already in an overload state, simply decrease |
| 723 | // `queue_overload_count_` by one. |
| 724 | if (queue_overload_count_ == 0) { |
| 725 | const int frames_scheduled_for_processing = |
| 726 | frames_scheduled_for_processing_.load(std::memory_order_relaxed); |
| 727 | if (frames_scheduled_for_processing > 0) { |
| 728 | TimeDelta encode_time = clock_->CurrentTime() - encode_start_time; |
| 729 | if (encode_time > FrameDuration()) { |
| 730 | queue_overload_count_ = frames_scheduled_for_processing; |
| 731 | // Invalidates any outstanding repeat to avoid sending pending repeat |
| 732 | // directly after too long encode. |
| 733 | current_frame_id_++; |
| 734 | } |
| 735 | } |
| 736 | } else { |
| 737 | queue_overload_count_--; |
| 738 | } |
| 739 | RTC_HISTOGRAM_BOOLEAN("WebRTC.Screenshare.ZeroHz.QueueOverload", |
| 740 | queue_overload_count_ > 0); |
| 741 | } |
| 742 |
| 743 | TimeDelta ZeroHertzAdapterMode::FrameDuration() const { |
| 744 | RTC_DCHECK_RUN_ON(&sequence_checker_); |
| 745 | return std::max(frame_delay_, restricted_frame_delay_.value_or(frame_delay_)); |
| 746 | } |
| 747 |
| 748 | TimeDelta ZeroHertzAdapterMode::RepeatDuration(bool idle_repeat) const { |
| 749 | RTC_DCHECK_RUN_ON(&sequence_checker_); |
| 750 | return idle_repeat |
| 751 | ? FrameCadenceAdapterInterface::kZeroHertzIdleRepeatRatePeriod |
| 752 | : FrameDuration(); |
| 753 | } |
| 754 |
| 755 | void ZeroHertzAdapterMode::MaybeStartRefreshFrameRequester() { |
| 756 | RTC_DCHECK_RUN_ON(&sequence_checker_); |
| 757 | if (!refresh_frame_requester_.Running()) { |
| 758 | refresh_frame_requester_ = RepeatingTaskHandle::DelayedStart( |
| 759 | queue_, |
| 760 | FrameCadenceAdapterInterface::kOnDiscardedFrameRefreshFramePeriod * |
| 761 | frame_delay_, |
| 762 | [this] { |
| 763 | RTC_DLOG(LS_VERBOSE) << __func__ << " RequestRefreshFrame"; |
| 764 | if (callback_) |
| 765 | callback_->RequestRefreshFrame(); |
| 766 | return frame_delay_; |
| 767 | }); |
| 768 | } |
| 769 | } |
| 770 |
| 771 | void VSyncEncodeAdapterMode::OnFrame(Timestamp post_time, |
| 772 | bool queue_overload, |
| 773 | const VideoFrame& frame) { |
| 774 | // We expect `metronome_` and `EncodeAllEnqueuedFrames()` runs on |
| 775 | // `worker_queue_`. |
| 776 | if (!worker_queue_->IsCurrent()) { |
| 777 | worker_queue_->PostTask(SafeTask( |
| 778 | worker_safety_.flag(), [this, post_time, queue_overload, frame] { |
| 779 | OnFrame(post_time, queue_overload, frame); |
| 780 | })); |
| 781 | return; |
| 782 | } |
| 783 |
| 784 | RTC_DCHECK_RUN_ON(&worker_sequence_checker_); |
| 785 | TRACE_EVENT0("webrtc", "VSyncEncodeAdapterMode::OnFrame"); |
| 786 |
| 787 | input_queue_.emplace_back(std::move(frame), post_time); |
| 788 |
| 789 | // The `metronome_` tick period maybe throttled in some case, so here we only |
| 790 | // align encode task to VSync event when `metronome_` tick period is less |
| 791 | // than 34ms (30Hz). |
| 792 | static constexpr TimeDelta kMaxAllowedDelay = TimeDelta::Millis(34); |
| 793 | if (metronome_->TickPeriod() <= kMaxAllowedDelay) { |
| 794 | // The metronome is ticking frequently enough that it is worth the extra |
| 795 | // delay. |
| 796 | metronome_->RequestCallOnNextTick( |
| 797 | SafeTask(worker_safety_.flag(), [this] { EncodeAllEnqueuedFrames(); })); |
| 798 | } else { |
| 799 | // The metronome is ticking too infrequently, encode immediately. |
| 800 | EncodeAllEnqueuedFrames(); |
| 801 | } |
| 802 | } |
| 803 |
| 804 | void VSyncEncodeAdapterMode::EncodeAllEnqueuedFrames() { |
| 805 | RTC_DCHECK_RUN_ON(&worker_sequence_checker_); |
| 806 | TRACE_EVENT0("webrtc", "VSyncEncodeAdapterMode::EncodeAllEnqueuedFrames"); |
| 807 |
| 808 | // Local time in webrtc time base. |
| 809 | Timestamp post_time = clock_->CurrentTime(); |
| 810 |
| 811 | for (auto& input : input_queue_) { |
| 812 | TRACE_EVENT1("webrtc", "FrameCadenceAdapterImpl::EncodeAllEnqueuedFrames", |
| 813 | "VSyncEncodeDelay", |
| 814 | (post_time - input.time_when_posted_us).ms()); |
| 815 |
| 816 | const VideoFrame frame = std::move(input.video_frame); |
| 817 | queue_->PostTask(SafeTask(queue_safety_flag_, [this, post_time, frame] { |
| 818 | RTC_DCHECK_RUN_ON(queue_); |
| 819 |
| 820 | // TODO(b/304158952): Support more refined queue overload control. |
| 821 | callback_->OnFrame(post_time, /*queue_overload=*/false, frame); |
| 822 | })); |
| 823 | } |
| 824 |
| 825 | input_queue_.clear(); |
| 826 | } |
| 827 |
| 828 | FrameCadenceAdapterImpl::FrameCadenceAdapterImpl( |
| 829 | Clock* clock, |
| 830 | TaskQueueBase* queue, |
| 831 | Metronome* metronome, |
| 832 | TaskQueueBase* worker_queue, |
| 833 | const FieldTrialsView& field_trials) |
| 834 | : clock_(clock), |
| 835 | queue_(queue), |
| 836 | zero_hertz_screenshare_enabled_( |
| 837 | !field_trials.IsDisabled("WebRTC-ZeroHertzScreenshare")), |
| 838 | frame_cadence_adapter_zero_hertz_queue_overload_enabled_( |
| 839 | !field_trials.IsDisabled("WebRTC-ZeroHertzQueueOverload")), |
| 840 | metronome_(metronome), |
| 841 | worker_queue_(worker_queue) {} |
| 842 |
| 843 | FrameCadenceAdapterImpl::~FrameCadenceAdapterImpl() { |
| 844 | RTC_DLOG(LS_VERBOSE) << __func__ << " this " << this; |
| 845 |
| 846 | // VSync adapter needs to be destroyed on worker queue when metronome is |
| 847 | // valid. |
| 848 | if (metronome_) { |
| 849 | absl::Cleanup cleanup = [adapter = std::move(vsync_encode_adapter_)] {}; |
| 850 | worker_queue_->PostTask([cleanup = std::move(cleanup)] {}); |
| 851 | } |
| 852 | } |
| 853 |
| 854 | void FrameCadenceAdapterImpl::Initialize(Callback* callback) { |
| 855 | callback_ = callback; |
| 856 | // Use VSync encode mode if metronome is valid, otherwise passthrough mode |
| 857 | // would be used. |
| 858 | if (metronome_) { |
| 859 | vsync_encode_adapter_ = std::make_unique<VSyncEncodeAdapterMode>( |
| 860 | clock_, queue_, safety_.flag(), metronome_, worker_queue_, callback_); |
| 861 | } else { |
| 862 | passthrough_adapter_.emplace(clock_, callback); |
| 863 | } |
| 864 | ConfigureCurrentAdapterWithoutZeroHertz(); |
| 865 | } |
| 866 |
| 867 | void FrameCadenceAdapterImpl::SetZeroHertzModeEnabled( |
| 868 | absl::optional<ZeroHertzModeParams> params) { |
| 869 | RTC_DCHECK_RUN_ON(queue_); |
| 870 | bool was_zero_hertz_enabled = zero_hertz_params_.has_value(); |
| 871 | zero_hertz_params_ = params; |
| 872 | MaybeReconfigureAdapters(was_zero_hertz_enabled); |
| 873 | } |
| 874 |
| 875 | absl::optional<uint32_t> FrameCadenceAdapterImpl::GetInputFrameRateFps() { |
| 876 | RTC_DCHECK_RUN_ON(queue_); |
| 877 | return current_adapter_mode_->GetInputFrameRateFps(); |
| 878 | } |
| 879 |
| 880 | void FrameCadenceAdapterImpl::UpdateFrameRate() { |
| 881 | RTC_DCHECK_RUN_ON(queue_); |
| 882 | // The frame rate need not be updated for the zero-hertz adapter. The |
| 883 | // vsync encode and passthrough adapter however uses it. Always pass frames |
| 884 | // into the vsync encode or passthrough to keep the estimation alive should |
| 885 | // there be an adapter switch. |
| 886 | if (metronome_) { |
| 887 | RTC_CHECK(vsync_encode_adapter_); |
| 888 | vsync_encode_adapter_->UpdateFrameRate(); |
| 889 | } else { |
| 890 | RTC_CHECK(passthrough_adapter_); |
| 891 | passthrough_adapter_->UpdateFrameRate(); |
| 892 | } |
| 893 | } |
| 894 |
| 895 | void FrameCadenceAdapterImpl::UpdateLayerQualityConvergence( |
| 896 | size_t spatial_index, |
| 897 | bool quality_converged) { |
| 898 | if (zero_hertz_adapter_.has_value()) |
| 899 | zero_hertz_adapter_->UpdateLayerQualityConvergence(spatial_index, |
| 900 | quality_converged); |
| 901 | } |
| 902 |
| 903 | void FrameCadenceAdapterImpl::UpdateLayerStatus(size_t spatial_index, |
| 904 | bool enabled) { |
| 905 | if (zero_hertz_adapter_.has_value()) |
| 906 | zero_hertz_adapter_->UpdateLayerStatus(spatial_index, enabled); |
| 907 | } |
| 908 |
| 909 | void FrameCadenceAdapterImpl::UpdateVideoSourceRestrictions( |
| 910 | absl::optional<double> max_frame_rate) { |
| 911 | RTC_DCHECK_RUN_ON(queue_); |
| 912 | // Store the restriction to ensure that it can be reapplied in possible |
| 913 | // future adapter creations on configuration changes. |
| 914 | restricted_max_frame_rate_ = max_frame_rate; |
| 915 | if (zero_hertz_adapter_) { |
| 916 | zero_hertz_adapter_->UpdateVideoSourceRestrictions(max_frame_rate); |
| 917 | } |
| 918 | } |
| 919 |
| 920 | void FrameCadenceAdapterImpl::ProcessKeyFrameRequest() { |
| 921 | RTC_DCHECK_RUN_ON(queue_); |
| 922 | if (zero_hertz_adapter_) |
| 923 | zero_hertz_adapter_->ProcessKeyFrameRequest(); |
| 924 | } |
| 925 |
| 926 | void FrameCadenceAdapterImpl::OnFrame(const VideoFrame& frame) { |
| 927 | // This method is called on the network thread under Chromium, or other |
| 928 | // various contexts in test. |
| 929 | RTC_DCHECK_RUNS_SERIALIZED(&incoming_frame_race_checker_); |
| 930 | TRACE_EVENT0("webrtc", "FrameCadenceAdapterImpl::OnFrame"); |
| 931 |
| 932 | // Local time in webrtc time base. |
| 933 | Timestamp post_time = clock_->CurrentTime(); |
| 934 | frames_scheduled_for_processing_.fetch_add(1, std::memory_order_relaxed); |
| 935 | queue_->PostTask(SafeTask(safety_.flag(), [this, post_time, frame] { |
| 936 | RTC_DCHECK_RUN_ON(queue_); |
| 937 | if (zero_hertz_adapter_created_timestamp_.has_value()) { |
| 938 | TimeDelta time_until_first_frame = |
| 939 | clock_->CurrentTime() - *zero_hertz_adapter_created_timestamp_; |
| 940 | zero_hertz_adapter_created_timestamp_ = absl::nullopt; |
| 941 | RTC_HISTOGRAM_COUNTS_10000( |
| 942 | "WebRTC.Screenshare.ZeroHz.TimeUntilFirstFrameMs", |
| 943 | time_until_first_frame.ms()); |
| 944 | } |
| 945 |
| 946 | const int frames_scheduled_for_processing = |
| 947 | frames_scheduled_for_processing_.fetch_sub(1, |
| 948 | std::memory_order_relaxed); |
| 949 | OnFrameOnMainQueue(post_time, frames_scheduled_for_processing > 1, |
| 950 | std::move(frame)); |
| 951 | })); |
| 952 | } |
| 953 |
| 954 | void FrameCadenceAdapterImpl::OnDiscardedFrame() { |
| 955 | callback_->OnDiscardedFrame(); |
| 956 | queue_->PostTask(SafeTask(safety_.flag(), [this] { |
| 957 | RTC_DCHECK_RUN_ON(queue_); |
| 958 | if (zero_hertz_adapter_) { |
| 959 | zero_hertz_adapter_->OnDiscardedFrame(); |
| 960 | } |
| 961 | })); |
| 962 | } |
| 963 |
| 964 | void FrameCadenceAdapterImpl::OnConstraintsChanged( |
| 965 | const VideoTrackSourceConstraints& constraints) { |
| 966 | RTC_LOG(LS_INFO) << __func__ << " this " << this << " min_fps " |
| 967 | << constraints.min_fps.value_or(-1) << " max_fps " |
| 968 | << constraints.max_fps.value_or(-1); |
| 969 | queue_->PostTask(SafeTask(safety_.flag(), [this, constraints] { |
| 970 | RTC_DCHECK_RUN_ON(queue_); |
| 971 | bool was_zero_hertz_enabled = IsZeroHertzScreenshareEnabled(); |
| 972 | source_constraints_ = constraints; |
| 973 | MaybeReconfigureAdapters(was_zero_hertz_enabled); |
| 974 | })); |
| 975 | } |
| 976 |
| 977 | void FrameCadenceAdapterImpl::OnFrameOnMainQueue(Timestamp post_time, |
| 978 | bool queue_overload, |
| 979 | const VideoFrame& frame) { |
| 980 | RTC_DCHECK_RUN_ON(queue_); |
| 981 | current_adapter_mode_->OnFrame(post_time, queue_overload, frame); |
| 982 | } |
| 983 |
| 984 | bool FrameCadenceAdapterImpl::IsZeroHertzScreenshareEnabled() const { |
| 985 | RTC_DCHECK_RUN_ON(queue_); |
| 986 | return zero_hertz_screenshare_enabled_ && source_constraints_.has_value() && |
| 987 | source_constraints_->max_fps.value_or(-1) > 0 && |
| 988 | source_constraints_->min_fps.value_or(-1) == 0 && |
| 989 | zero_hertz_params_.has_value(); |
| 990 | } |
| 991 |
| 992 | void FrameCadenceAdapterImpl::ConfigureCurrentAdapterWithoutZeroHertz() { |
| 993 | // Enable VSyncEncodeAdapterMode if metronome is valid. |
| 994 | if (metronome_) { |
| 995 | RTC_CHECK(vsync_encode_adapter_); |
| 996 | current_adapter_mode_ = vsync_encode_adapter_.get(); |
| 997 | } else { |
| 998 | RTC_CHECK(passthrough_adapter_); |
| 999 | current_adapter_mode_ = &passthrough_adapter_.value(); |
| 1000 | } |
| 1001 | } |
| 1002 |
| 1003 | void FrameCadenceAdapterImpl::MaybeReconfigureAdapters( |
| 1004 | bool was_zero_hertz_enabled) { |
| 1005 | RTC_DCHECK_RUN_ON(queue_); |
| 1006 | bool is_zero_hertz_enabled = IsZeroHertzScreenshareEnabled(); |
| 1007 | if (is_zero_hertz_enabled) { |
| 1008 | bool max_fps_has_changed = GetInputFrameRateFps().value_or(-1) != |
| 1009 | source_constraints_->max_fps.value_or(-1); |
| 1010 | if (!was_zero_hertz_enabled || max_fps_has_changed) { |
| 1011 | RTC_LOG(LS_INFO) << "Zero hertz mode enabled (max_fps=" |
| 1012 | << source_constraints_->max_fps.value() << ")"; |
| 1013 | zero_hertz_adapter_.emplace( |
| 1014 | queue_, clock_, callback_, source_constraints_->max_fps.value(), |
| 1015 | frames_scheduled_for_processing_, |
| 1016 | frame_cadence_adapter_zero_hertz_queue_overload_enabled_); |
| 1017 | zero_hertz_adapter_->UpdateVideoSourceRestrictions( |
| 1018 | restricted_max_frame_rate_); |
| 1019 | zero_hertz_adapter_created_timestamp_ = clock_->CurrentTime(); |
| 1020 | } |
| 1021 | zero_hertz_adapter_->ReconfigureParameters(zero_hertz_params_.value()); |
| 1022 | current_adapter_mode_ = &zero_hertz_adapter_.value(); |
| 1023 | } else { |
| 1024 | if (was_zero_hertz_enabled) { |
| 1025 | zero_hertz_adapter_ = absl::nullopt; |
| 1026 | RTC_LOG(LS_INFO) << "Zero hertz mode disabled."; |
| 1027 | } |
| 1028 | ConfigureCurrentAdapterWithoutZeroHertz(); |
| 1029 | } |
| 1030 | } |
| 1031 |
| 1032 | } // namespace |
| 1033 |
| 1034 | std::unique_ptr<FrameCadenceAdapterInterface> |
| 1035 | FrameCadenceAdapterInterface::Create(Clock* clock, |
| 1036 | TaskQueueBase* queue, |
| 1037 | Metronome* metronome, |
| 1038 | TaskQueueBase* worker_queue, |
| 1039 | const FieldTrialsView& field_trials) { |
| 1040 | return std::make_unique<FrameCadenceAdapterImpl>(clock, queue, metronome, |
| 1041 | worker_queue, field_trials); |
| 1042 | } |
| 1043 |
| 1044 | } // namespace webrtc |
| 1045 |