[gtk/gamma-shenanigans] Support loading and saving float textures




commit a3eef31a917a6d23c1af16d96445673cf7fba639
Author: Matthias Clasen <mclasen redhat com>
Date:   Tue Sep 7 14:25:52 2021 -0400

    Support loading and saving float textures
    
    Add support for the tiff file format, which allows
    us to save all our memory formats without loss.

 gdk/gdktexture.c |  91 +++++++++-
 gdk/gdktiff.c    | 494 +++++++++++++++++++++++++++++++++++++++++++++++++++++++
 gdk/gdktiff.h    |  37 +++++
 gdk/meson.build  |   3 +-
 meson.build      |   1 +
 5 files changed, 623 insertions(+), 3 deletions(-)
---
diff --git a/gdk/gdktexture.c b/gdk/gdktexture.c
index 391ba9a307..6c9e27b3fb 100644
--- a/gdk/gdktexture.c
+++ b/gdk/gdktexture.c
@@ -47,6 +47,7 @@
 
 #include <graphene.h>
 #include <png.h>
+#include "gdktiff.h"
 
 /* HACK: So we don't need to include any (not-yet-created) GSK or GTK headers */
 void
@@ -402,6 +403,33 @@ gdk_texture_new_from_png (GFile   *file,
   return texture;
 }
 
+static GdkTexture *
+gdk_texture_new_from_tiff (GFile   *file,
+                           GError **error)
+{
+  GBytes *bytes;
+  GdkTexture *texture;
+  guchar *data;
+  int width, height;
+  GdkMemoryFormat format;
+  gsize bpp;
+
+  data = gdk_load_tiff (file, &width, &height, &format, error);
+  if (!data)
+    return NULL;
+
+  bpp = gdk_memory_format_bytes_per_pixel (format);
+  bytes = g_bytes_new_take (data, width * height * bpp);
+
+  texture = gdk_memory_texture_new (width, height,
+                                    format,
+                                    bytes, width * bpp);
+
+  g_bytes_unref (bytes);
+
+  return texture;
+}
+
 /**
  * gdk_texture_new_from_file:
  * @file: `GFile` to load
@@ -451,6 +479,13 @@ gdk_texture_new_from_file (GFile   *file,
       return gdk_texture_new_from_png (file, error);
     }
 
+  if (memcmp (data, "MM\x00\x2a", 4) == 0 ||
+      memcmp (data, "II\x2a\x00", 4) == 0)
+    {
+      g_object_unref (stream);
+      return gdk_texture_new_from_tiff (file, error);
+    }
+
   pixbuf = gdk_pixbuf_new_from_stream (stream, NULL, error);
   g_object_unref (stream);
   if (pixbuf == NULL)
@@ -678,6 +713,57 @@ gdk_texture_save_to_png (GdkTexture *texture,
   return result;
 }
 
+static gboolean
+gdk_texture_save_to_tiff (GdkTexture *texture,
+                          const char *filename)
+{
+  GBytes *bytes = NULL;
+  gboolean result;
+  GdkMemoryFormat formats[] = {
+    GDK_MEMORY_R32G32B32_FLOAT,
+    GDK_MEMORY_R16G16B16_FLOAT,
+    GDK_MEMORY_R16G16B16A16_PREMULTIPLIED,
+    GDK_MEMORY_B8G8R8A8_PREMULTIPLIED,
+    GDK_MEMORY_A8R8G8B8_PREMULTIPLIED,
+    GDK_MEMORY_R8G8B8A8_PREMULTIPLIED,
+    GDK_MEMORY_B8G8R8A8,
+    GDK_MEMORY_A8R8G8B8,
+    GDK_MEMORY_R8G8B8A8,
+    GDK_MEMORY_A8B8G8R8,
+    GDK_MEMORY_R8G8B8,
+    GDK_MEMORY_B8G8R8,
+  };
+  GdkMemoryFormat format;
+  GFile *file;
+
+  for (int i = 0; i < G_N_ELEMENTS (formats); i++)
+    {
+      bytes = gdk_texture_download_format (texture, formats[i]);
+      if (bytes)
+        {
+          format = formats[i];
+          break;
+        }
+    }
+
+  if (!bytes)
+    return FALSE;
+
+  file = g_file_new_for_path (filename);
+
+  result = gdk_save_tiff (file,
+                          g_bytes_get_data (bytes, NULL),
+                          gdk_texture_get_width (texture),
+                          gdk_texture_get_height (texture),
+                          format,
+                          NULL);
+
+  g_bytes_unref (bytes);
+  g_object_unref (file);
+
+  return result;
+}
+
 /**
  * gdk_texture_save_to_file:
  * @texture: a `GdkTexture`
@@ -686,7 +772,8 @@ gdk_texture_save_to_png (GdkTexture *texture,
  * Store the given @texture to the @filename.
  *
  * GTK will choose a suitable file format to save the data in
- * depending on the format of the texture.
+ * depending on the format of the texture. Currently, that is
+ * tiff, for all kinds of textures.
  *
  * This is a utility function intended for debugging and testing.
  * If you want more control over formats, proper error handling or
@@ -704,5 +791,5 @@ gdk_texture_save_to_file (GdkTexture  *texture,
   g_return_val_if_fail (GDK_IS_TEXTURE (texture), FALSE);
   g_return_val_if_fail (filename != NULL, FALSE);
 
-  return gdk_texture_save_to_png (texture, filename);
+  return gdk_texture_save_to_tiff (texture, filename);
 }
diff --git a/gdk/gdktiff.c b/gdk/gdktiff.c
new file mode 100644
index 0000000000..301ecdce41
--- /dev/null
+++ b/gdk/gdktiff.c
@@ -0,0 +1,494 @@
+/* GDK - The GIMP Drawing Kit
+ * Copyright (C) 2021 Red Hat, Inc.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include "config.h"
+
+#include "gdktiff.h"
+
+#include "gdktexture.h"
+#include "gdkmemorytextureprivate.h"
+#include <tiffio.h>
+
+/* {{{ IO handling */
+
+typedef struct
+{
+  GFile *file;
+  GObject *stream;
+  GInputStream *input;
+  GOutputStream *output;
+
+  gchar *buffer;
+  gsize allocated;
+  gsize used;
+  gsize position;
+  char *error;
+} TiffIO;
+
+static TiffIO tiff_io = { 0, };
+
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wsuggest-attribute=format"
+
+static void
+tiff_io_warning (const char *module,
+                 const char *fmt,
+                 va_list     ap) 
+{
+  g_logv (G_LOG_DOMAIN, G_LOG_LEVEL_MESSAGE, fmt, ap);
+}
+
+static void
+tiff_io_error (const char *module,
+               const char *fmt,
+               va_list     ap)
+{
+  char *msg = g_strdup_vprintf (fmt, ap);
+  g_log (G_LOG_DOMAIN, G_LOG_LEVEL_MESSAGE, "%s", msg);
+  if (!tiff_io.error)
+    tiff_io.error = msg;
+  else
+    g_free (msg);
+}
+
+#pragma GCC diagnostic pop
+
+static tsize_t
+tiff_io_read (thandle_t handle,
+              tdata_t   buffer,
+              tsize_t   size)
+{
+  TiffIO *io = (TiffIO *) handle;
+  GError *error = NULL;
+  gssize read  = -1;
+  gsize bytes_read = 0;
+
+  if (! g_input_stream_read_all (io->input,
+                                 (void *) buffer, (gsize) size,
+                                 &bytes_read,
+                                 NULL, &error))
+    {
+      g_printerr ("%s", error->message);
+      g_clear_error (&error);
+    }
+
+  read = bytes_read;
+
+  return (tsize_t) read;
+}
+
+static tsize_t
+tiff_io_write (thandle_t handle,
+               tdata_t   buffer,
+               tsize_t   size)
+{
+  TiffIO *io = (TiffIO *) handle;
+  GError *error = NULL;
+  gssize written = -1;
+  gsize bytes_written = 0;
+
+  if (! g_output_stream_write_all (io->output,
+                                   (void *) buffer, (gsize) size,
+                                   &bytes_written,
+                                   NULL, &error))
+    {
+      g_printerr ("%s", error->message);
+      g_clear_error (&error);
+    }
+
+  written = bytes_written;
+
+  return (tsize_t) written;
+}
+
+static GSeekType
+lseek_to_seek_type (int whence)
+{
+  switch (whence)
+    {
+    default:
+    case SEEK_SET:
+      return G_SEEK_SET;
+    case SEEK_CUR:
+      return G_SEEK_CUR;
+    case SEEK_END:
+      return G_SEEK_END;
+    }
+}
+
+static toff_t
+tiff_io_seek (thandle_t handle,
+              toff_t    offset,
+              int       whence)
+{
+  TiffIO *io = (TiffIO *) handle;
+  GError *error = NULL;
+  gboolean sought = FALSE;
+  goffset position = -1;
+
+  sought = g_seekable_seek (G_SEEKABLE (io->stream),
+                            (goffset) offset, lseek_to_seek_type (whence),
+                            NULL, &error);
+  if (sought)
+    {
+      position = g_seekable_tell (G_SEEKABLE (io->stream));
+    }
+  else
+    {
+      g_printerr ("%s", error->message);
+      g_clear_error (&error);
+    }
+
+  return (toff_t) position;
+}
+
+static int
+tiff_io_close (thandle_t handle)
+{
+  TiffIO *io = (TiffIO *) handle;
+  GError *error = NULL;
+  gboolean closed = FALSE;
+
+  if (io->input)
+    closed = g_input_stream_close (io->input, NULL, &error);
+  else if (io->output)
+    closed = g_output_stream_close (io->output, NULL, &error);
+
+  if (!closed)
+    {
+      g_printerr ("%s", error->message);
+      g_clear_error (&error);
+    }
+
+  g_object_unref (io->stream);
+  io->stream = NULL;
+  io->input = NULL;
+  io->output = NULL;
+
+  g_free (io->buffer);
+  io->buffer = NULL;
+
+  io->allocated = 0;
+  io->used = 0;
+  io->position  = 0;
+
+  g_free (io->error);
+  io->error = NULL;
+
+  return closed ? 0 : -1;
+}
+
+static toff_t
+tiff_io_get_file_size (thandle_t handle)
+{
+  TiffIO *io = (TiffIO *) handle;
+  GError *error = NULL;
+  GFileInfo *info;
+  goffset size = 0;
+
+  info = g_file_query_info (io->file,
+                            G_FILE_ATTRIBUTE_STANDARD_SIZE,
+                            G_FILE_QUERY_INFO_NONE,
+                            NULL, &error);
+  if (!info)
+    {
+      g_printerr ("%s", error->message);
+      g_clear_error (&error);
+    }
+  else
+    {
+      size = g_file_info_get_size (info);
+      g_object_unref (info);
+    }
+
+  return (toff_t) size;
+}
+
+static TIFF *
+tiff_open (GFile        *file,
+           const gchar  *mode,
+           GError      **error)
+{
+  TIFFSetWarningHandler ((TIFFErrorHandler) tiff_io_warning);
+  TIFFSetErrorHandler ((TIFFErrorHandler) tiff_io_error);
+
+  tiff_io.file = file;
+
+  if (strcmp (mode, "r") == 0)
+    {
+      tiff_io.input = G_INPUT_STREAM (g_file_read (file, NULL, error));
+      if (!tiff_io.input)
+        return NULL;
+
+      tiff_io.stream = G_OBJECT (tiff_io.input);
+    }
+  else if (strcmp (mode, "w") == 0)
+    {
+      tiff_io.output = G_OUTPUT_STREAM (g_file_replace (file,
+                                                        NULL, FALSE,
+                                                        G_FILE_CREATE_NONE,
+                                                        NULL, error));
+      if (!tiff_io.output)
+        return NULL;
+
+      tiff_io.stream = G_OBJECT (tiff_io.output);
+    }
+  else
+    {
+      g_assert_not_reached ();
+    }
+
+  return TIFFClientOpen ("GTK", mode,
+                         (thandle_t) &tiff_io,
+                         tiff_io_read,
+                         tiff_io_write,
+                         tiff_io_seek,
+                         tiff_io_close,
+                         tiff_io_get_file_size,
+                         NULL, NULL);
+}
+
+/* }}} */
+
+static struct {
+  GdkMemoryFormat format;
+  guint16 bits_per_sample;
+  guint16 samples_per_pixel;
+  guint16 sample_format;
+} format_data[] = {
+  { GDK_MEMORY_DEFAULT,                     8, 4, SAMPLEFORMAT_UINT   },
+  { GDK_MEMORY_R8G8B8,                      8, 3, SAMPLEFORMAT_UINT   },
+  { GDK_MEMORY_R16G16B16A16_PREMULTIPLIED, 16, 4, SAMPLEFORMAT_UINT   },
+  { GDK_MEMORY_R16G16B16_FLOAT,            16, 3, SAMPLEFORMAT_IEEEFP },
+  { GDK_MEMORY_R32G32B32_FLOAT,            32, 3, SAMPLEFORMAT_IEEEFP },
+};
+
+gboolean
+gdk_save_tiff (GFile            *file,
+               const guchar     *data,
+               int               width,
+               int               height,
+               GdkMemoryFormat   format,
+               GError          **error)
+{
+  TIFF *tif;
+  guint16 bits_per_sample = 0;
+  guint16 samples_per_pixel = 0;
+  guint16 sample_format = 0;
+  int bytes_per_pixel;
+  int bytes_per_row;
+
+  tif = tiff_open (file, "w", error);
+  if (!tif)
+    return FALSE;
+
+  for (int i = 0; i < G_N_ELEMENTS (format_data); i++)
+    {
+      if (format == format_data[i].format)
+        {
+          bits_per_sample = format_data[i].bits_per_sample;
+          samples_per_pixel = format_data[i].samples_per_pixel;
+          sample_format = format_data[i].sample_format;
+          break;
+        }
+    }
+
+  g_assert (bits_per_sample != 0);
+
+  bytes_per_pixel = bits_per_sample / 8 * samples_per_pixel;
+  bytes_per_row = width * bytes_per_pixel;
+
+  TIFFSetField (tif, TIFFTAG_SOFTWARE, "GTK");
+  TIFFSetField (tif, TIFFTAG_IMAGEWIDTH, width);
+  TIFFSetField (tif, TIFFTAG_IMAGELENGTH, height);
+  TIFFSetField (tif, TIFFTAG_BITSPERSAMPLE, bits_per_sample);
+  TIFFSetField (tif, TIFFTAG_SAMPLESPERPIXEL, samples_per_pixel);
+  TIFFSetField (tif, TIFFTAG_SAMPLEFORMAT, sample_format);
+  TIFFSetField (tif, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
+  TIFFSetField (tif, TIFFTAG_COMPRESSION, COMPRESSION_NONE);
+  // TODO: save gamma / colorspace
+
+  if (samples_per_pixel > 3)
+    {
+      guint16 extra_samples[] = { EXTRASAMPLE_ASSOCALPHA };
+      TIFFSetField (tif, TIFFTAG_EXTRASAMPLES, 1, extra_samples);
+    }
+
+  TIFFSetField (tif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB);
+  TIFFSetField (tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
+
+  for (int y = 0; y < height; y++)
+    {
+      guchar *t = (guchar *)data + bytes_per_row * y;
+
+      TIFFWriteScanline (tif, t, y, 0);
+    }
+
+  if (tiff_io.error)
+    {
+      TIFFClose (tif);
+      g_set_error_literal (error,
+                           G_IO_ERROR, G_IO_ERROR_FAILED,
+                           tiff_io.error);
+      return FALSE;
+    }
+
+  TIFFFlushData (tif);
+  TIFFClose (tif);
+
+  return TRUE;
+}
+
+/* This isn't meant to be a very versatile tiff loader.
+ * It just aims to load the subset that we're saving
+ * ourselves, above.
+ */
+guchar *
+gdk_load_tiff (GFile            *file,
+               int              *out_width,
+               int              *out_height,
+               GdkMemoryFormat  *out_format,
+               GError          **error)
+{
+  TIFF *tif;
+  guint16 samples_per_pixel;
+  guint16 bits_per_sample;
+  guint16 photometric;
+  guint16 planarconfig;
+  guint16 sample_format;
+  guint16 orientation;
+  guint32 width, height;
+  GdkMemoryFormat format;
+  guchar *data, *line;
+  gsize stride;
+
+  tif = tiff_open (file, "r", error);
+  if (!tif)
+    return NULL;
+
+  TIFFSetDirectory (tif, 0);
+
+  TIFFGetFieldDefaulted (tif, TIFFTAG_SAMPLESPERPIXEL, &samples_per_pixel);
+  TIFFGetFieldDefaulted (tif, TIFFTAG_BITSPERSAMPLE, &bits_per_sample);
+  TIFFGetFieldDefaulted (tif, TIFFTAG_SAMPLEFORMAT, &sample_format);
+  TIFFGetFieldDefaulted (tif, TIFFTAG_PHOTOMETRIC, &photometric);
+  TIFFGetFieldDefaulted (tif, TIFFTAG_PLANARCONFIG, &planarconfig);
+  TIFFGetFieldDefaulted (tif, TIFFTAG_ORIENTATION, &orientation);
+  TIFFGetFieldDefaulted (tif, TIFFTAG_IMAGEWIDTH, &width);
+  TIFFGetFieldDefaulted (tif, TIFFTAG_IMAGELENGTH, &height);
+
+  if (samples_per_pixel == 4)
+    {
+      guint16 extra;
+      guint16 *extra_types;
+
+      if (!TIFFGetField (tif, TIFFTAG_EXTRASAMPLES, &extra, &extra_types))
+        extra = 0;
+
+      if (extra == 0 || extra_types[0] != EXTRASAMPLE_ASSOCALPHA)
+        {
+          g_set_error_literal (error,
+                               G_IO_ERROR, G_IO_ERROR_FAILED,
+                               "Did not find the alpha channel");
+          TIFFClose (tif);
+          return NULL;
+        }
+    }
+
+  format = 0;
+
+  for (int i = 0; i < G_N_ELEMENTS (format_data); i++)
+    {
+      if (format_data[i].sample_format == sample_format &&
+          format_data[i].bits_per_sample == bits_per_sample &&
+          format_data[i].samples_per_pixel == samples_per_pixel)
+        {
+          format = format_data[i].format;
+          break;
+        }
+    }
+
+  if (format == 0)
+    {
+      g_set_error (error,
+                   G_IO_ERROR, G_IO_ERROR_FAILED,
+                   "Format %s/%d-bit/%s not handled",
+                   samples_per_pixel == 3 ? "RGB" : "RGBA",
+                   bits_per_sample,
+                   sample_format == SAMPLEFORMAT_UINT ? "int" : "float");
+      TIFFClose (tif);
+      return NULL;
+    }
+
+  if (photometric != PHOTOMETRIC_RGB)
+    {
+      g_set_error (error,
+                   G_IO_ERROR, G_IO_ERROR_FAILED,
+                   "Photometric %d not handled", photometric);
+      TIFFClose (tif);
+      return NULL;
+    }
+
+  if (planarconfig != PLANARCONFIG_CONTIG ||
+      TIFFIsTiled (tif))
+    {
+      g_set_error_literal (error,
+                           G_IO_ERROR, G_IO_ERROR_FAILED,
+                           "Non-contiguous or tiled tiff not handled");
+      TIFFClose (tif);
+      return NULL;
+    }
+
+  if (orientation != ORIENTATION_TOPLEFT)
+    {
+      g_set_error (error,
+                   G_IO_ERROR, G_IO_ERROR_FAILED,
+                   "Orientation %d not handled", orientation);
+      TIFFClose (tif);
+      return NULL;
+    }
+
+  stride = width * gdk_memory_format_bytes_per_pixel (format);
+
+  g_assert (TIFFScanlineSize (tif) == stride);
+
+  data = g_new (guchar, height * stride);
+
+  line = data;
+  for (int y = 0; y < height; y++)
+    {
+      if (TIFFReadScanline (tif, line, y, 0) == -1)
+        {
+          g_set_error (error,
+                       G_IO_ERROR, G_IO_ERROR_FAILED,
+                       "Reading data failed at row %d", y);
+          TIFFClose (tif);
+          g_free (data);
+          return NULL;
+        }
+
+      line += stride;
+    }
+
+  *out_width = width;
+  *out_height = height;
+  *out_format = format;
+
+  return data;
+}
+
+/* vim:set foldmethod=marker expandtab: */
diff --git a/gdk/gdktiff.h b/gdk/gdktiff.h
new file mode 100644
index 0000000000..9736efcd13
--- /dev/null
+++ b/gdk/gdktiff.h
@@ -0,0 +1,37 @@
+/* GDK - The GIMP Drawing Kit
+ * Copyright (C) 2021 Red Hat, Inc.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#ifndef __GDK_TIFF_H__
+#define __GDK_TIFF_H__
+
+#include "gdkmemorytexture.h"
+#include <gio/gio.h>
+
+guchar *gdk_load_tiff   (GFile            *file,
+                         int              *out_width,
+                         int              *out_height,
+                         GdkMemoryFormat  *out_format,
+                         GError          **error);
+
+gboolean gdk_save_tiff   (GFile            *file,
+                          const guchar     *data,
+                          int               width,
+                          int               height,
+                          GdkMemoryFormat   format,
+                          GError          **error);
+
+#endif
diff --git a/gdk/meson.build b/gdk/meson.build
index 6539c225f4..babc226265 100644
--- a/gdk/meson.build
+++ b/gdk/meson.build
@@ -50,6 +50,7 @@ gdk_public_sources = files([
   'gdktoplevelsize.c',
   'gdktoplevel.c',
   'gdkdragsurface.c',
+  'gdktiff.c',
 ])
 
 gdk_public_headers = files([
@@ -254,7 +255,7 @@ endif
 
 libgdk = static_library('gdk',
   sources: [gdk_sources, gdk_backends_gen_headers, gdkconfig],
-  dependencies: gdk_deps + [libgtk_css_dep, png_dep],
+  dependencies: gdk_deps + [libgtk_css_dep, png_dep, tiff_dep],
   link_with: [libgtk_css],
   include_directories: [confinc, gdkx11_inc, wlinc],
   c_args: libgdk_c_args + common_cflags,
diff --git a/meson.build b/meson.build
index fc50b6e3eb..0a7132011c 100644
--- a/meson.build
+++ b/meson.build
@@ -395,6 +395,7 @@ pixbuf_dep     = dependency('gdk-pixbuf-2.0', version: gdk_pixbuf_req,
                             fallback : ['gdk-pixbuf', 'gdkpixbuf_dep'],
                             default_options: ['png=enabled', 'jpeg=enabled', 'builtin_loaders=png,jpeg', 
'man=false'])
 png_dep        = dependency('libpng16')
+tiff_dep        = dependency('libtiff-4')
 epoxy_dep      = dependency('epoxy', version: epoxy_req,
                             fallback: ['libepoxy', 'libepoxy_dep'])
 harfbuzz_dep   = dependency('harfbuzz', version: '>= 2.1.0', required: false,


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]