/*
 *  Copyright 1994-2022 Olivier Girondel
 *  Copyright 2019-2022 Tavasti
 *
 *  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/>.
 */

/* Plugin idea: show only pixels that differ more than MIN_DIFFERENCE
   from reference picture */


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


#define MAX_DIFFERENCE 110 /* how much color value has to differ from initial
                             picture to be shown. This value is use when not
                             in beat */

#define MIN_DIFFERENCE 20  /* at highest beat, how much difference to inital
                              is required */
#define CURVE_BEAT     10  /* decrement to difference on beat */
#define CURVE_VOL_MIN  0.05
#define CURVE_VOL_STEP 0.1
#define CURVE_VOL_MULT 1.7
#define CURVE_START    2   /* CURVE_START * CURVE_VOL_MULT needs to be > 2,
                              so we need at least 2 */

uint32_t version = 0;
uint32_t options = BO_GFX | BO_LENS | BO_SFX | BO_WEBCAM | BO_NORANDOM;
char desc[] = "Show cam pic which differs, react beat";
char dname[] = "TV diff beat";

enum LayerMode mode = LM_OVERLAY;


void
run(Context_t *ctx)
{
  int diff = CURVE_START;

  if (ctx->input->on_beat) {
    double peak;
    for (peak = ctx->input->curpeak; peak > CURVE_VOL_MIN; peak -= CURVE_VOL_STEP) {
      diff *= CURVE_VOL_MULT;
    }
    diff += CURVE_BEAT;
  }
  diff = MAX_DIFFERENCE - diff;
  if (diff < MIN_DIFFERENCE) {
    diff = MIN_DIFFERENCE;
  }

  Pixel_t *src1, *start, *src2, *dst;
  dst = start = passive_buffer(ctx)->buffer;

  if (!xpthread_mutex_lock(&ctx->cam_mtx[ctx->cam])) {
    src1 = ctx->cam_save[ctx->cam][0]->buffer;
    src2 = ctx->cam_ref0[ctx->cam]->buffer;
    for (; dst < start + BUFFSIZE * sizeof(Pixel_t); src1++, src2++, dst++) {
      if (((*src1 - *src2) > diff) ||
          ((*src2 - *src1) > diff) ) {
        *dst = *src1;
      } else {
        *dst = 0;
      }
    }
    xpthread_mutex_unlock(&ctx->cam_mtx[ctx->cam]);
  }
}
