summaryrefslogtreecommitdiffstats
path: root/src/com/android/messaging/datamodel/BitmapPool.java
blob: 1ec4f765207c417e15be2289c8b4b2270b013b79 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
/*
 * Copyright (C) 2015 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.messaging.datamodel;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.SparseArray;

import com.android.messaging.datamodel.MemoryCacheManager.MemoryCache;
import com.android.messaging.util.Assert;
import com.android.messaging.util.LogUtil;

import java.io.InputStream;

/**
 * Class for creating / loading / reusing bitmaps. This class allow the user to create a new bitmap,
 * reuse an bitmap from the pool and to return a bitmap for future reuse.  The pool of bitmaps
 * allows for faster decode and more efficient memory usage.
 * Note: consumers should not create BitmapPool directly, but instead get the pool they want from
 * the BitmapPoolManager.
 */
public class BitmapPool implements MemoryCache {
    public static final int MAX_SUPPORTED_IMAGE_DIMENSION = 0xFFFF;

    protected static final boolean VERBOSE = false;

    /**
     * Number of reuse failures to skip before reporting.
     */
    private static final int FAILED_REPORTING_FREQUENCY = 100;

    /**
     * Count of reuse failures which have occurred.
     */
    private static volatile int sFailedBitmapReuseCount = 0;

    /**
     * Overall pool data structure which currently only supports rectangular bitmaps. The size of
     * one of the sides is used to index into the SparseArray.
     */
    private final SparseArray<SingleSizePool> mPool;
    private final Object mPoolLock = new Object();
    private final String mPoolName;
    private final int mMaxSize;

    /**
     * Inner structure which holds a pool of bitmaps all the same size (i.e. all have the same
     * width as each other and height as each other, but not necessarily the same).
     */
    private class SingleSizePool {
        int mNumItems;
        final Bitmap[] mBitmaps;

        SingleSizePool(final int maxPoolSize) {
            mNumItems = 0;
            mBitmaps = new Bitmap[maxPoolSize];
        }
    }

    /**
     * Creates a pool of reused bitmaps with helper decode methods which will attempt to use the
     * reclaimed bitmaps. This will help speed up the creation of bitmaps by using already allocated
     * bitmaps.
     * @param maxSize The overall max size of the pool. When the pool exceeds this size, all calls
     * to reclaimBitmap(Bitmap) will result in recycling the bitmap.
     * @param name Name of the bitmap pool and only used for logging. Can not be null.
     */
    BitmapPool(final int maxSize, @NonNull final String name) {
        Assert.isTrue(maxSize > 0);
        Assert.isTrue(!TextUtils.isEmpty(name));
        mPoolName = name;
        mMaxSize = maxSize;
        mPool = new SparseArray<SingleSizePool>();
    }

    @Override
    public void reclaim() {
        synchronized (mPoolLock) {
            for (int p = 0; p < mPool.size(); p++) {
                final SingleSizePool singleSizePool = mPool.valueAt(p);
                for (int i = 0; i < singleSizePool.mNumItems; i++) {
                    singleSizePool.mBitmaps[i].recycle();
                    singleSizePool.mBitmaps[i] = null;
                }
                singleSizePool.mNumItems = 0;
            }
            mPool.clear();
        }
    }

    /**
     * Creates a new BitmapFactory.Options.
     */
    public static BitmapFactory.Options getBitmapOptionsForPool(final boolean scaled,
            final int inputDensity, final int targetDensity) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inScaled = scaled;
        options.inDensity = inputDensity;
        options.inTargetDensity = targetDensity;
        options.inSampleSize = 1;
        options.inJustDecodeBounds = false;
        options.inMutable = true;
        return options;
    }

    /**
     * @return The pool key for the provided image dimensions or 0 if either width or height is
     * greater than the max supported image dimension.
     */
    private int getPoolKey(final int width, final int height) {
        if (width > MAX_SUPPORTED_IMAGE_DIMENSION || height > MAX_SUPPORTED_IMAGE_DIMENSION) {
            return 0;
        }
        return (width << 16) | height;
    }

    /**
     *
     * @return A bitmap in the pool with the specified dimensions or null if no bitmap with the
     * specified dimension is available.
     */
    private Bitmap findPoolBitmap(final int width, final int height) {
        final int poolKey = getPoolKey(width, height);
        if (poolKey != 0) {
            synchronized (mPoolLock) {
                // Take a bitmap from the pool if one is available
                final SingleSizePool singlePool = mPool.get(poolKey);
                if (singlePool != null && singlePool.mNumItems > 0) {
                    singlePool.mNumItems--;
                    final Bitmap foundBitmap = singlePool.mBitmaps[singlePool.mNumItems];
                    singlePool.mBitmaps[singlePool.mNumItems] = null;
                    return foundBitmap;
                }
            }
        }
        return null;
    }

    /**
     * Internal function to try and find a bitmap in the pool which matches the desired width and
     * height and then set that in the bitmap options properly.
     *
     * TODO: Why do we take a width/height? Shouldn't this already be in the
     * BitmapFactory.Options instance? Can we assert that they match?
     * @param optionsTmp The BitmapFactory.Options to update with the bitmap for the system to try
     * to reuse.
     * @param width The width of the reusable bitmap.
     * @param height The height of the reusable bitmap.
     */
    private void assignPoolBitmap(final BitmapFactory.Options optionsTmp, final int width,
            final int height) {
        if (optionsTmp.inJustDecodeBounds) {
            return;
        }
        optionsTmp.inBitmap = findPoolBitmap(width, height);
    }

    /**
     * Load a resource into a bitmap. Uses a bitmap from the pool if possible to reduce memory
     * turnover.
     * @param resourceId Resource id to load.
     * @param resources Application resources. Cannot be null.
     * @param optionsTmp Should be the same options returned from getBitmapOptionsForPool(). Cannot
     * be null.
     * @param width The width of the bitmap.
     * @param height The height of the bitmap.
     * @return The decoded Bitmap with the resource drawn in it.
     */
    public Bitmap decodeSampledBitmapFromResource(final int resourceId,
            @NonNull final Resources resources, @NonNull final BitmapFactory.Options optionsTmp,
            final int width, final int height) {
        Assert.notNull(resources);
        Assert.notNull(optionsTmp);
        Assert.isTrue(width > 0);
        Assert.isTrue(height > 0);
        assignPoolBitmap(optionsTmp, width, height);
        Bitmap b = null;
        try {
            b = BitmapFactory.decodeResource(resources, resourceId, optionsTmp);
        } catch (final IllegalArgumentException e) {
            // BitmapFactory couldn't decode the file, try again without an inputBufferBitmap.
            if (optionsTmp.inBitmap != null) {
                optionsTmp.inBitmap = null;
                b = BitmapFactory.decodeResource(resources, resourceId, optionsTmp);
                sFailedBitmapReuseCount++;
                if (sFailedBitmapReuseCount % FAILED_REPORTING_FREQUENCY == 0) {
                    LogUtil.w(LogUtil.BUGLE_TAG,
                            "Pooled bitmap consistently not being reused count = " +
                            sFailedBitmapReuseCount);
                }
            }
        } catch (final OutOfMemoryError e) {
            LogUtil.w(LogUtil.BUGLE_TAG, "Oom decoding resource " + resourceId);
            reclaim();
        }
        return b;
    }

    /**
     * Load an input stream into a bitmap. Uses a bitmap from the pool if possible to reduce memory
     * turnover.
     * @param inputStream InputStream load. Cannot be null.
     * @param optionsTmp Should be the same options returned from getBitmapOptionsForPool(). Cannot
     * be null.
     * @param width The width of the bitmap.
     * @param height The height of the bitmap.
     * @return The decoded Bitmap with the resource drawn in it.
     */
    public Bitmap decodeSampledBitmapFromInputStream(@NonNull final InputStream inputStream,
            @NonNull final BitmapFactory.Options optionsTmp,
            final int width, final int height) {
        Assert.notNull(inputStream);
        Assert.isTrue(width > 0);
        Assert.isTrue(height > 0);
        assignPoolBitmap(optionsTmp, width, height);
        Bitmap b = null;
        try {
            b = BitmapFactory.decodeStream(inputStream, null, optionsTmp);
        } catch (final IllegalArgumentException e) {
            // BitmapFactory couldn't decode the file, try again without an inputBufferBitmap.
            if (optionsTmp.inBitmap != null) {
                optionsTmp.inBitmap = null;
                b = BitmapFactory.decodeStream(inputStream, null, optionsTmp);
                sFailedBitmapReuseCount++;
                if (sFailedBitmapReuseCount % FAILED_REPORTING_FREQUENCY == 0) {
                    LogUtil.w(LogUtil.BUGLE_TAG,
                            "Pooled bitmap consistently not being reused count = " +
                            sFailedBitmapReuseCount);
                }
            }
        } catch (final OutOfMemoryError e) {
            LogUtil.w(LogUtil.BUGLE_TAG, "Oom decoding inputStream");
            reclaim();
        }
        return b;
    }

    /**
     * Turn encoded bytes into a bitmap. Uses a bitmap from the pool if possible to reduce memory
     * turnover.
     * @param bytes Encoded bytes to draw on the bitmap. Cannot be null.
     * @param optionsTmp The bitmap will set here and the input should be generated from
     * getBitmapOptionsForPool(). Cannot be null.
     * @param width The width of the bitmap.
     * @param height The height of the bitmap.
     * @return A Bitmap with the encoded bytes drawn in it.
     */
    public Bitmap decodeByteArray(@NonNull final byte[] bytes,
            @NonNull final BitmapFactory.Options optionsTmp, final int width,
            final int height) throws OutOfMemoryError {
        Assert.notNull(bytes);
        Assert.notNull(optionsTmp);
        Assert.isTrue(width > 0);
        Assert.isTrue(height > 0);
        assignPoolBitmap(optionsTmp, width, height);
        Bitmap b = null;
        try {
            b = BitmapFactory.decodeByteArray(bytes, 0, bytes.length, optionsTmp);
        } catch (final IllegalArgumentException e) {
            if (VERBOSE) {
                LogUtil.v(LogUtil.BUGLE_TAG, "BitmapPool(" + mPoolName +
                        ") Unable to use pool bitmap");
            }
            // BitmapFactory couldn't decode the file, try again without an inputBufferBitmap.
            // (i.e. without the bitmap from the pool)
            if (optionsTmp.inBitmap != null) {
                optionsTmp.inBitmap = null;
                b = BitmapFactory.decodeByteArray(bytes, 0, bytes.length, optionsTmp);
                sFailedBitmapReuseCount++;
                if (sFailedBitmapReuseCount % FAILED_REPORTING_FREQUENCY == 0) {
                    LogUtil.w(LogUtil.BUGLE_TAG,
                            "Pooled bitmap consistently not being reused count = " +
                            sFailedBitmapReuseCount);
                }
            }
        }
        return b;
    }

    /**
     * Creates a bitmap with the given size, this will reuse a bitmap in the pool, if one is
     * available, otherwise this will create a new one.
     * @param width The desired width of the bitmap.
     * @param height The desired height of the bitmap.
     * @return A bitmap with the desired width and height, this maybe a reused bitmap from the pool.
     */
    public Bitmap createOrReuseBitmap(final int width, final int height) {
        Bitmap b = findPoolBitmap(width, height);
        if (b == null) {
            b = createBitmap(width, height);
        }
        return b;
    }

    /**
     * This will create a new bitmap regardless of pool state.
     * @param width The desired width of the bitmap.
     * @param height The desired height of the bitmap.
     * @return A bitmap with the desired width and height.
     */
    private Bitmap createBitmap(final int width, final int height) {
        return Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    }

    /**
     * Called when a bitmap is finished being used so that it can be used for another bitmap in the
     * future or recycled. Any bitmaps returned should not be used by the caller again.
     * @param b The bitmap to return to the pool for future usage or recycled. This cannot be null.
     */
    public void reclaimBitmap(@NonNull final Bitmap b) {
        Assert.notNull(b);
        final int poolKey = getPoolKey(b.getWidth(), b.getHeight());
        if (poolKey == 0 || !b.isMutable()) {
            // Unsupported image dimensions or a immutable bitmap.
            b.recycle();
            return;
        }
        synchronized (mPoolLock) {
            SingleSizePool singleSizePool = mPool.get(poolKey);
            if (singleSizePool == null) {
                singleSizePool = new SingleSizePool(mMaxSize);
                mPool.append(poolKey, singleSizePool);
            }
            if (singleSizePool.mNumItems < singleSizePool.mBitmaps.length) {
                singleSizePool.mBitmaps[singleSizePool.mNumItems] = b;
                singleSizePool.mNumItems++;
            } else {
                b.recycle();
            }
        }
    }

    /**
     * @return whether the pool is full for a given width and height.
     */
    public boolean isFull(final int width, final int height) {
        final int poolKey = getPoolKey(width, height);
        synchronized (mPoolLock) {
            final SingleSizePool singleSizePool = mPool.get(poolKey);
            if (singleSizePool != null &&
                    singleSizePool.mNumItems >= singleSizePool.mBitmaps.length) {
                return true;
            }
            return false;
        }
    }
}