Add wuffs_aux::DecodeImage

This commit is contained in:
Nigel Tao committed 2021-03-03 23:19:58 +11:00
1 parent ccee207661
commit 04f8686989
9 files changed
+1044 -319

No files matched your search

+82 -283
View File
@@ -53,6 +53,8 @@ The Escape key quits.
// code simply isn't compiled.
#define WUFFS_CONFIG__MODULES
#define WUFFS_CONFIG__MODULE__ADLER32
#define WUFFS_CONFIG__MODULE__AUX__BASE
#define WUFFS_CONFIG__MODULE__AUX__IMAGE
#define WUFFS_CONFIG__MODULE__BASE
#define WUFFS_CONFIG__MODULE__BMP
#define WUFFS_CONFIG__MODULE__CRC32
@@ -70,7 +72,7 @@ The Escape key quits.
#include "../../release/c/wuffs-unsupported-snapshot.c"
// X11 limits its image dimensions to uint16_t.
#define MAX_DIMENSION 65535
#define MAX_INCL_DIMENSION 65535
#define NUM_BACKGROUND_COLORS 3
#define SRC_BUFFER_ARRAY_SIZE (64 * 1024)
@@ -81,313 +83,110 @@ wuffs_base__color_u32_argb_premul g_background_colors[NUM_BACKGROUND_COLORS] = {
0xFFA9009A,
};
FILE* g_file = NULL;
const char* g_filename = NULL;
uint32_t g_width = 0;
uint32_t g_height = 0;
wuffs_base__slice_u8 g_workbuf_slice = {0};
wuffs_base__slice_u8 g_pixbuf_slice = {0};
wuffs_base__pixel_buffer g_pixbuf = {0};
uint8_t g_src_buffer_array[SRC_BUFFER_ARRAY_SIZE] = {0};
wuffs_base__io_buffer g_src = {0};
wuffs_base__image_config g_image_config = {0};
wuffs_base__frame_config g_frame_config = {0};
wuffs_base__image_decoder* g_image_decoder = NULL;
wuffs_aux::MemOwner g_pixbuf_mem_owner(nullptr, &free);
wuffs_base__slice_u8 g_pixbuf_mem_slice = {0};
uint32_t g_background_color_index = 0;
union {
wuffs_bmp__decoder bmp;
wuffs_gif__decoder gif;
wuffs_nie__decoder nie;
wuffs_png__decoder png;
wuffs_wbmp__decoder wbmp;
} g_potential_decoders;
bool //
read_more_src() {
if (g_src.meta.closed) {
printf("%s: unexpected end of file\n", g_filename);
return false;
}
wuffs_base__io_buffer__compact(&g_src);
g_src.meta.wi += fread(g_src.data.ptr + g_src.meta.wi, sizeof(uint8_t),
g_src.data.len - g_src.meta.wi, g_file);
if (feof(g_file)) {
g_src.meta.closed = true;
} else if (ferror(g_file)) {
printf("%s: read error\n", g_filename);
return false;
}
return true;
}
bool //
load_image_type() {
int32_t fourcc = 0;
while (true) {
fourcc = wuffs_base__magic_number_guess_fourcc(
wuffs_base__io_buffer__reader_slice(&g_src));
if (fourcc >= 0) {
break;
} else if (wuffs_base__io_buffer__writer_length(&g_src) == 0) {
printf("%s: could not determine file format\n", g_filename);
return false;
} else if (!read_more_src()) {
return false;
class Callbacks : public wuffs_aux::DecodeImageCallbacks {
wuffs_base__image_decoder::unique_ptr //
OnImageFormat(uint32_t fourcc, wuffs_base__slice_u8 prefix) override {
switch (fourcc) {
case WUFFS_BASE__FOURCC__BMP:
return wuffs_bmp__decoder::alloc_as__wuffs_base__image_decoder();
case WUFFS_BASE__FOURCC__GIF:
return wuffs_gif__decoder::alloc_as__wuffs_base__image_decoder();
case WUFFS_BASE__FOURCC__NIE:
return wuffs_nie__decoder::alloc_as__wuffs_base__image_decoder();
case WUFFS_BASE__FOURCC__PNG: {
auto dec = wuffs_png__decoder::alloc_as__wuffs_base__image_decoder();
dec->set_quirk_enabled(WUFFS_BASE__QUIRK_IGNORE_CHECKSUM, true);
return dec;
}
case WUFFS_BASE__FOURCC__WBMP:
return wuffs_wbmp__decoder::alloc_as__wuffs_base__image_decoder();
}
return wuffs_base__image_decoder::unique_ptr(nullptr, &free);
}
wuffs_base__status status;
switch (fourcc) {
case WUFFS_BASE__FOURCC__WBMP:
status = wuffs_wbmp__decoder__initialize(
&g_potential_decoders.wbmp, sizeof g_potential_decoders.wbmp,
WUFFS_VERSION, WUFFS_INITIALIZE__DEFAULT_OPTIONS);
if (!wuffs_base__status__is_ok(&status)) {
printf("%s: %s\n", g_filename, wuffs_base__status__message(&status));
return false;
}
g_image_decoder =
wuffs_wbmp__decoder__upcast_as__wuffs_base__image_decoder(
&g_potential_decoders.wbmp);
break;
case WUFFS_BASE__FOURCC__BMP:
status = wuffs_bmp__decoder__initialize(
&g_potential_decoders.bmp, sizeof g_potential_decoders.bmp,
WUFFS_VERSION, WUFFS_INITIALIZE__DEFAULT_OPTIONS);
if (!wuffs_base__status__is_ok(&status)) {
printf("%s: %s\n", g_filename, wuffs_base__status__message(&status));
return false;
}
g_image_decoder =
wuffs_bmp__decoder__upcast_as__wuffs_base__image_decoder(
&g_potential_decoders.bmp);
break;
case WUFFS_BASE__FOURCC__GIF:
status = wuffs_gif__decoder__initialize(
&g_potential_decoders.gif, sizeof g_potential_decoders.gif,
WUFFS_VERSION, WUFFS_INITIALIZE__DEFAULT_OPTIONS);
if (!wuffs_base__status__is_ok(&status)) {
printf("%s: %s\n", g_filename, wuffs_base__status__message(&status));
return false;
}
g_image_decoder =
wuffs_gif__decoder__upcast_as__wuffs_base__image_decoder(
&g_potential_decoders.gif);
break;
case WUFFS_BASE__FOURCC__NIE:
status = wuffs_nie__decoder__initialize(
&g_potential_decoders.nie, sizeof g_potential_decoders.nie,
WUFFS_VERSION, WUFFS_INITIALIZE__DEFAULT_OPTIONS);
if (!wuffs_base__status__is_ok(&status)) {
printf("%s: %s\n", g_filename, wuffs_base__status__message(&status));
return false;
}
g_image_decoder =
wuffs_nie__decoder__upcast_as__wuffs_base__image_decoder(
&g_potential_decoders.nie);
break;
case WUFFS_BASE__FOURCC__PNG:
status = wuffs_png__decoder__initialize(
&g_potential_decoders.png, sizeof g_potential_decoders.png,
WUFFS_VERSION, WUFFS_INITIALIZE__DEFAULT_OPTIONS);
if (!wuffs_base__status__is_ok(&status)) {
printf("%s: %s\n", g_filename, wuffs_base__status__message(&status));
return false;
}
g_image_decoder =
wuffs_png__decoder__upcast_as__wuffs_base__image_decoder(
&g_potential_decoders.png);
break;
default:
printf("%s: unrecognized file format\n", g_filename);
return false;
}
return true;
}
bool //
load_image_config() {
// Decode the wuffs_base__image_config.
while (true) {
wuffs_base__status status = wuffs_base__image_decoder__decode_image_config(
g_image_decoder, &g_image_config, &g_src);
if (status.repr == NULL) {
break;
} else if (status.repr != wuffs_base__suspension__short_read) {
// TODO: handle wuffs_base__note__i_o_redirect.
printf("%s: %s\n", g_filename, wuffs_base__status__message(&status));
return false;
DecodeImageCallbacks::AllocResult //
OnImageConfig(const wuffs_base__image_config& image_config) {
uint32_t w = image_config.pixcfg.width();
uint32_t h = image_config.pixcfg.height();
if ((w == 0) || (h == 0)) {
return DecodeImageCallbacks::AllocResult("");
}
uint64_t len = image_config.pixcfg.pixbuf_len();
if ((len == 0) || (SIZE_MAX < len)) {
return DecodeImageCallbacks::AllocResult(
wuffs_aux::DecodeImage_UnsupportedPixelConfiguration);
}
void* ptr = malloc((size_t)len);
if (!ptr) {
return DecodeImageCallbacks::AllocResult(
wuffs_aux::DecodeImage_OutOfMemory);
}
if (!read_more_src()) {
return false;
}
}
// Read the dimensions.
uint32_t w = wuffs_base__pixel_config__width(&g_image_config.pixcfg);
uint32_t h = wuffs_base__pixel_config__height(&g_image_config.pixcfg);
if ((w > MAX_DIMENSION) || (h > MAX_DIMENSION)) {
printf("%s: image is too large\n", g_filename);
return false;
}
g_width = w;
g_height = h;
// Override the image's native pixel format to be BGRA_PREMUL.
wuffs_base__pixel_config__set(&g_image_config.pixcfg,
WUFFS_BASE__PIXEL_FORMAT__BGRA_PREMUL,
WUFFS_BASE__PIXEL_SUBSAMPLING__NONE, w, h);
// Allocate the work buffer memory.
uint64_t workbuf_len =
wuffs_base__image_decoder__workbuf_len(g_image_decoder).max_incl;
if (workbuf_len > SIZE_MAX) {
printf("%s: out of memory\n", g_filename);
return false;
}
if (workbuf_len > 0) {
void* p = malloc(workbuf_len);
if (!p) {
printf("%s: out of memory\n", g_filename);
return false;
}
g_workbuf_slice.ptr = (uint8_t*)p;
g_workbuf_slice.len = workbuf_len;
}
// Allocate the pixel buffer memory.
uint64_t num_pixels = ((uint64_t)w) * ((uint64_t)h);
if (num_pixels > (SIZE_MAX / sizeof(wuffs_base__color_u32_argb_premul))) {
printf("%s: image is too large\n", g_filename);
return false;
}
size_t n = num_pixels * sizeof(wuffs_base__color_u32_argb_premul);
void* p = malloc(n);
if (!p) {
printf("%s: out of memory\n", g_filename);
return false;
}
{
uint8_t* ptr = (uint8_t*)p;
// Fill in the background color. The default OnImageConfig implementation
// fills with zeroes (transparent black).
wuffs_base__color_u32_argb_premul color =
g_background_colors[g_background_color_index];
for (size_t i = 0; i < num_pixels; i++) {
wuffs_base__poke_u32le__no_bounds_check(ptr, color);
ptr += 4;
uint8_t* p4 = (uint8_t*)ptr;
size_t n4 = ((size_t)len) / 4;
for (size_t i = 0; i < n4; i++) {
wuffs_base__poke_u32le__no_bounds_check(p4, color);
p4 += 4;
}
return DecodeImageCallbacks::AllocResult(
wuffs_aux::MemOwner(ptr, &free),
wuffs_base__make_slice_u8((uint8_t*)ptr, (size_t)len));
}
g_pixbuf_slice.ptr = (uint8_t*)p;
g_pixbuf_slice.len = n;
// Configure the wuffs_base__pixel_buffer struct.
wuffs_base__status status = wuffs_base__pixel_buffer__set_from_slice(
&g_pixbuf, &g_image_config.pixcfg, g_pixbuf_slice);
if (!wuffs_base__status__is_ok(&status)) {
printf("%s: %s\n", g_filename, wuffs_base__status__message(&status));
return false;
}
return true;
}
bool //
load_image_frame() {
// Decode the wuffs_base__frame_config.
while (true) {
wuffs_base__status status = wuffs_base__image_decoder__decode_frame_config(
g_image_decoder, &g_frame_config, &g_src);
if (status.repr == NULL) {
break;
} else if (status.repr != wuffs_base__suspension__short_read) {
printf("%s: %s\n", g_filename, wuffs_base__status__message(&status));
return false;
}
if (!read_more_src()) {
return false;
}
}
// From here on, this function always returns true. If we get this far, we
// still display a partial image, even if we encounter an error.
// Decode the frame (the pixels).
while (true) {
wuffs_base__status status = wuffs_base__image_decoder__decode_frame(
g_image_decoder, &g_pixbuf, &g_src,
wuffs_base__frame_config__overwrite_instead_of_blend(&g_frame_config)
? WUFFS_BASE__PIXEL_BLEND__SRC
: WUFFS_BASE__PIXEL_BLEND__SRC_OVER,
g_workbuf_slice, NULL);
if (status.repr == NULL) {
break;
} else if (status.repr != wuffs_base__suspension__short_read) {
printf("%s: %s\n", g_filename, wuffs_base__status__message(&status));
return true;
}
if (!read_more_src()) {
return true;
}
}
uint32_t w = wuffs_base__pixel_config__width(&g_image_config.pixcfg);
uint32_t h = wuffs_base__pixel_config__height(&g_image_config.pixcfg);
printf("%s: ok (%" PRIu32 " x %" PRIu32 ")\n", g_filename, w, h);
return true;
}
};
bool //
load_image(const char* filename) {
if (g_workbuf_slice.ptr != NULL) {
free(g_workbuf_slice.ptr);
g_workbuf_slice.ptr = NULL;
g_workbuf_slice.len = 0;
}
if (g_pixbuf_slice.ptr != NULL) {
free(g_pixbuf_slice.ptr);
g_pixbuf_slice.ptr = NULL;
g_pixbuf_slice.len = 0;
}
g_width = 0;
g_height = 0;
g_src.data.ptr = g_src_buffer_array;
g_src.data.len = SRC_BUFFER_ARRAY_SIZE;
g_src.meta.wi = 0;
g_src.meta.ri = 0;
g_src.meta.pos = 0;
g_src.meta.closed = false;
g_image_config = wuffs_base__null_image_config();
g_image_decoder = NULL;
g_file = stdin;
g_filename = "<stdin>";
FILE* file = stdin;
const char* adj_filename = "<stdin>";
if (filename) {
FILE* f = fopen(filename, "r");
if (f == NULL) {
printf("%s: could not open file\n", filename);
return false;
}
g_file = f;
g_filename = filename;
file = f;
adj_filename = filename;
}
bool ret = load_image_type() && load_image_config() && load_image_frame();
g_width = 0;
g_height = 0;
g_pixbuf_mem_owner.reset();
g_pixbuf_mem_slice = wuffs_base__empty_slice_u8();
Callbacks callbacks;
wuffs_aux::sync_io::FileInput input(file);
wuffs_aux::DecodeImageResult res = wuffs_aux::DecodeImage(
callbacks, input, WUFFS_BASE__PIXEL_FORMAT__BGRA_PREMUL,
// Use PIXEL_BLEND__SRC_OVER, not the default PIXEL_BLEND__SRC, because
// we override OnImageConfig to fill in the background color.
WUFFS_BASE__PIXEL_BLEND__SRC_OVER, MAX_INCL_DIMENSION);
if (filename) {
fclose(g_file);
g_file = NULL;
fclose(file);
}
return ret;
g_width = res.pixbuf.pixcfg.width();
g_height = res.pixbuf.pixcfg.height();
g_pixbuf_mem_owner = std::move(res.pixbuf_mem_owner);
g_pixbuf_mem_slice = res.pixbuf_mem_slice;
if (res.error_message.empty()) {
printf("%s: ok (%" PRIu32 " x %" PRIu32 ")\n", adj_filename, g_width,
g_height);
} else {
printf("%s: %s\n", adj_filename, res.error_message.c_str());
}
return res.pixbuf.pixcfg.is_valid();
}
// ---------------------------------------------------------------------
@@ -453,7 +252,7 @@ load(xcb_connection_t* c,
xcb_create_pixmap(c, s->root_depth, g_pixmap, w, g_width, g_height);
xcb_image_t* image = xcb_image_create_native(
c, g_width, g_height, XCB_IMAGE_FORMAT_Z_PIXMAP, s->root_depth, NULL,
g_pixbuf_slice.len, g_pixbuf_slice.ptr);
g_pixbuf_mem_slice.len, g_pixbuf_mem_slice.ptr);
xcb_image_put(c, g_pixmap, g, image, 0, 0, 0);
xcb_image_destroy(image);
return true;
+7
View File
@@ -27,6 +27,13 @@ namespace wuffs_aux {
using IOBuffer = wuffs_base__io_buffer;
// MemOwner represents ownership of some memory. Dynamically allocated memory
// (e.g. from malloc or new) is typically paired with free or delete, invoked
// when the std::unique_ptr is destroyed. Statically allocated memory might use
// MemOwner(nullptr, &free), even if that statically allocated memory is not
// nullptr, since calling free(nullptr) is a no-op.
using MemOwner = std::unique_ptr<void, decltype(&free)>;
namespace sync_io {
// --------
+6 -7
View File
@@ -64,9 +64,8 @@ class DecodeCborCallbacks {
// as DecodeCbor may then de-allocate the backing array.
//
// The default Done implementation is a no-op.
virtual void Done(DecodeCborResult& result,
sync_io::Input& input,
IOBuffer& buffer);
virtual void //
Done(DecodeCborResult& result, sync_io::Input& input, IOBuffer& buffer);
};
// DecodeCbor calls callbacks based on the CBOR-formatted data in input.
@@ -75,9 +74,9 @@ class DecodeCborCallbacks {
// the number of bytes consumed. On failure, error_message is non-empty and
// cursor_position is the location of the error. That error may be a content
// error (invalid CBOR) or an input error (e.g. network failure).
DecodeCborResult DecodeCbor(
DecodeCborCallbacks& callbacks,
sync_io::Input& input,
wuffs_base__slice_u32 quirks = wuffs_base__empty_slice_u32());
DecodeCborResult //
DecodeCbor(DecodeCborCallbacks& callbacks,
sync_io::Input& input,
wuffs_base__slice_u32 quirks = wuffs_base__empty_slice_u32());
} // namespace wuffs_aux
+306
View File
@@ -0,0 +1,306 @@
// After editing this file, run "go generate" in the ../data directory.
// Copyright 2021 The Wuffs Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ---------------- Auxiliary - Image
#if !defined(WUFFS_CONFIG__MODULES) || defined(WUFFS_CONFIG__MODULE__AUX__IMAGE)
#include <utility>
namespace wuffs_aux {
DecodeImageResult::DecodeImageResult(MemOwner&& pixbuf_mem_owner0,
wuffs_base__slice_u8 pixbuf_mem_slice0,
wuffs_base__pixel_buffer pixbuf0,
std::string&& error_message0)
: pixbuf_mem_owner(std::move(pixbuf_mem_owner0)),
pixbuf_mem_slice(pixbuf_mem_slice0),
pixbuf(pixbuf0),
error_message(std::move(error_message0)) {}
DecodeImageResult::DecodeImageResult(std::string&& error_message0)
: pixbuf_mem_owner(nullptr, &free),
pixbuf_mem_slice(wuffs_base__empty_slice_u8()),
pixbuf({0}),
error_message(std::move(error_message0)) {}
DecodeImageCallbacks::AllocResult::AllocResult(MemOwner&& mem_owner0,
wuffs_base__slice_u8 mem_slice0)
: mem_owner(std::move(mem_owner0)),
mem_slice(mem_slice0),
error_message("") {}
DecodeImageCallbacks::AllocResult::AllocResult(std::string&& error_message0)
: mem_owner(nullptr, &free),
mem_slice(wuffs_base__empty_slice_u8()),
error_message(std::move(error_message0)) {}
DecodeImageCallbacks::AllocResult //
DecodeImageCallbacks::OnImageConfig(
const wuffs_base__image_config& image_config) {
uint32_t w = image_config.pixcfg.width();
uint32_t h = image_config.pixcfg.height();
if ((w == 0) || (h == 0)) {
return AllocResult("");
}
uint64_t len = image_config.pixcfg.pixbuf_len();
if ((len == 0) || (SIZE_MAX < len)) {
return AllocResult(DecodeImage_UnsupportedPixelConfiguration);
}
void* ptr = calloc((size_t)len, 1);
if (!ptr) {
return AllocResult(DecodeImage_OutOfMemory);
}
return AllocResult(MemOwner(ptr, &free),
wuffs_base__make_slice_u8((uint8_t*)ptr, (size_t)len));
}
DecodeImageCallbacks::AllocResult //
DecodeImageCallbacks::AllocWorkbuf(wuffs_base__range_ii_u64 len) {
if (len.max_incl == 0) {
return DecodeImageCallbacks::AllocResult("");
} else if (SIZE_MAX < len.max_incl) {
return DecodeImageCallbacks::AllocResult(DecodeImage_OutOfMemory);
}
void* p = calloc((size_t)len.max_incl, 1);
if (!p) {
return DecodeImageCallbacks::AllocResult(DecodeImage_OutOfMemory);
}
return DecodeImageCallbacks::AllocResult(
MemOwner(p, &free),
wuffs_base__make_slice_u8((uint8_t*)p, (size_t)len.max_incl));
}
void //
DecodeImageCallbacks::Done(DecodeImageResult& result,
sync_io::Input& input,
IOBuffer& buffer) {}
const char DecodeImage_BufferIsTooShort[] = //
"wuffs_aux::DecodeImage: buffer is too short";
const char DecodeImage_MaxInclDimensionExceeded[] = //
"wuffs_aux::DecodeImage: max_incl_dimension exceeded";
const char DecodeImage_OutOfMemory[] = //
"wuffs_aux::DecodeImage: out of memory";
const char DecodeImage_UnexpectedEndOfFile[] = //
"wuffs_aux::DecodeImage: unexpected end of file";
const char DecodeImage_UnsupportedImageFormat[] = //
"wuffs_aux::DecodeImage: unsupported image format";
const char DecodeImage_UnsupportedPixelBlend[] = //
"wuffs_aux::DecodeImage: unsupported pixel blend";
const char DecodeImage_UnsupportedPixelConfiguration[] = //
"wuffs_aux::DecodeImage: unsupported pixel configuration";
const char DecodeImage_UnsupportedPixelFormat[] = //
"wuffs_aux::DecodeImage: unsupported pixel format";
// --------
namespace {
DecodeImageResult //
DecodeImage0(DecodeImageCallbacks& callbacks,
sync_io::Input& input,
wuffs_base__io_buffer& io_buf,
uint32_t override_pixel_format_repr,
wuffs_base__pixel_blend pixel_blend,
uint32_t max_incl_dimension) {
// Check args.
switch (override_pixel_format_repr) {
case 0:
case WUFFS_BASE__PIXEL_FORMAT__BGR_565:
case WUFFS_BASE__PIXEL_FORMAT__BGR:
case WUFFS_BASE__PIXEL_FORMAT__BGRA_NONPREMUL:
case WUFFS_BASE__PIXEL_FORMAT__BGRA_PREMUL:
break;
default:
return DecodeImageResult(DecodeImage_UnsupportedPixelFormat);
}
switch (pixel_blend) {
case WUFFS_BASE__PIXEL_BLEND__SRC:
case WUFFS_BASE__PIXEL_BLEND__SRC_OVER:
break;
default:
return DecodeImageResult(DecodeImage_UnsupportedPixelBlend);
}
// Determine the image format.
int32_t fourcc = 0;
while (true) {
fourcc = wuffs_base__magic_number_guess_fourcc(io_buf.reader_slice());
if (fourcc > 0) {
break;
} else if ((fourcc == 0) && (io_buf.reader_length() >= 64)) {
break;
} else if (io_buf.meta.closed || (io_buf.writer_length() == 0)) {
fourcc = 0;
break;
}
std::string error_message = input.CopyIn(&io_buf);
if (!error_message.empty()) {
return DecodeImageResult(std::move(error_message));
}
}
wuffs_base__image_decoder::unique_ptr image_decoder =
callbacks.OnImageFormat(fourcc, io_buf.reader_slice());
if (!image_decoder) {
return DecodeImageResult(DecodeImage_UnsupportedImageFormat);
}
// Decode the image config.
wuffs_base__image_config image_config;
while (true) {
wuffs_base__status id_dic_status =
image_decoder->decode_image_config(&image_config, &io_buf);
if (id_dic_status.repr == NULL) {
break;
} else if (id_dic_status.repr != wuffs_base__suspension__short_read) {
// TODO: handle wuffs_base__note__i_o_redirect.
return DecodeImageResult(id_dic_status.message());
} else if (io_buf.meta.closed) {
return DecodeImageResult(DecodeImage_UnexpectedEndOfFile);
} else {
std::string error_message = input.CopyIn(&io_buf);
if (!error_message.empty()) {
return DecodeImageResult(std::move(error_message));
}
}
}
// Apply the override pixel format.
uint32_t w = image_config.pixcfg.width();
uint32_t h = image_config.pixcfg.height();
if ((w > max_incl_dimension) || (h > max_incl_dimension)) {
return DecodeImageResult(DecodeImage_MaxInclDimensionExceeded);
}
if (override_pixel_format_repr != 0) {
image_config.pixcfg.set(override_pixel_format_repr,
WUFFS_BASE__PIXEL_SUBSAMPLING__NONE, w, h);
}
// Allocate the pixel buffer.
size_t pixbuf_len_min_incl = 0;
if ((w > 0) && (h > 0)) {
pixbuf_len_min_incl = image_config.pixcfg.pixbuf_len();
if (pixbuf_len_min_incl == 0) {
return DecodeImageResult(DecodeImage_UnsupportedPixelFormat);
}
}
DecodeImageCallbacks::AllocResult oic_result =
callbacks.OnImageConfig(image_config);
if (!oic_result.error_message.empty()) {
return DecodeImageResult(std::move(oic_result.error_message));
} else if (oic_result.mem_slice.len < pixbuf_len_min_incl) {
return DecodeImageResult(DecodeImage_BufferIsTooShort);
}
wuffs_base__pixel_buffer pixel_buffer;
wuffs_base__status pb_sfs_status =
pixel_buffer.set_from_slice(&image_config.pixcfg, oic_result.mem_slice);
if (!pb_sfs_status.is_ok()) {
return DecodeImageResult(pb_sfs_status.message());
}
// Allocate the work buffer.
wuffs_base__range_ii_u64 workbuf_len = image_decoder->workbuf_len();
DecodeImageCallbacks::AllocResult alloc_workbuf_result =
callbacks.AllocWorkbuf(workbuf_len);
if (!alloc_workbuf_result.error_message.empty()) {
return DecodeImageResult(std::move(alloc_workbuf_result.error_message));
} else if (alloc_workbuf_result.mem_slice.len < workbuf_len.min_incl) {
return DecodeImageResult(DecodeImage_BufferIsTooShort);
}
// Decode the frame config.
wuffs_base__frame_config frame_config;
while (true) {
wuffs_base__status id_dfc_status =
image_decoder->decode_frame_config(&frame_config, &io_buf);
if (id_dfc_status.repr == NULL) {
break;
} else if (id_dfc_status.repr != wuffs_base__suspension__short_read) {
return DecodeImageResult(id_dfc_status.message());
} else if (io_buf.meta.closed) {
return DecodeImageResult(DecodeImage_UnexpectedEndOfFile);
} else {
std::string error_message = input.CopyIn(&io_buf);
if (!error_message.empty()) {
return DecodeImageResult(std::move(error_message));
}
}
}
// Decode the frame (the pixels).
//
// From here on, always returns the pixel_buffer. If we get this far, we can
// still display a partial image, even if we encounter an error.
std::string message("");
if ((pixel_blend == WUFFS_BASE__PIXEL_BLEND__SRC_OVER) &&
frame_config.overwrite_instead_of_blend()) {
pixel_blend = WUFFS_BASE__PIXEL_BLEND__SRC;
}
while (true) {
wuffs_base__status id_df_status =
image_decoder->decode_frame(&pixel_buffer, &io_buf, pixel_blend,
alloc_workbuf_result.mem_slice, NULL);
if (id_df_status.repr == NULL) {
break;
} else if (id_df_status.repr != wuffs_base__suspension__short_read) {
message = id_df_status.message();
break;
} else if (io_buf.meta.closed) {
message = DecodeImage_UnexpectedEndOfFile;
break;
} else {
std::string error_message = input.CopyIn(&io_buf);
if (!error_message.empty()) {
message = std::move(error_message);
break;
}
}
}
return DecodeImageResult(std::move(oic_result.mem_owner),
oic_result.mem_slice, pixel_buffer,
std::move(message));
}
} // namespace
DecodeImageResult //
DecodeImage(DecodeImageCallbacks& callbacks,
sync_io::Input& input,
uint32_t override_pixel_format_repr,
wuffs_base__pixel_blend pixel_blend,
uint32_t max_incl_dimension) {
wuffs_base__io_buffer* io_buf = input.BringsItsOwnIOBuffer();
wuffs_base__io_buffer fallback_io_buf = wuffs_base__empty_io_buffer();
std::unique_ptr<uint8_t[]> fallback_io_array(nullptr);
if (!io_buf) {
fallback_io_array = std::unique_ptr<uint8_t[]>(new uint8_t[32768]);
fallback_io_buf =
wuffs_base__ptr_u8__writer(fallback_io_array.get(), 32768);
io_buf = &fallback_io_buf;
}
DecodeImageResult result =
DecodeImage0(callbacks, input, *io_buf, override_pixel_format_repr,
pixel_blend, max_incl_dimension);
callbacks.Done(result, input, *io_buf);
return result;
}
} // namespace wuffs_aux
#endif // !defined(WUFFS_CONFIG__MODULES) ||
// defined(WUFFS_CONFIG__MODULE__AUX__IMAGE)
+153
View File
@@ -0,0 +1,153 @@
// After editing this file, run "go generate" in the ../data directory.
// Copyright 2021 The Wuffs Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ---------------- Auxiliary - Image
namespace wuffs_aux {
struct DecodeImageResult {
DecodeImageResult(MemOwner&& pixbuf_mem_owner0,
wuffs_base__slice_u8 pixbuf_mem_slice0,
wuffs_base__pixel_buffer pixbuf0,
std::string&& error_message0);
DecodeImageResult(std::string&& error_message0);
MemOwner pixbuf_mem_owner;
wuffs_base__slice_u8 pixbuf_mem_slice;
wuffs_base__pixel_buffer pixbuf;
std::string error_message;
};
// DecodeImageCallbacks are the callbacks given to DecodeImage. They are always
// called in this order:
// 1. OnImageFormat
// 2. OnImageConfig
// 3. AllocWorkbuf
// 4. Done
//
// It may return early - the third callback might not be invoked if the second
// one fails (returns a non-empty error message) - but the final callback
// (Done) is always invoked.
class DecodeImageCallbacks {
public:
// AllocResult holds a memory allocation (the result of malloc or new, a
// statically allocated pointer, etc), or an error message. The memory is
// de-allocated when mem_owner goes out of scope and is destroyed.
struct AllocResult {
AllocResult(MemOwner&& mem_owner0, wuffs_base__slice_u8 mem_slice0);
AllocResult(std::string&& error_message0);
MemOwner mem_owner;
wuffs_base__slice_u8 mem_slice;
std::string error_message;
};
// OnImageFormat returns the image decoder for the input data's file format.
// Returning a nullptr means failure (DecodeImage_UnsupportedImageFormat).
//
// Common formats will have a non-zero FourCC value, such as
// WUFFS_BASE__FOURCC__JPEG. A zero FourCC code means that the caller is
// responsible for examining the opening bytes (a prefix) of the input data.
// OnImageFormat implementations should not modify those bytes.
//
// OnImageFormat might be called more than once, since some image file
// formats can wrap others. For example, a nominal BMP file can actually
// contain a JPEG or a PNG.
//
// There is no default implementation, as modular Wuffs builds (those that
// define WUFFS_CONFIG__MODULES) may enable or disable particular codecs.
virtual wuffs_base__image_decoder::unique_ptr //
OnImageFormat(uint32_t fourcc, wuffs_base__slice_u8 prefix) = 0;
// OnImageConfig allocates the pixel buffer.
//
// The default OnImageConfig implementation allocates zeroed memory.
virtual AllocResult //
OnImageConfig(const wuffs_base__image_config& image_config);
// AllocWorkbuf allocates the work buffer. The allocated buffer's length
// should be at least len.min_incl, but larger allocations (up to
// len.max_incl) may have better performance (by using more memory).
//
// The default AllocWorkbuf implementation allocates len.max_incl bytes of
// zeroed memory.
virtual AllocResult //
AllocWorkbuf(wuffs_base__range_ii_u64 len);
// Done is always the last Callback method called by DecodeImage, whether or
// not parsing the input encountered an error. Even when successful, trailing
// data may remain in input and buffer.
//
// Do not keep a reference to buffer or buffer.data.ptr after Done returns,
// as DecodeImage may then de-allocate the backing array.
//
// The default Done implementation is a no-op.
virtual void //
Done(DecodeImageResult& result, sync_io::Input& input, IOBuffer& buffer);
};
extern const char DecodeImage_BufferIsTooShort[];
extern const char DecodeImage_MaxInclDimensionExceeded[];
extern const char DecodeImage_OutOfMemory[];
extern const char DecodeImage_UnexpectedEndOfFile[];
extern const char DecodeImage_UnsupportedImageFormat[];
extern const char DecodeImage_UnsupportedPixelBlend[];
extern const char DecodeImage_UnsupportedPixelConfiguration[];
extern const char DecodeImage_UnsupportedPixelFormat[];
// DecodeImage decodes the image data in input. A variety of image file formats
// can be decoded, depending on what callbacks.OnImageFormat returns. For
// animated formats, only the first frame is returned.
//
// - On total success, the returned error_message is empty.
// - On partial success (e.g. the input file was truncated but we are still
// able to decode some pixels), error_message is non-empty but the returned
// pixbuf.pixcfg.is_valid() is true.
// - On failure, the error_message is non_empty and pixbuf.pixcfg.is_valid()
// is false.
//
// The callbacks allocate the pixel buffer memory and work buffer memory. On
// success, pixel buffer memory ownership is passed to the DecodeImage caller
// as the returned pixbuf_mem_owner. Regardless of success or failure, the work
// buffer memory is deleted.
//
// If override_pixel_format_repr is zero then the pixel buffer will have the
// image file's natural pixel format. For example, GIF images' natural pixel
// format is an indexed one.
//
// If override_pixel_format_repr is non-zero (and one of the constants listed
// below) then the image will be decoded to that particular pixel format:
// - WUFFS_BASE__PIXEL_FORMAT__BGR_565
// - WUFFS_BASE__PIXEL_FORMAT__BGR
// - WUFFS_BASE__PIXEL_FORMAT__BGRA_NONPREMUL
// - WUFFS_BASE__PIXEL_FORMAT__BGRA_PREMUL
//
// The pixel_blend (one of the constants listed below) determines how to
// composite the decoded image over the pixel buffer's original pixels (as
// returned by callbacks.OnImageConfig):
// - WUFFS_BASE__PIXEL_BLEND__SRC
// - WUFFS_BASE__PIXEL_BLEND__SRC_OVER
//
// Decoding fails (with DecodeImage_MaxInclDimensionExceeded) if the image's
// width or height is greater than max_incl_dimension.
DecodeImageResult //
DecodeImage(DecodeImageCallbacks& callbacks,
sync_io::Input& input,
uint32_t override_pixel_format_repr,
wuffs_base__pixel_blend pixel_blend = WUFFS_BASE__PIXEL_BLEND__SRC,
uint32_t max_incl_dimension = 1048575); // 0x000F_FFFF
} // namespace wuffs_aux
+7 -8
View File
@@ -62,9 +62,8 @@ class DecodeJsonCallbacks {
// as DecodeJson may then de-allocate the backing array.
//
// The default Done implementation is a no-op.
virtual void Done(DecodeJsonResult& result,
sync_io::Input& input,
IOBuffer& buffer);
virtual void //
Done(DecodeJsonResult& result, sync_io::Input& input, IOBuffer& buffer);
};
extern const char DecodeJson_BadJsonPointer[];
@@ -84,10 +83,10 @@ extern const char DecodeJson_NoMatch[];
//
// The JSON Pointer implementation is greedy: duplicate keys are not rejected
// but only the first match for each '/'-separated fragment is followed.
DecodeJsonResult DecodeJson(
DecodeJsonCallbacks& callbacks,
sync_io::Input& input,
wuffs_base__slice_u32 quirks = wuffs_base__empty_slice_u32(),
std::string json_pointer = std::string());
DecodeJsonResult //
DecodeJson(DecodeJsonCallbacks& callbacks,
sync_io::Input& input,
wuffs_base__slice_u32 quirks = wuffs_base__empty_slice_u32(),
std::string json_pointer = std::string());
} // namespace wuffs_aux
+32 -6
View File
@@ -698,7 +698,7 @@ const AuxBaseCc = "" +
""
const AuxBaseHh = "" +
"// ---------------- Auxiliary - Base\n\n// Auxiliary code is discussed at\n// https://github.com/google/wuffs/blob/main/doc/note/auxiliary-code.md\n\n#include <stdio.h>\n\n#include <string>\n\nnamespace wuffs_aux {\n\nusing IOBuffer = wuffs_base__io_buffer;\n\nnamespace sync_io {\n\n" +
"// ---------------- Auxiliary - Base\n\n// Auxiliary code is discussed at\n// https://github.com/google/wuffs/blob/main/doc/note/auxiliary-code.md\n\n#include <stdio.h>\n\n#include <string>\n\nnamespace wuffs_aux {\n\nusing IOBuffer = wuffs_base__io_buffer;\n\n// MemOwner represents ownership of some memory. Dynamically allocated memory\n// (e.g. from malloc or new) is typically paired with free or delete, invoked\n// when the std::unique_ptr is destroyed. Statically allocated memory might use\n// MemOwner(nullptr, &free), even if that statically allocated memory is not\n// nullptr, since calling free(nullptr) is a no-op.\nusing MemOwner = std::unique_ptr<void, decltype(&free)>;\n\nnamespace sync_io {\n\n" +
"" +
"// --------\n\nclass Input {\n public:\n virtual IOBuffer* BringsItsOwnIOBuffer();\n virtual std::string CopyIn(IOBuffer* dst) = 0;\n};\n\n" +
"" +
@@ -726,8 +726,32 @@ const AuxCborCc = "" +
const AuxCborHh = "" +
"// ---------------- Auxiliary - CBOR\n\nnamespace wuffs_aux {\n\nstruct DecodeCborResult {\n DecodeCborResult(std::string&& error_message0, uint64_t cursor_position0);\n\n std::string error_message;\n uint64_t cursor_position;\n};\n\nclass DecodeCborCallbacks {\n public:\n // AppendXxx are called for leaf nodes: literals, numbers, strings, etc.\n\n virtual std::string AppendNull() = 0;\n virtual std::string AppendUndefined() = 0;\n virtual std::string AppendBool(bool val) = 0;\n virtual std::string AppendF64(double val) = 0;\n virtual std::string AppendI64(int64_t val) = 0;\n virtual std::string AppendU64(uint64_t val) = 0;\n virtual std::string AppendByteString(std::string&& val) = 0;\n virtual std::string AppendTextString(std::string&& val) = 0;\n virtual std::string AppendMinus1MinusX(uint64_t val) = 0;\n virtual std::string AppendCborSimpleValue(uint8_t val) = 0;\n virtual std::string AppendCborTag(uint64_t val) = 0;\n\n // Push and Pop are called for container nodes: CBOR arrays (lists) and CBOR\n // maps (dictiona" +
"ries).\n //\n // The flags bits combine exactly one of:\n // - WUFFS_BASE__TOKEN__VBD__STRUCTURE__FROM_NONE\n // - WUFFS_BASE__TOKEN__VBD__STRUCTURE__FROM_LIST\n // - WUFFS_BASE__TOKEN__VBD__STRUCTURE__FROM_DICT\n // and exactly one of:\n // - WUFFS_BASE__TOKEN__VBD__STRUCTURE__TO_NONE\n // - WUFFS_BASE__TOKEN__VBD__STRUCTURE__TO_LIST\n // - WUFFS_BASE__TOKEN__VBD__STRUCTURE__TO_DICT\n\n virtual std::string Push(uint32_t flags) = 0;\n virtual std::string Pop(uint32_t flags) = 0;\n\n // Done is always the last Callback method called by DecodeCbor, whether or\n // not parsing the input as CBOR encountered an error. Even when successful,\n // trailing data may remain in input and buffer.\n //\n // Do not keep a reference to buffer or buffer.data.ptr after Done returns,\n // as DecodeCbor may then de-allocate the backing array.\n //\n // The default Done implementation is a no-op.\n virtual void Done(DecodeCborResult& result,\n sync_io::Input& input,\n IOBuffer& buffer);\n};" +
"\n\n// DecodeCbor calls callbacks based on the CBOR-formatted data in input.\n//\n// On success, the returned error_message is empty and cursor_position counts\n// the number of bytes consumed. On failure, error_message is non-empty and\n// cursor_position is the location of the error. That error may be a content\n// error (invalid CBOR) or an input error (e.g. network failure).\nDecodeCborResult DecodeCbor(\n DecodeCborCallbacks& callbacks,\n sync_io::Input& input,\n wuffs_base__slice_u32 quirks = wuffs_base__empty_slice_u32());\n\n} // namespace wuffs_aux\n" +
"ries).\n //\n // The flags bits combine exactly one of:\n // - WUFFS_BASE__TOKEN__VBD__STRUCTURE__FROM_NONE\n // - WUFFS_BASE__TOKEN__VBD__STRUCTURE__FROM_LIST\n // - WUFFS_BASE__TOKEN__VBD__STRUCTURE__FROM_DICT\n // and exactly one of:\n // - WUFFS_BASE__TOKEN__VBD__STRUCTURE__TO_NONE\n // - WUFFS_BASE__TOKEN__VBD__STRUCTURE__TO_LIST\n // - WUFFS_BASE__TOKEN__VBD__STRUCTURE__TO_DICT\n\n virtual std::string Push(uint32_t flags) = 0;\n virtual std::string Pop(uint32_t flags) = 0;\n\n // Done is always the last Callback method called by DecodeCbor, whether or\n // not parsing the input as CBOR encountered an error. Even when successful,\n // trailing data may remain in input and buffer.\n //\n // Do not keep a reference to buffer or buffer.data.ptr after Done returns,\n // as DecodeCbor may then de-allocate the backing array.\n //\n // The default Done implementation is a no-op.\n virtual void //\n Done(DecodeCborResult& result, sync_io::Input& input, IOBuffer& buffer);\n};\n\n// DecodeCbor calls callbacks ba" +
"sed on the CBOR-formatted data in input.\n//\n// On success, the returned error_message is empty and cursor_position counts\n// the number of bytes consumed. On failure, error_message is non-empty and\n// cursor_position is the location of the error. That error may be a content\n// error (invalid CBOR) or an input error (e.g. network failure).\nDecodeCborResult //\nDecodeCbor(DecodeCborCallbacks& callbacks,\n sync_io::Input& input,\n wuffs_base__slice_u32 quirks = wuffs_base__empty_slice_u32());\n\n} // namespace wuffs_aux\n" +
""
const AuxImageCc = "" +
"// ---------------- Auxiliary - Image\n\n#if !defined(WUFFS_CONFIG__MODULES) || defined(WUFFS_CONFIG__MODULE__AUX__IMAGE)\n\n#include <utility>\n\nnamespace wuffs_aux {\n\nDecodeImageResult::DecodeImageResult(MemOwner&& pixbuf_mem_owner0,\n wuffs_base__slice_u8 pixbuf_mem_slice0,\n wuffs_base__pixel_buffer pixbuf0,\n std::string&& error_message0)\n : pixbuf_mem_owner(std::move(pixbuf_mem_owner0)),\n pixbuf_mem_slice(pixbuf_mem_slice0),\n pixbuf(pixbuf0),\n error_message(std::move(error_message0)) {}\n\nDecodeImageResult::DecodeImageResult(std::string&& error_message0)\n : pixbuf_mem_owner(nullptr, &free),\n pixbuf_mem_slice(wuffs_base__empty_slice_u8()),\n pixbuf({0}),\n error_message(std::move(error_message0)) {}\n\nDecodeImageCallbacks::AllocResult::AllocResult(MemOwner&& mem_owner0,\n wuffs_base__slice_u8 mem_slice0)\n : mem_owner(std::move(" +
"mem_owner0)),\n mem_slice(mem_slice0),\n error_message(\"\") {}\n\nDecodeImageCallbacks::AllocResult::AllocResult(std::string&& error_message0)\n : mem_owner(nullptr, &free),\n mem_slice(wuffs_base__empty_slice_u8()),\n error_message(std::move(error_message0)) {}\n\nDecodeImageCallbacks::AllocResult //\nDecodeImageCallbacks::OnImageConfig(\n const wuffs_base__image_config& image_config) {\n uint32_t w = image_config.pixcfg.width();\n uint32_t h = image_config.pixcfg.height();\n if ((w == 0) || (h == 0)) {\n return AllocResult(\"\");\n }\n uint64_t len = image_config.pixcfg.pixbuf_len();\n if ((len == 0) || (SIZE_MAX < len)) {\n return AllocResult(DecodeImage_UnsupportedPixelConfiguration);\n }\n void* ptr = calloc((size_t)len, 1);\n if (!ptr) {\n return AllocResult(DecodeImage_OutOfMemory);\n }\n return AllocResult(MemOwner(ptr, &free),\n wuffs_base__make_slice_u8((uint8_t*)ptr, (size_t)len));\n}\n\nDecodeImageCallbacks::AllocResult //\nDecodeImageCallbacks::AllocWorkbuf(wuff" +
"s_base__range_ii_u64 len) {\n if (len.max_incl == 0) {\n return DecodeImageCallbacks::AllocResult(\"\");\n } else if (SIZE_MAX < len.max_incl) {\n return DecodeImageCallbacks::AllocResult(DecodeImage_OutOfMemory);\n }\n void* p = calloc((size_t)len.max_incl, 1);\n if (!p) {\n return DecodeImageCallbacks::AllocResult(DecodeImage_OutOfMemory);\n }\n return DecodeImageCallbacks::AllocResult(\n MemOwner(p, &free),\n wuffs_base__make_slice_u8((uint8_t*)p, (size_t)len.max_incl));\n}\n\nvoid //\nDecodeImageCallbacks::Done(DecodeImageResult& result,\n sync_io::Input& input,\n IOBuffer& buffer) {}\n\nconst char DecodeImage_BufferIsTooShort[] = //\n \"wuffs_aux::DecodeImage: buffer is too short\";\nconst char DecodeImage_MaxInclDimensionExceeded[] = //\n \"wuffs_aux::DecodeImage: max_incl_dimension exceeded\";\nconst char DecodeImage_OutOfMemory[] = //\n \"wuffs_aux::DecodeImage: out of memory\";\nconst char DecodeImage_UnexpectedEndOfFile[] = //\n \"wuffs_aux:" +
":DecodeImage: unexpected end of file\";\nconst char DecodeImage_UnsupportedImageFormat[] = //\n \"wuffs_aux::DecodeImage: unsupported image format\";\nconst char DecodeImage_UnsupportedPixelBlend[] = //\n \"wuffs_aux::DecodeImage: unsupported pixel blend\";\nconst char DecodeImage_UnsupportedPixelConfiguration[] = //\n \"wuffs_aux::DecodeImage: unsupported pixel configuration\";\nconst char DecodeImage_UnsupportedPixelFormat[] = //\n \"wuffs_aux::DecodeImage: unsupported pixel format\";\n\n" +
"" +
"// --------\n\nnamespace {\n\nDecodeImageResult //\nDecodeImage0(DecodeImageCallbacks& callbacks,\n sync_io::Input& input,\n wuffs_base__io_buffer& io_buf,\n uint32_t override_pixel_format_repr,\n wuffs_base__pixel_blend pixel_blend,\n uint32_t max_incl_dimension) {\n // Check args.\n switch (override_pixel_format_repr) {\n case 0:\n case WUFFS_BASE__PIXEL_FORMAT__BGR_565:\n case WUFFS_BASE__PIXEL_FORMAT__BGR:\n case WUFFS_BASE__PIXEL_FORMAT__BGRA_NONPREMUL:\n case WUFFS_BASE__PIXEL_FORMAT__BGRA_PREMUL:\n break;\n default:\n return DecodeImageResult(DecodeImage_UnsupportedPixelFormat);\n }\n switch (pixel_blend) {\n case WUFFS_BASE__PIXEL_BLEND__SRC:\n case WUFFS_BASE__PIXEL_BLEND__SRC_OVER:\n break;\n default:\n return DecodeImageResult(DecodeImage_UnsupportedPixelBlend);\n }\n\n // Determine the image format.\n int32_t fourcc = 0;\n while (true) {\n fourcc = wuffs_base__magic_number_guess_fourcc(io_buf.reader_slice());\n " +
" if (fourcc > 0) {\n break;\n } else if ((fourcc == 0) && (io_buf.reader_length() >= 64)) {\n break;\n } else if (io_buf.meta.closed || (io_buf.writer_length() == 0)) {\n fourcc = 0;\n break;\n }\n std::string error_message = input.CopyIn(&io_buf);\n if (!error_message.empty()) {\n return DecodeImageResult(std::move(error_message));\n }\n }\n wuffs_base__image_decoder::unique_ptr image_decoder =\n callbacks.OnImageFormat(fourcc, io_buf.reader_slice());\n if (!image_decoder) {\n return DecodeImageResult(DecodeImage_UnsupportedImageFormat);\n }\n\n // Decode the image config.\n wuffs_base__image_config image_config;\n while (true) {\n wuffs_base__status id_dic_status =\n image_decoder->decode_image_config(&image_config, &io_buf);\n if (id_dic_status.repr == NULL) {\n break;\n } else if (id_dic_status.repr != wuffs_base__suspension__short_read) {\n // TODO: handle wuffs_base__note__i_o_redirect.\n return DecodeImageResult(id_dic_status.message());\n " +
"} else if (io_buf.meta.closed) {\n return DecodeImageResult(DecodeImage_UnexpectedEndOfFile);\n } else {\n std::string error_message = input.CopyIn(&io_buf);\n if (!error_message.empty()) {\n return DecodeImageResult(std::move(error_message));\n }\n }\n }\n\n // Apply the override pixel format.\n uint32_t w = image_config.pixcfg.width();\n uint32_t h = image_config.pixcfg.height();\n if ((w > max_incl_dimension) || (h > max_incl_dimension)) {\n return DecodeImageResult(DecodeImage_MaxInclDimensionExceeded);\n }\n if (override_pixel_format_repr != 0) {\n image_config.pixcfg.set(override_pixel_format_repr,\n WUFFS_BASE__PIXEL_SUBSAMPLING__NONE, w, h);\n }\n\n // Allocate the pixel buffer.\n size_t pixbuf_len_min_incl = 0;\n if ((w > 0) && (h > 0)) {\n pixbuf_len_min_incl = image_config.pixcfg.pixbuf_len();\n if (pixbuf_len_min_incl == 0) {\n return DecodeImageResult(DecodeImage_UnsupportedPixelFormat);\n }\n }\n DecodeImageCallbacks::AllocResult oi" +
"c_result =\n callbacks.OnImageConfig(image_config);\n if (!oic_result.error_message.empty()) {\n return DecodeImageResult(std::move(oic_result.error_message));\n } else if (oic_result.mem_slice.len < pixbuf_len_min_incl) {\n return DecodeImageResult(DecodeImage_BufferIsTooShort);\n }\n wuffs_base__pixel_buffer pixel_buffer;\n wuffs_base__status pb_sfs_status =\n pixel_buffer.set_from_slice(&image_config.pixcfg, oic_result.mem_slice);\n if (!pb_sfs_status.is_ok()) {\n return DecodeImageResult(pb_sfs_status.message());\n }\n\n // Allocate the work buffer.\n wuffs_base__range_ii_u64 workbuf_len = image_decoder->workbuf_len();\n DecodeImageCallbacks::AllocResult alloc_workbuf_result =\n callbacks.AllocWorkbuf(workbuf_len);\n if (!alloc_workbuf_result.error_message.empty()) {\n return DecodeImageResult(std::move(alloc_workbuf_result.error_message));\n } else if (alloc_workbuf_result.mem_slice.len < workbuf_len.min_incl) {\n return DecodeImageResult(DecodeImage_BufferIsTooShort);\n }\n\n // Deco" +
"de the frame config.\n wuffs_base__frame_config frame_config;\n while (true) {\n wuffs_base__status id_dfc_status =\n image_decoder->decode_frame_config(&frame_config, &io_buf);\n if (id_dfc_status.repr == NULL) {\n break;\n } else if (id_dfc_status.repr != wuffs_base__suspension__short_read) {\n return DecodeImageResult(id_dfc_status.message());\n } else if (io_buf.meta.closed) {\n return DecodeImageResult(DecodeImage_UnexpectedEndOfFile);\n } else {\n std::string error_message = input.CopyIn(&io_buf);\n if (!error_message.empty()) {\n return DecodeImageResult(std::move(error_message));\n }\n }\n }\n\n // Decode the frame (the pixels).\n //\n // From here on, always returns the pixel_buffer. If we get this far, we can\n // still display a partial image, even if we encounter an error.\n std::string message(\"\");\n if ((pixel_blend == WUFFS_BASE__PIXEL_BLEND__SRC_OVER) &&\n frame_config.overwrite_instead_of_blend()) {\n pixel_blend = WUFFS_BASE__PIXEL_BLEND__" +
"SRC;\n }\n while (true) {\n wuffs_base__status id_df_status =\n image_decoder->decode_frame(&pixel_buffer, &io_buf, pixel_blend,\n alloc_workbuf_result.mem_slice, NULL);\n if (id_df_status.repr == NULL) {\n break;\n } else if (id_df_status.repr != wuffs_base__suspension__short_read) {\n message = id_df_status.message();\n break;\n } else if (io_buf.meta.closed) {\n message = DecodeImage_UnexpectedEndOfFile;\n break;\n } else {\n std::string error_message = input.CopyIn(&io_buf);\n if (!error_message.empty()) {\n message = std::move(error_message);\n break;\n }\n }\n }\n return DecodeImageResult(std::move(oic_result.mem_owner),\n oic_result.mem_slice, pixel_buffer,\n std::move(message));\n}\n\n} // namespace\n\nDecodeImageResult //\nDecodeImage(DecodeImageCallbacks& callbacks,\n sync_io::Input& input,\n uint32_t override_pixel_format_repr,\n " +
" wuffs_base__pixel_blend pixel_blend,\n uint32_t max_incl_dimension) {\n wuffs_base__io_buffer* io_buf = input.BringsItsOwnIOBuffer();\n wuffs_base__io_buffer fallback_io_buf = wuffs_base__empty_io_buffer();\n std::unique_ptr<uint8_t[]> fallback_io_array(nullptr);\n if (!io_buf) {\n fallback_io_array = std::unique_ptr<uint8_t[]>(new uint8_t[32768]);\n fallback_io_buf =\n wuffs_base__ptr_u8__writer(fallback_io_array.get(), 32768);\n io_buf = &fallback_io_buf;\n }\n\n DecodeImageResult result =\n DecodeImage0(callbacks, input, *io_buf, override_pixel_format_repr,\n pixel_blend, max_incl_dimension);\n callbacks.Done(result, input, *io_buf);\n return result;\n}\n\n} // namespace wuffs_aux\n\n#endif // !defined(WUFFS_CONFIG__MODULES) ||\n // defined(WUFFS_CONFIG__MODULE__AUX__IMAGE)\n" +
""
const AuxImageHh = "" +
"// ---------------- Auxiliary - Image\n\nnamespace wuffs_aux {\n\nstruct DecodeImageResult {\n DecodeImageResult(MemOwner&& pixbuf_mem_owner0,\n wuffs_base__slice_u8 pixbuf_mem_slice0,\n wuffs_base__pixel_buffer pixbuf0,\n std::string&& error_message0);\n DecodeImageResult(std::string&& error_message0);\n\n MemOwner pixbuf_mem_owner;\n wuffs_base__slice_u8 pixbuf_mem_slice;\n wuffs_base__pixel_buffer pixbuf;\n std::string error_message;\n};\n\n// DecodeImageCallbacks are the callbacks given to DecodeImage. They are always\n// called in this order:\n// 1. OnImageFormat\n// 2. OnImageConfig\n// 3. AllocWorkbuf\n// 4. Done\n//\n// It may return early - the third callback might not be invoked if the second\n// one fails (returns a non-empty error message) - but the final callback\n// (Done) is always invoked.\nclass DecodeImageCallbacks {\n public:\n // AllocResult holds a memory allocation (the result of malloc or new, a\n // statically allocated pointer, etc), or an error " +
"message. The memory is\n // de-allocated when mem_owner goes out of scope and is destroyed.\n struct AllocResult {\n AllocResult(MemOwner&& mem_owner0, wuffs_base__slice_u8 mem_slice0);\n AllocResult(std::string&& error_message0);\n\n MemOwner mem_owner;\n wuffs_base__slice_u8 mem_slice;\n std::string error_message;\n };\n\n // OnImageFormat returns the image decoder for the input data's file format.\n // Returning a nullptr means failure (DecodeImage_UnsupportedImageFormat).\n //\n // Common formats will have a non-zero FourCC value, such as\n // WUFFS_BASE__FOURCC__JPEG. A zero FourCC code means that the caller is\n // responsible for examining the opening bytes (a prefix) of the input data.\n // OnImageFormat implementations should not modify those bytes.\n //\n // OnImageFormat might be called more than once, since some image file\n // formats can wrap others. For example, a nominal BMP file can actually\n // contain a JPEG or a PNG.\n //\n // There is no default implementation, as modular Wuffs b" +
"uilds (those that\n // define WUFFS_CONFIG__MODULES) may enable or disable particular codecs.\n virtual wuffs_base__image_decoder::unique_ptr //\n OnImageFormat(uint32_t fourcc, wuffs_base__slice_u8 prefix) = 0;\n\n // OnImageConfig allocates the pixel buffer.\n //\n // The default OnImageConfig implementation allocates zeroed memory.\n virtual AllocResult //\n OnImageConfig(const wuffs_base__image_config& image_config);\n\n // AllocWorkbuf allocates the work buffer. The allocated buffer's length\n // should be at least len.min_incl, but larger allocations (up to\n // len.max_incl) may have better performance (by using more memory).\n //\n // The default AllocWorkbuf implementation allocates len.max_incl bytes of\n // zeroed memory.\n virtual AllocResult //\n AllocWorkbuf(wuffs_base__range_ii_u64 len);\n\n // Done is always the last Callback method called by DecodeImage, whether or\n // not parsing the input encountered an error. Even when successful, trailing\n // data may remain in input and buffer.\n //\n " +
"// Do not keep a reference to buffer or buffer.data.ptr after Done returns,\n // as DecodeImage may then de-allocate the backing array.\n //\n // The default Done implementation is a no-op.\n virtual void //\n Done(DecodeImageResult& result, sync_io::Input& input, IOBuffer& buffer);\n};\n\nextern const char DecodeImage_BufferIsTooShort[];\nextern const char DecodeImage_MaxInclDimensionExceeded[];\nextern const char DecodeImage_OutOfMemory[];\nextern const char DecodeImage_UnexpectedEndOfFile[];\nextern const char DecodeImage_UnsupportedImageFormat[];\nextern const char DecodeImage_UnsupportedPixelBlend[];\nextern const char DecodeImage_UnsupportedPixelConfiguration[];\nextern const char DecodeImage_UnsupportedPixelFormat[];\n\n// DecodeImage decodes the image data in input. A variety of image file formats\n// can be decoded, depending on what callbacks.OnImageFormat returns. For\n// animated formats, only the first frame is returned.\n//\n// - On total success, the returned error_message is empty.\n// - On partial success " +
"(e.g. the input file was truncated but we are still\n// able to decode some pixels), error_message is non-empty but the returned\n// pixbuf.pixcfg.is_valid() is true.\n// - On failure, the error_message is non_empty and pixbuf.pixcfg.is_valid()\n// is false.\n//\n// The callbacks allocate the pixel buffer memory and work buffer memory. On\n// success, pixel buffer memory ownership is passed to the DecodeImage caller\n// as the returned pixbuf_mem_owner. Regardless of success or failure, the work\n// buffer memory is deleted.\n//\n// If override_pixel_format_repr is zero then the pixel buffer will have the\n// image file's natural pixel format. For example, GIF images' natural pixel\n// format is an indexed one.\n//\n// If override_pixel_format_repr is non-zero (and one of the constants listed\n// below) then the image will be decoded to that particular pixel format:\n// - WUFFS_BASE__PIXEL_FORMAT__BGR_565\n// - WUFFS_BASE__PIXEL_FORMAT__BGR\n// - WUFFS_BASE__PIXEL_FORMAT__BGRA_NONPREMUL\n// - WUFFS_BASE__PIXEL_FORM" +
"AT__BGRA_PREMUL\n//\n// The pixel_blend (one of the constants listed below) determines how to\n// composite the decoded image over the pixel buffer's original pixels (as\n// returned by callbacks.OnImageConfig):\n// - WUFFS_BASE__PIXEL_BLEND__SRC\n// - WUFFS_BASE__PIXEL_BLEND__SRC_OVER\n//\n// Decoding fails (with DecodeImage_MaxInclDimensionExceeded) if the image's\n// width or height is greater than max_incl_dimension.\nDecodeImageResult //\nDecodeImage(DecodeImageCallbacks& callbacks,\n sync_io::Input& input,\n uint32_t override_pixel_format_repr,\n wuffs_base__pixel_blend pixel_blend = WUFFS_BASE__PIXEL_BLEND__SRC,\n uint32_t max_incl_dimension = 1048575); // 0x000F_FFFF\n\n} // namespace wuffs_aux\n" +
""
const AuxJsonCc = "" +
@@ -760,18 +784,20 @@ const AuxJsonCc = "" +
const AuxJsonHh = "" +
"// ---------------- Auxiliary - JSON\n\nnamespace wuffs_aux {\n\nstruct DecodeJsonResult {\n DecodeJsonResult(std::string&& error_message0, uint64_t cursor_position0);\n\n std::string error_message;\n uint64_t cursor_position;\n};\n\nclass DecodeJsonCallbacks {\n public:\n // AppendXxx are called for leaf nodes: literals, numbers and strings. For\n // strings, the Callbacks implementation is responsible for tracking map keys\n // versus other values.\n\n virtual std::string AppendNull() = 0;\n virtual std::string AppendBool(bool val) = 0;\n virtual std::string AppendF64(double val) = 0;\n virtual std::string AppendI64(int64_t val) = 0;\n virtual std::string AppendTextString(std::string&& val) = 0;\n\n // Push and Pop are called for container nodes: JSON arrays (lists) and JSON\n // objects (dictionaries).\n //\n // The flags bits combine exactly one of:\n // - WUFFS_BASE__TOKEN__VBD__STRUCTURE__FROM_NONE\n // - WUFFS_BASE__TOKEN__VBD__STRUCTURE__FROM_LIST\n // - WUFFS_BASE__TOKEN__VBD__STRUCTURE__FROM_DICT\n // and e" +
"xactly one of:\n // - WUFFS_BASE__TOKEN__VBD__STRUCTURE__TO_NONE\n // - WUFFS_BASE__TOKEN__VBD__STRUCTURE__TO_LIST\n // - WUFFS_BASE__TOKEN__VBD__STRUCTURE__TO_DICT\n\n virtual std::string Push(uint32_t flags) = 0;\n virtual std::string Pop(uint32_t flags) = 0;\n\n // Done is always the last Callback method called by DecodeJson, whether or\n // not parsing the input as JSON encountered an error. Even when successful,\n // trailing data may remain in input and buffer. See \"Unintuitive JSON\n // Parsing\" (https://nullprogram.com/blog/2019/12/28/) which discusses JSON\n // parsing and when it stops.\n //\n // Do not keep a reference to buffer or buffer.data.ptr after Done returns,\n // as DecodeJson may then de-allocate the backing array.\n //\n // The default Done implementation is a no-op.\n virtual void Done(DecodeJsonResult& result,\n sync_io::Input& input,\n IOBuffer& buffer);\n};\n\nextern const char DecodeJson_BadJsonPointer[];\nextern const char DecodeJson_NoMatch[];\n\n// " +
"DecodeJson calls callbacks based on the JSON-formatted data in input.\n//\n// On success, the returned error_message is empty and cursor_position counts\n// the number of bytes consumed. On failure, error_message is non-empty and\n// cursor_position is the location of the error. That error may be a content\n// error (invalid JSON) or an input error (e.g. network failure).\n//\n// json_pointer is a query in the JSON Pointer (RFC 6901) syntax. The callbacks\n// run for the input's sub-node that matches the query. DecodeJson_NoMatch is\n// returned if no matching sub-node was found. The empty query matches the\n// input's root node, consistent with JSON Pointer semantics.\n//\n// The JSON Pointer implementation is greedy: duplicate keys are not rejected\n// but only the first match for each '/'-separated fragment is followed.\nDecodeJsonResult DecodeJson(\n DecodeJsonCallbacks& callbacks,\n sync_io::Input& input,\n wuffs_base__slice_u32 quirks = wuffs_base__empty_slice_u32(),\n std::string json_pointer = std::string()" +
");\n\n} // namespace wuffs_aux\n" +
"xactly one of:\n // - WUFFS_BASE__TOKEN__VBD__STRUCTURE__TO_NONE\n // - WUFFS_BASE__TOKEN__VBD__STRUCTURE__TO_LIST\n // - WUFFS_BASE__TOKEN__VBD__STRUCTURE__TO_DICT\n\n virtual std::string Push(uint32_t flags) = 0;\n virtual std::string Pop(uint32_t flags) = 0;\n\n // Done is always the last Callback method called by DecodeJson, whether or\n // not parsing the input as JSON encountered an error. Even when successful,\n // trailing data may remain in input and buffer. See \"Unintuitive JSON\n // Parsing\" (https://nullprogram.com/blog/2019/12/28/) which discusses JSON\n // parsing and when it stops.\n //\n // Do not keep a reference to buffer or buffer.data.ptr after Done returns,\n // as DecodeJson may then de-allocate the backing array.\n //\n // The default Done implementation is a no-op.\n virtual void //\n Done(DecodeJsonResult& result, sync_io::Input& input, IOBuffer& buffer);\n};\n\nextern const char DecodeJson_BadJsonPointer[];\nextern const char DecodeJson_NoMatch[];\n\n// DecodeJson calls callbacks based o" +
"n the JSON-formatted data in input.\n//\n// On success, the returned error_message is empty and cursor_position counts\n// the number of bytes consumed. On failure, error_message is non-empty and\n// cursor_position is the location of the error. That error may be a content\n// error (invalid JSON) or an input error (e.g. network failure).\n//\n// json_pointer is a query in the JSON Pointer (RFC 6901) syntax. The callbacks\n// run for the input's sub-node that matches the query. DecodeJson_NoMatch is\n// returned if no matching sub-node was found. The empty query matches the\n// input's root node, consistent with JSON Pointer semantics.\n//\n// The JSON Pointer implementation is greedy: duplicate keys are not rejected\n// but only the first match for each '/'-separated fragment is followed.\nDecodeJsonResult //\nDecodeJson(DecodeJsonCallbacks& callbacks,\n sync_io::Input& input,\n wuffs_base__slice_u32 quirks = wuffs_base__empty_slice_u32(),\n std::string json_pointer = std::string());\n\n} // name" +
"space wuffs_aux\n" +
""
var AuxNonBaseCcFiles = []string{
AuxCborCc,
AuxImageCc,
AuxJsonCc,
}
var AuxNonBaseHhFiles = []string{
AuxCborHh,
AuxImageHh,
AuxJsonHh,
}
+2
View File
@@ -102,6 +102,8 @@ func genData(out *bytes.Buffer) error {
{"../auxiliary/base.hh", "AuxBaseHh"},
{"../auxiliary/cbor.cc", "AuxCborCc"},
{"../auxiliary/cbor.hh", "AuxCborHh"},
{"../auxiliary/image.cc", "AuxImageCc"},
{"../auxiliary/image.hh", "AuxImageHh"},
{"../auxiliary/json.cc", "AuxJsonCc"},
{"../auxiliary/json.hh", "AuxJsonHh"},
}
+449 -15
View File
@@ -9231,6 +9231,13 @@ namespace wuffs_aux {
using IOBuffer = wuffs_base__io_buffer;
// MemOwner represents ownership of some memory. Dynamically allocated memory
// (e.g. from malloc or new) is typically paired with free or delete, invoked
// when the std::unique_ptr is destroyed. Statically allocated memory might use
// MemOwner(nullptr, &free), even if that statically allocated memory is not
// nullptr, since calling free(nullptr) is a no-op.
using MemOwner = std::unique_ptr<void, decltype(&free)>;
namespace sync_io {
// --------
@@ -9337,9 +9344,8 @@ class DecodeCborCallbacks {
// as DecodeCbor may then de-allocate the backing array.
//
// The default Done implementation is a no-op.
virtual void Done(DecodeCborResult& result,
sync_io::Input& input,
IOBuffer& buffer);
virtual void //
Done(DecodeCborResult& result, sync_io::Input& input, IOBuffer& buffer);
};
// DecodeCbor calls callbacks based on the CBOR-formatted data in input.
@@ -9348,10 +9354,148 @@ class DecodeCborCallbacks {
// the number of bytes consumed. On failure, error_message is non-empty and
// cursor_position is the location of the error. That error may be a content
// error (invalid CBOR) or an input error (e.g. network failure).
DecodeCborResult DecodeCbor(
DecodeCborCallbacks& callbacks,
sync_io::Input& input,
wuffs_base__slice_u32 quirks = wuffs_base__empty_slice_u32());
DecodeCborResult //
DecodeCbor(DecodeCborCallbacks& callbacks,
sync_io::Input& input,
wuffs_base__slice_u32 quirks = wuffs_base__empty_slice_u32());
} // namespace wuffs_aux
// ---------------- Auxiliary - Image
namespace wuffs_aux {
struct DecodeImageResult {
DecodeImageResult(MemOwner&& pixbuf_mem_owner0,
wuffs_base__slice_u8 pixbuf_mem_slice0,
wuffs_base__pixel_buffer pixbuf0,
std::string&& error_message0);
DecodeImageResult(std::string&& error_message0);
MemOwner pixbuf_mem_owner;
wuffs_base__slice_u8 pixbuf_mem_slice;
wuffs_base__pixel_buffer pixbuf;
std::string error_message;
};
// DecodeImageCallbacks are the callbacks given to DecodeImage. They are always
// called in this order:
// 1. OnImageFormat
// 2. OnImageConfig
// 3. AllocWorkbuf
// 4. Done
//
// It may return early - the third callback might not be invoked if the second
// one fails (returns a non-empty error message) - but the final callback
// (Done) is always invoked.
class DecodeImageCallbacks {
public:
// AllocResult holds a memory allocation (the result of malloc or new, a
// statically allocated pointer, etc), or an error message. The memory is
// de-allocated when mem_owner goes out of scope and is destroyed.
struct AllocResult {
AllocResult(MemOwner&& mem_owner0, wuffs_base__slice_u8 mem_slice0);
AllocResult(std::string&& error_message0);
MemOwner mem_owner;
wuffs_base__slice_u8 mem_slice;
std::string error_message;
};
// OnImageFormat returns the image decoder for the input data's file format.
// Returning a nullptr means failure (DecodeImage_UnsupportedImageFormat).
//
// Common formats will have a non-zero FourCC value, such as
// WUFFS_BASE__FOURCC__JPEG. A zero FourCC code means that the caller is
// responsible for examining the opening bytes (a prefix) of the input data.
// OnImageFormat implementations should not modify those bytes.
//
// OnImageFormat might be called more than once, since some image file
// formats can wrap others. For example, a nominal BMP file can actually
// contain a JPEG or a PNG.
//
// There is no default implementation, as modular Wuffs builds (those that
// define WUFFS_CONFIG__MODULES) may enable or disable particular codecs.
virtual wuffs_base__image_decoder::unique_ptr //
OnImageFormat(uint32_t fourcc, wuffs_base__slice_u8 prefix) = 0;
// OnImageConfig allocates the pixel buffer.
//
// The default OnImageConfig implementation allocates zeroed memory.
virtual AllocResult //
OnImageConfig(const wuffs_base__image_config& image_config);
// AllocWorkbuf allocates the work buffer. The allocated buffer's length
// should be at least len.min_incl, but larger allocations (up to
// len.max_incl) may have better performance (by using more memory).
//
// The default AllocWorkbuf implementation allocates len.max_incl bytes of
// zeroed memory.
virtual AllocResult //
AllocWorkbuf(wuffs_base__range_ii_u64 len);
// Done is always the last Callback method called by DecodeImage, whether or
// not parsing the input encountered an error. Even when successful, trailing
// data may remain in input and buffer.
//
// Do not keep a reference to buffer or buffer.data.ptr after Done returns,
// as DecodeImage may then de-allocate the backing array.
//
// The default Done implementation is a no-op.
virtual void //
Done(DecodeImageResult& result, sync_io::Input& input, IOBuffer& buffer);
};
extern const char DecodeImage_BufferIsTooShort[];
extern const char DecodeImage_MaxInclDimensionExceeded[];
extern const char DecodeImage_OutOfMemory[];
extern const char DecodeImage_UnexpectedEndOfFile[];
extern const char DecodeImage_UnsupportedImageFormat[];
extern const char DecodeImage_UnsupportedPixelBlend[];
extern const char DecodeImage_UnsupportedPixelConfiguration[];
extern const char DecodeImage_UnsupportedPixelFormat[];
// DecodeImage decodes the image data in input. A variety of image file formats
// can be decoded, depending on what callbacks.OnImageFormat returns. For
// animated formats, only the first frame is returned.
//
// - On total success, the returned error_message is empty.
// - On partial success (e.g. the input file was truncated but we are still
// able to decode some pixels), error_message is non-empty but the returned
// pixbuf.pixcfg.is_valid() is true.
// - On failure, the error_message is non_empty and pixbuf.pixcfg.is_valid()
// is false.
//
// The callbacks allocate the pixel buffer memory and work buffer memory. On
// success, pixel buffer memory ownership is passed to the DecodeImage caller
// as the returned pixbuf_mem_owner. Regardless of success or failure, the work
// buffer memory is deleted.
//
// If override_pixel_format_repr is zero then the pixel buffer will have the
// image file's natural pixel format. For example, GIF images' natural pixel
// format is an indexed one.
//
// If override_pixel_format_repr is non-zero (and one of the constants listed
// below) then the image will be decoded to that particular pixel format:
// - WUFFS_BASE__PIXEL_FORMAT__BGR_565
// - WUFFS_BASE__PIXEL_FORMAT__BGR
// - WUFFS_BASE__PIXEL_FORMAT__BGRA_NONPREMUL
// - WUFFS_BASE__PIXEL_FORMAT__BGRA_PREMUL
//
// The pixel_blend (one of the constants listed below) determines how to
// composite the decoded image over the pixel buffer's original pixels (as
// returned by callbacks.OnImageConfig):
// - WUFFS_BASE__PIXEL_BLEND__SRC
// - WUFFS_BASE__PIXEL_BLEND__SRC_OVER
//
// Decoding fails (with DecodeImage_MaxInclDimensionExceeded) if the image's
// width or height is greater than max_incl_dimension.
DecodeImageResult //
DecodeImage(DecodeImageCallbacks& callbacks,
sync_io::Input& input,
uint32_t override_pixel_format_repr,
wuffs_base__pixel_blend pixel_blend = WUFFS_BASE__PIXEL_BLEND__SRC,
uint32_t max_incl_dimension = 1048575); // 0x000F_FFFF
} // namespace wuffs_aux
@@ -9403,9 +9547,8 @@ class DecodeJsonCallbacks {
// as DecodeJson may then de-allocate the backing array.
//
// The default Done implementation is a no-op.
virtual void Done(DecodeJsonResult& result,
sync_io::Input& input,
IOBuffer& buffer);
virtual void //
Done(DecodeJsonResult& result, sync_io::Input& input, IOBuffer& buffer);
};
extern const char DecodeJson_BadJsonPointer[];
@@ -9425,11 +9568,11 @@ extern const char DecodeJson_NoMatch[];
//
// The JSON Pointer implementation is greedy: duplicate keys are not rejected
// but only the first match for each '/'-separated fragment is followed.
DecodeJsonResult DecodeJson(
DecodeJsonCallbacks& callbacks,
sync_io::Input& input,
wuffs_base__slice_u32 quirks = wuffs_base__empty_slice_u32(),
std::string json_pointer = std::string());
DecodeJsonResult //
DecodeJson(DecodeJsonCallbacks& callbacks,
sync_io::Input& input,
wuffs_base__slice_u32 quirks = wuffs_base__empty_slice_u32(),
std::string json_pointer = std::string());
} // namespace wuffs_aux
@@ -36303,6 +36446,297 @@ done:
#endif // !defined(WUFFS_CONFIG__MODULES) ||
// defined(WUFFS_CONFIG__MODULE__AUX__CBOR)
// ---------------- Auxiliary - Image
#if !defined(WUFFS_CONFIG__MODULES) || defined(WUFFS_CONFIG__MODULE__AUX__IMAGE)
#include <utility>
namespace wuffs_aux {
DecodeImageResult::DecodeImageResult(MemOwner&& pixbuf_mem_owner0,
wuffs_base__slice_u8 pixbuf_mem_slice0,
wuffs_base__pixel_buffer pixbuf0,
std::string&& error_message0)
: pixbuf_mem_owner(std::move(pixbuf_mem_owner0)),
pixbuf_mem_slice(pixbuf_mem_slice0),
pixbuf(pixbuf0),
error_message(std::move(error_message0)) {}
DecodeImageResult::DecodeImageResult(std::string&& error_message0)
: pixbuf_mem_owner(nullptr, &free),
pixbuf_mem_slice(wuffs_base__empty_slice_u8()),
pixbuf({0}),
error_message(std::move(error_message0)) {}
DecodeImageCallbacks::AllocResult::AllocResult(MemOwner&& mem_owner0,
wuffs_base__slice_u8 mem_slice0)
: mem_owner(std::move(mem_owner0)),
mem_slice(mem_slice0),
error_message("") {}
DecodeImageCallbacks::AllocResult::AllocResult(std::string&& error_message0)
: mem_owner(nullptr, &free),
mem_slice(wuffs_base__empty_slice_u8()),
error_message(std::move(error_message0)) {}
DecodeImageCallbacks::AllocResult //
DecodeImageCallbacks::OnImageConfig(
const wuffs_base__image_config& image_config) {
uint32_t w = image_config.pixcfg.width();
uint32_t h = image_config.pixcfg.height();
if ((w == 0) || (h == 0)) {
return AllocResult("");
}
uint64_t len = image_config.pixcfg.pixbuf_len();
if ((len == 0) || (SIZE_MAX < len)) {
return AllocResult(DecodeImage_UnsupportedPixelConfiguration);
}
void* ptr = calloc((size_t)len, 1);
if (!ptr) {
return AllocResult(DecodeImage_OutOfMemory);
}
return AllocResult(MemOwner(ptr, &free),
wuffs_base__make_slice_u8((uint8_t*)ptr, (size_t)len));
}
DecodeImageCallbacks::AllocResult //
DecodeImageCallbacks::AllocWorkbuf(wuffs_base__range_ii_u64 len) {
if (len.max_incl == 0) {
return DecodeImageCallbacks::AllocResult("");
} else if (SIZE_MAX < len.max_incl) {
return DecodeImageCallbacks::AllocResult(DecodeImage_OutOfMemory);
}
void* p = calloc((size_t)len.max_incl, 1);
if (!p) {
return DecodeImageCallbacks::AllocResult(DecodeImage_OutOfMemory);
}
return DecodeImageCallbacks::AllocResult(
MemOwner(p, &free),
wuffs_base__make_slice_u8((uint8_t*)p, (size_t)len.max_incl));
}
void //
DecodeImageCallbacks::Done(DecodeImageResult& result,
sync_io::Input& input,
IOBuffer& buffer) {}
const char DecodeImage_BufferIsTooShort[] = //
"wuffs_aux::DecodeImage: buffer is too short";
const char DecodeImage_MaxInclDimensionExceeded[] = //
"wuffs_aux::DecodeImage: max_incl_dimension exceeded";
const char DecodeImage_OutOfMemory[] = //
"wuffs_aux::DecodeImage: out of memory";
const char DecodeImage_UnexpectedEndOfFile[] = //
"wuffs_aux::DecodeImage: unexpected end of file";
const char DecodeImage_UnsupportedImageFormat[] = //
"wuffs_aux::DecodeImage: unsupported image format";
const char DecodeImage_UnsupportedPixelBlend[] = //
"wuffs_aux::DecodeImage: unsupported pixel blend";
const char DecodeImage_UnsupportedPixelConfiguration[] = //
"wuffs_aux::DecodeImage: unsupported pixel configuration";
const char DecodeImage_UnsupportedPixelFormat[] = //
"wuffs_aux::DecodeImage: unsupported pixel format";
// --------
namespace {
DecodeImageResult //
DecodeImage0(DecodeImageCallbacks& callbacks,
sync_io::Input& input,
wuffs_base__io_buffer& io_buf,
uint32_t override_pixel_format_repr,
wuffs_base__pixel_blend pixel_blend,
uint32_t max_incl_dimension) {
// Check args.
switch (override_pixel_format_repr) {
case 0:
case WUFFS_BASE__PIXEL_FORMAT__BGR_565:
case WUFFS_BASE__PIXEL_FORMAT__BGR:
case WUFFS_BASE__PIXEL_FORMAT__BGRA_NONPREMUL:
case WUFFS_BASE__PIXEL_FORMAT__BGRA_PREMUL:
break;
default:
return DecodeImageResult(DecodeImage_UnsupportedPixelFormat);
}
switch (pixel_blend) {
case WUFFS_BASE__PIXEL_BLEND__SRC:
case WUFFS_BASE__PIXEL_BLEND__SRC_OVER:
break;
default:
return DecodeImageResult(DecodeImage_UnsupportedPixelBlend);
}
// Determine the image format.
int32_t fourcc = 0;
while (true) {
fourcc = wuffs_base__magic_number_guess_fourcc(io_buf.reader_slice());
if (fourcc > 0) {
break;
} else if ((fourcc == 0) && (io_buf.reader_length() >= 64)) {
break;
} else if (io_buf.meta.closed || (io_buf.writer_length() == 0)) {
fourcc = 0;
break;
}
std::string error_message = input.CopyIn(&io_buf);
if (!error_message.empty()) {
return DecodeImageResult(std::move(error_message));
}
}
wuffs_base__image_decoder::unique_ptr image_decoder =
callbacks.OnImageFormat(fourcc, io_buf.reader_slice());
if (!image_decoder) {
return DecodeImageResult(DecodeImage_UnsupportedImageFormat);
}
// Decode the image config.
wuffs_base__image_config image_config;
while (true) {
wuffs_base__status id_dic_status =
image_decoder->decode_image_config(&image_config, &io_buf);
if (id_dic_status.repr == NULL) {
break;
} else if (id_dic_status.repr != wuffs_base__suspension__short_read) {
// TODO: handle wuffs_base__note__i_o_redirect.
return DecodeImageResult(id_dic_status.message());
} else if (io_buf.meta.closed) {
return DecodeImageResult(DecodeImage_UnexpectedEndOfFile);
} else {
std::string error_message = input.CopyIn(&io_buf);
if (!error_message.empty()) {
return DecodeImageResult(std::move(error_message));
}
}
}
// Apply the override pixel format.
uint32_t w = image_config.pixcfg.width();
uint32_t h = image_config.pixcfg.height();
if ((w > max_incl_dimension) || (h > max_incl_dimension)) {
return DecodeImageResult(DecodeImage_MaxInclDimensionExceeded);
}
if (override_pixel_format_repr != 0) {
image_config.pixcfg.set(override_pixel_format_repr,
WUFFS_BASE__PIXEL_SUBSAMPLING__NONE, w, h);
}
// Allocate the pixel buffer.
size_t pixbuf_len_min_incl = 0;
if ((w > 0) && (h > 0)) {
pixbuf_len_min_incl = image_config.pixcfg.pixbuf_len();
if (pixbuf_len_min_incl == 0) {
return DecodeImageResult(DecodeImage_UnsupportedPixelFormat);
}
}
DecodeImageCallbacks::AllocResult oic_result =
callbacks.OnImageConfig(image_config);
if (!oic_result.error_message.empty()) {
return DecodeImageResult(std::move(oic_result.error_message));
} else if (oic_result.mem_slice.len < pixbuf_len_min_incl) {
return DecodeImageResult(DecodeImage_BufferIsTooShort);
}
wuffs_base__pixel_buffer pixel_buffer;
wuffs_base__status pb_sfs_status =
pixel_buffer.set_from_slice(&image_config.pixcfg, oic_result.mem_slice);
if (!pb_sfs_status.is_ok()) {
return DecodeImageResult(pb_sfs_status.message());
}
// Allocate the work buffer.
wuffs_base__range_ii_u64 workbuf_len = image_decoder->workbuf_len();
DecodeImageCallbacks::AllocResult alloc_workbuf_result =
callbacks.AllocWorkbuf(workbuf_len);
if (!alloc_workbuf_result.error_message.empty()) {
return DecodeImageResult(std::move(alloc_workbuf_result.error_message));
} else if (alloc_workbuf_result.mem_slice.len < workbuf_len.min_incl) {
return DecodeImageResult(DecodeImage_BufferIsTooShort);
}
// Decode the frame config.
wuffs_base__frame_config frame_config;
while (true) {
wuffs_base__status id_dfc_status =
image_decoder->decode_frame_config(&frame_config, &io_buf);
if (id_dfc_status.repr == NULL) {
break;
} else if (id_dfc_status.repr != wuffs_base__suspension__short_read) {
return DecodeImageResult(id_dfc_status.message());
} else if (io_buf.meta.closed) {
return DecodeImageResult(DecodeImage_UnexpectedEndOfFile);
} else {
std::string error_message = input.CopyIn(&io_buf);
if (!error_message.empty()) {
return DecodeImageResult(std::move(error_message));
}
}
}
// Decode the frame (the pixels).
//
// From here on, always returns the pixel_buffer. If we get this far, we can
// still display a partial image, even if we encounter an error.
std::string message("");
if ((pixel_blend == WUFFS_BASE__PIXEL_BLEND__SRC_OVER) &&
frame_config.overwrite_instead_of_blend()) {
pixel_blend = WUFFS_BASE__PIXEL_BLEND__SRC;
}
while (true) {
wuffs_base__status id_df_status =
image_decoder->decode_frame(&pixel_buffer, &io_buf, pixel_blend,
alloc_workbuf_result.mem_slice, NULL);
if (id_df_status.repr == NULL) {
break;
} else if (id_df_status.repr != wuffs_base__suspension__short_read) {
message = id_df_status.message();
break;
} else if (io_buf.meta.closed) {
message = DecodeImage_UnexpectedEndOfFile;
break;
} else {
std::string error_message = input.CopyIn(&io_buf);
if (!error_message.empty()) {
message = std::move(error_message);
break;
}
}
}
return DecodeImageResult(std::move(oic_result.mem_owner),
oic_result.mem_slice, pixel_buffer,
std::move(message));
}
} // namespace
DecodeImageResult //
DecodeImage(DecodeImageCallbacks& callbacks,
sync_io::Input& input,
uint32_t override_pixel_format_repr,
wuffs_base__pixel_blend pixel_blend,
uint32_t max_incl_dimension) {
wuffs_base__io_buffer* io_buf = input.BringsItsOwnIOBuffer();
wuffs_base__io_buffer fallback_io_buf = wuffs_base__empty_io_buffer();
std::unique_ptr<uint8_t[]> fallback_io_array(nullptr);
if (!io_buf) {
fallback_io_array = std::unique_ptr<uint8_t[]>(new uint8_t[32768]);
fallback_io_buf =
wuffs_base__ptr_u8__writer(fallback_io_array.get(), 32768);
io_buf = &fallback_io_buf;
}
DecodeImageResult result =
DecodeImage0(callbacks, input, *io_buf, override_pixel_format_repr,
pixel_blend, max_incl_dimension);
callbacks.Done(result, input, *io_buf);
return result;
}
} // namespace wuffs_aux
#endif // !defined(WUFFS_CONFIG__MODULES) ||
// defined(WUFFS_CONFIG__MODULE__AUX__IMAGE)
// ---------------- Auxiliary - JSON
#if !defined(WUFFS_CONFIG__MODULES) || defined(WUFFS_CONFIG__MODULE__AUX__JSON)