/*
 *  Copyright 1994-2022 Olivier Girondel
 *
 *  This file is part of lebiniou.
 *
 *  lebiniou 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.
 *
 *  lebiniou 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 lebiniou. If not, see <http://www.gnu.org/licenses/>.
 */

#ifdef MAGICKWAND7
#include <MagickWand/MagickWand.h>
#else
#include <wand/magick_wand.h>
#endif
#include "context.h"
#include "pthread_utils.h"


// Data must be freed using MagickRelinquishMemory()

void
Context_to_PNG(Context_t *ctx, uint8_t **data, size_t *datalen, const uint16_t width, const uint16_t height)
{
  *data = NULL;
  *datalen = 0;

  if (!xpthread_mutex_lock(&ctx->frame_mutex)) {
    assert(NULL != ctx->frame);
    MagickWand *wand = NULL;
    MagickBooleanType status;

    wand = NewMagickWand();
    if (NULL != wand) {
      status = MagickConstituteImage(wand, WIDTH, HEIGHT, "RGB", CharPixel, ctx->frame);

      if (status == MagickTrue) {
        status = MagickSetImageFormat(wand, "PNG");
        if (status == MagickTrue) {
          if (width && height) { // rescale
            /* Available filters
             *
             * Bessel   Blackman   Box
             * Catrom   CubicGaussian
             * Hanning  Hermite    Lanczos
             * Mitchell PointQuandratic
             * Sinc     Triangle
             */
#ifdef MAGICKWAND7
            status = MagickResizeImage(wand, width, height, BesselFilter);
#else
            status = MagickResizeImage(wand, width, height, BesselFilter, 1.0);
#endif
          }
          if (status == MagickTrue) {
            size_t png_datalen;

            *data = MagickGetImageBlob(wand, &png_datalen);
            *datalen = png_datalen;
          } else {
            xerror("%s MagickResizeImage() failed: status= %d\n", __func__, status);
          }
        }
      }
      DestroyMagickWand(wand);
    }
    xpthread_mutex_unlock(&ctx->frame_mutex);
  }
}
