diff --git a/app/CMakeLists.txt b/app/CMakeLists.txt index 176a9ea..62844d1 100644 --- a/app/CMakeLists.txt +++ b/app/CMakeLists.txt @@ -10,7 +10,18 @@ option(CZ_TARGET_DEVICE "Build for CardputerZero Linux fbdev/evdev target" OFF) option(CZ_BUILD_TESTS "Build czcamera unit tests" ON) option(CZ_ENABLE_LVGL "Enable optional LVGL UI hook if available" OFF) -find_package(JPEG REQUIRED) +find_package(JPEG QUIET) +if(NOT JPEG_FOUND) + find_package(PkgConfig QUIET) + if(PkgConfig_FOUND) + pkg_check_modules(LIBJPEG IMPORTED_TARGET libjpeg) + endif() + if(TARGET PkgConfig::LIBJPEG) + add_library(JPEG::JPEG ALIAS PkgConfig::LIBJPEG) + else() + find_package(JPEG REQUIRED) + endif() +endif() find_package(Freetype QUIET) find_package(Threads REQUIRED) @@ -22,6 +33,8 @@ add_library(czcamera_core STATIC src/theme.cpp src/config.cpp src/storage.cpp + src/filters.cpp + src/jpeg_pipeline.cpp ) target_include_directories(czcamera_core @@ -39,6 +52,7 @@ target_compile_options(czcamera_core target_link_libraries(czcamera_core PUBLIC Threads::Threads + JPEG::JPEG ) if(Freetype_FOUND) @@ -72,4 +86,9 @@ if(CZ_BUILD_TESTS) target_compile_options(test_config_and_storage PRIVATE -Wall -Wextra -Wpedantic) target_link_libraries(test_config_and_storage PRIVATE czcamera_core) add_test(NAME test_config_and_storage COMMAND test_config_and_storage) + + add_executable(test_filters_and_jpeg tests/test_filters_and_jpeg.cpp) + target_compile_options(test_filters_and_jpeg PRIVATE -Wall -Wextra -Wpedantic) + target_link_libraries(test_filters_and_jpeg PRIVATE czcamera_core) + add_test(NAME test_filters_and_jpeg COMMAND test_filters_and_jpeg) endif() diff --git a/app/src/filters.cpp b/app/src/filters.cpp new file mode 100644 index 0000000..f98fda1 --- /dev/null +++ b/app/src/filters.cpp @@ -0,0 +1,367 @@ +#include "filters.hpp" + +#include +#include +#include +#include + +namespace cz { + +namespace { + +constexpr int kFilterCount = 9; + +inline uint8_t clamp_u8(int v) { + if (v < 0) return 0; + if (v > 255) return 255; + return static_cast(v); +} + +inline int luma_bt601(int r, int g, int b) { + return (77 * r + 150 * g + 29 * b) >> 8; +} + +uint32_t hash_pixel_coords(int x, int y) { + uint32_t h = static_cast(x) * 374761393u + + static_cast(y) * 668265263u; + h = (h ^ (h >> 13)) * 1274126177u; + return h ^ (h >> 16); +} + +void apply_bw(uint8_t* rgb, size_t count) { + for (size_t i = 0; i < count; ++i) { + uint8_t* p = rgb + i * 3; + const uint8_t y = static_cast(luma_bt601(p[0], p[1], p[2])); + p[0] = y; + p[1] = y; + p[2] = y; + } +} + +void apply_hicon(uint8_t* rgb, size_t count) { + for (size_t i = 0; i < count; ++i) { + uint8_t* p = rgb + i * 3; + const int y = luma_bt601(p[0], p[1], p[2]); + // ~1.6x contrast stretch around mid-gray (128) + const uint8_t out = clamp_u8((((y - 128) * 410) >> 8) + 128); + p[0] = out; + p[1] = out; + p[2] = out; + } +} + +void apply_sepia(uint8_t* rgb, size_t count) { + for (size_t i = 0; i < count; ++i) { + uint8_t* p = rgb + i * 3; + const int r = p[0]; + const int g = p[1]; + const int b = p[2]; + p[0] = clamp_u8((101 * r + 197 * g + 48 * b) >> 8); + p[1] = clamp_u8((89 * r + 176 * g + 43 * b) >> 8); + p[2] = clamp_u8((70 * r + 137 * g + 34 * b) >> 8); + } +} + +void apply_cool(uint8_t* rgb, size_t count) { + for (size_t i = 0; i < count; ++i) { + uint8_t* p = rgb + i * 3; + const int cr = (((static_cast(p[0]) - 128) * 276) >> 8) + 128; + const int cg = (((static_cast(p[1]) - 128) * 276) >> 8) + 128; + const int cb = (((static_cast(p[2]) - 128) * 276) >> 8) + 128; + p[0] = clamp_u8(cr - 14); + p[1] = clamp_u8(cg + 2); + p[2] = clamp_u8(cb + 20); + } +} + +void apply_vivid(uint8_t* rgb, size_t count) { + for (size_t i = 0; i < count; ++i) { + uint8_t* p = rgb + i * 3; + const int r = p[0]; + const int g = p[1]; + const int b = p[2]; + const int y = luma_bt601(r, g, b); + const int cy = (((y - 128) * 276) >> 8) + 128; + p[0] = clamp_u8(cy + (((r - y) * 346) >> 8)); + p[1] = clamp_u8(cy + (((g - y) * 346) >> 8)); + p[2] = clamp_u8(cy + (((b - y) * 346) >> 8)); + } +} + +void apply_invert(uint8_t* rgb, size_t count) { + for (size_t i = 0; i < count; ++i) { + uint8_t* p = rgb + i * 3; + p[0] = static_cast(255 - p[0]); + p[1] = static_cast(255 - p[1]); + p[2] = static_cast(255 - p[2]); + } +} + +void apply_retro(uint8_t* rgb, int width, int height) { + const float inv_w = (width > 1) ? (2.0f / static_cast(width - 1)) : 0.0f; + const float inv_h = (height > 1) ? (2.0f / static_cast(height - 1)) : 0.0f; + + for (int y = 0; y < height; ++y) { + const float ny = (height > 1) ? (static_cast(y) * inv_h - 1.0f) : 0.0f; + const float ny2 = ny * ny; + uint8_t* row = rgb + static_cast(y) * static_cast(width) * 3; + for (int x = 0; x < width; ++x) { + const float nx = (width > 1) ? (static_cast(x) * inv_w - 1.0f) : 0.0f; + const float d2 = std::min(nx * nx + ny2, 2.0f); + // Fixed-point vignette scale in [0, 256] (~0.72 at corners, 1.0 at center) + const int vig_fp = static_cast((1.0f - 0.14f * d2) * 256.0f); + + uint8_t* p = row + static_cast(x) * 3; + // Lifted shadows (+14) + highlight roll-off (*228/256) + warm midtone tint + int r = ((static_cast(p[0]) * 228) >> 8) + 24; + int g = ((static_cast(p[1]) * 228) >> 8) + 18; + int b = ((static_cast(p[2]) * 228) >> 8) + 8; + + r = (r * vig_fp) >> 8; + g = (g * vig_fp) >> 8; + b = (b * vig_fp) >> 8; + + // Deterministic subtle film grain in [-4, +3] + const int grain = static_cast(hash_pixel_coords(x, y) & 7u) - 4; + p[0] = clamp_u8(r + grain); + p[1] = clamp_u8(g + grain); + p[2] = clamp_u8(b + grain); + } + } +} + +void apply_gameboy(uint8_t* rgb, int width, int height) { + static constexpr uint8_t kDmgPalette[4][3] = { + {0x0f, 0x38, 0x0f}, + {0x30, 0x62, 0x30}, + {0x8b, 0xac, 0x0f}, + {0x9b, 0xbc, 0x0f}, + }; + static constexpr int kBayer4x4[4][4] = { + {0, 8, 2, 10}, + {12, 4, 14, 6}, + {3, 11, 1, 9}, + {15, 7, 13, 5}, + }; + + const int block = std::max(1, width / 160); + + for (int y0 = 0, by = 0; y0 < height; y0 += block, ++by) { + const int y1 = std::min(height, y0 + block); + for (int x0 = 0, bx = 0; x0 < width; x0 += block, ++bx) { + const int x1 = std::min(width, x0 + block); + + int lum_sum = 0; + int pix_count = 0; + for (int y = y0; y < y1; ++y) { + const uint8_t* row = + rgb + static_cast(y) * static_cast(width) * 3; + for (int x = x0; x < x1; ++x) { + const uint8_t* p = row + static_cast(x) * 3; + lum_sum += luma_bt601(p[0], p[1], p[2]); + ++pix_count; + } + } + + const int avg_lum = (pix_count > 0) ? (lum_sum / pix_count) : 0; + const int bayer = kBayer4x4[by & 3][bx & 3]; + const int shade = + std::min(3, std::max(0, (avg_lum * 48 + bayer * 255) / 4080)); + const uint8_t* col = kDmgPalette[shade]; + + for (int y = y0; y < y1; ++y) { + uint8_t* row = + rgb + static_cast(y) * static_cast(width) * 3; + for (int x = x0; x < x1; ++x) { + uint8_t* p = row + static_cast(x) * 3; + p[0] = col[0]; + p[1] = col[1]; + p[2] = col[2]; + } + } + } + } +} + +} // namespace + +std::string filter_to_string(FilterId id) { + switch (id) { + case FilterId::None: + return "none"; + case FilterId::BW: + return "bw"; + case FilterId::HiCon: + return "hicon"; + case FilterId::Sepia: + return "sepia"; + case FilterId::Cool: + return "cool"; + case FilterId::Vivid: + return "vivid"; + case FilterId::Invert: + return "invert"; + case FilterId::Retro: + return "retro"; + case FilterId::GameBoy: + return "gameboy"; + } + return "none"; +} + +FilterId filter_from_string(const std::string& value) { + std::string lower = value; + std::transform(lower.begin(), lower.end(), lower.begin(), + [](unsigned char c) { return static_cast(std::tolower(c)); }); + if (lower == "bw") return FilterId::BW; + if (lower == "hicon") return FilterId::HiCon; + if (lower == "sepia") return FilterId::Sepia; + if (lower == "cool") return FilterId::Cool; + if (lower == "vivid") return FilterId::Vivid; + if (lower == "invert") return FilterId::Invert; + if (lower == "retro") return FilterId::Retro; + if (lower == "gameboy") return FilterId::GameBoy; + return FilterId::None; +} + +std::string filter_display_name(FilterId id) { + switch (id) { + case FilterId::None: + return "None"; + case FilterId::BW: + return "B&W"; + case FilterId::HiCon: + return "Hi-Con"; + case FilterId::Sepia: + return "Sepia"; + case FilterId::Cool: + return "Cool"; + case FilterId::Vivid: + return "Vivid"; + case FilterId::Invert: + return "Invert"; + case FilterId::Retro: + return "Retro"; + case FilterId::GameBoy: + return "GameBoy"; + } + return "None"; +} + +FilterId next_filter(FilterId current, int delta) { + const int cur = static_cast(current); + int idx = (cur + delta) % kFilterCount; + if (idx < 0) idx += kFilterCount; + return static_cast(idx); +} + +void apply_filter_rgb24(uint8_t* rgb, int width, int height, FilterId filter) { + if (!rgb || width <= 0 || height <= 0 || filter == FilterId::None) { + return; + } + const size_t count = static_cast(width) * static_cast(height); + switch (filter) { + case FilterId::None: + return; + case FilterId::BW: + apply_bw(rgb, count); + return; + case FilterId::HiCon: + apply_hicon(rgb, count); + return; + case FilterId::Sepia: + apply_sepia(rgb, count); + return; + case FilterId::Cool: + apply_cool(rgb, count); + return; + case FilterId::Vivid: + apply_vivid(rgb, count); + return; + case FilterId::Invert: + apply_invert(rgb, count); + return; + case FilterId::Retro: + apply_retro(rgb, width, height); + return; + case FilterId::GameBoy: + apply_gameboy(rgb, width, height); + return; + } +} + +void scale_crop_rgb24(const uint8_t* src, + int src_w, + int src_h, + uint8_t* dst, + int dst_w, + int dst_h, + float loupe_factor) { + if (!src || !dst || src_w <= 0 || src_h <= 0 || dst_w <= 0 || dst_h <= 0) { + return; + } + const double loupe = (loupe_factor < 1.0f) ? 1.0 : static_cast(loupe_factor); + + const double src_aspect = static_cast(src_w) / static_cast(src_h); + const double dst_aspect = static_cast(dst_w) / static_cast(dst_h); + + double crop_w = static_cast(src_w); + double crop_h = static_cast(src_h); + if (src_aspect > dst_aspect) { + crop_w = static_cast(src_h) * dst_aspect; + } else if (src_aspect < dst_aspect) { + crop_h = static_cast(src_w) / dst_aspect; + } + + crop_w /= loupe; + crop_h /= loupe; + const double x0 = (static_cast(src_w) - crop_w) * 0.5; + const double y0 = (static_cast(src_h) - crop_h) * 0.5; + + const double step_x = crop_w / static_cast(dst_w); + const double step_y = crop_h / static_cast(dst_h); + + for (int dy = 0; dy < dst_h; ++dy) { + double sy = y0 + (static_cast(dy) + 0.5) * step_y - 0.5; + if (sy < 0.0) sy = 0.0; + if (sy > static_cast(src_h - 1)) sy = static_cast(src_h - 1); + + const int iy0 = static_cast(std::floor(sy)); + const int iy1 = std::min(src_h - 1, iy0 + 1); + const int fy = static_cast((sy - static_cast(iy0)) * 256.0); + const int ify = 256 - fy; + + const uint8_t* row0 = src + static_cast(iy0) * static_cast(src_w) * 3; + const uint8_t* row1 = src + static_cast(iy1) * static_cast(src_w) * 3; + uint8_t* dst_row = dst + static_cast(dy) * static_cast(dst_w) * 3; + + for (int dx = 0; dx < dst_w; ++dx) { + double sx = x0 + (static_cast(dx) + 0.5) * step_x - 0.5; + if (sx < 0.0) sx = 0.0; + if (sx > static_cast(src_w - 1)) sx = static_cast(src_w - 1); + + const int ix0 = static_cast(std::floor(sx)); + const int ix1 = std::min(src_w - 1, ix0 + 1); + const int fx = static_cast((sx - static_cast(ix0)) * 256.0); + const int ifx = 256 - fx; + + const int w00 = ifx * ify; + const int w10 = fx * ify; + const int w01 = ifx * fy; + const int w11 = fx * fy; + + const uint8_t* p00 = row0 + static_cast(ix0) * 3; + const uint8_t* p10 = row0 + static_cast(ix1) * 3; + const uint8_t* p01 = row1 + static_cast(ix0) * 3; + const uint8_t* p11 = row1 + static_cast(ix1) * 3; + + uint8_t* out = dst_row + static_cast(dx) * 3; + for (int c = 0; c < 3; ++c) { + out[c] = static_cast( + (p00[c] * w00 + p10[c] * w10 + p01[c] * w01 + p11[c] * w11) >> 16); + } + } + } +} + +} // namespace cz diff --git a/app/src/filters.hpp b/app/src/filters.hpp new file mode 100644 index 0000000..2b2ee27 --- /dev/null +++ b/app/src/filters.hpp @@ -0,0 +1,35 @@ +#pragma once + +#include +#include + +namespace cz { + +enum class FilterId { + None, + BW, + HiCon, + Sepia, + Cool, + Vivid, + Invert, + Retro, + GameBoy, +}; + +std::string filter_to_string(FilterId id); +FilterId filter_from_string(const std::string& value); +std::string filter_display_name(FilterId id); +FilterId next_filter(FilterId current, int delta = 1); + +void apply_filter_rgb24(uint8_t* rgb, int width, int height, FilterId filter); + +void scale_crop_rgb24(const uint8_t* src, + int src_w, + int src_h, + uint8_t* dst, + int dst_w, + int dst_h, + float loupe_factor = 1.0f); + +} // namespace cz diff --git a/app/src/jpeg_pipeline.cpp b/app/src/jpeg_pipeline.cpp new file mode 100644 index 0000000..743700f --- /dev/null +++ b/app/src/jpeg_pipeline.cpp @@ -0,0 +1,265 @@ +#include "jpeg_pipeline.hpp" + +#include "storage.hpp" + +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace fs = std::filesystem; + +namespace cz { + +namespace { + +struct CzJpegErrorMgr { + jpeg_error_mgr pub; + jmp_buf setjmp_buffer; + char message[JMSG_LENGTH_MAX]; +}; + +void cz_jpeg_error_exit(j_common_ptr cinfo) { + auto* err = reinterpret_cast(cinfo->err); + (*cinfo->err->format_message)(cinfo, err->message); + longjmp(err->setjmp_buffer, 1); +} + +void cz_jpeg_output_message(j_common_ptr /*cinfo*/) { + // Suppress libjpeg stderr chatter; errors are surfaced via out_err. +} + +void remove_silent(const std::string& path) { + if (path.empty()) return; + std::error_code ec; + fs::remove(path, ec); +} + +bool decode_jpeg_impl(const std::string& path, + int target_w, + int target_h, + bool use_scaling, + RgbImage& out, + std::string& out_err) { + out_err.clear(); + out = RgbImage{}; + + if (path.empty()) { + out_err = "empty JPEG path"; + return false; + } + + FILE* fp = std::fopen(path.c_str(), "rb"); + if (!fp) { + out_err = "failed to open JPEG '" + path + "': " + std::strerror(errno); + return false; + } + + jpeg_decompress_struct cinfo{}; + CzJpegErrorMgr jerr{}; + jerr.message[0] = '\0'; + + cinfo.err = jpeg_std_error(&jerr.pub); + jerr.pub.error_exit = cz_jpeg_error_exit; + jerr.pub.output_message = cz_jpeg_output_message; + + if (setjmp(jerr.setjmp_buffer) != 0) { + jpeg_destroy_decompress(&cinfo); + std::fclose(fp); + out = RgbImage{}; + out_err = jerr.message[0] != '\0' ? std::string(jerr.message) + : std::string("libjpeg decode error"); + return false; + } + + jpeg_create_decompress(&cinfo); + jpeg_stdio_src(&cinfo, fp); + jpeg_read_header(&cinfo, TRUE); + cinfo.out_color_space = JCS_RGB; + + if (use_scaling && target_w > 0 && target_h > 0) { + static constexpr unsigned int kDenoms[] = {8, 4, 2, 1}; + for (unsigned int denom : kDenoms) { + cinfo.scale_num = 1; + cinfo.scale_denom = denom; + jpeg_calc_output_dimensions(&cinfo); + if (cinfo.output_width >= static_cast(target_w) && + cinfo.output_height >= static_cast(target_h)) { + break; + } + } + } + + jpeg_start_decompress(&cinfo); + + if (cinfo.output_width == 0 || cinfo.output_height == 0 || + cinfo.output_components != 3) { + jpeg_destroy_decompress(&cinfo); + std::fclose(fp); + out_err = "unexpected JPEG output dimensions or components"; + return false; + } + + const int w = static_cast(cinfo.output_width); + const int h = static_cast(cinfo.output_height); + const size_t row_stride = static_cast(w) * 3u; + + out.width = w; + out.height = h; + out.rgb24.resize(row_stride * static_cast(h)); + + while (cinfo.output_scanline < cinfo.output_height) { + JSAMPROW row_ptr[1]; + row_ptr[0] = out.rgb24.data() + + static_cast(cinfo.output_scanline) * row_stride; + jpeg_read_scanlines(&cinfo, row_ptr, 1); + } + + jpeg_finish_decompress(&cinfo); + jpeg_destroy_decompress(&cinfo); + std::fclose(fp); + return true; +} + +} // namespace + +bool decode_jpeg_rgb24(const std::string& path, + RgbImage& out, + std::string& out_err) { + return decode_jpeg_impl(path, 0, 0, false, out, out_err); +} + +bool decode_jpeg_scaled_rgb24(const std::string& path, + int target_w, + int target_h, + RgbImage& out, + std::string& out_err) { + return decode_jpeg_impl(path, target_w, target_h, true, out, out_err); +} + +bool encode_jpeg_rgb24(const std::string& path, + const uint8_t* rgb, + int width, + int height, + int quality, + std::string& out_err) { + out_err.clear(); + if (path.empty() || !rgb || width <= 0 || height <= 0) { + out_err = "invalid JPEG encode arguments"; + return false; + } + + const int clamped_quality = std::max(1, std::min(100, quality)); + FILE* fp = std::fopen(path.c_str(), "wb"); + if (!fp) { + out_err = "failed to open output JPEG '" + path + "': " + std::strerror(errno); + return false; + } + + jpeg_compress_struct cinfo{}; + CzJpegErrorMgr jerr{}; + jerr.message[0] = '\0'; + + cinfo.err = jpeg_std_error(&jerr.pub); + jerr.pub.error_exit = cz_jpeg_error_exit; + jerr.pub.output_message = cz_jpeg_output_message; + + if (setjmp(jerr.setjmp_buffer) != 0) { + jpeg_destroy_compress(&cinfo); + std::fclose(fp); + remove_silent(path); + out_err = jerr.message[0] != '\0' ? std::string(jerr.message) + : std::string("libjpeg encode error"); + return false; + } + + jpeg_create_compress(&cinfo); + jpeg_stdio_dest(&cinfo, fp); + + cinfo.image_width = static_cast(width); + cinfo.image_height = static_cast(height); + cinfo.input_components = 3; + cinfo.in_color_space = JCS_RGB; + + jpeg_set_defaults(&cinfo); + jpeg_set_quality(&cinfo, clamped_quality, TRUE); + jpeg_start_compress(&cinfo, TRUE); + + const size_t row_stride = static_cast(width) * 3u; + while (cinfo.next_scanline < cinfo.image_height) { + JSAMPROW row_ptr[1]; + row_ptr[0] = const_cast( + rgb + static_cast(cinfo.next_scanline) * row_stride); + jpeg_write_scanlines(&cinfo, row_ptr, 1); + } + + jpeg_finish_compress(&cinfo); + jpeg_destroy_compress(&cinfo); + + if (std::fflush(fp) != 0) { + out_err = std::string("fflush failed: ") + std::strerror(errno); + std::fclose(fp); + remove_silent(path); + return false; + } + ::fsync(fileno(fp)); + if (std::fclose(fp) != 0) { + out_err = std::string("fclose failed: ") + std::strerror(errno); + remove_silent(path); + return false; + } + return true; +} + +bool finalize_still_photo(const std::string& tmp_path, + const std::string& final_path, + FilterId filter, + std::string& out_err) { + out_err.clear(); + if (tmp_path.empty() || final_path.empty()) { + out_err = "empty staging path"; + return false; + } + + if (filter == FilterId::None) { + if (!commit_staged_file(tmp_path, final_path, out_err)) { + remove_silent(tmp_path); + return false; + } + return true; + } + + RgbImage img; + if (!decode_jpeg_rgb24(tmp_path, img, out_err)) { + remove_silent(tmp_path); + return false; + } + + apply_filter_rgb24(img.rgb24.data(), img.width, img.height, filter); + + const std::string filtered_tmp = tmp_path + ".filtered.tmp"; + if (!encode_jpeg_rgb24(filtered_tmp, img.rgb24.data(), img.width, img.height, + 92, out_err)) { + remove_silent(filtered_tmp); + remove_silent(tmp_path); + return false; + } + + if (!commit_staged_file(filtered_tmp, final_path, out_err)) { + remove_silent(filtered_tmp); + remove_silent(tmp_path); + return false; + } + + if (tmp_path != final_path) { + remove_silent(tmp_path); + } + return true; +} + +} // namespace cz diff --git a/app/src/jpeg_pipeline.hpp b/app/src/jpeg_pipeline.hpp new file mode 100644 index 0000000..186bed6 --- /dev/null +++ b/app/src/jpeg_pipeline.hpp @@ -0,0 +1,39 @@ +#pragma once + +#include "filters.hpp" + +#include +#include +#include + +namespace cz { + +struct RgbImage { + int width = 0; + int height = 0; + std::vector rgb24; +}; + +bool decode_jpeg_rgb24(const std::string& path, + RgbImage& out, + std::string& out_err); + +bool decode_jpeg_scaled_rgb24(const std::string& path, + int target_w, + int target_h, + RgbImage& out, + std::string& out_err); + +bool encode_jpeg_rgb24(const std::string& path, + const uint8_t* rgb, + int width, + int height, + int quality, + std::string& out_err); + +bool finalize_still_photo(const std::string& tmp_path, + const std::string& final_path, + FilterId filter, + std::string& out_err); + +} // namespace cz diff --git a/app/tests/test_filters_and_jpeg.cpp b/app/tests/test_filters_and_jpeg.cpp new file mode 100644 index 0000000..82200cd --- /dev/null +++ b/app/tests/test_filters_and_jpeg.cpp @@ -0,0 +1,408 @@ +#include "filters.hpp" +#include "jpeg_pipeline.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace fs = std::filesystem; + +namespace { + +struct TempDir { + std::string path; + explicit TempDir(const std::string& name) { + const std::string base = + "/tmp/czcamera_test_" + name + "_" + std::to_string(::getpid()); + std::error_code ec; + fs::remove_all(base, ec); + fs::create_directories(base, ec); + assert(!ec); + path = base; + } + ~TempDir() { + std::error_code ec; + fs::remove_all(path, ec); + } +}; + +void write_bytes(const std::string& path, const std::string& data) { + std::ofstream out(path, std::ios::binary | std::ios::trunc); + assert(out.is_open()); + out.write(data.data(), static_cast(data.size())); + out.close(); + assert(out.good()); +} + +std::string read_bytes(const std::string& path) { + std::ifstream in(path, std::ios::binary); + assert(in.is_open()); + return std::string((std::istreambuf_iterator(in)), + std::istreambuf_iterator()); +} + +bool is_dmg_olive(uint8_t r, uint8_t g, uint8_t b) { + return (r == 0x0f && g == 0x38 && b == 0x0f) || + (r == 0x30 && g == 0x62 && b == 0x30) || + (r == 0x8b && g == 0xac && b == 0x0f) || + (r == 0x9b && g == 0xbc && b == 0x0f); +} + +bool is_near_dmg_olive(uint8_t r, uint8_t g, uint8_t b, int tol = 28) { + const uint8_t palette[4][3] = { + {0x0f, 0x38, 0x0f}, + {0x30, 0x62, 0x30}, + {0x8b, 0xac, 0x0f}, + {0x9b, 0xbc, 0x0f}, + }; + for (const auto& c : palette) { + if (std::abs(static_cast(r) - c[0]) <= tol && + std::abs(static_cast(g) - c[1]) <= tol && + std::abs(static_cast(b) - c[2]) <= tol) { + return true; + } + } + return false; +} + +void test_filter_cycle_and_serialization() { + struct Case { + cz::FilterId id; + const char* serialized; + }; + const Case cases[] = { + {cz::FilterId::None, "none"}, {cz::FilterId::BW, "bw"}, + {cz::FilterId::HiCon, "hicon"}, {cz::FilterId::Sepia, "sepia"}, + {cz::FilterId::Cool, "cool"}, {cz::FilterId::Vivid, "vivid"}, + {cz::FilterId::Invert, "invert"}, {cz::FilterId::Retro, "retro"}, + {cz::FilterId::GameBoy, "gameboy"}, + }; + + for (const auto& c : cases) { + assert(cz::filter_to_string(c.id) == c.serialized); + assert(cz::filter_from_string(c.serialized) == c.id); + assert(!cz::filter_display_name(c.id).empty()); + } + + assert(cz::filter_from_string("invalid_filter") == cz::FilterId::None); + assert(cz::filter_from_string("") == cz::FilterId::None); + + // Forward cycle and wrap-around + cz::FilterId cur = cz::FilterId::None; + for (int i = 0; i < 9; ++i) { + assert(cur == cases[i].id); + cur = cz::next_filter(cur, 1); + } + assert(cur == cz::FilterId::None); + + // Backward wrap-around + assert(cz::next_filter(cz::FilterId::None, -1) == cz::FilterId::GameBoy); + assert(cz::next_filter(cz::FilterId::GameBoy, 1) == cz::FilterId::None); + assert(cz::next_filter(cz::FilterId::Sepia, 9) == cz::FilterId::Sepia); + assert(cz::next_filter(cz::FilterId::Sepia, -9) == cz::FilterId::Sepia); +} + +void test_all_nine_filters_pixel_behavior() { + // Base 4x1 test pixels: mid-dark, mid-light, warm-ish color, saturated color + const std::vector base = { + 70, 70, 70, // pixel 0: mid-dark gray + 185, 185, 185, // pixel 1: mid-light gray + 180, 110, 90, // pixel 2: warm midtone + 128, 128, 128, // pixel 3: neutral gray + }; + + // 1. None: exact no-op + { + auto buf = base; + cz::apply_filter_rgb24(buf.data(), 4, 1, cz::FilterId::None); + assert(buf == base); + } + + // 2. BW: R == G == B + std::vector bw_buf = base; + cz::apply_filter_rgb24(bw_buf.data(), 4, 1, cz::FilterId::BW); + for (int i = 0; i < 4; ++i) { + const uint8_t r = bw_buf[i * 3 + 0]; + const uint8_t g = bw_buf[i * 3 + 1]; + const uint8_t b = bw_buf[i * 3 + 2]; + assert(r == g && g == b); + } + assert(bw_buf[0] < bw_buf[3]); // dark < light + + // 3. HiCon: pushes mid-dark lower and mid-light higher than BW + { + auto buf = base; + cz::apply_filter_rgb24(buf.data(), 4, 1, cz::FilterId::HiCon); + for (int i = 0; i < 4; ++i) { + assert(buf[i * 3 + 0] == buf[i * 3 + 1] && + buf[i * 3 + 1] == buf[i * 3 + 2]); + } + assert(buf[0] < bw_buf[0]); + assert(buf[3] > bw_buf[3]); + } + + // 4. Sepia: warm R >= G >= B and R > B on neutral gray + { + auto buf = base; + cz::apply_filter_rgb24(buf.data(), 4, 1, cz::FilterId::Sepia); + for (int i = 0; i < 4; ++i) { + const uint8_t r = buf[i * 3 + 0]; + const uint8_t g = buf[i * 3 + 1]; + const uint8_t b = buf[i * 3 + 2]; + assert(r >= g && g >= b); + assert(r > b); + } + } + + // 5. Cool: boosts B over R on neutral gray + { + auto buf = base; + cz::apply_filter_rgb24(buf.data(), 4, 1, cz::FilterId::Cool); + assert(buf[3 * 3 + 2] > buf[3 * 3 + 0]); // neutral gray: B > R + assert(buf[0 * 3 + 2] > buf[0 * 3 + 0]); + } + + // 6. Vivid: widens chroma spread on colorful pixel + { + auto buf = base; + cz::apply_filter_rgb24(buf.data(), 4, 1, cz::FilterId::Vivid); + const int orig_spread = + std::max({base[6], base[7], base[8]}) - std::min({base[6], base[7], base[8]}); + const int vivid_spread = + std::max({buf[6], buf[7], buf[8]}) - std::min({buf[6], buf[7], buf[8]}); + assert(vivid_spread > orig_spread); + } + + // 7. Invert: 255 - c + { + auto buf = base; + cz::apply_filter_rgb24(buf.data(), 4, 1, cz::FilterId::Invert); + for (size_t i = 0; i < buf.size(); ++i) { + assert(buf[i] == static_cast(255 - base[i])); + } + } + + // 8. Retro: deterministic across runs, lifted shadows, subtle edge vignette + { + const int w = 64; + const int h = 48; + std::vector zeros(w * h * 3, 0); + cz::apply_filter_rgb24(zeros.data(), w, h, cz::FilterId::Retro); + // Center pixel shadow lifted above 0 + const size_t center_idx = ((h / 2) * w + (w / 2)) * 3; + assert(zeros[center_idx] > 0 || zeros[center_idx + 1] > 0 || + zeros[center_idx + 2] > 0); + + std::vector gray1(w * h * 3, 140); + std::vector gray2(w * h * 3, 140); + cz::apply_filter_rgb24(gray1.data(), w, h, cz::FilterId::Retro); + cz::apply_filter_rgb24(gray2.data(), w, h, cz::FilterId::Retro); + assert(gray1 == gray2); // deterministic + + // Center brighter than corner due to vignette + const int corner_sum = gray1[0] + gray1[1] + gray1[2]; + const int center_sum = + gray1[center_idx] + gray1[center_idx + 1] + gray1[center_idx + 2]; + assert(center_sum > corner_sum); + } + + // 9. GameBoy: strictly 4 DMG olive colors + uniform max(1, width/160) blocks + { + // 226x170 viewfinder check (block = 1) + const int vw = 226; + const int vh = 170; + std::vector vf(vw * vh * 3); + for (int y = 0; y < vh; ++y) { + for (int x = 0; x < vw; ++x) { + const uint8_t v = static_cast((x * 255) / (vw - 1)); + const size_t idx = (static_cast(y) * vw + x) * 3; + vf[idx + 0] = v; + vf[idx + 1] = v; + vf[idx + 2] = v; + } + } + cz::apply_filter_rgb24(vf.data(), vw, vh, cz::FilterId::GameBoy); + for (int i = 0; i < vw * vh; ++i) { + assert(is_dmg_olive(vf[i * 3 + 0], vf[i * 3 + 1], vf[i * 3 + 2])); + } + + // 1600x1200 check: block = 1600 / 160 = 10 -> identical pixels inside 10x10 block + const int hw = 1600; + const int hh = 1200; + std::vector hi(static_cast(hw) * hh * 3); + for (int y = 0; y < hh; ++y) { + for (int x = 0; x < hw; ++x) { + const size_t idx = (static_cast(y) * hw + x) * 3; + hi[idx + 0] = static_cast((x * 7 + y * 13) & 0xFF); + hi[idx + 1] = static_cast((x * 3 + y * 11) & 0xFF); + hi[idx + 2] = static_cast((x * 5 + y * 17) & 0xFF); + } + } + cz::apply_filter_rgb24(hi.data(), hw, hh, cz::FilterId::GameBoy); + + // Check every pixel is strictly one of the 4 DMG colors and every 10x10 block is uniform + for (int by = 0; by < hh; by += 10) { + for (int bx = 0; bx < hw; bx += 10) { + const size_t ref_idx = (static_cast(by) * hw + bx) * 3; + const uint8_t rr = hi[ref_idx + 0]; + const uint8_t rg = hi[ref_idx + 1]; + const uint8_t rb = hi[ref_idx + 2]; + assert(is_dmg_olive(rr, rg, rb)); + for (int dy = 0; dy < 10; ++dy) { + for (int dx = 0; dx < 10; ++dx) { + const size_t idx = (static_cast(by + dy) * hw + (bx + dx)) * 3; + assert(hi[idx + 0] == rr); + assert(hi[idx + 1] == rg); + assert(hi[idx + 2] == rb); + } + } + } + } + } +} + +void test_scale_crop_loupe() { + const int src_w = 640; + const int src_h = 480; + std::vector src(static_cast(src_w) * src_h * 3, 0); + + // Outer frame: pure red (255, 0, 0). Central 50%x50% [160..480) x [120..360): pure green (0, 255, 0) + for (int y = 0; y < src_h; ++y) { + for (int x = 0; x < src_w; ++x) { + const size_t idx = (static_cast(y) * src_w + x) * 3; + const bool in_center = + (x >= src_w / 4 && x < (3 * src_w) / 4 && y >= src_h / 4 && + y < (3 * src_h) / 4); + if (in_center) { + src[idx + 0] = 0; + src[idx + 1] = 255; + src[idx + 2] = 0; + } else { + src[idx + 0] = 255; + src[idx + 1] = 0; + src[idx + 2] = 0; + } + } + } + + const int dst_w = 226; + const int dst_h = 170; + std::vector dst(static_cast(dst_w) * dst_h * 3, 0); + + // With loupe_factor = 1.0f, corners should be red and center should be green + cz::scale_crop_rgb24(src.data(), src_w, src_h, dst.data(), dst_w, dst_h, 1.0f); + assert(dst[0] == 255 && dst[1] == 0 && dst[2] == 0); + const size_t c_idx = (static_cast(dst_h / 2) * dst_w + (dst_w / 2)) * 3; + assert(dst[c_idx] == 0 && dst[c_idx + 1] == 255 && dst[c_idx + 2] == 0); + + // With loupe_factor = 2.0f, crops central 50%x50%, so all 226x170 pixels must be pure green + std::fill(dst.begin(), dst.end(), 0); + cz::scale_crop_rgb24(src.data(), src_w, src_h, dst.data(), dst_w, dst_h, 2.0f); + for (int i = 0; i < dst_w * dst_h; ++i) { + assert(dst[i * 3 + 0] == 0); + assert(dst[i * 3 + 1] == 255); + assert(dst[i * 3 + 2] == 0); + } +} + +void test_jpeg_roundtrip_none_passthrough_and_corrupt_cleanup() { + TempDir tmp("jpeg"); + std::string err; + + // 1. Encode synthetic 1600x1200 image to .IMG1.jpg.tmp and test FilterId::None passthrough + const int w = 1600; + const int h = 1200; + std::vector rgb(static_cast(w) * h * 3); + for (int y = 0; y < h; ++y) { + for (int x = 0; x < w; ++x) { + const size_t idx = (static_cast(y) * w + x) * 3; + rgb[idx + 0] = static_cast((x * 255) / (w - 1)); + rgb[idx + 1] = static_cast((y * 255) / (h - 1)); + rgb[idx + 2] = 200; + } + } + + const std::string tmp1 = tmp.path + "/.IMG1.jpg.tmp"; + const std::string fin1 = tmp.path + "/IMG1.jpg"; + assert(cz::encode_jpeg_rgb24(tmp1, rgb.data(), w, h, 92, err)); + assert(fs::exists(tmp1)); + const std::string raw_tmp1 = read_bytes(tmp1); + assert(!raw_tmp1.empty()); + + assert(cz::finalize_still_photo(tmp1, fin1, cz::FilterId::None, err)); + assert(!fs::exists(tmp1)); + assert(fs::exists(fin1)); + assert(read_bytes(fin1) == raw_tmp1); // exact byte-for-byte passthrough + + // Full decode check + cz::RgbImage full; + assert(cz::decode_jpeg_rgb24(fin1, full, err)); + assert(full.width == w); + assert(full.height == h); + assert(full.rgb24.size() == static_cast(w) * h * 3); + + // Scaled decode check via libjpeg scale_denom + cz::RgbImage scaled; + assert(cz::decode_jpeg_scaled_rgb24(fin1, 226, 170, scaled, err)); + assert(scaled.width > 0 && scaled.height > 0); + assert(scaled.width < w && scaled.height < h); + assert(scaled.width >= 226 && scaled.height >= 170); + assert(scaled.rgb24.size() == + static_cast(scaled.width) * scaled.height * 3); + + // 2. GameBoy still finalization bakes DMG colors into final_path + const std::string tmp2 = tmp.path + "/.IMG2.jpg.tmp"; + const std::string fin2 = tmp.path + "/IMG2.jpg"; + assert(cz::encode_jpeg_rgb24(tmp2, rgb.data(), w, h, 92, err)); + assert(cz::finalize_still_photo(tmp2, fin2, cz::FilterId::GameBoy, err)); + assert(!fs::exists(tmp2)); + assert(fs::exists(fin2)); + + cz::RgbImage gb_decoded; + assert(cz::decode_jpeg_rgb24(fin2, gb_decoded, err)); + assert(gb_decoded.width == w && gb_decoded.height == h); + // Sample points across image to verify DMG olive tones were baked in + for (int y = 5; y < h; y += 120) { + for (int x = 5; x < w; x += 160) { + const size_t idx = (static_cast(y) * w + x) * 3; + assert(is_near_dmg_olive(gb_decoded.rgb24[idx + 0], + gb_decoded.rgb24[idx + 1], + gb_decoded.rgb24[idx + 2])); + } + } + + // 3. Corrupt .tmp cleans up .tmp and leaves no final_path (and no crash/exit) + const std::string bad_tmp = tmp.path + "/.BAD.jpg.tmp"; + const std::string bad_fin = tmp.path + "/BAD.jpg"; + write_bytes(bad_tmp, "not_a_valid_jpeg_stream_12345"); + assert(!cz::finalize_still_photo(bad_tmp, bad_fin, cz::FilterId::BW, err)); + assert(!err.empty()); + assert(!fs::exists(bad_tmp)); + assert(!fs::exists(bad_fin)); + assert(!fs::exists(bad_tmp + ".filtered.tmp")); + + // Corrupt decode_jpeg_rgb24 returns false cleanly + cz::RgbImage bad_img; + const std::string bad_src = tmp.path + "/corrupt.jpg"; + write_bytes(bad_src, "\xff\xd8\xff\xe0garbage"); + assert(!cz::decode_jpeg_rgb24(bad_src, bad_img, err)); + assert(!err.empty()); +} + +} // namespace + +int main() { + test_filter_cycle_and_serialization(); + test_all_nine_filters_pixel_behavior(); + test_scale_crop_loupe(); + test_jpeg_roundtrip_none_passthrough_and_corrupt_cleanup(); + std::cout << "test_filters_and_jpeg: all tests passed\n"; + return 0; +}