summaryrefslogtreecommitdiffstats
path: root/src/com/android/camera/CameraScreenNail.java
blob: 993a7d336539754166c57571183aac162d5edb60 (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
/*
 * Copyright (C) 2012 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.camera;

import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.SurfaceTexture;
import android.opengl.Matrix;
import android.util.Log;

import com.android.gallery3d.common.ApiHelper;
import com.android.gallery3d.glrenderer.GLCanvas;
import com.android.gallery3d.glrenderer.RawTexture;
import com.android.gallery3d.ui.SurfaceTextureScreenNail;

/*
 * This is a ScreenNail which can display camera's preview.
 */
@TargetApi(ApiHelper.VERSION_CODES.HONEYCOMB)
public class CameraScreenNail extends SurfaceTextureScreenNail {
    private static final String TAG = "CAM_ScreenNail";
    private static final int ANIM_NONE = 0;
    // Capture animation is about to start.
    private static final int ANIM_CAPTURE_START = 1;
    // Capture animation is running.
    private static final int ANIM_CAPTURE_RUNNING = 2;
    // Switch camera animation needs to copy texture.
    private static final int ANIM_SWITCH_COPY_TEXTURE = 3;
    // Switch camera animation shows the initial feedback by darkening the
    // preview.
    private static final int ANIM_SWITCH_DARK_PREVIEW = 4;
    // Switch camera animation is waiting for the first frame.
    private static final int ANIM_SWITCH_WAITING_FIRST_FRAME = 5;
    // Switch camera animation is about to start.
    private static final int ANIM_SWITCH_START = 6;
    // Switch camera animation is running.
    private static final int ANIM_SWITCH_RUNNING = 7;

    private boolean mVisible;
    // True if first onFrameAvailable has been called. If screen nail is drawn
    // too early, it will be all white.
    private boolean mFirstFrameArrived;
    private Listener mListener;
    private final float[] mTextureTransformMatrix = new float[16];

    // Animation.
    private CaptureAnimManager mCaptureAnimManager;
    private SwitchAnimManager mSwitchAnimManager = new SwitchAnimManager();
    private int mAnimState = ANIM_NONE;
    private RawTexture mAnimTexture;
    // Some methods are called by GL thread and some are called by main thread.
    // This protects mAnimState, mVisible, and surface texture. This also makes
    // sure some code are atomic. For example, requestRender and setting
    // mAnimState.
    private Object mLock = new Object();

    private OnFrameDrawnListener mOneTimeFrameDrawnListener;
    private int mRenderWidth;
    private int mRenderHeight;
    // This represents the scaled, uncropped size of the texture
    // Needed for FaceView
    private int mUncroppedRenderWidth;
    private int mUncroppedRenderHeight;
    private float mScaleX = 1f, mScaleY = 1f;
    private boolean mFullScreen;
    private boolean mEnableAspectRatioClamping = false;
    private boolean mAcquireTexture = false;
    private final DrawClient mDefaultDraw = new DrawClient() {
        @Override
        public void onDraw(GLCanvas canvas, int x, int y, int width, int height) {
            CameraScreenNail.super.draw(canvas, x, y, width, height);
        }

        @Override
        public boolean requiresSurfaceTexture() {
            return true;
        }

        @Override
        public RawTexture copyToTexture(GLCanvas c, RawTexture texture, int w, int h) {
            // We shouldn't be here since requireSurfaceTexture() returns true.
            return null;
        }
    };
    private DrawClient mDraw = mDefaultDraw;
    private float mAlpha = 1f;
    private Runnable mOnFrameDrawnListener;

    public interface Listener {
        void requestRender();
        // Preview has been copied to a texture.
        void onPreviewTextureCopied();

        void onCaptureTextureCopied();
    }

    public interface OnFrameDrawnListener {
        void onFrameDrawn(CameraScreenNail c);
    }

    public interface DrawClient {
        void onDraw(GLCanvas canvas, int x, int y, int width, int height);

        boolean requiresSurfaceTexture();
        // The client should implement this if requiresSurfaceTexture() is false;
        RawTexture copyToTexture(GLCanvas c, RawTexture texture, int width, int height);
    }

    public CameraScreenNail(Listener listener, Context ctx) {
        mListener = listener;
        mCaptureAnimManager = new CaptureAnimManager(ctx);
    }

    public void setFullScreen(boolean full) {
        synchronized (mLock) {
            mFullScreen = full;
        }
    }

    /**
     * returns the uncropped, but scaled, width of the rendered texture
     */
    public int getUncroppedRenderWidth() {
        return mUncroppedRenderWidth;
    }

    /**
     * returns the uncropped, but scaled, width of the rendered texture
     */
    public int getUncroppedRenderHeight() {
        return mUncroppedRenderHeight;
    }

    @Override
    public int getWidth() {
        return mEnableAspectRatioClamping ? mRenderWidth : getTextureWidth();
    }

    @Override
    public int getHeight() {
        return mEnableAspectRatioClamping ? mRenderHeight : getTextureHeight();
    }

    private int getTextureWidth() {
        return super.getWidth();
    }

    private int getTextureHeight() {
        return super.getHeight();
    }

    @Override
    public void setSize(int w, int h) {
        super.setSize(w,  h);
        mEnableAspectRatioClamping = false;
        if (mRenderWidth == 0) {
            mRenderWidth = w;
            mRenderHeight = h;
        }
        updateRenderSize();
    }

    /**
     * Tells the ScreenNail to override the default aspect ratio scaling
     * and instead perform custom scaling to basically do a centerCrop instead
     * of the default centerInside
     *
     * Note that calls to setSize will disable this
     */
    public void enableAspectRatioClamping() {
        mEnableAspectRatioClamping = true;
        updateRenderSize();
    }

    private void setPreviewLayoutSize(int w, int h) {
        Log.i(TAG, "preview layout size: "+w+"/"+h);
        mRenderWidth = w;
        mRenderHeight = h;
        updateRenderSize();
    }

    private void updateRenderSize() {
        if (!mEnableAspectRatioClamping) {
            mScaleX = mScaleY = 1f;
            mUncroppedRenderWidth = getTextureWidth();
            mUncroppedRenderHeight = getTextureHeight();
            Log.i(TAG, "aspect ratio clamping disabled");
            return;
        }

        float aspectRatio;
        if (getTextureWidth() > getTextureHeight()) {
            aspectRatio = (float) getTextureWidth() / (float) getTextureHeight();
        } else {
            aspectRatio = (float) getTextureHeight() / (float) getTextureWidth();
        }
        float scaledTextureWidth, scaledTextureHeight;
        if (mRenderWidth > mRenderHeight) {
            scaledTextureWidth = Math.max(mRenderWidth,
                    (int) (mRenderHeight * aspectRatio));
            scaledTextureHeight = Math.max(mRenderHeight,
                    (int)(mRenderWidth / aspectRatio));
        } else {
            scaledTextureWidth = Math.max(mRenderWidth,
                    (int) (mRenderHeight / aspectRatio));
            scaledTextureHeight = Math.max(mRenderHeight,
                    (int) (mRenderWidth * aspectRatio));
        }
        mScaleX = mRenderWidth / scaledTextureWidth;
        mScaleY = mRenderHeight / scaledTextureHeight;
        mUncroppedRenderWidth = Math.round(scaledTextureWidth);
        mUncroppedRenderHeight = Math.round(scaledTextureHeight);
        Log.i(TAG, "aspect ratio clamping enabled, surfaceTexture scale: " + mScaleX + ", " + mScaleY);
    }

    public void acquireSurfaceTexture() {
        synchronized (mLock) {
            mFirstFrameArrived = false;
            mAnimTexture = new RawTexture(getTextureWidth(), getTextureHeight(), true);
            mAcquireTexture = true;
        }
        mListener.requestRender();
    }

    @Override
    public void releaseSurfaceTexture() {
        synchronized (mLock) {
            if (mAcquireTexture) {
                mAcquireTexture = false;
                mLock.notifyAll();
            } else {
                if (super.getSurfaceTexture() != null) {
                    super.releaseSurfaceTexture();
                }
                mAnimState = ANIM_NONE; // stop the animation
            }
        }
    }

    public void copyTexture() {
        synchronized (mLock) {
            mListener.requestRender();
            mAnimState = ANIM_SWITCH_COPY_TEXTURE;
        }
    }

    public void animateSwitchCamera() {
        Log.v(TAG, "animateSwitchCamera");
        synchronized (mLock) {
            if (mAnimState == ANIM_SWITCH_DARK_PREVIEW) {
                // Do not request render here because camera has been just
                // started. We do not want to draw black frames.
                mAnimState = ANIM_SWITCH_WAITING_FIRST_FRAME;
            }
        }
    }

    public void animateCapture(int displayRotation) {
        synchronized (mLock) {
            mCaptureAnimManager.setOrientation(displayRotation);
            mCaptureAnimManager.animateFlashAndSlide();
            mListener.requestRender();
            mAnimState = ANIM_CAPTURE_START;
        }
    }

    public RawTexture getAnimationTexture() {
        return mAnimTexture;
    }

    public void animateFlash(int displayRotation) {
        synchronized (mLock) {
            mCaptureAnimManager.setOrientation(displayRotation);
            mCaptureAnimManager.animateFlash();
            mListener.requestRender();
            mAnimState = ANIM_CAPTURE_START;
        }
    }

    public void animateSlide() {
        synchronized (mLock) {
            mCaptureAnimManager.animateSlide();
            mListener.requestRender();
        }
    }

    private void callbackIfNeeded() {
        if (mOneTimeFrameDrawnListener != null) {
            mOneTimeFrameDrawnListener.onFrameDrawn(this);
            mOneTimeFrameDrawnListener = null;
        }
    }

    @Override
    protected void updateTransformMatrix(float[] matrix) {
        super.updateTransformMatrix(matrix);
        Matrix.translateM(matrix, 0, .5f, .5f, 0);
        Matrix.scaleM(matrix, 0, mScaleX, mScaleY, 1f);
        Matrix.translateM(matrix, 0, -.5f, -.5f, 0);
    }

    public void directDraw(GLCanvas canvas, int x, int y, int width, int height) {
        DrawClient draw;
        synchronized (mLock) {
            draw = mDraw;
        }
        draw.onDraw(canvas, x, y, width, height);
    }

    public void setDraw(DrawClient draw) {
        synchronized (mLock) {
            if (draw == null) {
                mDraw = mDefaultDraw;
            } else {
                mDraw = draw;
            }
        }
        mListener.requestRender();
    }

    @Override
    public void draw(GLCanvas canvas, int x, int y, int width, int height) {
        synchronized (mLock) {
            allocateTextureIfRequested(canvas);
            if (!mVisible) mVisible = true;
            SurfaceTexture surfaceTexture = getSurfaceTexture();
            if (mDraw.requiresSurfaceTexture() && (surfaceTexture == null || !mFirstFrameArrived)) {
                return;
            }
            if (mOnFrameDrawnListener != null) {
                mOnFrameDrawnListener.run();
                mOnFrameDrawnListener = null;
            }
            float oldAlpha = canvas.getAlpha();
            canvas.setAlpha(mAlpha);

            switch (mAnimState) {
                case ANIM_NONE:
                    directDraw(canvas, x, y, width, height);
                    break;
                case ANIM_SWITCH_COPY_TEXTURE:
                    copyPreviewTexture(canvas);
                    mSwitchAnimManager.setReviewDrawingSize(width, height);
                    mListener.onPreviewTextureCopied();
                    mAnimState = ANIM_SWITCH_DARK_PREVIEW;
                    // The texture is ready. Fall through to draw darkened
                    // preview.
                case ANIM_SWITCH_DARK_PREVIEW:
                case ANIM_SWITCH_WAITING_FIRST_FRAME:
                    // Consume the frame. If the buffers are full,
                    // onFrameAvailable will not be called. Animation state
                    // relies on onFrameAvailable.
                    surfaceTexture.updateTexImage();
                    mSwitchAnimManager.drawDarkPreview(canvas, x, y, width,
                            height, mAnimTexture);
                    break;
                case ANIM_SWITCH_START:
                    mSwitchAnimManager.startAnimation();
                    mAnimState = ANIM_SWITCH_RUNNING;
                    break;
                case ANIM_CAPTURE_START:
                    copyPreviewTexture(canvas);
                    mListener.onCaptureTextureCopied();
                    mCaptureAnimManager.startAnimation();
                    mAnimState = ANIM_CAPTURE_RUNNING;
                    break;
            }

            if (mAnimState == ANIM_CAPTURE_RUNNING || mAnimState == ANIM_SWITCH_RUNNING) {
                boolean drawn;
                if (mAnimState == ANIM_CAPTURE_RUNNING) {
                    if (!mFullScreen) {
                        // Skip the animation if no longer in full screen mode
                        drawn = false;
                    } else {
                        drawn = mCaptureAnimManager.drawAnimation(canvas, this, mAnimTexture,
                                x, y, width, height);
                    }
                } else {
                    drawn = mSwitchAnimManager.drawAnimation(canvas, x, y,
                            width, height, this, mAnimTexture);
                }
                if (drawn) {
                    mListener.requestRender();
                } else {
                    // Continue to the normal draw procedure if the animation is
                    // not drawn.
                    mAnimState = ANIM_NONE;
                    directDraw(canvas, x, y, width, height);
                }
            }
            canvas.setAlpha(oldAlpha);
            callbackIfNeeded();
        } // mLock
    }

    private void copyPreviewTexture(GLCanvas canvas) {
        if (!mDraw.requiresSurfaceTexture()) {
            mAnimTexture =  mDraw.copyToTexture(
                    canvas, mAnimTexture, getTextureWidth(), getTextureHeight());
        } else {
            int width = mAnimTexture.getWidth();
            int height = mAnimTexture.getHeight();
            canvas.beginRenderTarget(mAnimTexture);
            // Flip preview texture vertically. OpenGL uses bottom left point
            // as the origin (0, 0).
            canvas.translate(0, height);
            canvas.scale(1, -1, 1);
            getSurfaceTexture().getTransformMatrix(mTextureTransformMatrix);
            updateTransformMatrix(mTextureTransformMatrix);
            canvas.drawTexture(mExtTexture, mTextureTransformMatrix, 0, 0, width, height);
            canvas.endRenderTarget();
        }
    }

    @Override
    public void noDraw() {
        synchronized (mLock) {
            mVisible = false;
        }
    }

    @Override
    public void recycle() {
        synchronized (mLock) {
            mVisible = false;
        }
    }

    @Override
    public void onFrameAvailable(SurfaceTexture surfaceTexture) {
        synchronized (mLock) {
            if (getSurfaceTexture() != surfaceTexture) {
                return;
            }
            mFirstFrameArrived = true;
            if (mVisible) {
                if (mAnimState == ANIM_SWITCH_WAITING_FIRST_FRAME) {
                    mAnimState = ANIM_SWITCH_START;
                }
                // We need to ask for re-render if the SurfaceTexture receives a new
                // frame.
                mListener.requestRender();
            }
        }
    }

    // We need to keep track of the size of preview frame on the screen because
    // it's needed when we do switch-camera animation. See comments in
    // SwitchAnimManager.java. This is based on the natural orientation, not the
    // view system orientation.
    public void setPreviewFrameLayoutSize(int width, int height) {
        synchronized (mLock) {
            mSwitchAnimManager.setPreviewFrameLayoutSize(width, height);
            setPreviewLayoutSize(width, height);
        }
    }

    public void setOneTimeOnFrameDrawnListener(OnFrameDrawnListener l) {
        synchronized (mLock) {
            mFirstFrameArrived = false;
            mOneTimeFrameDrawnListener = l;
        }
    }

    @Override
    public SurfaceTexture getSurfaceTexture() {
        synchronized (mLock) {
            SurfaceTexture surfaceTexture = super.getSurfaceTexture();
            if (surfaceTexture == null && mAcquireTexture) {
                try {
                    mLock.wait();
                    surfaceTexture = super.getSurfaceTexture();
                } catch (InterruptedException e) {
                    Log.w(TAG, "unexpected interruption");
                }
            }
            return surfaceTexture;
        }
    }

    private void allocateTextureIfRequested(GLCanvas canvas) {
        synchronized (mLock) {
            if (mAcquireTexture) {
                super.acquireSurfaceTexture(canvas);
                mAcquireTexture = false;
                mLock.notifyAll();
            }
        }
    }

    public void setOnFrameDrawnOneShot(Runnable run) {
        synchronized (mLock) {
            mOnFrameDrawnListener = run;
        }
    }

    public float getAlpha() {
        synchronized (mLock) {
            return mAlpha;
        }
    }

    public void setAlpha(float alpha) {
        synchronized (mLock) {
            mAlpha = alpha;
            mListener.requestRender();
        }
    }
}