animation-optimize.c 44.5 KB
Newer Older
Manish Singh's avatar
Manish Singh committed
1
/*
2
 * Animation Optimizer plug-in version 1.1.2
Manish Singh's avatar
Manish Singh committed
3
 *
4
 * (c) Adam D. Moss, 1997-2003
Manish Singh's avatar
Manish Singh committed
5 6 7
 *     adam@gimp.org
 *     adam@foxbox.org
 *
8
 * GIMP - The GNU Image Manipulation Program
9
 * Copyright (C) 1995 Spencer Kimball and Peter Mattis
10
 *
11
 * This program is free software: you can redistribute it and/or modify
12
 * it under the terms of the GNU General Public License as published by
13
 * the Free Software Foundation; either version 3 of the License, or
14
 * (at your option) any later version.
15
 *
16 17 18 19
 * 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.
Manish Singh's avatar
Manish Singh committed
20
 *
21
 * You should have received a copy of the GNU General Public License
22
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
Manish Singh's avatar
Manish Singh committed
23 24
 */

25 26 27 28 29
/*
#define EXPERIMENTAL_BACKDROP_CODE
*/


30 31
#include "config.h"

Manish Singh's avatar
Manish Singh committed
32 33
#include <string.h>

34 35 36
#include <libgimp/gimp.h>

#include "libgimp/stdplugins-intl.h"
Manish Singh's avatar
Manish Singh committed
37 38


39 40 41 42 43 44 45
#define OPTIMIZE_PROC        "plug-in-animationoptimize"
#define OPTIMIZE_DIFF_PROC   "plug-in-animationoptimize-diff"
#define UNOPTIMIZE_PROC      "plug-in-animationunoptimize"
#define REMOVE_BACKDROP_PROC "plug-in-animation-remove-backdrop"
#define FIND_BACKDROP_PROC   "plug-in-animation-find-backdrop"


Manish Singh's avatar
Manish Singh committed
46 47 48 49 50 51 52 53
typedef enum
{
  DISPOSE_UNDEFINED = 0x00,
  DISPOSE_COMBINE   = 0x01,
  DISPOSE_REPLACE   = 0x02
} DisposeType;


54 55 56 57 58 59 60 61
typedef enum
{
  OPOPTIMIZE   = 0L,
  OPUNOPTIMIZE = 1L,
  OPFOREGROUND = 2L,
  OPBACKGROUND = 3L
} operatingMode;

Manish Singh's avatar
Manish Singh committed
62

63 64
typedef struct _Optimize      Optimize;
typedef struct _OptimizeClass OptimizeClass;
Manish Singh's avatar
Manish Singh committed
65

66 67 68 69
struct _Optimize
{
  GimpPlugIn parent_instance;
};
70

71
struct _OptimizeClass
Manish Singh's avatar
Manish Singh committed
72
{
73
  GimpPlugInClass parent_class;
Manish Singh's avatar
Manish Singh committed
74 75 76
};


77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
#define OPTIMIZE_TYPE  (optimize_get_type ())
#define OPTIMIZE (obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), OPTIMIZE_TYPE, Optimize))

GType                   optimize_get_type         (void) G_GNUC_CONST;

static GList          * optimize_query_procedures (GimpPlugIn           *plug_in);
static GimpProcedure  * optimize_create_procedure (GimpPlugIn           *plug_in,
                                                   const gchar          *name);

static GimpValueArray * optimize_run              (GimpProcedure        *procedure,
                                                   GimpRunMode           run_mode,
                                                   GimpImage            *image,
                                                   GimpDrawable         *drawable,
                                                   const GimpValueArray *args,
                                                   gpointer              run_data);

static  GimpImage     * do_optimizations          (GimpRunMode  run_mode,
                                                   GimpImage   *image,
                                                   gboolean     diff_only);

/* tag util functions*/
static  gint            parse_ms_tag              (const gchar *str);
static  DisposeType     parse_disposal_tag        (const gchar *str);
static  DisposeType     get_frame_disposal        (guint        whichframe);
static  guint32         get_frame_duration        (guint        whichframe);
static  void            remove_disposal_tag       (gchar       *dest,
                                                   gchar       *src);
static  void            remove_ms_tag             (gchar       *dest,
                                                   gchar       *src);
static  gboolean        is_disposal_tag           (const gchar *str,
                                                   DisposeType *disposal,
                                                   gint        *taglength);
static  gboolean        is_ms_tag                 (const gchar *str,
                                                   gint        *duration,
                                                   gint        *taglength);


G_DEFINE_TYPE (Optimize, optimize, GIMP_TYPE_PLUG_IN)

GIMP_MAIN (OPTIMIZE_TYPE)


Manish Singh's avatar
Manish Singh committed
119
/* Global widgets'n'stuff */
Sven Neumann's avatar
Sven Neumann committed
120 121
static  guint             width, height;
static  gint32            total_frames;
122
static  GimpLayer       **layers;
Sven Neumann's avatar
Sven Neumann committed
123 124
static  guchar            pixelstep;
static  guchar           *palette;
125
static  gint              ncolors;
Sven Neumann's avatar
Sven Neumann committed
126
static  operatingMode     opmode;
127 128


129 130 131 132 133 134 135 136
static void
optimize_class_init (OptimizeClass *klass)
{
  GimpPlugInClass *plug_in_class = GIMP_PLUG_IN_CLASS (klass);

  plug_in_class->query_procedures = optimize_query_procedures;
  plug_in_class->create_procedure = optimize_create_procedure;
}
137 138

static void
139
optimize_init (Optimize *optimize)
Manish Singh's avatar
Manish Singh committed
140
{
141
}
142

143 144 145 146 147 148 149 150
static GList *
optimize_query_procedures (GimpPlugIn *plug_in)
{
  GList *list = NULL;

  list = g_list_append (list, g_strdup (OPTIMIZE_PROC));
  list = g_list_append (list, g_strdup (OPTIMIZE_DIFF_PROC));
  list = g_list_append (list, g_strdup (UNOPTIMIZE_PROC));
151
#ifdef EXPERIMENTAL_BACKDROP_CODE
152 153
  list = g_list_append (list, g_strdup (REMOVE_BACKDROP_PROC));
  list = g_list_append (list, g_strdup (FIND_BACKDROP_PROC));
154
#endif
155 156

  return list;
Manish Singh's avatar
Manish Singh committed
157 158
}

159 160 161
static GimpProcedure *
optimize_create_procedure (GimpPlugIn  *plug_in,
                           const gchar *name)
Manish Singh's avatar
Manish Singh committed
162
{
163 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 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
  GimpProcedure *procedure = NULL;

  if (! strcmp (name, OPTIMIZE_PROC))
    {
      procedure = gimp_image_procedure_new (plug_in, name,
                                            GIMP_PDB_PROC_TYPE_PLUGIN,
                                            optimize_run, NULL, NULL);

      gimp_procedure_set_menu_label (procedure, N_("Optimize (for _GIF)"));

      gimp_procedure_set_documentation (procedure,
                                        N_("Modify image to reduce size when "
                                           "saved as GIF animation"),
                                        "This procedure applies various "
                                        "optimizations to a GIMP layer-based "
                                        "animation in an attempt to reduce the "
                                        "final file size.  If a frame of the"
                                        "animation can use the 'combine' "
                                        "mode, this procedure attempts to "
                                        "maximize the number of ajdacent "
                                        "pixels having the same color, which"
                                        "improves the compression for some "
                                        "image formats such as GIF or MNG.",
                                        name);
    }
  else if (! strcmp (name, OPTIMIZE_DIFF_PROC))
    {
      procedure = gimp_image_procedure_new (plug_in, name,
                                            GIMP_PDB_PROC_TYPE_PLUGIN,
                                            optimize_run, NULL, NULL);

      gimp_procedure_set_menu_label (procedure, N_("_Optimize (Difference)"));

      gimp_procedure_set_documentation (procedure,
                                        N_("Reduce file size where "
                                           "combining layers is possible"),
                                        "This procedure applies various "
                                        "optimizations to a GIMP layer-based "
                                        "animation in an attempt to reduce "
                                        "the final file size.  If a frame of "
                                        "the animation can use the 'combine' "
                                        "mode, this procedure uses a simple "
                                        "difference between the frames.",
                                        name);
    }
  else if (! strcmp (name, UNOPTIMIZE_PROC))
    {
      procedure = gimp_image_procedure_new (plug_in, name,
                                            GIMP_PDB_PROC_TYPE_PLUGIN,
                                            optimize_run, NULL, NULL);

      gimp_procedure_set_menu_label (procedure, N_("_Unoptimize"));

      gimp_procedure_set_documentation (procedure,
                                        N_("Remove optimization to make "
                                           "editing easier"),
                                        "This procedure 'simplifies' a GIMP "
                                        "layer-based animation that has been "
                                        "optimized for animation. This makes "
                                        "editing the animation much easier.",
                                        name);
    }
  else if (! strcmp (name, REMOVE_BACKDROP_PROC))
    {
      procedure = gimp_image_procedure_new (plug_in, name,
                                            GIMP_PDB_PROC_TYPE_PLUGIN,
                                            optimize_run, NULL, NULL);

      gimp_procedure_set_menu_label (procedure, N_("_Remove Backdrop"));

      gimp_procedure_set_documentation (procedure,
                                        "This procedure attempts to remove "
                                        "the backdrop from a GIMP layer-based "
                                        "animation, leaving the foreground "
                                        "animation over transparency.",
                                        NULL,
                                        name);
    }
  else if (! strcmp (name, FIND_BACKDROP_PROC))
    {
      procedure = gimp_image_procedure_new (plug_in, name,
                                            GIMP_PDB_PROC_TYPE_PLUGIN,
                                            optimize_run, NULL, NULL);

      gimp_procedure_set_menu_label (procedure, N_("_Find Backdrop"));

      gimp_procedure_set_documentation (procedure,
                                        "This procedure attempts to remove "
                                        "the foreground from a GIMP "
                                        "layer-based animation, leaving"
                                        " a one-layered image containing only "
                                        "the constant backdrop image.",
                                        NULL,
                                        name);
    }

  if (procedure)
    {
      gimp_procedure_set_image_types (procedure, "*");

      gimp_procedure_add_menu_path (procedure, "<Image>/Filters/Animation");

      gimp_procedure_set_attribution (procedure,
                                      "Adam D. Moss <adam@gimp.org>",
                                      "Adam D. Moss <adam@gimp.org>",
                                      "1997-2003");

      GIMP_PROC_VAL_IMAGE (procedure, "result",
                           "Result",
                           "Resultimg image",
                           FALSE,
                           G_PARAM_READWRITE);
    }
Manish Singh's avatar
Manish Singh committed
276

277 278
  return procedure;
}
Manish Singh's avatar
Manish Singh committed
279

280 281 282 283 284 285 286 287 288 289 290
static GimpValueArray *
optimize_run (GimpProcedure        *procedure,
              GimpRunMode           run_mode,
              GimpImage            *image,
              GimpDrawable         *drawable,
              const GimpValueArray *args,
              gpointer              run_data)
{
  GimpValueArray *return_vals;
  const gchar    *name      = gimp_procedure_get_name (procedure);
  gboolean        diff_only = FALSE;
291

292
  INIT_I18N ();
293
  gegl_init (NULL, NULL);
294

295
  if (! strcmp (name, OPTIMIZE_PROC))
Manish Singh's avatar
Manish Singh committed
296
    {
297
      opmode = OPOPTIMIZE;
Manish Singh's avatar
Manish Singh committed
298
    }
299
  else if (! strcmp (name, OPTIMIZE_DIFF_PROC))
300 301 302 303
    {
      opmode = OPOPTIMIZE;
      diff_only = TRUE;
    }
304 305 306 307 308
  else if (! strcmp (name, UNOPTIMIZE_PROC))
    {
      opmode = OPUNOPTIMIZE;
    }
  else if (strcmp (name, FIND_BACKDROP_PROC))
Manish Singh's avatar
Manish Singh committed
309
    {
310 311 312 313 314 315
      opmode = OPBACKGROUND;
    }
  else if (strcmp (name, REMOVE_BACKDROP_PROC))
    {
      opmode = OPFOREGROUND;
    }
316

317
  image = do_optimizations (run_mode, image, diff_only);
318

319 320 321 322 323 324
  if (run_mode != GIMP_RUN_NONINTERACTIVE)
    gimp_displays_flush();

  return_vals = gimp_procedure_new_return_values (procedure,
                                                  GIMP_PDB_SUCCESS,
                                                  NULL);
325

326
  GIMP_VALUES_SET_IMAGE (return_vals, 1, image);
327

328
  return return_vals;
Manish Singh's avatar
Manish Singh committed
329 330 331 332 333 334 335
}



/* Rendering Functions */

static void
336 337 338
total_alpha (guchar  *imdata,
             guint32  numpix,
             guchar   bytespp)
Manish Singh's avatar
Manish Singh committed
339 340 341 342
{
  /* Set image to total-transparency w/black
   */

343
  memset (imdata, 0, numpix * bytespp);
Manish Singh's avatar
Manish Singh committed
344 345
}

346
static const Babl *
347
get_format (GimpDrawable *drawable)
348
{
349
  if (gimp_drawable_is_rgb (drawable))
350
    {
351
      if (gimp_drawable_has_alpha (drawable))
352 353 354 355
        return babl_format ("R'G'B'A u8");
      else
        return babl_format ("R'G'B' u8");
    }
356
  else if (gimp_drawable_is_gray (drawable))
357
    {
358
      if (gimp_drawable_has_alpha (drawable))
359 360 361 362 363
        return babl_format ("Y'A u8");
      else
        return babl_format ("Y' u8");
    }

364
  return gimp_drawable_get_format (drawable);
365
}
366 367

static void
368 369 370 371 372
compose_row (gint          frame_num,
             DisposeType   dispose,
             gint          row_num,
             guchar       *dest,
             gint          dest_width,
373
             GimpDrawable *drawable,
374
             gboolean      cleanup)
375
{
376
  static guchar *line_buf = NULL;
377 378
  GeglBuffer    *src_buffer;
  const Babl    *format;
379 380 381 382
  guchar        *srcptr;
  gint           rawx, rawy, rawbpp, rawwidth, rawheight;
  gint           i;
  gboolean       has_alpha;
383 384 385 386

  if (cleanup)
    {
      if (line_buf)
387 388 389 390
        {
          g_free (line_buf);
          line_buf = NULL;
        }
391 392 393 394 395 396 397 398 399

      return;
    }

  if (dispose == DISPOSE_REPLACE)
    {
      total_alpha (dest, dest_width, pixelstep);
    }

400
  gimp_drawable_offsets (drawable, &rawx, &rawy);
401

402 403
  rawwidth  = gimp_drawable_width (drawable);
  rawheight = gimp_drawable_height (drawable);
404 405 406 407 408 409

  /* this frame has nothing to give us for this row; return */
  if (row_num >= rawheight + rawy ||
      row_num < rawy)
    return;

410
  format = get_format (drawable);
411

412
  has_alpha = gimp_drawable_has_alpha (drawable);
413
  rawbpp    = babl_format_get_bytes_per_pixel (format);
414 415 416

  if (line_buf)
    {
417
      g_free (line_buf);
418 419
      line_buf = NULL;
    }
420
  line_buf = g_malloc (rawwidth * rawbpp);
421 422 423

  /* Initialise and fetch the raw new frame row */

424
  src_buffer = gimp_drawable_get_buffer (drawable);
425 426 427 428 429 430 431

  gegl_buffer_get (src_buffer, GEGL_RECTANGLE (0, row_num - rawy,
                                               rawwidth, 1), 1.0,
                   format, line_buf,
                   GEGL_AUTO_ROWSTRIDE, GEGL_ABYSS_NONE);

  g_object_unref (src_buffer);
432 433 434 435

  /* render... */

  srcptr = line_buf;
436

437 438 439
  for (i=rawx; i<rawwidth+rawx; i++)
    {
      if (i>=0 && i<dest_width)
440 441 442 443 444 445 446 447 448
        {
          if ((!has_alpha) || ((*(srcptr+rawbpp-1))&128))
            {
              gint pi;

              for (pi = 0; pi < pixelstep-1; pi++)
                {
                  dest[i*pixelstep +pi] = *(srcptr + pi);
                }
449

450 451 452
              dest[i*pixelstep + pixelstep - 1] = 255;
            }
        }
453

454 455 456 457 458
      srcptr += rawbpp;
    }
}


459
static GimpImage *
460 461 462
do_optimizations (GimpRunMode  run_mode,
                  GimpImage   *image,
                  gboolean     diff_only)
Manish Singh's avatar
Manish Singh committed
463
{
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490
  GimpImage         *new_image;
  GimpImageBaseType  imagetype;
  GimpImageType      drawabletype_alpha;
  static guchar     *rawframe = NULL;
  guchar            *srcptr;
  guchar            *destptr;
  gint               row, this_frame_num;
  guint32            frame_sizebytes;
  GimpLayer         *new_layer;
  DisposeType        dispose;
  guchar            *this_frame = NULL;
  guchar            *last_frame = NULL;
  guchar            *opti_frame = NULL;
  guchar            *back_frame = NULL;

  gint               this_delay;
  gint               cumulated_delay = 0;
  GimpLayer         *last_true_frame = NULL;
  gint               buflen;

  gchar             *oldlayer_name;
  gchar             *newlayer_name;

  gboolean           can_combine;

  gint32             bbox_top, bbox_bottom, bbox_left, bbox_right;
  gint32             rbox_top, rbox_bottom, rbox_left, rbox_right;
Manish Singh's avatar
Manish Singh committed
491

492 493 494
  switch (opmode)
    {
    case OPUNOPTIMIZE:
495
      gimp_progress_init (_("Unoptimizing animation"));
496 497
      break;
    case OPFOREGROUND:
498
      gimp_progress_init (_("Removing animation background"));
499 500
      break;
    case OPBACKGROUND:
501
      gimp_progress_init (_("Finding animation background"));
502 503 504
      break;
    case OPOPTIMIZE:
    default:
505
      gimp_progress_init (_("Optimizing animation"));
506 507
      break;
    }
Manish Singh's avatar
Manish Singh committed
508

509 510 511 512
  width     = gimp_image_width (image);
  height    = gimp_image_height (image);
  layers    = gimp_image_get_layers (image, &total_frames);
  imagetype = gimp_image_base_type (image);
Sven Neumann's avatar
Sven Neumann committed
513
  pixelstep = (imagetype == GIMP_RGB) ? 4 : 2;
Manish Singh's avatar
Manish Singh committed
514

Sven Neumann's avatar
Sven Neumann committed
515 516
  drawabletype_alpha = (imagetype == GIMP_RGB) ? GIMP_RGBA_IMAGE :
    ((imagetype == GIMP_INDEXED) ? GIMP_INDEXEDA_IMAGE : GIMP_GRAYA_IMAGE);
Manish Singh's avatar
Manish Singh committed
517 518 519

  frame_sizebytes = width * height * pixelstep;

520 521 522
  this_frame = g_malloc (frame_sizebytes);
  last_frame = g_malloc (frame_sizebytes);
  opti_frame = g_malloc (frame_sizebytes);
523

524 525 526
  if (opmode == OPBACKGROUND ||
      opmode == OPFOREGROUND)
    back_frame = g_malloc (frame_sizebytes);
Manish Singh's avatar
Manish Singh committed
527

528 529
  total_alpha (this_frame, width*height, pixelstep);
  total_alpha (last_frame, width*height, pixelstep);
Manish Singh's avatar
Manish Singh committed
530

531 532
  new_image = gimp_image_new (width, height, imagetype);
  gimp_image_undo_disable (new_image);
Manish Singh's avatar
Manish Singh committed
533

Sven Neumann's avatar
Sven Neumann committed
534
  if (imagetype == GIMP_INDEXED)
Manish Singh's avatar
Manish Singh committed
535
    {
536 537
      palette = gimp_image_get_colormap (image, &ncolors);
      gimp_image_set_colormap (new_image, palette, ncolors);
Manish Singh's avatar
Manish Singh committed
538 539
    }

540 541 542
#if 1
  if (opmode == OPBACKGROUND ||
      opmode == OPFOREGROUND)
Manish Singh's avatar
Manish Singh committed
543
    {
544
      /* iterate through all rows of all frames, find statistical
545
         mode for each pixel position. */
546
      gint     i,j;
547 548 549 550
      guchar **these_rows;
      guchar **red;
      guchar **green;
      guchar **blue;
551
      guint  **count;
552
      guint   *num_colors;
553

554 555 556 557 558
      these_rows = g_new (guchar *, total_frames);
      red =        g_new (guchar *, total_frames);
      green =      g_new (guchar *, total_frames);
      blue =       g_new (guchar *, total_frames);
      count =      g_new (guint *, total_frames);
Manish Singh's avatar
Manish Singh committed
559

560
      num_colors = g_new (guint, width);
Manish Singh's avatar
Manish Singh committed
561

562
      for (this_frame_num=0; this_frame_num<total_frames; this_frame_num++)
563 564
        {
          these_rows[this_frame_num] = g_malloc(width * pixelstep);
Manish Singh's avatar
Manish Singh committed
565

566 567 568
          red[this_frame_num]   = g_new (guchar, width);
          green[this_frame_num] = g_new (guchar, width);
          blue[this_frame_num]  = g_new (guchar, width);
Manish Singh's avatar
Manish Singh committed
569

570 571
          count[this_frame_num] = g_new0(guint, width);
        }
572

573
      for (row = 0; row < height; row++)
574
        {
575
          memset(num_colors, 0, width * sizeof(guint));
576 577 578

          for (this_frame_num=0; this_frame_num<total_frames; this_frame_num++)
            {
579 580
              GimpDrawable *drawable =
                GIMP_DRAWABLE (layers[total_frames-(this_frame_num+1)]);
581 582 583

              dispose = get_frame_disposal (this_frame_num);

584 585 586 587 588
              compose_row (this_frame_num,
                           dispose,
                           row,
                           these_rows[this_frame_num],
                           width,
589
                           drawable,
590
                           FALSE);
591 592 593 594 595 596 597 598 599
            }

          for (this_frame_num=0; this_frame_num<total_frames; this_frame_num++)
            {
              for (i=0; i<width; i++)
                {
                  if (these_rows[this_frame_num][i * pixelstep + pixelstep -1]
                      >= 128)
                    {
600
                      for (j=0; j<num_colors[i]; j++)
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
                        {

                          switch (pixelstep)
                            {
                            case 4:
                              if (these_rows[this_frame_num][i * 4 +0] ==
                                  red[j][i] &&
                                  these_rows[this_frame_num][i * 4 +1] ==
                                  green[j][i] &&
                                  these_rows[this_frame_num][i * 4 +2] ==
                                  blue[j][i])
                                {
                                  (count[j][i])++;
                                  goto same;
                                }
                              break;
                            case 2:
                              if (these_rows[this_frame_num][i * 2 +0] ==
                                  red[j][i])
                                {
                                  (count[j][i])++;
                                  goto same;
                                }
                              break;
                            default:
                              g_error ("Eeep!");
                              break;
                            }
                        }

631 632
                      count[num_colors[i]][i] = 1;
                      red[num_colors[i]][i] =
633 634 635
                        these_rows[this_frame_num][i * pixelstep];
                      if (pixelstep == 4)
                        {
636
                          green[num_colors[i]][i] =
637
                            these_rows[this_frame_num][i * 4 +1];
638
                          blue[num_colors[i]][i] =
639 640
                            these_rows[this_frame_num][i * 4 +2];
                        }
641
                      num_colors[i]++;
642 643 644 645 646 647 648 649 650 651 652
                    }
                same:
                  /* nop */;
                }
            }

          for (i=0; i<width; i++)
            {
              guint  best_count = 0;
              guchar best_r = 255, best_g = 0, best_b = 255;

653
              for (j=0; j<num_colors[i]; j++)
654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681
                {
                  if (count[j][i] > best_count)
                    {
                      best_count = count[j][i];
                      best_r = red[j][i];
                      best_g = green[j][i];
                      best_b = blue[j][i];
                    }
                }

              back_frame[width * pixelstep * row +i*pixelstep + 0] = best_r;
              if (pixelstep == 4)
                {
                  back_frame[width * pixelstep * row +i*pixelstep + 1] =
                    best_g;
                  back_frame[width * pixelstep * row +i*pixelstep + 2] =
                    best_b;
                }
              back_frame[width * pixelstep * row +i*pixelstep +pixelstep-1] =
                (best_count == 0) ? 0 : 255;

              if (best_count == 0)
                g_warning("yayyyy!");
            }
          /*      memcpy(&back_frame[width * pixelstep * row],
                  these_rows[0],
                  width * pixelstep);*/
        }
682

683
      for (this_frame_num=0; this_frame_num<total_frames; this_frame_num++)
684 685 686 687 688 689 690 691 692 693 694 695 696
        {
          g_free (these_rows[this_frame_num]);
          g_free (red[this_frame_num]);
          g_free (green[this_frame_num]);
          g_free (blue[this_frame_num]);
          g_free (count[this_frame_num]);
        }

      g_free (these_rows);
      g_free (red);
      g_free (green);
      g_free (blue);
      g_free (count);
697
      g_free (num_colors);
698 699 700 701
    }
#endif

  if (opmode == OPBACKGROUND)
702
    {
703 704 705
      GeglBuffer *buffer;
      const Babl *format;

706 707 708 709 710 711
      new_layer = gimp_layer_new (new_image,
                                  "Backgroundx",
                                  width, height,
                                  drawabletype_alpha,
                                  100.0,
                                  gimp_image_get_default_new_layer_mode (new_image));
712

713
      gimp_image_insert_layer (new_image, new_layer, NULL, 0);
714

715
      buffer = gimp_drawable_get_buffer (GIMP_DRAWABLE (new_layer));
716

717
      format = get_format (GIMP_DRAWABLE (new_layer));
718 719 720 721 722 723

      gegl_buffer_set (buffer, GEGL_RECTANGLE (0, 0, width, height), 0,
                       format, back_frame,
                       GEGL_ABYSS_NONE);

      g_object_unref (buffer);
724 725 726 727
    }
  else
    {
      for (this_frame_num=0; this_frame_num<total_frames; this_frame_num++)
728 729 730 731 732
        {
          /*
           * BUILD THIS FRAME into our 'this_frame' buffer.
           */

733 734
          GimpDrawable *drawable =
            GIMP_DRAWABLE (layers[total_frames-(this_frame_num+1)]);
735 736 737

          /* Image has been closed/etc since we got the layer list? */
          /* FIXME - How do we tell if a gimp_drawable_get() fails? */
738
          if (gimp_drawable_width (drawable) == 0)
739 740 741 742 743 744 745 746 747 748 749 750 751 752
            {
              gimp_quit ();
            }

          this_delay = get_frame_duration (this_frame_num);
          dispose    = get_frame_disposal (this_frame_num);

          for (row = 0; row < height; row++)
            {
              compose_row (this_frame_num,
                           dispose,
                           row,
                           &this_frame[pixelstep*width * row],
                           width,
753
                           drawable,
754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864
                           FALSE
                           );
            }

          if (opmode == OPFOREGROUND)
            {
              gint xit, yit, byteit;

              for (yit=0; yit<height; yit++)
                {
                  for (xit=0; xit<width; xit++)
                    {
                      for (byteit=0; byteit<pixelstep-1; byteit++)
                        {
                          if (back_frame[yit*width*pixelstep + xit*pixelstep
                                        + byteit]
                              !=
                              this_frame[yit*width*pixelstep + xit*pixelstep
                                        + byteit])
                            {
                              goto enough;
                            }
                        }
                      this_frame[yit*width*pixelstep + xit*pixelstep
                                + pixelstep - 1] = 0;
                    enough:
                      /* nop */;
                    }
                }
            }

          can_combine = FALSE;
          bbox_left   = 0;
          bbox_top    = 0;
          bbox_right  = width;
          bbox_bottom = height;
          rbox_left   = 0;
          rbox_top    = 0;
          rbox_right  = width;
          rbox_bottom = height;

          /* copy 'this' frame into a buffer which we can safely molest */
          memcpy (opti_frame, this_frame, frame_sizebytes);
          /*
           *
           * OPTIMIZE HERE!
           *
           */
          if (
              (this_frame_num != 0) /* Can't delta bottom frame! */
              && (opmode == OPOPTIMIZE)
              )
            {
              gint xit, yit, byteit;

              can_combine = TRUE;

              /*
               * SEARCH FOR BOUNDING BOX
               */
              bbox_left   = width;
              bbox_top    = height;
              bbox_right  = 0;
              bbox_bottom = 0;
              rbox_left   = width;
              rbox_top    = height;
              rbox_right  = 0;
              rbox_bottom = 0;

              for (yit=0; yit<height; yit++)
                {
                  for (xit=0; xit<width; xit++)
                    {
                      gboolean keep_pix;
                      gboolean opaq_pix;

                      /* Check if 'this' and 'last' are transparent */
                      if (!(this_frame[yit*width*pixelstep + xit*pixelstep
                                      + pixelstep-1]&128)
                          &&
                          !(last_frame[yit*width*pixelstep + xit*pixelstep
                                      + pixelstep-1]&128))
                        {
                          keep_pix = FALSE;
                          opaq_pix = FALSE;
                          goto decided;
                        }
                      /* Check if just 'this' is transparent */
                      if ((last_frame[yit*width*pixelstep + xit*pixelstep
                                     + pixelstep-1]&128)
                          &&
                          !(this_frame[yit*width*pixelstep + xit*pixelstep
                                      + pixelstep-1]&128))
                        {
                          keep_pix = TRUE;
                          opaq_pix = FALSE;
                          can_combine = FALSE;
                          goto decided;
                        }
                      /* Check if just 'last' is transparent */
                      if (!(last_frame[yit*width*pixelstep + xit*pixelstep
                                      + pixelstep-1]&128)
                          &&
                          (this_frame[yit*width*pixelstep + xit*pixelstep
                                     + pixelstep-1]&128))
                        {
                          keep_pix = TRUE;
                          opaq_pix = TRUE;
                          goto decided;
                        }
                      /* If 'last' and 'this' are opaque, we have
865
                       *  to check if they're the same color - we
866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 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 926 927 928 929 930 931 932 933 934 935 936 937 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 1001 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
                       *  only have to keep the pixel if 'last' or
                       *  'this' are opaque and different.
                       */
                      keep_pix = FALSE;
                      opaq_pix = TRUE;
                      for (byteit=0; byteit<pixelstep-1; byteit++)
                        {
                          if ((last_frame[yit*width*pixelstep + xit*pixelstep
                                         + byteit]
                               !=
                               this_frame[yit*width*pixelstep + xit*pixelstep
                                         + byteit])
                              )
                            {
                              keep_pix = TRUE;
                              goto decided;
                            }
                        }
                    decided:
                      if (opaq_pix)
                        {
                          if (xit<rbox_left) rbox_left=xit;
                          if (xit>rbox_right) rbox_right=xit;
                          if (yit<rbox_top) rbox_top=yit;
                          if (yit>rbox_bottom) rbox_bottom=yit;
                        }
                      if (keep_pix)
                        {
                          if (xit<bbox_left) bbox_left=xit;
                          if (xit>bbox_right) bbox_right=xit;
                          if (yit<bbox_top) bbox_top=yit;
                          if (yit>bbox_bottom) bbox_bottom=yit;
                        }
                      else
                        {
                          /* pixel didn't change this frame - make
                           *  it transparent in our optimized buffer!
                           */
                          opti_frame[yit*width*pixelstep + xit*pixelstep
                                    + pixelstep-1] = 0;
                        }
                    } /* xit */
                } /* yit */

              if (!can_combine)
                {
                  bbox_left = rbox_left;
                  bbox_top = rbox_top;
                  bbox_right = rbox_right;
                  bbox_bottom = rbox_bottom;
                }

              bbox_right++;
              bbox_bottom++;

              if (can_combine && !diff_only)
                {
                  /* Try to optimize the pixel data for RLE or LZW compression
                   * by making some transparent pixels non-transparent if they
                   * would have the same color as the adjacent pixels.  This
                   * gives a better compression if the algorithm compresses
                   * the image line by line.
                   * See: http://bugzilla.gnome.org/show_bug.cgi?id=66367
                   * It may not be very efficient to add two additional passes
                   * over the pixels, but this hopefully makes the code easier
                   * to maintain and less error-prone.
                   */
                  for (yit = bbox_top; yit < bbox_bottom; yit++)
                    {
                      /* Compare with previous pixels from left to right */
                      for (xit = bbox_left + 1; xit < bbox_right; xit++)
                        {
                          if (!(opti_frame[yit*width*pixelstep
                                           + xit*pixelstep
                                           + pixelstep-1]&128)
                              && (opti_frame[yit*width*pixelstep
                                             + (xit-1)*pixelstep
                                             + pixelstep-1]&128)
                              && (last_frame[yit*width*pixelstep
                                             + xit*pixelstep
                                             + pixelstep-1]&128))
                            {
                              for (byteit=0; byteit<pixelstep-1; byteit++)
                                {
                                  if (opti_frame[yit*width*pixelstep
                                                 + (xit-1)*pixelstep
                                                 + byteit]
                                      !=
                                      last_frame[yit*width*pixelstep
                                                 + xit*pixelstep
                                                 + byteit])
                                    {
                                      goto skip_right;
                                    }
                                }
                              /* copy the color and alpha */
                              for (byteit=0; byteit<pixelstep; byteit++)
                                {
                                  opti_frame[yit*width*pixelstep
                                             + xit*pixelstep
                                             + byteit]
                                    = last_frame[yit*width*pixelstep
                                                 + xit*pixelstep
                                                 + byteit];
                                }
                            }
                        skip_right:
                          /* nop */;
                        } /* xit */

                      /* Compare with next pixels from right to left */
                      for (xit = bbox_right - 2; xit >= bbox_left; xit--)
                        {
                          if (!(opti_frame[yit*width*pixelstep
                                           + xit*pixelstep
                                           + pixelstep-1]&128)
                              && (opti_frame[yit*width*pixelstep
                                             + (xit+1)*pixelstep
                                             + pixelstep-1]&128)
                              && (last_frame[yit*width*pixelstep
                                             + xit*pixelstep
                                             + pixelstep-1]&128))
                            {
                              for (byteit=0; byteit<pixelstep-1; byteit++)
                                {
                                  if (opti_frame[yit*width*pixelstep
                                                 + (xit+1)*pixelstep
                                                 + byteit]
                                      !=
                                      last_frame[yit*width*pixelstep
                                                 + xit*pixelstep
                                                 + byteit])
                                    {
                                      goto skip_left;
                                    }
                                }
                              /* copy the color and alpha */
                              for (byteit=0; byteit<pixelstep; byteit++)
                                {
                                  opti_frame[yit*width*pixelstep
                                             + xit*pixelstep
                                             + byteit]
                                    = last_frame[yit*width*pixelstep
                                                 + xit*pixelstep
                                                 + byteit];
                                }
                            }
                        skip_left:
                          /* nop */;
                        } /* xit */
                    } /* yit */
                }

              /*
               * Collapse opti_frame data down such that the data
               *  which occupies the bounding box sits at the start
               *  of the data (for convenience with ..set_rect()).
               */
              destptr = opti_frame;
              /*
               * If can_combine, then it's safe to use our optimized
               *  alpha information.  Otherwise, an opaque pixel became
               *  transparent this frame, and we'll have to use the
               *  actual true frame's alpha.
               */
              if (can_combine)
                srcptr = opti_frame;
              else
                srcptr = this_frame;
              for (yit=bbox_top; yit<bbox_bottom; yit++)
                {
                  for (xit=bbox_left; xit<bbox_right; xit++)
                    {
                      for (byteit=0; byteit<pixelstep; byteit++)
                        {
                          *(destptr++) = srcptr[yit*pixelstep*width +
                                               pixelstep*xit + byteit];
                        }
                    }
                }
            } /* !bot frame? */
          else
            {
              memcpy (opti_frame, this_frame, frame_sizebytes);
            }

          /*
           *
           * REMEMBER THE ANIMATION STATUS TO DELTA AGAINST NEXT TIME
           *
           */
          memcpy (last_frame, this_frame, frame_sizebytes);


          /*
           *
           * PUT THIS FRAME INTO A NEW LAYER IN THE NEW IMAGE
           *
           */

          oldlayer_name =
1067
            gimp_item_get_name (GIMP_ITEM (layers[total_frames-(this_frame_num+1)]));
1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094

          buflen = strlen(oldlayer_name) + 40;

          newlayer_name = g_malloc(buflen);

          remove_disposal_tag(newlayer_name, oldlayer_name);
          g_free(oldlayer_name);

          oldlayer_name = g_malloc(buflen);

          remove_ms_tag(oldlayer_name, newlayer_name);

          g_snprintf(newlayer_name, buflen, "%s(%dms)%s",
                     oldlayer_name, this_delay,
                     (this_frame_num ==  0) ? "" :
                     can_combine ? "(combine)" : "(replace)");

          g_free(oldlayer_name);

          /* Empty frame! */
          if (bbox_right <= bbox_left ||
              bbox_bottom <= bbox_top)
            {
              cumulated_delay += this_delay;

              g_free (newlayer_name);

1095
              oldlayer_name = gimp_item_get_name (GIMP_ITEM (last_true_frame));
1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108

              buflen = strlen (oldlayer_name) + 40;

              newlayer_name = g_malloc (buflen);

              remove_disposal_tag (newlayer_name, oldlayer_name);
              g_free (oldlayer_name);

              oldlayer_name = g_malloc (buflen);

              remove_ms_tag (oldlayer_name, newlayer_name);

              g_snprintf (newlayer_name, buflen, "%s(%dms)%s",
1109 1110 1111
                          oldlayer_name, cumulated_delay,
                          (this_frame_num ==  0) ? "" :
                          can_combine ? "(combine)" : "(replace)");
1112

1113
              gimp_item_set_name (GIMP_ITEM (last_true_frame), newlayer_name);
1114

1115 1116 1117 1118
              g_free (newlayer_name);
            }
          else
            {
1119 1120 1121
              GeglBuffer *buffer;
              const Babl *format;

1122
              cumulated_delay = this_delay;
1123

1124
              last_true_frame =
1125 1126 1127 1128 1129 1130 1131
                new_layer = gimp_layer_new (new_image,
                                            newlayer_name,
                                            bbox_right-bbox_left,
                                            bbox_bottom-bbox_top,
                                            drawabletype_alpha,
                                            100.0,
                                            gimp_image_get_default_new_layer_mode (new_image));
1132 1133
              g_free (newlayer_name);

1134
              gimp_image_insert_layer (new_image, new_layer, NULL, 0);
1135

1136
              buffer = gimp_drawable_get_buffer (GIMP_DRAWABLE (new_layer));
1137

1138
              format = get_format (GIMP_DRAWABLE (new_layer));
1139 1140 1141 1142 1143 1144 1145 1146 1147

              gegl_buffer_set (buffer,
                               GEGL_RECTANGLE (0, 0,
                                               bbox_right-bbox_left,
                                               bbox_bottom-bbox_top), 0,
                               format, opti_frame,
                               GEGL_AUTO_ROWSTRIDE);

              g_object_unref (buffer);
1148
              gimp_item_transform_translate (GIMP_ITEM (new_layer), bbox_left, bbox_top);
1149 1150 1151 1152 1153
            }

          gimp_progress_update (((gdouble) this_frame_num + 1.0) /
                                ((gdouble) total_frames));
        }
1154

1155
      gimp_progress_update (1.0);
Manish Singh's avatar
Manish Singh committed
1156
    }
1157

1158
  gimp_image_undo_enable (new_image);
1159

1160
  if (run_mode != GIMP_RUN_NONINTERACTIVE)
1161
    gimp_display_new (new_image);
Manish Singh's avatar
Manish Singh committed
1162

1163
  g_free (rawframe);
Manish Singh's avatar
Manish Singh committed
1164
  rawframe = NULL;
1165 1166

  g_free (last_frame);
Manish Singh's avatar
Manish Singh committed
1167
  last_frame = NULL;
1168 1169

  g_free (this_frame);
Manish Singh's avatar
Manish Singh committed
1170
  this_frame = NULL;
1171 1172

  g_free (opti_frame);
Manish Singh's avatar
Manish Singh committed
1173
  opti_frame = NULL;
1174 1175 1176

  g_free (back_frame);
  back_frame = NULL;
1177

1178
  return new_image;
Manish Singh's avatar
Manish Singh committed
1179 1180 1181 1182 1183
}

/* Util. */

static DisposeType
1184
get_frame_disposal (guint whichframe)
Manish Singh's avatar
Manish Singh committed
1185
{
1186 1187
  gchar       *layer_name;
  DisposeType  disposal;
1188

1189 1190 1191
  layer_name = gimp_item_get_name (GIMP_ITEM (layers[total_frames-(whichframe+1)]));
  disposal = parse_disposal_tag (layer_name);
  g_free (layer_name);
Manish Singh's avatar
Manish Singh committed
1192

1193
  return disposal;
Manish Singh's avatar
Manish Singh committed
1194 1195
}

1196
static guint32
1197
get_frame_duration (guint whichframe)
1198 1199 1200 1201
{
  gchar* layer_name;
  gint   duration = 0;

1202
  layer_name = gimp_item_get_name (GIMP_ITEM (layers[total_frames-(whichframe+1)]));
1203
  if (layer_name)
1204
    {
1205 1206
      duration = parse_ms_tag (layer_name);
      g_free (layer_name);
1207
    }
1208

Adam D. Moss's avatar
Adam D. Moss committed
1209 1210
  if (duration < 0) duration = 100;  /* FIXME for default-if-not-said  */
  if (duration == 0) duration = 100; /* FIXME - 0-wait is nasty */
1211

1212
  return (guint32) duration;
1213 1214
}

1215 1216 1217 1218
static gboolean
is_ms_tag (const gchar *str,
           gint        *duration,
           gint        *taglength)
1219 1220 1221 1222 1223 1224 1225 1226
{
  gint sum = 0;
  gint offset;
  gint length;

  length = strlen(str);

  if (str[0] != '(')
1227
    return FALSE;
1228 1229 1230 1231 1232 1233

  offset = 1;

  /* eat any spaces between open-parenthesis and number */
  while ((offset<length) && (str[offset] == ' '))
    offset++;
1234

1235
  if ((offset>=length) || (!g_ascii_isdigit (str[offset])))
1236 1237 1238 1239 1240 1241 1242 1243
    return 0;

  do
    {
      sum *= 10;
      sum += str[offset] - '0';
      offset++;
    }
1244
  while ((offset<length) && (g_ascii_isdigit (str[offset])));
1245 1246

  if (length-offset <= 2)
1247
    return FALSE;
1248 1249 1250 1251 1252 1253

  /* eat any spaces between number and 'ms' */
  while ((offset<length) && (str[offset] == ' '))
    offset++;

  if ((length-offset <= 2) ||
1254 1255
      (g_ascii_toupper (str[offset]) != 'M') ||
      (g_ascii_toupper (str[offset+1]) != 'S'))
1256
    return FALSE;
1257 1258 1259 1260 1261 1262 1263 1264

  offset += 2;

  /* eat any spaces between 'ms' and close-parenthesis */
  while ((offset<length) && (str[offset] == ' '))
    offset++;

  if ((length-offset < 1) || (str[offset] != ')'))
1265
    return FALSE;
1266 1267

  offset++;
1268

1269
  *duration  = sum;
1270 1271
  *taglength = offset;

1272
  return TRUE;
1273 1274 1275 1276 1277
}

static int
parse_ms_tag (const char *str)
{
1278 1279 1280 1281
  gint i;
  gint rtn;
  gint dummy;
  gint length;
1282

1283
  length = strlen (str);
1284