[gtk/gamma-shenanigans: 5/20] Support loading and saving 16bit pngs




commit 68f07b7b5ec33b623afede3474fae6fb55e628e2
Author: Matthias Clasen <mclasen redhat com>
Date:   Tue Sep 7 09:27:01 2021 -0400

    Support loading and saving 16bit pngs
    
    Using libpng instead of the lowest-common-denominator
    gdk-pixbuf loader allows us to load >8bit data, and
    apply gamma correction.
    
    For other file formats, we still fall back to using
    gdk-pixbuf.
    
    As a consequence, we are now linking against libpng.

 gdk/gdkpng.c     | 177 +++++++++++++++++++++++++++++++++++++++++++++++++++++++
 gdk/gdkpng.h     |  34 +++++++++++
 gdk/gdktexture.c |  78 +++++++++++++++++++-----
 gdk/meson.build  |   5 +-
 meson.build      |   1 +
 5 files changed, 277 insertions(+), 18 deletions(-)
---
diff --git a/gdk/gdkpng.c b/gdk/gdkpng.c
new file mode 100644
index 0000000000..ca091acfa8
--- /dev/null
+++ b/gdk/gdkpng.c
@@ -0,0 +1,177 @@
+/* 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 "gdkpng.h"
+
+#include "gdktexture.h"
+#include "gdkmemorytextureprivate.h"
+#include <png.h>
+#include <stdio.h>
+
+/* {{{ IO handling */
+
+static ssize_t
+read_stream (void   *cookie,
+             char   *buf,
+             size_t  size)
+{
+  GInputStream *stream = cookie;
+
+  return g_input_stream_read (stream, buf, size, NULL, NULL);
+}
+
+static ssize_t
+write_stream (void       *cookie,
+              const char *buf,
+              size_t      size)
+{
+  GOutputStream *stream = cookie;
+
+  return g_output_stream_write (stream, buf, size, NULL, NULL);
+}
+
+static int
+seek_stream (void    *cookie,
+             off64_t *offset,
+             int      whence)
+{
+  GSeekable *seekable = cookie;
+  GSeekType seek_type;
+
+  if (whence == SEEK_SET)
+    seek_type = G_SEEK_SET;
+  else if (whence == SEEK_CUR)
+    seek_type = G_SEEK_CUR;
+  else if (whence == SEEK_END)
+    seek_type = G_SEEK_END;
+  else
+    g_assert_not_reached ();
+
+  if (g_seekable_seek (seekable, *offset, seek_type, NULL, NULL))
+    {
+      *offset = g_seekable_tell (seekable);
+      return 0;
+    }
+
+  return -1;
+}
+
+static int
+close_stream (void *cookie)
+{
+  GInputStream *stream = cookie;
+
+  g_object_unref (stream);
+
+  return 0;
+}
+
+static cookie_io_functions_t cookie_funcs = {
+  read_stream,
+  write_stream,
+  seek_stream,
+  close_stream
+};
+
+/* }}} */
+
+GdkTexture *
+gdk_load_png (GInputStream  *stream,
+              GError       **error)
+{
+  png_image image = { NULL, PNG_IMAGE_VERSION, 0, };
+  gsize size;
+  gsize stride;
+  guint16 *buffer;
+  GBytes *bytes;
+  GdkTexture *texture;
+  FILE *file;
+
+  file = fopencookie (g_object_ref (stream), "r", cookie_funcs);
+
+  png_image_begin_read_from_stdio (&image, file);
+
+  image.format = PNG_FORMAT_LINEAR_RGB_ALPHA;
+
+  stride = PNG_IMAGE_ROW_STRIDE (image);
+  size = PNG_IMAGE_BUFFER_SIZE (image, stride);
+  buffer = g_malloc (size);
+
+  png_image_finish_read (&image, NULL, buffer, stride, NULL);
+
+  fclose (file);
+
+  bytes = g_bytes_new_take (buffer, size);
+
+  texture = gdk_memory_texture_new (image.width, image.height,
+                                    GDK_MEMORY_R16G16B16A16_PREMULTIPLIED,
+                                    bytes, 2 * stride);
+
+  g_bytes_unref (bytes);
+
+  png_image_free (&image);
+
+  return texture;
+}
+
+gboolean
+gdk_save_png (GOutputStream    *stream,
+              const guchar     *data,
+              int               width,
+              int               height,
+              GdkMemoryFormat   format,
+              GError          **error)
+{
+  png_image image = { NULL, PNG_IMAGE_VERSION, 0, };
+  FILE *file;
+  gboolean result;
+  int stride;
+
+  stride = width * gdk_memory_format_bytes_per_pixel (format);
+
+  if (format == GDK_MEMORY_R16G16B16A16_PREMULTIPLIED)
+    image.format = PNG_FORMAT_LINEAR_RGB_ALPHA;
+  else if (format == GDK_MEMORY_DEFAULT)
+    image.format = PNG_FORMAT_RGBA;
+  else
+    {
+      g_set_error (error,
+                   G_IO_ERROR, G_IO_ERROR_FAILED,
+                   "Saving memory format %d to png not implemented", format);
+      return FALSE;
+    }
+
+  file = fopencookie (g_object_ref (stream), "w", cookie_funcs);
+
+  result = png_image_write_to_stdio (&image, file, FALSE, data, stride, NULL);
+  if (!result)
+    {
+      g_set_error_literal (error,
+                           G_IO_ERROR, G_IO_ERROR_FAILED,
+                           "Saving png failed");
+    }
+
+  png_image_free (&image);
+
+  fclose (file);
+
+  return result;
+}
+
+/* vim:set foldmethod=marker expandtab: */
diff --git a/gdk/gdkpng.h b/gdk/gdkpng.h
new file mode 100644
index 0000000000..36413aec72
--- /dev/null
+++ b/gdk/gdkpng.h
@@ -0,0 +1,34 @@
+/* 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_PNG_H__
+#define __GDK_PNG_H__
+
+#include "gdkmemorytexture.h"
+#include <gio/gio.h>
+
+GdkTexture *gdk_load_png (GInputStream     *stream,
+                          GError          **error);
+
+gboolean    gdk_save_png (GOutputStream    *stream,
+                          const guchar     *data,
+                          int               width,
+                          int               height,
+                          GdkMemoryFormat   format,
+                          GError          **error);
+
+#endif
diff --git a/gdk/gdktexture.c b/gdk/gdktexture.c
index 4681eec531..7097279a8d 100644
--- a/gdk/gdktexture.c
+++ b/gdk/gdktexture.c
@@ -46,6 +46,7 @@
 #include "gdksnapshot.h"
 
 #include <graphene.h>
+#include "gdkpng.h"
 
 /* HACK: So we don't need to include any (not-yet-created) GSK or GTK headers */
 void
@@ -359,6 +360,10 @@ gdk_texture_new_from_resource (const char *resource_path)
  * The file format is detected automatically. The supported formats
  * are PNG and JPEG, though more formats might be available.
  *
+ * For PNG files, this function supports conversion from SRGB to
+ * linear data (including gamma correction) and can load 16bit
+ * data.
+ *
  * If %NULL is returned, then @error will be set.
  *
  * Return value: A newly-created `GdkTexture`
@@ -370,6 +375,9 @@ gdk_texture_new_from_file (GFile   *file,
   GdkTexture *texture;
   GdkPixbuf *pixbuf;
   GInputStream *stream;
+  GInputStream *buffered;
+  const void *data;
+  gsize size;
 
   g_return_val_if_fail (G_IS_FILE (file), NULL);
   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
@@ -378,6 +386,20 @@ gdk_texture_new_from_file (GFile   *file,
   if (stream == NULL)
     return NULL;
 
+  buffered = g_buffered_input_stream_new (stream);
+  g_object_unref (stream);
+  stream = buffered;
+
+  g_buffered_input_stream_fill (G_BUFFERED_INPUT_STREAM (stream), 8, NULL, NULL);
+  data = g_buffered_input_stream_peek_buffer (G_BUFFERED_INPUT_STREAM (stream), &size);
+
+  if (memcmp (data, "\x89PNG", 4) == 0)
+    {
+      texture = gdk_load_png (stream, error);
+      g_object_unref (stream);
+      return texture;
+    }
+
   pixbuf = gdk_pixbuf_new_from_stream (stream, NULL, error);
   g_object_unref (stream);
   if (pixbuf == NULL)
@@ -555,6 +577,9 @@ gdk_texture_get_render_data (GdkTexture  *self,
  *
  * Store the given @texture to the @filename as a PNG file.
  *
+ * If the texture contains 16bit data, the generated PNG file
+ * will have linear 16bit data, otherwise it will contain SRGB.
+ *
  * This is a utility function intended for debugging and testing.
  * If you want more control over formats, proper error handling or
  * want to store to a `GFile` or other location, you might want to
@@ -566,30 +591,51 @@ gboolean
 gdk_texture_save_to_png (GdkTexture *texture,
                          const char *filename)
 {
-  cairo_surface_t *surface;
-  cairo_status_t status;
+  int width, height;
+  GBytes *bytes;
+  GdkMemoryFormat format;
   gboolean result;
+  GFile *file;
+  GOutputStream *stream;
 
   g_return_val_if_fail (GDK_IS_TEXTURE (texture), FALSE);
   g_return_val_if_fail (filename != NULL, FALSE);
 
-  surface = cairo_image_surface_create (CAIRO_FORMAT_ARGB32,
-                                        gdk_texture_get_width (texture),
-                                        gdk_texture_get_height (texture));
-  gdk_texture_download (texture,
-                        cairo_image_surface_get_data (surface),
-                        cairo_image_surface_get_stride (surface));
-  cairo_surface_mark_dirty (surface);
-
-  status = cairo_surface_write_to_png (surface, filename);
+  width = gdk_texture_get_width (texture);
+  height = gdk_texture_get_height (texture);
 
-  if (status != CAIRO_STATUS_SUCCESS ||
-      cairo_surface_status (surface) != CAIRO_STATUS_SUCCESS)
-    result = FALSE;
+  bytes = gdk_texture_download_format (texture, GDK_MEMORY_R16G16B16A16_PREMULTIPLIED);
+  if (bytes)
+    {
+      format = GDK_MEMORY_R16G16B16A16_PREMULTIPLIED;
+    }
   else
-    result = TRUE;
+    {
+      gpointer data;
+
+      data = g_malloc (width * height * 4);
+
+      gdk_texture_download (texture, data, width * 4);
 
-  cairo_surface_destroy (surface);
+      bytes = g_bytes_new_take (data, width * height * 4);
+
+      format = GDK_MEMORY_DEFAULT;
+    }
+
+  file = g_file_new_for_path (filename);
+  stream = G_OUTPUT_STREAM (g_file_replace (file, NULL, FALSE,
+                                            G_FILE_CREATE_NONE,
+                                            NULL, NULL));
+  g_object_unref (file);
+
+  result = gdk_save_png (stream,
+                         g_bytes_get_data (bytes, NULL),
+                         width, height,
+                         format,
+                         NULL);
+
+  g_object_unref (file);
+  g_bytes_unref (bytes);
 
   return result;
 }
diff --git a/gdk/meson.build b/gdk/meson.build
index db64565c2c..47729fb1dc 100644
--- a/gdk/meson.build
+++ b/gdk/meson.build
@@ -50,6 +50,7 @@ gdk_public_sources = files([
   'gdktoplevelsize.c',
   'gdktoplevel.c',
   'gdkdragsurface.c',
+  'gdkpng.c',
 ])
 
 gdk_public_headers = files([
@@ -254,8 +255,8 @@ endif
 
 libgdk = static_library('gdk',
   sources: [gdk_sources, gdk_backends_gen_headers, gdkconfig],
-  dependencies: gdk_deps + [libgtk_css_dep],
-  link_with: [libgtk_css, ],
+  dependencies: gdk_deps + [libgtk_css_dep, png_dep],
+  link_with: [libgtk_css],
   include_directories: [confinc, gdkx11_inc, wlinc],
   c_args: libgdk_c_args + common_cflags,
   link_whole: gdk_backends,
diff --git a/meson.build b/meson.build
index c0b5407a0d..fc50b6e3eb 100644
--- a/meson.build
+++ b/meson.build
@@ -394,6 +394,7 @@ pangocairo_dep = dependency('pangocairo', version: pango_req,
 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')
 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]