<commit_before>/*
 * Copyright (c) 2015 Intel Corporation
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice (including the next
 * paragraph) shall be included in all copies or substantial portions of the
 * Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 */

/**
 * \file lower_shared_reference.cpp
 *
 * IR lower pass to replace dereferences of compute shader shared variables
 * with intrinsic function calls.
 *
 * This relieves drivers of the responsibility of allocating space for the
 * shared variables in the shared memory region.
 */

#include "lower_buffer_access.h"
#include "ir_builder.h"
#include "main/macros.h"
#include "util/list.h"
#include "glsl_parser_extras.h"

using namespace ir_builder;

namespace {

struct var_offset {
   struct list_head node;
   const ir_variable *var;
   unsigned offset;
};

class lower_shared_reference_visitor :
      public lower_buffer_access::lower_buffer_access {
public:

   lower_shared_reference_visitor(struct gl_shader *shader)
      : list_ctx(ralloc_context(NULL)), shader(shader), shared_size(0u)
   {
      list_inithead(&var_offsets);
   }

   ~lower_shared_reference_visitor()
   {
      ralloc_free(list_ctx);
   }

   enum {
      shared_load_access,
      shared_store_access,
      shared_atomic_access,
   } buffer_access_type;

   void insert_buffer_access(void *mem_ctx, ir_dereference *deref,
                             const glsl_type *type, ir_rvalue *offset,
                             unsigned mask, int channel);

   void handle_rvalue(ir_rvalue **rvalue);
   ir_visitor_status visit_enter(ir_assignment *ir);
   void handle_assignment(ir_assignment *ir);

   unsigned get_shared_offset(const ir_variable *);

   ir_call *shared_load(void *mem_ctx, const struct glsl_type *type,
                        ir_rvalue *offset);
   ir_call *shared_store(void *mem_ctx, ir_rvalue *deref, ir_rvalue *offset,
                         unsigned write_mask);

   void *list_ctx;
   struct gl_shader *shader;
   struct list_head var_offsets;
   unsigned shared_size;
   bool progress;
};

unsigned
lower_shared_reference_visitor::get_shared_offset(const ir_variable *var)
{
   list_for_each_entry(var_offset, var_entry, &var_offsets, node) {
      if (var_entry->var == var)
         return var_entry->offset;
   }

   struct var_offset *new_entry = rzalloc(list_ctx, struct var_offset);
   list_add(&new_entry->node, &var_offsets);
   new_entry->var = var;

   unsigned var_align = var->type->std430_base_alignment(false);
   new_entry->offset = glsl_align(shared_size, var_align);

   unsigned var_size = var->type->std430_size(false);
   shared_size = new_entry->offset + var_size;

   return new_entry->offset;
}

void
lower_shared_reference_visitor::handle_rvalue(ir_rvalue **rvalue)
{
   if (!*rvalue)
      return;

   ir_dereference *deref = (*rvalue)->as_dereference();
   if (!deref)
      return;

   ir_variable *var = deref->variable_referenced();
   if (!var || var->data.mode != ir_var_shader_shared)
      return;

   buffer_access_type = shared_load_access;

   void *mem_ctx = ralloc_parent(shader->ir);

   ir_rvalue *offset = NULL;
   unsigned const_offset = get_shared_offset(var);
   bool row_major;
   int matrix_columns;
   assert(var->get_interface_type() == NULL);
   const unsigned packing = GLSL_INTERFACE_PACKING_STD430;

   setup_buffer_access(mem_ctx, var, deref,
                       &offset, &const_offset,
                       &row_major, &matrix_columns, packing);

   /* Now that we've calculated the offset to the start of the
    * dereference, walk over the type and emit loads into a temporary.
    */
   const glsl_type *type = (*rvalue)->type;
   ir_variable *load_var = new(mem_ctx) ir_variable(type,
                                                    "shared_load_temp",
                                                    ir_var_temporary);
   base_ir->insert_before(load_var);

   ir_variable *load_offset = new(mem_ctx) ir_variable(glsl_type::uint_type,
                                                       "shared_load_temp_offset",
                                                       ir_var_temporary);
   base_ir->insert_before(load_offset);
   base_ir->insert_before(assign(load_offset, offset));

   deref = new(mem_ctx) ir_dereference_variable(load_var);

   emit_access(mem_ctx, false, deref, load_offset, const_offset, row_major,
               matrix_columns, packing, 0);

   *rvalue = deref;

   progress = true;
}

void
lower_shared_reference_visitor::handle_assignment(ir_assignment *ir)
{
   if (!ir || !ir->lhs)
      return;

   ir_rvalue *rvalue = ir->lhs->as_rvalue();
   if (!rvalue)
      return;

   ir_dereference *deref = ir->lhs->as_dereference();
   if (!deref)
      return;

   ir_variable *var = ir->lhs->variable_referenced();
   if (!var || var->data.mode != ir_var_shader_shared)
      return;

   buffer_access_type = shared_store_access;

   /* We have a write to a shared variable, so declare a temporary and rewrite
    * the assignment so that the temporary is the LHS.
    */
   void *mem_ctx = ralloc_parent(shader->ir);

   const glsl_type *type = rvalue->type;
   ir_variable *store_var = new(mem_ctx) ir_variable(type,
                                                     "shared_store_temp",
                                                     ir_var_temporary);
   base_ir->insert_before(store_var);
   ir->lhs = new(mem_ctx) ir_dereference_variable(store_var);

   ir_rvalue *offset = NULL;
   unsigned const_offset = get_shared_offset(var);
   bool row_major;
   int matrix_columns;
   assert(var->get_interface_type() == NULL);
   const unsigned packing = GLSL_INTERFACE_PACKING_STD430;

   setup_buffer_access(mem_ctx, var, deref,
                       &offset, &const_offset,
                       &row_major, &matrix_columns, packing);

   deref = new(mem_ctx) ir_dereference_variable(store_var);

   ir_variable *store_offset = new(mem_ctx) ir_variable(glsl_type::uint_type,
                                                        "shared_store_temp_offset",
                                                        ir_var_temporary);
   base_ir->insert_before(store_offset);
   base_ir->insert_before(assign(store_offset, offset));

   /* Now we have to write the value assigned to the temporary back to memory */
   emit_access(mem_ctx, true, deref, store_offset, const_offset, row_major,
               matrix_columns, packing, ir->write_mask);

   progress = true;
}

ir_visitor_status
lower_shared_reference_visitor::visit_enter(ir_assignment *ir)
{
   handle_assignment(ir);
   return rvalue_visit(ir);
}

void
lower_shared_reference_visitor::insert_buffer_access(void *mem_ctx,
                                                     ir_dereference *deref,
                                                     const glsl_type *type,
                                                     ir_rvalue *offset,
                                                     unsigned mask,
                                                     int channel)
{
   if (buffer_access_type == shared_store_access) {
      ir_call *store = shared_store(mem_ctx, deref, offset, mask);
      base_ir->insert_after(store);
   } else {
      ir_call *load = shared_load(mem_ctx, type, offset);
      base_ir->insert_before(load);
      ir_rvalue *value = load->return_deref->as_rvalue()->clone(mem_ctx, NULL);
      base_ir->insert_before(assign(deref->clone(mem_ctx, NULL),
                                    value));
   }
}

static bool
compute_shader_enabled(const _mesa_glsl_parse_state *state)
{
   return state->stage == MESA_SHADER_COMPUTE;
}

ir_call *
lower_shared_reference_visitor::shared_store(void *mem_ctx,
                                             ir_rvalue *deref,
                                             ir_rvalue *offset,
                                             unsigned write_mask)
{
   exec_list sig_params;

   ir_variable *offset_ref = new(mem_ctx)
      ir_variable(glsl_type::uint_type, "offset" , ir_var_function_in);
   sig_params.push_tail(offset_ref);

   ir_variable *val_ref = new(mem_ctx)
      ir_variable(deref->type, "value" , ir_var_function_in);
   sig_params.push_tail(val_ref);

   ir_variable *writemask_ref = new(mem_ctx)
      ir_variable(glsl_type::uint_type, "write_mask" , ir_var_function_in);
   sig_params.push_tail(writemask_ref);

   ir_function_signature *sig = new(mem_ctx)
      ir_function_signature(glsl_type::void_type, compute_shader_enabled);
   assert(sig);
   sig->replace_parameters(&sig_params);
   sig->is_intrinsic = true;

   ir_function *f = new(mem_ctx) ir_function("__intrinsic_store_shared");
   f->add_signature(sig);

   exec_list call_params;
   call_params.push_tail(offset->clone(mem_ctx, NULL));
   call_params.push_tail(deref->clone(mem_ctx, NULL));
   call_params.push_tail(new(mem_ctx) ir_constant(write_mask));
   return new(mem_ctx) ir_call(sig, NULL, &call_params);
}

ir_call *
lower_shared_reference_visitor::shared_load(void *mem_ctx,
                                            const struct glsl_type *type,
                                            ir_rvalue *offset)
{
   exec_list sig_params;

   ir_variable *offset_ref = new(mem_ctx)
      ir_variable(glsl_type::uint_type, "offset_ref" , ir_var_function_in);
   sig_params.push_tail(offset_ref);

   ir_function_signature *sig =
      new(mem_ctx) ir_function_signature(type, compute_shader_enabled);
   assert(sig);
   sig->replace_parameters(&sig_params);
   sig->is_intrinsic = true;

   ir_function *f = new(mem_ctx) ir_function("__intrinsic_load_shared");
   f->add_signature(sig);

   ir_variable *result = new(mem_ctx)
      ir_variable(type, "shared_load_result", ir_var_temporary);
   base_ir->insert_before(result);
   ir_dereference_variable *deref_result = new(mem_ctx)
      ir_dereference_variable(result);

   exec_list call_params;
   call_params.push_tail(offset->clone(mem_ctx, NULL));

   return new(mem_ctx) ir_call(sig, deref_result, &call_params);
}

} /* unnamed namespace */

void
lower_shared_reference(struct gl_shader *shader, unsigned *shared_size)
{
   if (shader->Stage != MESA_SHADER_COMPUTE)
      return;

   lower_shared_reference_visitor v(shader);

   /* Loop over the instructions lowering references, because we take a deref
    * of an shared variable array using a shared variable dereference as the
    * index will produce a collection of instructions all of which have cloned
    * shared variable dereferences for that array index.
    */
   do {
      v.progress = false;
      visit_list_elements(&v, shader->ir);
   } while (v.progress);

   *shared_size = v.shared_size;
}
<commit_msg>glsl: Translate atomic intrinsic functions on shared variables<commit_after>/*
 * Copyright (c) 2015 Intel Corporation
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice (including the next
 * paragraph) shall be included in all copies or substantial portions of the
 * Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 */

/**
 * \file lower_shared_reference.cpp
 *
 * IR lower pass to replace dereferences of compute shader shared variables
 * with intrinsic function calls.
 *
 * This relieves drivers of the responsibility of allocating space for the
 * shared variables in the shared memory region.
 */

#include "lower_buffer_access.h"
#include "ir_builder.h"
#include "main/macros.h"
#include "util/list.h"
#include "glsl_parser_extras.h"

using namespace ir_builder;

namespace {

struct var_offset {
   struct list_head node;
   const ir_variable *var;
   unsigned offset;
};

class lower_shared_reference_visitor :
      public lower_buffer_access::lower_buffer_access {
public:

   lower_shared_reference_visitor(struct gl_shader *shader)
      : list_ctx(ralloc_context(NULL)), shader(shader), shared_size(0u)
   {
      list_inithead(&var_offsets);
   }

   ~lower_shared_reference_visitor()
   {
      ralloc_free(list_ctx);
   }

   enum {
      shared_load_access,
      shared_store_access,
      shared_atomic_access,
   } buffer_access_type;

   void insert_buffer_access(void *mem_ctx, ir_dereference *deref,
                             const glsl_type *type, ir_rvalue *offset,
                             unsigned mask, int channel);

   void handle_rvalue(ir_rvalue **rvalue);
   ir_visitor_status visit_enter(ir_assignment *ir);
   void handle_assignment(ir_assignment *ir);

   ir_call *lower_shared_atomic_intrinsic(ir_call *ir);
   ir_call *check_for_shared_atomic_intrinsic(ir_call *ir);
   ir_visitor_status visit_enter(ir_call *ir);

   unsigned get_shared_offset(const ir_variable *);

   ir_call *shared_load(void *mem_ctx, const struct glsl_type *type,
                        ir_rvalue *offset);
   ir_call *shared_store(void *mem_ctx, ir_rvalue *deref, ir_rvalue *offset,
                         unsigned write_mask);

   void *list_ctx;
   struct gl_shader *shader;
   struct list_head var_offsets;
   unsigned shared_size;
   bool progress;
};

unsigned
lower_shared_reference_visitor::get_shared_offset(const ir_variable *var)
{
   list_for_each_entry(var_offset, var_entry, &var_offsets, node) {
      if (var_entry->var == var)
         return var_entry->offset;
   }

   struct var_offset *new_entry = rzalloc(list_ctx, struct var_offset);
   list_add(&new_entry->node, &var_offsets);
   new_entry->var = var;

   unsigned var_align = var->type->std430_base_alignment(false);
   new_entry->offset = glsl_align(shared_size, var_align);

   unsigned var_size = var->type->std430_size(false);
   shared_size = new_entry->offset + var_size;

   return new_entry->offset;
}

void
lower_shared_reference_visitor::handle_rvalue(ir_rvalue **rvalue)
{
   if (!*rvalue)
      return;

   ir_dereference *deref = (*rvalue)->as_dereference();
   if (!deref)
      return;

   ir_variable *var = deref->variable_referenced();
   if (!var || var->data.mode != ir_var_shader_shared)
      return;

   buffer_access_type = shared_load_access;

   void *mem_ctx = ralloc_parent(shader->ir);

   ir_rvalue *offset = NULL;
   unsigned const_offset = get_shared_offset(var);
   bool row_major;
   int matrix_columns;
   assert(var->get_interface_type() == NULL);
   const unsigned packing = GLSL_INTERFACE_PACKING_STD430;

   setup_buffer_access(mem_ctx, var, deref,
                       &offset, &const_offset,
                       &row_major, &matrix_columns, packing);

   /* Now that we've calculated the offset to the start of the
    * dereference, walk over the type and emit loads into a temporary.
    */
   const glsl_type *type = (*rvalue)->type;
   ir_variable *load_var = new(mem_ctx) ir_variable(type,
                                                    "shared_load_temp",
                                                    ir_var_temporary);
   base_ir->insert_before(load_var);

   ir_variable *load_offset = new(mem_ctx) ir_variable(glsl_type::uint_type,
                                                       "shared_load_temp_offset",
                                                       ir_var_temporary);
   base_ir->insert_before(load_offset);
   base_ir->insert_before(assign(load_offset, offset));

   deref = new(mem_ctx) ir_dereference_variable(load_var);

   emit_access(mem_ctx, false, deref, load_offset, const_offset, row_major,
               matrix_columns, packing, 0);

   *rvalue = deref;

   progress = true;
}

void
lower_shared_reference_visitor::handle_assignment(ir_assignment *ir)
{
   if (!ir || !ir->lhs)
      return;

   ir_rvalue *rvalue = ir->lhs->as_rvalue();
   if (!rvalue)
      return;

   ir_dereference *deref = ir->lhs->as_dereference();
   if (!deref)
      return;

   ir_variable *var = ir->lhs->variable_referenced();
   if (!var || var->data.mode != ir_var_shader_shared)
      return;

   buffer_access_type = shared_store_access;

   /* We have a write to a shared variable, so declare a temporary and rewrite
    * the assignment so that the temporary is the LHS.
    */
   void *mem_ctx = ralloc_parent(shader->ir);

   const glsl_type *type = rvalue->type;
   ir_variable *store_var = new(mem_ctx) ir_variable(type,
                                                     "shared_store_temp",
                                                     ir_var_temporary);
   base_ir->insert_before(store_var);
   ir->lhs = new(mem_ctx) ir_dereference_variable(store_var);

   ir_rvalue *offset = NULL;
   unsigned const_offset = get_shared_offset(var);
   bool row_major;
   int matrix_columns;
   assert(var->get_interface_type() == NULL);
   const unsigned packing = GLSL_INTERFACE_PACKING_STD430;

   setup_buffer_access(mem_ctx, var, deref,
                       &offset, &const_offset,
                       &row_major, &matrix_columns, packing);

   deref = new(mem_ctx) ir_dereference_variable(store_var);

   ir_variable *store_offset = new(mem_ctx) ir_variable(glsl_type::uint_type,
                                                        "shared_store_temp_offset",
                                                        ir_var_temporary);
   base_ir->insert_before(store_offset);
   base_ir->insert_before(assign(store_offset, offset));

   /* Now we have to write the value assigned to the temporary back to memory */
   emit_access(mem_ctx, true, deref, store_offset, const_offset, row_major,
               matrix_columns, packing, ir->write_mask);

   progress = true;
}

ir_visitor_status
lower_shared_reference_visitor::visit_enter(ir_assignment *ir)
{
   handle_assignment(ir);
   return rvalue_visit(ir);
}

void
lower_shared_reference_visitor::insert_buffer_access(void *mem_ctx,
                                                     ir_dereference *deref,
                                                     const glsl_type *type,
                                                     ir_rvalue *offset,
                                                     unsigned mask,
                                                     int channel)
{
   if (buffer_access_type == shared_store_access) {
      ir_call *store = shared_store(mem_ctx, deref, offset, mask);
      base_ir->insert_after(store);
   } else {
      ir_call *load = shared_load(mem_ctx, type, offset);
      base_ir->insert_before(load);
      ir_rvalue *value = load->return_deref->as_rvalue()->clone(mem_ctx, NULL);
      base_ir->insert_before(assign(deref->clone(mem_ctx, NULL),
                                    value));
   }
}

static bool
compute_shader_enabled(const _mesa_glsl_parse_state *state)
{
   return state->stage == MESA_SHADER_COMPUTE;
}

ir_call *
lower_shared_reference_visitor::shared_store(void *mem_ctx,
                                             ir_rvalue *deref,
                                             ir_rvalue *offset,
                                             unsigned write_mask)
{
   exec_list sig_params;

   ir_variable *offset_ref = new(mem_ctx)
      ir_variable(glsl_type::uint_type, "offset" , ir_var_function_in);
   sig_params.push_tail(offset_ref);

   ir_variable *val_ref = new(mem_ctx)
      ir_variable(deref->type, "value" , ir_var_function_in);
   sig_params.push_tail(val_ref);

   ir_variable *writemask_ref = new(mem_ctx)
      ir_variable(glsl_type::uint_type, "write_mask" , ir_var_function_in);
   sig_params.push_tail(writemask_ref);

   ir_function_signature *sig = new(mem_ctx)
      ir_function_signature(glsl_type::void_type, compute_shader_enabled);
   assert(sig);
   sig->replace_parameters(&sig_params);
   sig->is_intrinsic = true;

   ir_function *f = new(mem_ctx) ir_function("__intrinsic_store_shared");
   f->add_signature(sig);

   exec_list call_params;
   call_params.push_tail(offset->clone(mem_ctx, NULL));
   call_params.push_tail(deref->clone(mem_ctx, NULL));
   call_params.push_tail(new(mem_ctx) ir_constant(write_mask));
   return new(mem_ctx) ir_call(sig, NULL, &call_params);
}

ir_call *
lower_shared_reference_visitor::shared_load(void *mem_ctx,
                                            const struct glsl_type *type,
                                            ir_rvalue *offset)
{
   exec_list sig_params;

   ir_variable *offset_ref = new(mem_ctx)
      ir_variable(glsl_type::uint_type, "offset_ref" , ir_var_function_in);
   sig_params.push_tail(offset_ref);

   ir_function_signature *sig =
      new(mem_ctx) ir_function_signature(type, compute_shader_enabled);
   assert(sig);
   sig->replace_parameters(&sig_params);
   sig->is_intrinsic = true;

   ir_function *f = new(mem_ctx) ir_function("__intrinsic_load_shared");
   f->add_signature(sig);

   ir_variable *result = new(mem_ctx)
      ir_variable(type, "shared_load_result", ir_var_temporary);
   base_ir->insert_before(result);
   ir_dereference_variable *deref_result = new(mem_ctx)
      ir_dereference_variable(result);

   exec_list call_params;
   call_params.push_tail(offset->clone(mem_ctx, NULL));

   return new(mem_ctx) ir_call(sig, deref_result, &call_params);
}

/* Lowers the intrinsic call to a new internal intrinsic that swaps the access
 * to the shared variable in the first parameter by an offset. This involves
 * creating the new internal intrinsic (i.e. the new function signature).
 */
ir_call *
lower_shared_reference_visitor::lower_shared_atomic_intrinsic(ir_call *ir)
{
   /* Shared atomics usually have 2 parameters, the shared variable and an
    * integer argument. The exception is CompSwap, that has an additional
    * integer parameter.
    */
   int param_count = ir->actual_parameters.length();
   assert(param_count == 2 || param_count == 3);

   /* First argument must be a scalar integer shared variable */
   exec_node *param = ir->actual_parameters.get_head();
   ir_instruction *inst = (ir_instruction *) param;
   assert(inst->ir_type == ir_type_dereference_variable ||
          inst->ir_type == ir_type_dereference_array ||
          inst->ir_type == ir_type_dereference_record ||
          inst->ir_type == ir_type_swizzle);

   ir_rvalue *deref = (ir_rvalue *) inst;
   assert(deref->type->is_scalar() && deref->type->is_integer());

   ir_variable *var = deref->variable_referenced();
   assert(var);

   /* Compute the offset to the start if the dereference
    */
   void *mem_ctx = ralloc_parent(shader->ir);

   ir_rvalue *offset = NULL;
   unsigned const_offset = get_shared_offset(var);
   bool row_major;
   int matrix_columns;
   assert(var->get_interface_type() == NULL);
   const unsigned packing = GLSL_INTERFACE_PACKING_STD430;
   buffer_access_type = shared_atomic_access;

   setup_buffer_access(mem_ctx, var, deref,
                       &offset, &const_offset,
                       &row_major, &matrix_columns, packing);

   assert(offset);
   assert(!row_major);
   assert(matrix_columns == 1);

   ir_rvalue *deref_offset =
      add(offset, new(mem_ctx) ir_constant(const_offset));

   /* Create the new internal function signature that will take an offset
    * instead of a shared variable
    */
   exec_list sig_params;
   ir_variable *sig_param = new(mem_ctx)
      ir_variable(glsl_type::uint_type, "offset" , ir_var_function_in);
   sig_params.push_tail(sig_param);

   const glsl_type *type = deref->type->base_type == GLSL_TYPE_INT ?
      glsl_type::int_type : glsl_type::uint_type;
   sig_param = new(mem_ctx)
         ir_variable(type, "data1", ir_var_function_in);
   sig_params.push_tail(sig_param);

   if (param_count == 3) {
      sig_param = new(mem_ctx)
            ir_variable(type, "data2", ir_var_function_in);
      sig_params.push_tail(sig_param);
   }

   ir_function_signature *sig =
      new(mem_ctx) ir_function_signature(deref->type,
                                         compute_shader_enabled);
   assert(sig);
   sig->replace_parameters(&sig_params);
   sig->is_intrinsic = true;

   char func_name[64];
   sprintf(func_name, "%s_shared", ir->callee_name());
   ir_function *f = new(mem_ctx) ir_function(func_name);
   f->add_signature(sig);

   /* Now, create the call to the internal intrinsic */
   exec_list call_params;
   call_params.push_tail(deref_offset);
   param = ir->actual_parameters.get_head()->get_next();
   ir_rvalue *param_as_rvalue = ((ir_instruction *) param)->as_rvalue();
   call_params.push_tail(param_as_rvalue->clone(mem_ctx, NULL));
   if (param_count == 3) {
      param = param->get_next();
      param_as_rvalue = ((ir_instruction *) param)->as_rvalue();
      call_params.push_tail(param_as_rvalue->clone(mem_ctx, NULL));
   }
   ir_dereference_variable *return_deref =
      ir->return_deref->clone(mem_ctx, NULL);
   return new(mem_ctx) ir_call(sig, return_deref, &call_params);
}

ir_call *
lower_shared_reference_visitor::check_for_shared_atomic_intrinsic(ir_call *ir)
{
   exec_list& params = ir->actual_parameters;

   if (params.length() < 2 || params.length() > 3)
      return ir;

   ir_rvalue *rvalue =
      ((ir_instruction *) params.get_head())->as_rvalue();
   if (!rvalue)
      return ir;

   ir_variable *var = rvalue->variable_referenced();
   if (!var || var->data.mode != ir_var_shader_shared)
      return ir;

   const char *callee = ir->callee_name();
   if (!strcmp("__intrinsic_atomic_add", callee) ||
       !strcmp("__intrinsic_atomic_min", callee) ||
       !strcmp("__intrinsic_atomic_max", callee) ||
       !strcmp("__intrinsic_atomic_and", callee) ||
       !strcmp("__intrinsic_atomic_or", callee) ||
       !strcmp("__intrinsic_atomic_xor", callee) ||
       !strcmp("__intrinsic_atomic_exchange", callee) ||
       !strcmp("__intrinsic_atomic_comp_swap", callee)) {
      return lower_shared_atomic_intrinsic(ir);
   }

   return ir;
}

ir_visitor_status
lower_shared_reference_visitor::visit_enter(ir_call *ir)
{
   ir_call *new_ir = check_for_shared_atomic_intrinsic(ir);
   if (new_ir != ir) {
      progress = true;
      base_ir->replace_with(new_ir);
      return visit_continue_with_parent;
   }

   return rvalue_visit(ir);
}

} /* unnamed namespace */

void
lower_shared_reference(struct gl_shader *shader, unsigned *shared_size)
{
   if (shader->Stage != MESA_SHADER_COMPUTE)
      return;

   lower_shared_reference_visitor v(shader);

   /* Loop over the instructions lowering references, because we take a deref
    * of an shared variable array using a shared variable dereference as the
    * index will produce a collection of instructions all of which have cloned
    * shared variable dereferences for that array index.
    */
   do {
      v.progress = false;
      visit_list_elements(&v, shader->ir);
   } while (v.progress);

   *shared_size = v.shared_size;
}
<|endoftext|>


<commit_before>/*
 * Copyright 2015 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "SkGpuDevice.h"
#include "GrBlurUtils.h"
#include "GrCaps.h"
#include "GrColorSpaceXform.h"
#include "GrRenderTargetContext.h"
#include "GrStyle.h"
#include "GrTextureAdjuster.h"
#include "GrTextureMaker.h"
#include "SkDraw.h"
#include "SkGr.h"
#include "SkMaskFilter.h"
#include "effects/GrBicubicEffect.h"
#include "effects/GrSimpleTextureEffect.h"
#include "effects/GrTextureDomain.h"

static inline bool use_shader(bool textureIsAlphaOnly, const SkPaint& paint) {
    return textureIsAlphaOnly && paint.getShader();
}

//////////////////////////////////////////////////////////////////////////////
//  Helper functions for dropping src rect constraint in bilerp mode.

static const SkScalar kColorBleedTolerance = 0.001f;

static bool has_aligned_samples(const SkRect& srcRect, const SkRect& transformedRect) {
    // detect pixel disalignment
    if (SkScalarAbs(SkScalarRoundToScalar(transformedRect.left()) - transformedRect.left()) < kColorBleedTolerance &&
        SkScalarAbs(SkScalarRoundToScalar(transformedRect.top())  - transformedRect.top())  < kColorBleedTolerance &&
        SkScalarAbs(transformedRect.width()  - srcRect.width())  < kColorBleedTolerance &&
        SkScalarAbs(transformedRect.height() - srcRect.height()) < kColorBleedTolerance) {
        return true;
    }
    return false;
}

static bool may_color_bleed(const SkRect& srcRect,
                            const SkRect& transformedRect,
                            const SkMatrix& m,
                            GrFSAAType fsaaType) {
    // Only gets called if has_aligned_samples returned false.
    // So we can assume that sampling is axis aligned but not texel aligned.
    SkASSERT(!has_aligned_samples(srcRect, transformedRect));
    SkRect innerSrcRect(srcRect), innerTransformedRect, outerTransformedRect(transformedRect);
    if (GrFSAAType::kUnifiedMSAA == fsaaType) {
        innerSrcRect.inset(SK_Scalar1, SK_Scalar1);
    } else {
        innerSrcRect.inset(SK_ScalarHalf, SK_ScalarHalf);
    }
    m.mapRect(&innerTransformedRect, innerSrcRect);

    // The gap between outerTransformedRect and innerTransformedRect
    // represents the projection of the source border area, which is
    // problematic for color bleeding.  We must check whether any
    // destination pixels sample the border area.
    outerTransformedRect.inset(kColorBleedTolerance, kColorBleedTolerance);
    innerTransformedRect.outset(kColorBleedTolerance, kColorBleedTolerance);
    SkIRect outer, inner;
    outerTransformedRect.round(&outer);
    innerTransformedRect.round(&inner);
    // If the inner and outer rects round to the same result, it means the
    // border does not overlap any pixel centers. Yay!
    return inner != outer;
}

static bool can_ignore_bilerp_constraint(const GrTextureProducer& producer,
                                         const SkRect& srcRect,
                                         const SkMatrix& srcRectToDeviceSpace,
                                         GrFSAAType fsaaType) {
    if (srcRectToDeviceSpace.rectStaysRect()) {
        // sampling is axis-aligned
        SkRect transformedRect;
        srcRectToDeviceSpace.mapRect(&transformedRect, srcRect);

        if (has_aligned_samples(srcRect, transformedRect) ||
            !may_color_bleed(srcRect, transformedRect, srcRectToDeviceSpace, fsaaType)) {
            return true;
        }
    }
    return false;
}

/**
 * Checks whether the paint, matrix, and constraint are compatible with using
 * GrRenderTargetContext::drawTextureAffine. It is more effecient than the GrTextureProducer
 * general case.
 */
static bool can_use_draw_texture_affine(const SkPaint& paint, const SkMatrix& ctm,
                                        SkCanvas::SrcRectConstraint constraint) {
    return (!paint.getColorFilter() && !paint.getShader() && !paint.getMaskFilter() &&
            !paint.getImageFilter() && paint.getFilterQuality() < kMedium_SkFilterQuality &&
            paint.getBlendMode() == SkBlendMode::kSrcOver && !ctm.hasPerspective() &&
            SkCanvas::kFast_SrcRectConstraint == constraint);
}

static void draw_texture_affine(const SkPaint& paint, const SkMatrix& ctm, const SkRect* src,
                                const SkRect* dst, GrAA aa, sk_sp<GrTextureProxy> proxy,
                                SkColorSpace* colorSpace, const GrClip& clip,
                                GrRenderTargetContext* rtc) {
    SkASSERT(!(SkToBool(src) && !SkToBool(dst)));
    SkRect srcRect = src ? *src : SkRect::MakeWH(proxy->width(), proxy->height());
    SkRect dstRect = dst ? *dst : srcRect;
    if (src && !SkRect::MakeIWH(proxy->width(), proxy->height()).contains(srcRect)) {
        // Shrink the src rect to be within bounds and proportionately shrink the dst rect.
        SkMatrix srcToDst;
        srcToDst.setRectToRect(srcRect, dstRect, SkMatrix::kFill_ScaleToFit);
        SkAssertResult(srcRect.intersect(SkRect::MakeIWH(proxy->width(), proxy->height())));
        srcToDst.mapRect(&dstRect, srcRect);
    }
    auto csxf = GrColorSpaceXform::Make(colorSpace, proxy->config(),
                                        rtc->colorSpaceInfo().colorSpace());
    GrSamplerState::Filter filter;
    switch (paint.getFilterQuality()) {
        case kNone_SkFilterQuality:
            filter = GrSamplerState::Filter::kNearest;
            break;
        case kLow_SkFilterQuality:
            filter = GrSamplerState::Filter::kBilerp;
            break;
        case kMedium_SkFilterQuality:
        case kHigh_SkFilterQuality:
            SK_ABORT("Quality level not allowed.");
    }
    GrColor color = GrPixelConfigIsAlphaOnly(proxy->config())
                            ? SkColorToPremulGrColor(paint.getColor())
                            : SkColorAlphaToGrColor(paint.getColor());
    rtc->drawTextureAffine(clip, std::move(proxy), filter, color, srcRect, dstRect, aa, ctm,
                           std::move(csxf));
}

//////////////////////////////////////////////////////////////////////////////

void SkGpuDevice::drawPinnedTextureProxy(sk_sp<GrTextureProxy> proxy, uint32_t pinnedUniqueID,
                                         SkColorSpace* colorSpace, SkAlphaType alphaType,
                                         const SkRect* srcRect, const SkRect* dstRect,
                                         SkCanvas::SrcRectConstraint constraint,
                                         const SkMatrix& viewMatrix, const SkPaint& paint) {
    if (can_use_draw_texture_affine(paint, this->ctm(), constraint)) {
        draw_texture_affine(paint, viewMatrix, srcRect, dstRect, GrAA(paint.isAntiAlias()),
                            std::move(proxy), colorSpace, this->clip(), fRenderTargetContext.get());
        return;
    }
    GrTextureAdjuster adjuster(this->context(), std::move(proxy), alphaType, pinnedUniqueID,
                               colorSpace);
    this->drawTextureProducer(&adjuster, srcRect, dstRect, constraint, viewMatrix, paint);
}

void SkGpuDevice::drawTextureMaker(GrTextureMaker* maker, int imageW, int imageH,
                                   const SkRect* srcRect, const SkRect* dstRect,
                                   SkCanvas::SrcRectConstraint constraint,
                                   const SkMatrix& viewMatrix, const SkPaint& paint) {
    if (can_use_draw_texture_affine(paint, viewMatrix, constraint)) {
        sk_sp<SkColorSpace> cs;
        // We've done enough checks above to allow us to pass ClampNearest() and not check for
        // scaling adjustments.
        auto proxy = maker->refTextureProxyForParams(
                GrSamplerState::ClampNearest(), fRenderTargetContext->colorSpaceInfo().colorSpace(),
                &cs, nullptr);
        if (!proxy) {
            return;
        }
        draw_texture_affine(paint, viewMatrix, srcRect, dstRect, GrAA(paint.isAntiAlias()),
                            std::move(proxy), cs.get(), this->clip(), fRenderTargetContext.get());
        return;
    }
    this->drawTextureProducer(maker, srcRect, dstRect, constraint, viewMatrix, paint);
}

void SkGpuDevice::drawTextureProducer(GrTextureProducer* producer,
                                      const SkRect* srcRect,
                                      const SkRect* dstRect,
                                      SkCanvas::SrcRectConstraint constraint,
                                      const SkMatrix& viewMatrix,
                                      const SkPaint& paint) {
    // This is the funnel for all non-tiled bitmap/image draw calls. Log a histogram entry.
    SK_HISTOGRAM_BOOLEAN("DrawTiled", false);

    // Figure out the actual dst and src rect by clipping the src rect to the bounds of the
    // adjuster. If the src rect is clipped then the dst rect must be recomputed. Also determine
    // the matrix that maps the src rect to the dst rect.
    SkRect clippedSrcRect;
    SkRect clippedDstRect;
    const SkRect srcBounds = SkRect::MakeIWH(producer->width(), producer->height());
    SkMatrix srcToDstMatrix;
    if (srcRect) {
        if (!dstRect) {
            dstRect = &srcBounds;
        }
        if (!srcBounds.contains(*srcRect)) {
            clippedSrcRect = *srcRect;
            if (!clippedSrcRect.intersect(srcBounds)) {
                return;
            }
            if (!srcToDstMatrix.setRectToRect(*srcRect, *dstRect, SkMatrix::kFill_ScaleToFit)) {
                return;
            }
            srcToDstMatrix.mapRect(&clippedDstRect, clippedSrcRect);
        } else {
            clippedSrcRect = *srcRect;
            clippedDstRect = *dstRect;
            if (!srcToDstMatrix.setRectToRect(*srcRect, *dstRect, SkMatrix::kFill_ScaleToFit)) {
                return;
            }
        }
    } else {
        clippedSrcRect = srcBounds;
        if (dstRect) {
            clippedDstRect = *dstRect;
            if (!srcToDstMatrix.setRectToRect(srcBounds, *dstRect, SkMatrix::kFill_ScaleToFit)) {
                return;
            }
        } else {
            clippedDstRect = srcBounds;
            srcToDstMatrix.reset();
        }
    }

    // Now that we have both the view and srcToDst matrices, log our scale factor.
    LogDrawScaleFactor(SkMatrix::Concat(viewMatrix, srcToDstMatrix), paint.getFilterQuality());

    this->drawTextureProducerImpl(producer, clippedSrcRect, clippedDstRect, constraint, viewMatrix,
                                  srcToDstMatrix, paint);
}

void SkGpuDevice::drawTextureProducerImpl(GrTextureProducer* producer,
                                          const SkRect& clippedSrcRect,
                                          const SkRect& clippedDstRect,
                                          SkCanvas::SrcRectConstraint constraint,
                                          const SkMatrix& viewMatrix,
                                          const SkMatrix& srcToDstMatrix,
                                          const SkPaint& paint) {
    // Specifying the texture coords as local coordinates is an attempt to enable more GrDrawOp
    // combining by not baking anything about the srcRect, dstRect, or viewMatrix, into the texture
    // FP. In the future this should be an opaque optimization enabled by the combination of
    // GrDrawOp/GP and FP.
    const SkMaskFilter* mf = paint.getMaskFilter();
    // The shader expects proper local coords, so we can't replace local coords with texture coords
    // if the shader will be used. If we have a mask filter we will change the underlying geometry
    // that is rendered.
    bool canUseTextureCoordsAsLocalCoords = !use_shader(producer->isAlphaOnly(), paint) && !mf;

    bool doBicubic;
    GrSamplerState::Filter fm = GrSkFilterQualityToGrFilterMode(
            paint.getFilterQuality(), viewMatrix, srcToDstMatrix, &doBicubic);
    const GrSamplerState::Filter* filterMode = doBicubic ? nullptr : &fm;

    GrTextureProducer::FilterConstraint constraintMode;
    if (SkCanvas::kFast_SrcRectConstraint == constraint) {
        constraintMode = GrTextureAdjuster::kNo_FilterConstraint;
    } else {
        constraintMode = GrTextureAdjuster::kYes_FilterConstraint;
    }

    // If we have to outset for AA then we will generate texture coords outside the src rect. The
    // same happens for any mask filter that extends the bounds rendered in the dst.
    // This is conservative as a mask filter does not have to expand the bounds rendered.
    bool coordsAllInsideSrcRect = !paint.isAntiAlias() && !mf;

    // Check for optimization to drop the src rect constraint when on bilerp.
    if (filterMode && GrSamplerState::Filter::kBilerp == *filterMode &&
        GrTextureAdjuster::kYes_FilterConstraint == constraintMode && coordsAllInsideSrcRect) {
        SkMatrix combinedMatrix;
        combinedMatrix.setConcat(viewMatrix, srcToDstMatrix);
        if (can_ignore_bilerp_constraint(*producer, clippedSrcRect, combinedMatrix,
                                         fRenderTargetContext->fsaaType())) {
            constraintMode = GrTextureAdjuster::kNo_FilterConstraint;
        }
    }

    const SkMatrix* textureMatrix;
    SkMatrix tempMatrix;
    if (canUseTextureCoordsAsLocalCoords) {
        textureMatrix = &SkMatrix::I();
    } else {
        if (!srcToDstMatrix.invert(&tempMatrix)) {
            return;
        }
        textureMatrix = &tempMatrix;
    }
    auto fp = producer->createFragmentProcessor(
            *textureMatrix, clippedSrcRect, constraintMode, coordsAllInsideSrcRect, filterMode,
            fRenderTargetContext->colorSpaceInfo().colorSpace());
    if (!fp) {
        return;
    }

    GrPaint grPaint;
    if (!SkPaintToGrPaintWithTexture(fContext.get(), fRenderTargetContext->colorSpaceInfo(), paint,
                                     viewMatrix, std::move(fp), producer->isAlphaOnly(),
                                     &grPaint)) {
        return;
    }
    GrAA aa = GrAA(paint.isAntiAlias());
    if (canUseTextureCoordsAsLocalCoords) {
        fRenderTargetContext->fillRectToRect(this->clip(), std::move(grPaint), aa, viewMatrix,
                                             clippedDstRect, clippedSrcRect);
        return;
    }

    if (!mf) {
        fRenderTargetContext->drawRect(this->clip(), std::move(grPaint), aa, viewMatrix,
                                       clippedDstRect);
        return;
    }

    // First see if we can do the draw + mask filter direct to the dst.
    if (viewMatrix.isScaleTranslate()) {
        SkRect devClippedDstRect;
        viewMatrix.mapRectScaleTranslate(&devClippedDstRect, clippedDstRect);

        SkStrokeRec rec(SkStrokeRec::kFill_InitStyle);
        if (mf->directFilterRRectMaskGPU(fContext.get(),
                                         fRenderTargetContext.get(),
                                         std::move(grPaint),
                                         this->clip(),
                                         viewMatrix,
                                         rec,
                                         SkRRect::MakeRect(clippedDstRect),
                                         SkRRect::MakeRect(devClippedDstRect))) {
            return;
        }
    }

    SkPath rectPath;
    rectPath.addRect(clippedDstRect);
    rectPath.setIsVolatile(true);
    GrBlurUtils::drawPathWithMaskFilter(this->context(), fRenderTargetContext.get(), this->clip(),
                                        rectPath, std::move(grPaint), aa, viewMatrix, mf,
                                        GrStyle::SimpleFill(), true);
}
<commit_msg>Add macro to disable using GrTextureOp for AA in Chrome<commit_after>/*
 * Copyright 2015 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "SkGpuDevice.h"
#include "GrBlurUtils.h"
#include "GrCaps.h"
#include "GrColorSpaceXform.h"
#include "GrRenderTargetContext.h"
#include "GrStyle.h"
#include "GrTextureAdjuster.h"
#include "GrTextureMaker.h"
#include "SkDraw.h"
#include "SkGr.h"
#include "SkMaskFilter.h"
#include "effects/GrBicubicEffect.h"
#include "effects/GrSimpleTextureEffect.h"
#include "effects/GrTextureDomain.h"

static inline bool use_shader(bool textureIsAlphaOnly, const SkPaint& paint) {
    return textureIsAlphaOnly && paint.getShader();
}

//////////////////////////////////////////////////////////////////////////////
//  Helper functions for dropping src rect constraint in bilerp mode.

static const SkScalar kColorBleedTolerance = 0.001f;

static bool has_aligned_samples(const SkRect& srcRect, const SkRect& transformedRect) {
    // detect pixel disalignment
    if (SkScalarAbs(SkScalarRoundToScalar(transformedRect.left()) - transformedRect.left()) < kColorBleedTolerance &&
        SkScalarAbs(SkScalarRoundToScalar(transformedRect.top())  - transformedRect.top())  < kColorBleedTolerance &&
        SkScalarAbs(transformedRect.width()  - srcRect.width())  < kColorBleedTolerance &&
        SkScalarAbs(transformedRect.height() - srcRect.height()) < kColorBleedTolerance) {
        return true;
    }
    return false;
}

static bool may_color_bleed(const SkRect& srcRect,
                            const SkRect& transformedRect,
                            const SkMatrix& m,
                            GrFSAAType fsaaType) {
    // Only gets called if has_aligned_samples returned false.
    // So we can assume that sampling is axis aligned but not texel aligned.
    SkASSERT(!has_aligned_samples(srcRect, transformedRect));
    SkRect innerSrcRect(srcRect), innerTransformedRect, outerTransformedRect(transformedRect);
    if (GrFSAAType::kUnifiedMSAA == fsaaType) {
        innerSrcRect.inset(SK_Scalar1, SK_Scalar1);
    } else {
        innerSrcRect.inset(SK_ScalarHalf, SK_ScalarHalf);
    }
    m.mapRect(&innerTransformedRect, innerSrcRect);

    // The gap between outerTransformedRect and innerTransformedRect
    // represents the projection of the source border area, which is
    // problematic for color bleeding.  We must check whether any
    // destination pixels sample the border area.
    outerTransformedRect.inset(kColorBleedTolerance, kColorBleedTolerance);
    innerTransformedRect.outset(kColorBleedTolerance, kColorBleedTolerance);
    SkIRect outer, inner;
    outerTransformedRect.round(&outer);
    innerTransformedRect.round(&inner);
    // If the inner and outer rects round to the same result, it means the
    // border does not overlap any pixel centers. Yay!
    return inner != outer;
}

static bool can_ignore_bilerp_constraint(const GrTextureProducer& producer,
                                         const SkRect& srcRect,
                                         const SkMatrix& srcRectToDeviceSpace,
                                         GrFSAAType fsaaType) {
    if (srcRectToDeviceSpace.rectStaysRect()) {
        // sampling is axis-aligned
        SkRect transformedRect;
        srcRectToDeviceSpace.mapRect(&transformedRect, srcRect);

        if (has_aligned_samples(srcRect, transformedRect) ||
            !may_color_bleed(srcRect, transformedRect, srcRectToDeviceSpace, fsaaType)) {
            return true;
        }
    }
    return false;
}

/**
 * Checks whether the paint, matrix, and constraint are compatible with using
 * GrRenderTargetContext::drawTextureAffine. It is more effecient than the GrTextureProducer
 * general case.
 */
static bool can_use_draw_texture_affine(const SkPaint& paint, GrAA aa, const SkMatrix& ctm,
                                        SkCanvas::SrcRectConstraint constraint) {
// This is disabled in Chrome until crbug.com/802408 and crbug.com/801783 can be sorted out.
#ifdef SK_DISABLE_TEXTURE_OP_AA
    if (GrAA::kYes == aa) {
        return false;
    }
#endif
    return (!paint.getColorFilter() && !paint.getShader() && !paint.getMaskFilter() &&
            !paint.getImageFilter() && paint.getFilterQuality() < kMedium_SkFilterQuality &&
            paint.getBlendMode() == SkBlendMode::kSrcOver && !ctm.hasPerspective() &&
            SkCanvas::kFast_SrcRectConstraint == constraint);
}

static void draw_texture_affine(const SkPaint& paint, const SkMatrix& ctm, const SkRect* src,
                                const SkRect* dst, GrAA aa, sk_sp<GrTextureProxy> proxy,
                                SkColorSpace* colorSpace, const GrClip& clip,
                                GrRenderTargetContext* rtc) {
    SkASSERT(!(SkToBool(src) && !SkToBool(dst)));
    SkRect srcRect = src ? *src : SkRect::MakeWH(proxy->width(), proxy->height());
    SkRect dstRect = dst ? *dst : srcRect;
    if (src && !SkRect::MakeIWH(proxy->width(), proxy->height()).contains(srcRect)) {
        // Shrink the src rect to be within bounds and proportionately shrink the dst rect.
        SkMatrix srcToDst;
        srcToDst.setRectToRect(srcRect, dstRect, SkMatrix::kFill_ScaleToFit);
        SkAssertResult(srcRect.intersect(SkRect::MakeIWH(proxy->width(), proxy->height())));
        srcToDst.mapRect(&dstRect, srcRect);
    }
    auto csxf = GrColorSpaceXform::Make(colorSpace, proxy->config(),
                                        rtc->colorSpaceInfo().colorSpace());
    GrSamplerState::Filter filter;
    switch (paint.getFilterQuality()) {
        case kNone_SkFilterQuality:
            filter = GrSamplerState::Filter::kNearest;
            break;
        case kLow_SkFilterQuality:
            filter = GrSamplerState::Filter::kBilerp;
            break;
        case kMedium_SkFilterQuality:
        case kHigh_SkFilterQuality:
            SK_ABORT("Quality level not allowed.");
    }
    GrColor color = GrPixelConfigIsAlphaOnly(proxy->config())
                            ? SkColorToPremulGrColor(paint.getColor())
                            : SkColorAlphaToGrColor(paint.getColor());
    rtc->drawTextureAffine(clip, std::move(proxy), filter, color, srcRect, dstRect, aa, ctm,
                           std::move(csxf));
}

//////////////////////////////////////////////////////////////////////////////

void SkGpuDevice::drawPinnedTextureProxy(sk_sp<GrTextureProxy> proxy, uint32_t pinnedUniqueID,
                                         SkColorSpace* colorSpace, SkAlphaType alphaType,
                                         const SkRect* srcRect, const SkRect* dstRect,
                                         SkCanvas::SrcRectConstraint constraint,
                                         const SkMatrix& viewMatrix, const SkPaint& paint) {
    GrAA aa = GrAA(paint.isAntiAlias());
    if (can_use_draw_texture_affine(paint, aa, this->ctm(), constraint)) {
        draw_texture_affine(paint, viewMatrix, srcRect, dstRect, aa, std::move(proxy), colorSpace,
                            this->clip(), fRenderTargetContext.get());
        return;
    }
    GrTextureAdjuster adjuster(this->context(), std::move(proxy), alphaType, pinnedUniqueID,
                               colorSpace);
    this->drawTextureProducer(&adjuster, srcRect, dstRect, constraint, viewMatrix, paint);
}

void SkGpuDevice::drawTextureMaker(GrTextureMaker* maker, int imageW, int imageH,
                                   const SkRect* srcRect, const SkRect* dstRect,
                                   SkCanvas::SrcRectConstraint constraint,
                                   const SkMatrix& viewMatrix, const SkPaint& paint) {
    GrAA aa = GrAA(paint.isAntiAlias());
    if (can_use_draw_texture_affine(paint, aa, viewMatrix, constraint)) {
        sk_sp<SkColorSpace> cs;
        // We've done enough checks above to allow us to pass ClampNearest() and not check for
        // scaling adjustments.
        auto proxy = maker->refTextureProxyForParams(
                GrSamplerState::ClampNearest(), fRenderTargetContext->colorSpaceInfo().colorSpace(),
                &cs, nullptr);
        if (!proxy) {
            return;
        }
        draw_texture_affine(paint, viewMatrix, srcRect, dstRect, aa, std::move(proxy), cs.get(),
                            this->clip(), fRenderTargetContext.get());
        return;
    }
    this->drawTextureProducer(maker, srcRect, dstRect, constraint, viewMatrix, paint);
}

void SkGpuDevice::drawTextureProducer(GrTextureProducer* producer,
                                      const SkRect* srcRect,
                                      const SkRect* dstRect,
                                      SkCanvas::SrcRectConstraint constraint,
                                      const SkMatrix& viewMatrix,
                                      const SkPaint& paint) {
    // This is the funnel for all non-tiled bitmap/image draw calls. Log a histogram entry.
    SK_HISTOGRAM_BOOLEAN("DrawTiled", false);

    // Figure out the actual dst and src rect by clipping the src rect to the bounds of the
    // adjuster. If the src rect is clipped then the dst rect must be recomputed. Also determine
    // the matrix that maps the src rect to the dst rect.
    SkRect clippedSrcRect;
    SkRect clippedDstRect;
    const SkRect srcBounds = SkRect::MakeIWH(producer->width(), producer->height());
    SkMatrix srcToDstMatrix;
    if (srcRect) {
        if (!dstRect) {
            dstRect = &srcBounds;
        }
        if (!srcBounds.contains(*srcRect)) {
            clippedSrcRect = *srcRect;
            if (!clippedSrcRect.intersect(srcBounds)) {
                return;
            }
            if (!srcToDstMatrix.setRectToRect(*srcRect, *dstRect, SkMatrix::kFill_ScaleToFit)) {
                return;
            }
            srcToDstMatrix.mapRect(&clippedDstRect, clippedSrcRect);
        } else {
            clippedSrcRect = *srcRect;
            clippedDstRect = *dstRect;
            if (!srcToDstMatrix.setRectToRect(*srcRect, *dstRect, SkMatrix::kFill_ScaleToFit)) {
                return;
            }
        }
    } else {
        clippedSrcRect = srcBounds;
        if (dstRect) {
            clippedDstRect = *dstRect;
            if (!srcToDstMatrix.setRectToRect(srcBounds, *dstRect, SkMatrix::kFill_ScaleToFit)) {
                return;
            }
        } else {
            clippedDstRect = srcBounds;
            srcToDstMatrix.reset();
        }
    }

    // Now that we have both the view and srcToDst matrices, log our scale factor.
    LogDrawScaleFactor(SkMatrix::Concat(viewMatrix, srcToDstMatrix), paint.getFilterQuality());

    this->drawTextureProducerImpl(producer, clippedSrcRect, clippedDstRect, constraint, viewMatrix,
                                  srcToDstMatrix, paint);
}

void SkGpuDevice::drawTextureProducerImpl(GrTextureProducer* producer,
                                          const SkRect& clippedSrcRect,
                                          const SkRect& clippedDstRect,
                                          SkCanvas::SrcRectConstraint constraint,
                                          const SkMatrix& viewMatrix,
                                          const SkMatrix& srcToDstMatrix,
                                          const SkPaint& paint) {
    // Specifying the texture coords as local coordinates is an attempt to enable more GrDrawOp
    // combining by not baking anything about the srcRect, dstRect, or viewMatrix, into the texture
    // FP. In the future this should be an opaque optimization enabled by the combination of
    // GrDrawOp/GP and FP.
    const SkMaskFilter* mf = paint.getMaskFilter();
    // The shader expects proper local coords, so we can't replace local coords with texture coords
    // if the shader will be used. If we have a mask filter we will change the underlying geometry
    // that is rendered.
    bool canUseTextureCoordsAsLocalCoords = !use_shader(producer->isAlphaOnly(), paint) && !mf;

    bool doBicubic;
    GrSamplerState::Filter fm = GrSkFilterQualityToGrFilterMode(
            paint.getFilterQuality(), viewMatrix, srcToDstMatrix, &doBicubic);
    const GrSamplerState::Filter* filterMode = doBicubic ? nullptr : &fm;

    GrTextureProducer::FilterConstraint constraintMode;
    if (SkCanvas::kFast_SrcRectConstraint == constraint) {
        constraintMode = GrTextureAdjuster::kNo_FilterConstraint;
    } else {
        constraintMode = GrTextureAdjuster::kYes_FilterConstraint;
    }

    // If we have to outset for AA then we will generate texture coords outside the src rect. The
    // same happens for any mask filter that extends the bounds rendered in the dst.
    // This is conservative as a mask filter does not have to expand the bounds rendered.
    bool coordsAllInsideSrcRect = !paint.isAntiAlias() && !mf;

    // Check for optimization to drop the src rect constraint when on bilerp.
    if (filterMode && GrSamplerState::Filter::kBilerp == *filterMode &&
        GrTextureAdjuster::kYes_FilterConstraint == constraintMode && coordsAllInsideSrcRect) {
        SkMatrix combinedMatrix;
        combinedMatrix.setConcat(viewMatrix, srcToDstMatrix);
        if (can_ignore_bilerp_constraint(*producer, clippedSrcRect, combinedMatrix,
                                         fRenderTargetContext->fsaaType())) {
            constraintMode = GrTextureAdjuster::kNo_FilterConstraint;
        }
    }

    const SkMatrix* textureMatrix;
    SkMatrix tempMatrix;
    if (canUseTextureCoordsAsLocalCoords) {
        textureMatrix = &SkMatrix::I();
    } else {
        if (!srcToDstMatrix.invert(&tempMatrix)) {
            return;
        }
        textureMatrix = &tempMatrix;
    }
    auto fp = producer->createFragmentProcessor(
            *textureMatrix, clippedSrcRect, constraintMode, coordsAllInsideSrcRect, filterMode,
            fRenderTargetContext->colorSpaceInfo().colorSpace());
    if (!fp) {
        return;
    }

    GrPaint grPaint;
    if (!SkPaintToGrPaintWithTexture(fContext.get(), fRenderTargetContext->colorSpaceInfo(), paint,
                                     viewMatrix, std::move(fp), producer->isAlphaOnly(),
                                     &grPaint)) {
        return;
    }
    GrAA aa = GrAA(paint.isAntiAlias());
    if (canUseTextureCoordsAsLocalCoords) {
        fRenderTargetContext->fillRectToRect(this->clip(), std::move(grPaint), aa, viewMatrix,
                                             clippedDstRect, clippedSrcRect);
        return;
    }

    if (!mf) {
        fRenderTargetContext->drawRect(this->clip(), std::move(grPaint), aa, viewMatrix,
                                       clippedDstRect);
        return;
    }

    // First see if we can do the draw + mask filter direct to the dst.
    if (viewMatrix.isScaleTranslate()) {
        SkRect devClippedDstRect;
        viewMatrix.mapRectScaleTranslate(&devClippedDstRect, clippedDstRect);

        SkStrokeRec rec(SkStrokeRec::kFill_InitStyle);
        if (mf->directFilterRRectMaskGPU(fContext.get(),
                                         fRenderTargetContext.get(),
                                         std::move(grPaint),
                                         this->clip(),
                                         viewMatrix,
                                         rec,
                                         SkRRect::MakeRect(clippedDstRect),
                                         SkRRect::MakeRect(devClippedDstRect))) {
            return;
        }
    }

    SkPath rectPath;
    rectPath.addRect(clippedDstRect);
    rectPath.setIsVolatile(true);
    GrBlurUtils::drawPathWithMaskFilter(this->context(), fRenderTargetContext.get(), this->clip(),
                                        rectPath, std::move(grPaint), aa, viewMatrix, mf,
                                        GrStyle::SimpleFill(), true);
}
<|endoftext|>


<commit_before>/****************************************************************************
 *
 *   Copyright (c) 2017 PX4 Development Team. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 * 3. Neither the name PX4 nor the names of its contributors may be
 *    used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 ****************************************************************************/

/**
 * @file flight_taks.h
 *
 * Library class to hold and manage all implemented flight task instances
 *
 * @author Matthias Grob <maetugr@gmail.com>
 */

#pragma once

#include "tasks/FlightTask.hpp"
#include "tasks/FlightTaskManual.hpp"
#include "tasks/FlightTaskOrbit.hpp"

#include "SubscriptionArray.hpp"

#include <new>

class FlightTasks : control::SuperBlock
{
public:
	FlightTasks() :
		SuperBlock(nullptr, "TSK")
	{};

	~FlightTasks()
	{
		if (_current_task) {
			_current_task->~FlightTask();
		}
	};

	/**
	 * Call regularly in the control loop cycle to execute the task
	 * @return 0 on success, <0 on error
	 */
	int update()
	{
		if (is_any_task_active()) {
			_subscription_array.update();
			return _current_task->update();
		}

		return 1;
	}

	/**
	 * Get the output data from the current task
	 */
	const vehicle_local_position_setpoint_s &get_position_setpoint()
	{
		return _current_task->get_position_setpoint();
	}

	/**
	 * Call this function initially to point all tasks to the general output data
	 */
	inline const vehicle_local_position_setpoint_s &operator()()
	{
		return get_position_setpoint();
	}

	/**
	 * Switch to the next task in the available list (for testing)
	 * @return 0 on success, <0 on error
	 */
	int switch_task()
	{
		return switch_task(_current_task_index + 1);
	}

	/**
	 * Switch to a specific task (for normal usage)
	 * @param task number to switch to
	 * @return 0 on success, <0 on error
	 */
	int switch_task(int task_number)
	{
		/* switch to the running task, nothing to do */
		if (task_number == _current_task_index) {
			return 0;
		}

		/* disable the old task if there is any */
		if (_current_task) {
			_current_task->~FlightTask();
			_current_task = nullptr;
			_current_task_index = -1;
		}

		switch (task_number) {
		case 0:
			_current_task = new (&_task_union.manual) FlightTaskManual(this, "MAN");
			break;

		case 1:
			_current_task = new (&_task_union.orbit) FlightTaskOrbit(this, "ORB");
			break;

		default:
			/* invalid task */
			return -1;
		}

		if (!_current_task->initializeSubscriptions(_subscription_array)) {
			_current_task->~FlightTask();
			_current_task = nullptr;
			_current_task_index = -1;
			return -2;
		}

		_subscription_array.update();

		if (_current_task->activate()) {
			_current_task->~FlightTask();
			_current_task = nullptr;
			_current_task_index = -1;
			return -3;
		}

		_subscription_array.forcedUpdate(); // make sure data is available for all new subscriptions

		_current_task_index = task_number;
		return 0;
	}

	/**
	 * Get the number of the active task
	 * @return number of active task, -1 if there is none
	 */
	int get_active_task() const { return _current_task_index; };

	/**
	 * Check if any task is active
	 * @return true if a task is active, false if not
	 */
	bool is_any_task_active() const { return _current_task; };

	/**
	 * Check if the task number exists
	 * @return true if yes, false if not
	 */
	bool is_task_number_valid(int task_number) const { return task_number > -1 && task_number < _task_count; };

private:
	static constexpr int _task_count = 2;

	/** union with all existing tasks: we use it to make sure that only the memory of the largest existing
	 * task is needed, and to avoid using dynamic memory allocations.
	 */
	union TaskUnion {
		TaskUnion() {}
		~TaskUnion() {}

		FlightTaskManual manual;
		FlightTaskOrbit orbit;
	};
	TaskUnion _task_union; ///< storage for the currently active task

	FlightTask *_current_task = nullptr;
	int _current_task_index = -1;

	SubscriptionArray _subscription_array;
};
<commit_msg>FlightTasks: use forced update just after initialization<commit_after>/****************************************************************************
 *
 *   Copyright (c) 2017 PX4 Development Team. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 * 3. Neither the name PX4 nor the names of its contributors may be
 *    used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 ****************************************************************************/

/**
 * @file flight_taks.h
 *
 * Library class to hold and manage all implemented flight task instances
 *
 * @author Matthias Grob <maetugr@gmail.com>
 */

#pragma once

#include "tasks/FlightTask.hpp"
#include "tasks/FlightTaskManual.hpp"
#include "tasks/FlightTaskOrbit.hpp"

#include "SubscriptionArray.hpp"

#include <new>

class FlightTasks : control::SuperBlock
{
public:
	FlightTasks() :
		SuperBlock(nullptr, "TSK")
	{};

	~FlightTasks()
	{
		if (_current_task) {
			_current_task->~FlightTask();
		}
	};

	/**
	 * Call regularly in the control loop cycle to execute the task
	 * @return 0 on success, <0 on error
	 */
	int update()
	{
		if (is_any_task_active()) {
			_subscription_array.update();
			return _current_task->update();
		}

		return 1;
	}

	/**
	 * Get the output data from the current task
	 */
	const vehicle_local_position_setpoint_s &get_position_setpoint()
	{
		return _current_task->get_position_setpoint();
	}

	/**
	 * Call this function initially to point all tasks to the general output data
	 */
	inline const vehicle_local_position_setpoint_s &operator()()
	{
		return get_position_setpoint();
	}

	/**
	 * Switch to the next task in the available list (for testing)
	 * @return 0 on success, <0 on error
	 */
	int switch_task()
	{
		return switch_task(_current_task_index + 1);
	}

	/**
	 * Switch to a specific task (for normal usage)
	 * @param task number to switch to
	 * @return 0 on success, <0 on error
	 */
	int switch_task(int task_number)
	{
		/* switch to the running task, nothing to do */
		if (task_number == _current_task_index) {
			return 0;
		}

		/* disable the old task if there is any */
		if (_current_task) {
			_current_task->~FlightTask();
			_current_task = nullptr;
			_current_task_index = -1;
		}

		switch (task_number) {
		case 0:
			_current_task = new (&_task_union.manual) FlightTaskManual(this, "MAN");
			break;

		case 1:
			_current_task = new (&_task_union.orbit) FlightTaskOrbit(this, "ORB");
			break;

		default:
			/* invalid task */
			return -1;
		}

		if (!_current_task->initializeSubscriptions(_subscription_array)) {
			_current_task->~FlightTask();
			_current_task = nullptr;
			_current_task_index = -1;
			return -2;
		}

		_subscription_array.forcedUpdate(); // make sure data is available for all new subscriptions

		if (_current_task->activate()) {
			_current_task->~FlightTask();
			_current_task = nullptr;
			_current_task_index = -1;
			return -3;
		}

		_current_task_index = task_number;
		return 0;
	}

	/**
	 * Get the number of the active task
	 * @return number of active task, -1 if there is none
	 */
	int get_active_task() const { return _current_task_index; };

	/**
	 * Check if any task is active
	 * @return true if a task is active, false if not
	 */
	bool is_any_task_active() const { return _current_task; };

	/**
	 * Check if the task number exists
	 * @return true if yes, false if not
	 */
	bool is_task_number_valid(int task_number) const { return task_number > -1 && task_number < _task_count; };

private:
	static constexpr int _task_count = 2;

	/** union with all existing tasks: we use it to make sure that only the memory of the largest existing
	 * task is needed, and to avoid using dynamic memory allocations.
	 */
	union TaskUnion {
		TaskUnion() {}
		~TaskUnion() {}

		FlightTaskManual manual;
		FlightTaskOrbit orbit;
	};
	TaskUnion _task_union; ///< storage for the currently active task

	FlightTask *_current_task = nullptr;
	int _current_task_index = -1;

	SubscriptionArray _subscription_array;
};
<|endoftext|>


<commit_before>/*
*
* Copyright 2015 Telefonica Investigacion y Desarrollo, S.A.U
*
* This file is part of Orion Context Broker.
*
* Orion Context Broker is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Orion Context Broker 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 Affero
* General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Orion Context Broker. If not, see http://www.gnu.org/licenses/.
*
* For those usages not covered by this license please contact with
* iot_support at tid dot es
*
* Author: Orion dev team
*/
#include <pthread.h>

#include "logMsg/logMsg.h"
#include "logMsg/traceLevels.h"

#include "common/globals.h"
#include "common/clockFunctions.h"
#include "common/statistics.h"
#include "common/limits.h"
#include "common/logTracing.h"
#include "alarmMgr/alarmMgr.h"

#include "cache/subCache.h"
#include "ngsi10/NotifyContextRequest.h"
#include "rest/httpRequestSend.h"
#include "ngsiNotify/QueueStatistics.h"
#include "ngsiNotify/QueueWorkers.h"

/* ****************************************************************************
*
* workerFunc - prototype
*/
static void* workerFunc(void* pSyncQ);

/* ****************************************************************************
*
* QueueWorkers::start() -
*/
int QueueWorkers::start()
{
  for (int i = 0; i < numberOfThreads; ++i)
  {
    pthread_t  tid;
    int        rc = pthread_create(&tid, NULL, workerFunc, pQueue);

    if (rc != 0)
    {
      LM_E(("Internal Error (pthread_create: %s)", strerror(errno)));
      return rc;
    }
    threadIds.push_back(tid);
  }

  return 0;
}

/* ****************************************************************************
*
* QueueWorkers::stop() -
*/
int QueueWorkers::stop()
{
  for (unsigned int ix = 0; ix < threadIds.size(); ++ix)
  {
    // FIXME PR: insert comment
    if (pthread_cancel(threadIds[ix]) != 0)
    {
      return -1;
    }
    pthread_join(threadIds[ix], NULL);
  }

  return 0;
}

/* ****************************************************************************
*
* workerFinish -
*
* This is invoked upon worker thread termination (typically using pthread_cancel on it)
*/
static void workerFinishes(void* curl)
{
  curl_easy_cleanup((CURL*) curl);
}

/* ****************************************************************************
*
* workerFunc -
*/
static void* workerFunc(void* pSyncQ)
{
  SyncQOverflow<std::vector<SenderThreadParams*>*>*  queue = (SyncQOverflow<std::vector<SenderThreadParams*>*> *) pSyncQ;
  CURL*                                              curl;

  // Initialize curl context
  curl = curl_easy_init();

  if (curl == NULL)
  {
    LM_E(("Runtime Error (curl_easy_init)"));
    pthread_exit(NULL);
  }

  // FIXME PR: insert comment
  // See: https://stackoverflow.com/questions/67872576/pthread-join-doesnt-return-on-a-just-cancelled-thread-with-pthread-cancel?noredirect=1#comment119968712_67872576
  pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);

  // Set pthread_cancel handler
  pthread_cleanup_push(workerFinishes, curl);

  for (;;)
  {
    std::vector<SenderThreadParams*>* paramsV = queue->pop();

    for (unsigned ix = 0; ix < paramsV->size(); ix++)
    {
      struct timespec     now;
      struct timespec     howlong;
      size_t              estimatedQSize;

      SenderThreadParams* params = (*paramsV)[ix];

      QueueStatistics::incOut();
      clock_gettime(CLOCK_REALTIME, &now);
      clock_difftime(&now, &params->timeStamp, &howlong);
      estimatedQSize = queue->size();
      QueueStatistics::addTimeInQWithSize(&howlong, estimatedQSize);

      strncpy(transactionId, params->transactionId, sizeof(transactionId));

      LM_T(LmtNotifier, ("worker sending to: host='%s', port=%d, verb=%s, tenant='%s', service-path: '%s', xauthToken: '%s', path='%s', content-type: %s",
                         params->ip.c_str(),
                         params->port,
                         params->verb.c_str(),
                         params->tenant.c_str(),
                         params->servicePath.c_str(),
                         params->xauthToken.c_str(),
                         params->resource.c_str(),
                         params->content_type.c_str()));

      char                portV[STRING_SIZE_FOR_INT];
      std::string         url;

      snprintf(portV, sizeof(portV), "%d", params->port);
      url = params->ip + ":" + portV + params->resource;

      long long    statusCode = -1;
      std::string  out;

      if (simulatedNotification)
      {
        LM_T(LmtNotifier, ("simulatedNotification is 'true', skipping outgoing request"));
        __sync_fetch_and_add(&noOfSimulatedNotifications, 1);
      }
      else // we'll send the notification
      {
        int          r;

        r =  httpRequestSendWithCurl(curl,
                                     params->from,
                                     params->ip,
                                     params->port,
                                     params->protocol,
                                     params->verb,
                                     params->tenant,
                                     params->servicePath,
                                     params->xauthToken,
                                     params->resource,
                                     params->content_type,
                                     params->content,
                                     params->fiwareCorrelator,
                                     params->renderFormat,
                                     &out,
                                     &statusCode,
                                     params->extraHeaders);

        //
        // FIXME: ok and error counter should be incremented in the other notification modes (generalizing the concept, i.e.
        // not as member of QueueStatistics:: which seems to be tied to just the threadpool notification mode)
        //
        if (r == 0)
        {
          __sync_fetch_and_add(&noOfNotificationsSent, 1);
          QueueStatistics::incSentOK();
          alarmMgr.notificationErrorReset(url);

          if (params->registration == false)
          {
            subNotificationErrorStatus(params->tenant, params->subscriptionId, 0, statusCode, "");
          }
        }
        else
        {
          QueueStatistics::incSentError();
          alarmMgr.notificationError(url, "notification failure for queue worker: " + out);

          if (params->registration == false)
          {
            subNotificationErrorStatus(params->tenant, params->subscriptionId, 1, -1, out);
          }
        }
      }

      // Add notificacion result summary in log INFO level
      if (statusCode != -1)
      {
        logInfoNotification(params->subscriptionId.c_str(), params->verb.c_str(), url.c_str(), statusCode);
      }
      else
      {
        logInfoNotification(params->subscriptionId.c_str(), params->verb.c_str(), url.c_str(), out.c_str());
      }

      // End transaction
      lmTransactionEnd();

      // Free params memory
      delete params;
    }

    // Free params vector memory
    delete paramsV;

    // Reset curl for next iteration
    curl_easy_reset(curl);
  }

  // Next statemement never executes but compilation breaks without it. See this note in pthread.h:
  // "pthread_cleanup_push and pthread_cleanup_pop are macros and must always be used in
  // matching pairs at the same nesting level of braces".
  pthread_cleanup_pop(0);
}
<commit_msg>FIX improve code comments<commit_after>/*
*
* Copyright 2015 Telefonica Investigacion y Desarrollo, S.A.U
*
* This file is part of Orion Context Broker.
*
* Orion Context Broker is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Orion Context Broker 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 Affero
* General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Orion Context Broker. If not, see http://www.gnu.org/licenses/.
*
* For those usages not covered by this license please contact with
* iot_support at tid dot es
*
* Author: Orion dev team
*/
#include <pthread.h>

#include "logMsg/logMsg.h"
#include "logMsg/traceLevels.h"

#include "common/globals.h"
#include "common/clockFunctions.h"
#include "common/statistics.h"
#include "common/limits.h"
#include "common/logTracing.h"
#include "alarmMgr/alarmMgr.h"

#include "cache/subCache.h"
#include "ngsi10/NotifyContextRequest.h"
#include "rest/httpRequestSend.h"
#include "ngsiNotify/QueueStatistics.h"
#include "ngsiNotify/QueueWorkers.h"

/* ****************************************************************************
*
* workerFunc - prototype
*/
static void* workerFunc(void* pSyncQ);

/* ****************************************************************************
*
* QueueWorkers::start() -
*/
int QueueWorkers::start()
{
  for (int i = 0; i < numberOfThreads; ++i)
  {
    pthread_t  tid;
    int        rc = pthread_create(&tid, NULL, workerFunc, pQueue);

    if (rc != 0)
    {
      LM_E(("Internal Error (pthread_create: %s)", strerror(errno)));
      return rc;
    }
    threadIds.push_back(tid);
  }

  return 0;
}

/* ****************************************************************************
*
* QueueWorkers::stop() -
*/
int QueueWorkers::stop()
{
  for (unsigned int ix = 0; ix < threadIds.size(); ++ix)
  {
    // FIXME #3877: this is not the best way of cancelling a thread in our case.
    // By the moment is not a problem (as the release is done only during the process
    // tear down phase) but if this gets dynamic at some moment (creation/destroying
    // pools by API) it needs to be changed
    if (pthread_cancel(threadIds[ix]) != 0)
    {
      return -1;
    }
    pthread_join(threadIds[ix], NULL);
  }

  return 0;
}

/* ****************************************************************************
*
* workerFinish -
*
* This is invoked upon worker thread termination (typically using pthread_cancel on it)
*/
static void workerFinishes(void* curl)
{
  curl_easy_cleanup((CURL*) curl);
}

/* ****************************************************************************
*
* workerFunc -
*/
static void* workerFunc(void* pSyncQ)
{
  SyncQOverflow<std::vector<SenderThreadParams*>*>*  queue = (SyncQOverflow<std::vector<SenderThreadParams*>*> *) pSyncQ;
  CURL*                                              curl;

  // Initialize curl context
  curl = curl_easy_init();

  if (curl == NULL)
  {
    LM_E(("Runtime Error (curl_easy_init)"));
    pthread_exit(NULL);
  }

  // FIXME #3877: this is not the best way of cancelling a thread in our case.
  // By the moment is not a problem (as the release is done only during the process
  // tear down phase) but if this gets dynamic at some moment (creation/destroying
  // pools by API) it needs to be changed
  pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);

  // Set pthread_cancel handler
  pthread_cleanup_push(workerFinishes, curl);

  for (;;)
  {
    std::vector<SenderThreadParams*>* paramsV = queue->pop();

    for (unsigned ix = 0; ix < paramsV->size(); ix++)
    {
      struct timespec     now;
      struct timespec     howlong;
      size_t              estimatedQSize;

      SenderThreadParams* params = (*paramsV)[ix];

      QueueStatistics::incOut();
      clock_gettime(CLOCK_REALTIME, &now);
      clock_difftime(&now, &params->timeStamp, &howlong);
      estimatedQSize = queue->size();
      QueueStatistics::addTimeInQWithSize(&howlong, estimatedQSize);

      strncpy(transactionId, params->transactionId, sizeof(transactionId));

      LM_T(LmtNotifier, ("worker sending to: host='%s', port=%d, verb=%s, tenant='%s', service-path: '%s', xauthToken: '%s', path='%s', content-type: %s",
                         params->ip.c_str(),
                         params->port,
                         params->verb.c_str(),
                         params->tenant.c_str(),
                         params->servicePath.c_str(),
                         params->xauthToken.c_str(),
                         params->resource.c_str(),
                         params->content_type.c_str()));

      char                portV[STRING_SIZE_FOR_INT];
      std::string         url;

      snprintf(portV, sizeof(portV), "%d", params->port);
      url = params->ip + ":" + portV + params->resource;

      long long    statusCode = -1;
      std::string  out;

      if (simulatedNotification)
      {
        LM_T(LmtNotifier, ("simulatedNotification is 'true', skipping outgoing request"));
        __sync_fetch_and_add(&noOfSimulatedNotifications, 1);
      }
      else // we'll send the notification
      {
        int          r;

        r =  httpRequestSendWithCurl(curl,
                                     params->from,
                                     params->ip,
                                     params->port,
                                     params->protocol,
                                     params->verb,
                                     params->tenant,
                                     params->servicePath,
                                     params->xauthToken,
                                     params->resource,
                                     params->content_type,
                                     params->content,
                                     params->fiwareCorrelator,
                                     params->renderFormat,
                                     &out,
                                     &statusCode,
                                     params->extraHeaders);

        //
        // FIXME: ok and error counter should be incremented in the other notification modes (generalizing the concept, i.e.
        // not as member of QueueStatistics:: which seems to be tied to just the threadpool notification mode)
        //
        if (r == 0)
        {
          __sync_fetch_and_add(&noOfNotificationsSent, 1);
          QueueStatistics::incSentOK();
          alarmMgr.notificationErrorReset(url);

          if (params->registration == false)
          {
            subNotificationErrorStatus(params->tenant, params->subscriptionId, 0, statusCode, "");
          }
        }
        else
        {
          QueueStatistics::incSentError();
          alarmMgr.notificationError(url, "notification failure for queue worker: " + out);

          if (params->registration == false)
          {
            subNotificationErrorStatus(params->tenant, params->subscriptionId, 1, -1, out);
          }
        }
      }

      // Add notificacion result summary in log INFO level
      if (statusCode != -1)
      {
        logInfoNotification(params->subscriptionId.c_str(), params->verb.c_str(), url.c_str(), statusCode);
      }
      else
      {
        logInfoNotification(params->subscriptionId.c_str(), params->verb.c_str(), url.c_str(), out.c_str());
      }

      // End transaction
      lmTransactionEnd();

      // Free params memory
      delete params;
    }

    // Free params vector memory
    delete paramsV;

    // Reset curl for next iteration
    curl_easy_reset(curl);
  }

  // Next statement never executes but compilation breaks without it. See this note in pthread.h:
  // "pthread_cleanup_push and pthread_cleanup_pop are macros and must always be used in
  // matching pairs at the same nesting level of braces".
  pthread_cleanup_pop(0);
}
<|endoftext|>


<commit_before>/*
This file is part of BGSLibrary.

BGSLibrary 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 3 of the License, or
(at your option) any later version.

BGSLibrary 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 BGSLibrary.  If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <opencv2/opencv.hpp>

#include "package_bgs/FrameDifferenceBGS.h"
#include "package_bgs/StaticFrameDifferenceBGS.h"
#include "package_bgs/WeightedMovingMeanBGS.h"
#include "package_bgs/WeightedMovingVarianceBGS.h"
#include "package_bgs/MixtureOfGaussianV1BGS.h"
#include "package_bgs/MixtureOfGaussianV2BGS.h"
#include "package_bgs/AdaptiveBackgroundLearning.h"
#include "package_bgs/AdaptiveSelectiveBackgroundLearning.h"

#if CV_MAJOR_VERSION >= 2 && CV_MINOR_VERSION >= 4 && CV_SUBMINOR_VERSION >= 3
#include "package_bgs/GMG.h"
#endif

#include "package_bgs/dp/DPAdaptiveMedianBGS.h"
#include "package_bgs/dp/DPGrimsonGMMBGS.h"
#include "package_bgs/dp/DPZivkovicAGMMBGS.h"
#include "package_bgs/dp/DPMeanBGS.h"
#include "package_bgs/dp/DPWrenGABGS.h"
#include "package_bgs/dp/DPPratiMediodBGS.h"
#include "package_bgs/dp/DPEigenbackgroundBGS.h"
#include "package_bgs/dp/DPTextureBGS.h"

#include "package_bgs/tb/T2FGMM_UM.h"
#include "package_bgs/tb/T2FGMM_UV.h"
#include "package_bgs/tb/T2FMRF_UM.h"
#include "package_bgs/tb/T2FMRF_UV.h"
#include "package_bgs/tb/FuzzySugenoIntegral.h"
#include "package_bgs/tb/FuzzyChoquetIntegral.h"

#include "package_bgs/lb/LBSimpleGaussian.h"
#include "package_bgs/lb/LBFuzzyGaussian.h"
#include "package_bgs/lb/LBMixtureOfGaussians.h"
#include "package_bgs/lb/LBAdaptiveSOM.h"
#include "package_bgs/lb/LBFuzzyAdaptiveSOM.h"

#include "package_bgs/ck/LbpMrf.h"
#include "package_bgs/jmo/MultiLayerBGS.h"
// The PBAS algorithm was removed from BGSLibrary because it is
// based on patented algorithm ViBE
// http://www2.ulg.ac.be/telecom/research/vibe/
//#include "package_bgs/pt/PixelBasedAdaptiveSegmenter.h"
#include "package_bgs/av/VuMeter.h"
#include "package_bgs/ae/KDE.h"
#include "package_bgs/db/IndependentMultimodalBGS.h"
#include "package_bgs/sjn/SJN_MultiCueBGS.h"
#include "package_bgs/bl/SigmaDeltaBGS.h"

#include "package_bgs/pl/SuBSENSE.h"
#include "package_bgs/pl/LOBSTER.h"

int main(int argc, char **argv)
{
  std::cout << "Using OpenCV " << CV_MAJOR_VERSION << "." << CV_MINOR_VERSION << "." << CV_SUBMINOR_VERSION << std::endl;

  CvCapture *capture = 0;
  int resize_factor = 100;

  if(argc > 1)
  {
    std::cout << "Openning: " << argv[1] << std::endl;
    capture = cvCaptureFromAVI(argv[1]);
  }
  else
  {
    capture = cvCaptureFromCAM(0);
    resize_factor = 50; // set size = 50% of original image
  }

  if(!capture)
  {
    std::cerr << "Cannot initialize video!" << std::endl;
    return -1;
  }

  IplImage *frame_aux = cvQueryFrame(capture);
  IplImage *frame = cvCreateImage(cvSize((int)((frame_aux->width*resize_factor)/100) , (int)((frame_aux->height*resize_factor)/100)), frame_aux->depth, frame_aux->nChannels);
  cvResize(frame_aux, frame);

  /* Background Subtraction Methods */
  IBGS *bgs;

  /*** Default Package ***/
  bgs = new FrameDifferenceBGS;
  //bgs = new StaticFrameDifferenceBGS;
  //bgs = new WeightedMovingMeanBGS;
  //bgs = new WeightedMovingVarianceBGS;
  //bgs = new MixtureOfGaussianV1BGS;
  //bgs = new MixtureOfGaussianV2BGS;
  //bgs = new AdaptiveBackgroundLearning;
  //bgs = new AdaptiveSelectiveBackgroundLearning;
  //bgs = new GMG;

  /*** DP Package (thanks to Donovan Parks) ***/
  //bgs = new DPAdaptiveMedianBGS;
  //bgs = new DPGrimsonGMMBGS;
  //bgs = new DPZivkovicAGMMBGS;
  //bgs = new DPMeanBGS;
  //bgs = new DPWrenGABGS;
  //bgs = new DPPratiMediodBGS;
  //bgs = new DPEigenbackgroundBGS;
  //bgs = new DPTextureBGS;

  /*** TB Package (thanks to Thierry Bouwmans, Fida EL BAF and Zhenjie Zhao) ***/
  //bgs = new T2FGMM_UM;
  //bgs = new T2FGMM_UV;
  //bgs = new T2FMRF_UM;
  //bgs = new T2FMRF_UV;
  //bgs = new FuzzySugenoIntegral;
  //bgs = new FuzzyChoquetIntegral;

  /*** JMO Package (thanks to Jean-Marc Odobez) ***/
  //bgs = new MultiLayerBGS;

  /*** PT Package (thanks to Martin Hofmann, Philipp Tiefenbacher and Gerhard Rigoll) ***/
  //bgs = new PixelBasedAdaptiveSegmenter;

  /*** LB Package (thanks to Laurence Bender) ***/
  //bgs = new LBSimpleGaussian;
  //bgs = new LBFuzzyGaussian;
  //bgs = new LBMixtureOfGaussians;
  //bgs = new LBAdaptiveSOM;
  //bgs = new LBFuzzyAdaptiveSOM;

  /*** LBP-MRF Package (thanks to Csaba Kertész) ***/
  //bgs = new LbpMrf;

  /*** AV Package (thanks to Lionel Robinault and Antoine Vacavant) ***/
  //bgs = new VuMeter;

  /*** EG Package (thanks to Ahmed Elgammal) ***/
  //bgs = new KDE;

  /*** DB Package (thanks to Domenico Daniele Bloisi) ***/
  //bgs = new IndependentMultimodalBGS;

  /*** SJN Package (thanks to SeungJong Noh) ***/
  //bgs = new SJN_MultiCueBGS;

  /*** BL Package (thanks to Benjamin Laugraud) ***/
  //bgs = new SigmaDeltaBGS;

  /*** PL Package ***/
  //bgs = new SuBSENSEBGS();
  //bgs = new LOBSTERBGS();

  int key = 0;
  while(key != 'q')
  {
    frame_aux = cvQueryFrame(capture);
    if(!frame_aux) break;

    cvResize(frame_aux, frame);

    cv::Mat img_input(frame);
    cv::imshow("input", img_input);

    cv::Mat img_mask;
    cv::Mat img_bkgmodel;
    bgs->process(img_input, img_mask, img_bkgmodel); // by default, it shows automatically the foreground mask image

    //if(!img_mask.empty())
    //  cv::imshow("Foreground", img_mask);
    //  do something

    key = cvWaitKey(33);
  }

  delete bgs;

  cvDestroyAllWindows();
  cvReleaseCapture(&capture);

  return 0;
}
<commit_msg>minor mod (added thank you note)<commit_after>/*
This file is part of BGSLibrary.

BGSLibrary 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 3 of the License, or
(at your option) any later version.

BGSLibrary 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 BGSLibrary.  If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <opencv2/opencv.hpp>

#include "package_bgs/FrameDifferenceBGS.h"
#include "package_bgs/StaticFrameDifferenceBGS.h"
#include "package_bgs/WeightedMovingMeanBGS.h"
#include "package_bgs/WeightedMovingVarianceBGS.h"
#include "package_bgs/MixtureOfGaussianV1BGS.h"
#include "package_bgs/MixtureOfGaussianV2BGS.h"
#include "package_bgs/AdaptiveBackgroundLearning.h"
#include "package_bgs/AdaptiveSelectiveBackgroundLearning.h"

#if CV_MAJOR_VERSION >= 2 && CV_MINOR_VERSION >= 4 && CV_SUBMINOR_VERSION >= 3
#include "package_bgs/GMG.h"
#endif

#include "package_bgs/dp/DPAdaptiveMedianBGS.h"
#include "package_bgs/dp/DPGrimsonGMMBGS.h"
#include "package_bgs/dp/DPZivkovicAGMMBGS.h"
#include "package_bgs/dp/DPMeanBGS.h"
#include "package_bgs/dp/DPWrenGABGS.h"
#include "package_bgs/dp/DPPratiMediodBGS.h"
#include "package_bgs/dp/DPEigenbackgroundBGS.h"
#include "package_bgs/dp/DPTextureBGS.h"

#include "package_bgs/tb/T2FGMM_UM.h"
#include "package_bgs/tb/T2FGMM_UV.h"
#include "package_bgs/tb/T2FMRF_UM.h"
#include "package_bgs/tb/T2FMRF_UV.h"
#include "package_bgs/tb/FuzzySugenoIntegral.h"
#include "package_bgs/tb/FuzzyChoquetIntegral.h"

#include "package_bgs/lb/LBSimpleGaussian.h"
#include "package_bgs/lb/LBFuzzyGaussian.h"
#include "package_bgs/lb/LBMixtureOfGaussians.h"
#include "package_bgs/lb/LBAdaptiveSOM.h"
#include "package_bgs/lb/LBFuzzyAdaptiveSOM.h"

#include "package_bgs/ck/LbpMrf.h"
#include "package_bgs/jmo/MultiLayerBGS.h"
// The PBAS algorithm was removed from BGSLibrary because it is
// based on patented algorithm ViBE
// http://www2.ulg.ac.be/telecom/research/vibe/
//#include "package_bgs/pt/PixelBasedAdaptiveSegmenter.h"
#include "package_bgs/av/VuMeter.h"
#include "package_bgs/ae/KDE.h"
#include "package_bgs/db/IndependentMultimodalBGS.h"
#include "package_bgs/sjn/SJN_MultiCueBGS.h"
#include "package_bgs/bl/SigmaDeltaBGS.h"

#include "package_bgs/pl/SuBSENSE.h"
#include "package_bgs/pl/LOBSTER.h"

int main(int argc, char **argv)
{
  std::cout << "Using OpenCV " << CV_MAJOR_VERSION << "." << CV_MINOR_VERSION << "." << CV_SUBMINOR_VERSION << std::endl;

  CvCapture *capture = 0;
  int resize_factor = 100;

  if(argc > 1)
  {
    std::cout << "Openning: " << argv[1] << std::endl;
    capture = cvCaptureFromAVI(argv[1]);
  }
  else
  {
    capture = cvCaptureFromCAM(0);
    resize_factor = 50; // set size = 50% of original image
  }

  if(!capture)
  {
    std::cerr << "Cannot initialize video!" << std::endl;
    return -1;
  }

  IplImage *frame_aux = cvQueryFrame(capture);
  IplImage *frame = cvCreateImage(cvSize((int)((frame_aux->width*resize_factor)/100) , (int)((frame_aux->height*resize_factor)/100)), frame_aux->depth, frame_aux->nChannels);
  cvResize(frame_aux, frame);

  /* Background Subtraction Methods */
  IBGS *bgs;

  /*** Default Package ***/
  bgs = new FrameDifferenceBGS;
  //bgs = new StaticFrameDifferenceBGS;
  //bgs = new WeightedMovingMeanBGS;
  //bgs = new WeightedMovingVarianceBGS;
  //bgs = new MixtureOfGaussianV1BGS;
  //bgs = new MixtureOfGaussianV2BGS;
  //bgs = new AdaptiveBackgroundLearning;
  //bgs = new AdaptiveSelectiveBackgroundLearning;
  //bgs = new GMG;

  /*** DP Package (thanks to Donovan Parks) ***/
  //bgs = new DPAdaptiveMedianBGS;
  //bgs = new DPGrimsonGMMBGS;
  //bgs = new DPZivkovicAGMMBGS;
  //bgs = new DPMeanBGS;
  //bgs = new DPWrenGABGS;
  //bgs = new DPPratiMediodBGS;
  //bgs = new DPEigenbackgroundBGS;
  //bgs = new DPTextureBGS;

  /*** TB Package (thanks to Thierry Bouwmans, Fida EL BAF and Zhenjie Zhao) ***/
  //bgs = new T2FGMM_UM;
  //bgs = new T2FGMM_UV;
  //bgs = new T2FMRF_UM;
  //bgs = new T2FMRF_UV;
  //bgs = new FuzzySugenoIntegral;
  //bgs = new FuzzyChoquetIntegral;

  /*** JMO Package (thanks to Jean-Marc Odobez) ***/
  //bgs = new MultiLayerBGS;

  /*** PT Package (thanks to Martin Hofmann, Philipp Tiefenbacher and Gerhard Rigoll) ***/
  //bgs = new PixelBasedAdaptiveSegmenter;

  /*** LB Package (thanks to Laurence Bender) ***/
  //bgs = new LBSimpleGaussian;
  //bgs = new LBFuzzyGaussian;
  //bgs = new LBMixtureOfGaussians;
  //bgs = new LBAdaptiveSOM;
  //bgs = new LBFuzzyAdaptiveSOM;

  /*** LBP-MRF Package (thanks to Csaba Kertész) ***/
  //bgs = new LbpMrf;

  /*** AV Package (thanks to Lionel Robinault and Antoine Vacavant) ***/
  //bgs = new VuMeter;

  /*** EG Package (thanks to Ahmed Elgammal) ***/
  //bgs = new KDE;

  /*** DB Package (thanks to Domenico Daniele Bloisi) ***/
  //bgs = new IndependentMultimodalBGS;

  /*** SJN Package (thanks to SeungJong Noh) ***/
  //bgs = new SJN_MultiCueBGS;

  /*** BL Package (thanks to Benjamin Laugraud) ***/
  //bgs = new SigmaDeltaBGS;

  /*** PL Package (thanks to Pierre-Luc) ***/
  //bgs = new SuBSENSEBGS();
  //bgs = new LOBSTERBGS();

  int key = 0;
  while(key != 'q')
  {
    frame_aux = cvQueryFrame(capture);
    if(!frame_aux) break;

    cvResize(frame_aux, frame);

    cv::Mat img_input(frame);
    cv::imshow("input", img_input);

    cv::Mat img_mask;
    cv::Mat img_bkgmodel;
    bgs->process(img_input, img_mask, img_bkgmodel); // by default, it shows automatically the foreground mask image

    //if(!img_mask.empty())
    //  cv::imshow("Foreground", img_mask);
    //  do something

    key = cvWaitKey(33);
  }

  delete bgs;

  cvDestroyAllWindows();
  cvReleaseCapture(&capture);

  return 0;
}
<|endoftext|>