blob: d2cbf7d7cbd0b1118eaa22c59264f252d45d51fa [file] [log] [blame]
Erik Språng6a7baa72019-02-26 18:31:00 +01001/*
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
Ilya Nikolaevskiy2ebf5232019-05-13 16:13:36 +020011#include "video/frame_encode_metadata_writer.h"
Erik Språng6a7baa72019-02-26 18:31:00 +010012
13#include <algorithm>
Niels Möller4d504c72019-06-18 15:56:56 +020014#include <utility>
Erik Språng6a7baa72019-02-26 18:31:00 +010015
Mirta Dvornicic28f0eb22019-05-28 16:30:16 +020016#include "absl/memory/memory.h"
17#include "common_video/h264/sps_vui_rewriter.h"
Erik Språng6a7baa72019-02-26 18:31:00 +010018#include "modules/include/module_common_types_public.h"
19#include "modules/video_coding/include/video_coding_defines.h"
20#include "rtc_base/logging.h"
Niels Möller4d504c72019-06-18 15:56:56 +020021#include "rtc_base/ref_counted_object.h"
Erik Språng6a7baa72019-02-26 18:31:00 +010022#include "rtc_base/time_utils.h"
23
24namespace webrtc {
25namespace {
26const int kMessagesThrottlingThreshold = 2;
27const int kThrottleRatio = 100000;
Niels Möller4d504c72019-06-18 15:56:56 +020028
29class EncodedImageBufferWrapper : public EncodedImageBufferInterface {
30 public:
31 explicit EncodedImageBufferWrapper(rtc::Buffer&& buffer)
32 : buffer_(std::move(buffer)) {}
33
34 const uint8_t* data() const override { return buffer_.data(); }
35 uint8_t* data() override { return buffer_.data(); }
36 size_t size() const override { return buffer_.size(); }
37
38 void Realloc(size_t t) override { RTC_NOTREACHED(); }
39
40 private:
41 rtc::Buffer buffer_;
42};
43
Erik Språng6a7baa72019-02-26 18:31:00 +010044} // namespace
45
Ilya Nikolaevskiy2ebf5232019-05-13 16:13:36 +020046FrameEncodeMetadataWriter::TimingFramesLayerInfo::TimingFramesLayerInfo() =
47 default;
48FrameEncodeMetadataWriter::TimingFramesLayerInfo::~TimingFramesLayerInfo() =
49 default;
Erik Språng6a7baa72019-02-26 18:31:00 +010050
Ilya Nikolaevskiy2ebf5232019-05-13 16:13:36 +020051FrameEncodeMetadataWriter::FrameEncodeMetadataWriter(
52 EncodedImageCallback* frame_drop_callback)
Erik Språng6a7baa72019-02-26 18:31:00 +010053 : frame_drop_callback_(frame_drop_callback),
54 internal_source_(false),
55 framerate_fps_(0),
56 last_timing_frame_time_ms_(-1),
Erik Språng6a7baa72019-02-26 18:31:00 +010057 reordered_frames_logged_messages_(0),
58 stalled_encoder_logged_messages_(0) {
59 codec_settings_.timing_frame_thresholds = {-1, 0};
60}
Ilya Nikolaevskiy2ebf5232019-05-13 16:13:36 +020061FrameEncodeMetadataWriter::~FrameEncodeMetadataWriter() {}
Erik Språng6a7baa72019-02-26 18:31:00 +010062
Ilya Nikolaevskiy2ebf5232019-05-13 16:13:36 +020063void FrameEncodeMetadataWriter::OnEncoderInit(const VideoCodec& codec,
64 bool internal_source) {
Erik Språng6a7baa72019-02-26 18:31:00 +010065 rtc::CritScope cs(&lock_);
66 codec_settings_ = codec;
67 internal_source_ = internal_source;
68}
69
Ilya Nikolaevskiy2ebf5232019-05-13 16:13:36 +020070void FrameEncodeMetadataWriter::OnSetRates(
Erik Språng6a7baa72019-02-26 18:31:00 +010071 const VideoBitrateAllocation& bitrate_allocation,
72 uint32_t framerate_fps) {
73 rtc::CritScope cs(&lock_);
74 framerate_fps_ = framerate_fps;
75 const size_t num_spatial_layers = NumSpatialLayers();
76 if (timing_frames_info_.size() < num_spatial_layers) {
77 timing_frames_info_.resize(num_spatial_layers);
78 }
79 for (size_t i = 0; i < num_spatial_layers; ++i) {
80 timing_frames_info_[i].target_bitrate_bytes_per_sec =
81 bitrate_allocation.GetSpatialLayerSum(i) / 8;
82 }
83}
84
Ilya Nikolaevskiy2ebf5232019-05-13 16:13:36 +020085void FrameEncodeMetadataWriter::OnEncodeStarted(const VideoFrame& frame) {
Erik Språng6a7baa72019-02-26 18:31:00 +010086 rtc::CritScope cs(&lock_);
87 if (internal_source_) {
88 return;
89 }
90
91 const size_t num_spatial_layers = NumSpatialLayers();
92 timing_frames_info_.resize(num_spatial_layers);
Ilya Nikolaevskiy2ebf5232019-05-13 16:13:36 +020093 FrameMetadata metadata;
94 metadata.rtp_timestamp = frame.timestamp();
95 metadata.encode_start_time_ms = rtc::TimeMillis();
96 metadata.ntp_time_ms = frame.ntp_time_ms();
97 metadata.timestamp_us = frame.timestamp_us();
98 metadata.rotation = frame.rotation();
99 metadata.color_space = frame.color_space();
Erik Språng6a7baa72019-02-26 18:31:00 +0100100 for (size_t si = 0; si < num_spatial_layers; ++si) {
Ilya Nikolaevskiy2ebf5232019-05-13 16:13:36 +0200101 RTC_DCHECK(timing_frames_info_[si].frames.empty() ||
102 rtc::TimeDiff(
103 frame.render_time_ms(),
104 timing_frames_info_[si].frames.back().timestamp_us / 1000) >=
105 0);
Erik Språng6a7baa72019-02-26 18:31:00 +0100106 // If stream is disabled due to low bandwidth OnEncodeStarted still will be
107 // called and have to be ignored.
108 if (timing_frames_info_[si].target_bitrate_bytes_per_sec == 0)
109 return;
Ilya Nikolaevskiy2ebf5232019-05-13 16:13:36 +0200110 if (timing_frames_info_[si].frames.size() == kMaxEncodeStartTimeListSize) {
Erik Språng6a7baa72019-02-26 18:31:00 +0100111 ++stalled_encoder_logged_messages_;
112 if (stalled_encoder_logged_messages_ <= kMessagesThrottlingThreshold ||
113 stalled_encoder_logged_messages_ % kThrottleRatio == 0) {
114 RTC_LOG(LS_WARNING) << "Too many frames in the encode_start_list."
115 " Did encoder stall?";
116 if (stalled_encoder_logged_messages_ == kMessagesThrottlingThreshold) {
117 RTC_LOG(LS_WARNING)
118 << "Too many log messages. Further stalled encoder"
119 "warnings will be throttled.";
120 }
121 }
122 frame_drop_callback_->OnDroppedFrame(
123 EncodedImageCallback::DropReason::kDroppedByEncoder);
Ilya Nikolaevskiy2ebf5232019-05-13 16:13:36 +0200124 timing_frames_info_[si].frames.pop_front();
Erik Språng6a7baa72019-02-26 18:31:00 +0100125 }
Ilya Nikolaevskiy2ebf5232019-05-13 16:13:36 +0200126 timing_frames_info_[si].frames.emplace_back(metadata);
Erik Språng6a7baa72019-02-26 18:31:00 +0100127 }
128}
129
Ilya Nikolaevskiy2ebf5232019-05-13 16:13:36 +0200130void FrameEncodeMetadataWriter::FillTimingInfo(size_t simulcast_svc_idx,
131 EncodedImage* encoded_image) {
Erik Språng6a7baa72019-02-26 18:31:00 +0100132 rtc::CritScope cs(&lock_);
133 absl::optional<size_t> outlier_frame_size;
134 absl::optional<int64_t> encode_start_ms;
135 uint8_t timing_flags = VideoSendTiming::kNotTriggered;
136
Ilya Nikolaevskiy2ebf5232019-05-13 16:13:36 +0200137 int64_t encode_done_ms = rtc::TimeMillis();
138
Erik Språng6a7baa72019-02-26 18:31:00 +0100139 // Encoders with internal sources do not call OnEncodeStarted
140 // |timing_frames_info_| may be not filled here.
141 if (!internal_source_) {
Ilya Nikolaevskiy2ebf5232019-05-13 16:13:36 +0200142 encode_start_ms =
143 ExtractEncodeStartTimeAndFillMetadata(simulcast_svc_idx, encoded_image);
Erik Språng6a7baa72019-02-26 18:31:00 +0100144 }
145
146 if (timing_frames_info_.size() > simulcast_svc_idx) {
147 size_t target_bitrate =
148 timing_frames_info_[simulcast_svc_idx].target_bitrate_bytes_per_sec;
149 if (framerate_fps_ > 0 && target_bitrate > 0) {
150 // framerate and target bitrate were reported by encoder.
151 size_t average_frame_size = target_bitrate / framerate_fps_;
152 outlier_frame_size.emplace(
153 average_frame_size *
154 codec_settings_.timing_frame_thresholds.outlier_ratio_percent / 100);
155 }
156 }
157
158 // Outliers trigger timing frames, but do not affect scheduled timing
159 // frames.
160 if (outlier_frame_size && encoded_image->size() >= *outlier_frame_size) {
161 timing_flags |= VideoSendTiming::kTriggeredBySize;
162 }
163
164 // Check if it's time to send a timing frame.
165 int64_t timing_frame_delay_ms =
166 encoded_image->capture_time_ms_ - last_timing_frame_time_ms_;
167 // Trigger threshold if it's a first frame, too long passed since the last
168 // timing frame, or we already sent timing frame on a different simulcast
169 // stream with the same capture time.
170 if (last_timing_frame_time_ms_ == -1 ||
171 timing_frame_delay_ms >=
172 codec_settings_.timing_frame_thresholds.delay_ms ||
173 timing_frame_delay_ms == 0) {
174 timing_flags |= VideoSendTiming::kTriggeredByTimer;
175 last_timing_frame_time_ms_ = encoded_image->capture_time_ms_;
176 }
177
178 // Workaround for chromoting encoder: it passes encode start and finished
179 // timestamps in |timing_| field, but they (together with capture timestamp)
180 // are not in the WebRTC clock.
181 if (internal_source_ && encoded_image->timing_.encode_finish_ms > 0 &&
182 encoded_image->timing_.encode_start_ms > 0) {
183 int64_t clock_offset_ms =
184 encode_done_ms - encoded_image->timing_.encode_finish_ms;
185 // Translate capture timestamp to local WebRTC clock.
186 encoded_image->capture_time_ms_ += clock_offset_ms;
187 encoded_image->SetTimestamp(
188 static_cast<uint32_t>(encoded_image->capture_time_ms_ * 90));
189 encode_start_ms.emplace(encoded_image->timing_.encode_start_ms +
190 clock_offset_ms);
191 }
192
193 // If encode start is not available that means that encoder uses internal
194 // source. In that case capture timestamp may be from a different clock with a
195 // drift relative to rtc::TimeMillis(). We can't use it for Timing frames,
196 // because to being sent in the network capture time required to be less than
197 // all the other timestamps.
198 if (encode_start_ms) {
199 encoded_image->SetEncodeTime(*encode_start_ms, encode_done_ms);
200 encoded_image->timing_.flags = timing_flags;
201 } else {
202 encoded_image->timing_.flags = VideoSendTiming::kInvalid;
203 }
204}
205
Mirta Dvornicic28f0eb22019-05-28 16:30:16 +0200206std::unique_ptr<RTPFragmentationHeader>
207FrameEncodeMetadataWriter::UpdateBitstream(
208 const CodecSpecificInfo* codec_specific_info,
209 const RTPFragmentationHeader* fragmentation,
210 EncodedImage* encoded_image) {
211 if (!codec_specific_info ||
212 codec_specific_info->codecType != kVideoCodecH264 || !fragmentation ||
213 encoded_image->_frameType != VideoFrameType::kVideoFrameKey) {
214 return nullptr;
215 }
216
Niels Möller4d504c72019-06-18 15:56:56 +0200217 rtc::Buffer modified_buffer;
Mirta Dvornicic28f0eb22019-05-28 16:30:16 +0200218 std::unique_ptr<RTPFragmentationHeader> modified_fragmentation =
219 absl::make_unique<RTPFragmentationHeader>();
220 modified_fragmentation->CopyFrom(*fragmentation);
221
222 // Make sure that the data is not copied if owned by EncodedImage.
223 const EncodedImage& buffer = *encoded_image;
224 SpsVuiRewriter::ParseOutgoingBitstreamAndRewriteSps(
225 buffer, fragmentation->fragmentationVectorSize,
226 fragmentation->fragmentationOffset, fragmentation->fragmentationLength,
Sergey Silkin0c0c9692019-06-12 14:27:34 +0200227 encoded_image->ColorSpace(), &modified_buffer,
228 modified_fragmentation->fragmentationOffset,
Mirta Dvornicic28f0eb22019-05-28 16:30:16 +0200229 modified_fragmentation->fragmentationLength);
230
Niels Möller4d504c72019-06-18 15:56:56 +0200231 encoded_image->SetEncodedData(
232 new rtc::RefCountedObject<EncodedImageBufferWrapper>(
233 std::move(modified_buffer)));
Mirta Dvornicic28f0eb22019-05-28 16:30:16 +0200234
235 return modified_fragmentation;
236}
237
Ilya Nikolaevskiy2ebf5232019-05-13 16:13:36 +0200238void FrameEncodeMetadataWriter::Reset() {
Erik Språng6a7baa72019-02-26 18:31:00 +0100239 rtc::CritScope cs(&lock_);
Ilya Nikolaevskiyba96e2f2019-06-04 15:15:14 +0200240 for (auto& info : timing_frames_info_) {
241 info.frames.clear();
242 }
Erik Språng6a7baa72019-02-26 18:31:00 +0100243 last_timing_frame_time_ms_ = -1;
244 reordered_frames_logged_messages_ = 0;
245 stalled_encoder_logged_messages_ = 0;
246}
247
Ilya Nikolaevskiy2ebf5232019-05-13 16:13:36 +0200248absl::optional<int64_t>
249FrameEncodeMetadataWriter::ExtractEncodeStartTimeAndFillMetadata(
Erik Språng6a7baa72019-02-26 18:31:00 +0100250 size_t simulcast_svc_idx,
251 EncodedImage* encoded_image) {
252 absl::optional<int64_t> result;
253 size_t num_simulcast_svc_streams = timing_frames_info_.size();
254 if (simulcast_svc_idx < num_simulcast_svc_streams) {
Ilya Nikolaevskiy2ebf5232019-05-13 16:13:36 +0200255 auto metadata_list = &timing_frames_info_[simulcast_svc_idx].frames;
Erik Språng6a7baa72019-02-26 18:31:00 +0100256 // Skip frames for which there was OnEncodeStarted but no OnEncodedImage
257 // call. These are dropped by encoder internally.
258 // Because some hardware encoders don't preserve capture timestamp we
259 // use RTP timestamps here.
Ilya Nikolaevskiy2ebf5232019-05-13 16:13:36 +0200260 while (!metadata_list->empty() &&
Erik Språng6a7baa72019-02-26 18:31:00 +0100261 IsNewerTimestamp(encoded_image->Timestamp(),
Ilya Nikolaevskiy2ebf5232019-05-13 16:13:36 +0200262 metadata_list->front().rtp_timestamp)) {
Erik Språng6a7baa72019-02-26 18:31:00 +0100263 frame_drop_callback_->OnDroppedFrame(
264 EncodedImageCallback::DropReason::kDroppedByEncoder);
Ilya Nikolaevskiy2ebf5232019-05-13 16:13:36 +0200265 metadata_list->pop_front();
Erik Språng6a7baa72019-02-26 18:31:00 +0100266 }
Ilya Nikolaevskiyba96e2f2019-06-04 15:15:14 +0200267
268 encoded_image->content_type_ =
269 (codec_settings_.mode == VideoCodecMode::kScreensharing)
270 ? VideoContentType::SCREENSHARE
271 : VideoContentType::UNSPECIFIED;
272
Ilya Nikolaevskiy2ebf5232019-05-13 16:13:36 +0200273 if (!metadata_list->empty() &&
274 metadata_list->front().rtp_timestamp == encoded_image->Timestamp()) {
275 result.emplace(metadata_list->front().encode_start_time_ms);
Ilya Nikolaevskiy2ebf5232019-05-13 16:13:36 +0200276 encoded_image->capture_time_ms_ =
277 metadata_list->front().timestamp_us / 1000;
278 encoded_image->ntp_time_ms_ = metadata_list->front().ntp_time_ms;
279 encoded_image->rotation_ = metadata_list->front().rotation;
280 encoded_image->SetColorSpace(metadata_list->front().color_space);
Ilya Nikolaevskiy2ebf5232019-05-13 16:13:36 +0200281 metadata_list->pop_front();
Erik Språng6a7baa72019-02-26 18:31:00 +0100282 } else {
283 ++reordered_frames_logged_messages_;
284 if (reordered_frames_logged_messages_ <= kMessagesThrottlingThreshold ||
285 reordered_frames_logged_messages_ % kThrottleRatio == 0) {
286 RTC_LOG(LS_WARNING) << "Frame with no encode started time recordings. "
287 "Encoder may be reordering frames "
288 "or not preserving RTP timestamps.";
289 if (reordered_frames_logged_messages_ == kMessagesThrottlingThreshold) {
290 RTC_LOG(LS_WARNING) << "Too many log messages. Further frames "
291 "reordering warnings will be throttled.";
292 }
293 }
294 }
295 }
296 return result;
297}
298
Ilya Nikolaevskiy2ebf5232019-05-13 16:13:36 +0200299size_t FrameEncodeMetadataWriter::NumSpatialLayers() const {
Erik Språng6a7baa72019-02-26 18:31:00 +0100300 size_t num_spatial_layers = codec_settings_.numberOfSimulcastStreams;
301 if (codec_settings_.codecType == kVideoCodecVP9) {
302 num_spatial_layers = std::max(
303 num_spatial_layers,
304 static_cast<size_t>(codec_settings_.VP9().numberOfSpatialLayers));
305 }
306 return std::max(num_spatial_layers, size_t{1});
307}
308
309} // namespace webrtc