SurfaceTexture.java revision dc02e18d154ed6271bbd7bc346de619f2698bd9a
1/*
2 * Copyright (C) 2010 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
17package android.graphics;
18
19import java.lang.ref.WeakReference;
20import android.os.Handler;
21import android.os.Looper;
22import android.os.Message;
23
24/**
25 * Captures frames from an image stream as an OpenGL ES texture.
26 *
27 * <p>The image stream may come from either camera preview or video decode.  A SurfaceTexture
28 * may be used in place of a SurfaceHolder when specifying the output destination of a
29 * {@link android.hardware.Camera} or {@link android.media.MediaPlayer}
30 * object.  Doing so will cause all the frames from the image stream to be sent to the
31 * SurfaceTexture object rather than to the device's display.  When {@link #updateTexImage} is
32 * called, the contents of the texture object specified when the SurfaceTexture was created are
33 * updated to contain the most recent image from the image stream.  This may cause some frames of
34 * the stream to be skipped.
35 *
36 * <p>When sampling from the texture one should first transform the texture coordinates using the
37 * matrix queried via {@link #getTransformMatrix}.  The transform matrix may change each time {@link
38 * #updateTexImage} is called, so it should be re-queried each time the texture image is updated.
39 * This matrix transforms traditional 2D OpenGL ES texture coordinate column vectors of the form (s,
40 * t, 0, 1) where s and t are on the inclusive interval [0, 1] to the proper sampling location in
41 * the streamed texture.  This transform compensates for any properties of the image stream source
42 * that cause it to appear different from a traditional OpenGL ES texture.  For example, sampling
43 * from the bottom left corner of the image can be accomplished by transforming the column vector
44 * (0, 0, 0, 1) using the queried matrix, while sampling from the top right corner of the image can
45 * be done by transforming (1, 1, 0, 1).
46 *
47 * <p>The texture object uses the GL_TEXTURE_EXTERNAL_OES texture target, which is defined by the
48 * OES_EGL_image_external OpenGL ES extension.  This limits how the texture may be used.
49 *
50 * <p>SurfaceTexture objects may be created on any thread.  {@link #updateTexImage} may only be
51 * called on the thread with the OpenGL ES context that contains the texture object.  The
52 * frame-available callback is called on an arbitrary thread, so unless special care is taken {@link
53 * #updateTexImage} should not be called directly from the callback.
54 */
55public class SurfaceTexture {
56
57    private EventHandler mEventHandler;
58    private OnFrameAvailableListener mOnFrameAvailableListener;
59
60    @SuppressWarnings("unused")
61    private int mSurfaceTexture;
62
63    /**
64     * Callback interface for being notified that a new stream frame is available.
65     */
66    public interface OnFrameAvailableListener {
67        void onFrameAvailable(SurfaceTexture surfaceTexture);
68    }
69
70    /**
71     * Exception thrown when a surface couldn't be created or resized
72     */
73    public static class OutOfResourcesException extends Exception {
74        public OutOfResourcesException() {
75        }
76        public OutOfResourcesException(String name) {
77            super(name);
78        }
79    }
80
81    /**
82     * Construct a new SurfaceTexture to stream images to a given OpenGL texture.
83     *
84     * @param texName the OpenGL texture object name (e.g. generated via glGenTextures)
85     */
86    public SurfaceTexture(int texName) {
87        Looper looper;
88        if ((looper = Looper.myLooper()) != null) {
89            mEventHandler = new EventHandler(looper);
90        } else if ((looper = Looper.getMainLooper()) != null) {
91            mEventHandler = new EventHandler(looper);
92        } else {
93            mEventHandler = null;
94        }
95        nativeInit(texName, new WeakReference<SurfaceTexture>(this));
96    }
97
98    /**
99     * Register a callback to be invoked when a new image frame becomes available to the
100     * SurfaceTexture.  Note that this callback may be called on an arbitrary thread, so it is not
101     * safe to call {@link #updateTexImage} without first binding the OpenGL ES context to the
102     * thread invoking the callback.
103     */
104    public void setOnFrameAvailableListener(OnFrameAvailableListener l) {
105        mOnFrameAvailableListener = l;
106    }
107
108    /**
109     * Update the texture image to the most recent frame from the image stream.  This may only be
110     * called while the OpenGL ES context that owns the texture is bound to the thread.  It will
111     * implicitly bind its texture to the GL_TEXTURE_EXTERNAL_OES texture target.
112     */
113    public void updateTexImage() {
114        nativeUpdateTexImage();
115    }
116
117    /**
118     * Retrieve the 4x4 texture coordinate transform matrix associated with the texture image set by
119     * the most recent call to updateTexImage.
120     *
121     * This transform matrix maps 2D homogeneous texture coordinates of the form (s, t, 0, 1) with s
122     * and t in the inclusive range [0, 1] to the texture coordinate that should be used to sample
123     * that location from the texture.  Sampling the texture outside of the range of this transform
124     * is undefined.
125     *
126     * The matrix is stored in column-major order so that it may be passed directly to OpenGL ES via
127     * the glLoadMatrixf or glUniformMatrix4fv functions.
128     *
129     * @param mtx the array into which the 4x4 matrix will be stored.  The array must have exactly
130     *     16 elements.
131     */
132    public void getTransformMatrix(float[] mtx) {
133        // Note we intentionally don't check mtx for null, so this will result in a
134        // NullPointerException. But it's safe because it happens before the call to native.
135        if (mtx.length != 16) {
136            throw new IllegalArgumentException();
137        }
138        nativeGetTransformMatrix(mtx);
139    }
140
141    protected void finalize() throws Throwable {
142        try {
143            nativeFinalize();
144        } finally {
145            super.finalize();
146        }
147    }
148
149    private class EventHandler extends Handler {
150        public EventHandler(Looper looper) {
151            super(looper);
152        }
153
154        @Override
155        public void handleMessage(Message msg) {
156            if (mOnFrameAvailableListener != null) {
157                mOnFrameAvailableListener.onFrameAvailable(SurfaceTexture.this);
158            }
159            return;
160        }
161    }
162
163    private static void postEventFromNative(Object selfRef) {
164        WeakReference weakSelf = (WeakReference)selfRef;
165        SurfaceTexture st = (SurfaceTexture)weakSelf.get();
166        if (st == null) {
167            return;
168        }
169
170        if (st.mEventHandler != null) {
171            Message m = st.mEventHandler.obtainMessage();
172            st.mEventHandler.sendMessage(m);
173        }
174    }
175
176    private native void nativeInit(int texName, Object weakSelf);
177    private native void nativeFinalize();
178    private native void nativeGetTransformMatrix(float[] mtx);
179    private native void nativeUpdateTexImage();
180
181    /*
182     * We use a class initializer to allow the native code to cache some
183     * field offsets.
184     */
185    private static native void nativeClassInit();
186    static { nativeClassInit(); }
187}
188