/*
 *  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/>.
 */
/*
 * EffecTV - Realtime Digital Video Effector
 * Copyright (C) 2001-2006 FUKUCHI Kentaro
 *
 * PredatorTV - makes incoming objects invisible like the Predator.
 * Copyright (C) 2001-2002 FUKUCHI Kentaro
 *
 */

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


uint32_t version = 0;
uint32_t options = BO_GFX | BO_WEBCAM | BO_NORANDOM | BO_SCHEMES;
char desc[] = "PredatorTV plugin from the EffecTV project";
char dname[] = "TV predator";

enum LayerMode mode = LM_OVERLAY;

#define MAGIC_THRESHOLD 40

static Buffer8_t *diff = NULL;


int8_t
create(Context_t *ctx)
{
  diff = Buffer8_new();

  return 1;
}


void
destroy(Context_t *ctx)
{
  Buffer8_delete(diff);
}


void
on_switch_on(Context_t *ctx)
{
  ctx->ref_taken[ctx->cam] = 0;
}


void
run(Context_t *ctx)
{
  Buffer8_t *src1;
  Buffer8_t *src2;
  Pixel_t *d, *src;
  Pixel_t *dst;
  uint16_t x, y;

  if (!xpthread_mutex_lock(&ctx->cam_mtx[ctx->cam])) {
    src1 = ctx->cam_save[ctx->cam][0];
    src2 = ctx->cam_ref[ctx->cam];
    Buffer8_substract_y(src1, src2, MAGIC_THRESHOLD, diff);

    d = diff->buffer;

    dst = passive_buffer(ctx)->buffer;
    dst += WIDTH * sizeof(Pixel_t);
    d += WIDTH * sizeof(Pixel_t);
    src = ctx->cam_ref[ctx->cam]->buffer + (WIDTH * sizeof(Pixel_t));

    for (y = 1; y < MAXY; y++) {
      for (x = 0; x < WIDTH; x++) {
        if (*d) {
          *dst = src[4] & 0xfc;
        } else {
          *dst = *src;
        }

        d++;
        src++;
        dst++;
      }
    }
    xpthread_mutex_unlock(&ctx->cam_mtx[ctx->cam]);
  }
}
