/*
 *  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 | BO_VER;
enum LayerMode mode = LM_OVERLAY;
char desc[] = "Vertical stereo spectrum";
char dname[] = "Spectrum stereo 2";

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 * MAXY, 0, MAXY);
    v_end[k]   = float_to_nearest_ushort(log1p((float)k) / logf(10.0) / da_log * MAXY, 0, MAXY); /* 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, xe;

      /* left => left channel */
      top = float_to_nearest_ushort(HWIDTH * ctx->input->spectrum_log[A_LEFT][i]* volume_scale, 0, HWIDTH);
      for (xe = 0; xe < top; xe++) {
        Pixel_t color = (Pixel_t)floor((float)xe / top * 255.0);
        v_line_nc(dst, HWIDTH + xe, v_start[i], v_end[i], color);
      }

      /* right => right channel */
      top = float_to_nearest_ushort(HWIDTH * ctx->input->spectrum_log[A_RIGHT][i] * volume_scale, 0, HWIDTH);
      for (xe = 0; xe < top; xe++) {
        Pixel_t color = (Pixel_t)floor((float)xe / top * 255.0);
        v_line_nc(dst, HWIDTH - xe, v_start[i], v_end[i], color);
      }
    }
    xpthread_mutex_unlock(&ctx->input->mutex);
  }
}
