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

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

Issue 1100643002: [cast] Handle frame size changes directly in the VideoToolbox encoder (v2). (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Created 5 years, 8 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/h264_vt_encoder.h ('k') | media/cast/sender/h264_vt_encoder_unittest.cc » ('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/h264_vt_encoder.h" 5 #include "media/cast/sender/h264_vt_encoder.h"
6 6
7 #include <string> 7 #include <string>
8 #include <vector> 8 #include <vector>
9 9
10 #include "base/big_endian.h" 10 #include "base/big_endian.h"
(...skipping 19 matching lines...) Expand all
30 const VideoEncoder::FrameEncodedCallback frame_encoded_callback; 30 const VideoEncoder::FrameEncodedCallback frame_encoded_callback;
31 31
32 InProgressFrameEncode(RtpTimestamp rtp, 32 InProgressFrameEncode(RtpTimestamp rtp,
33 base::TimeTicks r_time, 33 base::TimeTicks r_time,
34 VideoEncoder::FrameEncodedCallback callback) 34 VideoEncoder::FrameEncodedCallback callback)
35 : rtp_timestamp(rtp), 35 : rtp_timestamp(rtp),
36 reference_time(r_time), 36 reference_time(r_time),
37 frame_encoded_callback(callback) {} 37 frame_encoded_callback(callback) {}
38 }; 38 };
39 39
40 base::ScopedCFTypeRef<CFDictionaryRef> DictionaryWithKeysAndValues( 40 base::ScopedCFTypeRef<CFDictionaryRef>
41 CFTypeRef* keys, 41 DictionaryWithKeysAndValues(CFTypeRef* keys, CFTypeRef* values, size_t size) {
42 CFTypeRef* values,
43 size_t size) {
44 return base::ScopedCFTypeRef<CFDictionaryRef>(CFDictionaryCreate( 42 return base::ScopedCFTypeRef<CFDictionaryRef>(CFDictionaryCreate(
45 kCFAllocatorDefault, 43 kCFAllocatorDefault, keys, values, size, &kCFTypeDictionaryKeyCallBacks,
46 keys,
47 values,
48 size,
49 &kCFTypeDictionaryKeyCallBacks,
50 &kCFTypeDictionaryValueCallBacks)); 44 &kCFTypeDictionaryValueCallBacks));
51 } 45 }
52 46
53 base::ScopedCFTypeRef<CFDictionaryRef> DictionaryWithKeyValue(CFTypeRef key, 47 base::ScopedCFTypeRef<CFDictionaryRef> DictionaryWithKeyValue(CFTypeRef key,
54 CFTypeRef value) { 48 CFTypeRef value) {
55 CFTypeRef keys[1] = {key}; 49 CFTypeRef keys[1] = {key};
56 CFTypeRef values[1] = {value}; 50 CFTypeRef values[1] = {value};
57 return DictionaryWithKeysAndValues(keys, values, 1); 51 return DictionaryWithKeysAndValues(keys, values, 1);
58 } 52 }
59 53
(...skipping 142 matching lines...) Expand 10 before | Expand all | Expand 10 after
202 CopyNalsToAnnexB<uint8_t>(bb_data, bb_size, annexb_buffer); 196 CopyNalsToAnnexB<uint8_t>(bb_data, bb_size, annexb_buffer);
203 } else if (nal_size_field_bytes == 2) { 197 } else if (nal_size_field_bytes == 2) {
204 CopyNalsToAnnexB<uint16_t>(bb_data, bb_size, annexb_buffer); 198 CopyNalsToAnnexB<uint16_t>(bb_data, bb_size, annexb_buffer);
205 } else if (nal_size_field_bytes == 4) { 199 } else if (nal_size_field_bytes == 4) {
206 CopyNalsToAnnexB<uint32_t>(bb_data, bb_size, annexb_buffer); 200 CopyNalsToAnnexB<uint32_t>(bb_data, bb_size, annexb_buffer);
207 } else { 201 } else {
208 NOTREACHED(); 202 NOTREACHED();
209 } 203 }
210 } 204 }
211 205
212 // Implementation of the VideoFrameFactory interface using |CVPixelBufferPool|. 206 } // namespace
213 class VideoFrameFactoryCVPixelBufferPoolImpl : public VideoFrameFactory { 207
208 class H264VideoToolboxEncoder::VideoFrameFactoryImpl
209 : public base::RefCountedThreadSafe<VideoFrameFactoryImpl>,
210 public VideoFrameFactory {
214 public: 211 public:
215 VideoFrameFactoryCVPixelBufferPoolImpl( 212 // Type that proxies the VideoFrameFactory interface to this class.
216 const base::ScopedCFTypeRef<CVPixelBufferPoolRef>& pool, 213 class Proxy;
217 const gfx::Size& frame_size)
218 : pool_(pool),
219 frame_size_(frame_size) {}
220 214
221 ~VideoFrameFactoryCVPixelBufferPoolImpl() override {} 215 VideoFrameFactoryImpl(const base::WeakPtr<H264VideoToolboxEncoder>& encoder,
216 const scoped_refptr<CastEnvironment>& cast_environment)
217 : encoder_(encoder), cast_environment_(cast_environment) {}
222 218
223 scoped_refptr<VideoFrame> MaybeCreateFrame( 219 scoped_refptr<VideoFrame> MaybeCreateFrame(
224 const gfx::Size& frame_size, base::TimeDelta timestamp) override { 220 const gfx::Size& frame_size,
225 if (frame_size != frame_size_) 221 base::TimeDelta timestamp) override {
226 return nullptr; // Buffer pool is not a match for requested frame size. 222 base::AutoLock auto_lock(lock_);
227 223
224 // If the pool size does not match, speculatively reset the encoder to use
225 // the new size and return null. Cache the new frame size right away and
226 // toss away the pixel buffer pool to avoid spurious tasks until the encoder
227 // is done resetting.
228 if (frame_size != pool_frame_size_) {
229 DVLOG(1) << "MaybeCreateFrame: Detected frame size change.";
230 cast_environment_->PostTask(
231 CastEnvironment::MAIN, FROM_HERE,
232 base::Bind(&H264VideoToolboxEncoder::UpdateFrameSize, encoder_,
233 frame_size));
234 pool_frame_size_ = frame_size;
235 pool_.reset();
236 return nullptr;
237 }
238
239 if (!pool_) {
240 DVLOG(1) << "MaybeCreateFrame: No pixel buffer pool.";
241 return nullptr;
242 }
243
244 // Allocate a pixel buffer from the pool and return a wrapper VideoFrame.
228 base::ScopedCFTypeRef<CVPixelBufferRef> buffer; 245 base::ScopedCFTypeRef<CVPixelBufferRef> buffer;
229 if (CVPixelBufferPoolCreatePixelBuffer(kCFAllocatorDefault, pool_, 246 auto status = CVPixelBufferPoolCreatePixelBuffer(kCFAllocatorDefault, pool_,
230 buffer.InitializeInto()) != 247 buffer.InitializeInto());
231 kCVReturnSuccess) 248 if (status != kCVReturnSuccess) {
232 return nullptr; // Buffer pool has run out of pixel buffers. 249 DLOG(ERROR) << "CVPixelBufferPoolCreatePixelBuffer failed: " << status;
250 return nullptr;
251 }
252
233 DCHECK(buffer); 253 DCHECK(buffer);
234
235 return VideoFrame::WrapCVPixelBuffer(buffer, timestamp); 254 return VideoFrame::WrapCVPixelBuffer(buffer, timestamp);
236 } 255 }
237 256
257 void Update(const base::ScopedCFTypeRef<CVPixelBufferPoolRef>& pool,
258 const gfx::Size& frame_size) {
259 base::AutoLock auto_lock(lock_);
260 pool_ = pool;
261 pool_frame_size_ = frame_size;
262 }
263
238 private: 264 private:
239 const base::ScopedCFTypeRef<CVPixelBufferPoolRef> pool_; 265 friend class base::RefCountedThreadSafe<VideoFrameFactoryImpl>;
240 const gfx::Size frame_size_; 266 ~VideoFrameFactoryImpl() override {}
241 267
242 DISALLOW_COPY_AND_ASSIGN(VideoFrameFactoryCVPixelBufferPoolImpl); 268 base::Lock lock_;
269 base::ScopedCFTypeRef<CVPixelBufferPoolRef> pool_;
270 gfx::Size pool_frame_size_;
271
272 // Weak back reference to the encoder and the cast envrionment so we can
273 // message the encoder when the frame size changes.
274 const base::WeakPtr<H264VideoToolboxEncoder> encoder_;
275 const scoped_refptr<CastEnvironment> cast_environment_;
276
277 DISALLOW_COPY_AND_ASSIGN(VideoFrameFactoryImpl);
243 }; 278 };
244 279
245 } // namespace 280 class H264VideoToolboxEncoder::VideoFrameFactoryImpl::Proxy
281 : public VideoFrameFactory {
282 public:
283 explicit Proxy(
284 const scoped_refptr<VideoFrameFactoryImpl>& video_frame_factory)
285 : video_frame_factory_(video_frame_factory) {
286 DCHECK(video_frame_factory_);
287 }
288
289 scoped_refptr<VideoFrame> MaybeCreateFrame(
290 const gfx::Size& frame_size,
291 base::TimeDelta timestamp) override {
292 return video_frame_factory_->MaybeCreateFrame(frame_size, timestamp);
293 }
294
295 private:
296 ~Proxy() override {}
297
298 const scoped_refptr<VideoFrameFactoryImpl> video_frame_factory_;
299
300 DISALLOW_COPY_AND_ASSIGN(Proxy);
301 };
246 302
247 // static 303 // static
248 bool H264VideoToolboxEncoder::IsSupported( 304 bool H264VideoToolboxEncoder::IsSupported(
249 const VideoSenderConfig& video_config) { 305 const VideoSenderConfig& video_config) {
250 return video_config.codec == CODEC_VIDEO_H264 && VideoToolboxGlue::Get(); 306 return video_config.codec == CODEC_VIDEO_H264 && VideoToolboxGlue::Get();
251 } 307 }
252 308
253 H264VideoToolboxEncoder::H264VideoToolboxEncoder( 309 H264VideoToolboxEncoder::H264VideoToolboxEncoder(
254 const scoped_refptr<CastEnvironment>& cast_environment, 310 const scoped_refptr<CastEnvironment>& cast_environment,
255 const VideoSenderConfig& video_config, 311 const VideoSenderConfig& video_config,
256 const gfx::Size& frame_size,
257 uint32 first_frame_id,
258 const StatusChangeCallback& status_change_cb) 312 const StatusChangeCallback& status_change_cb)
259 : cast_environment_(cast_environment), 313 : cast_environment_(cast_environment),
260 videotoolbox_glue_(VideoToolboxGlue::Get()), 314 videotoolbox_glue_(VideoToolboxGlue::Get()),
261 frame_size_(frame_size), 315 video_config_(video_config),
262 status_change_cb_(status_change_cb), 316 status_change_cb_(status_change_cb),
263 next_frame_id_(first_frame_id), 317 last_frame_id_(kStartFrameId),
264 encode_next_frame_as_keyframe_(false) { 318 encode_next_frame_as_keyframe_(false),
265 DCHECK(!frame_size_.IsEmpty()); 319 weak_factory_(this) {
320 DCHECK(cast_environment_->CurrentlyOn(CastEnvironment::MAIN));
266 DCHECK(!status_change_cb_.is_null()); 321 DCHECK(!status_change_cb_.is_null());
267 322
268 OperationalStatus operational_status; 323 OperationalStatus operational_status =
269 if (video_config.codec == CODEC_VIDEO_H264 && videotoolbox_glue_) { 324 H264VideoToolboxEncoder::IsSupported(video_config)
270 operational_status = Initialize(video_config) ? 325 ? STATUS_INITIALIZED
271 STATUS_INITIALIZED : STATUS_INVALID_CONFIGURATION; 326 : STATUS_UNSUPPORTED_CODEC;
272 } else { 327 cast_environment_->PostTask(
273 operational_status = STATUS_UNSUPPORTED_CODEC; 328 CastEnvironment::MAIN, FROM_HERE,
329 base::Bind(status_change_cb_, operational_status));
330
331 if (operational_status == STATUS_INITIALIZED) {
332 video_frame_factory_ =
333 scoped_refptr<VideoFrameFactoryImpl>(new VideoFrameFactoryImpl(
334 weak_factory_.GetWeakPtr(), cast_environment_));
274 } 335 }
275 cast_environment_->PostTask(
276 CastEnvironment::MAIN,
277 FROM_HERE,
278 base::Bind(status_change_cb_, operational_status));
279 } 336 }
280 337
281 H264VideoToolboxEncoder::~H264VideoToolboxEncoder() { 338 H264VideoToolboxEncoder::~H264VideoToolboxEncoder() {
282 Teardown(); 339 DestroyCompressionSession();
283 } 340 }
284 341
285 bool H264VideoToolboxEncoder::Initialize( 342 void H264VideoToolboxEncoder::ResetCompressionSession() {
286 const VideoSenderConfig& video_config) {
287 DCHECK(thread_checker_.CalledOnValidThread()); 343 DCHECK(thread_checker_.CalledOnValidThread());
288 DCHECK(!compression_session_);
289 344
290 // Note that the encoder object is given to the compression session as the 345 // Notify that we're resetting the encoder.
291 // callback context using a raw pointer. The C API does not allow us to use 346 cast_environment_->PostTask(
292 // a smart pointer, nor is this encoder ref counted. However, this is still 347 CastEnvironment::MAIN, FROM_HERE,
293 // safe, because we 1) we own the compression session and 2) we tear it down 348 base::Bind(status_change_cb_, STATUS_CODEC_REINIT_PENDING));
294 // safely. When destructing the encoder, the compression session is flushed 349
295 // and invalidated. Internally, VideoToolbox will join all of its threads 350 // Destroy the current session, if any.
296 // before returning to the client. Therefore, when control returns to us, we 351 DestroyCompressionSession();
297 // are guaranteed that the output callback will not execute again.
298 352
299 // On OS X, allow the hardware encoder. Don't require it, it does not support 353 // On OS X, allow the hardware encoder. Don't require it, it does not support
300 // all configurations (some of which are used for testing). 354 // all configurations (some of which are used for testing).
301 base::ScopedCFTypeRef<CFDictionaryRef> encoder_spec; 355 base::ScopedCFTypeRef<CFDictionaryRef> encoder_spec;
302 #if !defined(OS_IOS) 356 #if !defined(OS_IOS)
303 encoder_spec = DictionaryWithKeyValue( 357 encoder_spec = DictionaryWithKeyValue(
304 videotoolbox_glue_ 358 videotoolbox_glue_
305 ->kVTVideoEncoderSpecification_EnableHardwareAcceleratedVideoEncoder() , 359 ->kVTVideoEncoderSpecification_EnableHardwareAcceleratedVideoEncoder() ,
306 kCFBooleanTrue); 360 kCFBooleanTrue);
307 #endif 361 #endif
308 362
309 // Certain encoders prefer kCVPixelFormatType_422YpCbCr8, which is not 363 // Certain encoders prefer kCVPixelFormatType_422YpCbCr8, which is not
310 // supported through VideoFrame. We can force 420 formats to be used instead. 364 // supported through VideoFrame. We can force 420 formats to be used instead.
311 const int formats[] = { 365 const int formats[] = {
312 kCVPixelFormatType_420YpCbCr8Planar, 366 kCVPixelFormatType_420YpCbCr8Planar,
313 CoreVideoGlue::kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange 367 CoreVideoGlue::kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange};
314 };
315 // Keep these attachment settings in-sync with those in ConfigureSession(). 368 // Keep these attachment settings in-sync with those in ConfigureSession().
316 CFTypeRef attachments_keys[] = { 369 CFTypeRef attachments_keys[] = {kCVImageBufferColorPrimariesKey,
317 kCVImageBufferColorPrimariesKey, 370 kCVImageBufferTransferFunctionKey,
318 kCVImageBufferTransferFunctionKey, 371 kCVImageBufferYCbCrMatrixKey};
319 kCVImageBufferYCbCrMatrixKey 372 CFTypeRef attachments_values[] = {kCVImageBufferColorPrimaries_ITU_R_709_2,
320 }; 373 kCVImageBufferTransferFunction_ITU_R_709_2,
321 CFTypeRef attachments_values[] = { 374 kCVImageBufferYCbCrMatrix_ITU_R_709_2};
322 kCVImageBufferColorPrimaries_ITU_R_709_2, 375 CFTypeRef buffer_attributes_keys[] = {kCVPixelBufferPixelFormatTypeKey,
323 kCVImageBufferTransferFunction_ITU_R_709_2, 376 kCVBufferPropagatedAttachmentsKey};
324 kCVImageBufferYCbCrMatrix_ITU_R_709_2
325 };
326 CFTypeRef buffer_attributes_keys[] = {
327 kCVPixelBufferPixelFormatTypeKey,
328 kCVBufferPropagatedAttachmentsKey
329 };
330 CFTypeRef buffer_attributes_values[] = { 377 CFTypeRef buffer_attributes_values[] = {
331 ArrayWithIntegers(formats, arraysize(formats)).release(), 378 ArrayWithIntegers(formats, arraysize(formats)).release(),
332 DictionaryWithKeysAndValues(attachments_keys, 379 DictionaryWithKeysAndValues(attachments_keys, attachments_values,
333 attachments_values, 380 arraysize(attachments_keys))
334 arraysize(attachments_keys)).release() 381 .release()};
335 };
336 const base::ScopedCFTypeRef<CFDictionaryRef> buffer_attributes = 382 const base::ScopedCFTypeRef<CFDictionaryRef> buffer_attributes =
337 DictionaryWithKeysAndValues(buffer_attributes_keys, 383 DictionaryWithKeysAndValues(buffer_attributes_keys,
338 buffer_attributes_values, 384 buffer_attributes_values,
339 arraysize(buffer_attributes_keys)); 385 arraysize(buffer_attributes_keys));
340 for (auto& v : buffer_attributes_values) 386 for (auto& v : buffer_attributes_values)
341 CFRelease(v); 387 CFRelease(v);
342 388
343 VTCompressionSessionRef session; 389 // Create the compression session.
390
391 // Note that the encoder object is given to the compression session as the
392 // callback context using a raw pointer. The C API does not allow us to use a
393 // smart pointer, nor is this encoder ref counted. However, this is still
394 // safe, because we 1) we own the compression session and 2) we tear it down
395 // safely. When destructing the encoder, the compression session is flushed
396 // and invalidated. Internally, VideoToolbox will join all of its threads
397 // before returning to the client. Therefore, when control returns to us, we
398 // are guaranteed that the output callback will not execute again.
344 OSStatus status = videotoolbox_glue_->VTCompressionSessionCreate( 399 OSStatus status = videotoolbox_glue_->VTCompressionSessionCreate(
345 kCFAllocatorDefault, frame_size_.width(), frame_size_.height(), 400 kCFAllocatorDefault, frame_size_.width(), frame_size_.height(),
346 CoreMediaGlue::kCMVideoCodecType_H264, encoder_spec, buffer_attributes, 401 CoreMediaGlue::kCMVideoCodecType_H264, encoder_spec, buffer_attributes,
347 nullptr /* compressedDataAllocator */, 402 nullptr /* compressedDataAllocator */,
348 &H264VideoToolboxEncoder::CompressionCallback, 403 &H264VideoToolboxEncoder::CompressionCallback,
349 reinterpret_cast<void*>(this), &session); 404 reinterpret_cast<void*>(this), compression_session_.InitializeInto());
350 if (status != noErr) { 405 if (status != noErr) {
351 DLOG(ERROR) << " VTCompressionSessionCreate failed: " << status; 406 DLOG(ERROR) << " VTCompressionSessionCreate failed: " << status;
352 return false; 407 // Notify that reinitialization has failed.
408 cast_environment_->PostTask(
409 CastEnvironment::MAIN, FROM_HERE,
410 base::Bind(status_change_cb_, STATUS_CODEC_INIT_FAILED));
411 return;
353 } 412 }
354 compression_session_.reset(session);
355 413
356 ConfigureSession(video_config); 414 // Configure the session (apply session properties based on the current state
415 // of the encoder, experimental tuning and requirements).
416 ConfigureCompressionSession();
357 417
358 return true; 418 // Update the video frame factory.
419 base::ScopedCFTypeRef<CVPixelBufferPoolRef> pool(
420 videotoolbox_glue_->VTCompressionSessionGetPixelBufferPool(
421 compression_session_),
422 base::scoped_policy::RETAIN);
423 video_frame_factory_->Update(pool, frame_size_);
424
425 // Notify that reinitialization is done.
426 cast_environment_->PostTask(
427 CastEnvironment::MAIN, FROM_HERE,
428 base::Bind(status_change_cb_, STATUS_INITIALIZED));
359 } 429 }
360 430
361 void H264VideoToolboxEncoder::ConfigureSession( 431 void H264VideoToolboxEncoder::ConfigureCompressionSession() {
362 const VideoSenderConfig& video_config) {
363 SetSessionProperty( 432 SetSessionProperty(
364 videotoolbox_glue_->kVTCompressionPropertyKey_ProfileLevel(), 433 videotoolbox_glue_->kVTCompressionPropertyKey_ProfileLevel(),
365 videotoolbox_glue_->kVTProfileLevel_H264_Main_AutoLevel()); 434 videotoolbox_glue_->kVTProfileLevel_H264_Main_AutoLevel());
366 SetSessionProperty(videotoolbox_glue_->kVTCompressionPropertyKey_RealTime(), 435 SetSessionProperty(videotoolbox_glue_->kVTCompressionPropertyKey_RealTime(),
367 true); 436 true);
368 SetSessionProperty( 437 SetSessionProperty(
369 videotoolbox_glue_->kVTCompressionPropertyKey_AllowFrameReordering(), 438 videotoolbox_glue_->kVTCompressionPropertyKey_AllowFrameReordering(),
370 false); 439 false);
371 SetSessionProperty( 440 SetSessionProperty(
372 videotoolbox_glue_->kVTCompressionPropertyKey_MaxKeyFrameInterval(), 240); 441 videotoolbox_glue_->kVTCompressionPropertyKey_MaxKeyFrameInterval(), 240);
373 SetSessionProperty( 442 SetSessionProperty(
374 videotoolbox_glue_ 443 videotoolbox_glue_
375 ->kVTCompressionPropertyKey_MaxKeyFrameIntervalDuration(), 444 ->kVTCompressionPropertyKey_MaxKeyFrameIntervalDuration(),
376 240); 445 240);
377 // TODO(jfroy): implement better bitrate control 446 // TODO(jfroy): implement better bitrate control
378 // https://crbug.com/425352 447 // https://crbug.com/425352
379 SetSessionProperty( 448 SetSessionProperty(
380 videotoolbox_glue_->kVTCompressionPropertyKey_AverageBitRate(), 449 videotoolbox_glue_->kVTCompressionPropertyKey_AverageBitRate(),
381 (video_config.min_bitrate + video_config.max_bitrate) / 2); 450 (video_config_.min_bitrate + video_config_.max_bitrate) / 2);
382 SetSessionProperty( 451 SetSessionProperty(
383 videotoolbox_glue_->kVTCompressionPropertyKey_ExpectedFrameRate(), 452 videotoolbox_glue_->kVTCompressionPropertyKey_ExpectedFrameRate(),
384 video_config.max_frame_rate); 453 video_config_.max_frame_rate);
385 // Keep these attachment settings in-sync with those in Initialize(). 454 // Keep these attachment settings in-sync with those in Initialize().
386 SetSessionProperty( 455 SetSessionProperty(
387 videotoolbox_glue_->kVTCompressionPropertyKey_ColorPrimaries(), 456 videotoolbox_glue_->kVTCompressionPropertyKey_ColorPrimaries(),
388 kCVImageBufferColorPrimaries_ITU_R_709_2); 457 kCVImageBufferColorPrimaries_ITU_R_709_2);
389 SetSessionProperty( 458 SetSessionProperty(
390 videotoolbox_glue_->kVTCompressionPropertyKey_TransferFunction(), 459 videotoolbox_glue_->kVTCompressionPropertyKey_TransferFunction(),
391 kCVImageBufferTransferFunction_ITU_R_709_2); 460 kCVImageBufferTransferFunction_ITU_R_709_2);
392 SetSessionProperty( 461 SetSessionProperty(
393 videotoolbox_glue_->kVTCompressionPropertyKey_YCbCrMatrix(), 462 videotoolbox_glue_->kVTCompressionPropertyKey_YCbCrMatrix(),
394 kCVImageBufferYCbCrMatrix_ITU_R_709_2); 463 kCVImageBufferYCbCrMatrix_ITU_R_709_2);
395 if (video_config.max_number_of_video_buffers_used > 0) { 464 if (video_config_.max_number_of_video_buffers_used > 0) {
396 SetSessionProperty( 465 SetSessionProperty(
397 videotoolbox_glue_->kVTCompressionPropertyKey_MaxFrameDelayCount(), 466 videotoolbox_glue_->kVTCompressionPropertyKey_MaxFrameDelayCount(),
398 video_config.max_number_of_video_buffers_used); 467 video_config_.max_number_of_video_buffers_used);
399 } 468 }
400 } 469 }
401 470
402 void H264VideoToolboxEncoder::Teardown() { 471 void H264VideoToolboxEncoder::DestroyCompressionSession() {
403 DCHECK(thread_checker_.CalledOnValidThread()); 472 DCHECK(thread_checker_.CalledOnValidThread());
404 473
405 // If the compression session exists, invalidate it. This blocks until all 474 // If the compression session exists, invalidate it. This blocks until all
406 // pending output callbacks have returned and any internal threads have 475 // pending output callbacks have returned and any internal threads have
407 // joined, ensuring no output callback ever sees a dangling encoder pointer. 476 // joined, ensuring no output callback ever sees a dangling encoder pointer.
408 if (compression_session_) { 477 if (compression_session_) {
409 videotoolbox_glue_->VTCompressionSessionInvalidate(compression_session_); 478 videotoolbox_glue_->VTCompressionSessionInvalidate(compression_session_);
410 compression_session_.reset(); 479 compression_session_.reset();
411 } 480 }
412 } 481 }
413 482
414 bool H264VideoToolboxEncoder::EncodeVideoFrame( 483 bool H264VideoToolboxEncoder::EncodeVideoFrame(
415 const scoped_refptr<media::VideoFrame>& video_frame, 484 const scoped_refptr<media::VideoFrame>& video_frame,
416 const base::TimeTicks& reference_time, 485 const base::TimeTicks& reference_time,
417 const FrameEncodedCallback& frame_encoded_callback) { 486 const FrameEncodedCallback& frame_encoded_callback) {
418 DCHECK(thread_checker_.CalledOnValidThread()); 487 DCHECK(thread_checker_.CalledOnValidThread());
419 DCHECK(!frame_encoded_callback.is_null()); 488 DCHECK(!frame_encoded_callback.is_null());
420 489
421 if (!compression_session_) { 490 // Reject empty video frames.
422 DLOG(ERROR) << " compression session is null"; 491 const gfx::Size frame_size = video_frame->visible_rect().size();
492 if (frame_size.IsEmpty()) {
493 DVLOG(1) << "Rejecting empty video frame.";
423 return false; 494 return false;
424 } 495 }
425 496
426 if (video_frame->visible_rect().size() != frame_size_) 497 // Handle frame size changes. This will reset the compression session.
498 if (frame_size != frame_size_) {
499 DVLOG(1) << "EncodeVideoFrame: Detected frame size change.";
500 UpdateFrameSize(frame_size);
501
502 // Tests and clients expect |EncodeVideoFrame| to fail on frame size changes
miu 2015/04/21 07:20:00 Wait. We shouldn't sacrifice production performan
jfroy 2015/04/21 16:07:54 video_encoder_unittest EncodesVariedFrameSizes, th
503 // because the encoder is resetting. So even though we reset the compression
504 // session synchronously, we must fail this request.
427 return false; 505 return false;
506 }
507
508 // Need a compression session to continue.
509 if (!compression_session_) {
510 DLOG(ERROR) << "No compression session.";
511 return false;
512 }
428 513
429 // Wrap the VideoFrame in a CVPixelBuffer. In all cases, no data will be 514 // Wrap the VideoFrame in a CVPixelBuffer. In all cases, no data will be
430 // copied. If the VideoFrame was created by this encoder's video frame 515 // copied. If the VideoFrame was created by this encoder's video frame
431 // factory, then the returned CVPixelBuffer will have been obtained from the 516 // factory, then the returned CVPixelBuffer will have been obtained from the
432 // compression session's pixel buffer pool. This will eliminate a copy of the 517 // compression session's pixel buffer pool. This will eliminate a copy of the
433 // frame into memory visible by the hardware encoder. The VideoFrame's 518 // frame into memory visible by the hardware encoder. The VideoFrame's
434 // lifetime is extended for the lifetime of the returned CVPixelBuffer. 519 // lifetime is extended for the lifetime of the returned CVPixelBuffer.
435 auto pixel_buffer = media::WrapVideoFrameInCVPixelBuffer(*video_frame); 520 auto pixel_buffer = media::WrapVideoFrameInCVPixelBuffer(*video_frame);
436 if (!pixel_buffer) { 521 if (!pixel_buffer) {
522 DLOG(ERROR) << "WrapVideoFrameInCVPixelBuffer failed.";
437 return false; 523 return false;
438 } 524 }
439 525
526 // Convert the frame timestamp to CMTime.
440 auto timestamp_cm = CoreMediaGlue::CMTimeMake( 527 auto timestamp_cm = CoreMediaGlue::CMTimeMake(
441 (reference_time - base::TimeTicks()).InMicroseconds(), USEC_PER_SEC); 528 (reference_time - base::TimeTicks()).InMicroseconds(), USEC_PER_SEC);
442 529
530 // Wrap information we'll need after the frame is encoded in a heap object.
531 // We'll get the pointer back from the VideoToolbox completion callback.
443 scoped_ptr<InProgressFrameEncode> request(new InProgressFrameEncode( 532 scoped_ptr<InProgressFrameEncode> request(new InProgressFrameEncode(
444 TimeDeltaToRtpDelta(video_frame->timestamp(), kVideoFrequency), 533 TimeDeltaToRtpDelta(video_frame->timestamp(), kVideoFrequency),
445 reference_time, frame_encoded_callback)); 534 reference_time, frame_encoded_callback));
446 535
536 // Build a suitable frame properties dictionary for keyframes.
447 base::ScopedCFTypeRef<CFDictionaryRef> frame_props; 537 base::ScopedCFTypeRef<CFDictionaryRef> frame_props;
448 if (encode_next_frame_as_keyframe_) { 538 if (encode_next_frame_as_keyframe_) {
449 frame_props = DictionaryWithKeyValue( 539 frame_props = DictionaryWithKeyValue(
450 videotoolbox_glue_->kVTEncodeFrameOptionKey_ForceKeyFrame(), 540 videotoolbox_glue_->kVTEncodeFrameOptionKey_ForceKeyFrame(),
451 kCFBooleanTrue); 541 kCFBooleanTrue);
452 encode_next_frame_as_keyframe_ = false; 542 encode_next_frame_as_keyframe_ = false;
453 } 543 }
454 544
455 VTEncodeInfoFlags info; 545 // Submit the frame to the compression session. The function returns as soon
546 // as the frame has been enqueued.
456 OSStatus status = videotoolbox_glue_->VTCompressionSessionEncodeFrame( 547 OSStatus status = videotoolbox_glue_->VTCompressionSessionEncodeFrame(
457 compression_session_, pixel_buffer, timestamp_cm, 548 compression_session_, pixel_buffer, timestamp_cm,
458 CoreMediaGlue::CMTime{0, 0, 0, 0}, frame_props, 549 CoreMediaGlue::CMTime{0, 0, 0, 0}, frame_props,
459 reinterpret_cast<void*>(request.release()), &info); 550 reinterpret_cast<void*>(request.release()), nullptr);
460 if (status != noErr) { 551 if (status != noErr) {
461 DLOG(ERROR) << " VTCompressionSessionEncodeFrame failed: " << status; 552 DLOG(ERROR) << " VTCompressionSessionEncodeFrame failed: " << status;
462 return false; 553 return false;
463 } 554 }
464 if ((info & VideoToolboxGlue::kVTEncodeInfo_FrameDropped)) {
465 DLOG(ERROR) << " frame dropped";
466 return false;
467 }
468 555
469 return true; 556 return true;
470 } 557 }
471 558
472 void H264VideoToolboxEncoder::SetBitRate(int new_bit_rate) { 559 void H264VideoToolboxEncoder::UpdateFrameSize(const gfx::Size& size_needed) {
560 DCHECK(thread_checker_.CalledOnValidThread());
561
562 // Our video frame factory posts a task to update the frame size when its
563 // cache of the frame size differs from what the client requested. To avoid
564 // spurious encoder resets, check again here.
565 if (size_needed == frame_size_) {
566 DCHECK(compression_session_);
567 return;
568 }
569
570 VLOG(1) << "Resetting compression session (for frame size change from "
571 << frame_size_.ToString() << " to " << size_needed.ToString() << ").";
572
573 // If there is an existing session, finish every pending frame.
574 if (compression_session_) {
575 EmitFrames();
576 }
577
578 // Store the new frame size.
579 frame_size_ = size_needed;
580
581 // Reset the compression session.
582 ResetCompressionSession();
583 }
584
585 void H264VideoToolboxEncoder::SetBitRate(int /*new_bit_rate*/) {
473 DCHECK(thread_checker_.CalledOnValidThread()); 586 DCHECK(thread_checker_.CalledOnValidThread());
474 // VideoToolbox does not seem to support bitrate reconfiguration. 587 // VideoToolbox does not seem to support bitrate reconfiguration.
475 } 588 }
476 589
477 void H264VideoToolboxEncoder::GenerateKeyFrame() { 590 void H264VideoToolboxEncoder::GenerateKeyFrame() {
478 DCHECK(thread_checker_.CalledOnValidThread()); 591 DCHECK(thread_checker_.CalledOnValidThread());
479 DCHECK(compression_session_);
480
481 encode_next_frame_as_keyframe_ = true; 592 encode_next_frame_as_keyframe_ = true;
482 } 593 }
483 594
484 void H264VideoToolboxEncoder::LatestFrameIdToReference(uint32 /*frame_id*/) { 595 void H264VideoToolboxEncoder::LatestFrameIdToReference(uint32 /*frame_id*/) {
485 // Not supported by VideoToolbox in any meaningful manner. 596 // Not supported by VideoToolbox in any meaningful manner.
486 } 597 }
487 598
488 scoped_ptr<VideoFrameFactory> 599 scoped_ptr<VideoFrameFactory>
489 H264VideoToolboxEncoder::CreateVideoFrameFactory() { 600 H264VideoToolboxEncoder::CreateVideoFrameFactory() {
490 if (!videotoolbox_glue_ || !compression_session_) 601 DCHECK(thread_checker_.CalledOnValidThread());
491 return nullptr;
492 base::ScopedCFTypeRef<CVPixelBufferPoolRef> pool(
493 videotoolbox_glue_->VTCompressionSessionGetPixelBufferPool(
494 compression_session_),
495 base::scoped_policy::RETAIN);
496 return scoped_ptr<VideoFrameFactory>( 602 return scoped_ptr<VideoFrameFactory>(
497 new VideoFrameFactoryCVPixelBufferPoolImpl(pool, frame_size_)); 603 new VideoFrameFactoryImpl::Proxy(video_frame_factory_));
498 } 604 }
499 605
500 void H264VideoToolboxEncoder::EmitFrames() { 606 void H264VideoToolboxEncoder::EmitFrames() {
501 DCHECK(thread_checker_.CalledOnValidThread()); 607 DCHECK(thread_checker_.CalledOnValidThread());
502 608 if (!compression_session_)
503 if (!compression_session_) {
504 DLOG(ERROR) << " compression session is null";
505 return; 609 return;
506 }
507 610
508 OSStatus status = videotoolbox_glue_->VTCompressionSessionCompleteFrames( 611 OSStatus status = videotoolbox_glue_->VTCompressionSessionCompleteFrames(
509 compression_session_, CoreMediaGlue::CMTime{0, 0, 0, 0}); 612 compression_session_, CoreMediaGlue::CMTime{0, 0, 0, 0});
510 if (status != noErr) { 613 if (status != noErr) {
511 DLOG(ERROR) << " VTCompressionSessionCompleteFrames failed: " << status; 614 DLOG(ERROR) << " VTCompressionSessionCompleteFrames failed: " << status;
512 } 615 }
513 } 616 }
514 617
515 bool H264VideoToolboxEncoder::SetSessionProperty(CFStringRef key, 618 bool H264VideoToolboxEncoder::SetSessionProperty(CFStringRef key,
516 int32_t value) { 619 int32_t value) {
(...skipping 22 matching lines...) Expand all
539 CMSampleBufferRef sbuf) { 642 CMSampleBufferRef sbuf) {
540 auto encoder = reinterpret_cast<H264VideoToolboxEncoder*>(encoder_opaque); 643 auto encoder = reinterpret_cast<H264VideoToolboxEncoder*>(encoder_opaque);
541 const scoped_ptr<InProgressFrameEncode> request( 644 const scoped_ptr<InProgressFrameEncode> request(
542 reinterpret_cast<InProgressFrameEncode*>(request_opaque)); 645 reinterpret_cast<InProgressFrameEncode*>(request_opaque));
543 bool keyframe = false; 646 bool keyframe = false;
544 bool has_frame_data = false; 647 bool has_frame_data = false;
545 648
546 if (status != noErr) { 649 if (status != noErr) {
547 DLOG(ERROR) << " encoding failed: " << status; 650 DLOG(ERROR) << " encoding failed: " << status;
548 encoder->cast_environment_->PostTask( 651 encoder->cast_environment_->PostTask(
549 CastEnvironment::MAIN, 652 CastEnvironment::MAIN, FROM_HERE,
550 FROM_HERE,
551 base::Bind(encoder->status_change_cb_, STATUS_CODEC_RUNTIME_ERROR)); 653 base::Bind(encoder->status_change_cb_, STATUS_CODEC_RUNTIME_ERROR));
552 } else if ((info & VideoToolboxGlue::kVTEncodeInfo_FrameDropped)) { 654 } else if ((info & VideoToolboxGlue::kVTEncodeInfo_FrameDropped)) {
553 DVLOG(2) << " frame dropped"; 655 DVLOG(2) << " frame dropped";
554 } else { 656 } else {
555 auto sample_attachments = static_cast<CFDictionaryRef>( 657 auto sample_attachments =
556 CFArrayGetValueAtIndex( 658 static_cast<CFDictionaryRef>(CFArrayGetValueAtIndex(
557 CoreMediaGlue::CMSampleBufferGetSampleAttachmentsArray(sbuf, true), 659 CoreMediaGlue::CMSampleBufferGetSampleAttachmentsArray(sbuf, true),
558 0)); 660 0));
559 661
560 // If the NotSync key is not present, it implies Sync, which indicates a 662 // If the NotSync key is not present, it implies Sync, which indicates a
561 // keyframe (at least I think, VT documentation is, erm, sparse). Could 663 // keyframe (at least I think, VT documentation is, erm, sparse). Could
562 // alternatively use kCMSampleAttachmentKey_DependsOnOthers == false. 664 // alternatively use kCMSampleAttachmentKey_DependsOnOthers == false.
563 keyframe = !CFDictionaryContainsKey( 665 keyframe = !CFDictionaryContainsKey(
564 sample_attachments, 666 sample_attachments,
565 CoreMediaGlue::kCMSampleAttachmentKey_NotSync()); 667 CoreMediaGlue::kCMSampleAttachmentKey_NotSync());
566 has_frame_data = true; 668 has_frame_data = true;
567 } 669 }
568 670
569 // Increment the encoder-scoped frame id and assign the new value to this 671 // Increment the encoder-scoped frame id and assign the new value to this
570 // frame. VideoToolbox calls the output callback serially, so this is safe. 672 // frame. VideoToolbox calls the output callback serially, so this is safe.
571 const uint32 frame_id = encoder->next_frame_id_++; 673 const uint32 frame_id = ++encoder->last_frame_id_;
572 674
573 scoped_ptr<EncodedFrame> encoded_frame(new EncodedFrame()); 675 scoped_ptr<EncodedFrame> encoded_frame(new EncodedFrame());
574 encoded_frame->frame_id = frame_id; 676 encoded_frame->frame_id = frame_id;
575 encoded_frame->reference_time = request->reference_time; 677 encoded_frame->reference_time = request->reference_time;
576 encoded_frame->rtp_timestamp = request->rtp_timestamp; 678 encoded_frame->rtp_timestamp = request->rtp_timestamp;
577 if (keyframe) { 679 if (keyframe) {
578 encoded_frame->dependency = EncodedFrame::KEY; 680 encoded_frame->dependency = EncodedFrame::KEY;
579 encoded_frame->referenced_frame_id = frame_id; 681 encoded_frame->referenced_frame_id = frame_id;
580 } else { 682 } else {
581 encoded_frame->dependency = EncodedFrame::DEPENDENT; 683 encoded_frame->dependency = EncodedFrame::DEPENDENT;
(...skipping 11 matching lines...) Expand all
593 695
594 if (has_frame_data) 696 if (has_frame_data)
595 CopySampleBufferToAnnexBBuffer(sbuf, &encoded_frame->data, keyframe); 697 CopySampleBufferToAnnexBBuffer(sbuf, &encoded_frame->data, keyframe);
596 698
597 encoder->cast_environment_->PostTask( 699 encoder->cast_environment_->PostTask(
598 CastEnvironment::MAIN, FROM_HERE, 700 CastEnvironment::MAIN, FROM_HERE,
599 base::Bind(request->frame_encoded_callback, 701 base::Bind(request->frame_encoded_callback,
600 base::Passed(&encoded_frame))); 702 base::Passed(&encoded_frame)));
601 } 703 }
602 704
603 // A ref-counted structure that is shared to provide concurrent access to the
604 // VideoFrameFactory instance for the current encoder. OnEncoderReplaced() can
605 // change |factory| whenever an encoder instance has been replaced, while users
606 // of CreateVideoFrameFactory() may attempt to read/use |factory| by any thread
607 // at any time.
608 struct SizeAdaptableH264VideoToolboxVideoEncoder::FactoryHolder
609 : public base::RefCountedThreadSafe<FactoryHolder> {
610 base::Lock lock;
611 scoped_ptr<VideoFrameFactory> factory;
612
613 private:
614 friend class base::RefCountedThreadSafe<FactoryHolder>;
615 ~FactoryHolder() {}
616 };
617
618 SizeAdaptableH264VideoToolboxVideoEncoder::
619 SizeAdaptableH264VideoToolboxVideoEncoder(
620 const scoped_refptr<CastEnvironment>& cast_environment,
621 const VideoSenderConfig& video_config,
622 const StatusChangeCallback& status_change_cb)
623 : SizeAdaptableVideoEncoderBase(cast_environment,
624 video_config,
625 status_change_cb),
626 holder_(new FactoryHolder()) {}
627
628 SizeAdaptableH264VideoToolboxVideoEncoder::
629 ~SizeAdaptableH264VideoToolboxVideoEncoder() {}
630
631 // A proxy allowing SizeAdaptableH264VideoToolboxVideoEncoder to swap out the
632 // VideoFrameFactory instance to match one appropriate for the current encoder
633 // instance.
634 class SizeAdaptableH264VideoToolboxVideoEncoder::VideoFrameFactoryProxy
635 : public VideoFrameFactory {
636 public:
637 explicit VideoFrameFactoryProxy(const scoped_refptr<FactoryHolder>& holder)
638 : holder_(holder) {}
639
640 ~VideoFrameFactoryProxy() override {}
641
642 scoped_refptr<VideoFrame> MaybeCreateFrame(
643 const gfx::Size& frame_size, base::TimeDelta timestamp) override {
644 base::AutoLock auto_lock(holder_->lock);
645 return holder_->factory ?
646 holder_->factory->MaybeCreateFrame(frame_size, timestamp) : nullptr;
647 }
648
649 private:
650 const scoped_refptr<FactoryHolder> holder_;
651
652 DISALLOW_COPY_AND_ASSIGN(VideoFrameFactoryProxy);
653 };
654
655 scoped_ptr<VideoFrameFactory>
656 SizeAdaptableH264VideoToolboxVideoEncoder::CreateVideoFrameFactory() {
657 return scoped_ptr<VideoFrameFactory>(new VideoFrameFactoryProxy(holder_));
658 }
659
660 scoped_ptr<VideoEncoder>
661 SizeAdaptableH264VideoToolboxVideoEncoder::CreateEncoder() {
662 return scoped_ptr<VideoEncoder>(new H264VideoToolboxEncoder(
663 cast_environment(),
664 video_config(),
665 frame_size(),
666 last_frame_id() + 1,
667 CreateEncoderStatusChangeCallback()));
668 }
669
670 void SizeAdaptableH264VideoToolboxVideoEncoder::OnEncoderReplaced(
671 VideoEncoder* replacement_encoder) {
672 scoped_ptr<VideoFrameFactory> current_factory(
673 replacement_encoder->CreateVideoFrameFactory());
674 base::AutoLock auto_lock(holder_->lock);
675 holder_->factory = current_factory.Pass();
676 SizeAdaptableVideoEncoderBase::OnEncoderReplaced(replacement_encoder);
677 }
678
679 void SizeAdaptableH264VideoToolboxVideoEncoder::DestroyEncoder() {
680 {
681 base::AutoLock auto_lock(holder_->lock);
682 holder_->factory.reset();
683 }
684 SizeAdaptableVideoEncoderBase::DestroyEncoder();
685 }
686
687 } // namespace cast 705 } // namespace cast
688 } // namespace media 706 } // namespace media
OLDNEW
« no previous file with comments | « media/cast/sender/h264_vt_encoder.h ('k') | media/cast/sender/h264_vt_encoder_unittest.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698