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

Side by Side Diff: webrtc/modules/video_coding/codecs/h264/h264_video_toolbox_encoder.cc

Issue 1660963002: Bitrate controller for VideoToolbox encoder. (Closed) Base URL: https://chromium.googlesource.com/external/webrtc.git@master
Patch Set: Fix UT Created 4 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
OLDNEW
1 /* 1 /*
2 * Copyright (c) 2015 The WebRTC project authors. All Rights Reserved. 2 * Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.
3 * 3 *
4 * Use of this source code is governed by a BSD-style license 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 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 6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may 7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree. 8 * be found in the AUTHORS file in the root of the source tree.
9 * 9 *
10 */ 10 */
11 11
12 #include "webrtc/modules/video_coding/codecs/h264/h264_video_toolbox_encoder.h" 12 #include "webrtc/modules/video_coding/codecs/h264/h264_video_toolbox_encoder.h"
13 13
14 #if defined(WEBRTC_VIDEO_TOOLBOX_SUPPORTED) 14 #if defined(WEBRTC_VIDEO_TOOLBOX_SUPPORTED)
15 15
16 #include <string> 16 #include <string>
17 #include <vector> 17 #include <vector>
18 18
19 #include "libyuv/convert_from.h" 19 #include "libyuv/convert_from.h"
20 #include "webrtc/base/checks.h" 20 #include "webrtc/base/checks.h"
21 #include "webrtc/base/logging.h" 21 #include "webrtc/base/logging.h"
22 #include "webrtc/base/scoped_ptr.h" 22 #include "webrtc/base/scoped_ptr.h"
23 #include "webrtc/modules/video_coding/codecs/h264/h264_video_toolbox_nalu.h" 23 #include "webrtc/modules/video_coding/codecs/h264/h264_video_toolbox_nalu.h"
24 #include "webrtc/system_wrappers/include/clock.h"
24 25
25 namespace internal { 26 namespace internal {
26 27
27 // Convenience function for creating a dictionary. 28 // Convenience function for creating a dictionary.
28 inline CFDictionaryRef CreateCFDictionary(CFTypeRef* keys, 29 inline CFDictionaryRef CreateCFDictionary(CFTypeRef* keys,
29 CFTypeRef* values, 30 CFTypeRef* values,
30 size_t size) { 31 size_t size) {
31 return CFDictionaryCreate(kCFAllocatorDefault, keys, values, size, 32 return CFDictionaryCreate(kCFAllocatorDefault, keys, values, size,
32 &kCFTypeDictionaryKeyCallBacks, 33 &kCFTypeDictionaryKeyCallBacks,
33 &kCFTypeDictionaryValueCallBacks); 34 &kCFTypeDictionaryValueCallBacks);
(...skipping 26 matching lines...) Expand all
60 OSStatus status = VTSessionSetProperty(session, key, cfNum); 61 OSStatus status = VTSessionSetProperty(session, key, cfNum);
61 CFRelease(cfNum); 62 CFRelease(cfNum);
62 if (status != noErr) { 63 if (status != noErr) {
63 std::string key_string = CFStringToString(key); 64 std::string key_string = CFStringToString(key);
64 LOG(LS_ERROR) << "VTSessionSetProperty failed to set: " << key_string 65 LOG(LS_ERROR) << "VTSessionSetProperty failed to set: " << key_string
65 << " to " << value << ": " << status; 66 << " to " << value << ": " << status;
66 } 67 }
67 } 68 }
68 69
69 // Convenience function for setting a VT property. 70 // Convenience function for setting a VT property.
71 void SetVTSessionProperty(VTSessionRef session,
72 CFStringRef key,
73 uint32_t value) {
74 int64_t value_64 = value;
75 CFNumberRef cfNum =
76 CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt64Type, &value_64);
77 OSStatus status = VTSessionSetProperty(session, key, cfNum);
78 CFRelease(cfNum);
79 if (status != noErr) {
80 std::string key_string = CFStringToString(key);
81 LOG(LS_ERROR) << "VTSessionSetProperty failed to set: " << key_string
82 << " to " << value << ": " << status;
83 }
84 }
85
86 // Convenience function for setting a VT property.
70 void SetVTSessionProperty(VTSessionRef session, CFStringRef key, bool value) { 87 void SetVTSessionProperty(VTSessionRef session, CFStringRef key, bool value) {
71 CFBooleanRef cf_bool = (value) ? kCFBooleanTrue : kCFBooleanFalse; 88 CFBooleanRef cf_bool = (value) ? kCFBooleanTrue : kCFBooleanFalse;
72 OSStatus status = VTSessionSetProperty(session, key, cf_bool); 89 OSStatus status = VTSessionSetProperty(session, key, cf_bool);
73 if (status != noErr) { 90 if (status != noErr) {
74 std::string key_string = CFStringToString(key); 91 std::string key_string = CFStringToString(key);
75 LOG(LS_ERROR) << "VTSessionSetProperty failed to set: " << key_string 92 LOG(LS_ERROR) << "VTSessionSetProperty failed to set: " << key_string
76 << " to " << value << ": " << status; 93 << " to " << value << ": " << status;
77 } 94 }
78 } 95 }
79 96
80 // Convenience function for setting a VT property. 97 // Convenience function for setting a VT property.
81 void SetVTSessionProperty(VTSessionRef session, 98 void SetVTSessionProperty(VTSessionRef session,
82 CFStringRef key, 99 CFStringRef key,
83 CFStringRef value) { 100 CFStringRef value) {
84 OSStatus status = VTSessionSetProperty(session, key, value); 101 OSStatus status = VTSessionSetProperty(session, key, value);
85 if (status != noErr) { 102 if (status != noErr) {
86 std::string key_string = CFStringToString(key); 103 std::string key_string = CFStringToString(key);
87 std::string val_string = CFStringToString(value); 104 std::string val_string = CFStringToString(value);
88 LOG(LS_ERROR) << "VTSessionSetProperty failed to set: " << key_string 105 LOG(LS_ERROR) << "VTSessionSetProperty failed to set: " << key_string
89 << " to " << val_string << ": " << status; 106 << " to " << val_string << ": " << status;
90 } 107 }
91 } 108 }
92 109
93 // Struct that we pass to the encoder per frame to encode. We receive it again 110 // Struct that we pass to the encoder per frame to encode. We receive it again
94 // in the encoder callback. 111 // in the encoder callback.
95 struct FrameEncodeParams { 112 struct FrameEncodeParams {
96 FrameEncodeParams(webrtc::EncodedImageCallback* cb, 113 FrameEncodeParams(webrtc::H264VideoToolboxEncoder* e,
97 const webrtc::CodecSpecificInfo* csi, 114 const webrtc::CodecSpecificInfo* csi,
98 int32_t w, 115 int32_t w,
99 int32_t h, 116 int32_t h,
100 int64_t rtms, 117 int64_t rtms,
101 uint32_t ts) 118 uint32_t ts)
102 : callback(cb), width(w), height(h), render_time_ms(rtms), timestamp(ts) { 119 : encoder(e), width(w), height(h), render_time_ms(rtms), timestamp(ts) {
103 if (csi) { 120 if (csi) {
104 codec_specific_info = *csi; 121 codec_specific_info = *csi;
105 } else { 122 } else {
106 codec_specific_info.codecType = webrtc::kVideoCodecH264; 123 codec_specific_info.codecType = webrtc::kVideoCodecH264;
107 } 124 }
108 } 125 }
109 webrtc::EncodedImageCallback* callback; 126
127 webrtc::H264VideoToolboxEncoder* encoder;
110 webrtc::CodecSpecificInfo codec_specific_info; 128 webrtc::CodecSpecificInfo codec_specific_info;
111 int32_t width; 129 int32_t width;
112 int32_t height; 130 int32_t height;
113 int64_t render_time_ms; 131 int64_t render_time_ms;
114 uint32_t timestamp; 132 uint32_t timestamp;
115 }; 133 };
116 134
117 // We receive I420Frames as input, but we need to feed CVPixelBuffers into the 135 // We receive I420Frames as input, but we need to feed CVPixelBuffers into the
118 // encoder. This performs the copy and format conversion. 136 // encoder. This performs the copy and format conversion.
119 // TODO(tkchin): See if encoder will accept i420 frames and compare performance. 137 // TODO(tkchin): See if encoder will accept i420 frames and compare performance.
(...skipping 26 matching lines...) Expand all
146 dst_stride_y, dst_uv, dst_stride_uv, frame.width(), frame.height()); 164 dst_stride_y, dst_uv, dst_stride_uv, frame.width(), frame.height());
147 CVPixelBufferUnlockBaseAddress(pixel_buffer, 0); 165 CVPixelBufferUnlockBaseAddress(pixel_buffer, 0);
148 if (ret) { 166 if (ret) {
149 LOG(LS_ERROR) << "Error converting I420 VideoFrame to NV12 :" << ret; 167 LOG(LS_ERROR) << "Error converting I420 VideoFrame to NV12 :" << ret;
150 return false; 168 return false;
151 } 169 }
152 return true; 170 return true;
153 } 171 }
154 172
155 // This is the callback function that VideoToolbox calls when encode is 173 // This is the callback function that VideoToolbox calls when encode is
156 // complete. 174 // complete. From inspection this happens on its own queue.
157 void VTCompressionOutputCallback(void* encoder, 175 void VTCompressionOutputCallback(void* encoder,
158 void* params, 176 void* params,
159 OSStatus status, 177 OSStatus status,
160 VTEncodeInfoFlags info_flags, 178 VTEncodeInfoFlags info_flags,
161 CMSampleBufferRef sample_buffer) { 179 CMSampleBufferRef sample_buffer) {
162 rtc::scoped_ptr<FrameEncodeParams> encode_params( 180 rtc::scoped_ptr<FrameEncodeParams> encode_params(
163 reinterpret_cast<FrameEncodeParams*>(params)); 181 reinterpret_cast<FrameEncodeParams*>(params));
164 if (status != noErr) { 182 encode_params->encoder->OnEncodedFrame(
165 LOG(LS_ERROR) << "H264 encoding failed."; 183 status, info_flags, sample_buffer, encode_params->codec_specific_info,
166 return; 184 encode_params->width, encode_params->height,
167 } 185 encode_params->render_time_ms, encode_params->timestamp);
168 if (info_flags & kVTEncodeInfo_FrameDropped) {
169 LOG(LS_INFO) << "H264 encode dropped frame.";
170 }
171
172 bool is_keyframe = false;
173 CFArrayRef attachments =
174 CMSampleBufferGetSampleAttachmentsArray(sample_buffer, 0);
175 if (attachments != nullptr && CFArrayGetCount(attachments)) {
176 CFDictionaryRef attachment =
177 static_cast<CFDictionaryRef>(CFArrayGetValueAtIndex(attachments, 0));
178 is_keyframe =
179 !CFDictionaryContainsKey(attachment, kCMSampleAttachmentKey_NotSync);
180 }
181
182 // Convert the sample buffer into a buffer suitable for RTP packetization.
183 // TODO(tkchin): Allocate buffers through a pool.
184 rtc::scoped_ptr<rtc::Buffer> buffer(new rtc::Buffer());
185 rtc::scoped_ptr<webrtc::RTPFragmentationHeader> header;
186 if (!H264CMSampleBufferToAnnexBBuffer(sample_buffer, is_keyframe,
187 buffer.get(), header.accept())) {
188 return;
189 }
190 webrtc::EncodedImage frame(buffer->data(), buffer->size(), buffer->size());
191 frame._encodedWidth = encode_params->width;
192 frame._encodedHeight = encode_params->height;
193 frame._completeFrame = true;
194 frame._frameType =
195 is_keyframe ? webrtc::kVideoFrameKey : webrtc::kVideoFrameDelta;
196 frame.capture_time_ms_ = encode_params->render_time_ms;
197 frame._timeStamp = encode_params->timestamp;
198
199 int result = encode_params->callback->Encoded(
200 frame, &(encode_params->codec_specific_info), header.get());
201 if (result != 0) {
202 LOG(LS_ERROR) << "Encoded callback failed: " << result;
203 }
204 } 186 }
205 187
206 } // namespace internal 188 } // namespace internal
207 189
208 namespace webrtc { 190 namespace webrtc {
209 191
210 H264VideoToolboxEncoder::H264VideoToolboxEncoder() 192 H264VideoToolboxEncoder::H264VideoToolboxEncoder()
211 : callback_(nullptr), compression_session_(nullptr) {} 193 : callback_(nullptr),
194 compression_session_(nullptr),
195 bitrate_adjuster_(Clock::GetRealTimeClock()) {}
212 196
213 H264VideoToolboxEncoder::~H264VideoToolboxEncoder() { 197 H264VideoToolboxEncoder::~H264VideoToolboxEncoder() {
214 DestroyCompressionSession(); 198 DestroyCompressionSession();
215 } 199 }
216 200
217 int H264VideoToolboxEncoder::InitEncode(const VideoCodec* codec_settings, 201 int H264VideoToolboxEncoder::InitEncode(const VideoCodec* codec_settings,
218 int number_of_cores, 202 int number_of_cores,
219 size_t max_payload_size) { 203 size_t max_payload_size) {
220 RTC_DCHECK(codec_settings); 204 RTC_DCHECK(codec_settings);
221 RTC_DCHECK_EQ(codec_settings->codecType, kVideoCodecH264); 205 RTC_DCHECK_EQ(codec_settings->codecType, kVideoCodecH264);
222 // TODO(tkchin): We may need to enforce width/height dimension restrictions 206 // TODO(tkchin): We may need to enforce width/height dimension restrictions
223 // to match what the encoder supports. 207 // to match what the encoder supports.
224 width_ = codec_settings->width; 208 width_ = codec_settings->width;
225 height_ = codec_settings->height; 209 height_ = codec_settings->height;
226 // We can only set average bitrate on the HW encoder. 210 // We can only set average bitrate on the HW encoder.
227 bitrate_ = codec_settings->startBitrate * 1000; 211 target_bitrate_bps_ = codec_settings->startBitrate;
212 bitrate_adjuster_.SetTargetBitrateBps(target_bitrate_bps_);
228 213
229 // TODO(tkchin): Try setting payload size via 214 // TODO(tkchin): Try setting payload size via
230 // kVTCompressionPropertyKey_MaxH264SliceBytes. 215 // kVTCompressionPropertyKey_MaxH264SliceBytes.
231 216
232 return ResetCompressionSession(); 217 return ResetCompressionSession();
233 } 218 }
234 219
235 int H264VideoToolboxEncoder::Encode( 220 int H264VideoToolboxEncoder::Encode(
236 const VideoFrame& input_image, 221 const VideoFrame& input_image,
237 const CodecSpecificInfo* codec_specific_info, 222 const CodecSpecificInfo* codec_specific_info,
(...skipping 42 matching lines...) Expand 10 before | Expand all | Expand 10 after
280 CMTime presentation_time_stamp = 265 CMTime presentation_time_stamp =
281 CMTimeMake(input_image.render_time_ms(), 1000); 266 CMTimeMake(input_image.render_time_ms(), 1000);
282 CFDictionaryRef frame_properties = nullptr; 267 CFDictionaryRef frame_properties = nullptr;
283 if (is_keyframe_required) { 268 if (is_keyframe_required) {
284 CFTypeRef keys[] = {kVTEncodeFrameOptionKey_ForceKeyFrame}; 269 CFTypeRef keys[] = {kVTEncodeFrameOptionKey_ForceKeyFrame};
285 CFTypeRef values[] = {kCFBooleanTrue}; 270 CFTypeRef values[] = {kCFBooleanTrue};
286 frame_properties = internal::CreateCFDictionary(keys, values, 1); 271 frame_properties = internal::CreateCFDictionary(keys, values, 1);
287 } 272 }
288 rtc::scoped_ptr<internal::FrameEncodeParams> encode_params; 273 rtc::scoped_ptr<internal::FrameEncodeParams> encode_params;
289 encode_params.reset(new internal::FrameEncodeParams( 274 encode_params.reset(new internal::FrameEncodeParams(
290 callback_, codec_specific_info, width_, height_, 275 this, codec_specific_info, width_, height_, input_image.render_time_ms(),
291 input_image.render_time_ms(), input_image.timestamp())); 276 input_image.timestamp()));
277
278 // Update the bitrate if needed.
279 SetBitrateBps(bitrate_adjuster_.GetAdjustedBitrateBps());
280
292 VTCompressionSessionEncodeFrame( 281 VTCompressionSessionEncodeFrame(
293 compression_session_, pixel_buffer, presentation_time_stamp, 282 compression_session_, pixel_buffer, presentation_time_stamp,
294 kCMTimeInvalid, frame_properties, encode_params.release(), nullptr); 283 kCMTimeInvalid, frame_properties, encode_params.release(), nullptr);
295 if (frame_properties) { 284 if (frame_properties) {
296 CFRelease(frame_properties); 285 CFRelease(frame_properties);
297 } 286 }
298 if (pixel_buffer) { 287 if (pixel_buffer) {
299 CVBufferRelease(pixel_buffer); 288 CVBufferRelease(pixel_buffer);
300 } 289 }
301 return WEBRTC_VIDEO_CODEC_OK; 290 return WEBRTC_VIDEO_CODEC_OK;
302 } 291 }
303 292
304 int H264VideoToolboxEncoder::RegisterEncodeCompleteCallback( 293 int H264VideoToolboxEncoder::RegisterEncodeCompleteCallback(
305 EncodedImageCallback* callback) { 294 EncodedImageCallback* callback) {
306 callback_ = callback; 295 callback_ = callback;
307 return WEBRTC_VIDEO_CODEC_OK; 296 return WEBRTC_VIDEO_CODEC_OK;
308 } 297 }
309 298
310 int H264VideoToolboxEncoder::SetChannelParameters(uint32_t packet_loss, 299 int H264VideoToolboxEncoder::SetChannelParameters(uint32_t packet_loss,
311 int64_t rtt) { 300 int64_t rtt) {
312 // Encoder doesn't know anything about packet loss or rtt so just return. 301 // Encoder doesn't know anything about packet loss or rtt so just return.
313 return WEBRTC_VIDEO_CODEC_OK; 302 return WEBRTC_VIDEO_CODEC_OK;
314 } 303 }
315 304
316 int H264VideoToolboxEncoder::SetRates(uint32_t new_bitrate_kbit, 305 int H264VideoToolboxEncoder::SetRates(uint32_t new_bitrate_kbit,
317 uint32_t frame_rate) { 306 uint32_t frame_rate) {
318 bitrate_ = new_bitrate_kbit * 1000; 307 target_bitrate_bps_ = 1000 * new_bitrate_kbit;
319 if (compression_session_) { 308 bitrate_adjuster_.SetTargetBitrateBps(target_bitrate_bps_);
320 internal::SetVTSessionProperty(compression_session_, 309 SetBitrateBps(bitrate_adjuster_.GetAdjustedBitrateBps());
321 kVTCompressionPropertyKey_AverageBitRate, 310
322 bitrate_);
323 }
324 return WEBRTC_VIDEO_CODEC_OK; 311 return WEBRTC_VIDEO_CODEC_OK;
325 } 312 }
326 313
327 int H264VideoToolboxEncoder::Release() { 314 int H264VideoToolboxEncoder::Release() {
315 // Need to reset so that the session is invalidated and won't use the
316 // callback anymore. Do not remove callback until the session is invalidated
317 // since async encoder callbacks can occur until invalidation.
318 int ret = ResetCompressionSession();
328 callback_ = nullptr; 319 callback_ = nullptr;
329 // Need to reset to that the session is invalidated and won't use the 320 return ret;
330 // callback anymore.
331 return ResetCompressionSession();
332 } 321 }
333 322
334 int H264VideoToolboxEncoder::ResetCompressionSession() { 323 int H264VideoToolboxEncoder::ResetCompressionSession() {
335 DestroyCompressionSession(); 324 DestroyCompressionSession();
336 325
337 // Set source image buffer attributes. These attributes will be present on 326 // Set source image buffer attributes. These attributes will be present on
338 // buffers retrieved from the encoder's pixel buffer pool. 327 // buffers retrieved from the encoder's pixel buffer pool.
339 const size_t attributes_size = 3; 328 const size_t attributes_size = 3;
340 CFTypeRef keys[attributes_size] = { 329 CFTypeRef keys[attributes_size] = {
341 #if defined(WEBRTC_IOS) 330 #if defined(WEBRTC_IOS)
(...skipping 40 matching lines...) Expand 10 before | Expand all | Expand 10 after
382 return WEBRTC_VIDEO_CODEC_OK; 371 return WEBRTC_VIDEO_CODEC_OK;
383 } 372 }
384 373
385 void H264VideoToolboxEncoder::ConfigureCompressionSession() { 374 void H264VideoToolboxEncoder::ConfigureCompressionSession() {
386 RTC_DCHECK(compression_session_); 375 RTC_DCHECK(compression_session_);
387 internal::SetVTSessionProperty(compression_session_, 376 internal::SetVTSessionProperty(compression_session_,
388 kVTCompressionPropertyKey_RealTime, true); 377 kVTCompressionPropertyKey_RealTime, true);
389 internal::SetVTSessionProperty(compression_session_, 378 internal::SetVTSessionProperty(compression_session_,
390 kVTCompressionPropertyKey_ProfileLevel, 379 kVTCompressionPropertyKey_ProfileLevel,
391 kVTProfileLevel_H264_Baseline_AutoLevel); 380 kVTProfileLevel_H264_Baseline_AutoLevel);
392 internal::SetVTSessionProperty(
393 compression_session_, kVTCompressionPropertyKey_AverageBitRate, bitrate_);
394 internal::SetVTSessionProperty(compression_session_, 381 internal::SetVTSessionProperty(compression_session_,
395 kVTCompressionPropertyKey_AllowFrameReordering, 382 kVTCompressionPropertyKey_AllowFrameReordering,
396 false); 383 false);
384 SetEncoderBitrateBps(target_bitrate_bps_);
397 // TODO(tkchin): Look at entropy mode and colorspace matrices. 385 // TODO(tkchin): Look at entropy mode and colorspace matrices.
398 // TODO(tkchin): Investigate to see if there's any way to make this work. 386 // TODO(tkchin): Investigate to see if there's any way to make this work.
399 // May need it to interop with Android. Currently this call just fails. 387 // May need it to interop with Android. Currently this call just fails.
400 // On inspecting encoder output on iOS8, this value is set to 6. 388 // On inspecting encoder output on iOS8, this value is set to 6.
401 // internal::SetVTSessionProperty(compression_session_, 389 // internal::SetVTSessionProperty(compression_session_,
402 // kVTCompressionPropertyKey_MaxFrameDelayCount, 390 // kVTCompressionPropertyKey_MaxFrameDelayCount,
403 // 1); 391 // 1);
404 // TODO(tkchin): See if enforcing keyframe frequency is beneficial in any 392 // TODO(tkchin): See if enforcing keyframe frequency is beneficial in any
405 // way. 393 // way.
406 // internal::SetVTSessionProperty( 394 // internal::SetVTSessionProperty(
407 // compression_session_, 395 // compression_session_,
408 // kVTCompressionPropertyKey_MaxKeyFrameInterval, 240); 396 // kVTCompressionPropertyKey_MaxKeyFrameInterval, 240);
409 // internal::SetVTSessionProperty( 397 // internal::SetVTSessionProperty(
410 // compression_session_, 398 // compression_session_,
411 // kVTCompressionPropertyKey_MaxKeyFrameIntervalDuration, 240); 399 // kVTCompressionPropertyKey_MaxKeyFrameIntervalDuration, 240);
412 } 400 }
413 401
414 void H264VideoToolboxEncoder::DestroyCompressionSession() { 402 void H264VideoToolboxEncoder::DestroyCompressionSession() {
415 if (compression_session_) { 403 if (compression_session_) {
416 VTCompressionSessionInvalidate(compression_session_); 404 VTCompressionSessionInvalidate(compression_session_);
417 CFRelease(compression_session_); 405 CFRelease(compression_session_);
418 compression_session_ = nullptr; 406 compression_session_ = nullptr;
419 } 407 }
420 } 408 }
421 409
422 const char* H264VideoToolboxEncoder::ImplementationName() const { 410 const char* H264VideoToolboxEncoder::ImplementationName() const {
423 return "VideoToolbox"; 411 return "VideoToolbox";
424 } 412 }
425 413
414 void H264VideoToolboxEncoder::SetBitrateBps(uint32_t bitrate_bps) {
415 if (encoder_bitrate_bps_ != bitrate_bps) {
416 SetEncoderBitrateBps(bitrate_bps);
417 }
418 }
419
420 void H264VideoToolboxEncoder::SetEncoderBitrateBps(uint32_t bitrate_bps) {
421 if (compression_session_) {
422 internal::SetVTSessionProperty(compression_session_,
423 kVTCompressionPropertyKey_AverageBitRate,
424 bitrate_bps);
425 encoder_bitrate_bps_ = bitrate_bps;
426 }
427 }
428
429 void H264VideoToolboxEncoder::OnEncodedFrame(
430 OSStatus status,
431 VTEncodeInfoFlags info_flags,
432 CMSampleBufferRef sample_buffer,
433 CodecSpecificInfo codec_specific_info,
434 int32_t width,
435 int32_t height,
436 int64_t render_time_ms,
437 uint32_t timestamp) {
438 if (status != noErr) {
439 LOG(LS_ERROR) << "H264 encode failed.";
440 return;
441 }
442 if (info_flags & kVTEncodeInfo_FrameDropped) {
443 LOG(LS_INFO) << "H264 encode dropped frame.";
444 }
445
446 bool is_keyframe = false;
447 CFArrayRef attachments =
448 CMSampleBufferGetSampleAttachmentsArray(sample_buffer, 0);
449 if (attachments != nullptr && CFArrayGetCount(attachments)) {
450 CFDictionaryRef attachment =
451 static_cast<CFDictionaryRef>(CFArrayGetValueAtIndex(attachments, 0));
452 is_keyframe =
453 !CFDictionaryContainsKey(attachment, kCMSampleAttachmentKey_NotSync);
454 }
455
456 // Convert the sample buffer into a buffer suitable for RTP packetization.
457 // TODO(tkchin): Allocate buffers through a pool.
458 rtc::scoped_ptr<rtc::Buffer> buffer(new rtc::Buffer());
459 rtc::scoped_ptr<webrtc::RTPFragmentationHeader> header;
460 if (!H264CMSampleBufferToAnnexBBuffer(sample_buffer, is_keyframe,
461 buffer.get(), header.accept())) {
462 return;
463 }
464 webrtc::EncodedImage frame(buffer->data(), buffer->size(), buffer->size());
465 frame._encodedWidth = width;
466 frame._encodedHeight = height;
467 frame._completeFrame = true;
468 frame._frameType =
469 is_keyframe ? webrtc::kVideoFrameKey : webrtc::kVideoFrameDelta;
470 frame.capture_time_ms_ = render_time_ms;
471 frame._timeStamp = timestamp;
472
473 int result = callback_->Encoded(frame, &codec_specific_info, header.get());
474 if (result != 0) {
475 LOG(LS_ERROR) << "Encode callback failed: " << result;
476 return;
477 }
478 bitrate_adjuster_.Update(frame._size);
479 }
480
426 } // namespace webrtc 481 } // namespace webrtc
427 482
428 #endif // defined(WEBRTC_VIDEO_TOOLBOX_SUPPORTED) 483 #endif // defined(WEBRTC_VIDEO_TOOLBOX_SUPPORTED)
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698