Oolite
Loading...
Searching...
No Matches
tinyexr.h
Go to the documentation of this file.
1#ifndef TINYEXR_H_
2#define TINYEXR_H_
3/*
4Copyright (c) 2014 - 2021, Syoyo Fujita and many contributors.
5All rights reserved.
6
7Redistribution and use in source and binary forms, with or without
8modification, are permitted provided that the following conditions are met:
9 * Redistributions of source code must retain the above copyright
10 notice, this list of conditions and the following disclaimer.
11 * Redistributions in binary form must reproduce the above copyright
12 notice, this list of conditions and the following disclaimer in the
13 documentation and/or other materials provided with the distribution.
14 * Neither the name of the Syoyo Fujita nor the
15 names of its contributors may be used to endorse or promote products
16 derived from this software without specific prior written permission.
17
18THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
19ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
22DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
23(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
24LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
25ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
27SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28*/
29
30// TinyEXR contains some OpenEXR code, which is licensed under ------------
31
33//
34// Copyright (c) 2002, Industrial Light & Magic, a division of Lucas
35// Digital Ltd. LLC
36//
37// All rights reserved.
38//
39// Redistribution and use in source and binary forms, with or without
40// modification, are permitted provided that the following conditions are
41// met:
42// * Redistributions of source code must retain the above copyright
43// notice, this list of conditions and the following disclaimer.
44// * Redistributions in binary form must reproduce the above
45// copyright notice, this list of conditions and the following disclaimer
46// in the documentation and/or other materials provided with the
47// distribution.
48// * Neither the name of Industrial Light & Magic nor the names of
49// its contributors may be used to endorse or promote products derived
50// from this software without specific prior written permission.
51//
52// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
53// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
54// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
55// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
56// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
57// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
58// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
59// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
60// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
61// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
62// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
63//
65
66// End of OpenEXR license -------------------------------------------------
67
68//
69//
70// Do this:
71// #define TINYEXR_IMPLEMENTATION
72// before you include this file in *one* C or C++ file to create the
73// implementation.
74//
75// // i.e. it should look like this:
76// #include ...
77// #include ...
78// #include ...
79// #define TINYEXR_IMPLEMENTATION
80// #include "tinyexr.h"
81//
82//
83
84#include <stddef.h> // for size_t
85#include <stdint.h> // guess stdint.h is available(C99)
86
87#ifdef __cplusplus
88extern "C" {
89#endif
90
91#if defined(_M_IX86) || defined(_M_X64) || defined(__i386__) || defined(__i386) || defined(__i486__) || defined(__i486) || defined(i386) || defined(__ia64__) || defined(__x86_64__)
92#define TINYEXR_X86_OR_X64_CPU 1
93#else
94#define TINYEXR_X86_OR_X64_CPU 0
95#endif
96
97#if (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) || TINYEXR_X86_OR_X64_CPU
98#define TINYEXR_LITTLE_ENDIAN 1
99#else
100#define TINYEXR_LITTLE_ENDIAN 0
101#endif
102
103// Use miniz or not to decode ZIP format pixel. Linking with zlib
104// required if this flag is 0 and TINYEXR_USE_STB_ZLIB is 0.
105#ifndef TINYEXR_USE_MINIZ
106#define TINYEXR_USE_MINIZ (1)
107#endif
108
109// Use the ZIP implementation of stb_image.h and stb_image_write.h.
110#ifndef TINYEXR_USE_STB_ZLIB
111#define TINYEXR_USE_STB_ZLIB (0)
112#endif
113
114// Use nanozlib.
115#ifndef TINYEXR_USE_NANOZLIB
116#define TINYEXR_USE_NANOZLIB (0)
117#endif
118
119// Disable PIZ compression when applying cpplint.
120#ifndef TINYEXR_USE_PIZ
121#define TINYEXR_USE_PIZ (1)
122#endif
123
124#ifndef TINYEXR_USE_ZFP
125#define TINYEXR_USE_ZFP (0) // TinyEXR extension.
126// http://computation.llnl.gov/projects/floating-point-compression
127#endif
128
129#ifndef TINYEXR_USE_THREAD
130#define TINYEXR_USE_THREAD (0) // No threaded loading.
131// http://computation.llnl.gov/projects/floating-point-compression
132#endif
133
134#ifndef TINYEXR_USE_OPENMP
135#ifdef _OPENMP
136#define TINYEXR_USE_OPENMP (1)
137#else
138#define TINYEXR_USE_OPENMP (0)
139#endif
140#endif
141
142#define TINYEXR_SUCCESS (0)
143#define TINYEXR_ERROR_INVALID_MAGIC_NUMBER (-1)
144#define TINYEXR_ERROR_INVALID_EXR_VERSION (-2)
145#define TINYEXR_ERROR_INVALID_ARGUMENT (-3)
146#define TINYEXR_ERROR_INVALID_DATA (-4)
147#define TINYEXR_ERROR_INVALID_FILE (-5)
148#define TINYEXR_ERROR_INVALID_PARAMETER (-6)
149#define TINYEXR_ERROR_CANT_OPEN_FILE (-7)
150#define TINYEXR_ERROR_UNSUPPORTED_FORMAT (-8)
151#define TINYEXR_ERROR_INVALID_HEADER (-9)
152#define TINYEXR_ERROR_UNSUPPORTED_FEATURE (-10)
153#define TINYEXR_ERROR_CANT_WRITE_FILE (-11)
154#define TINYEXR_ERROR_SERIALIZATION_FAILED (-12)
155#define TINYEXR_ERROR_LAYER_NOT_FOUND (-13)
156#define TINYEXR_ERROR_DATA_TOO_LARGE (-14)
157
158// @note { OpenEXR file format: http://www.openexr.com/openexrfilelayout.pdf }
159
160// pixel type: possible values are: UINT = 0 HALF = 1 FLOAT = 2
161#define TINYEXR_PIXELTYPE_UINT (0)
162#define TINYEXR_PIXELTYPE_HALF (1)
163#define TINYEXR_PIXELTYPE_FLOAT (2)
164
165#define TINYEXR_MAX_HEADER_ATTRIBUTES (1024)
166#define TINYEXR_MAX_CUSTOM_ATTRIBUTES (128)
167
168#define TINYEXR_COMPRESSIONTYPE_NONE (0)
169#define TINYEXR_COMPRESSIONTYPE_RLE (1)
170#define TINYEXR_COMPRESSIONTYPE_ZIPS (2)
171#define TINYEXR_COMPRESSIONTYPE_ZIP (3)
172#define TINYEXR_COMPRESSIONTYPE_PIZ (4)
173#define TINYEXR_COMPRESSIONTYPE_ZFP (128) // TinyEXR extension
174
175#define TINYEXR_ZFP_COMPRESSIONTYPE_RATE (0)
176#define TINYEXR_ZFP_COMPRESSIONTYPE_PRECISION (1)
177#define TINYEXR_ZFP_COMPRESSIONTYPE_ACCURACY (2)
178
179#define TINYEXR_TILE_ONE_LEVEL (0)
180#define TINYEXR_TILE_MIPMAP_LEVELS (1)
181#define TINYEXR_TILE_RIPMAP_LEVELS (2)
182
183#define TINYEXR_TILE_ROUND_DOWN (0)
184#define TINYEXR_TILE_ROUND_UP (1)
185
186typedef struct TEXRVersion {
187 int version; // this must be 2
188 // tile format image;
189 // not zero for only a single-part "normal" tiled file (according to spec.)
190 int tiled;
191 int long_name; // long name attribute
192 // deep image(EXR 2.0);
193 // for a multi-part file, indicates that at least one part is of type deep* (according to spec.)
195 int multipart; // multi-part(EXR 2.0)
197
198typedef struct TEXRAttribute {
199 char name[256]; // name and type are up to 255 chars long.
200 char type[256];
201 unsigned char* value; // uint8_t*
202 int size;
203 int pad0;
205
206typedef struct TEXRChannelInfo {
207 char name[256]; // less than 255 bytes long
211 unsigned char p_linear;
212 unsigned char pad[3];
214
215typedef struct TEXRTile {
220
221 int width; // actual width in a tile.
222 int height; // actual height int a tile.
223
224 unsigned char** images; // image[channels][pixels]
226
227typedef struct TEXRBox2i {
228 int min_x;
229 int min_y;
230 int max_x;
231 int max_y;
233
234typedef struct TEXRHeader {
241
243
244 // Properties for tiled format(`tiledesc`).
245 int tiled;
250
252 // for a single-part file, agree with the version field bit 11
253 // for a multi-part file, it is consistent with the type of part
256 unsigned int header_len;
257
258 // Custom attributes(exludes required attributes(e.g. `channels`,
259 // `compression`, etc)
261 EXRAttribute* custom_attributes; // array of EXRAttribute. size =
262 // `num_custom_attributes`.
263
264 EXRChannelInfo* channels; // [num_channels]
265
266 int* pixel_types; // Loaded pixel type(TINYEXR_PIXELTYPE_*) of `images` for
267 // each channel. This is overwritten with `requested_pixel_types` when
268 // loading.
270
271 int compression_type; // compression type(TINYEXR_COMPRESSIONTYPE_*)
272 int* requested_pixel_types; // Filled initially by
273 // ParseEXRHeaderFrom(Meomory|File), then users
274 // can edit it(only valid for HALF pixel type
275 // channel)
276 // name attribute required for multipart files;
277 // must be unique and non empty (according to spec.);
278 // use EXRSetNameAttr for setting value;
279 // max 255 character allowed - excluding terminating zero
280 char name[256];
282
288
289typedef struct TEXRImage {
290 EXRTile* tiles; // Tiled pixel data. The application must reconstruct image
291 // from tiles manually. NULL if scanline format.
292 struct TEXRImage* next_level; // NULL if scanline format or image is the last level.
293 int level_x; // x level index
294 int level_y; // y level index
295
296 unsigned char** images; // image[channels][pixels]. NULL if tiled format.
297
298 int width;
301
302 // Properties for tile format.
304
306
312
313typedef struct TDeepImage {
314 const char** channel_names;
315 float*** image; // image[channels][scanlines][samples]
316 int** offset_table; // offset_table[scanline][offsets]
318 int width;
320 int pad0;
322
323// @deprecated { For backward compatibility. Not recommended to use. }
324// Loads single-frame OpenEXR image. Assume EXR image contains A(single channel
325// alpha) or RGB(A) channels.
326// Application must free image data as returned by `out_rgba`
327// Result image format is: float x RGBA x width x hight
328// Returns negative value and may set error string in `err` when there's an
329// error
330extern int LoadEXR(float** out_rgba, int* width, int* height,
331 const char* filename, const char** err);
332
333// Loads single-frame OpenEXR image by specifying layer name. Assume EXR image
334// contains A(single channel alpha) or RGB(A) channels. Application must free
335// image data as returned by `out_rgba` Result image format is: float x RGBA x
336// width x hight Returns negative value and may set error string in `err` when
337// there's an error When the specified layer name is not found in the EXR file,
338// the function will return `TINYEXR_ERROR_LAYER_NOT_FOUND`.
339extern int LoadEXRWithLayer(float** out_rgba, int* width, int* height,
340 const char* filename, const char* layer_name,
341 const char** err);
342
343//
344// Get layer infos from EXR file.
345//
346// @param[out] layer_names List of layer names. Application must free memory
347// after using this.
348// @param[out] num_layers The number of layers
349// @param[out] err Error string(will be filled when the function returns error
350// code). Free it using FreeEXRErrorMessage after using this value.
351//
352// @return TINYEXR_SUCCEES upon success.
353//
354extern int EXRLayers(const char* filename, const char** layer_names[],
355 int* num_layers, const char** err);
356
357// @deprecated
358// Simple wrapper API for ParseEXRHeaderFromFile.
359// checking given file is a EXR file(by just look up header)
360// @return TINYEXR_SUCCEES for EXR image, TINYEXR_ERROR_INVALID_HEADER for
361// others
362extern int IsEXR(const char* filename);
363
364// Simple wrapper API for ParseEXRHeaderFromMemory.
365// Check if given data is a EXR image(by just looking up a header section)
366// @return TINYEXR_SUCCEES for EXR image, TINYEXR_ERROR_INVALID_HEADER for
367// others
368extern int IsEXRFromMemory(const unsigned char* memory, size_t size);
369
370// @deprecated
371// Saves single-frame OpenEXR image to a buffer. Assume EXR image contains RGB(A) channels.
372// components must be 1(Grayscale), 3(RGB) or 4(RGBA).
373// Input image format is: `float x width x height`, or `float x RGB(A) x width x
374// hight`
375// Save image as fp16(HALF) format when `save_as_fp16` is positive non-zero
376// value.
377// Save image as fp32(FLOAT) format when `save_as_fp16` is 0.
378// Use ZIP compression by default.
379// `buffer` is the pointer to write EXR data.
380// Memory for `buffer` is allocated internally in SaveEXRToMemory.
381// Returns the data size of EXR file when the value is positive(up to 2GB EXR data).
382// Returns negative value and may set error string in `err` when there's an
383// error
384extern int SaveEXRToMemory(const float* data, const int width, const int height,
385 const int components, const int save_as_fp16,
386 unsigned char** buffer, const char** err);
387
388// @deprecated { Not recommended, but handy to use. }
389// Saves single-frame OpenEXR image to a buffer. Assume EXR image contains RGB(A) channels.
390// components must be 1(Grayscale), 3(RGB) or 4(RGBA).
391// Input image format is: `float x width x height`, or `float x RGB(A) x width x
392// hight`
393// Save image as fp16(HALF) format when `save_as_fp16` is positive non-zero
394// value.
395// Save image as fp32(FLOAT) format when `save_as_fp16` is 0.
396// Use ZIP compression by default.
397// Returns TINYEXR_SUCCEES(0) when success.
398// Returns negative value and may set error string in `err` when there's an
399// error
400extern int SaveEXR(const float* data, const int width, const int height,
401 const int components, const int save_as_fp16,
402 const char* filename, const char** err);
403
404// Returns the number of resolution levels of the image (including the base)
405extern int EXRNumLevels(const EXRImage* exr_image);
406
407// Initialize EXRHeader struct
408extern void InitEXRHeader(EXRHeader* exr_header);
409
410// Set name attribute of EXRHeader struct (it makes a copy)
411extern void EXRSetNameAttr(EXRHeader* exr_header, const char* name);
412
413// Initialize EXRImage struct
414extern void InitEXRImage(EXRImage* exr_image);
415
416// Frees internal data of EXRHeader struct
417extern int FreeEXRHeader(EXRHeader* exr_header);
418
419// Frees internal data of EXRImage struct
420extern int FreeEXRImage(EXRImage* exr_image);
421
422// Frees error message
423extern void FreeEXRErrorMessage(const char* msg);
424
425// Parse EXR version header of a file.
426extern int ParseEXRVersionFromFile(EXRVersion* version, const char* filename);
427
428// Parse EXR version header from memory-mapped EXR data.
430 const unsigned char* memory, size_t size);
431
432// Parse single-part OpenEXR header from a file and initialize `EXRHeader`.
433// When there was an error message, Application must free `err` with
434// FreeEXRErrorMessage()
435extern int ParseEXRHeaderFromFile(EXRHeader* header, const EXRVersion* version,
436 const char* filename, const char** err);
437
438// Parse single-part OpenEXR header from a memory and initialize `EXRHeader`.
439// When there was an error message, Application must free `err` with
440// FreeEXRErrorMessage()
442 const EXRVersion* version,
443 const unsigned char* memory, size_t size,
444 const char** err);
445
446// Parse multi-part OpenEXR headers from a file and initialize `EXRHeader*`
447// array.
448// When there was an error message, Application must free `err` with
449// FreeEXRErrorMessage()
451 int* num_headers,
452 const EXRVersion* version,
453 const char* filename,
454 const char** err);
455
456// Parse multi-part OpenEXR headers from a memory and initialize `EXRHeader*`
457// array
458// When there was an error message, Application must free `err` with
459// FreeEXRErrorMessage()
461 int* num_headers,
462 const EXRVersion* version,
463 const unsigned char* memory,
464 size_t size, const char** err);
465
466// Loads single-part OpenEXR image from a file.
467// Application must setup `ParseEXRHeaderFromFile` before calling this function.
468// Application can free EXRImage using `FreeEXRImage`
469// Returns negative value and may set error string in `err` when there's an
470// error
471// When there was an error message, Application must free `err` with
472// FreeEXRErrorMessage()
473extern int LoadEXRImageFromFile(EXRImage* image, const EXRHeader* header,
474 const char* filename, const char** err);
475
476// Loads single-part OpenEXR image from a memory.
477// Application must setup `EXRHeader` with
478// `ParseEXRHeaderFromMemory` before calling this function.
479// Application can free EXRImage using `FreeEXRImage`
480// Returns negative value and may set error string in `err` when there's an
481// error
482// When there was an error message, Application must free `err` with
483// FreeEXRErrorMessage()
484extern int LoadEXRImageFromMemory(EXRImage* image, const EXRHeader* header,
485 const unsigned char* memory,
486 const size_t size, const char** err);
487
488// Loads multi-part OpenEXR image from a file.
489// Application must setup `ParseEXRMultipartHeaderFromFile` before calling this
490// function.
491// Application can free EXRImage using `FreeEXRImage`
492// Returns negative value and may set error string in `err` when there's an
493// error
494// When there was an error message, Application must free `err` with
495// FreeEXRErrorMessage()
497 const EXRHeader** headers,
498 unsigned int num_parts,
499 const char* filename,
500 const char** err);
501
502// Loads multi-part OpenEXR image from a memory.
503// Application must setup `EXRHeader*` array with
504// `ParseEXRMultipartHeaderFromMemory` before calling this function.
505// Application can free EXRImage using `FreeEXRImage`
506// Returns negative value and may set error string in `err` when there's an
507// error
508// When there was an error message, Application must free `err` with
509// FreeEXRErrorMessage()
511 const EXRHeader** headers,
512 unsigned int num_parts,
513 const unsigned char* memory,
514 const size_t size, const char** err);
515
516// Saves multi-channel, single-frame OpenEXR image to a file.
517// Returns negative value and may set error string in `err` when there's an
518// error
519// When there was an error message, Application must free `err` with
520// FreeEXRErrorMessage()
521extern int SaveEXRImageToFile(const EXRImage* image,
522 const EXRHeader* exr_header, const char* filename,
523 const char** err);
524
525// Saves multi-channel, single-frame OpenEXR image to a memory.
526// Image is compressed using EXRImage.compression value.
527// Return the number of bytes if success.
528// Return zero and will set error string in `err` when there's an
529// error.
530// When there was an error message, Application must free `err` with
531// FreeEXRErrorMessage()
532extern size_t SaveEXRImageToMemory(const EXRImage* image,
533 const EXRHeader* exr_header,
534 unsigned char** memory, const char** err);
535
536// Saves multi-channel, multi-frame OpenEXR image to a memory.
537// Image is compressed using EXRImage.compression value.
538// File global attributes (eg. display_window) must be set in the first header.
539// Returns negative value and may set error string in `err` when there's an
540// error
541// When there was an error message, Application must free `err` with
542// FreeEXRErrorMessage()
543extern int SaveEXRMultipartImageToFile(const EXRImage* images,
544 const EXRHeader** exr_headers,
545 unsigned int num_parts,
546 const char* filename, const char** err);
547
548// Saves multi-channel, multi-frame OpenEXR image to a memory.
549// Image is compressed using EXRImage.compression value.
550// File global attributes (eg. display_window) must be set in the first header.
551// Return the number of bytes if success.
552// Return zero and will set error string in `err` when there's an
553// error.
554// When there was an error message, Application must free `err` with
555// FreeEXRErrorMessage()
556extern size_t SaveEXRMultipartImageToMemory(const EXRImage* images,
557 const EXRHeader** exr_headers,
558 unsigned int num_parts,
559 unsigned char** memory, const char** err);
560// Loads single-frame OpenEXR deep image.
561// Application must free memory of variables in DeepImage(image, offset_table)
562// Returns negative value and may set error string in `err` when there's an
563// error
564// When there was an error message, Application must free `err` with
565// FreeEXRErrorMessage()
566extern int LoadDeepEXR(DeepImage* out_image, const char* filename,
567 const char** err);
568
569// NOT YET IMPLEMENTED:
570// Saves single-frame OpenEXR deep image.
571// Returns negative value and may set error string in `err` when there's an
572// error
573// extern int SaveDeepEXR(const DeepImage *in_image, const char *filename,
574// const char **err);
575
576// NOT YET IMPLEMENTED:
577// Loads multi-part OpenEXR deep image.
578// Application must free memory of variables in DeepImage(image, offset_table)
579// extern int LoadMultiPartDeepEXR(DeepImage **out_image, int num_parts, const
580// char *filename,
581// const char **err);
582
583// For emscripten.
584// Loads single-frame OpenEXR image from memory. Assume EXR image contains
585// RGB(A) channels.
586// Returns negative value and may set error string in `err` when there's an
587// error
588// When there was an error message, Application must free `err` with
589// FreeEXRErrorMessage()
590extern int LoadEXRFromMemory(float** out_rgba, int* width, int* height,
591 const unsigned char* memory, size_t size,
592 const char** err);
593
594#ifdef __cplusplus
595}
596#endif
597
598#endif // TINYEXR_H_
599
600#ifdef TINYEXR_IMPLEMENTATION
601#ifndef TINYEXR_IMPLEMENTATION_DEFINED
602#define TINYEXR_IMPLEMENTATION_DEFINED
603
604#ifdef _WIN32
605
606#ifndef WIN32_LEAN_AND_MEAN
607#define WIN32_LEAN_AND_MEAN
608#endif
609#ifndef NOMINMAX
610#define NOMINMAX
611#endif
612#include <windows.h> // for UTF-8 and memory-mapping
613
614#if !defined(WINAPI_FAMILY) || (WINAPI_FAMILY == WINAPI_FAMILY_DESKTOP_APP)
615#define TINYEXR_USE_WIN32_MMAP (1)
616#endif
617
618#elif defined(__linux__) || defined(__unix__)
619#include <fcntl.h> // for open()
620#include <sys/mman.h> // for memory-mapping
621#include <sys/stat.h> // for stat
622#include <unistd.h> // for close()
623#define TINYEXR_USE_POSIX_MMAP (1)
624#endif
625
626#include <algorithm>
627#include <cstdio>
628#include <cstdlib>
629#include <cstring>
630#include <sstream>
631
632// #include <iostream> // debug
633
634#include <limits>
635#include <set>
636#include <string>
637#include <vector>
638
639// https://stackoverflow.com/questions/5047971/how-do-i-check-for-c11-support
640#if __cplusplus > 199711L || (defined(_MSC_VER) && _MSC_VER >= 1900)
641#define TINYEXR_HAS_CXX11 (1)
642// C++11
643#include <cstdint>
644
645#if TINYEXR_USE_THREAD
646#include <atomic>
647#include <thread>
648#endif
649
650#else // __cplusplus > 199711L
651#define TINYEXR_HAS_CXX11 (0)
652#endif // __cplusplus > 199711L
653
654#if TINYEXR_USE_OPENMP
655#include <omp.h>
656#endif
657
658#if defined(TINYEXR_USE_MINIZ) && (TINYEXR_USE_MINIZ == 1)
659#include <miniz.h>
660#else
661// Issue #46. Please include your own zlib-compatible API header before
662// including `tinyexr.h`
663// #include "zlib.h"
664#endif
665
666#if defined(TINYEXR_USE_NANOZLIB) && (TINYEXR_USE_NANOZLIB == 1)
667#define NANOZLIB_IMPLEMENTATION
668#include "nanozlib.h"
669#endif
670
671#if TINYEXR_USE_STB_ZLIB
672// Since we don't know where a project has stb_image.h and stb_image_write.h
673// and whether they are in the include path, we don't include them here, and
674// instead declare the two relevant functions manually.
675// from stb_image.h:
676extern "C" int stbi_zlib_decode_buffer(char* obuffer, int olen, const char* ibuffer, int ilen);
677// from stb_image_write.h:
678extern "C" unsigned char* stbi_zlib_compress(unsigned char* data, int data_len, int* out_len, int quality);
679#endif
680
681#if TINYEXR_USE_ZFP
682
683#ifdef __clang__
684#pragma clang diagnostic push
685#pragma clang diagnostic ignored "-Weverything"
686#endif
687
688#include "zfp.h"
689
690#ifdef __clang__
691#pragma clang diagnostic pop
692#endif
693
694#endif
695
696// cond: conditional expression
697// msg: std::string
698// err: std::string*
699#define TINYEXR_CHECK_AND_RETURN_MSG(cond, msg, err) \
700 do { \
701 if (!(cond)) { \
702 if (!err) { \
703 std::ostringstream ss_e; \
704 ss_e << __func__ << "():" << __LINE__ << msg << "\n"; \
705 (*err) += ss_e.str(); \
706 } \
707 return false; \
708 } \
709 } while (0)
710
711// no error message.
712#define TINYEXR_CHECK_AND_RETURN_C(cond, retcode) \
713 do { \
714 if (!(cond)) { \
715 return retcode; \
716 } \
717 } while (0)
718
719namespace tinyexr {
720
721#if __cplusplus > 199711L
722// C++11
723typedef uint64_t tinyexr_uint64;
724typedef int64_t tinyexr_int64;
725#else
726// Although `long long` is not a standard type pre C++11, assume it is defined
727// as a compiler's extension.
728#ifdef __clang__
729#pragma clang diagnostic push
730#pragma clang diagnostic ignored "-Wc++11-long-long"
731#endif
732typedef unsigned long long tinyexr_uint64;
733typedef long long tinyexr_int64;
734#ifdef __clang__
735#pragma clang diagnostic pop
736#endif
737#endif
738
739// static bool IsBigEndian(void) {
740// union {
741// unsigned int i;
742// char c[4];
743// } bint = {0x01020304};
744//
745// return bint.c[0] == 1;
746//}
747
748static void SetErrorMessage(const std::string& msg, const char** err)
749{
750 if (err) {
751#ifdef _WIN32
752 (*err) = _strdup(msg.c_str());
753#else
754 (*err) = strdup(msg.c_str());
755#endif
756 }
757}
758
759#if 0
760static void SetWarningMessage(const std::string &msg, const char **warn) {
761 if (warn) {
762#ifdef _WIN32
763 (*warn) = _strdup(msg.c_str());
764#else
765 (*warn) = strdup(msg.c_str());
766#endif
767 }
768}
769#endif
770
771static const unsigned int kEXRVersionSize = 8;
772
773static void cpy2(unsigned short* dst_val, const unsigned short* src_val)
774{
775 unsigned char* dst = reinterpret_cast<unsigned char*>(dst_val);
776 const unsigned char* src = reinterpret_cast<const unsigned char*>(src_val);
777
778 dst[0] = src[0];
779 dst[1] = src[1];
780}
781
782static void swap2(unsigned short* val)
783{
784#if TINYEXR_LITTLE_ENDIAN
785 (void)val;
786#else
787 unsigned short tmp = *val;
788 unsigned char* dst = reinterpret_cast<unsigned char*>(val);
789 unsigned char* src = reinterpret_cast<unsigned char*>(&tmp);
790
791 dst[0] = src[1];
792 dst[1] = src[0];
793#endif
794}
795
796#ifdef __clang__
797#pragma clang diagnostic push
798#pragma clang diagnostic ignored "-Wunused-function"
799#endif
800
801#ifdef __GNUC__
802#pragma GCC diagnostic push
803#pragma GCC diagnostic ignored "-Wunused-function"
804#endif
805static void cpy4(int* dst_val, const int* src_val)
806{
807 unsigned char* dst = reinterpret_cast<unsigned char*>(dst_val);
808 const unsigned char* src = reinterpret_cast<const unsigned char*>(src_val);
809
810 dst[0] = src[0];
811 dst[1] = src[1];
812 dst[2] = src[2];
813 dst[3] = src[3];
814}
815
816static void cpy4(unsigned int* dst_val, const unsigned int* src_val)
817{
818 unsigned char* dst = reinterpret_cast<unsigned char*>(dst_val);
819 const unsigned char* src = reinterpret_cast<const unsigned char*>(src_val);
820
821 dst[0] = src[0];
822 dst[1] = src[1];
823 dst[2] = src[2];
824 dst[3] = src[3];
825}
826
827static void cpy4(float* dst_val, const float* src_val)
828{
829 unsigned char* dst = reinterpret_cast<unsigned char*>(dst_val);
830 const unsigned char* src = reinterpret_cast<const unsigned char*>(src_val);
831
832 dst[0] = src[0];
833 dst[1] = src[1];
834 dst[2] = src[2];
835 dst[3] = src[3];
836}
837#ifdef __clang__
838#pragma clang diagnostic pop
839#endif
840
841#ifdef __GNUC__
842#pragma GCC diagnostic pop
843#endif
844
845static void swap4(unsigned int* val)
846{
847#if TINYEXR_LITTLE_ENDIAN
848 (void)val;
849#else
850 unsigned int tmp = *val;
851 unsigned char* dst = reinterpret_cast<unsigned char*>(val);
852 unsigned char* src = reinterpret_cast<unsigned char*>(&tmp);
853
854 dst[0] = src[3];
855 dst[1] = src[2];
856 dst[2] = src[1];
857 dst[3] = src[0];
858#endif
859}
860
861static void swap4(int* val)
862{
863#if TINYEXR_LITTLE_ENDIAN
864 (void)val;
865#else
866 int tmp = *val;
867 unsigned char* dst = reinterpret_cast<unsigned char*>(val);
868 unsigned char* src = reinterpret_cast<unsigned char*>(&tmp);
869
870 dst[0] = src[3];
871 dst[1] = src[2];
872 dst[2] = src[1];
873 dst[3] = src[0];
874#endif
875}
876
877static void swap4(float* val)
878{
879#if TINYEXR_LITTLE_ENDIAN
880 (void)val;
881#else
882 float tmp = *val;
883 unsigned char* dst = reinterpret_cast<unsigned char*>(val);
884 unsigned char* src = reinterpret_cast<unsigned char*>(&tmp);
885
886 dst[0] = src[3];
887 dst[1] = src[2];
888 dst[2] = src[1];
889 dst[3] = src[0];
890#endif
891}
892
893#if 0
894static void cpy8(tinyexr::tinyexr_uint64 *dst_val, const tinyexr::tinyexr_uint64 *src_val) {
895 unsigned char *dst = reinterpret_cast<unsigned char *>(dst_val);
896 const unsigned char *src = reinterpret_cast<const unsigned char *>(src_val);
897
898 dst[0] = src[0];
899 dst[1] = src[1];
900 dst[2] = src[2];
901 dst[3] = src[3];
902 dst[4] = src[4];
903 dst[5] = src[5];
904 dst[6] = src[6];
905 dst[7] = src[7];
906}
907#endif
908
909static void swap8(tinyexr::tinyexr_uint64* val)
910{
911#if TINYEXR_LITTLE_ENDIAN
912 (void)val;
913#else
914 tinyexr::tinyexr_uint64 tmp = (*val);
915 unsigned char* dst = reinterpret_cast<unsigned char*>(val);
916 unsigned char* src = reinterpret_cast<unsigned char*>(&tmp);
917
918 dst[0] = src[7];
919 dst[1] = src[6];
920 dst[2] = src[5];
921 dst[3] = src[4];
922 dst[4] = src[3];
923 dst[5] = src[2];
924 dst[6] = src[1];
925 dst[7] = src[0];
926#endif
927}
928
929// https://gist.github.com/rygorous/2156668
930union FP32 {
931 unsigned int u;
932 float f;
933 struct {
934#if TINYEXR_LITTLE_ENDIAN
935 unsigned int Mantissa : 23;
936 unsigned int Exponent : 8;
937 unsigned int Sign : 1;
938#else
939 unsigned int Sign : 1;
940 unsigned int Exponent : 8;
941 unsigned int Mantissa : 23;
942#endif
943 } s;
944};
945
946#ifdef __clang__
947#pragma clang diagnostic push
948#pragma clang diagnostic ignored "-Wpadded"
949#endif
950
951union FP16 {
952 unsigned short u;
953 struct {
954#if TINYEXR_LITTLE_ENDIAN
955 unsigned int Mantissa : 10;
956 unsigned int Exponent : 5;
957 unsigned int Sign : 1;
958#else
959 unsigned int Sign : 1;
960 unsigned int Exponent : 5;
961 unsigned int Mantissa : 10;
962#endif
963 } s;
964};
965
966#ifdef __clang__
967#pragma clang diagnostic pop
968#endif
969
970static FP32 half_to_float(FP16 h)
971{
972 static const FP32 magic = { 113 << 23 };
973 static const unsigned int shifted_exp = 0x7c00
974 << 13; // exponent mask after shift
975 FP32 o;
976
977 o.u = (h.u & 0x7fffU) << 13U; // exponent/mantissa bits
978 unsigned int exp_ = shifted_exp & o.u; // just the exponent
979 o.u += (127 - 15) << 23; // exponent adjust
980
981 // handle exponent special cases
982 if (exp_ == shifted_exp) // Inf/NaN?
983 o.u += (128 - 16) << 23; // extra exp adjust
984 else if (exp_ == 0) // Zero/Denormal?
985 {
986 o.u += 1 << 23; // extra exp adjust
987 o.f -= magic.f; // renormalize
988 }
989
990 o.u |= (h.u & 0x8000U) << 16U; // sign bit
991 return o;
992}
993
994static FP16 float_to_half_full(FP32 f)
995{
996 FP16 o = { 0 };
997
998 // Based on ISPC reference code (with minor modifications)
999 if (f.s.Exponent == 0) // Signed zero/denormal (which will underflow)
1000 o.s.Exponent = 0;
1001 else if (f.s.Exponent == 255) // Inf or NaN (all exponent bits set)
1002 {
1003 o.s.Exponent = 31;
1004 o.s.Mantissa = f.s.Mantissa ? 0x200 : 0; // NaN->qNaN and Inf->Inf
1005 } else // Normalized number
1006 {
1007 // Exponent unbias the single, then bias the halfp
1008 int newexp = f.s.Exponent - 127 + 15;
1009 if (newexp >= 31) // Overflow, return signed infinity
1010 o.s.Exponent = 31;
1011 else if (newexp <= 0) // Underflow
1012 {
1013 if ((14 - newexp) <= 24) // Mantissa might be non-zero
1014 {
1015 unsigned int mant = f.s.Mantissa | 0x800000; // Hidden 1 bit
1016 o.s.Mantissa = mant >> (14 - newexp);
1017 if ((mant >> (13 - newexp)) & 1) // Check for rounding
1018 o.u++; // Round, might overflow into exp bit, but this is OK
1019 }
1020 } else {
1021 o.s.Exponent = static_cast<unsigned int>(newexp);
1022 o.s.Mantissa = f.s.Mantissa >> 13;
1023 if (f.s.Mantissa & 0x1000) // Check for rounding
1024 o.u++; // Round, might overflow to inf, this is OK
1025 }
1026 }
1027
1028 o.s.Sign = f.s.Sign;
1029 return o;
1030}
1031
1032// NOTE: From OpenEXR code
1033// #define IMF_INCREASING_Y 0
1034// #define IMF_DECREASING_Y 1
1035// #define IMF_RAMDOM_Y 2
1036//
1037// #define IMF_NO_COMPRESSION 0
1038// #define IMF_RLE_COMPRESSION 1
1039// #define IMF_ZIPS_COMPRESSION 2
1040// #define IMF_ZIP_COMPRESSION 3
1041// #define IMF_PIZ_COMPRESSION 4
1042// #define IMF_PXR24_COMPRESSION 5
1043// #define IMF_B44_COMPRESSION 6
1044// #define IMF_B44A_COMPRESSION 7
1045
1046#ifdef __clang__
1047#pragma clang diagnostic push
1048
1049#if __has_warning("-Wzero-as-null-pointer-constant")
1050#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant"
1051#endif
1052
1053#endif
1054
1055static const char* ReadString(std::string* s, const char* ptr, size_t len)
1056{
1057 // Read untile NULL(\0).
1058 const char* p = ptr;
1059 const char* q = ptr;
1060 while ((size_t(q - ptr) < len) && (*q) != 0) {
1061 q++;
1062 }
1063
1064 if (size_t(q - ptr) >= len) {
1065 (*s).clear();
1066 return NULL;
1067 }
1068
1069 (*s) = std::string(p, q);
1070
1071 return q + 1; // skip '\0'
1072}
1073
1074static bool ReadAttribute(std::string* name, std::string* type,
1075 std::vector<unsigned char>* data, size_t* marker_size,
1076 const char* marker, size_t size)
1077{
1078 size_t name_len = strnlen(marker, size);
1079 if (name_len == size) {
1080 // String does not have a terminating character.
1081 return false;
1082 }
1083 *name = std::string(marker, name_len);
1084
1085 marker += name_len + 1;
1086 size -= name_len + 1;
1087
1088 size_t type_len = strnlen(marker, size);
1089 if (type_len == size) {
1090 return false;
1091 }
1092 *type = std::string(marker, type_len);
1093
1094 marker += type_len + 1;
1095 size -= type_len + 1;
1096
1097 if (size < sizeof(uint32_t)) {
1098 return false;
1099 }
1100
1101 uint32_t data_len;
1102 memcpy(&data_len, marker, sizeof(uint32_t));
1103 tinyexr::swap4(reinterpret_cast<unsigned int*>(&data_len));
1104
1105 if (data_len == 0) {
1106 if ((*type).compare("string") == 0) {
1107 // Accept empty string attribute.
1108
1109 marker += sizeof(uint32_t);
1110 size -= sizeof(uint32_t);
1111
1112 *marker_size = name_len + 1 + type_len + 1 + sizeof(uint32_t);
1113
1114 data->resize(1);
1115 (*data)[0] = '\0';
1116
1117 return true;
1118 } else {
1119 return false;
1120 }
1121 }
1122
1123 marker += sizeof(uint32_t);
1124 size -= sizeof(uint32_t);
1125
1126 if (size < data_len) {
1127 return false;
1128 }
1129
1130 data->resize(static_cast<size_t>(data_len));
1131 memcpy(&data->at(0), marker, static_cast<size_t>(data_len));
1132
1133 *marker_size = name_len + 1 + type_len + 1 + sizeof(uint32_t) + data_len;
1134 return true;
1135}
1136
1137static void WriteAttributeToMemory(std::vector<unsigned char>* out,
1138 const char* name, const char* type,
1139 const unsigned char* data, int len)
1140{
1141 out->insert(out->end(), name, name + strlen(name) + 1);
1142 out->insert(out->end(), type, type + strlen(type) + 1);
1143
1144 int outLen = len;
1145 tinyexr::swap4(&outLen);
1146 out->insert(out->end(), reinterpret_cast<unsigned char*>(&outLen),
1147 reinterpret_cast<unsigned char*>(&outLen) + sizeof(int));
1148 out->insert(out->end(), data, data + len);
1149}
1150
1151typedef struct TChannelInfo {
1152 std::string name; // less than 255 bytes long
1153 int pixel_type;
1154 int requested_pixel_type;
1155 int x_sampling;
1156 int y_sampling;
1157 unsigned char p_linear;
1158 unsigned char pad[3];
1159} ChannelInfo;
1160
1161typedef struct {
1162 int min_x;
1163 int min_y;
1164 int max_x;
1165 int max_y;
1166} Box2iInfo;
1167
1168struct HeaderInfo {
1169 std::vector<tinyexr::ChannelInfo> channels;
1170 std::vector<EXRAttribute> attributes;
1171
1172 Box2iInfo data_window;
1173 int line_order;
1174 Box2iInfo display_window;
1175 float screen_window_center[2];
1176 float screen_window_width;
1177 float pixel_aspect_ratio;
1178
1179 int chunk_count;
1180
1181 // Tiled format
1182 int tiled; // Non-zero if the part is tiled.
1183 int tile_size_x;
1184 int tile_size_y;
1185 int tile_level_mode;
1186 int tile_rounding_mode;
1187
1188 unsigned int header_len;
1189
1190 int compression_type;
1191
1192 // required for multi-part or non-image files
1193 std::string name;
1194 // required for multi-part or non-image files
1195 std::string type;
1196
1197 void clear()
1198 {
1199 channels.clear();
1200 attributes.clear();
1201
1202 data_window.min_x = 0;
1203 data_window.min_y = 0;
1204 data_window.max_x = 0;
1205 data_window.max_y = 0;
1206 line_order = 0;
1207 display_window.min_x = 0;
1208 display_window.min_y = 0;
1209 display_window.max_x = 0;
1210 display_window.max_y = 0;
1211 screen_window_center[0] = 0.0f;
1212 screen_window_center[1] = 0.0f;
1213 screen_window_width = 0.0f;
1214 pixel_aspect_ratio = 0.0f;
1215
1216 chunk_count = 0;
1217
1218 // Tiled format
1219 tiled = 0;
1220 tile_size_x = 0;
1221 tile_size_y = 0;
1222 tile_level_mode = 0;
1223 tile_rounding_mode = 0;
1224
1225 header_len = 0;
1226 compression_type = 0;
1227
1228 name.clear();
1229 type.clear();
1230 }
1231};
1232
1233static bool ReadChannelInfo(std::vector<ChannelInfo>& channels,
1234 const std::vector<unsigned char>& data)
1235{
1236 const char* p = reinterpret_cast<const char*>(&data.at(0));
1237
1238 for (;;) {
1239 if ((*p) == 0) {
1240 break;
1241 }
1242 ChannelInfo info;
1243 info.requested_pixel_type = 0;
1244
1245 tinyexr_int64 data_len = static_cast<tinyexr_int64>(data.size()) - (p - reinterpret_cast<const char*>(data.data()));
1246 if (data_len < 0) {
1247 return false;
1248 }
1249
1250 p = ReadString(&info.name, p, size_t(data_len));
1251 if ((p == NULL) && (info.name.empty())) {
1252 // Buffer overrun. Issue #51.
1253 return false;
1254 }
1255
1256 const unsigned char* data_end = reinterpret_cast<const unsigned char*>(p) + 16;
1257 if (data_end >= (data.data() + data.size())) {
1258 return false;
1259 }
1260
1261 memcpy(&info.pixel_type, p, sizeof(int));
1262 p += 4;
1263 info.p_linear = static_cast<unsigned char>(p[0]); // uchar
1264 p += 1 + 3; // reserved: uchar[3]
1265 memcpy(&info.x_sampling, p, sizeof(int)); // int
1266 p += 4;
1267 memcpy(&info.y_sampling, p, sizeof(int)); // int
1268 p += 4;
1269
1270 tinyexr::swap4(&info.pixel_type);
1271 tinyexr::swap4(&info.x_sampling);
1272 tinyexr::swap4(&info.y_sampling);
1273
1274 channels.push_back(info);
1275 }
1276
1277 return true;
1278}
1279
1280static void WriteChannelInfo(std::vector<unsigned char>& data,
1281 const std::vector<ChannelInfo>& channels)
1282{
1283 size_t sz = 0;
1284
1285 // Calculate total size.
1286 for (size_t c = 0; c < channels.size(); c++) {
1287 sz += channels[c].name.length() + 1; // +1 for \0
1288 sz += 16; // 4 * int
1289 }
1290 data.resize(sz + 1);
1291
1292 unsigned char* p = &data.at(0);
1293
1294 for (size_t c = 0; c < channels.size(); c++) {
1295 memcpy(p, channels[c].name.c_str(), channels[c].name.length());
1296 p += channels[c].name.length();
1297 (*p) = '\0';
1298 p++;
1299
1300 int pixel_type = channels[c].requested_pixel_type;
1301 int x_sampling = channels[c].x_sampling;
1302 int y_sampling = channels[c].y_sampling;
1303 tinyexr::swap4(&pixel_type);
1304 tinyexr::swap4(&x_sampling);
1305 tinyexr::swap4(&y_sampling);
1306
1307 memcpy(p, &pixel_type, sizeof(int));
1308 p += sizeof(int);
1309
1310 (*p) = channels[c].p_linear;
1311 p += 4;
1312
1313 memcpy(p, &x_sampling, sizeof(int));
1314 p += sizeof(int);
1315
1316 memcpy(p, &y_sampling, sizeof(int));
1317 p += sizeof(int);
1318 }
1319
1320 (*p) = '\0';
1321}
1322
1323static bool CompressZip(unsigned char* dst,
1324 tinyexr::tinyexr_uint64& compressedSize,
1325 const unsigned char* src, unsigned long src_size)
1326{
1327 std::vector<unsigned char> tmpBuf(src_size);
1328
1329 //
1330 // Apply EXR-specific? postprocess. Grabbed from OpenEXR's
1331 // ImfZipCompressor.cpp
1332 //
1333
1334 //
1335 // Reorder the pixel data.
1336 //
1337
1338 const char* srcPtr = reinterpret_cast<const char*>(src);
1339
1340 {
1341 char* t1 = reinterpret_cast<char*>(&tmpBuf.at(0));
1342 char* t2 = reinterpret_cast<char*>(&tmpBuf.at(0)) + (src_size + 1) / 2;
1343 const char* stop = srcPtr + src_size;
1344
1345 for (;;) {
1346 if (srcPtr < stop)
1347 *(t1++) = *(srcPtr++);
1348 else
1349 break;
1350
1351 if (srcPtr < stop)
1352 *(t2++) = *(srcPtr++);
1353 else
1354 break;
1355 }
1356 }
1357
1358 //
1359 // Predictor.
1360 //
1361
1362 {
1363 unsigned char* t = &tmpBuf.at(0) + 1;
1364 unsigned char* stop = &tmpBuf.at(0) + src_size;
1365 int p = t[-1];
1366
1367 while (t < stop) {
1368 int d = int(t[0]) - p + (128 + 256);
1369 p = t[0];
1370 t[0] = static_cast<unsigned char>(d);
1371 ++t;
1372 }
1373 }
1374
1375#if defined(TINYEXR_USE_MINIZ) && (TINYEXR_USE_MINIZ == 1)
1376 //
1377 // Compress the data using miniz
1378 //
1379
1380 mz_ulong outSize = mz_compressBound(src_size);
1381 int ret = mz_compress(
1382 dst, &outSize, static_cast<const unsigned char*>(&tmpBuf.at(0)),
1383 src_size);
1384 if (ret != MZ_OK) {
1385 return false;
1386 }
1387
1388 compressedSize = outSize;
1389#elif defined(TINYEXR_USE_STB_ZLIB) && (TINYEXR_USE_STB_ZLIB == 1)
1390 int outSize;
1391 unsigned char* ret = stbi_zlib_compress(const_cast<unsigned char*>(&tmpBuf.at(0)), src_size, &outSize, 8);
1392 if (!ret) {
1393 return false;
1394 }
1395 memcpy(dst, ret, outSize);
1396 free(ret);
1397
1398 compressedSize = outSize;
1399#elif defined(TINYEXR_USE_NANOZLIB) && (TINYEXR_USE_NANOZLIB == 1)
1400 uint64_t dstSize = nanoz_compressBound(static_cast<uint64_t>(src_size));
1401 int outSize { 0 };
1402 unsigned char* ret = nanoz_compress(&tmpBuf.at(0), src_size, &outSize, /* quality */ 8);
1403 if (!ret) {
1404 return false;
1405 }
1406
1407 memcpy(dst, ret, outSize);
1408 free(ret);
1409
1410 compressedSize = outSize;
1411#else
1412 uLong outSize = compressBound(static_cast<uLong>(src_size));
1413 int ret = compress(dst, &outSize, static_cast<const Bytef*>(&tmpBuf.at(0)),
1414 src_size);
1415 if (ret != Z_OK) {
1416 return false;
1417 }
1418
1419 compressedSize = outSize;
1420#endif
1421
1422 // Use uncompressed data when compressed data is larger than uncompressed.
1423 // (Issue 40)
1424 if (compressedSize >= src_size) {
1425 compressedSize = src_size;
1426 memcpy(dst, src, src_size);
1427 }
1428
1429 return true;
1430}
1431
1432static bool DecompressZip(unsigned char* dst,
1433 unsigned long* uncompressed_size /* inout */,
1434 const unsigned char* src, unsigned long src_size)
1435{
1436 if ((*uncompressed_size) == src_size) {
1437 // Data is not compressed(Issue 40).
1438 memcpy(dst, src, src_size);
1439 return true;
1440 }
1441 std::vector<unsigned char> tmpBuf(*uncompressed_size);
1442
1443#if defined(TINYEXR_USE_MINIZ) && (TINYEXR_USE_MINIZ == 1)
1444 int ret = mz_uncompress(&tmpBuf.at(0), uncompressed_size, src, src_size);
1445 if (MZ_OK != ret) {
1446 return false;
1447 }
1448#elif TINYEXR_USE_STB_ZLIB
1449 int ret = stbi_zlib_decode_buffer(reinterpret_cast<char*>(&tmpBuf.at(0)),
1450 *uncompressed_size, reinterpret_cast<const char*>(src), src_size);
1451 if (ret < 0) {
1452 return false;
1453 }
1454#elif defined(TINYEXR_USE_NANOZLIB) && (TINYEXR_USE_NANOZLIB == 1)
1455 uint64_t dest_size = (*uncompressed_size);
1456 uint64_t uncomp_size { 0 };
1457 nanoz_status_t ret = nanoz_uncompress(src, src_size, dest_size, &tmpBuf.at(0), &uncomp_size);
1458 if (NANOZ_SUCCESS != ret) {
1459 return false;
1460 }
1461 if ((*uncompressed_size) != uncomp_size) {
1462 return false;
1463 }
1464#else
1465 int ret = uncompress(&tmpBuf.at(0), uncompressed_size, src, src_size);
1466 if (Z_OK != ret) {
1467 return false;
1468 }
1469#endif
1470
1471 //
1472 // Apply EXR-specific? postprocess. Grabbed from OpenEXR's
1473 // ImfZipCompressor.cpp
1474 //
1475
1476 // Predictor.
1477 {
1478 unsigned char* t = &tmpBuf.at(0) + 1;
1479 unsigned char* stop = &tmpBuf.at(0) + (*uncompressed_size);
1480
1481 while (t < stop) {
1482 int d = int(t[-1]) + int(t[0]) - 128;
1483 t[0] = static_cast<unsigned char>(d);
1484 ++t;
1485 }
1486 }
1487
1488 // Reorder the pixel data.
1489 {
1490 const char* t1 = reinterpret_cast<const char*>(&tmpBuf.at(0));
1491 const char* t2 = reinterpret_cast<const char*>(&tmpBuf.at(0)) + (*uncompressed_size + 1) / 2;
1492 char* s = reinterpret_cast<char*>(dst);
1493 char* stop = s + (*uncompressed_size);
1494
1495 for (;;) {
1496 if (s < stop)
1497 *(s++) = *(t1++);
1498 else
1499 break;
1500
1501 if (s < stop)
1502 *(s++) = *(t2++);
1503 else
1504 break;
1505 }
1506 }
1507
1508 return true;
1509}
1510
1511// RLE code from OpenEXR --------------------------------------
1512
1513#ifdef __clang__
1514#pragma clang diagnostic push
1515#pragma clang diagnostic ignored "-Wsign-conversion"
1516#if __has_warning("-Wextra-semi-stmt")
1517#pragma clang diagnostic ignored "-Wextra-semi-stmt"
1518#endif
1519#endif
1520
1521#ifdef _MSC_VER
1522#pragma warning(push)
1523#pragma warning(disable : 4204) // nonstandard extension used : non-constant
1524 // aggregate initializer (also supported by GNU
1525 // C and C99, so no big deal)
1526#pragma warning(disable : 4244) // 'initializing': conversion from '__int64' to
1527 // 'int', possible loss of data
1528#pragma warning(disable : 4267) // 'argument': conversion from '__int64' to
1529 // 'int', possible loss of data
1530#pragma warning(disable : 4996) // 'strdup': The POSIX name for this item is
1531 // deprecated. Instead, use the ISO C and C++
1532 // conformant name: _strdup.
1533#endif
1534
1535const int MIN_RUN_LENGTH = 3;
1536const int MAX_RUN_LENGTH = 127;
1537
1538//
1539// Compress an array of bytes, using run-length encoding,
1540// and return the length of the compressed data.
1541//
1542
1543static int rleCompress(int inLength, const char in[], signed char out[])
1544{
1545 const char* inEnd = in + inLength;
1546 const char* runStart = in;
1547 const char* runEnd = in + 1;
1548 signed char* outWrite = out;
1549
1550 while (runStart < inEnd) {
1551 while (runEnd < inEnd && *runStart == *runEnd && runEnd - runStart - 1 < MAX_RUN_LENGTH) {
1552 ++runEnd;
1553 }
1554
1555 if (runEnd - runStart >= MIN_RUN_LENGTH) {
1556 //
1557 // Compressible run
1558 //
1559
1560 *outWrite++ = static_cast<char>(runEnd - runStart) - 1;
1561 *outWrite++ = *(reinterpret_cast<const signed char*>(runStart));
1562 runStart = runEnd;
1563 } else {
1564 //
1565 // Uncompressable run
1566 //
1567
1568 while (runEnd < inEnd && ((runEnd + 1 >= inEnd || *runEnd != *(runEnd + 1)) || (runEnd + 2 >= inEnd || *(runEnd + 1) != *(runEnd + 2))) && runEnd - runStart < MAX_RUN_LENGTH) {
1569 ++runEnd;
1570 }
1571
1572 *outWrite++ = static_cast<char>(runStart - runEnd);
1573
1574 while (runStart < runEnd) {
1575 *outWrite++ = *(reinterpret_cast<const signed char*>(runStart++));
1576 }
1577 }
1578
1579 ++runEnd;
1580 }
1581
1582 return static_cast<int>(outWrite - out);
1583}
1584
1585//
1586// Uncompress an array of bytes compressed with rleCompress().
1587// Returns the length of the uncompressed data, or 0 if the
1588// length of the uncompressed data would be more than maxLength.
1589//
1590
1591static int rleUncompress(int inLength, int maxLength, const signed char in[],
1592 char out[])
1593{
1594 char* outStart = out;
1595
1596 while (inLength > 0) {
1597 if (*in < 0) {
1598 int count = -(static_cast<int>(*in++));
1599 inLength -= count + 1;
1600
1601 // Fixes #116: Add bounds check to in buffer.
1602 if ((0 > (maxLength -= count)) || (inLength < 0))
1603 return 0;
1604
1605 memcpy(out, in, count);
1606 out += count;
1607 in += count;
1608 } else {
1609 int count = *in++;
1610 inLength -= 2;
1611
1612 if ((0 > (maxLength -= count + 1)) || (inLength < 0))
1613 return 0;
1614
1615 memset(out, *reinterpret_cast<const char*>(in), count + 1);
1616 out += count + 1;
1617
1618 in++;
1619 }
1620 }
1621
1622 return static_cast<int>(out - outStart);
1623}
1624
1625#ifdef __clang__
1626#pragma clang diagnostic pop
1627#endif
1628
1629// End of RLE code from OpenEXR -----------------------------------
1630
1631static bool CompressRle(unsigned char* dst,
1632 tinyexr::tinyexr_uint64& compressedSize,
1633 const unsigned char* src, unsigned long src_size)
1634{
1635 std::vector<unsigned char> tmpBuf(src_size);
1636
1637 //
1638 // Apply EXR-specific? postprocess. Grabbed from OpenEXR's
1639 // ImfRleCompressor.cpp
1640 //
1641
1642 //
1643 // Reorder the pixel data.
1644 //
1645
1646 const char* srcPtr = reinterpret_cast<const char*>(src);
1647
1648 {
1649 char* t1 = reinterpret_cast<char*>(&tmpBuf.at(0));
1650 char* t2 = reinterpret_cast<char*>(&tmpBuf.at(0)) + (src_size + 1) / 2;
1651 const char* stop = srcPtr + src_size;
1652
1653 for (;;) {
1654 if (srcPtr < stop)
1655 *(t1++) = *(srcPtr++);
1656 else
1657 break;
1658
1659 if (srcPtr < stop)
1660 *(t2++) = *(srcPtr++);
1661 else
1662 break;
1663 }
1664 }
1665
1666 //
1667 // Predictor.
1668 //
1669
1670 {
1671 unsigned char* t = &tmpBuf.at(0) + 1;
1672 unsigned char* stop = &tmpBuf.at(0) + src_size;
1673 int p = t[-1];
1674
1675 while (t < stop) {
1676 int d = int(t[0]) - p + (128 + 256);
1677 p = t[0];
1678 t[0] = static_cast<unsigned char>(d);
1679 ++t;
1680 }
1681 }
1682
1683 // outSize will be (srcSiz * 3) / 2 at max.
1684 int outSize = rleCompress(static_cast<int>(src_size),
1685 reinterpret_cast<const char*>(&tmpBuf.at(0)),
1686 reinterpret_cast<signed char*>(dst));
1687 TINYEXR_CHECK_AND_RETURN_C(outSize > 0, false);
1688
1689 compressedSize = static_cast<tinyexr::tinyexr_uint64>(outSize);
1690
1691 // Use uncompressed data when compressed data is larger than uncompressed.
1692 // (Issue 40)
1693 if (compressedSize >= src_size) {
1694 compressedSize = src_size;
1695 memcpy(dst, src, src_size);
1696 }
1697
1698 return true;
1699}
1700
1701static bool DecompressRle(unsigned char* dst,
1702 const unsigned long uncompressed_size,
1703 const unsigned char* src, unsigned long src_size)
1704{
1705 if (uncompressed_size == src_size) {
1706 // Data is not compressed(Issue 40).
1707 memcpy(dst, src, src_size);
1708 return true;
1709 }
1710
1711 // Workaround for issue #112.
1712 // TODO(syoyo): Add more robust out-of-bounds check in `rleUncompress`.
1713 if (src_size <= 2) {
1714 return false;
1715 }
1716
1717 std::vector<unsigned char> tmpBuf(uncompressed_size);
1718
1719 int ret = rleUncompress(static_cast<int>(src_size),
1720 static_cast<int>(uncompressed_size),
1721 reinterpret_cast<const signed char*>(src),
1722 reinterpret_cast<char*>(&tmpBuf.at(0)));
1723 if (ret != static_cast<int>(uncompressed_size)) {
1724 return false;
1725 }
1726
1727 //
1728 // Apply EXR-specific? postprocess. Grabbed from OpenEXR's
1729 // ImfRleCompressor.cpp
1730 //
1731
1732 // Predictor.
1733 {
1734 unsigned char* t = &tmpBuf.at(0) + 1;
1735 unsigned char* stop = &tmpBuf.at(0) + uncompressed_size;
1736
1737 while (t < stop) {
1738 int d = int(t[-1]) + int(t[0]) - 128;
1739 t[0] = static_cast<unsigned char>(d);
1740 ++t;
1741 }
1742 }
1743
1744 // Reorder the pixel data.
1745 {
1746 const char* t1 = reinterpret_cast<const char*>(&tmpBuf.at(0));
1747 const char* t2 = reinterpret_cast<const char*>(&tmpBuf.at(0)) + (uncompressed_size + 1) / 2;
1748 char* s = reinterpret_cast<char*>(dst);
1749 char* stop = s + uncompressed_size;
1750
1751 for (;;) {
1752 if (s < stop)
1753 *(s++) = *(t1++);
1754 else
1755 break;
1756
1757 if (s < stop)
1758 *(s++) = *(t2++);
1759 else
1760 break;
1761 }
1762 }
1763
1764 return true;
1765}
1766
1767#if TINYEXR_USE_PIZ
1768
1769#ifdef __clang__
1770#pragma clang diagnostic push
1771#pragma clang diagnostic ignored "-Wc++11-long-long"
1772#pragma clang diagnostic ignored "-Wold-style-cast"
1773#pragma clang diagnostic ignored "-Wpadded"
1774#pragma clang diagnostic ignored "-Wsign-conversion"
1775#pragma clang diagnostic ignored "-Wc++11-extensions"
1776#pragma clang diagnostic ignored "-Wconversion"
1777#pragma clang diagnostic ignored "-Wc++98-compat-pedantic"
1778
1779#if __has_warning("-Wcast-qual")
1780#pragma clang diagnostic ignored "-Wcast-qual"
1781#endif
1782
1783#if __has_warning("-Wextra-semi-stmt")
1784#pragma clang diagnostic ignored "-Wextra-semi-stmt"
1785#endif
1786
1787#endif
1788
1789//
1790// PIZ compress/uncompress, based on OpenEXR's ImfPizCompressor.cpp
1791//
1792// -----------------------------------------------------------------
1793// Copyright (c) 2004, Industrial Light & Magic, a division of Lucas
1794// Digital Ltd. LLC)
1795// (3 clause BSD license)
1796//
1797
1798struct PIZChannelData {
1799 unsigned short* start;
1800 unsigned short* end;
1801 int nx;
1802 int ny;
1803 int ys;
1804 int size;
1805};
1806
1807//-----------------------------------------------------------------------------
1808//
1809// 16-bit Haar Wavelet encoding and decoding
1810//
1811// The source code in this file is derived from the encoding
1812// and decoding routines written by Christian Rouet for his
1813// PIZ image file format.
1814//
1815//-----------------------------------------------------------------------------
1816
1817//
1818// Wavelet basis functions without modulo arithmetic; they produce
1819// the best compression ratios when the wavelet-transformed data are
1820// Huffman-encoded, but the wavelet transform works only for 14-bit
1821// data (untransformed data values must be less than (1 << 14)).
1822//
1823
1824inline void wenc14(unsigned short a, unsigned short b, unsigned short& l,
1825 unsigned short& h)
1826{
1827 short as = static_cast<short>(a);
1828 short bs = static_cast<short>(b);
1829
1830 short ms = (as + bs) >> 1;
1831 short ds = as - bs;
1832
1833 l = static_cast<unsigned short>(ms);
1834 h = static_cast<unsigned short>(ds);
1835}
1836
1837inline void wdec14(unsigned short l, unsigned short h, unsigned short& a,
1838 unsigned short& b)
1839{
1840 short ls = static_cast<short>(l);
1841 short hs = static_cast<short>(h);
1842
1843 int hi = hs;
1844 int ai = ls + (hi & 1) + (hi >> 1);
1845
1846 short as = static_cast<short>(ai);
1847 short bs = static_cast<short>(ai - hi);
1848
1849 a = static_cast<unsigned short>(as);
1850 b = static_cast<unsigned short>(bs);
1851}
1852
1853//
1854// Wavelet basis functions with modulo arithmetic; they work with full
1855// 16-bit data, but Huffman-encoding the wavelet-transformed data doesn't
1856// compress the data quite as well.
1857//
1858
1859const int NBITS = 16;
1860const int A_OFFSET = 1 << (NBITS - 1);
1861const int M_OFFSET = 1 << (NBITS - 1);
1862const int MOD_MASK = (1 << NBITS) - 1;
1863
1864inline void wenc16(unsigned short a, unsigned short b, unsigned short& l,
1865 unsigned short& h)
1866{
1867 int ao = (a + A_OFFSET) & MOD_MASK;
1868 int m = ((ao + b) >> 1);
1869 int d = ao - b;
1870
1871 if (d < 0)
1872 m = (m + M_OFFSET) & MOD_MASK;
1873
1874 d &= MOD_MASK;
1875
1876 l = static_cast<unsigned short>(m);
1877 h = static_cast<unsigned short>(d);
1878}
1879
1880inline void wdec16(unsigned short l, unsigned short h, unsigned short& a,
1881 unsigned short& b)
1882{
1883 int m = l;
1884 int d = h;
1885 int bb = (m - (d >> 1)) & MOD_MASK;
1886 int aa = (d + bb - A_OFFSET) & MOD_MASK;
1887 b = static_cast<unsigned short>(bb);
1888 a = static_cast<unsigned short>(aa);
1889}
1890
1891//
1892// 2D Wavelet encoding:
1893//
1894
1895static void wav2Encode(
1896 unsigned short* in, // io: values are transformed in place
1897 int nx, // i : x size
1898 int ox, // i : x offset
1899 int ny, // i : y size
1900 int oy, // i : y offset
1901 unsigned short mx) // i : maximum in[x][y] value
1902{
1903 bool w14 = (mx < (1 << 14));
1904 int n = (nx > ny) ? ny : nx;
1905 int p = 1; // == 1 << level
1906 int p2 = 2; // == 1 << (level+1)
1907
1908 //
1909 // Hierarchical loop on smaller dimension n
1910 //
1911
1912 while (p2 <= n) {
1913 unsigned short* py = in;
1914 unsigned short* ey = in + oy * (ny - p2);
1915 int oy1 = oy * p;
1916 int oy2 = oy * p2;
1917 int ox1 = ox * p;
1918 int ox2 = ox * p2;
1919 unsigned short i00, i01, i10, i11;
1920
1921 //
1922 // Y loop
1923 //
1924
1925 for (; py <= ey; py += oy2) {
1926 unsigned short* px = py;
1927 unsigned short* ex = py + ox * (nx - p2);
1928
1929 //
1930 // X loop
1931 //
1932
1933 for (; px <= ex; px += ox2) {
1934 unsigned short* p01 = px + ox1;
1935 unsigned short* p10 = px + oy1;
1936 unsigned short* p11 = p10 + ox1;
1937
1938 //
1939 // 2D wavelet encoding
1940 //
1941
1942 if (w14) {
1943 wenc14(*px, *p01, i00, i01);
1944 wenc14(*p10, *p11, i10, i11);
1945 wenc14(i00, i10, *px, *p10);
1946 wenc14(i01, i11, *p01, *p11);
1947 } else {
1948 wenc16(*px, *p01, i00, i01);
1949 wenc16(*p10, *p11, i10, i11);
1950 wenc16(i00, i10, *px, *p10);
1951 wenc16(i01, i11, *p01, *p11);
1952 }
1953 }
1954
1955 //
1956 // Encode (1D) odd column (still in Y loop)
1957 //
1958
1959 if (nx & p) {
1960 unsigned short* p10 = px + oy1;
1961
1962 if (w14)
1963 wenc14(*px, *p10, i00, *p10);
1964 else
1965 wenc16(*px, *p10, i00, *p10);
1966
1967 *px = i00;
1968 }
1969 }
1970
1971 //
1972 // Encode (1D) odd line (must loop in X)
1973 //
1974
1975 if (ny & p) {
1976 unsigned short* px = py;
1977 unsigned short* ex = py + ox * (nx - p2);
1978
1979 for (; px <= ex; px += ox2) {
1980 unsigned short* p01 = px + ox1;
1981
1982 if (w14)
1983 wenc14(*px, *p01, i00, *p01);
1984 else
1985 wenc16(*px, *p01, i00, *p01);
1986
1987 *px = i00;
1988 }
1989 }
1990
1991 //
1992 // Next level
1993 //
1994
1995 p = p2;
1996 p2 <<= 1;
1997 }
1998}
1999
2000//
2001// 2D Wavelet decoding:
2002//
2003
2004static void wav2Decode(
2005 unsigned short* in, // io: values are transformed in place
2006 int nx, // i : x size
2007 int ox, // i : x offset
2008 int ny, // i : y size
2009 int oy, // i : y offset
2010 unsigned short mx) // i : maximum in[x][y] value
2011{
2012 bool w14 = (mx < (1 << 14));
2013 int n = (nx > ny) ? ny : nx;
2014 int p = 1;
2015 int p2;
2016
2017 //
2018 // Search max level
2019 //
2020
2021 while (p <= n)
2022 p <<= 1;
2023
2024 p >>= 1;
2025 p2 = p;
2026 p >>= 1;
2027
2028 //
2029 // Hierarchical loop on smaller dimension n
2030 //
2031
2032 while (p >= 1) {
2033 unsigned short* py = in;
2034 unsigned short* ey = in + oy * (ny - p2);
2035 int oy1 = oy * p;
2036 int oy2 = oy * p2;
2037 int ox1 = ox * p;
2038 int ox2 = ox * p2;
2039 unsigned short i00, i01, i10, i11;
2040
2041 //
2042 // Y loop
2043 //
2044
2045 for (; py <= ey; py += oy2) {
2046 unsigned short* px = py;
2047 unsigned short* ex = py + ox * (nx - p2);
2048
2049 //
2050 // X loop
2051 //
2052
2053 for (; px <= ex; px += ox2) {
2054 unsigned short* p01 = px + ox1;
2055 unsigned short* p10 = px + oy1;
2056 unsigned short* p11 = p10 + ox1;
2057
2058 //
2059 // 2D wavelet decoding
2060 //
2061
2062 if (w14) {
2063 wdec14(*px, *p10, i00, i10);
2064 wdec14(*p01, *p11, i01, i11);
2065 wdec14(i00, i01, *px, *p01);
2066 wdec14(i10, i11, *p10, *p11);
2067 } else {
2068 wdec16(*px, *p10, i00, i10);
2069 wdec16(*p01, *p11, i01, i11);
2070 wdec16(i00, i01, *px, *p01);
2071 wdec16(i10, i11, *p10, *p11);
2072 }
2073 }
2074
2075 //
2076 // Decode (1D) odd column (still in Y loop)
2077 //
2078
2079 if (nx & p) {
2080 unsigned short* p10 = px + oy1;
2081
2082 if (w14)
2083 wdec14(*px, *p10, i00, *p10);
2084 else
2085 wdec16(*px, *p10, i00, *p10);
2086
2087 *px = i00;
2088 }
2089 }
2090
2091 //
2092 // Decode (1D) odd line (must loop in X)
2093 //
2094
2095 if (ny & p) {
2096 unsigned short* px = py;
2097 unsigned short* ex = py + ox * (nx - p2);
2098
2099 for (; px <= ex; px += ox2) {
2100 unsigned short* p01 = px + ox1;
2101
2102 if (w14)
2103 wdec14(*px, *p01, i00, *p01);
2104 else
2105 wdec16(*px, *p01, i00, *p01);
2106
2107 *px = i00;
2108 }
2109 }
2110
2111 //
2112 // Next level
2113 //
2114
2115 p2 = p;
2116 p >>= 1;
2117 }
2118}
2119
2120//-----------------------------------------------------------------------------
2121//
2122// 16-bit Huffman compression and decompression.
2123//
2124// The source code in this file is derived from the 8-bit
2125// Huffman compression and decompression routines written
2126// by Christian Rouet for his PIZ image file format.
2127//
2128//-----------------------------------------------------------------------------
2129
2130// Adds some modification for tinyexr.
2131
2132const int HUF_ENCBITS = 16; // literal (value) bit length
2133const int HUF_DECBITS = 14; // decoding bit size (>= 8)
2134
2135const int HUF_ENCSIZE = (1 << HUF_ENCBITS) + 1; // encoding table size
2136const int HUF_DECSIZE = 1 << HUF_DECBITS; // decoding table size
2137const int HUF_DECMASK = HUF_DECSIZE - 1;
2138
2139struct HufDec { // short code long code
2140 //-------------------------------
2141 unsigned int len : 8; // code length 0
2142 unsigned int lit : 24; // lit p size
2143 unsigned int* p; // 0 lits
2144};
2145
2146inline long long hufLength(long long code) { return code & 63; }
2147
2148inline long long hufCode(long long code) { return code >> 6; }
2149
2150inline void outputBits(int nBits, long long bits, long long& c, int& lc,
2151 char*& out)
2152{
2153 c <<= nBits;
2154 lc += nBits;
2155
2156 c |= bits;
2157
2158 while (lc >= 8)
2159 *out++ = static_cast<char>((c >> (lc -= 8)));
2160}
2161
2162inline long long getBits(int nBits, long long& c, int& lc, const char*& in)
2163{
2164 while (lc < nBits) {
2165 c = (c << 8) | *(reinterpret_cast<const unsigned char*>(in++));
2166 lc += 8;
2167 }
2168
2169 lc -= nBits;
2170 return (c >> lc) & ((1 << nBits) - 1);
2171}
2172
2173//
2174// ENCODING TABLE BUILDING & (UN)PACKING
2175//
2176
2177//
2178// Build a "canonical" Huffman code table:
2179// - for each (uncompressed) symbol, hcode contains the length
2180// of the corresponding code (in the compressed data)
2181// - canonical codes are computed and stored in hcode
2182// - the rules for constructing canonical codes are as follows:
2183// * shorter codes (if filled with zeroes to the right)
2184// have a numerically higher value than longer codes
2185// * for codes with the same length, numerical values
2186// increase with numerical symbol values
2187// - because the canonical code table can be constructed from
2188// symbol lengths alone, the code table can be transmitted
2189// without sending the actual code values
2190// - see http://www.compressconsult.com/huffman/
2191//
2192
2193static void hufCanonicalCodeTable(long long hcode[HUF_ENCSIZE])
2194{
2195 long long n[59];
2196
2197 //
2198 // For each i from 0 through 58, count the
2199 // number of different codes of length i, and
2200 // store the count in n[i].
2201 //
2202
2203 for (int i = 0; i <= 58; ++i)
2204 n[i] = 0;
2205
2206 for (int i = 0; i < HUF_ENCSIZE; ++i)
2207 n[hcode[i]] += 1;
2208
2209 //
2210 // For each i from 58 through 1, compute the
2211 // numerically lowest code with length i, and
2212 // store that code in n[i].
2213 //
2214
2215 long long c = 0;
2216
2217 for (int i = 58; i > 0; --i) {
2218 long long nc = ((c + n[i]) >> 1);
2219 n[i] = c;
2220 c = nc;
2221 }
2222
2223 //
2224 // hcode[i] contains the length, l, of the
2225 // code for symbol i. Assign the next available
2226 // code of length l to the symbol and store both
2227 // l and the code in hcode[i].
2228 //
2229
2230 for (int i = 0; i < HUF_ENCSIZE; ++i) {
2231 int l = static_cast<int>(hcode[i]);
2232
2233 if (l > 0)
2234 hcode[i] = l | (n[l]++ << 6);
2235 }
2236}
2237
2238//
2239// Compute Huffman codes (based on frq input) and store them in frq:
2240// - code structure is : [63:lsb - 6:msb] | [5-0: bit length];
2241// - max code length is 58 bits;
2242// - codes outside the range [im-iM] have a null length (unused values);
2243// - original frequencies are destroyed;
2244// - encoding tables are used by hufEncode() and hufBuildDecTable();
2245//
2246
2247struct FHeapCompare {
2248 bool operator()(long long* a, long long* b) { return *a > *b; }
2249};
2250
2251static bool hufBuildEncTable(
2252 long long* frq, // io: input frequencies [HUF_ENCSIZE], output table
2253 int* im, // o: min frq index
2254 int* iM) // o: max frq index
2255{
2256 //
2257 // This function assumes that when it is called, array frq
2258 // indicates the frequency of all possible symbols in the data
2259 // that are to be Huffman-encoded. (frq[i] contains the number
2260 // of occurrences of symbol i in the data.)
2261 //
2262 // The loop below does three things:
2263 //
2264 // 1) Finds the minimum and maximum indices that point
2265 // to non-zero entries in frq:
2266 //
2267 // frq[im] != 0, and frq[i] == 0 for all i < im
2268 // frq[iM] != 0, and frq[i] == 0 for all i > iM
2269 //
2270 // 2) Fills array fHeap with pointers to all non-zero
2271 // entries in frq.
2272 //
2273 // 3) Initializes array hlink such that hlink[i] == i
2274 // for all array entries.
2275 //
2276
2277 std::vector<int> hlink(HUF_ENCSIZE);
2278 std::vector<long long*> fHeap(HUF_ENCSIZE);
2279
2280 *im = 0;
2281
2282 while (!frq[*im])
2283 (*im)++;
2284
2285 int nf = 0;
2286
2287 for (int i = *im; i < HUF_ENCSIZE; i++) {
2288 hlink[i] = i;
2289
2290 if (frq[i]) {
2291 fHeap[nf] = &frq[i];
2292 nf++;
2293 *iM = i;
2294 }
2295 }
2296
2297 //
2298 // Add a pseudo-symbol, with a frequency count of 1, to frq;
2299 // adjust the fHeap and hlink array accordingly. Function
2300 // hufEncode() uses the pseudo-symbol for run-length encoding.
2301 //
2302
2303 (*iM)++;
2304 frq[*iM] = 1;
2305 fHeap[nf] = &frq[*iM];
2306 nf++;
2307
2308 //
2309 // Build an array, scode, such that scode[i] contains the number
2310 // of bits assigned to symbol i. Conceptually this is done by
2311 // constructing a tree whose leaves are the symbols with non-zero
2312 // frequency:
2313 //
2314 // Make a heap that contains all symbols with a non-zero frequency,
2315 // with the least frequent symbol on top.
2316 //
2317 // Repeat until only one symbol is left on the heap:
2318 //
2319 // Take the two least frequent symbols off the top of the heap.
2320 // Create a new node that has first two nodes as children, and
2321 // whose frequency is the sum of the frequencies of the first
2322 // two nodes. Put the new node back into the heap.
2323 //
2324 // The last node left on the heap is the root of the tree. For each
2325 // leaf node, the distance between the root and the leaf is the length
2326 // of the code for the corresponding symbol.
2327 //
2328 // The loop below doesn't actually build the tree; instead we compute
2329 // the distances of the leaves from the root on the fly. When a new
2330 // node is added to the heap, then that node's descendants are linked
2331 // into a single linear list that starts at the new node, and the code
2332 // lengths of the descendants (that is, their distance from the root
2333 // of the tree) are incremented by one.
2334 //
2335
2336 std::make_heap(&fHeap[0], &fHeap[nf], FHeapCompare());
2337
2338 std::vector<long long> scode(HUF_ENCSIZE);
2339 memset(scode.data(), 0, sizeof(long long) * HUF_ENCSIZE);
2340
2341 while (nf > 1) {
2342 //
2343 // Find the indices, mm and m, of the two smallest non-zero frq
2344 // values in fHeap, add the smallest frq to the second-smallest
2345 // frq, and remove the smallest frq value from fHeap.
2346 //
2347
2348 int mm = fHeap[0] - frq;
2349 std::pop_heap(&fHeap[0], &fHeap[nf], FHeapCompare());
2350 --nf;
2351
2352 int m = fHeap[0] - frq;
2353 std::pop_heap(&fHeap[0], &fHeap[nf], FHeapCompare());
2354
2355 frq[m] += frq[mm];
2356 std::push_heap(&fHeap[0], &fHeap[nf], FHeapCompare());
2357
2358 //
2359 // The entries in scode are linked into lists with the
2360 // entries in hlink serving as "next" pointers and with
2361 // the end of a list marked by hlink[j] == j.
2362 //
2363 // Traverse the lists that start at scode[m] and scode[mm].
2364 // For each element visited, increment the length of the
2365 // corresponding code by one bit. (If we visit scode[j]
2366 // during the traversal, then the code for symbol j becomes
2367 // one bit longer.)
2368 //
2369 // Merge the lists that start at scode[m] and scode[mm]
2370 // into a single list that starts at scode[m].
2371 //
2372
2373 //
2374 // Add a bit to all codes in the first list.
2375 //
2376
2377 for (int j = m;; j = hlink[j]) {
2378 scode[j]++;
2379
2380 TINYEXR_CHECK_AND_RETURN_C(scode[j] <= 58, false);
2381
2382 if (hlink[j] == j) {
2383 //
2384 // Merge the two lists.
2385 //
2386
2387 hlink[j] = mm;
2388 break;
2389 }
2390 }
2391
2392 //
2393 // Add a bit to all codes in the second list
2394 //
2395
2396 for (int j = mm;; j = hlink[j]) {
2397 scode[j]++;
2398
2399 TINYEXR_CHECK_AND_RETURN_C(scode[j] <= 58, false);
2400
2401 if (hlink[j] == j)
2402 break;
2403 }
2404 }
2405
2406 //
2407 // Build a canonical Huffman code table, replacing the code
2408 // lengths in scode with (code, code length) pairs. Copy the
2409 // code table from scode into frq.
2410 //
2411
2412 hufCanonicalCodeTable(scode.data());
2413 memcpy(frq, scode.data(), sizeof(long long) * HUF_ENCSIZE);
2414
2415 return true;
2416}
2417
2418//
2419// Pack an encoding table:
2420// - only code lengths, not actual codes, are stored
2421// - runs of zeroes are compressed as follows:
2422//
2423// unpacked packed
2424// --------------------------------
2425// 1 zero 0 (6 bits)
2426// 2 zeroes 59
2427// 3 zeroes 60
2428// 4 zeroes 61
2429// 5 zeroes 62
2430// n zeroes (6 or more) 63 n-6 (6 + 8 bits)
2431//
2432
2433const int SHORT_ZEROCODE_RUN = 59;
2434const int LONG_ZEROCODE_RUN = 63;
2435const int SHORTEST_LONG_RUN = 2 + LONG_ZEROCODE_RUN - SHORT_ZEROCODE_RUN;
2436const int LONGEST_LONG_RUN = 255 + SHORTEST_LONG_RUN;
2437
2438static void hufPackEncTable(
2439 const long long* hcode, // i : encoding table [HUF_ENCSIZE]
2440 int im, // i : min hcode index
2441 int iM, // i : max hcode index
2442 char** pcode) // o: ptr to packed table (updated)
2443{
2444 char* p = *pcode;
2445 long long c = 0;
2446 int lc = 0;
2447
2448 for (; im <= iM; im++) {
2449 int l = hufLength(hcode[im]);
2450
2451 if (l == 0) {
2452 int zerun = 1;
2453
2454 while ((im < iM) && (zerun < LONGEST_LONG_RUN)) {
2455 if (hufLength(hcode[im + 1]) > 0)
2456 break;
2457 im++;
2458 zerun++;
2459 }
2460
2461 if (zerun >= 2) {
2462 if (zerun >= SHORTEST_LONG_RUN) {
2463 outputBits(6, LONG_ZEROCODE_RUN, c, lc, p);
2464 outputBits(8, zerun - SHORTEST_LONG_RUN, c, lc, p);
2465 } else {
2466 outputBits(6, SHORT_ZEROCODE_RUN + zerun - 2, c, lc, p);
2467 }
2468 continue;
2469 }
2470 }
2471
2472 outputBits(6, l, c, lc, p);
2473 }
2474
2475 if (lc > 0)
2476 *p++ = (unsigned char)(c << (8 - lc));
2477
2478 *pcode = p;
2479}
2480
2481//
2482// Unpack an encoding table packed by hufPackEncTable():
2483//
2484
2485static bool hufUnpackEncTable(
2486 const char** pcode, // io: ptr to packed table (updated)
2487 int ni, // i : input size (in bytes)
2488 int im, // i : min hcode index
2489 int iM, // i : max hcode index
2490 long long* hcode) // o: encoding table [HUF_ENCSIZE]
2491{
2492 memset(hcode, 0, sizeof(long long) * HUF_ENCSIZE);
2493
2494 const char* p = *pcode;
2495 long long c = 0;
2496 int lc = 0;
2497
2498 for (; im <= iM; im++) {
2499 if (p - *pcode >= ni) {
2500 return false;
2501 }
2502
2503 long long l = hcode[im] = getBits(6, c, lc, p); // code length
2504
2505 if (l == (long long)LONG_ZEROCODE_RUN) {
2506 if (p - *pcode > ni) {
2507 return false;
2508 }
2509
2510 int zerun = getBits(8, c, lc, p) + SHORTEST_LONG_RUN;
2511
2512 if (im + zerun > iM + 1) {
2513 return false;
2514 }
2515
2516 while (zerun--)
2517 hcode[im++] = 0;
2518
2519 im--;
2520 } else if (l >= (long long)SHORT_ZEROCODE_RUN) {
2521 int zerun = l - SHORT_ZEROCODE_RUN + 2;
2522
2523 if (im + zerun > iM + 1) {
2524 return false;
2525 }
2526
2527 while (zerun--)
2528 hcode[im++] = 0;
2529
2530 im--;
2531 }
2532 }
2533
2534 *pcode = const_cast<char*>(p);
2535
2536 hufCanonicalCodeTable(hcode);
2537
2538 return true;
2539}
2540
2541//
2542// DECODING TABLE BUILDING
2543//
2544
2545//
2546// Clear a newly allocated decoding table so that it contains only zeroes.
2547//
2548
2549static void hufClearDecTable(HufDec* hdecod) // io: (allocated by caller)
2550// decoding table [HUF_DECSIZE]
2551{
2552 for (int i = 0; i < HUF_DECSIZE; i++) {
2553 hdecod[i].len = 0;
2554 hdecod[i].lit = 0;
2555 hdecod[i].p = NULL;
2556 }
2557 // memset(hdecod, 0, sizeof(HufDec) * HUF_DECSIZE);
2558}
2559
2560//
2561// Build a decoding hash table based on the encoding table hcode:
2562// - short codes (<= HUF_DECBITS) are resolved with a single table access;
2563// - long code entry allocations are not optimized, because long codes are
2564// unfrequent;
2565// - decoding tables are used by hufDecode();
2566//
2567
2568static bool hufBuildDecTable(const long long* hcode, // i : encoding table
2569 int im, // i : min index in hcode
2570 int iM, // i : max index in hcode
2571 HufDec* hdecod) // o: (allocated by caller)
2572// decoding table [HUF_DECSIZE]
2573{
2574 //
2575 // Init hashtable & loop on all codes.
2576 // Assumes that hufClearDecTable(hdecod) has already been called.
2577 //
2578
2579 for (; im <= iM; im++) {
2580 long long c = hufCode(hcode[im]);
2581 int l = hufLength(hcode[im]);
2582
2583 if (c >> l) {
2584 //
2585 // Error: c is supposed to be an l-bit code,
2586 // but c contains a value that is greater
2587 // than the largest l-bit number.
2588 //
2589
2590 // invalidTableEntry();
2591 return false;
2592 }
2593
2594 if (l > HUF_DECBITS) {
2595 //
2596 // Long code: add a secondary entry
2597 //
2598
2599 HufDec* pl = hdecod + (c >> (l - HUF_DECBITS));
2600
2601 if (pl->len) {
2602 //
2603 // Error: a short code has already
2604 // been stored in table entry *pl.
2605 //
2606
2607 // invalidTableEntry();
2608 return false;
2609 }
2610
2611 pl->lit++;
2612
2613 if (pl->p) {
2614 unsigned int* p = pl->p;
2615 pl->p = new unsigned int[pl->lit];
2616
2617 for (unsigned int i = 0; i < pl->lit - 1u; ++i)
2618 pl->p[i] = p[i];
2619
2620 delete[] p;
2621 } else {
2622 pl->p = new unsigned int[1];
2623 }
2624
2625 pl->p[pl->lit - 1] = im;
2626 } else if (l) {
2627 //
2628 // Short code: init all primary entries
2629 //
2630
2631 HufDec* pl = hdecod + (c << (HUF_DECBITS - l));
2632
2633 for (long long i = 1ULL << (HUF_DECBITS - l); i > 0; i--, pl++) {
2634 if (pl->len || pl->p) {
2635 //
2636 // Error: a short code or a long code has
2637 // already been stored in table entry *pl.
2638 //
2639
2640 // invalidTableEntry();
2641 return false;
2642 }
2643
2644 pl->len = l;
2645 pl->lit = im;
2646 }
2647 }
2648 }
2649
2650 return true;
2651}
2652
2653//
2654// Free the long code entries of a decoding table built by hufBuildDecTable()
2655//
2656
2657static void hufFreeDecTable(HufDec* hdecod) // io: Decoding table
2658{
2659 for (int i = 0; i < HUF_DECSIZE; i++) {
2660 if (hdecod[i].p) {
2661 delete[] hdecod[i].p;
2662 hdecod[i].p = 0;
2663 }
2664 }
2665}
2666
2667//
2668// ENCODING
2669//
2670
2671inline void outputCode(long long code, long long& c, int& lc, char*& out)
2672{
2673 outputBits(hufLength(code), hufCode(code), c, lc, out);
2674}
2675
2676inline void sendCode(long long sCode, int runCount, long long runCode,
2677 long long& c, int& lc, char*& out)
2678{
2679 //
2680 // Output a run of runCount instances of the symbol sCount.
2681 // Output the symbols explicitly, or if that is shorter, output
2682 // the sCode symbol once followed by a runCode symbol and runCount
2683 // expressed as an 8-bit number.
2684 //
2685
2686 if (hufLength(sCode) + hufLength(runCode) + 8 < hufLength(sCode) * runCount) {
2687 outputCode(sCode, c, lc, out);
2688 outputCode(runCode, c, lc, out);
2689 outputBits(8, runCount, c, lc, out);
2690 } else {
2691 while (runCount-- >= 0)
2692 outputCode(sCode, c, lc, out);
2693 }
2694}
2695
2696//
2697// Encode (compress) ni values based on the Huffman encoding table hcode:
2698//
2699
2700static int hufEncode // return: output size (in bits)
2701 (const long long* hcode, // i : encoding table
2702 const unsigned short* in, // i : uncompressed input buffer
2703 const int ni, // i : input buffer size (in bytes)
2704 int rlc, // i : rl code
2705 char* out) // o: compressed output buffer
2706{
2707 char* outStart = out;
2708 long long c = 0; // bits not yet written to out
2709 int lc = 0; // number of valid bits in c (LSB)
2710 int s = in[0];
2711 int cs = 0;
2712
2713 //
2714 // Loop on input values
2715 //
2716
2717 for (int i = 1; i < ni; i++) {
2718 //
2719 // Count same values or send code
2720 //
2721
2722 if (s == in[i] && cs < 255) {
2723 cs++;
2724 } else {
2725 sendCode(hcode[s], cs, hcode[rlc], c, lc, out);
2726 cs = 0;
2727 }
2728
2729 s = in[i];
2730 }
2731
2732 //
2733 // Send remaining code
2734 //
2735
2736 sendCode(hcode[s], cs, hcode[rlc], c, lc, out);
2737
2738 if (lc)
2739 *out = (c << (8 - lc)) & 0xff;
2740
2741 return (out - outStart) * 8 + lc;
2742}
2743
2744//
2745// DECODING
2746//
2747
2748//
2749// In order to force the compiler to inline them,
2750// getChar() and getCode() are implemented as macros
2751// instead of "inline" functions.
2752//
2753
2754#define getChar(c, lc, in) \
2755 { \
2756 c = (c << 8) | *(unsigned char*)(in++); \
2757 lc += 8; \
2758 }
2759
2760#if 0
2761#define getCode(po, rlc, c, lc, in, out, ob, oe) \
2762 { \
2763 if (po == rlc) { \
2764 if (lc < 8) \
2765 getChar(c, lc, in); \
2766 \
2767 lc -= 8; \
2768 \
2769 unsigned char cs = (c >> lc); \
2770 \
2771 if (out + cs > oe) \
2772 return false; \
2773 \
2774 /* TinyEXR issue 78 */ \
2775 unsigned short s = out[-1]; \
2776 \
2777 while (cs-- > 0) \
2778 *out++ = s; \
2779 } else if (out < oe) { \
2780 *out++ = po; \
2781 } else { \
2782 return false; \
2783 } \
2784 }
2785#else
2786static bool getCode(int po, int rlc, long long& c, int& lc, const char*& in,
2787 const char* in_end, unsigned short*& out,
2788 const unsigned short* ob, const unsigned short* oe)
2789{
2790 (void)ob;
2791 if (po == rlc) {
2792 if (lc < 8) {
2793 /* TinyEXR issue 78 */
2794 /* TinyEXR issue 160. in + 1 -> in */
2795 if (in >= in_end) {
2796 return false;
2797 }
2798
2799 getChar(c, lc, in);
2800 }
2801
2802 lc -= 8;
2803
2804 unsigned char cs = (c >> lc);
2805
2806 if (out + cs > oe)
2807 return false;
2808
2809 // Bounds check for safety
2810 // Issue 100.
2811 if ((out - 1) < ob)
2812 return false;
2813 unsigned short s = out[-1];
2814
2815 while (cs-- > 0)
2816 *out++ = s;
2817 } else if (out < oe) {
2818 *out++ = po;
2819 } else {
2820 return false;
2821 }
2822 return true;
2823}
2824#endif
2825
2826//
2827// Decode (uncompress) ni bits based on encoding & decoding tables:
2828//
2829
2830static bool hufDecode(const long long* hcode, // i : encoding table
2831 const HufDec* hdecod, // i : decoding table
2832 const char* in, // i : compressed input buffer
2833 int ni, // i : input size (in bits)
2834 int rlc, // i : run-length code
2835 int no, // i : expected output size (in bytes)
2836 unsigned short* out) // o: uncompressed output buffer
2837{
2838 long long c = 0;
2839 int lc = 0;
2840 unsigned short* outb = out; // begin
2841 unsigned short* oe = out + no; // end
2842 const char* ie = in + (ni + 7) / 8; // input byte size
2843
2844 //
2845 // Loop on input bytes
2846 //
2847
2848 while (in < ie) {
2849 getChar(c, lc, in);
2850
2851 //
2852 // Access decoding table
2853 //
2854
2855 while (lc >= HUF_DECBITS) {
2856 const HufDec pl = hdecod[(c >> (lc - HUF_DECBITS)) & HUF_DECMASK];
2857
2858 if (pl.len) {
2859 //
2860 // Get short code
2861 //
2862
2863 lc -= pl.len;
2864 // std::cout << "lit = " << pl.lit << std::endl;
2865 // std::cout << "rlc = " << rlc << std::endl;
2866 // std::cout << "c = " << c << std::endl;
2867 // std::cout << "lc = " << lc << std::endl;
2868 // std::cout << "in = " << in << std::endl;
2869 // std::cout << "out = " << out << std::endl;
2870 // std::cout << "oe = " << oe << std::endl;
2871 if (!getCode(pl.lit, rlc, c, lc, in, ie, out, outb, oe)) {
2872 return false;
2873 }
2874 } else {
2875 if (!pl.p) {
2876 return false;
2877 }
2878 // invalidCode(); // wrong code
2879
2880 //
2881 // Search long code
2882 //
2883
2884 unsigned int j;
2885
2886 for (j = 0; j < pl.lit; j++) {
2887 int l = hufLength(hcode[pl.p[j]]);
2888
2889 while (lc < l && in < ie) // get more bits
2890 getChar(c, lc, in);
2891
2892 if (lc >= l) {
2893 if (hufCode(hcode[pl.p[j]]) == ((c >> (lc - l)) & (((long long)(1) << l) - 1))) {
2894 //
2895 // Found : get long code
2896 //
2897
2898 lc -= l;
2899 if (!getCode(pl.p[j], rlc, c, lc, in, ie, out, outb, oe)) {
2900 return false;
2901 }
2902 break;
2903 }
2904 }
2905 }
2906
2907 if (j == pl.lit) {
2908 return false;
2909 // invalidCode(); // Not found
2910 }
2911 }
2912 }
2913 }
2914
2915 //
2916 // Get remaining (short) codes
2917 //
2918
2919 int i = (8 - ni) & 7;
2920 c >>= i;
2921 lc -= i;
2922
2923 while (lc > 0) {
2924 const HufDec pl = hdecod[(c << (HUF_DECBITS - lc)) & HUF_DECMASK];
2925
2926 if (pl.len) {
2927 lc -= pl.len;
2928 if (!getCode(pl.lit, rlc, c, lc, in, ie, out, outb, oe)) {
2929 return false;
2930 }
2931 } else {
2932 return false;
2933 // invalidCode(); // wrong (long) code
2934 }
2935 }
2936
2937 if (out - outb != no) {
2938 return false;
2939 }
2940 // notEnoughData ();
2941
2942 return true;
2943}
2944
2945static void countFrequencies(std::vector<long long>& freq,
2946 const unsigned short data[/*n*/], int n)
2947{
2948 for (int i = 0; i < HUF_ENCSIZE; ++i)
2949 freq[i] = 0;
2950
2951 for (int i = 0; i < n; ++i)
2952 ++freq[data[i]];
2953}
2954
2955static void writeUInt(char buf[4], unsigned int i)
2956{
2957 unsigned char* b = (unsigned char*)buf;
2958
2959 b[0] = i;
2960 b[1] = i >> 8;
2961 b[2] = i >> 16;
2962 b[3] = i >> 24;
2963}
2964
2965static unsigned int readUInt(const char buf[4])
2966{
2967 const unsigned char* b = (const unsigned char*)buf;
2968
2969 return (b[0] & 0x000000ff) | ((b[1] << 8) & 0x0000ff00) | ((b[2] << 16) & 0x00ff0000) | ((b[3] << 24) & 0xff000000);
2970}
2971
2972//
2973// EXTERNAL INTERFACE
2974//
2975
2976static int hufCompress(const unsigned short raw[], int nRaw,
2977 char compressed[])
2978{
2979 if (nRaw == 0)
2980 return 0;
2981
2982 std::vector<long long> freq(HUF_ENCSIZE);
2983
2984 countFrequencies(freq, raw, nRaw);
2985
2986 int im = 0;
2987 int iM = 0;
2988 hufBuildEncTable(freq.data(), &im, &iM);
2989
2990 char* tableStart = compressed + 20;
2991 char* tableEnd = tableStart;
2992 hufPackEncTable(freq.data(), im, iM, &tableEnd);
2993 int tableLength = tableEnd - tableStart;
2994
2995 char* dataStart = tableEnd;
2996 int nBits = hufEncode(freq.data(), raw, nRaw, iM, dataStart);
2997 int data_length = (nBits + 7) / 8;
2998
2999 writeUInt(compressed, im);
3000 writeUInt(compressed + 4, iM);
3001 writeUInt(compressed + 8, tableLength);
3002 writeUInt(compressed + 12, nBits);
3003 writeUInt(compressed + 16, 0); // room for future extensions
3004
3005 return dataStart + data_length - compressed;
3006}
3007
3008static bool hufUncompress(const char compressed[], int nCompressed,
3009 std::vector<unsigned short>* raw)
3010{
3011 if (nCompressed == 0) {
3012 if (raw->size() != 0)
3013 return false;
3014
3015 return false;
3016 }
3017
3018 int im = readUInt(compressed);
3019 int iM = readUInt(compressed + 4);
3020 // int tableLength = readUInt (compressed + 8);
3021 int nBits = readUInt(compressed + 12);
3022
3023 if (im < 0 || im >= HUF_ENCSIZE || iM < 0 || iM >= HUF_ENCSIZE)
3024 return false;
3025
3026 const char* ptr = compressed + 20;
3027
3028 //
3029 // Fast decoder needs at least 2x64-bits of compressed data, and
3030 // needs to be run-able on this platform. Otherwise, fall back
3031 // to the original decoder
3032 //
3033
3034 // if (FastHufDecoder::enabled() && nBits > 128)
3035 //{
3036 // FastHufDecoder fhd (ptr, nCompressed - (ptr - compressed), im, iM, iM);
3037 // fhd.decode ((unsigned char*)ptr, nBits, raw, nRaw);
3038 //}
3039 // else
3040 {
3041 std::vector<long long> freq(HUF_ENCSIZE);
3042 std::vector<HufDec> hdec(HUF_DECSIZE);
3043
3044 hufClearDecTable(&hdec.at(0));
3045
3046 hufUnpackEncTable(&ptr, nCompressed - (ptr - compressed), im, iM,
3047 &freq.at(0));
3048
3049 {
3050 if (nBits > 8 * (nCompressed - (ptr - compressed))) {
3051 return false;
3052 }
3053
3054 hufBuildDecTable(&freq.at(0), im, iM, &hdec.at(0));
3055 hufDecode(&freq.at(0), &hdec.at(0), ptr, nBits, iM, raw->size(),
3056 raw->data());
3057 }
3058 // catch (...)
3059 //{
3060 // hufFreeDecTable (hdec);
3061 // throw;
3062 //}
3063
3064 hufFreeDecTable(&hdec.at(0));
3065 }
3066
3067 return true;
3068}
3069
3070//
3071// Functions to compress the range of values in the pixel data
3072//
3073
3074const int USHORT_RANGE = (1 << 16);
3075const int BITMAP_SIZE = (USHORT_RANGE >> 3);
3076
3077static void bitmapFromData(const unsigned short data[/*nData*/], int nData,
3078 unsigned char bitmap[BITMAP_SIZE],
3079 unsigned short& minNonZero,
3080 unsigned short& maxNonZero)
3081{
3082 for (int i = 0; i < BITMAP_SIZE; ++i)
3083 bitmap[i] = 0;
3084
3085 for (int i = 0; i < nData; ++i)
3086 bitmap[data[i] >> 3] |= (1 << (data[i] & 7));
3087
3088 bitmap[0] &= ~1; // zero is not explicitly stored in
3089 // the bitmap; we assume that the
3090 // data always contain zeroes
3091 minNonZero = BITMAP_SIZE - 1;
3092 maxNonZero = 0;
3093
3094 for (int i = 0; i < BITMAP_SIZE; ++i) {
3095 if (bitmap[i]) {
3096 if (minNonZero > i)
3097 minNonZero = i;
3098 if (maxNonZero < i)
3099 maxNonZero = i;
3100 }
3101 }
3102}
3103
3104static unsigned short forwardLutFromBitmap(
3105 const unsigned char bitmap[BITMAP_SIZE], unsigned short lut[USHORT_RANGE])
3106{
3107 int k = 0;
3108
3109 for (int i = 0; i < USHORT_RANGE; ++i) {
3110 if ((i == 0) || (bitmap[i >> 3] & (1 << (i & 7))))
3111 lut[i] = k++;
3112 else
3113 lut[i] = 0;
3114 }
3115
3116 return k - 1; // maximum value stored in lut[],
3117} // i.e. number of ones in bitmap minus 1
3118
3119static unsigned short reverseLutFromBitmap(
3120 const unsigned char bitmap[BITMAP_SIZE], unsigned short lut[USHORT_RANGE])
3121{
3122 int k = 0;
3123
3124 for (int i = 0; i < USHORT_RANGE; ++i) {
3125 if ((i == 0) || (bitmap[i >> 3] & (1 << (i & 7))))
3126 lut[k++] = i;
3127 }
3128
3129 int n = k - 1;
3130
3131 while (k < USHORT_RANGE)
3132 lut[k++] = 0;
3133
3134 return n; // maximum k where lut[k] is non-zero,
3135} // i.e. number of ones in bitmap minus 1
3136
3137static void applyLut(const unsigned short lut[USHORT_RANGE],
3138 unsigned short data[/*nData*/], int nData)
3139{
3140 for (int i = 0; i < nData; ++i)
3141 data[i] = lut[data[i]];
3142}
3143
3144#ifdef __clang__
3145#pragma clang diagnostic pop
3146#endif // __clang__
3147
3148#ifdef _MSC_VER
3149#pragma warning(pop)
3150#endif
3151
3152static bool CompressPiz(unsigned char* outPtr, unsigned int* outSize,
3153 const unsigned char* inPtr, size_t inSize,
3154 const std::vector<ChannelInfo>& channelInfo,
3155 int data_width, int num_lines)
3156{
3157 std::vector<unsigned char> bitmap(BITMAP_SIZE);
3158 unsigned short minNonZero;
3159 unsigned short maxNonZero;
3160
3161#if !TINYEXR_LITTLE_ENDIAN
3162 // @todo { PIZ compression on BigEndian architecture. }
3163 return false;
3164#endif
3165
3166 // Assume `inSize` is multiple of 2 or 4.
3167 std::vector<unsigned short> tmpBuffer(inSize / sizeof(unsigned short));
3168
3169 std::vector<PIZChannelData> channelData(channelInfo.size());
3170 unsigned short* tmpBufferEnd = &tmpBuffer.at(0);
3171
3172 for (size_t c = 0; c < channelData.size(); c++) {
3173 PIZChannelData& cd = channelData[c];
3174
3175 cd.start = tmpBufferEnd;
3176 cd.end = cd.start;
3177
3178 cd.nx = data_width;
3179 cd.ny = num_lines;
3180 // cd.ys = c.channel().ySampling;
3181
3182 size_t pixelSize = sizeof(int); // UINT and FLOAT
3183 if (channelInfo[c].requested_pixel_type == TINYEXR_PIXELTYPE_HALF) {
3184 pixelSize = sizeof(short);
3185 }
3186
3187 cd.size = static_cast<int>(pixelSize / sizeof(short));
3188
3189 tmpBufferEnd += cd.nx * cd.ny * cd.size;
3190 }
3191
3192 const unsigned char* ptr = inPtr;
3193 for (int y = 0; y < num_lines; ++y) {
3194 for (size_t i = 0; i < channelData.size(); ++i) {
3195 PIZChannelData& cd = channelData[i];
3196
3197 // if (modp (y, cd.ys) != 0)
3198 // continue;
3199
3200 size_t n = static_cast<size_t>(cd.nx * cd.size);
3201 memcpy(cd.end, ptr, n * sizeof(unsigned short));
3202 ptr += n * sizeof(unsigned short);
3203 cd.end += n;
3204 }
3205 }
3206
3207 bitmapFromData(&tmpBuffer.at(0), static_cast<int>(tmpBuffer.size()),
3208 bitmap.data(), minNonZero, maxNonZero);
3209
3210 std::vector<unsigned short> lut(USHORT_RANGE);
3211 unsigned short maxValue = forwardLutFromBitmap(bitmap.data(), lut.data());
3212 applyLut(lut.data(), &tmpBuffer.at(0), static_cast<int>(tmpBuffer.size()));
3213
3214 //
3215 // Store range compression info in _outBuffer
3216 //
3217
3218 char* buf = reinterpret_cast<char*>(outPtr);
3219
3220 memcpy(buf, &minNonZero, sizeof(unsigned short));
3221 buf += sizeof(unsigned short);
3222 memcpy(buf, &maxNonZero, sizeof(unsigned short));
3223 buf += sizeof(unsigned short);
3224
3225 if (minNonZero <= maxNonZero) {
3226 memcpy(buf, reinterpret_cast<char*>(&bitmap[0] + minNonZero),
3227 maxNonZero - minNonZero + 1);
3228 buf += maxNonZero - minNonZero + 1;
3229 }
3230
3231 //
3232 // Apply wavelet encoding
3233 //
3234
3235 for (size_t i = 0; i < channelData.size(); ++i) {
3236 PIZChannelData& cd = channelData[i];
3237
3238 for (int j = 0; j < cd.size; ++j) {
3239 wav2Encode(cd.start + j, cd.nx, cd.size, cd.ny, cd.nx * cd.size,
3240 maxValue);
3241 }
3242 }
3243
3244 //
3245 // Apply Huffman encoding; append the result to _outBuffer
3246 //
3247
3248 // length header(4byte), then huff data. Initialize length header with zero,
3249 // then later fill it by `length`.
3250 char* lengthPtr = buf;
3251 int zero = 0;
3252 memcpy(buf, &zero, sizeof(int));
3253 buf += sizeof(int);
3254
3255 int length = hufCompress(&tmpBuffer.at(0), static_cast<int>(tmpBuffer.size()), buf);
3256 memcpy(lengthPtr, &length, sizeof(int));
3257
3258 (*outSize) = static_cast<unsigned int>(
3259 (reinterpret_cast<unsigned char*>(buf) - outPtr) + static_cast<unsigned int>(length));
3260
3261 // Use uncompressed data when compressed data is larger than uncompressed.
3262 // (Issue 40)
3263 if ((*outSize) >= inSize) {
3264 (*outSize) = static_cast<unsigned int>(inSize);
3265 memcpy(outPtr, inPtr, inSize);
3266 }
3267 return true;
3268}
3269
3270static bool DecompressPiz(unsigned char* outPtr, const unsigned char* inPtr,
3271 size_t tmpBufSizeInBytes, size_t inLen, int num_channels,
3272 const EXRChannelInfo* channels, int data_width,
3273 int num_lines)
3274{
3275 if (inLen == tmpBufSizeInBytes) {
3276 // Data is not compressed(Issue 40).
3277 memcpy(outPtr, inPtr, inLen);
3278 return true;
3279 }
3280
3281 std::vector<unsigned char> bitmap(BITMAP_SIZE);
3282 unsigned short minNonZero;
3283 unsigned short maxNonZero;
3284
3285#if !TINYEXR_LITTLE_ENDIAN
3286 // @todo { PIZ compression on BigEndian architecture. }
3287 return false;
3288#endif
3289
3290 memset(bitmap.data(), 0, BITMAP_SIZE);
3291
3292 if (inLen < 4) {
3293 return false;
3294 }
3295
3296 size_t readLen = 0;
3297
3298 const unsigned char* ptr = inPtr;
3299 // minNonZero = *(reinterpret_cast<const unsigned short *>(ptr));
3300 tinyexr::cpy2(&minNonZero, reinterpret_cast<const unsigned short*>(ptr));
3301 // maxNonZero = *(reinterpret_cast<const unsigned short *>(ptr + 2));
3302 tinyexr::cpy2(&maxNonZero, reinterpret_cast<const unsigned short*>(ptr + 2));
3303 ptr += 4;
3304 readLen += 4;
3305
3306 if (maxNonZero >= BITMAP_SIZE) {
3307 return false;
3308 }
3309
3310 // printf("maxNonZero = %d\n", maxNonZero);
3311 // printf("minNonZero = %d\n", minNonZero);
3312 // printf("len = %d\n", (maxNonZero - minNonZero + 1));
3313 // printf("BITMAPSIZE - min = %d\n", (BITMAP_SIZE - minNonZero));
3314
3315 if (minNonZero <= maxNonZero) {
3316 if (((maxNonZero - minNonZero + 1) + readLen) > inLen) {
3317 // Input too short
3318 return false;
3319 }
3320
3321 memcpy(reinterpret_cast<char*>(&bitmap[0] + minNonZero), ptr,
3322 maxNonZero - minNonZero + 1);
3323 ptr += maxNonZero - minNonZero + 1;
3324 readLen += maxNonZero - minNonZero + 1;
3325 } else {
3326 // Issue 194
3327 if ((minNonZero == (BITMAP_SIZE - 1)) && (maxNonZero == 0)) {
3328 // OK. all pixels are zero. And no need to read `bitmap` data.
3329 } else {
3330 // invalid minNonZero/maxNonZero combination.
3331 return false;
3332 }
3333 }
3334
3335 std::vector<unsigned short> lut(USHORT_RANGE);
3336 memset(lut.data(), 0, sizeof(unsigned short) * USHORT_RANGE);
3337 unsigned short maxValue = reverseLutFromBitmap(bitmap.data(), lut.data());
3338
3339 //
3340 // Huffman decoding
3341 //
3342
3343 if ((readLen + 4) > inLen) {
3344 return false;
3345 }
3346
3347 int length = 0;
3348
3349 // length = *(reinterpret_cast<const int *>(ptr));
3350 tinyexr::cpy4(&length, reinterpret_cast<const int*>(ptr));
3351 ptr += sizeof(int);
3352
3353 if (size_t((ptr - inPtr) + length) > inLen) {
3354 return false;
3355 }
3356
3357 std::vector<unsigned short> tmpBuffer(tmpBufSizeInBytes / sizeof(unsigned short));
3358 hufUncompress(reinterpret_cast<const char*>(ptr), length, &tmpBuffer);
3359
3360 //
3361 // Wavelet decoding
3362 //
3363
3364 std::vector<PIZChannelData> channelData(static_cast<size_t>(num_channels));
3365
3366 unsigned short* tmpBufferEnd = &tmpBuffer.at(0);
3367
3368 for (size_t i = 0; i < static_cast<size_t>(num_channels); ++i) {
3369 const EXRChannelInfo& chan = channels[i];
3370
3371 size_t pixelSize = sizeof(int); // UINT and FLOAT
3372 if (chan.pixel_type == TINYEXR_PIXELTYPE_HALF) {
3373 pixelSize = sizeof(short);
3374 }
3375
3376 channelData[i].start = tmpBufferEnd;
3377 channelData[i].end = channelData[i].start;
3378 channelData[i].nx = data_width;
3379 channelData[i].ny = num_lines;
3380 // channelData[i].ys = 1;
3381 channelData[i].size = static_cast<int>(pixelSize / sizeof(short));
3382
3383 tmpBufferEnd += channelData[i].nx * channelData[i].ny * channelData[i].size;
3384 }
3385
3386 for (size_t i = 0; i < channelData.size(); ++i) {
3387 PIZChannelData& cd = channelData[i];
3388
3389 for (int j = 0; j < cd.size; ++j) {
3390 wav2Decode(cd.start + j, cd.nx, cd.size, cd.ny, cd.nx * cd.size,
3391 maxValue);
3392 }
3393 }
3394
3395 //
3396 // Expand the pixel data to their original range
3397 //
3398
3399 applyLut(lut.data(), &tmpBuffer.at(0), static_cast<int>(tmpBufSizeInBytes / sizeof(unsigned short)));
3400
3401 for (int y = 0; y < num_lines; y++) {
3402 for (size_t i = 0; i < channelData.size(); ++i) {
3403 PIZChannelData& cd = channelData[i];
3404
3405 // if (modp (y, cd.ys) != 0)
3406 // continue;
3407
3408 size_t n = static_cast<size_t>(cd.nx * cd.size);
3409 memcpy(outPtr, cd.end, static_cast<size_t>(n * sizeof(unsigned short)));
3410 outPtr += n * sizeof(unsigned short);
3411 cd.end += n;
3412 }
3413 }
3414
3415 return true;
3416}
3417#endif // TINYEXR_USE_PIZ
3418
3419#if TINYEXR_USE_ZFP
3420
3421struct ZFPCompressionParam {
3422 double rate;
3423 unsigned int precision;
3424 unsigned int __pad0;
3425 double tolerance;
3426 int type; // TINYEXR_ZFP_COMPRESSIONTYPE_*
3427 unsigned int __pad1;
3428
3429 ZFPCompressionParam()
3430 {
3432 rate = 2.0;
3433 precision = 0;
3434 tolerance = 0.0;
3435 }
3436};
3437
3438static bool FindZFPCompressionParam(ZFPCompressionParam* param,
3439 const EXRAttribute* attributes,
3440 int num_attributes, std::string* err)
3441{
3442 bool foundType = false;
3443
3444 for (int i = 0; i < num_attributes; i++) {
3445 if ((strcmp(attributes[i].name, "zfpCompressionType") == 0)) {
3446 if (attributes[i].size == 1) {
3447 param->type = static_cast<int>(attributes[i].value[0]);
3448 foundType = true;
3449 break;
3450 } else {
3451 if (err) {
3452 (*err) += "zfpCompressionType attribute must be uchar(1 byte) type.\n";
3453 }
3454 return false;
3455 }
3456 }
3457 }
3458
3459 if (!foundType) {
3460 if (err) {
3461 (*err) += "`zfpCompressionType` attribute not found.\n";
3462 }
3463 return false;
3464 }
3465
3466 if (param->type == TINYEXR_ZFP_COMPRESSIONTYPE_RATE) {
3467 for (int i = 0; i < num_attributes; i++) {
3468 if ((strcmp(attributes[i].name, "zfpCompressionRate") == 0) && (attributes[i].size == 8)) {
3469 param->rate = *(reinterpret_cast<double*>(attributes[i].value));
3470 return true;
3471 }
3472 }
3473
3474 if (err) {
3475 (*err) += "`zfpCompressionRate` attribute not found.\n";
3476 }
3477
3478 } else if (param->type == TINYEXR_ZFP_COMPRESSIONTYPE_PRECISION) {
3479 for (int i = 0; i < num_attributes; i++) {
3480 if ((strcmp(attributes[i].name, "zfpCompressionPrecision") == 0) && (attributes[i].size == 4)) {
3481 param->rate = *(reinterpret_cast<int*>(attributes[i].value));
3482 return true;
3483 }
3484 }
3485
3486 if (err) {
3487 (*err) += "`zfpCompressionPrecision` attribute not found.\n";
3488 }
3489
3490 } else if (param->type == TINYEXR_ZFP_COMPRESSIONTYPE_ACCURACY) {
3491 for (int i = 0; i < num_attributes; i++) {
3492 if ((strcmp(attributes[i].name, "zfpCompressionTolerance") == 0) && (attributes[i].size == 8)) {
3493 param->tolerance = *(reinterpret_cast<double*>(attributes[i].value));
3494 return true;
3495 }
3496 }
3497
3498 if (err) {
3499 (*err) += "`zfpCompressionTolerance` attribute not found.\n";
3500 }
3501 } else {
3502 if (err) {
3503 (*err) += "Unknown value specified for `zfpCompressionType`.\n";
3504 }
3505 }
3506
3507 return false;
3508}
3509
3510// Assume pixel format is FLOAT for all channels.
3511static bool DecompressZfp(float* dst, int dst_width, int dst_num_lines,
3512 size_t num_channels, const unsigned char* src,
3513 unsigned long src_size,
3514 const ZFPCompressionParam& param)
3515{
3516 size_t uncompressed_size = size_t(dst_width) * size_t(dst_num_lines) * num_channels;
3517
3518 if (uncompressed_size == src_size) {
3519 // Data is not compressed(Issue 40).
3520 memcpy(dst, src, src_size);
3521 }
3522
3523 zfp_stream* zfp = NULL;
3524 zfp_field* field = NULL;
3525
3526 TINYEXR_CHECK_AND_RETURN_C((dst_width % 4) == 0, false);
3527 TINYEXR_CHECK_AND_RETURN_C((dst_num_lines % 4) == 0, false);
3528
3529 if ((size_t(dst_width) & 3U) || (size_t(dst_num_lines) & 3U)) {
3530 return false;
3531 }
3532
3533 field = zfp_field_2d(reinterpret_cast<void*>(const_cast<unsigned char*>(src)),
3534 zfp_type_float, static_cast<unsigned int>(dst_width),
3535 static_cast<unsigned int>(dst_num_lines) * static_cast<unsigned int>(num_channels));
3536 zfp = zfp_stream_open(NULL);
3537
3538 if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_RATE) {
3539 zfp_stream_set_rate(zfp, param.rate, zfp_type_float, /* dimension */ 2,
3540 /* write random access */ 0);
3541 } else if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_PRECISION) {
3542 zfp_stream_set_precision(zfp, param.precision);
3543 } else if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_ACCURACY) {
3544 zfp_stream_set_accuracy(zfp, param.tolerance);
3545 } else {
3546 return false;
3547 }
3548
3549 size_t buf_size = zfp_stream_maximum_size(zfp, field);
3550 std::vector<unsigned char> buf(buf_size);
3551 memcpy(&buf.at(0), src, src_size);
3552
3553 bitstream* stream = stream_open(&buf.at(0), buf_size);
3554 zfp_stream_set_bit_stream(zfp, stream);
3555 zfp_stream_rewind(zfp);
3556
3557 size_t image_size = size_t(dst_width) * size_t(dst_num_lines);
3558
3559 for (size_t c = 0; c < size_t(num_channels); c++) {
3560 // decompress 4x4 pixel block.
3561 for (size_t y = 0; y < size_t(dst_num_lines); y += 4) {
3562 for (size_t x = 0; x < size_t(dst_width); x += 4) {
3563 float fblock[16];
3564 zfp_decode_block_float_2(zfp, fblock);
3565 for (size_t j = 0; j < 4; j++) {
3566 for (size_t i = 0; i < 4; i++) {
3567 dst[c * image_size + ((y + j) * size_t(dst_width) + (x + i))] = fblock[j * 4 + i];
3568 }
3569 }
3570 }
3571 }
3572 }
3573
3574 zfp_field_free(field);
3575 zfp_stream_close(zfp);
3576 stream_close(stream);
3577
3578 return true;
3579}
3580
3581// Assume pixel format is FLOAT for all channels.
3582static bool CompressZfp(std::vector<unsigned char>* outBuf,
3583 unsigned int* outSize, const float* inPtr, int width,
3584 int num_lines, int num_channels,
3585 const ZFPCompressionParam& param)
3586{
3587 zfp_stream* zfp = NULL;
3588 zfp_field* field = NULL;
3589
3590 TINYEXR_CHECK_AND_RETURN_C((width % 4) == 0, false);
3591 TINYEXR_CHECK_AND_RETURN_C((num_lines % 4) == 0, false);
3592
3593 if ((size_t(width) & 3U) || (size_t(num_lines) & 3U)) {
3594 return false;
3595 }
3596
3597 // create input array.
3598 field = zfp_field_2d(reinterpret_cast<void*>(const_cast<float*>(inPtr)),
3599 zfp_type_float, static_cast<unsigned int>(width),
3600 static_cast<unsigned int>(num_lines * num_channels));
3601
3602 zfp = zfp_stream_open(NULL);
3603
3604 if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_RATE) {
3605 zfp_stream_set_rate(zfp, param.rate, zfp_type_float, 2, 0);
3606 } else if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_PRECISION) {
3607 zfp_stream_set_precision(zfp, param.precision);
3608 } else if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_ACCURACY) {
3609 zfp_stream_set_accuracy(zfp, param.tolerance);
3610 } else {
3611 return false;
3612 }
3613
3614 size_t buf_size = zfp_stream_maximum_size(zfp, field);
3615
3616 outBuf->resize(buf_size);
3617
3618 bitstream* stream = stream_open(&outBuf->at(0), buf_size);
3619 zfp_stream_set_bit_stream(zfp, stream);
3620 zfp_field_free(field);
3621
3622 size_t image_size = size_t(width) * size_t(num_lines);
3623
3624 for (size_t c = 0; c < size_t(num_channels); c++) {
3625 // compress 4x4 pixel block.
3626 for (size_t y = 0; y < size_t(num_lines); y += 4) {
3627 for (size_t x = 0; x < size_t(width); x += 4) {
3628 float fblock[16];
3629 for (size_t j = 0; j < 4; j++) {
3630 for (size_t i = 0; i < 4; i++) {
3631 fblock[j * 4 + i] = inPtr[c * image_size + ((y + j) * size_t(width) + (x + i))];
3632 }
3633 }
3634 zfp_encode_block_float_2(zfp, fblock);
3635 }
3636 }
3637 }
3638
3639 zfp_stream_flush(zfp);
3640 (*outSize) = static_cast<unsigned int>(zfp_stream_compressed_size(zfp));
3641
3642 zfp_stream_close(zfp);
3643
3644 return true;
3645}
3646
3647#endif
3648
3649//
3650// -----------------------------------------------------------------
3651//
3652
3653// heuristics
3654#define TINYEXR_DIMENSION_THRESHOLD (1024 * 8192)
3655
3656// TODO(syoyo): Refactor function arguments.
3657static bool DecodePixelData(/* out */ unsigned char** out_images,
3658 const int* requested_pixel_types,
3659 const unsigned char* data_ptr, size_t data_len,
3660 int compression_type, int line_order, int width,
3661 int height, int x_stride, int y, int line_no,
3662 int num_lines, size_t pixel_data_size,
3663 size_t num_attributes,
3664 const EXRAttribute* attributes, size_t num_channels,
3665 const EXRChannelInfo* channels,
3666 const std::vector<size_t>& channel_offset_list)
3667{
3668 if (compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) { // PIZ
3669#if TINYEXR_USE_PIZ
3670 if ((width == 0) || (num_lines == 0) || (pixel_data_size == 0)) {
3671 // Invalid input #90
3672 return false;
3673 }
3674
3675 // Allocate original data size.
3676 std::vector<unsigned char> outBuf(static_cast<size_t>(
3677 static_cast<size_t>(width * num_lines) * pixel_data_size));
3678 size_t tmpBufLen = outBuf.size();
3679
3680 bool ret = tinyexr::DecompressPiz(
3681 reinterpret_cast<unsigned char*>(&outBuf.at(0)), data_ptr, tmpBufLen,
3682 data_len, static_cast<int>(num_channels), channels, width, num_lines);
3683
3684 if (!ret) {
3685 return false;
3686 }
3687
3688 // For PIZ_COMPRESSION:
3689 // pixel sample data for channel 0 for scanline 0
3690 // pixel sample data for channel 1 for scanline 0
3691 // pixel sample data for channel ... for scanline 0
3692 // pixel sample data for channel n for scanline 0
3693 // pixel sample data for channel 0 for scanline 1
3694 // pixel sample data for channel 1 for scanline 1
3695 // pixel sample data for channel ... for scanline 1
3696 // pixel sample data for channel n for scanline 1
3697 // ...
3698 for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) {
3699 if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) {
3700 for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {
3701 const unsigned short* line_ptr = reinterpret_cast<unsigned short*>(
3702 &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) + channel_offset_list[c] * static_cast<size_t>(width)));
3703 for (size_t u = 0; u < static_cast<size_t>(width); u++) {
3704 FP16 hf;
3705
3706 // hf.u = line_ptr[u];
3707 // use `cpy` to avoid unaligned memory access when compiler's
3708 // optimization is on.
3709 tinyexr::cpy2(&(hf.u), line_ptr + u);
3710
3711 tinyexr::swap2(reinterpret_cast<unsigned short*>(&hf.u));
3712
3713 if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) {
3714 unsigned short* image = reinterpret_cast<unsigned short**>(out_images)[c];
3715 if (line_order == 0) {
3716 image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u;
3717 } else {
3718 image += static_cast<size_t>(
3719 (height - 1 - (line_no + static_cast<int>(v))))
3720 * static_cast<size_t>(x_stride)
3721 + u;
3722 }
3723 *image = hf.u;
3724 } else { // HALF -> FLOAT
3725 FP32 f32 = half_to_float(hf);
3726 float* image = reinterpret_cast<float**>(out_images)[c];
3727 size_t offset = 0;
3728 if (line_order == 0) {
3729 offset = (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u;
3730 } else {
3731 offset = static_cast<size_t>(
3732 (height - 1 - (line_no + static_cast<int>(v))))
3733 * static_cast<size_t>(x_stride)
3734 + u;
3735 }
3736 image += offset;
3737 *image = f32.f;
3738 }
3739 }
3740 }
3741 } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) {
3742 TINYEXR_CHECK_AND_RETURN_C(requested_pixel_types[c] == TINYEXR_PIXELTYPE_UINT, false);
3743
3744 for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {
3745 const unsigned int* line_ptr = reinterpret_cast<unsigned int*>(
3746 &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) + channel_offset_list[c] * static_cast<size_t>(width)));
3747 for (size_t u = 0; u < static_cast<size_t>(width); u++) {
3748 unsigned int val;
3749 // val = line_ptr[u];
3750 tinyexr::cpy4(&val, line_ptr + u);
3751
3752 tinyexr::swap4(&val);
3753
3754 unsigned int* image = reinterpret_cast<unsigned int**>(out_images)[c];
3755 if (line_order == 0) {
3756 image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u;
3757 } else {
3758 image += static_cast<size_t>(
3759 (height - 1 - (line_no + static_cast<int>(v))))
3760 * static_cast<size_t>(x_stride)
3761 + u;
3762 }
3763 *image = val;
3764 }
3765 }
3766 } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) {
3767 TINYEXR_CHECK_AND_RETURN_C(requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT, false);
3768 for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {
3769 const float* line_ptr = reinterpret_cast<float*>(&outBuf.at(
3770 v * pixel_data_size * static_cast<size_t>(width) + channel_offset_list[c] * static_cast<size_t>(width)));
3771 for (size_t u = 0; u < static_cast<size_t>(width); u++) {
3772 float val;
3773 // val = line_ptr[u];
3774 tinyexr::cpy4(&val, line_ptr + u);
3775
3776 tinyexr::swap4(reinterpret_cast<unsigned int*>(&val));
3777
3778 float* image = reinterpret_cast<float**>(out_images)[c];
3779 if (line_order == 0) {
3780 image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u;
3781 } else {
3782 image += static_cast<size_t>(
3783 (height - 1 - (line_no + static_cast<int>(v))))
3784 * static_cast<size_t>(x_stride)
3785 + u;
3786 }
3787 *image = val;
3788 }
3789 }
3790 } else {
3791 return false;
3792 }
3793 }
3794#else
3795 return false;
3796#endif
3797
3798 } else if (compression_type == TINYEXR_COMPRESSIONTYPE_ZIPS || compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) {
3799 // Allocate original data size.
3800 std::vector<unsigned char> outBuf(static_cast<size_t>(width) * static_cast<size_t>(num_lines) * pixel_data_size);
3801
3802 unsigned long dstLen = static_cast<unsigned long>(outBuf.size());
3803 TINYEXR_CHECK_AND_RETURN_C(dstLen > 0, false);
3804 if (!tinyexr::DecompressZip(
3805 reinterpret_cast<unsigned char*>(&outBuf.at(0)), &dstLen, data_ptr,
3806 static_cast<unsigned long>(data_len))) {
3807 return false;
3808 }
3809
3810 // For ZIP_COMPRESSION:
3811 // pixel sample data for channel 0 for scanline 0
3812 // pixel sample data for channel 1 for scanline 0
3813 // pixel sample data for channel ... for scanline 0
3814 // pixel sample data for channel n for scanline 0
3815 // pixel sample data for channel 0 for scanline 1
3816 // pixel sample data for channel 1 for scanline 1
3817 // pixel sample data for channel ... for scanline 1
3818 // pixel sample data for channel n for scanline 1
3819 // ...
3820 for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) {
3821 if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) {
3822 for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {
3823 const unsigned short* line_ptr = reinterpret_cast<unsigned short*>(
3824 &outBuf.at(v * static_cast<size_t>(pixel_data_size) * static_cast<size_t>(width) + channel_offset_list[c] * static_cast<size_t>(width)));
3825 for (size_t u = 0; u < static_cast<size_t>(width); u++) {
3826 tinyexr::FP16 hf;
3827
3828 // hf.u = line_ptr[u];
3829 tinyexr::cpy2(&(hf.u), line_ptr + u);
3830
3831 tinyexr::swap2(reinterpret_cast<unsigned short*>(&hf.u));
3832
3833 if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) {
3834 unsigned short* image = reinterpret_cast<unsigned short**>(out_images)[c];
3835 if (line_order == 0) {
3836 image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u;
3837 } else {
3838 image += (static_cast<size_t>(height) - 1U - (static_cast<size_t>(line_no) + v)) * static_cast<size_t>(x_stride) + u;
3839 }
3840 *image = hf.u;
3841 } else { // HALF -> FLOAT
3842 tinyexr::FP32 f32 = half_to_float(hf);
3843 float* image = reinterpret_cast<float**>(out_images)[c];
3844 size_t offset = 0;
3845 if (line_order == 0) {
3846 offset = (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u;
3847 } else {
3848 offset = (static_cast<size_t>(height) - 1U - (static_cast<size_t>(line_no) + v)) * static_cast<size_t>(x_stride) + u;
3849 }
3850 image += offset;
3851
3852 *image = f32.f;
3853 }
3854 }
3855 }
3856 } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) {
3857 TINYEXR_CHECK_AND_RETURN_C(requested_pixel_types[c] == TINYEXR_PIXELTYPE_UINT, false);
3858
3859 for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {
3860 const unsigned int* line_ptr = reinterpret_cast<unsigned int*>(
3861 &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) + channel_offset_list[c] * static_cast<size_t>(width)));
3862 for (size_t u = 0; u < static_cast<size_t>(width); u++) {
3863 unsigned int val;
3864 // val = line_ptr[u];
3865 tinyexr::cpy4(&val, line_ptr + u);
3866
3867 tinyexr::swap4(&val);
3868
3869 unsigned int* image = reinterpret_cast<unsigned int**>(out_images)[c];
3870 if (line_order == 0) {
3871 image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u;
3872 } else {
3873 image += (static_cast<size_t>(height) - 1U - (static_cast<size_t>(line_no) + v)) * static_cast<size_t>(x_stride) + u;
3874 }
3875 *image = val;
3876 }
3877 }
3878 } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) {
3879 TINYEXR_CHECK_AND_RETURN_C(requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT, false);
3880 for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {
3881 const float* line_ptr = reinterpret_cast<float*>(
3882 &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) + channel_offset_list[c] * static_cast<size_t>(width)));
3883 for (size_t u = 0; u < static_cast<size_t>(width); u++) {
3884 float val;
3885 // val = line_ptr[u];
3886 tinyexr::cpy4(&val, line_ptr + u);
3887
3888 tinyexr::swap4(reinterpret_cast<unsigned int*>(&val));
3889
3890 float* image = reinterpret_cast<float**>(out_images)[c];
3891 if (line_order == 0) {
3892 image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u;
3893 } else {
3894 image += (static_cast<size_t>(height) - 1U - (static_cast<size_t>(line_no) + v)) * static_cast<size_t>(x_stride) + u;
3895 }
3896 *image = val;
3897 }
3898 }
3899 } else {
3900 return false;
3901 }
3902 }
3903 } else if (compression_type == TINYEXR_COMPRESSIONTYPE_RLE) {
3904 // Allocate original data size.
3905 std::vector<unsigned char> outBuf(static_cast<size_t>(width) * static_cast<size_t>(num_lines) * pixel_data_size);
3906
3907 unsigned long dstLen = static_cast<unsigned long>(outBuf.size());
3908 if (dstLen == 0) {
3909 return false;
3910 }
3911
3912 if (!tinyexr::DecompressRle(
3913 reinterpret_cast<unsigned char*>(&outBuf.at(0)), dstLen, data_ptr,
3914 static_cast<unsigned long>(data_len))) {
3915 return false;
3916 }
3917
3918 // For RLE_COMPRESSION:
3919 // pixel sample data for channel 0 for scanline 0
3920 // pixel sample data for channel 1 for scanline 0
3921 // pixel sample data for channel ... for scanline 0
3922 // pixel sample data for channel n for scanline 0
3923 // pixel sample data for channel 0 for scanline 1
3924 // pixel sample data for channel 1 for scanline 1
3925 // pixel sample data for channel ... for scanline 1
3926 // pixel sample data for channel n for scanline 1
3927 // ...
3928 for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) {
3929 if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) {
3930 for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {
3931 const unsigned short* line_ptr = reinterpret_cast<unsigned short*>(
3932 &outBuf.at(v * static_cast<size_t>(pixel_data_size) * static_cast<size_t>(width) + channel_offset_list[c] * static_cast<size_t>(width)));
3933 for (size_t u = 0; u < static_cast<size_t>(width); u++) {
3934 tinyexr::FP16 hf;
3935
3936 // hf.u = line_ptr[u];
3937 tinyexr::cpy2(&(hf.u), line_ptr + u);
3938
3939 tinyexr::swap2(reinterpret_cast<unsigned short*>(&hf.u));
3940
3941 if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) {
3942 unsigned short* image = reinterpret_cast<unsigned short**>(out_images)[c];
3943 if (line_order == 0) {
3944 image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u;
3945 } else {
3946 image += (static_cast<size_t>(height) - 1U - (static_cast<size_t>(line_no) + v)) * static_cast<size_t>(x_stride) + u;
3947 }
3948 *image = hf.u;
3949 } else { // HALF -> FLOAT
3950 tinyexr::FP32 f32 = half_to_float(hf);
3951 float* image = reinterpret_cast<float**>(out_images)[c];
3952 if (line_order == 0) {
3953 image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u;
3954 } else {
3955 image += (static_cast<size_t>(height) - 1U - (static_cast<size_t>(line_no) + v)) * static_cast<size_t>(x_stride) + u;
3956 }
3957 *image = f32.f;
3958 }
3959 }
3960 }
3961 } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) {
3962 TINYEXR_CHECK_AND_RETURN_C(requested_pixel_types[c] == TINYEXR_PIXELTYPE_UINT, false);
3963
3964 for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {
3965 const unsigned int* line_ptr = reinterpret_cast<unsigned int*>(
3966 &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) + channel_offset_list[c] * static_cast<size_t>(width)));
3967 for (size_t u = 0; u < static_cast<size_t>(width); u++) {
3968 unsigned int val;
3969 // val = line_ptr[u];
3970 tinyexr::cpy4(&val, line_ptr + u);
3971
3972 tinyexr::swap4(&val);
3973
3974 unsigned int* image = reinterpret_cast<unsigned int**>(out_images)[c];
3975 if (line_order == 0) {
3976 image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u;
3977 } else {
3978 image += (static_cast<size_t>(height) - 1U - (static_cast<size_t>(line_no) + v)) * static_cast<size_t>(x_stride) + u;
3979 }
3980 *image = val;
3981 }
3982 }
3983 } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) {
3984 TINYEXR_CHECK_AND_RETURN_C(requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT, false);
3985 for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {
3986 const float* line_ptr = reinterpret_cast<float*>(
3987 &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) + channel_offset_list[c] * static_cast<size_t>(width)));
3988 for (size_t u = 0; u < static_cast<size_t>(width); u++) {
3989 float val;
3990 // val = line_ptr[u];
3991 tinyexr::cpy4(&val, line_ptr + u);
3992
3993 tinyexr::swap4(reinterpret_cast<unsigned int*>(&val));
3994
3995 float* image = reinterpret_cast<float**>(out_images)[c];
3996 if (line_order == 0) {
3997 image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u;
3998 } else {
3999 image += (static_cast<size_t>(height) - 1U - (static_cast<size_t>(line_no) + v)) * static_cast<size_t>(x_stride) + u;
4000 }
4001 *image = val;
4002 }
4003 }
4004 } else {
4005 return false;
4006 }
4007 }
4008 } else if (compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) {
4009#if TINYEXR_USE_ZFP
4010 tinyexr::ZFPCompressionParam zfp_compression_param;
4011 std::string e;
4012 if (!tinyexr::FindZFPCompressionParam(&zfp_compression_param, attributes,
4013 int(num_attributes), &e)) {
4014 // This code path should not be reachable.
4015 return false;
4016 }
4017
4018 // Allocate original data size.
4019 std::vector<unsigned char> outBuf(static_cast<size_t>(width) * static_cast<size_t>(num_lines) * pixel_data_size);
4020
4021 unsigned long dstLen = outBuf.size();
4022 TINYEXR_CHECK_AND_RETURN_C(dstLen > 0, false);
4023 tinyexr::DecompressZfp(reinterpret_cast<float*>(&outBuf.at(0)), width,
4024 num_lines, num_channels, data_ptr,
4025 static_cast<unsigned long>(data_len),
4026 zfp_compression_param);
4027
4028 // For ZFP_COMPRESSION:
4029 // pixel sample data for channel 0 for scanline 0
4030 // pixel sample data for channel 1 for scanline 0
4031 // pixel sample data for channel ... for scanline 0
4032 // pixel sample data for channel n for scanline 0
4033 // pixel sample data for channel 0 for scanline 1
4034 // pixel sample data for channel 1 for scanline 1
4035 // pixel sample data for channel ... for scanline 1
4036 // pixel sample data for channel n for scanline 1
4037 // ...
4038 for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) {
4039 TINYEXR_CHECK_AND_RETURN_C(channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT, false);
4040 if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) {
4041 TINYEXR_CHECK_AND_RETURN_C(requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT, false);
4042 for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {
4043 const float* line_ptr = reinterpret_cast<float*>(
4044 &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) + channel_offset_list[c] * static_cast<size_t>(width)));
4045 for (size_t u = 0; u < static_cast<size_t>(width); u++) {
4046 float val;
4047 tinyexr::cpy4(&val, line_ptr + u);
4048
4049 tinyexr::swap4(reinterpret_cast<unsigned int*>(&val));
4050
4051 float* image = reinterpret_cast<float**>(out_images)[c];
4052 if (line_order == 0) {
4053 image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u;
4054 } else {
4055 image += (static_cast<size_t>(height) - 1U - (static_cast<size_t>(line_no) + v)) * static_cast<size_t>(x_stride) + u;
4056 }
4057 *image = val;
4058 }
4059 }
4060 } else {
4061 return false;
4062 }
4063 }
4064#else
4065 (void)attributes;
4066 (void)num_attributes;
4067 (void)num_channels;
4068 return false;
4069#endif
4070 } else if (compression_type == TINYEXR_COMPRESSIONTYPE_NONE) {
4071 for (size_t c = 0; c < num_channels; c++) {
4072 for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {
4073 if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) {
4074 const unsigned short* line_ptr = reinterpret_cast<const unsigned short*>(
4075 data_ptr + v * pixel_data_size * size_t(width) + channel_offset_list[c] * static_cast<size_t>(width));
4076
4077 if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) {
4078 unsigned short* outLine = reinterpret_cast<unsigned short*>(out_images[c]);
4079 if (line_order == 0) {
4080 outLine += (size_t(y) + v) * size_t(x_stride);
4081 } else {
4082 outLine += (size_t(height) - 1 - (size_t(y) + v)) * size_t(x_stride);
4083 }
4084
4085 for (int u = 0; u < width; u++) {
4086 tinyexr::FP16 hf;
4087
4088 // hf.u = line_ptr[u];
4089 tinyexr::cpy2(&(hf.u), line_ptr + u);
4090
4091 tinyexr::swap2(reinterpret_cast<unsigned short*>(&hf.u));
4092
4093 outLine[u] = hf.u;
4094 }
4095 } else if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT) {
4096 float* outLine = reinterpret_cast<float*>(out_images[c]);
4097 if (line_order == 0) {
4098 outLine += (size_t(y) + v) * size_t(x_stride);
4099 } else {
4100 outLine += (size_t(height) - 1 - (size_t(y) + v)) * size_t(x_stride);
4101 }
4102
4103 if (reinterpret_cast<const unsigned char*>(line_ptr + width) > (data_ptr + data_len)) {
4104 // Insufficient data size
4105 return false;
4106 }
4107
4108 for (int u = 0; u < width; u++) {
4109 tinyexr::FP16 hf;
4110
4111 // address may not be aligned. use byte-wise copy for safety.#76
4112 // hf.u = line_ptr[u];
4113 tinyexr::cpy2(&(hf.u), line_ptr + u);
4114
4115 tinyexr::swap2(reinterpret_cast<unsigned short*>(&hf.u));
4116
4117 tinyexr::FP32 f32 = half_to_float(hf);
4118
4119 outLine[u] = f32.f;
4120 }
4121 } else {
4122 return false;
4123 }
4124 } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) {
4125 const float* line_ptr = reinterpret_cast<const float*>(
4126 data_ptr + v * pixel_data_size * size_t(width) + channel_offset_list[c] * static_cast<size_t>(width));
4127
4128 float* outLine = reinterpret_cast<float*>(out_images[c]);
4129 if (line_order == 0) {
4130 outLine += (size_t(y) + v) * size_t(x_stride);
4131 } else {
4132 outLine += (size_t(height) - 1 - (size_t(y) + v)) * size_t(x_stride);
4133 }
4134
4135 if (reinterpret_cast<const unsigned char*>(line_ptr + width) > (data_ptr + data_len)) {
4136 // Insufficient data size
4137 return false;
4138 }
4139
4140 for (int u = 0; u < width; u++) {
4141 float val;
4142 tinyexr::cpy4(&val, line_ptr + u);
4143
4144 tinyexr::swap4(reinterpret_cast<unsigned int*>(&val));
4145
4146 outLine[u] = val;
4147 }
4148 } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) {
4149 const unsigned int* line_ptr = reinterpret_cast<const unsigned int*>(
4150 data_ptr + v * pixel_data_size * size_t(width) + channel_offset_list[c] * static_cast<size_t>(width));
4151
4152 unsigned int* outLine = reinterpret_cast<unsigned int*>(out_images[c]);
4153 if (line_order == 0) {
4154 outLine += (size_t(y) + v) * size_t(x_stride);
4155 } else {
4156 outLine += (size_t(height) - 1 - (size_t(y) + v)) * size_t(x_stride);
4157 }
4158
4159 if (reinterpret_cast<const unsigned char*>(line_ptr + width) > (data_ptr + data_len)) {
4160 // Corrupted data
4161 return false;
4162 }
4163
4164 for (int u = 0; u < width; u++) {
4165
4166 unsigned int val;
4167 tinyexr::cpy4(&val, line_ptr + u);
4168
4169 tinyexr::swap4(reinterpret_cast<unsigned int*>(&val));
4170
4171 outLine[u] = val;
4172 }
4173 }
4174 }
4175 }
4176 }
4177
4178 return true;
4179}
4180
4181static bool DecodeTiledPixelData(
4182 unsigned char** out_images, int* width, int* height,
4183 const int* requested_pixel_types, const unsigned char* data_ptr,
4184 size_t data_len, int compression_type, int line_order, int data_width,
4185 int data_height, int tile_offset_x, int tile_offset_y, int tile_size_x,
4186 int tile_size_y, size_t pixel_data_size, size_t num_attributes,
4187 const EXRAttribute* attributes, size_t num_channels,
4188 const EXRChannelInfo* channels,
4189 const std::vector<size_t>& channel_offset_list)
4190{
4191 // Here, data_width and data_height are the dimensions of the current (sub)level.
4192 if (tile_size_x * tile_offset_x > data_width || tile_size_y * tile_offset_y > data_height) {
4193 return false;
4194 }
4195
4196 // Compute actual image size in a tile.
4197 if ((tile_offset_x + 1) * tile_size_x >= data_width) {
4198 (*width) = data_width - (tile_offset_x * tile_size_x);
4199 } else {
4200 (*width) = tile_size_x;
4201 }
4202
4203 if ((tile_offset_y + 1) * tile_size_y >= data_height) {
4204 (*height) = data_height - (tile_offset_y * tile_size_y);
4205 } else {
4206 (*height) = tile_size_y;
4207 }
4208
4209 // Image size = tile size.
4210 return DecodePixelData(out_images, requested_pixel_types, data_ptr, data_len,
4211 compression_type, line_order, (*width), tile_size_y,
4212 /* stride */ tile_size_x, /* y */ 0, /* line_no */ 0,
4213 (*height), pixel_data_size, num_attributes, attributes,
4214 num_channels, channels, channel_offset_list);
4215}
4216
4217static bool ComputeChannelLayout(std::vector<size_t>* channel_offset_list,
4218 int* pixel_data_size, size_t* channel_offset,
4219 int num_channels,
4220 const EXRChannelInfo* channels)
4221{
4222 channel_offset_list->resize(static_cast<size_t>(num_channels));
4223
4224 (*pixel_data_size) = 0;
4225 (*channel_offset) = 0;
4226
4227 for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) {
4228 (*channel_offset_list)[c] = (*channel_offset);
4229 if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) {
4230 (*pixel_data_size) += sizeof(unsigned short);
4231 (*channel_offset) += sizeof(unsigned short);
4232 } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) {
4233 (*pixel_data_size) += sizeof(float);
4234 (*channel_offset) += sizeof(float);
4235 } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) {
4236 (*pixel_data_size) += sizeof(unsigned int);
4237 (*channel_offset) += sizeof(unsigned int);
4238 } else {
4239 // ???
4240 return false;
4241 }
4242 }
4243 return true;
4244}
4245
4246// TODO: Simply return nullptr when failed to allocate?
4247static unsigned char** AllocateImage(int num_channels,
4248 const EXRChannelInfo* channels,
4249 const int* requested_pixel_types,
4250 int data_width, int data_height, bool* success)
4251{
4252 unsigned char** images = reinterpret_cast<unsigned char**>(static_cast<float**>(
4253 malloc(sizeof(float*) * static_cast<size_t>(num_channels))));
4254
4255 for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) {
4256 images[c] = NULL;
4257 }
4258
4259 bool valid = true;
4260
4261 for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) {
4262 size_t data_len = static_cast<size_t>(data_width) * static_cast<size_t>(data_height);
4263 if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) {
4264 // pixel_data_size += sizeof(unsigned short);
4265 // channel_offset += sizeof(unsigned short);
4266 // Alloc internal image for half type.
4267 if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) {
4268 images[c] = reinterpret_cast<unsigned char*>(static_cast<unsigned short*>(
4269 malloc(sizeof(unsigned short) * data_len)));
4270 } else if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT) {
4271 images[c] = reinterpret_cast<unsigned char*>(
4272 static_cast<float*>(malloc(sizeof(float) * data_len)));
4273 } else {
4274 images[c] = NULL; // just in case.
4275 valid = false;
4276 break;
4277 }
4278 } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) {
4279 // pixel_data_size += sizeof(float);
4280 // channel_offset += sizeof(float);
4281 images[c] = reinterpret_cast<unsigned char*>(
4282 static_cast<float*>(malloc(sizeof(float) * data_len)));
4283 } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) {
4284 // pixel_data_size += sizeof(unsigned int);
4285 // channel_offset += sizeof(unsigned int);
4286 images[c] = reinterpret_cast<unsigned char*>(
4287 static_cast<unsigned int*>(malloc(sizeof(unsigned int) * data_len)));
4288 } else {
4289 images[c] = NULL; // just in case.
4290 valid = false;
4291 break;
4292 }
4293 }
4294
4295 if (!valid) {
4296 for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) {
4297 if (images[c]) {
4298 free(images[c]);
4299 images[c] = NULL;
4300 }
4301 }
4302
4303 if (success) {
4304 (*success) = false;
4305 }
4306 } else {
4307 if (success) {
4308 (*success) = true;
4309 }
4310 }
4311
4312 return images;
4313}
4314
4315#ifdef _WIN32
4316static inline std::wstring UTF8ToWchar(const std::string& str)
4317{
4318 int wstr_size = MultiByteToWideChar(CP_UTF8, 0, str.data(), (int)str.size(), NULL, 0);
4319 std::wstring wstr(wstr_size, 0);
4320 MultiByteToWideChar(CP_UTF8, 0, str.data(), (int)str.size(), &wstr[0],
4321 (int)wstr.size());
4322 return wstr;
4323}
4324#endif
4325
4326static int ParseEXRHeader(HeaderInfo* info, bool* empty_header,
4327 const EXRVersion* version, std::string* err,
4328 const unsigned char* buf, size_t size)
4329{
4330 const char* marker = reinterpret_cast<const char*>(&buf[0]);
4331
4332 if (empty_header) {
4333 (*empty_header) = false;
4334 }
4335
4336 if (version->multipart) {
4337 if (size > 0 && marker[0] == '\0') {
4338 // End of header list.
4339 if (empty_header) {
4340 (*empty_header) = true;
4341 }
4342 return TINYEXR_SUCCESS;
4343 }
4344 }
4345
4346 // According to the spec, the header of every OpenEXR file must contain at
4347 // least the following attributes:
4348 //
4349 // channels chlist
4350 // compression compression
4351 // dataWindow box2i
4352 // displayWindow box2i
4353 // lineOrder lineOrder
4354 // pixelAspectRatio float
4355 // screenWindowCenter v2f
4356 // screenWindowWidth float
4357 bool has_channels = false;
4358 bool has_compression = false;
4359 bool has_data_window = false;
4360 bool has_display_window = false;
4361 bool has_line_order = false;
4362 bool has_pixel_aspect_ratio = false;
4363 bool has_screen_window_center = false;
4364 bool has_screen_window_width = false;
4365 bool has_name = false;
4366 bool has_type = false;
4367
4368 info->name.clear();
4369 info->type.clear();
4370
4371 info->data_window.min_x = 0;
4372 info->data_window.min_y = 0;
4373 info->data_window.max_x = 0;
4374 info->data_window.max_y = 0;
4375 info->line_order = 0; // @fixme
4376 info->display_window.min_x = 0;
4377 info->display_window.min_y = 0;
4378 info->display_window.max_x = 0;
4379 info->display_window.max_y = 0;
4380 info->screen_window_center[0] = 0.0f;
4381 info->screen_window_center[1] = 0.0f;
4382 info->screen_window_width = -1.0f;
4383 info->pixel_aspect_ratio = -1.0f;
4384
4385 info->tiled = 0;
4386 info->tile_size_x = -1;
4387 info->tile_size_y = -1;
4388 info->tile_level_mode = -1;
4389 info->tile_rounding_mode = -1;
4390
4391 info->attributes.clear();
4392
4393 // Read attributes
4394 size_t orig_size = size;
4395 for (size_t nattr = 0; nattr < TINYEXR_MAX_HEADER_ATTRIBUTES; nattr++) {
4396 if (0 == size) {
4397 if (err) {
4398 (*err) += "Insufficient data size for attributes.\n";
4399 }
4401 } else if (marker[0] == '\0') {
4402 size--;
4403 break;
4404 }
4405
4406 std::string attr_name;
4407 std::string attr_type;
4408 std::vector<unsigned char> data;
4409 size_t marker_size;
4410 if (!tinyexr::ReadAttribute(&attr_name, &attr_type, &data, &marker_size,
4411 marker, size)) {
4412 if (err) {
4413 (*err) += "Failed to read attribute.\n";
4414 }
4416 }
4417 marker += marker_size;
4418 size -= marker_size;
4419
4420 // For a multipart file, the version field 9th bit is 0.
4421 if ((version->tiled || version->multipart || version->non_image) && attr_name.compare("tiles") == 0) {
4422 unsigned int x_size, y_size;
4423 unsigned char tile_mode;
4424 if (data.size() != 9) {
4425 if (err) {
4426 (*err) += "(ParseEXRHeader) Invalid attribute data size. Attribute data size must be 9.\n";
4427 }
4429 }
4430
4431 memcpy(&x_size, &data.at(0), sizeof(int));
4432 memcpy(&y_size, &data.at(4), sizeof(int));
4433 tile_mode = data[8];
4434 tinyexr::swap4(&x_size);
4435 tinyexr::swap4(&y_size);
4436
4437 if (x_size > static_cast<unsigned int>(std::numeric_limits<int>::max()) || y_size > static_cast<unsigned int>(std::numeric_limits<int>::max())) {
4438 if (err) {
4439 (*err) = "Tile sizes were invalid.";
4440 }
4442 }
4443
4444 info->tile_size_x = static_cast<int>(x_size);
4445 info->tile_size_y = static_cast<int>(y_size);
4446
4447 // mode = levelMode + roundingMode * 16
4448 info->tile_level_mode = tile_mode & 0x3;
4449 info->tile_rounding_mode = (tile_mode >> 4) & 0x1;
4450 info->tiled = 1;
4451 } else if (attr_name.compare("compression") == 0) {
4452 bool ok = false;
4453 if (data[0] < TINYEXR_COMPRESSIONTYPE_PIZ) {
4454 ok = true;
4455 }
4456
4457 if (data[0] == TINYEXR_COMPRESSIONTYPE_PIZ) {
4458#if TINYEXR_USE_PIZ
4459 ok = true;
4460#else
4461 if (err) {
4462 (*err) = "PIZ compression is not supported.";
4463 }
4465#endif
4466 }
4467
4468 if (data[0] == TINYEXR_COMPRESSIONTYPE_ZFP) {
4469#if TINYEXR_USE_ZFP
4470 ok = true;
4471#else
4472 if (err) {
4473 (*err) = "ZFP compression is not supported.";
4474 }
4476#endif
4477 }
4478
4479 if (!ok) {
4480 if (err) {
4481 (*err) = "Unknown compression type.";
4482 }
4484 }
4485
4486 info->compression_type = static_cast<int>(data[0]);
4487 has_compression = true;
4488
4489 } else if (attr_name.compare("channels") == 0) {
4490 // name: zero-terminated string, from 1 to 255 bytes long
4491 // pixel type: int, possible values are: UINT = 0 HALF = 1 FLOAT = 2
4492 // pLinear: unsigned char, possible values are 0 and 1
4493 // reserved: three chars, should be zero
4494 // xSampling: int
4495 // ySampling: int
4496
4497 if (!ReadChannelInfo(info->channels, data)) {
4498 if (err) {
4499 (*err) += "Failed to parse channel info.\n";
4500 }
4502 }
4503
4504 if (info->channels.size() < 1) {
4505 if (err) {
4506 (*err) += "# of channels is zero.\n";
4507 }
4509 }
4510
4511 has_channels = true;
4512
4513 } else if (attr_name.compare("dataWindow") == 0) {
4514 if (data.size() >= 16) {
4515 memcpy(&info->data_window.min_x, &data.at(0), sizeof(int));
4516 memcpy(&info->data_window.min_y, &data.at(4), sizeof(int));
4517 memcpy(&info->data_window.max_x, &data.at(8), sizeof(int));
4518 memcpy(&info->data_window.max_y, &data.at(12), sizeof(int));
4519 tinyexr::swap4(&info->data_window.min_x);
4520 tinyexr::swap4(&info->data_window.min_y);
4521 tinyexr::swap4(&info->data_window.max_x);
4522 tinyexr::swap4(&info->data_window.max_y);
4523 has_data_window = true;
4524 }
4525 } else if (attr_name.compare("displayWindow") == 0) {
4526 if (data.size() >= 16) {
4527 memcpy(&info->display_window.min_x, &data.at(0), sizeof(int));
4528 memcpy(&info->display_window.min_y, &data.at(4), sizeof(int));
4529 memcpy(&info->display_window.max_x, &data.at(8), sizeof(int));
4530 memcpy(&info->display_window.max_y, &data.at(12), sizeof(int));
4531 tinyexr::swap4(&info->display_window.min_x);
4532 tinyexr::swap4(&info->display_window.min_y);
4533 tinyexr::swap4(&info->display_window.max_x);
4534 tinyexr::swap4(&info->display_window.max_y);
4535
4536 has_display_window = true;
4537 }
4538 } else if (attr_name.compare("lineOrder") == 0) {
4539 if (data.size() >= 1) {
4540 info->line_order = static_cast<int>(data[0]);
4541 has_line_order = true;
4542 }
4543 } else if (attr_name.compare("pixelAspectRatio") == 0) {
4544 if (data.size() >= sizeof(float)) {
4545 memcpy(&info->pixel_aspect_ratio, &data.at(0), sizeof(float));
4546 tinyexr::swap4(&info->pixel_aspect_ratio);
4547 has_pixel_aspect_ratio = true;
4548 }
4549 } else if (attr_name.compare("screenWindowCenter") == 0) {
4550 if (data.size() >= 8) {
4551 memcpy(&info->screen_window_center[0], &data.at(0), sizeof(float));
4552 memcpy(&info->screen_window_center[1], &data.at(4), sizeof(float));
4553 tinyexr::swap4(&info->screen_window_center[0]);
4554 tinyexr::swap4(&info->screen_window_center[1]);
4555 has_screen_window_center = true;
4556 }
4557 } else if (attr_name.compare("screenWindowWidth") == 0) {
4558 if (data.size() >= sizeof(float)) {
4559 memcpy(&info->screen_window_width, &data.at(0), sizeof(float));
4560 tinyexr::swap4(&info->screen_window_width);
4561
4562 has_screen_window_width = true;
4563 }
4564 } else if (attr_name.compare("chunkCount") == 0) {
4565 if (data.size() >= sizeof(int)) {
4566 memcpy(&info->chunk_count, &data.at(0), sizeof(int));
4567 tinyexr::swap4(&info->chunk_count);
4568 }
4569 } else if (attr_name.compare("name") == 0) {
4570 if (!data.empty() && data[0]) {
4571 data.push_back(0);
4572 size_t len = strlen(reinterpret_cast<const char*>(&data[0]));
4573 info->name.resize(len);
4574 info->name.assign(reinterpret_cast<const char*>(&data[0]), len);
4575 has_name = true;
4576 }
4577 } else if (attr_name.compare("type") == 0) {
4578 if (!data.empty() && data[0]) {
4579 data.push_back(0);
4580 size_t len = strlen(reinterpret_cast<const char*>(&data[0]));
4581 info->type.resize(len);
4582 info->type.assign(reinterpret_cast<const char*>(&data[0]), len);
4583 has_type = true;
4584 }
4585 } else {
4586 // Custom attribute(up to TINYEXR_MAX_CUSTOM_ATTRIBUTES)
4587 if (info->attributes.size() < TINYEXR_MAX_CUSTOM_ATTRIBUTES) {
4588 EXRAttribute attrib;
4589#ifdef _MSC_VER
4590 strncpy_s(attrib.name, attr_name.c_str(), 255);
4591 strncpy_s(attrib.type, attr_type.c_str(), 255);
4592#else
4593 strncpy(attrib.name, attr_name.c_str(), 255);
4594 strncpy(attrib.type, attr_type.c_str(), 255);
4595#endif
4596 attrib.name[255] = '\0';
4597 attrib.type[255] = '\0';
4598 // std::cout << "i = " << info->attributes.size() << ", dsize = " << data.size() << "\n";
4599 attrib.size = static_cast<int>(data.size());
4600 attrib.value = static_cast<unsigned char*>(malloc(data.size()));
4601 memcpy(reinterpret_cast<char*>(attrib.value), &data.at(0),
4602 data.size());
4603 info->attributes.push_back(attrib);
4604 }
4605 }
4606 }
4607
4608 // Check if required attributes exist
4609 {
4610 std::stringstream ss_err;
4611
4612 if (!has_compression) {
4613 ss_err << "\"compression\" attribute not found in the header."
4614 << std::endl;
4615 }
4616
4617 if (!has_channels) {
4618 ss_err << "\"channels\" attribute not found in the header." << std::endl;
4619 }
4620
4621 if (!has_line_order) {
4622 ss_err << "\"lineOrder\" attribute not found in the header." << std::endl;
4623 }
4624
4625 if (!has_display_window) {
4626 ss_err << "\"displayWindow\" attribute not found in the header."
4627 << std::endl;
4628 }
4629
4630 if (!has_data_window) {
4631 ss_err << "\"dataWindow\" attribute not found in the header or invalid."
4632 << std::endl;
4633 }
4634
4635 if (!has_pixel_aspect_ratio) {
4636 ss_err << "\"pixelAspectRatio\" attribute not found in the header."
4637 << std::endl;
4638 }
4639
4640 if (!has_screen_window_width) {
4641 ss_err << "\"screenWindowWidth\" attribute not found in the header."
4642 << std::endl;
4643 }
4644
4645 if (!has_screen_window_center) {
4646 ss_err << "\"screenWindowCenter\" attribute not found in the header."
4647 << std::endl;
4648 }
4649
4650 if (version->multipart || version->non_image) {
4651 if (!has_name) {
4652 ss_err << "\"name\" attribute not found in the header."
4653 << std::endl;
4654 }
4655 if (!has_type) {
4656 ss_err << "\"type\" attribute not found in the header."
4657 << std::endl;
4658 }
4659 }
4660
4661 if (!(ss_err.str().empty())) {
4662 if (err) {
4663 (*err) += ss_err.str();
4664 }
4665
4667 }
4668 }
4669
4670 info->header_len = static_cast<unsigned int>(orig_size - size);
4671
4672 return TINYEXR_SUCCESS;
4673}
4674
4675// C++ HeaderInfo to C EXRHeader conversion.
4676static bool ConvertHeader(EXRHeader* exr_header, const HeaderInfo& info, std::string* warn, std::string* err)
4677{
4678 exr_header->pixel_aspect_ratio = info.pixel_aspect_ratio;
4679 exr_header->screen_window_center[0] = info.screen_window_center[0];
4680 exr_header->screen_window_center[1] = info.screen_window_center[1];
4681 exr_header->screen_window_width = info.screen_window_width;
4682 exr_header->chunk_count = info.chunk_count;
4683 exr_header->display_window.min_x = info.display_window.min_x;
4684 exr_header->display_window.min_y = info.display_window.min_y;
4685 exr_header->display_window.max_x = info.display_window.max_x;
4686 exr_header->display_window.max_y = info.display_window.max_y;
4687 exr_header->data_window.min_x = info.data_window.min_x;
4688 exr_header->data_window.min_y = info.data_window.min_y;
4689 exr_header->data_window.max_x = info.data_window.max_x;
4690 exr_header->data_window.max_y = info.data_window.max_y;
4691 exr_header->line_order = info.line_order;
4692 exr_header->compression_type = info.compression_type;
4693 exr_header->tiled = info.tiled;
4694 exr_header->tile_size_x = info.tile_size_x;
4695 exr_header->tile_size_y = info.tile_size_y;
4696 exr_header->tile_level_mode = info.tile_level_mode;
4697 exr_header->tile_rounding_mode = info.tile_rounding_mode;
4698
4699 EXRSetNameAttr(exr_header, info.name.c_str());
4700
4701 if (!info.type.empty()) {
4702 bool valid = true;
4703 if (info.type == "scanlineimage") {
4704 if (exr_header->tiled) {
4705 if (err) {
4706 (*err) += "(ConvertHeader) tiled bit must be off for `scanlineimage` type.\n";
4707 }
4708 valid = false;
4709 }
4710 } else if (info.type == "tiledimage") {
4711 if (!exr_header->tiled) {
4712 if (err) {
4713 (*err) += "(ConvertHeader) tiled bit must be on for `tiledimage` type.\n";
4714 }
4715 valid = false;
4716 }
4717 } else if (info.type == "deeptile") {
4718 exr_header->non_image = 1;
4719 if (!exr_header->tiled) {
4720 if (err) {
4721 (*err) += "(ConvertHeader) tiled bit must be on for `deeptile` type.\n";
4722 }
4723 valid = false;
4724 }
4725 } else if (info.type == "deepscanline") {
4726 exr_header->non_image = 1;
4727 if (exr_header->tiled) {
4728 if (err) {
4729 (*err) += "(ConvertHeader) tiled bit must be off for `deepscanline` type.\n";
4730 }
4731 // valid = false;
4732 }
4733 } else {
4734 if (warn) {
4735 std::stringstream ss;
4736 ss << "(ConvertHeader) Unsupported or unknown info.type: " << info.type << "\n";
4737 (*warn) += ss.str();
4738 }
4739 }
4740
4741 if (!valid) {
4742 return false;
4743 }
4744 }
4745
4746 exr_header->num_channels = static_cast<int>(info.channels.size());
4747
4748 exr_header->channels = static_cast<EXRChannelInfo*>(malloc(
4749 sizeof(EXRChannelInfo) * static_cast<size_t>(exr_header->num_channels)));
4750 for (size_t c = 0; c < static_cast<size_t>(exr_header->num_channels); c++) {
4751#ifdef _MSC_VER
4752 strncpy_s(exr_header->channels[c].name, info.channels[c].name.c_str(), 255);
4753#else
4754 strncpy(exr_header->channels[c].name, info.channels[c].name.c_str(), 255);
4755#endif
4756 // manually add '\0' for safety.
4757 exr_header->channels[c].name[255] = '\0';
4758
4759 exr_header->channels[c].pixel_type = info.channels[c].pixel_type;
4760 exr_header->channels[c].p_linear = info.channels[c].p_linear;
4761 exr_header->channels[c].x_sampling = info.channels[c].x_sampling;
4762 exr_header->channels[c].y_sampling = info.channels[c].y_sampling;
4763 }
4764
4765 exr_header->pixel_types = static_cast<int*>(
4766 malloc(sizeof(int) * static_cast<size_t>(exr_header->num_channels)));
4767 for (size_t c = 0; c < static_cast<size_t>(exr_header->num_channels); c++) {
4768 exr_header->pixel_types[c] = info.channels[c].pixel_type;
4769 }
4770
4771 // Initially fill with values of `pixel_types`
4772 exr_header->requested_pixel_types = static_cast<int*>(
4773 malloc(sizeof(int) * static_cast<size_t>(exr_header->num_channels)));
4774 for (size_t c = 0; c < static_cast<size_t>(exr_header->num_channels); c++) {
4775 exr_header->requested_pixel_types[c] = info.channels[c].pixel_type;
4776 }
4777
4778 exr_header->num_custom_attributes = static_cast<int>(info.attributes.size());
4779
4780 if (exr_header->num_custom_attributes > 0) {
4781 // TODO(syoyo): Report warning when # of attributes exceeds
4782 // `TINYEXR_MAX_CUSTOM_ATTRIBUTES`
4785 }
4786
4787 exr_header->custom_attributes = static_cast<EXRAttribute*>(malloc(
4788 sizeof(EXRAttribute) * size_t(exr_header->num_custom_attributes)));
4789
4790 for (size_t i = 0; i < size_t(exr_header->num_custom_attributes); i++) {
4791 memcpy(exr_header->custom_attributes[i].name, info.attributes[i].name,
4792 256);
4793 memcpy(exr_header->custom_attributes[i].type, info.attributes[i].type,
4794 256);
4795 exr_header->custom_attributes[i].size = info.attributes[i].size;
4796 // Just copy pointer
4797 exr_header->custom_attributes[i].value = info.attributes[i].value;
4798 }
4799
4800 } else {
4801 exr_header->custom_attributes = NULL;
4802 }
4803
4804 exr_header->header_len = info.header_len;
4805
4806 return true;
4807}
4808
4809struct OffsetData {
4810 OffsetData()
4811 : num_x_levels(0)
4812 , num_y_levels(0)
4813 {
4814 }
4815 std::vector<std::vector<std::vector<tinyexr::tinyexr_uint64>>> offsets;
4816 int num_x_levels;
4817 int num_y_levels;
4818};
4819
4820// -1 = error
4821static int LevelIndex(int lx, int ly, int tile_level_mode, int num_x_levels)
4822{
4823 switch (tile_level_mode) {
4825 return 0;
4826
4828 return lx;
4829
4831 return lx + ly * num_x_levels;
4832
4833 default:
4834 return -1;
4835 }
4836 return 0;
4837}
4838
4839static int LevelSize(int toplevel_size, int level, int tile_rounding_mode)
4840{
4841 if (level < 0) {
4842 return -1;
4843 }
4844
4845 int b = static_cast<int>(1u << static_cast<unsigned int>(level));
4846 int level_size = toplevel_size / b;
4847
4848 if (tile_rounding_mode == TINYEXR_TILE_ROUND_UP && level_size * b < toplevel_size)
4849 level_size += 1;
4850
4851 return std::max(level_size, 1);
4852}
4853
4854static int DecodeTiledLevel(EXRImage* exr_image, const EXRHeader* exr_header,
4855 const OffsetData& offset_data,
4856 const std::vector<size_t>& channel_offset_list,
4857 int pixel_data_size,
4858 const unsigned char* head, const size_t size,
4859 std::string* err)
4860{
4861 int num_channels = exr_header->num_channels;
4862
4863 int level_index = LevelIndex(exr_image->level_x, exr_image->level_y, exr_header->tile_level_mode, offset_data.num_x_levels);
4864 int num_y_tiles = int(offset_data.offsets[size_t(level_index)].size());
4865 if (num_y_tiles < 1) {
4867 }
4868 int num_x_tiles = int(offset_data.offsets[size_t(level_index)][0].size());
4869 if (num_x_tiles < 1) {
4871 }
4872 int num_tiles = num_x_tiles * num_y_tiles;
4873
4874 int err_code = TINYEXR_SUCCESS;
4875
4876 enum {
4877 EF_SUCCESS = 0,
4878 EF_INVALID_DATA = 1,
4879 EF_INSUFFICIENT_DATA = 2,
4880 EF_FAILED_TO_DECODE = 4
4881 };
4882#if TINYEXR_HAS_CXX11 && (TINYEXR_USE_THREAD > 0)
4883 std::atomic<unsigned> error_flag(EF_SUCCESS);
4884#else
4885 unsigned error_flag(EF_SUCCESS);
4886#endif
4887
4888 // Although the spec says : "...the data window is subdivided into an array of smaller rectangles...",
4889 // the IlmImf library allows the dimensions of the tile to be larger (or equal) than the dimensions of the data window.
4890#if 0
4891 if ((exr_header->tile_size_x > exr_image->width || exr_header->tile_size_y > exr_image->height) &&
4892 exr_image->level_x == 0 && exr_image->level_y == 0) {
4893 if (err) {
4894 (*err) += "Failed to decode tile data.\n";
4895 }
4896 err_code = TINYEXR_ERROR_INVALID_DATA;
4897 }
4898#endif
4899 exr_image->tiles = static_cast<EXRTile*>(
4900 calloc(static_cast<size_t>(num_tiles), sizeof(EXRTile)));
4901
4902#if TINYEXR_HAS_CXX11 && (TINYEXR_USE_THREAD > 0)
4903 std::vector<std::thread> workers;
4904 std::atomic<int> tile_count(0);
4905
4906 int num_threads = std::max(1, int(std::thread::hardware_concurrency()));
4907 if (num_threads > int(num_tiles)) {
4908 num_threads = int(num_tiles);
4909 }
4910
4911 for (int t = 0; t < num_threads; t++) {
4912 workers.emplace_back(std::thread([&]() {
4913 int tile_idx = 0;
4914 while ((tile_idx = tile_count++) < num_tiles) {
4915
4916#else
4917#if TINYEXR_USE_OPENMP
4918#pragma omp parallel for
4919#endif
4920 for (int tile_idx = 0; tile_idx < num_tiles; tile_idx++) {
4921#endif
4922 // Allocate memory for each tile.
4923 bool alloc_success = false;
4924 exr_image->tiles[tile_idx].images = tinyexr::AllocateImage(
4925 num_channels, exr_header->channels,
4926 exr_header->requested_pixel_types, exr_header->tile_size_x,
4927 exr_header->tile_size_y, &alloc_success);
4928
4929 if (!alloc_success) {
4930 error_flag |= EF_INVALID_DATA;
4931 continue;
4932 }
4933
4934 int x_tile = tile_idx % num_x_tiles;
4935 int y_tile = tile_idx / num_x_tiles;
4936 // 16 byte: tile coordinates
4937 // 4 byte : data size
4938 // ~ : data(uncompressed or compressed)
4939 tinyexr::tinyexr_uint64 offset = offset_data.offsets[size_t(level_index)][size_t(y_tile)][size_t(x_tile)];
4940 if (offset + sizeof(int) * 5 > size) {
4941 // Insufficient data size.
4942 error_flag |= EF_INSUFFICIENT_DATA;
4943 continue;
4944 }
4945
4946 size_t data_size = size_t(size - (offset + sizeof(int) * 5));
4947 const unsigned char* data_ptr = reinterpret_cast<const unsigned char*>(head + offset);
4948
4949 int tile_coordinates[4];
4950 memcpy(tile_coordinates, data_ptr, sizeof(int) * 4);
4951 tinyexr::swap4(&tile_coordinates[0]);
4952 tinyexr::swap4(&tile_coordinates[1]);
4953 tinyexr::swap4(&tile_coordinates[2]);
4954 tinyexr::swap4(&tile_coordinates[3]);
4955
4956 if (tile_coordinates[2] != exr_image->level_x) {
4957 // Invalid data.
4958 error_flag |= EF_INVALID_DATA;
4959 continue;
4960 }
4961 if (tile_coordinates[3] != exr_image->level_y) {
4962 // Invalid data.
4963 error_flag |= EF_INVALID_DATA;
4964 continue;
4965 }
4966
4967 int data_len;
4968 memcpy(&data_len, data_ptr + 16,
4969 sizeof(int)); // 16 = sizeof(tile_coordinates)
4970 tinyexr::swap4(&data_len);
4971
4972 if (data_len < 2 || size_t(data_len) > data_size) {
4973 // Insufficient data size.
4974 error_flag |= EF_INSUFFICIENT_DATA;
4975 continue;
4976 }
4977
4978 // Move to data addr: 20 = 16 + 4;
4979 data_ptr += 20;
4980 bool ret = tinyexr::DecodeTiledPixelData(
4981 exr_image->tiles[tile_idx].images,
4982 &(exr_image->tiles[tile_idx].width),
4983 &(exr_image->tiles[tile_idx].height),
4984 exr_header->requested_pixel_types, data_ptr,
4985 static_cast<size_t>(data_len), exr_header->compression_type,
4986 exr_header->line_order,
4987 exr_image->width, exr_image->height,
4988 tile_coordinates[0], tile_coordinates[1], exr_header->tile_size_x,
4989 exr_header->tile_size_y, static_cast<size_t>(pixel_data_size),
4990 static_cast<size_t>(exr_header->num_custom_attributes),
4991 exr_header->custom_attributes,
4992 static_cast<size_t>(exr_header->num_channels),
4993 exr_header->channels, channel_offset_list);
4994
4995 if (!ret) {
4996 // Failed to decode tile data.
4997 error_flag |= EF_FAILED_TO_DECODE;
4998 }
4999
5000 exr_image->tiles[tile_idx].offset_x = tile_coordinates[0];
5001 exr_image->tiles[tile_idx].offset_y = tile_coordinates[1];
5002 exr_image->tiles[tile_idx].level_x = tile_coordinates[2];
5003 exr_image->tiles[tile_idx].level_y = tile_coordinates[3];
5004
5005#if TINYEXR_HAS_CXX11 && (TINYEXR_USE_THREAD > 0)
5006 }
5007 }));
5008 } // num_thread loop
5009
5010 for (auto& t : workers) {
5011 t.join();
5012 }
5013
5014#else
5015 } // parallel for
5016#endif
5017
5018 // Even in the event of an error, the reserved memory may be freed.
5019 exr_image->num_channels = num_channels;
5020 exr_image->num_tiles = static_cast<int>(num_tiles);
5021
5022 if (error_flag)
5023 err_code = TINYEXR_ERROR_INVALID_DATA;
5024 if (err) {
5025 if (error_flag & EF_INSUFFICIENT_DATA) {
5026 (*err) += "Insufficient data length.\n";
5027 }
5028 if (error_flag & EF_FAILED_TO_DECODE) {
5029 (*err) += "Failed to decode tile data.\n";
5030 }
5031 }
5032 return err_code;
5033}
5034
5035static int DecodeChunk(EXRImage* exr_image, const EXRHeader* exr_header,
5036 const OffsetData& offset_data,
5037 const unsigned char* head, const size_t size,
5038 std::string* err)
5039{
5040 int num_channels = exr_header->num_channels;
5041
5042 int num_scanline_blocks = 1;
5043 if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) {
5044 num_scanline_blocks = 16;
5045 } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) {
5046 num_scanline_blocks = 32;
5047 } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) {
5048 num_scanline_blocks = 16;
5049
5050#if TINYEXR_USE_ZFP
5051 tinyexr::ZFPCompressionParam zfp_compression_param;
5052 if (!FindZFPCompressionParam(&zfp_compression_param,
5053 exr_header->custom_attributes,
5054 int(exr_header->num_custom_attributes), err)) {
5056 }
5057#endif
5058 }
5059
5060 if (exr_header->data_window.max_x < exr_header->data_window.min_x || exr_header->data_window.max_y < exr_header->data_window.min_y) {
5061 if (err) {
5062 (*err) += "Invalid data window.\n";
5063 }
5065 }
5066
5067 tinyexr_int64 data_width = static_cast<tinyexr_int64>(exr_header->data_window.max_x) - static_cast<tinyexr_int64>(exr_header->data_window.min_x) + static_cast<tinyexr_int64>(1);
5068 tinyexr_int64 data_height = static_cast<tinyexr_int64>(exr_header->data_window.max_y) - static_cast<tinyexr_int64>(exr_header->data_window.min_y) + static_cast<tinyexr_int64>(1);
5069
5070 if (data_width <= 0) {
5071 if (err) {
5072 (*err) += "Invalid data window width.\n";
5073 }
5075 }
5076
5077 if (data_height <= 0) {
5078 if (err) {
5079 (*err) += "Invalid data window height.\n";
5080 }
5082 }
5083
5084 // Do not allow too large data_width and data_height. header invalid?
5085 {
5086 if ((data_width > TINYEXR_DIMENSION_THRESHOLD) || (data_height > TINYEXR_DIMENSION_THRESHOLD)) {
5087 if (err) {
5088 std::stringstream ss;
5089 ss << "data_with or data_height too large. data_width: " << data_width
5090 << ", "
5091 << "data_height = " << data_height << std::endl;
5092 (*err) += ss.str();
5093 }
5095 }
5096 if (exr_header->tiled) {
5097 if ((exr_header->tile_size_x > TINYEXR_DIMENSION_THRESHOLD) || (exr_header->tile_size_y > TINYEXR_DIMENSION_THRESHOLD)) {
5098 if (err) {
5099 std::stringstream ss;
5100 ss << "tile with or tile height too large. tile width: " << exr_header->tile_size_x
5101 << ", "
5102 << "tile height = " << exr_header->tile_size_y << std::endl;
5103 (*err) += ss.str();
5104 }
5106 }
5107 }
5108 }
5109
5110 const std::vector<tinyexr::tinyexr_uint64>& offsets = offset_data.offsets[0][0];
5111 size_t num_blocks = offsets.size();
5112
5113 std::vector<size_t> channel_offset_list;
5114 int pixel_data_size = 0;
5115 size_t channel_offset = 0;
5116 if (!tinyexr::ComputeChannelLayout(&channel_offset_list, &pixel_data_size,
5117 &channel_offset, num_channels,
5118 exr_header->channels)) {
5119 if (err) {
5120 (*err) += "Failed to compute channel layout.\n";
5121 }
5123 }
5124
5125#if TINYEXR_HAS_CXX11 && (TINYEXR_USE_THREAD > 0)
5126 std::atomic<bool> invalid_data(false);
5127#else
5128 bool invalid_data(false);
5129#endif
5130
5131 if (exr_header->tiled) {
5132 // value check
5133 if (exr_header->tile_size_x < 0) {
5134 if (err) {
5135 std::stringstream ss;
5136 ss << "Invalid tile size x : " << exr_header->tile_size_x << "\n";
5137 (*err) += ss.str();
5138 }
5140 }
5141
5142 if (exr_header->tile_size_y < 0) {
5143 if (err) {
5144 std::stringstream ss;
5145 ss << "Invalid tile size y : " << exr_header->tile_size_y << "\n";
5146 (*err) += ss.str();
5147 }
5149 }
5150 if (exr_header->tile_level_mode != TINYEXR_TILE_RIPMAP_LEVELS) {
5151 EXRImage* level_image = NULL;
5152 for (int level = 0; level < offset_data.num_x_levels; ++level) {
5153 if (!level_image) {
5154 level_image = exr_image;
5155 } else {
5156 level_image->next_level = new EXRImage;
5157 InitEXRImage(level_image->next_level);
5158 level_image = level_image->next_level;
5159 }
5160 level_image->width = LevelSize(exr_header->data_window.max_x - exr_header->data_window.min_x + 1, level, exr_header->tile_rounding_mode);
5161 if (level_image->width < 1) {
5163 }
5164
5165 level_image->height = LevelSize(exr_header->data_window.max_y - exr_header->data_window.min_y + 1, level, exr_header->tile_rounding_mode);
5166
5167 if (level_image->height < 1) {
5169 }
5170
5171 level_image->level_x = level;
5172 level_image->level_y = level;
5173
5174 int ret = DecodeTiledLevel(level_image, exr_header,
5175 offset_data,
5176 channel_offset_list,
5177 pixel_data_size,
5178 head, size,
5179 err);
5180 if (ret != TINYEXR_SUCCESS)
5181 return ret;
5182 }
5183 } else {
5184 EXRImage* level_image = NULL;
5185 for (int level_y = 0; level_y < offset_data.num_y_levels; ++level_y)
5186 for (int level_x = 0; level_x < offset_data.num_x_levels; ++level_x) {
5187 if (!level_image) {
5188 level_image = exr_image;
5189 } else {
5190 level_image->next_level = new EXRImage;
5191 InitEXRImage(level_image->next_level);
5192 level_image = level_image->next_level;
5193 }
5194
5195 level_image->width = LevelSize(exr_header->data_window.max_x - exr_header->data_window.min_x + 1, level_x, exr_header->tile_rounding_mode);
5196 if (level_image->width < 1) {
5198 }
5199
5200 level_image->height = LevelSize(exr_header->data_window.max_y - exr_header->data_window.min_y + 1, level_y, exr_header->tile_rounding_mode);
5201 if (level_image->height < 1) {
5203 }
5204
5205 level_image->level_x = level_x;
5206 level_image->level_y = level_y;
5207
5208 int ret = DecodeTiledLevel(level_image, exr_header,
5209 offset_data,
5210 channel_offset_list,
5211 pixel_data_size,
5212 head, size,
5213 err);
5214 if (ret != TINYEXR_SUCCESS)
5215 return ret;
5216 }
5217 }
5218 } else { // scanline format
5219 // Don't allow too large image(256GB * pixel_data_size or more). Workaround
5220 // for #104.
5221 size_t total_data_len = size_t(data_width) * size_t(data_height) * size_t(num_channels);
5222 const bool total_data_len_overflown = sizeof(void*) == 8 ? (total_data_len >= 0x4000000000) : false;
5223 if ((total_data_len == 0) || total_data_len_overflown) {
5224 if (err) {
5225 std::stringstream ss;
5226 ss << "Image data size is zero or too large: width = " << data_width
5227 << ", height = " << data_height << ", channels = " << num_channels
5228 << std::endl;
5229 (*err) += ss.str();
5230 }
5232 }
5233
5234 bool alloc_success = false;
5235 exr_image->images = tinyexr::AllocateImage(
5236 num_channels, exr_header->channels, exr_header->requested_pixel_types,
5237 int(data_width), int(data_height), &alloc_success);
5238
5239 if (!alloc_success) {
5240 if (err) {
5241 std::stringstream ss;
5242 ss << "Failed to allocate memory for Images. Maybe EXR header is corrupted or Image data size is too large: width = " << data_width
5243 << ", height = " << data_height << ", channels = " << num_channels
5244 << std::endl;
5245 (*err) += ss.str();
5246 }
5248 }
5249
5250#if TINYEXR_HAS_CXX11 && (TINYEXR_USE_THREAD > 0)
5251 std::vector<std::thread> workers;
5252 std::atomic<int> y_count(0);
5253
5254 int num_threads = std::max(1, int(std::thread::hardware_concurrency()));
5255 if (num_threads > int(num_blocks)) {
5256 num_threads = int(num_blocks);
5257 }
5258
5259 for (int t = 0; t < num_threads; t++) {
5260 workers.emplace_back(std::thread([&]() {
5261 int y = 0;
5262 while ((y = y_count++) < int(num_blocks)) {
5263
5264#else
5265
5266#if TINYEXR_USE_OPENMP
5267#pragma omp parallel for
5268#endif
5269 for (int y = 0; y < static_cast<int>(num_blocks); y++) {
5270
5271#endif
5272 size_t y_idx = static_cast<size_t>(y);
5273
5274 if (offsets[y_idx] + sizeof(int) * 2 > size) {
5275 invalid_data = true;
5276 } else {
5277 // 4 byte: scan line
5278 // 4 byte: data size
5279 // ~ : pixel data(uncompressed or compressed)
5280 size_t data_size = size_t(size - (offsets[y_idx] + sizeof(int) * 2));
5281 const unsigned char* data_ptr = reinterpret_cast<const unsigned char*>(head + offsets[y_idx]);
5282
5283 int line_no;
5284 memcpy(&line_no, data_ptr, sizeof(int));
5285 int data_len;
5286 memcpy(&data_len, data_ptr + 4, sizeof(int));
5287 tinyexr::swap4(&line_no);
5288 tinyexr::swap4(&data_len);
5289
5290 if (size_t(data_len) > data_size) {
5291 invalid_data = true;
5292
5293 } else if ((line_no > (2 << 20)) || (line_no < -(2 << 20))) {
5294 // Too large value. Assume this is invalid
5295 // 2**20 = 1048576 = heuristic value.
5296 invalid_data = true;
5297 } else if (data_len == 0) {
5298 // TODO(syoyo): May be ok to raise the threshold for example
5299 // `data_len < 4`
5300 invalid_data = true;
5301 } else {
5302 // line_no may be negative.
5303 int end_line_no = (std::min)(line_no + num_scanline_blocks,
5304 (exr_header->data_window.max_y + 1));
5305
5306 int num_lines = end_line_no - line_no;
5307
5308 if (num_lines <= 0) {
5309 invalid_data = true;
5310 } else {
5311 // Move to data addr: 8 = 4 + 4;
5312 data_ptr += 8;
5313
5314 // Adjust line_no with data_window.bmin.y
5315
5316 // overflow check
5317 tinyexr_int64 lno = static_cast<tinyexr_int64>(line_no) - static_cast<tinyexr_int64>(exr_header->data_window.min_y);
5318 if (lno > std::numeric_limits<int>::max()) {
5319 line_no = -1; // invalid
5320 } else if (lno < -std::numeric_limits<int>::max()) {
5321 line_no = -1; // invalid
5322 } else {
5323 line_no -= exr_header->data_window.min_y;
5324 }
5325
5326 if (line_no < 0) {
5327 invalid_data = true;
5328 } else {
5329 if (!tinyexr::DecodePixelData(
5330 exr_image->images, exr_header->requested_pixel_types,
5331 data_ptr, static_cast<size_t>(data_len),
5332 exr_header->compression_type, exr_header->line_order,
5333 int(data_width), int(data_height), int(data_width), y, line_no,
5334 num_lines, static_cast<size_t>(pixel_data_size),
5335 static_cast<size_t>(
5336 exr_header->num_custom_attributes),
5337 exr_header->custom_attributes,
5338 static_cast<size_t>(exr_header->num_channels),
5339 exr_header->channels, channel_offset_list)) {
5340 invalid_data = true;
5341 }
5342 }
5343 }
5344 }
5345 }
5346
5347#if TINYEXR_HAS_CXX11 && (TINYEXR_USE_THREAD > 0)
5348 }
5349 }));
5350 }
5351
5352 for (auto& t : workers) {
5353 t.join();
5354 }
5355#else
5356 } // omp parallel
5357#endif
5358 }
5359
5360 if (invalid_data) {
5361 if (err) {
5362 (*err) += "Invalid/Corrupted data found when decoding pixels.\n";
5363 }
5364
5365 // free alloced image.
5366 for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) {
5367 if (exr_image->images[c]) {
5368 free(exr_image->images[c]);
5369 exr_image->images[c] = NULL;
5370 }
5371 }
5373 }
5374
5375 // Overwrite `pixel_type` with `requested_pixel_type`.
5376 {
5377 for (int c = 0; c < exr_header->num_channels; c++) {
5378 exr_header->pixel_types[c] = exr_header->requested_pixel_types[c];
5379 }
5380 }
5381
5382 {
5383 exr_image->num_channels = num_channels;
5384
5385 exr_image->width = int(data_width);
5386 exr_image->height = int(data_height);
5387 }
5388
5389 return TINYEXR_SUCCESS;
5390}
5391
5392static bool ReconstructLineOffsets(
5393 std::vector<tinyexr::tinyexr_uint64>* offsets, size_t n,
5394 const unsigned char* head, const unsigned char* marker, const size_t size)
5395{
5396 if (head >= marker) {
5397 return false;
5398 }
5399 if (offsets->size() != n) {
5400 return false;
5401 }
5402
5403 for (size_t i = 0; i < n; i++) {
5404 size_t offset = static_cast<size_t>(marker - head);
5405 // Offset should not exceed whole EXR file/data size.
5406 if ((offset + sizeof(tinyexr::tinyexr_uint64)) >= size) {
5407 return false;
5408 }
5409
5410 int y;
5411 unsigned int data_len;
5412
5413 memcpy(&y, marker, sizeof(int));
5414 memcpy(&data_len, marker + 4, sizeof(unsigned int));
5415
5416 if (data_len >= size) {
5417 return false;
5418 }
5419
5420 tinyexr::swap4(&y);
5421 tinyexr::swap4(&data_len);
5422
5423 (*offsets)[i] = offset;
5424
5425 marker += data_len + 8; // 8 = 4 bytes(y) + 4 bytes(data_len)
5426 }
5427
5428 return true;
5429}
5430
5431static int FloorLog2(unsigned x)
5432{
5433 //
5434 // For x > 0, floorLog2(y) returns floor(log(x)/log(2)).
5435 //
5436 int y = 0;
5437 while (x > 1) {
5438 y += 1;
5439 x >>= 1u;
5440 }
5441 return y;
5442}
5443
5444static int CeilLog2(unsigned x)
5445{
5446 //
5447 // For x > 0, ceilLog2(y) returns ceil(log(x)/log(2)).
5448 //
5449 int y = 0;
5450 int r = 0;
5451 while (x > 1) {
5452 if (x & 1)
5453 r = 1;
5454
5455 y += 1;
5456 x >>= 1u;
5457 }
5458 return y + r;
5459}
5460
5461static int RoundLog2(int x, int tile_rounding_mode)
5462{
5463 return (tile_rounding_mode == TINYEXR_TILE_ROUND_DOWN) ? FloorLog2(static_cast<unsigned>(x)) : CeilLog2(static_cast<unsigned>(x));
5464}
5465
5466static int CalculateNumXLevels(const EXRHeader* exr_header)
5467{
5468 int min_x = exr_header->data_window.min_x;
5469 int max_x = exr_header->data_window.max_x;
5470 int min_y = exr_header->data_window.min_y;
5471 int max_y = exr_header->data_window.max_y;
5472
5473 int num = 0;
5474 switch (exr_header->tile_level_mode) {
5476
5477 num = 1;
5478 break;
5479
5481
5482 {
5483 int w = max_x - min_x + 1;
5484 int h = max_y - min_y + 1;
5485 num = RoundLog2(std::max(w, h), exr_header->tile_rounding_mode) + 1;
5486 } break;
5487
5489
5490 {
5491 int w = max_x - min_x + 1;
5492 num = RoundLog2(w, exr_header->tile_rounding_mode) + 1;
5493 } break;
5494
5495 default:
5496
5497 return -1;
5498 }
5499
5500 return num;
5501}
5502
5503static int CalculateNumYLevels(const EXRHeader* exr_header)
5504{
5505 int min_x = exr_header->data_window.min_x;
5506 int max_x = exr_header->data_window.max_x;
5507 int min_y = exr_header->data_window.min_y;
5508 int max_y = exr_header->data_window.max_y;
5509 int num = 0;
5510
5511 switch (exr_header->tile_level_mode) {
5513
5514 num = 1;
5515 break;
5516
5518
5519 {
5520 int w = max_x - min_x + 1;
5521 int h = max_y - min_y + 1;
5522 num = RoundLog2(std::max(w, h), exr_header->tile_rounding_mode) + 1;
5523 } break;
5524
5526
5527 {
5528 int h = max_y - min_y + 1;
5529 num = RoundLog2(h, exr_header->tile_rounding_mode) + 1;
5530 } break;
5531
5532 default:
5533
5534 return -1;
5535 }
5536
5537 return num;
5538}
5539
5540static bool CalculateNumTiles(std::vector<int>& numTiles,
5541 int toplevel_size,
5542 int size,
5543 int tile_rounding_mode)
5544{
5545 for (unsigned i = 0; i < numTiles.size(); i++) {
5546 int l = LevelSize(toplevel_size, int(i), tile_rounding_mode);
5547 if (l < 0) {
5548 return false;
5549 }
5550 TINYEXR_CHECK_AND_RETURN_C(l <= std::numeric_limits<int>::max() - size + 1, false);
5551
5552 numTiles[i] = (l + size - 1) / size;
5553 }
5554 return true;
5555}
5556
5557static bool PrecalculateTileInfo(std::vector<int>& num_x_tiles,
5558 std::vector<int>& num_y_tiles,
5559 const EXRHeader* exr_header)
5560{
5561 int min_x = exr_header->data_window.min_x;
5562 int max_x = exr_header->data_window.max_x;
5563 int min_y = exr_header->data_window.min_y;
5564 int max_y = exr_header->data_window.max_y;
5565
5566 int num_x_levels = CalculateNumXLevels(exr_header);
5567
5568 if (num_x_levels < 0) {
5569 return false;
5570 }
5571
5572 int num_y_levels = CalculateNumYLevels(exr_header);
5573
5574 if (num_y_levels < 0) {
5575 return false;
5576 }
5577
5578 num_x_tiles.resize(size_t(num_x_levels));
5579 num_y_tiles.resize(size_t(num_y_levels));
5580
5581 if (!CalculateNumTiles(num_x_tiles,
5582 max_x - min_x + 1,
5583 exr_header->tile_size_x,
5584 exr_header->tile_rounding_mode)) {
5585 return false;
5586 }
5587
5588 if (!CalculateNumTiles(num_y_tiles,
5589 max_y - min_y + 1,
5590 exr_header->tile_size_y,
5591 exr_header->tile_rounding_mode)) {
5592 return false;
5593 }
5594
5595 return true;
5596}
5597
5598static void InitSingleResolutionOffsets(OffsetData& offset_data, size_t num_blocks)
5599{
5600 offset_data.offsets.resize(1);
5601 offset_data.offsets[0].resize(1);
5602 offset_data.offsets[0][0].resize(num_blocks);
5603 offset_data.num_x_levels = 1;
5604 offset_data.num_y_levels = 1;
5605}
5606
5607// Return sum of tile blocks.
5608// 0 = error
5609static int InitTileOffsets(OffsetData& offset_data,
5610 const EXRHeader* exr_header,
5611 const std::vector<int>& num_x_tiles,
5612 const std::vector<int>& num_y_tiles)
5613{
5614 int num_tile_blocks = 0;
5615 offset_data.num_x_levels = static_cast<int>(num_x_tiles.size());
5616 offset_data.num_y_levels = static_cast<int>(num_y_tiles.size());
5617 switch (exr_header->tile_level_mode) {
5620 TINYEXR_CHECK_AND_RETURN_C(offset_data.num_x_levels == offset_data.num_y_levels, 0);
5621 offset_data.offsets.resize(size_t(offset_data.num_x_levels));
5622
5623 for (unsigned int l = 0; l < offset_data.offsets.size(); ++l) {
5624 offset_data.offsets[l].resize(size_t(num_y_tiles[l]));
5625
5626 for (unsigned int dy = 0; dy < offset_data.offsets[l].size(); ++dy) {
5627 offset_data.offsets[l][dy].resize(size_t(num_x_tiles[l]));
5628 num_tile_blocks += num_x_tiles[l];
5629 }
5630 }
5631 break;
5632
5634
5635 offset_data.offsets.resize(static_cast<size_t>(offset_data.num_x_levels) * static_cast<size_t>(offset_data.num_y_levels));
5636
5637 for (int ly = 0; ly < offset_data.num_y_levels; ++ly) {
5638 for (int lx = 0; lx < offset_data.num_x_levels; ++lx) {
5639 int l = ly * offset_data.num_x_levels + lx;
5640 offset_data.offsets[size_t(l)].resize(size_t(num_y_tiles[size_t(ly)]));
5641
5642 for (size_t dy = 0; dy < offset_data.offsets[size_t(l)].size(); ++dy) {
5643 offset_data.offsets[size_t(l)][dy].resize(size_t(num_x_tiles[size_t(lx)]));
5644 num_tile_blocks += num_x_tiles[size_t(lx)];
5645 }
5646 }
5647 }
5648 break;
5649
5650 default:
5651 return 0;
5652 }
5653 return num_tile_blocks;
5654}
5655
5656static bool IsAnyOffsetsAreInvalid(const OffsetData& offset_data)
5657{
5658 for (unsigned int l = 0; l < offset_data.offsets.size(); ++l)
5659 for (unsigned int dy = 0; dy < offset_data.offsets[l].size(); ++dy)
5660 for (unsigned int dx = 0; dx < offset_data.offsets[l][dy].size(); ++dx)
5661 if (reinterpret_cast<const tinyexr::tinyexr_int64&>(offset_data.offsets[l][dy][dx]) <= 0)
5662 return true;
5663
5664 return false;
5665}
5666
5667static bool isValidTile(const EXRHeader* exr_header,
5668 const OffsetData& offset_data,
5669 int dx, int dy, int lx, int ly)
5670{
5671 if (lx < 0 || ly < 0 || dx < 0 || dy < 0)
5672 return false;
5673 int num_x_levels = offset_data.num_x_levels;
5674 int num_y_levels = offset_data.num_y_levels;
5675 switch (exr_header->tile_level_mode) {
5677
5678 if (lx == 0 && ly == 0 && offset_data.offsets.size() > 0 && offset_data.offsets[0].size() > static_cast<size_t>(dy) && offset_data.offsets[0][size_t(dy)].size() > static_cast<size_t>(dx)) {
5679 return true;
5680 }
5681
5682 break;
5683
5685
5686 if (lx < num_x_levels && ly < num_y_levels && offset_data.offsets.size() > static_cast<size_t>(lx) && offset_data.offsets[size_t(lx)].size() > static_cast<size_t>(dy) && offset_data.offsets[size_t(lx)][size_t(dy)].size() > static_cast<size_t>(dx)) {
5687 return true;
5688 }
5689
5690 break;
5691
5693 size_t idx = static_cast<size_t>(lx) + static_cast<size_t>(ly) * static_cast<size_t>(num_x_levels);
5694 if (lx < num_x_levels && ly < num_y_levels && (offset_data.offsets.size() > idx) && offset_data.offsets[idx].size() > static_cast<size_t>(dy) && offset_data.offsets[idx][size_t(dy)].size() > static_cast<size_t>(dx)) {
5695 return true;
5696 }
5697 }
5698
5699 break;
5700
5701 default:
5702
5703 return false;
5704 }
5705
5706 return false;
5707}
5708
5709static bool ReconstructTileOffsets(OffsetData& offset_data,
5710 const EXRHeader* exr_header,
5711 const unsigned char* head, const unsigned char* marker, const size_t size,
5712 bool isMultiPartFile,
5713 bool isDeep)
5714{
5715 int numXLevels = offset_data.num_x_levels;
5716 for (unsigned int l = 0; l < offset_data.offsets.size(); ++l) {
5717 for (unsigned int dy = 0; dy < offset_data.offsets[l].size(); ++dy) {
5718 for (unsigned int dx = 0; dx < offset_data.offsets[l][dy].size(); ++dx) {
5719 tinyexr::tinyexr_uint64 tileOffset = tinyexr::tinyexr_uint64(marker - head);
5720
5721 if (isMultiPartFile) {
5722 if ((marker + sizeof(int)) >= (head + size)) {
5723 return false;
5724 }
5725
5726 // int partNumber;
5727 marker += sizeof(int);
5728 }
5729
5730 if ((marker + 4 * sizeof(int)) >= (head + size)) {
5731 return false;
5732 }
5733
5734 int tileX;
5735 memcpy(&tileX, marker, sizeof(int));
5736 tinyexr::swap4(&tileX);
5737 marker += sizeof(int);
5738
5739 int tileY;
5740 memcpy(&tileY, marker, sizeof(int));
5741 tinyexr::swap4(&tileY);
5742 marker += sizeof(int);
5743
5744 int levelX;
5745 memcpy(&levelX, marker, sizeof(int));
5746 tinyexr::swap4(&levelX);
5747 marker += sizeof(int);
5748
5749 int levelY;
5750 memcpy(&levelY, marker, sizeof(int));
5751 tinyexr::swap4(&levelY);
5752 marker += sizeof(int);
5753
5754 if (isDeep) {
5755 if ((marker + 2 * sizeof(tinyexr::tinyexr_int64)) >= (head + size)) {
5756 return false;
5757 }
5758 tinyexr::tinyexr_int64 packed_offset_table_size;
5759 memcpy(&packed_offset_table_size, marker, sizeof(tinyexr::tinyexr_int64));
5760 tinyexr::swap8(reinterpret_cast<tinyexr::tinyexr_uint64*>(&packed_offset_table_size));
5761 marker += sizeof(tinyexr::tinyexr_int64);
5762
5763 tinyexr::tinyexr_int64 packed_sample_size;
5764 memcpy(&packed_sample_size, marker, sizeof(tinyexr::tinyexr_int64));
5765 tinyexr::swap8(reinterpret_cast<tinyexr::tinyexr_uint64*>(&packed_sample_size));
5766 marker += sizeof(tinyexr::tinyexr_int64);
5767
5768 // next Int64 is unpacked sample size - skip that too
5769 marker += packed_offset_table_size + packed_sample_size + 8;
5770
5771 if (marker >= (head + size)) {
5772 return false;
5773 }
5774
5775 } else {
5776
5777 if ((marker + sizeof(uint32_t)) >= (head + size)) {
5778 return false;
5779 }
5780
5781 uint32_t dataSize;
5782 memcpy(&dataSize, marker, sizeof(uint32_t));
5783 tinyexr::swap4(&dataSize);
5784 marker += sizeof(uint32_t);
5785
5786 marker += dataSize;
5787
5788 if (marker >= (head + size)) {
5789 return false;
5790 }
5791 }
5792
5793 if (!isValidTile(exr_header, offset_data,
5794 tileX, tileY, levelX, levelY)) {
5795 return false;
5796 }
5797
5798 int level_idx = LevelIndex(levelX, levelY, exr_header->tile_level_mode, numXLevels);
5799 if (level_idx < 0) {
5800 return false;
5801 }
5802
5803 if (size_t(level_idx) >= offset_data.offsets.size()) {
5804 return false;
5805 }
5806
5807 if (size_t(tileY) >= offset_data.offsets[size_t(level_idx)].size()) {
5808 return false;
5809 }
5810
5811 if (size_t(tileX) >= offset_data.offsets[size_t(level_idx)][size_t(tileY)].size()) {
5812 return false;
5813 }
5814
5815 offset_data.offsets[size_t(level_idx)][size_t(tileY)][size_t(tileX)] = tileOffset;
5816 }
5817 }
5818 }
5819 return true;
5820}
5821
5822// marker output is also
5823static int ReadOffsets(OffsetData& offset_data,
5824 const unsigned char* head,
5825 const unsigned char*& marker,
5826 const size_t size,
5827 const char** err)
5828{
5829 for (unsigned int l = 0; l < offset_data.offsets.size(); ++l) {
5830 for (unsigned int dy = 0; dy < offset_data.offsets[l].size(); ++dy) {
5831 for (unsigned int dx = 0; dx < offset_data.offsets[l][dy].size(); ++dx) {
5832 tinyexr::tinyexr_uint64 offset;
5833 if ((marker + sizeof(tinyexr_uint64)) >= (head + size)) {
5834 tinyexr::SetErrorMessage("Insufficient data size in offset table.", err);
5836 }
5837
5838 memcpy(&offset, marker, sizeof(tinyexr::tinyexr_uint64));
5839 tinyexr::swap8(&offset);
5840 if (offset >= size) {
5841 tinyexr::SetErrorMessage("Invalid offset value in DecodeEXRImage.", err);
5843 }
5844 marker += sizeof(tinyexr::tinyexr_uint64); // = 8
5845 offset_data.offsets[l][dy][dx] = offset;
5846 }
5847 }
5848 }
5849 return TINYEXR_SUCCESS;
5850}
5851
5852static int DecodeEXRImage(EXRImage* exr_image, const EXRHeader* exr_header,
5853 const unsigned char* head,
5854 const unsigned char* marker, const size_t size,
5855 const char** err)
5856{
5857 if (exr_image == NULL || exr_header == NULL || head == NULL || marker == NULL || (size <= tinyexr::kEXRVersionSize)) {
5858 tinyexr::SetErrorMessage("Invalid argument for DecodeEXRImage().", err);
5860 }
5861
5862 int num_scanline_blocks = 1;
5863 if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) {
5864 num_scanline_blocks = 16;
5865 } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) {
5866 num_scanline_blocks = 32;
5867 } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) {
5868 num_scanline_blocks = 16;
5869 }
5870
5871 if (exr_header->data_window.max_x < exr_header->data_window.min_x || exr_header->data_window.max_x - exr_header->data_window.min_x == std::numeric_limits<int>::max()) {
5872 // Issue 63
5873 tinyexr::SetErrorMessage("Invalid data width value", err);
5875 }
5876 tinyexr_int64 data_width = static_cast<tinyexr_int64>(exr_header->data_window.max_x) - static_cast<tinyexr_int64>(exr_header->data_window.min_x) + static_cast<tinyexr_int64>(1);
5877 if (data_width <= 0) {
5878 tinyexr::SetErrorMessage("Invalid data window width value", err);
5880 }
5881
5882 if (exr_header->data_window.max_y < exr_header->data_window.min_y || exr_header->data_window.max_y - exr_header->data_window.min_y == std::numeric_limits<int>::max()) {
5883 tinyexr::SetErrorMessage("Invalid data height value", err);
5885 }
5886 tinyexr_int64 data_height = static_cast<tinyexr_int64>(exr_header->data_window.max_y) - static_cast<tinyexr_int64>(exr_header->data_window.min_y) + static_cast<tinyexr_int64>(1);
5887
5888 if (data_height <= 0) {
5889 tinyexr::SetErrorMessage("Invalid data window height value", err);
5891 }
5892
5893 // Do not allow too large data_width and data_height. header invalid?
5894 {
5895 if (data_width > TINYEXR_DIMENSION_THRESHOLD) {
5896 tinyexr::SetErrorMessage("data width too large.", err);
5898 }
5899 if (data_height > TINYEXR_DIMENSION_THRESHOLD) {
5900 tinyexr::SetErrorMessage("data height too large.", err);
5902 }
5903 }
5904
5905 if (exr_header->tiled) {
5906 if (exr_header->tile_size_x > TINYEXR_DIMENSION_THRESHOLD) {
5907 tinyexr::SetErrorMessage("tile width too large.", err);
5909 }
5910 if (exr_header->tile_size_y > TINYEXR_DIMENSION_THRESHOLD) {
5911 tinyexr::SetErrorMessage("tile height too large.", err);
5913 }
5914 }
5915
5916 // Read offset tables.
5917 OffsetData offset_data;
5918 size_t num_blocks = 0;
5919 // For a multi-resolution image, the size of the offset table will be calculated from the other attributes of the header.
5920 // If chunk_count > 0 then chunk_count must be equal to the calculated tile count.
5921 if (exr_header->tiled) {
5922 {
5923 std::vector<int> num_x_tiles, num_y_tiles;
5924 if (!PrecalculateTileInfo(num_x_tiles, num_y_tiles, exr_header)) {
5925 tinyexr::SetErrorMessage("Failed to precalculate tile info.", err);
5927 }
5928 num_blocks = size_t(InitTileOffsets(offset_data, exr_header, num_x_tiles, num_y_tiles));
5929 if (exr_header->chunk_count > 0) {
5930 if (exr_header->chunk_count != static_cast<int>(num_blocks)) {
5931 tinyexr::SetErrorMessage("Invalid offset table size.", err);
5933 }
5934 }
5935 }
5936
5937 int ret = ReadOffsets(offset_data, head, marker, size, err);
5938 if (ret != TINYEXR_SUCCESS)
5939 return ret;
5940 if (IsAnyOffsetsAreInvalid(offset_data)) {
5941 if (!ReconstructTileOffsets(offset_data, exr_header,
5942 head, marker, size,
5943 exr_header->multipart, exr_header->non_image)) {
5944
5945 tinyexr::SetErrorMessage("Invalid Tile Offsets data.", err);
5947 }
5948 }
5949 } else if (exr_header->chunk_count > 0) {
5950 // Use `chunkCount` attribute.
5951 num_blocks = static_cast<size_t>(exr_header->chunk_count);
5952 InitSingleResolutionOffsets(offset_data, num_blocks);
5953 } else {
5954 num_blocks = static_cast<size_t>(data_height) / static_cast<size_t>(num_scanline_blocks);
5955 if (num_blocks * static_cast<size_t>(num_scanline_blocks) < static_cast<size_t>(data_height)) {
5956 num_blocks++;
5957 }
5958
5959 InitSingleResolutionOffsets(offset_data, num_blocks);
5960 }
5961
5962 if (!exr_header->tiled) {
5963 std::vector<tinyexr::tinyexr_uint64>& offsets = offset_data.offsets[0][0];
5964 for (size_t y = 0; y < num_blocks; y++) {
5965 tinyexr::tinyexr_uint64 offset;
5966 // Issue #81
5967 if ((marker + sizeof(tinyexr_uint64)) >= (head + size)) {
5968 tinyexr::SetErrorMessage("Insufficient data size in offset table.", err);
5970 }
5971
5972 memcpy(&offset, marker, sizeof(tinyexr::tinyexr_uint64));
5973 tinyexr::swap8(&offset);
5974 if (offset >= size) {
5975 tinyexr::SetErrorMessage("Invalid offset value in DecodeEXRImage.", err);
5977 }
5978 marker += sizeof(tinyexr::tinyexr_uint64); // = 8
5979 offsets[y] = offset;
5980 }
5981
5982 // If line offsets are invalid, we try to reconstruct it.
5983 // See OpenEXR/IlmImf/ImfScanLineInputFile.cpp::readLineOffsets() for details.
5984 for (size_t y = 0; y < num_blocks; y++) {
5985 if (offsets[y] <= 0) {
5986 // TODO(syoyo) Report as warning?
5987 // if (err) {
5988 // stringstream ss;
5989 // ss << "Incomplete lineOffsets." << std::endl;
5990 // (*err) += ss.str();
5991 //}
5992 bool ret = ReconstructLineOffsets(&offsets, num_blocks, head, marker, size);
5993 if (ret) {
5994 // OK
5995 break;
5996 } else {
5997 tinyexr::SetErrorMessage(
5998 "Cannot reconstruct lineOffset table in DecodeEXRImage.", err);
6000 }
6001 }
6002 }
6003 }
6004
6005 {
6006 std::string e;
6007 int ret = DecodeChunk(exr_image, exr_header, offset_data, head, size, &e);
6008
6009 if (ret != TINYEXR_SUCCESS) {
6010 if (!e.empty()) {
6011 tinyexr::SetErrorMessage(e, err);
6012 }
6013
6014#if 1
6015 FreeEXRImage(exr_image);
6016#else
6017 // release memory(if exists)
6018 if ((exr_header->num_channels > 0) && exr_image && exr_image->images) {
6019 for (size_t c = 0; c < size_t(exr_header->num_channels); c++) {
6020 if (exr_image->images[c]) {
6021 free(exr_image->images[c]);
6022 exr_image->images[c] = NULL;
6023 }
6024 }
6025 free(exr_image->images);
6026 exr_image->images = NULL;
6027 }
6028#endif
6029 }
6030
6031 return ret;
6032 }
6033}
6034
6035static void GetLayers(const EXRHeader& exr_header,
6036 std::vector<std::string>& layer_names)
6037{
6038 // Naive implementation
6039 // Group channels by layers
6040 // go over all channel names, split by periods
6041 // collect unique names
6042 layer_names.clear();
6043 for (int c = 0; c < exr_header.num_channels; c++) {
6044 std::string full_name(exr_header.channels[c].name);
6045 const size_t pos = full_name.find_last_of('.');
6046 if (pos != std::string::npos && pos != 0 && pos + 1 < full_name.size()) {
6047 full_name.erase(pos);
6048 if (std::find(layer_names.begin(), layer_names.end(), full_name) == layer_names.end())
6049 layer_names.push_back(full_name);
6050 }
6051 }
6052}
6053
6054struct LayerChannel {
6055 explicit LayerChannel(size_t i, std::string n)
6056 : index(i)
6057 , name(n)
6058 {
6059 }
6060 size_t index;
6061 std::string name;
6062};
6063
6064static void ChannelsInLayer(const EXRHeader& exr_header,
6065 const std::string& layer_name,
6066 std::vector<LayerChannel>& channels)
6067{
6068 channels.clear();
6069 // std::cout << "layer_name = " << layer_name << "\n";
6070 for (int c = 0; c < exr_header.num_channels; c++) {
6071 // std::cout << "chan[" << c << "] = " << exr_header.channels[c].name << "\n";
6072 std::string ch_name(exr_header.channels[c].name);
6073 if (layer_name.empty()) {
6074 const size_t pos = ch_name.find_last_of('.');
6075 if (pos != std::string::npos && pos < ch_name.size()) {
6076 if (pos != 0)
6077 continue;
6078 ch_name = ch_name.substr(pos + 1);
6079 }
6080 } else {
6081 const size_t pos = ch_name.find(layer_name + '.');
6082 if (pos == std::string::npos)
6083 continue;
6084 if (pos == 0) {
6085 ch_name = ch_name.substr(layer_name.size() + 1);
6086 }
6087 }
6088 LayerChannel ch(size_t(c), ch_name);
6089 channels.push_back(ch);
6090 }
6091}
6092
6093} // namespace tinyexr
6094
6095int EXRLayers(const char* filename, const char** layer_names[], int* num_layers,
6096 const char** err)
6097{
6098 EXRVersion exr_version;
6099 EXRHeader exr_header;
6100 InitEXRHeader(&exr_header);
6101
6102 {
6103 int ret = ParseEXRVersionFromFile(&exr_version, filename);
6104 if (ret != TINYEXR_SUCCESS) {
6105 tinyexr::SetErrorMessage("Invalid EXR header.", err);
6106 return ret;
6107 }
6108
6109 if (exr_version.multipart || exr_version.non_image) {
6110 tinyexr::SetErrorMessage(
6111 "Loading multipart or DeepImage is not supported in LoadEXR() API",
6112 err);
6113 return TINYEXR_ERROR_INVALID_DATA; // @fixme.
6114 }
6115 }
6116
6117 int ret = ParseEXRHeaderFromFile(&exr_header, &exr_version, filename, err);
6118 if (ret != TINYEXR_SUCCESS) {
6119 FreeEXRHeader(&exr_header);
6120 return ret;
6121 }
6122
6123 std::vector<std::string> layer_vec;
6124 tinyexr::GetLayers(exr_header, layer_vec);
6125
6126 (*num_layers) = int(layer_vec.size());
6127 (*layer_names) = static_cast<const char**>(
6128 malloc(sizeof(const char*) * static_cast<size_t>(layer_vec.size())));
6129 for (size_t c = 0; c < static_cast<size_t>(layer_vec.size()); c++) {
6130#ifdef _MSC_VER
6131 (*layer_names)[c] = _strdup(layer_vec[c].c_str());
6132#else
6133 (*layer_names)[c] = strdup(layer_vec[c].c_str());
6134#endif
6135 }
6136
6137 FreeEXRHeader(&exr_header);
6138 return TINYEXR_SUCCESS;
6139}
6140
6141int LoadEXR(float** out_rgba, int* width, int* height, const char* filename,
6142 const char** err)
6143{
6144 return LoadEXRWithLayer(out_rgba, width, height, filename,
6145 /* layername */ NULL, err);
6146}
6147
6148int LoadEXRWithLayer(float** out_rgba, int* width, int* height,
6149 const char* filename, const char* layername,
6150 const char** err)
6151{
6152 if (out_rgba == NULL) {
6153 tinyexr::SetErrorMessage("Invalid argument for LoadEXR()", err);
6155 }
6156
6157 EXRVersion exr_version;
6158 EXRImage exr_image;
6159 EXRHeader exr_header;
6160 InitEXRHeader(&exr_header);
6161 InitEXRImage(&exr_image);
6162
6163 {
6164 int ret = ParseEXRVersionFromFile(&exr_version, filename);
6165 if (ret != TINYEXR_SUCCESS) {
6166 std::stringstream ss;
6167 ss << "Failed to open EXR file or read version info from EXR file. code("
6168 << ret << ")";
6169 tinyexr::SetErrorMessage(ss.str(), err);
6170 return ret;
6171 }
6172
6173 if (exr_version.multipart || exr_version.non_image) {
6174 tinyexr::SetErrorMessage(
6175 "Loading multipart or DeepImage is not supported in LoadEXR() API",
6176 err);
6177 return TINYEXR_ERROR_INVALID_DATA; // @fixme.
6178 }
6179 }
6180
6181 {
6182 int ret = ParseEXRHeaderFromFile(&exr_header, &exr_version, filename, err);
6183 if (ret != TINYEXR_SUCCESS) {
6184 FreeEXRHeader(&exr_header);
6185 return ret;
6186 }
6187 }
6188
6189 // Read HALF channel as FLOAT.
6190 for (int i = 0; i < exr_header.num_channels; i++) {
6191 if (exr_header.pixel_types[i] == TINYEXR_PIXELTYPE_HALF) {
6193 }
6194 }
6195
6196 // TODO: Probably limit loading to layers (channels) selected by layer index
6197 {
6198 int ret = LoadEXRImageFromFile(&exr_image, &exr_header, filename, err);
6199 if (ret != TINYEXR_SUCCESS) {
6200 FreeEXRHeader(&exr_header);
6201 return ret;
6202 }
6203 }
6204
6205 // RGBA
6206 int idxR = -1;
6207 int idxG = -1;
6208 int idxB = -1;
6209 int idxA = -1;
6210
6211 std::vector<std::string> layer_names;
6212 tinyexr::GetLayers(exr_header, layer_names);
6213
6214 std::vector<tinyexr::LayerChannel> channels;
6215 tinyexr::ChannelsInLayer(
6216 exr_header, layername == NULL ? "" : std::string(layername), channels);
6217
6218 if (channels.size() < 1) {
6219 if (layername == NULL) {
6220 tinyexr::SetErrorMessage("Layer Not Found. Seems EXR contains channels with layer(e.g. `diffuse.R`). if you are using LoadEXR(), please try LoadEXRWithLayer(). LoadEXR() cannot load EXR having channels with layer.", err);
6221
6222 } else {
6223 tinyexr::SetErrorMessage("Layer Not Found", err);
6224 }
6225 FreeEXRHeader(&exr_header);
6226 FreeEXRImage(&exr_image);
6228 }
6229
6230 size_t ch_count = channels.size() < 4 ? channels.size() : 4;
6231 for (size_t c = 0; c < ch_count; c++) {
6232 const tinyexr::LayerChannel& ch = channels[c];
6233
6234 if (ch.name == "R") {
6235 idxR = int(ch.index);
6236 } else if (ch.name == "G") {
6237 idxG = int(ch.index);
6238 } else if (ch.name == "B") {
6239 idxB = int(ch.index);
6240 } else if (ch.name == "A") {
6241 idxA = int(ch.index);
6242 }
6243 }
6244
6245 if (channels.size() == 1) {
6246 int chIdx = int(channels.front().index);
6247 // Grayscale channel only.
6248
6249 (*out_rgba) = reinterpret_cast<float*>(
6250 malloc(4 * sizeof(float) * static_cast<size_t>(exr_image.width) * static_cast<size_t>(exr_image.height)));
6251
6252 if (exr_header.tiled) {
6253 const size_t tile_size_x = static_cast<size_t>(exr_header.tile_size_x);
6254 const size_t tile_size_y = static_cast<size_t>(exr_header.tile_size_y);
6255 for (int it = 0; it < exr_image.num_tiles; it++) {
6256 for (size_t j = 0; j < tile_size_y; j++) {
6257 for (size_t i = 0; i < tile_size_x; i++) {
6258 const size_t ii = static_cast<size_t>(exr_image.tiles[it].offset_x) * tile_size_x + i;
6259 const size_t jj = static_cast<size_t>(exr_image.tiles[it].offset_y) * tile_size_y + j;
6260 const size_t idx = ii + jj * static_cast<size_t>(exr_image.width);
6261
6262 // out of region check.
6263 if (ii >= static_cast<size_t>(exr_image.width)) {
6264 continue;
6265 }
6266 if (jj >= static_cast<size_t>(exr_image.height)) {
6267 continue;
6268 }
6269 const size_t srcIdx = i + j * tile_size_x;
6270 unsigned char** src = exr_image.tiles[it].images;
6271 (*out_rgba)[4 * idx + 0] = reinterpret_cast<float**>(src)[chIdx][srcIdx];
6272 (*out_rgba)[4 * idx + 1] = reinterpret_cast<float**>(src)[chIdx][srcIdx];
6273 (*out_rgba)[4 * idx + 2] = reinterpret_cast<float**>(src)[chIdx][srcIdx];
6274 (*out_rgba)[4 * idx + 3] = reinterpret_cast<float**>(src)[chIdx][srcIdx];
6275 }
6276 }
6277 }
6278 } else {
6279 const size_t pixel_size = static_cast<size_t>(exr_image.width) * static_cast<size_t>(exr_image.height);
6280 for (size_t i = 0; i < pixel_size; i++) {
6281 const float val = reinterpret_cast<float**>(exr_image.images)[chIdx][i];
6282 (*out_rgba)[4 * i + 0] = val;
6283 (*out_rgba)[4 * i + 1] = val;
6284 (*out_rgba)[4 * i + 2] = val;
6285 (*out_rgba)[4 * i + 3] = val;
6286 }
6287 }
6288 } else {
6289 // Assume RGB(A)
6290
6291 if (idxR == -1) {
6292 tinyexr::SetErrorMessage("R channel not found", err);
6293
6294 FreeEXRHeader(&exr_header);
6295 FreeEXRImage(&exr_image);
6297 }
6298
6299 if (idxG == -1) {
6300 tinyexr::SetErrorMessage("G channel not found", err);
6301 FreeEXRHeader(&exr_header);
6302 FreeEXRImage(&exr_image);
6304 }
6305
6306 if (idxB == -1) {
6307 tinyexr::SetErrorMessage("B channel not found", err);
6308 FreeEXRHeader(&exr_header);
6309 FreeEXRImage(&exr_image);
6311 }
6312
6313 (*out_rgba) = reinterpret_cast<float*>(
6314 malloc(4 * sizeof(float) * static_cast<size_t>(exr_image.width) * static_cast<size_t>(exr_image.height)));
6315 if (exr_header.tiled) {
6316 const size_t tile_size_x = static_cast<size_t>(exr_header.tile_size_x);
6317 const size_t tile_size_y = static_cast<size_t>(exr_header.tile_size_y);
6318 for (int it = 0; it < exr_image.num_tiles; it++) {
6319 for (size_t j = 0; j < tile_size_y; j++) {
6320 for (size_t i = 0; i < tile_size_x; i++) {
6321 const size_t ii = static_cast<size_t>(exr_image.tiles[it].offset_x) * tile_size_x + i;
6322 const size_t jj = static_cast<size_t>(exr_image.tiles[it].offset_y) * tile_size_y + j;
6323 const size_t idx = ii + jj * static_cast<size_t>(exr_image.width);
6324
6325 // out of region check.
6326 if (ii >= static_cast<size_t>(exr_image.width)) {
6327 continue;
6328 }
6329 if (jj >= static_cast<size_t>(exr_image.height)) {
6330 continue;
6331 }
6332 const size_t srcIdx = i + j * tile_size_x;
6333 unsigned char** src = exr_image.tiles[it].images;
6334 (*out_rgba)[4 * idx + 0] = reinterpret_cast<float**>(src)[idxR][srcIdx];
6335 (*out_rgba)[4 * idx + 1] = reinterpret_cast<float**>(src)[idxG][srcIdx];
6336 (*out_rgba)[4 * idx + 2] = reinterpret_cast<float**>(src)[idxB][srcIdx];
6337 if (idxA != -1) {
6338 (*out_rgba)[4 * idx + 3] = reinterpret_cast<float**>(src)[idxA][srcIdx];
6339 } else {
6340 (*out_rgba)[4 * idx + 3] = 1.0;
6341 }
6342 }
6343 }
6344 }
6345 } else {
6346 const size_t pixel_size = static_cast<size_t>(exr_image.width) * static_cast<size_t>(exr_image.height);
6347 for (size_t i = 0; i < pixel_size; i++) {
6348 (*out_rgba)[4 * i + 0] = reinterpret_cast<float**>(exr_image.images)[idxR][i];
6349 (*out_rgba)[4 * i + 1] = reinterpret_cast<float**>(exr_image.images)[idxG][i];
6350 (*out_rgba)[4 * i + 2] = reinterpret_cast<float**>(exr_image.images)[idxB][i];
6351 if (idxA != -1) {
6352 (*out_rgba)[4 * i + 3] = reinterpret_cast<float**>(exr_image.images)[idxA][i];
6353 } else {
6354 (*out_rgba)[4 * i + 3] = 1.0;
6355 }
6356 }
6357 }
6358 }
6359
6360 (*width) = exr_image.width;
6361 (*height) = exr_image.height;
6362
6363 FreeEXRHeader(&exr_header);
6364 FreeEXRImage(&exr_image);
6365
6366 return TINYEXR_SUCCESS;
6367}
6368
6369int IsEXR(const char* filename)
6370{
6371 EXRVersion exr_version;
6372
6373 int ret = ParseEXRVersionFromFile(&exr_version, filename);
6374 if (ret != TINYEXR_SUCCESS) {
6375 return ret;
6376 }
6377
6378 return TINYEXR_SUCCESS;
6379}
6380
6381int IsEXRFromMemory(const unsigned char* memory, size_t size)
6382{
6383 EXRVersion exr_version;
6384
6385 int ret = ParseEXRVersionFromMemory(&exr_version, memory, size);
6386 if (ret != TINYEXR_SUCCESS) {
6387 return ret;
6388 }
6389
6390 return TINYEXR_SUCCESS;
6391}
6392
6393int ParseEXRHeaderFromMemory(EXRHeader* exr_header, const EXRVersion* version,
6394 const unsigned char* memory, size_t size,
6395 const char** err)
6396{
6397 if (memory == NULL || exr_header == NULL) {
6398 tinyexr::SetErrorMessage(
6399 "Invalid argument. `memory` or `exr_header` argument is null in "
6400 "ParseEXRHeaderFromMemory()",
6401 err);
6402
6403 // Invalid argument
6405 }
6406
6407 if (size < tinyexr::kEXRVersionSize) {
6408 tinyexr::SetErrorMessage("Insufficient header/data size.\n", err);
6410 }
6411
6412 const unsigned char* marker = memory + tinyexr::kEXRVersionSize;
6413 size_t marker_size = size - tinyexr::kEXRVersionSize;
6414
6415 tinyexr::HeaderInfo info;
6416 info.clear();
6417
6418 int ret;
6419 {
6420 std::string err_str;
6421 ret = ParseEXRHeader(&info, NULL, version, &err_str, marker, marker_size);
6422
6423 if (ret != TINYEXR_SUCCESS) {
6424 if (err && !err_str.empty()) {
6425 tinyexr::SetErrorMessage(err_str, err);
6426 }
6427 }
6428 }
6429
6430 {
6431 std::string warn;
6432 std::string err_str;
6433
6434 if (!ConvertHeader(exr_header, info, &warn, &err_str)) {
6435 // release mem
6436 for (size_t i = 0; i < info.attributes.size(); i++) {
6437 if (info.attributes[i].value) {
6438 free(info.attributes[i].value);
6439 }
6440 }
6441 if (err && !err_str.empty()) {
6442 tinyexr::SetErrorMessage(err_str, err);
6443 }
6445 }
6446 }
6447
6448 exr_header->multipart = version->multipart ? 1 : 0;
6449 exr_header->non_image = version->non_image ? 1 : 0;
6450
6451 return ret;
6452}
6453
6454int LoadEXRFromMemory(float** out_rgba, int* width, int* height,
6455 const unsigned char* memory, size_t size,
6456 const char** err)
6457{
6458 if (out_rgba == NULL || memory == NULL) {
6459 tinyexr::SetErrorMessage("Invalid argument for LoadEXRFromMemory", err);
6461 }
6462
6463 EXRVersion exr_version;
6464 EXRImage exr_image;
6465 EXRHeader exr_header;
6466
6467 InitEXRHeader(&exr_header);
6468
6469 int ret = ParseEXRVersionFromMemory(&exr_version, memory, size);
6470 if (ret != TINYEXR_SUCCESS) {
6471 std::stringstream ss;
6472 ss << "Failed to parse EXR version. code(" << ret << ")";
6473 tinyexr::SetErrorMessage(ss.str(), err);
6474 return ret;
6475 }
6476
6477 ret = ParseEXRHeaderFromMemory(&exr_header, &exr_version, memory, size, err);
6478 if (ret != TINYEXR_SUCCESS) {
6479 return ret;
6480 }
6481
6482 // Read HALF channel as FLOAT.
6483 for (int i = 0; i < exr_header.num_channels; i++) {
6484 if (exr_header.pixel_types[i] == TINYEXR_PIXELTYPE_HALF) {
6486 }
6487 }
6488
6489 InitEXRImage(&exr_image);
6490 ret = LoadEXRImageFromMemory(&exr_image, &exr_header, memory, size, err);
6491 if (ret != TINYEXR_SUCCESS) {
6492 return ret;
6493 }
6494
6495 // RGBA
6496 int idxR = -1;
6497 int idxG = -1;
6498 int idxB = -1;
6499 int idxA = -1;
6500 for (int c = 0; c < exr_header.num_channels; c++) {
6501 if (strcmp(exr_header.channels[c].name, "R") == 0) {
6502 idxR = c;
6503 } else if (strcmp(exr_header.channels[c].name, "G") == 0) {
6504 idxG = c;
6505 } else if (strcmp(exr_header.channels[c].name, "B") == 0) {
6506 idxB = c;
6507 } else if (strcmp(exr_header.channels[c].name, "A") == 0) {
6508 idxA = c;
6509 }
6510 }
6511
6512 // TODO(syoyo): Refactor removing same code as used in LoadEXR().
6513 if (exr_header.num_channels == 1) {
6514 // Grayscale channel only.
6515
6516 (*out_rgba) = reinterpret_cast<float*>(
6517 malloc(4 * sizeof(float) * static_cast<size_t>(exr_image.width) * static_cast<size_t>(exr_image.height)));
6518
6519 if (exr_header.tiled) {
6520 const size_t tile_size_x = static_cast<size_t>(exr_header.tile_size_x);
6521 const size_t tile_size_y = static_cast<size_t>(exr_header.tile_size_y);
6522 for (int it = 0; it < exr_image.num_tiles; it++) {
6523 for (size_t j = 0; j < tile_size_y; j++) {
6524 for (size_t i = 0; i < tile_size_x; i++) {
6525 const size_t ii = static_cast<size_t>(exr_image.tiles[it].offset_x) * tile_size_x + i;
6526 const size_t jj = static_cast<size_t>(exr_image.tiles[it].offset_y) * tile_size_y + j;
6527 const size_t idx = ii + jj * static_cast<size_t>(exr_image.width);
6528
6529 // out of region check.
6530 if (ii >= static_cast<size_t>(exr_image.width)) {
6531 continue;
6532 }
6533 if (jj >= static_cast<size_t>(exr_image.height)) {
6534 continue;
6535 }
6536 const size_t srcIdx = i + j * tile_size_x;
6537 unsigned char** src = exr_image.tiles[it].images;
6538 (*out_rgba)[4 * idx + 0] = reinterpret_cast<float**>(src)[0][srcIdx];
6539 (*out_rgba)[4 * idx + 1] = reinterpret_cast<float**>(src)[0][srcIdx];
6540 (*out_rgba)[4 * idx + 2] = reinterpret_cast<float**>(src)[0][srcIdx];
6541 (*out_rgba)[4 * idx + 3] = reinterpret_cast<float**>(src)[0][srcIdx];
6542 }
6543 }
6544 }
6545 } else {
6546 const size_t pixel_size = static_cast<size_t>(exr_image.width) * static_cast<size_t>(exr_image.height);
6547 for (size_t i = 0; i < pixel_size; i++) {
6548 const float val = reinterpret_cast<float**>(exr_image.images)[0][i];
6549 (*out_rgba)[4 * i + 0] = val;
6550 (*out_rgba)[4 * i + 1] = val;
6551 (*out_rgba)[4 * i + 2] = val;
6552 (*out_rgba)[4 * i + 3] = val;
6553 }
6554 }
6555
6556 } else {
6557 // TODO(syoyo): Support non RGBA image.
6558
6559 if (idxR == -1) {
6560 tinyexr::SetErrorMessage("R channel not found", err);
6561
6562 // @todo { free exr_image }
6564 }
6565
6566 if (idxG == -1) {
6567 tinyexr::SetErrorMessage("G channel not found", err);
6568 // @todo { free exr_image }
6570 }
6571
6572 if (idxB == -1) {
6573 tinyexr::SetErrorMessage("B channel not found", err);
6574 // @todo { free exr_image }
6576 }
6577
6578 (*out_rgba) = reinterpret_cast<float*>(
6579 malloc(4 * sizeof(float) * static_cast<size_t>(exr_image.width) * static_cast<size_t>(exr_image.height)));
6580
6581 if (exr_header.tiled) {
6582 const size_t tile_size_x = static_cast<size_t>(exr_header.tile_size_x);
6583 const size_t tile_size_y = static_cast<size_t>(exr_header.tile_size_y);
6584 for (int it = 0; it < exr_image.num_tiles; it++) {
6585 for (size_t j = 0; j < tile_size_y; j++)
6586 for (size_t i = 0; i < tile_size_x; i++) {
6587 const size_t ii = static_cast<size_t>(exr_image.tiles[it].offset_x) * tile_size_x + i;
6588 const size_t jj = static_cast<size_t>(exr_image.tiles[it].offset_y) * tile_size_y + j;
6589 const size_t idx = ii + jj * static_cast<size_t>(exr_image.width);
6590
6591 // out of region check.
6592 if (ii >= static_cast<size_t>(exr_image.width)) {
6593 continue;
6594 }
6595 if (jj >= static_cast<size_t>(exr_image.height)) {
6596 continue;
6597 }
6598 const size_t srcIdx = i + j * tile_size_x;
6599 unsigned char** src = exr_image.tiles[it].images;
6600 (*out_rgba)[4 * idx + 0] = reinterpret_cast<float**>(src)[idxR][srcIdx];
6601 (*out_rgba)[4 * idx + 1] = reinterpret_cast<float**>(src)[idxG][srcIdx];
6602 (*out_rgba)[4 * idx + 2] = reinterpret_cast<float**>(src)[idxB][srcIdx];
6603 if (idxA != -1) {
6604 (*out_rgba)[4 * idx + 3] = reinterpret_cast<float**>(src)[idxA][srcIdx];
6605 } else {
6606 (*out_rgba)[4 * idx + 3] = 1.0;
6607 }
6608 }
6609 }
6610 } else {
6611 const size_t pixel_size = static_cast<size_t>(exr_image.width) * static_cast<size_t>(exr_image.height);
6612 for (size_t i = 0; i < pixel_size; i++) {
6613 (*out_rgba)[4 * i + 0] = reinterpret_cast<float**>(exr_image.images)[idxR][i];
6614 (*out_rgba)[4 * i + 1] = reinterpret_cast<float**>(exr_image.images)[idxG][i];
6615 (*out_rgba)[4 * i + 2] = reinterpret_cast<float**>(exr_image.images)[idxB][i];
6616 if (idxA != -1) {
6617 (*out_rgba)[4 * i + 3] = reinterpret_cast<float**>(exr_image.images)[idxA][i];
6618 } else {
6619 (*out_rgba)[4 * i + 3] = 1.0;
6620 }
6621 }
6622 }
6623 }
6624
6625 (*width) = exr_image.width;
6626 (*height) = exr_image.height;
6627
6628 FreeEXRHeader(&exr_header);
6629 FreeEXRImage(&exr_image);
6630
6631 return TINYEXR_SUCCESS;
6632}
6633
6634// Represents a read-only file mapped to an address space in memory.
6635// If no memory-mapping API is available, falls back to allocating a buffer
6636// with a copy of the file's data.
6637struct MemoryMappedFile {
6638 unsigned char* data; // To the start of the file's data.
6639 size_t size; // The size of the file in bytes.
6640#ifdef TINYEXR_USE_WIN32_MMAP
6641 HANDLE windows_file;
6642 HANDLE windows_file_mapping;
6643#elif defined(TINYEXR_USE_POSIX_MMAP)
6644 int posix_descriptor;
6645#endif
6646
6647 // MemoryMappedFile's constructor tries to map memory to a file.
6648 // If this succeeds, valid() will return true and all fields
6649 // are usable; otherwise, valid() will return false.
6650 MemoryMappedFile(const char* filename)
6651 {
6652 data = NULL;
6653 size = 0;
6654#ifdef TINYEXR_USE_WIN32_MMAP
6655 windows_file_mapping = NULL;
6656 windows_file = CreateFileW(tinyexr::UTF8ToWchar(filename).c_str(), // lpFileName
6657 GENERIC_READ, // dwDesiredAccess
6658 FILE_SHARE_READ, // dwShareMode
6659 NULL, // lpSecurityAttributes
6660 OPEN_EXISTING, // dwCreationDisposition
6661 FILE_ATTRIBUTE_READONLY, // dwFlagsAndAttributes
6662 NULL); // hTemplateFile
6663 if (windows_file == INVALID_HANDLE_VALUE) {
6664 return;
6665 }
6666
6667 windows_file_mapping = CreateFileMapping(windows_file, // hFile
6668 NULL, // lpFileMappingAttributes
6669 PAGE_READONLY, // flProtect
6670 0, // dwMaximumSizeHigh
6671 0, // dwMaximumSizeLow
6672 NULL); // lpName
6673 if (windows_file_mapping == NULL) {
6674 return;
6675 }
6676
6677 data = reinterpret_cast<unsigned char*>(
6678 MapViewOfFile(windows_file_mapping, // hFileMappingObject
6679 FILE_MAP_READ, // dwDesiredAccess
6680 0, // dwFileOffsetHigh
6681 0, // dwFileOffsetLow
6682 0)); // dwNumberOfBytesToMap
6683 if (!data) {
6684 return;
6685 }
6686
6687 LARGE_INTEGER windows_file_size = { };
6688 if (!GetFileSizeEx(windows_file, &windows_file_size) || static_cast<ULONGLONG>(windows_file_size.QuadPart) > std::numeric_limits<size_t>::max()) {
6689 UnmapViewOfFile(data);
6690 data = NULL;
6691 return;
6692 }
6693 size = static_cast<size_t>(windows_file_size.QuadPart);
6694#elif defined(TINYEXR_USE_POSIX_MMAP)
6695 posix_descriptor = open(filename, O_RDONLY);
6696 if (posix_descriptor == -1) {
6697 return;
6698 }
6699
6700 struct stat info;
6701 if (fstat(posix_descriptor, &info) < 0) {
6702 return;
6703 }
6704 // Make sure st_size is in the valid range for a size_t. The second case
6705 // can only fail if a POSIX implementation defines off_t to be a larger
6706 // type than size_t - for instance, compiling with _FILE_OFFSET_BITS=64
6707 // on a 32-bit system. On current 64-bit systems, this check can never
6708 // fail, so we turn off clang's Wtautological-type-limit-compare warning
6709 // around this code.
6710#ifdef __clang__
6711#pragma clang diagnostic push
6712#pragma clang diagnostic ignored "-Wtautological-type-limit-compare"
6713#endif
6714 if (info.st_size < 0 || info.st_size > std::numeric_limits<ssize_t>::max()) {
6715 return;
6716 }
6717#ifdef __clang__
6718#pragma clang diagnostic pop
6719#endif
6720 size = static_cast<size_t>(info.st_size);
6721
6722 data = reinterpret_cast<unsigned char*>(
6723 mmap(0, size, PROT_READ, MAP_SHARED, posix_descriptor, 0));
6724 if (data == MAP_FAILED) {
6725 data = nullptr;
6726 return;
6727 }
6728#else
6729 FILE* fp = fopen(filename, "rb");
6730 if (!fp) {
6731 return;
6732 }
6733
6734 // Calling fseek(fp, 0, SEEK_END) isn't strictly-conforming C code, but
6735 // since neither the WIN32 nor POSIX APIs are available in this branch, this
6736 // is a reasonable fallback option.
6737 if (fseek(fp, 0, SEEK_END) != 0) {
6738 fclose(fp);
6739 return;
6740 }
6741 const long ftell_result = ftell(fp);
6742 if (ftell_result < 0) {
6743 // Error from ftell
6744 fclose(fp);
6745 return;
6746 }
6747 size = static_cast<size_t>(ftell_result);
6748 if (fseek(fp, 0, SEEK_SET) != 0) {
6749 fclose(fp);
6750 size = 0;
6751 return;
6752 }
6753
6754 data = reinterpret_cast<unsigned char*>(malloc(size));
6755 if (!data) {
6756 size = 0;
6757 fclose(fp);
6758 return;
6759 }
6760 size_t read_bytes = fread(data, 1, size, fp);
6761 if (read_bytes != size) {
6762 // TODO: Try to read data until reading `size` bytes.
6763 fclose(fp);
6764 size = 0;
6765 data = nullptr;
6766 return;
6767 }
6768 fclose(fp);
6769#endif
6770 }
6771
6772 // MemoryMappedFile's destructor closes all its handles.
6773 ~MemoryMappedFile()
6774 {
6775#ifdef TINYEXR_USE_WIN32_MMAP
6776 if (data) {
6777 (void)UnmapViewOfFile(data);
6778 data = NULL;
6779 }
6780
6781 if (windows_file_mapping != NULL) {
6782 (void)CloseHandle(windows_file_mapping);
6783 }
6784
6785 if (windows_file != INVALID_HANDLE_VALUE) {
6786 (void)CloseHandle(windows_file);
6787 }
6788#elif defined(TINYEXR_USE_POSIX_MMAP)
6789 if (data) {
6790 (void)munmap(data, size);
6791 data = NULL;
6792 }
6793
6794 if (posix_descriptor != -1) {
6795 (void)close(posix_descriptor);
6796 }
6797#else
6798 if (data) {
6799 (void)free(data);
6800 }
6801 data = NULL;
6802#endif
6803 }
6804
6805 // A MemoryMappedFile cannot be copied or moved.
6806 // Only check for this when compiling with C++11 or higher, since deleted
6807 // function definitions were added then.
6808#if TINYEXR_HAS_CXX11
6809#ifdef __clang__
6810#pragma clang diagnostic push
6811#pragma clang diagnostic ignored "-Wc++98-compat"
6812#endif
6813 MemoryMappedFile(const MemoryMappedFile&) = delete;
6814 MemoryMappedFile& operator=(const MemoryMappedFile&) = delete;
6815 MemoryMappedFile(MemoryMappedFile&& other) noexcept = delete;
6816 MemoryMappedFile& operator=(MemoryMappedFile&& other) noexcept = delete;
6817#ifdef __clang__
6818#pragma clang diagnostic pop
6819#endif
6820#endif
6821
6822 // Returns whether this was successfully opened.
6823 bool valid() const { return data; }
6824};
6825
6826int LoadEXRImageFromFile(EXRImage* exr_image, const EXRHeader* exr_header,
6827 const char* filename, const char** err)
6828{
6829 if (exr_image == NULL) {
6830 tinyexr::SetErrorMessage("Invalid argument for LoadEXRImageFromFile", err);
6832 }
6833
6834 MemoryMappedFile file(filename);
6835 if (!file.valid()) {
6836 tinyexr::SetErrorMessage("Cannot read file " + std::string(filename), err);
6838 }
6839
6840 if (file.size < 16) {
6841 tinyexr::SetErrorMessage("File size too short : " + std::string(filename),
6842 err);
6844 }
6845
6846 return LoadEXRImageFromMemory(exr_image, exr_header, file.data, file.size,
6847 err);
6848}
6849
6850int LoadEXRImageFromMemory(EXRImage* exr_image, const EXRHeader* exr_header,
6851 const unsigned char* memory, const size_t size,
6852 const char** err)
6853{
6854 if (exr_image == NULL || memory == NULL || (size < tinyexr::kEXRVersionSize)) {
6855 tinyexr::SetErrorMessage("Invalid argument for LoadEXRImageFromMemory",
6856 err);
6858 }
6859
6860 if (exr_header->header_len == 0) {
6861 tinyexr::SetErrorMessage("EXRHeader variable is not initialized.", err);
6863 }
6864
6865 const unsigned char* head = memory;
6866 const unsigned char* marker = reinterpret_cast<const unsigned char*>(
6867 memory + exr_header->header_len + 8); // +8 for magic number + version header.
6868 return tinyexr::DecodeEXRImage(exr_image, exr_header, head, marker, size,
6869 err);
6870}
6871
6872namespace tinyexr {
6873
6874#ifdef __clang__
6875#pragma clang diagnostic push
6876#pragma clang diagnostic ignored "-Wsign-conversion"
6877#endif
6878
6879// out_data must be allocated initially with the block-header size
6880// of the current image(-part) type
6881static bool EncodePixelData(/* out */ std::vector<unsigned char>& out_data,
6882 const unsigned char* const* images,
6883 int compression_type,
6884 int /*line_order*/,
6885 int width, // for tiled : tile.width
6886 int /*height*/, // for tiled : header.tile_size_y
6887 int x_stride, // for tiled : header.tile_size_x
6888 int line_no, // for tiled : 0
6889 int num_lines, // for tiled : tile.height
6890 size_t pixel_data_size,
6891 const std::vector<ChannelInfo>& channels,
6892 const std::vector<size_t>& channel_offset_list,
6893 std::string* err,
6894 const void* compression_param = 0) // zfp compression param
6895{
6896 size_t buf_size = static_cast<size_t>(width) * static_cast<size_t>(num_lines) * static_cast<size_t>(pixel_data_size);
6897 // int last2bit = (buf_size & 3);
6898 // buf_size must be multiple of four
6899 // if(last2bit) buf_size += 4 - last2bit;
6900 std::vector<unsigned char> buf(buf_size);
6901
6902 size_t start_y = static_cast<size_t>(line_no);
6903 for (size_t c = 0; c < channels.size(); c++) {
6904 if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) {
6905 if (channels[c].requested_pixel_type == TINYEXR_PIXELTYPE_FLOAT) {
6906 for (int y = 0; y < num_lines; y++) {
6907 // Assume increasing Y
6908 float* line_ptr = reinterpret_cast<float*>(&buf.at(
6909 static_cast<size_t>(pixel_data_size * size_t(y) * size_t(width)) + channel_offset_list[c] * static_cast<size_t>(width)));
6910 for (int x = 0; x < width; x++) {
6911 tinyexr::FP16 h16;
6912 h16.u = reinterpret_cast<const unsigned short* const*>(
6913 images)[c][(y + start_y) * size_t(x_stride) + size_t(x)];
6914
6915 tinyexr::FP32 f32 = half_to_float(h16);
6916
6917 tinyexr::swap4(&f32.f);
6918
6919 // line_ptr[x] = f32.f;
6920 tinyexr::cpy4(line_ptr + x, &(f32.f));
6921 }
6922 }
6923 } else if (channels[c].requested_pixel_type == TINYEXR_PIXELTYPE_HALF) {
6924 for (int y = 0; y < num_lines; y++) {
6925 // Assume increasing Y
6926 unsigned short* line_ptr = reinterpret_cast<unsigned short*>(
6927 &buf.at(static_cast<size_t>(pixel_data_size * y * width) + channel_offset_list[c] * static_cast<size_t>(width)));
6928 for (int x = 0; x < width; x++) {
6929 unsigned short val = reinterpret_cast<const unsigned short* const*>(
6930 images)[c][(y + start_y) * x_stride + x];
6931
6932 tinyexr::swap2(&val);
6933
6934 // line_ptr[x] = val;
6935 tinyexr::cpy2(line_ptr + x, &val);
6936 }
6937 }
6938 } else {
6939 if (err) {
6940 (*err) += "Invalid requested_pixel_type.\n";
6941 }
6942 return false;
6943 }
6944
6945 } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) {
6946 if (channels[c].requested_pixel_type == TINYEXR_PIXELTYPE_HALF) {
6947 for (int y = 0; y < num_lines; y++) {
6948 // Assume increasing Y
6949 unsigned short* line_ptr = reinterpret_cast<unsigned short*>(
6950 &buf.at(static_cast<size_t>(pixel_data_size * y * width) + channel_offset_list[c] * static_cast<size_t>(width)));
6951 for (int x = 0; x < width; x++) {
6952 tinyexr::FP32 f32;
6953 f32.f = reinterpret_cast<const float* const*>(
6954 images)[c][(y + start_y) * x_stride + x];
6955
6956 tinyexr::FP16 h16;
6957 h16 = float_to_half_full(f32);
6958
6959 tinyexr::swap2(reinterpret_cast<unsigned short*>(&h16.u));
6960
6961 // line_ptr[x] = h16.u;
6962 tinyexr::cpy2(line_ptr + x, &(h16.u));
6963 }
6964 }
6965 } else if (channels[c].requested_pixel_type == TINYEXR_PIXELTYPE_FLOAT) {
6966 for (int y = 0; y < num_lines; y++) {
6967 // Assume increasing Y
6968 float* line_ptr = reinterpret_cast<float*>(&buf.at(
6969 static_cast<size_t>(pixel_data_size * y * width) + channel_offset_list[c] * static_cast<size_t>(width)));
6970 for (int x = 0; x < width; x++) {
6971 float val = reinterpret_cast<const float* const*>(
6972 images)[c][(y + start_y) * x_stride + x];
6973
6974 tinyexr::swap4(&val);
6975
6976 // line_ptr[x] = val;
6977 tinyexr::cpy4(line_ptr + x, &val);
6978 }
6979 }
6980 } else {
6981 if (err) {
6982 (*err) += "Invalid requested_pixel_type.\n";
6983 }
6984 return false;
6985 }
6986 } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) {
6987 for (int y = 0; y < num_lines; y++) {
6988 // Assume increasing Y
6989 unsigned int* line_ptr = reinterpret_cast<unsigned int*>(&buf.at(
6990 static_cast<size_t>(pixel_data_size * y * width) + channel_offset_list[c] * static_cast<size_t>(width)));
6991 for (int x = 0; x < width; x++) {
6992 unsigned int val = reinterpret_cast<const unsigned int* const*>(
6993 images)[c][(y + start_y) * x_stride + x];
6994
6995 tinyexr::swap4(&val);
6996
6997 // line_ptr[x] = val;
6998 tinyexr::cpy4(line_ptr + x, &val);
6999 }
7000 }
7001 }
7002 }
7003
7004 if (compression_type == TINYEXR_COMPRESSIONTYPE_NONE) {
7005 // 4 byte: scan line
7006 // 4 byte: data size
7007 // ~ : pixel data(uncompressed)
7008 out_data.insert(out_data.end(), buf.begin(), buf.end());
7009
7010 } else if ((compression_type == TINYEXR_COMPRESSIONTYPE_ZIPS) || (compression_type == TINYEXR_COMPRESSIONTYPE_ZIP)) {
7011#if defined(TINYEXR_USE_MINIZ) && (TINYEXR_USE_MINIZ == 1)
7012 std::vector<unsigned char> block(mz_compressBound(
7013 static_cast<unsigned long>(buf.size())));
7014#elif TINYEXR_USE_STB_ZLIB
7015 // there is no compressBound() function, so we use a value that
7016 // is grossly overestimated, but should always work
7017 std::vector<unsigned char> block(256 + 2 * buf.size());
7018#elif defined(TINYEXR_USE_NANOZLIB) && (TINYEXR_USE_NANOZLIB == 1)
7019 std::vector<unsigned char> block(nanoz_compressBound(
7020 static_cast<unsigned long>(buf.size())));
7021#else
7022 std::vector<unsigned char> block(
7023 compressBound(static_cast<uLong>(buf.size())));
7024#endif
7025 tinyexr::tinyexr_uint64 outSize = block.size();
7026
7027 if (!tinyexr::CompressZip(&block.at(0), outSize,
7028 reinterpret_cast<const unsigned char*>(&buf.at(0)),
7029 static_cast<unsigned long>(buf.size()))) {
7030 if (err) {
7031 (*err) += "Zip compresssion failed.\n";
7032 }
7033 return false;
7034 }
7035
7036 // 4 byte: scan line
7037 // 4 byte: data size
7038 // ~ : pixel data(compressed)
7039 unsigned int data_len = static_cast<unsigned int>(outSize); // truncate
7040
7041 out_data.insert(out_data.end(), block.begin(), block.begin() + data_len);
7042
7043 } else if (compression_type == TINYEXR_COMPRESSIONTYPE_RLE) {
7044 // (buf.size() * 3) / 2 would be enough.
7045 std::vector<unsigned char> block((buf.size() * 3) / 2);
7046
7047 tinyexr::tinyexr_uint64 outSize = block.size();
7048
7049 if (!tinyexr::CompressRle(&block.at(0), outSize,
7050 reinterpret_cast<const unsigned char*>(&buf.at(0)),
7051 static_cast<unsigned long>(buf.size()))) {
7052 if (err) {
7053 (*err) += "RLE compresssion failed.\n";
7054 }
7055 return false;
7056 }
7057
7058 // 4 byte: scan line
7059 // 4 byte: data size
7060 // ~ : pixel data(compressed)
7061 unsigned int data_len = static_cast<unsigned int>(outSize); // truncate
7062 out_data.insert(out_data.end(), block.begin(), block.begin() + data_len);
7063
7064 } else if (compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) {
7065#if TINYEXR_USE_PIZ
7066 unsigned int bufLen = 8192 + static_cast<unsigned int>(2 * static_cast<unsigned int>(buf.size())); // @fixme { compute good bound. }
7067 std::vector<unsigned char> block(bufLen);
7068 unsigned int outSize = static_cast<unsigned int>(block.size());
7069
7070 if (!CompressPiz(&block.at(0), &outSize,
7071 reinterpret_cast<const unsigned char*>(&buf.at(0)),
7072 buf.size(), channels, width, num_lines)) {
7073 if (err) {
7074 (*err) += "PIZ compresssion failed.\n";
7075 }
7076 return false;
7077 }
7078
7079 // 4 byte: scan line
7080 // 4 byte: data size
7081 // ~ : pixel data(compressed)
7082 unsigned int data_len = outSize;
7083 out_data.insert(out_data.end(), block.begin(), block.begin() + data_len);
7084
7085#else
7086 if (err) {
7087 (*err) += "PIZ compression is disabled in this build.\n";
7088 }
7089 return false;
7090#endif
7091 } else if (compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) {
7092#if TINYEXR_USE_ZFP
7093 const ZFPCompressionParam* zfp_compression_param = reinterpret_cast<const ZFPCompressionParam*>(compression_param);
7094 std::vector<unsigned char> block;
7095 unsigned int outSize;
7096
7097 tinyexr::CompressZfp(
7098 &block, &outSize, reinterpret_cast<const float*>(&buf.at(0)),
7099 width, num_lines, static_cast<int>(channels.size()), *zfp_compression_param);
7100
7101 // 4 byte: scan line
7102 // 4 byte: data size
7103 // ~ : pixel data(compressed)
7104 unsigned int data_len = outSize;
7105 out_data.insert(out_data.end(), block.begin(), block.begin() + data_len);
7106
7107#else
7108 if (err) {
7109 (*err) += "ZFP compression is disabled in this build.\n";
7110 }
7111 (void)compression_param;
7112 return false;
7113#endif
7114 } else {
7115 return false;
7116 }
7117
7118 return true;
7119}
7120
7121static int EncodeTiledLevel(const EXRImage* level_image, const EXRHeader* exr_header,
7122 const std::vector<tinyexr::ChannelInfo>& channels,
7123 std::vector<std::vector<unsigned char>>& data_list,
7124 size_t start_index, // for data_list
7125 int num_x_tiles, int num_y_tiles,
7126 const std::vector<size_t>& channel_offset_list,
7127 int pixel_data_size,
7128 const void* compression_param, // must be set if zfp compression is enabled
7129 std::string* err)
7130{
7131 int num_tiles = num_x_tiles * num_y_tiles;
7132 if (num_tiles != level_image->num_tiles) {
7133 if (err) {
7134 (*err) += "Invalid number of tiles in argument.\n";
7135 }
7137 }
7138
7139 if ((exr_header->tile_size_x > level_image->width || exr_header->tile_size_y > level_image->height) && level_image->level_x == 0 && level_image->level_y == 0) {
7140 if (err) {
7141 (*err) += "Failed to encode tile data.\n";
7142 }
7144 }
7145
7146#if TINYEXR_HAS_CXX11 && (TINYEXR_USE_THREAD > 0)
7147 std::atomic<bool> invalid_data(false);
7148#else
7149 bool invalid_data(false);
7150#endif
7151
7152#if TINYEXR_HAS_CXX11 && (TINYEXR_USE_THREAD > 0)
7153 std::vector<std::thread> workers;
7154 std::atomic<int> tile_count(0);
7155
7156 int num_threads = std::max(1, int(std::thread::hardware_concurrency()));
7157 if (num_threads > int(num_tiles)) {
7158 num_threads = int(num_tiles);
7159 }
7160
7161 for (int t = 0; t < num_threads; t++) {
7162 workers.emplace_back(std::thread([&]() {
7163 int i = 0;
7164 while ((i = tile_count++) < num_tiles) {
7165
7166#else
7167 // Use signed int since some OpenMP compiler doesn't allow unsigned type for
7168 // `parallel for`
7169#if TINYEXR_USE_OPENMP
7170#pragma omp parallel for
7171#endif
7172 for (int i = 0; i < num_tiles; i++) {
7173
7174#endif
7175 size_t tile_idx = static_cast<size_t>(i);
7176 size_t data_idx = tile_idx + start_index;
7177
7178 int x_tile = i % num_x_tiles;
7179 int y_tile = i / num_x_tiles;
7180
7181 EXRTile& tile = level_image->tiles[tile_idx];
7182
7183 const unsigned char* const* images = static_cast<const unsigned char* const*>(tile.images);
7184
7185 data_list[data_idx].resize(5 * sizeof(int));
7186 size_t data_header_size = data_list[data_idx].size();
7187 bool ret = EncodePixelData(data_list[data_idx],
7188 images,
7189 exr_header->compression_type,
7190 0, // increasing y
7191 tile.width,
7192 exr_header->tile_size_y,
7193 exr_header->tile_size_x,
7194 0,
7195 tile.height,
7196 pixel_data_size,
7197 channels,
7198 channel_offset_list,
7199 err, compression_param);
7200 if (!ret) {
7201 invalid_data = true;
7202 continue;
7203 }
7204 if (data_list[data_idx].size() <= data_header_size) {
7205 invalid_data = true;
7206 continue;
7207 }
7208
7209 int data_len = static_cast<int>(data_list[data_idx].size() - data_header_size);
7210 // tileX, tileY, levelX, levelY // pixel_data_size(int)
7211 memcpy(&data_list[data_idx][0], &x_tile, sizeof(int));
7212 memcpy(&data_list[data_idx][4], &y_tile, sizeof(int));
7213 memcpy(&data_list[data_idx][8], &level_image->level_x, sizeof(int));
7214 memcpy(&data_list[data_idx][12], &level_image->level_y, sizeof(int));
7215 memcpy(&data_list[data_idx][16], &data_len, sizeof(int));
7216
7217 swap4(reinterpret_cast<int*>(&data_list[data_idx][0]));
7218 swap4(reinterpret_cast<int*>(&data_list[data_idx][4]));
7219 swap4(reinterpret_cast<int*>(&data_list[data_idx][8]));
7220 swap4(reinterpret_cast<int*>(&data_list[data_idx][12]));
7221 swap4(reinterpret_cast<int*>(&data_list[data_idx][16]));
7222
7223#if TINYEXR_HAS_CXX11 && (TINYEXR_USE_THREAD > 0)
7224 }
7225 }));
7226 }
7227
7228 for (auto& t : workers) {
7229 t.join();
7230 }
7231#else
7232 } // omp parallel
7233#endif
7234
7235 if (invalid_data) {
7236 if (err) {
7237 (*err) += "Failed to encode tile data.\n";
7238 }
7240 }
7241 return TINYEXR_SUCCESS;
7242}
7243
7244static int NumScanlines(int compression_type)
7245{
7246 int num_scanlines = 1;
7247 if (compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) {
7248 num_scanlines = 16;
7249 } else if (compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) {
7250 num_scanlines = 32;
7251 } else if (compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) {
7252 num_scanlines = 16;
7253 }
7254 return num_scanlines;
7255}
7256
7257static int EncodeChunk(const EXRImage* exr_image, const EXRHeader* exr_header,
7258 const std::vector<ChannelInfo>& channels,
7259 int num_blocks,
7260 tinyexr_uint64 chunk_offset, // starting offset of current chunk
7261 bool is_multipart,
7262 OffsetData& offset_data, // output block offsets, must be initialized
7263 std::vector<std::vector<unsigned char>>& data_list, // output
7264 tinyexr_uint64& total_size, // output: ending offset of current chunk
7265 std::string* err)
7266{
7267 int num_scanlines = NumScanlines(exr_header->compression_type);
7268
7269 data_list.resize(num_blocks);
7270
7271 std::vector<size_t> channel_offset_list(
7272 static_cast<size_t>(exr_header->num_channels));
7273
7274 int pixel_data_size = 0;
7275 {
7276 size_t channel_offset = 0;
7277 for (size_t c = 0; c < static_cast<size_t>(exr_header->num_channels); c++) {
7278 channel_offset_list[c] = channel_offset;
7279 if (channels[c].requested_pixel_type == TINYEXR_PIXELTYPE_HALF) {
7280 pixel_data_size += sizeof(unsigned short);
7281 channel_offset += sizeof(unsigned short);
7282 } else if (channels[c].requested_pixel_type == TINYEXR_PIXELTYPE_FLOAT) {
7283 pixel_data_size += sizeof(float);
7284 channel_offset += sizeof(float);
7285 } else if (channels[c].requested_pixel_type == TINYEXR_PIXELTYPE_UINT) {
7286 pixel_data_size += sizeof(unsigned int);
7287 channel_offset += sizeof(unsigned int);
7288 } else {
7289 if (err) {
7290 (*err) += "Invalid requested_pixel_type.\n";
7291 }
7293 }
7294 }
7295 }
7296
7297 const void* compression_param = 0;
7298#if TINYEXR_USE_ZFP
7299 tinyexr::ZFPCompressionParam zfp_compression_param;
7300
7301 // Use ZFP compression parameter from custom attributes(if such a parameter
7302 // exists)
7303 {
7304 std::string e;
7305 bool ret = tinyexr::FindZFPCompressionParam(
7306 &zfp_compression_param, exr_header->custom_attributes,
7307 exr_header->num_custom_attributes, &e);
7308
7309 if (!ret) {
7310 // Use predefined compression parameter.
7311 zfp_compression_param.type = 0;
7312 zfp_compression_param.rate = 2;
7313 }
7314 compression_param = &zfp_compression_param;
7315 }
7316#endif
7317
7318 tinyexr_uint64 offset = chunk_offset;
7319 tinyexr_uint64 doffset = is_multipart ? 4u : 0u;
7320
7321 if (exr_image->tiles) {
7322 const EXRImage* level_image = exr_image;
7323 size_t block_idx = 0;
7324 // tinyexr::tinyexr_uint64 block_data_size = 0;
7325 int num_levels = (exr_header->tile_level_mode != TINYEXR_TILE_RIPMAP_LEVELS) ? offset_data.num_x_levels : (offset_data.num_x_levels * offset_data.num_y_levels);
7326 for (int level_index = 0; level_index < num_levels; ++level_index) {
7327 if (!level_image) {
7328 if (err) {
7329 (*err) += "Invalid number of tiled levels for EncodeChunk\n";
7330 }
7332 }
7333
7334 int level_index_from_image = LevelIndex(level_image->level_x, level_image->level_y,
7335 exr_header->tile_level_mode, offset_data.num_x_levels);
7336 if (level_index_from_image < 0) {
7337 if (err) {
7338 (*err) += "Invalid tile level mode\n";
7339 }
7341 }
7342
7343 if (level_index_from_image != level_index) {
7344 if (err) {
7345 (*err) += "Incorrect level ordering in tiled image\n";
7346 }
7348 }
7349 int num_y_tiles = int(offset_data.offsets[level_index].size());
7350 if (num_y_tiles <= 0) {
7351 if (err) {
7352 (*err) += "Invalid Y tile size\n";
7353 }
7355 }
7356
7357 int num_x_tiles = int(offset_data.offsets[level_index][0].size());
7358 if (num_x_tiles <= 0) {
7359 if (err) {
7360 (*err) += "Invalid X tile size\n";
7361 }
7363 }
7364
7365 std::string e;
7366 int ret = EncodeTiledLevel(level_image,
7367 exr_header,
7368 channels,
7369 data_list,
7370 block_idx,
7371 num_x_tiles,
7372 num_y_tiles,
7373 channel_offset_list,
7374 pixel_data_size,
7375 compression_param,
7376 &e);
7377 if (ret != TINYEXR_SUCCESS) {
7378 if (!e.empty() && err) {
7379 (*err) += e;
7380 }
7381 return ret;
7382 }
7383
7384 for (size_t j = 0; j < static_cast<size_t>(num_y_tiles); ++j)
7385 for (size_t i = 0; i < static_cast<size_t>(num_x_tiles); ++i) {
7386 offset_data.offsets[level_index][j][i] = offset;
7387 swap8(reinterpret_cast<tinyexr_uint64*>(&offset_data.offsets[level_index][j][i]));
7388 offset += data_list[block_idx].size() + doffset;
7389 // block_data_size += data_list[block_idx].size();
7390 ++block_idx;
7391 }
7392 level_image = level_image->next_level;
7393 }
7394 TINYEXR_CHECK_AND_RETURN_C(static_cast<int>(block_idx) == num_blocks, TINYEXR_ERROR_INVALID_DATA);
7395 total_size = offset;
7396 } else { // scanlines
7397 std::vector<tinyexr::tinyexr_uint64>& offsets = offset_data.offsets[0][0];
7398
7399#if TINYEXR_HAS_CXX11 && (TINYEXR_USE_THREAD > 0)
7400 std::atomic<bool> invalid_data(false);
7401 std::vector<std::thread> workers;
7402 std::atomic<int> block_count(0);
7403
7404 int num_threads = std::min(std::max(1, int(std::thread::hardware_concurrency())), num_blocks);
7405
7406 for (int t = 0; t < num_threads; t++) {
7407 workers.emplace_back(std::thread([&]() {
7408 int i = 0;
7409 while ((i = block_count++) < num_blocks) {
7410
7411#else
7412 bool invalid_data(false);
7413#if TINYEXR_USE_OPENMP
7414#pragma omp parallel for
7415#endif
7416 for (int i = 0; i < num_blocks; i++) {
7417
7418#endif
7419 int start_y = num_scanlines * i;
7420 int end_Y = (std::min)(num_scanlines * (i + 1), exr_image->height);
7421 int num_lines = end_Y - start_y;
7422
7423 const unsigned char* const* images = static_cast<const unsigned char* const*>(exr_image->images);
7424
7425 data_list[i].resize(2 * sizeof(int));
7426 size_t data_header_size = data_list[i].size();
7427
7428 bool ret = EncodePixelData(data_list[i],
7429 images,
7430 exr_header->compression_type,
7431 0, // increasing y
7432 exr_image->width,
7433 exr_image->height,
7434 exr_image->width,
7435 start_y,
7436 num_lines,
7437 pixel_data_size,
7438 channels,
7439 channel_offset_list,
7440 err,
7441 compression_param);
7442 if (!ret) {
7443 invalid_data = true;
7444 continue; // "break" cannot be used with OpenMP
7445 }
7446 if (data_list[i].size() <= data_header_size) {
7447 invalid_data = true;
7448 continue; // "break" cannot be used with OpenMP
7449 }
7450 int data_len = static_cast<int>(data_list[i].size() - data_header_size);
7451 memcpy(&data_list[i][0], &start_y, sizeof(int));
7452 memcpy(&data_list[i][4], &data_len, sizeof(int));
7453
7454 swap4(reinterpret_cast<int*>(&data_list[i][0]));
7455 swap4(reinterpret_cast<int*>(&data_list[i][4]));
7456#if TINYEXR_HAS_CXX11 && (TINYEXR_USE_THREAD > 0)
7457 }
7458 }));
7459 }
7460
7461 for (auto& t : workers) {
7462 t.join();
7463 }
7464#else
7465 } // omp parallel
7466#endif
7467
7468 if (invalid_data) {
7469 if (err) {
7470 (*err) += "Failed to encode scanline data.\n";
7471 }
7473 }
7474
7475 for (size_t i = 0; i < static_cast<size_t>(num_blocks); i++) {
7476 offsets[i] = offset;
7477 tinyexr::swap8(reinterpret_cast<tinyexr::tinyexr_uint64*>(&offsets[i]));
7478 offset += data_list[i].size() + doffset;
7479 }
7480
7481 total_size = static_cast<size_t>(offset);
7482 }
7483 return TINYEXR_SUCCESS;
7484}
7485
7486// can save a single or multi-part image (no deep* formats)
7487static size_t SaveEXRNPartImageToMemory(const EXRImage* exr_images,
7488 const EXRHeader** exr_headers,
7489 unsigned int num_parts,
7490 unsigned char** memory_out, const char** err)
7491{
7492 if (exr_images == NULL || exr_headers == NULL || num_parts == 0 || memory_out == NULL) {
7493 SetErrorMessage("Invalid argument for SaveEXRNPartImageToMemory",
7494 err);
7495 return 0;
7496 }
7497 {
7498 for (unsigned int i = 0; i < num_parts; ++i) {
7499 if (exr_headers[i]->compression_type < 0) {
7500 SetErrorMessage("Invalid argument for SaveEXRNPartImageToMemory",
7501 err);
7502 return 0;
7503 }
7504#if !TINYEXR_USE_PIZ
7505 if (exr_headers[i]->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) {
7506 SetErrorMessage("PIZ compression is not supported in this build",
7507 err);
7508 return 0;
7509 }
7510#endif
7511 if (exr_headers[i]->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) {
7512#if !TINYEXR_USE_ZFP
7513 SetErrorMessage("ZFP compression is not supported in this build",
7514 err);
7515 return 0;
7516#else
7517 // All channels must be fp32.
7518 // No fp16 support in ZFP atm(as of 2023 June)
7519 // https://github.com/LLNL/fpzip/issues/2
7520 for (int c = 0; c < exr_headers[i]->num_channels; ++c) {
7521 if (exr_headers[i]->requested_pixel_types[c] != TINYEXR_PIXELTYPE_FLOAT) {
7522 SetErrorMessage("Pixel type must be FLOAT for ZFP compression",
7523 err);
7524 return 0;
7525 }
7526 }
7527#endif
7528 }
7529 }
7530 }
7531
7532 std::vector<unsigned char> memory;
7533
7534 // Header
7535 {
7536 const char header[] = { 0x76, 0x2f, 0x31, 0x01 };
7537 memory.insert(memory.end(), header, header + 4);
7538 }
7539
7540 // Version
7541 // using value from the first header
7542 int long_name = exr_headers[0]->long_name;
7543 {
7544 char marker[] = { 2, 0, 0, 0 };
7545 /* @todo
7546 if (exr_header->non_image) {
7547 marker[1] |= 0x8;
7548 }
7549 */
7550 // tiled
7551 if (num_parts == 1 && exr_images[0].tiles) {
7552 marker[1] |= 0x2;
7553 }
7554 // long_name
7555 if (long_name) {
7556 marker[1] |= 0x4;
7557 }
7558 // multipart
7559 if (num_parts > 1) {
7560 marker[1] |= 0x10;
7561 }
7562 memory.insert(memory.end(), marker, marker + 4);
7563 }
7564
7565 int total_chunk_count = 0;
7566 std::vector<int> chunk_count(num_parts);
7567 std::vector<OffsetData> offset_data(num_parts);
7568 for (unsigned int i = 0; i < num_parts; ++i) {
7569 if (!exr_images[i].tiles) {
7570 int num_scanlines = NumScanlines(exr_headers[i]->compression_type);
7571 chunk_count[i] = (exr_images[i].height + num_scanlines - 1) / num_scanlines;
7572 InitSingleResolutionOffsets(offset_data[i], chunk_count[i]);
7573 total_chunk_count += chunk_count[i];
7574 } else {
7575 {
7576 std::vector<int> num_x_tiles, num_y_tiles;
7577 if (!PrecalculateTileInfo(num_x_tiles, num_y_tiles, exr_headers[i])) {
7578 SetErrorMessage("Failed to precalculate Tile info",
7579 err);
7581 }
7582 int ntiles = InitTileOffsets(offset_data[i], exr_headers[i], num_x_tiles, num_y_tiles);
7583 if (ntiles > 0) {
7584 chunk_count[i] = ntiles;
7585 } else {
7586 SetErrorMessage("Failed to compute Tile offsets",
7587 err);
7589 }
7590 total_chunk_count += chunk_count[i];
7591 }
7592 }
7593 }
7594 // Write attributes to memory buffer.
7595 std::vector<std::vector<tinyexr::ChannelInfo>> channels(num_parts);
7596 {
7597 std::set<std::string> partnames;
7598 for (unsigned int i = 0; i < num_parts; ++i) {
7599 // channels
7600 {
7601 std::vector<unsigned char> data;
7602
7603 for (int c = 0; c < exr_headers[i]->num_channels; c++) {
7604 tinyexr::ChannelInfo info;
7605 info.p_linear = 0;
7606 info.pixel_type = exr_headers[i]->pixel_types[c];
7607 info.requested_pixel_type = exr_headers[i]->requested_pixel_types[c];
7608 info.x_sampling = 1;
7609 info.y_sampling = 1;
7610 info.name = std::string(exr_headers[i]->channels[c].name);
7611 channels[i].push_back(info);
7612 }
7613
7614 tinyexr::WriteChannelInfo(data, channels[i]);
7615
7616 tinyexr::WriteAttributeToMemory(&memory, "channels", "chlist", &data.at(0),
7617 static_cast<int>(data.size()));
7618 }
7619
7620 {
7621 int comp = exr_headers[i]->compression_type;
7622 swap4(&comp);
7623 WriteAttributeToMemory(
7624 &memory, "compression", "compression",
7625 reinterpret_cast<const unsigned char*>(&comp), 1);
7626 }
7627
7628 {
7629 int data[4] = { 0, 0, exr_images[i].width - 1, exr_images[i].height - 1 };
7630 swap4(&data[0]);
7631 swap4(&data[1]);
7632 swap4(&data[2]);
7633 swap4(&data[3]);
7634 WriteAttributeToMemory(
7635 &memory, "dataWindow", "box2i",
7636 reinterpret_cast<const unsigned char*>(data), sizeof(int) * 4);
7637
7638 int data0[4] = { 0, 0, exr_images[0].width - 1, exr_images[0].height - 1 };
7639 swap4(&data0[0]);
7640 swap4(&data0[1]);
7641 swap4(&data0[2]);
7642 swap4(&data0[3]);
7643 // Note: must be the same across parts (currently, using value from the first header)
7644 WriteAttributeToMemory(
7645 &memory, "displayWindow", "box2i",
7646 reinterpret_cast<const unsigned char*>(data0), sizeof(int) * 4);
7647 }
7648
7649 {
7650 unsigned char line_order = 0; // @fixme { read line_order from EXRHeader }
7651 WriteAttributeToMemory(&memory, "lineOrder", "lineOrder",
7652 &line_order, 1);
7653 }
7654
7655 {
7656 // Note: must be the same across parts
7657 float aspectRatio = 1.0f;
7658 swap4(&aspectRatio);
7659 WriteAttributeToMemory(
7660 &memory, "pixelAspectRatio", "float",
7661 reinterpret_cast<const unsigned char*>(&aspectRatio), sizeof(float));
7662 }
7663
7664 {
7665 float center[2] = { 0.0f, 0.0f };
7666 swap4(&center[0]);
7667 swap4(&center[1]);
7668 WriteAttributeToMemory(
7669 &memory, "screenWindowCenter", "v2f",
7670 reinterpret_cast<const unsigned char*>(center), 2 * sizeof(float));
7671 }
7672
7673 {
7674 float w = 1.0f;
7675 swap4(&w);
7676 WriteAttributeToMemory(&memory, "screenWindowWidth", "float",
7677 reinterpret_cast<const unsigned char*>(&w),
7678 sizeof(float));
7679 }
7680
7681 if (exr_images[i].tiles) {
7682 unsigned char tile_mode = static_cast<unsigned char>(exr_headers[i]->tile_level_mode & 0x3);
7683 if (exr_headers[i]->tile_rounding_mode)
7684 tile_mode |= (1u << 4u);
7685 // unsigned char data[9] = { 0, 0, 0, 0, 0, 0, 0, 0, 0 };
7686 unsigned int datai[3] = { 0, 0, 0 };
7687 unsigned char* data = reinterpret_cast<unsigned char*>(&datai[0]);
7688 datai[0] = static_cast<unsigned int>(exr_headers[i]->tile_size_x);
7689 datai[1] = static_cast<unsigned int>(exr_headers[i]->tile_size_y);
7690 data[8] = tile_mode;
7691 swap4(reinterpret_cast<unsigned int*>(&data[0]));
7692 swap4(reinterpret_cast<unsigned int*>(&data[4]));
7693 WriteAttributeToMemory(
7694 &memory, "tiles", "tiledesc",
7695 reinterpret_cast<const unsigned char*>(data), 9);
7696 }
7697
7698 // must be present for multi-part files - according to spec.
7699 if (num_parts > 1) {
7700 // name
7701 {
7702 size_t len = 0;
7703 if ((len = strlen(exr_headers[i]->name)) > 0) {
7704#if TINYEXR_HAS_CXX11
7705 partnames.emplace(exr_headers[i]->name);
7706#else
7707 partnames.insert(std::string(exr_headers[i]->name));
7708#endif
7709 if (partnames.size() != i + 1) {
7710 SetErrorMessage("'name' attributes must be unique for a multi-part file", err);
7711 return 0;
7712 }
7713 WriteAttributeToMemory(
7714 &memory, "name", "string",
7715 reinterpret_cast<const unsigned char*>(exr_headers[i]->name),
7716 static_cast<int>(len));
7717 } else {
7718 SetErrorMessage("Invalid 'name' attribute for a multi-part file", err);
7719 return 0;
7720 }
7721 }
7722 // type
7723 {
7724 const char* type = "scanlineimage";
7725 if (exr_images[i].tiles)
7726 type = "tiledimage";
7727 WriteAttributeToMemory(
7728 &memory, "type", "string",
7729 reinterpret_cast<const unsigned char*>(type),
7730 static_cast<int>(strlen(type)));
7731 }
7732 // chunkCount
7733 {
7734 WriteAttributeToMemory(
7735 &memory, "chunkCount", "int",
7736 reinterpret_cast<const unsigned char*>(&chunk_count[i]),
7737 4);
7738 }
7739 }
7740
7741 // Custom attributes
7742 if (exr_headers[i]->num_custom_attributes > 0) {
7743 for (int j = 0; j < exr_headers[i]->num_custom_attributes; j++) {
7744 tinyexr::WriteAttributeToMemory(
7745 &memory, exr_headers[i]->custom_attributes[j].name,
7746 exr_headers[i]->custom_attributes[j].type,
7747 reinterpret_cast<const unsigned char*>(
7748 exr_headers[i]->custom_attributes[j].value),
7749 exr_headers[i]->custom_attributes[j].size);
7750 }
7751 }
7752
7753 { // end of header
7754 memory.push_back(0);
7755 }
7756 }
7757 }
7758 if (num_parts > 1) {
7759 // end of header list
7760 memory.push_back(0);
7761 }
7762
7763 tinyexr_uint64 chunk_offset = memory.size() + size_t(total_chunk_count) * sizeof(tinyexr_uint64);
7764
7765 tinyexr_uint64 total_size = 0;
7766 std::vector<std::vector<std::vector<unsigned char>>> data_lists(num_parts);
7767 for (unsigned int i = 0; i < num_parts; ++i) {
7768 std::string e;
7769 int ret = EncodeChunk(&exr_images[i], exr_headers[i],
7770 channels[i],
7771 chunk_count[i],
7772 // starting offset of current chunk after part-number
7773 chunk_offset,
7774 num_parts > 1,
7775 offset_data[i], // output: block offsets, must be initialized
7776 data_lists[i], // output
7777 total_size, // output
7778 &e);
7779 if (ret != TINYEXR_SUCCESS) {
7780 if (!e.empty()) {
7781 tinyexr::SetErrorMessage(e, err);
7782 }
7783 return 0;
7784 }
7785 chunk_offset = total_size;
7786 }
7787
7788 // Allocating required memory
7789 if (total_size == 0) { // something went wrong
7790 tinyexr::SetErrorMessage("Output memory size is zero", err);
7792 }
7793 (*memory_out) = static_cast<unsigned char*>(malloc(size_t(total_size)));
7794
7795 // Writing header
7796 memcpy((*memory_out), &memory[0], memory.size());
7797 unsigned char* memory_ptr = *memory_out + memory.size();
7798 size_t sum = memory.size();
7799
7800 // Writing offset data for chunks
7801 for (unsigned int i = 0; i < num_parts; ++i) {
7802 if (exr_images[i].tiles) {
7803 const EXRImage* level_image = &exr_images[i];
7804 int num_levels = (exr_headers[i]->tile_level_mode != TINYEXR_TILE_RIPMAP_LEVELS) ? offset_data[i].num_x_levels : (offset_data[i].num_x_levels * offset_data[i].num_y_levels);
7805 for (int level_index = 0; level_index < num_levels; ++level_index) {
7806 for (size_t j = 0; j < offset_data[i].offsets[level_index].size(); ++j) {
7807 size_t num_bytes = sizeof(tinyexr_uint64) * offset_data[i].offsets[level_index][j].size();
7808 sum += num_bytes;
7809 if (sum > total_size) {
7810 tinyexr::SetErrorMessage("Invalid offset bytes in Tiled Part image.", err);
7812 }
7813
7814 memcpy(memory_ptr,
7815 reinterpret_cast<unsigned char*>(&offset_data[i].offsets[level_index][j][0]),
7816 num_bytes);
7817 memory_ptr += num_bytes;
7818 }
7819 level_image = level_image->next_level;
7820 }
7821 } else {
7822 size_t num_bytes = sizeof(tinyexr::tinyexr_uint64) * static_cast<size_t>(chunk_count[i]);
7823 sum += num_bytes;
7824 if (sum > total_size) {
7825 tinyexr::SetErrorMessage("Invalid offset bytes in Part image.", err);
7827 }
7828 std::vector<tinyexr::tinyexr_uint64>& offsets = offset_data[i].offsets[0][0];
7829 memcpy(memory_ptr, reinterpret_cast<unsigned char*>(&offsets[0]), num_bytes);
7830 memory_ptr += num_bytes;
7831 }
7832 }
7833
7834 // Writing chunk data
7835 for (unsigned int i = 0; i < num_parts; ++i) {
7836 for (size_t j = 0; j < static_cast<size_t>(chunk_count[i]); ++j) {
7837 if (num_parts > 1) {
7838 sum += 4;
7839 if (sum > total_size) {
7840 tinyexr::SetErrorMessage("Buffer overrun in reading Part image chunk data.", err);
7842 }
7843 unsigned int part_number = i;
7844 swap4(&part_number);
7845 memcpy(memory_ptr, &part_number, 4);
7846 memory_ptr += 4;
7847 }
7848 sum += data_lists[i][j].size();
7849 if (sum > total_size) {
7850 tinyexr::SetErrorMessage("Buffer overrun in reading Part image chunk data.", err);
7852 }
7853 memcpy(memory_ptr, &data_lists[i][j][0], data_lists[i][j].size());
7854 memory_ptr += data_lists[i][j].size();
7855 }
7856 }
7857
7858 if (sum != total_size) {
7859 tinyexr::SetErrorMessage("Corrupted Part image chunk data.", err);
7861 }
7862
7863 return size_t(total_size); // OK
7864}
7865
7866#ifdef __clang__
7867#pragma clang diagnostic pop
7868#endif
7869
7870} // tinyexr
7871
7872size_t SaveEXRImageToMemory(const EXRImage* exr_image,
7873 const EXRHeader* exr_header,
7874 unsigned char** memory_out, const char** err)
7875{
7876 return tinyexr::SaveEXRNPartImageToMemory(exr_image, &exr_header, 1, memory_out, err);
7877}
7878
7879int SaveEXRImageToFile(const EXRImage* exr_image, const EXRHeader* exr_header,
7880 const char* filename, const char** err)
7881{
7882 if (exr_image == NULL || filename == NULL || exr_header->compression_type < 0) {
7883 tinyexr::SetErrorMessage("Invalid argument for SaveEXRImageToFile", err);
7885 }
7886
7887#if !TINYEXR_USE_PIZ
7888 if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) {
7889 tinyexr::SetErrorMessage("PIZ compression is not supported in this build",
7890 err);
7892 }
7893#endif
7894
7895#if !TINYEXR_USE_ZFP
7896 if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) {
7897 tinyexr::SetErrorMessage("ZFP compression is not supported in this build",
7898 err);
7900 }
7901#endif
7902
7903 FILE* fp = NULL;
7904#ifdef _WIN32
7905#if defined(_MSC_VER) || (defined(MINGW_HAS_SECURE_API) && MINGW_HAS_SECURE_API) // MSVC, MinGW GCC, or Clang
7906 errno_t errcode = _wfopen_s(&fp, tinyexr::UTF8ToWchar(filename).c_str(), L"wb");
7907 if (errcode != 0) {
7908 tinyexr::SetErrorMessage("Cannot write a file: " + std::string(filename),
7909 err);
7911 }
7912#else
7913 // Unknown compiler or MinGW without MINGW_HAS_SECURE_API.
7914 fp = fopen(filename, "wb");
7915#endif
7916#else
7917 fp = fopen(filename, "wb");
7918#endif
7919 if (!fp) {
7920 tinyexr::SetErrorMessage("Cannot write a file: " + std::string(filename),
7921 err);
7923 }
7924
7925 unsigned char* mem = NULL;
7926 size_t mem_size = SaveEXRImageToMemory(exr_image, exr_header, &mem, err);
7927 if (mem_size == 0) {
7928 fclose(fp);
7930 }
7931
7932 size_t written_size = 0;
7933 if ((mem_size > 0) && mem) {
7934 written_size = fwrite(mem, 1, mem_size, fp);
7935 }
7936 free(mem);
7937
7938 fclose(fp);
7939
7940 if (written_size != mem_size) {
7941 tinyexr::SetErrorMessage("Cannot write a file", err);
7943 }
7944
7945 return TINYEXR_SUCCESS;
7946}
7947
7948size_t SaveEXRMultipartImageToMemory(const EXRImage* exr_images,
7949 const EXRHeader** exr_headers,
7950 unsigned int num_parts,
7951 unsigned char** memory_out, const char** err)
7952{
7953 if (exr_images == NULL || exr_headers == NULL || num_parts < 2 || memory_out == NULL) {
7954 tinyexr::SetErrorMessage("Invalid argument for SaveEXRNPartImageToMemory",
7955 err);
7956 return 0;
7957 }
7958 return tinyexr::SaveEXRNPartImageToMemory(exr_images, exr_headers, num_parts, memory_out, err);
7959}
7960
7961int SaveEXRMultipartImageToFile(const EXRImage* exr_images,
7962 const EXRHeader** exr_headers,
7963 unsigned int num_parts,
7964 const char* filename,
7965 const char** err)
7966{
7967 if (exr_images == NULL || exr_headers == NULL || num_parts < 2) {
7968 tinyexr::SetErrorMessage("Invalid argument for SaveEXRMultipartImageToFile",
7969 err);
7971 }
7972
7973 FILE* fp = NULL;
7974#ifdef _WIN32
7975#if defined(_MSC_VER) || (defined(MINGW_HAS_SECURE_API) && MINGW_HAS_SECURE_API) // MSVC, MinGW GCC, or Clang.
7976 errno_t errcode = _wfopen_s(&fp, tinyexr::UTF8ToWchar(filename).c_str(), L"wb");
7977 if (errcode != 0) {
7978 tinyexr::SetErrorMessage("Cannot write a file: " + std::string(filename),
7979 err);
7981 }
7982#else
7983 // Unknown compiler or MinGW without MINGW_HAS_SECURE_API.
7984 fp = fopen(filename, "wb");
7985#endif
7986#else
7987 fp = fopen(filename, "wb");
7988#endif
7989 if (!fp) {
7990 tinyexr::SetErrorMessage("Cannot write a file: " + std::string(filename),
7991 err);
7993 }
7994
7995 unsigned char* mem = NULL;
7996 size_t mem_size = SaveEXRMultipartImageToMemory(exr_images, exr_headers, num_parts, &mem, err);
7997 if (mem_size == 0) {
7998 fclose(fp);
8000 }
8001
8002 size_t written_size = 0;
8003 if ((mem_size > 0) && mem) {
8004 written_size = fwrite(mem, 1, mem_size, fp);
8005 }
8006 free(mem);
8007
8008 fclose(fp);
8009
8010 if (written_size != mem_size) {
8011 tinyexr::SetErrorMessage("Cannot write a file", err);
8013 }
8014
8015 return TINYEXR_SUCCESS;
8016}
8017
8018int LoadDeepEXR(DeepImage* deep_image, const char* filename, const char** err)
8019{
8020 if (deep_image == NULL) {
8021 tinyexr::SetErrorMessage("Invalid argument for LoadDeepEXR", err);
8023 }
8024
8025 MemoryMappedFile file(filename);
8026 if (!file.valid()) {
8027 tinyexr::SetErrorMessage("Cannot read file " + std::string(filename), err);
8029 }
8030
8031 if (file.size == 0) {
8032 tinyexr::SetErrorMessage("File size is zero : " + std::string(filename),
8033 err);
8035 }
8036
8037 const char* head = reinterpret_cast<const char*>(file.data);
8038 const char* marker = reinterpret_cast<const char*>(file.data);
8039
8040 // Header check.
8041 {
8042 const char header[] = { 0x76, 0x2f, 0x31, 0x01 };
8043
8044 if (memcmp(marker, header, 4) != 0) {
8045 tinyexr::SetErrorMessage("Invalid magic number", err);
8047 }
8048 marker += 4;
8049 }
8050
8051 // Version, scanline.
8052 {
8053 // ver 2.0, scanline, deep bit on(0x800)
8054 // must be [2, 0, 0, 0]
8055 if (marker[0] != 2 || marker[1] != 8 || marker[2] != 0 || marker[3] != 0) {
8056 tinyexr::SetErrorMessage("Unsupported version or scanline", err);
8058 }
8059
8060 marker += 4;
8061 }
8062
8063 int dx = -1;
8064 int dy = -1;
8065 int dw = -1;
8066 int dh = -1;
8067 int num_scanline_blocks = 1; // 16 for ZIP compression.
8068 int compression_type = -1;
8069 int num_channels = -1;
8070 std::vector<tinyexr::ChannelInfo> channels;
8071
8072 // Read attributes
8073 size_t size = file.size - tinyexr::kEXRVersionSize;
8074 for (;;) {
8075 if (0 == size) {
8077 } else if (marker[0] == '\0') {
8078 marker++;
8079 size--;
8080 break;
8081 }
8082
8083 std::string attr_name;
8084 std::string attr_type;
8085 std::vector<unsigned char> data;
8086 size_t marker_size;
8087 if (!tinyexr::ReadAttribute(&attr_name, &attr_type, &data, &marker_size,
8088 marker, size)) {
8089 std::stringstream ss;
8090 ss << "Failed to parse attribute\n";
8091 tinyexr::SetErrorMessage(ss.str(), err);
8093 }
8094 marker += marker_size;
8095 size -= marker_size;
8096
8097 if (attr_name.compare("compression") == 0) {
8098 compression_type = data[0];
8099 if (compression_type > TINYEXR_COMPRESSIONTYPE_PIZ) {
8100 std::stringstream ss;
8101 ss << "Unsupported compression type : " << compression_type;
8102 tinyexr::SetErrorMessage(ss.str(), err);
8104 }
8105
8106 if (compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) {
8107 num_scanline_blocks = 16;
8108 }
8109
8110 } else if (attr_name.compare("channels") == 0) {
8111 // name: zero-terminated string, from 1 to 255 bytes long
8112 // pixel type: int, possible values are: UINT = 0 HALF = 1 FLOAT = 2
8113 // pLinear: unsigned char, possible values are 0 and 1
8114 // reserved: three chars, should be zero
8115 // xSampling: int
8116 // ySampling: int
8117
8118 if (!tinyexr::ReadChannelInfo(channels, data)) {
8119 tinyexr::SetErrorMessage("Failed to parse channel info", err);
8121 }
8122
8123 num_channels = static_cast<int>(channels.size());
8124
8125 if (num_channels < 1) {
8126 tinyexr::SetErrorMessage("Invalid channels format", err);
8128 }
8129
8130 } else if (attr_name.compare("dataWindow") == 0) {
8131 memcpy(&dx, &data.at(0), sizeof(int));
8132 memcpy(&dy, &data.at(4), sizeof(int));
8133 memcpy(&dw, &data.at(8), sizeof(int));
8134 memcpy(&dh, &data.at(12), sizeof(int));
8135 tinyexr::swap4(&dx);
8136 tinyexr::swap4(&dy);
8137 tinyexr::swap4(&dw);
8138 tinyexr::swap4(&dh);
8139
8140 } else if (attr_name.compare("displayWindow") == 0) {
8141 int x;
8142 int y;
8143 int w;
8144 int h;
8145 memcpy(&x, &data.at(0), sizeof(int));
8146 memcpy(&y, &data.at(4), sizeof(int));
8147 memcpy(&w, &data.at(8), sizeof(int));
8148 memcpy(&h, &data.at(12), sizeof(int));
8149 tinyexr::swap4(&x);
8150 tinyexr::swap4(&y);
8151 tinyexr::swap4(&w);
8152 tinyexr::swap4(&h);
8153 }
8154 }
8155
8156 TINYEXR_CHECK_AND_RETURN_C(dx >= 0, TINYEXR_ERROR_INVALID_DATA);
8157 TINYEXR_CHECK_AND_RETURN_C(dy >= 0, TINYEXR_ERROR_INVALID_DATA);
8158 TINYEXR_CHECK_AND_RETURN_C(dw >= 0, TINYEXR_ERROR_INVALID_DATA);
8159 TINYEXR_CHECK_AND_RETURN_C(dh >= 0, TINYEXR_ERROR_INVALID_DATA);
8160 TINYEXR_CHECK_AND_RETURN_C(num_channels >= 1, TINYEXR_ERROR_INVALID_DATA);
8161
8162 int data_width = dw - dx + 1;
8163 int data_height = dh - dy + 1;
8164
8165 // Read offset tables.
8166 int num_blocks = data_height / num_scanline_blocks;
8167 if (num_blocks * num_scanline_blocks < data_height) {
8168 num_blocks++;
8169 }
8170
8171 std::vector<tinyexr::tinyexr_int64> offsets(static_cast<size_t>(num_blocks));
8172
8173 for (size_t y = 0; y < static_cast<size_t>(num_blocks); y++) {
8174 tinyexr::tinyexr_int64 offset;
8175 memcpy(&offset, marker, sizeof(tinyexr::tinyexr_int64));
8176 tinyexr::swap8(reinterpret_cast<tinyexr::tinyexr_uint64*>(&offset));
8177 marker += sizeof(tinyexr::tinyexr_int64); // = 8
8178 offsets[y] = offset;
8179 }
8180
8181#if TINYEXR_USE_PIZ
8182 if ((compression_type == TINYEXR_COMPRESSIONTYPE_NONE) || (compression_type == TINYEXR_COMPRESSIONTYPE_RLE) || (compression_type == TINYEXR_COMPRESSIONTYPE_ZIPS) || (compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) || (compression_type == TINYEXR_COMPRESSIONTYPE_PIZ)) {
8183#else
8184 if ((compression_type == TINYEXR_COMPRESSIONTYPE_NONE) || (compression_type == TINYEXR_COMPRESSIONTYPE_RLE) || (compression_type == TINYEXR_COMPRESSIONTYPE_ZIPS) || (compression_type == TINYEXR_COMPRESSIONTYPE_ZIP)) {
8185#endif
8186 // OK
8187 } else {
8188 tinyexr::SetErrorMessage("Unsupported compression format", err);
8190 }
8191
8192 deep_image->image = static_cast<float***>(
8193 malloc(sizeof(float**) * static_cast<size_t>(num_channels)));
8194 for (int c = 0; c < num_channels; c++) {
8195 deep_image->image[c] = static_cast<float**>(
8196 malloc(sizeof(float*) * static_cast<size_t>(data_height)));
8197 for (int y = 0; y < data_height; y++) {
8198 }
8199 }
8200
8201 deep_image->offset_table = static_cast<int**>(
8202 malloc(sizeof(int*) * static_cast<size_t>(data_height)));
8203 for (int y = 0; y < data_height; y++) {
8204 deep_image->offset_table[y] = static_cast<int*>(
8205 malloc(sizeof(int) * static_cast<size_t>(data_width)));
8206 }
8207
8208 for (size_t y = 0; y < static_cast<size_t>(num_blocks); y++) {
8209 const unsigned char* data_ptr = reinterpret_cast<const unsigned char*>(head + offsets[y]);
8210
8211 // int: y coordinate
8212 // int64: packed size of pixel offset table
8213 // int64: packed size of sample data
8214 // int64: unpacked size of sample data
8215 // compressed pixel offset table
8216 // compressed sample data
8217 int line_no;
8218 tinyexr::tinyexr_int64 packedOffsetTableSize;
8219 tinyexr::tinyexr_int64 packedSampleDataSize;
8220 tinyexr::tinyexr_int64 unpackedSampleDataSize;
8221 memcpy(&line_no, data_ptr, sizeof(int));
8222 memcpy(&packedOffsetTableSize, data_ptr + 4,
8223 sizeof(tinyexr::tinyexr_int64));
8224 memcpy(&packedSampleDataSize, data_ptr + 12,
8225 sizeof(tinyexr::tinyexr_int64));
8226 memcpy(&unpackedSampleDataSize, data_ptr + 20,
8227 sizeof(tinyexr::tinyexr_int64));
8228
8229 tinyexr::swap4(&line_no);
8230 tinyexr::swap8(
8231 reinterpret_cast<tinyexr::tinyexr_uint64*>(&packedOffsetTableSize));
8232 tinyexr::swap8(
8233 reinterpret_cast<tinyexr::tinyexr_uint64*>(&packedSampleDataSize));
8234 tinyexr::swap8(
8235 reinterpret_cast<tinyexr::tinyexr_uint64*>(&unpackedSampleDataSize));
8236
8237 std::vector<int> pixelOffsetTable(static_cast<size_t>(data_width));
8238
8239 // decode pixel offset table.
8240 {
8241 unsigned long dstLen = static_cast<unsigned long>(pixelOffsetTable.size() * sizeof(int));
8242 if (!tinyexr::DecompressZip(
8243 reinterpret_cast<unsigned char*>(&pixelOffsetTable.at(0)),
8244 &dstLen, data_ptr + 28,
8245 static_cast<unsigned long>(packedOffsetTableSize))) {
8246 return false;
8247 }
8248
8249 TINYEXR_CHECK_AND_RETURN_C(dstLen == pixelOffsetTable.size() * sizeof(int), TINYEXR_ERROR_INVALID_DATA);
8250 for (size_t i = 0; i < static_cast<size_t>(data_width); i++) {
8251 deep_image->offset_table[y][i] = pixelOffsetTable[i];
8252 }
8253 }
8254
8255 std::vector<unsigned char> sample_data(
8256 static_cast<size_t>(unpackedSampleDataSize));
8257
8258 // decode sample data.
8259 {
8260 unsigned long dstLen = static_cast<unsigned long>(unpackedSampleDataSize);
8261 if (dstLen) {
8262 if (!tinyexr::DecompressZip(
8263 reinterpret_cast<unsigned char*>(&sample_data.at(0)), &dstLen,
8264 data_ptr + 28 + packedOffsetTableSize,
8265 static_cast<unsigned long>(packedSampleDataSize))) {
8266 return false;
8267 }
8268 TINYEXR_CHECK_AND_RETURN_C(dstLen == static_cast<unsigned long>(unpackedSampleDataSize), TINYEXR_ERROR_INVALID_DATA);
8269 }
8270 }
8271
8272 // decode sample
8273 int sampleSize = -1;
8274 std::vector<int> channel_offset_list(static_cast<size_t>(num_channels));
8275 {
8276 int channel_offset = 0;
8277 for (size_t i = 0; i < static_cast<size_t>(num_channels); i++) {
8278 channel_offset_list[i] = channel_offset;
8279 if (channels[i].pixel_type == TINYEXR_PIXELTYPE_UINT) { // UINT
8280 channel_offset += 4;
8281 } else if (channels[i].pixel_type == TINYEXR_PIXELTYPE_HALF) { // half
8282 channel_offset += 2;
8283 } else if (channels[i].pixel_type == TINYEXR_PIXELTYPE_FLOAT) { // float
8284 channel_offset += 4;
8285 } else {
8286 tinyexr::SetErrorMessage("Invalid pixel_type in chnnels.", err);
8288 }
8289 }
8290 sampleSize = channel_offset;
8291 }
8292 TINYEXR_CHECK_AND_RETURN_C(sampleSize >= 2, TINYEXR_ERROR_INVALID_DATA);
8293
8294 TINYEXR_CHECK_AND_RETURN_C(static_cast<size_t>(
8295 pixelOffsetTable[static_cast<size_t>(data_width - 1)] * sampleSize)
8296 == sample_data.size(),
8298 int samples_per_line = static_cast<int>(sample_data.size()) / sampleSize;
8299
8300 //
8301 // Alloc memory
8302 //
8303
8304 //
8305 // pixel data is stored as image[channels][pixel_samples]
8306 //
8307 {
8308 tinyexr::tinyexr_uint64 data_offset = 0;
8309 for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) {
8310 deep_image->image[c][y] = static_cast<float*>(
8311 malloc(sizeof(float) * static_cast<size_t>(samples_per_line)));
8312
8313 if (channels[c].pixel_type == 0) { // UINT
8314 for (size_t x = 0; x < static_cast<size_t>(samples_per_line); x++) {
8315 unsigned int ui;
8316 unsigned int* src_ptr = reinterpret_cast<unsigned int*>(
8317 &sample_data.at(size_t(data_offset) + x * sizeof(int)));
8318 tinyexr::cpy4(&ui, src_ptr);
8319 deep_image->image[c][y][x] = static_cast<float>(ui); // @fixme
8320 }
8321 data_offset += sizeof(unsigned int) * static_cast<size_t>(samples_per_line);
8322 } else if (channels[c].pixel_type == 1) { // half
8323 for (size_t x = 0; x < static_cast<size_t>(samples_per_line); x++) {
8324 tinyexr::FP16 f16;
8325 const unsigned short* src_ptr = reinterpret_cast<unsigned short*>(
8326 &sample_data.at(size_t(data_offset) + x * sizeof(short)));
8327 tinyexr::cpy2(&(f16.u), src_ptr);
8328 tinyexr::FP32 f32 = half_to_float(f16);
8329 deep_image->image[c][y][x] = f32.f;
8330 }
8331 data_offset += sizeof(short) * static_cast<size_t>(samples_per_line);
8332 } else { // float
8333 for (size_t x = 0; x < static_cast<size_t>(samples_per_line); x++) {
8334 float f;
8335 const float* src_ptr = reinterpret_cast<float*>(
8336 &sample_data.at(size_t(data_offset) + x * sizeof(float)));
8337 tinyexr::cpy4(&f, src_ptr);
8338 deep_image->image[c][y][x] = f;
8339 }
8340 data_offset += sizeof(float) * static_cast<size_t>(samples_per_line);
8341 }
8342 }
8343 }
8344 } // y
8345
8346 deep_image->width = data_width;
8347 deep_image->height = data_height;
8348
8349 deep_image->channel_names = static_cast<const char**>(
8350 malloc(sizeof(const char*) * static_cast<size_t>(num_channels)));
8351 for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) {
8352#ifdef _WIN32
8353 deep_image->channel_names[c] = _strdup(channels[c].name.c_str());
8354#else
8355 deep_image->channel_names[c] = strdup(channels[c].name.c_str());
8356#endif
8357 }
8358 deep_image->num_channels = num_channels;
8359
8360 return TINYEXR_SUCCESS;
8361}
8362
8363void InitEXRImage(EXRImage* exr_image)
8364{
8365 if (exr_image == NULL) {
8366 return;
8367 }
8368
8369 exr_image->width = 0;
8370 exr_image->height = 0;
8371 exr_image->num_channels = 0;
8372
8373 exr_image->images = NULL;
8374 exr_image->tiles = NULL;
8375 exr_image->next_level = NULL;
8376 exr_image->level_x = 0;
8377 exr_image->level_y = 0;
8378
8379 exr_image->num_tiles = 0;
8380}
8381
8382void FreeEXRErrorMessage(const char* msg)
8383{
8384 if (msg) {
8385 free(reinterpret_cast<void*>(const_cast<char*>(msg)));
8386 }
8387 return;
8388}
8389
8390void InitEXRHeader(EXRHeader* exr_header)
8391{
8392 if (exr_header == NULL) {
8393 return;
8394 }
8395
8396 memset(exr_header, 0, sizeof(EXRHeader));
8397}
8398
8399int FreeEXRHeader(EXRHeader* exr_header)
8400{
8401 if (exr_header == NULL) {
8403 }
8404
8405 if (exr_header->channels) {
8406 free(exr_header->channels);
8407 }
8408
8409 if (exr_header->pixel_types) {
8410 free(exr_header->pixel_types);
8411 }
8412
8413 if (exr_header->requested_pixel_types) {
8414 free(exr_header->requested_pixel_types);
8415 }
8416
8417 for (int i = 0; i < exr_header->num_custom_attributes; i++) {
8418 if (exr_header->custom_attributes[i].value) {
8419 free(exr_header->custom_attributes[i].value);
8420 }
8421 }
8422
8423 if (exr_header->custom_attributes) {
8424 free(exr_header->custom_attributes);
8425 }
8426
8427 EXRSetNameAttr(exr_header, NULL);
8428
8429 return TINYEXR_SUCCESS;
8430}
8431
8432void EXRSetNameAttr(EXRHeader* exr_header, const char* name)
8433{
8434 if (exr_header == NULL) {
8435 return;
8436 }
8437 memset(exr_header->name, 0, 256);
8438 if (name != NULL) {
8439 size_t len = std::min(strlen(name), size_t(255));
8440 if (len) {
8441 memcpy(exr_header->name, name, len);
8442 }
8443 }
8444}
8445
8446int EXRNumLevels(const EXRImage* exr_image)
8447{
8448 if (exr_image == NULL)
8449 return 0;
8450 if (exr_image->images)
8451 return 1; // scanlines
8452 int levels = 1;
8453 const EXRImage* level_image = exr_image;
8454 while ((level_image = level_image->next_level))
8455 ++levels;
8456 return levels;
8457}
8458
8459int FreeEXRImage(EXRImage* exr_image)
8460{
8461 if (exr_image == NULL) {
8463 }
8464
8465 if (exr_image->next_level) {
8466 FreeEXRImage(exr_image->next_level);
8467 delete exr_image->next_level;
8468 }
8469
8470 for (int i = 0; i < exr_image->num_channels; i++) {
8471 if (exr_image->images && exr_image->images[i]) {
8472 free(exr_image->images[i]);
8473 }
8474 }
8475
8476 if (exr_image->images) {
8477 free(exr_image->images);
8478 }
8479
8480 if (exr_image->tiles) {
8481 for (int tid = 0; tid < exr_image->num_tiles; tid++) {
8482 for (int i = 0; i < exr_image->num_channels; i++) {
8483 if (exr_image->tiles[tid].images && exr_image->tiles[tid].images[i]) {
8484 free(exr_image->tiles[tid].images[i]);
8485 }
8486 }
8487 if (exr_image->tiles[tid].images) {
8488 free(exr_image->tiles[tid].images);
8489 }
8490 }
8491 free(exr_image->tiles);
8492 }
8493
8494 return TINYEXR_SUCCESS;
8495}
8496
8497int ParseEXRHeaderFromFile(EXRHeader* exr_header, const EXRVersion* exr_version,
8498 const char* filename, const char** err)
8499{
8500 if (exr_header == NULL || exr_version == NULL || filename == NULL) {
8501 tinyexr::SetErrorMessage("Invalid argument for ParseEXRHeaderFromFile",
8502 err);
8504 }
8505
8506 MemoryMappedFile file(filename);
8507 if (!file.valid()) {
8508 tinyexr::SetErrorMessage("Cannot read file " + std::string(filename), err);
8510 }
8511
8512 return ParseEXRHeaderFromMemory(exr_header, exr_version, file.data, file.size,
8513 err);
8514}
8515
8517 int* num_headers,
8518 const EXRVersion* exr_version,
8519 const unsigned char* memory, size_t size,
8520 const char** err)
8521{
8522 if (memory == NULL || exr_headers == NULL || num_headers == NULL || exr_version == NULL) {
8523 // Invalid argument
8524 tinyexr::SetErrorMessage(
8525 "Invalid argument for ParseEXRMultipartHeaderFromMemory", err);
8527 }
8528
8529 if (size < tinyexr::kEXRVersionSize) {
8530 tinyexr::SetErrorMessage("Data size too short", err);
8532 }
8533
8534 const unsigned char* marker = memory + tinyexr::kEXRVersionSize;
8535 size_t marker_size = size - tinyexr::kEXRVersionSize;
8536
8537 std::vector<tinyexr::HeaderInfo> infos;
8538
8539 for (;;) {
8540 tinyexr::HeaderInfo info;
8541 info.clear();
8542
8543 std::string err_str;
8544 bool empty_header = false;
8545 int ret = ParseEXRHeader(&info, &empty_header, exr_version, &err_str,
8546 marker, marker_size);
8547
8548 if (ret != TINYEXR_SUCCESS) {
8549
8550 // Free malloc-allocated memory here.
8551 for (size_t i = 0; i < info.attributes.size(); i++) {
8552 if (info.attributes[i].value) {
8553 free(info.attributes[i].value);
8554 }
8555 }
8556
8557 tinyexr::SetErrorMessage(err_str, err);
8558 return ret;
8559 }
8560
8561 if (empty_header) {
8562 marker += 1; // skip '\0'
8563 break;
8564 }
8565
8566 // `chunkCount` must exist in the header.
8567 if (info.chunk_count == 0) {
8568
8569 // Free malloc-allocated memory here.
8570 for (size_t i = 0; i < info.attributes.size(); i++) {
8571 if (info.attributes[i].value) {
8572 free(info.attributes[i].value);
8573 }
8574 }
8575
8576 tinyexr::SetErrorMessage(
8577 "`chunkCount' attribute is not found in the header.", err);
8579 }
8580
8581 infos.push_back(info);
8582
8583 // move to next header.
8584 marker += info.header_len;
8585 size -= info.header_len;
8586 }
8587
8588 // allocate memory for EXRHeader and create array of EXRHeader pointers.
8589 (*exr_headers) = static_cast<EXRHeader**>(malloc(sizeof(EXRHeader*) * infos.size()));
8590
8591 int retcode = TINYEXR_SUCCESS;
8592
8593 for (size_t i = 0; i < infos.size(); i++) {
8594 EXRHeader* exr_header = static_cast<EXRHeader*>(malloc(sizeof(EXRHeader)));
8595 memset(exr_header, 0, sizeof(EXRHeader));
8596
8597 std::string warn;
8598 std::string _err;
8599 if (!ConvertHeader(exr_header, infos[i], &warn, &_err)) {
8600
8601 // Free malloc-allocated memory here.
8602 for (size_t k = 0; k < infos[i].attributes.size(); k++) {
8603 if (infos[i].attributes[k].value) {
8604 free(infos[i].attributes[k].value);
8605 }
8606 }
8607
8608 if (!_err.empty()) {
8609 tinyexr::SetErrorMessage(
8610 _err, err);
8611 }
8612 // continue to converting headers
8614 }
8615
8616 exr_header->multipart = exr_version->multipart ? 1 : 0;
8617
8618 (*exr_headers)[i] = exr_header;
8619 }
8620
8621 (*num_headers) = static_cast<int>(infos.size());
8622
8623 return retcode;
8624}
8625
8626int ParseEXRMultipartHeaderFromFile(EXRHeader*** exr_headers, int* num_headers,
8627 const EXRVersion* exr_version,
8628 const char* filename, const char** err)
8629{
8630 if (exr_headers == NULL || num_headers == NULL || exr_version == NULL || filename == NULL) {
8631 tinyexr::SetErrorMessage(
8632 "Invalid argument for ParseEXRMultipartHeaderFromFile()", err);
8634 }
8635
8636 MemoryMappedFile file(filename);
8637 if (!file.valid()) {
8638 tinyexr::SetErrorMessage("Cannot read file " + std::string(filename), err);
8640 }
8641
8643 exr_headers, num_headers, exr_version, file.data, file.size, err);
8644}
8645
8646int ParseEXRVersionFromMemory(EXRVersion* version, const unsigned char* memory,
8647 size_t size)
8648{
8649 if (version == NULL || memory == NULL) {
8651 }
8652
8653 if (size < tinyexr::kEXRVersionSize) {
8655 }
8656
8657 const unsigned char* marker = memory;
8658
8659 // Header check.
8660 {
8661 const char header[] = { 0x76, 0x2f, 0x31, 0x01 };
8662
8663 if (memcmp(marker, header, 4) != 0) {
8665 }
8666 marker += 4;
8667 }
8668
8669 version->tiled = false;
8670 version->long_name = false;
8671 version->non_image = false;
8672 version->multipart = false;
8673
8674 // Parse version header.
8675 {
8676 // must be 2
8677 if (marker[0] != 2) {
8679 }
8680
8681 if (version == NULL) {
8682 return TINYEXR_SUCCESS; // May OK
8683 }
8684
8685 version->version = 2;
8686
8687 if (marker[1] & 0x2) { // 9th bit
8688 version->tiled = true;
8689 }
8690 if (marker[1] & 0x4) { // 10th bit
8691 version->long_name = true;
8692 }
8693 if (marker[1] & 0x8) { // 11th bit
8694 version->non_image = true; // (deep image)
8695 }
8696 if (marker[1] & 0x10) { // 12th bit
8697 version->multipart = true;
8698 }
8699 }
8700
8701 return TINYEXR_SUCCESS;
8702}
8703
8704int ParseEXRVersionFromFile(EXRVersion* version, const char* filename)
8705{
8706 if (filename == NULL) {
8708 }
8709
8710 FILE* fp = NULL;
8711#ifdef _WIN32
8712#if defined(_MSC_VER) || (defined(MINGW_HAS_SECURE_API) && MINGW_HAS_SECURE_API) // MSVC, MinGW GCC, or Clang.
8713 errno_t err = _wfopen_s(&fp, tinyexr::UTF8ToWchar(filename).c_str(), L"rb");
8714 if (err != 0) {
8715 // TODO(syoyo): return wfopen_s erro code
8717 }
8718#else
8719 // Unknown compiler or MinGW without MINGW_HAS_SECURE_API.
8720 fp = fopen(filename, "rb");
8721#endif
8722#else
8723 fp = fopen(filename, "rb");
8724#endif
8725 if (!fp) {
8727 }
8728
8729 // Try to read kEXRVersionSize bytes; if the file is shorter than
8730 // kEXRVersionSize, this will produce an error. This avoids a call to
8731 // fseek(fp, 0, SEEK_END), which is not required to be supported by C
8732 // implementations.
8733 unsigned char buf[tinyexr::kEXRVersionSize];
8734 size_t ret = fread(&buf[0], 1, tinyexr::kEXRVersionSize, fp);
8735 fclose(fp);
8736
8737 if (ret != tinyexr::kEXRVersionSize) {
8739 }
8740
8741 return ParseEXRVersionFromMemory(version, buf, tinyexr::kEXRVersionSize);
8742}
8743
8745 const EXRHeader** exr_headers,
8746 unsigned int num_parts,
8747 const unsigned char* memory,
8748 const size_t size, const char** err)
8749{
8750 if (exr_images == NULL || exr_headers == NULL || num_parts == 0 || memory == NULL || (size <= tinyexr::kEXRVersionSize)) {
8751 tinyexr::SetErrorMessage(
8752 "Invalid argument for LoadEXRMultipartImageFromMemory()", err);
8754 }
8755
8756 // compute total header size.
8757 size_t total_header_size = 0;
8758 for (unsigned int i = 0; i < num_parts; i++) {
8759 if (exr_headers[i]->header_len == 0) {
8760 tinyexr::SetErrorMessage("EXRHeader variable is not initialized.", err);
8762 }
8763
8764 total_header_size += exr_headers[i]->header_len;
8765 }
8766
8767 const char* marker = reinterpret_cast<const char*>(
8768 memory + total_header_size + 4 + 4); // +8 for magic number and version header.
8769
8770 marker += 1; // Skip empty header.
8771
8772 // NOTE 1:
8773 // In multipart image, There is 'part number' before chunk data.
8774 // 4 byte : part number
8775 // 4+ : chunk
8776 //
8777 // NOTE 2:
8778 // EXR spec says 'part number' is 'unsigned long' but actually this is
8779 // 'unsigned int(4 bytes)' in OpenEXR implementation...
8780 // http://www.openexr.com/openexrfilelayout.pdf
8781
8782 // Load chunk offset table.
8783 std::vector<tinyexr::OffsetData> chunk_offset_table_list;
8784 chunk_offset_table_list.reserve(num_parts);
8785 for (size_t i = 0; i < static_cast<size_t>(num_parts); i++) {
8786 chunk_offset_table_list.resize(chunk_offset_table_list.size() + 1);
8787 tinyexr::OffsetData& offset_data = chunk_offset_table_list.back();
8788 if (!exr_headers[i]->tiled || exr_headers[i]->tile_level_mode == TINYEXR_TILE_ONE_LEVEL) {
8789 tinyexr::InitSingleResolutionOffsets(offset_data, size_t(exr_headers[i]->chunk_count));
8790 std::vector<tinyexr::tinyexr_uint64>& offset_table = offset_data.offsets[0][0];
8791
8792 for (size_t c = 0; c < offset_table.size(); c++) {
8793 tinyexr::tinyexr_uint64 offset;
8794 memcpy(&offset, marker, 8);
8795 tinyexr::swap8(&offset);
8796
8797 if (offset >= size) {
8798 tinyexr::SetErrorMessage("Invalid offset size in EXR header chunks.",
8799 err);
8801 }
8802
8803 offset_table[c] = offset + 4; // +4 to skip 'part number'
8804 marker += 8;
8805 }
8806 } else {
8807 {
8808 std::vector<int> num_x_tiles, num_y_tiles;
8809 if (!tinyexr::PrecalculateTileInfo(num_x_tiles, num_y_tiles, exr_headers[i])) {
8810 tinyexr::SetErrorMessage("Invalid tile info.", err);
8812 }
8813 int num_blocks = InitTileOffsets(offset_data, exr_headers[i], num_x_tiles, num_y_tiles);
8814 if (num_blocks != exr_headers[i]->chunk_count) {
8815 tinyexr::SetErrorMessage("Invalid offset table size.", err);
8817 }
8818 }
8819 for (unsigned int l = 0; l < offset_data.offsets.size(); ++l) {
8820 for (unsigned int dy = 0; dy < offset_data.offsets[l].size(); ++dy) {
8821 for (unsigned int dx = 0; dx < offset_data.offsets[l][dy].size(); ++dx) {
8822 tinyexr::tinyexr_uint64 offset;
8823 memcpy(&offset, marker, sizeof(tinyexr::tinyexr_uint64));
8824 tinyexr::swap8(&offset);
8825 if (offset >= size) {
8826 tinyexr::SetErrorMessage("Invalid offset size in EXR header chunks.",
8827 err);
8829 }
8830 offset_data.offsets[l][dy][dx] = offset + 4; // +4 to skip 'part number'
8831 marker += sizeof(tinyexr::tinyexr_uint64); // = 8
8832 }
8833 }
8834 }
8835 }
8836 }
8837
8838 // Decode image.
8839 for (size_t i = 0; i < static_cast<size_t>(num_parts); i++) {
8840 tinyexr::OffsetData& offset_data = chunk_offset_table_list[i];
8841
8842 // First check 'part number' is identical to 'i'
8843 for (unsigned int l = 0; l < offset_data.offsets.size(); ++l)
8844 for (unsigned int dy = 0; dy < offset_data.offsets[l].size(); ++dy)
8845 for (unsigned int dx = 0; dx < offset_data.offsets[l][dy].size(); ++dx) {
8846
8847 const unsigned char* part_number_addr = memory + offset_data.offsets[l][dy][dx] - 4; // -4 to move to 'part number' field.
8848 unsigned int part_no;
8849 memcpy(&part_no, part_number_addr, sizeof(unsigned int)); // 4
8850 tinyexr::swap4(&part_no);
8851
8852 if (part_no != i) {
8853 tinyexr::SetErrorMessage("Invalid `part number' in EXR header chunks.",
8854 err);
8856 }
8857 }
8858
8859 std::string e;
8860 int ret = tinyexr::DecodeChunk(&exr_images[i], exr_headers[i], offset_data,
8861 memory, size, &e);
8862 if (ret != TINYEXR_SUCCESS) {
8863 if (!e.empty()) {
8864 tinyexr::SetErrorMessage(e, err);
8865 }
8866 return ret;
8867 }
8868 }
8869
8870 return TINYEXR_SUCCESS;
8871}
8872
8874 const EXRHeader** exr_headers,
8875 unsigned int num_parts, const char* filename,
8876 const char** err)
8877{
8878 if (exr_images == NULL || exr_headers == NULL || num_parts == 0) {
8879 tinyexr::SetErrorMessage(
8880 "Invalid argument for LoadEXRMultipartImageFromFile", err);
8882 }
8883
8884 MemoryMappedFile file(filename);
8885 if (!file.valid()) {
8886 tinyexr::SetErrorMessage("Cannot read file " + std::string(filename), err);
8888 }
8889
8890 return LoadEXRMultipartImageFromMemory(exr_images, exr_headers, num_parts,
8891 file.data, file.size, err);
8892}
8893
8894int SaveEXRToMemory(const float* data, int width, int height, int components,
8895 const int save_as_fp16, unsigned char** outbuf, const char** err)
8896{
8897
8898 if ((components == 1) || components == 3 || components == 4) {
8899 // OK
8900 } else {
8901 std::stringstream ss;
8902 ss << "Unsupported component value : " << components << std::endl;
8903
8904 tinyexr::SetErrorMessage(ss.str(), err);
8906 }
8907
8908 EXRHeader header;
8909 InitEXRHeader(&header);
8910
8911 if ((width < 16) && (height < 16)) {
8912 // No compression for small image.
8914 } else {
8916 }
8917
8918 EXRImage image;
8919 InitEXRImage(&image);
8920
8921 image.num_channels = components;
8922
8923 std::vector<float> images[4];
8924
8925 if (components == 1) {
8926 images[0].resize(static_cast<size_t>(width * height));
8927 memcpy(images[0].data(), data, sizeof(float) * size_t(width * height));
8928 } else {
8929 images[0].resize(static_cast<size_t>(width * height));
8930 images[1].resize(static_cast<size_t>(width * height));
8931 images[2].resize(static_cast<size_t>(width * height));
8932 images[3].resize(static_cast<size_t>(width * height));
8933
8934 // Split RGB(A)RGB(A)RGB(A)... into R, G and B(and A) layers
8935 for (size_t i = 0; i < static_cast<size_t>(width * height); i++) {
8936 images[0][i] = data[static_cast<size_t>(components) * i + 0];
8937 images[1][i] = data[static_cast<size_t>(components) * i + 1];
8938 images[2][i] = data[static_cast<size_t>(components) * i + 2];
8939 if (components == 4) {
8940 images[3][i] = data[static_cast<size_t>(components) * i + 3];
8941 }
8942 }
8943 }
8944
8945 float* image_ptr[4] = { 0, 0, 0, 0 };
8946 if (components == 4) {
8947 image_ptr[0] = &(images[3].at(0)); // A
8948 image_ptr[1] = &(images[2].at(0)); // B
8949 image_ptr[2] = &(images[1].at(0)); // G
8950 image_ptr[3] = &(images[0].at(0)); // R
8951 } else if (components == 3) {
8952 image_ptr[0] = &(images[2].at(0)); // B
8953 image_ptr[1] = &(images[1].at(0)); // G
8954 image_ptr[2] = &(images[0].at(0)); // R
8955 } else if (components == 1) {
8956 image_ptr[0] = &(images[0].at(0)); // A
8957 }
8958
8959 image.images = reinterpret_cast<unsigned char**>(image_ptr);
8960 image.width = width;
8961 image.height = height;
8962
8963 header.num_channels = components;
8964 header.channels = static_cast<EXRChannelInfo*>(malloc(
8965 sizeof(EXRChannelInfo) * static_cast<size_t>(header.num_channels)));
8966 // Must be (A)BGR order, since most of EXR viewers expect this channel order.
8967 if (components == 4) {
8968#ifdef _MSC_VER
8969 strncpy_s(header.channels[0].name, "A", 255);
8970 strncpy_s(header.channels[1].name, "B", 255);
8971 strncpy_s(header.channels[2].name, "G", 255);
8972 strncpy_s(header.channels[3].name, "R", 255);
8973#else
8974 strncpy(header.channels[0].name, "A", 255);
8975 strncpy(header.channels[1].name, "B", 255);
8976 strncpy(header.channels[2].name, "G", 255);
8977 strncpy(header.channels[3].name, "R", 255);
8978#endif
8979 header.channels[0].name[strlen("A")] = '\0';
8980 header.channels[1].name[strlen("B")] = '\0';
8981 header.channels[2].name[strlen("G")] = '\0';
8982 header.channels[3].name[strlen("R")] = '\0';
8983 } else if (components == 3) {
8984#ifdef _MSC_VER
8985 strncpy_s(header.channels[0].name, "B", 255);
8986 strncpy_s(header.channels[1].name, "G", 255);
8987 strncpy_s(header.channels[2].name, "R", 255);
8988#else
8989 strncpy(header.channels[0].name, "B", 255);
8990 strncpy(header.channels[1].name, "G", 255);
8991 strncpy(header.channels[2].name, "R", 255);
8992#endif
8993 header.channels[0].name[strlen("B")] = '\0';
8994 header.channels[1].name[strlen("G")] = '\0';
8995 header.channels[2].name[strlen("R")] = '\0';
8996 } else {
8997#ifdef _MSC_VER
8998 strncpy_s(header.channels[0].name, "A", 255);
8999#else
9000 strncpy(header.channels[0].name, "A", 255);
9001#endif
9002 header.channels[0].name[strlen("A")] = '\0';
9003 }
9004
9005 header.pixel_types = static_cast<int*>(
9006 malloc(sizeof(int) * static_cast<size_t>(header.num_channels)));
9007 header.requested_pixel_types = static_cast<int*>(
9008 malloc(sizeof(int) * static_cast<size_t>(header.num_channels)));
9009 for (int i = 0; i < header.num_channels; i++) {
9010 header.pixel_types[i] = TINYEXR_PIXELTYPE_FLOAT; // pixel type of input image
9011
9012 if (save_as_fp16 > 0) {
9013 header.requested_pixel_types[i] = TINYEXR_PIXELTYPE_HALF; // save with half(fp16) pixel format
9014 } else {
9015 header.requested_pixel_types[i] = TINYEXR_PIXELTYPE_FLOAT; // save with float(fp32) pixel format(i.e.
9016 // no precision reduction)
9017 }
9018 }
9019
9020 unsigned char* mem_buf;
9021 size_t mem_size = SaveEXRImageToMemory(&image, &header, &mem_buf, err);
9022
9023 if (mem_size == 0) {
9025 }
9026
9027 free(header.channels);
9028 free(header.pixel_types);
9029 free(header.requested_pixel_types);
9030
9031 if (mem_size > size_t(std::numeric_limits<int>::max())) {
9032 free(mem_buf);
9034 }
9035
9036 (*outbuf) = mem_buf;
9037
9038 return int(mem_size);
9039}
9040
9041int SaveEXR(const float* data, int width, int height, int components,
9042 const int save_as_fp16, const char* outfilename, const char** err)
9043{
9044 if ((components == 1) || components == 3 || components == 4) {
9045 // OK
9046 } else {
9047 std::stringstream ss;
9048 ss << "Unsupported component value : " << components << std::endl;
9049
9050 tinyexr::SetErrorMessage(ss.str(), err);
9052 }
9053
9054 EXRHeader header;
9055 InitEXRHeader(&header);
9056
9057 if ((width < 16) && (height < 16)) {
9058 // No compression for small image.
9060 } else {
9062 }
9063
9064 EXRImage image;
9065 InitEXRImage(&image);
9066
9067 image.num_channels = components;
9068
9069 std::vector<float> images[4];
9070 const size_t pixel_count = static_cast<size_t>(width) * static_cast<size_t>(height);
9071
9072 if (components == 1) {
9073 images[0].resize(pixel_count);
9074 memcpy(images[0].data(), data, sizeof(float) * pixel_count);
9075 } else {
9076 images[0].resize(pixel_count);
9077 images[1].resize(pixel_count);
9078 images[2].resize(pixel_count);
9079 images[3].resize(pixel_count);
9080
9081 // Split RGB(A)RGB(A)RGB(A)... into R, G and B(and A) layers
9082 for (size_t i = 0; i < pixel_count; i++) {
9083 images[0][i] = data[static_cast<size_t>(components) * i + 0];
9084 images[1][i] = data[static_cast<size_t>(components) * i + 1];
9085 images[2][i] = data[static_cast<size_t>(components) * i + 2];
9086 if (components == 4) {
9087 images[3][i] = data[static_cast<size_t>(components) * i + 3];
9088 }
9089 }
9090 }
9091
9092 float* image_ptr[4] = { 0, 0, 0, 0 };
9093 if (components == 4) {
9094 image_ptr[0] = &(images[3].at(0)); // A
9095 image_ptr[1] = &(images[2].at(0)); // B
9096 image_ptr[2] = &(images[1].at(0)); // G
9097 image_ptr[3] = &(images[0].at(0)); // R
9098 } else if (components == 3) {
9099 image_ptr[0] = &(images[2].at(0)); // B
9100 image_ptr[1] = &(images[1].at(0)); // G
9101 image_ptr[2] = &(images[0].at(0)); // R
9102 } else if (components == 1) {
9103 image_ptr[0] = &(images[0].at(0)); // A
9104 }
9105
9106 image.images = reinterpret_cast<unsigned char**>(image_ptr);
9107 image.width = width;
9108 image.height = height;
9109
9110 header.num_channels = components;
9111 header.channels = static_cast<EXRChannelInfo*>(malloc(
9112 sizeof(EXRChannelInfo) * static_cast<size_t>(header.num_channels)));
9113 // Must be (A)BGR order, since most of EXR viewers expect this channel order.
9114 if (components == 4) {
9115#ifdef _MSC_VER
9116 strncpy_s(header.channels[0].name, "A", 255);
9117 strncpy_s(header.channels[1].name, "B", 255);
9118 strncpy_s(header.channels[2].name, "G", 255);
9119 strncpy_s(header.channels[3].name, "R", 255);
9120#else
9121 strncpy(header.channels[0].name, "A", 255);
9122 strncpy(header.channels[1].name, "B", 255);
9123 strncpy(header.channels[2].name, "G", 255);
9124 strncpy(header.channels[3].name, "R", 255);
9125#endif
9126 header.channels[0].name[strlen("A")] = '\0';
9127 header.channels[1].name[strlen("B")] = '\0';
9128 header.channels[2].name[strlen("G")] = '\0';
9129 header.channels[3].name[strlen("R")] = '\0';
9130 } else if (components == 3) {
9131#ifdef _MSC_VER
9132 strncpy_s(header.channels[0].name, "B", 255);
9133 strncpy_s(header.channels[1].name, "G", 255);
9134 strncpy_s(header.channels[2].name, "R", 255);
9135#else
9136 strncpy(header.channels[0].name, "B", 255);
9137 strncpy(header.channels[1].name, "G", 255);
9138 strncpy(header.channels[2].name, "R", 255);
9139#endif
9140 header.channels[0].name[strlen("B")] = '\0';
9141 header.channels[1].name[strlen("G")] = '\0';
9142 header.channels[2].name[strlen("R")] = '\0';
9143 } else {
9144#ifdef _MSC_VER
9145 strncpy_s(header.channels[0].name, "A", 255);
9146#else
9147 strncpy(header.channels[0].name, "A", 255);
9148#endif
9149 header.channels[0].name[strlen("A")] = '\0';
9150 }
9151
9152 header.pixel_types = static_cast<int*>(
9153 malloc(sizeof(int) * static_cast<size_t>(header.num_channels)));
9154 header.requested_pixel_types = static_cast<int*>(
9155 malloc(sizeof(int) * static_cast<size_t>(header.num_channels)));
9156 for (int i = 0; i < header.num_channels; i++) {
9157 header.pixel_types[i] = TINYEXR_PIXELTYPE_FLOAT; // pixel type of input image
9158
9159 if (save_as_fp16 > 0) {
9160 header.requested_pixel_types[i] = TINYEXR_PIXELTYPE_HALF; // save with half(fp16) pixel format
9161 } else {
9162 header.requested_pixel_types[i] = TINYEXR_PIXELTYPE_FLOAT; // save with float(fp32) pixel format(i.e.
9163 // no precision reduction)
9164 }
9165 }
9166
9167 int ret = SaveEXRImageToFile(&image, &header, outfilename, err);
9168
9169 free(header.channels);
9170 free(header.pixel_types);
9171 free(header.requested_pixel_types);
9172
9173 return ret;
9174}
9175
9176#ifdef __clang__
9177// zero-as-null-pointer-constant
9178#pragma clang diagnostic pop
9179#endif
9180
9181#endif // TINYEXR_IMPLEMENTATION_DEFINED
9182#endif // TINYEXR_IMPLEMENTATION
unsigned count
float y
float x
voidpf void uLong size
Definition ioapi.h:126
const char * filename
Definition ioapi.h:125
voidpf stream
Definition ioapi.h:126
voidpf uLong offset
Definition ioapi.h:132
typedef int(ZCALLBACK *close_file_func) OF((voidpf opaque
voidpf void * buf
Definition ioapi.h:126
int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len)
Definition miniz.c:334
mz_ulong mz_compressBound(mz_ulong source_len)
Definition miniz.c:339
int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len)
Definition miniz.c:570
unsigned long mz_ulong
Definition miniz.h:233
#define uncompress
Definition miniz.h:500
mz_ulong uLong
Definition miniz.h:440
#define compressBound
Definition miniz.h:491
@ MZ_OK
Definition miniz.h:295
#define Z_OK
Definition miniz.h:456
Byte Bytef
Definition miniz.h:441
#define compress
Definition miniz.h:489
const char ** channel_names
Definition tinyexr.h:314
int width
Definition tinyexr.h:318
int ** offset_table
Definition tinyexr.h:316
int num_channels
Definition tinyexr.h:317
float *** image
Definition tinyexr.h:315
int height
Definition tinyexr.h:319
char type[256]
Definition tinyexr.h:200
char name[256]
Definition tinyexr.h:199
unsigned char * value
Definition tinyexr.h:201
int min_y
Definition tinyexr.h:229
int max_x
Definition tinyexr.h:230
int max_y
Definition tinyexr.h:231
int min_x
Definition tinyexr.h:228
unsigned char p_linear
Definition tinyexr.h:211
char name[256]
Definition tinyexr.h:207
unsigned char pad[3]
Definition tinyexr.h:212
EXRChannelInfo * channels
Definition tinyexr.h:264
int tile_level_mode
Definition tinyexr.h:248
int num_custom_attributes
Definition tinyexr.h:260
int tile_size_x
Definition tinyexr.h:246
float screen_window_center[2]
Definition tinyexr.h:239
EXRBox2i data_window
Definition tinyexr.h:237
float pixel_aspect_ratio
Definition tinyexr.h:235
int multipart
Definition tinyexr.h:255
int tile_rounding_mode
Definition tinyexr.h:249
int tile_size_y
Definition tinyexr.h:247
char name[256]
Definition tinyexr.h:280
unsigned int header_len
Definition tinyexr.h:256
int long_name
Definition tinyexr.h:251
int tiled
Definition tinyexr.h:245
int compression_type
Definition tinyexr.h:271
EXRBox2i display_window
Definition tinyexr.h:238
EXRAttribute * custom_attributes
Definition tinyexr.h:261
int num_channels
Definition tinyexr.h:269
float screen_window_width
Definition tinyexr.h:240
int non_image
Definition tinyexr.h:254
int * pixel_types
Definition tinyexr.h:266
int line_order
Definition tinyexr.h:236
int chunk_count
Definition tinyexr.h:242
int * requested_pixel_types
Definition tinyexr.h:272
int num_channels
Definition tinyexr.h:300
unsigned char ** images
Definition tinyexr.h:296
int width
Definition tinyexr.h:298
EXRTile * tiles
Definition tinyexr.h:290
int num_tiles
Definition tinyexr.h:303
int level_x
Definition tinyexr.h:293
struct TEXRImage * next_level
Definition tinyexr.h:292
int level_y
Definition tinyexr.h:294
int height
Definition tinyexr.h:299
EXRHeader * headers
Definition tinyexr.h:285
EXRImage * images
Definition tinyexr.h:309
int level_x
Definition tinyexr.h:218
int height
Definition tinyexr.h:222
int offset_y
Definition tinyexr.h:217
int offset_x
Definition tinyexr.h:216
int level_y
Definition tinyexr.h:219
unsigned char ** images
Definition tinyexr.h:224
int width
Definition tinyexr.h:221
int version
Definition tinyexr.h:187
int long_name
Definition tinyexr.h:191
int multipart
Definition tinyexr.h:195
int non_image
Definition tinyexr.h:194
int LoadEXRFromMemory(float **out_rgba, int *width, int *height, const unsigned char *memory, size_t size, const char **err)
int ParseEXRHeaderFromMemory(EXRHeader *header, const EXRVersion *version, const unsigned char *memory, size_t size, const char **err)
struct TEXRBox2i EXRBox2i
int FreeEXRHeader(EXRHeader *exr_header)
#define TINYEXR_ERROR_UNSUPPORTED_FEATURE
Definition tinyexr.h:152
#define TINYEXR_COMPRESSIONTYPE_ZFP
Definition tinyexr.h:173
int FreeEXRImage(EXRImage *exr_image)
int IsEXRFromMemory(const unsigned char *memory, size_t size)
int ParseEXRMultipartHeaderFromFile(EXRHeader ***headers, int *num_headers, const EXRVersion *version, const char *filename, const char **err)
#define TINYEXR_ERROR_INVALID_ARGUMENT
Definition tinyexr.h:145
struct TEXRVersion EXRVersion
#define TINYEXR_COMPRESSIONTYPE_PIZ
Definition tinyexr.h:172
int LoadDeepEXR(DeepImage *out_image, const char *filename, const char **err)
int SaveEXRToMemory(const float *data, const int width, const int height, const int components, const int save_as_fp16, unsigned char **buffer, const char **err)
#define TINYEXR_ERROR_DATA_TOO_LARGE
Definition tinyexr.h:156
#define TINYEXR_ZFP_COMPRESSIONTYPE_PRECISION
Definition tinyexr.h:176
#define TINYEXR_COMPRESSIONTYPE_ZIPS
Definition tinyexr.h:170
#define TINYEXR_TILE_MIPMAP_LEVELS
Definition tinyexr.h:180
#define TINYEXR_TILE_RIPMAP_LEVELS
Definition tinyexr.h:181
#define TINYEXR_ERROR_INVALID_MAGIC_NUMBER
Definition tinyexr.h:143
#define TINYEXR_COMPRESSIONTYPE_RLE
Definition tinyexr.h:169
int ParseEXRVersionFromMemory(EXRVersion *version, const unsigned char *memory, size_t size)
#define TINYEXR_PIXELTYPE_UINT
Definition tinyexr.h:161
int SaveEXR(const float *data, const int width, const int height, const int components, const int save_as_fp16, const char *filename, const char **err)
int ParseEXRVersionFromFile(EXRVersion *version, const char *filename)
void FreeEXRErrorMessage(const char *msg)
#define TINYEXR_ZFP_COMPRESSIONTYPE_RATE
Definition tinyexr.h:175
int LoadEXRMultipartImageFromMemory(EXRImage *images, const EXRHeader **headers, unsigned int num_parts, const unsigned char *memory, const size_t size, const char **err)
int LoadEXR(float **out_rgba, int *width, int *height, const char *filename, const char **err)
#define TINYEXR_ERROR_SERIALIZATION_FAILED
Definition tinyexr.h:154
#define TINYEXR_SUCCESS
Definition tinyexr.h:142
int LoadEXRWithLayer(float **out_rgba, int *width, int *height, const char *filename, const char *layer_name, const char **err)
struct TEXRImage EXRImage
int LoadEXRImageFromMemory(EXRImage *image, const EXRHeader *header, const unsigned char *memory, const size_t size, const char **err)
#define TINYEXR_ZFP_COMPRESSIONTYPE_ACCURACY
Definition tinyexr.h:177
#define TINYEXR_ERROR_INVALID_EXR_VERSION
Definition tinyexr.h:144
#define TINYEXR_COMPRESSIONTYPE_NONE
Definition tinyexr.h:168
#define TINYEXR_PIXELTYPE_HALF
Definition tinyexr.h:162
#define TINYEXR_MAX_CUSTOM_ATTRIBUTES
Definition tinyexr.h:166
int ParseEXRHeaderFromFile(EXRHeader *header, const EXRVersion *version, const char *filename, const char **err)
int EXRLayers(const char *filename, const char **layer_names[], int *num_layers, const char **err)
int IsEXR(const char *filename)
#define TINYEXR_ERROR_LAYER_NOT_FOUND
Definition tinyexr.h:155
size_t SaveEXRImageToMemory(const EXRImage *image, const EXRHeader *exr_header, unsigned char **memory, const char **err)
#define TINYEXR_TILE_ROUND_UP
Definition tinyexr.h:184
#define TINYEXR_COMPRESSIONTYPE_ZIP
Definition tinyexr.h:171
int ParseEXRMultipartHeaderFromMemory(EXRHeader ***headers, int *num_headers, const EXRVersion *version, const unsigned char *memory, size_t size, const char **err)
#define TINYEXR_ERROR_CANT_OPEN_FILE
Definition tinyexr.h:149
int EXRNumLevels(const EXRImage *exr_image)
struct TEXRTile EXRTile
struct TEXRAttribute EXRAttribute
#define TINYEXR_ERROR_INVALID_FILE
Definition tinyexr.h:147
#define TINYEXR_ERROR_INVALID_DATA
Definition tinyexr.h:146
struct TEXRHeader EXRHeader
struct TEXRMultiPartImage EXRMultiPartImage
int LoadEXRMultipartImageFromFile(EXRImage *images, const EXRHeader **headers, unsigned int num_parts, const char *filename, const char **err)
#define TINYEXR_MAX_HEADER_ATTRIBUTES
Definition tinyexr.h:165
void InitEXRHeader(EXRHeader *exr_header)
struct TEXRMultiPartHeader EXRMultiPartHeader
size_t SaveEXRMultipartImageToMemory(const EXRImage *images, const EXRHeader **exr_headers, unsigned int num_parts, unsigned char **memory, const char **err)
#define TINYEXR_PIXELTYPE_FLOAT
Definition tinyexr.h:163
struct TEXRChannelInfo EXRChannelInfo
#define TINYEXR_TILE_ROUND_DOWN
Definition tinyexr.h:183
#define TINYEXR_ERROR_UNSUPPORTED_FORMAT
Definition tinyexr.h:150
void InitEXRImage(EXRImage *exr_image)
#define TINYEXR_ERROR_INVALID_HEADER
Definition tinyexr.h:151
int SaveEXRImageToFile(const EXRImage *image, const EXRHeader *exr_header, const char *filename, const char **err)
#define TINYEXR_ERROR_CANT_WRITE_FILE
Definition tinyexr.h:153
#define TINYEXR_TILE_ONE_LEVEL
Definition tinyexr.h:179
struct TDeepImage DeepImage
int SaveEXRMultipartImageToFile(const EXRImage *images, const EXRHeader **exr_headers, unsigned int num_parts, const char *filename, const char **err)
int LoadEXRImageFromFile(EXRImage *image, const EXRHeader *header, const char *filename, const char **err)
void EXRSetNameAttr(EXRHeader *exr_header, const char *name)