1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "content/renderer/media/rtc_video_decoder.h"
8 #include "base/logging.h"
9 #include "base/memory/ref_counted.h"
10 #include "base/message_loop/message_loop_proxy.h"
11 #include "base/metrics/histogram.h"
12 #include "base/numerics/safe_conversions.h"
13 #include "base/stl_util.h"
14 #include "base/synchronization/waitable_event.h"
15 #include "base/task_runner_util.h"
16 #include "content/renderer/media/native_handle_impl.h"
17 #include "gpu/command_buffer/common/mailbox_holder.h"
18 #include "media/base/bind_to_current_loop.h"
19 #include "media/renderers/gpu_video_accelerator_factories.h"
20 #include "third_party/skia/include/core/SkBitmap.h"
21 #include "third_party/webrtc/common_video/interface/i420_video_frame.h"
22 #include "third_party/webrtc/system_wrappers/interface/ref_count.h"
26 const int32
RTCVideoDecoder::ID_LAST
= 0x3FFFFFFF;
27 const int32
RTCVideoDecoder::ID_HALF
= 0x20000000;
28 const int32
RTCVideoDecoder::ID_INVALID
= -1;
30 // Maximum number of concurrent VDA::Decode() operations RVD will maintain.
31 // Higher values allow better pipelining in the GPU, but also require more
33 static const size_t kMaxInFlightDecodes
= 8;
35 // Size of shared-memory segments we allocate. Since we reuse them we let them
36 // be on the beefy side.
37 static const size_t kSharedMemorySegmentBytes
= 100 << 10;
39 // Maximum number of allocated shared-memory segments.
40 static const int kMaxNumSharedMemorySegments
= 16;
42 // Maximum number of pending WebRTC buffers that are waiting for the shared
43 // memory. 10 seconds for 30 fps.
44 static const size_t kMaxNumOfPendingBuffers
= 300;
46 // A shared memory segment and its allocated size. This class has the ownership
48 class RTCVideoDecoder::SHMBuffer
{
50 SHMBuffer(scoped_ptr
<base::SharedMemory
> shm
, size_t size
);
52 scoped_ptr
<base::SharedMemory
> const shm
;
56 RTCVideoDecoder::SHMBuffer::SHMBuffer(scoped_ptr
<base::SharedMemory
> shm
,
58 : shm(shm
.Pass()), size(size
) {
61 RTCVideoDecoder::SHMBuffer::~SHMBuffer() {
64 RTCVideoDecoder::BufferData::BufferData(int32 bitstream_buffer_id
,
67 : bitstream_buffer_id(bitstream_buffer_id
),
71 RTCVideoDecoder::BufferData::BufferData() {}
73 RTCVideoDecoder::BufferData::~BufferData() {}
75 RTCVideoDecoder::RTCVideoDecoder(
76 webrtc::VideoCodecType type
,
77 const scoped_refptr
<media::GpuVideoAcceleratorFactories
>& factories
)
78 : video_codec_type_(type
),
79 factories_(factories
),
80 decoder_texture_target_(0),
81 next_picture_buffer_id_(0),
82 state_(UNINITIALIZED
),
83 decode_complete_callback_(NULL
),
85 next_bitstream_buffer_id_(0),
86 reset_bitstream_buffer_id_(ID_INVALID
),
88 DCHECK(!factories_
->GetTaskRunner()->BelongsToCurrentThread());
91 RTCVideoDecoder::~RTCVideoDecoder() {
92 DVLOG(2) << "~RTCVideoDecoder";
93 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
96 // Delete all shared memories.
97 STLDeleteElements(&available_shm_segments_
);
98 STLDeleteValues(&bitstream_buffers_in_decoder_
);
99 STLDeleteContainerPairFirstPointers(decode_buffers_
.begin(),
100 decode_buffers_
.end());
101 decode_buffers_
.clear();
103 // Delete WebRTC input buffers.
104 for (std::deque
<std::pair
<webrtc::EncodedImage
, BufferData
> >::iterator it
=
105 pending_buffers_
.begin();
106 it
!= pending_buffers_
.end();
108 delete[] it
->first
._buffer
;
113 scoped_ptr
<RTCVideoDecoder
> RTCVideoDecoder::Create(
114 webrtc::VideoCodecType type
,
115 const scoped_refptr
<media::GpuVideoAcceleratorFactories
>& factories
) {
116 scoped_ptr
<RTCVideoDecoder
> decoder
;
117 // Convert WebRTC codec type to media codec profile.
118 media::VideoCodecProfile profile
;
120 case webrtc::kVideoCodecVP8
:
121 profile
= media::VP8PROFILE_ANY
;
123 case webrtc::kVideoCodecH264
:
124 profile
= media::H264PROFILE_MAIN
;
127 DVLOG(2) << "Video codec not supported:" << type
;
128 return decoder
.Pass();
131 base::WaitableEvent
waiter(true, false);
132 decoder
.reset(new RTCVideoDecoder(type
, factories
));
133 decoder
->factories_
->GetTaskRunner()->PostTask(
135 base::Bind(&RTCVideoDecoder::CreateVDA
,
136 base::Unretained(decoder
.get()),
140 // vda can be NULL if the codec is not supported.
141 if (decoder
->vda_
!= NULL
) {
142 decoder
->state_
= INITIALIZED
;
144 factories
->GetTaskRunner()->DeleteSoon(FROM_HERE
, decoder
.release());
146 return decoder
.Pass();
149 int32_t RTCVideoDecoder::InitDecode(const webrtc::VideoCodec
* codecSettings
,
150 int32_t /*numberOfCores*/) {
151 DVLOG(2) << "InitDecode";
152 DCHECK_EQ(video_codec_type_
, codecSettings
->codecType
);
153 if (codecSettings
->codecType
== webrtc::kVideoCodecVP8
&&
154 codecSettings
->codecSpecific
.VP8
.feedbackModeOn
) {
155 LOG(ERROR
) << "Feedback mode not supported";
156 return RecordInitDecodeUMA(WEBRTC_VIDEO_CODEC_ERROR
);
159 base::AutoLock
auto_lock(lock_
);
160 if (state_
== UNINITIALIZED
|| state_
== DECODE_ERROR
) {
161 LOG(ERROR
) << "VDA is not initialized. state=" << state_
;
162 return RecordInitDecodeUMA(WEBRTC_VIDEO_CODEC_UNINITIALIZED
);
164 // Create some shared memory if the queue is empty.
165 if (available_shm_segments_
.size() == 0) {
166 factories_
->GetTaskRunner()->PostTask(
168 base::Bind(&RTCVideoDecoder::CreateSHM
,
169 weak_factory_
.GetWeakPtr(),
171 kSharedMemorySegmentBytes
));
173 return RecordInitDecodeUMA(WEBRTC_VIDEO_CODEC_OK
);
176 int32_t RTCVideoDecoder::Decode(
177 const webrtc::EncodedImage
& inputImage
,
179 const webrtc::RTPFragmentationHeader
* /*fragmentation*/,
180 const webrtc::CodecSpecificInfo
* /*codecSpecificInfo*/,
181 int64_t /*renderTimeMs*/) {
182 DVLOG(3) << "Decode";
184 base::AutoLock
auto_lock(lock_
);
186 if (state_
== UNINITIALIZED
|| decode_complete_callback_
== NULL
) {
187 LOG(ERROR
) << "The decoder has not initialized.";
188 return WEBRTC_VIDEO_CODEC_UNINITIALIZED
;
191 if (state_
== DECODE_ERROR
) {
192 LOG(ERROR
) << "Decoding error occurred.";
193 return WEBRTC_VIDEO_CODEC_ERROR
;
196 if (missingFrames
|| !inputImage
._completeFrame
) {
197 DLOG(ERROR
) << "Missing or incomplete frames.";
198 // Unlike the SW decoder in libvpx, hw decoder cannot handle broken frames.
199 // Return an error to request a key frame.
200 return WEBRTC_VIDEO_CODEC_ERROR
;
203 // Most platforms' VDA implementations support mid-stream resolution change
204 // internally. Platforms whose VDAs fail to support mid-stream resolution
205 // change gracefully need to have their clients cover for them, and we do that
208 const bool kVDACanHandleMidstreamResize
= false;
210 const bool kVDACanHandleMidstreamResize
= true;
213 bool need_to_reset_for_midstream_resize
= false;
214 if (inputImage
._frameType
== webrtc::kKeyFrame
) {
215 DVLOG(2) << "Got key frame. size=" << inputImage
._encodedWidth
<< "x"
216 << inputImage
._encodedHeight
;
217 gfx::Size prev_frame_size
= frame_size_
;
218 frame_size_
.SetSize(inputImage
._encodedWidth
, inputImage
._encodedHeight
);
219 if (!kVDACanHandleMidstreamResize
&& !prev_frame_size
.IsEmpty() &&
220 prev_frame_size
!= frame_size_
) {
221 need_to_reset_for_midstream_resize
= true;
223 } else if (IsFirstBufferAfterReset(next_bitstream_buffer_id_
,
224 reset_bitstream_buffer_id_
)) {
225 // TODO(wuchengli): VDA should handle it. Remove this when
226 // http://crosbug.com/p/21913 is fixed.
227 DVLOG(1) << "The first frame should be a key frame. Drop this.";
228 return WEBRTC_VIDEO_CODEC_ERROR
;
231 // Create buffer metadata.
232 BufferData
buffer_data(next_bitstream_buffer_id_
,
233 inputImage
._timeStamp
,
235 // Mask against 30 bits, to avoid (undefined) wraparound on signed integer.
236 next_bitstream_buffer_id_
= (next_bitstream_buffer_id_
+ 1) & ID_LAST
;
238 // If a shared memory segment is available, there are no pending buffers, and
239 // this isn't a mid-stream resolution change, then send the buffer for decode
240 // immediately. Otherwise, save the buffer in the queue for later decode.
241 scoped_ptr
<SHMBuffer
> shm_buffer
;
242 if (!need_to_reset_for_midstream_resize
&& pending_buffers_
.size() == 0)
243 shm_buffer
= GetSHM_Locked(inputImage
._length
);
245 if (!SaveToPendingBuffers_Locked(inputImage
, buffer_data
))
246 return WEBRTC_VIDEO_CODEC_ERROR
;
247 if (need_to_reset_for_midstream_resize
) {
248 base::AutoUnlock
auto_unlock(lock_
);
251 return WEBRTC_VIDEO_CODEC_OK
;
254 SaveToDecodeBuffers_Locked(inputImage
, shm_buffer
.Pass(), buffer_data
);
255 factories_
->GetTaskRunner()->PostTask(
257 base::Bind(&RTCVideoDecoder::RequestBufferDecode
,
258 weak_factory_
.GetWeakPtr()));
259 return WEBRTC_VIDEO_CODEC_OK
;
262 int32_t RTCVideoDecoder::RegisterDecodeCompleteCallback(
263 webrtc::DecodedImageCallback
* callback
) {
264 DVLOG(2) << "RegisterDecodeCompleteCallback";
265 base::AutoLock
auto_lock(lock_
);
266 decode_complete_callback_
= callback
;
267 return WEBRTC_VIDEO_CODEC_OK
;
270 int32_t RTCVideoDecoder::Release() {
271 DVLOG(2) << "Release";
272 // Do not destroy VDA because WebRTC can call InitDecode and start decoding
277 int32_t RTCVideoDecoder::Reset() {
279 base::AutoLock
auto_lock(lock_
);
280 if (state_
== UNINITIALIZED
) {
281 LOG(ERROR
) << "Decoder not initialized.";
282 return WEBRTC_VIDEO_CODEC_UNINITIALIZED
;
284 if (next_bitstream_buffer_id_
!= 0)
285 reset_bitstream_buffer_id_
= next_bitstream_buffer_id_
- 1;
287 reset_bitstream_buffer_id_
= ID_LAST
;
288 // If VDA is already resetting, no need to request the reset again.
289 if (state_
!= RESETTING
) {
291 factories_
->GetTaskRunner()->PostTask(
293 base::Bind(&RTCVideoDecoder::ResetInternal
,
294 weak_factory_
.GetWeakPtr()));
296 return WEBRTC_VIDEO_CODEC_OK
;
299 void RTCVideoDecoder::ProvidePictureBuffers(uint32 count
,
300 const gfx::Size
& size
,
301 uint32 texture_target
) {
302 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
303 DVLOG(3) << "ProvidePictureBuffers. texture_target=" << texture_target
;
308 std::vector
<uint32
> texture_ids
;
309 std::vector
<gpu::Mailbox
> texture_mailboxes
;
310 decoder_texture_target_
= texture_target
;
311 if (!factories_
->CreateTextures(count
,
315 decoder_texture_target_
)) {
316 NotifyError(media::VideoDecodeAccelerator::PLATFORM_FAILURE
);
319 DCHECK_EQ(count
, texture_ids
.size());
320 DCHECK_EQ(count
, texture_mailboxes
.size());
322 std::vector
<media::PictureBuffer
> picture_buffers
;
323 for (size_t i
= 0; i
< texture_ids
.size(); ++i
) {
324 picture_buffers
.push_back(media::PictureBuffer(
325 next_picture_buffer_id_
++, size
, texture_ids
[i
], texture_mailboxes
[i
]));
326 bool inserted
= assigned_picture_buffers_
.insert(std::make_pair(
327 picture_buffers
.back().id(), picture_buffers
.back())).second
;
330 vda_
->AssignPictureBuffers(picture_buffers
);
333 void RTCVideoDecoder::DismissPictureBuffer(int32 id
) {
334 DVLOG(3) << "DismissPictureBuffer. id=" << id
;
335 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
337 std::map
<int32
, media::PictureBuffer
>::iterator it
=
338 assigned_picture_buffers_
.find(id
);
339 if (it
== assigned_picture_buffers_
.end()) {
340 NOTREACHED() << "Missing picture buffer: " << id
;
344 media::PictureBuffer buffer_to_dismiss
= it
->second
;
345 assigned_picture_buffers_
.erase(it
);
347 if (!picture_buffers_at_display_
.count(id
)) {
348 // We can delete the texture immediately as it's not being displayed.
349 factories_
->DeleteTexture(buffer_to_dismiss
.texture_id());
352 // Not destroying a texture in display in |picture_buffers_at_display_|.
353 // Postpone deletion until after it's returned to us.
356 void RTCVideoDecoder::PictureReady(const media::Picture
& picture
) {
357 DVLOG(3) << "PictureReady";
358 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
360 std::map
<int32
, media::PictureBuffer
>::iterator it
=
361 assigned_picture_buffers_
.find(picture
.picture_buffer_id());
362 if (it
== assigned_picture_buffers_
.end()) {
363 NOTREACHED() << "Missing picture buffer: " << picture
.picture_buffer_id();
364 NotifyError(media::VideoDecodeAccelerator::PLATFORM_FAILURE
);
367 const media::PictureBuffer
& pb
= it
->second
;
369 // Validate picture rectangle from GPU.
370 if (picture
.visible_rect().IsEmpty() ||
371 !gfx::Rect(pb
.size()).Contains(picture
.visible_rect())) {
372 NOTREACHED() << "Invalid picture size from VDA: "
373 << picture
.visible_rect().ToString() << " should fit in "
374 << pb
.size().ToString();
375 NotifyError(media::VideoDecodeAccelerator::PLATFORM_FAILURE
);
379 // Create a media::VideoFrame.
380 uint32_t timestamp
= 0;
381 GetBufferData(picture
.bitstream_buffer_id(), ×tamp
);
382 scoped_refptr
<media::VideoFrame
> frame
=
383 CreateVideoFrame(picture
, pb
, timestamp
);
385 picture_buffers_at_display_
.insert(std::make_pair(
386 picture
.picture_buffer_id(),
387 pb
.texture_id())).second
;
390 // Create a WebRTC video frame.
391 webrtc::RefCountImpl
<NativeHandleImpl
>* handle
=
392 new webrtc::RefCountImpl
<NativeHandleImpl
>(frame
);
393 webrtc::I420VideoFrame
decoded_image(handle
,
394 picture
.visible_rect().width(),
395 picture
.visible_rect().height(),
399 // Invoke decode callback. WebRTC expects no callback after Reset or Release.
401 base::AutoLock
auto_lock(lock_
);
402 DCHECK(decode_complete_callback_
!= NULL
);
403 if (IsBufferAfterReset(picture
.bitstream_buffer_id(),
404 reset_bitstream_buffer_id_
)) {
405 decode_complete_callback_
->Decoded(decoded_image
);
410 scoped_refptr
<media::VideoFrame
> RTCVideoDecoder::CreateVideoFrame(
411 const media::Picture
& picture
,
412 const media::PictureBuffer
& pb
,
413 uint32_t timestamp
) {
414 gfx::Rect
visible_rect(picture
.visible_rect());
415 DCHECK(decoder_texture_target_
);
416 // Convert timestamp from 90KHz to ms.
417 base::TimeDelta timestamp_ms
= base::TimeDelta::FromInternalValue(
418 base::checked_cast
<uint64_t>(timestamp
) * 1000 / 90);
419 return media::VideoFrame::WrapNativeTexture(
420 make_scoped_ptr(new gpu::MailboxHolder(pb
.texture_mailbox(),
421 decoder_texture_target_
, 0)),
422 media::BindToCurrentLoop(base::Bind(
423 &RTCVideoDecoder::ReleaseMailbox
, weak_factory_
.GetWeakPtr(),
424 factories_
, picture
.picture_buffer_id(), pb
.texture_id())),
425 pb
.size(), visible_rect
, visible_rect
.size(), timestamp_ms
,
426 picture
.allow_overlay());
429 void RTCVideoDecoder::NotifyEndOfBitstreamBuffer(int32 id
) {
430 DVLOG(3) << "NotifyEndOfBitstreamBuffer. id=" << id
;
431 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
433 std::map
<int32
, SHMBuffer
*>::iterator it
=
434 bitstream_buffers_in_decoder_
.find(id
);
435 if (it
== bitstream_buffers_in_decoder_
.end()) {
436 NotifyError(media::VideoDecodeAccelerator::PLATFORM_FAILURE
);
437 NOTREACHED() << "Missing bitstream buffer: " << id
;
442 base::AutoLock
auto_lock(lock_
);
443 PutSHM_Locked(scoped_ptr
<SHMBuffer
>(it
->second
));
445 bitstream_buffers_in_decoder_
.erase(it
);
447 RequestBufferDecode();
450 void RTCVideoDecoder::NotifyFlushDone() {
451 DVLOG(3) << "NotifyFlushDone";
452 NOTREACHED() << "Unexpected flush done notification.";
455 void RTCVideoDecoder::NotifyResetDone() {
456 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
457 DVLOG(3) << "NotifyResetDone";
462 input_buffer_data_
.clear();
464 base::AutoLock
auto_lock(lock_
);
465 state_
= INITIALIZED
;
467 // Send the pending buffers for decoding.
468 RequestBufferDecode();
471 void RTCVideoDecoder::NotifyError(media::VideoDecodeAccelerator::Error error
) {
472 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
476 LOG(ERROR
) << "VDA Error:" << error
;
477 UMA_HISTOGRAM_ENUMERATION("Media.RTCVideoDecoderError",
479 media::VideoDecodeAccelerator::LARGEST_ERROR_ENUM
);
482 base::AutoLock
auto_lock(lock_
);
483 state_
= DECODE_ERROR
;
486 void RTCVideoDecoder::RequestBufferDecode() {
487 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
491 MovePendingBuffersToDecodeBuffers();
493 while (CanMoreDecodeWorkBeDone()) {
494 // Get a buffer and data from the queue.
495 SHMBuffer
* shm_buffer
= NULL
;
496 BufferData buffer_data
;
498 base::AutoLock
auto_lock(lock_
);
499 // Do not request decode if VDA is resetting.
500 if (decode_buffers_
.size() == 0 || state_
== RESETTING
)
502 shm_buffer
= decode_buffers_
.front().first
;
503 buffer_data
= decode_buffers_
.front().second
;
504 decode_buffers_
.pop_front();
505 // Drop the buffers before Reset or Release is called.
506 if (!IsBufferAfterReset(buffer_data
.bitstream_buffer_id
,
507 reset_bitstream_buffer_id_
)) {
508 PutSHM_Locked(scoped_ptr
<SHMBuffer
>(shm_buffer
));
513 // Create a BitstreamBuffer and send to VDA to decode.
514 media::BitstreamBuffer
bitstream_buffer(buffer_data
.bitstream_buffer_id
,
515 shm_buffer
->shm
->handle(),
517 bool inserted
= bitstream_buffers_in_decoder_
518 .insert(std::make_pair(bitstream_buffer
.id(), shm_buffer
)).second
;
520 RecordBufferData(buffer_data
);
521 vda_
->Decode(bitstream_buffer
);
525 bool RTCVideoDecoder::CanMoreDecodeWorkBeDone() {
526 return bitstream_buffers_in_decoder_
.size() < kMaxInFlightDecodes
;
529 bool RTCVideoDecoder::IsBufferAfterReset(int32 id_buffer
, int32 id_reset
) {
530 if (id_reset
== ID_INVALID
)
532 int32 diff
= id_buffer
- id_reset
;
535 return diff
< ID_HALF
;
538 bool RTCVideoDecoder::IsFirstBufferAfterReset(int32 id_buffer
, int32 id_reset
) {
539 if (id_reset
== ID_INVALID
)
540 return id_buffer
== 0;
541 return id_buffer
== ((id_reset
+ 1) & ID_LAST
);
544 void RTCVideoDecoder::SaveToDecodeBuffers_Locked(
545 const webrtc::EncodedImage
& input_image
,
546 scoped_ptr
<SHMBuffer
> shm_buffer
,
547 const BufferData
& buffer_data
) {
548 memcpy(shm_buffer
->shm
->memory(), input_image
._buffer
, input_image
._length
);
549 std::pair
<SHMBuffer
*, BufferData
> buffer_pair
=
550 std::make_pair(shm_buffer
.release(), buffer_data
);
552 // Store the buffer and the metadata to the queue.
553 decode_buffers_
.push_back(buffer_pair
);
556 bool RTCVideoDecoder::SaveToPendingBuffers_Locked(
557 const webrtc::EncodedImage
& input_image
,
558 const BufferData
& buffer_data
) {
559 DVLOG(2) << "SaveToPendingBuffers_Locked"
560 << ". pending_buffers size=" << pending_buffers_
.size()
561 << ". decode_buffers_ size=" << decode_buffers_
.size()
562 << ". available_shm size=" << available_shm_segments_
.size();
563 // Queued too many buffers. Something goes wrong.
564 if (pending_buffers_
.size() >= kMaxNumOfPendingBuffers
) {
565 LOG(WARNING
) << "Too many pending buffers!";
569 // Clone the input image and save it to the queue.
570 uint8_t* buffer
= new uint8_t[input_image
._length
];
571 // TODO(wuchengli): avoid memcpy. Extend webrtc::VideoDecoder::Decode()
572 // interface to take a non-const ptr to the frame and add a method to the
573 // frame that will swap buffers with another.
574 memcpy(buffer
, input_image
._buffer
, input_image
._length
);
575 webrtc::EncodedImage
encoded_image(
576 buffer
, input_image
._length
, input_image
._length
);
577 std::pair
<webrtc::EncodedImage
, BufferData
> buffer_pair
=
578 std::make_pair(encoded_image
, buffer_data
);
580 pending_buffers_
.push_back(buffer_pair
);
584 void RTCVideoDecoder::MovePendingBuffersToDecodeBuffers() {
585 base::AutoLock
auto_lock(lock_
);
586 while (pending_buffers_
.size() > 0) {
587 // Get a pending buffer from the queue.
588 const webrtc::EncodedImage
& input_image
= pending_buffers_
.front().first
;
589 const BufferData
& buffer_data
= pending_buffers_
.front().second
;
591 // Drop the frame if it comes before Reset or Release.
592 if (!IsBufferAfterReset(buffer_data
.bitstream_buffer_id
,
593 reset_bitstream_buffer_id_
)) {
594 delete[] input_image
._buffer
;
595 pending_buffers_
.pop_front();
598 // Get shared memory and save it to decode buffers.
599 scoped_ptr
<SHMBuffer
> shm_buffer
= GetSHM_Locked(input_image
._length
);
602 SaveToDecodeBuffers_Locked(input_image
, shm_buffer
.Pass(), buffer_data
);
603 delete[] input_image
._buffer
;
604 pending_buffers_
.pop_front();
608 void RTCVideoDecoder::ResetInternal() {
609 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
610 DVLOG(2) << "ResetInternal";
616 void RTCVideoDecoder::ReleaseMailbox(
617 base::WeakPtr
<RTCVideoDecoder
> decoder
,
618 const scoped_refptr
<media::GpuVideoAcceleratorFactories
>& factories
,
619 int64 picture_buffer_id
,
621 uint32 release_sync_point
) {
622 DCHECK(factories
->GetTaskRunner()->BelongsToCurrentThread());
623 factories
->WaitSyncPoint(release_sync_point
);
626 decoder
->ReusePictureBuffer(picture_buffer_id
);
629 // It's the last chance to delete the texture after display,
630 // because RTCVideoDecoder was destructed.
631 factories
->DeleteTexture(texture_id
);
634 void RTCVideoDecoder::ReusePictureBuffer(int64 picture_buffer_id
) {
635 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
636 DVLOG(3) << "ReusePictureBuffer. id=" << picture_buffer_id
;
638 DCHECK(!picture_buffers_at_display_
.empty());
639 PictureBufferTextureMap::iterator display_iterator
=
640 picture_buffers_at_display_
.find(picture_buffer_id
);
641 uint32 texture_id
= display_iterator
->second
;
642 DCHECK(display_iterator
!= picture_buffers_at_display_
.end());
643 picture_buffers_at_display_
.erase(display_iterator
);
645 if (!assigned_picture_buffers_
.count(picture_buffer_id
)) {
646 // This picture was dismissed while in display, so we postponed deletion.
647 factories_
->DeleteTexture(texture_id
);
651 // DestroyVDA() might already have been called.
653 vda_
->ReusePictureBuffer(picture_buffer_id
);
656 void RTCVideoDecoder::CreateVDA(media::VideoCodecProfile profile
,
657 base::WaitableEvent
* waiter
) {
658 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
659 vda_
= factories_
->CreateVideoDecodeAccelerator();
660 if (vda_
&& !vda_
->Initialize(profile
, this))
661 vda_
.release()->Destroy();
665 void RTCVideoDecoder::DestroyTextures() {
666 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
668 // Not destroying PictureBuffers in |picture_buffers_at_display_| yet, since
669 // their textures may still be in use by the user of this RTCVideoDecoder.
670 for (PictureBufferTextureMap::iterator it
=
671 picture_buffers_at_display_
.begin();
672 it
!= picture_buffers_at_display_
.end();
674 assigned_picture_buffers_
.erase(it
->first
);
677 for (std::map
<int32
, media::PictureBuffer
>::iterator it
=
678 assigned_picture_buffers_
.begin();
679 it
!= assigned_picture_buffers_
.end();
681 factories_
->DeleteTexture(it
->second
.texture_id());
683 assigned_picture_buffers_
.clear();
686 void RTCVideoDecoder::DestroyVDA() {
687 DVLOG(2) << "DestroyVDA";
688 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
690 vda_
.release()->Destroy();
692 base::AutoLock
auto_lock(lock_
);
693 state_
= UNINITIALIZED
;
696 scoped_ptr
<RTCVideoDecoder::SHMBuffer
> RTCVideoDecoder::GetSHM_Locked(
698 // Reuse a SHM if possible.
699 SHMBuffer
* ret
= NULL
;
700 if (!available_shm_segments_
.empty() &&
701 available_shm_segments_
.back()->size
>= min_size
) {
702 ret
= available_shm_segments_
.back();
703 available_shm_segments_
.pop_back();
705 // Post to vda thread to create shared memory if SHM cannot be reused or the
706 // queue is almost empty.
707 if (num_shm_buffers_
< kMaxNumSharedMemorySegments
&&
708 (ret
== NULL
|| available_shm_segments_
.size() <= 1)) {
709 factories_
->GetTaskRunner()->PostTask(
711 base::Bind(&RTCVideoDecoder::CreateSHM
,
712 weak_factory_
.GetWeakPtr(),
716 return scoped_ptr
<SHMBuffer
>(ret
);
719 void RTCVideoDecoder::PutSHM_Locked(scoped_ptr
<SHMBuffer
> shm_buffer
) {
720 available_shm_segments_
.push_back(shm_buffer
.release());
723 void RTCVideoDecoder::CreateSHM(int number
, size_t min_size
) {
724 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
725 DVLOG(2) << "CreateSHM. size=" << min_size
;
726 int number_to_allocate
;
728 base::AutoLock
auto_lock(lock_
);
730 std::min(kMaxNumSharedMemorySegments
- num_shm_buffers_
, number
);
732 size_t size_to_allocate
= std::max(min_size
, kSharedMemorySegmentBytes
);
733 for (int i
= 0; i
< number_to_allocate
; i
++) {
734 scoped_ptr
<base::SharedMemory
> shm
=
735 factories_
->CreateSharedMemory(size_to_allocate
);
737 base::AutoLock
auto_lock(lock_
);
740 scoped_ptr
<SHMBuffer
>(new SHMBuffer(shm
.Pass(), size_to_allocate
)));
743 // Kick off the decoding.
744 RequestBufferDecode();
747 void RTCVideoDecoder::RecordBufferData(const BufferData
& buffer_data
) {
748 input_buffer_data_
.push_front(buffer_data
);
749 // Why this value? Because why not. avformat.h:MAX_REORDER_DELAY is 16, but
750 // that's too small for some pathological B-frame test videos. The cost of
751 // using too-high a value is low (192 bits per extra slot).
752 static const size_t kMaxInputBufferDataSize
= 128;
753 // Pop from the back of the list, because that's the oldest and least likely
754 // to be useful in the future data.
755 if (input_buffer_data_
.size() > kMaxInputBufferDataSize
)
756 input_buffer_data_
.pop_back();
759 void RTCVideoDecoder::GetBufferData(int32 bitstream_buffer_id
,
760 uint32_t* timestamp
) {
761 for (std::list
<BufferData
>::iterator it
= input_buffer_data_
.begin();
762 it
!= input_buffer_data_
.end();
764 if (it
->bitstream_buffer_id
!= bitstream_buffer_id
)
766 *timestamp
= it
->timestamp
;
769 NOTREACHED() << "Missing bitstream buffer id: " << bitstream_buffer_id
;
772 int32_t RTCVideoDecoder::RecordInitDecodeUMA(int32_t status
) {
773 // Logging boolean is enough to know if HW decoding has been used. Also,
774 // InitDecode is less likely to return an error so enum is not used here.
775 bool sample
= (status
== WEBRTC_VIDEO_CODEC_OK
) ? true : false;
776 UMA_HISTOGRAM_BOOLEAN("Media.RTCVideoDecoderInitDecodeSuccess", sample
);
780 void RTCVideoDecoder::DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent()
782 DCHECK(factories_
->GetTaskRunner()->BelongsToCurrentThread());
785 } // namespace content