Image decoding lived in the GL texture file and had no limits: a file of any size was read whole, stb and libwebp allocated whatever the header claimed (a WebP alone up to 1 GB), and a GIF was decoded at full size, every frame, before the 300-frame cap. A 720p 150-frame GIF avatar cost 0.2-1.5 s and 140-370 MB on the UI thread. stb's GIF loader also read before the start of its buffer on disposal-3 frames, and when a long GIF ran out of memory it freed the frame delays that the caller then freed again (an abort). Decoding, and the stb implementation, now live in the GL-free util/image_decode_core, safe on any thread: - the header is probed first; stills above 256 MP, any GIF or animated WebP canvas above 32 Mi px, and files above 256 MiB are rejected before anything is allocated (real photos, 200 MP phone shots and wide panoramas still load); - a GIF decodes one composited frame at a time, downscaled as it goes, and stops at the frame cap: peak memory is stb's working buffers, two canvases and the small frames; a truncated GIF keeps the frames decoded so far; - a header stb cannot read means "unsupported", never a blind decode; - decodes above 16 MP run one at a time; a decode can be cancelled between frames. util::StartImageDecode runs one decode on a detached worker that owns its job and its lane's in-flight counter, so nothing waits at exit; the next commits move avatars and the image picker onto it. The limits apply now to avatars and the picker's hover previews; thumbnails and avatar imports get them when they move to workers. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
132 lines
6.3 KiB
C++
132 lines
6.3 KiB
C++
// DragonX Wallet - ImGui Edition
|
|
// Copyright 2024-2026 The Hush Developers
|
|
// Released under the GPLv3
|
|
//
|
|
// GL-free image decoding (stb_image + libwebp) and a tiny off-thread decode launcher. Everything here is
|
|
// safe to call from any thread. GPU upload lives in texture_loader.{h,cpp} and must stay on the UI thread.
|
|
|
|
#pragma once
|
|
|
|
#include "image_decode_policy.h"
|
|
|
|
#include <atomic>
|
|
#include <cstddef>
|
|
#include <cstdint>
|
|
#include <functional>
|
|
#include <memory>
|
|
#include <string>
|
|
#include <vector>
|
|
|
|
namespace dragonx {
|
|
namespace util {
|
|
|
|
enum class ImageStatus {
|
|
Ok = 0,
|
|
ReadError, // missing / unreadable / empty file
|
|
TooLarge, // file bytes or pixel area above ImageLimits (or out of memory)
|
|
Unsupported, // not a format we decode, or the header is unreadable
|
|
DecodeError, // header ok, pixel decode failed
|
|
Cancelled, // the job's cancel flag was set
|
|
PostFailed, // decoded fine, but the afterDecode hook failed (e.g. the avatar copy)
|
|
};
|
|
|
|
/**
|
|
* @brief Downscaled RGBA frame sequence for an image (1 frame for stills, N for animations).
|
|
*/
|
|
struct AnimFrames {
|
|
std::vector<std::vector<unsigned char>> frames; ///< each is w*h*4 RGBA (already downscaled)
|
|
std::vector<float> delaysSec; ///< per-frame duration in seconds (parallel to frames)
|
|
int w = 0;
|
|
int h = 0;
|
|
bool animated = false; ///< the SOURCE has >1 frame (even if fewer were decoded); set on success
|
|
int srcW = 0, srcH = 0; ///< source canvas size; set on success
|
|
};
|
|
|
|
/// Decode from memory. Probes the header first and rejects anything over `limits` before allocating
|
|
/// pixels. GIFs decode one composited frame at a time and stop at maxFrames; animated WebP via libwebp's
|
|
/// demuxer; everything else (and APNG's default image) as one still. Frames are box-downscaled to
|
|
/// limits.stillMax / limits.animMax. `cancel` (may be null) is checked before decoding and between frames.
|
|
/// On any non-Ok status `out` is empty.
|
|
ImageStatus DecodeAnimatedFromMemory(const unsigned char* data, std::size_t len, int maxFrames,
|
|
const ImageLimits& limits, const std::atomic<bool>* cancel,
|
|
AnimFrames& out);
|
|
|
|
/// As above, reading `path` first (its size is checked against limits.maxFileBytes BEFORE the read).
|
|
ImageStatus LoadAnimatedRGBAEx(const char* path, int maxFrames, const ImageLimits& limits,
|
|
const std::atomic<bool>* cancel, AnimFrames& out);
|
|
|
|
/// Back-compat: default limits, no cancel. False on any failure.
|
|
bool LoadAnimatedRGBA(const char* path, int maxFrames, AnimFrames& out);
|
|
|
|
/// Cheap animation probe (GIF block walk / WebPGetFeatures) after reading the file.
|
|
bool IsAnimatedImageFile(const char* path);
|
|
|
|
/// Whole-file read. maxBytes == 0 = unlimited; TooLarge is reported before any allocation.
|
|
ImageStatus ReadFileCapped(const char* path, std::uint64_t maxBytes, std::vector<unsigned char>& buf);
|
|
bool ReadFileToBuffer(const char* path, std::vector<unsigned char>& buf);
|
|
|
|
/// Decode to a fresh RGBA8 buffer (free with FreeRawPixels). nullptr on failure. No limits.
|
|
unsigned char* DecodeImageRGBA(const unsigned char* data, std::size_t len, int* outW, int* outH);
|
|
|
|
/**
|
|
* @brief Load raw RGBA pixel data from an image file (no GPU texture, no limits).
|
|
* @return Pointer to RGBA pixels (caller must free with FreeRawPixels), or nullptr on failure
|
|
*/
|
|
unsigned char* LoadRawPixelsFromFile(const char* path, int* outW, int* outH);
|
|
|
|
/**
|
|
* @brief Load raw RGBA pixel data from in-memory compressed image data (no GPU texture, no limits).
|
|
* @return Pointer to RGBA pixels (caller must free with FreeRawPixels), or nullptr on failure
|
|
*/
|
|
unsigned char* LoadRawPixelsFromMemory(const unsigned char* data, std::size_t dataSize, int* outW, int* outH);
|
|
|
|
/**
|
|
* @brief Free pixels returned by LoadRawPixelsFromFile / LoadRawPixelsFromMemory / DecodeImageRGBA.
|
|
*/
|
|
void FreeRawPixels(unsigned char* pixels);
|
|
|
|
// ---- Off-thread decode ------------------------------------------------------------------------------
|
|
|
|
/// One background decode. The worker writes result/status/outPath, then release-stores `done`; the UI
|
|
/// reads them only after finished() returned true, and may then move `result` out. The UI never writes
|
|
/// the payload while the worker runs; it may set `cancel` at any time.
|
|
struct ImageDecodeJob {
|
|
std::atomic<bool> done{false};
|
|
std::atomic<bool> cancel{false};
|
|
AnimFrames result; // empty unless status == Ok
|
|
ImageStatus status = ImageStatus::DecodeError;
|
|
std::string outPath; // afterDecode's return value ("" if unused / failed)
|
|
|
|
bool finished() const { return done.load(std::memory_order_acquire); }
|
|
bool ok() const { return finished() && status == ImageStatus::Ok; }
|
|
};
|
|
using ImageDecodeJobPtr = std::shared_ptr<ImageDecodeJob>;
|
|
|
|
/// Runs on the worker after a successful decode (e.g. copy the file). "" means failure (PostFailed).
|
|
/// Must not touch UI state; capture everything it needs BY VALUE.
|
|
using ImageAfterDecodeFn = std::function<std::string(const std::string& path)>;
|
|
|
|
/// Caps how many decodes of one kind run at once. Use from the UI thread only. The counter is heap-owned
|
|
/// and co-owned by every worker started on the lane, so a detached worker still running at process exit
|
|
/// never touches a destroyed static (the rule from commit 6f0f95f).
|
|
class ImageDecodeLane {
|
|
public:
|
|
explicit ImageDecodeLane(int cap) : cap_(cap) {}
|
|
int inFlight() const { return count_->load(std::memory_order_acquire); }
|
|
bool full() const { return inFlight() >= cap_; }
|
|
std::shared_ptr<std::atomic<int>> counter() const { return count_; }
|
|
private:
|
|
int cap_;
|
|
std::shared_ptr<std::atomic<int>> count_ = std::make_shared<std::atomic<int>>(0);
|
|
};
|
|
|
|
/// Start decoding `path` on a detached worker if `lane` has a free slot. Returns nullptr when the lane is
|
|
/// full (show a placeholder, request a frame, retry next frame). Never blocks. If no thread can be created
|
|
/// it returns a job that is already finished with DecodeError (shown as a failed image, never retried in a
|
|
/// loop). Results are polled; the caller keeps the render loop awake with material::RequestProgressFrame().
|
|
ImageDecodeJobPtr StartImageDecode(ImageDecodeLane& lane, std::string path, int maxFrames,
|
|
const ImageLimits& limits, ImageAfterDecodeFn afterDecode = {});
|
|
|
|
} // namespace util
|
|
} // namespace dragonx
|