You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

799 lines
28 KiB

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