• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
21 import java.util.LinkedList;
22 
23 /**
24  * Pool of samples to recycle ByteBuffers as much as possible.
25  */
26 public class SamplePool {
27     private final LinkedList<SampleHolder> mSamplePool = new LinkedList<>();
28 
29     /**
30      * Acquires a sample with a buffer larger than size from the pool. Allocate new one or resize
31      * an existing buffer if necessary.
32      */
acquireSample(int size)33     public synchronized SampleHolder acquireSample(int size) {
34         if (mSamplePool.isEmpty()) {
35             SampleHolder sample = new SampleHolder(SampleHolder.BUFFER_REPLACEMENT_MODE_NORMAL);
36             sample.ensureSpaceForWrite(size);
37             return sample;
38         }
39         SampleHolder smallestSufficientSample = null;
40         SampleHolder maxSample = mSamplePool.getFirst();
41         for (SampleHolder sample : mSamplePool) {
42             // Grab the smallest sufficient sample.
43             if (sample.data.capacity() >= size && (smallestSufficientSample == null
44                     || smallestSufficientSample.data.capacity() > sample.data.capacity())) {
45                 smallestSufficientSample = sample;
46             }
47 
48             // Grab the max size sample.
49             if (maxSample.data.capacity() < sample.data.capacity()) {
50                 maxSample = sample;
51             }
52         }
53         SampleHolder sampleFromPool = smallestSufficientSample;
54 
55         // If there's no sufficient sample, grab the maximum sample and resize it to size.
56         if (sampleFromPool == null) {
57             sampleFromPool = maxSample;
58             sampleFromPool.ensureSpaceForWrite(size);
59         }
60         mSamplePool.remove(sampleFromPool);
61         return sampleFromPool;
62     }
63 
64     /**
65      * Releases the sample back to the pool.
66      */
releaseSample(SampleHolder sample)67     public synchronized void releaseSample(SampleHolder sample) {
68         sample.clearData();
69         mSamplePool.offerLast(sample);
70     }
71 }
72