| 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 "modules/video_coding/frame_buffer2.h" |
| 12 |
| 13 | #include <algorithm> |
| 14 | #include <cstdlib> |
| 15 | #include <iterator> |
| 16 | #include <queue> |
| 17 | #include <utility> |
| 18 | #include <vector> |
| 19 |
| 20 | #include "absl/memory/memory.h" |
| 21 | #include "api/video/encoded_image.h" |
| 22 | #include "api/video/video_timing.h" |
| 23 | #include "modules/video_coding/include/video_coding_defines.h" |
| 24 | #include "modules/video_coding/jitter_estimator.h" |
| 25 | #include "modules/video_coding/timing.h" |
| 26 | #include "rtc_base/checks.h" |
| 27 | #include "rtc_base/experiments/rtt_mult_experiment.h" |
| 28 | #include "rtc_base/logging.h" |
| 29 | #include "rtc_base/numerics/sequence_number_util.h" |
| 30 | #include "rtc_base/trace_event.h" |
| 31 | #include "system_wrappers/include/clock.h" |
| 32 | #include "system_wrappers/include/field_trial.h" |
| 33 |
| 34 | namespace webrtc { |
| 35 | namespace video_coding { |
| 36 |
| 37 | namespace { |
| 38 | // Max number of frames the buffer will hold. |
| 39 | constexpr size_t kMaxFramesBuffered = 800; |
| 40 |
| 41 | // Max number of decoded frame info that will be saved. |
| 42 | constexpr int kMaxFramesHistory = 1 << 13; |
| 43 |
| 44 | // The time it's allowed for a frame to be late to its rendering prediction and |
| 45 | // still be rendered. |
| 46 | constexpr int kMaxAllowedFrameDelayMs = 5; |
| 47 |
| 48 | constexpr int64_t kLogNonDecodedIntervalMs = 5000; |
| 49 | } // namespace |
| 50 |
| 51 | FrameBuffer::FrameBuffer(Clock* clock, |
| 52 | VCMTiming* timing, |
| 53 | VCMReceiveStatisticsCallback* stats_callback) |
| 54 | : decoded_frames_history_(kMaxFramesHistory), |
| 55 | clock_(clock), |
| 56 | callback_queue_(nullptr), |
| 57 | jitter_estimator_(clock), |
| 58 | timing_(timing), |
| 59 | inter_frame_delay_(clock_->TimeInMilliseconds()), |
| 60 | stopped_(false), |
| 61 | protection_mode_(kProtectionNack), |
| 62 | stats_callback_(stats_callback), |
| 63 | last_log_non_decoded_ms_(-kLogNonDecodedIntervalMs), |
| 64 | add_rtt_to_playout_delay_( |
| 65 | webrtc::field_trial::IsEnabled("WebRTC-AddRttToPlayoutDelay")), |
| 66 | rtt_mult_settings_(RttMultExperiment::GetRttMultValue()) { |
| 67 | callback_checker_.Detach(); |
| 68 | } |
| 69 |
| 70 | FrameBuffer::~FrameBuffer() { |
| 71 | RTC_DCHECK_RUN_ON(&construction_checker_); |
| 72 | } |
| 73 |
| 74 | void FrameBuffer::NextFrame( |
| 75 | int64_t max_wait_time_ms, |
| 76 | bool keyframe_required, |
| 77 | rtc::TaskQueue* callback_queue, |
| 78 | std::function<void(std::unique_ptr<EncodedFrame>, ReturnReason)> handler) { |
| 79 | RTC_DCHECK_RUN_ON(&callback_checker_); |
| 80 | RTC_DCHECK(callback_queue->IsCurrent()); |
| 81 | TRACE_EVENT0("webrtc", "FrameBuffer::NextFrame"); |
| 82 | int64_t latest_return_time_ms = |
| 83 | clock_->TimeInMilliseconds() + max_wait_time_ms; |
| 84 |
| 85 | MutexLock lock(&mutex_); |
| 86 | if (stopped_) { |
| 87 | return; |
| 88 | } |
| 89 | latest_return_time_ms_ = latest_return_time_ms; |
| 90 | keyframe_required_ = keyframe_required; |
| 91 | frame_handler_ = handler; |
| 92 | callback_queue_ = callback_queue; |
| 93 | StartWaitForNextFrameOnQueue(); |
| 94 | } |
| 95 |
| 96 | void FrameBuffer::StartWaitForNextFrameOnQueue() { |
| 97 | RTC_DCHECK(callback_queue_); |
| 98 | RTC_DCHECK(!callback_task_.Running()); |
| 99 | int64_t wait_ms = FindNextFrame(clock_->TimeInMilliseconds()); |
| 100 | callback_task_ = RepeatingTaskHandle::DelayedStart( |
| 101 | callback_queue_->Get(), TimeDelta::Millis(wait_ms), [this] { |
| 102 | RTC_DCHECK_RUN_ON(&callback_checker_); |
| 103 | // If this task has not been cancelled, we did not get any new frames |
| 104 | // while waiting. Continue with frame delivery. |
| 105 | MutexLock lock(&mutex_); |
| 106 | if (!frames_to_decode_.empty()) { |
| 107 | // We have frames, deliver! |
| 108 | frame_handler_(absl::WrapUnique(GetNextFrame()), kFrameFound); |
| 109 | CancelCallback(); |
| 110 | return TimeDelta::Zero(); // Ignored. |
| 111 | } else if (clock_->TimeInMilliseconds() >= latest_return_time_ms_) { |
| 112 | // We have timed out, signal this and stop repeating. |
| 113 | frame_handler_(nullptr, kTimeout); |
| 114 | CancelCallback(); |
| 115 | return TimeDelta::Zero(); // Ignored. |
| 116 | } else { |
| 117 | // If there's no frames to decode and there is still time left, it |
| 118 | // means that the frame buffer was cleared between creation and |
| 119 | // execution of this task. Continue waiting for the remaining time. |
| 120 | int64_t wait_ms = FindNextFrame(clock_->TimeInMilliseconds()); |
| 121 | return TimeDelta::Millis(wait_ms); |
| 122 | } |
| 123 | }); |
| 124 | } |
| 125 |
| 126 | int64_t FrameBuffer::FindNextFrame(int64_t now_ms) { |
| 127 | int64_t wait_ms = latest_return_time_ms_ - now_ms; |
| 128 | frames_to_decode_.clear(); |
| 129 |
| 130 | // |last_continuous_frame_| may be empty below, but nullopt is smaller |
| 131 | // than everything else and loop will immediately terminate as expected. |
| 132 | for (auto frame_it = frames_.begin(); |
| 133 | frame_it != frames_.end() && frame_it->first <= last_continuous_frame_; |
| 134 | ++frame_it) { |
| 135 | if (!frame_it->second.continuous || |
| 136 | frame_it->second.num_missing_decodable > 0) { |
| 137 | continue; |
| 138 | } |
| 139 |
| 140 | EncodedFrame* frame = frame_it->second.frame.get(); |
| 141 |
| 142 | if (keyframe_required_ && !frame->is_keyframe()) |
| 143 | continue; |
| 144 |
| 145 | auto last_decoded_frame_timestamp = |
| 146 | decoded_frames_history_.GetLastDecodedFrameTimestamp(); |
| 147 |
| 148 | // TODO(https://bugs.webrtc.org/9974): consider removing this check |
| 149 | // as it may make a stream undecodable after a very long delay between |
| 150 | // frames. |
| 151 | if (last_decoded_frame_timestamp && |
| 152 | AheadOf(*last_decoded_frame_timestamp, frame->Timestamp())) { |
| 153 | continue; |
| 154 | } |
| 155 |
| 156 | // Only ever return all parts of a superframe. Therefore skip this |
| 157 | // frame if it's not a beginning of a superframe. |
| 158 | if (frame->inter_layer_predicted) { |
| 159 | continue; |
| 160 | } |
| 161 |
| 162 | // Gather all remaining frames for the same superframe. |
| 163 | std::vector<FrameMap::iterator> current_superframe; |
| 164 | current_superframe.push_back(frame_it); |
| 165 | bool last_layer_completed = frame_it->second.frame->is_last_spatial_layer; |
| 166 | FrameMap::iterator next_frame_it = frame_it; |
| 167 | while (true) { |
| 168 | ++next_frame_it; |
| 169 | if (next_frame_it == frames_.end() || |
| 170 | next_frame_it->first.picture_id != frame->id.picture_id || |
| 171 | !next_frame_it->second.continuous) { |
| 172 | break; |
| 173 | } |
| 174 | // Check if the next frame has some undecoded references other than |
| 175 | // the previous frame in the same superframe. |
| 176 | size_t num_allowed_undecoded_refs = |
| 177 | (next_frame_it->second.frame->inter_layer_predicted) ? 1 : 0; |
| 178 | if (next_frame_it->second.num_missing_decodable > |
| 179 | num_allowed_undecoded_refs) { |
| 180 | break; |
| 181 | } |
| 182 | // All frames in the superframe should have the same timestamp. |
| 183 | if (frame->Timestamp() != next_frame_it->second.frame->Timestamp()) { |
| 184 | RTC_LOG(LS_WARNING) << "Frames in a single superframe have different" |
| 185 | " timestamps. Skipping undecodable superframe."; |
| 186 | break; |
| 187 | } |
| 188 | current_superframe.push_back(next_frame_it); |
| 189 | last_layer_completed = next_frame_it->second.frame->is_last_spatial_layer; |
| 190 | } |
| 191 | // Check if the current superframe is complete. |
| 192 | // TODO(bugs.webrtc.org/10064): consider returning all available to |
| 193 | // decode frames even if the superframe is not complete yet. |
| 194 | if (!last_layer_completed) { |
| 195 | continue; |
| 196 | } |
| 197 |
| 198 | frames_to_decode_ = std::move(current_superframe); |
| 199 |
| 200 | if (frame->RenderTime() == -1) { |
| 201 | frame->SetRenderTime(timing_->RenderTimeMs(frame->Timestamp(), now_ms)); |
| 202 | } |
| 203 | wait_ms = timing_->MaxWaitingTime(frame->RenderTime(), now_ms); |
| 204 |
| 205 | // This will cause the frame buffer to prefer high framerate rather |
| 206 | // than high resolution in the case of the decoder not decoding fast |
| 207 | // enough and the stream has multiple spatial and temporal layers. |
| 208 | // For multiple temporal layers it may cause non-base layer frames to be |
| 209 | // skipped if they are late. |
| 210 | if (wait_ms < -kMaxAllowedFrameDelayMs) |
| 211 | continue; |
| 212 |
| 213 | break; |
| 214 | } |
| 215 | wait_ms = std::min<int64_t>(wait_ms, latest_return_time_ms_ - now_ms); |
| 216 | wait_ms = std::max<int64_t>(wait_ms, 0); |
| 217 | return wait_ms; |
| 218 | } |
| 219 |
| 220 | EncodedFrame* FrameBuffer::GetNextFrame() { |
| 221 | RTC_DCHECK_RUN_ON(&callback_checker_); |
| 222 | int64_t now_ms = clock_->TimeInMilliseconds(); |
| 223 | // TODO(ilnik): remove |frames_out| use frames_to_decode_ directly. |
| 224 | std::vector<EncodedFrame*> frames_out; |
| 225 |
| 226 | RTC_DCHECK(!frames_to_decode_.empty()); |
| 227 | bool superframe_delayed_by_retransmission = false; |
| 228 | size_t superframe_size = 0; |
| 229 | EncodedFrame* first_frame = frames_to_decode_[0]->second.frame.get(); |
| 230 | int64_t render_time_ms = first_frame->RenderTime(); |
| 231 | int64_t receive_time_ms = first_frame->ReceivedTime(); |
| 232 | // Gracefully handle bad RTP timestamps and render time issues. |
| 233 | if (HasBadRenderTiming(*first_frame, now_ms)) { |
| 234 | jitter_estimator_.Reset(); |
| 235 | timing_->Reset(); |
| 236 | render_time_ms = timing_->RenderTimeMs(first_frame->Timestamp(), now_ms); |
| 237 | } |
| 238 |
| 239 | for (FrameMap::iterator& frame_it : frames_to_decode_) { |
| 240 | RTC_DCHECK(frame_it != frames_.end()); |
| 241 | EncodedFrame* frame = frame_it->second.frame.release(); |
| 242 |
| 243 | frame->SetRenderTime(render_time_ms); |
| 244 |
| 245 | superframe_delayed_by_retransmission |= frame->delayed_by_retransmission(); |
| 246 | receive_time_ms = std::max(receive_time_ms, frame->ReceivedTime()); |
| 247 | superframe_size += frame->size(); |
| 248 |
| 249 | PropagateDecodability(frame_it->second); |
| 250 | decoded_frames_history_.InsertDecoded(frame_it->first, frame->Timestamp()); |
| 251 |
| 252 | // Remove decoded frame and all undecoded frames before it. |
| 253 | if (stats_callback_) { |
| 254 | unsigned int dropped_frames = std::count_if( |
| 255 | frames_.begin(), frame_it, |
| 256 | [](const std::pair<const VideoLayerFrameId, FrameInfo>& frame) { |
| 257 | return frame.second.frame != nullptr; |
| 258 | }); |
| 259 | if (dropped_frames > 0) { |
| 260 | stats_callback_->OnDroppedFrames(dropped_frames); |
| 261 | } |
| 262 | } |
| 263 |
| 264 | frames_.erase(frames_.begin(), ++frame_it); |
| 265 |
| 266 | frames_out.push_back(frame); |
| 267 | } |
| 268 |
| 269 | if (!superframe_delayed_by_retransmission) { |
| 270 | int64_t frame_delay; |
| 271 |
| 272 | if (inter_frame_delay_.CalculateDelay(first_frame->Timestamp(), |
| 273 | &frame_delay, receive_time_ms)) { |
| 274 | jitter_estimator_.UpdateEstimate(frame_delay, superframe_size); |
| 275 | } |
| 276 |
| 277 | float rtt_mult = protection_mode_ == kProtectionNackFEC ? 0.0 : 1.0; |
| 278 | absl::optional<float> rtt_mult_add_cap_ms = absl::nullopt; |
| 279 | if (rtt_mult_settings_.has_value()) { |
| 280 | rtt_mult = rtt_mult_settings_->rtt_mult_setting; |
| 281 | rtt_mult_add_cap_ms = rtt_mult_settings_->rtt_mult_add_cap_ms; |
| 282 | } |
| 283 | timing_->SetJitterDelay( |
| 284 | jitter_estimator_.GetJitterEstimate(rtt_mult, rtt_mult_add_cap_ms)); |
| 285 | timing_->UpdateCurrentDelay(render_time_ms, now_ms); |
| 286 | } else { |
| 287 | if (RttMultExperiment::RttMultEnabled() || add_rtt_to_playout_delay_) |
| 288 | jitter_estimator_.FrameNacked(); |
| 289 | } |
| 290 |
| 291 | UpdateJitterDelay(); |
| 292 | UpdateTimingFrameInfo(); |
| 293 |
| 294 | if (frames_out.size() == 1) { |
| 295 | return frames_out[0]; |
| 296 | } else { |
| 297 | return CombineAndDeleteFrames(frames_out); |
| 298 | } |
| 299 | } |
| 300 |
| 301 | bool FrameBuffer::HasBadRenderTiming(const EncodedFrame& frame, |
| 302 | int64_t now_ms) { |
| 303 | // Assume that render timing errors are due to changes in the video stream. |
| 304 | int64_t render_time_ms = frame.RenderTimeMs(); |
| 305 | // Zero render time means render immediately. |
| 306 | if (render_time_ms == 0) { |
| 307 | return false; |
| 308 | } |
| 309 | if (render_time_ms < 0) { |
| 310 | return true; |
| 311 | } |
| 312 | const int64_t kMaxVideoDelayMs = 10000; |
| 313 | if (std::abs(render_time_ms - now_ms) > kMaxVideoDelayMs) { |
| 314 | int frame_delay = static_cast<int>(std::abs(render_time_ms - now_ms)); |
| 315 | RTC_LOG(LS_WARNING) |
| 316 | << "A frame about to be decoded is out of the configured " |
| 317 | "delay bounds (" |
| 318 | << frame_delay << " > " << kMaxVideoDelayMs |
| 319 | << "). Resetting the video jitter buffer."; |
| 320 | return true; |
| 321 | } |
| 322 | if (static_cast<int>(timing_->TargetVideoDelay()) > kMaxVideoDelayMs) { |
| 323 | RTC_LOG(LS_WARNING) << "The video target delay has grown larger than " |
| 324 | << kMaxVideoDelayMs << " ms."; |
| 325 | return true; |
| 326 | } |
| 327 | return false; |
| 328 | } |
| 329 |
| 330 | void FrameBuffer::SetProtectionMode(VCMVideoProtection mode) { |
| 331 | TRACE_EVENT0("webrtc", "FrameBuffer::SetProtectionMode"); |
| 332 | MutexLock lock(&mutex_); |
| 333 | protection_mode_ = mode; |
| 334 | } |
| 335 |
| 336 | void FrameBuffer::Stop() { |
| 337 | TRACE_EVENT0("webrtc", "FrameBuffer::Stop"); |
| 338 | MutexLock lock(&mutex_); |
| 339 | if (stopped_) |
| 340 | return; |
| 341 | stopped_ = true; |
| 342 |
| 343 | CancelCallback(); |
| 344 | } |
| 345 |
| 346 | void FrameBuffer::Clear() { |
| 347 | MutexLock lock(&mutex_); |
| 348 | ClearFramesAndHistory(); |
| 349 | } |
| 350 |
| 351 | void FrameBuffer::UpdateRtt(int64_t rtt_ms) { |
| 352 | MutexLock lock(&mutex_); |
| 353 | jitter_estimator_.UpdateRtt(rtt_ms); |
| 354 | } |
| 355 |
| 356 | bool FrameBuffer::ValidReferences(const EncodedFrame& frame) const { |
| 357 | for (size_t i = 0; i < frame.num_references; ++i) { |
| 358 | if (frame.references[i] >= frame.id.picture_id) |
| 359 | return false; |
| 360 |
| 361 | for (size_t j = i + 1; j < frame.num_references; ++j) { |
| 362 | if (frame.references[i] == frame.references[j]) |
| 363 | return false; |
| 364 | } |
| 365 | } |
| 366 |
| 367 | if (frame.inter_layer_predicted && frame.id.spatial_layer == 0) |
| 368 | return false; |
| 369 |
| 370 | return true; |
| 371 | } |
| 372 |
| 373 | void FrameBuffer::CancelCallback() { |
| 374 | // Called from the callback queue or from within Stop(). |
| 375 | frame_handler_ = {}; |
| 376 | callback_task_.Stop(); |
| 377 | callback_queue_ = nullptr; |
| 378 | callback_checker_.Detach(); |
| 379 | } |
| 380 |
| 381 | bool FrameBuffer::IsCompleteSuperFrame(const EncodedFrame& frame) { |
| 382 | if (frame.inter_layer_predicted) { |
| 383 | // Check that all previous spatial layers are already inserted. |
| 384 | VideoLayerFrameId id = frame.id; |
| 385 | RTC_DCHECK_GT(id.spatial_layer, 0); |
| 386 | --id.spatial_layer; |
| 387 | FrameMap::iterator prev_frame = frames_.find(id); |
| 388 | if (prev_frame == frames_.end() || !prev_frame->second.frame) |
| 389 | return false; |
| 390 | while (prev_frame->second.frame->inter_layer_predicted) { |
| 391 | if (prev_frame == frames_.begin()) |
| 392 | return false; |
| 393 | --prev_frame; |
| 394 | --id.spatial_layer; |
| 395 | if (!prev_frame->second.frame || |
| 396 | prev_frame->first.picture_id != id.picture_id || |
| 397 | prev_frame->first.spatial_layer != id.spatial_layer) { |
| 398 | return false; |
| 399 | } |
| 400 | } |
| 401 | } |
| 402 |
| 403 | if (!frame.is_last_spatial_layer) { |
| 404 | // Check that all following spatial layers are already inserted. |
| 405 | VideoLayerFrameId id = frame.id; |
| 406 | ++id.spatial_layer; |
| 407 | FrameMap::iterator next_frame = frames_.find(id); |
| 408 | if (next_frame == frames_.end() || !next_frame->second.frame) |
| 409 | return false; |
| 410 | while (!next_frame->second.frame->is_last_spatial_layer) { |
| 411 | ++next_frame; |
| 412 | ++id.spatial_layer; |
| 413 | if (next_frame == frames_.end() || !next_frame->second.frame || |
| 414 | next_frame->first.picture_id != id.picture_id || |
| 415 | next_frame->first.spatial_layer != id.spatial_layer) { |
| 416 | return false; |
| 417 | } |
| 418 | } |
| 419 | } |
| 420 |
| 421 | return true; |
| 422 | } |
| 423 |
| 424 | int64_t FrameBuffer::InsertFrame(std::unique_ptr<EncodedFrame> frame) { |
| 425 | TRACE_EVENT0("webrtc", "FrameBuffer::InsertFrame"); |
| 426 | RTC_DCHECK(frame); |
| 427 |
| 428 | MutexLock lock(&mutex_); |
| 429 |
| 430 | const VideoLayerFrameId& id = frame->id; |
| 431 | int64_t last_continuous_picture_id = |
| 432 | !last_continuous_frame_ ? -1 : last_continuous_frame_->picture_id; |
| 433 |
| 434 | if (!ValidReferences(*frame)) { |
| 435 | RTC_LOG(LS_WARNING) << "Frame with (picture_id:spatial_id) (" |
| 436 | << id.picture_id << ":" |
| 437 | << static_cast<int>(id.spatial_layer) |
| 438 | << ") has invalid frame references, dropping frame."; |
| 439 | return last_continuous_picture_id; |
| 440 | } |
| 441 |
| 442 | if (frames_.size() >= kMaxFramesBuffered) { |
| 443 | if (frame->is_keyframe()) { |
| 444 | RTC_LOG(LS_WARNING) << "Inserting keyframe (picture_id:spatial_id) (" |
| 445 | << id.picture_id << ":" |
| 446 | << static_cast<int>(id.spatial_layer) |
| 447 | << ") but buffer is full, clearing" |
| 448 | " buffer and inserting the frame."; |
| 449 | ClearFramesAndHistory(); |
| 450 | } else { |
| 451 | RTC_LOG(LS_WARNING) << "Frame with (picture_id:spatial_id) (" |
| 452 | << id.picture_id << ":" |
| 453 | << static_cast<int>(id.spatial_layer) |
| 454 | << ") could not be inserted due to the frame " |
| 455 | "buffer being full, dropping frame."; |
| 456 | return last_continuous_picture_id; |
| 457 | } |
| 458 | } |
| 459 |
| 460 | auto last_decoded_frame = decoded_frames_history_.GetLastDecodedFrameId(); |
| 461 | auto last_decoded_frame_timestamp = |
| 462 | decoded_frames_history_.GetLastDecodedFrameTimestamp(); |
| 463 | if (last_decoded_frame && id <= *last_decoded_frame) { |
| 464 | if (AheadOf(frame->Timestamp(), *last_decoded_frame_timestamp) && |
| 465 | frame->is_keyframe()) { |
| 466 | // If this frame has a newer timestamp but an earlier picture id then we |
| 467 | // assume there has been a jump in the picture id due to some encoder |
| 468 | // reconfiguration or some other reason. Even though this is not according |
| 469 | // to spec we can still continue to decode from this frame if it is a |
| 470 | // keyframe. |
| 471 | RTC_LOG(LS_WARNING) |
| 472 | << "A jump in picture id was detected, clearing buffer."; |
| 473 | ClearFramesAndHistory(); |
| 474 | last_continuous_picture_id = -1; |
| 475 | } else { |
| 476 | RTC_LOG(LS_WARNING) << "Frame with (picture_id:spatial_id) (" |
| 477 | << id.picture_id << ":" |
| 478 | << static_cast<int>(id.spatial_layer) |
| 479 | << ") inserted after frame (" |
| 480 | << last_decoded_frame->picture_id << ":" |
| 481 | << static_cast<int>(last_decoded_frame->spatial_layer) |
| 482 | << ") was handed off for decoding, dropping frame."; |
| 483 | return last_continuous_picture_id; |
| 484 | } |
| 485 | } |
| 486 |
| 487 | // Test if inserting this frame would cause the order of the frames to become |
| 488 | // ambiguous (covering more than half the interval of 2^16). This can happen |
| 489 | // when the picture id make large jumps mid stream. |
| 490 | if (!frames_.empty() && id < frames_.begin()->first && |
| 491 | frames_.rbegin()->first < id) { |
| 492 | RTC_LOG(LS_WARNING) |
| 493 | << "A jump in picture id was detected, clearing buffer."; |
| 494 | ClearFramesAndHistory(); |
| 495 | last_continuous_picture_id = -1; |
| 496 | } |
| 497 |
| 498 | auto info = frames_.emplace(id, FrameInfo()).first; |
| 499 |
| 500 | if (info->second.frame) { |
| 501 | return last_continuous_picture_id; |
| 502 | } |
| 503 |
| 504 | if (!UpdateFrameInfoWithIncomingFrame(*frame, info)) |
| 505 | return last_continuous_picture_id; |
| 506 |
| 507 | if (!frame->delayed_by_retransmission()) |
| 508 | timing_->IncomingTimestamp(frame->Timestamp(), frame->ReceivedTime()); |
| 509 |
| 510 | if (stats_callback_ && IsCompleteSuperFrame(*frame)) { |
| 511 | stats_callback_->OnCompleteFrame(frame->is_keyframe(), frame->size(), |
| 512 | frame->contentType()); |
| 513 | } |
| 514 |
| 515 | info->second.frame = std::move(frame); |
| 516 |
| 517 | if (info->second.num_missing_continuous == 0) { |
| 518 | info->second.continuous = true; |
| 519 | PropagateContinuity(info); |
| 520 | last_continuous_picture_id = last_continuous_frame_->picture_id; |
| 521 |
| 522 | // Since we now have new continuous frames there might be a better frame |
| 523 | // to return from NextFrame. |
| 524 | if (callback_queue_) { |
| 525 | callback_queue_->PostTask([this] { |
| 526 | MutexLock lock(&mutex_); |
| 527 | if (!callback_task_.Running()) |
| 528 | return; |
| 529 | RTC_CHECK(frame_handler_); |
| 530 | callback_task_.Stop(); |
| 531 | StartWaitForNextFrameOnQueue(); |
| 532 | }); |
| 533 | } |
| 534 | } |
| 535 |
| 536 | return last_continuous_picture_id; |
| 537 | } |
| 538 |
| 539 | void FrameBuffer::PropagateContinuity(FrameMap::iterator start) { |
| 540 | TRACE_EVENT0("webrtc", "FrameBuffer::PropagateContinuity"); |
| 541 | RTC_DCHECK(start->second.continuous); |
| 542 |
| 543 | std::queue<FrameMap::iterator> continuous_frames; |
| 544 | continuous_frames.push(start); |
| 545 |
| 546 | // A simple BFS to traverse continuous frames. |
| 547 | while (!continuous_frames.empty()) { |
| 548 | auto frame = continuous_frames.front(); |
| 549 | continuous_frames.pop(); |
| 550 |
| 551 | if (!last_continuous_frame_ || *last_continuous_frame_ < frame->first) { |
| 552 | last_continuous_frame_ = frame->first; |
| 553 | } |
| 554 |
| 555 | // Loop through all dependent frames, and if that frame no longer has |
| 556 | // any unfulfilled dependencies then that frame is continuous as well. |
| 557 | for (size_t d = 0; d < frame->second.dependent_frames.size(); ++d) { |
| 558 | auto frame_ref = frames_.find(frame->second.dependent_frames[d]); |
| 559 | RTC_DCHECK(frame_ref != frames_.end()); |
| 560 |
| 561 | // TODO(philipel): Look into why we've seen this happen. |
| 562 | if (frame_ref != frames_.end()) { |
| 563 | --frame_ref->second.num_missing_continuous; |
| 564 | if (frame_ref->second.num_missing_continuous == 0) { |
| 565 | frame_ref->second.continuous = true; |
| 566 | continuous_frames.push(frame_ref); |
| 567 | } |
| 568 | } |
| 569 | } |
| 570 | } |
| 571 | } |
| 572 |
| 573 | void FrameBuffer::PropagateDecodability(const FrameInfo& info) { |
| 574 | TRACE_EVENT0("webrtc", "FrameBuffer::PropagateDecodability"); |
| 575 | for (size_t d = 0; d < info.dependent_frames.size(); ++d) { |
| 576 | auto ref_info = frames_.find(info.dependent_frames[d]); |
| 577 | RTC_DCHECK(ref_info != frames_.end()); |
| 578 | // TODO(philipel): Look into why we've seen this happen. |
| 579 | if (ref_info != frames_.end()) { |
| 580 | RTC_DCHECK_GT(ref_info->second.num_missing_decodable, 0U); |
| 581 | --ref_info->second.num_missing_decodable; |
| 582 | } |
| 583 | } |
| 584 | } |
| 585 |
| 586 | bool FrameBuffer::UpdateFrameInfoWithIncomingFrame(const EncodedFrame& frame, |
| 587 | FrameMap::iterator info) { |
| 588 | TRACE_EVENT0("webrtc", "FrameBuffer::UpdateFrameInfoWithIncomingFrame"); |
| 589 | const VideoLayerFrameId& id = frame.id; |
| 590 |
| 591 | auto last_decoded_frame = decoded_frames_history_.GetLastDecodedFrameId(); |
| 592 | RTC_DCHECK(!last_decoded_frame || *last_decoded_frame < info->first); |
| 593 |
| 594 | // In this function we determine how many missing dependencies this |frame| |
| 595 | // has to become continuous/decodable. If a frame that this |frame| depend |
| 596 | // on has already been decoded then we can ignore that dependency since it has |
| 597 | // already been fulfilled. |
| 598 | // |
| 599 | // For all other frames we will register a backwards reference to this |frame| |
| 600 | // so that |num_missing_continuous| and |num_missing_decodable| can be |
| 601 | // decremented as frames become continuous/are decoded. |
| 602 | struct Dependency { |
| 603 | VideoLayerFrameId id; |
| 604 | bool continuous; |
| 605 | }; |
| 606 | std::vector<Dependency> not_yet_fulfilled_dependencies; |
| 607 |
| 608 | // Find all dependencies that have not yet been fulfilled. |
| 609 | for (size_t i = 0; i < frame.num_references; ++i) { |
| 610 | VideoLayerFrameId ref_key(frame.references[i], frame.id.spatial_layer); |
| 611 | // Does |frame| depend on a frame earlier than the last decoded one? |
| 612 | if (last_decoded_frame && ref_key <= *last_decoded_frame) { |
| 613 | // Was that frame decoded? If not, this |frame| will never become |
| 614 | // decodable. |
| 615 | if (!decoded_frames_history_.WasDecoded(ref_key)) { |
| 616 | int64_t now_ms = clock_->TimeInMilliseconds(); |
| 617 | if (last_log_non_decoded_ms_ + kLogNonDecodedIntervalMs < now_ms) { |
| 618 | RTC_LOG(LS_WARNING) |
| 619 | << "Frame with (picture_id:spatial_id) (" << id.picture_id << ":" |
| 620 | << static_cast<int>(id.spatial_layer) |
| 621 | << ") depends on a non-decoded frame more previous than" |
| 622 | " the last decoded frame, dropping frame."; |
| 623 | last_log_non_decoded_ms_ = now_ms; |
| 624 | } |
| 625 | return false; |
| 626 | } |
| 627 | } else { |
| 628 | auto ref_info = frames_.find(ref_key); |
| 629 | bool ref_continuous = |
| 630 | ref_info != frames_.end() && ref_info->second.continuous; |
| 631 | not_yet_fulfilled_dependencies.push_back({ref_key, ref_continuous}); |
| 632 | } |
| 633 | } |
| 634 |
| 635 | // Does |frame| depend on the lower spatial layer? |
| 636 | if (frame.inter_layer_predicted) { |
| 637 | VideoLayerFrameId ref_key(frame.id.picture_id, frame.id.spatial_layer - 1); |
| 638 | auto ref_info = frames_.find(ref_key); |
| 639 |
| 640 | bool lower_layer_decoded = |
| 641 | last_decoded_frame && *last_decoded_frame == ref_key; |
| 642 | bool lower_layer_continuous = |
| 643 | lower_layer_decoded || |
| 644 | (ref_info != frames_.end() && ref_info->second.continuous); |
| 645 |
| 646 | if (!lower_layer_continuous || !lower_layer_decoded) { |
| 647 | not_yet_fulfilled_dependencies.push_back( |
| 648 | {ref_key, lower_layer_continuous}); |
| 649 | } |
| 650 | } |
| 651 |
| 652 | info->second.num_missing_continuous = not_yet_fulfilled_dependencies.size(); |
| 653 | info->second.num_missing_decodable = not_yet_fulfilled_dependencies.size(); |
| 654 |
| 655 | for (const Dependency& dep : not_yet_fulfilled_dependencies) { |
| 656 | if (dep.continuous) |
| 657 | --info->second.num_missing_continuous; |
| 658 |
| 659 | frames_[dep.id].dependent_frames.push_back(id); |
| 660 | } |
| 661 |
| 662 | return true; |
| 663 | } |
| 664 |
| 665 | void FrameBuffer::UpdateJitterDelay() { |
| 666 | TRACE_EVENT0("webrtc", "FrameBuffer::UpdateJitterDelay"); |
| 667 | if (!stats_callback_) |
| 668 | return; |
| 669 |
| 670 | int max_decode_ms; |
| 671 | int current_delay_ms; |
| 672 | int target_delay_ms; |
| 673 | int jitter_buffer_ms; |
| 674 | int min_playout_delay_ms; |
| 675 | int render_delay_ms; |
| 676 | if (timing_->GetTimings(&max_decode_ms, ¤t_delay_ms, &target_delay_ms, |
| 677 | &jitter_buffer_ms, &min_playout_delay_ms, |
| 678 | &render_delay_ms)) { |
| 679 | stats_callback_->OnFrameBufferTimingsUpdated( |
| 680 | max_decode_ms, current_delay_ms, target_delay_ms, jitter_buffer_ms, |
| 681 | min_playout_delay_ms, render_delay_ms); |
| 682 | } |
| 683 | } |
| 684 |
| 685 | void FrameBuffer::UpdateTimingFrameInfo() { |
| 686 | TRACE_EVENT0("webrtc", "FrameBuffer::UpdateTimingFrameInfo"); |
| 687 | absl::optional<TimingFrameInfo> info = timing_->GetTimingFrameInfo(); |
| 688 | if (info && stats_callback_) |
| 689 | stats_callback_->OnTimingFrameInfoUpdated(*info); |
| 690 | } |
| 691 |
| 692 | void FrameBuffer::ClearFramesAndHistory() { |
| 693 | TRACE_EVENT0("webrtc", "FrameBuffer::ClearFramesAndHistory"); |
| 694 | if (stats_callback_) { |
| 695 | unsigned int dropped_frames = std::count_if( |
| 696 | frames_.begin(), frames_.end(), |
| 697 | [](const std::pair<const VideoLayerFrameId, FrameInfo>& frame) { |
| 698 | return frame.second.frame != nullptr; |
| 699 | }); |
| 700 | if (dropped_frames > 0) { |
| 701 | stats_callback_->OnDroppedFrames(dropped_frames); |
| 702 | } |
| 703 | } |
| 704 | frames_.clear(); |
| 705 | last_continuous_frame_.reset(); |
| 706 | frames_to_decode_.clear(); |
| 707 | decoded_frames_history_.Clear(); |
| 708 | } |
| 709 |
| 710 | // TODO(philipel): Avoid the concatenation of frames here, by replacing |
| 711 | // NextFrame and GetNextFrame with methods returning multiple frames. |
| 712 | EncodedFrame* FrameBuffer::CombineAndDeleteFrames( |
| 713 | const std::vector<EncodedFrame*>& frames) const { |
| 714 | RTC_DCHECK(!frames.empty()); |
| 715 | EncodedFrame* first_frame = frames[0]; |
| 716 | EncodedFrame* last_frame = frames.back(); |
| 717 | size_t total_length = 0; |
| 718 | for (size_t i = 0; i < frames.size(); ++i) { |
| 719 | total_length += frames[i]->size(); |
| 720 | } |
| 721 | auto encoded_image_buffer = EncodedImageBuffer::Create(total_length); |
| 722 | uint8_t* buffer = encoded_image_buffer->data(); |
| 723 | first_frame->SetSpatialLayerFrameSize(first_frame->id.spatial_layer, |
| 724 | first_frame->size()); |
| 725 | memcpy(buffer, first_frame->data(), first_frame->size()); |
| 726 | buffer += first_frame->size(); |
| 727 |
| 728 | // Spatial index of combined frame is set equal to spatial index of its top |
| 729 | // spatial layer. |
| 730 | first_frame->SetSpatialIndex(last_frame->id.spatial_layer); |
| 731 | first_frame->id.spatial_layer = last_frame->id.spatial_layer; |
| 732 |
| 733 | first_frame->video_timing_mutable()->network2_timestamp_ms = |
| 734 | last_frame->video_timing().network2_timestamp_ms; |
| 735 | first_frame->video_timing_mutable()->receive_finish_ms = |
| 736 | last_frame->video_timing().receive_finish_ms; |
| 737 |
| 738 | // Append all remaining frames to the first one. |
| 739 | for (size_t i = 1; i < frames.size(); ++i) { |
| 740 | EncodedFrame* next_frame = frames[i]; |
| 741 | first_frame->SetSpatialLayerFrameSize(next_frame->id.spatial_layer, |
| 742 | next_frame->size()); |
| 743 | memcpy(buffer, next_frame->data(), next_frame->size()); |
| 744 | buffer += next_frame->size(); |
| 745 | delete next_frame; |
| 746 | } |
| 747 | first_frame->SetEncodedData(encoded_image_buffer); |
| 748 | return first_frame; |
| 749 | } |
| 750 |
| 751 | FrameBuffer::FrameInfo::FrameInfo() = default; |
| 752 | FrameBuffer::FrameInfo::FrameInfo(FrameInfo&&) = default; |
| 753 | FrameBuffer::FrameInfo::~FrameInfo() = default; |
| 754 |
| 755 | } // namespace video_coding |
| 756 | } // namespace webrtc |
| 757 |