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.imageproc;
19
20import android.filterfw.core.Filter;
21import android.filterfw.core.FilterContext;
22import android.filterfw.core.Frame;
23import android.filterfw.core.FrameFormat;
24import android.filterfw.core.GenerateFieldPort;
25import android.filterfw.core.KeyValueMap;
26import android.filterfw.core.NativeProgram;
27import android.filterfw.core.NativeFrame;
28import android.filterfw.core.Program;
29import android.filterfw.core.ShaderProgram;
30import android.filterfw.format.ImageFormat;
31
32import android.util.Log;
33
34import java.lang.Math;
35import java.util.Set;
36
37/**
38 * @hide
39 */
40public class FisheyeFilter extends Filter {
41    private static final String TAG = "FisheyeFilter";
42
43    // This parameter has range between 0 and 1. It controls the effect of radial distortion.
44    // The larger the value, the more prominent the distortion effect becomes (a straight line
45    // becomes a curve).
46    @GenerateFieldPort(name = "scale", hasDefault = true)
47    private float mScale = 0f;
48
49    @GenerateFieldPort(name = "tile_size", hasDefault = true)
50    private int mTileSize = 640;
51
52    private Program mProgram;
53
54    private int mWidth = 0;
55    private int mHeight = 0;
56    private int mTarget = FrameFormat.TARGET_UNSPECIFIED;
57
58    private static final String mFisheyeShader =
59            "precision mediump float;\n" +
60            "uniform sampler2D tex_sampler_0;\n" +
61            "uniform vec2 scale;\n" +
62            "uniform float alpha;\n" +
63            "uniform float radius2;\n" +
64            "uniform float factor;\n" +
65            "varying vec2 v_texcoord;\n" +
66            "void main() {\n" +
67            "  const float m_pi_2 = 1.570963;\n" +
68            "  vec2 coord = v_texcoord - vec2(0.5, 0.5);\n" +
69            "  float dist = length(coord * scale);\n" +
70            "  float radian = m_pi_2 - atan(alpha * sqrt(radius2 - dist * dist), dist);\n" +
71            "  float scalar = radian * factor / dist;\n" +
72            "  vec2 new_coord = coord * scalar + vec2(0.5, 0.5);\n" +
73            "  gl_FragColor = texture2D(tex_sampler_0, new_coord);\n" +
74            "}\n";
75
76    public FisheyeFilter(String name) {
77        super(name);
78    }
79
80    @Override
81    public void setupPorts() {
82        addMaskedInputPort("image", ImageFormat.create(ImageFormat.COLORSPACE_RGBA));
83        addOutputBasedOnInput("image", "image");
84    }
85
86    @Override
87    public FrameFormat getOutputFormat(String portName, FrameFormat inputFormat) {
88        return inputFormat;
89    }
90
91    public void initProgram(FilterContext context, int target) {
92        switch (target) {
93            case FrameFormat.TARGET_GPU:
94                ShaderProgram shaderProgram = new ShaderProgram(context, mFisheyeShader);
95                shaderProgram.setMaximumTileSize(mTileSize);
96                mProgram = shaderProgram;
97                break;
98
99            default:
100                throw new RuntimeException("Filter FisheyeFilter does not support frames of " +
101                    "target " + target + "!");
102        }
103        mTarget = target;
104    }
105
106    @Override
107    public void process(FilterContext context) {
108        // Get input frame
109        Frame input = pullInput("image");
110        FrameFormat inputFormat = input.getFormat();
111
112        // Create output frame
113        Frame output = context.getFrameManager().newFrame(inputFormat);
114
115        // Create program if not created already
116        if (mProgram == null || inputFormat.getTarget() != mTarget) {
117            initProgram(context, inputFormat.getTarget());
118        }
119
120        // Check if the frame size has changed
121        if (inputFormat.getWidth() != mWidth || inputFormat.getHeight() != mHeight) {
122            updateFrameSize(inputFormat.getWidth(), inputFormat.getHeight());
123        }
124
125        // Process
126        mProgram.process(input, output);
127
128        // Push output
129        pushOutput("image", output);
130
131        // Release pushed frame
132        output.release();
133    }
134
135    @Override
136    public void fieldPortValueUpdated(String name, FilterContext context) {
137        if (mProgram != null) {
138            updateProgramParams();
139        }
140    }
141
142    private void updateFrameSize(int width, int height) {
143        mWidth = width;
144        mHeight = height;
145
146        updateProgramParams();
147    }
148
149    private void updateProgramParams() {
150        final float pi = 3.14159265f;
151        float scale[] = new float[2];
152        if (mWidth > mHeight) {
153          scale[0] = 1f;
154          scale[1] = ((float) mHeight) / mWidth;
155        } else {
156          scale[0] = ((float) mWidth) / mHeight;
157          scale[1] = 1f;
158        }
159        float alpha = mScale * 2.0f + 0.75f;
160        float bound2 = 0.25f * (scale[0] * scale[0] + scale[1] * scale[1]);
161        float bound = (float) Math.sqrt(bound2);
162        float radius = 1.15f * bound;
163        float radius2 = radius * radius;
164        float max_radian = 0.5f * pi -
165            (float) Math.atan(alpha / bound * (float) Math.sqrt(radius2 - bound2));
166        float factor = bound / max_radian;
167
168        mProgram.setHostValue("scale", scale);
169        mProgram.setHostValue("radius2",radius2);
170        mProgram.setHostValue("factor", factor);
171        mProgram.setHostValue("alpha", alpha);
172    }
173}
174