src/video/SDL_RLEaccel.c
author Sam Lantinga <slouken@libsdl.org>
Sun, 06 Mar 2011 23:54:50 -0800
changeset 5435 3de226f0cc06
parent 5423 b69fa50e80d7
child 5439 3a778c6c0269
permissions -rw-r--r--
Fixed up structure to match header, added missing Aloss
     1 /*
     2     SDL - Simple DirectMedia Layer
     3     Copyright (C) 1997-2011 Sam Lantinga
     4 
     5     This library is free software; you can redistribute it and/or
     6     modify it under the terms of the GNU Lesser General Public
     7     License as published by the Free Software Foundation; either
     8     version 2.1 of the License, or (at your option) any later version.
     9 
    10     This library is distributed in the hope that it will be useful,
    11     but WITHOUT ANY WARRANTY; without even the implied warranty of
    12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    13     Lesser General Public License for more details.
    14 
    15     You should have received a copy of the GNU Lesser General Public
    16     License along with this library; if not, write to the Free Software
    17     Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
    18 
    19     Sam Lantinga
    20     slouken@libsdl.org
    21 */
    22 #include "SDL_config.h"
    23 
    24 /*
    25  * RLE encoding for software colorkey and alpha-channel acceleration
    26  *
    27  * Original version by Sam Lantinga
    28  *
    29  * Mattias Engdegård (Yorick): Rewrite. New encoding format, encoder and
    30  * decoder. Added per-surface alpha blitter. Added per-pixel alpha
    31  * format, encoder and blitter.
    32  *
    33  * Many thanks to Xark and johns for hints, benchmarks and useful comments
    34  * leading to this code.
    35  *
    36  * Welcome to Macro Mayhem.
    37  */
    38 
    39 /*
    40  * The encoding translates the image data to a stream of segments of the form
    41  *
    42  * <skip> <run> <data>
    43  *
    44  * where <skip> is the number of transparent pixels to skip,
    45  *       <run>  is the number of opaque pixels to blit,
    46  * and   <data> are the pixels themselves.
    47  *
    48  * This basic structure is used both for colorkeyed surfaces, used for simple
    49  * binary transparency and for per-surface alpha blending, and for surfaces
    50  * with per-pixel alpha. The details differ, however:
    51  *
    52  * Encoding of colorkeyed surfaces:
    53  *
    54  *   Encoded pixels always have the same format as the target surface.
    55  *   <skip> and <run> are unsigned 8 bit integers, except for 32 bit depth
    56  *   where they are 16 bit. This makes the pixel data aligned at all times.
    57  *   Segments never wrap around from one scan line to the next.
    58  *
    59  *   The end of the sequence is marked by a zero <skip>,<run> pair at the *
    60  *   beginning of a line.
    61  *
    62  * Encoding of surfaces with per-pixel alpha:
    63  *
    64  *   The sequence begins with a struct RLEDestFormat describing the target
    65  *   pixel format, to provide reliable un-encoding.
    66  *
    67  *   Each scan line is encoded twice: First all completely opaque pixels,
    68  *   encoded in the target format as described above, and then all
    69  *   partially transparent (translucent) pixels (where 1 <= alpha <= 254),
    70  *   in the following 32-bit format:
    71  *
    72  *   For 32-bit targets, each pixel has the target RGB format but with
    73  *   the alpha value occupying the highest 8 bits. The <skip> and <run>
    74  *   counts are 16 bit.
    75  * 
    76  *   For 16-bit targets, each pixel has the target RGB format, but with
    77  *   the middle component (usually green) shifted 16 steps to the left,
    78  *   and the hole filled with the 5 most significant bits of the alpha value.
    79  *   i.e. if the target has the format         rrrrrggggggbbbbb,
    80  *   the encoded pixel will be 00000gggggg00000rrrrr0aaaaabbbbb.
    81  *   The <skip> and <run> counts are 8 bit for the opaque lines, 16 bit
    82  *   for the translucent lines. Two padding bytes may be inserted
    83  *   before each translucent line to keep them 32-bit aligned.
    84  *
    85  *   The end of the sequence is marked by a zero <skip>,<run> pair at the
    86  *   beginning of an opaque line.
    87  */
    88 
    89 #include "SDL_video.h"
    90 #include "SDL_sysvideo.h"
    91 #include "SDL_blit.h"
    92 #include "SDL_RLEaccel_c.h"
    93 
    94 #ifndef MAX
    95 #define MAX(a, b) ((a) > (b) ? (a) : (b))
    96 #endif
    97 #ifndef MIN
    98 #define MIN(a, b) ((a) < (b) ? (a) : (b))
    99 #endif
   100 
   101 #define PIXEL_COPY(to, from, len, bpp)			\
   102 do {							\
   103     if(bpp == 4) {					\
   104 	SDL_memcpy4(to, from, (size_t)(len));		\
   105     } else {						\
   106 	SDL_memcpy(to, from, (size_t)(len) * (bpp));	\
   107     }							\
   108 } while(0)
   109 
   110 /*
   111  * Various colorkey blit methods, for opaque and per-surface alpha
   112  */
   113 
   114 #define OPAQUE_BLIT(to, from, length, bpp, alpha)	\
   115     PIXEL_COPY(to, from, length, bpp)
   116 
   117 /*
   118  * For 32bpp pixels on the form 0x00rrggbb:
   119  * If we treat the middle component separately, we can process the two
   120  * remaining in parallel. This is safe to do because of the gap to the left
   121  * of each component, so the bits from the multiplication don't collide.
   122  * This can be used for any RGB permutation of course.
   123  */
   124 #define ALPHA_BLIT32_888(to, from, length, bpp, alpha)		\
   125     do {							\
   126         int i;							\
   127 	Uint32 *src = (Uint32 *)(from);				\
   128 	Uint32 *dst = (Uint32 *)(to);				\
   129 	for(i = 0; i < (int)(length); i++) {			\
   130 	    Uint32 s = *src++;					\
   131 	    Uint32 d = *dst;					\
   132 	    Uint32 s1 = s & 0xff00ff;				\
   133 	    Uint32 d1 = d & 0xff00ff;				\
   134 	    d1 = (d1 + ((s1 - d1) * alpha >> 8)) & 0xff00ff;	\
   135 	    s &= 0xff00;					\
   136 	    d &= 0xff00;					\
   137 	    d = (d + ((s - d) * alpha >> 8)) & 0xff00;		\
   138 	    *dst++ = d1 | d;					\
   139 	}							\
   140     } while(0)
   141 
   142 /*
   143  * For 16bpp pixels we can go a step further: put the middle component
   144  * in the high 16 bits of a 32 bit word, and process all three RGB
   145  * components at the same time. Since the smallest gap is here just
   146  * 5 bits, we have to scale alpha down to 5 bits as well.
   147  */
   148 #define ALPHA_BLIT16_565(to, from, length, bpp, alpha)	\
   149     do {						\
   150         int i;						\
   151 	Uint16 *src = (Uint16 *)(from);			\
   152 	Uint16 *dst = (Uint16 *)(to);			\
   153 	Uint32 ALPHA = alpha >> 3;			\
   154 	for(i = 0; i < (int)(length); i++) {		\
   155 	    Uint32 s = *src++;				\
   156 	    Uint32 d = *dst;				\
   157 	    s = (s | s << 16) & 0x07e0f81f;		\
   158 	    d = (d | d << 16) & 0x07e0f81f;		\
   159 	    d += (s - d) * ALPHA >> 5;			\
   160 	    d &= 0x07e0f81f;				\
   161 	    *dst++ = (Uint16)(d | d >> 16);			\
   162 	}						\
   163     } while(0)
   164 
   165 #define ALPHA_BLIT16_555(to, from, length, bpp, alpha)	\
   166     do {						\
   167         int i;						\
   168 	Uint16 *src = (Uint16 *)(from);			\
   169 	Uint16 *dst = (Uint16 *)(to);			\
   170 	Uint32 ALPHA = alpha >> 3;			\
   171 	for(i = 0; i < (int)(length); i++) {		\
   172 	    Uint32 s = *src++;				\
   173 	    Uint32 d = *dst;				\
   174 	    s = (s | s << 16) & 0x03e07c1f;		\
   175 	    d = (d | d << 16) & 0x03e07c1f;		\
   176 	    d += (s - d) * ALPHA >> 5;			\
   177 	    d &= 0x03e07c1f;				\
   178 	    *dst++ = (Uint16)(d | d >> 16);			\
   179 	}						\
   180     } while(0)
   181 
   182 /*
   183  * The general slow catch-all function, for remaining depths and formats
   184  */
   185 #define ALPHA_BLIT_ANY(to, from, length, bpp, alpha)			\
   186     do {								\
   187         int i;								\
   188 	Uint8 *src = from;						\
   189 	Uint8 *dst = to;						\
   190 	for(i = 0; i < (int)(length); i++) {				\
   191 	    Uint32 s, d;						\
   192 	    unsigned rs, gs, bs, rd, gd, bd;				\
   193 	    switch(bpp) {						\
   194 	    case 2:							\
   195 		s = *(Uint16 *)src;					\
   196 		d = *(Uint16 *)dst;					\
   197 		break;							\
   198 	    case 3:							\
   199 		if(SDL_BYTEORDER == SDL_BIG_ENDIAN) {			\
   200 		    s = (src[0] << 16) | (src[1] << 8) | src[2];	\
   201 		    d = (dst[0] << 16) | (dst[1] << 8) | dst[2];	\
   202 		} else {						\
   203 		    s = (src[2] << 16) | (src[1] << 8) | src[0];	\
   204 		    d = (dst[2] << 16) | (dst[1] << 8) | dst[0];	\
   205 		}							\
   206 		break;							\
   207 	    case 4:							\
   208 		s = *(Uint32 *)src;					\
   209 		d = *(Uint32 *)dst;					\
   210 		break;							\
   211 	    }								\
   212 	    RGB_FROM_PIXEL(s, fmt, rs, gs, bs);				\
   213 	    RGB_FROM_PIXEL(d, fmt, rd, gd, bd);				\
   214 	    rd += (rs - rd) * alpha >> 8;				\
   215 	    gd += (gs - gd) * alpha >> 8;				\
   216 	    bd += (bs - bd) * alpha >> 8;				\
   217 	    PIXEL_FROM_RGB(d, fmt, rd, gd, bd);				\
   218 	    switch(bpp) {						\
   219 	    case 2:							\
   220 		*(Uint16 *)dst = (Uint16)d;					\
   221 		break;							\
   222 	    case 3:							\
   223 		if(SDL_BYTEORDER == SDL_BIG_ENDIAN) {			\
   224 		    dst[0] = (Uint8)(d >> 16);					\
   225 		    dst[1] = (Uint8)(d >> 8);					\
   226 		    dst[2] = (Uint8)(d);						\
   227 		} else {						\
   228 		    dst[0] = (Uint8)d;						\
   229 		    dst[1] = (Uint8)(d >> 8);					\
   230 		    dst[2] = (Uint8)(d >> 16);					\
   231 		}							\
   232 		break;							\
   233 	    case 4:							\
   234 		*(Uint32 *)dst = d;					\
   235 		break;							\
   236 	    }								\
   237 	    src += bpp;							\
   238 	    dst += bpp;							\
   239 	}								\
   240     } while(0)
   241 
   242 /*
   243  * Special case: 50% alpha (alpha=128)
   244  * This is treated specially because it can be optimized very well, and
   245  * since it is good for many cases of semi-translucency.
   246  * The theory is to do all three components at the same time:
   247  * First zero the lowest bit of each component, which gives us room to
   248  * add them. Then shift right and add the sum of the lowest bits.
   249  */
   250 #define ALPHA_BLIT32_888_50(to, from, length, bpp, alpha)		\
   251     do {								\
   252         int i;								\
   253 	Uint32 *src = (Uint32 *)(from);					\
   254 	Uint32 *dst = (Uint32 *)(to);					\
   255 	for(i = 0; i < (int)(length); i++) {				\
   256 	    Uint32 s = *src++;						\
   257 	    Uint32 d = *dst;						\
   258 	    *dst++ = (((s & 0x00fefefe) + (d & 0x00fefefe)) >> 1)	\
   259 		     + (s & d & 0x00010101);				\
   260 	}								\
   261     } while(0)
   262 
   263 /*
   264  * For 16bpp, we can actually blend two pixels in parallel, if we take
   265  * care to shift before we add, not after.
   266  */
   267 
   268 /* helper: blend a single 16 bit pixel at 50% */
   269 #define BLEND16_50(dst, src, mask)			\
   270     do {						\
   271 	Uint32 s = *src++;				\
   272 	Uint32 d = *dst;				\
   273 	*dst++ = (Uint16)((((s & mask) + (d & mask)) >> 1) +	\
   274 	                  (s & d & (~mask & 0xffff)));		\
   275     } while(0)
   276 
   277 /* basic 16bpp blender. mask is the pixels to keep when adding. */
   278 #define ALPHA_BLIT16_50(to, from, length, bpp, alpha, mask)		\
   279     do {								\
   280 	unsigned n = (length);						\
   281 	Uint16 *src = (Uint16 *)(from);					\
   282 	Uint16 *dst = (Uint16 *)(to);					\
   283 	if(((uintptr_t)src ^ (uintptr_t)dst) & 3) {			\
   284 	    /* source and destination not in phase, blit one by one */	\
   285 	    while(n--)							\
   286 		BLEND16_50(dst, src, mask);				\
   287 	} else {							\
   288 	    if((uintptr_t)src & 3) {					\
   289 		/* first odd pixel */					\
   290 		BLEND16_50(dst, src, mask);				\
   291 		n--;							\
   292 	    }								\
   293 	    for(; n > 1; n -= 2) {					\
   294 		Uint32 s = *(Uint32 *)src;				\
   295 		Uint32 d = *(Uint32 *)dst;				\
   296 		*(Uint32 *)dst = ((s & (mask | mask << 16)) >> 1)	\
   297 		               + ((d & (mask | mask << 16)) >> 1)	\
   298 		               + (s & d & (~(mask | mask << 16)));	\
   299 		src += 2;						\
   300 		dst += 2;						\
   301 	    }								\
   302 	    if(n)							\
   303 		BLEND16_50(dst, src, mask); /* last odd pixel */	\
   304 	}								\
   305     } while(0)
   306 
   307 #define ALPHA_BLIT16_565_50(to, from, length, bpp, alpha)	\
   308     ALPHA_BLIT16_50(to, from, length, bpp, alpha, 0xf7de)
   309 
   310 #define ALPHA_BLIT16_555_50(to, from, length, bpp, alpha)	\
   311     ALPHA_BLIT16_50(to, from, length, bpp, alpha, 0xfbde)
   312 
   313 #define CHOOSE_BLIT(blitter, alpha, fmt)				\
   314     do {								\
   315         if(alpha == 255) {						\
   316 	    switch(fmt->BytesPerPixel) {				\
   317 	    case 1: blitter(1, Uint8, OPAQUE_BLIT); break;		\
   318 	    case 2: blitter(2, Uint8, OPAQUE_BLIT); break;		\
   319 	    case 3: blitter(3, Uint8, OPAQUE_BLIT); break;		\
   320 	    case 4: blitter(4, Uint16, OPAQUE_BLIT); break;		\
   321 	    }								\
   322 	} else {							\
   323 	    switch(fmt->BytesPerPixel) {				\
   324 	    case 1:							\
   325 		/* No 8bpp alpha blitting */				\
   326 		break;							\
   327 									\
   328 	    case 2:							\
   329 		switch(fmt->Rmask | fmt->Gmask | fmt->Bmask) {		\
   330 		case 0xffff:						\
   331 		    if(fmt->Gmask == 0x07e0				\
   332 		       || fmt->Rmask == 0x07e0				\
   333 		       || fmt->Bmask == 0x07e0) {			\
   334 			if(alpha == 128)				\
   335 			    blitter(2, Uint8, ALPHA_BLIT16_565_50);	\
   336 			else {						\
   337 			    blitter(2, Uint8, ALPHA_BLIT16_565);	\
   338 			}						\
   339 		    } else						\
   340 			goto general16;					\
   341 		    break;						\
   342 									\
   343 		case 0x7fff:						\
   344 		    if(fmt->Gmask == 0x03e0				\
   345 		       || fmt->Rmask == 0x03e0				\
   346 		       || fmt->Bmask == 0x03e0) {			\
   347 			if(alpha == 128)				\
   348 			    blitter(2, Uint8, ALPHA_BLIT16_555_50);	\
   349 			else {						\
   350 			    blitter(2, Uint8, ALPHA_BLIT16_555);	\
   351 			}						\
   352 			break;						\
   353 		    }							\
   354 		    /* fallthrough */					\
   355 									\
   356 		default:						\
   357 		general16:						\
   358 		    blitter(2, Uint8, ALPHA_BLIT_ANY);			\
   359 		}							\
   360 		break;							\
   361 									\
   362 	    case 3:							\
   363 		blitter(3, Uint8, ALPHA_BLIT_ANY);			\
   364 		break;							\
   365 									\
   366 	    case 4:							\
   367 		if((fmt->Rmask | fmt->Gmask | fmt->Bmask) == 0x00ffffff	\
   368 		   && (fmt->Gmask == 0xff00 || fmt->Rmask == 0xff00	\
   369 		       || fmt->Bmask == 0xff00)) {			\
   370 		    if(alpha == 128)					\
   371 			blitter(4, Uint16, ALPHA_BLIT32_888_50);	\
   372 		    else						\
   373 			blitter(4, Uint16, ALPHA_BLIT32_888);		\
   374 		} else							\
   375 		    blitter(4, Uint16, ALPHA_BLIT_ANY);			\
   376 		break;							\
   377 	    }								\
   378 	}								\
   379     } while(0)
   380 
   381 /*
   382  * This takes care of the case when the surface is clipped on the left and/or
   383  * right. Top clipping has already been taken care of.
   384  */
   385 static void
   386 RLEClipBlit(int w, Uint8 * srcbuf, SDL_Surface * dst,
   387             Uint8 * dstbuf, SDL_Rect * srcrect, unsigned alpha)
   388 {
   389     SDL_PixelFormat *fmt = dst->format;
   390 
   391 #define RLECLIPBLIT(bpp, Type, do_blit)					   \
   392     do {								   \
   393 	int linecount = srcrect->h;					   \
   394 	int ofs = 0;							   \
   395 	int left = srcrect->x;						   \
   396 	int right = left + srcrect->w;					   \
   397 	dstbuf -= left * bpp;						   \
   398 	for(;;) {							   \
   399 	    int run;							   \
   400 	    ofs += *(Type *)srcbuf;					   \
   401 	    run = ((Type *)srcbuf)[1];					   \
   402 	    srcbuf += 2 * sizeof(Type);					   \
   403 	    if(run) {							   \
   404 		/* clip to left and right borders */			   \
   405 		if(ofs < right) {					   \
   406 		    int start = 0;					   \
   407 		    int len = run;					   \
   408 		    int startcol;					   \
   409 		    if(left - ofs > 0) {				   \
   410 			start = left - ofs;				   \
   411 			len -= start;					   \
   412 			if(len <= 0)					   \
   413 			    goto nocopy ## bpp ## do_blit;		   \
   414 		    }							   \
   415 		    startcol = ofs + start;				   \
   416 		    if(len > right - startcol)				   \
   417 			len = right - startcol;				   \
   418 		    do_blit(dstbuf + startcol * bpp, srcbuf + start * bpp, \
   419 			    len, bpp, alpha);				   \
   420 		}							   \
   421 	    nocopy ## bpp ## do_blit:					   \
   422 		srcbuf += run * bpp;					   \
   423 		ofs += run;						   \
   424 	    } else if(!ofs)						   \
   425 		break;							   \
   426 	    if(ofs == w) {						   \
   427 		ofs = 0;						   \
   428 		dstbuf += dst->pitch;					   \
   429 		if(!--linecount)					   \
   430 		    break;						   \
   431 	    }								   \
   432 	}								   \
   433     } while(0)
   434 
   435     CHOOSE_BLIT(RLECLIPBLIT, alpha, fmt);
   436 
   437 #undef RLECLIPBLIT
   438 
   439 }
   440 
   441 
   442 /* blit a colorkeyed RLE surface */
   443 int
   444 SDL_RLEBlit(SDL_Surface * src, SDL_Rect * srcrect,
   445             SDL_Surface * dst, SDL_Rect * dstrect)
   446 {
   447     Uint8 *dstbuf;
   448     Uint8 *srcbuf;
   449     int x, y;
   450     int w = src->w;
   451     unsigned alpha;
   452 
   453     /* Lock the destination if necessary */
   454     if (SDL_MUSTLOCK(dst)) {
   455         if (SDL_LockSurface(dst) < 0) {
   456             return (-1);
   457         }
   458     }
   459 
   460     /* Set up the source and destination pointers */
   461     x = dstrect->x;
   462     y = dstrect->y;
   463     dstbuf = (Uint8 *) dst->pixels
   464         + y * dst->pitch + x * src->format->BytesPerPixel;
   465     srcbuf = (Uint8 *) src->map->data;
   466 
   467     {
   468         /* skip lines at the top if neccessary */
   469         int vskip = srcrect->y;
   470         int ofs = 0;
   471         if (vskip) {
   472 
   473 #define RLESKIP(bpp, Type)			\
   474 		for(;;) {			\
   475 		    int run;			\
   476 		    ofs += *(Type *)srcbuf;	\
   477 		    run = ((Type *)srcbuf)[1];	\
   478 		    srcbuf += sizeof(Type) * 2;	\
   479 		    if(run) {			\
   480 			srcbuf += run * bpp;	\
   481 			ofs += run;		\
   482 		    } else if(!ofs)		\
   483 			goto done;		\
   484 		    if(ofs == w) {		\
   485 			ofs = 0;		\
   486 			if(!--vskip)		\
   487 			    break;		\
   488 		    }				\
   489 		}
   490 
   491             switch (src->format->BytesPerPixel) {
   492             case 1:
   493                 RLESKIP(1, Uint8);
   494                 break;
   495             case 2:
   496                 RLESKIP(2, Uint8);
   497                 break;
   498             case 3:
   499                 RLESKIP(3, Uint8);
   500                 break;
   501             case 4:
   502                 RLESKIP(4, Uint16);
   503                 break;
   504             }
   505 
   506 #undef RLESKIP
   507 
   508         }
   509     }
   510 
   511     alpha = src->map->info.a;
   512     /* if left or right edge clipping needed, call clip blit */
   513     if (srcrect->x || srcrect->w != src->w) {
   514         RLEClipBlit(w, srcbuf, dst, dstbuf, srcrect, alpha);
   515     } else {
   516         SDL_PixelFormat *fmt = src->format;
   517 
   518 #define RLEBLIT(bpp, Type, do_blit)					      \
   519 	    do {							      \
   520 		int linecount = srcrect->h;				      \
   521 		int ofs = 0;						      \
   522 		for(;;) {						      \
   523 		    unsigned run;					      \
   524 		    ofs += *(Type *)srcbuf;				      \
   525 		    run = ((Type *)srcbuf)[1];				      \
   526 		    srcbuf += 2 * sizeof(Type);				      \
   527 		    if(run) {						      \
   528 			do_blit(dstbuf + ofs * bpp, srcbuf, run, bpp, alpha); \
   529 			srcbuf += run * bpp;				      \
   530 			ofs += run;					      \
   531 		    } else if(!ofs)					      \
   532 			break;						      \
   533 		    if(ofs == w) {					      \
   534 			ofs = 0;					      \
   535 			dstbuf += dst->pitch;				      \
   536 			if(!--linecount)				      \
   537 			    break;					      \
   538 		    }							      \
   539 		}							      \
   540 	    } while(0)
   541 
   542         CHOOSE_BLIT(RLEBLIT, alpha, fmt);
   543 
   544 #undef RLEBLIT
   545     }
   546 
   547   done:
   548     /* Unlock the destination if necessary */
   549     if (SDL_MUSTLOCK(dst)) {
   550         SDL_UnlockSurface(dst);
   551     }
   552     return (0);
   553 }
   554 
   555 #undef OPAQUE_BLIT
   556 
   557 /*
   558  * Per-pixel blitting macros for translucent pixels:
   559  * These use the same techniques as the per-surface blitting macros
   560  */
   561 
   562 /*
   563  * For 32bpp pixels, we have made sure the alpha is stored in the top
   564  * 8 bits, so proceed as usual
   565  */
   566 #define BLIT_TRANSL_888(src, dst)				\
   567     do {							\
   568         Uint32 s = src;						\
   569 	Uint32 d = dst;						\
   570 	unsigned alpha = s >> 24;				\
   571 	Uint32 s1 = s & 0xff00ff;				\
   572 	Uint32 d1 = d & 0xff00ff;				\
   573 	d1 = (d1 + ((s1 - d1) * alpha >> 8)) & 0xff00ff;	\
   574 	s &= 0xff00;						\
   575 	d &= 0xff00;						\
   576 	d = (d + ((s - d) * alpha >> 8)) & 0xff00;		\
   577 	dst = d1 | d | 0xff000000;				\
   578     } while(0)
   579 
   580 /*
   581  * For 16bpp pixels, we have stored the 5 most significant alpha bits in
   582  * bits 5-10. As before, we can process all 3 RGB components at the same time.
   583  */
   584 #define BLIT_TRANSL_565(src, dst)		\
   585     do {					\
   586 	Uint32 s = src;				\
   587 	Uint32 d = dst;				\
   588 	unsigned alpha = (s & 0x3e0) >> 5;	\
   589 	s &= 0x07e0f81f;			\
   590 	d = (d | d << 16) & 0x07e0f81f;		\
   591 	d += (s - d) * alpha >> 5;		\
   592 	d &= 0x07e0f81f;			\
   593 	dst = (Uint16)(d | d >> 16);			\
   594     } while(0)
   595 
   596 #define BLIT_TRANSL_555(src, dst)		\
   597     do {					\
   598 	Uint32 s = src;				\
   599 	Uint32 d = dst;				\
   600 	unsigned alpha = (s & 0x3e0) >> 5;	\
   601 	s &= 0x03e07c1f;			\
   602 	d = (d | d << 16) & 0x03e07c1f;		\
   603 	d += (s - d) * alpha >> 5;		\
   604 	d &= 0x03e07c1f;			\
   605 	dst = (Uint16)(d | d >> 16);			\
   606     } while(0)
   607 
   608 /* used to save the destination format in the encoding. Designed to be
   609    macro-compatible with SDL_PixelFormat but without the unneeded fields */
   610 typedef struct
   611 {
   612     Uint8 BytesPerPixel;
   613     Uint8 padding[3];
   614     Uint32 Rmask;
   615     Uint32 Gmask;
   616     Uint32 Bmask;
   617     Uint32 Amask;
   618     Uint8 Rloss;
   619     Uint8 Gloss;
   620     Uint8 Bloss;
   621     Uint8 Aloss;
   622     Uint8 Rshift;
   623     Uint8 Gshift;
   624     Uint8 Bshift;
   625     Uint8 Ashift;
   626 } RLEDestFormat;
   627 
   628 /* blit a pixel-alpha RLE surface clipped at the right and/or left edges */
   629 static void
   630 RLEAlphaClipBlit(int w, Uint8 * srcbuf, SDL_Surface * dst,
   631                  Uint8 * dstbuf, SDL_Rect * srcrect)
   632 {
   633     SDL_PixelFormat *df = dst->format;
   634     /*
   635      * clipped blitter: Ptype is the destination pixel type,
   636      * Ctype the translucent count type, and do_blend the macro
   637      * to blend one pixel.
   638      */
   639 #define RLEALPHACLIPBLIT(Ptype, Ctype, do_blend)			  \
   640     do {								  \
   641 	int linecount = srcrect->h;					  \
   642 	int left = srcrect->x;						  \
   643 	int right = left + srcrect->w;					  \
   644 	dstbuf -= left * sizeof(Ptype);					  \
   645 	do {								  \
   646 	    int ofs = 0;						  \
   647 	    /* blit opaque pixels on one line */			  \
   648 	    do {							  \
   649 		unsigned run;						  \
   650 		ofs += ((Ctype *)srcbuf)[0];				  \
   651 		run = ((Ctype *)srcbuf)[1];				  \
   652 		srcbuf += 2 * sizeof(Ctype);				  \
   653 		if(run) {						  \
   654 		    /* clip to left and right borders */		  \
   655 		    int cofs = ofs;					  \
   656 		    int crun = run;					  \
   657 		    if(left - cofs > 0) {				  \
   658 			crun -= left - cofs;				  \
   659 			cofs = left;					  \
   660 		    }							  \
   661 		    if(crun > right - cofs)				  \
   662 			crun = right - cofs;				  \
   663 		    if(crun > 0)					  \
   664 			PIXEL_COPY(dstbuf + cofs * sizeof(Ptype),	  \
   665 				   srcbuf + (cofs - ofs) * sizeof(Ptype), \
   666 				   (unsigned)crun, sizeof(Ptype));	  \
   667 		    srcbuf += run * sizeof(Ptype);			  \
   668 		    ofs += run;						  \
   669 		} else if(!ofs)						  \
   670 		    return;						  \
   671 	    } while(ofs < w);						  \
   672 	    /* skip padding if necessary */				  \
   673 	    if(sizeof(Ptype) == 2)					  \
   674 		srcbuf += (uintptr_t)srcbuf & 2;			  \
   675 	    /* blit translucent pixels on the same line */		  \
   676 	    ofs = 0;							  \
   677 	    do {							  \
   678 		unsigned run;						  \
   679 		ofs += ((Uint16 *)srcbuf)[0];				  \
   680 		run = ((Uint16 *)srcbuf)[1];				  \
   681 		srcbuf += 4;						  \
   682 		if(run) {						  \
   683 		    /* clip to left and right borders */		  \
   684 		    int cofs = ofs;					  \
   685 		    int crun = run;					  \
   686 		    if(left - cofs > 0) {				  \
   687 			crun -= left - cofs;				  \
   688 			cofs = left;					  \
   689 		    }							  \
   690 		    if(crun > right - cofs)				  \
   691 			crun = right - cofs;				  \
   692 		    if(crun > 0) {					  \
   693 			Ptype *dst = (Ptype *)dstbuf + cofs;		  \
   694 			Uint32 *src = (Uint32 *)srcbuf + (cofs - ofs);	  \
   695 			int i;						  \
   696 			for(i = 0; i < crun; i++)			  \
   697 			    do_blend(src[i], dst[i]);			  \
   698 		    }							  \
   699 		    srcbuf += run * 4;					  \
   700 		    ofs += run;						  \
   701 		}							  \
   702 	    } while(ofs < w);						  \
   703 	    dstbuf += dst->pitch;					  \
   704 	} while(--linecount);						  \
   705     } while(0)
   706 
   707     switch (df->BytesPerPixel) {
   708     case 2:
   709         if (df->Gmask == 0x07e0 || df->Rmask == 0x07e0 || df->Bmask == 0x07e0)
   710             RLEALPHACLIPBLIT(Uint16, Uint8, BLIT_TRANSL_565);
   711         else
   712             RLEALPHACLIPBLIT(Uint16, Uint8, BLIT_TRANSL_555);
   713         break;
   714     case 4:
   715         RLEALPHACLIPBLIT(Uint32, Uint16, BLIT_TRANSL_888);
   716         break;
   717     }
   718 }
   719 
   720 /* blit a pixel-alpha RLE surface */
   721 int
   722 SDL_RLEAlphaBlit(SDL_Surface * src, SDL_Rect * srcrect,
   723                  SDL_Surface * dst, SDL_Rect * dstrect)
   724 {
   725     int x, y;
   726     int w = src->w;
   727     Uint8 *srcbuf, *dstbuf;
   728     SDL_PixelFormat *df = dst->format;
   729 
   730     /* Lock the destination if necessary */
   731     if (SDL_MUSTLOCK(dst)) {
   732         if (SDL_LockSurface(dst) < 0) {
   733             return -1;
   734         }
   735     }
   736 
   737     x = dstrect->x;
   738     y = dstrect->y;
   739     dstbuf = (Uint8 *) dst->pixels + y * dst->pitch + x * df->BytesPerPixel;
   740     srcbuf = (Uint8 *) src->map->data + sizeof(RLEDestFormat);
   741 
   742     {
   743         /* skip lines at the top if necessary */
   744         int vskip = srcrect->y;
   745         if (vskip) {
   746             int ofs;
   747             if (df->BytesPerPixel == 2) {
   748                 /* the 16/32 interleaved format */
   749                 do {
   750                     /* skip opaque line */
   751                     ofs = 0;
   752                     do {
   753                         int run;
   754                         ofs += srcbuf[0];
   755                         run = srcbuf[1];
   756                         srcbuf += 2;
   757                         if (run) {
   758                             srcbuf += 2 * run;
   759                             ofs += run;
   760                         } else if (!ofs)
   761                             goto done;
   762                     } while (ofs < w);
   763 
   764                     /* skip padding */
   765                     srcbuf += (uintptr_t) srcbuf & 2;
   766 
   767                     /* skip translucent line */
   768                     ofs = 0;
   769                     do {
   770                         int run;
   771                         ofs += ((Uint16 *) srcbuf)[0];
   772                         run = ((Uint16 *) srcbuf)[1];
   773                         srcbuf += 4 * (run + 1);
   774                         ofs += run;
   775                     } while (ofs < w);
   776                 } while (--vskip);
   777             } else {
   778                 /* the 32/32 interleaved format */
   779                 vskip <<= 1;    /* opaque and translucent have same format */
   780                 do {
   781                     ofs = 0;
   782                     do {
   783                         int run;
   784                         ofs += ((Uint16 *) srcbuf)[0];
   785                         run = ((Uint16 *) srcbuf)[1];
   786                         srcbuf += 4;
   787                         if (run) {
   788                             srcbuf += 4 * run;
   789                             ofs += run;
   790                         } else if (!ofs)
   791                             goto done;
   792                     } while (ofs < w);
   793                 } while (--vskip);
   794             }
   795         }
   796     }
   797 
   798     /* if left or right edge clipping needed, call clip blit */
   799     if (srcrect->x || srcrect->w != src->w) {
   800         RLEAlphaClipBlit(w, srcbuf, dst, dstbuf, srcrect);
   801     } else {
   802 
   803         /*
   804          * non-clipped blitter. Ptype is the destination pixel type,
   805          * Ctype the translucent count type, and do_blend the
   806          * macro to blend one pixel.
   807          */
   808 #define RLEALPHABLIT(Ptype, Ctype, do_blend)				 \
   809 	do {								 \
   810 	    int linecount = srcrect->h;					 \
   811 	    do {							 \
   812 		int ofs = 0;						 \
   813 		/* blit opaque pixels on one line */			 \
   814 		do {							 \
   815 		    unsigned run;					 \
   816 		    ofs += ((Ctype *)srcbuf)[0];			 \
   817 		    run = ((Ctype *)srcbuf)[1];				 \
   818 		    srcbuf += 2 * sizeof(Ctype);			 \
   819 		    if(run) {						 \
   820 			PIXEL_COPY(dstbuf + ofs * sizeof(Ptype), srcbuf, \
   821 				   run, sizeof(Ptype));			 \
   822 			srcbuf += run * sizeof(Ptype);			 \
   823 			ofs += run;					 \
   824 		    } else if(!ofs)					 \
   825 			goto done;					 \
   826 		} while(ofs < w);					 \
   827 		/* skip padding if necessary */				 \
   828 		if(sizeof(Ptype) == 2)					 \
   829 		    srcbuf += (uintptr_t)srcbuf & 2;		 	 \
   830 		/* blit translucent pixels on the same line */		 \
   831 		ofs = 0;						 \
   832 		do {							 \
   833 		    unsigned run;					 \
   834 		    ofs += ((Uint16 *)srcbuf)[0];			 \
   835 		    run = ((Uint16 *)srcbuf)[1];			 \
   836 		    srcbuf += 4;					 \
   837 		    if(run) {						 \
   838 			Ptype *dst = (Ptype *)dstbuf + ofs;		 \
   839 			unsigned i;					 \
   840 			for(i = 0; i < run; i++) {			 \
   841 			    Uint32 src = *(Uint32 *)srcbuf;		 \
   842 			    do_blend(src, *dst);			 \
   843 			    srcbuf += 4;				 \
   844 			    dst++;					 \
   845 			}						 \
   846 			ofs += run;					 \
   847 		    }							 \
   848 		} while(ofs < w);					 \
   849 		dstbuf += dst->pitch;					 \
   850 	    } while(--linecount);					 \
   851 	} while(0)
   852 
   853         switch (df->BytesPerPixel) {
   854         case 2:
   855             if (df->Gmask == 0x07e0 || df->Rmask == 0x07e0
   856                 || df->Bmask == 0x07e0)
   857                 RLEALPHABLIT(Uint16, Uint8, BLIT_TRANSL_565);
   858             else
   859                 RLEALPHABLIT(Uint16, Uint8, BLIT_TRANSL_555);
   860             break;
   861         case 4:
   862             RLEALPHABLIT(Uint32, Uint16, BLIT_TRANSL_888);
   863             break;
   864         }
   865     }
   866 
   867   done:
   868     /* Unlock the destination if necessary */
   869     if (SDL_MUSTLOCK(dst)) {
   870         SDL_UnlockSurface(dst);
   871     }
   872     return 0;
   873 }
   874 
   875 /*
   876  * Auxiliary functions:
   877  * The encoding functions take 32bpp rgb + a, and
   878  * return the number of bytes copied to the destination.
   879  * The decoding functions copy to 32bpp rgb + a, and
   880  * return the number of bytes copied from the source.
   881  * These are only used in the encoder and un-RLE code and are therefore not
   882  * highly optimised.
   883  */
   884 
   885 /* encode 32bpp rgb + a into 16bpp rgb, losing alpha */
   886 static int
   887 copy_opaque_16(void *dst, Uint32 * src, int n,
   888                SDL_PixelFormat * sfmt, SDL_PixelFormat * dfmt)
   889 {
   890     int i;
   891     Uint16 *d = dst;
   892     for (i = 0; i < n; i++) {
   893         unsigned r, g, b;
   894         RGB_FROM_PIXEL(*src, sfmt, r, g, b);
   895         PIXEL_FROM_RGB(*d, dfmt, r, g, b);
   896 #ifdef __NDS__
   897 		*d |= NDS_BIT15;
   898 #endif
   899         src++;
   900         d++;
   901     }
   902     return n * 2;
   903 }
   904 
   905 /* decode opaque pixels from 16bpp to 32bpp rgb + a */
   906 static int
   907 uncopy_opaque_16(Uint32 * dst, void *src, int n,
   908                  RLEDestFormat * sfmt, SDL_PixelFormat * dfmt)
   909 {
   910     int i;
   911     Uint16 *s = src;
   912     unsigned alpha = dfmt->Amask ? 255 : 0;
   913     for (i = 0; i < n; i++) {
   914         unsigned r, g, b;
   915         RGB_FROM_PIXEL(*s, sfmt, r, g, b);
   916         PIXEL_FROM_RGBA(*dst, dfmt, r, g, b, alpha);
   917         s++;
   918         dst++;
   919     }
   920     return n * 2;
   921 }
   922 
   923 
   924 
   925 /* encode 32bpp rgb + a into 32bpp G0RAB format for blitting into 565 */
   926 static int
   927 copy_transl_565(void *dst, Uint32 * src, int n,
   928                 SDL_PixelFormat * sfmt, SDL_PixelFormat * dfmt)
   929 {
   930     int i;
   931     Uint32 *d = dst;
   932     for (i = 0; i < n; i++) {
   933         unsigned r, g, b, a;
   934         Uint16 pix;
   935         RGBA_FROM_8888(*src, sfmt, r, g, b, a);
   936         PIXEL_FROM_RGB(pix, dfmt, r, g, b);
   937         *d = ((pix & 0x7e0) << 16) | (pix & 0xf81f) | ((a << 2) & 0x7e0);
   938         src++;
   939         d++;
   940     }
   941     return n * 4;
   942 }
   943 
   944 /* encode 32bpp rgb + a into 32bpp G0RAB format for blitting into 555 */
   945 static int
   946 copy_transl_555(void *dst, Uint32 * src, int n,
   947                 SDL_PixelFormat * sfmt, SDL_PixelFormat * dfmt)
   948 {
   949     int i;
   950     Uint32 *d = dst;
   951     for (i = 0; i < n; i++) {
   952         unsigned r, g, b, a;
   953         Uint16 pix;
   954         RGBA_FROM_8888(*src, sfmt, r, g, b, a);
   955         PIXEL_FROM_RGB(pix, dfmt, r, g, b);
   956         *d = ((pix & 0x3e0) << 16) | (pix & 0xfc1f) | ((a << 2) & 0x3e0) | NDS_BIT15;
   957         src++;
   958         d++;
   959     }
   960     return n * 4;
   961 }
   962 
   963 /* decode translucent pixels from 32bpp GORAB to 32bpp rgb + a */
   964 static int
   965 uncopy_transl_16(Uint32 * dst, void *src, int n,
   966                  RLEDestFormat * sfmt, SDL_PixelFormat * dfmt)
   967 {
   968     int i;
   969     Uint32 *s = src;
   970     for (i = 0; i < n; i++) {
   971         unsigned r, g, b, a;
   972         Uint32 pix = *s++;
   973         a = (pix & 0x3e0) >> 2;
   974         pix = (pix & ~0x3e0) | pix >> 16;
   975         RGB_FROM_PIXEL(pix, sfmt, r, g, b);
   976         PIXEL_FROM_RGBA(*dst, dfmt, r, g, b, a);
   977         dst++;
   978     }
   979     return n * 4;
   980 }
   981 
   982 /* encode 32bpp rgba into 32bpp rgba, keeping alpha (dual purpose) */
   983 static int
   984 copy_32(void *dst, Uint32 * src, int n,
   985         SDL_PixelFormat * sfmt, SDL_PixelFormat * dfmt)
   986 {
   987     int i;
   988     Uint32 *d = dst;
   989     for (i = 0; i < n; i++) {
   990         unsigned r, g, b, a;
   991         Uint32 pixel;
   992         RGBA_FROM_8888(*src, sfmt, r, g, b, a);
   993         PIXEL_FROM_RGB(pixel, dfmt, r, g, b);
   994         *d++ = pixel | a << 24;
   995         src++;
   996     }
   997     return n * 4;
   998 }
   999 
  1000 /* decode 32bpp rgba into 32bpp rgba, keeping alpha (dual purpose) */
  1001 static int
  1002 uncopy_32(Uint32 * dst, void *src, int n,
  1003           RLEDestFormat * sfmt, SDL_PixelFormat * dfmt)
  1004 {
  1005     int i;
  1006     Uint32 *s = src;
  1007     for (i = 0; i < n; i++) {
  1008         unsigned r, g, b, a;
  1009         Uint32 pixel = *s++;
  1010         RGB_FROM_PIXEL(pixel, sfmt, r, g, b);
  1011         a = pixel >> 24;
  1012         PIXEL_FROM_RGBA(*dst, dfmt, r, g, b, a);
  1013         dst++;
  1014     }
  1015     return n * 4;
  1016 }
  1017 
  1018 #define ISOPAQUE(pixel, fmt) ((((pixel) & fmt->Amask) >> fmt->Ashift) == 255)
  1019 
  1020 #define ISTRANSL(pixel, fmt)	\
  1021     ((unsigned)((((pixel) & fmt->Amask) >> fmt->Ashift) - 1U) < 254U)
  1022 
  1023 /* convert surface to be quickly alpha-blittable onto dest, if possible */
  1024 static int
  1025 RLEAlphaSurface(SDL_Surface * surface)
  1026 {
  1027     SDL_Surface *dest;
  1028     SDL_PixelFormat *df;
  1029     int maxsize = 0;
  1030     int max_opaque_run;
  1031     int max_transl_run = 65535;
  1032     unsigned masksum;
  1033     Uint8 *rlebuf, *dst;
  1034     int (*copy_opaque) (void *, Uint32 *, int,
  1035                         SDL_PixelFormat *, SDL_PixelFormat *);
  1036     int (*copy_transl) (void *, Uint32 *, int,
  1037                         SDL_PixelFormat *, SDL_PixelFormat *);
  1038 
  1039     dest = surface->map->dst;
  1040     if (!dest)
  1041         return -1;
  1042     df = dest->format;
  1043     if (surface->format->BitsPerPixel != 32)
  1044         return -1;              /* only 32bpp source supported */
  1045 
  1046     /* find out whether the destination is one we support,
  1047        and determine the max size of the encoded result */
  1048     masksum = df->Rmask | df->Gmask | df->Bmask;
  1049     switch (df->BytesPerPixel) {
  1050     case 2:
  1051         /* 16bpp: only support 565 and 555 formats */
  1052         switch (masksum) {
  1053         case 0xffff:
  1054             if (df->Gmask == 0x07e0
  1055                 || df->Rmask == 0x07e0 || df->Bmask == 0x07e0) {
  1056                 copy_opaque = copy_opaque_16;
  1057                 copy_transl = copy_transl_565;
  1058             } else
  1059                 return -1;
  1060             break;
  1061         case 0x7fff:
  1062             if (df->Gmask == 0x03e0
  1063                 || df->Rmask == 0x03e0 || df->Bmask == 0x03e0) {
  1064                 copy_opaque = copy_opaque_16;
  1065                 copy_transl = copy_transl_555;
  1066             } else
  1067                 return -1;
  1068             break;
  1069         default:
  1070             return -1;
  1071         }
  1072         max_opaque_run = 255;   /* runs stored as bytes */
  1073 
  1074         /* worst case is alternating opaque and translucent pixels,
  1075            with room for alignment padding between lines */
  1076         maxsize = surface->h * (2 + (4 + 2) * (surface->w + 1)) + 2;
  1077         break;
  1078     case 4:
  1079         if (masksum != 0x00ffffff)
  1080             return -1;          /* requires unused high byte */
  1081         copy_opaque = copy_32;
  1082         copy_transl = copy_32;
  1083         max_opaque_run = 255;   /* runs stored as short ints */
  1084 
  1085         /* worst case is alternating opaque and translucent pixels */
  1086         maxsize = surface->h * 2 * 4 * (surface->w + 1) + 4;
  1087         break;
  1088     default:
  1089         return -1;              /* anything else unsupported right now */
  1090     }
  1091 
  1092     maxsize += sizeof(RLEDestFormat);
  1093     rlebuf = (Uint8 *) SDL_malloc(maxsize);
  1094     if (!rlebuf) {
  1095         SDL_OutOfMemory();
  1096         return -1;
  1097     }
  1098     {
  1099         /* save the destination format so we can undo the encoding later */
  1100         RLEDestFormat *r = (RLEDestFormat *) rlebuf;
  1101         r->BytesPerPixel = df->BytesPerPixel;
  1102         r->Rmask = df->Rmask;
  1103         r->Gmask = df->Gmask;
  1104         r->Bmask = df->Bmask;
  1105         r->Amask = df->Amask;
  1106         r->Rloss = df->Rloss;
  1107         r->Gloss = df->Gloss;
  1108         r->Bloss = df->Bloss;
  1109         r->Aloss = df->Aloss;
  1110         r->Rshift = df->Rshift;
  1111         r->Gshift = df->Gshift;
  1112         r->Bshift = df->Bshift;
  1113         r->Ashift = df->Ashift;
  1114     }
  1115     dst = rlebuf + sizeof(RLEDestFormat);
  1116 
  1117     /* Do the actual encoding */
  1118     {
  1119         int x, y;
  1120         int h = surface->h, w = surface->w;
  1121         SDL_PixelFormat *sf = surface->format;
  1122         Uint32 *src = (Uint32 *) surface->pixels;
  1123         Uint8 *lastline = dst;  /* end of last non-blank line */
  1124 
  1125         /* opaque counts are 8 or 16 bits, depending on target depth */
  1126 #define ADD_OPAQUE_COUNTS(n, m)			\
  1127 	if(df->BytesPerPixel == 4) {		\
  1128 	    ((Uint16 *)dst)[0] = n;		\
  1129 	    ((Uint16 *)dst)[1] = m;		\
  1130 	    dst += 4;				\
  1131 	} else {				\
  1132 	    dst[0] = n;				\
  1133 	    dst[1] = m;				\
  1134 	    dst += 2;				\
  1135 	}
  1136 
  1137         /* translucent counts are always 16 bit */
  1138 #define ADD_TRANSL_COUNTS(n, m)		\
  1139 	(((Uint16 *)dst)[0] = n, ((Uint16 *)dst)[1] = m, dst += 4)
  1140 
  1141         for (y = 0; y < h; y++) {
  1142             int runstart, skipstart;
  1143             int blankline = 0;
  1144             /* First encode all opaque pixels of a scan line */
  1145             x = 0;
  1146             do {
  1147                 int run, skip, len;
  1148                 skipstart = x;
  1149                 while (x < w && !ISOPAQUE(src[x], sf))
  1150                     x++;
  1151                 runstart = x;
  1152                 while (x < w && ISOPAQUE(src[x], sf))
  1153                     x++;
  1154                 skip = runstart - skipstart;
  1155                 if (skip == w)
  1156                     blankline = 1;
  1157                 run = x - runstart;
  1158                 while (skip > max_opaque_run) {
  1159                     ADD_OPAQUE_COUNTS(max_opaque_run, 0);
  1160                     skip -= max_opaque_run;
  1161                 }
  1162                 len = MIN(run, max_opaque_run);
  1163                 ADD_OPAQUE_COUNTS(skip, len);
  1164                 dst += copy_opaque(dst, src + runstart, len, sf, df);
  1165                 runstart += len;
  1166                 run -= len;
  1167                 while (run) {
  1168                     len = MIN(run, max_opaque_run);
  1169                     ADD_OPAQUE_COUNTS(0, len);
  1170                     dst += copy_opaque(dst, src + runstart, len, sf, df);
  1171                     runstart += len;
  1172                     run -= len;
  1173                 }
  1174             } while (x < w);
  1175 
  1176             /* Make sure the next output address is 32-bit aligned */
  1177             dst += (uintptr_t) dst & 2;
  1178 
  1179             /* Next, encode all translucent pixels of the same scan line */
  1180             x = 0;
  1181             do {
  1182                 int run, skip, len;
  1183                 skipstart = x;
  1184                 while (x < w && !ISTRANSL(src[x], sf))
  1185                     x++;
  1186                 runstart = x;
  1187                 while (x < w && ISTRANSL(src[x], sf))
  1188                     x++;
  1189                 skip = runstart - skipstart;
  1190                 blankline &= (skip == w);
  1191                 run = x - runstart;
  1192                 while (skip > max_transl_run) {
  1193                     ADD_TRANSL_COUNTS(max_transl_run, 0);
  1194                     skip -= max_transl_run;
  1195                 }
  1196                 len = MIN(run, max_transl_run);
  1197                 ADD_TRANSL_COUNTS(skip, len);
  1198                 dst += copy_transl(dst, src + runstart, len, sf, df);
  1199                 runstart += len;
  1200                 run -= len;
  1201                 while (run) {
  1202                     len = MIN(run, max_transl_run);
  1203                     ADD_TRANSL_COUNTS(0, len);
  1204                     dst += copy_transl(dst, src + runstart, len, sf, df);
  1205                     runstart += len;
  1206                     run -= len;
  1207                 }
  1208                 if (!blankline)
  1209                     lastline = dst;
  1210             } while (x < w);
  1211 
  1212             src += surface->pitch >> 2;
  1213         }
  1214         dst = lastline;         /* back up past trailing blank lines */
  1215         ADD_OPAQUE_COUNTS(0, 0);
  1216     }
  1217 
  1218 #undef ADD_OPAQUE_COUNTS
  1219 #undef ADD_TRANSL_COUNTS
  1220 
  1221     /* Now that we have it encoded, release the original pixels */
  1222     if (!(surface->flags & SDL_PREALLOC)) {
  1223         SDL_free(surface->pixels);
  1224         surface->pixels = NULL;
  1225     }
  1226 
  1227     /* realloc the buffer to release unused memory */
  1228     {
  1229         Uint8 *p = SDL_realloc(rlebuf, dst - rlebuf);
  1230         if (!p)
  1231             p = rlebuf;
  1232         surface->map->data = p;
  1233     }
  1234 
  1235     return 0;
  1236 }
  1237 
  1238 static Uint32
  1239 getpix_8(Uint8 * srcbuf)
  1240 {
  1241     return *srcbuf;
  1242 }
  1243 
  1244 static Uint32
  1245 getpix_16(Uint8 * srcbuf)
  1246 {
  1247     return *(Uint16 *) srcbuf;
  1248 }
  1249 
  1250 static Uint32
  1251 getpix_24(Uint8 * srcbuf)
  1252 {
  1253 #if SDL_BYTEORDER == SDL_LIL_ENDIAN
  1254     return srcbuf[0] + (srcbuf[1] << 8) + (srcbuf[2] << 16);
  1255 #else
  1256     return (srcbuf[0] << 16) + (srcbuf[1] << 8) + srcbuf[2];
  1257 #endif
  1258 }
  1259 
  1260 static Uint32
  1261 getpix_32(Uint8 * srcbuf)
  1262 {
  1263     return *(Uint32 *) srcbuf;
  1264 }
  1265 
  1266 typedef Uint32(*getpix_func) (Uint8 *);
  1267 
  1268 static const getpix_func getpixes[4] = {
  1269     getpix_8, getpix_16, getpix_24, getpix_32
  1270 };
  1271 
  1272 static int
  1273 RLEColorkeySurface(SDL_Surface * surface)
  1274 {
  1275     Uint8 *rlebuf, *dst;
  1276     int maxn;
  1277     int y;
  1278     Uint8 *srcbuf, *curbuf, *lastline;
  1279     int maxsize = 0;
  1280     int skip, run;
  1281     int bpp = surface->format->BytesPerPixel;
  1282     getpix_func getpix;
  1283     Uint32 ckey, rgbmask;
  1284     int w, h;
  1285 
  1286     /* calculate the worst case size for the compressed surface */
  1287     switch (bpp) {
  1288     case 1:
  1289         /* worst case is alternating opaque and transparent pixels,
  1290            starting with an opaque pixel */
  1291         maxsize = surface->h * 3 * (surface->w / 2 + 1) + 2;
  1292         break;
  1293     case 2:
  1294     case 3:
  1295         /* worst case is solid runs, at most 255 pixels wide */
  1296         maxsize = surface->h * (2 * (surface->w / 255 + 1)
  1297                                 + surface->w * bpp) + 2;
  1298         break;
  1299     case 4:
  1300         /* worst case is solid runs, at most 65535 pixels wide */
  1301         maxsize = surface->h * (4 * (surface->w / 65535 + 1)
  1302                                 + surface->w * 4) + 4;
  1303         break;
  1304     }
  1305 
  1306     rlebuf = (Uint8 *) SDL_malloc(maxsize);
  1307     if (rlebuf == NULL) {
  1308         SDL_OutOfMemory();
  1309         return (-1);
  1310     }
  1311 
  1312     /* Set up the conversion */
  1313     srcbuf = (Uint8 *) surface->pixels;
  1314     curbuf = srcbuf;
  1315     maxn = bpp == 4 ? 65535 : 255;
  1316     skip = run = 0;
  1317     dst = rlebuf;
  1318     rgbmask = ~surface->format->Amask;
  1319     ckey = surface->map->info.colorkey & rgbmask;
  1320     lastline = dst;
  1321     getpix = getpixes[bpp - 1];
  1322     w = surface->w;
  1323     h = surface->h;
  1324 
  1325 #define ADD_COUNTS(n, m)			\
  1326 	if(bpp == 4) {				\
  1327 	    ((Uint16 *)dst)[0] = n;		\
  1328 	    ((Uint16 *)dst)[1] = m;		\
  1329 	    dst += 4;				\
  1330 	} else {				\
  1331 	    dst[0] = n;				\
  1332 	    dst[1] = m;				\
  1333 	    dst += 2;				\
  1334 	}
  1335 
  1336     for (y = 0; y < h; y++) {
  1337         int x = 0;
  1338         int blankline = 0;
  1339         do {
  1340             int run, skip, len;
  1341             int runstart;
  1342             int skipstart = x;
  1343 
  1344             /* find run of transparent, then opaque pixels */
  1345             while (x < w && (getpix(srcbuf + x * bpp) & rgbmask) == ckey)
  1346                 x++;
  1347             runstart = x;
  1348             while (x < w && (getpix(srcbuf + x * bpp) & rgbmask) != ckey)
  1349                 x++;
  1350             skip = runstart - skipstart;
  1351             if (skip == w)
  1352                 blankline = 1;
  1353             run = x - runstart;
  1354 
  1355             /* encode segment */
  1356             while (skip > maxn) {
  1357                 ADD_COUNTS(maxn, 0);
  1358                 skip -= maxn;
  1359             }
  1360             len = MIN(run, maxn);
  1361             ADD_COUNTS(skip, len);
  1362             SDL_memcpy(dst, srcbuf + runstart * bpp, len * bpp);
  1363             dst += len * bpp;
  1364             run -= len;
  1365             runstart += len;
  1366             while (run) {
  1367                 len = MIN(run, maxn);
  1368                 ADD_COUNTS(0, len);
  1369                 SDL_memcpy(dst, srcbuf + runstart * bpp, len * bpp);
  1370                 dst += len * bpp;
  1371                 runstart += len;
  1372                 run -= len;
  1373             }
  1374             if (!blankline)
  1375                 lastline = dst;
  1376         } while (x < w);
  1377 
  1378         srcbuf += surface->pitch;
  1379     }
  1380     dst = lastline;             /* back up bast trailing blank lines */
  1381     ADD_COUNTS(0, 0);
  1382 
  1383 #undef ADD_COUNTS
  1384 
  1385     /* Now that we have it encoded, release the original pixels */
  1386     if (!(surface->flags & SDL_PREALLOC)) {
  1387         SDL_free(surface->pixels);
  1388         surface->pixels = NULL;
  1389     }
  1390 
  1391     /* realloc the buffer to release unused memory */
  1392     {
  1393         /* If realloc returns NULL, the original block is left intact */
  1394         Uint8 *p = SDL_realloc(rlebuf, dst - rlebuf);
  1395         if (!p)
  1396             p = rlebuf;
  1397         surface->map->data = p;
  1398     }
  1399 
  1400     return (0);
  1401 }
  1402 
  1403 int
  1404 SDL_RLESurface(SDL_Surface * surface)
  1405 {
  1406     int flags;
  1407 
  1408     /* Clear any previous RLE conversion */
  1409     if ((surface->flags & SDL_RLEACCEL) == SDL_RLEACCEL) {
  1410         SDL_UnRLESurface(surface, 1);
  1411     }
  1412 
  1413     /* We don't support RLE encoding of bitmaps */
  1414     if (surface->format->BitsPerPixel < 8) {
  1415         return -1;
  1416     }
  1417 
  1418     /* Make sure the pixels are available */
  1419     if (!surface->pixels) {
  1420         return -1;
  1421     }
  1422 
  1423     /* If we don't have colorkey or blending, nothing to do... */
  1424     flags = surface->map->info.flags;
  1425     if (!(flags & (SDL_COPY_COLORKEY | SDL_COPY_BLEND))) {
  1426         return -1;
  1427     }
  1428 
  1429     /* Pass on combinations not supported */
  1430     if ((flags & SDL_COPY_MODULATE_COLOR) ||
  1431         ((flags & SDL_COPY_MODULATE_ALPHA) && surface->format->Amask) ||
  1432         (flags & (SDL_COPY_ADD | SDL_COPY_MOD)) ||
  1433         (flags & SDL_COPY_NEAREST)) {
  1434         return -1;
  1435     }
  1436 
  1437     /* Encode and set up the blit */
  1438     if (!surface->format->Amask || !(flags & SDL_COPY_BLEND)) {
  1439         if (!surface->map->identity) {
  1440             return -1;
  1441         }
  1442         if (RLEColorkeySurface(surface) < 0) {
  1443             return -1;
  1444         }
  1445         surface->map->blit = SDL_RLEBlit;
  1446         surface->map->info.flags |= SDL_COPY_RLE_COLORKEY;
  1447     } else {
  1448         if (RLEAlphaSurface(surface) < 0) {
  1449             return -1;
  1450         }
  1451         surface->map->blit = SDL_RLEAlphaBlit;
  1452         surface->map->info.flags |= SDL_COPY_RLE_ALPHAKEY;
  1453     }
  1454 
  1455     /* The surface is now accelerated */
  1456     surface->flags |= SDL_RLEACCEL;
  1457 
  1458     return (0);
  1459 }
  1460 
  1461 /*
  1462  * Un-RLE a surface with pixel alpha
  1463  * This may not give back exactly the image before RLE-encoding; all
  1464  * completely transparent pixels will be lost, and colour and alpha depth
  1465  * may have been reduced (when encoding for 16bpp targets).
  1466  */
  1467 static SDL_bool
  1468 UnRLEAlpha(SDL_Surface * surface)
  1469 {
  1470     Uint8 *srcbuf;
  1471     Uint32 *dst;
  1472     SDL_PixelFormat *sf = surface->format;
  1473     RLEDestFormat *df = surface->map->data;
  1474     int (*uncopy_opaque) (Uint32 *, void *, int,
  1475                           RLEDestFormat *, SDL_PixelFormat *);
  1476     int (*uncopy_transl) (Uint32 *, void *, int,
  1477                           RLEDestFormat *, SDL_PixelFormat *);
  1478     int w = surface->w;
  1479     int bpp = df->BytesPerPixel;
  1480 
  1481     if (bpp == 2) {
  1482         uncopy_opaque = uncopy_opaque_16;
  1483         uncopy_transl = uncopy_transl_16;
  1484     } else {
  1485         uncopy_opaque = uncopy_transl = uncopy_32;
  1486     }
  1487 
  1488     surface->pixels = SDL_malloc(surface->h * surface->pitch);
  1489     if (!surface->pixels) {
  1490         return (SDL_FALSE);
  1491     }
  1492     /* fill background with transparent pixels */
  1493     SDL_memset(surface->pixels, 0, surface->h * surface->pitch);
  1494 
  1495     dst = surface->pixels;
  1496     srcbuf = (Uint8 *) (df + 1);
  1497     for (;;) {
  1498         /* copy opaque pixels */
  1499         int ofs = 0;
  1500         do {
  1501             unsigned run;
  1502             if (bpp == 2) {
  1503                 ofs += srcbuf[0];
  1504                 run = srcbuf[1];
  1505                 srcbuf += 2;
  1506             } else {
  1507                 ofs += ((Uint16 *) srcbuf)[0];
  1508                 run = ((Uint16 *) srcbuf)[1];
  1509                 srcbuf += 4;
  1510             }
  1511             if (run) {
  1512                 srcbuf += uncopy_opaque(dst + ofs, srcbuf, run, df, sf);
  1513                 ofs += run;
  1514             } else if (!ofs)
  1515                 return (SDL_TRUE);
  1516         } while (ofs < w);
  1517 
  1518         /* skip padding if needed */
  1519         if (bpp == 2)
  1520             srcbuf += (uintptr_t) srcbuf & 2;
  1521 
  1522         /* copy translucent pixels */
  1523         ofs = 0;
  1524         do {
  1525             unsigned run;
  1526             ofs += ((Uint16 *) srcbuf)[0];
  1527             run = ((Uint16 *) srcbuf)[1];
  1528             srcbuf += 4;
  1529             if (run) {
  1530                 srcbuf += uncopy_transl(dst + ofs, srcbuf, run, df, sf);
  1531                 ofs += run;
  1532             }
  1533         } while (ofs < w);
  1534         dst += surface->pitch >> 2;
  1535     }
  1536     /* Make the compiler happy */
  1537     return (SDL_TRUE);
  1538 }
  1539 
  1540 void
  1541 SDL_UnRLESurface(SDL_Surface * surface, int recode)
  1542 {
  1543     if (surface->flags & SDL_RLEACCEL) {
  1544         surface->flags &= ~SDL_RLEACCEL;
  1545 
  1546         if (recode && !(surface->flags & SDL_PREALLOC)) {
  1547             if (surface->map->info.flags & SDL_COPY_RLE_COLORKEY) {
  1548                 SDL_Rect full;
  1549 
  1550                 /* re-create the original surface */
  1551                 surface->pixels = SDL_malloc(surface->h * surface->pitch);
  1552                 if (!surface->pixels) {
  1553                     /* Oh crap... */
  1554                     surface->flags |= SDL_RLEACCEL;
  1555                     return;
  1556                 }
  1557 
  1558                 /* fill it with the background colour */
  1559                 SDL_FillRect(surface, NULL, surface->map->info.colorkey);
  1560 
  1561                 /* now render the encoded surface */
  1562                 full.x = full.y = 0;
  1563                 full.w = surface->w;
  1564                 full.h = surface->h;
  1565                 SDL_RLEBlit(surface, &full, surface, &full);
  1566             } else {
  1567                 if (!UnRLEAlpha(surface)) {
  1568                     /* Oh crap... */
  1569                     surface->flags |= SDL_RLEACCEL;
  1570                     return;
  1571                 }
  1572             }
  1573         }
  1574         surface->map->info.flags &=
  1575             ~(SDL_COPY_RLE_COLORKEY | SDL_COPY_RLE_ALPHAKEY);
  1576 
  1577         if (surface->map->data) {
  1578             SDL_free(surface->map->data);
  1579             surface->map->data = NULL;
  1580         }
  1581     }
  1582 }
  1583 
  1584 /* vi: set ts=4 sw=4 expandtab: */