// Tabmorph's small LibRaw adapter. Application glue: MIT.
#include <libraw/libraw.h>
#include <emscripten/emscripten.h>
#include <algorithm>
#include <array>
#include <chrono>
#include <cmath>
#include <cstring>
#include <new>
#include <string>
#include <vector>

struct RawContext {
  LibRaw raw;
  libraw_processed_image_t *image = nullptr;
  std::string error, make, model;
  unsigned width=0, height=0, count=0, warnings=0, maxPixels=0;
  std::chrono::steady_clock::time_point start;
  ~RawContext() { if(image) LibRaw::dcraw_clear_mem(image); }
};
static int progress(void *ptr, enum LibRaw_progress, int, int) {
  auto *ctx=static_cast<RawContext*>(ptr);
  return std::chrono::steady_clock::now()-ctx->start > std::chrono::seconds(90);
}
static int fail(RawContext *ctx, int code) { ctx->error=libraw_strerror(code); return code; }
extern "C" {
EMSCRIPTEN_KEEPALIVE RawContext *raw_create() { try { return new RawContext; } catch (...) { return nullptr; } }
EMSCRIPTEN_KEEPALIVE int raw_open(RawContext *ctx, unsigned char *input, unsigned size, unsigned maxPixels, unsigned maxMemoryMB) {
  if (!ctx || !input || !size) return -1;
  ctx->start=std::chrono::steady_clock::now(); ctx->maxPixels=maxPixels;
  ctx->raw.set_progress_handler(progress,ctx);
  ctx->raw.imgdata.rawparams.max_raw_memory_mb=maxMemoryMB;
  int code=ctx->raw.open_buffer(input,size); if(code) return fail(ctx,code);
  ctx->make=ctx->raw.imgdata.idata.normalized_make[0] ? ctx->raw.imgdata.idata.normalized_make : ctx->raw.imgdata.idata.make;
  ctx->model=ctx->raw.imgdata.idata.normalized_model[0] ? ctx->raw.imgdata.idata.normalized_model : ctx->raw.imgdata.idata.model;
  ctx->count=ctx->raw.imgdata.idata.raw_count;
  ctx->width=ctx->raw.imgdata.sizes.width;ctx->height=ctx->raw.imgdata.sizes.height;
  if (!ctx->count || !ctx->width || !ctx->height || uint64_t(ctx->width)*ctx->height>120000000) { ctx->error="This RAW image has unsupported dimensions (maximum 120 megapixels).";return -1; }
  return 0;
}
EMSCRIPTEN_KEEPALIVE int raw_process(RawContext *ctx,int wb,int autoBright,double exposure,int halfSize) {
  if (!ctx || ctx->image) return -1;
  auto &params=ctx->raw.imgdata.params;
  params.output_bps=16;params.output_color=1;params.gamm[0]=1;params.gamm[1]=1;
  params.adjust_maximum_thr=0;
  params.user_qual=3;params.use_camera_wb=wb==0;params.use_auto_wb=wb==1;
  params.no_auto_bright=!autoBright;params.half_size=!!halfSize;
  if (std::isfinite(exposure) && exposure!=0) { params.exp_correc=1;params.exp_shift=std::pow(2.0,std::clamp(exposure,-2.0,3.0));params.exp_preser=0; }
  auto &sizes=ctx->raw.imgdata.sizes;
  bool shrinks=halfSize && ctx->raw.imgdata.idata.filters;
  if (uint64_t((sizes.width+(shrinks?1:0))/(shrinks?2:1))*((sizes.height+(shrinks?1:0))/(shrinks?2:1))>ctx->maxPixels) { ctx->error="This RAW is too large for full-resolution processing on this device. Choose Half resolution in Settings or use a desktop browser.";return -1; }
  auto code=ctx->raw.unpack();if(code)return fail(ctx,code);
  code=ctx->raw.dcraw_process();if(code)return fail(ctx,code);
  ctx->warnings=ctx->raw.imgdata.process_warnings;
  int error=0;ctx->image=ctx->raw.dcraw_make_mem_image(&error);
  if (!ctx->image) return fail(ctx,error ? error : LIBRAW_UNSPECIFIED_ERROR);
  if(ctx->image->type!=LIBRAW_IMAGE_BITMAP || ctx->image->bits!=16 || (ctx->image->colors!=1 && ctx->image->colors!=3) || uint64_t(ctx->image->width)*ctx->image->height>ctx->maxPixels) { ctx->error="The RAW decoder returned an unsupported image layout or size.";return -1; }
  ctx->raw.recycle();
  return 0;
}
// Antialiased separable Lanczos-3 in linear light, keeping 16-bit samples.
struct Weight { unsigned index; double value; };
static std::vector<std::vector<Weight>> weights(unsigned from,unsigned to) {
  double scale=double(to)/from,filterScale=std::min(1.0,scale),radius=3/filterScale;
  std::vector<std::vector<Weight>> all(to);
  auto sinc=[](double x){return x==0 ? 1.0 : std::sin(3.141592653589793*x)/(3.141592653589793*x);};
  for(unsigned at=0;at<to;at++) {
    double center=(at+.5)/scale-.5,sum=0;
    for(int i=std::ceil(center-radius);i<=std::floor(center+radius);i++) {
      double d=(i-center)*filterScale;
      double value=std::abs(d)<3 ? sinc(d)*sinc(d/3) : 0;
      if(value!=0) {all[at].push_back({unsigned(std::clamp(i,0,int(from)-1)),value});sum+=value;}
    }
    for(auto &w:all[at])w.value/=sum;
  }
  return all;
}
EMSCRIPTEN_KEEPALIVE int raw_resize(RawContext *ctx,unsigned maxSide) {
  if(!ctx || !ctx->image) return -1;
  auto *old=ctx->image;unsigned w=old->width,h=old->height,c=old->colors;
  if(!maxSide || std::max(w,h)<=maxSide)return 0;
  unsigned nw=std::max(1U,unsigned(std::lround(w*double(maxSide)/std::max(w,h)))),nh=std::max(1U,unsigned(std::lround(h*double(maxSide)/std::max(w,h))));
  try {
    auto wx=weights(w,nw),wy=weights(h,nh);
    std::vector<float> temp(size_t(nw)*h*c);
    auto *input=reinterpret_cast<const unsigned short*>(old->data);
    for(unsigned y=0;y<h;y++)for(unsigned x=0;x<nw;x++)for(unsigned channel=0;channel<c;channel++) {
      double sum=0;for(auto &weight:wx[x])sum+=input[(size_t(y)*w+weight.index)*c+channel]*weight.value;
      temp[(size_t(y)*nw+x)*c+channel]=sum;
    }
    size_t length=size_t(nw)*nh*c*2;
    auto *result=static_cast<libraw_processed_image_t*>(std::malloc(sizeof(libraw_processed_image_t)+length));
    if(!result)throw std::bad_alloc();
    *result=*old;result->width=nw;result->height=nh;result->data_size=length;
    auto *output=reinterpret_cast<unsigned short*>(result->data);
    for(unsigned y=0;y<nh;y++)for(unsigned x=0;x<nw;x++)for(unsigned channel=0;channel<c;channel++) {
      double sum=0;for(auto &weight:wy[y])sum+=temp[(size_t(weight.index)*nw+x)*c+channel]*weight.value;
      output[(size_t(y)*nw+x)*c+channel]=std::clamp(std::lround(sum),0L,65535L);
    }
    LibRaw::dcraw_clear_mem(old);ctx->image=result;return 0;
  } catch(...) {ctx->error="Not enough memory to resize this RAW image. Choose Half resolution or a smaller file.";return -1;}
}
// Convert linear sRGB to the exact IEC 61966-2-1 transfer curve. The full 16-bit
// lookup avoids an 8-bit canvas and the approximate BT.709 curve used by dcraw.
EMSCRIPTEN_KEEPALIVE int raw_srgb(RawContext *ctx) {
  if(!ctx || !ctx->image) return -1;
  std::array<unsigned short,65536> curve;
  for(unsigned i=0;i<65536;i++) {double v=i/65535.0;curve[i]=static_cast<unsigned short>(std::lround(65535.0*(v<=0.0031308 ? 12.92*v : 1.055*std::pow(v,1/2.4)-0.055)));}
  auto *p=reinterpret_cast<unsigned short*>(ctx->image->data);
  for(unsigned i=0;i<ctx->image->data_size/2;i++)p[i]=curve[p[i]];
  return 0;
}
EMSCRIPTEN_KEEPALIVE unsigned raw_width(RawContext *ctx) {return ctx->image ? ctx->image->width : ctx->width;}
EMSCRIPTEN_KEEPALIVE unsigned raw_height(RawContext *ctx) {return ctx->image ? ctx->image->height : ctx->height;}
EMSCRIPTEN_KEEPALIVE unsigned raw_channels(RawContext *ctx) {return ctx->image ? ctx->image->colors : 0;}
EMSCRIPTEN_KEEPALIVE unsigned raw_length(RawContext *ctx) {return ctx->image ? ctx->image->data_size : 0;}
EMSCRIPTEN_KEEPALIVE unsigned char *raw_pixels(RawContext *ctx) {return ctx->image ? ctx->image->data : nullptr;}
EMSCRIPTEN_KEEPALIVE unsigned raw_count(RawContext *ctx) {return ctx->count;}
EMSCRIPTEN_KEEPALIVE unsigned raw_warnings(RawContext *ctx) {return ctx->warnings;}
EMSCRIPTEN_KEEPALIVE const char *raw_error(RawContext *ctx) {return ctx->error.c_str();}
EMSCRIPTEN_KEEPALIVE const char *raw_make(RawContext *ctx) {return ctx->make.c_str();}
EMSCRIPTEN_KEEPALIVE const char *raw_model(RawContext *ctx) {return ctx->model.c_str();}
EMSCRIPTEN_KEEPALIVE const char *raw_version() {return LibRaw::version();}
EMSCRIPTEN_KEEPALIVE void raw_destroy(RawContext *ctx) {delete ctx;}
}
