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