Commit 6702018ba for imagemagick.org

commit 6702018bab302cda406000735d95ee08ddc0a561
Author: Cristy <urban-warrior@imagemagick.org>
Date:   Fri Dec 4 19:01:09 2026 -0500

    every ReadASEImage error path now goes through one cleanup macro

diff --git a/coders/ase.c b/coders/ase.c
index 86e404b51..629d773b0 100644
--- a/coders/ase.c
+++ b/coders/ase.c
@@ -45,6 +45,8 @@
 #include "MagickCore/blob-private.h"
 #include "MagickCore/cache.h"
 #include "MagickCore/colormap.h"
+#include "MagickCore/colorspace.h"
+#include "MagickCore/colorspace-private.h"
 #include "MagickCore/exception.h"
 #include "MagickCore/exception-private.h"
 #include "MagickCore/image.h"
@@ -408,8 +410,8 @@ static MagickBooleanType ReadASELayerChunk(const Image *image,
   AsepriteLayer
     *layer;

-  if (payload_size < 18)
-    return(MagickTrue);
+  if (layers->count >= 65536)
+    return(MagickTrue);  /* cels address layers with a 16-bit index */
   if (layers->count == layers->capacity)
     {
       size_t
@@ -439,9 +441,19 @@ static MagickBooleanType ReadASELayerChunk(const Image *image,
       layers->capacity=new_capacity;
     }
   layer=layers->layers+layers->count;
-  layer->visible=((chunk_data[0] & 0x01) != 0) ? MagickTrue : MagickFalse;
-  layer->blend_mode=(uint16_t) (chunk_data[10] | (chunk_data[11] << 8));
-  layer->opacity=(opacity_is_valid != MagickFalse) ? chunk_data[12] : 255;
+  layer->visible=MagickTrue;
+  layer->blend_mode=0;
+  layer->opacity=255;
+  if (payload_size >= 18)
+    {
+      layer->visible=((chunk_data[0] & 0x01) != 0) ? MagickTrue : MagickFalse;
+      layer->blend_mode=(uint16_t) (chunk_data[10] | (chunk_data[11] << 8));
+      layer->opacity=(opacity_is_valid != MagickFalse) ? chunk_data[12] : 255;
+    }
+  /*
+    A short layer chunk still occupies a layer index; appending a default
+    entry keeps later layers aligned with the indices cels refer to.
+  */
   layers->count++;
   return(MagickTrue);
 }
@@ -671,9 +683,12 @@ static MagickBooleanType ReadASECelChunk(const Image *image,
   if ((visible != MagickFalse) && (layer_index < layers->count) &&
       (layers->layers[layer_index].blend_mode != 0))
     {
+      /*
+        Only "normal" blending is implemented; degrade gracefully instead of
+        rejecting the whole sprite because one layer uses another mode.
+      */
       (void) ThrowMagickException(exception,GetMagickModule(),
-        CoderError,"UnsupportedBlendMode","`%s'",image->filename);
-      return(MagickFalse);
+        CoderWarning,"UnsupportedBlendMode","`%s'",image->filename);
     }
   if (cel_type == 1)
     {
@@ -800,6 +815,29 @@ static MagickBooleanType ReadASECelChunk(const Image *image,

 static Image *ReadASEImage(const ImageInfo *image_info,ExceptionInfo *exception)
 {
+/*
+  Release every resource this reader may own, so that no error path leaks
+  heap memory or MemoryResource accounting (which would otherwise make a
+  long-running process progressively refuse to read images).
+*/
+#define CleanupASEReader() \
+{ \
+  if (chunk_data != (uint8_t *) NULL) \
+    chunk_data=(uint8_t *) RelinquishMagickMemory(chunk_data); \
+  if (pixel_data != (uint8_t *) NULL) \
+    { \
+      pixel_data=(uint8_t *) RelinquishMagickMemory(pixel_data); \
+      RelinquishMagickResource(MemoryResource,(MagickSizeType) pixels_size); \
+    } \
+  DestroyASELayerList(&layers); \
+  DestroyASECelCache(&cel_cache); \
+}
+#define ThrowASEReaderException(severity,tag) \
+{ \
+  CleanupASEReader(); \
+  ThrowReaderException(severity,tag); \
+}
+
   AsepriteCanvas
     canvas;

@@ -829,6 +867,7 @@ static Image *ReadASEImage(const ImageInfo *image_info,ExceptionInfo *exception)
     *q;

   size_t
+    chunk_count,
     chunk_idx,
     count,
     frame_idx,
@@ -863,6 +902,9 @@ static Image *ReadASEImage(const ImageInfo *image_info,ExceptionInfo *exception)
   cel_cache.count=0;
   cel_cache.capacity=0;
   cel_cache.index_capacity=0;
+  chunk_data=(uint8_t *) NULL;
+  pixel_data=(uint8_t *) NULL;
+  pixels_size=0;
   image=AcquireImage(image_info,exception);
   status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
   if (status == MagickFalse)
@@ -883,10 +925,15 @@ static Image *ReadASEImage(const ImageInfo *image_info,ExceptionInfo *exception)
   ase_header.ignore1=(uint8_t) ReadBlobByte(image);
   ase_header.ignore2=(uint8_t) ReadBlobByte(image);
   ase_header.ignore3=(uint8_t) ReadBlobByte(image);
+  /*
+    Bytes 32..35: number of colors (WORD), pixel width and height (BYTEs).
+  */
   ase_header.pixel_width=ReadBlobLSBShort(image);
   ase_header.pixel_height=ReadBlobLSBShort(image);
-  (void) SeekBlob(image,92,SEEK_CUR);
-  if ((GetBlobSize(image) != 0) &&
+  (void) SeekBlob(image,92,SEEK_CUR);  /* grid x/y/width/height + reserved */
+  if (EOFBlob(image) != MagickFalse)
+    ThrowReaderException(CorruptImageError,"ImproperImageHeader");
+  if ((GetBlobSize(image) != 0) &&
       ((MagickSizeType) ase_header.file_size > GetBlobSize(image)))
     ThrowReaderException(CorruptImageError,"FileSizeTooLarge");
   if ((ase_header.width == 0) || (ase_header.height == 0))
@@ -911,14 +958,16 @@ static Image *ReadASEImage(const ImageInfo *image_info,ExceptionInfo *exception)
   if (ase_header.color_depth == 8)
     {
       if (AcquireImageColormap(image,256,exception) == MagickFalse)
-        {
-          DestroyASELayerList(&layers);
-          DestroyASECelCache(&cel_cache);
-          ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
-        }
+        ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
     }
   if (AcquireMagickResource(ListLengthResource,ase_header.frames) == MagickFalse)
     ThrowReaderException(ResourceLimitError,"ListLengthExceedsLimit");
+  switch (ase_header.color_depth)
+  {
+    case 32: pixels_size=(size_t) ase_header.width*ase_header.height*4; break;
+    case 16: pixels_size=(size_t) ase_header.width*ase_header.height*2; break;
+    default: pixels_size=(size_t) ase_header.width*ase_header.height; break;
+  }
   frame_image=image;
   for (frame_idx=0; frame_idx < (size_t) ase_header.frames; frame_idx++)
   {
@@ -927,8 +976,7 @@ static Image *ReadASEImage(const ImageInfo *image_info,ExceptionInfo *exception)
         AcquireNextImage(image_info,frame_image,exception);
         if (GetNextImageInList(frame_image) == (Image *) NULL)
           {
-            DestroyASELayerList(&layers);
-            DestroyASECelCache(&cel_cache);
+            CleanupASEReader();
             return(DestroyImageList(image));
           }
         frame_image=SyncNextImageInList(frame_image);
@@ -941,74 +989,54 @@ static Image *ReadASEImage(const ImageInfo *image_info,ExceptionInfo *exception)
           {
             if (AcquireImageColormap(frame_image,256,exception) ==
                 MagickFalse)
-              {
-                DestroyASELayerList(&layers);
-                DestroyASECelCache(&cel_cache);
-                ThrowReaderException(ResourceLimitError,
-                  "MemoryAllocationFailed");
-              }
+              ThrowASEReaderException(ResourceLimitError,
+                "MemoryAllocationFailed");
             (void) memcpy(frame_image->colormap,
               frame_image->previous->colormap,256*
               sizeof(*frame_image->colormap));
+            frame_image->colors=frame_image->previous->colors;
           }
       }
     ase_frame.frame_size=ReadBlobLSBLong(image);
     ase_frame.frame_magic=ReadBlobLSBShort(image);
-    if (ase_frame.frame_magic != ASE_FRAME_MAGIC)
-      {
-        DestroyASELayerList(&layers);
-        DestroyASECelCache(&cel_cache);
-        ThrowReaderException(CorruptImageError,"InvalidFrameHeader");
-      }
+    if ((ase_frame.frame_magic != ASE_FRAME_MAGIC) ||
+        (ase_frame.frame_size < 16))
+      ThrowASEReaderException(CorruptImageError,"InvalidFrameHeader");
     ase_frame.chunk_count=ReadBlobLSBShort(image);
     ase_frame.duration=ReadBlobLSBShort(image);
     ase_frame.padding1=(uint8_t) ReadBlobByte(image);
     ase_frame.padding2=(uint8_t) ReadBlobByte(image);
-    ase_frame.next_frame=ReadBlobLSBLong(image);
+    ase_frame.next_frame=ReadBlobLSBLong(image);  /* new chunk count */
+    /*
+      The 16-bit chunk count saturates at 0xFFFF; when the 32-bit field is
+      non-zero it is authoritative.
+    */
+    chunk_count=ase_frame.chunk_count;
+    if (ase_frame.next_frame != 0)
+      chunk_count=ase_frame.next_frame;
     if (ase_frame.duration > 0)
       frame_image->delay=ase_frame.duration;
     if (image_info->ping != MagickFalse)
       {
-        (void) SeekBlob(image,(MagickOffsetType) ase_frame.frame_size-16,
-          SEEK_CUR);
+        if (SeekBlob(image,(MagickOffsetType) ase_frame.frame_size-16,
+            SEEK_CUR) < 0)
+          ThrowASEReaderException(CorruptImageError,"InvalidFrameHeader");
         continue;
       }
     status=SetImageExtent(frame_image,frame_image->columns,
       frame_image->rows,exception);
     if (status == MagickFalse)
       {
-        DestroyASELayerList(&layers);
-        DestroyASECelCache(&cel_cache);
+        CleanupASEReader();
         return(DestroyImageList(image));
       }
-    switch (ase_header.color_depth)
-    {
-      case 32:
-        pixels_size=(size_t) ase_header.width*ase_header.height*4;
-        break;
-      case 16:
-        pixels_size=(size_t) ase_header.width*ase_header.height*2;
-        break;
-      case 8:
-        pixels_size=(size_t) ase_header.width*ase_header.height;
-        break;
-      default:
-        pixels_size=0;
-        break;
-    }
     if (AcquireMagickResource(MemoryResource,(MagickSizeType) pixels_size) == MagickFalse)
-      {
-        DestroyASELayerList(&layers);
-        DestroyASECelCache(&cel_cache);
-        ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
-      }
+      ThrowASEReaderException(ResourceLimitError,"MemoryAllocationFailed");
     pixel_data=(uint8_t *) AcquireQuantumMemory(pixels_size,sizeof(uint8_t));
     if (pixel_data == (uint8_t *) NULL)
       {
         RelinquishMagickResource(MemoryResource,(MagickSizeType) pixels_size);
-        DestroyASELayerList(&layers);
-        DestroyASECelCache(&cel_cache);
-        ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
+        ThrowASEReaderException(ResourceLimitError,"MemoryAllocationFailed");
       }
     if (ase_header.color_depth == 8)
       (void) memset(pixel_data,ase_header.palette_index,pixels_size);
@@ -1019,59 +1047,42 @@ static Image *ReadASEImage(const ImageInfo *image_info,ExceptionInfo *exception)
     canvas.height=ase_header.height;
     canvas.color_depth=ase_header.color_depth;
     canvas.transparent_index=ase_header.palette_index;
-    for (chunk_idx=0; chunk_idx < (size_t) ase_frame.chunk_count; chunk_idx++)
+    for (chunk_idx=0; chunk_idx < chunk_count; chunk_idx++)
     {
       size_t
         payload_size;

       ase_chunk.chunk_size=ReadBlobLSBLong(image);
       ase_chunk.chunk_type=ReadBlobLSBShort(image);
-      if ((ase_chunk.chunk_size < 6) || (ase_chunk.chunk_size > 100*1024*1024))
-        {
-          pixel_data=(uint8_t *) RelinquishMagickMemory(pixel_data);
-          DestroyASELayerList(&layers);
-          DestroyASECelCache(&cel_cache);
-          ThrowReaderException(CorruptImageError,"InvalidChunkSize");
-        }
+      if ((EOFBlob(image) != MagickFalse) || (ase_chunk.chunk_size < 6) ||
+          (ase_chunk.chunk_size > 100*1024*1024))
+        ThrowASEReaderException(CorruptImageError,"InvalidChunkSize");
       payload_size=ase_chunk.chunk_size-6;
+      if (payload_size == 0)
+        continue;
+      if ((GetBlobSize(image) != 0) && ((MagickSizeType) payload_size >
+          (GetBlobSize(image)-(MagickSizeType) TellBlob(image))))
+        ThrowASEReaderException(CorruptImageError,"InvalidChunkSize");
       chunk_data=(uint8_t *) AcquireQuantumMemory(payload_size,
         sizeof(uint8_t));
       if (chunk_data == (uint8_t *) NULL)
-        {
-          pixel_data=(uint8_t *) RelinquishMagickMemory(pixel_data);
-          DestroyASELayerList(&layers);
-          DestroyASECelCache(&cel_cache);
-          ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
-        }
-      count=ReadBlob(image,payload_size,chunk_data);
+        ThrowASEReaderException(ResourceLimitError,"MemoryAllocationFailed");
+      count=(size_t) ReadBlob(image,payload_size,chunk_data);
       if (count != payload_size)
-        {
-          chunk_data=(uint8_t *) RelinquishMagickMemory(chunk_data);
-          pixel_data=(uint8_t *) RelinquishMagickMemory(pixel_data);
-          DestroyASELayerList(&layers);
-          DestroyASECelCache(&cel_cache);
-          ThrowReaderException(CorruptImageError,"UnableToReadImageData");
-        }
+        ThrowASEReaderException(CorruptImageError,"UnableToReadImageData");
       switch (ase_chunk.chunk_type)
       {
-        /* CEL chunk (0x2005): composite the raw or compressed cel image
+        /* CEL chunk (0x2005): composite the raw or compressed cel image
            payload onto the frame canvas. */
         case 0x2005:
         {
-          MagickBooleanType
-            cel_status;
-
-          cel_status=ReadASECelChunk(image,chunk_data,payload_size,&canvas,
-            &layers,frame_idx,&cel_cache,exception);
-          chunk_data=(uint8_t *) RelinquishMagickMemory(chunk_data);
-          if (cel_status == MagickFalse)
+          if (ReadASECelChunk(image,chunk_data,payload_size,&canvas,
+              &layers,frame_idx,&cel_cache,exception) == MagickFalse)
             {
-              pixel_data=(uint8_t *) RelinquishMagickMemory(pixel_data);
-              DestroyASELayerList(&layers);
-              DestroyASECelCache(&cel_cache);
+              CleanupASEReader();
               return(DestroyImageList(image));
             }
-          continue;
+          break;
         }
         /* New palette chunk: populate the RGBA color table. */
         case 0x2019:
@@ -1080,7 +1091,7 @@ static Image *ReadASEImage(const ImageInfo *image_info,ExceptionInfo *exception)
             ReadASEPaletteChunk(frame_image,chunk_data,payload_size);
           break;
         }
-        /* Layer chunk: track visibility/blend mode/opacity for later cel
+        /* Layer chunk: track visibility/blend mode/opacity for later cel
            compositing. */
         case 0x2004:
         {
@@ -1088,10 +1099,7 @@ static Image *ReadASEImage(const ImageInfo *image_info,ExceptionInfo *exception)
               (ase_header.flags & 0x01) != 0 ? MagickTrue : MagickFalse,
               &layers,exception) == MagickFalse)
             {
-              chunk_data=(uint8_t *) RelinquishMagickMemory(chunk_data);
-              pixel_data=(uint8_t *) RelinquishMagickMemory(pixel_data);
-              DestroyASELayerList(&layers);
-              DestroyASECelCache(&cel_cache);
+              CleanupASEReader();
               return(DestroyImageList(image));
             }
           break;
@@ -1160,7 +1168,7 @@ static Image *ReadASEImage(const ImageInfo *image_info,ExceptionInfo *exception)
         }
         break;
       }
-      case 8:
+      default:
       {
         unsigned char
           *p;
@@ -1173,12 +1181,14 @@ static Image *ReadASEImage(const ImageInfo *image_info,ExceptionInfo *exception)
             break;
           for (x=0; x < (ssize_t) frame_image->columns; x++)
           {
-            ssize_t index = (ssize_t) *p;
+            ssize_t
+              index;
+
+            index=(ssize_t) *p++;
             if (index >= (ssize_t) frame_image->colors)
               index=0;
             SetPixelIndex(frame_image,(Quantum) index,q);
             SetPixelViaPixelInfo(frame_image,frame_image->colormap+index,q);
-            p++;
             q+=GetPixelChannels(frame_image);
           }
           if (SyncAuthenticPixels(frame_image,exception) == MagickFalse)
@@ -1191,9 +1201,10 @@ static Image *ReadASEImage(const ImageInfo *image_info,ExceptionInfo *exception)
     }
     RelinquishMagickResource(MemoryResource,(MagickSizeType) pixels_size);
     pixel_data=(uint8_t *) RelinquishMagickMemory(pixel_data);
+    if (y < (ssize_t) frame_image->rows)
+      ThrowASEReaderException(CorruptImageError,"UnableToReadImageData");
   }
-  DestroyASELayerList(&layers);
-  DestroyASECelCache(&cel_cache);
+  CleanupASEReader();
   if (EOFBlob(image) != MagickFalse)
     ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
       image->filename);
@@ -1301,15 +1312,76 @@ ModuleExport void UnregisterASEImage(void)
 %    o exception: return any errors or warnings in this structure.
 %
 */
+static MagickBooleanType IsASEColormapShared(const Image *image)
+{
+  const Image
+    *next;
+
+  /*
+    Indexed output carries a single palette, so every frame must be
+    PseudoClass with the same colormap as the first frame.
+  */
+  if ((image->storage_class != PseudoClass) || (image->colors == 0) ||
+      (image->colors > 256) || (image->colormap == (PixelInfo *) NULL))
+    return(MagickFalse);
+  for (next=image->next; next != (Image *) NULL; next=next->next)
+  {
+    size_t
+      i;
+
+    if ((next->storage_class != PseudoClass) ||
+        (next->colors != image->colors) ||
+        (next->colormap == (PixelInfo *) NULL))
+      return(MagickFalse);
+    for (i=0; i < image->colors; i++)
+      if ((next->colormap[i].red != image->colormap[i].red) ||
+          (next->colormap[i].green != image->colormap[i].green) ||
+          (next->colormap[i].blue != image->colormap[i].blue) ||
+          (next->colormap[i].alpha != image->colormap[i].alpha))
+        return(MagickFalse);
+  }
+  return(MagickTrue);
+}
+
+static unsigned short ASEDelay(const Image *image)
+{
+  double
+    delay_ms;
+
+  size_t
+    ticks_per_second;
+
+  ticks_per_second=(image->ticks_per_second > 0) ?
+    (size_t) image->ticks_per_second : 100;
+  delay_ms=((double) image->delay*1000.0)/(double) ticks_per_second+0.5;
+  if (delay_ms > 65535.0)
+    delay_ms=65535.0;
+  return((unsigned short) delay_ms);
+}
+
+static void WriteASECelHeader(Image *image,const size_t chunk_size,
+  const unsigned short cel_type,const size_t cel_width,
+  const size_t cel_height)
+{
+  (void) WriteBlobLSBLong(image,(unsigned int) chunk_size);
+  (void) WriteBlobLSBShort(image,0x2005);
+  (void) WriteBlobLSBShort(image,0);         /* layer index */
+  (void) WriteBlobLSBShort(image,0);         /* x */
+  (void) WriteBlobLSBShort(image,0);         /* y */
+  (void) WriteBlobByte(image,255);           /* opacity */
+  (void) WriteBlobLSBShort(image,cel_type);  /* 0 = raw, 2 = compressed */
+  (void) WriteBlobLSBShort(image,0);         /* z-index */
+  (void) WriteBlobPadding(image,5,'\0');     /* reserved */
+  (void) WriteBlobLSBShort(image,(unsigned short) cel_width);
+  (void) WriteBlobLSBShort(image,(unsigned short) cel_height);
+}
+
 static MagickBooleanType WriteASEImage(const ImageInfo *image_info,
   Image *image,ExceptionInfo *exception)
 {
   const Quantum
     *q;

-  double
-    delay_ms;
-
   Image
     *p;

@@ -1318,21 +1390,23 @@ static MagickBooleanType WriteASEImage(const ImageInfo *image_info,
     status;

   MagickOffsetType
-    chunk_count_offset,
     end_offset,
     file_size_offset,
-    frame_size_offset;
+    frame_size_offset,
+    scene;

   size_t
     bytes_per_pixel,
+    cel_height,
+    cel_size,
+    cel_width,
     chunk_count,
     color_depth,
     count,
     frame_count,
     frame_x,
     frame_y,
-    pixel_count,
-    ticks_per_second;
+    pixel_count;

   ssize_t
     i;
@@ -1353,19 +1427,31 @@ static MagickBooleanType WriteASEImage(const ImageInfo *image_info,
   status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
   if (status == MagickFalse)
     return(status);
-  frame_count=0;
-  for (p=image; p != (Image *) NULL; p=p->next)
-    frame_count++;
   /*
-    Indexed (PseudoClass) images with 256 colors or fewer are written as
-    8bpp Indexed sprites with a real Palette Chunk; everything else is
-    written as 32bpp RGBA, as before.
+    The sprite format stores canvas size, frame count and per-cel sizes in
+    16-bit fields; refuse anything that would silently truncate.
+  */
+  if ((image->columns == 0) || (image->rows == 0) ||
+      (image->columns > 65535UL) || (image->rows > 65535UL))
+    ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit");
+  frame_count=GetImageListLength(image);
+  if (frame_count > 65535UL)
+    ThrowWriterException(ImageError,"ListLengthExceedsLimit");
+  /*
+    Indexed (PseudoClass) image lists that share one colormap of 256 colors
+    or fewer are written as 8bpp Indexed sprites with a real Palette Chunk;
+    everything else is written as 32bpp RGBA.
   */
-  is_indexed=((image->storage_class == PseudoClass) &&
-    (image->colors > 0) && (image->colors <= 256)) ? MagickTrue :
-    MagickFalse;
+  is_indexed=IsASEColormapShared(image);
   color_depth=(is_indexed != MagickFalse) ? 8 : 32;
   bytes_per_pixel=color_depth/8;
+  pixel_count=image->columns*image->rows;
+  if ((pixel_count*bytes_per_pixel+26) > 0xFFFFFFFFUL)
+    ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit");
+  if (is_indexed == MagickFalse)
+    for (p=image; p != (Image *) NULL; p=p->next)
+      if (IssRGBCompatibleColorspace(p->colorspace) == MagickFalse)
+        (void) TransformImageColorspace(p,sRGBColorspace,exception);
   transparent_index=0;
   if (is_indexed != MagickFalse)
     for (i=0; i < (ssize_t) image->colors; i++)
@@ -1382,37 +1468,33 @@ static MagickBooleanType WriteASEImage(const ImageInfo *image_info,
   (void) WriteBlobLSBShort(image,(unsigned short) image->rows);
   (void) WriteBlobLSBShort(image,(unsigned short) color_depth);
   (void) WriteBlobLSBLong(image,1);  /* flags: bit 0 = layer opacity has valid value */
-  ticks_per_second=(image->ticks_per_second > 0) ? image->ticks_per_second :
-    100;
-  (void) WriteBlobLSBShort(image,(unsigned short) (((double) image->delay*1000.0)/
-    (double) ticks_per_second+0.5));
+  (void) WriteBlobLSBShort(image,ASEDelay(image));  /* deprecated speed */
   (void) WriteBlobLSBLong(image,0);
   (void) WriteBlobLSBLong(image,0);
   (void) WriteBlobByte(image,transparent_index);
   (void) WriteBlobByte(image,0);
   (void) WriteBlobByte(image,0);
   (void) WriteBlobByte(image,0);
-  (void) WriteBlobLSBShort(image,1);
-  (void) WriteBlobLSBShort(image,1);
+  (void) WriteBlobLSBShort(image,(unsigned short) (is_indexed != MagickFalse ?
+    image->colors : 0));  /* number of colors */
+  (void) WriteBlobByte(image,1);  /* pixel width */
+  (void) WriteBlobByte(image,1);  /* pixel height */
   (void) WriteBlobPadding(image,92,'\0');  /* grid x/y/width/height + reserved[84] */
-  pixel_count=image->columns*image->rows;
   pixels=(uint8_t *) AcquireQuantumMemory(pixel_count,bytes_per_pixel);
   if (pixels == (uint8_t *) NULL)
     ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
+  scene=0;
   for (p=image; p != (Image *) NULL; p=p->next)
   {
     chunk_count=0;
     frame_size_offset=TellBlob(image);
     (void) WriteBlobLSBLong(image,0);
     (void) WriteBlobLSBShort(image,ASE_FRAME_MAGIC);
-    chunk_count_offset=TellBlob(image);
-    (void) WriteBlobLSBShort(image,0);
-    ticks_per_second=(p->ticks_per_second > 0) ? p->ticks_per_second : 100;
-    delay_ms=((double) p->delay*1000.0)/(double) ticks_per_second;
-    (void) WriteBlobLSBShort(image,(unsigned short) (delay_ms+0.5));
+    (void) WriteBlobLSBShort(image,0);  /* old chunk count, patched below */
+    (void) WriteBlobLSBShort(image,ASEDelay(p));
     (void) WriteBlobByte(image,0);
     (void) WriteBlobByte(image,0);
-    (void) WriteBlobLSBLong(image,0);
+    (void) WriteBlobLSBLong(image,0);  /* new chunk count, patched below */
     if (p == image)
       {
         /*
@@ -1463,52 +1545,53 @@ static MagickBooleanType WriteASEImage(const ImageInfo *image_info,
             chunk_count++;
           }
       }
-    (void) memset(pixels,0,pixel_count*bytes_per_pixel);
-    for (frame_y=0; frame_y < p->rows; frame_y++)
+    /*
+      Each frame becomes one cel anchored at (0,0); a frame larger than the
+      canvas is clipped so the cel never exceeds the declared sprite size,
+      and the cel header always matches the bytes that follow it.
+    */
+    cel_width=MagickMin(p->columns,image->columns);
+    cel_height=MagickMin(p->rows,image->rows);
+    cel_size=cel_width*cel_height*bytes_per_pixel;
+    if (cel_size == 0)
+      {
+        pixels=(uint8_t *) RelinquishMagickMemory(pixels);
+        ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit");
+      }
+    for (frame_y=0; frame_y < cel_height; frame_y++)
     {
-      q=GetVirtualPixels(p,0,(ssize_t)frame_y,p->columns,1,exception);
+      q=GetVirtualPixels(p,0,(ssize_t) frame_y,cel_width,1,exception);
       if (q == (const Quantum *) NULL)
         break;
-      for (frame_x=0; frame_x < p->columns; frame_x++)
+      for (frame_x=0; frame_x < cel_width; frame_x++)
       {
         size_t
           offset;
-        offset=(frame_y*p->columns+frame_x)*bytes_per_pixel;
-        if (offset+bytes_per_pixel <= pixel_count*bytes_per_pixel)
+
+        offset=(frame_y*cel_width+frame_x)*bytes_per_pixel;
+        if (is_indexed != MagickFalse)
+          pixels[offset]=(uint8_t) GetPixelIndex(p,q);
+        else
           {
-            if (is_indexed != MagickFalse)
-              pixels[offset]=(uint8_t) GetPixelIndex(p,q);
-            else
-              {
-                pixels[offset]=ScaleQuantumToChar(GetPixelRed(p,q));
-                pixels[offset+1]=ScaleQuantumToChar(GetPixelGreen(p,q));
-                pixels[offset+2]=ScaleQuantumToChar(GetPixelBlue(p,q));
-                pixels[offset+3]=ScaleQuantumToChar(GetPixelAlpha(p,q));
-              }
+            pixels[offset]=ScaleQuantumToChar(GetPixelRed(p,q));
+            pixels[offset+1]=ScaleQuantumToChar(GetPixelGreen(p,q));
+            pixels[offset+2]=ScaleQuantumToChar(GetPixelBlue(p,q));
+            pixels[offset+3]=ScaleQuantumToChar(GetPixelAlpha(p,q));
           }
         q+=GetPixelChannels(p);
       }
     }
+    if (frame_y < cel_height)
+      {
+        pixels=(uint8_t *) RelinquishMagickMemory(pixels);
+        ThrowWriterException(CorruptImageError,"UnableToWriteBlob");
+      }
     if (image_info->compression == NoCompression)
       {
-        (void) WriteBlobLSBLong(image,(unsigned int) (pixel_count*bytes_per_pixel+26));
-        (void) WriteBlobLSBShort(image,0x2005);
-        (void) WriteBlobLSBShort(image,0); /* layer index */
-        (void) WriteBlobLSBShort(image,0); /* x */
-        (void) WriteBlobLSBShort(image,0); /* y */
-        (void) WriteBlobByte(image,255);   /* opacity */
-        (void) WriteBlobLSBShort(image,0);  /* raw image */
-        (void) WriteBlobLSBShort(image,0);  /* z-index */
-        (void) WriteBlobByte(image,0);
-        (void) WriteBlobByte(image,0);
-        (void) WriteBlobByte(image,0);
-        (void) WriteBlobByte(image,0);
-        (void) WriteBlobByte(image,0);
-        (void) WriteBlobLSBShort(image,(unsigned short) p->columns);
-        (void) WriteBlobLSBShort(image,(unsigned short) p->rows);
-        count=WriteBlob(image,pixel_count*bytes_per_pixel,pixels);
+        WriteASECelHeader(image,cel_size+26,0,cel_width,cel_height);
+        count=(size_t) WriteBlob(image,cel_size,pixels);
         chunk_count++;
-        if (count != pixel_count*bytes_per_pixel)
+        if (count != cel_size)
           {
             pixels=(uint8_t *) RelinquishMagickMemory(pixels);
             ThrowWriterException(FileOpenError,"UnableToWriteBlob");
@@ -1518,13 +1601,12 @@ static MagickBooleanType WriteASEImage(const ImageInfo *image_info,
 #if defined(MAGICKCORE_ZLIB_DELEGATE)
     {
       uLongf
-        compressed_size,
-        payload_size;
+        compressed_size;
+
       uint8_t
         *compressed;

-      payload_size=(uLongf) (pixel_count*bytes_per_pixel);
-      compressed_size=compressBound((uLong) payload_size);
+      compressed_size=compressBound((uLong) cel_size);
       compressed=(uint8_t *) AcquireQuantumMemory((size_t) compressed_size,
         sizeof(uint8_t));
       if (compressed == (uint8_t *) NULL)
@@ -1532,29 +1614,16 @@ static MagickBooleanType WriteASEImage(const ImageInfo *image_info,
           pixels=(uint8_t *) RelinquishMagickMemory(pixels);
           ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
         }
-      if (compress2(compressed,&compressed_size,pixels,payload_size,
+      if (compress2(compressed,&compressed_size,pixels,(uLong) cel_size,
           Z_BEST_COMPRESSION) != Z_OK)
         {
           compressed=(uint8_t *) RelinquishMagickMemory(compressed);
           pixels=(uint8_t *) RelinquishMagickMemory(pixels);
           ThrowWriterException(CorruptImageError,"UnableToCompressImage");
         }
-      (void) WriteBlobLSBLong(image,(unsigned int) (compressed_size+26));
-      (void) WriteBlobLSBShort(image,0x2005);
-      (void) WriteBlobLSBShort(image,0); /* layer index */
-      (void) WriteBlobLSBShort(image,0); /* x */
-      (void) WriteBlobLSBShort(image,0); /* y */
-      (void) WriteBlobByte(image,255);   /* opacity */
-      (void) WriteBlobLSBShort(image,2);  /* compressed image */
-      (void) WriteBlobLSBShort(image,0);  /* z-index */
-      (void) WriteBlobByte(image,0);
-      (void) WriteBlobByte(image,0);
-      (void) WriteBlobByte(image,0);
-      (void) WriteBlobByte(image,0);
-      (void) WriteBlobByte(image,0);
-      (void) WriteBlobLSBShort(image,(unsigned short) p->columns);
-      (void) WriteBlobLSBShort(image,(unsigned short) p->rows);
-      count=WriteBlob(image,(size_t) compressed_size,compressed);
+      WriteASECelHeader(image,(size_t) compressed_size+26,2,cel_width,
+        cel_height);
+      count=(size_t) WriteBlob(image,(size_t) compressed_size,compressed);
       compressed=(uint8_t *) RelinquishMagickMemory(compressed);
       chunk_count++;
       if (count != (size_t) compressed_size)
@@ -1567,23 +1636,30 @@ static MagickBooleanType WriteASEImage(const ImageInfo *image_info,
     {
       pixels=(uint8_t *) RelinquishMagickMemory(pixels);
       (void) ThrowMagickException(exception,GetMagickModule(),
-      MissingDelegateError,"DelegateLibrarySupportNotBuiltIn","`%s' (ZLIB)",
-      image->filename);
+        MissingDelegateError,"DelegateLibrarySupportNotBuiltIn","`%s' (ZLIB)",
+        image->filename);
+      (void) CloseBlob(image);
       return(MagickFalse);
     }
 #endif
     end_offset=TellBlob(image);
-    SeekBlob(image,chunk_count_offset,SEEK_SET);
-    (void) WriteBlobLSBShort(image,(unsigned short) chunk_count);
-    SeekBlob(image,frame_size_offset,SEEK_SET);
+    (void) SeekBlob(image,frame_size_offset,SEEK_SET);
     (void) WriteBlobLSBLong(image,(unsigned int) (end_offset-frame_size_offset));
-    SeekBlob(image,0,SEEK_END);
+    (void) SeekBlob(image,frame_size_offset+6,SEEK_SET);
+    (void) WriteBlobLSBShort(image,(unsigned short) MagickMin(chunk_count,
+      0xFFFF));
+    (void) SeekBlob(image,frame_size_offset+12,SEEK_SET);
+    (void) WriteBlobLSBLong(image,(unsigned int) chunk_count);
+    (void) SeekBlob(image,0,SEEK_END);
+    status=SetImageProgress(image,SaveImagesTag,scene++,frame_count);
+    if (status == MagickFalse)
+      break;
   }
   pixels=(uint8_t *) RelinquishMagickMemory(pixels);
   end_offset=TellBlob(image);
-  SeekBlob(image,file_size_offset,SEEK_SET);
+  (void) SeekBlob(image,file_size_offset,SEEK_SET);
   (void) WriteBlobLSBLong(image,(unsigned int) end_offset);
-  SeekBlob(image,0,SEEK_END);
+  (void) SeekBlob(image,0,SEEK_END);
   if (CloseBlob(image) == MagickFalse)
     status=MagickFalse;
   return(status);