file-heif.c 40.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/*
 * GIMP HEIF loader / write plugin.
 * Copyright (c) 2018 struktur AG, Dirk Farin <farin@struktur.de>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
16
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
 */

#include "config.h"

#include <libheif/heif.h>

#include <libgimp/gimp.h>
#include <libgimp/gimpui.h>

#include "libgimp/stdplugins-intl.h"


#define LOAD_PROC      "file-heif-load"
#define SAVE_PROC      "file-heif-save"
#define PLUG_IN_BINARY "file-heif"


34 35 36 37 38 39 40 41 42
typedef struct _Heif      Heif;
typedef struct _HeifClass HeifClass;

struct _Heif
{
  GimpPlugIn      parent_instance;
};

struct _HeifClass
43
{
44
  GimpPlugInClass parent_class;
45 46 47
};


48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
#define HEIF_TYPE  (heif_get_type ())
#define HEIF (obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), HEIF_TYPE, Heif))

GType                   heif_get_type         (void) G_GNUC_CONST;

static GList          * heif_query_procedures (GimpPlugIn           *plug_in);
static GimpProcedure  * heif_create_procedure (GimpPlugIn           *plug_in,
                                               const gchar          *name);

static GimpValueArray * heif_load             (GimpProcedure        *procedure,
                                               GimpRunMode           run_mode,
                                               GFile                *file,
                                               const GimpValueArray *args,
                                               gpointer              run_data);
static GimpValueArray * heif_save             (GimpProcedure        *procedure,
                                               GimpRunMode           run_mode,
                                               GimpImage            *image,
                                               GimpDrawable         *drawable,
                                               GFile                *file,
                                               const GimpValueArray *args,
                                               gpointer              run_data);

static GimpImage      * load_image            (GFile               *file,
                                               gboolean             interactive,
                                               GimpPDBStatusType    *status,
                                               GError              **error);
static gboolean         save_image            (GFile                *file,
                                               GimpImage            *image,
                                               GimpDrawable         *drawable,
77
                                               GObject              *config,
78 79 80 81
                                               GError              **error);

static gboolean         load_dialog           (struct heif_context  *heif,
                                               uint32_t             *selected_image);
82 83
static gboolean         save_dialog           (GimpProcedure        *procedure,
                                               GObject              *config);
84 85 86 87 88


G_DEFINE_TYPE (Heif, heif, GIMP_TYPE_PLUG_IN)

GIMP_MAIN (HEIF_TYPE)
89 90 91


static void
92
heif_class_init (HeifClass *klass)
93
{
94
  GimpPlugInClass *plug_in_class = GIMP_PLUG_IN_CLASS (klass);
95

96 97 98
  plug_in_class->query_procedures = heif_query_procedures;
  plug_in_class->create_procedure = heif_create_procedure;
}
99

100 101 102 103
static void
heif_init (Heif *heif)
{
}
104

105 106 107 108 109 110 111 112 113
static GList *
heif_query_procedures (GimpPlugIn *plug_in)
{
  GList *list = NULL;

  list = g_list_append (list, g_strdup (LOAD_PROC));
  list = g_list_append (list, g_strdup (SAVE_PROC));

  return list;
114 115
}

116 117 118 119 120
static GimpProcedure *
heif_create_procedure (GimpPlugIn  *plug_in,
                      const gchar *name)
{
  GimpProcedure *procedure = NULL;
121

122 123
  if (! strcmp (name, LOAD_PROC))
    {
124 125
      procedure = gimp_load_procedure_new (plug_in, name,
                                           GIMP_PDB_PROC_TYPE_PLUGIN,
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
                                           heif_load, NULL, NULL);

      gimp_procedure_set_menu_label (procedure, N_("HEIF/HEIC"));

      gimp_procedure_set_documentation (procedure,
                                        _("Loads HEIF images"),
                                        _("Load image stored in HEIF format (High "
                                          "Efficiency Image File Format). Typical "
                                          "suffices for HEIF files are .heif, "
                                          ".heic."),
                                        name);
      gimp_procedure_set_attribution (procedure,
                                      "Dirk Farin <farin@struktur.de>",
                                      "Dirk Farin <farin@struktur.de>",
                                      "2018");

      gimp_file_procedure_set_handles_remote (GIMP_FILE_PROCEDURE (procedure),
                                              TRUE);
      gimp_file_procedure_set_mime_types (GIMP_FILE_PROCEDURE (procedure),
                                          "image/heif");
      gimp_file_procedure_set_extensions (GIMP_FILE_PROCEDURE (procedure),
                                          "heif,heic");

      /* HEIF is an ISOBMFF format whose "brand" (the value after "ftyp")
       * can be of various values.
       * See also: https://gitlab.gnome.org/GNOME/gimp/issues/2209
       */
      gimp_file_procedure_set_magics (GIMP_FILE_PROCEDURE (procedure),
                                      "4,string,ftypheic,4,string,ftypheix,"
                                      "4,string,ftyphevc,4,string,ftypheim,"
                                      "4,string,ftypheis,4,string,ftyphevm,"
                                      "4,string,ftyphevs,4,string,ftypmif1,"
                                      "4,string,ftypmsf1");
    }
  else if (! strcmp (name, SAVE_PROC))
    {
162 163
      procedure = gimp_save_procedure_new (plug_in, name,
                                           GIMP_PDB_PROC_TYPE_PLUGIN,
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
                                           heif_save, NULL, NULL);

      gimp_procedure_set_image_types (procedure, "RGB*");

      gimp_procedure_set_menu_label (procedure, N_("HEIF/HEIC"));

      gimp_procedure_set_documentation (procedure,
                                        _("Exports HEIF images"),
                                        _("Save image in HEIF format (High "
                                          "Efficiency Image File Format)."),
                                        name);
      gimp_procedure_set_attribution (procedure,
                                      "Dirk Farin <farin@struktur.de>",
                                      "Dirk Farin <farin@struktur.de>",
                                      "2018");

      gimp_file_procedure_set_handles_remote (GIMP_FILE_PROCEDURE (procedure),
                                              TRUE);
      gimp_file_procedure_set_mime_types (GIMP_FILE_PROCEDURE (procedure),
                                          "image/heif");
      gimp_file_procedure_set_extensions (GIMP_FILE_PROCEDURE (procedure),
                                          "heif,heic");

      GIMP_PROC_ARG_INT (procedure, "quality",
                         "Quality",
                         "Quality factor (0 = worst, 100 = best)",
                         0, 100, 50,
                         G_PARAM_READWRITE);

      GIMP_PROC_ARG_BOOLEAN (procedure, "lossless",
                             "Lossless",
                             "Use lossless compression",
                             FALSE,
                             G_PARAM_READWRITE);
198 199 200 201 202 203

      GIMP_PROC_AUX_ARG_BOOLEAN (procedure, "save-profile",
                                 "Save profile",
                                 "Save the image's color profile",
                                 gimp_export_color_profile (),
                                 G_PARAM_READWRITE);
204 205 206 207 208 209 210 211 212 213 214
    }

  return procedure;
}

static GimpValueArray *
heif_load (GimpProcedure        *procedure,
          GimpRunMode           run_mode,
          GFile                *file,
          const GimpValueArray *args,
          gpointer              run_data)
215
{
216
  GimpValueArray    *return_vals;
217
  GimpPDBStatusType  status = GIMP_PDB_SUCCESS;
218 219 220
  GimpImage         *image;
  gboolean           interactive;
  GError            *error = NULL;
221 222

  INIT_I18N ();
223
  gegl_init (NULL, NULL);
224

225
  interactive = (run_mode == GIMP_RUN_INTERACTIVE);
226

227
  if (interactive)
228
    gimp_ui_init (PLUG_IN_BINARY);
229

230
  image = load_image (file, interactive, &status, &error);
231

232 233
  if (! image)
    return gimp_procedure_new_return_values (procedure, status, error);
234

235 236 237
  return_vals = gimp_procedure_new_return_values (procedure,
                                                  GIMP_PDB_SUCCESS,
                                                  NULL);
238

239
  GIMP_VALUES_SET_IMAGE (return_vals, 1, image);
240

241 242
  return return_vals;
}
243

244 245 246 247 248 249 250 251 252
static GimpValueArray *
heif_save (GimpProcedure        *procedure,
          GimpRunMode           run_mode,
          GimpImage            *image,
          GimpDrawable         *drawable,
          GFile                *file,
          const GimpValueArray *args,
          gpointer              run_data)
{
253 254 255 256 257
  GimpProcedureConfig  *config;
  GimpPDBStatusType     status = GIMP_PDB_SUCCESS;
  GimpExportReturn      export = GIMP_EXPORT_CANCEL;
  GimpImage            *orig_image;
  GError               *error  = NULL;
258

259 260
  INIT_I18N ();
  gegl_init (NULL, NULL);
261

262
  orig_image = image;
263

264 265 266 267
  switch (run_mode)
    {
    case GIMP_RUN_INTERACTIVE:
    case GIMP_RUN_WITH_LAST_VALS:
268
      gimp_ui_init (PLUG_IN_BINARY);
269

270 271 272 273 274 275 276 277 278
      export = gimp_export_image (&image, &drawable, "HEIF",
                                  GIMP_EXPORT_CAN_HANDLE_RGB |
                                  GIMP_EXPORT_CAN_HANDLE_ALPHA);

      if (export == GIMP_EXPORT_CANCEL)
        return gimp_procedure_new_return_values (procedure,
                                                 GIMP_PDB_CANCEL,
                                                 NULL);
      break;
279

280 281 282
    default:
      break;
    }
283

284 285
  config = gimp_procedure_create_config (procedure);
  gimp_procedure_config_begin_run (config, orig_image, run_mode, args);
286

287 288 289
  if (run_mode == GIMP_RUN_INTERACTIVE)
    {
      if (! save_dialog (procedure, G_OBJECT (config)))
290 291
        status = GIMP_PDB_CANCEL;
    }
292

293
  if (status == GIMP_PDB_SUCCESS)
294
    {
295 296 297 298 299
      if (save_image (file, image, drawable, G_OBJECT (config),
                      &error))
        {
          GimpMetadata          *metadata;
          GimpMetadataSaveFlags  metadata_flags;
300

301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
          metadata = gimp_image_metadata_save_prepare (orig_image,
                                                       "image/heif",
                                                       &metadata_flags);

          if (metadata)
            {
              gimp_image_metadata_save_finish (image,
                                               "image/heif",
                                               metadata, metadata_flags,
                                               file, NULL);
              g_object_unref (metadata);
            }

          gimp_procedure_config_end_run (config, orig_image, run_mode);
        }
      else
        {
          status = GIMP_PDB_EXECUTION_ERROR;
        }
320 321
    }

322 323 324 325
  g_object_unref (config);

  if (export == GIMP_EXPORT_EXPORT)
    gimp_image_delete (image);
326

327
  return gimp_procedure_new_return_values (procedure, status, error);
328 329
}

330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350
static goffset
get_file_size (GFile   *file,
               GError **error)
{
  GFileInfo *info;
  goffset    size = 1;

  info = g_file_query_info (file,
                            G_FILE_ATTRIBUTE_STANDARD_SIZE,
                            G_FILE_QUERY_INFO_NONE,
                            NULL, error);
  if (info)
    {
      size = g_file_info_get_size (info);

      g_object_unref (info);
    }

  return size;
}

351 352 353 354 355
GimpImage *
load_image (GFile              *file,
            gboolean            interactive,
            GimpPDBStatusType  *status,
            GError            **error)
356
{
357 358 359 360
  GInputStream             *input;
  goffset                   file_size;
  guchar                   *file_buffer;
  gsize                     bytes_read;
361 362
  struct heif_context      *ctx;
  struct heif_error         err;
363 364
  struct heif_image_handle *handle  = NULL;
  struct heif_image        *img     = NULL;
365
  GimpColorProfile         *profile = NULL;
366 367 368 369 370 371
  gint                      n_images;
  heif_item_id              primary;
  heif_item_id              selected_image;
  gboolean                  has_alpha;
  gint                      width;
  gint                      height;
372 373
  GimpImage                *image;
  GimpLayer                *layer;
374 375
  GeglBuffer               *buffer;
  const Babl               *format;
376 377 378
  const guint8             *data;
  gint                      stride;

379 380 381 382 383
  gimp_progress_init_printf (_("Opening '%s'"),
                             g_file_get_parse_name (file));

  file_size = get_file_size (file, error);
  if (file_size <= 0)
384
    return NULL;
385 386 387

  input = G_INPUT_STREAM (g_file_read (file, NULL, error));
  if (! input)
388
    return NULL;
389 390 391 392 393 394 395 396 397

  file_buffer = g_malloc (file_size);

  if (! g_input_stream_read_all (input, file_buffer, file_size,
                                 &bytes_read, NULL, error) &&
      bytes_read == 0)
    {
      g_free (file_buffer);
      g_object_unref (input);
398
      return NULL;
399 400 401 402
    }

  gimp_progress_update (0.25);

403 404
  ctx = heif_context_alloc ();

405
  err = heif_context_read_from_memory (ctx, file_buffer, file_size, NULL);
406 407 408 409 410 411
  if (err.code)
    {
      g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED,
                   _("Loading HEIF image failed: %s"),
                   err.message);
      heif_context_free (ctx);
412 413
      g_free (file_buffer);
      g_object_unref (input);
414

415
      return NULL;
416 417
    }

418 419 420 421 422
  g_free (file_buffer);
  g_object_unref (input);

  gimp_progress_update (0.5);

423 424 425 426 427 428 429 430 431 432 433 434
  /* analyze image content
   * Is there more than one image? Which image is the primary image?
   */

  n_images = heif_context_get_number_of_top_level_images (ctx);
  if (n_images == 0)
    {
      g_set_error_literal (error, G_FILE_ERROR, G_FILE_ERROR_FAILED,
                           _("Loading HEIF image failed: "
                             "Input file contains no readable images"));
      heif_context_free (ctx);

435
      return NULL;
436 437 438 439 440 441 442 443 444 445
    }

  err = heif_context_get_primary_image_ID (ctx, &primary);
  if (err.code)
    {
      g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED,
                   _("Loading HEIF image failed: %s"),
                   err.message);
      heif_context_free (ctx);

446
      return NULL;
447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470
    }

  /* if primary image is no top level image or not present (invalid
   * file), just take the first image
   */

  if (! heif_context_is_top_level_image_ID (ctx, primary))
    {
      gint n = heif_context_get_list_of_top_level_image_IDs (ctx, &primary, 1);
      g_assert (n == 1);
    }

  selected_image = primary;

  /* if there are several images in the file and we are running
   * interactive, let the user choose a picture
   */

  if (interactive && n_images > 1)
    {
      if (! load_dialog (ctx, &selected_image))
        {
          heif_context_free (ctx);

471 472 473
          *status = GIMP_PDB_CANCEL;

          return NULL;
474 475 476 477 478 479 480 481 482 483 484 485 486
        }
    }

  /* load the picture */

  err = heif_context_get_image_handle (ctx, selected_image, &handle);
  if (err.code)
    {
      g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED,
                   _("Loading HEIF image failed: %s"),
                   err.message);
      heif_context_free (ctx);

487
      return NULL;
488 489 490 491 492 493 494
    }

  has_alpha = heif_image_handle_has_alpha_channel (handle);

  err = heif_decode_image (handle,
                           &img,
                           heif_colorspace_RGB,
495 496
                           has_alpha ? heif_chroma_interleaved_RGBA :
                           heif_chroma_interleaved_RGB,
497 498 499 500 501 502 503 504 505
                           NULL);
  if (err.code)
    {
      g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED,
                   _("Loading HEIF image failed: %s"),
                   err.message);
     heif_image_handle_release (handle);
     heif_context_free (ctx);

506
     return NULL;
507 508
    }

509
#ifdef HAVE_LIBHEIF_1_4_0
510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536
  switch (heif_image_handle_get_color_profile_type (handle))
    {
    case heif_color_profile_type_not_present:
      break;
    case heif_color_profile_type_rICC:
    case heif_color_profile_type_prof:
      /* I am unsure, but it looks like both these types represent an
       * ICC color profile. XXX
       */
        {
          void   *profile_data;
          size_t  profile_size;

          profile_size = heif_image_handle_get_raw_color_profile_size (handle);
          profile_data = g_malloc0 (profile_size);
          err = heif_image_handle_get_raw_color_profile (handle, profile_data);

          if (err.code)
            g_warning ("%s: color profile loading failed and discarded.",
                       G_STRFUNC);
          else
            profile = gimp_color_profile_new_from_icc_profile ((guint8 *) profile_data,
                                                               profile_size, NULL);

          g_free (profile_data);
        }
      break;
537

538 539 540 541 542 543 544 545
    default:
      /* heif_color_profile_type_nclx (what is that?) and any future
       * profile type which we don't support in GIMP (yet).
       */
      g_warning ("%s: unknown color profile type has been discarded.",
                 G_STRFUNC);
      break;
    }
546
#endif /* HAVE_LIBHEIF_1_4_0 */
547

548 549
  gimp_progress_update (0.75);

550 551 552 553 554 555 556
  width  = heif_image_get_width  (img, heif_channel_interleaved);
  height = heif_image_get_height (img, heif_channel_interleaved);

  /* create GIMP image and copy HEIF image into the GIMP image
   * (converting it to RGB)
   */

557
  image = gimp_image_new (width, height, GIMP_RGB);
558
  gimp_image_set_file (image, file);
559

560
  if (profile)
561
    gimp_image_set_color_profile (image, profile);
562

563 564 565 566 567 568
  layer = gimp_layer_new (image,
                          _("image content"),
                          width, height,
                          has_alpha ? GIMP_RGBA_IMAGE : GIMP_RGB_IMAGE,
                          100.0,
                          gimp_image_get_default_new_layer_mode (image));
569

570
  gimp_image_insert_layer (image, layer, NULL, 0);
571

572
  buffer = gimp_drawable_get_buffer (GIMP_DRAWABLE (layer));
573

574
  if (has_alpha)
575 576
    format = babl_format_with_space ("R'G'B'A u8",
                                     gegl_buffer_get_format (buffer));
577
  else
578 579
    format = babl_format_with_space ("R'G'B' u8",
                                     gegl_buffer_get_format (buffer));
580 581 582 583

  data = heif_image_get_plane_readonly (img, heif_channel_interleaved,
                                        &stride);

584 585 586
  gegl_buffer_set (buffer,
                   GEGL_RECTANGLE (0, 0, width, height),
                   0, format, data, stride);
587

588
  g_object_unref (buffer);
589

590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635
  {
    size_t        exif_data_size = 0;
    uint8_t      *exif_data      = NULL;
    size_t        xmp_data_size  = 0;
    uint8_t      *xmp_data       = NULL;
    gint          n_metadata;
    heif_item_id  metadata_id;

    n_metadata =
      heif_image_handle_get_list_of_metadata_block_IDs (handle,
                                                        "Exif",
                                                        &metadata_id, 1);
    if (n_metadata > 0)
      {
        exif_data_size = heif_image_handle_get_metadata_size (handle,
                                                              metadata_id);
        exif_data = g_alloca (exif_data_size);

        err = heif_image_handle_get_metadata (handle, metadata_id, exif_data);
        if (err.code != 0)
          {
            exif_data      = NULL;
            exif_data_size = 0;
          }
      }

    n_metadata =
      heif_image_handle_get_list_of_metadata_block_IDs (handle,
                                                        "XMP",
                                                        &metadata_id, 1);
    if (n_metadata > 0)
      {
        xmp_data_size = heif_image_handle_get_metadata_size (handle,
                                                             metadata_id);
        xmp_data = g_alloca (xmp_data_size);

        err = heif_image_handle_get_metadata (handle, metadata_id, xmp_data);
        if (err.code != 0)
          {
            xmp_data      = NULL;
            xmp_data_size = 0;
          }
      }

    if (exif_data || xmp_data)
      {
636 637
        GimpMetadata          *metadata = gimp_metadata_new ();
        GimpMetadataLoadFlags  flags    = GIMP_METADATA_LOAD_ALL;
638 639 640 641 642 643 644 645 646

        if (exif_data)
          gimp_metadata_set_from_exif (metadata,
                                       exif_data, exif_data_size, NULL);

        if (xmp_data)
          gimp_metadata_set_from_xmp (metadata,
                                      xmp_data, xmp_data_size, NULL);

647 648 649
        if (profile)
          flags &= ~GIMP_METADATA_LOAD_COLORSPACE;

650
        gimp_image_metadata_load_finish (image, "image/heif",
651
                                         metadata, flags,
652 653 654
                                         interactive);
      }
  }
655

656 657 658
  if (profile)
    g_object_unref (profile);

659 660 661 662
  heif_image_handle_release (handle);
  heif_context_free (ctx);
  heif_image_release (img);

663 664
  gimp_progress_update (1.0);

665
  return image;
666 667
}

668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690
static struct heif_error
write_callback (struct heif_context *ctx,
                const void          *data,
                size_t               size,
                void                *userdata)
{
  GOutputStream     *output = userdata;
  GError            *error  = NULL;
  struct heif_error  heif_error;

  heif_error.code    = heif_error_Ok;
  heif_error.subcode = heif_error_Ok;
  heif_error.message = "";

  if (! g_output_stream_write_all (output, data, size, NULL, NULL, &error))
    {
      heif_error.code    = 99; /* hmm */
      heif_error.message = error->message;
    }

  return heif_error;
}

691
static gboolean
692 693 694 695 696
save_image (GFile         *file,
            GimpImage     *image,
            GimpDrawable  *drawable,
            GObject       *config,
            GError       **error)
697
{
698
  struct heif_image        *h_image = NULL;
699
  struct heif_context      *context = heif_context_alloc ();
700 701
  struct heif_encoder      *encoder = NULL;
  struct heif_image_handle *handle  = NULL;
702
  struct heif_writer        writer;
703
  struct heif_error         err;
704
  GOutputStream            *output;
705
  GeglBuffer               *buffer;
706
  const gchar              *encoding;
707
  const Babl               *format;
708
  const Babl               *space   = NULL;
709 710 711 712 713
  guint8                   *data;
  gint                      stride;
  gint                      width;
  gint                      height;
  gboolean                  has_alpha;
714
  gboolean                  out_linear = FALSE;
715 716 717 718 719 720 721 722 723
  gboolean                  lossless;
  gint                      quality;
  gboolean                  save_profile;

  g_object_get (config,
                "lossless",     &lossless,
                "quality",      &quality,
                "save-profile", &save_profile,
                NULL);
724

725 726 727
  gimp_progress_init_printf (_("Exporting '%s'"),
                             g_file_get_parse_name (file));

728 729
  width   = gimp_drawable_width  (drawable);
  height  = gimp_drawable_height (drawable);
730

731
  has_alpha = gimp_drawable_has_alpha (drawable);
732 733 734 735

  err = heif_image_create (width, height,
                           heif_colorspace_RGB,
                           has_alpha ?
736 737
                           heif_chroma_interleaved_RGBA :
                           heif_chroma_interleaved_RGB,
738
                           &h_image);
739

740
#ifdef HAVE_LIBHEIF_1_4_0
741
  if (save_profile)
742
    {
743 744 745 746
      GimpColorProfile *profile = NULL;
      const guint8     *icc_data;
      gsize             icc_length;

747
      profile = gimp_image_get_color_profile (image);
748 749
      if (profile && gimp_color_profile_is_linear (profile))
        out_linear = TRUE;
750

751
      if (! profile)
752
        {
753
          profile = gimp_image_get_effective_color_profile (image);
754

755
          if (gimp_color_profile_is_linear (profile))
756
            {
757
              if (gimp_image_get_precision (image) != GIMP_PRECISION_U8_LINEAR)
758 759 760 761 762 763 764 765 766 767 768 769 770
                {
                  /* If stored data was linear, let's convert the profile. */
                  GimpColorProfile *saved_profile;

                  saved_profile = gimp_color_profile_new_srgb_trc_from_color_profile (profile);
                  g_clear_object (&profile);
                  profile = saved_profile;
                }
              else
                {
                  /* Keep linear profile as-is for 8-bit linear image. */
                  out_linear = TRUE;
                }
771
            }
772 773
        }

774
      icc_data = gimp_color_profile_get_icc_profile (profile, &icc_length);
775
      heif_image_set_raw_color_profile (h_image, "prof", icc_data, icc_length);
776 777 778 779 780 781 782 783 784 785
      space = gimp_color_profile_get_space (profile,
                                            GIMP_COLOR_RENDERING_INTENT_RELATIVE_COLORIMETRIC,
                                            error);
      if (error && *error)
        {
          /* Don't make this a hard failure yet output the error. */
          g_printerr ("%s: error getting the profile space: %s",
                      G_STRFUNC, (*error)->message);
          g_clear_error (error);
        }
786

787 788
      g_object_unref (profile);
    }
789 790
#endif /* HAVE_LIBHEIF_1_4_0 */

791
  if (! space)
792
    space = gimp_drawable_get_format (drawable);
793

794
  heif_image_add_plane (h_image, heif_channel_interleaved,
795 796
                        width, height, has_alpha ? 32 : 24);

797
  data = heif_image_get_plane (h_image, heif_channel_interleaved, &stride);
798

799
  buffer = gimp_drawable_get_buffer (drawable);
800

801
  if (has_alpha)
802 803
    {
      if (out_linear)
804
        encoding = "RGBA u8";
805
      else
806
        encoding = "R'G'B'A u8";
807
    }
808
  else
809 810
    {
      if (out_linear)
811
        encoding = "RGB u8";
812
      else
813
        encoding = "R'G'B' u8";
814
    }
815
  format = babl_format_with_space (encoding, space);
816

817 818 819
  gegl_buffer_get (buffer,
                   GEGL_RECTANGLE (0, 0, width, height),
                   1.0, format, data, stride, GEGL_ABYSS_NONE);
820

821
  g_object_unref (buffer);
822

823 824
  gimp_progress_update (0.33);

825 826 827 828 829 830
  /*  encode to HEIF file  */

  err = heif_context_get_encoder_for_format (context,
                                             heif_compression_HEVC,
                                             &encoder);

831 832
  heif_encoder_set_lossy_quality (encoder, quality);
  heif_encoder_set_lossless (encoder, lossless);
833 834 835
  /* heif_encoder_set_logging_level (encoder, logging_level); */

  err = heif_context_encode_image (context,
836
                                   h_image,
837 838 839 840 841 842 843 844 845 846 847 848 849
                                   encoder,
                                   NULL,
                                   &handle);
  if (err.code != 0)
    {
      g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED,
                   _("Encoding HEIF image failed: %s"),
                   err.message);
      return FALSE;
    }

  heif_image_handle_release (handle);

850 851 852 853 854 855 856 857 858 859 860 861
  gimp_progress_update (0.66);

  writer.writer_api_version = 1;
  writer.write              = write_callback;

  output = G_OUTPUT_STREAM (g_file_replace (file,
                                            NULL, FALSE, G_FILE_CREATE_NONE,
                                            NULL, error));
  if (! output)
    return FALSE;

  err = heif_context_write (context, &writer, output);
862 863 864

  if (err.code != 0)
    {
865 866 867 868 869 870
      GCancellable *cancellable = g_cancellable_new ();

      g_cancellable_cancel (cancellable);
      g_output_stream_close (output, cancellable, NULL);
      g_object_unref (cancellable);

871 872 873 874 875 876
      g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED,
                   _("Writing HEIF image failed: %s"),
                   err.message);
      return FALSE;
    }

877 878
  g_object_unref (output);

879
  heif_context_free (context);
880
  heif_image_release (h_image);
881 882 883

  heif_encoder_release (encoder);

884 885
  gimp_progress_update (1.0);

886 887 888 889
  return TRUE;
}


890
/*  the load dialog  */
891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925

#define MAX_THUMBNAIL_SIZE 320

typedef struct _HeifImage HeifImage;

struct _HeifImage
{
  uint32_t           ID;
  gchar              caption[100];
  struct heif_image *thumbnail;
  gint               width;
  gint               height;
};

static gboolean
load_thumbnails (struct heif_context *heif,
                 HeifImage           *images)
{
  guint32 *IDs;
  gint     n_images;
  gint     i;

  n_images = heif_context_get_number_of_top_level_images (heif);

  /* get list of all (top level) image IDs */

  IDs = g_alloca (n_images * sizeof (guint32));

  heif_context_get_list_of_top_level_image_IDs (heif, IDs, n_images);


  /* Load a thumbnail for each image. */

  for (i = 0; i < n_images; i++)
    {
926
      struct heif_image_handle *handle = NULL;
927 928 929
      struct heif_error         err;
      gint                      width;
      gint                      height;
930
      struct heif_image_handle *thumbnail_handle = NULL;
931 932
      heif_item_id              thumbnail_ID;
      gint                      n_thumbnails;
933
      struct heif_image        *thumbnail_img = NULL;
934 935 936
      gint                      thumbnail_width;
      gint                      thumbnail_height;

937
      images[i].ID         = IDs[i];
938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000
      images[i].caption[0] = 0;
      images[i].thumbnail  = NULL;

      /* get image handle */

      err = heif_context_get_image_handle (heif, IDs[i], &handle);
      if (err.code)
        {
          gimp_message (err.message);
          continue;
        }

      /* generate image caption */

      width  = heif_image_handle_get_width  (handle);
      height = heif_image_handle_get_height (handle);

      if (heif_image_handle_is_primary_image (handle))
        {
          g_snprintf (images[i].caption, sizeof (images[i].caption),
                      "%dx%d (%s)", width, height, _("primary"));
        }
      else
        {
          g_snprintf (images[i].caption, sizeof (images[i].caption),
                      "%dx%d", width, height);
        }

      /* get handle to thumbnail image
       *
       * if there is no thumbnail image, just the the image itself
       * (will be scaled down later)
       */

      n_thumbnails = heif_image_handle_get_list_of_thumbnail_IDs (handle,
                                                                  &thumbnail_ID,
                                                                  1);

      if (n_thumbnails > 0)
        {
          err = heif_image_handle_get_thumbnail (handle, thumbnail_ID,
                                                 &thumbnail_handle);
          if (err.code)
            {
              gimp_message (err.message);
              continue;
            }
        }
      else
        {
          err = heif_context_get_image_handle (heif, IDs[i], &thumbnail_handle);
          if (err.code)
            {
              gimp_message (err.message);
              continue;
            }
        }

      /* decode the thumbnail image */

      err = heif_decode_image (thumbnail_handle,
                               &thumbnail_img,
                               heif_colorspace_RGB,
1001
                               heif_chroma_interleaved_RGB,
1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069
                               NULL);
      if (err.code)
        {
          gimp_message (err.message);
          continue;
        }

      /* if thumbnail image size exceeds the maximum, scale it down */

      thumbnail_width  = heif_image_handle_get_width  (thumbnail_handle);
      thumbnail_height = heif_image_handle_get_height (thumbnail_handle);

      if (thumbnail_width  > MAX_THUMBNAIL_SIZE ||
          thumbnail_height > MAX_THUMBNAIL_SIZE)
        {
          /* compute scaling factor to fit into a max sized box */

          gfloat factor_h = thumbnail_width  / (gfloat) MAX_THUMBNAIL_SIZE;
          gfloat factor_v = thumbnail_height / (gfloat) MAX_THUMBNAIL_SIZE;
          gint   new_width, new_height;
          struct heif_image *scaled_img = NULL;

          if (factor_v > factor_h)
            {
              new_height = MAX_THUMBNAIL_SIZE;
              new_width  = thumbnail_width / factor_v;
            }
          else
            {
              new_height = thumbnail_height / factor_h;
              new_width  = MAX_THUMBNAIL_SIZE;
            }

          /* scale the image */

          err = heif_image_scale_image (thumbnail_img,
                                        &scaled_img,
                                        new_width, new_height,
                                        NULL);
          if (err.code)
            {
              gimp_message (err.message);
              continue;
            }

          /* release the old image and only keep the scaled down version */

          heif_image_release (thumbnail_img);
          thumbnail_img = scaled_img;

          thumbnail_width  = new_width;
          thumbnail_height = new_height;
        }

      heif_image_handle_release (thumbnail_handle);
      heif_image_handle_release (handle);

      /* remember the HEIF thumbnail image (we need it for the GdkPixbuf) */

      images[i].thumbnail = thumbnail_img;

      images[i].width  = thumbnail_width;
      images[i].height = thumbnail_height;
    }

  return TRUE;
}

1070 1071 1072 1073 1074 1075 1076
static void
load_dialog_item_activated (GtkIconView *icon_view,
                            GtkTreePath *path,
                            GtkDialog   *dialog)
{
  gtk_dialog_response (dialog, GTK_RESPONSE_OK);
}
1077 1078 1079 1080 1081

static gboolean
load_dialog (struct heif_context *heif,
             uint32_t            *selected_image)
{
1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094
  GtkWidget       *dialog;
  GtkWidget       *main_vbox;
  GtkWidget       *frame;
  HeifImage       *heif_images;
  GtkListStore    *list_store;
  GtkTreeIter      iter;
  GtkWidget       *scrolled_window;
  GtkWidget       *icon_view;
  GtkCellRenderer *renderer;
  gint             n_images;
  gint             i;
  gint             selected_idx = -1;
  gboolean         run          = FALSE;
1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106

  n_images = heif_context_get_number_of_top_level_images (heif);

  heif_images = g_alloca (n_images * sizeof (HeifImage));

  if (! load_thumbnails (heif, heif_images))
    return FALSE;

  dialog = gimp_dialog_new (_("Load HEIF Image"), PLUG_IN_BINARY,
                            NULL, 0,
                            gimp_standard_help_func, LOAD_PROC,

1107 1108
                            _("_Cancel"), GTK_RESPONSE_CANCEL,
                            _("_OK"),     GTK_RESPONSE_OK,
1109 1110 1111

                            NULL);

1112
  main_vbox = gtk_box_new (GTK_ORIENTATION_VERTICAL, 12);
1113 1114 1115 1116 1117
  gtk_container_set_border_width (GTK_CONTAINER (main_vbox), 12);
  gtk_box_pack_start (GTK_BOX (gtk_dialog_get_content_area (GTK_DIALOG (dialog))),
                      main_vbox, TRUE, TRUE, 0);

  frame = gimp_frame_new (_("Select Image"));
1118
  gtk_box_pack_start (GTK_BOX (main_vbox), frame, TRUE, TRUE, 0);
1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150
  gtk_widget_show (frame);

  /* prepare list store with all thumbnails and caption */

  list_store = gtk_list_store_new (2, G_TYPE_STRING, GDK_TYPE_PIXBUF);

  for (i = 0; i < n_images; i++)
    {
      GdkPixbuf    *pixbuf;
      const guint8 *data;
      gint          stride;

      gtk_list_store_append (list_store, &iter);
      gtk_list_store_set (list_store, &iter, 0, heif_images[i].caption, -1);

      data = heif_image_get_plane_readonly (heif_images[i].thumbnail,
                                            heif_channel_interleaved,
                                            &stride);

      pixbuf = gdk_pixbuf_new_from_data (data,
                                         GDK_COLORSPACE_RGB,
                                         FALSE,
                                         8,
                                         heif_images[i].width,
                                         heif_images[i].height,
                                         stride,
                                         NULL,
                                         NULL);

      gtk_list_store_set (list_store, &iter, 1, pixbuf, -1);
    }

1151 1152 1153 1154 1155 1156 1157 1158 1159
  scrolled_window = gtk_scrolled_window_new (NULL, NULL);
  gtk_scrolled_window_set_shadow_type (GTK_SCROLLED_WINDOW (scrolled_window),
                                       GTK_SHADOW_IN);
  gtk_widget_set_size_request (scrolled_window,
                               2   * MAX_THUMBNAIL_SIZE,
                               1.5 * MAX_THUMBNAIL_SIZE);
  gtk_container_add (GTK_CONTAINER (frame), scrolled_window);
  gtk_widget_show (scrolled_window);

1160
  icon_view = gtk_icon_view_new_with_model (GTK_TREE_MODEL (list_store));
1161
  gtk_container_add (GTK_CONTAINER (scrolled_window), icon_view);
1162 1163
  gtk_widget_show (icon_view);

1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185
  renderer = gtk_cell_renderer_pixbuf_new ();
  gtk_cell_layout_pack_start (GTK_CELL_LAYOUT (icon_view), renderer, FALSE);
  gtk_cell_layout_set_attributes (GTK_CELL_LAYOUT (icon_view), renderer,
                                  "pixbuf", 1,
                                  NULL);

  renderer = gtk_cell_renderer_text_new ();
  gtk_cell_layout_pack_start (GTK_CELL_LAYOUT (icon_view), renderer, FALSE);
  gtk_cell_layout_set_attributes (GTK_CELL_LAYOUT (icon_view), renderer,
                                  "text", 0,
                                  NULL);
  g_object_set (renderer,
                "alignment", PANGO_ALIGN_CENTER,
                "wrap-mode", PANGO_WRAP_WORD_CHAR,
                "xalign",    0.5,
                "yalign",    0.0,
                NULL);

  g_signal_connect (icon_view, "item-activated",
                    G_CALLBACK (load_dialog_item_activated),
                    dialog);

1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236
  /* pre-select the primary image */

  for (i = 0; i < n_images; i++)
    {
      if (heif_images[i].ID == *selected_image)
        {
          selected_idx = i;
          break;
        }
    }

  if (selected_idx != -1)
    {
      GtkTreePath *path = gtk_tree_path_new_from_indices (selected_idx, -1);

      gtk_icon_view_select_path (GTK_ICON_VIEW (icon_view), path);
      gtk_tree_path_free (path);
    }

  gtk_widget_show (main_vbox);
  gtk_widget_show (dialog);

  run = (gimp_dialog_run (GIMP_DIALOG (dialog)) == GTK_RESPONSE_OK);

  if (run)
    {
      GList *selected_items =
        gtk_icon_view_get_selected_items (GTK_ICON_VIEW (icon_view));

      if (selected_items)
        {
          GtkTreePath *path    = selected_items->data;
          gint        *indices = gtk_tree_path_get_indices (path);

          *selected_image = heif_images[indices[0]].ID;

          g_list_free_full (selected_items,
                            (GDestroyNotify) gtk_tree_path_free);
        }
    }

  gtk_widget_destroy (dialog);

  /* release thumbnail images */

  for (i = 0 ; i < n_images; i++)
    heif_image_release (heif_images[i].thumbnail);

  return run;
}

1237 1238 1239

/*  the save dialog  */

1240
gboolean
1241 1242
save_dialog (GimpProcedure *procedure,
             GObject       *config)
1243 1244 1245
{
  GtkWidget *dialog;
  GtkWidget *main_vbox;
1246 1247
  GtkWidget *grid;
  GtkWidget *button;
1248
  GtkWidget *frame;
1249
  gboolean   run;
1250

1251 1252 1253
  dialog = gimp_procedure_dialog_new (procedure,
                                      GIMP_PROCEDURE_CONFIG (config),
                                      _("Export Image as HEIF"));
1254

1255
  main_vbox = gtk_box_new (GTK_ORIENTATION_VERTICAL, 12);
1256
  gtk_container_set_border_width (GTK_CONTAINER (main_vbox), 12);
1257 1258 1259
  gtk_box_pack_start (GTK_BOX (gtk_dialog_get_content_area (GTK_DIALOG (dialog))),
                      main_vbox, FALSE, FALSE, 0);
  gtk_widget_show (main_vbox);
1260

1261 1262
  frame = gimp_frame_new (NULL);
  gtk_box_pack_start (GTK_BOX (main_vbox), frame, FALSE, FALSE, 0);
1263
  gtk_widget_show (frame);
1264

1265 1266 1267 1268
  button = gimp_prop_check_button_new (config, "lossless",
                                       _("_Lossless"));
  gtk_frame_set_label_widget (GTK_FRAME (frame), button);
  gtk_widget_show (button);
1269

1270 1271 1272 1273
  grid = gtk_grid_new ();
  gtk_grid_set_column_spacing (GTK_GRID (grid), 6);
  gtk_container_add (GTK_CONTAINER (frame), grid);
  gtk_widget_show (grid);
1274

1275 1276 1277 1278
  g_object_bind_property (config, "lossless",
                          grid,   "sensitive",
                          G_BINDING_SYNC_CREATE |
                          G_BINDING_INVERT_BOOLEAN);
1279

1280 1281 1282 1283 1284
  gimp_prop_scale_entry_new (config, "quality",
                             GTK_GRID (grid), 0, 1,
                             _("_Quality"),
                             1, 10, 0,
                             FALSE, 0, 0);
1285

1286
#ifdef HAVE_LIBHEIF_1_4_0
1287 1288 1289 1290
  button = gimp_prop_check_button_new (config, "save-profile",
                                       _("Save color _profile"));
  gtk_box_pack_start (GTK_BOX (main_vbox), button, FALSE, FALSE, 0);
  gtk_widget_show (button);
1291 1292
#endif

1293
  gtk_widget_show (dialog);
1294

1295
  run = gimp_procedure_dialog_run (GIMP_PROCEDURE_DIALOG (dialog));
1296 1297 1298 1299 1300

  gtk_widget_destroy (dialog);

  return run;
}