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

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

Issue 1187573004: iOS HW H264 support. (Closed) Base URL: https://chromium.googlesource.com/external/webrtc@master
Patch Set: Fix partial availability errors Created 5 years, 6 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
(Empty)
1 /*
2 * Copyright (c) 2015 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 */
11
12 #include "webrtc/modules/video_coding/codecs/h264/h264_video_toolbox_encoder.h"
13
14 #if defined(WEBRTC_VIDEO_TOOLBOX_SUPPORTED)
15
16 #include <string>
17 #include <vector>
18
19 #include "libyuv/convert_from.h"
20 #include "webrtc/base/checks.h"
21 #include "webrtc/base/logging.h"
22 #include "webrtc/base/scoped_ptr.h"
23 #include "webrtc/modules/video_coding/codecs/h264/h264_video_toolbox_nalu.h"
24
25 namespace internal {
26
27 // Convenience function for creating a dictionary.
28 inline CFDictionaryRef CreateCFDictionary(CFTypeRef* keys,
29 CFTypeRef* values,
30 size_t size) {
31 return CFDictionaryCreate(kCFAllocatorDefault, keys, values, size,
32 &kCFTypeDictionaryKeyCallBacks,
33 &kCFTypeDictionaryValueCallBacks);
34 }
35
36 // Copies characters from a CFStringRef into a std::string.
37 std::string CFStringToString(const CFStringRef cf_string) {
38 DCHECK(cf_string);
39 std::string std_string;
40 // Get the size needed for UTF8 plus terminating character.
41 size_t buffer_size =
42 CFStringGetMaximumSizeForEncoding(CFStringGetLength(cf_string),
43 kCFStringEncodingUTF8) +
44 1;
45 rtc::scoped_ptr<char[]> buffer(new char[buffer_size]);
46 if (CFStringGetCString(cf_string, buffer.get(), buffer_size,
47 kCFStringEncodingUTF8)) {
48 // Copy over the characters.
49 std_string.assign(buffer.get());
50 }
51 return std_string;
52 }
53
54 // Convenience function for setting a VT property.
55 void SetVTSessionProperty(VTSessionRef session,
56 CFStringRef key,
57 int32_t value) {
58 CFNumberRef cfNum =
59 CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &value);
60 OSStatus status = VTSessionSetProperty(session, key, cfNum);
61 CFRelease(cfNum);
62 if (status != noErr) {
63 std::string key_string = CFStringToString(key);
64 LOG(LS_ERROR) << "VTSessionSetProperty failed to set: " << key_string
65 << " to " << value << ": " << status;
66 }
67 }
68
69 // Convenience function for setting a VT property.
70 void SetVTSessionProperty(VTSessionRef session, CFStringRef key, bool value) {
71 CFBooleanRef cf_bool = (value) ? kCFBooleanTrue : kCFBooleanFalse;
72 OSStatus status = VTSessionSetProperty(session, key, cf_bool);
73 if (status != noErr) {
74 std::string key_string = CFStringToString(key);
75 LOG(LS_ERROR) << "VTSessionSetProperty failed to set: " << key_string
76 << " to " << value << ": " << status;
77 }
78 }
79
80 // Convenience function for setting a VT property.
81 void SetVTSessionProperty(VTSessionRef session,
82 CFStringRef key,
83 CFStringRef value) {
84 OSStatus status = VTSessionSetProperty(session, key, value);
85 if (status != noErr) {
86 std::string key_string = CFStringToString(key);
87 std::string val_string = CFStringToString(value);
88 LOG(LS_ERROR) << "VTSessionSetProperty failed to set: " << key_string
89 << " to " << val_string << ": " << status;
90 }
91 }
92
93 // Struct that we pass to the encoder per frame to encode. We receive it again
94 // in the encoder callback.
95 struct FrameEncodeParams {
96 FrameEncodeParams(webrtc::EncodedImageCallback* cb,
97 const webrtc::CodecSpecificInfo& csi,
98 int32_t w,
99 int32_t h,
100 int64_t rtms,
101 uint32_t ts)
102 : callback(cb),
103 codec_specific_info(csi),
104 width(w),
105 height(h),
106 render_time_ms(rtms),
107 timestamp(ts) {}
108 webrtc::EncodedImageCallback* callback;
109 webrtc::CodecSpecificInfo codec_specific_info;
110 int32_t width;
111 int32_t height;
112 int64_t render_time_ms;
113 uint32_t timestamp;
114 };
115
116 // We receive I420Frames as input, but we need to feed CVPixelBuffers into the
117 // encoder. This performs the copy and format conversion.
118 // TODO(tkchin): See if encoder will accept i420 frames and compare performance.
119 bool CopyVideoFrameToPixelBuffer(const webrtc::VideoFrame& frame,
120 CVPixelBufferRef pixel_buffer) {
121 DCHECK(pixel_buffer);
122 DCHECK(CVPixelBufferGetPixelFormatType(pixel_buffer) ==
123 kCVPixelFormatType_420YpCbCr8BiPlanarFullRange);
124 DCHECK(CVPixelBufferGetHeightOfPlane(pixel_buffer, 0) ==
125 static_cast<size_t>(frame.height()));
126 DCHECK(CVPixelBufferGetWidthOfPlane(pixel_buffer, 0) ==
127 static_cast<size_t>(frame.width()));
128
129 CVReturn cvRet = CVPixelBufferLockBaseAddress(pixel_buffer, 0);
130 if (cvRet != kCVReturnSuccess) {
131 LOG(LS_ERROR) << "Failed to lock base address: " << cvRet;
132 return false;
133 }
134 uint8* dst_y = reinterpret_cast<uint8*>(
135 CVPixelBufferGetBaseAddressOfPlane(pixel_buffer, 0));
136 int dst_stride_y = CVPixelBufferGetBytesPerRowOfPlane(pixel_buffer, 0);
137 uint8* dst_uv = reinterpret_cast<uint8*>(
138 CVPixelBufferGetBaseAddressOfPlane(pixel_buffer, 1));
139 int dst_stride_uv = CVPixelBufferGetBytesPerRowOfPlane(pixel_buffer, 1);
140 // Convert I420 to NV12.
141 int ret = libyuv::I420ToNV12(
142 frame.buffer(webrtc::kYPlane), frame.stride(webrtc::kYPlane),
143 frame.buffer(webrtc::kUPlane), frame.stride(webrtc::kUPlane),
144 frame.buffer(webrtc::kVPlane), frame.stride(webrtc::kVPlane),
145 dst_y, dst_stride_y, dst_uv, dst_stride_uv,
146 frame.width(), frame.height());
147 CVPixelBufferUnlockBaseAddress(pixel_buffer, 0);
148 if (ret) {
149 LOG(LS_ERROR) << "Error converting I420 VideoFrame to NV12 :" << ret;
150 return false;
151 }
152 return true;
153 }
154
155 // This is the callback function that VideoToolbox calls when encode is
156 // complete.
157 void VTCompressionOutputCallback(void* encoder,
158 void* params,
159 OSStatus status,
160 VTEncodeInfoFlags info_flags,
161 CMSampleBufferRef sample_buffer) {
162 rtc::scoped_ptr<FrameEncodeParams> encode_params(
163 reinterpret_cast<FrameEncodeParams*>(params));
164 if (status != noErr) {
165 LOG(LS_ERROR) << "H264 encoding failed.";
166 return;
167 }
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,
187 is_keyframe,
188 buffer.get(),
189 header.accept())) {
190 return;
191 }
192 webrtc::EncodedImage frame(buffer->data(), buffer->size(), buffer->size());
193 frame._encodedWidth = encode_params->width;
194 frame._encodedHeight = encode_params->height;
195 frame._completeFrame = true;
196 frame._frameType = is_keyframe ? webrtc::kKeyFrame : webrtc::kDeltaFrame;
197 frame.capture_time_ms_ = encode_params->render_time_ms;
198 frame._timeStamp = encode_params->timestamp;
199
200 int result = encode_params->callback->Encoded(
201 frame, &(encode_params->codec_specific_info), header.get());
202 if (result != 0) {
203 LOG(LS_ERROR) << "Encoded callback failed: " << result;
204 }
205 }
206
207 } // namespace internal
208
209 namespace webrtc {
210
211 H264VideoToolboxEncoder::H264VideoToolboxEncoder()
212 : callback_(nullptr), compression_session_(nullptr) {
213 }
214
215 H264VideoToolboxEncoder::~H264VideoToolboxEncoder() {
216 DestroyCompressionSession();
217 }
218
219 int H264VideoToolboxEncoder::InitEncode(const VideoCodec* codec_settings,
220 int number_of_cores,
221 size_t max_payload_size) {
222 DCHECK(codec_settings);
223 DCHECK_EQ(codec_settings->codecType, kVideoCodecH264);
224 // TODO(tkchin): We may need to enforce width/height dimension restrictions
225 // to match what the encoder supports.
226 width_ = codec_settings->width;
227 height_ = codec_settings->height;
228 // We can only set average bitrate on the HW encoder.
229 bitrate_ = codec_settings->startBitrate * 1000;
230
231 // TODO(tkchin): Try setting payload size via
232 // kVTCompressionPropertyKey_MaxH264SliceBytes.
233
234 return ResetCompressionSession();
235 }
236
237 int H264VideoToolboxEncoder::Encode(
238 const VideoFrame& input_image,
239 const CodecSpecificInfo* codec_specific_info,
240 const std::vector<VideoFrameType>* frame_types) {
241 if (input_image.IsZeroSize()) {
242 // It's possible to get zero sizes as a signal to produce keyframes (this
243 // happens for internal sources). But this shouldn't happen in
244 // webrtcvideoengine2.
245 RTC_NOTREACHED();
246 return WEBRTC_VIDEO_CODEC_OK;
247 }
248 if (!callback_ || !compression_session_) {
249 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
250 }
251
252 // Get a pixel buffer from the pool and copy frame data over.
253 CVPixelBufferPoolRef pixel_buffer_pool =
254 VTCompressionSessionGetPixelBufferPool(compression_session_);
255 CVPixelBufferRef pixel_buffer = nullptr;
256 CVReturn ret = CVPixelBufferPoolCreatePixelBuffer(nullptr, pixel_buffer_pool,
257 &pixel_buffer);
258 if (ret != kCVReturnSuccess) {
259 LOG(LS_ERROR) << "Failed to create pixel buffer: " << ret;
260 // We probably want to drop frames here, since failure probably means
261 // that the pool is empty.
262 return WEBRTC_VIDEO_CODEC_ERROR;
263 }
264 DCHECK(pixel_buffer);
265 if (!internal::CopyVideoFrameToPixelBuffer(input_image, pixel_buffer)) {
266 LOG(LS_ERROR) << "Failed to copy frame data.";
267 CVBufferRelease(pixel_buffer);
268 return WEBRTC_VIDEO_CODEC_ERROR;
269 }
270
271 // Check if we need a keyframe.
272 bool is_keyframe_required = false;
273 if (frame_types) {
274 for (auto frame_type : *frame_types) {
275 if (frame_type == kKeyFrame) {
276 is_keyframe_required = true;
277 break;
278 }
279 }
280 }
281
282 CMTime presentation_time_stamp =
283 CMTimeMake(input_image.render_time_ms(), 1000);
284 CFDictionaryRef frame_properties = nullptr;
285 if (is_keyframe_required) {
286 CFTypeRef keys[] = { kVTEncodeFrameOptionKey_ForceKeyFrame };
287 CFTypeRef values[] = { kCFBooleanTrue };
288 frame_properties = internal::CreateCFDictionary(keys, values, 1);
289 }
290 rtc::scoped_ptr<internal::FrameEncodeParams> encode_params;
291 encode_params.reset(new internal::FrameEncodeParams(
292 callback_, *codec_specific_info, width_, height_,
293 input_image.render_time_ms(), input_image.timestamp()));
294 VTCompressionSessionEncodeFrame(
295 compression_session_, pixel_buffer, presentation_time_stamp,
296 kCMTimeInvalid, frame_properties, encode_params.release(), nullptr);
297 if (frame_properties) {
298 CFRelease(frame_properties);
299 }
300 if (pixel_buffer) {
301 CVBufferRelease(pixel_buffer);
302 }
303 return WEBRTC_VIDEO_CODEC_OK;
304 }
305
306 int H264VideoToolboxEncoder::RegisterEncodeCompleteCallback(
307 EncodedImageCallback* callback) {
308 callback_ = callback;
309 return WEBRTC_VIDEO_CODEC_OK;
310 }
311
312 int H264VideoToolboxEncoder::SetChannelParameters(uint32_t packet_loss,
313 int64_t rtt) {
314 // Encoder doesn't know anything about packet loss or rtt so just return.
315 return WEBRTC_VIDEO_CODEC_OK;
316 }
317
318 int H264VideoToolboxEncoder::SetRates(uint32_t new_bitrate_kbit,
319 uint32_t frame_rate) {
320 bitrate_ = new_bitrate_kbit * 1000;
321 if (compression_session_) {
322 internal::SetVTSessionProperty(compression_session_,
323 kVTCompressionPropertyKey_AverageBitRate,
324 bitrate_);
325 }
326 return WEBRTC_VIDEO_CODEC_OK;
327 }
328
329 int H264VideoToolboxEncoder::Release() {
330 callback_ = nullptr;
331 // Need to reset to that the session is invalidated and won't use the
332 // callback anymore.
333 return ResetCompressionSession();
334 }
335
336 int H264VideoToolboxEncoder::ResetCompressionSession() {
337 DestroyCompressionSession();
338
339 // Set source image buffer attributes. These attributes will be present on
340 // buffers retrieved from the encoder's pixel buffer pool.
341 const size_t attributes_size = 3;
342 CFTypeRef keys[attributes_size] = {
343 #if defined(WEBRTC_IOS)
344 kCVPixelBufferOpenGLESCompatibilityKey,
345 #elif defined(WEBRTC_MAC)
346 kCVPixelBufferOpenGLCompatibilityKey,
347 #endif
348 kCVPixelBufferIOSurfacePropertiesKey,
349 kCVPixelBufferPixelFormatTypeKey
350 };
351 CFDictionaryRef io_surface_value =
352 internal::CreateCFDictionary(nullptr, nullptr, 0);
353 int64_t nv12type = kCVPixelFormatType_420YpCbCr8BiPlanarFullRange;
354 CFNumberRef pixel_format =
355 CFNumberCreate(nullptr, kCFNumberLongType, &nv12type);
356 CFTypeRef values[attributes_size] = {
357 kCFBooleanTrue,
358 io_surface_value,
359 pixel_format
360 };
361 CFDictionaryRef source_attributes =
362 internal::CreateCFDictionary(keys, values, attributes_size);
363 if (io_surface_value) {
364 CFRelease(io_surface_value);
365 io_surface_value = nullptr;
366 }
367 if (pixel_format) {
368 CFRelease(pixel_format);
369 pixel_format = nullptr;
370 }
371 OSStatus status = VTCompressionSessionCreate(
372 nullptr, // use default allocator
373 width_,
374 height_,
375 kCMVideoCodecType_H264,
376 nullptr, // use default encoder
377 source_attributes,
378 nullptr, // use default compressed data allocator
379 internal::VTCompressionOutputCallback,
380 this,
381 &compression_session_);
382 if (source_attributes) {
383 CFRelease(source_attributes);
384 source_attributes = nullptr;
385 }
386 if (status != noErr) {
387 LOG(LS_ERROR) << "Failed to create compression session: " << status;
388 return WEBRTC_VIDEO_CODEC_ERROR;
389 }
390 ConfigureCompressionSession();
391 return WEBRTC_VIDEO_CODEC_OK;
392 }
393
394 void H264VideoToolboxEncoder::ConfigureCompressionSession() {
395 DCHECK(compression_session_);
396 internal::SetVTSessionProperty(compression_session_,
397 kVTCompressionPropertyKey_RealTime, true);
398 internal::SetVTSessionProperty(compression_session_,
399 kVTCompressionPropertyKey_ProfileLevel,
400 kVTProfileLevel_H264_Baseline_AutoLevel);
401 internal::SetVTSessionProperty(
402 compression_session_, kVTCompressionPropertyKey_AverageBitRate, bitrate_);
403 internal::SetVTSessionProperty(compression_session_,
404 kVTCompressionPropertyKey_AllowFrameReordering,
405 false);
406 // TODO(tkchin): Look at entropy mode and colorspace matrices.
407 // TODO(tkchin): Investigate to see if there's any way to make this work.
408 // May need it to interop with Android. Currently this call just fails.
409 // On inspecting encoder output on iOS8, this value is set to 6.
410 // internal::SetVTSessionProperty(compression_session_,
411 // kVTCompressionPropertyKey_MaxFrameDelayCount,
412 // 1);
413 // TODO(tkchin): See if enforcing keyframe frequency is beneficial in any
414 // way.
415 // internal::SetVTSessionProperty(
416 // compression_session_,
417 // kVTCompressionPropertyKey_MaxKeyFrameInterval, 240);
418 // internal::SetVTSessionProperty(
419 // compression_session_,
420 // kVTCompressionPropertyKey_MaxKeyFrameIntervalDuration, 240);
421 }
422
423 void H264VideoToolboxEncoder::DestroyCompressionSession() {
424 if (compression_session_) {
425 VTCompressionSessionInvalidate(compression_session_);
426 CFRelease(compression_session_);
427 compression_session_ = nullptr;
428 }
429 }
430
431 } // namespace webrtc
432
433 #endif // defined(WEBRTC_VIDEO_TOOLBOX_SUPPORTED)
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698