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.

515 lines
18 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/packet_buffer.h"
  11. #include <string.h>
  12. #include <algorithm>
  13. #include <cstdint>
  14. #include <utility>
  15. #include "absl/types/variant.h"
  16. #include "api/video/encoded_frame.h"
  17. #include "common_video/h264/h264_common.h"
  18. #include "modules/rtp_rtcp/source/rtp_video_header.h"
  19. #include "modules/video_coding/codecs/h264/include/h264_globals.h"
  20. #include "modules/video_coding/frame_object.h"
  21. #include "rtc_base/checks.h"
  22. #include "rtc_base/logging.h"
  23. #include "rtc_base/numerics/mod_ops.h"
  24. #include "system_wrappers/include/clock.h"
  25. #include "system_wrappers/include/field_trial.h"
  26. namespace webrtc {
  27. namespace video_coding {
  28. PacketBuffer::PacketBuffer(Clock* clock,
  29. size_t start_buffer_size,
  30. size_t max_buffer_size,
  31. OnAssembledFrameCallback* assembled_frame_callback)
  32. : clock_(clock),
  33. max_size_(max_buffer_size),
  34. first_seq_num_(0),
  35. first_packet_received_(false),
  36. is_cleared_to_first_seq_num_(false),
  37. buffer_(start_buffer_size),
  38. assembled_frame_callback_(assembled_frame_callback),
  39. unique_frames_seen_(0),
  40. sps_pps_idr_is_h264_keyframe_(
  41. field_trial::IsEnabled("WebRTC-SpsPpsIdrIsH264Keyframe")) {
  42. RTC_DCHECK_LE(start_buffer_size, max_buffer_size);
  43. // Buffer size must always be a power of 2.
  44. RTC_DCHECK((start_buffer_size & (start_buffer_size - 1)) == 0);
  45. RTC_DCHECK((max_buffer_size & (max_buffer_size - 1)) == 0);
  46. }
  47. PacketBuffer::~PacketBuffer() {
  48. Clear();
  49. }
  50. bool PacketBuffer::InsertPacket(VCMPacket* packet) {
  51. std::vector<std::unique_ptr<RtpFrameObject>> found_frames;
  52. {
  53. rtc::CritScope lock(&crit_);
  54. OnTimestampReceived(packet->timestamp);
  55. uint16_t seq_num = packet->seqNum;
  56. size_t index = seq_num % buffer_.size();
  57. if (!first_packet_received_) {
  58. first_seq_num_ = seq_num;
  59. first_packet_received_ = true;
  60. } else if (AheadOf(first_seq_num_, seq_num)) {
  61. // If we have explicitly cleared past this packet then it's old,
  62. // don't insert it, just silently ignore it.
  63. if (is_cleared_to_first_seq_num_) {
  64. delete[] packet->dataPtr;
  65. packet->dataPtr = nullptr;
  66. return true;
  67. }
  68. first_seq_num_ = seq_num;
  69. }
  70. if (buffer_[index].used) {
  71. // Duplicate packet, just delete the payload.
  72. if (buffer_[index].seq_num() == packet->seqNum) {
  73. delete[] packet->dataPtr;
  74. packet->dataPtr = nullptr;
  75. return true;
  76. }
  77. // The packet buffer is full, try to expand the buffer.
  78. while (ExpandBufferSize() && buffer_[seq_num % buffer_.size()].used) {
  79. }
  80. index = seq_num % buffer_.size();
  81. // Packet buffer is still full since we were unable to expand the buffer.
  82. if (buffer_[index].used) {
  83. // Clear the buffer, delete payload, and return false to signal that a
  84. // new keyframe is needed.
  85. RTC_LOG(LS_WARNING) << "Clear PacketBuffer and request key frame.";
  86. Clear();
  87. delete[] packet->dataPtr;
  88. packet->dataPtr = nullptr;
  89. return false;
  90. }
  91. }
  92. StoredPacket& new_entry = buffer_[index];
  93. new_entry.continuous = false;
  94. new_entry.used = true;
  95. new_entry.data = *packet;
  96. packet->dataPtr = nullptr;
  97. UpdateMissingPackets(packet->seqNum);
  98. int64_t now_ms = clock_->TimeInMilliseconds();
  99. last_received_packet_ms_ = now_ms;
  100. if (packet->video_header.frame_type == VideoFrameType::kVideoFrameKey)
  101. last_received_keyframe_packet_ms_ = now_ms;
  102. found_frames = FindFrames(seq_num);
  103. }
  104. for (std::unique_ptr<RtpFrameObject>& frame : found_frames)
  105. assembled_frame_callback_->OnAssembledFrame(std::move(frame));
  106. return true;
  107. }
  108. void PacketBuffer::ClearTo(uint16_t seq_num) {
  109. rtc::CritScope lock(&crit_);
  110. // We have already cleared past this sequence number, no need to do anything.
  111. if (is_cleared_to_first_seq_num_ &&
  112. AheadOf<uint16_t>(first_seq_num_, seq_num)) {
  113. return;
  114. }
  115. // If the packet buffer was cleared between a frame was created and returned.
  116. if (!first_packet_received_)
  117. return;
  118. // Avoid iterating over the buffer more than once by capping the number of
  119. // iterations to the |size_| of the buffer.
  120. ++seq_num;
  121. size_t diff = ForwardDiff<uint16_t>(first_seq_num_, seq_num);
  122. size_t iterations = std::min(diff, buffer_.size());
  123. for (size_t i = 0; i < iterations; ++i) {
  124. size_t index = first_seq_num_ % buffer_.size();
  125. if (AheadOf<uint16_t>(seq_num, buffer_[index].seq_num())) {
  126. delete[] buffer_[index].data.dataPtr;
  127. buffer_[index].data.dataPtr = nullptr;
  128. buffer_[index].used = false;
  129. }
  130. ++first_seq_num_;
  131. }
  132. // If |diff| is larger than |iterations| it means that we don't increment
  133. // |first_seq_num_| until we reach |seq_num|, so we set it here.
  134. first_seq_num_ = seq_num;
  135. is_cleared_to_first_seq_num_ = true;
  136. auto clear_to_it = missing_packets_.upper_bound(seq_num);
  137. if (clear_to_it != missing_packets_.begin()) {
  138. --clear_to_it;
  139. missing_packets_.erase(missing_packets_.begin(), clear_to_it);
  140. }
  141. }
  142. void PacketBuffer::ClearInterval(uint16_t start_seq_num,
  143. uint16_t stop_seq_num) {
  144. size_t iterations = ForwardDiff<uint16_t>(start_seq_num, stop_seq_num + 1);
  145. RTC_DCHECK_LE(iterations, buffer_.size());
  146. uint16_t seq_num = start_seq_num;
  147. for (size_t i = 0; i < iterations; ++i) {
  148. size_t index = seq_num % buffer_.size();
  149. RTC_DCHECK_EQ(buffer_[index].seq_num(), seq_num);
  150. delete[] buffer_[index].data.dataPtr;
  151. buffer_[index].data.dataPtr = nullptr;
  152. buffer_[index].used = false;
  153. ++seq_num;
  154. }
  155. }
  156. void PacketBuffer::Clear() {
  157. rtc::CritScope lock(&crit_);
  158. for (StoredPacket& entry : buffer_) {
  159. delete[] entry.data.dataPtr;
  160. entry.data.dataPtr = nullptr;
  161. entry.used = false;
  162. }
  163. first_packet_received_ = false;
  164. is_cleared_to_first_seq_num_ = false;
  165. last_received_packet_ms_.reset();
  166. last_received_keyframe_packet_ms_.reset();
  167. newest_inserted_seq_num_.reset();
  168. missing_packets_.clear();
  169. }
  170. void PacketBuffer::PaddingReceived(uint16_t seq_num) {
  171. std::vector<std::unique_ptr<RtpFrameObject>> found_frames;
  172. {
  173. rtc::CritScope lock(&crit_);
  174. UpdateMissingPackets(seq_num);
  175. found_frames = FindFrames(static_cast<uint16_t>(seq_num + 1));
  176. }
  177. for (std::unique_ptr<RtpFrameObject>& frame : found_frames)
  178. assembled_frame_callback_->OnAssembledFrame(std::move(frame));
  179. }
  180. absl::optional<int64_t> PacketBuffer::LastReceivedPacketMs() const {
  181. rtc::CritScope lock(&crit_);
  182. return last_received_packet_ms_;
  183. }
  184. absl::optional<int64_t> PacketBuffer::LastReceivedKeyframePacketMs() const {
  185. rtc::CritScope lock(&crit_);
  186. return last_received_keyframe_packet_ms_;
  187. }
  188. int PacketBuffer::GetUniqueFramesSeen() const {
  189. rtc::CritScope lock(&crit_);
  190. return unique_frames_seen_;
  191. }
  192. bool PacketBuffer::ExpandBufferSize() {
  193. if (buffer_.size() == max_size_) {
  194. RTC_LOG(LS_WARNING) << "PacketBuffer is already at max size (" << max_size_
  195. << "), failed to increase size.";
  196. return false;
  197. }
  198. size_t new_size = std::min(max_size_, 2 * buffer_.size());
  199. std::vector<StoredPacket> new_buffer(new_size);
  200. for (StoredPacket& entry : buffer_) {
  201. if (entry.used) {
  202. new_buffer[entry.seq_num() % new_size] = entry;
  203. }
  204. }
  205. buffer_ = std::move(new_buffer);
  206. RTC_LOG(LS_INFO) << "PacketBuffer size expanded to " << new_size;
  207. return true;
  208. }
  209. bool PacketBuffer::PotentialNewFrame(uint16_t seq_num) const {
  210. size_t index = seq_num % buffer_.size();
  211. int prev_index = index > 0 ? index - 1 : buffer_.size() - 1;
  212. const StoredPacket& entry = buffer_[index];
  213. const StoredPacket& prev_entry = buffer_[prev_index];
  214. if (!entry.used)
  215. return false;
  216. if (entry.seq_num() != seq_num)
  217. return false;
  218. if (entry.frame_begin())
  219. return true;
  220. if (!prev_entry.used)
  221. return false;
  222. if (prev_entry.seq_num() != static_cast<uint16_t>(entry.seq_num() - 1))
  223. return false;
  224. if (prev_entry.data.timestamp != entry.data.timestamp)
  225. return false;
  226. if (prev_entry.continuous)
  227. return true;
  228. return false;
  229. }
  230. std::vector<std::unique_ptr<RtpFrameObject>> PacketBuffer::FindFrames(
  231. uint16_t seq_num) {
  232. std::vector<std::unique_ptr<RtpFrameObject>> found_frames;
  233. for (size_t i = 0; i < buffer_.size() && PotentialNewFrame(seq_num); ++i) {
  234. size_t index = seq_num % buffer_.size();
  235. buffer_[index].continuous = true;
  236. // If all packets of the frame is continuous, find the first packet of the
  237. // frame and create an RtpFrameObject.
  238. if (buffer_[index].frame_end()) {
  239. size_t frame_size = 0;
  240. int max_nack_count = -1;
  241. uint16_t start_seq_num = seq_num;
  242. int64_t min_recv_time = buffer_[index].data.packet_info.receive_time_ms();
  243. int64_t max_recv_time = buffer_[index].data.packet_info.receive_time_ms();
  244. RtpPacketInfos::vector_type packet_infos;
  245. // Find the start index by searching backward until the packet with
  246. // the |frame_begin| flag is set.
  247. int start_index = index;
  248. size_t tested_packets = 0;
  249. int64_t frame_timestamp = buffer_[start_index].data.timestamp;
  250. // Identify H.264 keyframes by means of SPS, PPS, and IDR.
  251. bool is_h264 = buffer_[start_index].data.codec() == kVideoCodecH264;
  252. bool has_h264_sps = false;
  253. bool has_h264_pps = false;
  254. bool has_h264_idr = false;
  255. bool is_h264_keyframe = false;
  256. int idr_width = -1;
  257. int idr_height = -1;
  258. while (true) {
  259. ++tested_packets;
  260. frame_size += buffer_[start_index].data.sizeBytes;
  261. max_nack_count =
  262. std::max(max_nack_count, buffer_[start_index].data.timesNacked);
  263. min_recv_time =
  264. std::min(min_recv_time,
  265. buffer_[start_index].data.packet_info.receive_time_ms());
  266. max_recv_time =
  267. std::max(max_recv_time,
  268. buffer_[start_index].data.packet_info.receive_time_ms());
  269. // Should use |push_front()| since the loop traverses backwards. But
  270. // it's too inefficient to do so on a vector so we'll instead fix the
  271. // order afterwards.
  272. packet_infos.push_back(buffer_[start_index].data.packet_info);
  273. if (!is_h264 && buffer_[start_index].frame_begin())
  274. break;
  275. if (is_h264) {
  276. const auto* h264_header = absl::get_if<RTPVideoHeaderH264>(
  277. &buffer_[start_index].data.video_header.video_type_header);
  278. if (!h264_header || h264_header->nalus_length >= kMaxNalusPerPacket)
  279. return found_frames;
  280. for (size_t j = 0; j < h264_header->nalus_length; ++j) {
  281. if (h264_header->nalus[j].type == H264::NaluType::kSps) {
  282. has_h264_sps = true;
  283. } else if (h264_header->nalus[j].type == H264::NaluType::kPps) {
  284. has_h264_pps = true;
  285. } else if (h264_header->nalus[j].type == H264::NaluType::kIdr) {
  286. has_h264_idr = true;
  287. }
  288. }
  289. if ((sps_pps_idr_is_h264_keyframe_ && has_h264_idr && has_h264_sps &&
  290. has_h264_pps) ||
  291. (!sps_pps_idr_is_h264_keyframe_ && has_h264_idr)) {
  292. is_h264_keyframe = true;
  293. // Store the resolution of key frame which is the packet with
  294. // smallest index and valid resolution; typically its IDR or SPS
  295. // packet; there may be packet preceeding this packet, IDR's
  296. // resolution will be applied to them.
  297. if (buffer_[start_index].data.width() > 0 &&
  298. buffer_[start_index].data.height() > 0) {
  299. idr_width = buffer_[start_index].data.width();
  300. idr_height = buffer_[start_index].data.height();
  301. }
  302. }
  303. }
  304. if (tested_packets == buffer_.size())
  305. break;
  306. start_index = start_index > 0 ? start_index - 1 : buffer_.size() - 1;
  307. // In the case of H264 we don't have a frame_begin bit (yes,
  308. // |frame_begin| might be set to true but that is a lie). So instead
  309. // we traverese backwards as long as we have a previous packet and
  310. // the timestamp of that packet is the same as this one. This may cause
  311. // the PacketBuffer to hand out incomplete frames.
  312. // See: https://bugs.chromium.org/p/webrtc/issues/detail?id=7106
  313. if (is_h264 &&
  314. (!buffer_[start_index].used ||
  315. buffer_[start_index].data.timestamp != frame_timestamp)) {
  316. break;
  317. }
  318. --start_seq_num;
  319. }
  320. // Fix the order since the packet-finding loop traverses backwards.
  321. std::reverse(packet_infos.begin(), packet_infos.end());
  322. if (is_h264) {
  323. // Warn if this is an unsafe frame.
  324. if (has_h264_idr && (!has_h264_sps || !has_h264_pps)) {
  325. RTC_LOG(LS_WARNING)
  326. << "Received H.264-IDR frame "
  327. << "(SPS: " << has_h264_sps << ", PPS: " << has_h264_pps
  328. << "). Treating as "
  329. << (sps_pps_idr_is_h264_keyframe_ ? "delta" : "key")
  330. << " frame since WebRTC-SpsPpsIdrIsH264Keyframe is "
  331. << (sps_pps_idr_is_h264_keyframe_ ? "enabled." : "disabled");
  332. }
  333. // Now that we have decided whether to treat this frame as a key frame
  334. // or delta frame in the frame buffer, we update the field that
  335. // determines if the RtpFrameObject is a key frame or delta frame.
  336. const size_t first_packet_index = start_seq_num % buffer_.size();
  337. if (is_h264_keyframe) {
  338. buffer_[first_packet_index].data.video_header.frame_type =
  339. VideoFrameType::kVideoFrameKey;
  340. if (idr_width > 0 && idr_height > 0) {
  341. // IDR frame was finalized and we have the correct resolution for
  342. // IDR; update first packet to have same resolution as IDR.
  343. buffer_[first_packet_index].data.video_header.width = idr_width;
  344. buffer_[first_packet_index].data.video_header.height = idr_height;
  345. }
  346. } else {
  347. buffer_[first_packet_index].data.video_header.frame_type =
  348. VideoFrameType::kVideoFrameDelta;
  349. }
  350. // With IPPP, if this is not a keyframe, make sure there are no gaps
  351. // in the packet sequence numbers up until this point.
  352. const uint8_t h264tid =
  353. buffer_[start_index].data.video_header.frame_marking.temporal_id;
  354. if (h264tid == kNoTemporalIdx && !is_h264_keyframe &&
  355. missing_packets_.upper_bound(start_seq_num) !=
  356. missing_packets_.begin()) {
  357. return found_frames;
  358. }
  359. }
  360. missing_packets_.erase(missing_packets_.begin(),
  361. missing_packets_.upper_bound(seq_num));
  362. const VCMPacket* first_packet = GetPacket(start_seq_num);
  363. const VCMPacket* last_packet = GetPacket(seq_num);
  364. auto frame = std::make_unique<RtpFrameObject>(
  365. start_seq_num, seq_num, last_packet->markerBit, max_nack_count,
  366. min_recv_time, max_recv_time, first_packet->timestamp,
  367. first_packet->ntp_time_ms_, last_packet->video_header.video_timing,
  368. first_packet->payloadType, first_packet->codec(),
  369. last_packet->video_header.rotation,
  370. last_packet->video_header.content_type, first_packet->video_header,
  371. last_packet->video_header.color_space,
  372. first_packet->generic_descriptor,
  373. RtpPacketInfos(std::move(packet_infos)),
  374. GetEncodedImageBuffer(frame_size, start_seq_num, seq_num));
  375. found_frames.emplace_back(std::move(frame));
  376. ClearInterval(start_seq_num, seq_num);
  377. }
  378. ++seq_num;
  379. }
  380. return found_frames;
  381. }
  382. rtc::scoped_refptr<EncodedImageBuffer> PacketBuffer::GetEncodedImageBuffer(
  383. size_t frame_size,
  384. uint16_t first_seq_num,
  385. uint16_t last_seq_num) {
  386. size_t index = first_seq_num % buffer_.size();
  387. size_t end = (last_seq_num + 1) % buffer_.size();
  388. auto buffer = EncodedImageBuffer::Create(frame_size);
  389. size_t offset = 0;
  390. do {
  391. RTC_DCHECK(buffer_[index].used);
  392. size_t length = buffer_[index].data.sizeBytes;
  393. RTC_CHECK_LE(offset + length, buffer->size());
  394. memcpy(buffer->data() + offset, buffer_[index].data.dataPtr, length);
  395. offset += length;
  396. index = (index + 1) % buffer_.size();
  397. } while (index != end);
  398. return buffer;
  399. }
  400. VCMPacket* PacketBuffer::GetPacket(uint16_t seq_num) {
  401. StoredPacket& entry = buffer_[seq_num % buffer_.size()];
  402. if (!entry.used || seq_num != entry.seq_num()) {
  403. return nullptr;
  404. }
  405. return &entry.data;
  406. }
  407. void PacketBuffer::UpdateMissingPackets(uint16_t seq_num) {
  408. if (!newest_inserted_seq_num_)
  409. newest_inserted_seq_num_ = seq_num;
  410. const int kMaxPaddingAge = 1000;
  411. if (AheadOf(seq_num, *newest_inserted_seq_num_)) {
  412. uint16_t old_seq_num = seq_num - kMaxPaddingAge;
  413. auto erase_to = missing_packets_.lower_bound(old_seq_num);
  414. missing_packets_.erase(missing_packets_.begin(), erase_to);
  415. // Guard against inserting a large amount of missing packets if there is a
  416. // jump in the sequence number.
  417. if (AheadOf(old_seq_num, *newest_inserted_seq_num_))
  418. *newest_inserted_seq_num_ = old_seq_num;
  419. ++*newest_inserted_seq_num_;
  420. while (AheadOf(seq_num, *newest_inserted_seq_num_)) {
  421. missing_packets_.insert(*newest_inserted_seq_num_);
  422. ++*newest_inserted_seq_num_;
  423. }
  424. } else {
  425. missing_packets_.erase(seq_num);
  426. }
  427. }
  428. void PacketBuffer::OnTimestampReceived(uint32_t rtp_timestamp) {
  429. const size_t kMaxTimestampsHistory = 1000;
  430. if (rtp_timestamps_history_set_.insert(rtp_timestamp).second) {
  431. rtp_timestamps_history_queue_.push(rtp_timestamp);
  432. ++unique_frames_seen_;
  433. if (rtp_timestamps_history_set_.size() > kMaxTimestampsHistory) {
  434. uint32_t discarded_timestamp = rtp_timestamps_history_queue_.front();
  435. rtp_timestamps_history_set_.erase(discarded_timestamp);
  436. rtp_timestamps_history_queue_.pop();
  437. }
  438. }
  439. }
  440. } // namespace video_coding
  441. } // namespace webrtc