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