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
17
18package android.filterpacks.imageproc;
19
20import android.filterfw.core.FilterContext;
21import android.filterfw.core.FrameFormat;
22import android.filterfw.core.GenerateFieldPort;
23import android.filterfw.core.MutableFrameFormat;
24import android.filterfw.core.Program;
25import android.filterfw.core.ShaderProgram;
26import android.filterfw.format.ImageFormat;
27
28/**
29 * @hide
30 */
31public class ToGrayFilter extends SimpleImageFilter {
32
33    @GenerateFieldPort(name = "invertSource", hasDefault = true)
34    private boolean mInvertSource = false;
35
36    @GenerateFieldPort(name = "tile_size", hasDefault = true)
37    private int mTileSize = 640;
38
39    private MutableFrameFormat mOutputFormat;
40
41    private static final String mColorToGray4Shader =
42            "precision mediump float;\n" +
43            "uniform sampler2D tex_sampler_0;\n" +
44            "varying vec2 v_texcoord;\n" +
45            "void main() {\n" +
46            "  vec4 color = texture2D(tex_sampler_0, v_texcoord);\n" +
47            "  float y = dot(color, vec4(0.299, 0.587, 0.114, 0));\n" +
48            "  gl_FragColor = vec4(y, y, y, color.a);\n" +
49            "}\n";
50
51    public ToGrayFilter(String name) {
52        super(name, null);
53    }
54
55    @Override
56    public void setupPorts() {
57        addMaskedInputPort("image", ImageFormat.create(ImageFormat.COLORSPACE_RGBA,
58                                                       FrameFormat.TARGET_GPU));
59        addOutputBasedOnInput("image", "image");
60    }
61
62    @Override
63    protected Program getNativeProgram(FilterContext context) {
64        throw new RuntimeException("Native toGray not implemented yet!");
65    }
66
67    @Override
68    protected Program getShaderProgram(FilterContext context) {
69        int inputChannels = getInputFormat("image").getBytesPerSample();
70        if (inputChannels != 4) {
71            throw new RuntimeException("Unsupported GL input channels: " +
72                                       inputChannels + "! Channels must be 4!");
73        }
74        ShaderProgram program = new ShaderProgram(context, mColorToGray4Shader);
75        program.setMaximumTileSize(mTileSize);
76        if (mInvertSource)
77            program.setSourceRect(0.0f, 1.0f, 1.0f, -1.0f);
78        return program;
79    }
80
81}
82