GrainFilter.java revision ebdfce054988de002387c0bcedde7fda8a4f0eb0
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
17package android.filterpacks.imageproc;
18
19import android.filterfw.core.Filter;
20import android.filterfw.core.FilterContext;
21import android.filterfw.core.Frame;
22import android.filterfw.core.FrameFormat;
23import android.filterfw.core.GenerateFieldPort;
24import android.filterfw.core.KeyValueMap;
25import android.filterfw.core.NativeProgram;
26import android.filterfw.core.NativeFrame;
27import android.filterfw.core.Program;
28import android.filterfw.core.ShaderProgram;
29import android.filterfw.format.ImageFormat;
30import android.filterfw.geometry.Quad;
31import android.filterfw.geometry.Point;
32
33import java.util.Random;
34
35public class GrainFilter extends Filter {
36
37    private static final int RAND_THRESHOLD = 128;
38
39    @GenerateFieldPort(name = "strength", hasDefault = true)
40    private float mScale = 0f;
41
42    @GenerateFieldPort(name = "tile_size", hasDefault = true)
43    private int mTileSize = 640;
44
45    private Program mProgram;
46
47    private int mWidth = 0;
48    private int mHeight = 0;
49    private int mTarget = FrameFormat.TARGET_UNSPECIFIED;
50
51    private Frame mNoiseFrame = null;
52    private Random mRandom;
53
54    private final String mGrainShader =
55            "precision mediump float;\n" +
56            "uniform sampler2D tex_sampler_0;\n" +
57            "uniform sampler2D tex_sampler_1;\n" +
58            "uniform float scale;\n" +
59            "uniform float stepX;\n" +
60            "uniform float stepY;\n" +
61            "varying vec2 v_texcoord;\n" +
62            "void main() {\n" +
63            "  float noise = texture2D(tex_sampler_1, v_texcoord + vec2(-stepX, -stepY)).r * 0.224;\n" +
64            "  noise += texture2D(tex_sampler_1, v_texcoord + vec2(-stepX, stepY)).r * 0.224;\n" +
65            "  noise += texture2D(tex_sampler_1, v_texcoord + vec2(stepX, -stepY)).r * 0.224;\n" +
66            "  noise += texture2D(tex_sampler_1, v_texcoord + vec2(stepX, stepY)).r * 0.224;\n" +
67            "  noise += 0.4448;\n" +
68            "  noise *= scale;\n" +
69            "  vec4 color = texture2D(tex_sampler_0, v_texcoord);\n" +
70            "  float energy = 0.33333 * color.r + 0.33333 * color.g + 0.33333 * color.b;\n" +
71            "  float mask = (1.0 - sqrt(energy));\n" +
72            "  float weight = 1.0 - 1.333 * mask * noise;\n" +
73            "  gl_FragColor = vec4(color.rgb * weight, color.a);\n" +
74            "}\n";
75
76    public GrainFilter(String name) {
77        super(name);
78
79        mRandom = new Random();
80    }
81
82    @Override
83    public void setupPorts() {
84        addMaskedInputPort("image", ImageFormat.create(ImageFormat.COLORSPACE_RGBA));
85        addOutputBasedOnInput("image", "image");
86    }
87
88    @Override
89    public FrameFormat getOutputFormat(String portName, FrameFormat inputFormat) {
90        return inputFormat;
91    }
92
93    public void initProgram(FilterContext context, int target) {
94        switch (target) {
95            case FrameFormat.TARGET_GPU:
96                ShaderProgram shaderProgram = new ShaderProgram(context, mGrainShader);
97                shaderProgram.setMaximumTileSize(mTileSize);
98                mProgram = shaderProgram;
99                break;
100
101            default:
102                throw new RuntimeException("Filter Sharpen does not support frames of " +
103                    "target " + target + "!");
104        }
105        mTarget = target;
106    }
107
108    private void updateParameters() {
109        mProgram.setHostValue("scale", mScale);
110    }
111
112    private void updateFrameSize(int width, int height) {
113        mWidth = width;
114        mHeight = height;
115
116        if (mProgram != null) {
117            mProgram.setHostValue("stepX", 0.5f / mWidth);
118            mProgram.setHostValue("stepY", 0.5f / mHeight);
119            updateParameters();
120        }
121    }
122
123    @Override
124    public void fieldPortValueUpdated(String name, FilterContext context) {
125        if (mProgram != null) {
126            updateParameters();
127        }
128    }
129
130    @Override
131    public void tearDown(FilterContext context) {
132        if (mNoiseFrame != null) {
133            mNoiseFrame.release();
134            mNoiseFrame = null;
135        }
136    }
137
138    @Override
139    public void process(FilterContext context) {
140        // Get input frame
141        Frame input = pullInput("image");
142        FrameFormat inputFormat = input.getFormat();
143
144        // Create output frame
145        Frame output = context.getFrameManager().newFrame(inputFormat);
146
147        // Create program if not created already
148        if (mProgram == null || inputFormat.getTarget() != mTarget) {
149            initProgram(context, inputFormat.getTarget());
150            updateParameters();
151        }
152
153        // Check if the frame size has changed
154        if (inputFormat.getWidth() != mWidth || inputFormat.getHeight() != mHeight) {
155            updateFrameSize(inputFormat.getWidth(), inputFormat.getHeight());
156
157            int[] buffer = new int[mWidth * mHeight];
158            for (int i = 0; i < mWidth * mHeight; ++i) {
159                buffer[i] = (mRandom.nextInt(256) < RAND_THRESHOLD) ?
160                    mRandom.nextInt(256) : 0;
161            }
162            FrameFormat format = ImageFormat.create(mWidth, mHeight,
163                                                    ImageFormat.COLORSPACE_RGBA,
164                                                    FrameFormat.TARGET_GPU);
165            if (mNoiseFrame != null) {
166                mNoiseFrame.release();
167            }
168            mNoiseFrame = context.getFrameManager().newFrame(format);
169            mNoiseFrame.setInts(buffer);
170        }
171
172        if (mNoiseFrame.getFormat().getWidth() != mWidth ||
173            mNoiseFrame.getFormat().getHeight() != mHeight) {
174            throw new RuntimeException("Random map and imput image size mismatch!");
175        }
176
177        // Process
178        Frame[] inputs = {input, mNoiseFrame};
179        mProgram.process(inputs, output);
180
181        // Push output
182        pushOutput("image", output);
183
184        // Release pushed frame
185        output.release();
186    }
187}
188