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.

309 lines
12 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /*
  2. * Copyright (c) 2019 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 "video/frame_encode_metadata_writer.h"
  11. #include <algorithm>
  12. #include <memory>
  13. #include <utility>
  14. #include "common_video/h264/sps_vui_rewriter.h"
  15. #include "modules/include/module_common_types_public.h"
  16. #include "modules/video_coding/include/video_coding_defines.h"
  17. #include "rtc_base/logging.h"
  18. #include "rtc_base/ref_counted_object.h"
  19. #include "rtc_base/time_utils.h"
  20. namespace webrtc {
  21. namespace {
  22. const int kMessagesThrottlingThreshold = 2;
  23. const int kThrottleRatio = 100000;
  24. class EncodedImageBufferWrapper : public EncodedImageBufferInterface {
  25. public:
  26. explicit EncodedImageBufferWrapper(rtc::Buffer&& buffer)
  27. : buffer_(std::move(buffer)) {}
  28. const uint8_t* data() const override { return buffer_.data(); }
  29. uint8_t* data() override { return buffer_.data(); }
  30. size_t size() const override { return buffer_.size(); }
  31. private:
  32. rtc::Buffer buffer_;
  33. };
  34. } // namespace
  35. FrameEncodeMetadataWriter::TimingFramesLayerInfo::TimingFramesLayerInfo() =
  36. default;
  37. FrameEncodeMetadataWriter::TimingFramesLayerInfo::~TimingFramesLayerInfo() =
  38. default;
  39. FrameEncodeMetadataWriter::FrameEncodeMetadataWriter(
  40. EncodedImageCallback* frame_drop_callback)
  41. : frame_drop_callback_(frame_drop_callback),
  42. internal_source_(false),
  43. framerate_fps_(0),
  44. last_timing_frame_time_ms_(-1),
  45. reordered_frames_logged_messages_(0),
  46. stalled_encoder_logged_messages_(0) {
  47. codec_settings_.timing_frame_thresholds = {-1, 0};
  48. }
  49. FrameEncodeMetadataWriter::~FrameEncodeMetadataWriter() {}
  50. void FrameEncodeMetadataWriter::OnEncoderInit(const VideoCodec& codec,
  51. bool internal_source) {
  52. rtc::CritScope cs(&lock_);
  53. codec_settings_ = codec;
  54. internal_source_ = internal_source;
  55. }
  56. void FrameEncodeMetadataWriter::OnSetRates(
  57. const VideoBitrateAllocation& bitrate_allocation,
  58. uint32_t framerate_fps) {
  59. rtc::CritScope cs(&lock_);
  60. framerate_fps_ = framerate_fps;
  61. const size_t num_spatial_layers = NumSpatialLayers();
  62. if (timing_frames_info_.size() < num_spatial_layers) {
  63. timing_frames_info_.resize(num_spatial_layers);
  64. }
  65. for (size_t i = 0; i < num_spatial_layers; ++i) {
  66. timing_frames_info_[i].target_bitrate_bytes_per_sec =
  67. bitrate_allocation.GetSpatialLayerSum(i) / 8;
  68. }
  69. }
  70. void FrameEncodeMetadataWriter::OnEncodeStarted(const VideoFrame& frame) {
  71. rtc::CritScope cs(&lock_);
  72. if (internal_source_) {
  73. return;
  74. }
  75. const size_t num_spatial_layers = NumSpatialLayers();
  76. timing_frames_info_.resize(num_spatial_layers);
  77. FrameMetadata metadata;
  78. metadata.rtp_timestamp = frame.timestamp();
  79. metadata.encode_start_time_ms = rtc::TimeMillis();
  80. metadata.ntp_time_ms = frame.ntp_time_ms();
  81. metadata.timestamp_us = frame.timestamp_us();
  82. metadata.rotation = frame.rotation();
  83. metadata.color_space = frame.color_space();
  84. metadata.packet_infos = frame.packet_infos();
  85. for (size_t si = 0; si < num_spatial_layers; ++si) {
  86. RTC_DCHECK(timing_frames_info_[si].frames.empty() ||
  87. rtc::TimeDiff(
  88. frame.render_time_ms(),
  89. timing_frames_info_[si].frames.back().timestamp_us / 1000) >=
  90. 0);
  91. // If stream is disabled due to low bandwidth OnEncodeStarted still will be
  92. // called and have to be ignored.
  93. if (timing_frames_info_[si].target_bitrate_bytes_per_sec == 0)
  94. return;
  95. if (timing_frames_info_[si].frames.size() == kMaxEncodeStartTimeListSize) {
  96. ++stalled_encoder_logged_messages_;
  97. if (stalled_encoder_logged_messages_ <= kMessagesThrottlingThreshold ||
  98. stalled_encoder_logged_messages_ % kThrottleRatio == 0) {
  99. RTC_LOG(LS_WARNING) << "Too many frames in the encode_start_list."
  100. " Did encoder stall?";
  101. if (stalled_encoder_logged_messages_ == kMessagesThrottlingThreshold) {
  102. RTC_LOG(LS_WARNING)
  103. << "Too many log messages. Further stalled encoder"
  104. "warnings will be throttled.";
  105. }
  106. }
  107. frame_drop_callback_->OnDroppedFrame(
  108. EncodedImageCallback::DropReason::kDroppedByEncoder);
  109. timing_frames_info_[si].frames.pop_front();
  110. }
  111. timing_frames_info_[si].frames.emplace_back(metadata);
  112. }
  113. }
  114. void FrameEncodeMetadataWriter::FillTimingInfo(size_t simulcast_svc_idx,
  115. EncodedImage* encoded_image) {
  116. rtc::CritScope cs(&lock_);
  117. absl::optional<size_t> outlier_frame_size;
  118. absl::optional<int64_t> encode_start_ms;
  119. uint8_t timing_flags = VideoSendTiming::kNotTriggered;
  120. int64_t encode_done_ms = rtc::TimeMillis();
  121. // Encoders with internal sources do not call OnEncodeStarted
  122. // |timing_frames_info_| may be not filled here.
  123. if (!internal_source_) {
  124. encode_start_ms =
  125. ExtractEncodeStartTimeAndFillMetadata(simulcast_svc_idx, encoded_image);
  126. }
  127. if (timing_frames_info_.size() > simulcast_svc_idx) {
  128. size_t target_bitrate =
  129. timing_frames_info_[simulcast_svc_idx].target_bitrate_bytes_per_sec;
  130. if (framerate_fps_ > 0 && target_bitrate > 0) {
  131. // framerate and target bitrate were reported by encoder.
  132. size_t average_frame_size = target_bitrate / framerate_fps_;
  133. outlier_frame_size.emplace(
  134. average_frame_size *
  135. codec_settings_.timing_frame_thresholds.outlier_ratio_percent / 100);
  136. }
  137. }
  138. // Outliers trigger timing frames, but do not affect scheduled timing
  139. // frames.
  140. if (outlier_frame_size && encoded_image->size() >= *outlier_frame_size) {
  141. timing_flags |= VideoSendTiming::kTriggeredBySize;
  142. }
  143. // Check if it's time to send a timing frame.
  144. int64_t timing_frame_delay_ms =
  145. encoded_image->capture_time_ms_ - last_timing_frame_time_ms_;
  146. // Trigger threshold if it's a first frame, too long passed since the last
  147. // timing frame, or we already sent timing frame on a different simulcast
  148. // stream with the same capture time.
  149. if (last_timing_frame_time_ms_ == -1 ||
  150. timing_frame_delay_ms >=
  151. codec_settings_.timing_frame_thresholds.delay_ms ||
  152. timing_frame_delay_ms == 0) {
  153. timing_flags |= VideoSendTiming::kTriggeredByTimer;
  154. last_timing_frame_time_ms_ = encoded_image->capture_time_ms_;
  155. }
  156. // Workaround for chromoting encoder: it passes encode start and finished
  157. // timestamps in |timing_| field, but they (together with capture timestamp)
  158. // are not in the WebRTC clock.
  159. if (internal_source_ && encoded_image->timing_.encode_finish_ms > 0 &&
  160. encoded_image->timing_.encode_start_ms > 0) {
  161. int64_t clock_offset_ms =
  162. encode_done_ms - encoded_image->timing_.encode_finish_ms;
  163. // Translate capture timestamp to local WebRTC clock.
  164. encoded_image->capture_time_ms_ += clock_offset_ms;
  165. encoded_image->SetTimestamp(
  166. static_cast<uint32_t>(encoded_image->capture_time_ms_ * 90));
  167. encode_start_ms.emplace(encoded_image->timing_.encode_start_ms +
  168. clock_offset_ms);
  169. }
  170. // If encode start is not available that means that encoder uses internal
  171. // source. In that case capture timestamp may be from a different clock with a
  172. // drift relative to rtc::TimeMillis(). We can't use it for Timing frames,
  173. // because to being sent in the network capture time required to be less than
  174. // all the other timestamps.
  175. if (encode_start_ms) {
  176. encoded_image->SetEncodeTime(*encode_start_ms, encode_done_ms);
  177. encoded_image->timing_.flags = timing_flags;
  178. } else {
  179. encoded_image->timing_.flags = VideoSendTiming::kInvalid;
  180. }
  181. }
  182. std::unique_ptr<RTPFragmentationHeader>
  183. FrameEncodeMetadataWriter::UpdateBitstream(
  184. const CodecSpecificInfo* codec_specific_info,
  185. const RTPFragmentationHeader* fragmentation,
  186. EncodedImage* encoded_image) {
  187. if (!codec_specific_info ||
  188. codec_specific_info->codecType != kVideoCodecH264 || !fragmentation ||
  189. encoded_image->_frameType != VideoFrameType::kVideoFrameKey) {
  190. return nullptr;
  191. }
  192. rtc::Buffer modified_buffer;
  193. std::unique_ptr<RTPFragmentationHeader> modified_fragmentation =
  194. std::make_unique<RTPFragmentationHeader>();
  195. modified_fragmentation->CopyFrom(*fragmentation);
  196. // Make sure that the data is not copied if owned by EncodedImage.
  197. const EncodedImage& buffer = *encoded_image;
  198. SpsVuiRewriter::ParseOutgoingBitstreamAndRewriteSps(
  199. buffer, fragmentation->fragmentationVectorSize,
  200. fragmentation->fragmentationOffset, fragmentation->fragmentationLength,
  201. encoded_image->ColorSpace(), &modified_buffer,
  202. modified_fragmentation->fragmentationOffset,
  203. modified_fragmentation->fragmentationLength);
  204. encoded_image->SetEncodedData(
  205. new rtc::RefCountedObject<EncodedImageBufferWrapper>(
  206. std::move(modified_buffer)));
  207. return modified_fragmentation;
  208. }
  209. void FrameEncodeMetadataWriter::Reset() {
  210. rtc::CritScope cs(&lock_);
  211. for (auto& info : timing_frames_info_) {
  212. info.frames.clear();
  213. }
  214. last_timing_frame_time_ms_ = -1;
  215. reordered_frames_logged_messages_ = 0;
  216. stalled_encoder_logged_messages_ = 0;
  217. }
  218. absl::optional<int64_t>
  219. FrameEncodeMetadataWriter::ExtractEncodeStartTimeAndFillMetadata(
  220. size_t simulcast_svc_idx,
  221. EncodedImage* encoded_image) {
  222. absl::optional<int64_t> result;
  223. size_t num_simulcast_svc_streams = timing_frames_info_.size();
  224. if (simulcast_svc_idx < num_simulcast_svc_streams) {
  225. auto metadata_list = &timing_frames_info_[simulcast_svc_idx].frames;
  226. // Skip frames for which there was OnEncodeStarted but no OnEncodedImage
  227. // call. These are dropped by encoder internally.
  228. // Because some hardware encoders don't preserve capture timestamp we
  229. // use RTP timestamps here.
  230. while (!metadata_list->empty() &&
  231. IsNewerTimestamp(encoded_image->Timestamp(),
  232. metadata_list->front().rtp_timestamp)) {
  233. frame_drop_callback_->OnDroppedFrame(
  234. EncodedImageCallback::DropReason::kDroppedByEncoder);
  235. metadata_list->pop_front();
  236. }
  237. encoded_image->content_type_ =
  238. (codec_settings_.mode == VideoCodecMode::kScreensharing)
  239. ? VideoContentType::SCREENSHARE
  240. : VideoContentType::UNSPECIFIED;
  241. if (!metadata_list->empty() &&
  242. metadata_list->front().rtp_timestamp == encoded_image->Timestamp()) {
  243. result.emplace(metadata_list->front().encode_start_time_ms);
  244. encoded_image->capture_time_ms_ =
  245. metadata_list->front().timestamp_us / 1000;
  246. encoded_image->ntp_time_ms_ = metadata_list->front().ntp_time_ms;
  247. encoded_image->rotation_ = metadata_list->front().rotation;
  248. encoded_image->SetColorSpace(metadata_list->front().color_space);
  249. encoded_image->SetPacketInfos(metadata_list->front().packet_infos);
  250. metadata_list->pop_front();
  251. } else {
  252. ++reordered_frames_logged_messages_;
  253. if (reordered_frames_logged_messages_ <= kMessagesThrottlingThreshold ||
  254. reordered_frames_logged_messages_ % kThrottleRatio == 0) {
  255. RTC_LOG(LS_WARNING) << "Frame with no encode started time recordings. "
  256. "Encoder may be reordering frames "
  257. "or not preserving RTP timestamps.";
  258. if (reordered_frames_logged_messages_ == kMessagesThrottlingThreshold) {
  259. RTC_LOG(LS_WARNING) << "Too many log messages. Further frames "
  260. "reordering warnings will be throttled.";
  261. }
  262. }
  263. }
  264. }
  265. return result;
  266. }
  267. size_t FrameEncodeMetadataWriter::NumSpatialLayers() const {
  268. size_t num_spatial_layers = codec_settings_.numberOfSimulcastStreams;
  269. if (codec_settings_.codecType == kVideoCodecVP9) {
  270. num_spatial_layers = std::max(
  271. num_spatial_layers,
  272. static_cast<size_t>(codec_settings_.VP9().numberOfSpatialLayers));
  273. }
  274. return std::max(num_spatial_layers, size_t{1});
  275. }
  276. } // namespace webrtc