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

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 GN build. 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(), this) {}
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 bitrate_kbit_ = codec_settings->startBitrate;
212 bitrate_adjuster_.SetTargetBitrate(bitrate_kbit_);
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()));
292 VTCompressionSessionEncodeFrame( 277 VTCompressionSessionEncodeFrame(
293 compression_session_, pixel_buffer, presentation_time_stamp, 278 compression_session_, pixel_buffer, presentation_time_stamp,
294 kCMTimeInvalid, frame_properties, encode_params.release(), nullptr); 279 kCMTimeInvalid, frame_properties, encode_params.release(), nullptr);
295 if (frame_properties) { 280 if (frame_properties) {
296 CFRelease(frame_properties); 281 CFRelease(frame_properties);
297 } 282 }
298 if (pixel_buffer) { 283 if (pixel_buffer) {
299 CVBufferRelease(pixel_buffer); 284 CVBufferRelease(pixel_buffer);
300 } 285 }
301 return WEBRTC_VIDEO_CODEC_OK; 286 return WEBRTC_VIDEO_CODEC_OK;
302 } 287 }
303 288
304 int H264VideoToolboxEncoder::RegisterEncodeCompleteCallback( 289 int H264VideoToolboxEncoder::RegisterEncodeCompleteCallback(
305 EncodedImageCallback* callback) { 290 EncodedImageCallback* callback) {
306 callback_ = callback; 291 callback_ = callback;
307 return WEBRTC_VIDEO_CODEC_OK; 292 return WEBRTC_VIDEO_CODEC_OK;
308 } 293 }
309 294
310 int H264VideoToolboxEncoder::SetChannelParameters(uint32_t packet_loss, 295 int H264VideoToolboxEncoder::SetChannelParameters(uint32_t packet_loss,
311 int64_t rtt) { 296 int64_t rtt) {
312 // Encoder doesn't know anything about packet loss or rtt so just return. 297 // Encoder doesn't know anything about packet loss or rtt so just return.
313 return WEBRTC_VIDEO_CODEC_OK; 298 return WEBRTC_VIDEO_CODEC_OK;
314 } 299 }
315 300
316 int H264VideoToolboxEncoder::SetRates(uint32_t new_bitrate_kbit, 301 int H264VideoToolboxEncoder::SetRates(uint32_t new_bitrate_kbit,
317 uint32_t frame_rate) { 302 uint32_t frame_rate) {
318 bitrate_ = new_bitrate_kbit * 1000; 303 bitrate_kbit_ = new_bitrate_kbit;
319 if (compression_session_) { 304 bitrate_adjuster_.SetTargetBitrate(new_bitrate_kbit);
320 internal::SetVTSessionProperty(compression_session_, 305 SetBitrate(bitrate_kbit_);
321 kVTCompressionPropertyKey_AverageBitRate, 306
322 bitrate_);
323 }
324 return WEBRTC_VIDEO_CODEC_OK; 307 return WEBRTC_VIDEO_CODEC_OK;
325 } 308 }
326 309
327 int H264VideoToolboxEncoder::Release() { 310 int H264VideoToolboxEncoder::Release() {
311 // Need to reset so that the session is invalidated and won't use the
312 // callback anymore. Do not remove callback until the session is invalidated
313 // since async encoder callbacks can occur until invalidation.
314 int ret = ResetCompressionSession();
328 callback_ = nullptr; 315 callback_ = nullptr;
329 // Need to reset to that the session is invalidated and won't use the 316 return ret;
330 // callback anymore.
331 return ResetCompressionSession();
332 } 317 }
333 318
334 int H264VideoToolboxEncoder::ResetCompressionSession() { 319 int H264VideoToolboxEncoder::ResetCompressionSession() {
335 DestroyCompressionSession(); 320 DestroyCompressionSession();
336 321
337 // Set source image buffer attributes. These attributes will be present on 322 // Set source image buffer attributes. These attributes will be present on
338 // buffers retrieved from the encoder's pixel buffer pool. 323 // buffers retrieved from the encoder's pixel buffer pool.
339 const size_t attributes_size = 3; 324 const size_t attributes_size = 3;
340 CFTypeRef keys[attributes_size] = { 325 CFTypeRef keys[attributes_size] = {
341 #if defined(WEBRTC_IOS) 326 #if defined(WEBRTC_IOS)
(...skipping 40 matching lines...) Expand 10 before | Expand all | Expand 10 after
382 return WEBRTC_VIDEO_CODEC_OK; 367 return WEBRTC_VIDEO_CODEC_OK;
383 } 368 }
384 369
385 void H264VideoToolboxEncoder::ConfigureCompressionSession() { 370 void H264VideoToolboxEncoder::ConfigureCompressionSession() {
386 RTC_DCHECK(compression_session_); 371 RTC_DCHECK(compression_session_);
387 internal::SetVTSessionProperty(compression_session_, 372 internal::SetVTSessionProperty(compression_session_,
388 kVTCompressionPropertyKey_RealTime, true); 373 kVTCompressionPropertyKey_RealTime, true);
389 internal::SetVTSessionProperty(compression_session_, 374 internal::SetVTSessionProperty(compression_session_,
390 kVTCompressionPropertyKey_ProfileLevel, 375 kVTCompressionPropertyKey_ProfileLevel,
391 kVTProfileLevel_H264_Baseline_AutoLevel); 376 kVTProfileLevel_H264_Baseline_AutoLevel);
392 internal::SetVTSessionProperty(
393 compression_session_, kVTCompressionPropertyKey_AverageBitRate, bitrate_);
394 internal::SetVTSessionProperty(compression_session_, 377 internal::SetVTSessionProperty(compression_session_,
395 kVTCompressionPropertyKey_AllowFrameReordering, 378 kVTCompressionPropertyKey_AllowFrameReordering,
396 false); 379 false);
380 SetBitrate(bitrate_kbit_);
397 // TODO(tkchin): Look at entropy mode and colorspace matrices. 381 // TODO(tkchin): Look at entropy mode and colorspace matrices.
398 // TODO(tkchin): Investigate to see if there's any way to make this work. 382 // 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. 383 // 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. 384 // On inspecting encoder output on iOS8, this value is set to 6.
401 // internal::SetVTSessionProperty(compression_session_, 385 // internal::SetVTSessionProperty(compression_session_,
402 // kVTCompressionPropertyKey_MaxFrameDelayCount, 386 // kVTCompressionPropertyKey_MaxFrameDelayCount,
403 // 1); 387 // 1);
404 // TODO(tkchin): See if enforcing keyframe frequency is beneficial in any 388 // TODO(tkchin): See if enforcing keyframe frequency is beneficial in any
405 // way. 389 // way.
406 // internal::SetVTSessionProperty( 390 // internal::SetVTSessionProperty(
407 // compression_session_, 391 // compression_session_,
408 // kVTCompressionPropertyKey_MaxKeyFrameInterval, 240); 392 // kVTCompressionPropertyKey_MaxKeyFrameInterval, 240);
409 // internal::SetVTSessionProperty( 393 // internal::SetVTSessionProperty(
410 // compression_session_, 394 // compression_session_,
411 // kVTCompressionPropertyKey_MaxKeyFrameIntervalDuration, 240); 395 // kVTCompressionPropertyKey_MaxKeyFrameIntervalDuration, 240);
412 } 396 }
413 397
414 void H264VideoToolboxEncoder::DestroyCompressionSession() { 398 void H264VideoToolboxEncoder::DestroyCompressionSession() {
415 if (compression_session_) { 399 if (compression_session_) {
416 VTCompressionSessionInvalidate(compression_session_); 400 VTCompressionSessionInvalidate(compression_session_);
417 CFRelease(compression_session_); 401 CFRelease(compression_session_);
418 compression_session_ = nullptr; 402 compression_session_ = nullptr;
419 } 403 }
420 } 404 }
421 405
422 const char* H264VideoToolboxEncoder::ImplementationName() const { 406 const char* H264VideoToolboxEncoder::ImplementationName() const {
423 return "VideoToolbox"; 407 return "VideoToolbox";
424 } 408 }
425 409
410 void H264VideoToolboxEncoder::OnBitrateAdjusted(
411 uint32_t adjusted_bitrate_kbit) {
412 SetBitrate(adjusted_bitrate_kbit);
413 }
414
415 void H264VideoToolboxEncoder::SetBitrate(uint32_t bitrate_kbit) {
416 if (compression_session_) {
417 internal::SetVTSessionProperty(compression_session_,
418 kVTCompressionPropertyKey_AverageBitRate,
419 bitrate_kbit * 1000);
420 }
421 }
422
423 void H264VideoToolboxEncoder::OnEncodedFrame(
424 OSStatus status,
425 VTEncodeInfoFlags info_flags,
426 CMSampleBufferRef sample_buffer,
427 CodecSpecificInfo codec_specific_info,
428 int32_t width,
429 int32_t height,
430 int64_t render_time_ms,
431 uint32_t timestamp) {
432 if (status != noErr) {
433 LOG(LS_ERROR) << "H264 encode failed.";
434 return;
435 }
436 if (info_flags & kVTEncodeInfo_FrameDropped) {
437 LOG(LS_INFO) << "H264 encode dropped frame.";
438 }
439
440 bool is_keyframe = false;
441 CFArrayRef attachments =
442 CMSampleBufferGetSampleAttachmentsArray(sample_buffer, 0);
443 if (attachments != nullptr && CFArrayGetCount(attachments)) {
444 CFDictionaryRef attachment =
445 static_cast<CFDictionaryRef>(CFArrayGetValueAtIndex(attachments, 0));
446 is_keyframe =
447 !CFDictionaryContainsKey(attachment, kCMSampleAttachmentKey_NotSync);
448 }
449
450 // Convert the sample buffer into a buffer suitable for RTP packetization.
451 // TODO(tkchin): Allocate buffers through a pool.
452 rtc::scoped_ptr<rtc::Buffer> buffer(new rtc::Buffer());
453 rtc::scoped_ptr<webrtc::RTPFragmentationHeader> header;
454 if (!H264CMSampleBufferToAnnexBBuffer(sample_buffer, is_keyframe,
455 buffer.get(), header.accept())) {
456 return;
457 }
458 webrtc::EncodedImage frame(buffer->data(), buffer->size(), buffer->size());
459 frame._encodedWidth = width;
460 frame._encodedHeight = height;
461 frame._completeFrame = true;
462 frame._frameType =
463 is_keyframe ? webrtc::kVideoFrameKey : webrtc::kVideoFrameDelta;
464 frame.capture_time_ms_ = render_time_ms;
465 frame._timeStamp = timestamp;
466
467 int result = callback_->Encoded(frame, &(codec_specific_info), header.get());
stefan-webrtc 2016/02/18 20:56:58 Remove parentheses around codec_specific_info
tkchin_webrtc 2016/02/18 23:50:39 Done.
468 if (result != 0) {
469 LOG(LS_ERROR) << "Encode callback failed: " << result;
470 return;
471 }
472 bitrate_adjuster_.Update(frame._size);
473 }
474
426 } // namespace webrtc 475 } // namespace webrtc
427 476
428 #endif // defined(WEBRTC_VIDEO_TOOLBOX_SUPPORTED) 477 #endif // defined(WEBRTC_VIDEO_TOOLBOX_SUPPORTED)
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698