
// epimgconv: Enterprise 128 image converter utility
// Copyright (C) 2008-2016 Istvan Varga <istvanv@users.sourceforge.net>
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
// The Enterprise 128 program files generated by this utility are not covered
// by the GNU General Public License, and can be used, modified, and
// distributed without any restrictions.

#include "epimgconv.hpp"
#include "imageconv.hpp"
#include "pixel16_1.hpp"

#include <vector>

namespace Ep128ImgConv {

  void ImageConv_Pixel16_1::initializePalettes()
  {
    for (int i = 0; i < 256; i++)
      convertEPColorToYUV(i, paletteY[i], paletteU[i], paletteV[i]);
    for (int c0 = 0; c0 < 256; c0++) {
      for (int c1 = 0; c1 < 256; c1++) {
        errorTable[(c0 << 8) | c1] =
            Ep128ImgConv::calculateYUVErrorSqr(
                paletteY[c0], paletteU[c0], paletteV[c0],
                paletteY[c1], paletteU[c1], paletteV[c1],
                colorErrorScale);
      }
    }
  }

  void ImageConv_Pixel16_1::setFixBias(int n)
  {
    fixBiasValue = n & 31;
    for (int yc = 0; yc < height; yc++) {
      for (int i = 8; i < 16; i++)
        palette[yc][i] = (unsigned char) ((fixBiasValue << 3) | (i & 7));
    }
  }

  void ImageConv_Pixel16_1::randomizePalette(int yc, int seedValue)
  {
    int     tmp = 0;
    setRandomSeed(tmp, uint32_t(seedValue));
    for (int i = 0; i < 8; i++) {
      unsigned char c = (unsigned char) (getRandomNumber(tmp) & 0xFF);
      if (!fixedColors[i])
        palette[yc][i] = c;
    }
  }

  double ImageConv_Pixel16_1::calculateError(
      const size_t *colorCntTable, const unsigned char *palette_,
      int colorChanged, unsigned char *colorIndexCache, double *errorCache,
      double maxError)
  {
    double  totalError = 0.0;
    for (size_t c = 0; c < 256 && totalError < (maxError * 1.000001); c++) {
      if (colorCntTable[c] < 1)
        continue;
      const double  *tbl = &(errorTable[c << 8]);
      if (colorChanged >= 0) {
        if (int(colorIndexCache[c]) != colorChanged) {
          double  err = tbl[palette_[colorChanged]]
                        * double(long(colorCntTable[c]));
          double  minErr = errorCache[c];
          if (err < minErr) {
            minErr = err;
            colorIndexCache[c] = (unsigned char) colorChanged;
            errorCache[c] = err;
          }
          totalError += minErr;
          continue;
        }
      }
      double  minErr = tbl[palette_[0]];
      int     ci = 0;
      for (int i = 1; i < 16; i += 3) {
        double  err = tbl[palette_[i]];
        if (err < minErr) {
          minErr = err;
          ci = i;
        }
        err = tbl[palette_[i + 1]];
        if (err < minErr) {
          minErr = err;
          ci = i + 1;
        }
        err = tbl[palette_[i + 2]];
        if (err < minErr) {
          minErr = err;
          ci = i + 2;
        }
      }
      minErr *= double(long(colorCntTable[c]));
      if (colorIndexCache) {
        colorIndexCache[c] = (unsigned char) ci;
        errorCache[c] = minErr;
      }
      totalError += minErr;
    }
    return totalError;
  }

  double ImageConv_Pixel16_1::calculateLineError(
      int yc, int colorChanged, unsigned char *colorIndexCache,
      double *errorCache, double maxError)
  {
    double  totalError = 0.0;
    const unsigned char *palettePtr = palette[yc];
    for (int xc = 0; xc < width && totalError < (maxError * 1.00001); xc++) {
      const double  *tbl = &(errorTable[int(ditheredImage[yc][xc]) << 8]);
      if (colorChanged >= 0) {
        if (int(colorIndexCache[xc]) != colorChanged) {
          double  err = tbl[palettePtr[colorChanged]];
          double  minErr = errorCache[xc];
          if (err < minErr) {
            minErr = err;
            colorIndexCache[xc] = (unsigned char) colorChanged;
            errorCache[xc] = err;
          }
          totalError += minErr;
          continue;
        }
      }
      double  minErr = tbl[palettePtr[0]];
      int     ci = 0;
      for (int i = 1; i < 16; i += 3) {
        double  err = tbl[palettePtr[i]];
        if (err < minErr) {
          minErr = err;
          ci = i;
        }
        err = tbl[palettePtr[i + 1]];
        if (err < minErr) {
          minErr = err;
          ci = i + 1;
        }
        err = tbl[palettePtr[i + 2]];
        if (err < minErr) {
          minErr = err;
          ci = i + 2;
        }
      }
      if (colorIndexCache) {
        colorIndexCache[xc] = (unsigned char) ci;
        errorCache[xc] = minErr;
      }
      totalError += minErr;
    }
    return totalError;
  }

  double ImageConv_Pixel16_1::calculateTotalError(double maxError)
  {
    double  totalError = 0.0;
    for (int yc = 0; yc < height && totalError < (maxError * 1.000001); yc++)
      totalError += calculateLineError(yc);
    return totalError;
  }

  double ImageConv_Pixel16_1::optimizeLinePalette(int yc, int optimizeLevel)
  {
    bool    colorUsed[256];
    int     nColors = 0;
    float   minY = 1.0f;
    float   maxY = 0.0f;
    float   minU = 1.0f;
    float   maxU = -1.0f;
    float   minV = 1.0f;
    float   maxV = -1.0f;
    for (int i = 0; i < 256; i++)
      colorUsed[i] = false;
    for (int xc = 0; xc < width; xc++) {
      int     c = ditheredImage[yc][xc];
      if (!colorUsed[c]) {
        colorUsed[c] = true;
        nColors++;
      }
      float   y = paletteY[c];
      float   u = paletteU[c];
      float   v = paletteV[c];
      minY = (y < minY ? y : minY);
      maxY = (y > maxY ? y : maxY);
      minU = (u < minU ? u : minU);
      maxU = (u > maxU ? u : maxU);
      minV = (v < minV ? v : minV);
      maxV = (v > maxV ? v : maxV);
    }
    minY -= 0.0001f;
    maxY += 0.0001f;
    minU -= 0.0001f;
    maxU += 0.0001f;
    minV -= 0.0001f;
    maxV += 0.0001f;
    int     maxColors = 8;
    for (int i = 0; i < 16; i++) {
      if (i < 8) {
        if (!fixedColors[i])
          continue;
        maxColors--;
      }
      int     c = palette[yc][i];
      if (colorUsed[c]) {
        colorUsed[c] = false;
        nColors--;
      }
    }
    if (nColors <= maxColors) {
      // if lossless conversion is possible:
      nColors = 0;
      for (int i = 0; i < 256; i++) {
        if (colorUsed[i]) {
          while (fixedColors[nColors])
            nColors++;
          palette[yc][nColors] = (unsigned char) i;
          nColors++;
        }
      }
      for ( ; nColors < 8; nColors++) {
        if (!fixedColors[nColors])
          palette[yc][nColors] = 0x00;
      }
      return 0.0;
    }
    for (int i = 0; i < 256; i++) {
      float   y = paletteY[i];
      float   u = paletteU[i];
      float   v = paletteV[i];
      colorUsed[i] = (y >= minY && y <= maxY && u >= minU && u <= maxU &&
                      v >= minV && v <= maxV);
    }
    for (int i = 8; i < 16; i++)
      colorUsed[palette[yc][i]] = false;
    std::vector< unsigned char >  colorIndexCache(size_t(width), 0x00);
    std::vector< double >   errorCache(size_t(width), 1000000000.0);
    double  bestError = 1000000000.0;
    int     bestPalette[8];
    for (int l = 0; l < optimizeLevel; l++) {
      randomizePalette(yc, l + 1);
      double  minErr = calculateLineError(yc);
      bool    doneFlag = true;
      do {
        doneFlag = true;
        for (int i = 0; i < 8; i++) {
          int     bestColor = palette[yc][i];
          if (!fixedColors[i]) {
            (void) calculateLineError(yc, -1, &(colorIndexCache.front()),
                                      &(errorCache.front()));
            for (int c = 0; c < 256; c++) {
              if (!colorUsed[c])
                continue;
              palette[yc][i] = (unsigned char) c;
              double  err = calculateLineError(yc, i,
                                               &(colorIndexCache.front()),
                                               &(errorCache.front()), minErr);
              if (err < (minErr * 0.999999)) {
                bestColor = c;
                doneFlag = false;
                minErr = err;
              }
            }
          }
          palette[yc][i] = (unsigned char) bestColor;
          colorUsed[bestColor] = false;
        }
        for (int i = 0; i < 8; i++)
          colorUsed[palette[yc][i]] = true;
      } while (!doneFlag);
      if (minErr < bestError) {
        for (int i = 0; i < 8; i++)
          bestPalette[i] = palette[yc][i];
        bestError = minErr;
      }
    }
    for (int i = 0; i < 8; i++)
      palette[yc][i] = (unsigned char) bestPalette[i];
    sortLinePalette(yc);
    return bestError;
  }

  double ImageConv_Pixel16_1::optimizeImagePalette(int optimizeLevel,
                                                   bool optimizeFixBias)
  {
    std::vector< size_t > colorCntTable(256, 0);
    for (int yc = 0; yc < height; yc++) {
      for (int xc = 0; xc < width; xc++) {
        int     tmp = ditheredImage[yc][xc] & 0xFF;
        colorCntTable[tmp] = colorCntTable[tmp] + 1;
      }
    }
    if (optimizeFixBias)
      optimizeLevel = optimizeLevel * 32;
    std::vector< unsigned char >  colorIndexCache(256, 0x00);
    std::vector< double >   errorCache(256, 1000000000.0);
    double  bestError = 1000000000.0;
    int     bestPalette[8];
    int     bestFixBias = fixBiasValue;
    int     progressCnt = 0;
    int     progressMax = optimizeLevel;
    for (int l = 0; l < optimizeLevel; l++) {
      if (!setProgressPercentage(progressCnt * 100 / progressMax))
        return -1.0;
      progressCnt++;
      if (optimizeFixBias)
        setFixBias(l & 0x1F);
      randomizePalette(0, l + 1);
      setFixedPalette();
      double  minErr = calculateError(&(colorCntTable.front()), palette[0]);
      bool    doneFlag = true;
      do {
        doneFlag = true;
        for (int i = 0; i < 8; i++) {
          int     bestColor = palette[0][i];
          if (!fixedColors[i]) {
            (void) calculateError(&(colorCntTable.front()), palette[0],
                                  -1, &(colorIndexCache.front()),
                                  &(errorCache.front()));
            for (int c = 0; c < 256; c++) {
              palette[0][i] = (unsigned char) c;
              setFixedPalette();
              double  err =
                  calculateError(&(colorCntTable.front()), palette[0],
                                 i, &(colorIndexCache.front()),
                                 &(errorCache.front()), minErr);
              if (err < (minErr * 0.999999)) {
                bestColor = c;
                doneFlag = false;
                minErr = err;
              }
            }
          }
          palette[0][i] = (unsigned char) bestColor;
        }
      } while (!doneFlag);
      if (minErr < bestError) {
        for (int i = 0; i < 8; i++)
          bestPalette[i] = palette[0][i];
        bestFixBias = fixBiasValue;
        bestError = minErr;
      }
    }
    setFixBias(bestFixBias);
    for (int i = 0; i < 8; i++)
      palette[0][i] = (unsigned char) bestPalette[i];
    sortLinePalette(0);
    setFixedPalette();
    return bestError;
  }

  void ImageConv_Pixel16_1::sortLinePalette(int yc)
  {
    // sort palette colors by bit-reversed color value
    for (int i = 0; i < 8; i++) {
      unsigned char tmp = palette[yc][i];
      tmp = ((tmp & 0x55) << 1) | ((tmp & 0xAA) >> 1);
      tmp = ((tmp & 0x33) << 2) | ((tmp & 0xCC) >> 2);
      tmp = ((tmp & 0x0F) << 4) | ((tmp & 0xF0) >> 4);
      palette[yc][i] = tmp;
    }
    for (int i = 0; i < 7; i++) {
      for (int j = i + 1; j < 8; j++) {
        if (fixedColors[i] || fixedColors[j] ||
            palette[yc][i] <= palette[yc][j]) {
          continue;
        }
        unsigned char tmp = palette[yc][i];
        palette[yc][i] = palette[yc][j];
        palette[yc][j] = tmp;
      }
    }
    for (int i = 0; i < 8; i++) {
      unsigned char tmp = palette[yc][i];
      tmp = ((tmp & 0x55) << 1) | ((tmp & 0xAA) >> 1);
      tmp = ((tmp & 0x33) << 2) | ((tmp & 0xCC) >> 2);
      tmp = ((tmp & 0x0F) << 4) | ((tmp & 0xF0) >> 4);
      palette[yc][i] = tmp;
    }
  }

  void ImageConv_Pixel16_1::setFixedPalette()
  {
    for (int yc = 1; yc < height; yc++) {
      for (int i = 0; i < 8; i++)
        palette[yc][i] = palette[0][i];
    }
  }

  void ImageConv_Pixel16_1::preDitherImage()
  {
    ditherErrorImage.clear();
    unsigned char tmpPalette[256];
    for (int i = 0; i < 256; i++)
      tmpPalette[i] = (unsigned char) i;
    for (int yc = 0; yc < height; yc++) {
      ditherLine(ditheredImage, inputImage, ditherErrorImage, yc,
                 ditherType, ditherDiffusion, colorErrorScale,
                 &(tmpPalette[0]), 256, paletteY, paletteU, paletteV);
    }
  }

  void ImageConv_Pixel16_1::pixelStoreCallback(void *userData, int xc, int yc,
                                               float y, float u, float v)
  {
    ImageConv_Pixel16_1&  this_ =
        *(reinterpret_cast<ImageConv_Pixel16_1 *>(userData));
    xc = xc >> 2;
    yc = yc >> 1;
    if (xc < 0 || xc >= this_.width || yc < 0 || yc >= this_.height)
      return;
    limitYUVColor(y, u, v);
    this_.inputImage.y(xc, yc) += (y * 0.125f);
    this_.inputImage.u(xc, yc) += (u * 0.125f);
    this_.inputImage.v(xc, yc) += (v * 0.125f);
  }

  void ImageConv_Pixel16_1::pixelStoreCallbackI(void *userData, int xc, int yc,
                                                float y, float u, float v)
  {
    ImageConv_Pixel16_1&  this_ =
        *(reinterpret_cast<ImageConv_Pixel16_1 *>(userData));
    xc = xc >> 2;
    if (xc < 0 || xc >= this_.width || yc < 0 || yc >= this_.height)
      return;
    limitYUVColor(y, u, v);
    this_.inputImage.y(xc, yc) += (y * 0.25f);
    this_.inputImage.u(xc, yc) += (u * 0.25f);
    this_.inputImage.v(xc, yc) += (v * 0.25f);
  }

  ImageConv_Pixel16_1::ImageConv_Pixel16_1()
    : ImageConverter(),
      width(1),
      height(1),
      colorErrorScale(0.5f),
      fixBiasValue(0x00),
      inputImage(1, 1),
      ditherErrorImage(1, 1),
      ditheredImage(1, 1),
      convertedImage(1, 1),
      palette(16, 1),
      conversionQuality(3),
      borderColor(0x00),
      ditherType(1),
      ditherDiffusion(0.95f),
      errorTable((double *) 0)
  {
    for (int i = 0; i < 8; i++)
      fixedColors[i] = false;
    errorTable = new double[256 * 256];
    initializePalettes();
  }

  ImageConv_Pixel16_1::~ImageConv_Pixel16_1()
  {
    delete[] errorTable;
  }

  bool ImageConv_Pixel16_1::processImage(
      ImageData& imgData, const char *infileName,
      YUVImageConverter& imgConv, const ImageConvConfig& config)
  {
    width = config.width << 2;
    height = ((imgData[5] & 0x80) == 0 ? config.height : (config.height << 1));
    colorErrorScale = float(config.colorErrorScale);
    conversionQuality = config.conversionQuality;
    borderColor = config.borderColor & 0xFF;
    float   borderY = 0.0f;
    float   borderU = 0.0f;
    float   borderV = 0.0f;
    convertEPColorToYUV(borderColor, borderY, borderU, borderV);
    inputImage.setBorderColor(borderY, borderU, borderV);
    ditherType = config.ditherType;
    limitValue(ditherType, 0, 5);
    ditherDiffusion = float(config.ditherDiffusion);

    inputImage.resize(width, height);
    ditherErrorImage.resize(width, height);
    ditheredImage.resize(width, height);
    convertedImage.resize(width, height);
    palette.resize(16, height);
    inputImage.clear();
    ditherErrorImage.clear();
    ditheredImage.clear();
    convertedImage.clear();
    palette.clear();

    initializePalettes();
    setFixBias(0);
    for (int i = 0; i < 8; i++)
      fixedColors[i] = (config.paletteColors[i] >= 0);
    for (int yc = 0; yc < height; yc++) {
      randomizePalette(yc, yc + 1000);
      for (int i = 0; i < 8; i++) {
        if (fixedColors[i])
          palette[yc][i] = (unsigned char) (config.paletteColors[i] & 0xFF);
      }
    }

    if (!(imgData[5] & 0x80))
      imgConv.setPixelStoreCallback(&pixelStoreCallback, (void *) this);
    else
      imgConv.setPixelStoreCallback(&pixelStoreCallbackI, (void *) this);
    if (!imgConv.convertImageFile(infileName))
      return false;

    progressMessage("Converting image");
    setProgressPercentage(0);
    preDitherImage();
    if (config.conversionType == 2) {
      for (int yc = 0; yc < height; yc++) {
        for (int xc = 0; xc < width; xc++) {
          inputImage.y(xc, yc) = paletteY[ditheredImage[yc][xc]];
          inputImage.u(xc, yc) = paletteU[ditheredImage[yc][xc]];
          inputImage.v(xc, yc) = paletteV[ditheredImage[yc][xc]];
        }
      }
      ditherType = 0;
      ditherDiffusion = 0.0f;
    }
    int     optimizeLevel = 1 + ((conversionQuality - 1) >> 1);
    if (config.paletteResolution != 0) {
      // generate optimal palette independently for each line
      int     progressCnt = 0;
      if (conversionQuality < 9 && config.fixBias < 0) {
        int     progressMax =
            height * (((optimizeLevel + 1) * optimizeLevel) / 2);
        for (int l = 0; l < optimizeLevel; l++) {
          double  bestError = 1000000000.0;
          int     bestFixBias = 0;
          for (int fb = 0; fb < 32; fb++) {
            setFixBias(fb);
            double  err = calculateTotalError(bestError);
            if (err < bestError) {
              bestFixBias = fb;
              bestError = err;
            }
          }
          setFixBias(bestFixBias);
          for (int yc = 0; yc < height; yc++) {
            if (!setProgressPercentage((progressCnt * 100) / progressMax))
              return false;
            optimizeLinePalette(yc, l + 1);
            progressCnt += (l + 1);
          }
        }
      }
      else {
        // at the highest quality, use brute force search to find best FIXBIAS
        int     progressMax = height * optimizeLevel;
        int     bestFixBias = 0;
        if (config.fixBias < 0) {
          progressMax = progressMax + (height * 32 * 2);
          double  bestError = 1000000000.0;
          for (int fb = 0; fb < 32; fb++) {
            setFixBias(fb);
            for (int yc = 0; yc < height; yc++) {
              if (!setProgressPercentage((progressCnt * 100) / progressMax))
                return false;
              optimizeLinePalette(yc, 2);
              progressCnt += 2;
            }
            double  err = calculateTotalError(bestError);
            if (err < bestError) {
              bestFixBias = fb;
              bestError = err;
            }
          }
        }
        else {
          bestFixBias = config.fixBias & 0x1F;
        }
        setFixBias(bestFixBias);
        for (int yc = 0; yc < height; yc++) {
          if (!setProgressPercentage((progressCnt * 100) / progressMax))
            return false;
          optimizeLinePalette(yc, optimizeLevel);
          progressCnt += optimizeLevel;
        }
      }
    }
    else {
      // generate optimal palette for the whole image
      if (config.fixBias >= 0)
        setFixBias(config.fixBias & 0x1F);
      if (optimizeImagePalette(optimizeLevel, (config.fixBias < 0)) < -0.5)
        return false;
    }
    ditherErrorImage.clear();
    imgData.setBorderColor(borderColor);
    for (int yc = 0; yc < height; yc++) {
      ditherLine(convertedImage, inputImage, ditherErrorImage, yc,
                 ditherType, ditherDiffusion,
                 colorErrorScale, &(palette[yc][0]), 16,
                 paletteY, paletteU, paletteV);
      imgData.setFixBias(yc, fixBiasValue);
      for (int i = 0; i < 8; i++)
        imgData.setPaletteColor(yc, i, palette[yc][i]);
      for (int xc = 0; xc < width; xc++)
        imgData.setPixel(xc, yc, convertedImage[yc][xc]);
    }
    setProgressPercentage(100);
    progressMessage("");
    double  totalError = calculateTotalError();
    char    tmpBuf[96];
    if (config.paletteResolution != 0) {
      std::sprintf(&(tmpBuf[0]), "Done; RMS error = %.4f, bias = %d",
                   std::sqrt(totalError / (double(width) * double(height))),
                   fixBiasValue);
    }
    else {
      std::sprintf(&(tmpBuf[0]),
                   "Done; RMS error = %.4f, bias = %d, "
                   "palette = %d %d %d %d %d %d %d %d",
                   std::sqrt(totalError / (double(width) * double(height))),
                   fixBiasValue, int(palette[0][0]), int(palette[0][1]),
                   int(palette[0][2]), int(palette[0][3]), int(palette[0][4]),
                   int(palette[0][5]), int(palette[0][6]), int(palette[0][7]));
    }
    progressMessage(&(tmpBuf[0]));
    return true;
  }

}       // namespace Ep128ImgConv

