GrainFilter.java revision cc6475e1732ae5ad4df480fccf44e1cb3ddce153
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 mGrainProgram;
46    private Program mNoiseProgram;
47
48    private int mWidth = 0;
49    private int mHeight = 0;
50    private int mTarget = FrameFormat.TARGET_UNSPECIFIED;
51
52    private Random mRandom = new Random();
53
54    private final String mNoiseShader =
55            "precision mediump float;\n" +
56            "uniform vec2 seed;\n" +
57            "varying vec2 v_texcoord;\n" +
58            "float rand(vec2 loc) {\n" +
59            "  return fract(sin(dot(loc, vec2(12.9898, 78.233))) * 43758.5453);\n" +
60            "}\n" +
61            "void main() {\n" +
62            "  gl_FragColor = vec4(rand(v_texcoord + seed), 0.0, 0.0, 1.0);\n" +
63            "}\n";
64
65    private final String mGrainShader =
66            "precision mediump float;\n" +
67            "uniform sampler2D tex_sampler_0;\n" +
68            "uniform sampler2D tex_sampler_1;\n" +
69            "uniform float scale;\n" +
70            "uniform float stepX;\n" +
71            "uniform float stepY;\n" +
72            "varying vec2 v_texcoord;\n" +
73            "void main() {\n" +
74            "  float noise = texture2D(tex_sampler_1, v_texcoord + vec2(-stepX, -stepY)).r * 0.224;\n" +
75            "  noise += texture2D(tex_sampler_1, v_texcoord + vec2(-stepX, stepY)).r * 0.224;\n" +
76            "  noise += texture2D(tex_sampler_1, v_texcoord + vec2(stepX, -stepY)).r * 0.224;\n" +
77            "  noise += texture2D(tex_sampler_1, v_texcoord + vec2(stepX, stepY)).r * 0.224;\n" +
78            "  noise += 0.4448;\n" +
79            "  noise *= scale;\n" +
80            "  vec4 color = texture2D(tex_sampler_0, v_texcoord);\n" +
81            "  float energy = 0.33333 * color.r + 0.33333 * color.g + 0.33333 * color.b;\n" +
82            "  float mask = (1.0 - sqrt(energy));\n" +
83            "  float weight = 1.0 - 1.333 * mask * noise;\n" +
84            "  gl_FragColor = vec4(color.rgb * weight, color.a);\n" +
85            "}\n";
86
87    public GrainFilter(String name) {
88        super(name);
89    }
90
91    @Override
92    public void setupPorts() {
93        addMaskedInputPort("image", ImageFormat.create(ImageFormat.COLORSPACE_RGBA));
94        addOutputBasedOnInput("image", "image");
95    }
96
97    @Override
98    public FrameFormat getOutputFormat(String portName, FrameFormat inputFormat) {
99        return inputFormat;
100    }
101
102    public void initProgram(FilterContext context, int target) {
103        switch (target) {
104            case FrameFormat.TARGET_GPU:
105                ShaderProgram shaderProgram = new ShaderProgram(context, mNoiseShader);
106                shaderProgram.setMaximumTileSize(mTileSize);
107                mNoiseProgram = shaderProgram;
108
109                shaderProgram = new ShaderProgram(context, mGrainShader);
110                shaderProgram.setMaximumTileSize(mTileSize);
111                mGrainProgram = shaderProgram;
112                break;
113
114            default:
115                throw new RuntimeException("Filter Sharpen does not support frames of " +
116                    "target " + target + "!");
117        }
118        mTarget = target;
119    }
120
121    private void updateParameters() {
122        float seed[] = { mRandom.nextFloat(), mRandom.nextFloat() };
123        mNoiseProgram.setHostValue("seed", seed);
124
125        mGrainProgram.setHostValue("scale", mScale);
126    }
127
128    private void updateFrameSize(int width, int height) {
129        mWidth = width;
130        mHeight = height;
131
132        if (mGrainProgram != null) {
133            mGrainProgram.setHostValue("stepX", 0.5f / mWidth);
134            mGrainProgram.setHostValue("stepY", 0.5f / mHeight);
135            updateParameters();
136        }
137    }
138
139    @Override
140    public void fieldPortValueUpdated(String name, FilterContext context) {
141        if (mGrainProgram != null && mNoiseProgram != null) {
142            updateParameters();
143        }
144    }
145
146    @Override
147    public void process(FilterContext context) {
148        // Get input frame
149        Frame input = pullInput("image");
150        FrameFormat inputFormat = input.getFormat();
151
152        FrameFormat noiseFormat = ImageFormat.create(inputFormat.getWidth() / 2,
153                                                     inputFormat.getHeight() / 2,
154                                                     ImageFormat.COLORSPACE_RGBA,
155                                                     FrameFormat.TARGET_GPU);
156
157        // Create noise frame
158        Frame noiseFrame = context.getFrameManager().newFrame(inputFormat);
159
160        // Create output frame
161        Frame output = context.getFrameManager().newFrame(inputFormat);
162
163        // Create program if not created already
164        if (mNoiseProgram == null || mGrainProgram == null || inputFormat.getTarget() != mTarget) {
165            initProgram(context, inputFormat.getTarget());
166            updateParameters();
167        }
168
169        // Check if the frame size has changed
170        if (inputFormat.getWidth() != mWidth || inputFormat.getHeight() != mHeight) {
171            updateFrameSize(inputFormat.getWidth(), inputFormat.getHeight());
172        }
173
174        Frame[] empty = {};
175        mNoiseProgram.process(empty, noiseFrame);
176
177        // Process
178        Frame[] inputs = {input, noiseFrame};
179        mGrainProgram.process(inputs, output);
180
181        // Push output
182        pushOutput("image", output);
183
184        // Release pushed frame
185        output.release();
186        noiseFrame.release();
187    }
188}
189