1 /* 2 * Copyright (C) 2015 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.android.tv.tuner.exoplayer.buffer; 18 19 import com.google.android.exoplayer.SampleHolder; 20 import java.util.LinkedList; 21 22 /** Pool of samples to recycle ByteBuffers as much as possible. */ 23 public class SamplePool { 24 private final LinkedList<SampleHolder> mSamplePool = new LinkedList<>(); 25 26 /** 27 * Acquires a sample with a buffer larger than size from the pool. Allocate new one or resize an 28 * existing buffer if necessary. 29 */ acquireSample(int size)30 public synchronized SampleHolder acquireSample(int size) { 31 if (mSamplePool.isEmpty()) { 32 SampleHolder sample = new SampleHolder(SampleHolder.BUFFER_REPLACEMENT_MODE_NORMAL); 33 sample.ensureSpaceForWrite(size); 34 return sample; 35 } 36 SampleHolder smallestSufficientSample = null; 37 SampleHolder maxSample = mSamplePool.getFirst(); 38 for (SampleHolder sample : mSamplePool) { 39 // Grab the smallest sufficient sample. 40 if (sample.data.capacity() >= size 41 && (smallestSufficientSample == null 42 || smallestSufficientSample.data.capacity() > sample.data.capacity())) { 43 smallestSufficientSample = sample; 44 } 45 46 // Grab the max size sample. 47 if (maxSample.data.capacity() < sample.data.capacity()) { 48 maxSample = sample; 49 } 50 } 51 SampleHolder sampleFromPool = smallestSufficientSample; 52 53 // If there's no sufficient sample, grab the maximum sample and resize it to size. 54 if (sampleFromPool == null) { 55 sampleFromPool = maxSample; 56 sampleFromPool.ensureSpaceForWrite(size); 57 } 58 mSamplePool.remove(sampleFromPool); 59 return sampleFromPool; 60 } 61 62 /** Releases the sample back to the pool. */ releaseSample(SampleHolder sample)63 public synchronized void releaseSample(SampleHolder sample) { 64 sample.clearData(); 65 mSamplePool.offerLast(sample); 66 } 67 } 68