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

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: Video frame factory rejects empty frame sizes. 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 if (frame_size.IsEmpty()) {
223 DVLOG(1) << "Rejecting empty video frame.";
224 return nullptr;
225 }
227 226
227 base::AutoLock auto_lock(lock_);
228
229 // If the pool size does not match, speculatively reset the encoder to use
230 // the new size and return null. Cache the new frame size right away and
231 // toss away the pixel buffer pool to avoid spurious tasks until the encoder
232 // is done resetting.
233 if (frame_size != pool_frame_size_) {
234 DVLOG(1) << "MaybeCreateFrame: Detected frame size change.";
235 cast_environment_->PostTask(
236 CastEnvironment::MAIN, FROM_HERE,
237 base::Bind(&H264VideoToolboxEncoder::UpdateFrameSize, encoder_,
238 frame_size));
239 pool_frame_size_ = frame_size;
240 pool_.reset();
241 return nullptr;
242 }
243
244 if (!pool_) {
245 DVLOG(1) << "MaybeCreateFrame: No pixel buffer pool.";
246 return nullptr;
247 }
248
249 // Allocate a pixel buffer from the pool and return a wrapper VideoFrame.
228 base::ScopedCFTypeRef<CVPixelBufferRef> buffer; 250 base::ScopedCFTypeRef<CVPixelBufferRef> buffer;
229 if (CVPixelBufferPoolCreatePixelBuffer(kCFAllocatorDefault, pool_, 251 auto status = CVPixelBufferPoolCreatePixelBuffer(kCFAllocatorDefault, pool_,
230 buffer.InitializeInto()) != 252 buffer.InitializeInto());
231 kCVReturnSuccess) 253 if (status != kCVReturnSuccess) {
232 return nullptr; // Buffer pool has run out of pixel buffers. 254 DLOG(ERROR) << "CVPixelBufferPoolCreatePixelBuffer failed: " << status;
255 return nullptr;
256 }
257
233 DCHECK(buffer); 258 DCHECK(buffer);
234
235 return VideoFrame::WrapCVPixelBuffer(buffer, timestamp); 259 return VideoFrame::WrapCVPixelBuffer(buffer, timestamp);
236 } 260 }
237 261
262 void Update(const base::ScopedCFTypeRef<CVPixelBufferPoolRef>& pool,
263 const gfx::Size& frame_size) {
264 base::AutoLock auto_lock(lock_);
265 pool_ = pool;
266 pool_frame_size_ = frame_size;
267 }
268
238 private: 269 private:
239 const base::ScopedCFTypeRef<CVPixelBufferPoolRef> pool_; 270 friend class base::RefCountedThreadSafe<VideoFrameFactoryImpl>;
240 const gfx::Size frame_size_; 271 ~VideoFrameFactoryImpl() override {}
241 272
242 DISALLOW_COPY_AND_ASSIGN(VideoFrameFactoryCVPixelBufferPoolImpl); 273 base::Lock lock_;
274 base::ScopedCFTypeRef<CVPixelBufferPoolRef> pool_;
275 gfx::Size pool_frame_size_;
276
277 // Weak back reference to the encoder and the cast envrionment so we can
278 // message the encoder when the frame size changes.
279 const base::WeakPtr<H264VideoToolboxEncoder> encoder_;
280 const scoped_refptr<CastEnvironment> cast_environment_;
281
282 DISALLOW_COPY_AND_ASSIGN(VideoFrameFactoryImpl);
243 }; 283 };
244 284
245 } // namespace 285 class H264VideoToolboxEncoder::VideoFrameFactoryImpl::Proxy
286 : public VideoFrameFactory {
287 public:
288 explicit Proxy(
289 const scoped_refptr<VideoFrameFactoryImpl>& video_frame_factory)
290 : video_frame_factory_(video_frame_factory) {
291 DCHECK(video_frame_factory_);
292 }
293
294 scoped_refptr<VideoFrame> MaybeCreateFrame(
295 const gfx::Size& frame_size,
296 base::TimeDelta timestamp) override {
297 return video_frame_factory_->MaybeCreateFrame(frame_size, timestamp);
298 }
299
300 private:
301 ~Proxy() override {}
302
303 const scoped_refptr<VideoFrameFactoryImpl> video_frame_factory_;
304
305 DISALLOW_COPY_AND_ASSIGN(Proxy);
306 };
246 307
247 // static 308 // static
248 bool H264VideoToolboxEncoder::IsSupported( 309 bool H264VideoToolboxEncoder::IsSupported(
249 const VideoSenderConfig& video_config) { 310 const VideoSenderConfig& video_config) {
250 return video_config.codec == CODEC_VIDEO_H264 && VideoToolboxGlue::Get(); 311 return video_config.codec == CODEC_VIDEO_H264 && VideoToolboxGlue::Get();
251 } 312 }
252 313
253 H264VideoToolboxEncoder::H264VideoToolboxEncoder( 314 H264VideoToolboxEncoder::H264VideoToolboxEncoder(
254 const scoped_refptr<CastEnvironment>& cast_environment, 315 const scoped_refptr<CastEnvironment>& cast_environment,
255 const VideoSenderConfig& video_config, 316 const VideoSenderConfig& video_config,
256 const gfx::Size& frame_size,
257 uint32 first_frame_id,
258 const StatusChangeCallback& status_change_cb) 317 const StatusChangeCallback& status_change_cb)
259 : cast_environment_(cast_environment), 318 : cast_environment_(cast_environment),
260 videotoolbox_glue_(VideoToolboxGlue::Get()), 319 videotoolbox_glue_(VideoToolboxGlue::Get()),
261 frame_size_(frame_size), 320 video_config_(video_config),
262 status_change_cb_(status_change_cb), 321 status_change_cb_(status_change_cb),
263 next_frame_id_(first_frame_id), 322 last_frame_id_(kStartFrameId),
264 encode_next_frame_as_keyframe_(false) { 323 encode_next_frame_as_keyframe_(false),
265 DCHECK(!frame_size_.IsEmpty()); 324 weak_factory_(this) {
325 DCHECK(cast_environment_->CurrentlyOn(CastEnvironment::MAIN));
266 DCHECK(!status_change_cb_.is_null()); 326 DCHECK(!status_change_cb_.is_null());
267 327
268 OperationalStatus operational_status; 328 OperationalStatus operational_status =
269 if (video_config.codec == CODEC_VIDEO_H264 && videotoolbox_glue_) { 329 H264VideoToolboxEncoder::IsSupported(video_config)
270 operational_status = Initialize(video_config) ? 330 ? STATUS_INITIALIZED
271 STATUS_INITIALIZED : STATUS_INVALID_CONFIGURATION; 331 : STATUS_UNSUPPORTED_CODEC;
272 } else { 332 cast_environment_->PostTask(
273 operational_status = STATUS_UNSUPPORTED_CODEC; 333 CastEnvironment::MAIN, FROM_HERE,
334 base::Bind(status_change_cb_, operational_status));
335
336 if (operational_status == STATUS_INITIALIZED) {
337 video_frame_factory_ =
338 scoped_refptr<VideoFrameFactoryImpl>(new VideoFrameFactoryImpl(
339 weak_factory_.GetWeakPtr(), cast_environment_));
274 } 340 }
275 cast_environment_->PostTask(
276 CastEnvironment::MAIN,
277 FROM_HERE,
278 base::Bind(status_change_cb_, operational_status));
279 } 341 }
280 342
281 H264VideoToolboxEncoder::~H264VideoToolboxEncoder() { 343 H264VideoToolboxEncoder::~H264VideoToolboxEncoder() {
282 Teardown(); 344 DestroyCompressionSession();
283 } 345 }
284 346
285 bool H264VideoToolboxEncoder::Initialize( 347 void H264VideoToolboxEncoder::ResetCompressionSession() {
286 const VideoSenderConfig& video_config) {
287 DCHECK(thread_checker_.CalledOnValidThread()); 348 DCHECK(thread_checker_.CalledOnValidThread());
288 DCHECK(!compression_session_);
289 349
290 // Note that the encoder object is given to the compression session as the 350 // Notify that we're resetting the encoder.
291 // callback context using a raw pointer. The C API does not allow us to use 351 cast_environment_->PostTask(
292 // a smart pointer, nor is this encoder ref counted. However, this is still 352 CastEnvironment::MAIN, FROM_HERE,
293 // safe, because we 1) we own the compression session and 2) we tear it down 353 base::Bind(status_change_cb_, STATUS_CODEC_REINIT_PENDING));
294 // safely. When destructing the encoder, the compression session is flushed 354
295 // and invalidated. Internally, VideoToolbox will join all of its threads 355 // Destroy the current session, if any.
296 // before returning to the client. Therefore, when control returns to us, we 356 DestroyCompressionSession();
297 // are guaranteed that the output callback will not execute again.
298 357
299 // On OS X, allow the hardware encoder. Don't require it, it does not support 358 // 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). 359 // all configurations (some of which are used for testing).
301 base::ScopedCFTypeRef<CFDictionaryRef> encoder_spec; 360 base::ScopedCFTypeRef<CFDictionaryRef> encoder_spec;
302 #if !defined(OS_IOS) 361 #if !defined(OS_IOS)
303 encoder_spec = DictionaryWithKeyValue( 362 encoder_spec = DictionaryWithKeyValue(
304 videotoolbox_glue_ 363 videotoolbox_glue_
305 ->kVTVideoEncoderSpecification_EnableHardwareAcceleratedVideoEncoder() , 364 ->kVTVideoEncoderSpecification_EnableHardwareAcceleratedVideoEncoder() ,
306 kCFBooleanTrue); 365 kCFBooleanTrue);
307 #endif 366 #endif
308 367
309 // Certain encoders prefer kCVPixelFormatType_422YpCbCr8, which is not 368 // Certain encoders prefer kCVPixelFormatType_422YpCbCr8, which is not
310 // supported through VideoFrame. We can force 420 formats to be used instead. 369 // supported through VideoFrame. We can force 420 formats to be used instead.
311 const int formats[] = { 370 const int formats[] = {
312 kCVPixelFormatType_420YpCbCr8Planar, 371 kCVPixelFormatType_420YpCbCr8Planar,
313 CoreVideoGlue::kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange 372 CoreVideoGlue::kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange};
314 };
315 // Keep these attachment settings in-sync with those in ConfigureSession(). 373 // Keep these attachment settings in-sync with those in ConfigureSession().
316 CFTypeRef attachments_keys[] = { 374 CFTypeRef attachments_keys[] = {kCVImageBufferColorPrimariesKey,
317 kCVImageBufferColorPrimariesKey, 375 kCVImageBufferTransferFunctionKey,
318 kCVImageBufferTransferFunctionKey, 376 kCVImageBufferYCbCrMatrixKey};
319 kCVImageBufferYCbCrMatrixKey 377 CFTypeRef attachments_values[] = {kCVImageBufferColorPrimaries_ITU_R_709_2,
320 }; 378 kCVImageBufferTransferFunction_ITU_R_709_2,
321 CFTypeRef attachments_values[] = { 379 kCVImageBufferYCbCrMatrix_ITU_R_709_2};
322 kCVImageBufferColorPrimaries_ITU_R_709_2, 380 CFTypeRef buffer_attributes_keys[] = {kCVPixelBufferPixelFormatTypeKey,
323 kCVImageBufferTransferFunction_ITU_R_709_2, 381 kCVBufferPropagatedAttachmentsKey};
324 kCVImageBufferYCbCrMatrix_ITU_R_709_2
325 };
326 CFTypeRef buffer_attributes_keys[] = {
327 kCVPixelBufferPixelFormatTypeKey,
328 kCVBufferPropagatedAttachmentsKey
329 };
330 CFTypeRef buffer_attributes_values[] = { 382 CFTypeRef buffer_attributes_values[] = {
331 ArrayWithIntegers(formats, arraysize(formats)).release(), 383 ArrayWithIntegers(formats, arraysize(formats)).release(),
332 DictionaryWithKeysAndValues(attachments_keys, 384 DictionaryWithKeysAndValues(attachments_keys, attachments_values,
333 attachments_values, 385 arraysize(attachments_keys)).release()};
334 arraysize(attachments_keys)).release()
335 };
336 const base::ScopedCFTypeRef<CFDictionaryRef> buffer_attributes = 386 const base::ScopedCFTypeRef<CFDictionaryRef> buffer_attributes =
337 DictionaryWithKeysAndValues(buffer_attributes_keys, 387 DictionaryWithKeysAndValues(buffer_attributes_keys,
338 buffer_attributes_values, 388 buffer_attributes_values,
339 arraysize(buffer_attributes_keys)); 389 arraysize(buffer_attributes_keys));
340 for (auto& v : buffer_attributes_values) 390 for (auto& v : buffer_attributes_values)
341 CFRelease(v); 391 CFRelease(v);
342 392
343 VTCompressionSessionRef session; 393 // Create the compression session.
394
395 // Note that the encoder object is given to the compression session as the
396 // callback context using a raw pointer. The C API does not allow us to use a
397 // smart pointer, nor is this encoder ref counted. However, this is still
398 // safe, because we 1) we own the compression session and 2) we tear it down
399 // safely. When destructing the encoder, the compression session is flushed
400 // and invalidated. Internally, VideoToolbox will join all of its threads
401 // before returning to the client. Therefore, when control returns to us, we
402 // are guaranteed that the output callback will not execute again.
344 OSStatus status = videotoolbox_glue_->VTCompressionSessionCreate( 403 OSStatus status = videotoolbox_glue_->VTCompressionSessionCreate(
345 kCFAllocatorDefault, frame_size_.width(), frame_size_.height(), 404 kCFAllocatorDefault, frame_size_.width(), frame_size_.height(),
346 CoreMediaGlue::kCMVideoCodecType_H264, encoder_spec, buffer_attributes, 405 CoreMediaGlue::kCMVideoCodecType_H264, encoder_spec, buffer_attributes,
347 nullptr /* compressedDataAllocator */, 406 nullptr /* compressedDataAllocator */,
348 &H264VideoToolboxEncoder::CompressionCallback, 407 &H264VideoToolboxEncoder::CompressionCallback,
349 reinterpret_cast<void*>(this), &session); 408 reinterpret_cast<void*>(this), compression_session_.InitializeInto());
350 if (status != noErr) { 409 if (status != noErr) {
351 DLOG(ERROR) << " VTCompressionSessionCreate failed: " << status; 410 DLOG(ERROR) << " VTCompressionSessionCreate failed: " << status;
352 return false; 411 // Notify that reinitialization has failed.
412 cast_environment_->PostTask(
413 CastEnvironment::MAIN, FROM_HERE,
414 base::Bind(status_change_cb_, STATUS_CODEC_INIT_FAILED));
415 return;
353 } 416 }
354 compression_session_.reset(session);
355 417
356 ConfigureSession(video_config); 418 // Configure the session (apply session properties based on the current state
419 // of the encoder, experimental tuning and requirements).
420 ConfigureCompressionSession();
357 421
358 return true; 422 // Update the video frame factory.
423 base::ScopedCFTypeRef<CVPixelBufferPoolRef> pool(
424 videotoolbox_glue_->VTCompressionSessionGetPixelBufferPool(
425 compression_session_),
426 base::scoped_policy::RETAIN);
427 video_frame_factory_->Update(pool, frame_size_);
428
429 // Notify that reinitialization is done.
430 cast_environment_->PostTask(
431 CastEnvironment::MAIN, FROM_HERE,
432 base::Bind(status_change_cb_, STATUS_INITIALIZED));
359 } 433 }
360 434
361 void H264VideoToolboxEncoder::ConfigureSession( 435 void H264VideoToolboxEncoder::ConfigureCompressionSession() {
362 const VideoSenderConfig& video_config) {
363 SetSessionProperty( 436 SetSessionProperty(
364 videotoolbox_glue_->kVTCompressionPropertyKey_ProfileLevel(), 437 videotoolbox_glue_->kVTCompressionPropertyKey_ProfileLevel(),
365 videotoolbox_glue_->kVTProfileLevel_H264_Main_AutoLevel()); 438 videotoolbox_glue_->kVTProfileLevel_H264_Main_AutoLevel());
366 SetSessionProperty(videotoolbox_glue_->kVTCompressionPropertyKey_RealTime(), 439 SetSessionProperty(videotoolbox_glue_->kVTCompressionPropertyKey_RealTime(),
367 true); 440 true);
368 SetSessionProperty( 441 SetSessionProperty(
369 videotoolbox_glue_->kVTCompressionPropertyKey_AllowFrameReordering(), 442 videotoolbox_glue_->kVTCompressionPropertyKey_AllowFrameReordering(),
370 false); 443 false);
371 SetSessionProperty( 444 SetSessionProperty(
372 videotoolbox_glue_->kVTCompressionPropertyKey_MaxKeyFrameInterval(), 240); 445 videotoolbox_glue_->kVTCompressionPropertyKey_MaxKeyFrameInterval(), 240);
373 SetSessionProperty( 446 SetSessionProperty(
374 videotoolbox_glue_ 447 videotoolbox_glue_
375 ->kVTCompressionPropertyKey_MaxKeyFrameIntervalDuration(), 448 ->kVTCompressionPropertyKey_MaxKeyFrameIntervalDuration(),
376 240); 449 240);
377 // TODO(jfroy): implement better bitrate control 450 // TODO(jfroy): implement better bitrate control
378 // https://crbug.com/425352 451 // https://crbug.com/425352
379 SetSessionProperty( 452 SetSessionProperty(
380 videotoolbox_glue_->kVTCompressionPropertyKey_AverageBitRate(), 453 videotoolbox_glue_->kVTCompressionPropertyKey_AverageBitRate(),
381 (video_config.min_bitrate + video_config.max_bitrate) / 2); 454 (video_config_.min_bitrate + video_config_.max_bitrate) / 2);
382 SetSessionProperty( 455 SetSessionProperty(
383 videotoolbox_glue_->kVTCompressionPropertyKey_ExpectedFrameRate(), 456 videotoolbox_glue_->kVTCompressionPropertyKey_ExpectedFrameRate(),
384 video_config.max_frame_rate); 457 video_config_.max_frame_rate);
385 // Keep these attachment settings in-sync with those in Initialize(). 458 // Keep these attachment settings in-sync with those in Initialize().
386 SetSessionProperty( 459 SetSessionProperty(
387 videotoolbox_glue_->kVTCompressionPropertyKey_ColorPrimaries(), 460 videotoolbox_glue_->kVTCompressionPropertyKey_ColorPrimaries(),
388 kCVImageBufferColorPrimaries_ITU_R_709_2); 461 kCVImageBufferColorPrimaries_ITU_R_709_2);
389 SetSessionProperty( 462 SetSessionProperty(
390 videotoolbox_glue_->kVTCompressionPropertyKey_TransferFunction(), 463 videotoolbox_glue_->kVTCompressionPropertyKey_TransferFunction(),
391 kCVImageBufferTransferFunction_ITU_R_709_2); 464 kCVImageBufferTransferFunction_ITU_R_709_2);
392 SetSessionProperty( 465 SetSessionProperty(
393 videotoolbox_glue_->kVTCompressionPropertyKey_YCbCrMatrix(), 466 videotoolbox_glue_->kVTCompressionPropertyKey_YCbCrMatrix(),
394 kCVImageBufferYCbCrMatrix_ITU_R_709_2); 467 kCVImageBufferYCbCrMatrix_ITU_R_709_2);
395 if (video_config.max_number_of_video_buffers_used > 0) { 468 if (video_config_.max_number_of_video_buffers_used > 0) {
396 SetSessionProperty( 469 SetSessionProperty(
397 videotoolbox_glue_->kVTCompressionPropertyKey_MaxFrameDelayCount(), 470 videotoolbox_glue_->kVTCompressionPropertyKey_MaxFrameDelayCount(),
398 video_config.max_number_of_video_buffers_used); 471 video_config_.max_number_of_video_buffers_used);
399 } 472 }
400 } 473 }
401 474
402 void H264VideoToolboxEncoder::Teardown() { 475 void H264VideoToolboxEncoder::DestroyCompressionSession() {
403 DCHECK(thread_checker_.CalledOnValidThread()); 476 DCHECK(thread_checker_.CalledOnValidThread());
404 477
405 // If the compression session exists, invalidate it. This blocks until all 478 // If the compression session exists, invalidate it. This blocks until all
406 // pending output callbacks have returned and any internal threads have 479 // pending output callbacks have returned and any internal threads have
407 // joined, ensuring no output callback ever sees a dangling encoder pointer. 480 // joined, ensuring no output callback ever sees a dangling encoder pointer.
481 // The video frame factory's pool is updated to null so that it stops
482 // producing buffers. The current frame size is passed to prevent the video
483 // frame factory from posting |UpdateFrameSize| tasks. Indeed,
484 // |DestroyCompressionSession| is either called from
485 // |ResetCompressionSession|, in which case a new pool and frame size will be
486 // set, or from callsites that require that there be no compression session
487 // (ex: the dtor).
408 if (compression_session_) { 488 if (compression_session_) {
409 videotoolbox_glue_->VTCompressionSessionInvalidate(compression_session_); 489 videotoolbox_glue_->VTCompressionSessionInvalidate(compression_session_);
410 compression_session_.reset(); 490 compression_session_.reset();
491 video_frame_factory_->Update(
miu 2015/04/24 20:28:54 This should be moved to the top of this code block
jfroy 2015/04/24 20:52:23 Thanks, that's a good suggestion. Done.
492 base::ScopedCFTypeRef<CVPixelBufferPoolRef>(nullptr), frame_size_);
411 } 493 }
412 } 494 }
413 495
414 bool H264VideoToolboxEncoder::EncodeVideoFrame( 496 bool H264VideoToolboxEncoder::EncodeVideoFrame(
415 const scoped_refptr<media::VideoFrame>& video_frame, 497 const scoped_refptr<media::VideoFrame>& video_frame,
416 const base::TimeTicks& reference_time, 498 const base::TimeTicks& reference_time,
417 const FrameEncodedCallback& frame_encoded_callback) { 499 const FrameEncodedCallback& frame_encoded_callback) {
418 DCHECK(thread_checker_.CalledOnValidThread()); 500 DCHECK(thread_checker_.CalledOnValidThread());
419 DCHECK(!frame_encoded_callback.is_null()); 501 DCHECK(!frame_encoded_callback.is_null());
420 502
421 if (!compression_session_) { 503 // Reject empty video frames.
422 DLOG(ERROR) << " compression session is null"; 504 const gfx::Size frame_size = video_frame->visible_rect().size();
505 if (frame_size.IsEmpty()) {
506 DVLOG(1) << "Rejecting empty video frame.";
423 return false; 507 return false;
424 } 508 }
425 509
426 if (video_frame->visible_rect().size() != frame_size_) 510 // Handle frame size changes. This will reset the compression session.
511 if (frame_size != frame_size_) {
512 DVLOG(1) << "EncodeVideoFrame: Detected frame size change.";
513 UpdateFrameSize(frame_size);
514 }
515
516 // Need a compression session to continue.
517 if (!compression_session_) {
518 DLOG(ERROR) << "No compression session.";
427 return false; 519 return false;
520 }
428 521
429 // Wrap the VideoFrame in a CVPixelBuffer. In all cases, no data will be 522 // 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 523 // copied. If the VideoFrame was created by this encoder's video frame
431 // factory, then the returned CVPixelBuffer will have been obtained from the 524 // 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 525 // 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 526 // frame into memory visible by the hardware encoder. The VideoFrame's
434 // lifetime is extended for the lifetime of the returned CVPixelBuffer. 527 // lifetime is extended for the lifetime of the returned CVPixelBuffer.
435 auto pixel_buffer = media::WrapVideoFrameInCVPixelBuffer(*video_frame); 528 auto pixel_buffer = media::WrapVideoFrameInCVPixelBuffer(*video_frame);
436 if (!pixel_buffer) { 529 if (!pixel_buffer) {
530 DLOG(ERROR) << "WrapVideoFrameInCVPixelBuffer failed.";
437 return false; 531 return false;
438 } 532 }
439 533
534 // Convert the frame timestamp to CMTime.
440 auto timestamp_cm = CoreMediaGlue::CMTimeMake( 535 auto timestamp_cm = CoreMediaGlue::CMTimeMake(
441 (reference_time - base::TimeTicks()).InMicroseconds(), USEC_PER_SEC); 536 (reference_time - base::TimeTicks()).InMicroseconds(), USEC_PER_SEC);
442 537
538 // Wrap information we'll need after the frame is encoded in a heap object.
539 // We'll get the pointer back from the VideoToolbox completion callback.
443 scoped_ptr<InProgressFrameEncode> request(new InProgressFrameEncode( 540 scoped_ptr<InProgressFrameEncode> request(new InProgressFrameEncode(
444 TimeDeltaToRtpDelta(video_frame->timestamp(), kVideoFrequency), 541 TimeDeltaToRtpDelta(video_frame->timestamp(), kVideoFrequency),
445 reference_time, frame_encoded_callback)); 542 reference_time, frame_encoded_callback));
446 543
544 // Build a suitable frame properties dictionary for keyframes.
447 base::ScopedCFTypeRef<CFDictionaryRef> frame_props; 545 base::ScopedCFTypeRef<CFDictionaryRef> frame_props;
448 if (encode_next_frame_as_keyframe_) { 546 if (encode_next_frame_as_keyframe_) {
449 frame_props = DictionaryWithKeyValue( 547 frame_props = DictionaryWithKeyValue(
450 videotoolbox_glue_->kVTEncodeFrameOptionKey_ForceKeyFrame(), 548 videotoolbox_glue_->kVTEncodeFrameOptionKey_ForceKeyFrame(),
451 kCFBooleanTrue); 549 kCFBooleanTrue);
452 encode_next_frame_as_keyframe_ = false; 550 encode_next_frame_as_keyframe_ = false;
453 } 551 }
454 552
455 VTEncodeInfoFlags info; 553 // Submit the frame to the compression session. The function returns as soon
554 // as the frame has been enqueued.
456 OSStatus status = videotoolbox_glue_->VTCompressionSessionEncodeFrame( 555 OSStatus status = videotoolbox_glue_->VTCompressionSessionEncodeFrame(
457 compression_session_, pixel_buffer, timestamp_cm, 556 compression_session_, pixel_buffer, timestamp_cm,
458 CoreMediaGlue::CMTime{0, 0, 0, 0}, frame_props, 557 CoreMediaGlue::CMTime{0, 0, 0, 0}, frame_props,
459 reinterpret_cast<void*>(request.release()), &info); 558 reinterpret_cast<void*>(request.release()), nullptr);
460 if (status != noErr) { 559 if (status != noErr) {
461 DLOG(ERROR) << " VTCompressionSessionEncodeFrame failed: " << status; 560 DLOG(ERROR) << " VTCompressionSessionEncodeFrame failed: " << status;
462 return false; 561 return false;
463 } 562 }
464 if ((info & VideoToolboxGlue::kVTEncodeInfo_FrameDropped)) {
465 DLOG(ERROR) << " frame dropped";
466 return false;
467 }
468 563
469 return true; 564 return true;
470 } 565 }
471 566
472 void H264VideoToolboxEncoder::SetBitRate(int new_bit_rate) { 567 void H264VideoToolboxEncoder::UpdateFrameSize(const gfx::Size& size_needed) {
568 DCHECK(thread_checker_.CalledOnValidThread());
569
570 // Our video frame factory posts a task to update the frame size when its
571 // cache of the frame size differs from what the client requested. To avoid
572 // spurious encoder resets, check again here.
573 if (size_needed == frame_size_) {
574 DCHECK(compression_session_);
575 return;
576 }
577
578 VLOG(1) << "Resetting compression session (for frame size change from "
579 << frame_size_.ToString() << " to " << size_needed.ToString() << ").";
580
581 // If there is an existing session, finish every pending frame.
582 if (compression_session_) {
583 EmitFrames();
584 }
585
586 // Store the new frame size.
587 frame_size_ = size_needed;
588
589 // Reset the compression session.
590 ResetCompressionSession();
591 }
592
593 void H264VideoToolboxEncoder::SetBitRate(int /*new_bit_rate*/) {
473 DCHECK(thread_checker_.CalledOnValidThread()); 594 DCHECK(thread_checker_.CalledOnValidThread());
474 // VideoToolbox does not seem to support bitrate reconfiguration. 595 // VideoToolbox does not seem to support bitrate reconfiguration.
475 } 596 }
476 597
477 void H264VideoToolboxEncoder::GenerateKeyFrame() { 598 void H264VideoToolboxEncoder::GenerateKeyFrame() {
478 DCHECK(thread_checker_.CalledOnValidThread()); 599 DCHECK(thread_checker_.CalledOnValidThread());
479 DCHECK(compression_session_);
480
481 encode_next_frame_as_keyframe_ = true; 600 encode_next_frame_as_keyframe_ = true;
482 } 601 }
483 602
484 void H264VideoToolboxEncoder::LatestFrameIdToReference(uint32 /*frame_id*/) { 603 void H264VideoToolboxEncoder::LatestFrameIdToReference(uint32 /*frame_id*/) {
485 // Not supported by VideoToolbox in any meaningful manner. 604 // Not supported by VideoToolbox in any meaningful manner.
486 } 605 }
487 606
488 scoped_ptr<VideoFrameFactory> 607 scoped_ptr<VideoFrameFactory>
489 H264VideoToolboxEncoder::CreateVideoFrameFactory() { 608 H264VideoToolboxEncoder::CreateVideoFrameFactory() {
490 if (!videotoolbox_glue_ || !compression_session_) 609 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>( 610 return scoped_ptr<VideoFrameFactory>(
497 new VideoFrameFactoryCVPixelBufferPoolImpl(pool, frame_size_)); 611 new VideoFrameFactoryImpl::Proxy(video_frame_factory_));
498 } 612 }
499 613
500 void H264VideoToolboxEncoder::EmitFrames() { 614 void H264VideoToolboxEncoder::EmitFrames() {
501 DCHECK(thread_checker_.CalledOnValidThread()); 615 DCHECK(thread_checker_.CalledOnValidThread());
502 616 if (!compression_session_)
503 if (!compression_session_) {
504 DLOG(ERROR) << " compression session is null";
505 return; 617 return;
506 }
507 618
508 OSStatus status = videotoolbox_glue_->VTCompressionSessionCompleteFrames( 619 OSStatus status = videotoolbox_glue_->VTCompressionSessionCompleteFrames(
509 compression_session_, CoreMediaGlue::CMTime{0, 0, 0, 0}); 620 compression_session_, CoreMediaGlue::CMTime{0, 0, 0, 0});
510 if (status != noErr) { 621 if (status != noErr) {
511 DLOG(ERROR) << " VTCompressionSessionCompleteFrames failed: " << status; 622 DLOG(ERROR) << " VTCompressionSessionCompleteFrames failed: " << status;
512 } 623 }
513 } 624 }
514 625
515 bool H264VideoToolboxEncoder::SetSessionProperty(CFStringRef key, 626 bool H264VideoToolboxEncoder::SetSessionProperty(CFStringRef key,
516 int32_t value) { 627 int32_t value) {
(...skipping 22 matching lines...) Expand all
539 CMSampleBufferRef sbuf) { 650 CMSampleBufferRef sbuf) {
540 auto encoder = reinterpret_cast<H264VideoToolboxEncoder*>(encoder_opaque); 651 auto encoder = reinterpret_cast<H264VideoToolboxEncoder*>(encoder_opaque);
541 const scoped_ptr<InProgressFrameEncode> request( 652 const scoped_ptr<InProgressFrameEncode> request(
542 reinterpret_cast<InProgressFrameEncode*>(request_opaque)); 653 reinterpret_cast<InProgressFrameEncode*>(request_opaque));
543 bool keyframe = false; 654 bool keyframe = false;
544 bool has_frame_data = false; 655 bool has_frame_data = false;
545 656
546 if (status != noErr) { 657 if (status != noErr) {
547 DLOG(ERROR) << " encoding failed: " << status; 658 DLOG(ERROR) << " encoding failed: " << status;
548 encoder->cast_environment_->PostTask( 659 encoder->cast_environment_->PostTask(
549 CastEnvironment::MAIN, 660 CastEnvironment::MAIN, FROM_HERE,
550 FROM_HERE,
551 base::Bind(encoder->status_change_cb_, STATUS_CODEC_RUNTIME_ERROR)); 661 base::Bind(encoder->status_change_cb_, STATUS_CODEC_RUNTIME_ERROR));
552 } else if ((info & VideoToolboxGlue::kVTEncodeInfo_FrameDropped)) { 662 } else if ((info & VideoToolboxGlue::kVTEncodeInfo_FrameDropped)) {
553 DVLOG(2) << " frame dropped"; 663 DVLOG(2) << " frame dropped";
554 } else { 664 } else {
555 auto sample_attachments = static_cast<CFDictionaryRef>( 665 auto sample_attachments =
556 CFArrayGetValueAtIndex( 666 static_cast<CFDictionaryRef>(CFArrayGetValueAtIndex(
557 CoreMediaGlue::CMSampleBufferGetSampleAttachmentsArray(sbuf, true), 667 CoreMediaGlue::CMSampleBufferGetSampleAttachmentsArray(sbuf, true),
558 0)); 668 0));
559 669
560 // If the NotSync key is not present, it implies Sync, which indicates a 670 // 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 671 // keyframe (at least I think, VT documentation is, erm, sparse). Could
562 // alternatively use kCMSampleAttachmentKey_DependsOnOthers == false. 672 // alternatively use kCMSampleAttachmentKey_DependsOnOthers == false.
563 keyframe = !CFDictionaryContainsKey( 673 keyframe = !CFDictionaryContainsKey(
564 sample_attachments, 674 sample_attachments,
565 CoreMediaGlue::kCMSampleAttachmentKey_NotSync()); 675 CoreMediaGlue::kCMSampleAttachmentKey_NotSync());
566 has_frame_data = true; 676 has_frame_data = true;
567 } 677 }
568 678
569 // Increment the encoder-scoped frame id and assign the new value to this 679 // 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. 680 // frame. VideoToolbox calls the output callback serially, so this is safe.
571 const uint32 frame_id = encoder->next_frame_id_++; 681 const uint32 frame_id = ++encoder->last_frame_id_;
572 682
573 scoped_ptr<EncodedFrame> encoded_frame(new EncodedFrame()); 683 scoped_ptr<EncodedFrame> encoded_frame(new EncodedFrame());
574 encoded_frame->frame_id = frame_id; 684 encoded_frame->frame_id = frame_id;
575 encoded_frame->reference_time = request->reference_time; 685 encoded_frame->reference_time = request->reference_time;
576 encoded_frame->rtp_timestamp = request->rtp_timestamp; 686 encoded_frame->rtp_timestamp = request->rtp_timestamp;
577 if (keyframe) { 687 if (keyframe) {
578 encoded_frame->dependency = EncodedFrame::KEY; 688 encoded_frame->dependency = EncodedFrame::KEY;
579 encoded_frame->referenced_frame_id = frame_id; 689 encoded_frame->referenced_frame_id = frame_id;
580 } else { 690 } else {
581 encoded_frame->dependency = EncodedFrame::DEPENDENT; 691 encoded_frame->dependency = EncodedFrame::DEPENDENT;
(...skipping 11 matching lines...) Expand all
593 703
594 if (has_frame_data) 704 if (has_frame_data)
595 CopySampleBufferToAnnexBBuffer(sbuf, &encoded_frame->data, keyframe); 705 CopySampleBufferToAnnexBBuffer(sbuf, &encoded_frame->data, keyframe);
596 706
597 encoder->cast_environment_->PostTask( 707 encoder->cast_environment_->PostTask(
598 CastEnvironment::MAIN, FROM_HERE, 708 CastEnvironment::MAIN, FROM_HERE,
599 base::Bind(request->frame_encoded_callback, 709 base::Bind(request->frame_encoded_callback,
600 base::Passed(&encoded_frame))); 710 base::Passed(&encoded_frame)));
601 } 711 }
602 712
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 713 } // namespace cast
688 } // namespace media 714 } // 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