Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(1006)

Side by Side Diff: media/cast/sender/vp8_encoder.cc

Issue 899583002: Revert of [Cast] Software encoder support for varying video frame sizes. (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Created 5 years, 10 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « media/cast/sender/vp8_encoder.h ('k') | media/cast/test/fake_media_source.h » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 // Copyright 2014 The Chromium Authors. All rights reserved. 1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "media/cast/sender/vp8_encoder.h" 5 #include "media/cast/sender/vp8_encoder.h"
6 6
7 #include "base/logging.h" 7 #include "base/logging.h"
8 #include "media/base/video_frame.h" 8 #include "media/base/video_frame.h"
9 #include "media/cast/cast_defines.h" 9 #include "media/cast/cast_defines.h"
10 #include "media/cast/net/cast_transport_config.h" 10 #include "media/cast/net/cast_transport_config.h"
(...skipping 10 matching lines...) Expand all
21 // pause in the video stream. 21 // pause in the video stream.
22 const int kRestartFramePeriods = 3; 22 const int kRestartFramePeriods = 3;
23 23
24 } // namespace 24 } // namespace
25 25
26 Vp8Encoder::Vp8Encoder(const VideoSenderConfig& video_config) 26 Vp8Encoder::Vp8Encoder(const VideoSenderConfig& video_config)
27 : cast_config_(video_config), 27 : cast_config_(video_config),
28 use_multiple_video_buffers_( 28 use_multiple_video_buffers_(
29 cast_config_.max_number_of_video_buffers_used == 29 cast_config_.max_number_of_video_buffers_used ==
30 kNumberOfVp8VideoBuffers), 30 kNumberOfVp8VideoBuffers),
31 raw_image_(nullptr),
31 key_frame_requested_(true), 32 key_frame_requested_(true),
32 bitrate_kbit_(cast_config_.start_bitrate / 1000),
33 last_encoded_frame_id_(kStartFrameId), 33 last_encoded_frame_id_(kStartFrameId),
34 last_acked_frame_id_(kStartFrameId), 34 last_acked_frame_id_(kStartFrameId),
35 undroppable_frames_(0) { 35 undroppable_frames_(0) {
36 config_.g_timebase.den = 0; // Not initialized. 36 config_.g_timebase.den = 0; // Not initialized.
37 37
38 // VP8 have 3 buffers available for prediction, with 38 // VP8 have 3 buffers available for prediction, with
39 // max_number_of_video_buffers_used set to 1 we maximize the coding efficiency 39 // max_number_of_video_buffers_used set to 1 we maximize the coding efficiency
40 // however in this mode we can not skip frames in the receiver to catch up 40 // however in this mode we can not skip frames in the receiver to catch up
41 // after a temporary network outage; with max_number_of_video_buffers_used 41 // after a temporary network outage; with max_number_of_video_buffers_used
42 // set to 3 we allow 2 frames to be skipped by the receiver without error 42 // set to 3 we allow 2 frames to be skipped by the receiver without error
43 // propagation. 43 // propagation.
44 DCHECK(cast_config_.max_number_of_video_buffers_used == 1 || 44 DCHECK(cast_config_.max_number_of_video_buffers_used == 1 ||
45 cast_config_.max_number_of_video_buffers_used == 45 cast_config_.max_number_of_video_buffers_used ==
46 kNumberOfVp8VideoBuffers) 46 kNumberOfVp8VideoBuffers)
47 << "Invalid argument"; 47 << "Invalid argument";
48 48
49 thread_checker_.DetachFromThread(); 49 thread_checker_.DetachFromThread();
50 } 50 }
51 51
52 Vp8Encoder::~Vp8Encoder() { 52 Vp8Encoder::~Vp8Encoder() {
53 DCHECK(thread_checker_.CalledOnValidThread()); 53 DCHECK(thread_checker_.CalledOnValidThread());
54 if (is_initialized()) 54 if (is_initialized())
55 vpx_codec_destroy(&encoder_); 55 vpx_codec_destroy(&encoder_);
56 vpx_img_free(raw_image_);
56 } 57 }
57 58
58 void Vp8Encoder::Initialize() { 59 void Vp8Encoder::Initialize() {
59 DCHECK(thread_checker_.CalledOnValidThread()); 60 DCHECK(thread_checker_.CalledOnValidThread());
60 DCHECK(!is_initialized()); 61 DCHECK(!is_initialized());
61 // The encoder will be created/configured when the first frame encode is
62 // requested.
63 }
64 62
65 void Vp8Encoder::ConfigureForNewFrameSize(const gfx::Size& frame_size) { 63 // Creating a wrapper to the image - setting image data to NULL. Actual
66 if (is_initialized()) { 64 // pointer will be set during encode. Setting align to 1, as it is
67 // Workaround for VP8 bug: If the new size is strictly less-than-or-equal to 65 // meaningless (actual memory is not allocated).
68 // the old size, in terms of area, the existing encoder instance can 66 raw_image_ = vpx_img_wrap(
69 // continue. Otherwise, completely tear-down and re-create a new encoder to 67 NULL, VPX_IMG_FMT_I420, cast_config_.width, cast_config_.height, 1, NULL);
70 // avoid a shutdown crash.
71 if (frame_size.GetArea() <= gfx::Size(config_.g_w, config_.g_h).GetArea()) {
72 DVLOG(1) << "Continuing to use existing encoder at smaller frame size: "
73 << gfx::Size(config_.g_w, config_.g_h).ToString() << " --> "
74 << frame_size.ToString();
75 config_.g_w = frame_size.width();
76 config_.g_h = frame_size.height();
77 CHECK_EQ(vpx_codec_enc_config_set(&encoder_, &config_), VPX_CODEC_OK)
78 << "Failed to update frame size in encoder config.";
79 return;
80 }
81
82 DVLOG(1) << "Destroying/Re-Creating encoder for larger frame size: "
83 << gfx::Size(config_.g_w, config_.g_h).ToString() << " --> "
84 << frame_size.ToString();
85 vpx_codec_destroy(&encoder_);
86 } else {
87 DVLOG(1) << "Creating encoder for the first frame; size: "
88 << frame_size.ToString();
89 }
90 68
91 for (int i = 0; i < kNumberOfVp8VideoBuffers; ++i) { 69 for (int i = 0; i < kNumberOfVp8VideoBuffers; ++i) {
92 buffer_state_[i].frame_id = kStartFrameId; 70 buffer_state_[i].frame_id = kStartFrameId;
93 buffer_state_[i].state = kBufferStartState; 71 buffer_state_[i].state = kBufferStartState;
94 } 72 }
95 73
96 // Populate encoder configuration with default values. 74 // Populate encoder configuration with default values.
97 CHECK_EQ(vpx_codec_enc_config_default(vpx_codec_vp8_cx(), &config_, 0), 75 if (vpx_codec_enc_config_default(vpx_codec_vp8_cx(), &config_, 0)) {
98 VPX_CODEC_OK); 76 NOTREACHED() << "Invalid return value";
77 config_.g_timebase.den = 0; // Do not call vpx_codec_destroy() in dtor.
78 return;
79 }
99 80
100 config_.g_threads = cast_config_.number_of_encode_threads; 81 config_.g_threads = cast_config_.number_of_encode_threads;
101 config_.g_w = frame_size.width(); 82 config_.g_w = cast_config_.width;
102 config_.g_h = frame_size.height(); 83 config_.g_h = cast_config_.height;
103 // Set the timebase to match that of base::TimeDelta. 84 // Set the timebase to match that of base::TimeDelta.
104 config_.g_timebase.num = 1; 85 config_.g_timebase.num = 1;
105 config_.g_timebase.den = base::Time::kMicrosecondsPerSecond; 86 config_.g_timebase.den = base::Time::kMicrosecondsPerSecond;
106 if (use_multiple_video_buffers_) { 87 if (use_multiple_video_buffers_) {
107 // We must enable error resilience when we use multiple buffers, due to 88 // We must enable error resilience when we use multiple buffers, due to
108 // codec requirements. 89 // codec requirements.
109 config_.g_error_resilient = 1; 90 config_.g_error_resilient = 1;
110 } 91 }
111 // |g_pass| and |g_lag_in_frames| must be "one pass" and zero, respectively,
112 // in order for VP8 to support changing frame sizes during encoding:
113 config_.g_pass = VPX_RC_ONE_PASS; 92 config_.g_pass = VPX_RC_ONE_PASS;
114 config_.g_lag_in_frames = 0; // Immediate data output for each frame. 93 config_.g_lag_in_frames = 0; // Immediate data output for each frame.
115 94
116 // Rate control settings. 95 // Rate control settings.
117 config_.rc_dropframe_thresh = 0; // The encoder may not drop any frames. 96 config_.rc_dropframe_thresh = 0; // The encoder may not drop any frames.
118 config_.rc_resize_allowed = 0; // TODO(miu): Why not? Investigate this. 97 config_.rc_resize_allowed = 0; // TODO(miu): Why not? Investigate this.
119 config_.rc_end_usage = VPX_CBR; 98 config_.rc_end_usage = VPX_CBR;
120 config_.rc_target_bitrate = bitrate_kbit_; 99 config_.rc_target_bitrate = cast_config_.start_bitrate / 1000; // In kbit/s.
121 config_.rc_min_quantizer = cast_config_.min_qp; 100 config_.rc_min_quantizer = cast_config_.min_qp;
122 config_.rc_max_quantizer = cast_config_.max_qp; 101 config_.rc_max_quantizer = cast_config_.max_qp;
123 // TODO(miu): Revisit these now that the encoder is being successfully 102 // TODO(miu): Revisit these now that the encoder is being successfully
124 // micro-managed. 103 // micro-managed.
125 config_.rc_undershoot_pct = 100; 104 config_.rc_undershoot_pct = 100;
126 config_.rc_overshoot_pct = 15; 105 config_.rc_overshoot_pct = 15;
127 // TODO(miu): Document why these rc_buf_*_sz values were chosen and/or 106 // TODO(miu): Document why these rc_buf_*_sz values were chosen and/or
128 // research for better values. Should they be computed from the target 107 // research for better values. Should they be computed from the target
129 // playout delay? 108 // playout delay?
130 config_.rc_buf_initial_sz = 500; 109 config_.rc_buf_initial_sz = 500;
131 config_.rc_buf_optimal_sz = 600; 110 config_.rc_buf_optimal_sz = 600;
132 config_.rc_buf_sz = 1000; 111 config_.rc_buf_sz = 1000;
133 112
134 config_.kf_mode = VPX_KF_DISABLED; 113 config_.kf_mode = VPX_KF_DISABLED;
135 114
136 vpx_codec_flags_t flags = 0; 115 vpx_codec_flags_t flags = 0;
137 CHECK_EQ(vpx_codec_enc_init(&encoder_, vpx_codec_vp8_cx(), &config_, flags), 116 if (vpx_codec_enc_init(&encoder_, vpx_codec_vp8_cx(), &config_, flags)) {
138 VPX_CODEC_OK); 117 NOTREACHED() << "vpx_codec_enc_init() failed.";
118 config_.g_timebase.den = 0; // Do not call vpx_codec_destroy() in dtor.
119 return;
120 }
139 121
140 // Raise the threshold for considering macroblocks as static. The default is 122 // Raise the threshold for considering macroblocks as static. The default is
141 // zero, so this setting makes the encoder less sensitive to motion. This 123 // zero, so this setting makes the encoder less sensitive to motion. This
142 // lowers the probability of needing to utilize more CPU to search for motion 124 // lowers the probability of needing to utilize more CPU to search for motion
143 // vectors. 125 // vectors.
144 CHECK_EQ(vpx_codec_control(&encoder_, VP8E_SET_STATIC_THRESHOLD, 1), 126 vpx_codec_control(&encoder_, VP8E_SET_STATIC_THRESHOLD, 1);
145 VPX_CODEC_OK);
146 127
147 // Improve quality by enabling sets of codec features that utilize more CPU. 128 // Improve quality by enabling sets of codec features that utilize more CPU.
148 // The default is zero, with increasingly more CPU to be used as the value is 129 // The default is zero, with increasingly more CPU to be used as the value is
149 // more negative. 130 // more negative.
150 // TODO(miu): Document why this value was chosen and expected behaviors. 131 // TODO(miu): Document why this value was chosen and expected behaviors.
151 // Should this be dynamic w.r.t. hardware performance? 132 // Should this be dynamic w.r.t. hardware performance?
152 CHECK_EQ(vpx_codec_control(&encoder_, VP8E_SET_CPUUSED, -6), VPX_CODEC_OK); 133 vpx_codec_control(&encoder_, VP8E_SET_CPUUSED, -6);
153 } 134 }
154 135
155 void Vp8Encoder::Encode(const scoped_refptr<media::VideoFrame>& video_frame, 136 void Vp8Encoder::Encode(const scoped_refptr<media::VideoFrame>& video_frame,
156 const base::TimeTicks& reference_time, 137 const base::TimeTicks& reference_time,
157 EncodedFrame* encoded_frame) { 138 EncodedFrame* encoded_frame) {
158 DCHECK(thread_checker_.CalledOnValidThread()); 139 DCHECK(thread_checker_.CalledOnValidThread());
159 DCHECK(encoded_frame); 140 DCHECK(encoded_frame);
160 141
161 // Initialize on-demand. Later, if the video frame size has changed, update 142 CHECK(is_initialized()); // No illegal reference to |config_| or |encoder_|.
162 // the encoder configuration. 143
163 const gfx::Size frame_size = video_frame->visible_rect().size(); 144 // Image in vpx_image_t format.
164 if (!is_initialized() || gfx::Size(config_.g_w, config_.g_h) != frame_size) 145 // Input image is const. VP8's raw image is not defined as const.
165 ConfigureForNewFrameSize(frame_size); 146 raw_image_->planes[VPX_PLANE_Y] =
147 const_cast<uint8*>(video_frame->data(VideoFrame::kYPlane));
148 raw_image_->planes[VPX_PLANE_U] =
149 const_cast<uint8*>(video_frame->data(VideoFrame::kUPlane));
150 raw_image_->planes[VPX_PLANE_V] =
151 const_cast<uint8*>(video_frame->data(VideoFrame::kVPlane));
152
153 raw_image_->stride[VPX_PLANE_Y] = video_frame->stride(VideoFrame::kYPlane);
154 raw_image_->stride[VPX_PLANE_U] = video_frame->stride(VideoFrame::kUPlane);
155 raw_image_->stride[VPX_PLANE_V] = video_frame->stride(VideoFrame::kVPlane);
166 156
167 uint32 latest_frame_id_to_reference; 157 uint32 latest_frame_id_to_reference;
168 Vp8Buffers buffer_to_update; 158 Vp8Buffers buffer_to_update;
169 vpx_codec_flags_t flags = 0; 159 vpx_codec_flags_t flags = 0;
170 if (key_frame_requested_) { 160 if (key_frame_requested_) {
171 flags = VPX_EFLAG_FORCE_KF; 161 flags = VPX_EFLAG_FORCE_KF;
172 // Self reference. 162 // Self reference.
173 latest_frame_id_to_reference = last_encoded_frame_id_ + 1; 163 latest_frame_id_to_reference = last_encoded_frame_id_ + 1;
174 // We can pick any buffer as buffer_to_update since we update 164 // We can pick any buffer as buffer_to_update since we update
175 // them all. 165 // them all.
176 buffer_to_update = kLastBuffer; 166 buffer_to_update = kLastBuffer;
177 } else { 167 } else {
178 // Reference all acked frames (buffers). 168 // Reference all acked frames (buffers).
179 latest_frame_id_to_reference = GetCodecReferenceFlags(&flags); 169 latest_frame_id_to_reference = GetCodecReferenceFlags(&flags);
180 buffer_to_update = GetNextBufferToUpdate(); 170 buffer_to_update = GetNextBufferToUpdate();
181 GetCodecUpdateFlags(buffer_to_update, &flags); 171 GetCodecUpdateFlags(buffer_to_update, &flags);
182 } 172 }
183 173
184 // Wrapper for vpx_codec_encode() to access the YUV data in the |video_frame|.
185 // Only the VISIBLE rectangle within |video_frame| is exposed to the codec.
186 vpx_image_t vpx_image;
187 vpx_image_t* const result = vpx_img_wrap(
188 &vpx_image,
189 VPX_IMG_FMT_I420,
190 frame_size.width(),
191 frame_size.height(),
192 1,
193 video_frame->data(VideoFrame::kYPlane));
194 DCHECK_EQ(result, &vpx_image);
195 vpx_image.planes[VPX_PLANE_Y] =
196 video_frame->visible_data(VideoFrame::kYPlane);
197 vpx_image.planes[VPX_PLANE_U] =
198 video_frame->visible_data(VideoFrame::kUPlane);
199 vpx_image.planes[VPX_PLANE_V] =
200 video_frame->visible_data(VideoFrame::kVPlane);
201 vpx_image.stride[VPX_PLANE_Y] = video_frame->stride(VideoFrame::kYPlane);
202 vpx_image.stride[VPX_PLANE_U] = video_frame->stride(VideoFrame::kUPlane);
203 vpx_image.stride[VPX_PLANE_V] = video_frame->stride(VideoFrame::kVPlane);
204
205 // The frame duration given to the VP8 codec affects a number of important 174 // The frame duration given to the VP8 codec affects a number of important
206 // behaviors, including: per-frame bandwidth, CPU time spent encoding, 175 // behaviors, including: per-frame bandwidth, CPU time spent encoding,
207 // temporal quality trade-offs, and key/golden/alt-ref frame generation 176 // temporal quality trade-offs, and key/golden/alt-ref frame generation
208 // intervals. Use the actual amount of time between the current and previous 177 // intervals. Use the actual amount of time between the current and previous
209 // frames as a prediction for the next frame's duration, but bound the 178 // frames as a prediction for the next frame's duration, but bound the
210 // prediction to account for the fact that the frame rate can be highly 179 // prediction to account for the fact that the frame rate can be highly
211 // variable, including long pauses in the video stream. 180 // variable, including long pauses in the video stream.
212 const base::TimeDelta minimum_frame_duration = 181 const base::TimeDelta minimum_frame_duration =
213 base::TimeDelta::FromSecondsD(1.0 / cast_config_.max_frame_rate); 182 base::TimeDelta::FromSecondsD(1.0 / cast_config_.max_frame_rate);
214 const base::TimeDelta maximum_frame_duration = 183 const base::TimeDelta maximum_frame_duration =
215 base::TimeDelta::FromSecondsD(static_cast<double>(kRestartFramePeriods) / 184 base::TimeDelta::FromSecondsD(static_cast<double>(kRestartFramePeriods) /
216 cast_config_.max_frame_rate); 185 cast_config_.max_frame_rate);
217 const base::TimeDelta last_frame_duration = 186 const base::TimeDelta last_frame_duration =
218 video_frame->timestamp() - last_frame_timestamp_; 187 video_frame->timestamp() - last_frame_timestamp_;
219 const base::TimeDelta predicted_frame_duration = 188 const base::TimeDelta predicted_frame_duration =
220 std::max(minimum_frame_duration, 189 std::max(minimum_frame_duration,
221 std::min(maximum_frame_duration, last_frame_duration)); 190 std::min(maximum_frame_duration, last_frame_duration));
222 last_frame_timestamp_ = video_frame->timestamp(); 191 last_frame_timestamp_ = video_frame->timestamp();
223 192
224 // Encode the frame. The presentation time stamp argument here is fixed to 193 // Encode the frame. The presentation time stamp argument here is fixed to
225 // zero to force the encoder to base its single-frame bandwidth calculations 194 // zero to force the encoder to base its single-frame bandwidth calculations
226 // entirely on |predicted_frame_duration| and the target bitrate setting being 195 // entirely on |predicted_frame_duration| and the target bitrate setting being
227 // micro-managed via calls to UpdateRates(). 196 // micro-managed via calls to UpdateRates().
228 CHECK_EQ(vpx_codec_encode(&encoder_, 197 CHECK_EQ(vpx_codec_encode(&encoder_,
229 &vpx_image, 198 raw_image_,
230 0, 199 0,
231 predicted_frame_duration.InMicroseconds(), 200 predicted_frame_duration.InMicroseconds(),
232 flags, 201 flags,
233 VPX_DL_REALTIME), 202 VPX_DL_REALTIME),
234 VPX_CODEC_OK) 203 VPX_CODEC_OK)
235 << "BUG: Invalid arguments passed to vpx_codec_encode()."; 204 << "BUG: Invalid arguments passed to vpx_codec_encode().";
236 205
237 // Pull data from the encoder, populating a new EncodedFrame. 206 // Pull data from the encoder, populating a new EncodedFrame.
238 encoded_frame->frame_id = ++last_encoded_frame_id_; 207 encoded_frame->frame_id = ++last_encoded_frame_id_;
239 const vpx_codec_cx_pkt_t* pkt = NULL; 208 const vpx_codec_cx_pkt_t* pkt = NULL;
(...skipping 186 matching lines...) Expand 10 before | Expand all | Expand 10 after
426 void Vp8Encoder::UpdateRates(uint32 new_bitrate) { 395 void Vp8Encoder::UpdateRates(uint32 new_bitrate) {
427 DCHECK(thread_checker_.CalledOnValidThread()); 396 DCHECK(thread_checker_.CalledOnValidThread());
428 397
429 if (!is_initialized()) 398 if (!is_initialized())
430 return; 399 return;
431 400
432 uint32 new_bitrate_kbit = new_bitrate / 1000; 401 uint32 new_bitrate_kbit = new_bitrate / 1000;
433 if (config_.rc_target_bitrate == new_bitrate_kbit) 402 if (config_.rc_target_bitrate == new_bitrate_kbit)
434 return; 403 return;
435 404
436 config_.rc_target_bitrate = bitrate_kbit_ = new_bitrate_kbit; 405 config_.rc_target_bitrate = new_bitrate_kbit;
437 406
438 // Update encoder context. 407 // Update encoder context.
439 if (vpx_codec_enc_config_set(&encoder_, &config_)) { 408 if (vpx_codec_enc_config_set(&encoder_, &config_)) {
440 NOTREACHED() << "Invalid return value"; 409 NOTREACHED() << "Invalid return value";
441 } 410 }
442 411
443 VLOG(1) << "VP8 new rc_target_bitrate: " << new_bitrate_kbit << " kbps"; 412 VLOG(1) << "VP8 new rc_target_bitrate: " << new_bitrate_kbit << " kbps";
444 } 413 }
445 414
446 void Vp8Encoder::LatestFrameIdToReference(uint32 frame_id) { 415 void Vp8Encoder::LatestFrameIdToReference(uint32 frame_id) {
(...skipping 13 matching lines...) Expand all
460 } 429 }
461 } 430 }
462 431
463 void Vp8Encoder::GenerateKeyFrame() { 432 void Vp8Encoder::GenerateKeyFrame() {
464 DCHECK(thread_checker_.CalledOnValidThread()); 433 DCHECK(thread_checker_.CalledOnValidThread());
465 key_frame_requested_ = true; 434 key_frame_requested_ = true;
466 } 435 }
467 436
468 } // namespace cast 437 } // namespace cast
469 } // namespace media 438 } // namespace media
OLDNEW
« no previous file with comments | « media/cast/sender/vp8_encoder.h ('k') | media/cast/test/fake_media_source.h » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698