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 BlackWhiteFilter extends Filter {
32
33    @GenerateFieldPort(name = "black", hasDefault = true)
34    private float mBlack = 0f;
35
36    @GenerateFieldPort(name = "white", hasDefault = true)
37    private float mWhite = 1f;
38
39    @GenerateFieldPort(name = "tile_size", hasDefault = true)
40    private int mTileSize = 640;
41
42    private Program mProgram;
43    private Random mRandom;
44
45    private int mTarget = FrameFormat.TARGET_UNSPECIFIED;
46
47    private final String mBlackWhiteShader =
48            "precision mediump float;\n" +
49            "uniform sampler2D tex_sampler_0;\n" +
50            "uniform vec2 seed;\n" +
51            "uniform float black;\n" +
52            "uniform float scale;\n" +
53            "uniform float stepsize;\n" +
54            "varying vec2 v_texcoord;\n" +
55            "float rand(vec2 loc) {\n" +
56            // Compute sin(theta), theta = 12.9898 x + 78.233y
57            // because floating point has limited range, make theta = theta1 + theta2
58            // where theta1 = 12x + 78y and theta2 = 0.9898x + 0.233y)
59            // Note that theta1 and theta2 cover diffent range of theta.
60            "  float theta1 = dot(loc, vec2(0.9898, 0.233));\n" +
61            "  float theta2 = dot(loc, vec2(12.0, 78.0));\n" +
62            // Use the property sin(theta) = cos(theta1)*sin(theta2)+sin(theta1)*cos(theta2)
63            // this approach also increases the precisions of sin(theta)
64            "  float value = cos(theta1) * sin(theta2) + sin(theta1) * cos(theta2);\n" +
65            // fract(43758.5453 * x) = fract(43758 * x + 0.5453 * x)
66            // keep value of part1 in range: (2^-14 to 2^14). Since 43758 = 117 * 374
67            // fract(43758 * sin(theta)) = mod(221 * mod(198*sin(theta), 1.0), 1.0)
68            // also to keep as much decimal digits, use the property
69            // mod(mod(198*sin(theta)) = mod(mod(197*sin(theta) + sin(theta))
70            "  float temp = mod(197.0 * value, 1.0) + value;\n" +
71            "  float part1 = mod(220.0 * temp, 1.0) + temp;\n" +
72            "  float part2 = value * 0.5453;\n" +
73            "  float part3 = cos(theta1 + theta2) * 0.43758;\n" +
74            "  return fract(part1 + part2 + part3);\n" +
75            "}\n" +
76            "void main() {\n" +
77            "  vec4 color = texture2D(tex_sampler_0, v_texcoord);\n" +
78            "  float dither = rand(v_texcoord + seed);\n" +
79            "  vec3 xform = clamp((color.rgb - black) * scale, 0.0, 1.0);\n" +
80            "  vec3 temp = clamp((color.rgb + stepsize - black) * scale, 0.0, 1.0);\n" +
81            "  vec3 new_color = clamp(xform + (temp - xform) * (dither - 0.5), 0.0, 1.0);\n" +
82            "  gl_FragColor = vec4(new_color, color.a);\n" +
83            "}\n";
84
85    public BlackWhiteFilter(String name) {
86        super(name);
87        mRandom = new Random(new Date().getTime());
88    }
89
90    @Override
91    public void setupPorts() {
92        addMaskedInputPort("image", ImageFormat.create(ImageFormat.COLORSPACE_RGBA));
93        addOutputBasedOnInput("image", "image");
94    }
95
96    @Override
97    public FrameFormat getOutputFormat(String portName, FrameFormat inputFormat) {
98        return inputFormat;
99    }
100
101    public void initProgram(FilterContext context, int target) {
102        switch (target) {
103            case FrameFormat.TARGET_GPU:
104                ShaderProgram shaderProgram = new ShaderProgram(context, mBlackWhiteShader);
105                shaderProgram.setMaximumTileSize(mTileSize);
106                mProgram = shaderProgram;
107                updateParameters();
108                break;
109
110            default:
111                throw new RuntimeException("Filter Sharpen does not support frames of " +
112                    "target " + target + "!");
113        }
114        mTarget = target;
115    }
116
117    private void updateParameters() {
118        float scale = (mBlack != mWhite) ? 1.0f / (mWhite - mBlack) : 2000f;
119        float stepsize = 1.0f / 255.0f;
120        mProgram.setHostValue("black", mBlack);
121        mProgram.setHostValue("scale", scale);
122        mProgram.setHostValue("stepsize", stepsize);
123
124        float seed[] = { mRandom.nextFloat(), mRandom.nextFloat() };
125        mProgram.setHostValue("seed", seed);
126    }
127
128    @Override
129    public void fieldPortValueUpdated(String name, FilterContext context) {
130        if (mProgram != null) {
131            updateParameters();
132        }
133    }
134
135    @Override
136    public void process(FilterContext context) {
137        // Get input frame
138        Frame input = pullInput("image");
139        FrameFormat inputFormat = input.getFormat();
140
141        // Create program if not created already
142        if (mProgram == null || inputFormat.getTarget() != mTarget) {
143            initProgram(context, inputFormat.getTarget());
144        }
145
146        // Create output frame
147        Frame output = context.getFrameManager().newFrame(inputFormat);
148
149        // Process
150        mProgram.process(input, output);
151
152        // Push output
153        pushOutput("image", output);
154
155        // Release pushed frame
156        output.release();
157    }
158}
159