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;
30
31import java.util.Random;
32
33public class BlackWhiteFilter extends Filter {
34
35    @GenerateFieldPort(name = "black", hasDefault = true)
36    private float mBlack = 0f;
37
38    @GenerateFieldPort(name = "white", hasDefault = true)
39    private float mWhite = 1f;
40
41    @GenerateFieldPort(name = "tile_size", hasDefault = true)
42    private int mTileSize = 640;
43
44    private Program mProgram;
45
46    private int mWidth = 0;
47    private int mHeight = 0;
48    private int mTarget = FrameFormat.TARGET_UNSPECIFIED;
49
50    private Frame mNoiseFrame = null;
51    private Random mRandom;
52
53    private final String mBlackWhiteShader =
54            "precision mediump float;\n" +
55            "uniform sampler2D tex_sampler_0;\n" +
56            "uniform sampler2D tex_sampler_1;\n" +
57            "uniform float black;\n" +
58            "uniform float scale;\n" +
59            "uniform float stepsize;\n" +
60            "varying vec2 v_texcoord;\n" +
61            "void main() {\n" +
62            "  vec4 color = texture2D(tex_sampler_0, v_texcoord);\n" +
63            "  float dither = texture2D(tex_sampler_1, v_texcoord).r;\n" +
64            "  vec3 xform = clamp((color.rgb - black) * scale, 0.0, 1.0);\n" +
65            "  vec3 temp = clamp((color.rgb + stepsize - black) * scale, 0.0, 1.0);\n" +
66            "  vec3 new_color = clamp(xform + (temp - xform) * (dither - 0.5), 0.0, 1.0);\n" +
67            "  gl_FragColor = vec4(new_color, color.a);\n" +
68            "}\n";
69
70    public BlackWhiteFilter(String name) {
71        super(name);
72
73        mRandom = new Random();
74    }
75
76    @Override
77    public void setupPorts() {
78        addMaskedInputPort("image", ImageFormat.create(ImageFormat.COLORSPACE_RGBA));
79        addOutputBasedOnInput("image", "image");
80    }
81
82    @Override
83    public FrameFormat getOutputFormat(String portName, FrameFormat inputFormat) {
84        return inputFormat;
85    }
86
87    @Override
88    public void tearDown(FilterContext context) {
89        if (mNoiseFrame != null) {
90            mNoiseFrame.release();
91            mNoiseFrame = null;
92        }
93    }
94
95    public void initProgram(FilterContext context, int target) {
96        switch (target) {
97            case FrameFormat.TARGET_GPU:
98                ShaderProgram shaderProgram = new ShaderProgram(context, mBlackWhiteShader);
99                shaderProgram.setMaximumTileSize(mTileSize);
100                mProgram = shaderProgram;
101                updateParameters();
102                break;
103
104            default:
105                throw new RuntimeException("Filter Sharpen does not support frames of " +
106                    "target " + target + "!");
107        }
108        mTarget = target;
109    }
110
111    private void updateParameters() {
112        float scale = (mBlack != mWhite) ? 1.0f / (mWhite - mBlack) : 2000f;
113        float stepsize = 1.0f / 255.0f;
114
115        mProgram.setHostValue("black", mBlack);
116        mProgram.setHostValue("scale", scale);
117        mProgram.setHostValue("stepsize", stepsize);
118    }
119
120    @Override
121    public void fieldPortValueUpdated(String name, FilterContext context) {
122        if (mProgram != null) {
123            updateParameters();
124        }
125    }
126
127    @Override
128    public void process(FilterContext context) {
129        // Get input frame
130        Frame input = pullInput("image");
131        FrameFormat inputFormat = input.getFormat();
132
133        // Create program if not created already
134        if (mProgram == null || inputFormat.getTarget() != mTarget) {
135            initProgram(context, inputFormat.getTarget());
136        }
137
138        // Check if the frame size has changed
139        if (inputFormat.getWidth() != mWidth || inputFormat.getHeight() != mHeight) {
140            mWidth = inputFormat.getWidth();
141            mHeight = inputFormat.getHeight();
142
143            if (mNoiseFrame != null) {
144                mNoiseFrame.release();
145            }
146
147            int[] buffer = new int[mWidth * mHeight];
148            for (int i = 0; i < mWidth * mHeight; ++i) {
149              buffer[i] = mRandom.nextInt(255);
150            }
151            FrameFormat format = ImageFormat.create(mWidth, mHeight,
152                                                    ImageFormat.COLORSPACE_RGBA,
153                                                    FrameFormat.TARGET_GPU);
154            mNoiseFrame = context.getFrameManager().newFrame(format);
155            mNoiseFrame.setInts(buffer);
156        }
157
158        if (mNoiseFrame != null && (mNoiseFrame.getFormat().getWidth() != mWidth ||
159                                    mNoiseFrame.getFormat().getHeight() != mHeight)) {
160            throw new RuntimeException("Random map and imput image size mismatch!");
161        }
162
163        // Create output frame
164        Frame output = context.getFrameManager().newFrame(inputFormat);
165
166        // Process
167        Frame[] inputs = {input, mNoiseFrame};
168        mProgram.process(inputs, output);
169
170        // Push output
171        pushOutput("image", output);
172
173        // Release pushed frame
174        output.release();
175    }
176}
177