1/*
2 * Copyright (C) 2010 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#include <android/bitmap.h>
18#include <jni.h>
19
20#include <cmath>
21#include <cstdlib>
22
23#include "utils.h"
24#include "_jni.h"
25
26using android::apps::photoeditor::utils::LockBitmaps;
27using android::apps::photoeditor::utils::pixel32_t;
28using android::apps::photoeditor::utils::UnlockBitmaps;
29
30namespace {
31
32extern "C" JNIEXPORT void JNICALL Java_com_android_photoeditor_filters_ImageUtils_nativeQuantize(
33    JNIEnv *env, jobject obj, jobject src_bitmap, jobject dst_bitmap) {
34   pQuantizeType f = (pQuantizeType)JNIFunc[JNI_Quantize].func_ptr;
35   return f(env, obj, src_bitmap, dst_bitmap);
36}
37
38extern "C" void Quantize(
39    JNIEnv *env, jobject obj, jobject src_bitmap, jobject dst_bitmap) {
40  AndroidBitmapInfo src_info;
41  AndroidBitmapInfo dst_info;
42  void* src_pixels;
43  void* dst_pixels;
44
45  int ret = LockBitmaps(
46      env, src_bitmap, dst_bitmap, &src_info, &dst_info, &src_pixels, &dst_pixels);
47  if (ret < 0) {
48    LOGE("LockBitmaps in quantize failed, error=%d", ret);
49    return;
50  }
51
52  uint8_t quantize_map[256];
53
54  for (uint32_t i = 0; i < 256; i++) {
55    quantize_map[i] = i / 128 * 128 + 64;
56  }
57
58  for (uint32_t scan_line = 0; scan_line < src_info.height; scan_line++) {
59    pixel32_t* src = reinterpret_cast<pixel32_t*>(src_pixels);
60    pixel32_t* dst = reinterpret_cast<pixel32_t*>(dst_pixels);
61
62    pixel32_t* src_line_end = src + src_info.width;
63    while (src < src_line_end) {
64      dst->rgba8[0] = quantize_map[src->rgba8[0]];
65      dst->rgba8[1] = quantize_map[src->rgba8[1]];
66      dst->rgba8[2] = quantize_map[src->rgba8[2]];
67      dst->rgba8[3] = src->rgba8[3];
68      dst++;
69      src++;
70    }
71    dst_pixels = reinterpret_cast<char*>(dst_pixels) + dst_info.stride;
72    src_pixels = reinterpret_cast<char*>(src_pixels) + src_info.stride;
73  }
74
75  UnlockBitmaps(env, src_bitmap, dst_bitmap);
76}
77
78}  // namespace
79