<commit_before>#ifndef __STAN__PROB__DISTRIBUTIONS__UNIVARIATE__CONTINUOUS__GUMBEL_HPP__
#define __STAN__PROB__DISTRIBUTIONS__UNIVARIATE__CONTINUOUS__GUMBEL_HPP__

#include <boost/random/uniform_01.hpp>
#include <boost/random/variate_generator.hpp>

#include <stan/agrad.hpp>
#include <stan/math/error_handling.hpp>
#include <stan/math/special_functions.hpp>
#include <stan/meta/traits.hpp>
#include <stan/prob/constants.hpp>
#include <stan/prob/traits.hpp>
#include <stan/prob/internal_math.hpp>

namespace stan {

  namespace prob {

    template <bool propto,
              typename T_y, typename T_loc, typename T_scale,
              class Policy>
    typename return_type<T_y,T_loc,T_scale>::type
    gumbel_log(const T_y& y, const T_loc& mu, const T_scale& beta,
               const Policy& /*policy*/) {
      static const char* function = "stan::prob::gumbel_log(%1%)";

      using std::log;
      using std::exp;
      using stan::is_constant_struct;
      using stan::math::check_positive;
      using stan::math::check_finite;
      using stan::math::check_not_nan;
      using stan::math::check_consistent_sizes;
      using stan::math::value_of;
      using stan::prob::include_summand;

      // check if any vectors are zero length
      if (!(stan::length(y)
            && stan::length(mu)
            && stan::length(beta)))
        return 0.0;

      // set up return value accumulator
      double logp(0.0);

      // validate args (here done over var, which should be OK)
      if (!check_not_nan(function, y, "Random variable", &logp, Policy()))
        return logp;
      if (!check_finite(function, mu, "Location parameter",
                        &logp, Policy()))
        return logp;
      if (!check_positive(function, beta, "Scale parameter",
                          &logp, Policy()))
        return logp;
      if (!(check_consistent_sizes(function,
                                   y,mu,beta,
                                   "Random variable","Location parameter","Scale parameter",
                                   &logp, Policy())))
        return logp;

      // check if no variables are involved and prop-to
      if (!include_summand<propto,T_y,T_loc,T_scale>::value)
        return 0.0;

      // set up template expressions wrapping scalars into vector views
      agrad::OperandsAndPartials<T_y, T_loc, T_scale> operands_and_partials(y, mu, beta);

      VectorView<const T_y> y_vec(y);
      VectorView<const T_loc> mu_vec(mu);
      VectorView<const T_scale> beta_vec(beta);
      size_t N = max_size(y, mu, beta);

      DoubleVectorView<true,is_vector<T_scale>::value> inv_beta(length(beta));
      DoubleVectorView<include_summand<propto,T_scale>::value,is_vector<T_scale>::value> log_beta(length(beta));
      for (size_t i = 0; i < length(beta); i++) {
        inv_beta[i] = 1.0 / value_of(beta_vec[i]);
        if (include_summand<propto,T_scale>::value)
          log_beta[i] = log(value_of(beta_vec[i]));
      }

      for (size_t n = 0; n < N; n++) {
        // pull out values of arguments
        const double y_dbl = value_of(y_vec[n]);
        const double mu_dbl = value_of(mu_vec[n]);

        // reusable subexpression values
        const double y_minus_mu_over_beta
          = (y_dbl - mu_dbl) * inv_beta[n];

        // log probability
        if (include_summand<propto,T_scale>::value)
          logp -= log_beta[n];
        if (include_summand<propto,T_y,T_loc,T_scale>::value)
          logp += -y_minus_mu_over_beta - exp(-y_minus_mu_over_beta);

        // gradients
        double scaled_diff = inv_beta[n] * exp(-y_minus_mu_over_beta);
        if (!is_constant_struct<T_y>::value)
          operands_and_partials.d_x1[n] -= inv_beta[n] - scaled_diff;
        if (!is_constant_struct<T_loc>::value)
          operands_and_partials.d_x2[n] += inv_beta[n] - scaled_diff;
        if (!is_constant_struct<T_scale>::value)
          operands_and_partials.d_x3[n]
            += -inv_beta[n] + y_minus_mu_over_beta * inv_beta[n] - scaled_diff * y_minus_mu_over_beta;
      }
      return operands_and_partials.to_var(logp);
    }

    template <bool propto,
              typename T_y, typename T_loc, typename T_scale>
    inline
    typename return_type<T_y,T_loc,T_scale>::type
    gumbel_log(const T_y& y, const T_loc& mu, const T_scale& beta) {
      return gumbel_log<propto>(y,mu,beta,stan::math::default_policy());
    }

    template <typename T_y, typename T_loc, typename T_scale,
              class Policy>
    inline
    typename return_type<T_y,T_loc,T_scale>::type
    gumbel_log(const T_y& y, const T_loc& mu, const T_scale& beta,
               const Policy&) {
      return gumbel_log<false>(y,mu,beta,Policy());
    }

    template <typename T_y, typename T_loc, typename T_scale>
    inline
    typename return_type<T_y,T_loc,T_scale>::type
    gumbel_log(const T_y& y, const T_loc& mu, const T_scale& beta) {
      return gumbel_log<false>(y,mu,beta,stan::math::default_policy());
    }

    template <typename T_y, typename T_loc, typename T_scale,
              class Policy>
    typename return_type<T_y,T_loc,T_scale>::type
    gumbel_cdf(const T_y& y, const T_loc& mu, const T_scale& beta,
             const Policy&) {
      static const char* function = "stan::prob::gumbel_cdf(%1%)";

      using stan::math::check_positive;
      using stan::math::check_finite;
      using stan::math::check_not_nan;
      using stan::math::check_consistent_sizes;

      typename return_type<T_y, T_loc, T_scale>::type cdf(1);
      // check if any vectors are zero length
      if (!(stan::length(y)
            && stan::length(mu)
            && stan::length(beta)))
        return cdf;

      if (!check_not_nan(function, y, "Random variable", &cdf, Policy()))
        return cdf;
      if (!check_finite(function, mu, "Location parameter", &cdf, Policy()))
        return cdf;
      if (!check_not_nan(function, beta, "Scale parameter",
                         &cdf, Policy()))
        return cdf;
      if (!check_positive(function, beta, "Scale parameter",
                          &cdf, Policy()))
        return cdf;
      if (!(check_consistent_sizes(function,
                                   y,mu,beta,
                                   "Random variable","Location parameter","Scale parameter",
                                   &cdf, Policy())))
        return cdf;

      VectorView<const T_y> y_vec(y);
      VectorView<const T_loc> mu_vec(mu);
      VectorView<const T_scale> beta_vec(beta);
      size_t N = max_size(y, mu, beta);

      for (size_t n = 0; n < N; n++) {
        cdf *= exp(-exp(-((y_vec[n]) - (mu_vec[n])) / (beta_vec[n])));
      }

      return cdf;
    }

    template <typename T_y, typename T_loc, typename T_scale>
    inline
    typename return_type<T_y, T_loc, T_scale>::type
    gumbel_cdf(const T_y& y, const T_loc& mu, const T_scale& beta) {
      return gumbel_cdf(y,mu,beta,stan::math::default_policy());
    }

    template <class RNG>
    inline double
    gumbel_rng(double mu,
               double beta,
               RNG& rng) {
      using boost::variate_generator;
      using boost::uniform_01;
      variate_generator<RNG&, uniform_01<> >
        uniform01_rng(rng, uniform_01<>());
      return mu - beta * std::log(-std::log(uniform01_rng()));
    }
  }
}
#endif

<commit_msg>fixed gumbel dist includes<commit_after>#ifndef __STAN__PROB__DISTRIBUTIONS__UNIVARIATE__CONTINUOUS__GUMBEL_HPP__
#define __STAN__PROB__DISTRIBUTIONS__UNIVARIATE__CONTINUOUS__GUMBEL_HPP__

#include <boost/random/uniform_01.hpp>
#include <boost/random/variate_generator.hpp>

#include <stan/agrad.hpp>
#include <stan/math/error_handling.hpp>
#include <stan/meta/traits.hpp>
#include <stan/prob/constants.hpp>
#include <stan/prob/traits.hpp>
#include <stan/prob/internal_math.hpp>

namespace stan {

  namespace prob {

    template <bool propto,
              typename T_y, typename T_loc, typename T_scale,
              class Policy>
    typename return_type<T_y,T_loc,T_scale>::type
    gumbel_log(const T_y& y, const T_loc& mu, const T_scale& beta,
               const Policy& /*policy*/) {
      static const char* function = "stan::prob::gumbel_log(%1%)";

      using std::log;
      using std::exp;
      using stan::is_constant_struct;
      using stan::math::check_positive;
      using stan::math::check_finite;
      using stan::math::check_not_nan;
      using stan::math::check_consistent_sizes;
      using stan::math::value_of;
      using stan::prob::include_summand;

      // check if any vectors are zero length
      if (!(stan::length(y)
            && stan::length(mu)
            && stan::length(beta)))
        return 0.0;

      // set up return value accumulator
      double logp(0.0);

      // validate args (here done over var, which should be OK)
      if (!check_not_nan(function, y, "Random variable", &logp, Policy()))
        return logp;
      if (!check_finite(function, mu, "Location parameter",
                        &logp, Policy()))
        return logp;
      if (!check_positive(function, beta, "Scale parameter",
                          &logp, Policy()))
        return logp;
      if (!(check_consistent_sizes(function,
                                   y,mu,beta,
                                   "Random variable","Location parameter","Scale parameter",
                                   &logp, Policy())))
        return logp;

      // check if no variables are involved and prop-to
      if (!include_summand<propto,T_y,T_loc,T_scale>::value)
        return 0.0;

      // set up template expressions wrapping scalars into vector views
      agrad::OperandsAndPartials<T_y, T_loc, T_scale> operands_and_partials(y, mu, beta);

      VectorView<const T_y> y_vec(y);
      VectorView<const T_loc> mu_vec(mu);
      VectorView<const T_scale> beta_vec(beta);
      size_t N = max_size(y, mu, beta);

      DoubleVectorView<true,is_vector<T_scale>::value> inv_beta(length(beta));
      DoubleVectorView<include_summand<propto,T_scale>::value,is_vector<T_scale>::value> log_beta(length(beta));
      for (size_t i = 0; i < length(beta); i++) {
        inv_beta[i] = 1.0 / value_of(beta_vec[i]);
        if (include_summand<propto,T_scale>::value)
          log_beta[i] = log(value_of(beta_vec[i]));
      }

      for (size_t n = 0; n < N; n++) {
        // pull out values of arguments
        const double y_dbl = value_of(y_vec[n]);
        const double mu_dbl = value_of(mu_vec[n]);

        // reusable subexpression values
        const double y_minus_mu_over_beta
          = (y_dbl - mu_dbl) * inv_beta[n];

        // log probability
        if (include_summand<propto,T_scale>::value)
          logp -= log_beta[n];
        if (include_summand<propto,T_y,T_loc,T_scale>::value)
          logp += -y_minus_mu_over_beta - exp(-y_minus_mu_over_beta);

        // gradients
        double scaled_diff = inv_beta[n] * exp(-y_minus_mu_over_beta);
        if (!is_constant_struct<T_y>::value)
          operands_and_partials.d_x1[n] -= inv_beta[n] - scaled_diff;
        if (!is_constant_struct<T_loc>::value)
          operands_and_partials.d_x2[n] += inv_beta[n] - scaled_diff;
        if (!is_constant_struct<T_scale>::value)
          operands_and_partials.d_x3[n]
            += -inv_beta[n] + y_minus_mu_over_beta * inv_beta[n] - scaled_diff * y_minus_mu_over_beta;
      }
      return operands_and_partials.to_var(logp);
    }

    template <bool propto,
              typename T_y, typename T_loc, typename T_scale>
    inline
    typename return_type<T_y,T_loc,T_scale>::type
    gumbel_log(const T_y& y, const T_loc& mu, const T_scale& beta) {
      return gumbel_log<propto>(y,mu,beta,stan::math::default_policy());
    }

    template <typename T_y, typename T_loc, typename T_scale,
              class Policy>
    inline
    typename return_type<T_y,T_loc,T_scale>::type
    gumbel_log(const T_y& y, const T_loc& mu, const T_scale& beta,
               const Policy&) {
      return gumbel_log<false>(y,mu,beta,Policy());
    }

    template <typename T_y, typename T_loc, typename T_scale>
    inline
    typename return_type<T_y,T_loc,T_scale>::type
    gumbel_log(const T_y& y, const T_loc& mu, const T_scale& beta) {
      return gumbel_log<false>(y,mu,beta,stan::math::default_policy());
    }

    template <typename T_y, typename T_loc, typename T_scale,
              class Policy>
    typename return_type<T_y,T_loc,T_scale>::type
    gumbel_cdf(const T_y& y, const T_loc& mu, const T_scale& beta,
             const Policy&) {
      static const char* function = "stan::prob::gumbel_cdf(%1%)";

      using stan::math::check_positive;
      using stan::math::check_finite;
      using stan::math::check_not_nan;
      using stan::math::check_consistent_sizes;

      typename return_type<T_y, T_loc, T_scale>::type cdf(1);
      // check if any vectors are zero length
      if (!(stan::length(y)
            && stan::length(mu)
            && stan::length(beta)))
        return cdf;

      if (!check_not_nan(function, y, "Random variable", &cdf, Policy()))
        return cdf;
      if (!check_finite(function, mu, "Location parameter", &cdf, Policy()))
        return cdf;
      if (!check_not_nan(function, beta, "Scale parameter",
                         &cdf, Policy()))
        return cdf;
      if (!check_positive(function, beta, "Scale parameter",
                          &cdf, Policy()))
        return cdf;
      if (!(check_consistent_sizes(function,
                                   y,mu,beta,
                                   "Random variable","Location parameter","Scale parameter",
                                   &cdf, Policy())))
        return cdf;

      VectorView<const T_y> y_vec(y);
      VectorView<const T_loc> mu_vec(mu);
      VectorView<const T_scale> beta_vec(beta);
      size_t N = max_size(y, mu, beta);

      for (size_t n = 0; n < N; n++) {
        cdf *= exp(-exp(-((y_vec[n]) - (mu_vec[n])) / (beta_vec[n])));
      }

      return cdf;
    }

    template <typename T_y, typename T_loc, typename T_scale>
    inline
    typename return_type<T_y, T_loc, T_scale>::type
    gumbel_cdf(const T_y& y, const T_loc& mu, const T_scale& beta) {
      return gumbel_cdf(y,mu,beta,stan::math::default_policy());
    }

    template <class RNG>
    inline double
    gumbel_rng(double mu,
               double beta,
               RNG& rng) {
      using boost::variate_generator;
      using boost::uniform_01;
      variate_generator<RNG&, uniform_01<> >
        uniform01_rng(rng, uniform_01<>());
      return mu - beta * std::log(-std::log(uniform01_rng()));
    }
  }
}
#endif

<|endoftext|>


<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (info@qt.nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at info@qt.nokia.com.
**
**************************************************************************/

#include "qmljssemanticinfoupdater.h"

#include <qmljs/qmljsmodelmanagerinterface.h>
#include <qmljs/qmljsdocument.h>
#include <qmljs/qmljscheck.h>
#include <qmljs/qmljscontext.h>
#include <qmljs/qmljslink.h>
#include <qmljstools/qmljsmodelmanager.h>

namespace QmlJSEditor {
namespace Internal {

SemanticInfoUpdater::SemanticInfoUpdater(QObject *parent)
        : QThread(parent),
          m_done(false),
          m_modelManager(0)
{
}

SemanticInfoUpdater::~SemanticInfoUpdater()
{
}

void SemanticInfoUpdater::abort()
{
    QMutexLocker locker(&m_mutex);
    m_done = true;
    m_condition.wakeOne();
}

void SemanticInfoUpdater::update(const SemanticInfoUpdaterSource &source)
{
    QMutexLocker locker(&m_mutex);
    m_source = source;
    m_condition.wakeOne();
}

bool SemanticInfoUpdater::isOutdated()
{
    QMutexLocker locker(&m_mutex);
    const bool outdated = ! m_source.fileName.isEmpty() || m_done;
    return outdated;
}

void SemanticInfoUpdater::run()
{
    setPriority(QThread::LowestPriority);

    forever {
        m_mutex.lock();

        while (! (m_done || ! m_source.fileName.isEmpty()))
            m_condition.wait(&m_mutex);

        const bool done = m_done;
        const SemanticInfoUpdaterSource source = m_source;
        m_source.clear();

        m_mutex.unlock();

        if (done)
            break;

        const SemanticInfo info = semanticInfo(source);

        if (! isOutdated()) {
            m_mutex.lock();
            m_lastSemanticInfo = info;
            m_mutex.unlock();

            emit updated(info);
        }
    }
}

SemanticInfo SemanticInfoUpdater::semanticInfo(const SemanticInfoUpdaterSource &source)
{
    m_mutex.lock();
    const int revision = m_lastSemanticInfo.revision();
    m_mutex.unlock();

    QmlJS::Snapshot snapshot;
    QmlJS::Document::Ptr doc;

    if (! source.force && revision == source.revision) {
        m_mutex.lock();
        snapshot = m_lastSemanticInfo.snapshot;
        doc = m_lastSemanticInfo.document;
        m_mutex.unlock();
    }

    if (! doc) {
        snapshot = source.snapshot;
        QmlJS::Document::Language language;
        if (m_lastSemanticInfo.document)
            language = m_lastSemanticInfo.document->language();
        else
            language = QmlJSTools::languageOfFile(source.fileName);
        doc = snapshot.documentFromSource(source.code, source.fileName, language);
        doc->setEditorRevision(source.revision);
        doc->parse();
        snapshot.insert(doc);
    }

    SemanticInfo semanticInfo;
    semanticInfo.snapshot = snapshot;
    semanticInfo.document = doc;

    QmlJS::ModelManagerInterface *modelManager = QmlJS::ModelManagerInterface::instance();

    QmlJS::Link link(snapshot, modelManager->importPaths(), modelManager->builtins(doc));
    semanticInfo.context = link(doc, &semanticInfo.semanticMessages);

    QmlJS::ScopeChain *scopeChain = new QmlJS::ScopeChain(doc, semanticInfo.context);
    semanticInfo.m_rootScopeChain = QSharedPointer<const QmlJS::ScopeChain>(scopeChain);

    if (doc->language() != QmlJS::Document::JsonLanguage) {
        QmlJS::Check checker(doc, semanticInfo.context);
        foreach (const QmlJS::StaticAnalysis::Message &msg, checker()) {
            semanticInfo.semanticMessages += msg.toDiagnosticMessage();
    }

    return semanticInfo;
}

void SemanticInfoUpdater::setModelManager(QmlJS::ModelManagerInterface *modelManager)
{
    m_modelManager = modelManager;
}

} // namespace Internal
} // namespace QmlJSEditor
<commit_msg>QmlJS: Another compile fix for wrong rebase.<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (info@qt.nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at info@qt.nokia.com.
**
**************************************************************************/

#include "qmljssemanticinfoupdater.h"

#include <qmljs/qmljsmodelmanagerinterface.h>
#include <qmljs/qmljsdocument.h>
#include <qmljs/qmljscheck.h>
#include <qmljs/qmljscontext.h>
#include <qmljs/qmljslink.h>
#include <qmljstools/qmljsmodelmanager.h>

namespace QmlJSEditor {
namespace Internal {

SemanticInfoUpdater::SemanticInfoUpdater(QObject *parent)
        : QThread(parent),
          m_done(false),
          m_modelManager(0)
{
}

SemanticInfoUpdater::~SemanticInfoUpdater()
{
}

void SemanticInfoUpdater::abort()
{
    QMutexLocker locker(&m_mutex);
    m_done = true;
    m_condition.wakeOne();
}

void SemanticInfoUpdater::update(const SemanticInfoUpdaterSource &source)
{
    QMutexLocker locker(&m_mutex);
    m_source = source;
    m_condition.wakeOne();
}

bool SemanticInfoUpdater::isOutdated()
{
    QMutexLocker locker(&m_mutex);
    const bool outdated = ! m_source.fileName.isEmpty() || m_done;
    return outdated;
}

void SemanticInfoUpdater::run()
{
    setPriority(QThread::LowestPriority);

    forever {
        m_mutex.lock();

        while (! (m_done || ! m_source.fileName.isEmpty()))
            m_condition.wait(&m_mutex);

        const bool done = m_done;
        const SemanticInfoUpdaterSource source = m_source;
        m_source.clear();

        m_mutex.unlock();

        if (done)
            break;

        const SemanticInfo info = semanticInfo(source);

        if (! isOutdated()) {
            m_mutex.lock();
            m_lastSemanticInfo = info;
            m_mutex.unlock();

            emit updated(info);
        }
    }
}

SemanticInfo SemanticInfoUpdater::semanticInfo(const SemanticInfoUpdaterSource &source)
{
    m_mutex.lock();
    const int revision = m_lastSemanticInfo.revision();
    m_mutex.unlock();

    QmlJS::Snapshot snapshot;
    QmlJS::Document::Ptr doc;

    if (! source.force && revision == source.revision) {
        m_mutex.lock();
        snapshot = m_lastSemanticInfo.snapshot;
        doc = m_lastSemanticInfo.document;
        m_mutex.unlock();
    }

    if (! doc) {
        snapshot = source.snapshot;
        QmlJS::Document::Language language;
        if (m_lastSemanticInfo.document)
            language = m_lastSemanticInfo.document->language();
        else
            language = QmlJSTools::languageOfFile(source.fileName);
        doc = snapshot.documentFromSource(source.code, source.fileName, language);
        doc->setEditorRevision(source.revision);
        doc->parse();
        snapshot.insert(doc);
    }

    SemanticInfo semanticInfo;
    semanticInfo.snapshot = snapshot;
    semanticInfo.document = doc;

    QmlJS::ModelManagerInterface *modelManager = QmlJS::ModelManagerInterface::instance();

    QmlJS::Link link(snapshot, modelManager->importPaths(), modelManager->builtins(doc));
    semanticInfo.context = link(doc, &semanticInfo.semanticMessages);

    QmlJS::ScopeChain *scopeChain = new QmlJS::ScopeChain(doc, semanticInfo.context);
    semanticInfo.m_rootScopeChain = QSharedPointer<const QmlJS::ScopeChain>(scopeChain);

    if (doc->language() != QmlJS::Document::JsonLanguage) {
        QmlJS::Check checker(doc, semanticInfo.context);
        foreach (const QmlJS::StaticAnalysis::Message &msg, checker()) {
            semanticInfo.semanticMessages += msg.toDiagnosticMessage();
        }
    }

    return semanticInfo;
}

void SemanticInfoUpdater::setModelManager(QmlJS::ModelManagerInterface *modelManager)
{
    m_modelManager = modelManager;
}

} // namespace Internal
} // namespace QmlJSEditor
<|endoftext|>


<commit_before>/*
 * This program 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.
 *
 * Written (W) 2012 Chiyuan Zhang
 * Copyright (C) 2012 Chiyuan Zhang
 */

#include <shogun/multiclass/MulticlassOneVsOneStrategy.h>

using namespace shogun;

CMulticlassOneVsOneStrategy::CMulticlassOneVsOneStrategy()
	:CMulticlassStrategy(), m_num_machines(0)
{
}

void CMulticlassOneVsOneStrategy::train_start(CLabels *orig_labels, CLabels *train_labels)
{
	CMulticlassStrategy::train_start(orig_labels, train_labels);
	m_num_machines=m_num_classes*(m_num_classes-1)/2;

	m_train_pair_idx_1 = 0;
	m_train_pair_idx_2 = 1;
}

bool CMulticlassOneVsOneStrategy::train_has_more()
{
	return m_train_iter < m_num_machines;
}

SGVector<int32_t> CMulticlassOneVsOneStrategy::train_prepare_next()
{
	CMulticlassStrategy::train_prepare_next();

	SGVector<int32_t> subset(m_orig_labels->get_num_labels());
	int32_t tot=0;
	for (int32_t k=0; k < m_orig_labels->get_num_labels(); ++k)
	{
		if (m_orig_labels->get_int_label(k)==m_train_pair_idx_1)
		{
			m_train_labels->set_label(k, +1.0);
			subset[tot]=k;
			tot++;
		}
		else if (m_orig_labels->get_int_label(k)==m_train_pair_idx_2)
		{
			m_train_labels->set_label(k, -1.0);
			subset[tot]=k;
			tot++;
		}
	}

	m_train_pair_idx_2++;
	if (m_train_pair_idx_2 >= m_num_classes)
	{
		m_train_pair_idx_1++;
		m_train_pair_idx_2=m_train_pair_idx_1+1;
	}

	return subset;
}

int32_t CMulticlassOneVsOneStrategy::decide_label(SGVector<float64_t> outputs)
{
	int32_t s=0;
	SGVector<int32_t> votes(m_num_classes);
	votes.zero();

	for (int32_t i=0; i<m_num_classes; i++)
	{
		for (int32_t j=i+1; j<m_num_classes; j++)
		{
			if (outputs[s++]>0)
				votes[i]++;
			else
				votes[j]++;
		}
	}

	int32_t result=CMath::arg_max(votes.vector, 1, votes.vlen);

	return result;
}
<commit_msg>Fix memory error related to new SGVector API.<commit_after>/*
 * This program 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.
 *
 * Written (W) 2012 Chiyuan Zhang
 * Copyright (C) 2012 Chiyuan Zhang
 */

#include <shogun/multiclass/MulticlassOneVsOneStrategy.h>

using namespace shogun;

CMulticlassOneVsOneStrategy::CMulticlassOneVsOneStrategy()
	:CMulticlassStrategy(), m_num_machines(0)
{
}

void CMulticlassOneVsOneStrategy::train_start(CLabels *orig_labels, CLabels *train_labels)
{
	CMulticlassStrategy::train_start(orig_labels, train_labels);
	m_num_machines=m_num_classes*(m_num_classes-1)/2;

	m_train_pair_idx_1 = 0;
	m_train_pair_idx_2 = 1;
}

bool CMulticlassOneVsOneStrategy::train_has_more()
{
	return m_train_iter < m_num_machines;
}

SGVector<int32_t> CMulticlassOneVsOneStrategy::train_prepare_next()
{
	CMulticlassStrategy::train_prepare_next();

	SGVector<int32_t> subset(m_orig_labels->get_num_labels(), false);
	int32_t tot=0;
	for (int32_t k=0; k < m_orig_labels->get_num_labels(); ++k)
	{
		if (m_orig_labels->get_int_label(k)==m_train_pair_idx_1)
		{
			m_train_labels->set_label(k, +1.0);
			subset[tot]=k;
			tot++;
		}
		else if (m_orig_labels->get_int_label(k)==m_train_pair_idx_2)
		{
			m_train_labels->set_label(k, -1.0);
			subset[tot]=k;
			tot++;
		}
	}

	m_train_pair_idx_2++;
	if (m_train_pair_idx_2 >= m_num_classes)
	{
		m_train_pair_idx_1++;
		m_train_pair_idx_2=m_train_pair_idx_1+1;
	}

	return SGVector<int32_t>(subset.vector, tot, true);
}

int32_t CMulticlassOneVsOneStrategy::decide_label(SGVector<float64_t> outputs)
{
	int32_t s=0;
	SGVector<int32_t> votes(m_num_classes);
	votes.zero();

	for (int32_t i=0; i<m_num_classes; i++)
	{
		for (int32_t j=i+1; j<m_num_classes; j++)
		{
			if (outputs[s++]>0)
				votes[i]++;
			else
				votes[j]++;
		}
	}

	int32_t result=CMath::arg_max(votes.vector, 1, votes.vlen);

	return result;
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2012 The Native Client Authors. All rights reserved.
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "native_client/src/include/nacl_assert.h"
#include "native_client/src/trusted/service_runtime/mmap_test_check.h"

#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>

#define MAX_INPUT_LINE_LENGTH   4096

void CheckMapping(uintptr_t addr, size_t size, int protect, int map_type) {
  const char *maps_path = "/proc/self/maps";
  FILE *maps_file;
  char buf[MAX_INPUT_LINE_LENGTH];
  uint64_t start;
  uint64_t end;
  int64_t inode;
  char flags[4];
  int prot = 0;
  int type = 0;
  int num;
  int found = 0;

  // Open /proc/self/maps to read process memory mapping
  maps_file = fopen(maps_path, "r");
  ASSERT(maps_file != NULL);

  for (;;) {
    // Read each line from /proc/self/maps file
    if (!fgets(buf, sizeof(buf), maps_file)) {
      break;
    }
    // Parse the line
    if (3 < sscanf(buf, "%"SCNx64"-%"SCNx64" %4s %*d %*x:%*x %"SCNd64" %n",
                   &start, &end, flags, &inode, &num)) {
      // The maps file will merge regions with the same attributes.  Thus,
      // we allow the starting address to be before the expected starting
      // address, and we allow the ending address to be after the expected
      // end address (addr + size).
      if (start <= addr && end >= addr + size) {
        if (flags[0] == 'r')
          prot |= PROT_READ;
        if (flags[1] == 'w')
          prot |= PROT_WRITE;
        if (flags[2] == 'x')
          prot |= PROT_EXEC;

        if (flags[3] == 'p')
          type |= MAP_PRIVATE;
        else if (flags[3] == 's')
          type |= MAP_SHARED;

        found = 1;
        break;
      }
    }
  }

  ASSERT(found);
  ASSERT_EQ(prot, protect);
  ASSERT_EQ(type, map_type);
  ASSERT_EQ(fclose(maps_file), 0);
}
<commit_msg>Fix ASan report in tests.<commit_after>/*
 * Copyright (c) 2012 The Native Client Authors. All rights reserved.
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "native_client/src/include/nacl_assert.h"
#include "native_client/src/trusted/service_runtime/mmap_test_check.h"

#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>

#define MAX_INPUT_LINE_LENGTH   4096

void CheckMapping(uintptr_t addr, size_t size, int protect, int map_type) {
  const char *maps_path = "/proc/self/maps";
  FILE *maps_file;
  char buf[MAX_INPUT_LINE_LENGTH];
  uint64_t start;
  uint64_t end;
  int64_t inode;
  char flags[5];
  int prot = 0;
  int type = 0;
  int num;
  int found = 0;

  // Open /proc/self/maps to read process memory mapping
  maps_file = fopen(maps_path, "r");
  ASSERT(maps_file != NULL);

  for (;;) {
    // Read each line from /proc/self/maps file
    if (!fgets(buf, sizeof(buf), maps_file)) {
      break;
    }
    // Parse the line
    if (3 < sscanf(buf, "%"SCNx64"-%"SCNx64" %4s %*d %*x:%*x %"SCNd64" %n",
                   &start, &end, flags, &inode, &num)) {
      // The maps file will merge regions with the same attributes.  Thus,
      // we allow the starting address to be before the expected starting
      // address, and we allow the ending address to be after the expected
      // end address (addr + size).
      if (start <= addr && end >= addr + size) {
        if (flags[0] == 'r')
          prot |= PROT_READ;
        if (flags[1] == 'w')
          prot |= PROT_WRITE;
        if (flags[2] == 'x')
          prot |= PROT_EXEC;

        if (flags[3] == 'p')
          type |= MAP_PRIVATE;
        else if (flags[3] == 's')
          type |= MAP_SHARED;

        found = 1;
        break;
      }
    }
  }

  ASSERT(found);
  ASSERT_EQ(prot, protect);
  ASSERT_EQ(type, map_type);
  ASSERT_EQ(fclose(maps_file), 0);
}
<|endoftext|>


<commit_before>/*
 * Copyright 2015 - 2018 gtalent2@gmail.com
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#if defined(OX_USE_STDLIB)
#include <cstdlib>
#include <iostream>
#endif

void oxAssert(const char *file, int line, bool pass, const char *msg) {
	if (!pass) {
		std::cerr << '(' << file << ':' << line << "): " << msg << std::endl;
		std::abort();
	}
}<commit_msg>Remove assert implementation on non-stdlib builds, as the asserts use stdlib<commit_after>/*
 * Copyright 2015 - 2018 gtalent2@gmail.com
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#if defined(OX_USE_STDLIB)
#include <cstdlib>
#include <iostream>
#endif

void oxAssert(const char *file, int line, bool pass, const char *msg) {
#if defined(OX_USE_STDLIB)
	if (!pass) {
		std::cerr << '(' << file << ':' << line << "): " << msg << std::endl;
		std::abort();
	}
#endif
}<|endoftext|>


<commit_before>//
//  main.cpp
//  RoboNeko
//
//  Created by nspool on 8/3/17.
//  Copyright © 2017 nspool. All rights reserved.
//

#include <iostream>

#include <math.h>

#include <SDL2_ttf/SDL_ttf.h>
#include <SDL2/SDL.h>
#include <SDL2_image/SDL_image.h>
#include <SDL2/SDL_timer.h>

const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;

TTF_Font *_font = 0;
SDL_Window* _window = 0;
SDL_Surface* _screenSurface = 0;
SDL_Surface* _background = 0;
SDL_Renderer* _renderer = 0;

int _startTime = SDL_GetTicks();
int mouseX = 0;
int mouseY = 0;

class Robit
{
public:
  static const int SPRITE_WIDTH = 32;
  static const int SPRITE_ANIMATION_LEN = 3;
  Robit();
  void doEvent();
  SDL_Point p = {0, 200};
private:
  double rad = M_PI_2;
  double xDelta = 0;
  double yDelta = 0;
  SDL_Rect spriteClips[3];
  int _animationRate = 12;
  SDL_Texture* gRobitsTexture;
};

Robit::Robit()
{
  // Load the robit
  SDL_Surface* gRobits = IMG_Load( "robits.png" );
//  SDL_Surface* gTextureImage = IMG_Load( "tex.png" );

  if(gRobits == 0) // || gTextureImage == 0)
  {
    printf( "Failed to load images! SDL_Error: %s\n", SDL_GetError() );
  }

  // Setup Robit animation
  spriteClips[0].x = 0;
  spriteClips[0].y = 0;
  spriteClips[0].w = 32;
  spriteClips[0].h = 32;

  spriteClips[1].x = 32;
  spriteClips[1].y = 0;
  spriteClips[1].w = 32;
  spriteClips[1].h = 32;

  spriteClips[2].x = 64;
  spriteClips[2].y = 0;
  spriteClips[2].w = 32;
  spriteClips[2].h = 32;

  gRobitsTexture = SDL_CreateTextureFromSurface( _renderer, gRobits );
  SDL_SetTextureColorMod( gRobitsTexture, 255, 25, 25 );
}

void Robit::doEvent()
{
  // Update |p| to new position
  rad = atan2((mouseY - p.y), (mouseX - p.x));
  xDelta += cos(rad);
  yDelta += sin(rad);

  if(xDelta > 1 || xDelta < -1){
    p.x += (int)xDelta;
    xDelta = 0;
  }

  if(yDelta > 1 || yDelta < -1){
    p.y += (int)yDelta;
    yDelta = 0;
  }

  // Bounds
  if(p.x < 0) { rad = 2 * M_PI; }
  if((p.x + SPRITE_WIDTH) > SCREEN_WIDTH) { rad = M_PI; }

  if(p.y < 0) { rad = M_PI_2; }
  if((p.y + SPRITE_WIDTH) > SCREEN_HEIGHT) { rad = -M_PI_2; }

  // Animate at some fixed framerate
  int frameToDraw = ((SDL_GetTicks() - _startTime) * _animationRate / 1000) % SPRITE_ANIMATION_LEN;
  SDL_Rect robitLoc = { p.x, p.y, 32, 32 };
  SDL_RenderCopy( _renderer, gRobitsTexture, &spriteClips[frameToDraw], &robitLoc );
}

SDL_Surface *load_image(std::string filename)
{
  SDL_Surface* loadedImage = 0;
  SDL_Surface* optimisedImage = 0;
  loadedImage = SDL_LoadBMP(filename.c_str());
  if(loadedImage != 0)
  {
    optimisedImage = SDL_ConvertSurface(loadedImage, _screenSurface->format, 0);
  }
  SDL_FreeSurface(loadedImage);
  return optimisedImage;
}

int main(int argc, const char * argv[]) {

  if(SDL_Init(SDL_INIT_EVERYTHING) < 0 )
  {
    std::cout << "Failed to initialise SDL!" << std::endl;
    return 1;
  }

  //Initialize PNG loading
  int imgFlags = IMG_INIT_PNG | IMG_INIT_JPG;
  if( !( IMG_Init( imgFlags ) & imgFlags ) )
  {
    std::cout << "Failed to initialise SDL_image!" << std::endl;
    return 1;
  }

  //Create window
  _window = SDL_CreateWindow( "RoboNeko", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN );
  SDL_SetWindowTitle(_window, "RoboNeko");

  if( _window == 0 )
  {
    printf( "Window could not be created! SDL_Error: %s\n", SDL_GetError() );
    return 1;
  }

  _renderer = SDL_CreateRenderer( _window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC );

  if( _renderer == 0 )
  {
    printf( "Renderer could not be created! SDL Error: %s\n", SDL_GetError() );
    return 1;
  }

  //Initialize renderer color
  SDL_SetRenderDrawColor( _renderer, 0xFF, 0xFF, 0xFF, 0xFF );

  // TODO: background texture
  //    SDL_Texture* gTexture = SDL_CreateTextureFromSurface( gRenderer, gTextureImage );

  bool quit = false;

  // event handler
  SDL_Event e;

  Robit* r1 = new Robit();
  Robit* r2 = new Robit();
  r2->p = {0, 100};

  // Main event loop

  do {
    while(SDL_PollEvent(&e) != 0)
    {
      switch (e.type) {
        case SDL_QUIT:
          quit = true;
        case SDL_MOUSEMOTION:
          SDL_GetMouseState( &mouseX, &mouseY );
        default:
          break;
      }
    }

    // Clear window
    SDL_SetRenderDrawColor( _renderer, 0xFF, 0xFF, 0xFF, 0xFF );
    SDL_RenderClear( _renderer );

    r1->doEvent();
    r2->doEvent();

    SDL_RenderPresent( _renderer );

  } while(!quit);

  //Destroy window
  SDL_DestroyWindow( _window );

  //Quit SDL subsystems
  SDL_Quit();

  return 0;
}
<commit_msg>Add a robot Stop method. Only move when mouse position has changed.<commit_after>//
//  main.cpp
//  RoboNeko
//
//  Created by nspool on 8/3/17.
//  Copyright © 2017 nspool. All rights reserved.
//

#include <iostream>

#include <math.h>

#include <SDL2_ttf/SDL_ttf.h>
#include <SDL2/SDL.h>
#include <SDL2_image/SDL_image.h>
#include <SDL2/SDL_timer.h>

const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;

TTF_Font *_font = 0;
SDL_Window* _window = 0;
SDL_Surface* _screenSurface = 0;
SDL_Surface* _background = 0;
SDL_Renderer* _renderer = 0;

int _startTime = SDL_GetTicks();
int mouseX = 0;
int mouseY = 0;
int oldMouseX = 0;
int oldMouseY = 0;

class Robit
{
public:
  static const int SPRITE_WIDTH = 32;
  static const int SPRITE_ANIMATION_LEN = 3;
  Robit();
  void doEvent();
  void stop();
  SDL_Point p = {0, 200};
private:
  double rad = M_PI_2;
  double xDelta = 0;
  double yDelta = 0;
  SDL_Rect spriteClips[3];
  int _animationRate = 12;
  SDL_Texture* gRobitsTexture;
};

Robit::Robit()
{
  // Load the robit
  SDL_Surface* gRobits = IMG_Load( "robits.png" );
//  SDL_Surface* gTextureImage = IMG_Load( "tex.png" );

  if(gRobits == 0) // || gTextureImage == 0)
  {
    printf( "Failed to load images! SDL_Error: %s\n", SDL_GetError() );
  }

  // Setup Robit animation
  spriteClips[0].x = 0;
  spriteClips[0].y = 0;
  spriteClips[0].w = 32;
  spriteClips[0].h = 32;

  spriteClips[1].x = 32;
  spriteClips[1].y = 0;
  spriteClips[1].w = 32;
  spriteClips[1].h = 32;

  spriteClips[2].x = 64;
  spriteClips[2].y = 0;
  spriteClips[2].w = 32;
  spriteClips[2].h = 32;

  gRobitsTexture = SDL_CreateTextureFromSurface( _renderer, gRobits );
  SDL_SetTextureColorMod( gRobitsTexture, 255, 25, 25 );
}

void Robit::stop()
{
  SDL_Rect robitLoc = { p.x, p.y, 32, 32 };
  SDL_RenderCopy( _renderer, gRobitsTexture, &spriteClips[1], &robitLoc );
}

void Robit::doEvent()
{

  if(oldMouseX == mouseX && oldMouseY == mouseY) {
    stop();
    return;
  }

  oldMouseY = mouseY;
  oldMouseX = mouseX;

  // Update |p| to new position
  rad = atan2((mouseY - p.y), (mouseX - p.x));
  xDelta += cos(rad);
  yDelta += sin(rad);

  if(xDelta > 1 || xDelta < -1){
    p.x += (int)xDelta;
    xDelta = 0;
  }

  if(yDelta > 1 || yDelta < -1){
    p.y += (int)yDelta;
    yDelta = 0;
  }

  // Bounds
  if(p.x < 0) { rad = 2 * M_PI; }
  if((p.x + SPRITE_WIDTH) > SCREEN_WIDTH) { rad = M_PI; }

  if(p.y < 0) { rad = M_PI_2; }
  if((p.y + SPRITE_WIDTH) > SCREEN_HEIGHT) { rad = -M_PI_2; }

  // Animate at some fixed framerate
  int frameToDraw = ((SDL_GetTicks() - _startTime) * _animationRate / 1000) % SPRITE_ANIMATION_LEN;
  SDL_Rect robitLoc = { p.x, p.y, 32, 32 };
  SDL_RenderCopy( _renderer, gRobitsTexture, &spriteClips[frameToDraw], &robitLoc );
}

SDL_Surface *load_image(std::string filename)
{
  SDL_Surface* loadedImage = 0;
  SDL_Surface* optimisedImage = 0;
  loadedImage = SDL_LoadBMP(filename.c_str());
  if(loadedImage != 0)
  {
    optimisedImage = SDL_ConvertSurface(loadedImage, _screenSurface->format, 0);
  }
  SDL_FreeSurface(loadedImage);
  return optimisedImage;
}

int main(int argc, const char * argv[]) {

  if(SDL_Init(SDL_INIT_EVERYTHING) < 0 )
  {
    std::cout << "Failed to initialise SDL!" << std::endl;
    return 1;
  }

  //Initialize PNG loading
  int imgFlags = IMG_INIT_PNG | IMG_INIT_JPG;
  if( !( IMG_Init( imgFlags ) & imgFlags ) )
  {
    std::cout << "Failed to initialise SDL_image!" << std::endl;
    return 1;
  }

  //Create window
  _window = SDL_CreateWindow( "RoboNeko", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN );
  SDL_SetWindowTitle(_window, "RoboNeko");

  if( _window == 0 )
  {
    printf( "Window could not be created! SDL_Error: %s\n", SDL_GetError() );
    return 1;
  }

  _renderer = SDL_CreateRenderer( _window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC );

  if( _renderer == 0 )
  {
    printf( "Renderer could not be created! SDL Error: %s\n", SDL_GetError() );
    return 1;
  }

  //Initialize renderer color
  SDL_SetRenderDrawColor( _renderer, 0xFF, 0xFF, 0xFF, 0xFF );

  // TODO: background texture
  //    SDL_Texture* gTexture = SDL_CreateTextureFromSurface( gRenderer, gTextureImage );

  bool quit = false;

  // event handler
  SDL_Event e;

  Robit* r1 = new Robit();
  Robit* r2 = new Robit();
  r2->p = {0, 100};

  // Main event loop

  do {
    while(SDL_PollEvent(&e) != 0)
    {
      switch (e.type) {
        case SDL_QUIT:
          quit = true;
        case SDL_MOUSEMOTION:
          SDL_GetMouseState( &mouseX, &mouseY );
        default:
          break;
      }
    }

    // Clear window
    SDL_SetRenderDrawColor( _renderer, 0xFF, 0xFF, 0xFF, 0xFF );
    SDL_RenderClear( _renderer );

    r1->doEvent();
//    r2->doEvent();

    SDL_RenderPresent( _renderer );

  } while(!quit);

  //Destroy window
  SDL_DestroyWindow( _window );

  //Quit SDL subsystems
  SDL_Quit();

  return 0;
}
<|endoftext|>


<commit_before>/**
 * search.tcc -
 * @author: Jonathan Beard
 * @version: Thu Jun 19 14:07:49 2014
 *
 * Copyright 2014 Jonathan Beard
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at:
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#ifndef _SEARCH_TCC_
#define _SEARCH_TCC_  1
#include <cassert>
#include <cstring>
#include <vector>
#include <functional>

enum SearchAlgorithm
{
   RabinKarp,
   KnuthMorrisPratt,
   Automata
};

#define CHUNKSIZE 65536
struct Chunk
{
   Chunk() : start_position( 0 ),
             length( 0 )
   {
      std::memset( chunk, '\0', CHUNKSIZE );
   }

   Chunk( const Chunk &other ) : start_position( other.start_position ),
                                 length( other.length )
   {
      std::strncpy( chunk, other.chunk, CHUNKSIZE );
   }

   void operator = ( const Chunk &other )
   {
      start_position = other.start_position;
      length         = other.length;
      std::strncpy( chunk, other.chunk, CHUNKSIZE );
   }

   size_t start_position;
   size_t length;
   char   chunk[ CHUNKSIZE ];
};

struct Hit
{
   Hit() : position( 0 ),
           pattern_index( 0 )
   {
   }

   Hit( const Hit &other ) : position( other.position ),
                             pattern_index( other.pattern_index )
   {

   }

   void operator = (const Hit &other )
   {
      position = other.position;
      pattern_index = other.pattern_index;
   }

   size_t position;
   size_t pattern_index;
};

typedef RingBuffer< Line > InputBuffer;
typedef RingBuffer< Hit  > OutputBuffer;

template < SearchAlgorithm algorithm,
           size_t THREADS,
           size_t BUFFSIZE = 100 > class Search
{
public:
   Search()          = delete;
   virtual ~Search() = delete;

   static void search( const std::string           filename,
                       std::vector< std::string >  &search_terms,
                       std::vector< std::string >  &hits )
   {

      std::array< std::thread*,  THREADS + 1 > thread_pool;
      std::array< InputBuffer*,  THREADS > input_buffer;
      std::array< OutputBuffer*, THREADS > output_buffer;

      /** allocate buffers **/
      for( size_t buff_id( 0 ); buff_id < THREADS; buff_id++ )
      {
         input_buffers[  buff_id ] = new InputBuffer( BUFFSIZE );
         output_buffers[ buff_id ] = new OutputBuffer( BUFFSIZE );
      }
      /** allocate a place to store the matches **/
      std::vector< Hit > hits;
      /** allocate consumer thread **/
      thread_pool[ THREADS ] = new std::thread( consumer_function,
                                                std::ref( output_buffer ),
                                                std::ref( hits ) )

      /**
       * get longest search term
       */
      const size_t m( 0 );
      for( const std::string &str : search_terms )
      {
         const auto l( str.length() );
         if( m < l )
         {
            m = l;
         }
      }

      std::function< void( InputBuffer*, OutputBuffer* ) > worker_function;
      switch( algorithm )
      {
         case( RabinKarp ):
         {
            const auto prime_number( 3571 );
            auto rkfunction = [&]( Line &line, std::vector< Hit > &hits )
            {

            };
            worker_function = std::bind( worker_function_base, _1, _2, std::ref( rkfunction ) );
         }
         break;
         case( KnuthMorrisPratt ):
         {
            auto kmpfunction = []( Line &line, std::vector< Hit > &hits )
            {

            };
            worker_function =
               std::bind( worker_function_base,
                          _1,
                          _2,
                          std::ref( kmpfunction ) );
         }
         break;
         case( Automata ):
         {
            auto atfunction = []( Line &line, std::vector< Hit > &hits )
            {

            };
            worker_function =
               std::bind( worker_function_base, _1, _2, std::ref( atfunction ) );
         }
         break;
         default:
            assert( false );
      }

      /** get input file **/
      std::ifstream file_input( filename, std::ifstream::binary );
      if( ! file_input.is_open() )
      {
         std::cerr << "Failed to open input file: " << filename << "\n";
         exit( EXIT_FAILURE );
      }

      /** get file size **/
      file_input
      for( size_t thread_id( 0 ); thread_id < THREADS; thread_id++ )
      {
         thread_pool[ thread_id ] = new std::thread( worker_function,
                                                     input_buffer[  thread_id ],
                                                     output_buffer[ thread_id ] );
      }

      size_t output_stream( 0 );
      while( file_input.good() )
      {
         auto *buffer( input_buffer[ output_stream ] );
         Line &line( buffer->allocate() );
         input_file.read( line.line_chunk );
         output_stream = ( output_stream + 1 ) % THREADS;
      }

      file_input.close();
   }
private:

   static void worker_function_base( InputBuffer *input,
                                     OutputBuffer *output,
                                     std::function<
                                     void ( Line&,
                                            std::vector< Hit >& ) >
                                             search_function )
   {
      assert( input != nullptr );
      assert( output != nullptr );
      bool exit( false );
      std::vector< Hit > local_hits;
      bool has_data( false );
      Line line;
      RBSignal signal( RBSignal::NONE );
      while( signal != RBSignal::RBEOF )
      {
         input->pop( line, &signal );
         search_function( line, local_hits );
         if( local_hits.size() > 0 )
         {
            output->insert( local_hits.begin(), local_hits.end(), signal );
            local_hits.clear();
         }
      }
   }

   static void consumer_function( std::array< OutputBuffer*, THREADS > &input,
                                  std::vector< Hit >                   &hits )
   {

   }
};
#endif /* END _SEARCH_TCC_ */
<commit_msg>updates<commit_after>/**
 * search.tcc -
 * @author: Jonathan Beard
 * @version: Thu Jun 19 14:07:49 2014
 *
 * Copyright 2014 Jonathan Beard
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at:
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#ifndef _SEARCH_TCC_
#define _SEARCH_TCC_  1
#include <cassert>
#include <cstring>
#include <vector>
#include <functional>

enum SearchAlgorithm
{
   RabinKarp,
   KnuthMorrisPratt,
   Automata
};

#define CHUNKSIZE 65536
struct Chunk
{
   Chunk() : start_position( 0 ),
             length( 0 )
   {
      std::memset( chunk, '\0', CHUNKSIZE );
   }

   Chunk( const Chunk &other ) : start_position( other.start_position ),
                                 length( other.length )
   {
      std::strncpy( chunk, other.chunk, CHUNKSIZE );
   }

   void operator = ( const Chunk &other )
   {
      start_position = other.start_position;
      length         = other.length;
      std::strncpy( chunk, other.chunk, CHUNKSIZE );
   }

   size_t start_position;
   size_t length;
   char   chunk[ CHUNKSIZE ];
};

struct Hit
{
   Hit() : position( 0 ),
           pattern_index( 0 )
   {
   }

   Hit( const Hit &other ) : position( other.position ),
                             pattern_index( other.pattern_index )
   {

   }

   void operator = (const Hit &other )
   {
      position = other.position;
      pattern_index = other.pattern_index;
   }

   size_t position;
   size_t pattern_index;
};

typedef RingBuffer< Line > InputBuffer;
typedef RingBuffer< Hit  > OutputBuffer;

template < SearchAlgorithm algorithm,
           size_t THREADS,
           size_t BUFFSIZE = 100 > class Search
{
public:
   Search()          = delete;
   virtual ~Search() = delete;

   static void search( const std::string           filename,
                       std::vector< std::string >  &search_terms,
                       std::vector< std::string >  &hits )
   {

      std::array< std::thread*,  THREADS + 1 > thread_pool;
      std::array< InputBuffer*,  THREADS > input_buffer;
      std::array< OutputBuffer*, THREADS > output_buffer;

      /** allocate buffers **/
      for( size_t buff_id( 0 ); buff_id < THREADS; buff_id++ )
      {
         input_buffers[  buff_id ] = new InputBuffer( BUFFSIZE );
         output_buffers[ buff_id ] = new OutputBuffer( BUFFSIZE );
      }
      /** allocate a place to store the matches **/
      std::vector< Hit > hits;
      /** allocate consumer thread **/
      thread_pool[ THREADS ] = new std::thread( consumer_function,
                                                std::ref( output_buffer ),
                                                std::ref( hits ) )

      /**
       * get longest search term
       */
      const size_t m( 0 );
      for( const std::string &str : search_terms )
      {
         const auto l( str.length() );
         if( m < l )
         {
            m = l;
         }
      }

      std::function< void( InputBuffer*, OutputBuffer* ) > worker_function;
      switch( algorithm )
      {
         case( RabinKarp ):
         {
            const auto prime_number( 3571 );
            auto rkfunction = [&]( Line &line, std::vector< Hit > &hits )
            {

            };
            worker_function = std::bind( worker_function_base, _1, _2, std::ref( rkfunction ) );
         }
         break;
         default:
            assert( false );
      }

      /** get input file **/
      std::ifstream file_input( filename, std::ifstream::binary );
      if( ! file_input.is_open() )
      {
         std::cerr << "Failed to open input file: " << filename << "\n";
         exit( EXIT_FAILURE );
      }

      /** get file size **/
      file_input
      for( size_t thread_id( 0 ); thread_id < THREADS; thread_id++ )
      {
         thread_pool[ thread_id ] = new std::thread( worker_function,
                                                     input_buffer[  thread_id ],
                                                     output_buffer[ thread_id ] );
      }

      size_t output_stream( 0 );
      while( file_input.good() )
      {
         auto *buffer( input_buffer[ output_stream ] );
         Line &line( buffer->allocate() );
         input_file.read( line.line_chunk );
         output_stream = ( output_stream + 1 ) % THREADS;
      }

      file_input.close();
   }
private:

   static void worker_function_base( InputBuffer *input,
                                     OutputBuffer *output,
                                     std::function<
                                     void ( Line&,
                                            std::vector< Hit >& ) >
                                             search_function )
   {
      assert( input != nullptr );
      assert( output != nullptr );
      bool exit( false );
      std::vector< Hit > local_hits;
      bool has_data( false );
      Line line;
      RBSignal signal( RBSignal::NONE );
      while( signal != RBSignal::RBEOF )
      {
         input->pop( line, &signal );
         search_function( line, local_hits );
         if( local_hits.size() > 0 )
         {
            output->insert( local_hits.begin(), local_hits.end(), signal );
            local_hits.clear();
         }
      }
   }

   static void consumer_function( std::array< OutputBuffer*, THREADS > &input,
                                  std::vector< Hit >                   &hits )
   {

   }
};
#endif /* END _SEARCH_TCC_ */
<|endoftext|>


<commit_before><commit_msg>Fix bit count helper<commit_after><|endoftext|>


<commit_before>#include "Diagnostics.h"

#include <clang/Basic/SourceManager.h>
#include <clang/Lex/LexDiagnostic.h>
#include <clang/Sema/SemaDiagnostic.h>

namespace ccons {

DiagnosticsProvider::DiagnosticsProvider(llvm::raw_os_ostream& out,
                                         const clang::LangOptions& opts)
	: _tdp(out, false, true, false)
	, _diag(this)
{
	_tdp.SetLangOpts(opts);
	_diag.setDiagnosticMapping(clang::diag::ext_implicit_function_decl,
	                           clang::diag::MAP_ERROR);
	_diag.setDiagnosticMapping(clang::diag::warn_unused_expr,
	                           clang::diag::MAP_IGNORE);
	_diag.setDiagnosticMapping(clang::diag::warn_missing_prototype,
	                           clang::diag::MAP_IGNORE);
	_diag.setDiagnosticMapping(clang::diag::pp_macro_not_used,
	                           clang::diag::MAP_IGNORE);
	_diag.setSuppressSystemWarnings(true);
}

void DiagnosticsProvider::HandleDiagnostic(clang::Diagnostic::Level DiagLevel,
                                           const clang::DiagnosticInfo &Info)
{
	std::pair<clang::diag::kind, unsigned> record = std::make_pair(Info.getID(),
		Info.getLocation().getManager().getFileOffset(Info.getLocation()) - _offs);
	if (_memory.insert(record).second) {
		_tdp.HandleDiagnostic(DiagLevel, Info);
	}
}

void DiagnosticsProvider::setOffset(unsigned offset)
{
	_offs = offset;
}

clang::Diagnostic * DiagnosticsProvider::getDiagnostic()
{
	return &_diag;
}

} // namespace ccons

<commit_msg>don't print -W option since ccons doesn't support these<commit_after>#include "Diagnostics.h"

#include <clang/Basic/SourceManager.h>
#include <clang/Lex/LexDiagnostic.h>
#include <clang/Sema/SemaDiagnostic.h>

namespace ccons {

DiagnosticsProvider::DiagnosticsProvider(llvm::raw_os_ostream& out,
                                         const clang::LangOptions& opts)
	: _tdp(out, false, true, false, true, false)
	, _diag(this)
{
	_tdp.SetLangOpts(opts);
	_diag.setDiagnosticMapping(clang::diag::ext_implicit_function_decl,
	                           clang::diag::MAP_ERROR);
	_diag.setDiagnosticMapping(clang::diag::warn_unused_expr,
	                           clang::diag::MAP_IGNORE);
	_diag.setDiagnosticMapping(clang::diag::warn_missing_prototype,
	                           clang::diag::MAP_IGNORE);
	_diag.setDiagnosticMapping(clang::diag::pp_macro_not_used,
	                           clang::diag::MAP_IGNORE);
	_diag.setSuppressSystemWarnings(true);
}

void DiagnosticsProvider::HandleDiagnostic(clang::Diagnostic::Level DiagLevel,
                                           const clang::DiagnosticInfo &Info)
{
	std::pair<clang::diag::kind, unsigned> record = std::make_pair(Info.getID(),
		Info.getLocation().getManager().getFileOffset(Info.getLocation()) - _offs);
	if (_memory.insert(record).second) {
		_tdp.HandleDiagnostic(DiagLevel, Info);
	}
}

void DiagnosticsProvider::setOffset(unsigned offset)
{
	_offs = offset;
}

clang::Diagnostic * DiagnosticsProvider::getDiagnostic()
{
	return &_diag;
}

} // namespace ccons

<|endoftext|>


<commit_before>/*
 * libjingle
 * Copyright 2011 Google Inc.
 *
 * 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. The name of the author may not be used to endorse or promote products
 *     derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
 */

#include "talk/media/webrtc/webrtcvideoframe.h"

#include "libyuv/convert.h"
#include "talk/media/base/videocapturer.h"
#include "talk/media/base/videocommon.h"
#include "webrtc/base/logging.h"
#include "webrtc/video_frame.h"

using webrtc::kYPlane;
using webrtc::kUPlane;
using webrtc::kVPlane;

namespace cricket {

WebRtcVideoFrame::WebRtcVideoFrame():
    pixel_width_(0),
    pixel_height_(0),
    elapsed_time_ns_(0),
    time_stamp_ns_(0),
    rotation_(webrtc::kVideoRotation_0) {}

WebRtcVideoFrame::WebRtcVideoFrame(
    const rtc::scoped_refptr<webrtc::VideoFrameBuffer>& buffer,
    int64_t elapsed_time_ns,
    int64_t time_stamp_ns,
    webrtc::VideoRotation rotation)
    : video_frame_buffer_(buffer),
      pixel_width_(1),
      pixel_height_(1),
      elapsed_time_ns_(elapsed_time_ns),
      time_stamp_ns_(time_stamp_ns),
      rotation_(rotation) {
}

WebRtcVideoFrame::WebRtcVideoFrame(
    const rtc::scoped_refptr<webrtc::VideoFrameBuffer>& buffer,
    int64_t elapsed_time_ns,
    int64_t time_stamp_ns)
    : video_frame_buffer_(buffer),
      pixel_width_(1),
      pixel_height_(1),
      elapsed_time_ns_(elapsed_time_ns),
      time_stamp_ns_(time_stamp_ns),
      rotation_(webrtc::kVideoRotation_0) {
}

WebRtcVideoFrame::~WebRtcVideoFrame() {}

bool WebRtcVideoFrame::Init(uint32 format,
                            int w,
                            int h,
                            int dw,
                            int dh,
                            uint8* sample,
                            size_t sample_size,
                            size_t pixel_width,
                            size_t pixel_height,
                            int64_t elapsed_time_ns,
                            int64_t time_stamp_ns,
                            webrtc::VideoRotation rotation) {
  return Reset(format, w, h, dw, dh, sample, sample_size, pixel_width,
               pixel_height, elapsed_time_ns, time_stamp_ns, rotation,
               true /*apply_rotation*/);
}

bool WebRtcVideoFrame::Init(const CapturedFrame* frame, int dw, int dh,
                            bool apply_rotation) {
  return Reset(frame->fourcc, frame->width, frame->height, dw, dh,
               static_cast<uint8*>(frame->data), frame->data_size,
               frame->pixel_width, frame->pixel_height, frame->elapsed_time,
               frame->time_stamp,
               frame->GetRotation(),
               apply_rotation);
}

bool WebRtcVideoFrame::InitToBlack(int w, int h, size_t pixel_width,
                                   size_t pixel_height, int64_t elapsed_time_ns,
                                   int64_t time_stamp_ns) {
  InitToEmptyBuffer(w, h, pixel_width, pixel_height, elapsed_time_ns,
                    time_stamp_ns);
  return SetToBlack();
}

size_t WebRtcVideoFrame::GetWidth() const {
  return video_frame_buffer_ ? video_frame_buffer_->width() : 0;
}

size_t WebRtcVideoFrame::GetHeight() const {
  return video_frame_buffer_ ? video_frame_buffer_->height() : 0;
}

const uint8* WebRtcVideoFrame::GetYPlane() const {
  // Const cast to call the correct const-version of data.
  const webrtc::VideoFrameBuffer* const_ptr = video_frame_buffer_.get();
  return const_ptr ? const_ptr->data(kYPlane) : nullptr;
}

const uint8* WebRtcVideoFrame::GetUPlane() const {
  // Const cast to call the correct const-version of data.
  const webrtc::VideoFrameBuffer* const_ptr = video_frame_buffer_.get();
  return const_ptr ? const_ptr->data(kUPlane) : nullptr;
}

const uint8* WebRtcVideoFrame::GetVPlane() const {
  // Const cast to call the correct const-version of data.
  const webrtc::VideoFrameBuffer* const_ptr = video_frame_buffer_.get();
  return const_ptr ? const_ptr->data(kVPlane) : nullptr;
}

uint8* WebRtcVideoFrame::GetYPlane() {
  return video_frame_buffer_ ? video_frame_buffer_->data(kYPlane) : nullptr;
}

uint8* WebRtcVideoFrame::GetUPlane() {
  return video_frame_buffer_ ? video_frame_buffer_->data(kUPlane) : nullptr;
}

uint8* WebRtcVideoFrame::GetVPlane() {
  return video_frame_buffer_ ? video_frame_buffer_->data(kVPlane) : nullptr;
}

int32 WebRtcVideoFrame::GetYPitch() const {
  return video_frame_buffer_ ? video_frame_buffer_->stride(kYPlane) : 0;
}

int32 WebRtcVideoFrame::GetUPitch() const {
  return video_frame_buffer_ ? video_frame_buffer_->stride(kUPlane) : 0;
}

int32 WebRtcVideoFrame::GetVPitch() const {
  return video_frame_buffer_ ? video_frame_buffer_->stride(kVPlane) : 0;
}

bool WebRtcVideoFrame::IsExclusive() const {
  return video_frame_buffer_->HasOneRef();
}

void* WebRtcVideoFrame::GetNativeHandle() const {
  return video_frame_buffer_ ? video_frame_buffer_->native_handle() : nullptr;
}

rtc::scoped_refptr<webrtc::VideoFrameBuffer>
WebRtcVideoFrame::GetVideoFrameBuffer() const {
  return video_frame_buffer_;
}

VideoFrame* WebRtcVideoFrame::Copy() const {
  WebRtcVideoFrame* new_frame = new WebRtcVideoFrame(
      video_frame_buffer_, elapsed_time_ns_, time_stamp_ns_, rotation_);
  new_frame->pixel_width_ = pixel_width_;
  new_frame->pixel_height_ = pixel_height_;
  return new_frame;
}

bool WebRtcVideoFrame::MakeExclusive() {
  DCHECK(video_frame_buffer_->native_handle() == nullptr);
  if (IsExclusive())
    return true;

  // Not exclusive already, need to copy buffer.
  rtc::scoped_refptr<webrtc::VideoFrameBuffer> new_buffer =
      new rtc::RefCountedObject<webrtc::I420Buffer>(
          video_frame_buffer_->width(), video_frame_buffer_->height(),
          video_frame_buffer_->stride(kYPlane),
          video_frame_buffer_->stride(kUPlane),
          video_frame_buffer_->stride(kVPlane));

  if (!CopyToPlanes(new_buffer->data(kYPlane), new_buffer->data(kUPlane),
                    new_buffer->data(kVPlane), new_buffer->stride(kYPlane),
                    new_buffer->stride(kUPlane), new_buffer->stride(kVPlane))) {
    return false;
  }

  video_frame_buffer_ = new_buffer;
  return true;
}

size_t WebRtcVideoFrame::ConvertToRgbBuffer(uint32 to_fourcc, uint8* buffer,
                                            size_t size, int stride_rgb) const {
  CHECK(video_frame_buffer_);
  CHECK(video_frame_buffer_->native_handle() == nullptr);
  return VideoFrame::ConvertToRgbBuffer(to_fourcc, buffer, size, stride_rgb);
}

bool WebRtcVideoFrame::Reset(uint32 format,
                             int w,
                             int h,
                             int dw,
                             int dh,
                             uint8* sample,
                             size_t sample_size,
                             size_t pixel_width,
                             size_t pixel_height,
                             int64_t elapsed_time_ns,
                             int64_t time_stamp_ns,
                             webrtc::VideoRotation rotation,
                             bool apply_rotation) {
  if (!Validate(format, w, h, sample, sample_size)) {
    return false;
  }
  // Translate aliases to standard enums (e.g., IYUV -> I420).
  format = CanonicalFourCC(format);

  // Set up a new buffer.
  // TODO(fbarchard): Support lazy allocation.
  int new_width = dw;
  int new_height = dh;
  // If rotated swap width, height.
  if (apply_rotation && (rotation == 90 || rotation == 270)) {
    new_width = dh;
    new_height = dw;
  }

  InitToEmptyBuffer(new_width, new_height, pixel_width, pixel_height,
                    elapsed_time_ns, time_stamp_ns);
  rotation_ = apply_rotation ? webrtc::kVideoRotation_0 : rotation;

  int horiz_crop = ((w - dw) / 2) & ~1;
  // ARGB on Windows has negative height.
  // The sample's layout in memory is normal, so just correct crop.
  int vert_crop = ((abs(h) - dh) / 2) & ~1;
  // Conversion functions expect negative height to flip the image.
  int idh = (h < 0) ? -dh : dh;
  int r = libyuv::ConvertToI420(
      sample, sample_size,
      GetYPlane(), GetYPitch(),
      GetUPlane(), GetUPitch(),
      GetVPlane(), GetVPitch(),
      horiz_crop, vert_crop,
      w, h,
      dw, idh,
      static_cast<libyuv::RotationMode>(
          apply_rotation ? rotation : webrtc::kVideoRotation_0),
      format);
  if (r) {
    LOG(LS_ERROR) << "Error parsing format: " << GetFourccName(format)
                  << " return code : " << r;
    return false;
  }
  return true;
}

VideoFrame* WebRtcVideoFrame::CreateEmptyFrame(
    int w, int h, size_t pixel_width, size_t pixel_height,
    int64_t elapsed_time_ns, int64_t time_stamp_ns) const {
  WebRtcVideoFrame* frame = new WebRtcVideoFrame();
  frame->InitToEmptyBuffer(w, h, pixel_width, pixel_height, elapsed_time_ns,
                           time_stamp_ns);
  return frame;
}

void WebRtcVideoFrame::InitToEmptyBuffer(int w, int h, size_t pixel_width,
                                         size_t pixel_height,
                                         int64_t elapsed_time_ns,
                                         int64_t time_stamp_ns) {
  video_frame_buffer_ = new rtc::RefCountedObject<webrtc::I420Buffer>(w, h);
  pixel_width_ = pixel_width;
  pixel_height_ = pixel_height;
  elapsed_time_ns_ = elapsed_time_ns;
  time_stamp_ns_ = time_stamp_ns;
  rotation_ = webrtc::kVideoRotation_0;
}

const VideoFrame* WebRtcVideoFrame::GetCopyWithRotationApplied() const {
  // If the frame is not rotated, the caller should reuse this frame instead of
  // making a redundant copy.
  if (GetVideoRotation() == webrtc::kVideoRotation_0) {
    return this;
  }

  // If the video frame is backed up by a native handle, it resides in the GPU
  // memory which we can't rotate here. The assumption is that the renderers
  // which uses GPU to render should be able to rotate themselves.
  DCHECK(!GetNativeHandle());

  if (rotated_frame_) {
    return rotated_frame_.get();
  }

  int width = static_cast<int>(GetWidth());
  int height = static_cast<int>(GetHeight());

  int rotated_width = width;
  int rotated_height = height;
  if (GetVideoRotation() == webrtc::kVideoRotation_90 ||
      GetVideoRotation() == webrtc::kVideoRotation_270) {
    rotated_width = height;
    rotated_height = width;
  }

  rotated_frame_.reset(CreateEmptyFrame(rotated_width, rotated_height,
                                        GetPixelWidth(), GetPixelHeight(),
                                        GetElapsedTime(), GetTimeStamp()));

  // TODO(guoweis): Add a function in webrtc_libyuv.cc to convert from
  // VideoRotation to libyuv::RotationMode.
  int ret = libyuv::I420Rotate(
      GetYPlane(), GetYPitch(), GetUPlane(), GetUPitch(), GetVPlane(),
      GetVPitch(), rotated_frame_->GetYPlane(), rotated_frame_->GetYPitch(),
      rotated_frame_->GetUPlane(), rotated_frame_->GetUPitch(),
      rotated_frame_->GetVPlane(), rotated_frame_->GetVPitch(), width, height,
      static_cast<libyuv::RotationMode>(GetVideoRotation()));
  if (ret == 0) {
    return rotated_frame_.get();
  }
  return nullptr;
}

}  // namespace cricket
<commit_msg>VideoFrameBuffer: Make non-const data access explicit<commit_after>/*
 * libjingle
 * Copyright 2011 Google Inc.
 *
 * 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. The name of the author may not be used to endorse or promote products
 *     derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
 */

#include "talk/media/webrtc/webrtcvideoframe.h"

#include "libyuv/convert.h"
#include "talk/media/base/videocapturer.h"
#include "talk/media/base/videocommon.h"
#include "webrtc/base/logging.h"
#include "webrtc/video_frame.h"

using webrtc::kYPlane;
using webrtc::kUPlane;
using webrtc::kVPlane;

namespace cricket {

WebRtcVideoFrame::WebRtcVideoFrame():
    pixel_width_(0),
    pixel_height_(0),
    elapsed_time_ns_(0),
    time_stamp_ns_(0),
    rotation_(webrtc::kVideoRotation_0) {}

WebRtcVideoFrame::WebRtcVideoFrame(
    const rtc::scoped_refptr<webrtc::VideoFrameBuffer>& buffer,
    int64_t elapsed_time_ns,
    int64_t time_stamp_ns,
    webrtc::VideoRotation rotation)
    : video_frame_buffer_(buffer),
      pixel_width_(1),
      pixel_height_(1),
      elapsed_time_ns_(elapsed_time_ns),
      time_stamp_ns_(time_stamp_ns),
      rotation_(rotation) {
}

WebRtcVideoFrame::WebRtcVideoFrame(
    const rtc::scoped_refptr<webrtc::VideoFrameBuffer>& buffer,
    int64_t elapsed_time_ns,
    int64_t time_stamp_ns)
    : video_frame_buffer_(buffer),
      pixel_width_(1),
      pixel_height_(1),
      elapsed_time_ns_(elapsed_time_ns),
      time_stamp_ns_(time_stamp_ns),
      rotation_(webrtc::kVideoRotation_0) {
}

WebRtcVideoFrame::~WebRtcVideoFrame() {}

bool WebRtcVideoFrame::Init(uint32 format,
                            int w,
                            int h,
                            int dw,
                            int dh,
                            uint8* sample,
                            size_t sample_size,
                            size_t pixel_width,
                            size_t pixel_height,
                            int64_t elapsed_time_ns,
                            int64_t time_stamp_ns,
                            webrtc::VideoRotation rotation) {
  return Reset(format, w, h, dw, dh, sample, sample_size, pixel_width,
               pixel_height, elapsed_time_ns, time_stamp_ns, rotation,
               true /*apply_rotation*/);
}

bool WebRtcVideoFrame::Init(const CapturedFrame* frame, int dw, int dh,
                            bool apply_rotation) {
  return Reset(frame->fourcc, frame->width, frame->height, dw, dh,
               static_cast<uint8*>(frame->data), frame->data_size,
               frame->pixel_width, frame->pixel_height, frame->elapsed_time,
               frame->time_stamp,
               frame->GetRotation(),
               apply_rotation);
}

bool WebRtcVideoFrame::InitToBlack(int w, int h, size_t pixel_width,
                                   size_t pixel_height, int64_t elapsed_time_ns,
                                   int64_t time_stamp_ns) {
  InitToEmptyBuffer(w, h, pixel_width, pixel_height, elapsed_time_ns,
                    time_stamp_ns);
  return SetToBlack();
}

size_t WebRtcVideoFrame::GetWidth() const {
  return video_frame_buffer_ ? video_frame_buffer_->width() : 0;
}

size_t WebRtcVideoFrame::GetHeight() const {
  return video_frame_buffer_ ? video_frame_buffer_->height() : 0;
}

const uint8* WebRtcVideoFrame::GetYPlane() const {
  return video_frame_buffer_ ? video_frame_buffer_->data(kYPlane) : nullptr;
}

const uint8* WebRtcVideoFrame::GetUPlane() const {
  return video_frame_buffer_ ? video_frame_buffer_->data(kUPlane) : nullptr;
}

const uint8* WebRtcVideoFrame::GetVPlane() const {
  return video_frame_buffer_ ? video_frame_buffer_->data(kVPlane) : nullptr;
}

uint8* WebRtcVideoFrame::GetYPlane() {
  return video_frame_buffer_ ? video_frame_buffer_->MutableData(kYPlane)
                             : nullptr;
}

uint8* WebRtcVideoFrame::GetUPlane() {
  return video_frame_buffer_ ? video_frame_buffer_->MutableData(kUPlane)
                             : nullptr;
}

uint8* WebRtcVideoFrame::GetVPlane() {
  return video_frame_buffer_ ? video_frame_buffer_->MutableData(kVPlane)
                             : nullptr;
}

int32 WebRtcVideoFrame::GetYPitch() const {
  return video_frame_buffer_ ? video_frame_buffer_->stride(kYPlane) : 0;
}

int32 WebRtcVideoFrame::GetUPitch() const {
  return video_frame_buffer_ ? video_frame_buffer_->stride(kUPlane) : 0;
}

int32 WebRtcVideoFrame::GetVPitch() const {
  return video_frame_buffer_ ? video_frame_buffer_->stride(kVPlane) : 0;
}

bool WebRtcVideoFrame::IsExclusive() const {
  return video_frame_buffer_->HasOneRef();
}

void* WebRtcVideoFrame::GetNativeHandle() const {
  return video_frame_buffer_ ? video_frame_buffer_->native_handle() : nullptr;
}

rtc::scoped_refptr<webrtc::VideoFrameBuffer>
WebRtcVideoFrame::GetVideoFrameBuffer() const {
  return video_frame_buffer_;
}

VideoFrame* WebRtcVideoFrame::Copy() const {
  WebRtcVideoFrame* new_frame = new WebRtcVideoFrame(
      video_frame_buffer_, elapsed_time_ns_, time_stamp_ns_, rotation_);
  new_frame->pixel_width_ = pixel_width_;
  new_frame->pixel_height_ = pixel_height_;
  return new_frame;
}

bool WebRtcVideoFrame::MakeExclusive() {
  DCHECK(video_frame_buffer_->native_handle() == nullptr);
  if (IsExclusive())
    return true;

  // Not exclusive already, need to copy buffer.
  rtc::scoped_refptr<webrtc::VideoFrameBuffer> new_buffer =
      new rtc::RefCountedObject<webrtc::I420Buffer>(
          video_frame_buffer_->width(), video_frame_buffer_->height(),
          video_frame_buffer_->stride(kYPlane),
          video_frame_buffer_->stride(kUPlane),
          video_frame_buffer_->stride(kVPlane));

  if (!CopyToPlanes(
          new_buffer->MutableData(kYPlane), new_buffer->MutableData(kUPlane),
          new_buffer->MutableData(kVPlane), new_buffer->stride(kYPlane),
          new_buffer->stride(kUPlane), new_buffer->stride(kVPlane))) {
    return false;
  }

  video_frame_buffer_ = new_buffer;
  return true;
}

size_t WebRtcVideoFrame::ConvertToRgbBuffer(uint32 to_fourcc, uint8* buffer,
                                            size_t size, int stride_rgb) const {
  CHECK(video_frame_buffer_);
  CHECK(video_frame_buffer_->native_handle() == nullptr);
  return VideoFrame::ConvertToRgbBuffer(to_fourcc, buffer, size, stride_rgb);
}

bool WebRtcVideoFrame::Reset(uint32 format,
                             int w,
                             int h,
                             int dw,
                             int dh,
                             uint8* sample,
                             size_t sample_size,
                             size_t pixel_width,
                             size_t pixel_height,
                             int64_t elapsed_time_ns,
                             int64_t time_stamp_ns,
                             webrtc::VideoRotation rotation,
                             bool apply_rotation) {
  if (!Validate(format, w, h, sample, sample_size)) {
    return false;
  }
  // Translate aliases to standard enums (e.g., IYUV -> I420).
  format = CanonicalFourCC(format);

  // Set up a new buffer.
  // TODO(fbarchard): Support lazy allocation.
  int new_width = dw;
  int new_height = dh;
  // If rotated swap width, height.
  if (apply_rotation && (rotation == 90 || rotation == 270)) {
    new_width = dh;
    new_height = dw;
  }

  InitToEmptyBuffer(new_width, new_height, pixel_width, pixel_height,
                    elapsed_time_ns, time_stamp_ns);
  rotation_ = apply_rotation ? webrtc::kVideoRotation_0 : rotation;

  int horiz_crop = ((w - dw) / 2) & ~1;
  // ARGB on Windows has negative height.
  // The sample's layout in memory is normal, so just correct crop.
  int vert_crop = ((abs(h) - dh) / 2) & ~1;
  // Conversion functions expect negative height to flip the image.
  int idh = (h < 0) ? -dh : dh;
  int r = libyuv::ConvertToI420(
      sample, sample_size,
      GetYPlane(), GetYPitch(),
      GetUPlane(), GetUPitch(),
      GetVPlane(), GetVPitch(),
      horiz_crop, vert_crop,
      w, h,
      dw, idh,
      static_cast<libyuv::RotationMode>(
          apply_rotation ? rotation : webrtc::kVideoRotation_0),
      format);
  if (r) {
    LOG(LS_ERROR) << "Error parsing format: " << GetFourccName(format)
                  << " return code : " << r;
    return false;
  }
  return true;
}

VideoFrame* WebRtcVideoFrame::CreateEmptyFrame(
    int w, int h, size_t pixel_width, size_t pixel_height,
    int64_t elapsed_time_ns, int64_t time_stamp_ns) const {
  WebRtcVideoFrame* frame = new WebRtcVideoFrame();
  frame->InitToEmptyBuffer(w, h, pixel_width, pixel_height, elapsed_time_ns,
                           time_stamp_ns);
  return frame;
}

void WebRtcVideoFrame::InitToEmptyBuffer(int w, int h, size_t pixel_width,
                                         size_t pixel_height,
                                         int64_t elapsed_time_ns,
                                         int64_t time_stamp_ns) {
  video_frame_buffer_ = new rtc::RefCountedObject<webrtc::I420Buffer>(w, h);
  pixel_width_ = pixel_width;
  pixel_height_ = pixel_height;
  elapsed_time_ns_ = elapsed_time_ns;
  time_stamp_ns_ = time_stamp_ns;
  rotation_ = webrtc::kVideoRotation_0;
}

const VideoFrame* WebRtcVideoFrame::GetCopyWithRotationApplied() const {
  // If the frame is not rotated, the caller should reuse this frame instead of
  // making a redundant copy.
  if (GetVideoRotation() == webrtc::kVideoRotation_0) {
    return this;
  }

  // If the video frame is backed up by a native handle, it resides in the GPU
  // memory which we can't rotate here. The assumption is that the renderers
  // which uses GPU to render should be able to rotate themselves.
  DCHECK(!GetNativeHandle());

  if (rotated_frame_) {
    return rotated_frame_.get();
  }

  int width = static_cast<int>(GetWidth());
  int height = static_cast<int>(GetHeight());

  int rotated_width = width;
  int rotated_height = height;
  if (GetVideoRotation() == webrtc::kVideoRotation_90 ||
      GetVideoRotation() == webrtc::kVideoRotation_270) {
    rotated_width = height;
    rotated_height = width;
  }

  rotated_frame_.reset(CreateEmptyFrame(rotated_width, rotated_height,
                                        GetPixelWidth(), GetPixelHeight(),
                                        GetElapsedTime(), GetTimeStamp()));

  // TODO(guoweis): Add a function in webrtc_libyuv.cc to convert from
  // VideoRotation to libyuv::RotationMode.
  int ret = libyuv::I420Rotate(
      GetYPlane(), GetYPitch(), GetUPlane(), GetUPitch(), GetVPlane(),
      GetVPitch(), rotated_frame_->GetYPlane(), rotated_frame_->GetYPitch(),
      rotated_frame_->GetUPlane(), rotated_frame_->GetUPitch(),
      rotated_frame_->GetVPlane(), rotated_frame_->GetVPitch(), width, height,
      static_cast<libyuv::RotationMode>(GetVideoRotation()));
  if (ret == 0) {
    return rotated_frame_.get();
  }
  return nullptr;
}

}  // namespace cricket
<|endoftext|>