[ServiceWorker] Implement WebServiceWorkerContextClient::openWindow().
[chromium-blink-merge.git] / content / renderer / media / rtc_video_decoder.cc
blob0bfc9d87f0d6ff870dcf8f304f4ba76ad09853fd
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"
7 #include "base/bind.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/filters/gpu_video_accelerator_factories.h"
20 #include "third_party/skia/include/core/SkBitmap.h"
21 #include "third_party/webrtc/common_video/interface/texture_video_frame.h"
22 #include "third_party/webrtc/system_wrappers/interface/ref_count.h"
24 namespace content {
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
32 // resources.
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
47 // of |shm|.
48 class RTCVideoDecoder::SHMBuffer {
49 public:
50 SHMBuffer(scoped_ptr<base::SharedMemory> shm, size_t size);
51 ~SHMBuffer();
52 scoped_ptr<base::SharedMemory> const shm;
53 const size_t size;
56 RTCVideoDecoder::SHMBuffer::SHMBuffer(scoped_ptr<base::SharedMemory> shm,
57 size_t size)
58 : shm(shm.Pass()), size(size) {
61 RTCVideoDecoder::SHMBuffer::~SHMBuffer() {
64 RTCVideoDecoder::BufferData::BufferData(int32 bitstream_buffer_id,
65 uint32_t timestamp,
66 size_t size)
67 : bitstream_buffer_id(bitstream_buffer_id),
68 timestamp(timestamp),
69 size(size) {}
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),
84 num_shm_buffers_(0),
85 next_bitstream_buffer_id_(0),
86 reset_bitstream_buffer_id_(ID_INVALID),
87 weak_factory_(this) {
88 DCHECK(!factories_->GetTaskRunner()->BelongsToCurrentThread());
91 RTCVideoDecoder::~RTCVideoDecoder() {
92 DVLOG(2) << "~RTCVideoDecoder";
93 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
94 DestroyVDA();
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();
107 ++it) {
108 delete[] it->first._buffer;
112 // static
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;
119 switch (type) {
120 case webrtc::kVideoCodecVP8:
121 profile = media::VP8PROFILE_ANY;
122 break;
123 case webrtc::kVideoCodecH264:
124 profile = media::H264PROFILE_MAIN;
125 break;
126 default:
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(
134 FROM_HERE,
135 base::Bind(&RTCVideoDecoder::CreateVDA,
136 base::Unretained(decoder.get()),
137 profile,
138 &waiter));
139 waiter.Wait();
140 // vda can be NULL if the codec is not supported.
141 if (decoder->vda_ != NULL) {
142 decoder->state_ = INITIALIZED;
143 } else {
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(
167 FROM_HERE,
168 base::Bind(&RTCVideoDecoder::CreateSHM,
169 weak_factory_.GetWeakPtr(),
170 kMaxInFlightDecodes,
171 kSharedMemorySegmentBytes));
173 return RecordInitDecodeUMA(WEBRTC_VIDEO_CODEC_OK);
176 int32_t RTCVideoDecoder::Decode(
177 const webrtc::EncodedImage& inputImage,
178 bool missingFrames,
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
206 // here.
207 #ifdef ANDROID
208 const bool kVDACanHandleMidstreamResize = false;
209 #else
210 const bool kVDACanHandleMidstreamResize = true;
211 #endif
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,
234 inputImage._length);
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);
244 if (!shm_buffer) {
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_);
249 Reset();
251 return WEBRTC_VIDEO_CODEC_OK;
254 SaveToDecodeBuffers_Locked(inputImage, shm_buffer.Pass(), buffer_data);
255 factories_->GetTaskRunner()->PostTask(
256 FROM_HERE,
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
273 // again.
274 return Reset();
277 int32_t RTCVideoDecoder::Reset() {
278 DVLOG(2) << "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;
286 else
287 reset_bitstream_buffer_id_ = ID_LAST;
288 // If VDA is already resetting, no need to request the reset again.
289 if (state_ != RESETTING) {
290 state_ = RESETTING;
291 factories_->GetTaskRunner()->PostTask(
292 FROM_HERE,
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;
305 if (!vda_)
306 return;
308 std::vector<uint32> texture_ids;
309 std::vector<gpu::Mailbox> texture_mailboxes;
310 decoder_texture_target_ = texture_target;
311 if (!factories_->CreateTextures(count,
312 size,
313 &texture_ids,
314 &texture_mailboxes,
315 decoder_texture_target_)) {
316 NotifyError(media::VideoDecodeAccelerator::PLATFORM_FAILURE);
317 return;
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;
328 DCHECK(inserted);
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;
341 return;
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());
350 return;
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);
365 return;
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);
376 return;
379 // Create a media::VideoFrame.
380 uint32_t timestamp = 0;
381 GetBufferData(picture.bitstream_buffer_id(), &timestamp);
382 scoped_refptr<media::VideoFrame> frame =
383 CreateVideoFrame(picture, pb, timestamp);
384 bool inserted =
385 picture_buffers_at_display_.insert(std::make_pair(
386 picture.picture_buffer_id(),
387 pb.texture_id())).second;
388 DCHECK(inserted);
390 // Create a WebRTC video frame.
391 webrtc::RefCountImpl<NativeHandleImpl>* handle =
392 new webrtc::RefCountImpl<NativeHandleImpl>(frame);
393 webrtc::TextureVideoFrame decoded_image(handle,
394 picture.visible_rect().width(),
395 picture.visible_rect().height(),
396 timestamp,
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 static void ReadPixelsSyncInner(
411 const scoped_refptr<media::GpuVideoAcceleratorFactories>& factories,
412 uint32 texture_id,
413 const gfx::Rect& visible_rect,
414 const SkBitmap& pixels,
415 base::WaitableEvent* event) {
416 factories->ReadPixels(texture_id, visible_rect, pixels);
417 event->Signal();
420 static void ReadPixelsSync(
421 const scoped_refptr<media::GpuVideoAcceleratorFactories>& factories,
422 uint32 texture_id,
423 const gfx::Rect& visible_rect,
424 const SkBitmap& pixels) {
425 base::WaitableEvent event(true, false);
426 if (!factories->GetTaskRunner()->PostTask(FROM_HERE,
427 base::Bind(&ReadPixelsSyncInner,
428 factories,
429 texture_id,
430 visible_rect,
431 pixels,
432 &event)))
433 return;
434 event.Wait();
437 scoped_refptr<media::VideoFrame> RTCVideoDecoder::CreateVideoFrame(
438 const media::Picture& picture,
439 const media::PictureBuffer& pb,
440 uint32_t timestamp) {
441 gfx::Rect visible_rect(picture.visible_rect());
442 DCHECK(decoder_texture_target_);
443 // Convert timestamp from 90KHz to ms.
444 base::TimeDelta timestamp_ms = base::TimeDelta::FromInternalValue(
445 base::checked_cast<uint64_t>(timestamp) * 1000 / 90);
446 return media::VideoFrame::WrapNativeTexture(
447 make_scoped_ptr(new gpu::MailboxHolder(pb.texture_mailbox(),
448 decoder_texture_target_, 0)),
449 media::BindToCurrentLoop(base::Bind(
450 &RTCVideoDecoder::ReleaseMailbox, weak_factory_.GetWeakPtr(),
451 factories_, picture.picture_buffer_id(), pb.texture_id())),
452 pb.size(), visible_rect, visible_rect.size(), timestamp_ms,
453 base::Bind(&ReadPixelsSync, factories_, pb.texture_id(), visible_rect),
454 picture.allow_overlay());
457 void RTCVideoDecoder::NotifyEndOfBitstreamBuffer(int32 id) {
458 DVLOG(3) << "NotifyEndOfBitstreamBuffer. id=" << id;
459 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
461 std::map<int32, SHMBuffer*>::iterator it =
462 bitstream_buffers_in_decoder_.find(id);
463 if (it == bitstream_buffers_in_decoder_.end()) {
464 NotifyError(media::VideoDecodeAccelerator::PLATFORM_FAILURE);
465 NOTREACHED() << "Missing bitstream buffer: " << id;
466 return;
470 base::AutoLock auto_lock(lock_);
471 PutSHM_Locked(scoped_ptr<SHMBuffer>(it->second));
473 bitstream_buffers_in_decoder_.erase(it);
475 RequestBufferDecode();
478 void RTCVideoDecoder::NotifyFlushDone() {
479 DVLOG(3) << "NotifyFlushDone";
480 NOTREACHED() << "Unexpected flush done notification.";
483 void RTCVideoDecoder::NotifyResetDone() {
484 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
485 DVLOG(3) << "NotifyResetDone";
487 if (!vda_)
488 return;
490 input_buffer_data_.clear();
492 base::AutoLock auto_lock(lock_);
493 state_ = INITIALIZED;
495 // Send the pending buffers for decoding.
496 RequestBufferDecode();
499 void RTCVideoDecoder::NotifyError(media::VideoDecodeAccelerator::Error error) {
500 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
501 if (!vda_)
502 return;
504 LOG(ERROR) << "VDA Error:" << error;
505 UMA_HISTOGRAM_ENUMERATION("Media.RTCVideoDecoderError",
506 error,
507 media::VideoDecodeAccelerator::LARGEST_ERROR_ENUM);
508 DestroyVDA();
510 base::AutoLock auto_lock(lock_);
511 state_ = DECODE_ERROR;
514 void RTCVideoDecoder::RequestBufferDecode() {
515 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
516 if (!vda_)
517 return;
519 MovePendingBuffersToDecodeBuffers();
521 while (CanMoreDecodeWorkBeDone()) {
522 // Get a buffer and data from the queue.
523 SHMBuffer* shm_buffer = NULL;
524 BufferData buffer_data;
526 base::AutoLock auto_lock(lock_);
527 // Do not request decode if VDA is resetting.
528 if (decode_buffers_.size() == 0 || state_ == RESETTING)
529 return;
530 shm_buffer = decode_buffers_.front().first;
531 buffer_data = decode_buffers_.front().second;
532 decode_buffers_.pop_front();
533 // Drop the buffers before Reset or Release is called.
534 if (!IsBufferAfterReset(buffer_data.bitstream_buffer_id,
535 reset_bitstream_buffer_id_)) {
536 PutSHM_Locked(scoped_ptr<SHMBuffer>(shm_buffer));
537 continue;
541 // Create a BitstreamBuffer and send to VDA to decode.
542 media::BitstreamBuffer bitstream_buffer(buffer_data.bitstream_buffer_id,
543 shm_buffer->shm->handle(),
544 buffer_data.size);
545 bool inserted = bitstream_buffers_in_decoder_
546 .insert(std::make_pair(bitstream_buffer.id(), shm_buffer)).second;
547 DCHECK(inserted);
548 RecordBufferData(buffer_data);
549 vda_->Decode(bitstream_buffer);
553 bool RTCVideoDecoder::CanMoreDecodeWorkBeDone() {
554 return bitstream_buffers_in_decoder_.size() < kMaxInFlightDecodes;
557 bool RTCVideoDecoder::IsBufferAfterReset(int32 id_buffer, int32 id_reset) {
558 if (id_reset == ID_INVALID)
559 return true;
560 int32 diff = id_buffer - id_reset;
561 if (diff <= 0)
562 diff += ID_LAST + 1;
563 return diff < ID_HALF;
566 bool RTCVideoDecoder::IsFirstBufferAfterReset(int32 id_buffer, int32 id_reset) {
567 if (id_reset == ID_INVALID)
568 return id_buffer == 0;
569 return id_buffer == ((id_reset + 1) & ID_LAST);
572 void RTCVideoDecoder::SaveToDecodeBuffers_Locked(
573 const webrtc::EncodedImage& input_image,
574 scoped_ptr<SHMBuffer> shm_buffer,
575 const BufferData& buffer_data) {
576 memcpy(shm_buffer->shm->memory(), input_image._buffer, input_image._length);
577 std::pair<SHMBuffer*, BufferData> buffer_pair =
578 std::make_pair(shm_buffer.release(), buffer_data);
580 // Store the buffer and the metadata to the queue.
581 decode_buffers_.push_back(buffer_pair);
584 bool RTCVideoDecoder::SaveToPendingBuffers_Locked(
585 const webrtc::EncodedImage& input_image,
586 const BufferData& buffer_data) {
587 DVLOG(2) << "SaveToPendingBuffers_Locked"
588 << ". pending_buffers size=" << pending_buffers_.size()
589 << ". decode_buffers_ size=" << decode_buffers_.size()
590 << ". available_shm size=" << available_shm_segments_.size();
591 // Queued too many buffers. Something goes wrong.
592 if (pending_buffers_.size() >= kMaxNumOfPendingBuffers) {
593 LOG(WARNING) << "Too many pending buffers!";
594 return false;
597 // Clone the input image and save it to the queue.
598 uint8_t* buffer = new uint8_t[input_image._length];
599 // TODO(wuchengli): avoid memcpy. Extend webrtc::VideoDecoder::Decode()
600 // interface to take a non-const ptr to the frame and add a method to the
601 // frame that will swap buffers with another.
602 memcpy(buffer, input_image._buffer, input_image._length);
603 webrtc::EncodedImage encoded_image(
604 buffer, input_image._length, input_image._length);
605 std::pair<webrtc::EncodedImage, BufferData> buffer_pair =
606 std::make_pair(encoded_image, buffer_data);
608 pending_buffers_.push_back(buffer_pair);
609 return true;
612 void RTCVideoDecoder::MovePendingBuffersToDecodeBuffers() {
613 base::AutoLock auto_lock(lock_);
614 while (pending_buffers_.size() > 0) {
615 // Get a pending buffer from the queue.
616 const webrtc::EncodedImage& input_image = pending_buffers_.front().first;
617 const BufferData& buffer_data = pending_buffers_.front().second;
619 // Drop the frame if it comes before Reset or Release.
620 if (!IsBufferAfterReset(buffer_data.bitstream_buffer_id,
621 reset_bitstream_buffer_id_)) {
622 delete[] input_image._buffer;
623 pending_buffers_.pop_front();
624 continue;
626 // Get shared memory and save it to decode buffers.
627 scoped_ptr<SHMBuffer> shm_buffer = GetSHM_Locked(input_image._length);
628 if (!shm_buffer)
629 return;
630 SaveToDecodeBuffers_Locked(input_image, shm_buffer.Pass(), buffer_data);
631 delete[] input_image._buffer;
632 pending_buffers_.pop_front();
636 void RTCVideoDecoder::ResetInternal() {
637 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
638 DVLOG(2) << "ResetInternal";
639 if (vda_)
640 vda_->Reset();
643 // static
644 void RTCVideoDecoder::ReleaseMailbox(
645 base::WeakPtr<RTCVideoDecoder> decoder,
646 const scoped_refptr<media::GpuVideoAcceleratorFactories>& factories,
647 int64 picture_buffer_id,
648 uint32 texture_id,
649 uint32 release_sync_point) {
650 DCHECK(factories->GetTaskRunner()->BelongsToCurrentThread());
651 factories->WaitSyncPoint(release_sync_point);
653 if (decoder) {
654 decoder->ReusePictureBuffer(picture_buffer_id);
655 return;
657 // It's the last chance to delete the texture after display,
658 // because RTCVideoDecoder was destructed.
659 factories->DeleteTexture(texture_id);
662 void RTCVideoDecoder::ReusePictureBuffer(int64 picture_buffer_id) {
663 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
664 DVLOG(3) << "ReusePictureBuffer. id=" << picture_buffer_id;
666 DCHECK(!picture_buffers_at_display_.empty());
667 PictureBufferTextureMap::iterator display_iterator =
668 picture_buffers_at_display_.find(picture_buffer_id);
669 uint32 texture_id = display_iterator->second;
670 DCHECK(display_iterator != picture_buffers_at_display_.end());
671 picture_buffers_at_display_.erase(display_iterator);
673 if (!assigned_picture_buffers_.count(picture_buffer_id)) {
674 // This picture was dismissed while in display, so we postponed deletion.
675 factories_->DeleteTexture(texture_id);
676 return;
679 // DestroyVDA() might already have been called.
680 if (vda_)
681 vda_->ReusePictureBuffer(picture_buffer_id);
684 void RTCVideoDecoder::CreateVDA(media::VideoCodecProfile profile,
685 base::WaitableEvent* waiter) {
686 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
687 vda_ = factories_->CreateVideoDecodeAccelerator();
688 if (vda_ && !vda_->Initialize(profile, this))
689 vda_.release()->Destroy();
690 waiter->Signal();
693 void RTCVideoDecoder::DestroyTextures() {
694 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
696 // Not destroying PictureBuffers in |picture_buffers_at_display_| yet, since
697 // their textures may still be in use by the user of this RTCVideoDecoder.
698 for (PictureBufferTextureMap::iterator it =
699 picture_buffers_at_display_.begin();
700 it != picture_buffers_at_display_.end();
701 ++it) {
702 assigned_picture_buffers_.erase(it->first);
705 for (std::map<int32, media::PictureBuffer>::iterator it =
706 assigned_picture_buffers_.begin();
707 it != assigned_picture_buffers_.end();
708 ++it) {
709 factories_->DeleteTexture(it->second.texture_id());
711 assigned_picture_buffers_.clear();
714 void RTCVideoDecoder::DestroyVDA() {
715 DVLOG(2) << "DestroyVDA";
716 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
717 if (vda_)
718 vda_.release()->Destroy();
719 DestroyTextures();
720 base::AutoLock auto_lock(lock_);
721 state_ = UNINITIALIZED;
724 scoped_ptr<RTCVideoDecoder::SHMBuffer> RTCVideoDecoder::GetSHM_Locked(
725 size_t min_size) {
726 // Reuse a SHM if possible.
727 SHMBuffer* ret = NULL;
728 if (!available_shm_segments_.empty() &&
729 available_shm_segments_.back()->size >= min_size) {
730 ret = available_shm_segments_.back();
731 available_shm_segments_.pop_back();
733 // Post to vda thread to create shared memory if SHM cannot be reused or the
734 // queue is almost empty.
735 if (num_shm_buffers_ < kMaxNumSharedMemorySegments &&
736 (ret == NULL || available_shm_segments_.size() <= 1)) {
737 factories_->GetTaskRunner()->PostTask(
738 FROM_HERE,
739 base::Bind(&RTCVideoDecoder::CreateSHM,
740 weak_factory_.GetWeakPtr(),
742 min_size));
744 return scoped_ptr<SHMBuffer>(ret);
747 void RTCVideoDecoder::PutSHM_Locked(scoped_ptr<SHMBuffer> shm_buffer) {
748 available_shm_segments_.push_back(shm_buffer.release());
751 void RTCVideoDecoder::CreateSHM(int number, size_t min_size) {
752 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
753 DVLOG(2) << "CreateSHM. size=" << min_size;
754 int number_to_allocate;
756 base::AutoLock auto_lock(lock_);
757 number_to_allocate =
758 std::min(kMaxNumSharedMemorySegments - num_shm_buffers_, number);
760 size_t size_to_allocate = std::max(min_size, kSharedMemorySegmentBytes);
761 for (int i = 0; i < number_to_allocate; i++) {
762 scoped_ptr<base::SharedMemory> shm =
763 factories_->CreateSharedMemory(size_to_allocate);
764 if (shm) {
765 base::AutoLock auto_lock(lock_);
766 num_shm_buffers_++;
767 PutSHM_Locked(
768 scoped_ptr<SHMBuffer>(new SHMBuffer(shm.Pass(), size_to_allocate)));
771 // Kick off the decoding.
772 RequestBufferDecode();
775 void RTCVideoDecoder::RecordBufferData(const BufferData& buffer_data) {
776 input_buffer_data_.push_front(buffer_data);
777 // Why this value? Because why not. avformat.h:MAX_REORDER_DELAY is 16, but
778 // that's too small for some pathological B-frame test videos. The cost of
779 // using too-high a value is low (192 bits per extra slot).
780 static const size_t kMaxInputBufferDataSize = 128;
781 // Pop from the back of the list, because that's the oldest and least likely
782 // to be useful in the future data.
783 if (input_buffer_data_.size() > kMaxInputBufferDataSize)
784 input_buffer_data_.pop_back();
787 void RTCVideoDecoder::GetBufferData(int32 bitstream_buffer_id,
788 uint32_t* timestamp) {
789 for (std::list<BufferData>::iterator it = input_buffer_data_.begin();
790 it != input_buffer_data_.end();
791 ++it) {
792 if (it->bitstream_buffer_id != bitstream_buffer_id)
793 continue;
794 *timestamp = it->timestamp;
795 return;
797 NOTREACHED() << "Missing bitstream buffer id: " << bitstream_buffer_id;
800 int32_t RTCVideoDecoder::RecordInitDecodeUMA(int32_t status) {
801 // Logging boolean is enough to know if HW decoding has been used. Also,
802 // InitDecode is less likely to return an error so enum is not used here.
803 bool sample = (status == WEBRTC_VIDEO_CODEC_OK) ? true : false;
804 UMA_HISTOGRAM_BOOLEAN("Media.RTCVideoDecoderInitDecodeSuccess", sample);
805 return status;
808 void RTCVideoDecoder::DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent()
809 const {
810 DCHECK(factories_->GetTaskRunner()->BelongsToCurrentThread());
813 } // namespace content