SurfaceTextureTarget.java revision 2f708ce9cc7fc2e4d498bcc20a095bdf8e9c803d
1/*
2 * Copyright (C) 2011 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
18package android.filterpacks.videosrc;
19
20import android.filterfw.core.Filter;
21import android.filterfw.core.FilterContext;
22import android.filterfw.core.FilterSurfaceView;
23import android.filterfw.core.Frame;
24import android.filterfw.core.FrameFormat;
25import android.filterfw.core.GenerateFieldPort;
26import android.filterfw.core.GenerateFinalPort;
27import android.filterfw.core.GLEnvironment;
28import android.filterfw.core.GLFrame;
29import android.filterfw.core.KeyValueMap;
30import android.filterfw.core.MutableFrameFormat;
31import android.filterfw.core.NativeProgram;
32import android.filterfw.core.NativeFrame;
33import android.filterfw.core.Program;
34import android.filterfw.core.ShaderProgram;
35import android.filterfw.format.ImageFormat;
36
37import android.filterfw.geometry.Quad;
38import android.filterfw.geometry.Point;
39
40import android.view.Surface;
41import android.view.SurfaceHolder;
42import android.view.SurfaceView;
43
44import android.graphics.Rect;
45import android.graphics.SurfaceTexture;
46
47import android.util.Log;
48
49/**
50 * @hide
51 */
52public class SurfaceTextureTarget extends Filter {
53
54    private final int RENDERMODE_STRETCH   = 0;
55    private final int RENDERMODE_FIT       = 1;
56    private final int RENDERMODE_FILL_CROP = 2;
57    private final int RENDERMODE_CUSTOMIZE = 3;
58
59    /** Required. Sets the destination surfaceTexture.
60     */
61    @GenerateFinalPort(name = "surfaceTexture")
62    private SurfaceTexture mSurfaceTexture;
63
64    /** Required. Sets the width of the output surfaceTexture images */
65    @GenerateFinalPort(name = "width")
66    private int mScreenWidth;
67
68    /** Required. Sets the height of the output surfaceTexture images */
69    @GenerateFinalPort(name = "height")
70    private int mScreenHeight;
71
72
73    /** Optional. Control how the incoming frames are rendered onto the
74     * output. Default is FIT.
75     * RENDERMODE_STRETCH: Just fill the output surfaceView.
76     * RENDERMODE_FIT: Keep aspect ratio and fit without cropping. May
77     * have black bars.
78     * RENDERMODE_FILL_CROP: Keep aspect ratio and fit without black
79     * bars. May crop.
80     */
81    @GenerateFieldPort(name = "renderMode", hasDefault = true)
82    private String mRenderModeString;
83
84    @GenerateFieldPort(name = "sourceQuad", hasDefault = true)
85    private Quad mSourceQuad = new Quad(new Point(0.0f, 1.0f),
86                                        new Point(1.0f, 1.0f),
87                                        new Point(0.0f, 0.0f),
88                                        new Point(1.0f, 0.0f));
89
90    @GenerateFieldPort(name = "targetQuad", hasDefault = true)
91    private Quad mTargetQuad = new Quad(new Point(0.0f, 0.0f),
92                                        new Point(1.0f, 0.0f),
93                                        new Point(0.0f, 1.0f),
94                                        new Point(1.0f, 1.0f));
95
96    private int mSurfaceId;
97
98    private ShaderProgram mProgram;
99    private GLFrame mScreen;
100    private int mRenderMode = RENDERMODE_FIT;
101    private float mAspectRatio = 1.f;
102
103    private boolean mLogVerbose;
104    private static final String TAG = "SurfaceTextureTarget";
105
106    public SurfaceTextureTarget(String name) {
107        super(name);
108
109        mLogVerbose = Log.isLoggable(TAG, Log.VERBOSE);
110    }
111
112    @Override
113    public void setupPorts() {
114        // Make sure we have a SurfaceView
115        if (mSurfaceTexture == null) {
116            throw new RuntimeException("Null SurfaceTexture passed to SurfaceTextureTarget");
117        }
118
119        // Add input port - will accept anything that's 4-channel.
120        addMaskedInputPort("frame", ImageFormat.create(ImageFormat.COLORSPACE_RGBA));
121    }
122
123    public void updateRenderMode() {
124        if (mRenderModeString != null) {
125            if (mRenderModeString.equals("stretch")) {
126                mRenderMode = RENDERMODE_STRETCH;
127            } else if (mRenderModeString.equals("fit")) {
128                mRenderMode = RENDERMODE_FIT;
129            } else if (mRenderModeString.equals("fill_crop")) {
130                mRenderMode = RENDERMODE_FILL_CROP;
131            } else if (mRenderModeString.equals("customize")) {
132                mRenderMode = RENDERMODE_CUSTOMIZE;
133            } else {
134                throw new RuntimeException("Unknown render mode '" + mRenderModeString + "'!");
135            }
136        }
137        updateTargetRect();
138    }
139
140    @Override
141    public void prepare(FilterContext context) {
142        // Create identity shader to render, and make sure to render upside-down, as textures
143        // are stored internally bottom-to-top.
144        mProgram = ShaderProgram.createIdentity(context);
145        mProgram.setSourceRect(0, 1, 1, -1);
146        mProgram.setClearColor(0.0f, 0.0f, 0.0f);
147
148        updateRenderMode();
149
150        // Create a frame representing the screen
151        MutableFrameFormat screenFormat = new MutableFrameFormat(FrameFormat.TYPE_BYTE,
152                                                                 FrameFormat.TARGET_GPU);
153        screenFormat.setBytesPerSample(4);
154        screenFormat.setDimensions(mScreenWidth, mScreenHeight);
155        mScreen = (GLFrame)context.getFrameManager().newBoundFrame(screenFormat,
156                                                                   GLFrame.EXISTING_FBO_BINDING,
157                                                                   0);
158    }
159
160    @Override
161    public void open(FilterContext context) {
162        // Set up SurfaceTexture internals
163        mSurfaceId = context.getGLEnvironment().registerSurfaceTexture(
164            mSurfaceTexture, mScreenWidth, mScreenHeight);
165        if (mSurfaceId <= 0) {
166            throw new RuntimeException("Could not register SurfaceTexture: " + mSurfaceTexture);
167        }
168    }
169
170
171    @Override
172    public void close(FilterContext context) {
173        if (mSurfaceId > 0) {
174            context.getGLEnvironment().unregisterSurfaceId(mSurfaceId);
175        }
176    }
177
178
179    @Override
180    public void process(FilterContext context) {
181        if (mLogVerbose) Log.v(TAG, "Starting frame processing");
182
183        GLEnvironment glEnv = context.getGLEnvironment();
184
185        // Get input frame
186        Frame input = pullInput("frame");
187        boolean createdFrame = false;
188
189        float currentAspectRatio =
190          (float)input.getFormat().getWidth() / input.getFormat().getHeight();
191        if (currentAspectRatio != mAspectRatio) {
192            if (mLogVerbose) Log.v(TAG, "New aspect ratio: " + currentAspectRatio +
193                ", previously: " + mAspectRatio);
194            mAspectRatio = currentAspectRatio;
195            updateTargetRect();
196        }
197
198        // See if we need to copy to GPU
199        Frame gpuFrame = null;
200        if (mLogVerbose) Log.v("SurfaceTextureTarget", "Got input format: " + input.getFormat());
201
202        int target = input.getFormat().getTarget();
203        if (target != FrameFormat.TARGET_GPU) {
204            gpuFrame = context.getFrameManager().duplicateFrameToTarget(input,
205                                                                        FrameFormat.TARGET_GPU);
206            createdFrame = true;
207        } else {
208            gpuFrame = input;
209        }
210
211        // Activate our surface
212        glEnv.activateSurfaceWithId(mSurfaceId);
213
214        // Process
215        mProgram.process(gpuFrame, mScreen);
216
217        glEnv.setSurfaceTimestamp(input.getTimestamp());
218
219        // And swap buffers
220        glEnv.swapBuffers();
221
222        if (createdFrame) {
223            gpuFrame.release();
224        }
225    }
226
227    @Override
228    public void fieldPortValueUpdated(String name, FilterContext context) {
229        updateRenderMode();
230    }
231
232    @Override
233    public void tearDown(FilterContext context) {
234        if (mScreen != null) {
235            mScreen.release();
236        }
237    }
238
239    private void updateTargetRect() {
240        if (mScreenWidth > 0 && mScreenHeight > 0 && mProgram != null) {
241            float screenAspectRatio = (float)mScreenWidth / mScreenHeight;
242            float relativeAspectRatio = screenAspectRatio / mAspectRatio;
243
244            if (relativeAspectRatio == 1.0f && mRenderMode != RENDERMODE_CUSTOMIZE) {
245                mProgram.setClearsOutput(false);
246            } else {
247                switch (mRenderMode) {
248                    case RENDERMODE_STRETCH:
249                        mProgram.setTargetRect(0, 0, 1, 1);
250                        mTargetQuad.p0.set(0f, 0.0f);
251                        mTargetQuad.p1.set(1f, 0.0f);
252                        mTargetQuad.p2.set(0f, 1.0f);
253                        mTargetQuad.p3.set(1f, 1.0f);
254                        mProgram.setClearsOutput(false);
255                        break;
256                    case RENDERMODE_FIT:
257                        if (relativeAspectRatio > 1.0f) {
258                            // Screen is wider than the camera, scale down X
259                            mTargetQuad.p0.set(0.5f - 0.5f / relativeAspectRatio, 0.0f);
260                            mTargetQuad.p1.set(0.5f + 0.5f / relativeAspectRatio, 0.0f);
261                            mTargetQuad.p2.set(0.5f - 0.5f / relativeAspectRatio, 1.0f);
262                            mTargetQuad.p3.set(0.5f + 0.5f / relativeAspectRatio, 1.0f);
263
264                        } else {
265                            // Screen is taller than the camera, scale down Y
266                            mTargetQuad.p0.set(0.0f, 0.5f - 0.5f * relativeAspectRatio);
267                            mTargetQuad.p1.set(1.0f, 0.5f - 0.5f * relativeAspectRatio);
268                            mTargetQuad.p2.set(0.0f, 0.5f + 0.5f * relativeAspectRatio);
269                            mTargetQuad.p3.set(1.0f, 0.5f + 0.5f * relativeAspectRatio);
270                        }
271                        mProgram.setClearsOutput(true);
272                        break;
273                    case RENDERMODE_FILL_CROP:
274                        if (relativeAspectRatio > 1) {
275                            // Screen is wider than the camera, crop in Y
276                            mTargetQuad.p0.set(0.0f, 0.5f - 0.5f * relativeAspectRatio);
277                            mTargetQuad.p1.set(1.0f, 0.5f - 0.5f * relativeAspectRatio);
278                            mTargetQuad.p2.set(0.0f, 0.5f + 0.5f * relativeAspectRatio);
279                            mTargetQuad.p3.set(1.0f, 0.5f + 0.5f * relativeAspectRatio);
280                        } else {
281                            // Screen is taller than the camera, crop in X
282                            mTargetQuad.p0.set(0.5f - 0.5f / relativeAspectRatio, 0.0f);
283                            mTargetQuad.p1.set(0.5f + 0.5f / relativeAspectRatio, 0.0f);
284                            mTargetQuad.p2.set(0.5f - 0.5f / relativeAspectRatio, 1.0f);
285                            mTargetQuad.p3.set(0.5f + 0.5f / relativeAspectRatio, 1.0f);
286                        }
287                        mProgram.setClearsOutput(true);
288                        break;
289                    case RENDERMODE_CUSTOMIZE:
290                        ((ShaderProgram) mProgram).setSourceRegion(mSourceQuad);
291                        break;
292                }
293                ((ShaderProgram) mProgram).setTargetRegion(mTargetQuad);
294            }
295        }
296    }
297}
298