aboutsummaryrefslogtreecommitdiffstats
path: root/src/org/cyanogenmod/wallpapers/photophase/TextureManager.java
blob: 3c3ad785ab767a46947839e7f438f876dae83612 (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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
/*
 * Copyright (C) 2014 The CyanogenMod 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 org.cyanogenmod.wallpapers.photophase;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.graphics.RectF;
import android.media.ThumbnailUtils;
import android.media.effect.Effect;
import android.media.effect.EffectContext;
import android.opengl.GLES20;
import android.os.Handler;
import android.util.Log;
import android.widget.Toast;

import org.cyanogenmod.wallpapers.photophase.FixedQueue.EmptyQueueException;
import org.cyanogenmod.wallpapers.photophase.preferences.PreferencesProvider.Preferences;
import org.cyanogenmod.wallpapers.photophase.utils.GLESUtil;
import org.cyanogenmod.wallpapers.photophase.utils.Utils;
import org.cyanogenmod.wallpapers.photophase.utils.GLESUtil.GLESTextureInfo;
import org.cyanogenmod.wallpapers.photophase.MediaPictureDiscoverer.OnMediaPictureDiscoveredListener;
import org.cyanogenmod.wallpapers.photophase.effects.Effects;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * A class that manages the acquisition of new textures.
 */
public class TextureManager implements OnMediaPictureDiscoveredListener {

    private static final String TAG = "TextureManager";

    private static final int QUEUE_SIZE = 8;

    final Context mContext;
    final Handler mHandler;
    Effects mEffects;
    final Object mSync;
    final List<TextureRequestor> mPendingRequests;
    final FixedQueue<GLESTextureInfo> mQueue = new FixedQueue<GLESTextureInfo>(QUEUE_SIZE);
    BackgroundPictureLoaderThread mBackgroundTask;
    /*protected*/ final MediaPictureDiscoverer mPictureDiscoverer;

    Rect mScreenDimensions;
    Rect mDimensions;

    final GLESSurfaceDispatcher mDispatcher;

    // The status of the texture manager:
    // 0 - Loading
    // 1 - Loaded
    // 2 - Error
    private byte mStatus;

    /**
     * A private runnable that will run in the GLThread
     */
    class PictureDispatcher implements Runnable {
        File mImage;
        GLESTextureInfo ti = null;
        final Object mWait = new Object();

        /**
         * {@inheritDoc}
         */
        @Override
        public void run() {
            try {
                Effect effect = null;
                synchronized (mEffects) {
                    effect = mEffects.getNextEffect();
                }

                boolean enqueue = false;
                synchronized (mSync) {
                    enqueue = mPendingRequests.size() == 0;
                }

                // Load and bind to the GLES context. The effect is applied when the image
                // is associated to the destination target (only if aspect ratio will be applied)
                if (!Preferences.General.isFixAspectRatio()) {
                    ti = GLESUtil.loadTexture(
                            mImage, mDimensions, effect, mDimensions, false);
                } else {
                    ti = GLESUtil.loadTexture(mImage, mDimensions, null, null, false);
                    ti.effect = effect;
                }

                synchronized (mSync) {
                    // Notify the new images to all pending frames
                    if (!enqueue) {
                        // Invalid textures are also reported, so requestor can handle it
                        TextureRequestor requestor = mPendingRequests.remove(0);
                        fixAspectRatio(requestor, ti);
                        requestor.setTextureHandle(ti);

                        // Clean up memory
                        if (ti.bitmap != null) {
                            ti.bitmap.recycle();
                            ti.bitmap = null;
                        }

                    } else {
                        // Add to the queue (only valid textures)
                        if (ti.handle > 0) {
                            mQueue.insert(ti);
                        }
                    }
                }

            } catch (Throwable e) {
                Log.e(TAG, "Something was wrong loading the texture: " +
                        mImage.getAbsolutePath(), e);

            } finally {
                // Notify that we have a new image
                synchronized (mWait) {
                    mWait.notify();
                }
            }
        }
    }

    /**
     * Constructor of <code>TextureManager</code>
     *
     * @param ctx The current context
     * @param effectCtx The current effect context
     * @param dispatcher The GLES dispatcher
     * @param requestors The number of requestors
     * @param screenDimensions The screen dimensions
     */
    public TextureManager(final Context ctx, final Handler handler, final EffectContext effectCtx,
                        GLESSurfaceDispatcher dispatcher, int requestors, Rect screenDimensions) {
        super();
        mContext = ctx;
        mHandler = handler;
        mEffects = new Effects(effectCtx);
        mDispatcher = dispatcher;
        mScreenDimensions = screenDimensions;
        mDimensions = screenDimensions; // For now, use the screen dimensions as the preferred dimensions for bitmaps
        mSync = new Object();
        mPendingRequests = new ArrayList<TextureRequestor>(requestors);
        mPictureDiscoverer = new MediaPictureDiscoverer(mContext, this);

        // Run the media discovery thread
        mBackgroundTask = new BackgroundPictureLoaderThread();
        mBackgroundTask.mTaskPaused = false;
        reloadMedia(false);
    }

    /**
     * Method that update the effect context if the EGL context change
     *
     * @param effectCtx The new effect context
     */
    protected void updateEffectContext(final EffectContext effectCtx) {
        synchronized (mEffects) {
            if (mEffects != null) {
                mEffects.release();
                mEffects = null;
            }
            mEffects = new Effects(effectCtx);
        }
        emptyTextureQueue(true);
    }

    /**
     * Method that allow to change the preferred dimensions of the bitmaps loaded
     *
     * @param dimensions The new dimensions
     */
    public void setDimensions(Rect dimensions) {
        mDimensions = dimensions;
    }

    /**
     * Method that allow to change the screen dimensions
     *
     * @param dimensions The new dimensions
     */
    public void setScreenDimesions(Rect dimensions) {
        mScreenDimensions = dimensions;
    }

    /**
     * Method that returns if the texture manager is paused
     *
     * @return boolean whether the texture manager is paused
     */
    public boolean isPaused() {
        return mBackgroundTask != null && mBackgroundTask.mTaskPaused;
    }

    /**
     * Method that pauses the internal threads
     *
     * @param pause If the thread is paused (true) or resumed (false)
     */
    public synchronized void setPause(boolean pause) {
        synchronized (mBackgroundTask.mLoadSync) {
            mBackgroundTask.mTaskPaused = pause;
            if (!mBackgroundTask.mTaskPaused) {
                mBackgroundTask.mLoadSync.notify();
            }
        }
    }

    /**
     * Method that reload the references of media pictures
     *
     * @param userRequest If the request was generated by the user
     */
    void reloadMedia(final boolean userRequest) {
        Log.d(TAG, "Reload media picture data");
        // Discovery new media
        // GLThread doesn't run in the UI thread and AsyncThread can't create a
        // valid handler in ICS (it's fixed in JB+) so we force to run the async
        // thread in a valid UI thread
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                mPictureDiscoverer.discover(userRequest);
            }
        });
    }

    /**
     * Method that request a new picture for the {@link TextureRequestor}
     *
     * @param requestor The requestor of the texture
     */
    public void request(TextureRequestor requestor) {
        synchronized (mSync) {
            try {
                GLESTextureInfo ti = mQueue.remove();
                fixAspectRatio(requestor, ti);
                requestor.setTextureHandle(ti);

                // Clean up memory
                if (ti.bitmap != null) {
                    ti.bitmap.recycle();
                    ti.bitmap = null;
                }

            } catch (EmptyQueueException eqex) {
                // Add to queue of pending request to be notified when
                // we have a new bitmap in the queue
                mPendingRequests.add(requestor);
            }
        }

        synchronized (mBackgroundTask.mLoadSync) {
            mBackgroundTask.mLoadSync.notify();
        }
    }

    /**
     * Method that removes all the textures from the queue
     *
     * @param reload Forces a reload of the queue
     */
    public void emptyTextureQueue(boolean reload) {
        synchronized (mSync) {
            // Recycle the textures
            try {
                List<GLESTextureInfo> all = mQueue.removeAll();
                for (GLESTextureInfo info : all) {
                    if (GLES20.glIsTexture(info.handle)) {
                        int[] textures = new int[] {info.handle};
                        if (GLESUtil.DEBUG_GL_MEMOBJS) {
                            Log.d(GLESUtil.DEBUG_GL_MEMOBJS_DEL_TAG, "glDeleteTextures: ["
                                    + info.handle + "]");
                        }
                        GLES20.glDeleteTextures(1, textures, 0);
                        GLESUtil.glesCheckError("glDeleteTextures");
                    }
                    // Return the bitmap
                    info.bitmap.recycle();
                    info.bitmap = null;
                }
            } catch (EmptyQueueException eqex) {
                // Ignore
            }

            // Remove all pictures in the queue
            try {
                mQueue.removeAll();
            } catch (EmptyQueueException ex) {
                // Ignore
            }

            // Reload the queue
            if (reload) {
                synchronized (mBackgroundTask.mLoadSync) {
                    mBackgroundTask.resetAvailableImages();
                    mBackgroundTask.mLoadSync.notify();
                }
            }
        }
    }

    /**
     * Method that cancels a request did it previously.
     *
     * @param requestor The requestor of the texture
     */
    public void cancelRequest(TextureRequestor requestor) {
        synchronized (mSync) {
            if (mPendingRequests.contains(requestor)) {
                mPendingRequests.remove(requestor);
            }
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void onStartMediaDiscovered(boolean userRequest) {
        // No images but thread should start here to received partial data
        this.mStatus = 0; // Loading
        if (mBackgroundTask != null) {
            mBackgroundTask.setAvailableImages(new File[]{});
            if (!mBackgroundTask.mRun) {
                mBackgroundTask.start();
            } else {
                synchronized (mBackgroundTask.mLoadSync) {
                    mBackgroundTask.mLoadSync.notify();
                }
            }
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void onPartialMediaDiscovered(File[] images, boolean userRequest) {
        if (mBackgroundTask != null) {
            mBackgroundTask.setPartialAvailableImages(images);
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    @SuppressWarnings("boxing")
    public void onEndMediaDiscovered(File[] images, boolean userRequest) {
        // Now we have the paths of the images to use. Notify to the thread to
        // load pictures in background
        if (mBackgroundTask != null) {
            mBackgroundTask.setAvailableImages(images);
            synchronized (mBackgroundTask.mLoadSync) {
                mBackgroundTask.mLoadSync.notify();
            }
            this.mStatus = 1; // Loaded

            // Audit
            int found = images == null ? 0 : images.length;
            Log.d(TAG, "Media picture data reloaded: " + found + " images found.");
            if (userRequest) {
                CharSequence msg =
                        String.format(mContext.getResources().getQuantityText(
                                R.plurals.msg_media_reload_complete, found).toString(), found);
                Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
            }
        } else {
            this.mStatus = 2; // Error
        }
    }

    /**
     * Method that destroy the references of this class
     */
    public void recycle() {
        // Destroy the media discovery task
        mPictureDiscoverer.recycle();
        mEffects.release();

        // Destroy the background task
        if (mBackgroundTask != null) {
            mBackgroundTask.mRun = false;
            try {
                synchronized (mBackgroundTask.mLoadSync) {
                    mBackgroundTask.interrupt();
                }
            } catch (Exception e) {
                // Ignore
            }
        }
        mBackgroundTask = null;
    }


    /**
     * Returns the status of the texture manager
     *
     * @return byte The status
     */
    public byte getStatus() {
        return mStatus;
    }

    /**
     * Returns if the texture manager is empty
     *
     * @return boolean If the texture manager is empty
     */
    public boolean isEmpty() {
        return mBackgroundTask != null && mBackgroundTask.mEmpty;
    }

    /**
     * Method that fix the aspect ratio of a image to fit the destination target
     *
     * @param request The requestor target
     * @param ti The original texture information
     * @param effect The effect to apply to the destination picture
     */
    void fixAspectRatio(TextureRequestor requestor, GLESTextureInfo ti) {
        // Check if we have to apply any correction to the image
        if (Preferences.General.isFixAspectRatio()) {
            // Transform requestor dimensions to screen dimensions
            RectF dimens = requestor.getRequestorDimensions();
            Rect pixels = new Rect(
                                0,
                                0,
                                (int)(mScreenDimensions.width() * dimens.width() / 2),
                                (int)(mScreenDimensions.height() * dimens.height() / 2));

            // Create a thumbnail of the image
            Bitmap thumb = ThumbnailUtils.extractThumbnail(
                                    ti.bitmap,
                                    pixels.width(),
                                    pixels.height(),
                                    ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
            GLESTextureInfo dst = GLESUtil.loadTexture(thumb, ti.effect, pixels);

            // Destroy references
            int[] textures = new int[]{ti.handle};
            if (GLESUtil.DEBUG_GL_MEMOBJS) {
                Log.d(GLESUtil.DEBUG_GL_MEMOBJS_DEL_TAG, "glDeleteTextures: ["
                        + ti.handle + "]");
            }
            GLES20.glDeleteTextures(1, textures, 0);
            GLESUtil.glesCheckError("glDeleteTextures");
            if (ti.bitmap != null) {
                ti.bitmap.recycle();
                ti.bitmap = null;
            }

            // Swap references
            ti.bitmap = dst.bitmap;
            ti.handle = dst.handle;
            ti.effect = null;
        }
    }

    /**
     * An internal thread to load pictures in background
     */
    private class BackgroundPictureLoaderThread extends Thread {

        final Object mLoadSync = new Object();
        boolean mRun;
        boolean mTaskPaused;

        boolean mEmpty;
        private final List<File> mNewImages;
        private final List<File> mUsedImages;

        /**
         * Constructor of <code>BackgroundPictureLoaderThread</code>.
         */
        public BackgroundPictureLoaderThread() {
            super();
            mNewImages = new ArrayList<File>();
            mUsedImages = new ArrayList<File>();
        }

        /**
         * Method that sets the current available images.
         *
         * @param images The current images
         */
        public void setAvailableImages(File[] images) {
            synchronized (mLoadSync) {
                mNewImages.clear();
                mNewImages.addAll(Arrays.asList(images));

                // Retain used images
                int count = mUsedImages.size() - 1;
                for (int i = count; i >= 0; i--) {
                    File image = mUsedImages.get(i);
                    if (!mNewImages.contains(image)) {
                        mUsedImages.remove(image);
                    } else {
                        mNewImages.remove(image);
                    }
                }

                mEmpty = images.length == 0;
            }
        }

        /**
         * Method that adds some available images.
         *
         * @param images The current images
         */
        public void setPartialAvailableImages(File[] images) {
            synchronized (mLoadSync) {
                mNewImages.addAll(Arrays.asList(images));
                mEmpty = images.length == 0;
            }
        }

        /**
         * Method that reset the current available images queue.
         */
        public void resetAvailableImages() {
            synchronized (mLoadSync) {
                mNewImages.addAll(mUsedImages);
                mUsedImages.clear();
            }
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public void run() {
            mRun = true;
            while (mRun) {
                // Check if we need to load more images
                while (!mTaskPaused && TextureManager.this.mQueue.items() < TextureManager.this.mQueue.size()) {
                    File image = null;
                    synchronized (mLoadSync) {
                        // Swap arrays if needed
                        if (mNewImages.size() == 0) {
                            mNewImages.addAll(mUsedImages);
                            mUsedImages.clear();
                        }
                        if (mNewImages.size() == 0) {
                            if (!mEmpty) {
                                reloadMedia(false);
                            }
                            break;
                        }

                        // Extract a random image
                        int low = 0;
                        int high = mNewImages.size() - 1;
                        image = mNewImages.remove(Utils.getNextRandom(low, high));
                    }

                    // Run commands in the GLThread
                    if (!mRun) break;
                    PictureDispatcher pd = new PictureDispatcher();
                    pd.mImage = image;
                    mDispatcher.dispatch(pd);

                    // Wait until the texture is loaded
                    try {
                        synchronized (pd.mWait) {
                            pd.mWait.wait();
                        }
                    } catch (Exception e) {
                        // Ignore
                    }

                    // Add to used images
                    mUsedImages.add(image);
                }

                // Wait for new request
                synchronized (mLoadSync) {
                    try {
                        mLoadSync.wait();
                    } catch (Exception e) {
                        // Ignore
                    }
                }
            }
        }

    }
}