<commit_before>//============================================================================
// Name        : IEffect.cpp
// Author      : Duarte Peixinho
// Version     :
// Copyright   : ;)
// Description : Effect Interface
//============================================================================

#include <Pyros3D/Rendering/PostEffects/Effects/IEffect.h>

namespace p3d {

    IEffect::IEffect(const uint32 Width, const uint32 Height)
    {

        // Reset Handles
        positionHandle = texcoordHandle = -2;

        // Initialize Shaders
        shader = new Shader();

        // Set Vertex Shader
        // Because its always the same
        VertexShaderString =
                                "attribute vec3 aPosition;\n"
                                "attribute vec2 aTexcoord;\n"
                                "varying vec2 vTexcoord;\n"
                                "void main() {\n"
                                    "gl_Position = vec4(aPosition,1.0);\n"
                                    "vTexcoord = aTexcoord;\n"
                                "}\n";

        // Reset
        TextureUnits = 0;

		// Set FrameBuffers
		fbo = new FrameBuffer();

		attachment = new Texture();
		attachment->CreateEmptyTexture(TextureType::Texture, TextureDataType::RGBA, Width, Height);
		attachment->SetRepeat(TextureRepeat::ClampToEdge, TextureRepeat::ClampToEdge, TextureRepeat::ClampToEdge);
		fbo->Init(FrameBufferAttachmentFormat::Color_Attachment0, TextureType::Texture, attachment);

		this->Width = Width;
		this->Height = Height;

    }

    void IEffect::UseRTT(const uint32 RTT)
    {
        // Set Textures
        if (RTT & RTT::Color) UseColor();
        if (RTT & RTT::LastRTT) UseLastRTT();
        if (RTT & RTT::Depth) UseDepth();
    }

    void IEffect::CompileShaders()
    {
        shader->LoadShaderText(VertexShaderString);
        shader->CompileShader(ShaderType::VertexShader);

        shader->LoadShaderText(FragmentShaderString);
        shader->CompileShader(ShaderType::FragmentShader);

		shader->LinkProgram();
    }

    IEffect::~IEffect()
	{
		shader->DeleteShader();
		delete shader;
		delete fbo;
		delete attachment;
    }

    Uniform* IEffect::AddUniform(const Uniform &Data)
    {
		for (std::list<__UniformPostProcess>::iterator i = Uniforms.begin(); i != Uniforms.end(); i++)
		{
			if ((*i).uniform.NameID == Data.NameID)
			{
				Uniforms.erase(i);
				break;
			}
		}
		Uniforms.push_back(__UniformPostProcess(Data));
		return &Uniforms.back().uniform;
    }

    void IEffect::UseColor()
    {
        Uniform Color;
        std::ostringstream toSTR; toSTR << "uTex" << TextureUnits;
        Color.Name = toSTR.str();
        Color.Type = Uniforms::DataType::Int;
        Color.Usage = Uniforms::PostEffects::Other;
        Color.SetValue(&TextureUnits);
        AddUniform(Color);

        // Set RTT Order
        RTTOrder.push_back(RTT::Info(RTT::Color, TextureUnits));

        TextureUnits++;
    }
    void IEffect::UseDepth()
    {
        Uniform Depth;
        std::ostringstream toSTR; toSTR << "uTex" << TextureUnits;
        Depth.Name = toSTR.str();
        Depth.Type = Uniforms::DataType::Int;
        Depth.Usage = Uniforms::PostEffects::Other;
        Depth.SetValue(&TextureUnits);
        AddUniform(Depth);

        // Set RTT Order
        RTTOrder.push_back(RTT::Info(RTT::Depth, TextureUnits));

        TextureUnits++;
    }
    void IEffect::UseLastRTT()
    {
        Uniform RTT;
        std::ostringstream toSTR; toSTR << "uTex" << TextureUnits;
        RTT.Name = toSTR.str();
        RTT.Type = Uniforms::DataType::Int;
        RTT.Usage = Uniforms::PostEffects::Other;
        RTT.SetValue(&TextureUnits);
        AddUniform(RTT);

        // Set RTT Order
        RTTOrder.push_back(RTT::Info(RTT::LastRTT, TextureUnits));

        TextureUnits++;
    }
    void IEffect::UseCustomTexture(Texture* texture)
    {
        Uniform CustomTexture;
        std::ostringstream toSTR; toSTR << "uTex" << TextureUnits;
        CustomTexture.Name = toSTR.str();
        CustomTexture.Type = Uniforms::DataType::Int;
        CustomTexture.Usage = Uniforms::PostEffects::Other;
        CustomTexture.SetValue(&TextureUnits);
        AddUniform(CustomTexture);

        // Set RTT Order
        RTTOrder.push_back(RTT::Info(texture, RTT::CustomTexture, TextureUnits));

        TextureUnits++;
    }

    void IEffect::Resize(const uint32 width, const uint32 height)
    {
        // Save Dimensions
        Width = width;
        Height = height;
		fbo->Resize(width, height);
    }

    const uint32 IEffect::GetWidth() const
    {
        return Width;
    }
    const uint32 IEffect::GetHeight() const
    {
        return Height;
    }
}<commit_msg>Fixed Depth Of Field<commit_after>//============================================================================
// Name        : IEffect.cpp
// Author      : Duarte Peixinho
// Version     :
// Copyright   : ;)
// Description : Effect Interface
//============================================================================

#include <Pyros3D/Rendering/PostEffects/Effects/IEffect.h>

namespace p3d {

    IEffect::IEffect(const uint32 Width, const uint32 Height)
    {

        // Reset Handles
        positionHandle = texcoordHandle = -2;

        // Initialize Shaders
        shader = new Shader();

        // Set Vertex Shader
        // Because its always the same
        VertexShaderString =
                                "attribute vec3 aPosition;\n"
                                "attribute vec2 aTexcoord;\n"
                                "varying vec2 vTexcoord;\n"
                                "void main() {\n"
                                    "gl_Position = vec4(aPosition,1.0);\n"
                                    "vTexcoord = aTexcoord;\n"
                                "}\n";

        // Reset
        TextureUnits = 0;

		// Set FrameBuffers
		fbo = new FrameBuffer();

		attachment = new Texture();
		attachment->CreateEmptyTexture(TextureType::Texture, TextureDataType::RGBA, Width, Height);
		attachment->SetRepeat(TextureRepeat::ClampToEdge, TextureRepeat::ClampToEdge, TextureRepeat::ClampToEdge);
		fbo->Init(FrameBufferAttachmentFormat::Color_Attachment0, TextureType::Texture, attachment);

		this->Width = Width;
		this->Height = Height;

    }

    void IEffect::UseRTT(const uint32 RTT)
    {
        // Set Textures
        if (RTT & RTT::Color) UseColor();
        if (RTT & RTT::LastRTT) UseLastRTT();
        if (RTT & RTT::Depth) UseDepth();
    }

    void IEffect::CompileShaders()
    {
        shader->LoadShaderText(VertexShaderString);
        shader->CompileShader(ShaderType::VertexShader);

        shader->LoadShaderText(FragmentShaderString);
        shader->CompileShader(ShaderType::FragmentShader);

		shader->LinkProgram();
    }

    IEffect::~IEffect()
	{
		shader->DeleteShader();
		delete shader;
		delete fbo;
		delete attachment;
    }

    Uniform* IEffect::AddUniform(const Uniform &Data)
    {
		for (std::list<__UniformPostProcess>::iterator i = Uniforms.begin(); i != Uniforms.end(); i++)
		{
			if ((*i).uniform.NameID == Data.NameID)
			{
				Uniforms.erase(i);
				break;
			}
		}
		Uniforms.push_back(__UniformPostProcess(Data));
		return &Uniforms.back().uniform;
    }

    void IEffect::UseColor()
    {
        Uniform Color;
        std::ostringstream toSTR; toSTR << "uTex" << TextureUnits;
        AddUniform(Uniform(toSTR.str(), Uniforms::DataType::Int, &TextureUnits));

        // Set RTT Order
        RTTOrder.push_back(RTT::Info(RTT::Color, TextureUnits));

        TextureUnits++;
    }
    void IEffect::UseDepth()
    {
        Uniform Depth;
        std::ostringstream toSTR; toSTR << "uTex" << TextureUnits;
		AddUniform(Uniform(toSTR.str(), Uniforms::DataType::Int, &TextureUnits));

        // Set RTT Order
        RTTOrder.push_back(RTT::Info(RTT::Depth, TextureUnits));

        TextureUnits++;
    }
    void IEffect::UseLastRTT()
    {
        Uniform RTT;
        std::ostringstream toSTR; toSTR << "uTex" << TextureUnits;
		AddUniform(Uniform(toSTR.str(), Uniforms::DataType::Int, &TextureUnits));

        // Set RTT Order
        RTTOrder.push_back(RTT::Info(RTT::LastRTT, TextureUnits));

        TextureUnits++;
    }
    void IEffect::UseCustomTexture(Texture* texture)
    {
        Uniform CustomTexture;
        std::ostringstream toSTR; toSTR << "uTex" << TextureUnits;
		AddUniform(Uniform(toSTR.str(), Uniforms::DataType::Int, &TextureUnits));

        // Set RTT Order
        RTTOrder.push_back(RTT::Info(texture, RTT::CustomTexture, TextureUnits));

        TextureUnits++;
    }

    void IEffect::Resize(const uint32 width, const uint32 height)
    {
        // Save Dimensions
        Width = width;
        Height = height;
		fbo->Resize(width, height);
    }

    const uint32 IEffect::GetWidth() const
    {
        return Width;
    }
    const uint32 IEffect::GetHeight() const
    {
        return Height;
    }
}<|endoftext|>


<commit_before>#include <deal.II/base/quadrature_lib.h>
#include <deal.II/base/timer.h>
#include <deal.II/dofs/dof_handler.h>
#include <deal.II/dofs/dof_tools.h>
#include <deal.II/fe/fe_q.h>
#include <deal.II/grid/grid_generator.h>
#include <deal.II/grid/tria.h>
#include <deal.II/lac/dynamic_sparsity_pattern.h>
#include <deal.II/lac/linear_operator.h>
#include <deal.II/lac/sparse_matrix.h>
#include <deal.II/lac/vector.h>
#include <deal.II/numerics/matrix_tools.h>

#include <iostream>

using namespace dealii;

int main(int argc, char *argv[])
{
  if (argc != 3)
    throw ExcMessage("Invalid number of command line parameters");
  unsigned int refinement = std::atoi(argv[1]);
  unsigned int reps = std::atoi(argv[2]);

  Triangulation<2> triangulation;
  GridGenerator::hyper_cube(triangulation);
  triangulation.refine_global(refinement);

  FE_Q<2> fe(1);
  DoFHandler<2> dof_handler;
  dof_handler.initialize(triangulation, fe);

  std::cout << "n:    " << dof_handler.n_dofs() << std::endl;
  std::cout << "reps: " << reps << std::endl;

  DynamicSparsityPattern dynamic_sparsity_pattern(dof_handler.n_dofs());
  DoFTools::make_sparsity_pattern(dof_handler, dynamic_sparsity_pattern);
  SparsityPattern sparsity_pattern;
  sparsity_pattern.copy_from(dynamic_sparsity_pattern);

  SparseMatrix<double> matrix;
  matrix.reinit(sparsity_pattern);

  QGauss<2> quadrature(2);
  MatrixCreator::create_laplace_matrix(dof_handler, quadrature, matrix);

  Vector<double> x(dof_handler.n_dofs());
  for (unsigned int i = 0; i < x.size(); ++i)
    x(i) = i;

  TimerOutput timer(std::cout, TimerOutput::summary, TimerOutput::wall_times);

  timer.enter_subsection ("raw");
  Vector<double> tmp(dof_handler.n_dofs());
  for (unsigned int i = 0; i < reps; ++i)
    {
      matrix.vmult(tmp, x);
      x = tmp;
      x /= x.l2_norm();
    }
  timer.leave_subsection();

#ifdef DEBUG
  std::cout << "DEBUG" << std::endl;
  std::cout << x << std::endl;
#endif

  for (unsigned int i = 0; i < x.size(); ++i)
    x[i] = i;

  timer.enter_subsection ("linear_operator");
  const auto op = linear_operator(matrix);
  for (unsigned int i = 0; i < reps; ++i)
    {
      op.vmult(x, x);
      x /= x.l2_norm();
    }
  timer.leave_subsection();

#ifdef DEBUG
  std::cout << x << std::endl;
#endif
}
<commit_msg>Added sparse matrix 01 with Eigen and Blaze<commit_after>#include <deal.II/base/quadrature_lib.h>
#include <deal.II/base/timer.h>
#include <deal.II/dofs/dof_handler.h>
#include <deal.II/dofs/dof_tools.h>
#include <deal.II/fe/fe_q.h>
#include <deal.II/grid/grid_generator.h>
#include <deal.II/grid/tria.h>
#include <deal.II/lac/dynamic_sparsity_pattern.h>
#include <deal.II/lac/linear_operator.h>
#include <deal.II/lac/sparse_matrix.h>
#include <deal.II/lac/vector.h>
#include <deal.II/numerics/matrix_tools.h>

// Blaze include. All in one.
#include <blaze/Math.h>
#include "blaze_plugin.h"

#define EIGEN_MATRIX_PLUGIN "eigen_plugin.h"
#include <Eigen/Dense>
#include <Eigen/Sparse>

#include <iostream>

using namespace dealii;

int main(int argc, char *argv[])
{
  if (argc != 3)
    throw ExcMessage("Invalid number of command line parameters");
  unsigned int refinement = std::atoi(argv[1]);
  unsigned int reps = std::atoi(argv[2]);

  Triangulation<2> triangulation;
  GridGenerator::hyper_cube(triangulation);
  triangulation.refine_global(refinement);

  FE_Q<2> fe(1);
  DoFHandler<2> dof_handler;
  dof_handler.initialize(triangulation, fe);

  std::cout << "n:    " << dof_handler.n_dofs() << std::endl;
  std::cout << "reps: " << reps << std::endl;

  DynamicSparsityPattern dynamic_sparsity_pattern(dof_handler.n_dofs());
  DoFTools::make_sparsity_pattern(dof_handler, dynamic_sparsity_pattern);
  SparsityPattern sparsity_pattern;
  sparsity_pattern.copy_from(dynamic_sparsity_pattern);

  SparseMatrix<double> matrix;
  matrix.reinit(sparsity_pattern);

  QGauss<2> quadrature(2);
  MatrixCreator::create_laplace_matrix(dof_handler, quadrature, matrix);

  Vector<double> x(dof_handler.n_dofs());
  for (unsigned int i = 0; i < x.size(); ++i)
    x(i) = i;

  TimerOutput timer(std::cout, TimerOutput::summary, TimerOutput::wall_times);

  timer.enter_subsection ("dealii_raw");
  Vector<double> tmp(dof_handler.n_dofs());
  for (unsigned int i = 0; i < reps; ++i)
    {
      matrix.vmult(tmp, x);
      x = tmp;
      x /= x.l2_norm();
    }
  timer.leave_subsection();

#ifdef DEBUG
  std::cout << "DEBUG" << std::endl;
  std::cout << x << std::endl;
#endif

  for (unsigned int i = 0; i < x.size(); ++i)
    x[i] = i;

  timer.enter_subsection ("dealii_lo");
  const auto op = linear_operator(matrix);
  for (unsigned int i = 0; i < reps; ++i)
    {
      op.vmult(x, x);
      x /= x.l2_norm();
    }
  timer.leave_subsection();

#ifdef DEBUG
  std::cout << x << std::endl;
#endif

  // Now copy the sparse matrix to eigen and blaze
  blaze::CompressedMatrix<double, blaze::rowMajor> Bmatrix(dof_handler.n_dofs(), dof_handler.n_dofs());
  Eigen::SparseMatrix<double, Eigen::RowMajor> Ematrix(dof_handler.n_dofs(), dof_handler.n_dofs());

  typedef Eigen::Matrix<double, Eigen::Dynamic, 1, Eigen::ColMajor> EVector;

  Bmatrix.reserve(matrix.n_nonzero_elements());
  Ematrix.reserve(matrix.n_nonzero_elements());

  auto n = dof_handler.n_dofs();

  for(unsigned int i=0; i<n; ++i) {
    for(auto it = matrix.begin(i); it != matrix.end(i); ++it) {
      Bmatrix.append(i, it->column(), it->value());
      Ematrix.insert(i, it->column()) = it->value();
    }
    Bmatrix.finalize(i);
  }
  Ematrix.makeCompressed();

  // And create two vectors
  BVector Bxx(n);
  EVector Ex(n);

  auto &Bx = static_cast<BVector::T&>(Bxx);

  // ============================================================ Blaze Raw
  for (unsigned int i = 0; i < x.size(); ++i)
    Bx[i] = i;

  timer.enter_subsection ("blaze_raw");
  for (unsigned int i = 0; i < reps; ++i)
    {
      Bx = Bmatrix*Bx;
      Bx /= std::sqrt(blaze::trans(Bx)*Bx);
    }
  timer.leave_subsection();

#ifdef DEBUG
  std::cout << Bx << std::endl;
#endif

  // ============================================================ Eigen Raw
  for (unsigned int i = 0; i < x.size(); ++i)
    Ex[i] = i;

  timer.enter_subsection ("eigen_raw");
  for (unsigned int i = 0; i < reps; ++i)
    {
      Ex = Ematrix*Ex;
      Ex /= Ex.norm();
    }
  timer.leave_subsection();

#ifdef DEBUG
  std::cout << Ex << std::endl;
#endif

  // ============================================================ Blaze LO

  LinearOperator<BVector, BVector> Blo;

  Blo.vmult = [&Bmatrix] (BVector &d, const BVector &s) {
     static_cast<BVector::T&>(d) = Bmatrix*s;
  };

  for (unsigned int i = 0; i < x.size(); ++i)
    Bx[i] = i;

  timer.enter_subsection ("blaze_lo");
  for (unsigned int i = 0; i < reps; ++i)
    {
      Blo.vmult(Bxx,Bxx);
      Bx /= std::sqrt(blaze::trans(Bx)*Bx);
    }
  timer.leave_subsection();

#ifdef DEBUG
  std::cout << Bx << std::endl;
#endif

  // ============================================================ Eigen LO

  LinearOperator<EVector, EVector> Elo;

  Elo.vmult = [&Ematrix] (EVector &d, const EVector &s) {
    d = Ematrix*s;
  };

  for (unsigned int i = 0; i < x.size(); ++i)
    Ex[i] = i;

  timer.enter_subsection ("eigen_lo");
  for (unsigned int i = 0; i < reps; ++i)
    {
      Elo.vmult(Ex,Ex);
      Ex /= Ex.norm();
    }
  timer.leave_subsection();

#ifdef DEBUG
  std::cout << Ex << std::endl;
#endif
}
<|endoftext|>


<commit_before>/***************************************************************************
    copyright            : (C) 2004 by Allan Sandfeld Jensen
    email                : kde@carewolf.com
 ***************************************************************************/

/***************************************************************************
 *   This library is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU Lesser General Public License version   *
 *   2.1 as published by the Free Software Foundation.                     *
 *                                                                         *
 *   This library 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     *
 *   Lesser General Public License for more details.                       *
 *                                                                         *
 *   You should have received a copy of the GNU Lesser General Public      *
 *   License along with this library; if not, write to the Free Software   *
 *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA         *
 *   02110-1301  USA                                                       *
 *                                                                         *
 *   Alternatively, this file is available under the Mozilla Public        *
 *   License Version 1.1.  You may obtain a copy of the License at         *
 *   http://www.mozilla.org/MPL/                                           *
 ***************************************************************************/

#include <tbytevectorlist.h>
#include <tdebug.h>

#include "apeitem.h"

using namespace TagLib;
using namespace APE;

class APE::Item::ItemPrivate
{
public:
  ItemPrivate() :
    type(Text),
    readOnly(false) {}

  Item::ItemTypes type;
  String key;
  ByteVector value;
  StringList text;
  bool readOnly;
};

////////////////////////////////////////////////////////////////////////////////
// public members
////////////////////////////////////////////////////////////////////////////////

APE::Item::Item() :
  d(new ItemPrivate())
{
}

APE::Item::Item(const String &key, const String &value) :
  d(new ItemPrivate())
{
  d->key = key;
  d->text.append(value);
}

APE::Item::Item(const String &key, const StringList &values) :
  d(new ItemPrivate())
{
  d->key = key;
  d->text = values;
}

APE::Item::Item(const String &key, const ByteVector &value, bool binary) :
  d(new ItemPrivate())
{
  d->key = key;
  if(binary) {
    d->type = Binary;
    d->value = value;
  }
  else {
    d->text.append(value);
  }
}

APE::Item::Item(const Item &item) :
  d(new ItemPrivate(*item.d))
{
}

APE::Item::~Item()
{
  delete d;
}

Item &APE::Item::operator=(const Item &item)
{
  Item(item).swap(*this);
  return *this;
}

void APE::Item::swap(Item &item)
{
  using std::swap;

  swap(d, item.d);
}

void APE::Item::setReadOnly(bool readOnly)
{
  d->readOnly = readOnly;
}

bool APE::Item::isReadOnly() const
{
  return d->readOnly;
}

void APE::Item::setType(APE::Item::ItemTypes val)
{
  d->type = val;
}

APE::Item::ItemTypes APE::Item::type() const
{
  return d->type;
}

String APE::Item::key() const
{
  return d->key;
}

ByteVector APE::Item::binaryData() const
{
  return d->value;
}

void APE::Item::setBinaryData(const ByteVector &value)
{
  d->type = Binary;
  d->value = value;
  d->text.clear();
}

ByteVector APE::Item::value() const
{
  // This seems incorrect as it won't be actually rendering the value to keep it
  // up to date.

  return d->value;
}

void APE::Item::setKey(const String &key)
{
  d->key = key;
}

void APE::Item::setValue(const String &value)
{
  d->type = Text;
  d->text = value;
  d->value.clear();
}

void APE::Item::setValues(const StringList &value)
{
  d->type = Text;
  d->text = value;
  d->value.clear();
}

void APE::Item::appendValue(const String &value)
{
  d->type = Text;
  d->text.append(value);
  d->value.clear();
}

void APE::Item::appendValues(const StringList &values)
{
  d->type = Text;
  d->text.append(values);
  d->value.clear();
}

int APE::Item::size() const
{
  int result = 8 + d->key.size() + 1;
  switch(d->type) {
    case Text:
      if(!d->text.isEmpty()) {
        StringList::ConstIterator it = d->text.begin();

        result += it->data(String::UTF8).size();
        it++;
        for(; it != d->text.end(); ++it)
          result += 1 + it->data(String::UTF8).size();
      }
      break;

    case Binary:
    case Locator:
      result += d->value.size();
      break;
  }
  return result;
}

StringList APE::Item::toStringList() const
{
  return d->text;
}

StringList APE::Item::values() const
{
  return d->text;
}

String APE::Item::toString() const
{
  if(d->type == Text && !isEmpty())
    return d->text.front();
  else
    return String();
}

bool APE::Item::isEmpty() const
{
  switch(d->type) {
    case Text:
      if(d->text.isEmpty())
        return true;
      if(d->text.size() == 1 && d->text.front().isEmpty())
        return true;
      return false;
    case Binary:
    case Locator:
      return d->value.isEmpty();
    default:
      return false;
  }
}

void APE::Item::parse(const ByteVector &data)
{
  // 11 bytes is the minimum size for an APE item

  if(data.size() < 11) {
    debug("APE::Item::parse() -- no data in item");
    return;
  }

  const unsigned int valueLength  = data.toUInt(0, false);
  const unsigned int flags        = data.toUInt(4, false);

  // An item key can contain ASCII characters from 0x20 up to 0x7E, not UTF-8.
  // We assume that the validity of the given key has been checked.

  d->key = String(&data[8], String::Latin1);

  const ByteVector value = data.mid(8 + d->key.size() + 1, valueLength);

  setReadOnly(flags & 1);
  setType(ItemTypes((flags >> 1) & 3));

  if(Text == d->type)
    d->text = StringList(ByteVectorList::split(value, '\0'), String::UTF8);
  else
    d->value = value;
}

ByteVector APE::Item::render() const
{
  ByteVector data;
  unsigned int flags = ((d->readOnly) ? 1 : 0) | (d->type << 1);
  ByteVector value;

  if(isEmpty())
    return data;

  if(d->type == Text) {
    StringList::ConstIterator it = d->text.begin();

    value.append(it->data(String::UTF8));
    it++;
    for(; it != d->text.end(); ++it) {
      value.append('\0');
      value.append(it->data(String::UTF8));
    }
    d->value = value;
  }
  else
    value.append(d->value);

  data.append(ByteVector::fromUInt(value.size(), false));
  data.append(ByteVector::fromUInt(flags, false));
  data.append(d->key.data(String::Latin1));
  data.append(ByteVector('\0'));
  data.append(value);

  return data;
}
<commit_msg>clang-tidy: simplify boolean return<commit_after>/***************************************************************************
    copyright            : (C) 2004 by Allan Sandfeld Jensen
    email                : kde@carewolf.com
 ***************************************************************************/

/***************************************************************************
 *   This library is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU Lesser General Public License version   *
 *   2.1 as published by the Free Software Foundation.                     *
 *                                                                         *
 *   This library 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     *
 *   Lesser General Public License for more details.                       *
 *                                                                         *
 *   You should have received a copy of the GNU Lesser General Public      *
 *   License along with this library; if not, write to the Free Software   *
 *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA         *
 *   02110-1301  USA                                                       *
 *                                                                         *
 *   Alternatively, this file is available under the Mozilla Public        *
 *   License Version 1.1.  You may obtain a copy of the License at         *
 *   http://www.mozilla.org/MPL/                                           *
 ***************************************************************************/

#include <tbytevectorlist.h>
#include <tdebug.h>

#include "apeitem.h"

using namespace TagLib;
using namespace APE;

class APE::Item::ItemPrivate
{
public:
  ItemPrivate() :
    type(Text),
    readOnly(false) {}

  Item::ItemTypes type;
  String key;
  ByteVector value;
  StringList text;
  bool readOnly;
};

////////////////////////////////////////////////////////////////////////////////
// public members
////////////////////////////////////////////////////////////////////////////////

APE::Item::Item() :
  d(new ItemPrivate())
{
}

APE::Item::Item(const String &key, const String &value) :
  d(new ItemPrivate())
{
  d->key = key;
  d->text.append(value);
}

APE::Item::Item(const String &key, const StringList &values) :
  d(new ItemPrivate())
{
  d->key = key;
  d->text = values;
}

APE::Item::Item(const String &key, const ByteVector &value, bool binary) :
  d(new ItemPrivate())
{
  d->key = key;
  if(binary) {
    d->type = Binary;
    d->value = value;
  }
  else {
    d->text.append(value);
  }
}

APE::Item::Item(const Item &item) :
  d(new ItemPrivate(*item.d))
{
}

APE::Item::~Item()
{
  delete d;
}

Item &APE::Item::operator=(const Item &item)
{
  Item(item).swap(*this);
  return *this;
}

void APE::Item::swap(Item &item)
{
  using std::swap;

  swap(d, item.d);
}

void APE::Item::setReadOnly(bool readOnly)
{
  d->readOnly = readOnly;
}

bool APE::Item::isReadOnly() const
{
  return d->readOnly;
}

void APE::Item::setType(APE::Item::ItemTypes val)
{
  d->type = val;
}

APE::Item::ItemTypes APE::Item::type() const
{
  return d->type;
}

String APE::Item::key() const
{
  return d->key;
}

ByteVector APE::Item::binaryData() const
{
  return d->value;
}

void APE::Item::setBinaryData(const ByteVector &value)
{
  d->type = Binary;
  d->value = value;
  d->text.clear();
}

ByteVector APE::Item::value() const
{
  // This seems incorrect as it won't be actually rendering the value to keep it
  // up to date.

  return d->value;
}

void APE::Item::setKey(const String &key)
{
  d->key = key;
}

void APE::Item::setValue(const String &value)
{
  d->type = Text;
  d->text = value;
  d->value.clear();
}

void APE::Item::setValues(const StringList &value)
{
  d->type = Text;
  d->text = value;
  d->value.clear();
}

void APE::Item::appendValue(const String &value)
{
  d->type = Text;
  d->text.append(value);
  d->value.clear();
}

void APE::Item::appendValues(const StringList &values)
{
  d->type = Text;
  d->text.append(values);
  d->value.clear();
}

int APE::Item::size() const
{
  int result = 8 + d->key.size() + 1;
  switch(d->type) {
    case Text:
      if(!d->text.isEmpty()) {
        StringList::ConstIterator it = d->text.begin();

        result += it->data(String::UTF8).size();
        it++;
        for(; it != d->text.end(); ++it)
          result += 1 + it->data(String::UTF8).size();
      }
      break;

    case Binary:
    case Locator:
      result += d->value.size();
      break;
  }
  return result;
}

StringList APE::Item::toStringList() const
{
  return d->text;
}

StringList APE::Item::values() const
{
  return d->text;
}

String APE::Item::toString() const
{
  if(d->type == Text && !isEmpty())
    return d->text.front();
  else
    return String();
}

bool APE::Item::isEmpty() const
{
  switch(d->type) {
    case Text:
      if(d->text.isEmpty())
        return true;
      return d->text.size() == 1 && d->text.front().isEmpty();
    case Binary:
    case Locator:
      return d->value.isEmpty();
    default:
      return false;
  }
}

void APE::Item::parse(const ByteVector &data)
{
  // 11 bytes is the minimum size for an APE item

  if(data.size() < 11) {
    debug("APE::Item::parse() -- no data in item");
    return;
  }

  const unsigned int valueLength  = data.toUInt(0, false);
  const unsigned int flags        = data.toUInt(4, false);

  // An item key can contain ASCII characters from 0x20 up to 0x7E, not UTF-8.
  // We assume that the validity of the given key has been checked.

  d->key = String(&data[8], String::Latin1);

  const ByteVector value = data.mid(8 + d->key.size() + 1, valueLength);

  setReadOnly(flags & 1);
  setType(ItemTypes((flags >> 1) & 3));

  if(Text == d->type)
    d->text = StringList(ByteVectorList::split(value, '\0'), String::UTF8);
  else
    d->value = value;
}

ByteVector APE::Item::render() const
{
  ByteVector data;
  unsigned int flags = ((d->readOnly) ? 1 : 0) | (d->type << 1);
  ByteVector value;

  if(isEmpty())
    return data;

  if(d->type == Text) {
    StringList::ConstIterator it = d->text.begin();

    value.append(it->data(String::UTF8));
    it++;
    for(; it != d->text.end(); ++it) {
      value.append('\0');
      value.append(it->data(String::UTF8));
    }
    d->value = value;
  }
  else
    value.append(d->value);

  data.append(ByteVector::fromUInt(value.size(), false));
  data.append(ByteVector::fromUInt(flags, false));
  data.append(d->key.data(String::Latin1));
  data.append(ByteVector('\0'));
  data.append(value);

  return data;
}
<|endoftext|>


<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 1999-2000 The Apache Software Foundation.  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. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xerces" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache\@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
 * ITS 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.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation, and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com .  For more information
 * on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

/*
 * $Log$
 * Revision 1.10  2002/12/06 16:49:47  peiyongz
 * $XERCESCROOT/msg created as home directory for message files.
 *
 * Revision 1.9  2002/12/04 18:03:13  peiyongz
 * use $XERCESCROOT to search for msg catalog file if XERCESC_NLS_HOME
 * undefined
 *
 * Revision 1.8  2002/12/02 21:58:43  peiyongz
 * nls support
 *
 * Revision 1.7  2002/11/12 17:27:12  tng
 * DOM Message: add new domain for DOM Messages.
 *
 * Revision 1.6  2002/11/05 16:54:46  peiyongz
 * Using XERCESC_NLS_HOME
 *
 * Revision 1.5  2002/11/04 15:10:41  tng
 * C++ Namespace Support.
 *
 * Revision 1.4  2002/09/24 19:58:33  tng
 * Performance: use XMLString::equals instead of XMLString::compareString
 *
 * Revision 1.3  2002/09/23 21:05:40  peiyongz
 * remove debugging code
 *
 * Revision 1.2  2002/09/23 21:03:06  peiyongz
 * Build MsgCatalog on Solaris
 *
 * Revision 1.1.1.1  2002/02/01 22:22:21  peiyongz
 * sane_include
 *
 * Revision 1.7  2001/10/09 12:19:44  tng
 * Leak fix: can call transcode directly instead of using copyString.
 *
 * Revision 1.6  2000/07/25 22:28:40  aruna1
 * Char definitions in XMLUni moved to XMLUniDefs
 *
 * Revision 1.5  2000/03/02 19:55:16  roddey
 * This checkin includes many changes done while waiting for the
 * 1.1.0 code to be finished. I can't list them all here, but a list is
 * available elsewhere.
 *
 * Revision 1.4  2000/02/06 07:48:22  rahulj
 * Year 2K copyright swat.
 *
 * Revision 1.3  2000/01/05 22:00:22  aruna1
 * Modified message 'set' attribute reading sequence. Removed dependencies on  hard coded constants
 *
 * Revision 1.2  1999/12/23 01:43:37  aruna1
 * MsgCatalog support added for solaris
 *
 * Revision 1.1.1.1  1999/11/09 01:07:16  twl
 * Initial checkin
 *
 * Revision 1.2  1999/11/08 20:45:27  rahul
 * Swat for adding in Product name and CVS comment log variable.
 *
 */

// ---------------------------------------------------------------------------
//  Includes
// ---------------------------------------------------------------------------
#include <xercesc/util/XercesDefs.hpp>
#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/util/XMLMsgLoader.hpp>
#include <xercesc/util/XMLString.hpp>
#include <xercesc/util/XMLUniDefs.hpp>
#include <xercesc/util/XMLUni.hpp>
#include "MsgCatalogLoader.hpp"
#include "XMLMsgCat_Ids.hpp"

#include <locale.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

XERCES_CPP_NAMESPACE_BEGIN

// ---------------------------------------------------------------------------
//  Public Constructors and Destructor
// ---------------------------------------------------------------------------
MsgCatalogLoader::MsgCatalogLoader(const XMLCh* const msgDomain)
:fCatalogHandle(0)
,fMsgSet(0)
{
    if (!XMLString::equals(msgDomain, XMLUni::fgXMLErrDomain)
    &&  !XMLString::equals(msgDomain, XMLUni::fgExceptDomain)
    &&  !XMLString::equals(msgDomain, XMLUni::fgXMLDOMMsgDomain)
    &&  !XMLString::equals(msgDomain, XMLUni::fgValidityDomain))
    {
        XMLPlatformUtils::panic(XMLPlatformUtils::Panic_UnknownMsgDomain);
    }

    // Prepare the path info
    char catpath[1024];
    memset(catpath, 0, sizeof catpath);
    char *nlsHome = getenv("XERCESC_NLS_HOME");
    if (nlsHome)
    {
        strcpy(catpath, nlsHome);
        strcat(catpath, "/");
    }
    else
    {
        char *altHome = getenv("XERCESCROOT");
        if (altHome)
        {
            strcpy(catpath, altHome);
            strcat(catpath, "/msg/");
        }
    }

    // Prepare user-specified locale specific cat file
    char catuser[1024];
    memset(catuser, 0, sizeof catuser);
    strcpy(catuser, catpath);
    strcat(catuser, "XMLMessages_");
    strcat(catuser, XMLMsgLoader::getLocale());
    strcat(catuser, ".cat");

    char catdefault[1024];
    memset(catdefault, 0, sizeof catdefault);
    strcpy(catdefault, catpath);
    strcat(catdefault, "XMLMessages_en_US.cat");

   /**
    * To open user-specified locale specific cat file
    * and default cat file if necessary
    */
    if ( ((int)(fCatalogHandle=catopen(catuser, 0)) == -1) &&
         ((int)(fCatalogHandle=catopen(catdefault, 0)) == -1)   )
    {
        // Probably have to call panic here
        printf("Could not open catalog:\n %s\n or %s\n", catuser, catdefault);
        exit(1);
    }

    if (XMLString::equals(msgDomain, XMLUni::fgXMLErrDomain))
        fMsgSet = CatId_XMLErrs;
    else if (XMLString::equals(msgDomain, XMLUni::fgExceptDomain))
        fMsgSet = CatId_XMLExcepts;
    else if (XMLString::equals(msgDomain, XMLUni::fgValidityDomain))
        fMsgSet = CatId_XMLValid;
    else if (XMLString::equals(msgDomain, XMLUni::fgXMLDOMMsgDomain))
        fMsgSet = CatId_XMLDOMMsg;
}

MsgCatalogLoader::~MsgCatalogLoader()
{
    catclose(fCatalogHandle);
}

// ---------------------------------------------------------------------------
//  Implementation of the virtual message loader API
// ---------------------------------------------------------------------------
bool MsgCatalogLoader::loadMsg(const  XMLMsgLoader::XMLMsgId  msgToLoad
                              ,       XMLCh*   const          toFill
                              , const unsigned int            maxChars)
{
    char msgString[100];
    sprintf(msgString, "Could not find message ID %d from message set %d\n", msgToLoad, fMsgSet);
    char* catMessage = catgets( fCatalogHandle, fMsgSet, (int)msgToLoad, msgString);

    // catgets returns a pointer to msgString if it fails to locate the message
    // from the message catalog
    if (XMLString::equals(catMessage, msgString))
        return false;
    else
    {
        XMLString::transcode(catMessage, toFill, maxChars);
        return true;
    }

}

bool MsgCatalogLoader::loadMsg(const  XMLMsgLoader::XMLMsgId  msgToLoad
                            ,       XMLCh* const            toFill
                            , const unsigned int            maxChars
                            , const XMLCh* const            repText1
                            , const XMLCh* const            repText2
                            , const XMLCh* const            repText3
                            , const XMLCh* const            repText4)
{
    // Call the other version to load up the message
    if (!loadMsg(msgToLoad, toFill, maxChars))
        return false;

    // And do the token replacement
    XMLString::replaceTokens(toFill, maxChars, repText1, repText2, repText3, repText4);
    return true;
}

bool MsgCatalogLoader::loadMsg(const  XMLMsgLoader::XMLMsgId  msgToLoad
                            ,       XMLCh* const            toFill
                            , const unsigned int            maxChars
                            , const char* const             repText1
                            , const char* const             repText2
                            , const char* const             repText3
                            , const char* const             repText4)
{
    //
    //  Transcode the provided parameters and call the other version,
    //  which will do the replacement work.
    //
    XMLCh* tmp1 = 0;
    XMLCh* tmp2 = 0;
    XMLCh* tmp3 = 0;
    XMLCh* tmp4 = 0;

    bool bRet = false;
    if (repText1)
        tmp1 = XMLString::transcode(repText1);
    if (repText2)
        tmp2 = XMLString::transcode(repText2);
    if (repText3)
        tmp3 = XMLString::transcode(repText3);
    if (repText4)
        tmp4 = XMLString::transcode(repText4);

    bRet = loadMsg(msgToLoad, toFill, maxChars, tmp1, tmp2, tmp3, tmp4);

    if (tmp1)
        delete [] tmp1;
    if (tmp2)
        delete [] tmp2;
    if (tmp3)
        delete [] tmp3;
    if (tmp4)
        delete [] tmp4;

    return bRet;
}

XERCES_CPP_NAMESPACE_END
<commit_msg>MsgCatalog file name changed.<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 1999-2000 The Apache Software Foundation.  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. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xerces" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache\@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
 * ITS 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.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation, and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com .  For more information
 * on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

/*
 * $Log$
 * Revision 1.11  2002/12/12 16:46:18  peiyongz
 * MsgCatalog file name changed.
 *
 * Revision 1.10  2002/12/06 16:49:47  peiyongz
 * $XERCESCROOT/msg created as home directory for message files.
 *
 * Revision 1.9  2002/12/04 18:03:13  peiyongz
 * use $XERCESCROOT to search for msg catalog file if XERCESC_NLS_HOME
 * undefined
 *
 * Revision 1.8  2002/12/02 21:58:43  peiyongz
 * nls support
 *
 * Revision 1.7  2002/11/12 17:27:12  tng
 * DOM Message: add new domain for DOM Messages.
 *
 * Revision 1.6  2002/11/05 16:54:46  peiyongz
 * Using XERCESC_NLS_HOME
 *
 * Revision 1.5  2002/11/04 15:10:41  tng
 * C++ Namespace Support.
 *
 * Revision 1.4  2002/09/24 19:58:33  tng
 * Performance: use XMLString::equals instead of XMLString::compareString
 *
 * Revision 1.3  2002/09/23 21:05:40  peiyongz
 * remove debugging code
 *
 * Revision 1.2  2002/09/23 21:03:06  peiyongz
 * Build MsgCatalog on Solaris
 *
 * Revision 1.1.1.1  2002/02/01 22:22:21  peiyongz
 * sane_include
 *
 * Revision 1.7  2001/10/09 12:19:44  tng
 * Leak fix: can call transcode directly instead of using copyString.
 *
 * Revision 1.6  2000/07/25 22:28:40  aruna1
 * Char definitions in XMLUni moved to XMLUniDefs
 *
 * Revision 1.5  2000/03/02 19:55:16  roddey
 * This checkin includes many changes done while waiting for the
 * 1.1.0 code to be finished. I can't list them all here, but a list is
 * available elsewhere.
 *
 * Revision 1.4  2000/02/06 07:48:22  rahulj
 * Year 2K copyright swat.
 *
 * Revision 1.3  2000/01/05 22:00:22  aruna1
 * Modified message 'set' attribute reading sequence. Removed dependencies on  hard coded constants
 *
 * Revision 1.2  1999/12/23 01:43:37  aruna1
 * MsgCatalog support added for solaris
 *
 * Revision 1.1.1.1  1999/11/09 01:07:16  twl
 * Initial checkin
 *
 * Revision 1.2  1999/11/08 20:45:27  rahul
 * Swat for adding in Product name and CVS comment log variable.
 *
 */

// ---------------------------------------------------------------------------
//  Includes
// ---------------------------------------------------------------------------
#include <xercesc/util/XercesDefs.hpp>
#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/util/XMLMsgLoader.hpp>
#include <xercesc/util/XMLString.hpp>
#include <xercesc/util/XMLUniDefs.hpp>
#include <xercesc/util/XMLUni.hpp>
#include "MsgCatalogLoader.hpp"
#include "XMLMsgCat_Ids.hpp"

#include <locale.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

XERCES_CPP_NAMESPACE_BEGIN

// ---------------------------------------------------------------------------
//  Public Constructors and Destructor
// ---------------------------------------------------------------------------
MsgCatalogLoader::MsgCatalogLoader(const XMLCh* const msgDomain)
:fCatalogHandle(0)
,fMsgSet(0)
{
    if (!XMLString::equals(msgDomain, XMLUni::fgXMLErrDomain)
    &&  !XMLString::equals(msgDomain, XMLUni::fgExceptDomain)
    &&  !XMLString::equals(msgDomain, XMLUni::fgXMLDOMMsgDomain)
    &&  !XMLString::equals(msgDomain, XMLUni::fgValidityDomain))
    {
        XMLPlatformUtils::panic(XMLPlatformUtils::Panic_UnknownMsgDomain);
    }

    // Prepare the path info
    char catpath[1024];
    memset(catpath, 0, sizeof catpath);
    char *nlsHome = getenv("XERCESC_NLS_HOME");
    if (nlsHome)
    {
        strcpy(catpath, nlsHome);
        strcat(catpath, "/");
    }
    else
    {
        char *altHome = getenv("XERCESCROOT");
        if (altHome)
        {
            strcpy(catpath, altHome);
            strcat(catpath, "/msg/");
        }
    }

    // Prepare user-specified locale specific cat file
    char catuser[1024];
    memset(catuser, 0, sizeof catuser);
    strcpy(catuser, catpath);
    strcat(catuser, "XercesMessages_");
    strcat(catuser, XMLMsgLoader::getLocale());
    strcat(catuser, ".cat");

    char catdefault[1024];
    memset(catdefault, 0, sizeof catdefault);
    strcpy(catdefault, catpath);
    strcat(catdefault, "XercesMessages_en_US.cat");

   /**
    * To open user-specified locale specific cat file
    * and default cat file if necessary
    */
    if ( ((int)(fCatalogHandle=catopen(catuser, 0)) == -1) &&
         ((int)(fCatalogHandle=catopen(catdefault, 0)) == -1)   )
    {
        // Probably have to call panic here
        printf("Could not open catalog:\n %s\n or %s\n", catuser, catdefault);
        exit(1);
    }

    if (XMLString::equals(msgDomain, XMLUni::fgXMLErrDomain))
        fMsgSet = CatId_XMLErrs;
    else if (XMLString::equals(msgDomain, XMLUni::fgExceptDomain))
        fMsgSet = CatId_XMLExcepts;
    else if (XMLString::equals(msgDomain, XMLUni::fgValidityDomain))
        fMsgSet = CatId_XMLValid;
    else if (XMLString::equals(msgDomain, XMLUni::fgXMLDOMMsgDomain))
        fMsgSet = CatId_XMLDOMMsg;
}

MsgCatalogLoader::~MsgCatalogLoader()
{
    catclose(fCatalogHandle);
}

// ---------------------------------------------------------------------------
//  Implementation of the virtual message loader API
// ---------------------------------------------------------------------------
bool MsgCatalogLoader::loadMsg(const  XMLMsgLoader::XMLMsgId  msgToLoad
                              ,       XMLCh*   const          toFill
                              , const unsigned int            maxChars)
{
    char msgString[100];
    sprintf(msgString, "Could not find message ID %d from message set %d\n", msgToLoad, fMsgSet);
    char* catMessage = catgets( fCatalogHandle, fMsgSet, (int)msgToLoad, msgString);

    // catgets returns a pointer to msgString if it fails to locate the message
    // from the message catalog
    if (XMLString::equals(catMessage, msgString))
        return false;
    else
    {
        XMLString::transcode(catMessage, toFill, maxChars);
        return true;
    }

}

bool MsgCatalogLoader::loadMsg(const  XMLMsgLoader::XMLMsgId  msgToLoad
                            ,       XMLCh* const            toFill
                            , const unsigned int            maxChars
                            , const XMLCh* const            repText1
                            , const XMLCh* const            repText2
                            , const XMLCh* const            repText3
                            , const XMLCh* const            repText4)
{
    // Call the other version to load up the message
    if (!loadMsg(msgToLoad, toFill, maxChars))
        return false;

    // And do the token replacement
    XMLString::replaceTokens(toFill, maxChars, repText1, repText2, repText3, repText4);
    return true;
}

bool MsgCatalogLoader::loadMsg(const  XMLMsgLoader::XMLMsgId  msgToLoad
                            ,       XMLCh* const            toFill
                            , const unsigned int            maxChars
                            , const char* const             repText1
                            , const char* const             repText2
                            , const char* const             repText3
                            , const char* const             repText4)
{
    //
    //  Transcode the provided parameters and call the other version,
    //  which will do the replacement work.
    //
    XMLCh* tmp1 = 0;
    XMLCh* tmp2 = 0;
    XMLCh* tmp3 = 0;
    XMLCh* tmp4 = 0;

    bool bRet = false;
    if (repText1)
        tmp1 = XMLString::transcode(repText1);
    if (repText2)
        tmp2 = XMLString::transcode(repText2);
    if (repText3)
        tmp3 = XMLString::transcode(repText3);
    if (repText4)
        tmp4 = XMLString::transcode(repText4);

    bRet = loadMsg(msgToLoad, toFill, maxChars, tmp1, tmp2, tmp3, tmp4);

    if (tmp1)
        delete [] tmp1;
    if (tmp2)
        delete [] tmp2;
    if (tmp3)
        delete [] tmp3;
    if (tmp4)
        delete [] tmp4;

    return bRet;
}

XERCES_CPP_NAMESPACE_END
<|endoftext|>


<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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.
 */

/*
 * $Id$
 */

// ---------------------------------------------------------------------------
//  Includes
// ---------------------------------------------------------------------------
#include <stdio.h>
#include <xercesc/util/OutOfMemoryException.hpp>
#include <xercesc/util/XMLUTF8Transcoder.hpp>
#include <xercesc/validators/datatype/AnyURIDatatypeValidator.hpp>
#include <xercesc/validators/datatype/InvalidDatatypeFacetException.hpp>
#include <xercesc/validators/datatype/InvalidDatatypeValueException.hpp>

XERCES_CPP_NAMESPACE_BEGIN

// ---------------------------------------------------------------------------
//  Constructors and Destructor
// ---------------------------------------------------------------------------
AnyURIDatatypeValidator::AnyURIDatatypeValidator(MemoryManager* const manager)
:AbstractStringValidator(0, 0, 0, DatatypeValidator::AnyURI, manager)
{}

AnyURIDatatypeValidator::~AnyURIDatatypeValidator()
{
}

AnyURIDatatypeValidator::AnyURIDatatypeValidator(
                          DatatypeValidator*            const baseValidator
                        , RefHashTableOf<KVStringPair>* const facets
                        , RefArrayVectorOf<XMLCh>*      const enums
                        , const int                           finalSet
                        , MemoryManager* const manager)
:AbstractStringValidator(baseValidator, facets, finalSet, DatatypeValidator::AnyURI, manager)
{
    init(enums, manager);
}

DatatypeValidator* AnyURIDatatypeValidator::newInstance(
                                      RefHashTableOf<KVStringPair>* const facets
                                    , RefArrayVectorOf<XMLCh>*           const enums
                                    , const int                           finalSet
                                    , MemoryManager* const manager)
{
    return (DatatypeValidator*) new (manager) AnyURIDatatypeValidator(this, facets, enums, finalSet, manager);
}

// ---------------------------------------------------------------------------
//  Utilities
// ---------------------------------------------------------------------------

void AnyURIDatatypeValidator::checkValueSpace(const XMLCh* const content
                                              , MemoryManager* const manager)
{
    bool validURI = true;

    // check 3.2.17.c0 must: URI (rfc 2396/2723)
    try
    {
        // Support for relative URLs
        // According to Java 1.1: URLs may also be specified with a
        // String and the URL object that it is related to.
        //
        const unsigned int len = XMLString::stringLen(content);
        if (len)
        {
            // Encode special characters using XLink 5.4 algorithm
            XMLCh* encoded = (XMLCh*)manager->allocate((len*3+1) * sizeof(XMLCh));
            ArrayJanitor<XMLCh> encodedJan(encoded);
            encode(content, len, encoded, manager);
            validURI = XMLUri::isValidURI(true, encoded, true);
        }
    }
    catch(const OutOfMemoryException&)
    {
        throw;
    }
    catch (...)
    {
        ThrowXMLwithMemMgr1(InvalidDatatypeValueException
                , XMLExcepts::VALUE_URI_Malformed
                , content
                , manager);
    }

    if (!validURI) {
        ThrowXMLwithMemMgr1(InvalidDatatypeValueException
                    , XMLExcepts::VALUE_URI_Malformed
                    , content
                    , manager);
    }
}

/***
 * To encode special characters in anyURI, by using %HH to represent
 * special ASCII characters: 0x00~0x1F, 0x7F, ' ', '<', '>', etc.
 * and non-ASCII characters (whose value >= 128).
 ***/
void AnyURIDatatypeValidator::encode(const XMLCh* const content, const XMLSize_t len, XMLCh* encoded, MemoryManager* const manager)
{
    static const bool needEscapeMap[] = {
        true , true , true , true , true , true , true , true , true , true , true , true , true , true , true , true , /* 0x00 to 0x0F need escape */
        true , true , true , true , true , true , true , true , true , true , true , true , true , true , true , true , /* 0x10 to 0x1F need escape */
        true , false, true , false, false, false, false, false, false, false, false, false, false, false, false, false, /* 0x20:' ', 0x22:'"' */
        false, false, false, false, false, false, false, false, false, false, false, false, true , false, true , false, /* 0x3C:'<', 0x3E:'>' */
        false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false,
        false, false, false, false, false, false, false, false, false, false, false, false, true , false, true , false, /* 0x5C:'\\', 0x5E:'^' */
        true , false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, /* 0x60:'`' */
        false, false, false, false, false, false, false, false, false, false, false, true , true , true , true , true   /* 0x7B:'{', 0x7C:'|', 0x7D:'}', 0x7E:'~', 0x7F:DEL */
    };

    int bufferIndex = 0;

    // For each character in content
    XMLSize_t i;
    for (i = 0; i < len; i++)
    {
        int ch = (int)content[i];
        // If it's not an ASCII character, break here, and use UTF-8 encoding
        if (ch >= 128)
            break;

        if (needEscapeMap[ch])
        {
            char tempStr[2] = "\0";
            sprintf(tempStr, "%02X", ch);
            encoded[bufferIndex++] = '%';
            encoded[bufferIndex++] = (XMLCh)tempStr[0];
            encoded[bufferIndex++] = (XMLCh)tempStr[1];
        }
        else
        {
            encoded[bufferIndex++] = (XMLCh)ch;
        }
    }

    // we saw some non-ascii character
    if (i < len) {
        // get UTF-8 bytes for the remaining sub-string
        const XMLCh* remContent = (XMLCh*)&content[i];
        const XMLSize_t remContentLen = len - i;
        XMLByte* UTF8Byte = (XMLByte*)manager->allocate((remContentLen*4+1) * sizeof(XMLByte));
        XMLSize_t charsEaten;

        XMLUTF8Transcoder transcoder(XMLUni::fgUTF8EncodingString, remContentLen*4+1, manager);
        transcoder.transcodeTo(remContent, remContentLen, UTF8Byte, remContentLen*4, charsEaten, XMLTranscoder::UnRep_RepChar);
        assert(charsEaten == remContentLen);

        XMLSize_t j;
        for (j = 0; j < remContentLen; j++) {
            XMLByte b = UTF8Byte[j];
            // for non-ascii character: make it positive, then escape
            if (b < 0) {
                int ch = b + 256;
                char tempStr[2] = "\0";
                sprintf(tempStr, "%02X", ch);
                encoded[bufferIndex++] = '%';
                encoded[bufferIndex++] = (XMLCh)tempStr[0];
                encoded[bufferIndex++] = (XMLCh)tempStr[1];
            }
            else if (needEscapeMap[b])
            {
                char tempStr[2] = "\0";
                sprintf(tempStr, "%02X", b);
                encoded[bufferIndex++] = '%';
                encoded[bufferIndex++] = (XMLCh)tempStr[0];
                encoded[bufferIndex++] = (XMLCh)tempStr[1];
            }
            else
            {
                encoded[bufferIndex++] = (XMLCh)b;
            }
        }
        manager->deallocate(UTF8Byte);
    }

    encoded[bufferIndex] = (XMLCh)0;
}

/***
 * Support for Serialization/De-serialization
 ***/

IMPL_XSERIALIZABLE_TOCREATE(AnyURIDatatypeValidator)

void AnyURIDatatypeValidator::serialize(XSerializeEngine& serEng)
{
    AbstractStringValidator::serialize(serEng);
}

XERCES_CPP_NAMESPACE_END

/**
  * End of file AnyURIDatatypeValidator.cpp
  */
<commit_msg>Pass in memory manager to janitor.<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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.
 */

/*
 * $Id$
 */

// ---------------------------------------------------------------------------
//  Includes
// ---------------------------------------------------------------------------
#include <stdio.h>
#include <xercesc/util/OutOfMemoryException.hpp>
#include <xercesc/util/XMLUTF8Transcoder.hpp>
#include <xercesc/validators/datatype/AnyURIDatatypeValidator.hpp>
#include <xercesc/validators/datatype/InvalidDatatypeFacetException.hpp>
#include <xercesc/validators/datatype/InvalidDatatypeValueException.hpp>

XERCES_CPP_NAMESPACE_BEGIN

// ---------------------------------------------------------------------------
//  Constructors and Destructor
// ---------------------------------------------------------------------------
AnyURIDatatypeValidator::AnyURIDatatypeValidator(MemoryManager* const manager)
:AbstractStringValidator(0, 0, 0, DatatypeValidator::AnyURI, manager)
{}

AnyURIDatatypeValidator::~AnyURIDatatypeValidator()
{
}

AnyURIDatatypeValidator::AnyURIDatatypeValidator(
                          DatatypeValidator*            const baseValidator
                        , RefHashTableOf<KVStringPair>* const facets
                        , RefArrayVectorOf<XMLCh>*      const enums
                        , const int                           finalSet
                        , MemoryManager* const manager)
:AbstractStringValidator(baseValidator, facets, finalSet, DatatypeValidator::AnyURI, manager)
{
    init(enums, manager);
}

DatatypeValidator* AnyURIDatatypeValidator::newInstance(
                                      RefHashTableOf<KVStringPair>* const facets
                                    , RefArrayVectorOf<XMLCh>*           const enums
                                    , const int                           finalSet
                                    , MemoryManager* const manager)
{
    return (DatatypeValidator*) new (manager) AnyURIDatatypeValidator(this, facets, enums, finalSet, manager);
}

// ---------------------------------------------------------------------------
//  Utilities
// ---------------------------------------------------------------------------

void AnyURIDatatypeValidator::checkValueSpace(const XMLCh* const content
                                              , MemoryManager* const manager)
{
    bool validURI = true;

    // check 3.2.17.c0 must: URI (rfc 2396/2723)
    try
    {
        // Support for relative URLs
        // According to Java 1.1: URLs may also be specified with a
        // String and the URL object that it is related to.
        //
        const unsigned int len = XMLString::stringLen(content);
        if (len)
        {
            // Encode special characters using XLink 5.4 algorithm
            XMLCh* encoded = (XMLCh*)manager->allocate((len*3+1) * sizeof(XMLCh));
            ArrayJanitor<XMLCh> encodedJan(encoded, manager);
            encode(content, len, encoded, manager);
            validURI = XMLUri::isValidURI(true, encoded, true);
        }
    }
    catch(const OutOfMemoryException&)
    {
        throw;
    }
    catch (...)
    {
        ThrowXMLwithMemMgr1(InvalidDatatypeValueException
                , XMLExcepts::VALUE_URI_Malformed
                , content
                , manager);
    }

    if (!validURI) {
        ThrowXMLwithMemMgr1(InvalidDatatypeValueException
                    , XMLExcepts::VALUE_URI_Malformed
                    , content
                    , manager);
    }
}

/***
 * To encode special characters in anyURI, by using %HH to represent
 * special ASCII characters: 0x00~0x1F, 0x7F, ' ', '<', '>', etc.
 * and non-ASCII characters (whose value >= 128).
 ***/
void AnyURIDatatypeValidator::encode(const XMLCh* const content, const XMLSize_t len, XMLCh* encoded, MemoryManager* const manager)
{
    static const bool needEscapeMap[] = {
        true , true , true , true , true , true , true , true , true , true , true , true , true , true , true , true , /* 0x00 to 0x0F need escape */
        true , true , true , true , true , true , true , true , true , true , true , true , true , true , true , true , /* 0x10 to 0x1F need escape */
        true , false, true , false, false, false, false, false, false, false, false, false, false, false, false, false, /* 0x20:' ', 0x22:'"' */
        false, false, false, false, false, false, false, false, false, false, false, false, true , false, true , false, /* 0x3C:'<', 0x3E:'>' */
        false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false,
        false, false, false, false, false, false, false, false, false, false, false, false, true , false, true , false, /* 0x5C:'\\', 0x5E:'^' */
        true , false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, /* 0x60:'`' */
        false, false, false, false, false, false, false, false, false, false, false, true , true , true , true , true   /* 0x7B:'{', 0x7C:'|', 0x7D:'}', 0x7E:'~', 0x7F:DEL */
    };

    int bufferIndex = 0;

    // For each character in content
    XMLSize_t i;
    for (i = 0; i < len; i++)
    {
        int ch = (int)content[i];
        // If it's not an ASCII character, break here, and use UTF-8 encoding
        if (ch >= 128)
            break;

        if (needEscapeMap[ch])
        {
            char tempStr[2] = "\0";
            sprintf(tempStr, "%02X", ch);
            encoded[bufferIndex++] = '%';
            encoded[bufferIndex++] = (XMLCh)tempStr[0];
            encoded[bufferIndex++] = (XMLCh)tempStr[1];
        }
        else
        {
            encoded[bufferIndex++] = (XMLCh)ch;
        }
    }

    // we saw some non-ascii character
    if (i < len) {
        // get UTF-8 bytes for the remaining sub-string
        const XMLCh* remContent = (XMLCh*)&content[i];
        const XMLSize_t remContentLen = len - i;
        XMLByte* UTF8Byte = (XMLByte*)manager->allocate((remContentLen*4+1) * sizeof(XMLByte));
        XMLSize_t charsEaten;

        XMLUTF8Transcoder transcoder(XMLUni::fgUTF8EncodingString, remContentLen*4+1, manager);
        transcoder.transcodeTo(remContent, remContentLen, UTF8Byte, remContentLen*4, charsEaten, XMLTranscoder::UnRep_RepChar);
        assert(charsEaten == remContentLen);

        XMLSize_t j;
        for (j = 0; j < remContentLen; j++) {
            XMLByte b = UTF8Byte[j];
            // for non-ascii character: make it positive, then escape
            if (b < 0) {
                int ch = b + 256;
                char tempStr[2] = "\0";
                sprintf(tempStr, "%02X", ch);
                encoded[bufferIndex++] = '%';
                encoded[bufferIndex++] = (XMLCh)tempStr[0];
                encoded[bufferIndex++] = (XMLCh)tempStr[1];
            }
            else if (needEscapeMap[b])
            {
                char tempStr[2] = "\0";
                sprintf(tempStr, "%02X", b);
                encoded[bufferIndex++] = '%';
                encoded[bufferIndex++] = (XMLCh)tempStr[0];
                encoded[bufferIndex++] = (XMLCh)tempStr[1];
            }
            else
            {
                encoded[bufferIndex++] = (XMLCh)b;
            }
        }
        manager->deallocate(UTF8Byte);
    }

    encoded[bufferIndex] = (XMLCh)0;
}

/***
 * Support for Serialization/De-serialization
 ***/

IMPL_XSERIALIZABLE_TOCREATE(AnyURIDatatypeValidator)

void AnyURIDatatypeValidator::serialize(XSerializeEngine& serEng)
{
    AbstractStringValidator::serialize(serEng);
}

XERCES_CPP_NAMESPACE_END

/**
  * End of file AnyURIDatatypeValidator.cpp
  */
<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

// Commandline tool to unpack audioproc debug files.
//
// The debug files are dumped as protobuf blobs. For analysis, it's necessary
// to unpack the file into its component parts: audio and other data.

#include <stdio.h>

#include "gflags/gflags.h"
#include "webrtc/audio_processing/debug.pb.h"
#include "webrtc/base/scoped_ptr.h"
#include "webrtc/modules/audio_processing/test/test_utils.h"
#include "webrtc/typedefs.h"

// TODO(andrew): unpack more of the data.
DEFINE_string(input_file, "input", "The name of the input stream file.");
DEFINE_string(output_file, "ref_out",
              "The name of the reference output stream file.");
DEFINE_string(reverse_file, "reverse",
              "The name of the reverse input stream file.");
DEFINE_string(delay_file, "delay.int32", "The name of the delay file.");
DEFINE_string(drift_file, "drift.int32", "The name of the drift file.");
DEFINE_string(level_file, "level.int32", "The name of the level file.");
DEFINE_string(keypress_file, "keypress.bool", "The name of the keypress file.");
DEFINE_string(settings_file, "settings.txt", "The name of the settings file.");
DEFINE_bool(full, false,
            "Unpack the full set of files (normally not needed).");
DEFINE_bool(raw, false, "Write raw data instead of a WAV file.");

namespace webrtc {

using audioproc::Event;
using audioproc::ReverseStream;
using audioproc::Stream;
using audioproc::Init;

void WriteData(const void* data, size_t size, FILE* file,
               const std::string& filename) {
  if (fwrite(data, size, 1, file) != 1) {
    printf("Error when writing to %s\n", filename.c_str());
    exit(1);
  }
}

int do_main(int argc, char* argv[]) {
  std::string program_name = argv[0];
  std::string usage = "Commandline tool to unpack audioproc debug files.\n"
    "Example usage:\n" + program_name + " debug_dump.pb\n";
  google::SetUsageMessage(usage);
  google::ParseCommandLineFlags(&argc, &argv, true);

  if (argc < 2) {
    printf("%s", google::ProgramUsage());
    return 1;
  }

  FILE* debug_file = OpenFile(argv[1], "rb");

  Event event_msg;
  int frame_count = 0;
  int reverse_samples_per_channel = 0;
  int input_samples_per_channel = 0;
  int output_samples_per_channel = 0;
  int num_reverse_channels = 0;
  int num_input_channels = 0;
  int num_output_channels = 0;
  rtc::scoped_ptr<WavWriter> reverse_wav_file;
  rtc::scoped_ptr<WavWriter> input_wav_file;
  rtc::scoped_ptr<WavWriter> output_wav_file;
  rtc::scoped_ptr<RawFile> reverse_raw_file;
  rtc::scoped_ptr<RawFile> input_raw_file;
  rtc::scoped_ptr<RawFile> output_raw_file;
  while (ReadMessageFromFile(debug_file, &event_msg)) {
    if (event_msg.type() == Event::REVERSE_STREAM) {
      if (!event_msg.has_reverse_stream()) {
        printf("Corrupt input file: ReverseStream missing.\n");
        return 1;
      }

      const ReverseStream msg = event_msg.reverse_stream();
      if (msg.has_data()) {
        if (FLAGS_raw && !reverse_raw_file) {
          reverse_raw_file.reset(new RawFile(FLAGS_reverse_file + ".pcm"));
        }
        // TODO(aluebs): Replace "num_reverse_channels *
        // reverse_samples_per_channel" with "msg.data().size() /
        // sizeof(int16_t)" and so on when this fix in audio_processing has made
        // it into stable: https://webrtc-codereview.appspot.com/15299004/
        WriteIntData(reinterpret_cast<const int16_t*>(msg.data().data()),
                     num_reverse_channels * reverse_samples_per_channel,
                     reverse_wav_file.get(),
                     reverse_raw_file.get());
      } else if (msg.channel_size() > 0) {
        if (FLAGS_raw && !reverse_raw_file) {
          reverse_raw_file.reset(new RawFile(FLAGS_reverse_file + ".float"));
        }
        rtc::scoped_ptr<const float* []> data(
            new const float* [num_reverse_channels]);
        for (int i = 0; i < num_reverse_channels; ++i) {
          data[i] = reinterpret_cast<const float*>(msg.channel(i).data());
        }
        WriteFloatData(data.get(),
                       reverse_samples_per_channel,
                       num_reverse_channels,
                       reverse_wav_file.get(),
                       reverse_raw_file.get());
      }
    } else if (event_msg.type() == Event::STREAM) {
      frame_count++;
      if (!event_msg.has_stream()) {
        printf("Corrupt input file: Stream missing.\n");
        return 1;
      }

      const Stream msg = event_msg.stream();
      if (msg.has_input_data()) {
        if (FLAGS_raw && !input_raw_file) {
          input_raw_file.reset(new RawFile(FLAGS_input_file + ".pcm"));
        }
        WriteIntData(reinterpret_cast<const int16_t*>(msg.input_data().data()),
                     num_input_channels * input_samples_per_channel,
                     input_wav_file.get(),
                     input_raw_file.get());
      } else if (msg.input_channel_size() > 0) {
        if (FLAGS_raw && !input_raw_file) {
          input_raw_file.reset(new RawFile(FLAGS_input_file + ".float"));
        }
        rtc::scoped_ptr<const float* []> data(
            new const float* [num_input_channels]);
        for (int i = 0; i < num_input_channels; ++i) {
          data[i] = reinterpret_cast<const float*>(msg.input_channel(i).data());
        }
        WriteFloatData(data.get(),
                       input_samples_per_channel,
                       num_input_channels,
                       input_wav_file.get(),
                       input_raw_file.get());
      }

      if (msg.has_output_data()) {
        if (FLAGS_raw && !output_raw_file) {
          output_raw_file.reset(new RawFile(FLAGS_output_file + ".pcm"));
        }
        WriteIntData(reinterpret_cast<const int16_t*>(msg.output_data().data()),
                     num_output_channels * output_samples_per_channel,
                     output_wav_file.get(),
                     output_raw_file.get());
      } else if (msg.output_channel_size() > 0) {
        if (FLAGS_raw && !output_raw_file) {
          output_raw_file.reset(new RawFile(FLAGS_output_file + ".float"));
        }
        rtc::scoped_ptr<const float* []> data(
            new const float* [num_output_channels]);
        for (int i = 0; i < num_output_channels; ++i) {
          data[i] =
              reinterpret_cast<const float*>(msg.output_channel(i).data());
        }
        WriteFloatData(data.get(),
                       output_samples_per_channel,
                       num_output_channels,
                       output_wav_file.get(),
                       output_raw_file.get());
      }

      if (FLAGS_full) {
        if (msg.has_delay()) {
          static FILE* delay_file = OpenFile(FLAGS_delay_file, "wb");
          int32_t delay = msg.delay();
          WriteData(&delay, sizeof(delay), delay_file, FLAGS_delay_file);
        }

        if (msg.has_drift()) {
          static FILE* drift_file = OpenFile(FLAGS_drift_file, "wb");
          int32_t drift = msg.drift();
          WriteData(&drift, sizeof(drift), drift_file, FLAGS_drift_file);
        }

        if (msg.has_level()) {
          static FILE* level_file = OpenFile(FLAGS_level_file, "wb");
          int32_t level = msg.level();
          WriteData(&level, sizeof(level), level_file, FLAGS_level_file);
        }

        if (msg.has_keypress()) {
          static FILE* keypress_file = OpenFile(FLAGS_keypress_file, "wb");
          bool keypress = msg.keypress();
          WriteData(&keypress, sizeof(keypress), keypress_file,
                    FLAGS_keypress_file);
        }
      }
    } else if (event_msg.type() == Event::INIT) {
      if (!event_msg.has_init()) {
        printf("Corrupt input file: Init missing.\n");
        return 1;
      }

      static FILE* settings_file = OpenFile(FLAGS_settings_file, "wb");
      const Init msg = event_msg.init();
      // These should print out zeros if they're missing.
      fprintf(settings_file, "Init at frame: %d\n", frame_count);
      int input_sample_rate = msg.sample_rate();
      fprintf(settings_file, "  Input sample rate: %d\n", input_sample_rate);
      int output_sample_rate = msg.output_sample_rate();
      fprintf(settings_file, "  Output sample rate: %d\n", output_sample_rate);
      int reverse_sample_rate = msg.reverse_sample_rate();
      fprintf(settings_file,
              "  Reverse sample rate: %d\n",
              reverse_sample_rate);
      num_input_channels = msg.num_input_channels();
      fprintf(settings_file, "  Input channels: %d\n", num_input_channels);
      num_output_channels = msg.num_output_channels();
      fprintf(settings_file, "  Output channels: %d\n", num_output_channels);
      num_reverse_channels = msg.num_reverse_channels();
      fprintf(settings_file, "  Reverse channels: %d\n", num_reverse_channels);

      fprintf(settings_file, "\n");

      if (reverse_sample_rate == 0) {
        reverse_sample_rate = input_sample_rate;
      }
      if (output_sample_rate == 0) {
        output_sample_rate = input_sample_rate;
      }

      reverse_samples_per_channel = reverse_sample_rate / 100;
      input_samples_per_channel = input_sample_rate / 100;
      output_samples_per_channel = output_sample_rate / 100;

      if (!FLAGS_raw) {
        // The WAV files need to be reset every time, because they cant change
        // their sample rate or number of channels.
        reverse_wav_file.reset(new WavWriter(FLAGS_reverse_file + ".wav",
                                             reverse_sample_rate,
                                             num_reverse_channels));
        input_wav_file.reset(new WavWriter(FLAGS_input_file + ".wav",
                                           input_sample_rate,
                                           num_input_channels));
        output_wav_file.reset(new WavWriter(FLAGS_output_file + ".wav",
                                            output_sample_rate,
                                            num_output_channels));
      }
    }
  }

  return 0;
}

}  // namespace webrtc

int main(int argc, char* argv[]) {
  return webrtc::do_main(argc, argv);
}
<commit_msg>audio_processing/tests: Adds a flag to unpack input data to text file<commit_after>/*
 *  Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

// Commandline tool to unpack audioproc debug files.
//
// The debug files are dumped as protobuf blobs. For analysis, it's necessary
// to unpack the file into its component parts: audio and other data.

#include <stdio.h>

#include "gflags/gflags.h"
#include "webrtc/audio_processing/debug.pb.h"
#include "webrtc/base/scoped_ptr.h"
#include "webrtc/modules/audio_processing/test/test_utils.h"
#include "webrtc/typedefs.h"

// TODO(andrew): unpack more of the data.
DEFINE_string(input_file, "input", "The name of the input stream file.");
DEFINE_string(output_file, "ref_out",
              "The name of the reference output stream file.");
DEFINE_string(reverse_file, "reverse",
              "The name of the reverse input stream file.");
DEFINE_string(delay_file, "delay.int32", "The name of the delay file.");
DEFINE_string(drift_file, "drift.int32", "The name of the drift file.");
DEFINE_string(level_file, "level.int32", "The name of the level file.");
DEFINE_string(keypress_file, "keypress.bool", "The name of the keypress file.");
DEFINE_string(settings_file, "settings.txt", "The name of the settings file.");
DEFINE_bool(full, false,
            "Unpack the full set of files (normally not needed).");
DEFINE_bool(raw, false, "Write raw data instead of a WAV file.");
DEFINE_bool(text,
            false,
            "Write non-audio files as text files instead of binary files.");

namespace webrtc {

using audioproc::Event;
using audioproc::ReverseStream;
using audioproc::Stream;
using audioproc::Init;

void WriteData(const void* data, size_t size, FILE* file,
               const std::string& filename) {
  if (fwrite(data, size, 1, file) != 1) {
    printf("Error when writing to %s\n", filename.c_str());
    exit(1);
  }
}

int do_main(int argc, char* argv[]) {
  std::string program_name = argv[0];
  std::string usage = "Commandline tool to unpack audioproc debug files.\n"
    "Example usage:\n" + program_name + " debug_dump.pb\n";
  google::SetUsageMessage(usage);
  google::ParseCommandLineFlags(&argc, &argv, true);

  if (argc < 2) {
    printf("%s", google::ProgramUsage());
    return 1;
  }

  FILE* debug_file = OpenFile(argv[1], "rb");

  Event event_msg;
  int frame_count = 0;
  int reverse_samples_per_channel = 0;
  int input_samples_per_channel = 0;
  int output_samples_per_channel = 0;
  int num_reverse_channels = 0;
  int num_input_channels = 0;
  int num_output_channels = 0;
  rtc::scoped_ptr<WavWriter> reverse_wav_file;
  rtc::scoped_ptr<WavWriter> input_wav_file;
  rtc::scoped_ptr<WavWriter> output_wav_file;
  rtc::scoped_ptr<RawFile> reverse_raw_file;
  rtc::scoped_ptr<RawFile> input_raw_file;
  rtc::scoped_ptr<RawFile> output_raw_file;
  while (ReadMessageFromFile(debug_file, &event_msg)) {
    if (event_msg.type() == Event::REVERSE_STREAM) {
      if (!event_msg.has_reverse_stream()) {
        printf("Corrupt input file: ReverseStream missing.\n");
        return 1;
      }

      const ReverseStream msg = event_msg.reverse_stream();
      if (msg.has_data()) {
        if (FLAGS_raw && !reverse_raw_file) {
          reverse_raw_file.reset(new RawFile(FLAGS_reverse_file + ".pcm"));
        }
        // TODO(aluebs): Replace "num_reverse_channels *
        // reverse_samples_per_channel" with "msg.data().size() /
        // sizeof(int16_t)" and so on when this fix in audio_processing has made
        // it into stable: https://webrtc-codereview.appspot.com/15299004/
        WriteIntData(reinterpret_cast<const int16_t*>(msg.data().data()),
                     num_reverse_channels * reverse_samples_per_channel,
                     reverse_wav_file.get(),
                     reverse_raw_file.get());
      } else if (msg.channel_size() > 0) {
        if (FLAGS_raw && !reverse_raw_file) {
          reverse_raw_file.reset(new RawFile(FLAGS_reverse_file + ".float"));
        }
        rtc::scoped_ptr<const float* []> data(
            new const float* [num_reverse_channels]);
        for (int i = 0; i < num_reverse_channels; ++i) {
          data[i] = reinterpret_cast<const float*>(msg.channel(i).data());
        }
        WriteFloatData(data.get(),
                       reverse_samples_per_channel,
                       num_reverse_channels,
                       reverse_wav_file.get(),
                       reverse_raw_file.get());
      }
    } else if (event_msg.type() == Event::STREAM) {
      frame_count++;
      if (!event_msg.has_stream()) {
        printf("Corrupt input file: Stream missing.\n");
        return 1;
      }

      const Stream msg = event_msg.stream();
      if (msg.has_input_data()) {
        if (FLAGS_raw && !input_raw_file) {
          input_raw_file.reset(new RawFile(FLAGS_input_file + ".pcm"));
        }
        WriteIntData(reinterpret_cast<const int16_t*>(msg.input_data().data()),
                     num_input_channels * input_samples_per_channel,
                     input_wav_file.get(),
                     input_raw_file.get());
      } else if (msg.input_channel_size() > 0) {
        if (FLAGS_raw && !input_raw_file) {
          input_raw_file.reset(new RawFile(FLAGS_input_file + ".float"));
        }
        rtc::scoped_ptr<const float* []> data(
            new const float* [num_input_channels]);
        for (int i = 0; i < num_input_channels; ++i) {
          data[i] = reinterpret_cast<const float*>(msg.input_channel(i).data());
        }
        WriteFloatData(data.get(),
                       input_samples_per_channel,
                       num_input_channels,
                       input_wav_file.get(),
                       input_raw_file.get());
      }

      if (msg.has_output_data()) {
        if (FLAGS_raw && !output_raw_file) {
          output_raw_file.reset(new RawFile(FLAGS_output_file + ".pcm"));
        }
        WriteIntData(reinterpret_cast<const int16_t*>(msg.output_data().data()),
                     num_output_channels * output_samples_per_channel,
                     output_wav_file.get(),
                     output_raw_file.get());
      } else if (msg.output_channel_size() > 0) {
        if (FLAGS_raw && !output_raw_file) {
          output_raw_file.reset(new RawFile(FLAGS_output_file + ".float"));
        }
        rtc::scoped_ptr<const float* []> data(
            new const float* [num_output_channels]);
        for (int i = 0; i < num_output_channels; ++i) {
          data[i] =
              reinterpret_cast<const float*>(msg.output_channel(i).data());
        }
        WriteFloatData(data.get(),
                       output_samples_per_channel,
                       num_output_channels,
                       output_wav_file.get(),
                       output_raw_file.get());
      }

      if (FLAGS_full) {
        if (msg.has_delay()) {
          static FILE* delay_file = OpenFile(FLAGS_delay_file, "wb");
          int32_t delay = msg.delay();
          if (FLAGS_text) {
            fprintf(delay_file, "%d\n", delay);
          } else {
            WriteData(&delay, sizeof(delay), delay_file, FLAGS_delay_file);
          }
        }

        if (msg.has_drift()) {
          static FILE* drift_file = OpenFile(FLAGS_drift_file, "wb");
          int32_t drift = msg.drift();
          if (FLAGS_text) {
            fprintf(drift_file, "%d\n", drift);
          } else {
            WriteData(&drift, sizeof(drift), drift_file, FLAGS_drift_file);
          }
        }

        if (msg.has_level()) {
          static FILE* level_file = OpenFile(FLAGS_level_file, "wb");
          int32_t level = msg.level();
          if (FLAGS_text) {
            fprintf(level_file, "%d\n", level);
          } else {
            WriteData(&level, sizeof(level), level_file, FLAGS_level_file);
          }
        }

        if (msg.has_keypress()) {
          static FILE* keypress_file = OpenFile(FLAGS_keypress_file, "wb");
          bool keypress = msg.keypress();
          if (FLAGS_text) {
            fprintf(keypress_file, "%d\n", keypress);
          } else {
            WriteData(&keypress, sizeof(keypress), keypress_file,
                      FLAGS_keypress_file);
          }
        }
      }
    } else if (event_msg.type() == Event::INIT) {
      if (!event_msg.has_init()) {
        printf("Corrupt input file: Init missing.\n");
        return 1;
      }

      static FILE* settings_file = OpenFile(FLAGS_settings_file, "wb");
      const Init msg = event_msg.init();
      // These should print out zeros if they're missing.
      fprintf(settings_file, "Init at frame: %d\n", frame_count);
      int input_sample_rate = msg.sample_rate();
      fprintf(settings_file, "  Input sample rate: %d\n", input_sample_rate);
      int output_sample_rate = msg.output_sample_rate();
      fprintf(settings_file, "  Output sample rate: %d\n", output_sample_rate);
      int reverse_sample_rate = msg.reverse_sample_rate();
      fprintf(settings_file,
              "  Reverse sample rate: %d\n",
              reverse_sample_rate);
      num_input_channels = msg.num_input_channels();
      fprintf(settings_file, "  Input channels: %d\n", num_input_channels);
      num_output_channels = msg.num_output_channels();
      fprintf(settings_file, "  Output channels: %d\n", num_output_channels);
      num_reverse_channels = msg.num_reverse_channels();
      fprintf(settings_file, "  Reverse channels: %d\n", num_reverse_channels);

      fprintf(settings_file, "\n");

      if (reverse_sample_rate == 0) {
        reverse_sample_rate = input_sample_rate;
      }
      if (output_sample_rate == 0) {
        output_sample_rate = input_sample_rate;
      }

      reverse_samples_per_channel = reverse_sample_rate / 100;
      input_samples_per_channel = input_sample_rate / 100;
      output_samples_per_channel = output_sample_rate / 100;

      if (!FLAGS_raw) {
        // The WAV files need to be reset every time, because they cant change
        // their sample rate or number of channels.
        reverse_wav_file.reset(new WavWriter(FLAGS_reverse_file + ".wav",
                                             reverse_sample_rate,
                                             num_reverse_channels));
        input_wav_file.reset(new WavWriter(FLAGS_input_file + ".wav",
                                           input_sample_rate,
                                           num_input_channels));
        output_wav_file.reset(new WavWriter(FLAGS_output_file + ".wav",
                                            output_sample_rate,
                                            num_output_channels));
      }
    }
  }

  return 0;
}

}  // namespace webrtc

int main(int argc, char* argv[]) {
  return webrtc::do_main(argc, argv);
}
<|endoftext|>


<commit_before>#include "ansi_display_driver.hpp"

#include "document/code_line_element.hpp"
#include "tools/ansi_wrapper.hpp"

#include <iostream>
using namespace std;

typedef AnsiWrapper::Color Color;

void AnsiDisplayDriver::display(Document * doc) {
	display(doc, cout);
}

void AnsiDisplayDriver::display(Document * doc, ostream & output) {
	Paragraph *p(nullptr);
	LineElement *l(nullptr);
	CodeLineElement *code_le(nullptr);

	AnsiWrapper wrapper(output);

	for (size_t i(0); i < doc->size(); ++i) {
		p = (*doc)[i];
		switch (p->level()) {
			case Paragraph::Level::Title1:
				wrapper.fg(Color::Blue);
				wrapper.underline();
				break;
			case Paragraph::Level::Title2:
				wrapper << "  ";
				wrapper.fg(Color::Blue);
				break;
			case Paragraph::Level::Quote:
				wrapper << "    ";
				wrapper.fg(Color::Blue);
				wrapper.reverse();
				break;
			case Paragraph::Level::UList1:
				wrapper << "    ";
				wrapper.fg(Color::Cyan);
				wrapper << "* ";
				wrapper.reset();
				break;
			default:
				wrapper << "    ";
				break;

		}
		for (size_t j(0); j < p->size(); ++j) {
			l = (*p)[j];
			code_le = dynamic_cast<CodeLineElement*>(l);

			if (code_le) {
				wrapper.reverse();
			}

			wrapper << l->content();

			wrapper.reset();

		}
		wrapper.reset();
		wrapper << endl;
	}
}

<commit_msg>Add Title3 to AnsiDisplayDriver<commit_after>#include "ansi_display_driver.hpp"

#include "document/code_line_element.hpp"
#include "tools/ansi_wrapper.hpp"

#include <iostream>
using namespace std;

typedef AnsiWrapper::Color Color;

void AnsiDisplayDriver::display(Document * doc) {
	display(doc, cout);
}

void AnsiDisplayDriver::display(Document * doc, ostream & output) {
	Paragraph *p(nullptr);
	LineElement *l(nullptr);
	CodeLineElement *code_le(nullptr);

	AnsiWrapper wrapper(output);

	for (size_t i(0); i < doc->size(); ++i) {
		p = (*doc)[i];
		switch (p->level()) {
			case Paragraph::Level::Title1:
				wrapper.fg(Color::Blue);
				wrapper.underline();
				break;
			case Paragraph::Level::Title2:
				wrapper << "  ";
				wrapper.fg(Color::Blue);
				break;
			case Paragraph::Level::Title3:
				wrapper << "    ";
				wrapper.fg(Color::Blue);
				break;
			case Paragraph::Level::Quote:
				wrapper << "    ";
				wrapper.fg(Color::Blue);
				wrapper.reverse();
				break;
			case Paragraph::Level::UList1:
				wrapper << "    ";
				wrapper.fg(Color::Cyan);
				wrapper << "* ";
				wrapper.reset();
				break;
			default:
				wrapper << "    ";
				break;

		}
		for (size_t j(0); j < p->size(); ++j) {
			l = (*p)[j];
			code_le = dynamic_cast<CodeLineElement*>(l);

			if (code_le) {
				wrapper.reverse();
			}

			wrapper << l->content();

			wrapper.reset();

		}
		wrapper.reset();
		wrapper << endl;
	}
}

<|endoftext|>