/* Copyright  (C) 2010-2020 The RetroArch team
 *
 * ---------------------------------------------------------------------------------------
 * The following license statement only applies to this file (rtga.c).
 * ---------------------------------------------------------------------------------------
 *
 * Permission is hereby granted, free of charge,
 * to any person obtaining a copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation the rights to
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
 * and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
 * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

/* Modified version of stb_image's TGA sources. */

#include <stdio.h>
#include <stdint.h>
#include <stdarg.h>
#include <stddef.h> /* ptrdiff_t on osx */
#include <stdlib.h>
#include <string.h>
#include <limits.h> /* INT_MAX, SIZE_MAX via stdint */

#include <retro_inline.h>
#include <retro_endianness.h> /* MSB_FIRST: gates the LE memcpy fast path */

#include <formats/image.h>
#include <formats/rtga.h>

struct rtga
{
   uint8_t *buff_data;
   uint32_t *output_image;
};

typedef struct
{
   uint8_t *img_buffer;
   uint8_t *img_buffer_end;
   uint8_t *img_buffer_original;
   int buflen;
   int img_n, img_out_n;
   uint32_t img_x, img_y;
   uint8_t buffer_start[128];
} rtga_context;

static INLINE uint8_t rtga_get8(rtga_context *s)
{
   if (s->img_buffer < s->img_buffer_end)
      return *s->img_buffer++;
   return 0;
}

static void rtga_skip(rtga_context *s, int n)
{
   ptrdiff_t remaining;
   if (n < 0)
   {
      s->img_buffer = s->img_buffer_end;
      return;
   }
   /* Clamp the advance to the remaining input.  Pre-patch a large
    * attacker-supplied offset (TGA header byte 1, or palette
    * start) pushed img_buffer past img_buffer_end, which is
    * pointer arithmetic outside the allocated object (UB per C99).
    * All callers of rtga_get8 check "buffer < buffer_end" so the
    * clamped state parses as EOF and the subsequent header checks
    * or indexed-palette code fail cleanly. */
   remaining = s->img_buffer_end - s->img_buffer;
   if ((ptrdiff_t)n > remaining)
      s->img_buffer = s->img_buffer_end;
   else
      s->img_buffer += n;
}

static int rtga_get16le(rtga_context *s)
{
   return rtga_get8(s) + (rtga_get8(s) << 8);
}

static uint32_t *rtga_tga_load(rtga_context *s,
      unsigned *x, unsigned *y, int *comp,
      bool supports_rgba)
{
   /* Read in the TGA header stuff */
   int tga_offset          = rtga_get8(s);
   int tga_indexed         = rtga_get8(s);
   int tga_image_type      = rtga_get8(s);
   int tga_is_RLE          = 0;
   int tga_palette_start   = rtga_get16le(s);
   int tga_palette_len     = rtga_get16le(s);
   int tga_palette_bits    = rtga_get8(s);
   int tga_x_origin        = rtga_get16le(s);
   int tga_y_origin        = rtga_get16le(s);
   int tga_width           = rtga_get16le(s);
   int tga_height          = rtga_get16le(s);
   int tga_bits_per_pixel  = rtga_get8(s);
   int tga_comp            = tga_bits_per_pixel / 8;
   int tga_inverted        = rtga_get8(s);

   /* Output buffer — always 32bpp ARGB or ABGR */
   uint32_t *output        = NULL;

   (void)tga_palette_start;
   (void)tga_x_origin;
   (void)tga_y_origin;

   /*   do a tiny bit of precessing */
   if (tga_image_type >= 8)
   {
      tga_image_type -= 8;
      tga_is_RLE = 1;
   }

   /* int tga_alpha_bits = tga_inverted & 15; */
   tga_inverted = 1 - ((tga_inverted >> 5) & 1);

   /*   error check */
   if (
         (tga_width < 1) || (tga_height < 1) ||
         (tga_image_type < 1) || (tga_image_type > 3) ||
         (
          (tga_bits_per_pixel != 8)  && (tga_bits_per_pixel != 16) &&
          (tga_bits_per_pixel != 24) && (tga_bits_per_pixel != 32)
         )
      )
      return NULL;

   /*   If paletted, then we will use the number of bits from the palette.
    *
    *   tga_palette_bits is attacker-controlled (TGA byte 7, 0..255).
    *   Pre-patch the indexed-read loop below did
    *       for (j = 0; j * 8 < tga_palette_bits; ++j)
    *           raw_data[j] = tga_palette[pal_idx + j];
    *   raw_data is a 4-byte stack array, so tga_palette_bits > 32
    *   wrote past the end of raw_data -- a stack buffer overflow of
    *   up to 28 bytes, directly driven by the TGA header.  Reject
    *   bogus palette_bits / empty palettes here and everything
    *   downstream runs with bounded buffers. */
   if (tga_indexed)
   {
      if (    tga_palette_len < 1
           || (    tga_palette_bits != 15
                && tga_palette_bits != 16
                && tga_palette_bits != 24
                && tga_palette_bits != 32))
         return NULL;
      tga_comp = tga_palette_bits / 8;
   }

   /*   TGA info */
   *x = tga_width;
   *y = tga_height;
   if (comp)
      *comp = tga_comp;

   /* Bound the output allocation.  TGA dimensions are attacker-
    * controlled 16-bit values (max 65535), so their product is
    * up to ~4.29 G pixels.  Pre-patch a 32-bit build could wrap
    * (size_t)w * h * sizeof(uint32_t) to a small positive size_t
    * and the per-pixel decode ran off the undersized malloc.
    * Reject dimensions beyond a sane ceiling so the allocation
    * never grows anywhere near wrap territory and hostile
    * headers cannot drive the client into a multi-GiB malloc
    * attempt.  0x4000 x 0x4000 = 1 GiB of decoded RGBA,
    * comfortably larger than any real-world libretro asset. */
   if (tga_width > 0x4000 || tga_height > 0x4000)
      return NULL;
   output = (uint32_t*)malloc(
         (size_t)tga_width * (size_t)tga_height * sizeof(uint32_t));
   if (!output)
      return NULL;

   /* skip to the data's starting position (offset usually = 0) */
   rtga_skip(s, tga_offset);

   /* --- Decode all pixels directly into uint32 output --- */

   if (!tga_indexed && !tga_is_RLE && tga_comp >= 3)
   {
      /* Fast path: uncompressed, non-indexed, 24/32-bit.
       * Read entire rows via pointer arithmetic (no per-byte rtga_get8),
       * assemble uint32 pixels directly, handle row flip by writing
       * to the correct row offset. */
      int row;

      for (row = 0; row < tga_height; ++row)
      {
         int dst_row     = tga_inverted ? (tga_height - 1 - row) : row;
         uint32_t *dst   = output + dst_row * tga_width;
         int bytes_needed = tga_width * tga_comp;
         int col;

         if (s->img_buffer + bytes_needed > s->img_buffer_end)
            break;

         if (tga_comp == 4)
         {
            const uint8_t *src = s->img_buffer;
            if (supports_rgba)
            {
               /* TGA BGRA bytes → ABGR uint32: just memcpy on little-endian
                * since BGRA bytes = uint32 ARGB... no wait:
                * bytes [B,G,R,A] as little-endian uint32 = A<<24|R<<16|G<<8|B = ARGB.
                * We need ABGR = A<<24|B<<16|G<<8|R.
                * So we still need to swap R and B. */
               for (col = 0; col < tga_width; ++col)
               {
                  uint8_t b = src[0], g = src[1], r = src[2], a = src[3];
                  dst[col] = ((uint32_t)a << 24) | ((uint32_t)b << 16)
                           | ((uint32_t)g << 8)  | (uint32_t)r;
                  src += 4;
               }
            }
            else
            {
               /* !supports_rgba wants each pixel as the uint32 value
                * ARGB = A<<24|R<<16|G<<8|B.
                * TGA stores bytes [B,G,R,A]; on a little-endian host those
                * bytes reinterpreted as a uint32 already equal ARGB, so a
                * straight memcpy is correct and fast. On a big-endian host
                * the same bytes would read as BGRA, so we must build the
                * ARGB value explicitly by shifting. */
#ifndef MSB_FIRST
               /* Direct memcpy! (little-endian) */
               memcpy(dst, src, tga_width * 4);
#else
               for (col = 0; col < tga_width; ++col)
               {
                  uint8_t b = src[0], g = src[1], r = src[2], a = src[3];
                  dst[col] = ((uint32_t)a << 24) | ((uint32_t)r << 16)
                           | ((uint32_t)g << 8)  | (uint32_t)b;
                  src += 4;
               }
#endif
            }
         }
         else /* tga_comp == 3 */
         {
            const uint8_t *src = s->img_buffer;
            if (supports_rgba)
            {
               for (col = 0; col < tga_width; ++col)
               {
                  uint8_t b = src[0], g = src[1], r = src[2];
                  dst[col] = 0xFF000000u | ((uint32_t)b << 16)
                           | ((uint32_t)g << 8)  | (uint32_t)r;
                  src += 3;
               }
            }
            else
            {
               for (col = 0; col < tga_width; ++col)
               {
                  uint8_t b = src[0], g = src[1], r = src[2];
                  dst[col] = 0xFF000000u | ((uint32_t)r << 16)
                           | ((uint32_t)g << 8)  | (uint32_t)b;
                  src += 3;
               }
            }
         }

         s->img_buffer += bytes_needed;
      }
   }
   else
   {
      /* Generic path: RLE, indexed, or grayscale.
       * Per-pixel processing with row/column tracking. */
      int i, j;
      int RLE_repeating          = 0;
      int RLE_count              = 0;
      int read_next_pixel        = 1;
      unsigned char raw_data[4]  = {0};
      unsigned char *tga_palette = NULL;
      int pixel_count            = tga_width * tga_height;
      int cur_col                = 0;
      int cur_row                = 0;

      /* Load palette if indexed.  Header-level checks above have
       * ensured tga_palette_len >= 1 and tga_palette_bits in
       * {15,16,24,32}, so n is positive and bounded at
       * 65535 * 32 / 8 = 262140 bytes -- fits comfortably in int
       * and in the input length we've already accepted. */
      if (tga_indexed)
      {
         int n;
         rtga_skip(s, tga_palette_start);
         n = tga_palette_len * tga_palette_bits / 8;
         tga_palette = (unsigned char*)malloc((size_t)n);
         if (!tga_palette)
         {
            free(output);
            return NULL;
         }
         if (s->img_buffer_end - s->img_buffer >= (ptrdiff_t)n)
         {
            memcpy(tga_palette, s->img_buffer, n);
            s->img_buffer += n;
         }
         else
         {
            free(output);
            free(tga_palette);
            return NULL;
         }
      }

      for (i = 0; i < pixel_count; ++i)
      {
         int dst_row;
         uint32_t pixel;
         unsigned char b, g, r, a;

         /* RLE handling */
         if (tga_is_RLE)
         {
            if (RLE_count == 0)
            {
               int RLE_cmd     = rtga_get8(s);
               RLE_count       = 1 + (RLE_cmd & 127);
               RLE_repeating   = RLE_cmd >> 7;
               read_next_pixel = 1;
            }
            else if (!RLE_repeating)
               read_next_pixel = 1;
         }
         else
            read_next_pixel = 1;

         /* Read raw pixel data */
         if (read_next_pixel)
         {
            if (tga_indexed)
            {
               int pal_idx = rtga_get8(s);
               if (pal_idx >= tga_palette_len)
                  pal_idx = 0;
               pal_idx *= tga_palette_bits / 8;
               for (j = 0; j * 8 < tga_palette_bits; ++j)
                  raw_data[j] = tga_palette[pal_idx + j];
            }
            else
            {
               j = 0;
               switch (tga_bits_per_pixel)
               {
                  case 32:
                     raw_data[j++] = rtga_get8(s); /* fallthrough */
                  case 24:
                     raw_data[j++] = rtga_get8(s); /* fallthrough */
                  case 16:
                     raw_data[j++] = rtga_get8(s); /* fallthrough */
                  case  8:
                     raw_data[j++] = rtga_get8(s);
               }
            }
            read_next_pixel = 0;
         }

         /* Assemble pixel in correct byte order */
         if (tga_comp >= 3)
         {
            b = raw_data[0];
            g = raw_data[1];
            r = raw_data[2];
            a = (tga_comp >= 4) ? raw_data[3] : 0xFF;
         }
         else
         {
            r = g = b = raw_data[0];
            a = (tga_comp >= 2) ? raw_data[1] : 0xFF;
         }

         if (supports_rgba)
            pixel = ((uint32_t)a << 24) | ((uint32_t)b << 16)
                  | ((uint32_t)g << 8)  | (uint32_t)r;
         else
            pixel = ((uint32_t)a << 24) | ((uint32_t)r << 16)
                  | ((uint32_t)g << 8)  | (uint32_t)b;

         /* Write to correct position using tracked row/col
          * (avoids per-pixel division and modulo).  Use size_t for
          * the index so dst_row * tga_width does not overflow
          * signed int for a legitimate 65535 x 65535 image. */
         dst_row = tga_inverted ? (tga_height - 1 - cur_row) : cur_row;
         output[(size_t)dst_row * (size_t)tga_width + (size_t)cur_col] = pixel;

         if (++cur_col >= tga_width)
         {
            cur_col = 0;
            ++cur_row;
         }

         --RLE_count;
      }

      if (tga_palette)
         free(tga_palette);
   }

   return output;
}

static uint32_t *rtga_load_from_memory(uint8_t const *buffer, int len,
      unsigned *x, unsigned *y, int *comp, bool supports_rgba)
{
   rtga_context s;

   s.img_buffer          = (uint8_t *)buffer;
   s.img_buffer_original = (uint8_t *) buffer;
   s.img_buffer_end      = (uint8_t *) buffer+len;

   return rtga_tga_load(&s, x, y, comp, supports_rgba);
}

int rtga_process_image(rtga_t *rtga, void **buf_data,
      size_t size, unsigned *width, unsigned *height,
      bool supports_rgba)
{
   int comp;

   if (!rtga)
      return IMAGE_PROCESS_ERROR;

   /* Reject sizes that don't fit in int before casting.  A TGA
    * file larger than INT_MAX handed to an int-taking API would
    * truncate, the truncated value (potentially negative)
    * propagated to img_buffer_end = buffer + len, producing
    * pointer arithmetic outside the source object (UB).  A 2 GiB
    * TGA is unreasonable; reject early. */
   if (size > (size_t)INT_MAX)
      return IMAGE_PROCESS_ERROR;

   rtga->output_image   = rtga_load_from_memory(rtga->buff_data,
                           (int)size, width, height, &comp, supports_rgba);
   *buf_data             = rtga->output_image;

   if (!rtga->output_image)
      return IMAGE_PROCESS_ERROR;

   return IMAGE_PROCESS_END;
}

bool rtga_set_buf_ptr(rtga_t *rtga, void *data)
{
   if (!rtga)
      return false;

   rtga->buff_data = (uint8_t*)data;

   return true;
}

void rtga_free(rtga_t *rtga)
{
   if (!rtga)
      return;

   free(rtga);
}

rtga_t *rtga_alloc(void)
{
   rtga_t *rtga = (rtga_t*)calloc(1, sizeof(*rtga));
   if (!rtga)
      return NULL;
   return rtga;
}
