blob: 630955aff9ddce7748077f3b52fd2d0769fff925 [file] [log] [blame]
magjed@webrtc.org73d763e2015-03-17 11:40:45 +00001/*
2 * Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
kjellander6f8ce062015-11-16 13:52:24 -080011#include "webrtc/common_video/include/i420_buffer_pool.h"
magjed@webrtc.org73d763e2015-03-17 11:40:45 +000012
13#include "webrtc/base/checks.h"
14
magjed@webrtc.org73d763e2015-03-17 11:40:45 +000015namespace webrtc {
16
perkj5f8ebae2016-09-27 03:47:41 -070017const size_t I420BufferPool::kMaxNumberOfFramesBeforeCrash = 300;
18
hbos900f9752016-02-05 08:08:34 -080019I420BufferPool::I420BufferPool(bool zero_initialize)
Magnus Jedvert7fd92862016-09-17 11:27:35 +020020 : zero_initialize_(zero_initialize) {}
pbos@webrtc.orga3209a22015-03-20 13:35:56 +000021
22void I420BufferPool::Release() {
pbos@webrtc.orga3209a22015-03-20 13:35:56 +000023 buffers_.clear();
magjed@webrtc.org73d763e2015-03-17 11:40:45 +000024}
25
nissed591e3f2016-05-26 06:49:55 -070026rtc::scoped_refptr<I420Buffer> I420BufferPool::CreateBuffer(int width,
27 int height) {
Magnus Jedvert7fd92862016-09-17 11:27:35 +020028 RTC_DCHECK_RUNS_SERIALIZED(&race_checker_);
perkj5f8ebae2016-09-27 03:47:41 -070029 RTC_CHECK_LT(buffers_.size(), kMaxNumberOfFramesBeforeCrash)
30 << "I420BufferPool too big.";
magjed@webrtc.org73d763e2015-03-17 11:40:45 +000031 // Release buffers with wrong resolution.
32 for (auto it = buffers_.begin(); it != buffers_.end();) {
33 if ((*it)->width() != width || (*it)->height() != height)
34 it = buffers_.erase(it);
35 else
36 ++it;
37 }
38 // Look for a free buffer.
nissed591e3f2016-05-26 06:49:55 -070039 for (const rtc::scoped_refptr<PooledI420Buffer>& buffer : buffers_) {
40 // If the buffer is in use, the ref count will be >= 2, one from the list we
41 // are looping over and one from the application. If the ref count is 1,
42 // then the list we are looping over holds the only reference and it's safe
43 // to reuse.
44 if (buffer->HasOneRef())
45 return buffer;
magjed@webrtc.org73d763e2015-03-17 11:40:45 +000046 }
47 // Allocate new buffer.
nissed591e3f2016-05-26 06:49:55 -070048 rtc::scoped_refptr<PooledI420Buffer> buffer =
49 new PooledI420Buffer(width, height);
hbos900f9752016-02-05 08:08:34 -080050 if (zero_initialize_)
51 buffer->InitializeData();
52 buffers_.push_back(buffer);
nissed591e3f2016-05-26 06:49:55 -070053 return buffer;
magjed@webrtc.org73d763e2015-03-17 11:40:45 +000054}
55
56} // namespace webrtc