OpenToonz - An open-source full-featured 2D animation creation software
C
Add PNG checkerboard fallback; fix PNG and SGI leaks
andeon123a722ee32e
diff --git a/toonz/sources/image/png/tiio_png.cpp b/toonz/sources/image/png/tiio_png.cppindex 62ec4e5f5..0451edbba 100644--- a/toonz/sources/image/png/tiio_png.cpp+++ b/toonz/sources/image/png/tiio_png.cpp@@ -1,8 +1,12 @@++#if defined(_MSC_VER) && (_MSC_VER >= 1400)#define _CRT_SECURE_NO_DEPRECATE 1#endif#include <memory>+#include <stdexcept>+#include <vector>#include "tmachine.h"#include "texception.h"@@ -16,15 +20,14 @@#include "tpixel.h"#include "tpixelutils.h"-using namespace std;//------------------------------------------------------------extern "C" {-static void tnz_abort(jmp_buf, int) {}static void tnz_error_fun(png_structp pngPtr, png_const_charp error_message) {- *(int *)png_get_error_ptr(pngPtr) = 0;+ // Jump back to the setjmp point, libpng expects this for error recovery+ longjmp(png_jmpbuf(pngPtr), 1);}}@@ -61,8 +64,8 @@ static png_byte png_get_current_pass_number(const png_structp png_ptr) {inline USHORT mySwap(USHORT val) {#if TNZ_LITTLE_ENDIAN- return ((val) |- ((val & 0xff) << 8)); //((val>>8)|((val&0xff)<<8)); (vecchio codice)+ // Correct byte swapping for little-endian systems+ return static_cast<USHORT>((val >> 8) | (val << 8));#elsereturn val;#endif@@ -80,8 +83,14 @@ class PngReader final : public Tiio::Reader {int m_y;bool m_is16bitEnabled;std::unique_ptr<unsigned char[]> m_rowBuffer;- std::unique_ptr<unsigned char[]> m_tempBuffer; // Buffer temporaneoint m_canDelete;+ int m_channels;+ int m_rowBytes;+ bool m_hasPalette;+ png_colorp m_palette;+ int m_paletteSize;+ png_bytep m_transparency;+ int m_transparencySize;public:PngReader()@@ -97,75 +106,81 @@ public:, m_sig_read(0), m_y(0), m_is16bitEnabled(true)- , m_canDelete(0) {}+ , m_canDelete(0)+ , m_channels(0)+ , m_rowBytes(0)+ , m_hasPalette(false)+ , m_palette(nullptr)+ , m_paletteSize(0)+ , m_transparency(nullptr)+ , m_transparencySize(0) {}~PngReader() {- if (m_canDelete == 1) {+ if (m_png_ptr) {png_destroy_read_struct(&m_png_ptr, &m_info_ptr, &m_end_info_ptr);}+ // Note: libpng manages palette and transparency memory internally}bool read16BitIsEnabled() const override { return m_is16bitEnabled; }void enable16BitRead(bool enabled) override { m_is16bitEnabled = enabled; }- void readLineInterlace(char *buffer) {- readLineInterlace(buffer, 0, m_info.m_lx - 1, 1);- }- void readLineInterlace(short *buffer) {- readLineInterlace(buffer, 0, m_info.m_lx - 1, 1);- }-void open(FILE *file) override {try {m_chan = file;} catch (...) {- perror("uffa");- return;+ throw TException("Can't open file");+ }++ unsigned char signature[8];+ size_t bytesRead = fread(signature, 1, sizeof(signature), m_chan);+ if (bytesRead != sizeof(signature)) {+ throw TException("Can't read PNG signature");+ }++ bool isPng = !png_sig_cmp(signature, 0, sizeof(signature));+ if (!isPng) {+ throw TException("Not a valid PNG file");}- unsigned char signature[8]; // da 1 a 8 bytes- fread(signature, 1, sizeof signature, m_chan);- bool isPng = !png_sig_cmp(signature, 0, sizeof signature);- if (!isPng) return;+ m_png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr,+ nullptr);+ if (!m_png_ptr) {+ throw TException("Unable to create PNG read structure");+ }- m_png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, &m_canDelete,- tnz_error_fun, 0);- if (!m_png_ptr) return;+ // Set error handler+ png_set_error_fn(m_png_ptr, nullptr, tnz_error_fun, nullptr);#if defined(PNG_LIBPNG_VER)#if (PNG_LIBPNG_VER >= 10527)- png_set_longjmp_fn(m_png_ptr, tnz_abort,- sizeof(jmp_buf)); /* ignore all fatal errors */-#endif // (PNG_LIBPNG_VER >= 10527)-#endif // defined(PNG_LIBPNG_VER)+ png_set_longjmp_fn(m_png_ptr, tnz_abort, sizeof(jmp_buf));+#endif+#endif- m_canDelete = 1;- m_info_ptr = png_create_info_struct(m_png_ptr);+ m_info_ptr = png_create_info_struct(m_png_ptr);if (!m_info_ptr) {png_destroy_read_struct(&m_png_ptr, (png_infopp)0, (png_infopp)0);- return;+ throw TException("Unable to create PNG info structure");}m_end_info_ptr = png_create_info_struct(m_png_ptr);if (!m_end_info_ptr) {png_destroy_read_struct(&m_png_ptr, &m_info_ptr, (png_infopp)0);- return;+ throw TException("Unable to create PNG end info structure");}- png_init_io(m_png_ptr, m_chan);-- png_set_sig_bytes(m_png_ptr, sizeof signature);+ // Set up error handling with setjmp+ if (setjmp(png_jmpbuf(m_png_ptr))) {+ png_destroy_read_struct(&m_png_ptr, &m_info_ptr, &m_end_info_ptr);+ m_png_ptr = nullptr;+ m_info_ptr = nullptr;+ m_end_info_ptr = nullptr;+ throw TException("PNG initialization failed");+ }-#if defined(TNZ_MACHINE_CHANNEL_ORDER_MBGR)- png_set_bgr(m_png_ptr);- png_set_swap_alpha(m_png_ptr);-#elif defined(TNZ_MACHINE_CHANNEL_ORDER_BGRM)- png_set_bgr(m_png_ptr);-#elif defined(TNZ_MACHINE_CHANNEL_ORDER_MRGB)- png_set_swap_alpha(m_png_ptr);-#elif !defined(TNZ_MACHINE_CHANNEL_ORDER_RGBM)-#error "unknown channel order"-#endif+ png_init_io(m_png_ptr, m_chan);+ png_set_sig_bytes(m_png_ptr, sizeof(signature));png_read_info(m_png_ptr, m_info_ptr);@@ -176,8 +191,6 @@ public:m_info.m_dpiy = tround(ydpi * 0.0254);}- int rowBytes = png_get_rowbytes(m_png_ptr, m_info_ptr);-png_uint_32 lx = 0, ly = 0;png_get_IHDR(m_png_ptr, m_info_ptr, &lx, &ly, &m_bit_depth, &m_color_type,&m_interlace_type, &m_compression_type, &m_filter_type);@@ -186,28 +199,22 @@ public:m_info.m_bitsPerSample = m_bit_depth;- int channels = png_get_channels(m_png_ptr, m_info_ptr);- m_info.m_samplePerPixel = channels;+ // Check for palette+ if (m_color_type == PNG_COLOR_TYPE_PALETTE) {+ m_hasPalette = true;++ // Get palette information+ png_get_PLTE(m_png_ptr, m_info_ptr, &m_palette, &m_paletteSize);- if (channels == 1 || channels == 2) {- if (m_bit_depth <- 8) // (m_bit_depth == 1 || m_bit_depth == 2 || m_bit_depth == 4)- m_rowBuffer.reset(new unsigned char[lx * 3]);- else- m_rowBuffer.reset(new unsigned char[rowBytes * 4]);- } else {- m_rowBuffer.reset(new unsigned char[rowBytes]);+ // Get transparency information if available+ if (png_get_valid(m_png_ptr, m_info_ptr, PNG_INFO_tRNS)) {+ png_get_tRNS(m_png_ptr, m_info_ptr, &m_transparency,+ &m_transparencySize, nullptr);+ }}if (m_color_type == PNG_COLOR_TYPE_PALETTE) {- m_info.m_valid = true;png_set_palette_to_rgb(m_png_ptr);-- // treat the image as RGBA from now on- m_info.m_samplePerPixel =- 4; // there are 4 channels per pixel (R, G, B, and A)-- // if there is no alpha channel, then fill it with "255" (full opacity)png_set_filler(m_png_ptr, 0xFF, PNG_FILLER_AFTER);}@@ -223,554 +230,353 @@ public:png_set_strip_16(m_png_ptr);}-#if defined(TNZ_MACHINE_CHANNEL_ORDER_BGRM)- if (m_color_type == PNG_COLOR_TYPE_RGB ||- m_color_type == PNG_COLOR_TYPE_RGB_ALPHA) {- png_set_bgr(m_png_ptr);- }-#elif defined(TNZ_MACHINE_CHANNEL_ORDER_MBGR)- if (m_color_type == PNG_COLOR_TYPE_RGB_ALPHA) {- png_set_swap_alpha(m_png_ptr);+ if (m_color_type == PNG_COLOR_TYPE_GRAY ||+ m_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {+ png_set_gray_to_rgb(m_png_ptr);}-#elif !defined(TNZ_MACHINE_CHANNEL_ORDER_RGBM) && \- !defined(TNZ_MACHINE_CHANNEL_ORDER_MRGB)++#if defined(TNZ_MACHINE_CHANNEL_ORDER_MBGR)+ png_set_bgr(m_png_ptr);+ png_set_swap_alpha(m_png_ptr);+#elif defined(TNZ_MACHINE_CHANNEL_ORDER_BGRM)+ png_set_bgr(m_png_ptr);+#elif defined(TNZ_MACHINE_CHANNEL_ORDER_MRGB)+ png_set_swap_alpha(m_png_ptr);+#elif !defined(TNZ_MACHINE_CHANNEL_ORDER_RGBM)#error "unknown channel order"#endif- if (m_color_type == PNG_COLOR_TYPE_GRAY ||- m_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {- png_set_gray_to_rgb(m_png_ptr);+ // Handle interlacing if present - let libpng handle it+ if (m_interlace_type == PNG_INTERLACE_ADAM7) {+ png_set_interlace_handling(m_png_ptr);+ }++ // Update info after all transformations+ png_read_update_info(m_png_ptr, m_info_ptr);++ // Refresh variables after update+ m_channels = png_get_channels(m_png_ptr, m_info_ptr);+ m_rowBytes = png_get_rowbytes(m_png_ptr, m_info_ptr);+ png_get_IHDR(m_png_ptr, m_info_ptr, &lx, &ly, &m_bit_depth, &m_color_type,+ &m_interlace_type, &m_compression_type, &m_filter_type);+ m_info.m_samplePerPixel = m_channels;++ // Validate dimensions+ if (m_info.m_lx <= 0 || m_info.m_ly <= 0) {+ throw TException("Invalid PNG dimensions");+ }++ // Allocate row buffer based on updated rowBytes+ m_rowBuffer.reset(new unsigned char[m_rowBytes]);+ if (!m_rowBuffer) {+ throw TException("Memory allocation failed for row buffer");}}void readLine(char *buffer, int x0, int x1, int shrink) override {- int ly = m_info.m_ly;- if (!m_tempBuffer) {- int lx = m_info.m_lx;- int channels = png_get_channels(m_png_ptr, m_info_ptr);- int rowBytes = png_get_rowbytes(m_png_ptr, m_info_ptr);- if (m_interlace_type == 1) {- if (channels == 1 || channels == 2) {- if (m_bit_depth < 8)- m_tempBuffer.reset(new unsigned char[ly * lx * 3]);- else- m_tempBuffer.reset(new unsigned char[ly * rowBytes * 4]);+ // Validate input parameters+ if (!buffer || x0 < 0 || x1 >= m_info.m_lx || x0 > x1) {+ return;+ }++ if (setjmp(png_jmpbuf(m_png_ptr))) {+ // Error while reading a PNG row.+ // Fill the damaged area with a checkerboard pattern.+ TPixel32 *pix = (TPixel32 *)buffer + x0;+ for (int j = x0; j <= x1; ++j, ++pix) {+ // 8×8 checkerboard pattern+ bool isCheckerboard = (((j >> 3) + (m_y >> 3)) & 1) == 0;++ if (isCheckerboard) {+ pix->r = pix->g = pix->b = 120; // dark gray+ pix->m = 255; // opaque} else {- m_tempBuffer.reset(new unsigned char[ly * rowBytes]);+ pix->r = pix->g = pix->b = 180; // light gray+ pix->m = 255; // opaque}}- }- int lx = m_info.m_lx;- if (m_interlace_type == 1 && lx > 4) {- readLineInterlace(&buffer[0], x0, x1, shrink);m_y++;- if (m_tempBuffer && m_y == ly) {- m_tempBuffer.reset();- }- throw TException("Unable to read file");return;}- int y = m_info.m_ly - 1 - m_y;- if (y < 0) {- throw TException("Unable to read file");- return;- }+ png_read_row(m_png_ptr, m_rowBuffer.get(), nullptr);+ writeRow(buffer, x0, x1);m_y++;+ }- png_bytep row_pointer = m_rowBuffer.get();- png_read_row(m_png_ptr, row_pointer, NULL);-- if (setjmp(png_jmpbuf(m_png_ptr))) {- // If an error is caught in the next line, execution jumps here.- // We'll keep going in order to load whatever we can read.+ void readLine(short *buffer, int x0, int x1, int shrink) override {+ // Validate input parameters+ if (!buffer || x0 < 0 || x1 >= m_info.m_lx || x0 > x1) {return;}- writeRow(buffer, x0, x1);-- if (m_tempBuffer && m_y == ly) {- m_tempBuffer.reset();- }- }+ if (setjmp(png_jmpbuf(m_png_ptr))) {+ // Error while reading a PNG row.+ // Fill the damaged area with a checkerboard pattern.+ TPixel64 *pix = (TPixel64 *)buffer + x0;+ for (int j = x0; j <= x1; ++j, ++pix) {+ // 8×8 checkerboard pattern+ bool isCheckerboard = (((j >> 3) + (m_y >> 3)) & 1) == 0;- void readLine(short *buffer, int x0, int x1, int shrink) override {- int ly = m_info.m_ly;- if (!m_tempBuffer) {- int lx = m_info.m_lx;- int channels = png_get_channels(m_png_ptr, m_info_ptr);- int rowBytes = png_get_rowbytes(m_png_ptr, m_info_ptr);- if (m_interlace_type == 1) {- if (channels == 1 || channels == 2) {- if (m_bit_depth <- 8) // (m_bit_depth == 1 || m_bit_depth == 2 || m_bit_depth == 4)- m_tempBuffer.reset(new unsigned char[ly * lx * 3]);- else- m_tempBuffer.reset(new unsigned char[ly * rowBytes * 4]);+ if (isCheckerboard) {+ pix->r = pix->g = pix->b = 120; // dark gray+ pix->m = 255; // opaque} else {- m_tempBuffer.reset(new unsigned char[ly * rowBytes]);+ pix->r = pix->g = pix->b = 180; // light gray+ pix->m = 255; // opaque}}- }-- if (png_get_interlace_type(m_png_ptr, m_info_ptr) == PNG_INTERLACE_ADAM7) {- readLineInterlace(&buffer[0], x0, x1, shrink);m_y++;- if (m_tempBuffer && m_y == ly) {- m_tempBuffer.reset();- }return;}- int y = m_info.m_ly - 1 - m_y;- if (y < 0) return;- m_y++;-- png_bytep row_pointer = m_rowBuffer.get();- png_read_row(m_png_ptr, row_pointer, NULL);-+ png_read_row(m_png_ptr, m_rowBuffer.get(), nullptr);writeRow(buffer, x0, x1);-- if (m_tempBuffer && m_y == ly) {- m_tempBuffer.reset();- }+ m_y++;}int skipLines(int lineCount) override {- for (int i = 0; i < lineCount; i++) {- if (m_interlace_type == 1 &&- m_info.m_lx > 4) // pezza. Studiare il codice- {- int channels = png_get_channels(m_png_ptr, m_info_ptr);- char *lineBuffer = (char *)malloc(4 * m_info.m_lx * sizeof(char));- readLine(lineBuffer, 0, m_info.m_lx - 1, 1);- free(lineBuffer);- } else {- m_y++;- png_bytep row_pointer = m_rowBuffer.get();- png_read_row(m_png_ptr, row_pointer, NULL);+ if (lineCount <= 0) return 0;++ int skipped = 0;+ for (int i = 0; i < lineCount; ++i) {+ if (m_y >= m_info.m_ly) break;++ if (setjmp(png_jmpbuf(m_png_ptr))) {+ break; // Stop on error}++ png_read_row(m_png_ptr, m_rowBuffer.get(), nullptr);+ m_y++;+ skipped++;}- return lineCount;+ return skipped;}Tiio::RowOrder getRowOrder() const override { return Tiio::TOP2BOTTOM; }+ // Accessor for palette information (if needed by external code)+ bool hasPalette() const { return m_hasPalette; }+ int getPaletteSize() const { return m_paletteSize; }+ const png_color *getPalette() const { return m_palette; }+ const png_byte *getTransparency() const { return m_transparency; }+ int getTransparencySize() const { return m_transparencySize; }++private:void writeRow(char *buffer, int x0, int x1) {- if (m_color_type == PNG_COLOR_TYPE_RGB_ALPHA ||- m_color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||- m_color_type == PNG_COLOR_TYPE_PALETTE) { // PNG_COLOR_TYPE_PALETTE is- // expanded to RGBA- if (m_bit_depth == 16) {- TPixel32 *pix = (TPixel32 *)buffer;- int i = -2;- i += x0 * 2 * 4;- for (int j = x0; j <= x1; j++) {+ bool hasAlpha = (m_channels == 4);++ if (m_bit_depth == 16) {+ // 16-bit not supported for char* buffer+ TPixel32 *pix = (TPixel32 *)buffer + x0;+ for (int j = x0; j <= x1; ++j, ++pix) {+ pix->r = pix->g = pix->b = pix->m = 0;+ }+ return;+ }++ TPixel32 *pix = (TPixel32 *)buffer + x0;+ int srcIdx = x0 * m_channels;++ for (int j = x0; j <= x1; ++j, ++pix) {+ if (srcIdx + m_channels > m_rowBytes) {+ break; // Prevent buffer overflow+ }++ if (hasAlpha) {#if defined(TNZ_MACHINE_CHANNEL_ORDER_MRGB)- pix[j].m = m_rowBuffer[i = i + 2];- pix[j].r = m_rowBuffer[i = i + 2];- pix[j].g = m_rowBuffer[i = i + 2];- pix[j].b = m_rowBuffer[i = i + 2];+ pix->m = m_rowBuffer[srcIdx++];+ pix->r = m_rowBuffer[srcIdx++];+ pix->g = m_rowBuffer[srcIdx++];+ pix->b = m_rowBuffer[srcIdx++];#elif defined(TNZ_MACHINE_CHANNEL_ORDER_RGBM)- pix[j].r = m_rowBuffer[i = i + 2];- pix[j].g = m_rowBuffer[i = i + 2];- pix[j].b = m_rowBuffer[i = i + 2];- pix[j].m = m_rowBuffer[i = i + 2];+ pix->r = m_rowBuffer[srcIdx++];+ pix->g = m_rowBuffer[srcIdx++];+ pix->b = m_rowBuffer[srcIdx++];+ pix->m = m_rowBuffer[srcIdx++];#elif defined(TNZ_MACHINE_CHANNEL_ORDER_BGRM)- pix[j].b = m_rowBuffer[i = i + 2];- pix[j].g = m_rowBuffer[i = i + 2];- pix[j].r = m_rowBuffer[i = i + 2];- pix[j].m = m_rowBuffer[i = i + 2];+ pix->b = m_rowBuffer[srcIdx++];+ pix->g = m_rowBuffer[srcIdx++];+ pix->r = m_rowBuffer[srcIdx++];+ pix->m = m_rowBuffer[srcIdx++];#elif defined(TNZ_MACHINE_CHANNEL_ORDER_MBGR)- pix[j].m = m_rowBuffer[i = i + 2];- pix[j].b = m_rowBuffer[i = i + 2];- pix[j].g = m_rowBuffer[i = i + 2];- pix[j].r = m_rowBuffer[i = i + 2];+ pix->m = m_rowBuffer[srcIdx++];+ pix->b = m_rowBuffer[srcIdx++];+ pix->g = m_rowBuffer[srcIdx++];+ pix->r = m_rowBuffer[srcIdx++];#else#error "unknown channel order"#endif-- // premultiply here- premult(pix[j]);- }+ premult(*pix);} else {- TPixel32 *pix = (TPixel32 *)buffer;- int i = 0;- i += x0 * 4;- for (int j = x0; j <= x1; j++) {-#if defined(TNZ_MACHINE_CHANNEL_ORDER_MRGB)- pix[j].m = m_rowBuffer[i++];- pix[j].r = m_rowBuffer[i++];- pix[j].g = m_rowBuffer[i++];- pix[j].b = m_rowBuffer[i++];-#elif defined(TNZ_MACHINE_CHANNEL_ORDER_RGBM)- pix[j].r = m_rowBuffer[i++];- pix[j].g = m_rowBuffer[i++];- pix[j].b = m_rowBuffer[i++];- pix[j].m = m_rowBuffer[i++];-#elif defined(TNZ_MACHINE_CHANNEL_ORDER_BGRM)- pix[j].b = m_rowBuffer[i++];- pix[j].g = m_rowBuffer[i++];- pix[j].r = m_rowBuffer[i++];- pix[j].m = m_rowBuffer[i++];-#elif defined(TNZ_MACHINE_CHANNEL_ORDER_MBGR)- pix[j].m = m_rowBuffer[i++];- pix[j].b = m_rowBuffer[i++];- pix[j].g = m_rowBuffer[i++];- pix[j].r = m_rowBuffer[i++];+#if defined(TNZ_MACHINE_CHANNEL_ORDER_MRGB) || \+ defined(TNZ_MACHINE_CHANNEL_ORDER_RGBM)+ pix->r = m_rowBuffer[srcIdx++];+ pix->g = m_rowBuffer[srcIdx++];+ pix->b = m_rowBuffer[srcIdx++];+#elif defined(TNZ_MACHINE_CHANNEL_ORDER_MBGR) || \+ defined(TNZ_MACHINE_CHANNEL_ORDER_BGRM)+ pix->b = m_rowBuffer[srcIdx++];+ pix->g = m_rowBuffer[srcIdx++];+ pix->r = m_rowBuffer[srcIdx++];#else#error "unknown channel order"#endif- // premultiply here- premult(pix[j]);- }+ pix->m = 255;+ }+ }+ }++ void writeRow(short *buffer, int x0, int x1) {+ bool hasAlpha = (m_channels == 4);+ int bytesPerChannel = (m_bit_depth == 16) ? 2 : 1;++ TPixel64 *pix = (TPixel64 *)buffer + x0;+ int srcIdx = x0 * m_channels * bytesPerChannel;++ for (int j = x0; j <= x1; ++j, ++pix) {+ if (srcIdx >= m_rowBytes ||+ srcIdx + (m_channels * bytesPerChannel) > m_rowBytes) {+ break; // Prevent buffer overflow}- } else // qui gestisce RGB senza alpha.- { // grayscale e' gestito come RGB perche' si usa png_set_gray_to_rgb- if (m_bit_depth == 16) {- TPixel32 *pix = (TPixel32 *)buffer;- int i = -2;- i += x0 * 2 * 3;- for (int j = x0; j <= x1; j++) {++ if (hasAlpha) {+ if (m_bit_depth == 16) {#if defined(TNZ_MACHINE_CHANNEL_ORDER_MRGB) || \defined(TNZ_MACHINE_CHANNEL_ORDER_RGBM)- pix[j].r = m_rowBuffer[i = i + 2];- pix[j].g = m_rowBuffer[i = i + 2];- pix[j].b = m_rowBuffer[i = i + 2];+ USHORT r, g, b, m;+ memcpy(&r, m_rowBuffer.get() + srcIdx, sizeof(USHORT));+ srcIdx += 2;+ memcpy(&g, m_rowBuffer.get() + srcIdx, sizeof(USHORT));+ srcIdx += 2;+ memcpy(&b, m_rowBuffer.get() + srcIdx, sizeof(USHORT));+ srcIdx += 2;+ memcpy(&m, m_rowBuffer.get() + srcIdx, sizeof(USHORT));+ srcIdx += 2;+ pix->r = mySwap(r);+ pix->g = mySwap(g);+ pix->b = mySwap(b);+ pix->m = mySwap(m);#elif defined(TNZ_MACHINE_CHANNEL_ORDER_MBGR) || \defined(TNZ_MACHINE_CHANNEL_ORDER_BGRM)- pix[j].b = m_rowBuffer[i = i + 2];- pix[j].g = m_rowBuffer[i = i + 2];- pix[j].r = m_rowBuffer[i = i + 2];+ USHORT b, g, r, m;+ memcpy(&b, m_rowBuffer.get() + srcIdx, sizeof(USHORT));+ srcIdx += 2;+ memcpy(&g, m_rowBuffer.get() + srcIdx, sizeof(USHORT));+ srcIdx += 2;+ memcpy(&r, m_rowBuffer.get() + srcIdx, sizeof(USHORT));+ srcIdx += 2;+ memcpy(&m, m_rowBuffer.get() + srcIdx, sizeof(USHORT));+ srcIdx += 2;+ pix->b = mySwap(b);+ pix->g = mySwap(g);+ pix->r = mySwap(r);+ pix->m = mySwap(m);#else#error "unknown channel order"#endif- pix[j].m = 255;- }- } else {- TPixel32 *pix = (TPixel32 *)buffer;- int i = 0;- i += x0 * 3;- for (int j = x0; j <= x1; j++) {+ } else {+ // 8-bit with alpha: 1 byte per channel, converted to 16-bit+ // Layout: R(1) G(1) B(1) A(1) bytes#if defined(TNZ_MACHINE_CHANNEL_ORDER_MRGB) || \defined(TNZ_MACHINE_CHANNEL_ORDER_RGBM)- pix[j].r = m_rowBuffer[i++];- pix[j].g = m_rowBuffer[i++];- pix[j].b = m_rowBuffer[i++];+ pix->r =+ static_cast<USHORT>((m_rowBuffer[srcIdx++] * 65535 + 127) / 255);+ pix->g =+ static_cast<USHORT>((m_rowBuffer[srcIdx++] * 65535 + 127) / 255);+ pix->b =+ static_cast<USHORT>((m_rowBuffer[srcIdx++] * 65535 + 127) / 255);+ pix->m =+ static_cast<USHORT>((m_rowBuffer[srcIdx++] * 65535 + 127) / 255);#elif defined(TNZ_MACHINE_CHANNEL_ORDER_MBGR) || \defined(TNZ_MACHINE_CHANNEL_ORDER_BGRM)- pix[j].b = m_rowBuffer[i++];- pix[j].g = m_rowBuffer[i++];- pix[j].r = m_rowBuffer[i++];+ // Layout for 8-bit with alpha (BGR): B(1) G(1) R(1) A(1) bytes+ pix->b =+ static_cast<USHORT>((m_rowBuffer[srcIdx++] * 65535 + 127) / 255);+ pix->g =+ static_cast<USHORT>((m_rowBuffer[srcIdx++] * 65535 + 127) / 255);+ pix->r =+ static_cast<USHORT>((m_rowBuffer[srcIdx++] * 65535 + 127) / 255);+ pix->m =+ static_cast<USHORT>((m_rowBuffer[srcIdx++] * 65535 + 127) / 255);#else#error "unknown channel order"#endif- pix[j].m = 255;}- }- }- }-- void writeRow(short *buffer, int x0, int x1) {- if (m_color_type == PNG_COLOR_TYPE_RGB_ALPHA ||- m_color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||- m_color_type == PNG_COLOR_TYPE_PALETTE) { // PNG_COLOR_TYPE_PALETTE is- // expanded to RGBA- TPixel64 *pix = (TPixel64 *)buffer;- int i = -2; // 0;- i += x0 * 2 * 4;- for (int j = x0; j <= x1; j++) {+ premult(*pix);+ } else {+ if (m_bit_depth == 16) {#if defined(TNZ_MACHINE_CHANNEL_ORDER_MRGB) || \defined(TNZ_MACHINE_CHANNEL_ORDER_RGBM)- pix[j].r = mySwap(m_rowBuffer[i = i + 2]); // i++- pix[j].g = mySwap(m_rowBuffer[i = i + 2]);- pix[j].b = mySwap(m_rowBuffer[i = i + 2]);- pix[j].m = mySwap(m_rowBuffer[i = i + 2]);+ // Layout for 16-bit without alpha: R(2) G(2) B(2) bytes+ USHORT r, g, b;+ memcpy(&r, m_rowBuffer.get() + srcIdx, sizeof(USHORT));+ srcIdx += 2;+ memcpy(&g, m_rowBuffer.get() + srcIdx, sizeof(USHORT));+ srcIdx += 2;+ memcpy(&b, m_rowBuffer.get() + srcIdx, sizeof(USHORT));+ srcIdx += 2;+ pix->r = mySwap(r);+ pix->g = mySwap(g);+ pix->b = mySwap(b);#elif defined(TNZ_MACHINE_CHANNEL_ORDER_MBGR) || \defined(TNZ_MACHINE_CHANNEL_ORDER_BGRM)- pix[j].b = mySwap(m_rowBuffer[i = i + 2]); // i++- pix[j].g = mySwap(m_rowBuffer[i = i + 2]);- pix[j].r = mySwap(m_rowBuffer[i = i + 2]);- pix[j].m = mySwap(m_rowBuffer[i = i + 2]);+ // Layout for 16-bit without alpha (BGR): B(2) G(2) R(2) bytes+ USHORT b, g, r;+ memcpy(&b, m_rowBuffer.get() + srcIdx, sizeof(USHORT));+ srcIdx += 2;+ memcpy(&g, m_rowBuffer.get() + srcIdx, sizeof(USHORT));+ srcIdx += 2;+ memcpy(&r, m_rowBuffer.get() + srcIdx, sizeof(USHORT));+ srcIdx += 2;+ pix->b = mySwap(b);+ pix->g = mySwap(g);+ pix->r = mySwap(r);#else#error "unknown channel order"#endif- // pix[j].m = 255;-- // premultiply here- premult(pix[j]);- }- } else // qui gestisce RGB senza alpha.- { // grayscale e' gestito come RGB perche' si usa png_set_gray_to_rgb- TPixel64 *pix = (TPixel64 *)buffer;- int i = -2;- i += x0 * 2 * 3;- for (int j = x0; j <= x1; j++) {+ } else {+ // 8-bit without alpha+ // Layout: R(1) G(1) B(1) bytes#if defined(TNZ_MACHINE_CHANNEL_ORDER_MRGB) || \defined(TNZ_MACHINE_CHANNEL_ORDER_RGBM)- pix[j].r = mySwap(m_rowBuffer[i = i + 2]);- pix[j].g = mySwap(m_rowBuffer[i = i + 2]);- pix[j].b = mySwap(m_rowBuffer[i = i + 2]);+ pix->r =+ static_cast<USHORT>((m_rowBuffer[srcIdx++] * 65535 + 127) / 255);+ pix->g =+ static_cast<USHORT>((m_rowBuffer[srcIdx++] * 65535 + 127) / 255);+ pix->b =+ static_cast<USHORT>((m_rowBuffer[srcIdx++] * 65535 + 127) / 255);#elif defined(TNZ_MACHINE_CHANNEL_ORDER_MBGR) || \defined(TNZ_MACHINE_CHANNEL_ORDER_BGRM)- pix[j].b = mySwap(m_rowBuffer[i = i + 2]);- pix[j].g = mySwap(m_rowBuffer[i = i + 2]);- pix[j].r = mySwap(m_rowBuffer[i = i + 2]);+ // Layout for 8-bit without alpha (BGR): B(1) G(1) R(1) bytes+ pix->b =+ static_cast<USHORT>((m_rowBuffer[srcIdx++] * 65535 + 127) / 255);+ pix->g =+ static_cast<USHORT>((m_rowBuffer[srcIdx++] * 65535 + 127) / 255);+ pix->r =+ static_cast<USHORT>((m_rowBuffer[srcIdx++] * 65535 + 127) / 255);#else#error "unknown channel order"#endif- pix[j].m = mySwap(255);- }- }- }-- void copyPixel(int count, int dstX, int dstDx, int dstY) {- int channels = png_get_channels(m_png_ptr, m_info_ptr);- int rowBytes = png_get_rowbytes(m_png_ptr, m_info_ptr);- int lx = m_info.m_lx;-- if ((channels == 4 || channels == 3) && m_bit_depth == 16) {- for (int i = 0; i < count; i += 2) {- for (int j = 0; j < channels * 2; j++) {- (m_tempBuffer.get() +- (dstY * rowBytes))[(i * dstDx + dstX) * channels + j] =- m_rowBuffer[i * channels + j];- }- }- } else if (channels == 2 && m_bit_depth == 16) {- for (int i = 0; i < count; i += 2) {- for (int j = 0; j < 4 * 2; j++) {- (m_tempBuffer.get() +- (dstY * rowBytes * 4))[(i * dstDx + dstX) * 4 + j] =- m_rowBuffer[i * 4 + j];- }- }- } else if (channels == 1 && m_bit_depth == 16) {- for (int i = 0; i < count; i += 2) {- for (int j = 0; j < 3 * 2; j++) {- (m_tempBuffer.get() +- (dstY * rowBytes * 4))[(i * dstDx + dstX) * 3 + j] =- m_rowBuffer[i * 3 + j];- }- }- } else if (channels == 1 && m_bit_depth == 8) {- for (int i = 0; i < count; i++) {- for (int j = 0; j < 3; j++) {- (m_tempBuffer.get() +- (dstY * rowBytes * 4))[(i * dstDx + dstX) * 3 + j] =- m_rowBuffer[i * 3 + j];- }- }- } else if (channels == 2 && m_bit_depth == 8) {- for (int i = 0; i < count; i++) {- for (int j = 0; j < 4; j++) {- (m_tempBuffer.get() +- (dstY * rowBytes * 4))[(i * dstDx + dstX) * 4 + j] =- m_rowBuffer[i * 4 + j];- }- }- } else if ((channels == 1 || channels == 2) && m_bit_depth < 8) {- for (int i = 0; i < count; i++) {- for (int j = 0; j < 3; j++) {- (m_tempBuffer.get() + (dstY * lx * 3))[(i * dstDx + dstX) * 3 + j] =- m_rowBuffer[i * 3 + j];- }- }- } else {- for (int i = 0; i < count; i++) {- for (int j = 0; j < channels; j++) {- (m_tempBuffer.get() +- (dstY * rowBytes))[(i * dstDx + dstX) * channels + j] =- m_rowBuffer[i * channels + j];}+ pix->m = 65535;}}}-- void readLineInterlace(char *buffer, int x0, int x1, int shrink) {- // m_png_ptr->row_number è l'indice di riga che scorre quando chiamo la- // png_read_row- int rowNumber = png_get_current_row_number(m_png_ptr);- // numRows è il numero di righe processate in ogni passo- int numRows = (int)png_get_image_height(m_png_ptr, m_info_ptr) / 8;-- int passPng = png_get_current_pass_number(m_png_ptr);-- int passRow = 5 + (m_y & 1); // passo desiderato per la riga corrente-- int channels = png_get_channels(m_png_ptr, m_info_ptr);-- int rowBytes = png_get_rowbytes(m_png_ptr, m_info_ptr);- png_bytep row_pointer = m_rowBuffer.get();-- int lx = m_info.m_lx;-- while (passPng <= passRow &&- rowNumber <=- numRows) // finchè il passo d'interlacciamento è minore o uguale- // < //del passo desiderato effettua tante volte le lettura- // della riga- // quant'è il passo desiderato per quella riga- {- rowNumber = png_get_current_row_number(m_png_ptr);- png_read_row(m_png_ptr, row_pointer, NULL);- numRows = png_get_image_height(m_png_ptr, m_info_ptr);- // devo memorizzare la riga letta nel buffer di appoggio in base al passo- // di riga- // e al blocchetto di appartenenza della riga-- // copio i pixel che desidero nel buffer temporaneo-- // il membro di PngReader copyPixel deve tener conto della riga processata- // e del passo che si è effettuato ( e in base a quello so quanti pixel- // copiare!)-- if (m_bit_depth == 16) {- if (passPng == 0)- copyPixel(lx / 4, 0, 8, rowNumber * 8);- else if (passPng == 1)- copyPixel(lx / 4, 8, 8, rowNumber * 8);- else if (passPng == 2)- copyPixel(lx / 2, 0, 4, rowNumber * 8 + 4);- else if (passPng == 3)- copyPixel(lx / 2, 4, 4, rowNumber * 4);- else if (passPng == 4)- copyPixel(lx, 0, 2, rowNumber * 4 + 2);- else if (passPng == 5)- copyPixel(lx, 2, 2, rowNumber * 2);- else if (passPng == 6)- copyPixel(2 * lx, 0, 1, rowNumber * 2 + 1);- } else {- if (passPng == 0)- copyPixel((lx + 7) / 8, 0, 8, rowNumber * 8);- else if (passPng == 1)- copyPixel((lx + 3) / 8, 4, 8, rowNumber * 8);- else if (passPng == 2)- copyPixel((lx + 3) / 4, 0, 4, rowNumber * 8 + 4);- else if (passPng == 3)- copyPixel((lx + 1) / 4, 2, 4, rowNumber * 4);- else if (passPng == 4)- copyPixel((lx + 1) / 2, 0, 2, rowNumber * 4 + 2);- else if (passPng == 5)- copyPixel(lx / 2, 1, 2, rowNumber * 2);- else if (passPng == 6)- copyPixel(lx, 0, 1, rowNumber * 2 + 1);- }-- passPng = png_get_current_pass_number(m_png_ptr);- }-- // fase di copia- if (channels == 1 || channels == 2) {- if (m_bit_depth < 8)- memcpy(m_rowBuffer.get(), m_tempBuffer.get() + ((m_y)*lx * 3), lx * 3);- else- memcpy(m_rowBuffer.get(), m_tempBuffer.get() + ((m_y)*rowBytes * 4),- rowBytes * 4);- } else {- memcpy(m_rowBuffer.get(), m_tempBuffer.get() + ((m_y)*rowBytes),- rowBytes);- }-- // fase di copia vecchia- // memcpy(m_rowBuffer, m_tempBuffer+((m_y)*rowBytes), rowBytes);-- // tutto quello che segue lo metto in una funzione in cui scrivo il buffer- // di restituzione della readLine- // è una funzione comune alle ReadLine- writeRow(buffer, x0, x1);- }-- void readLineInterlace(short *buffer, int x0, int x1, int shrink) {- // m_png_ptr->row_number è l'indice di riga che scorre quando chiamo la- // png_read_row- int rowNumber = png_get_current_row_number(m_png_ptr);- // numRows è il numero di righe processate in ogni passo- int numRows = png_get_image_height(m_png_ptr, m_info_ptr) / 8;-- int passPng = png_get_current_pass_number(- m_png_ptr); // conosco il passo d'interlacciamento-- int passRow = 5 + (m_y & 1); // passo desiderato per la riga corrente-- int channels = png_get_channels(m_png_ptr, m_info_ptr);- int lx = m_info.m_lx;-- int rowBytes = png_get_rowbytes(m_png_ptr, m_info_ptr);- png_bytep row_pointer = m_rowBuffer.get();-- while (passPng <= passRow &&- rowNumber <- numRows) // finchè il passo d'interlacciamento è minore o uguale- // del passo desiderato effettua tante volte le lettura della riga- // quant'è il passo desiderato per quella riga- {- rowNumber = png_get_current_row_number(m_png_ptr);- png_read_row(m_png_ptr, row_pointer, NULL);- numRows = png_get_image_height(m_png_ptr, m_info_ptr);- int lx = m_info.m_lx;-- // devo memorizzare la riga letta nel buffer di appoggio in base al passo- // di riga- // e al blocchetto di appartenenza della riga-- // copio i pixel che desidero nel buffer temporaneo-- // il membro di PngReader copyPixel deve tener conto della riga processata- // e del passo che si è effettuato ( e in base a quello so quanti pixel- // copiare!)-- int channels = png_get_channels(m_png_ptr, m_info_ptr);-- if (passPng == 0)- copyPixel(lx / 4, 0, 8, rowNumber * 8);- else if (passPng == 1)- copyPixel(lx / 4, 8, 8, rowNumber * 8);- else if (passPng == 2)- copyPixel(lx / 2, 0, 4, rowNumber * 8 + 4);- else if (passPng == 3)- copyPixel(lx / 2, 4, 4, rowNumber * 4);- else if (passPng == 4)- copyPixel(lx, 0, 2, rowNumber * 4 + 2);- else if (passPng == 5)- copyPixel(lx, 2, 2, rowNumber * 2);- else if (passPng == 6)- copyPixel(2 * lx, 0, 1, rowNumber * 2 + 1);-- passPng = png_get_current_pass_number(m_png_ptr);- }-- // fase di copia- if (channels == 1 || channels == 2) {- memcpy(m_rowBuffer.get(), m_tempBuffer.get() + ((m_y)*rowBytes * 4),- rowBytes * 4);- } else {- memcpy(m_rowBuffer.get(), m_tempBuffer.get() + ((m_y)*rowBytes),- rowBytes);- }-- // fase di copia- // memcpy(m_rowBuffer, m_tempBuffer+((m_y)*rowBytes), rowBytes);-- // tutto quello che segue lo metto in una funzione in cui scrivo il buffer- // di restituzione della readLine- // è una funzione comune alle ReadLine- writeRow(buffer, x0, x1);- }};//=========================================================Tiio::PngWriterProperties::PngWriterProperties()- : m_matte("Alpha Channel", true)--{+ : m_matte("Alpha Channel", true), m_colormap("Colormap", nullptr) {bind(m_matte);+ bind(m_colormap);}void Tiio::PngWriterProperties::updateTranslation() {m_matte.setQStringName(tr("Alpha Channel"));+ m_colormap.setQStringName(tr("Colormap"));}//=========================================================@@ -780,237 +586,301 @@ class PngWriter final : public Tiio::Writer {png_infop m_info_ptr;FILE *m_chan;bool m_matte;- std::vector<TPixel> *m_colormap;+ bool m_written_end;+ const std::vector<TPixel32> *m_colormap;public:- PngWriter();- ~PngWriter();+ PngWriter()+ : m_png_ptr(0)+ , m_info_ptr(0)+ , m_chan(nullptr)+ , m_matte(true)+ , m_written_end(false)+ , m_colormap(nullptr) {}++ ~PngWriter() {+ // If an exception occurs in the destructor, we log the error but continue+ // trying to release resources to avoid leaks+ try {+ if (m_png_ptr && !m_written_end) {+ // Try to finalize writing if not done+ png_write_end(m_png_ptr, m_info_ptr);+ }+ } catch (...) {+ // Ignore exceptions in destructor+ }- void open(FILE *file, const TImageInfo &info) override;- void writeLine(char *buffer) override;- void writeLine(short *buffer) override;+ if (m_png_ptr) {+ png_destroy_write_struct(&m_png_ptr, &m_info_ptr);+ m_png_ptr = nullptr;+ m_info_ptr = nullptr;+ }- Tiio::RowOrder getRowOrder() const override { return Tiio::TOP2BOTTOM; }+ if (m_properties) {+ delete m_properties;+ m_properties = nullptr;+ }+ // Note: The FILE* is owned by the caller, we should not close it here+ // The caller is responsible for closing the file+ }- void flush() override;+ void open(FILE *file, const TImageInfo &info) override {+ // Null pointer check+ if (!file) {+ throw TException("Invalid file pointer (null)");+ }+ m_chan = file;+ m_info = info;- bool write64bitSupported() const override { return true; }- // m_matte is set to "Alpha Channel" property value in the function open()- bool writeAlphaSupported() const override { return m_matte; };-};+ m_png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr,+ nullptr);+ if (!m_png_ptr) {+ throw TException("Unable to create PNG write structure");+ }-//---------------------------------------------------------+ // Set error handler+ png_set_error_fn(m_png_ptr, nullptr, tnz_error_fun, nullptr);-PngWriter::PngWriter()- : m_png_ptr(0), m_info_ptr(0), m_matte(true), m_colormap(0) {}+ m_info_ptr = png_create_info_struct(m_png_ptr);+ if (!m_info_ptr) {+ png_destroy_write_struct(&m_png_ptr, nullptr);+ throw TException("Unable to create PNG info structure");+ }-//---------------------------------------------------------+ if (setjmp(png_jmpbuf(m_png_ptr))) {+ png_destroy_write_struct(&m_png_ptr, &m_info_ptr);+ throw TException("PNG write initialization failed");+ }-PngWriter::~PngWriter() {- if (m_png_ptr) {- png_destroy_write_struct(&m_png_ptr, &m_info_ptr);- }- if (m_chan) {- fflush(m_chan);- m_chan = 0;- }-}+ png_init_io(m_png_ptr, m_chan);-//-----------------------------------------------------------png_color palette[256];-png_byte alpha[1];--void PngWriter::open(FILE *file, const TImageInfo &info) {- m_info = info;- m_png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING,- (png_voidp)0, // user_error_ptr,- 0, // user_error_fn,- 0); // user_warning_fn);- if (!m_png_ptr) return;- m_info_ptr = png_create_info_struct(m_png_ptr);- if (!m_info_ptr) {- png_destroy_write_struct(&m_png_ptr, (png_infopp)0);- return;- }+ if (!m_properties) m_properties = new Tiio::PngWriterProperties();++ TBoolProperty *alphaProp = dynamic_cast<TBoolProperty *>(+ m_properties->getProperty("Alpha Channel"));+ m_matte = alphaProp ? alphaProp->getValue() : true;- m_chan = file;- png_init_io(m_png_ptr, m_chan);+ TPointerProperty *colormapProp =+ dynamic_cast<TPointerProperty *>(m_properties->getProperty("Colormap"));+ m_colormap = colormapProp ? static_cast<const std::vector<TPixel32> *>(+ colormapProp->getValue())+ : nullptr;- if (!m_properties) m_properties = new Tiio::PngWriterProperties();+ png_uint_32 x_pixels_per_meter = tround(m_info.m_dpix / 0.0254);+ png_uint_32 y_pixels_per_meter = tround(m_info.m_dpiy / 0.0254);- TBoolProperty *alphaProp =- (TBoolProperty *)(m_properties->getProperty("Alpha Channel"));- TPointerProperty *colormap =- (TPointerProperty *)(m_properties->getProperty("Colormap"));- m_matte = (alphaProp && alphaProp->getValue()) ? true : false;- if (colormap) m_colormap = (vector<TPixel> *)colormap->getValue();+ int colorType = PNG_COLOR_TYPE_RGB;+ int bitDepth = info.m_bitsPerSample;- TUINT32 x_pixels_per_meter = tround(m_info.m_dpix / 0.0254);- TUINT32 y_pixels_per_meter = tround(m_info.m_dpiy / 0.0254);+ if (m_colormap) {+ colorType = PNG_COLOR_TYPE_PALETTE;+ bitDepth = 8; // Palettes are always 8-bit++ // Validate palette size+ if (m_colormap->size() > 256) {+ throw TException("Palette too large (max 256 colors)");+ }+ } else if (m_matte) {+ colorType = PNG_COLOR_TYPE_RGB_ALPHA;+ }- if (!m_colormap)- png_set_IHDR(m_png_ptr, m_info_ptr, m_info.m_lx, m_info.m_ly,- info.m_bitsPerSample,- m_matte ? PNG_COLOR_TYPE_RGB_ALPHA : PNG_COLOR_TYPE_RGB,- PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT,+ png_set_IHDR(m_png_ptr, m_info_ptr, m_info.m_lx, m_info.m_ly, bitDepth,+ colorType, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT,PNG_FILTER_TYPE_DEFAULT);- else {- png_set_IHDR(m_png_ptr, m_info_ptr, m_info.m_lx, m_info.m_ly, 8,- PNG_COLOR_TYPE_PALETTE, PNG_INTERLACE_NONE,- PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);- for (unsigned int i = 0; i < m_colormap->size(); i++) {- /*unsigned char red = (i>>5)&0x7;- unsigned char green = (i>>2)&0x7;- unsigned char blue = i&0x3;- palette[i].red = (red>>1) | (red<<2) | (red<<5);- palette[i].green = (green>>1) | (green<<2) | (green<<5);- palette[i].blue = blue | (blue<<2) | (blue<<4) | (blue<<6);- if (red==0 && green==0) alpha[i] = 0; else if (blue==0 && green==0)- alpha[i] = 128; else alpha[i] = 255;*/- palette[i].red = (*m_colormap)[i].r;- palette[i].green = (*m_colormap)[i].g;- palette[i].blue = (*m_colormap)[i].b;- }-- png_set_PLTE(m_png_ptr, m_info_ptr, palette, m_colormap->size());- }- // png_set_dither(m_png_ptr, palette, 256, 256, 0, 1);+ // Configure palette if needed+ if (m_colormap) {+ png_color palette[256];+ size_t paletteSize = std::min(m_colormap->size(), (size_t)256);++ for (size_t i = 0; i < paletteSize; ++i) {+ palette[i].red = (*m_colormap)[i].r;+ palette[i].green = (*m_colormap)[i].g;+ palette[i].blue = (*m_colormap)[i].b;+ }++ png_set_PLTE(m_png_ptr, m_info_ptr, palette, (int)paletteSize);++ // Add transparency information if matte is enabled+ if (m_matte) {+ // Create transparency array - assume index 0 is transparent if alpha is+ // 0+ png_byte trans = 0;+ png_set_tRNS(m_png_ptr, m_info_ptr, &trans, 1, nullptr);+ }+ }#if defined(TNZ_MACHINE_CHANNEL_ORDER_MBGR)- png_set_bgr(m_png_ptr);- png_set_swap_alpha(m_png_ptr);+ png_set_bgr(m_png_ptr);+ png_set_swap_alpha(m_png_ptr);#elif defined(TNZ_MACHINE_CHANNEL_ORDER_BGRM)- png_set_bgr(m_png_ptr);+ png_set_bgr(m_png_ptr);#elif defined(TNZ_MACHINE_CHANNEL_ORDER_MRGB)- png_set_swap_alpha(m_png_ptr);+ png_set_swap_alpha(m_png_ptr);#elif !defined(TNZ_MACHINE_CHANNEL_ORDER_RGBM)-#error "unknownchannel order"+#error "unknown channel order"#endif- png_set_pHYs(m_png_ptr, m_info_ptr, x_pixels_per_meter, y_pixels_per_meter,- 1);+ png_set_pHYs(m_png_ptr, m_info_ptr, x_pixels_per_meter, y_pixels_per_meter,+ PNG_RESOLUTION_METER);- if (m_colormap && m_matte) {- alpha[0] = 0;- // png_set_tRNS(m_png_ptr, m_info_ptr, alpha, 1, PNG_COLOR_TYPE_PALETTE);- png_color_16 bgcolor;- bgcolor.index = 0;- png_set_tRNS(m_png_ptr, m_info_ptr, alpha, 1, &bgcolor);+ png_write_info(m_png_ptr, m_info_ptr);}- png_write_info(m_png_ptr, m_info_ptr);-}+ void writeLine(char *buffer) override {+ if (setjmp(png_jmpbuf(m_png_ptr))) {+ throw TException("PNG write error");+ }-//---------------------------------------------------------+ if (!buffer) {+ throw TException("Invalid buffer");+ }-void PngWriter::flush() {- png_write_end(m_png_ptr, m_info_ptr);- fflush(m_chan);-}+ // Handle palette mode+ if (m_colormap) {+ // For palette mode, buffer should contain palette indices (0-255)+ png_write_row(m_png_ptr, (unsigned char *)buffer);+ return;+ }-//---------------------------------------------------------+ // Normal RGBA or RGB mode: std::vector used instead of manual allocation+ std::vector<unsigned char> row(m_info.m_lx * (m_matte ? 4 : 3));+ TPixel32 *pix = (TPixel32 *)buffer;+ int k = 0;-void PngWriter::writeLine(short *buffer) {- {- TPixel64 *pix = (TPixel64 *)buffer;- unsigned short *tmp;- tmp = (unsigned short *)malloc((m_info.m_lx + 1) * 3);- // unsigned short tmp[10000];- int k = 0;- for (int j = 0; j < m_info.m_lx; j++, pix++) {- // depremultiply here- TPixel64 depremult_pix(*pix);- if (m_matte && depremult_pix.m != 0) depremult(depremult_pix);+ for (int j = 0; j < m_info.m_lx; ++j, ++pix) {+ int required = k + (m_matte ? 4 : 3);+ if (required > static_cast<int>(row.size())) {+ break; // Prevent buffer overflow+ }++ TPixel32 depix = *pix;+ if (m_matte && depix.m != 0) depremult(depix);+ if (m_matte) {+#if defined(TNZ_MACHINE_CHANNEL_ORDER_MRGB)+ row[k++] = depix.m;+ row[k++] = depix.r;+ row[k++] = depix.g;+ row[k++] = depix.b;+#elif defined(TNZ_MACHINE_CHANNEL_ORDER_RGBM)+ row[k++] = depix.r;+ row[k++] = depix.g;+ row[k++] = depix.b;+ row[k++] = depix.m;+#elif defined(TNZ_MACHINE_CHANNEL_ORDER_MBGR)+ row[k++] = depix.m;+ row[k++] = depix.b;+ row[k++] = depix.g;+ row[k++] = depix.r;+#elif defined(TNZ_MACHINE_CHANNEL_ORDER_BGRM)+ row[k++] = depix.b;+ row[k++] = depix.g;+ row[k++] = depix.r;+ row[k++] = depix.m;+#else+#error "unknown channel order"+#endif+ } else {#if defined(TNZ_MACHINE_CHANNEL_ORDER_MRGB) || \defined(TNZ_MACHINE_CHANNEL_ORDER_RGBM)- tmp[k++] = mySwap(pix->r);- tmp[k++] = mySwap(pix->g);- tmp[k++] = mySwap(pix->b);+ row[k++] = depix.r;+ row[k++] = depix.g;+ row[k++] = depix.b;#elif defined(TNZ_MACHINE_CHANNEL_ORDER_MBGR) || \defined(TNZ_MACHINE_CHANNEL_ORDER_BGRM)- tmp[k++] = mySwap(pix->b);- tmp[k++] = mySwap(pix->g);- tmp[k++] = mySwap(pix->r);+ row[k++] = depix.b;+ row[k++] = depix.g;+ row[k++] = depix.r;#else#error "unknown channel order"#endif- if (m_matte)- tmp[k++] = mySwap(pix->m); // ?? does it take care MRGB or MBGR case?+ }}- png_write_row(m_png_ptr, (unsigned char *)tmp);+ png_write_row(m_png_ptr, row.data());}-}-//=========================================================+ void writeLine(short *buffer) override {+ if (m_colormap) {+ // Palette mode doesn't support 16-bit+ throw TException("Palette mode doesn't support 16-bit data");+ }-void PngWriter::writeLine(char *buffer) {- // TBoolProperty* alphaProp =- // (TBoolProperty*)(m_properties->getProperty("Alpha Channel"));- if (m_matte || m_colormap) {- unsigned char *tmp = new unsigned char[(m_info.m_lx + 1) * 4];- TPixel32 *pix = (TPixel32 *)buffer;- int k = 0;- for (int j = 0; j < m_info.m_lx; j++, pix++) {- // depremultiply here- TPixel32 depremult_pix(*pix);- if (depremult_pix.m != 0) depremult(depremult_pix);-#if defined(TNZ_MACHINE_CHANNEL_ORDER_MRGB)- tmp[k++] = depremult_pix.m;- tmp[k++] = depremult_pix.r;- tmp[k++] = depremult_pix.g;- tmp[k++] = depremult_pix.b;-#elif defined(TNZ_MACHINE_CHANNEL_ORDER_RGBM)- tmp[k++] = depremult_pix.r;- tmp[k++] = depremult_pix.g;- tmp[k++] = depremult_pix.b;- tmp[k++] = depremult_pix.m;-#elif defined(TNZ_MACHINE_CHANNEL_ORDER_MBGR)- tmp[k++] = depremult_pix.m;- tmp[k++] = depremult_pix.b;- tmp[k++] = depremult_pix.g;- tmp[k++] = depremult_pix.r;-#elif defined(TNZ_MACHINE_CHANNEL_ORDER_BGRM)- tmp[k++] = depremult_pix.b;- tmp[k++] = depremult_pix.g;- tmp[k++] = depremult_pix.r;- tmp[k++] = depremult_pix.m;-#else-#error "unknown channel order"-#endif+ if (setjmp(png_jmpbuf(m_png_ptr))) {+ throw TException("PNG write error");+ }++ if (!buffer) {+ throw TException("Invalid buffer");}- png_write_row(m_png_ptr, tmp);- delete[] tmp;- } else {- TPixel32 *pix = (TPixel32 *)buffer;- unsigned char *tmp = new unsigned char[(m_info.m_lx + 1) * 3];- int k = 0;- for (int j = 0; j < m_info.m_lx; j++) {- // tmp = (pix->r&0xe0)|((pix->g&0xe0)>>3) | ((pix->b&0xc0)>>6);+ // Using std::vector instead of manual allocation+ std::vector<unsigned short> row(m_info.m_lx * (m_matte ? 4 : 3));+ TPixel64 *pix = (TPixel64 *)buffer;+ int k = 0;++ for (int j = 0; j < m_info.m_lx; ++j, ++pix) {+ int required = k + (m_matte ? 4 : 3);+ if (required > static_cast<int>(row.size())) {+ break; // Prevent buffer overflow+ }++ TPixel64 depix = *pix;+ if (m_matte && depix.m != 0) depremult(depix);+ if (m_matte) {#if defined(TNZ_MACHINE_CHANNEL_ORDER_MRGB) || \defined(TNZ_MACHINE_CHANNEL_ORDER_RGBM)- tmp[k++] = pix->r;- tmp[k++] = pix->g;- tmp[k++] = pix->b;+ row[k++] = mySwap(depix.r);+ row[k++] = mySwap(depix.g);+ row[k++] = mySwap(depix.b);+ row[k++] = mySwap(depix.m);#elif defined(TNZ_MACHINE_CHANNEL_ORDER_MBGR) || \defined(TNZ_MACHINE_CHANNEL_ORDER_BGRM)- tmp[k++] = pix->b;- tmp[k++] = pix->g;- tmp[k++] = pix->r;+ row[k++] = mySwap(depix.b);+ row[k++] = mySwap(depix.g);+ row[k++] = mySwap(depix.r);+ row[k++] = mySwap(depix.m);#else#error "unknown channel order"#endif+ } else {+#if defined(TNZ_MACHINE_CHANNEL_ORDER_MRGB) || \+ defined(TNZ_MACHINE_CHANNEL_ORDER_RGBM)+ row[k++] = mySwap(depix.r);+ row[k++] = mySwap(depix.g);+ row[k++] = mySwap(depix.b);+#elif defined(TNZ_MACHINE_CHANNEL_ORDER_MBGR) || \+ defined(TNZ_MACHINE_CHANNEL_ORDER_BGRM)+ row[k++] = mySwap(depix.b);+ row[k++] = mySwap(depix.g);+ row[k++] = mySwap(depix.r);+#else+#error "unknown channel order"+#endif+ }+ }+ png_write_row(m_png_ptr, reinterpret_cast<unsigned char *>(row.data()));+ }++ void flush() override {+ if (setjmp(png_jmpbuf(m_png_ptr))) {+ throw TException("PNG write error during flush");+ }+ png_write_end(m_png_ptr, m_info_ptr);+ m_written_end = true;- ++pix;+ if (m_chan) {+ fflush(m_chan);}- png_write_row(m_png_ptr, tmp);- delete[] tmp;}-}++ Tiio::RowOrder getRowOrder() const override { return Tiio::TOP2BOTTOM; }++ bool write64bitSupported() const override { return true; }++ bool writeAlphaSupported() const override { return m_matte; }+};//=========================================================diff --git a/toonz/sources/image/png/tiio_png.h b/toonz/sources/image/png/tiio_png.hindex ff2e2d848..4dfa62923 100644--- a/toonz/sources/image/png/tiio_png.h+++ b/toonz/sources/image/png/tiio_png.h@@ -1,10 +1,10 @@#pragma once-#ifndef TTIO_PNG_INCLUDED-#define TTIO_PNG_INCLUDED+#ifndef TIIO_PNG_INCLUDED+#define TIIO_PNG_INCLUDED#include "tiio.h"-//#include "timage_io.h"+// #include "timage_io.h"#include "tproperty.h"#include <QCoreApplication>@@ -19,6 +19,7 @@ class PngWriterProperties final : public TPropertyGroup {public:// TEnumProperty m_pixelSize;TBoolProperty m_matte;+ TPointerProperty m_colormap;PngWriterProperties();void updateTranslation() override;@@ -29,6 +30,6 @@ public:Tiio::Reader *makePngReader();Tiio::Writer *makePngWriter();-} // namespace+} // namespace Tiio-#endif+#endif // TIIO_PNG_INCLUDEDdiff --git a/toonz/sources/image/sgi/filesgi.cpp b/toonz/sources/image/sgi/filesgi.cppindex 4f172c1b9..cfd358e11 100644--- a/toonz/sources/image/sgi/filesgi.cpp+++ b/toonz/sources/image/sgi/filesgi.cpp@@ -12,7 +12,7 @@#include "tpixelgr.h"#include "../compatibility/tfile_io.h"#if defined(LINUX) || defined(FREEBSD)-//#define _XOPEN_SOURCE_EXTENDED+// #define _XOPEN_SOURCE_EXTENDED#include <string.h>#endif@@ -29,6 +29,7 @@#endif#include <assert.h>+#include <memory>#ifdef _WIN32#include <io.h>@@ -36,59 +37,54 @@#else#ifndef LINUX#include <strings.h>-#endif#include <unistd.h>#endif#include <stdarg.h>using namespace std;-//-// IMAGERGB:-// header file per le immagini sgi-//++// IMAGERGB: SGI image header structurestruct IMAGERGB {- unsigned short imagic; /* stuff saved on disk . . */- unsigned short type;- unsigned short dim;- unsigned short xsize;- unsigned short ysize;- unsigned short zsize;- TUINT32 min;- TUINT32 max;- TUINT32 wastebytes;- char name[80];- TUINT32 colormap;-- TINT32 file; /* stuff used in core only */- unsigned short flags;- short dorev;- short x;- short y;- short z;- short cnt;- unsigned short *ptr;- unsigned short *base;- unsigned short *tmpbuf;- TUINT32 offset;- TUINT32 rleend; /* for rle images */- TUINT32 *rowstart; /* for rle images */- TINT32 *rowsize; /* for rle images */+ unsigned short imagic; // Magic number+ unsigned short type; // Image type+ unsigned short dim; // Image dimensions+ unsigned short xsize; // Width+ unsigned short ysize; // Height+ unsigned short zsize; // Depth (channels)+ TUINT32 min; // Minimum pixel value+ TUINT32 max; // Maximum pixel value+ TUINT32 wastebytes; // Unused bytes+ char name[80]; // Image name+ TUINT32 colormap; // Colormap type++ TINT32 file; // File descriptor (in core only)+ unsigned short flags; // File flags+ short dorev; // Byte swapping needed+ short x; // Current x position+ short y; // Current y position+ short z; // Current z position+ short cnt; // Count+ unsigned short *ptr; // Current pointer+ unsigned short *base; // Base pointer+ unsigned short *tmpbuf; // Temporary buffer+ TUINT32 offset; // File offset+ TUINT32 rleend; // For RLE images+ TUINT32 *rowstart; // For RLE images+ TINT32 *rowsize; // For RLE images};const int IMAGERGB_HEADER_SIZE = sizeof(IMAGERGB);-//-// macro definite nel vecchio ImageP/filergb.h-//+// Macros defined in the old ImageP/filergb.h#define IMAGIC 0732#define TYPEMASK 0xff00#define ITYPE_RLE 0x0100-#define ISRLE(type) (((type)&0xff00) == ITYPE_RLE)+#define ISRLE(type) (((type) & 0xff00) == ITYPE_RLE)#define ITYPE_VERBATIM 0x0000-#define ISVERBATIM(type) (((type)&0xff00) == ITYPE_VERBATIM)+#define ISVERBATIM(type) (((type) & 0xff00) == ITYPE_VERBATIM)#define BPPMASK 0x00ff-#define BPP(type) ((type)&BPPMASK)+#define BPP(type) ((type) & BPPMASK)#define RLE(bpp) (ITYPE_RLE | (bpp))#define VERBATIM(bpp) (ITYPE_VERBATIM | (bpp))#define IBUFSIZE(pixels) ((pixels + (pixels >> 6)) << 2)@@ -101,6 +97,7 @@ const int IMAGERGB_HEADER_SIZE = sizeof(IMAGERGB);#define _IOERR 0x20#endif+// Forward declarationsstatic USHORT *ibufalloc(IMAGERGB *image, int bpp);static void cvtshorts(USHORT buffer[], TINT32 n);static void cvtTINT32s(TUINT32 *buffer, TINT32 n);@@ -120,7 +117,7 @@ static int iflush(IMAGERGB *image);/*-------------------------------------------------------------------------*/static int do_rgb_write_header(IMAGERGB *img, int fd) {- // DOBBIAMO SWAPPPPARE ?????????????????+ // Do we need to swap bytes?int count = 0;count += write(fd, &img->imagic, (int)sizeof(unsigned short));count += write(fd, &img->type, (int)sizeof(unsigned short));@@ -148,8 +145,7 @@ static int do_rgb_write_header(IMAGERGB *img, int fd) {count += write(fd, &img->rleend, (int)sizeof(TUINT32));count += write(fd, &img->rowstart, (int)sizeof(TUINT32 *));count += write(fd, &img->rowsize, (int)sizeof(TINT32 *));- if (sizeof(void *) == 8) // siamo a 64bit: l'header side ha dei padding- // bytes.+ if (sizeof(void *) == 8) // 64-bit: header has padding bytescount = (count + 0x7) & (~0x7);return count;}@@ -157,7 +153,7 @@ static int do_rgb_write_header(IMAGERGB *img, int fd) {/*-------------------------------------------------------------------------*/static int do_rgb_read_header(IMAGERGB *img, int fd) {- // DOBBIAMO SWAPPPPARE ?????????????????+ // Do we need to swap bytes?int count = 0;count += read(fd, &img->imagic, sizeof(unsigned short));count += read(fd, &img->type, sizeof(unsigned short));@@ -185,8 +181,7 @@ static int do_rgb_read_header(IMAGERGB *img, int fd) {count += read(fd, &img->rleend, sizeof(TUINT32));count += read(fd, &img->rowstart, sizeof(TUINT32 *));count += read(fd, &img->rowsize, sizeof(TINT32 *));- if (sizeof(void *) == 8) // siamo a 64bit: l'header side ha dei padding- // bytes.+ if (sizeof(void *) == 8) // 64-bit: header has padding bytescount = (count + 0x7) & (~0x7);return count;}@@ -199,17 +194,19 @@ enum OpenMode { OpenRead, OpenWrite };static IMAGERGB *iopen(int fd, OpenMode openMode, unsigned int type,unsigned int dim, unsigned int xsize, unsigned int ysize,unsigned int zsize, short dorev) {- IMAGERGB *image;- extern int errno;- int tablesize, f = fd;+ IMAGERGB *image = nullptr;+ int tablesize;+ int f = fd;image = (IMAGERGB *)malloc((int)sizeof(IMAGERGB));+ if (!image) {+ return nullptr;+ }memset(image, 0, sizeof(IMAGERGB));if (openMode == OpenWrite) {- // WRITE-+ // WRITE modeimage->imagic = IMAGIC;image->type = type;image->xsize = xsize;@@ -217,11 +214,10 @@ static IMAGERGB *iopen(int fd, OpenMode openMode, unsigned int type,image->zsize = 1;if (dim > 1) image->ysize = ysize;-if (dim > 2) image->zsize = zsize;if (image->zsize == 1) {- image->dim = 2;+ image->dim = 2;if (image->ysize == 1) image->dim = 1;} else {image->dim = 3;@@ -230,29 +226,34 @@ static IMAGERGB *iopen(int fd, OpenMode openMode, unsigned int type,image->min = 10000000;image->max = 0;strncpy(image->name, "no name", 80);+ image->name[79] = '\0'; // Ensure null terminationimage->wastebytes = 0;image->dorev = dorev;if (do_rgb_write_header(image, f) != IMAGERGB_HEADER_SIZE) {cout << "iopen: error on write of image header\n" << endl;- return NULL;+ free(image);+ return nullptr;}image->flags = _IOWRT;} else {- // READ+ // READ modeif (do_rgb_read_header(image, f) != IMAGERGB_HEADER_SIZE) {cout << "iopen: error on read of image header" << endl;- return NULL;+ free(image);+ return nullptr;}if (((image->imagic >> 8) | ((image->imagic & 0xff) << 8)) == IMAGIC) {image->dorev = 1;cvtimage(image);- } else+ } else {image->dorev = 0;+ }if (image->imagic != IMAGIC) {cout << "iopen: bad magic in image file " << image->imagic << endl;- return NULL;+ free(image);+ return nullptr;}image->flags = _IOREAD;}@@ -262,115 +263,111 @@ static IMAGERGB *iopen(int fd, OpenMode openMode, unsigned int type,image->rowstart = (TUINT32 *)malloc(tablesize);image->rowsize = (TINT32 *)malloc(tablesize);- if (image->rowstart == 0 || image->rowsize == 0) {+ if (image->rowstart == nullptr || image->rowsize == nullptr) {cout << "iopen: error on table alloc" << endl;- return NULL;+ free(image->rowstart);+ free(image->rowsize);+ free(image);+ return nullptr;}image->rleend = 512L + 2 * tablesize;if (openMode == OpenWrite) {- // WRITE+ // WRITE mode - initialize tablesint max = image->ysize * image->zsize;for (int i = 0; i < max; i++) {image->rowstart[i] = 0;image->rowsize[i] = -1;}} else {- // READ+ // READ mode - load tablestablesize = image->ysize * image->zsize * (int)sizeof(TINT32);lseek(f, 512L, 0);if (read(f, image->rowstart, tablesize) != tablesize) {-#ifdef _WIN32- DWORD error;- error = GetLastError();-#endifTSystem::outputDebug("iopen: error on read of rowstart\n");- return NULL;+ free(image->rowstart);+ free(image->rowsize);+ free(image);+ return nullptr;}if (image->dorev) cvtTINT32s(image->rowstart, tablesize);if (read(f, image->rowsize, tablesize) != tablesize) {-#ifdef _WIN32- DWORD error;- error = GetLastError();-#endifTSystem::outputDebug("iopen: error on read of rowsize\n");- return NULL;+ free(image->rowstart);+ free(image->rowsize);+ free(image);+ return nullptr;}if (image->dorev) cvtTINT32s((TUINT32 *)image->rowsize, tablesize);}- } // END ISRLE+ }image->cnt = 0;- image->ptr = 0;- image->base = 0;+ image->ptr = nullptr;+ image->base = nullptr;- if ((image->tmpbuf = ibufalloc(image, BPP(image->type))) == 0) {+ if ((image->tmpbuf = ibufalloc(image, BPP(image->type))) == nullptr) {char xs[1024];snprintf(xs, sizeof(xs), "%d", image->xsize);-TSystem::outputDebug(string("iopen: error on tmpbuf alloc %d\n") + xs);- return NULL;+ if (ISRLE(image->type)) {+ free(image->rowstart);+ free(image->rowsize);+ }+ free(image);+ return nullptr;}image->x = image->y = image->z = 0;image->file = fd;- image->offset = 512L; // set up for img_optseek+ image->offset = 512L; // Set up for img_optseeklseek((int)image->file, 512L, 0);- return (image);+ return image;}/*-------------------------------------------------------------------------*/static USHORT *ibufalloc(IMAGERGB *image, int bpp) {- return (USHORT *)malloc(IBUFSIZE(image->xsize) * bpp);+ size_t size = IBUFSIZE(image->xsize) * bpp;+ if (size == 0) return nullptr;+ return (USHORT *)malloc(size);}-/*-------------------------------------------------------------------------*/-/*- Inverte gli short del buffer-*/-+/*-----------------------------------------------------------------------------+ * Swap bytes in short buffer+ *----------------------------------------------------------------------------*/static void cvtshorts(unsigned short buffer[], TINT32 n) {TINT32 nshorts = n >> 1;for (int i = 0; i < nshorts; i++) {unsigned short swrd = *buffer;*buffer++ = (swrd >> 8) | (swrd << 8);}- return;}-/*-----------------------------------------------------------------------------*/-/*- * INVERTE I LONG DEL BUFFER- */-/*-----------------------------------------------------------------------------*/-+/*-----------------------------------------------------------------------------+ * Swap bytes in long buffer+ *----------------------------------------------------------------------------*/static void cvtTINT32s(TUINT32 buffer[], TINT32 n) {TINT32 nTINT32s = n >> 2;for (int i = 0; i < nTINT32s; i++) {TUINT32 lwrd = buffer[i];- buffer[i] = ((lwrd >> 24) | (lwrd >> 8 & 0xff00) | (lwrd << 8 & 0xff0000) |- (lwrd << 24));+ buffer[i] = ((lwrd >> 24) | ((lwrd >> 8) & 0xff00) |+ ((lwrd << 8) & 0xff0000) | (lwrd << 24));}- return;}-/*-----------------------------------------------------------------------------*/-/*- * INVERTE I LONG E GLI SHORT DEL BUFFER-*/-/*-----------------------------------------------------------------------------*/-+/*-----------------------------------------------------------------------------+ * Swap bytes in image header+ *----------------------------------------------------------------------------*/static void cvtimage(IMAGERGB *image) {TUINT32 *buffer = (TUINT32 *)image;cvtshorts((unsigned short *)buffer, 12);cvtTINT32s(buffer + 3, 12);cvtTINT32s(buffer + 26, 4);- return;}/*-----------------------------------------------------------------------------*/@@ -380,19 +377,16 @@ static void cvtimage(IMAGERGB *image) {pixel = *iptr++; \if (!(count = (pixel & 0x7f))) return; \if (pixel & 0x80) { \- while (count--) *optr++ = (TYPE)*iptr++; \+ while (count--) *optr++ = (TYPE) * iptr++; \} else { \- pixel = *iptr++; \+ pixel = *iptr++; \while (count--) *optr++ = (TYPE)pixel; \} \}-/*-----------------------------------------------------------------------------*/-/*- * ESPANDE UNA IMMAGINE FORMATO RGB-RLE-*/-/*-----------------------------------------------------------------------------*/-+/*-----------------------------------------------------------------------------+ * Expand RLE-compressed RGB image+ *----------------------------------------------------------------------------*/static void img_rle_expand(unsigned short *rlebuf, int ibpp,unsigned short *expbuf, int obpp) {if (ibpp == 1 && obpp == 1) {@@ -419,16 +413,14 @@ static void img_rle_expand(unsigned short *rlebuf, int ibpp,unsigned short pixel, count;EXPAND_CODE(unsigned short);- } else- cout << "rle_expand: bad bpp: " << ibpp << obpp << endl;+ } else {+ cout << "rle_expand: bad bpp: " << ibpp << " " << obpp << endl;+ }}-/*-----------------------------------------------------------------------------*/-/*- * RITORNA L'AMPIEZZA DELLA RIGA DI UN IMMAGINE RGB-*/-/*-----------------------------------------------------------------------------*/-+/*-----------------------------------------------------------------------------+ * Get row size of RGB image+ *----------------------------------------------------------------------------*/static int img_getrowsize(IMAGERGB *image) {switch (image->dim) {case 1:@@ -441,12 +433,9 @@ static int img_getrowsize(IMAGERGB *image) {return 0;}-/*-----------------------------------------------------------------------------*/-/*- * SPOSTA IL PUNTATORE AL FILE RGB-*/-/*-----------------------------------------------------------------------------*/-+/*-----------------------------------------------------------------------------+ * Seek to position in RGB file+ *----------------------------------------------------------------------------*/static TUINT32 img_optseek(IMAGERGB *image, TUINT32 offset) {if (image->offset != offset) {image->offset = offset;@@ -455,43 +444,32 @@ static TUINT32 img_optseek(IMAGERGB *image, TUINT32 offset) {return offset;}-/*-----------------------------------------------------------------------------*/-/*- * LEGGE DAL FILE RGB E RIEMPE IL BUFFER-*/-/*-----------------------------------------------------------------------------*/-+/*-----------------------------------------------------------------------------+ * Read from RGB file into buffer+ *----------------------------------------------------------------------------*/static TINT32 rgb_img_read(IMAGERGB *image, char *buffer, TINT32 count) {TINT32 retval;retval = read(image->file, buffer, count);- if (retval == count)+ if (retval == count) {image->offset += count;- else- // BRUTTO: ma qui non ci si deve mai passare, serve per fare un crash+ } else {+ // Error: set offset to invalid valueimage->offset = (TUINT32)-1;+ }return retval;}-/*-----------------------------------------------------------------------------*/-/*- * CONTROLLA SE LA RIGA CORRENTE DELL'IMMAGINE RGB E' VALIDA-*/-/*-----------------------------------------------------------------------------*/-+/*-----------------------------------------------------------------------------+ * Check if current row of RGB image is valid+ *----------------------------------------------------------------------------*/static int img_badrow(IMAGERGB *image, int y, int z) {- if (y >= image->ysize || z >= image->zsize)- return 1;- else- return 0;+ return (y >= image->ysize || z >= image->zsize) ? 1 : 0;}-/*-----------------------------------------------------------------------------*/-/*- * POSIZIONA IL PUNTATORE AL FILE RGB ALL'INIZIO DELL'AREA DATI IMMAGINE- */-/*-----------------------------------------------------------------------------*/-+/*-----------------------------------------------------------------------------+ * Seek to image data area in RGB file+ *----------------------------------------------------------------------------*/static TUINT32 img_seek(IMAGERGB *image, unsigned int y, unsigned int z,unsigned int offs) {if (img_badrow(image, y, z)) {@@ -529,23 +507,21 @@ static TUINT32 img_seek(IMAGERGB *image, unsigned int y, unsigned int z,cout << "img_seek: weird dim" << endl;break;}- } else+ } else {cout << "img_seek: weird image type" << endl;+ }return 0;}-/*-----------------------------------------------------------------------------*/-/*- Legge una riga (compressa/non compressa) di un file RGB.-*/-+/*-----------------------------------------------------------------------------+ * Read a row (compressed/uncompressed) from RGB file.+ *----------------------------------------------------------------------------*/static int new_getrow(IMAGERGB *image, void *buffer, UINT y, UINT z) {short cnt;if (!(image->flags & (_IORW | _IOREAD))) return -1;if (image->dim < 3) z = 0;-if (image->dim < 2) y = 0;img_seek(image, y, z, 0);@@ -555,7 +531,6 @@ static int new_getrow(IMAGERGB *image, void *buffer, UINT y, UINT z) {case 1:if (rgb_img_read(image, (char *)buffer, image->xsize) != image->xsize)return -1;-return image->xsize;case 2:cnt = image->xsize << 1;@@ -592,34 +567,34 @@ static int new_getrow(IMAGERGB *image, void *buffer, UINT y, UINT z) {cout << "getrow: weird bpp" << endl;break;}- } else+ } else {cout << "getrow: weird image type" << endl;+ }return -1;}-/*-----------------------------------------------------------------------------*/-/*- * ROBA PRESA DA ASMWRITERGB.C- */-/*-----------------------------------------------------------------------------*/-+/*-----------------------------------------------------------------------------+ * Code taken from ASMWRITERGB.C+ *----------------------------------------------------------------------------*/static TINT32 RGB_img_write(IMAGERGB *image, char *buffer, TINT32 count) {TINT32 retval;retval = write(image->file, buffer, count);- if (retval == count)+ if (retval == count) {image->offset += count;- else+ } else {image->offset = (TUINT32)-1;+ }return retval;}/*-----------------------------------------------------------------------------*/static void img_setrowsize(IMAGERGB *image, UINT cnt, UINT y, UINT z) {- TINT32 *sizeptr = 0;+ TINT32 *sizeptr = nullptr;if (img_badrow(image, y, z)) return;+switch (image->dim) {case 1:sizeptr = &image->rowsize[0];@@ -632,7 +607,9 @@ static void img_setrowsize(IMAGERGB *image, UINT cnt, UINT y, UINT z) {case 3:sizeptr = &image->rowsize[y + z * image->ysize];image->rowstart[y + z * image->ysize] = image->rleend;+ break;}+if (*sizeptr != -1) image->wastebytes += *sizeptr;*sizeptr = (TINT32)cnt;image->rleend += cnt;@@ -652,8 +629,8 @@ static void img_setrowsize(IMAGERGB *image, UINT cnt, UINT y, UINT z) {while (count) { \todo = (TYPE)(count > 126 ? 126 : count); \count -= todo; \- *optr++ = (TYPE)(0x80 | todo); \- while (todo--) *optr++ = (TYPE)*sptr++; \+ *optr++ = (TYPE)(0x80 | todo); \+ while (todo--) *optr++ = (TYPE) * sptr++; \} \sptr = iptr; \cc = *iptr++; \@@ -681,7 +658,7 @@ static TINT32 img_rle_compact(unsigned short *expbuf, int ibpp,TINT32 count;COMPACT_CODE(unsigned char);- return optr - (unsigned char *)rlebuf;+ return (TINT32)(optr - (unsigned char *)rlebuf);} else if (ibpp == 1 && obpp == 2) {unsigned char *iptr = (unsigned char *)expbuf;unsigned char *ibufend = iptr + cnt;@@ -691,7 +668,7 @@ static TINT32 img_rle_compact(unsigned short *expbuf, int ibpp,TINT32 count;COMPACT_CODE(unsigned short);- return optr - rlebuf;+ return (TINT32)(optr - rlebuf);} else if (ibpp == 2 && obpp == 1) {unsigned short *iptr = expbuf;unsigned short *ibufend = iptr + cnt;@@ -701,7 +678,7 @@ static TINT32 img_rle_compact(unsigned short *expbuf, int ibpp,TINT32 count;COMPACT_CODE(unsigned char);- return optr - (unsigned char *)rlebuf;+ return (TINT32)(optr - (unsigned char *)rlebuf);} else if (ibpp == 2 && obpp == 2) {unsigned short *iptr = expbuf;unsigned short *ibufend = iptr + cnt;@@ -711,9 +688,9 @@ static TINT32 img_rle_compact(unsigned short *expbuf, int ibpp,TINT32 count;COMPACT_CODE(unsigned short);- return optr - rlebuf;+ return (TINT32)(optr - rlebuf);} else {- cout << "rle_compact: bad bpp: %d %d" << ibpp << obpp;+ cout << "rle_compact: bad bpp: " << ibpp << " " << obpp;return 0;}}@@ -723,16 +700,18 @@ static TINT32 img_rle_compact(unsigned short *expbuf, int ibpp,static void iclose(IMAGERGB *image) {TINT32 tablesize;+ if (!image) return;+iflush(image);img_optseek(image, 0);- /* CONTROLLARE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/+ /* CHECK!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/if (image->flags & _IOWRT) {if (image->dorev) cvtimage(image);if (do_rgb_write_header(image, image->file) != IMAGERGB_HEADER_SIZE) {fprintf(stderr, "iflush: error on write of image header\n");- return;+ // Don't return early - continue cleanup}if (image->dorev) cvtimage(image);@@ -743,32 +722,31 @@ static void iclose(IMAGERGB *image) {if (RGB_img_write(image, (char *)(image->rowstart), tablesize) !=tablesize) {fprintf(stderr, "iflush: error on write of rowstart\n");- return;}if (image->dorev) cvtTINT32s((TUINT32 *)image->rowsize, tablesize);if (RGB_img_write(image, (char *)(image->rowsize), tablesize) !=tablesize) {fprintf(stderr, "iflush: error on write of rowsize\n");- return;}}}++ // Cleanup in reverse order of allocationif (image->base) {free(image->base);- image->base = 0;+ image->base = nullptr;}if (image->tmpbuf) {free(image->tmpbuf);- image->tmpbuf = 0;+ image->tmpbuf = nullptr;}if (ISRLE(image->type)) {free(image->rowstart);- image->rowstart = 0;+ image->rowstart = nullptr;free(image->rowsize);- image->rowsize = 0;+ image->rowsize = nullptr;}free(image);- return;}/*-------------------------------------------------------------------------*/@@ -780,15 +758,15 @@ static int new_putrow(IMAGERGB *image, void *buffer, UINT y, UINT z) {if (!(image->flags & (_IORW | _IOWRT))) return -1;if (image->dim < 3) z = 0;-if (image->dim < 2) y = 0;image->min = 0;bpp = BPP(image->type);dorev = image->dorev && bpp == 2;+ // Comment out all max/min calculations to speed upif (bpp == 1)- image->max = 255; /*commento tutti i calcoli su max e min per velocizzare */+ image->max = 255;elseimage->max = 65535;@@ -817,8 +795,9 @@ static int new_putrow(IMAGERGB *image, void *buffer, UINT y, UINT z) {if (dorev) cvtshorts(image->tmpbuf, cnt);return image->xsize;}- } else+ } else {fprintf(stderr, "putrow: weird image type\n");+ }return -1;}@@ -828,7 +807,7 @@ static int new_putrow(IMAGERGB *image, void *buffer, UINT y, UINT z) {static int iflush(IMAGERGB *image) {unsigned short *base;- if ((image->flags & _IOWRT) && (base = image->base) != NULL &&+ if ((image->flags & _IOWRT) && (base = image->base) != nullptr &&(image->ptr - base) > 0) {if (new_putrow(image, base, image->y, image->z) != image->xsize) {image->flags |= _IOERR;@@ -845,13 +824,13 @@ class SgiReader final : public Tiio::Reader {int m_currentY;public:- SgiReader() : m_header(0), m_currentY(0) {}+ SgiReader() : m_header(nullptr), m_currentY(0) {}- ~SgiReader();+ ~SgiReader() override;void open(FILE *file) override;- TPropertyGroup *getProperties() const override { return 0; }+ TPropertyGroup *getProperties() const override { return nullptr; }void readLine(char *buffer, int x0, int x1, int shrink) override;void readLine(short *buffer, int x0, int x1, int shrink) override;@@ -865,18 +844,17 @@ void SgiReader::open(FILE *file) {m_header = iopen(fileno(file), OpenRead, 0, 0, 0, 0, 0, 0);if (!m_header) {- string str("Can't open file");- throw(str);+ throw std::runtime_error("Can't open file");}- m_info.m_lx = m_header->xsize;- m_info.m_ly = m_header->ysize;- m_info.m_bitsPerSample = BPP(m_header->type) * 8;- m_info.m_samplePerPixel = m_header->zsize;- Tiio::SgiWriterProperties *prop = new Tiio::SgiWriterProperties();- m_info.m_properties = prop;+ m_info.m_lx = m_header->xsize;+ m_info.m_ly = m_header->ysize;+ m_info.m_bitsPerSample = BPP(m_header->type) * 8;+ m_info.m_samplePerPixel = m_header->zsize;+ auto *prop = new Tiio::SgiWriterProperties();+ m_info.m_properties = prop;prop->m_endianness.setValue(m_header->dorev == 1 ? L"Big Endian"- : L"Little Endian");+ : L"Little Endian");prop->m_compressed.setValue(ISRLE(m_header->type) ? true : false);wstring pixelSize;int ps = m_info.m_bitsPerSample * m_info.m_samplePerPixel;@@ -897,53 +875,46 @@ void SgiReader::open(FILE *file) {SgiReader::~SgiReader() {if (!m_header) return;- if (m_header->base) free(m_header->base);- if (m_header->tmpbuf) free(m_header->tmpbuf);- if ((ISRLE(m_header->type))) {- free(m_header->rowstart);- free(m_header->rowsize);- }- free(m_header);- m_header = 0;+ // Use iclose for proper cleanup+ iclose(m_header);+ m_header = nullptr;}//-------------------------------------------------------------------void SgiReader::readLine(short *buffer, int x0, int x1, int shrink) {- // assert(shrink == 1);- // assert(x0 == 0);- // assert(x1 == m_info.m_lx-1);-+ assert(shrink == 1);+ assert(x0 == 0);+ assert(x1 == m_info.m_lx - 1);assert(BPP(m_header->type) == 2);- { // 64 -> 32- TPixel64 *pix = (TPixel64 *)buffer;- std::vector<USHORT> rbuf(m_info.m_lx), gbuf(m_info.m_lx), bbuf(m_info.m_lx),- mbuf(m_info.m_lx);- if (m_header->zsize == 4) {- new_getrow(m_header, &rbuf[0], m_currentY, 0);- new_getrow(m_header, &gbuf[0], m_currentY, 1);- new_getrow(m_header, &bbuf[0], m_currentY, 2);- new_getrow(m_header, &mbuf[0], m_currentY, 3);- for (int i = 0; i < (x1 - x0 + 1); ++i) {- pix->r = rbuf[i];- pix->g = gbuf[i];- pix->b = bbuf[i];- pix->m = mbuf[i];- ++pix;- }- } else {- new_getrow(m_header, &rbuf[0], m_currentY, 0);- new_getrow(m_header, &gbuf[0], m_currentY, 1);- new_getrow(m_header, &bbuf[0], m_currentY, 2);- for (int i = 0; i < (x1 - x0 + 1); ++i) {- pix->r = rbuf[i];- pix->g = gbuf[i];- pix->b = bbuf[i];- pix->m = 0xffff;- ++pix;- }+ // 64 -> 32+ TPixel64 *pix = (TPixel64 *)buffer;+ std::vector<USHORT> rbuf(m_info.m_lx), gbuf(m_info.m_lx), bbuf(m_info.m_lx),+ mbuf(m_info.m_lx);+ if (m_header->zsize == 4) {+ new_getrow(m_header, &rbuf[0], m_currentY, 0);+ new_getrow(m_header, &gbuf[0], m_currentY, 1);+ new_getrow(m_header, &bbuf[0], m_currentY, 2);+ new_getrow(m_header, &mbuf[0], m_currentY, 3);+ for (int i = 0; i < (x1 - x0 + 1); ++i) {+ pix->r = rbuf[i];+ pix->g = gbuf[i];+ pix->b = bbuf[i];+ pix->m = mbuf[i];+ ++pix;+ }+ } else {+ new_getrow(m_header, &rbuf[0], m_currentY, 0);+ new_getrow(m_header, &gbuf[0], m_currentY, 1);+ new_getrow(m_header, &bbuf[0], m_currentY, 2);+ for (int i = 0; i < (x1 - x0 + 1); ++i) {+ pix->r = rbuf[i];+ pix->g = gbuf[i];+ pix->b = bbuf[i];+ pix->m = 0xffff;+ ++pix;}}m_currentY++;@@ -952,17 +923,12 @@ void SgiReader::readLine(short *buffer, int x0, int x1, int shrink) {//-------------------------------------------------------------------void SgiReader::readLine(char *buffer, int x0, int x1, int shrink) {- // assert(shrink == 1);- // assert(x0 == 0);- // assert(x1 == m_info.m_lx-1);-- // Non ancora implementata la lettura parziale+ // Partial read not yet implementedx0 = 0;x1 = m_info.m_lx - 1;shrink = 1;- if (BPP(m_header->type) == 1) // 32 -> 32- {+ if (BPP(m_header->type) == 1) { // 32 -> 32TPixel32 *pix = (TPixel32 *)buffer;std::vector<UCHAR> rbuf(m_info.m_lx), gbuf(m_info.m_lx), bbuf(m_info.m_lx),mbuf(m_info.m_lx);@@ -980,7 +946,7 @@ void SgiReader::readLine(char *buffer, int x0, int x1, int shrink) {}} else {new_getrow(m_header, &rbuf[0], m_currentY, 0);- if (m_header->zsize == 1)+ if (m_header->zsize == 1) {for (int i = 0; i < (x1 - x0 + 1); ++i) {pix->r = rbuf[i];pix->g = rbuf[i];@@ -988,7 +954,7 @@ void SgiReader::readLine(char *buffer, int x0, int x1, int shrink) {pix->m = 0xff;++pix;}- else {+ } else {new_getrow(m_header, &gbuf[0], m_currentY, 1);new_getrow(m_header, &bbuf[0], m_currentY, 2);for (int i = 0; i < (x1 - x0 + 1); ++i) {@@ -1039,24 +1005,21 @@ int SgiReader::skipLines(int lineCount) {return lineCount;}-//---------------------------------------------------------------------/*- WRITER-*/+/*-----------------------------------------------------------------------------+ * WRITER+ *----------------------------------------------------------------------------*/class SgiWriter final : public Tiio::Writer {int m_currentY;IMAGERGB *m_header;-protected:- TImageInfo m_info;-public:- SgiWriter() : m_currentY(0), m_header(0){};- ~SgiWriter() {- if (m_header) iclose(m_header);- delete m_properties;+ SgiWriter() : m_currentY(0), m_header(nullptr) {}+ ~SgiWriter() override {+ if (m_header) {+ iclose(m_header);+ m_header = nullptr;+ }}void open(FILE *file, const TImageInfo &info) override;@@ -1068,21 +1031,20 @@ public:void flush() override {}- // RowOrder getRowOrder() const { return BOTTOM2TOP; }bool write64bitSupported() const override { return true; }- void setProperties(TPropertyGroup *properties);+ void setProperties(TPropertyGroup *properties) {+ m_properties = dynamic_cast<Tiio::SgiWriterProperties *>(properties);+ }- // m_header->zsize is updated with "Bits Per Pixel" property value in the- // function open()bool writeAlphaSupported() const override {return m_header && (m_header->zsize == 4);}private:- // not implemented- SgiWriter(const SgiWriter &);- SgiWriter &operator=(const SgiWriter &);+ // Delete copy constructor and assignment operator+ SgiWriter(const SgiWriter &) = delete;+ SgiWriter &operator=(const SgiWriter &) = delete;};Tiio::Reader *Tiio::makeSgiReader() { return new SgiReader(); }@@ -1094,11 +1056,15 @@ Tiio::Writer *Tiio::makeSgiWriter() { return new SgiWriter(); }//---------------------------------------------------------void SgiWriter::open(FILE *file, const TImageInfo &info) {- if (!m_properties) m_properties = new Tiio::SgiWriterProperties();+ if (!m_properties) {+ m_properties = new Tiio::SgiWriterProperties();+ }- TEnumProperty *p =- (TEnumProperty *)(m_properties->getProperty("Bits Per Pixel"));- assert(p);+ auto *p = dynamic_cast<TEnumProperty *>(+ m_properties->getProperty("Bits Per Pixel"));+ if (!p) {+ throw std::runtime_error("Bits Per Pixel property not found");+ }string str = ::to_string(p->getValue());int bitPerPixel = atoi(str.c_str());int channelBytesNum = 1;@@ -1132,26 +1098,29 @@ void SgiWriter::open(FILE *file, const TImageInfo &info) {break;}- TBoolProperty *bp =- (TBoolProperty *)(m_properties->getProperty("RLE-Compressed"));+ auto *bp = dynamic_cast<TBoolProperty *>(+ m_properties->getProperty("RLE-Compressed"));assert(bp);bool compressed = bp->getValue();- p = (TEnumProperty *)(m_properties->getProperty("Endianness"));+ p = dynamic_cast<TEnumProperty *>(m_properties->getProperty("Endianness"));assert(p);str = ::to_string(p->getValue());bool bigEndian = (str == "Big Endian");- m_header = iopen(- fileno(file), OpenWrite,- compressed ? RLE(BPP(channelBytesNum)) : VERBATIM(BPP(channelBytesNum)),- dim, m_info.m_lx, m_info.m_ly, zsize, bigEndian ? 1 : 0);+ m_header =+ iopen(fileno(file), OpenWrite,+ compressed ? RLE(channelBytesNum) : VERBATIM(channelBytesNum), dim,+ m_info.m_lx, m_info.m_ly, zsize, bigEndian ? 1 : 0);++ if (!m_header) {+ throw std::runtime_error("Failed to open SGI file for writing");+ }}//---------------------------------------------------------void SgiWriter::writeLine(char *buffer) {if (BPP(m_header->type) == 1) {- if (m_header->dim < 3) // 32->8- {+ if (m_header->dim < 3) { // 32->8new_putrow(m_header, buffer, m_currentY, 0);} else {std::vector<UCHAR> rbuf(m_info.m_lx), gbuf(m_info.m_lx),@@ -1178,34 +1147,33 @@ void SgiWriter::writeLine(char *buffer) {void SgiWriter::writeLine(short *buffer) {assert(BPP(m_header->type) == 2);- {- if (m_header->dim < 3) {- std::vector<USHORT> tmp(m_info.m_lx);- TPixelRGBM64 *pix = (TPixelRGBM64 *)buffer;- for (int i = 0; i < m_info.m_lx; ++i) {- tmp[i] = TPixelGR16::from(*pix).value;- ++pix;- }- new_putrow(m_header, &tmp[0], m_currentY, 0);- } else {- std::vector<USHORT> rbuf(m_info.m_lx), gbuf(m_info.m_lx),- bbuf(m_info.m_lx), mbuf(m_info.m_lx);- TPixelRGBM64 *pix = (TPixelRGBM64 *)buffer;- for (int i = 0; i < m_info.m_lx; ++i) {- rbuf[i] = pix->r;- gbuf[i] = pix->g;- bbuf[i] = pix->b;- mbuf[i] = pix->m;- ++pix;- }- new_putrow(m_header, &rbuf[0], m_currentY, 0);- new_putrow(m_header, &gbuf[0], m_currentY, 1);- new_putrow(m_header, &bbuf[0], m_currentY, 2);- if (m_header->zsize == 4) new_putrow(m_header, &mbuf[0], m_currentY, 3);+ if (m_header->dim < 3) {+ std::vector<USHORT> tmp(m_info.m_lx);+ TPixelRGBM64 *pix = (TPixelRGBM64 *)buffer;+ for (int i = 0; i < m_info.m_lx; ++i) {+ tmp[i] = TPixelGR16::from(*pix).value;+ ++pix;+ }+ new_putrow(m_header, &tmp[0], m_currentY, 0);+ } else {+ std::vector<USHORT> rbuf(m_info.m_lx), gbuf(m_info.m_lx), bbuf(m_info.m_lx),+ mbuf(m_info.m_lx);+ TPixelRGBM64 *pix = (TPixelRGBM64 *)buffer;+ for (int i = 0; i < m_info.m_lx; ++i) {+ rbuf[i] = pix->r;+ gbuf[i] = pix->g;+ bbuf[i] = pix->b;+ mbuf[i] = pix->m;+ ++pix;}+ new_putrow(m_header, &rbuf[0], m_currentY, 0);+ new_putrow(m_header, &gbuf[0], m_currentY, 1);+ new_putrow(m_header, &bbuf[0], m_currentY, 2);+ if (m_header->zsize == 4) new_putrow(m_header, &mbuf[0], m_currentY, 3);}++m_currentY;}+//=========================================================Tiio::SgiWriterProperties::SgiWriterProperties()