blob: 48d6512971db27729c517ecb45c8e3f0c5cf4b85 [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
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "common_video/include/i420_buffer_pool.h"
magjed@webrtc.org73d763e2015-03-17 11:40:45 +000012
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020013#include "rtc_base/checks.h"
magjed@webrtc.org73d763e2015-03-17 11:40:45 +000014
magjed@webrtc.org73d763e2015-03-17 11:40:45 +000015namespace webrtc {
16
Per00983572016-11-04 08:57:26 +010017I420BufferPool::I420BufferPool(bool zero_initialize,
18 size_t max_number_of_buffers)
19 : zero_initialize_(zero_initialize),
20 max_number_of_buffers_(max_number_of_buffers) {}
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_);
magjed@webrtc.org73d763e2015-03-17 11:40:45 +000029 // Release buffers with wrong resolution.
30 for (auto it = buffers_.begin(); it != buffers_.end();) {
31 if ((*it)->width() != width || (*it)->height() != height)
32 it = buffers_.erase(it);
33 else
34 ++it;
35 }
36 // Look for a free buffer.
nissed591e3f2016-05-26 06:49:55 -070037 for (const rtc::scoped_refptr<PooledI420Buffer>& buffer : buffers_) {
38 // If the buffer is in use, the ref count will be >= 2, one from the list we
39 // are looping over and one from the application. If the ref count is 1,
40 // then the list we are looping over holds the only reference and it's safe
41 // to reuse.
42 if (buffer->HasOneRef())
43 return buffer;
magjed@webrtc.org73d763e2015-03-17 11:40:45 +000044 }
Per00983572016-11-04 08:57:26 +010045
46 if (buffers_.size() >= max_number_of_buffers_)
47 return nullptr;
magjed@webrtc.org73d763e2015-03-17 11:40:45 +000048 // Allocate new buffer.
nissed591e3f2016-05-26 06:49:55 -070049 rtc::scoped_refptr<PooledI420Buffer> buffer =
50 new PooledI420Buffer(width, height);
hbos900f9752016-02-05 08:08:34 -080051 if (zero_initialize_)
52 buffer->InitializeData();
53 buffers_.push_back(buffer);
nissed591e3f2016-05-26 06:49:55 -070054 return buffer;
magjed@webrtc.org73d763e2015-03-17 11:40:45 +000055}
56
57} // namespace webrtc