/*
 *  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/>.
 */

#include "context.h"
#include "spectrum.h"
#include "pthread_utils.h"


uint32_t version = 0;
uint32_t options = BO_SFX | BO_SCHEMES;
enum LayerMode mode = LM_OVERLAY;
char dname[] = "Spectrum";
char desc[] = "Display the spectrum";


static uint16_t *v_start = NULL, *v_end = NULL;


void
on_switch_on(Context_t *ctx)
{
  /* Initialize parameters */
  volume_scale = 1;
}


int8_t
create(Context_t *ctx)
{
  uint16_t k;
  float da_log;

  v_start = xcalloc(ctx->input->spectrum_size, sizeof(uint16_t));
  v_end   = xcalloc(ctx->input->spectrum_size, sizeof(uint16_t));

  da_log = logf(ctx->input->spectrum_size - 1) / logf(10.0);
  for (k = 1; k < ctx->input->spectrum_size; k++) {
    v_start[k] = float_to_nearest_ushort( logf((float) k) / logf(10.0) / da_log * MAXX, 0, MAXX);
    v_end[k]   = float_to_nearest_ushort(log1p((float) k) / logf(10.0) / da_log * MAXX, 0, MAXX); /* log1p(x)=logf(x+1) */
  }

  return 1;
}


void
destroy(Context_t *ctx)
{
  xfree(v_start);
  xfree(v_end);
}


void
run(Context_t *ctx)
{
  Buffer8_t *dst;
  uint16_t i;

  dst = passive_buffer(ctx);
  Buffer8_clear(dst);

  if (!xpthread_mutex_lock(&ctx->input->mutex)) {
    for (i = 1; i < ctx->input->spectrum_size; i++) {
      uint16_t top, ye;

      top = float_to_nearest_ushort(MAXY * ctx->input->spectrum_log[A_MONO][i] * volume_scale, 0, MAXY);
      for (ye = 0; ye < top; ye++) {
        Pixel_t color = (Pixel_t)floor((float)ye / top * 255.0);
        h_line_nc(dst, ye, v_start[i], v_end[i], color);
      }
    }
    xpthread_mutex_unlock(&ctx->input->mutex);
  }
}
