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

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: Set the video frame factory's pool to null before destroying the compression session. 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 //
482 // Before destroying the compression session, the video frame factory's pool
483 // is updated to null so that no thread will produce new video frames via the
484 // factory until a new compression session is created. The current frame size
485 // is passed to prevent the video frame factory from posting |UpdateFrameSize|
486 // tasks. Indeed, |DestroyCompressionSession| is either called from
487 // |ResetCompressionSession|, in which case a new pool and frame size will be
488 // set, or from callsites that require that there be no compression session
489 // (ex: the dtor).
408 if (compression_session_) { 490 if (compression_session_) {
491 video_frame_factory_->Update(
492 base::ScopedCFTypeRef<CVPixelBufferPoolRef>(nullptr), frame_size_);
409 videotoolbox_glue_->VTCompressionSessionInvalidate(compression_session_); 493 videotoolbox_glue_->VTCompressionSessionInvalidate(compression_session_);
410 compression_session_.reset(); 494 compression_session_.reset();
411 } 495 }
412 } 496 }
413 497
414 bool H264VideoToolboxEncoder::EncodeVideoFrame( 498 bool H264VideoToolboxEncoder::EncodeVideoFrame(
415 const scoped_refptr<media::VideoFrame>& video_frame, 499 const scoped_refptr<media::VideoFrame>& video_frame,
416 const base::TimeTicks& reference_time, 500 const base::TimeTicks& reference_time,
417 const FrameEncodedCallback& frame_encoded_callback) { 501 const FrameEncodedCallback& frame_encoded_callback) {
418 DCHECK(thread_checker_.CalledOnValidThread()); 502 DCHECK(thread_checker_.CalledOnValidThread());
419 DCHECK(!frame_encoded_callback.is_null()); 503 DCHECK(!frame_encoded_callback.is_null());
420 504
421 if (!compression_session_) { 505 // Reject empty video frames.
422 DLOG(ERROR) << " compression session is null"; 506 const gfx::Size frame_size = video_frame->visible_rect().size();
507 if (frame_size.IsEmpty()) {
508 DVLOG(1) << "Rejecting empty video frame.";
423 return false; 509 return false;
424 } 510 }
425 511
426 if (video_frame->visible_rect().size() != frame_size_) 512 // Handle frame size changes. This will reset the compression session.
513 if (frame_size != frame_size_) {
514 DVLOG(1) << "EncodeVideoFrame: Detected frame size change.";
515 UpdateFrameSize(frame_size);
516 }
517
518 // Need a compression session to continue.
519 if (!compression_session_) {
520 DLOG(ERROR) << "No compression session.";
427 return false; 521 return false;
522 }
428 523
429 // Wrap the VideoFrame in a CVPixelBuffer. In all cases, no data will be 524 // 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 525 // copied. If the VideoFrame was created by this encoder's video frame
431 // factory, then the returned CVPixelBuffer will have been obtained from the 526 // 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 527 // 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 528 // frame into memory visible by the hardware encoder. The VideoFrame's
434 // lifetime is extended for the lifetime of the returned CVPixelBuffer. 529 // lifetime is extended for the lifetime of the returned CVPixelBuffer.
435 auto pixel_buffer = media::WrapVideoFrameInCVPixelBuffer(*video_frame); 530 auto pixel_buffer = media::WrapVideoFrameInCVPixelBuffer(*video_frame);
436 if (!pixel_buffer) { 531 if (!pixel_buffer) {
532 DLOG(ERROR) << "WrapVideoFrameInCVPixelBuffer failed.";
437 return false; 533 return false;
438 } 534 }
439 535
536 // Convert the frame timestamp to CMTime.
440 auto timestamp_cm = CoreMediaGlue::CMTimeMake( 537 auto timestamp_cm = CoreMediaGlue::CMTimeMake(
441 (reference_time - base::TimeTicks()).InMicroseconds(), USEC_PER_SEC); 538 (reference_time - base::TimeTicks()).InMicroseconds(), USEC_PER_SEC);
442 539
540 // Wrap information we'll need after the frame is encoded in a heap object.
541 // We'll get the pointer back from the VideoToolbox completion callback.
443 scoped_ptr<InProgressFrameEncode> request(new InProgressFrameEncode( 542 scoped_ptr<InProgressFrameEncode> request(new InProgressFrameEncode(
444 TimeDeltaToRtpDelta(video_frame->timestamp(), kVideoFrequency), 543 TimeDeltaToRtpDelta(video_frame->timestamp(), kVideoFrequency),
445 reference_time, frame_encoded_callback)); 544 reference_time, frame_encoded_callback));
446 545
546 // Build a suitable frame properties dictionary for keyframes.
447 base::ScopedCFTypeRef<CFDictionaryRef> frame_props; 547 base::ScopedCFTypeRef<CFDictionaryRef> frame_props;
448 if (encode_next_frame_as_keyframe_) { 548 if (encode_next_frame_as_keyframe_) {
449 frame_props = DictionaryWithKeyValue( 549 frame_props = DictionaryWithKeyValue(
450 videotoolbox_glue_->kVTEncodeFrameOptionKey_ForceKeyFrame(), 550 videotoolbox_glue_->kVTEncodeFrameOptionKey_ForceKeyFrame(),
451 kCFBooleanTrue); 551 kCFBooleanTrue);
452 encode_next_frame_as_keyframe_ = false; 552 encode_next_frame_as_keyframe_ = false;
453 } 553 }
454 554
455 VTEncodeInfoFlags info; 555 // Submit the frame to the compression session. The function returns as soon
556 // as the frame has been enqueued.
456 OSStatus status = videotoolbox_glue_->VTCompressionSessionEncodeFrame( 557 OSStatus status = videotoolbox_glue_->VTCompressionSessionEncodeFrame(
457 compression_session_, pixel_buffer, timestamp_cm, 558 compression_session_, pixel_buffer, timestamp_cm,
458 CoreMediaGlue::CMTime{0, 0, 0, 0}, frame_props, 559 CoreMediaGlue::CMTime{0, 0, 0, 0}, frame_props,
459 reinterpret_cast<void*>(request.release()), &info); 560 reinterpret_cast<void*>(request.release()), nullptr);
460 if (status != noErr) { 561 if (status != noErr) {
461 DLOG(ERROR) << " VTCompressionSessionEncodeFrame failed: " << status; 562 DLOG(ERROR) << " VTCompressionSessionEncodeFrame failed: " << status;
462 return false; 563 return false;
463 } 564 }
464 if ((info & VideoToolboxGlue::kVTEncodeInfo_FrameDropped)) {
465 DLOG(ERROR) << " frame dropped";
466 return false;
467 }
468 565
469 return true; 566 return true;
470 } 567 }
471 568
472 void H264VideoToolboxEncoder::SetBitRate(int new_bit_rate) { 569 void H264VideoToolboxEncoder::UpdateFrameSize(const gfx::Size& size_needed) {
570 DCHECK(thread_checker_.CalledOnValidThread());
571
572 // Our video frame factory posts a task to update the frame size when its
573 // cache of the frame size differs from what the client requested. To avoid
574 // spurious encoder resets, check again here.
575 if (size_needed == frame_size_) {
576 DCHECK(compression_session_);
577 return;
578 }
579
580 VLOG(1) << "Resetting compression session (for frame size change from "
581 << frame_size_.ToString() << " to " << size_needed.ToString() << ").";
582
583 // If there is an existing session, finish every pending frame.
584 if (compression_session_) {
585 EmitFrames();
586 }
587
588 // Store the new frame size.
589 frame_size_ = size_needed;
590
591 // Reset the compression session.
592 ResetCompressionSession();
593 }
594
595 void H264VideoToolboxEncoder::SetBitRate(int /*new_bit_rate*/) {
473 DCHECK(thread_checker_.CalledOnValidThread()); 596 DCHECK(thread_checker_.CalledOnValidThread());
474 // VideoToolbox does not seem to support bitrate reconfiguration. 597 // VideoToolbox does not seem to support bitrate reconfiguration.
475 } 598 }
476 599
477 void H264VideoToolboxEncoder::GenerateKeyFrame() { 600 void H264VideoToolboxEncoder::GenerateKeyFrame() {
478 DCHECK(thread_checker_.CalledOnValidThread()); 601 DCHECK(thread_checker_.CalledOnValidThread());
479 DCHECK(compression_session_);
480
481 encode_next_frame_as_keyframe_ = true; 602 encode_next_frame_as_keyframe_ = true;
482 } 603 }
483 604
484 void H264VideoToolboxEncoder::LatestFrameIdToReference(uint32 /*frame_id*/) { 605 void H264VideoToolboxEncoder::LatestFrameIdToReference(uint32 /*frame_id*/) {
485 // Not supported by VideoToolbox in any meaningful manner. 606 // Not supported by VideoToolbox in any meaningful manner.
486 } 607 }
487 608
488 scoped_ptr<VideoFrameFactory> 609 scoped_ptr<VideoFrameFactory>
489 H264VideoToolboxEncoder::CreateVideoFrameFactory() { 610 H264VideoToolboxEncoder::CreateVideoFrameFactory() {
490 if (!videotoolbox_glue_ || !compression_session_) 611 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>( 612 return scoped_ptr<VideoFrameFactory>(
497 new VideoFrameFactoryCVPixelBufferPoolImpl(pool, frame_size_)); 613 new VideoFrameFactoryImpl::Proxy(video_frame_factory_));
498 } 614 }
499 615
500 void H264VideoToolboxEncoder::EmitFrames() { 616 void H264VideoToolboxEncoder::EmitFrames() {
501 DCHECK(thread_checker_.CalledOnValidThread()); 617 DCHECK(thread_checker_.CalledOnValidThread());
502 618 if (!compression_session_)
503 if (!compression_session_) {
504 DLOG(ERROR) << " compression session is null";
505 return; 619 return;
506 }
507 620
508 OSStatus status = videotoolbox_glue_->VTCompressionSessionCompleteFrames( 621 OSStatus status = videotoolbox_glue_->VTCompressionSessionCompleteFrames(
509 compression_session_, CoreMediaGlue::CMTime{0, 0, 0, 0}); 622 compression_session_, CoreMediaGlue::CMTime{0, 0, 0, 0});
510 if (status != noErr) { 623 if (status != noErr) {
511 DLOG(ERROR) << " VTCompressionSessionCompleteFrames failed: " << status; 624 DLOG(ERROR) << " VTCompressionSessionCompleteFrames failed: " << status;
512 } 625 }
513 } 626 }
514 627
515 bool H264VideoToolboxEncoder::SetSessionProperty(CFStringRef key, 628 bool H264VideoToolboxEncoder::SetSessionProperty(CFStringRef key,
516 int32_t value) { 629 int32_t value) {
(...skipping 22 matching lines...) Expand all
539 CMSampleBufferRef sbuf) { 652 CMSampleBufferRef sbuf) {
540 auto encoder = reinterpret_cast<H264VideoToolboxEncoder*>(encoder_opaque); 653 auto encoder = reinterpret_cast<H264VideoToolboxEncoder*>(encoder_opaque);
541 const scoped_ptr<InProgressFrameEncode> request( 654 const scoped_ptr<InProgressFrameEncode> request(
542 reinterpret_cast<InProgressFrameEncode*>(request_opaque)); 655 reinterpret_cast<InProgressFrameEncode*>(request_opaque));
543 bool keyframe = false; 656 bool keyframe = false;
544 bool has_frame_data = false; 657 bool has_frame_data = false;
545 658
546 if (status != noErr) { 659 if (status != noErr) {
547 DLOG(ERROR) << " encoding failed: " << status; 660 DLOG(ERROR) << " encoding failed: " << status;
548 encoder->cast_environment_->PostTask( 661 encoder->cast_environment_->PostTask(
549 CastEnvironment::MAIN, 662 CastEnvironment::MAIN, FROM_HERE,
550 FROM_HERE,
551 base::Bind(encoder->status_change_cb_, STATUS_CODEC_RUNTIME_ERROR)); 663 base::Bind(encoder->status_change_cb_, STATUS_CODEC_RUNTIME_ERROR));
552 } else if ((info & VideoToolboxGlue::kVTEncodeInfo_FrameDropped)) { 664 } else if ((info & VideoToolboxGlue::kVTEncodeInfo_FrameDropped)) {
553 DVLOG(2) << " frame dropped"; 665 DVLOG(2) << " frame dropped";
554 } else { 666 } else {
555 auto sample_attachments = static_cast<CFDictionaryRef>( 667 auto sample_attachments =
556 CFArrayGetValueAtIndex( 668 static_cast<CFDictionaryRef>(CFArrayGetValueAtIndex(
557 CoreMediaGlue::CMSampleBufferGetSampleAttachmentsArray(sbuf, true), 669 CoreMediaGlue::CMSampleBufferGetSampleAttachmentsArray(sbuf, true),
558 0)); 670 0));
559 671
560 // If the NotSync key is not present, it implies Sync, which indicates a 672 // 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 673 // keyframe (at least I think, VT documentation is, erm, sparse). Could
562 // alternatively use kCMSampleAttachmentKey_DependsOnOthers == false. 674 // alternatively use kCMSampleAttachmentKey_DependsOnOthers == false.
563 keyframe = !CFDictionaryContainsKey( 675 keyframe = !CFDictionaryContainsKey(
564 sample_attachments, 676 sample_attachments,
565 CoreMediaGlue::kCMSampleAttachmentKey_NotSync()); 677 CoreMediaGlue::kCMSampleAttachmentKey_NotSync());
566 has_frame_data = true; 678 has_frame_data = true;
567 } 679 }
568 680
569 // Increment the encoder-scoped frame id and assign the new value to this 681 // 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. 682 // frame. VideoToolbox calls the output callback serially, so this is safe.
571 const uint32 frame_id = encoder->next_frame_id_++; 683 const uint32 frame_id = ++encoder->last_frame_id_;
572 684
573 scoped_ptr<EncodedFrame> encoded_frame(new EncodedFrame()); 685 scoped_ptr<EncodedFrame> encoded_frame(new EncodedFrame());
574 encoded_frame->frame_id = frame_id; 686 encoded_frame->frame_id = frame_id;
575 encoded_frame->reference_time = request->reference_time; 687 encoded_frame->reference_time = request->reference_time;
576 encoded_frame->rtp_timestamp = request->rtp_timestamp; 688 encoded_frame->rtp_timestamp = request->rtp_timestamp;
577 if (keyframe) { 689 if (keyframe) {
578 encoded_frame->dependency = EncodedFrame::KEY; 690 encoded_frame->dependency = EncodedFrame::KEY;
579 encoded_frame->referenced_frame_id = frame_id; 691 encoded_frame->referenced_frame_id = frame_id;
580 } else { 692 } else {
581 encoded_frame->dependency = EncodedFrame::DEPENDENT; 693 encoded_frame->dependency = EncodedFrame::DEPENDENT;
(...skipping 11 matching lines...) Expand all
593 705
594 if (has_frame_data) 706 if (has_frame_data)
595 CopySampleBufferToAnnexBBuffer(sbuf, &encoded_frame->data, keyframe); 707 CopySampleBufferToAnnexBBuffer(sbuf, &encoded_frame->data, keyframe);
596 708
597 encoder->cast_environment_->PostTask( 709 encoder->cast_environment_->PostTask(
598 CastEnvironment::MAIN, FROM_HERE, 710 CastEnvironment::MAIN, FROM_HERE,
599 base::Bind(request->frame_encoded_callback, 711 base::Bind(request->frame_encoded_callback,
600 base::Passed(&encoded_frame))); 712 base::Passed(&encoded_frame)));
601 } 713 }
602 714
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 715 } // namespace cast
688 } // namespace media 716 } // 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