<commit_before>/*
 *  Copyright (c) 2015 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.
 */

#include "webrtc/modules/audio_coding/main/acm2/codec_owner.h"

#include "webrtc/base/checks.h"
#include "webrtc/engine_configurations.h"
#include "webrtc/modules/audio_coding/codecs/cng/include/audio_encoder_cng.h"
#include "webrtc/modules/audio_coding/codecs/g711/include/audio_encoder_pcm.h"
#include "webrtc/modules/audio_coding/codecs/g722/include/audio_encoder_g722.h"
#include "webrtc/modules/audio_coding/codecs/ilbc/interface/audio_encoder_ilbc.h"
#include "webrtc/modules/audio_coding/codecs/isac/fix/interface/audio_decoder_isacfix.h"
#include "webrtc/modules/audio_coding/codecs/isac/fix/interface/audio_encoder_isacfix.h"
#include "webrtc/modules/audio_coding/codecs/isac/main/interface/audio_decoder_isac.h"
#include "webrtc/modules/audio_coding/codecs/isac/main/interface/audio_encoder_isac.h"
#include "webrtc/modules/audio_coding/codecs/opus/interface/audio_encoder_opus.h"
#include "webrtc/modules/audio_coding/codecs/pcm16b/include/audio_encoder_pcm16b.h"
#include "webrtc/modules/audio_coding/codecs/red/audio_encoder_copy_red.h"

namespace webrtc {
namespace acm2 {

namespace {
bool IsIsac(const CodecInst& codec) {
  return
#if (defined(WEBRTC_CODEC_ISAC) || defined(WEBRTC_CODEC_ISACFX))
      !STR_CASE_CMP(codec.plname, "isac") ||
#endif
      false;
}

bool IsOpus(const CodecInst& codec) {
  return
#ifdef WEBRTC_CODEC_OPUS
      !STR_CASE_CMP(codec.plname, "opus") ||
#endif
      false;
}

bool IsPcmU(const CodecInst& codec) {
  return !STR_CASE_CMP(codec.plname, "pcmu");
}

bool IsPcmA(const CodecInst& codec) {
  return !STR_CASE_CMP(codec.plname, "pcma");
}

bool IsPcm16B(const CodecInst& codec) {
  return !STR_CASE_CMP(codec.plname, "l16");
}

bool IsIlbc(const CodecInst& codec) {
  return
#ifdef WEBRTC_CODEC_ILBC
      !STR_CASE_CMP(codec.plname, "ilbc") ||
#endif
      false;
}

bool IsG722(const CodecInst& codec) {
  return
#ifdef WEBRTC_CODEC_G722
      !STR_CASE_CMP(codec.plname, "g722") ||
#endif
      false;
}
}  // namespace

CodecOwner::CodecOwner() : external_speech_encoder_(nullptr) {
}

CodecOwner::~CodecOwner() = default;

namespace {

rtc::scoped_ptr<AudioDecoder> CreateIsacDecoder(
    LockedIsacBandwidthInfo* bwinfo) {
#if defined(WEBRTC_CODEC_ISACFX)
  return rtc_make_scoped_ptr(new AudioDecoderIsacFix(bwinfo));
#elif defined(WEBRTC_CODEC_ISAC)
  return rtc_make_scoped_ptr(new AudioDecoderIsac(bwinfo));
#else
  FATAL() << "iSAC is not supported.";
  return rtc::scoped_ptr<AudioDecoder>();
#endif
}

rtc::scoped_ptr<AudioEncoder> CreateIsacEncoder(
    const CodecInst& speech_inst,
    LockedIsacBandwidthInfo* bwinfo) {
#if defined(WEBRTC_CODEC_ISACFX)
  return rtc_make_scoped_ptr(new AudioEncoderIsacFix(speech_inst, bwinfo));
#elif defined(WEBRTC_CODEC_ISAC)
  return rtc_make_scoped_ptr(new AudioEncoderIsac(speech_inst, bwinfo));
#else
  FATAL() << "iSAC is not supported.";
  return rtc::scoped_ptr<AudioEncoderMutable>();
#endif
}

rtc::scoped_ptr<AudioEncoder> CreateSpeechEncoder(
    const CodecInst& speech_inst,
    LockedIsacBandwidthInfo* bwinfo) {
  if (IsIsac(speech_inst)) {
    return CreateIsacEncoder(speech_inst, bwinfo);
  } else if (IsOpus(speech_inst)) {
    return rtc_make_scoped_ptr(new AudioEncoderOpus(speech_inst));
  } else if (IsPcmU(speech_inst)) {
    return rtc_make_scoped_ptr(new AudioEncoderPcmU(speech_inst));
  } else if (IsPcmA(speech_inst)) {
    return rtc_make_scoped_ptr(new AudioEncoderPcmA(speech_inst));
  } else if (IsPcm16B(speech_inst)) {
    return rtc_make_scoped_ptr(new AudioEncoderPcm16B(speech_inst));
  } else if (IsIlbc(speech_inst)) {
    return rtc_make_scoped_ptr(new AudioEncoderIlbc(speech_inst));
  } else if (IsG722(speech_inst)) {
    return rtc_make_scoped_ptr(new AudioEncoderG722(speech_inst));
  } else {
    FATAL() << "Could not create encoder of type " << speech_inst.plname;
    return rtc::scoped_ptr<AudioEncoder>();
  }
}

AudioEncoder* CreateRedEncoder(int red_payload_type,
                               AudioEncoder* encoder,
                               rtc::scoped_ptr<AudioEncoder>* red_encoder) {
#ifdef WEBRTC_CODEC_RED
  if (red_payload_type != -1) {
    AudioEncoderCopyRed::Config config;
    config.payload_type = red_payload_type;
    config.speech_encoder = encoder;
    red_encoder->reset(new AudioEncoderCopyRed(config));
    return red_encoder->get();
  }
#endif

  red_encoder->reset();
  return encoder;
}

void CreateCngEncoder(int cng_payload_type,
                      ACMVADMode vad_mode,
                      AudioEncoder* encoder,
                      rtc::scoped_ptr<AudioEncoder>* cng_encoder) {
  if (cng_payload_type == -1) {
    cng_encoder->reset();
    return;
  }
  AudioEncoderCng::Config config;
  config.num_channels = encoder->NumChannels();
  config.payload_type = cng_payload_type;
  config.speech_encoder = encoder;
  switch (vad_mode) {
    case VADNormal:
      config.vad_mode = Vad::kVadNormal;
      break;
    case VADLowBitrate:
      config.vad_mode = Vad::kVadLowBitrate;
      break;
    case VADAggr:
      config.vad_mode = Vad::kVadAggressive;
      break;
    case VADVeryAggr:
      config.vad_mode = Vad::kVadVeryAggressive;
      break;
    default:
      FATAL();
  }
  cng_encoder->reset(new AudioEncoderCng(config));
}
}  // namespace

void CodecOwner::SetEncoders(const CodecInst& speech_inst,
                             int cng_payload_type,
                             ACMVADMode vad_mode,
                             int red_payload_type) {
  speech_encoder_ = CreateSpeechEncoder(speech_inst, &isac_bandwidth_info_);
  external_speech_encoder_ = nullptr;
  ChangeCngAndRed(cng_payload_type, vad_mode, red_payload_type);
}

void CodecOwner::SetEncoders(AudioEncoder* external_speech_encoder,
                             int cng_payload_type,
                             ACMVADMode vad_mode,
                             int red_payload_type) {
  external_speech_encoder_ = external_speech_encoder;
  speech_encoder_.reset();
  ChangeCngAndRed(cng_payload_type, vad_mode, red_payload_type);
}

void CodecOwner::ChangeCngAndRed(int cng_payload_type,
                                 ACMVADMode vad_mode,
                                 int red_payload_type) {
  AudioEncoder* speech_encoder = SpeechEncoder();
  if (cng_payload_type != -1 || red_payload_type != -1) {
    // The RED and CNG encoders need to be in sync with the speech encoder, so
    // reset the latter to ensure its buffer is empty.
    speech_encoder->Reset();
  }
  AudioEncoder* encoder =
      CreateRedEncoder(red_payload_type, speech_encoder, &red_encoder_);
  CreateCngEncoder(cng_payload_type, vad_mode, encoder, &cng_encoder_);
  RTC_DCHECK_EQ(!!speech_encoder_ + !!external_speech_encoder_, 1);
}

AudioDecoder* CodecOwner::GetIsacDecoder() {
  if (!isac_decoder_)
    isac_decoder_ = CreateIsacDecoder(&isac_bandwidth_info_);
  return isac_decoder_.get();
}

AudioEncoder* CodecOwner::Encoder() {
  const auto& const_this = *this;
  return const_cast<AudioEncoder*>(const_this.Encoder());
}

const AudioEncoder* CodecOwner::Encoder() const {
  if (cng_encoder_)
    return cng_encoder_.get();
  if (red_encoder_)
    return red_encoder_.get();
  return SpeechEncoder();
}

AudioEncoder* CodecOwner::SpeechEncoder() {
  const auto* const_this = this;
  return const_cast<AudioEncoder*>(const_this->SpeechEncoder());
}

const AudioEncoder* CodecOwner::SpeechEncoder() const {
  RTC_DCHECK(!speech_encoder_ || !external_speech_encoder_);
  return external_speech_encoder_ ? external_speech_encoder_
                                  : speech_encoder_.get();
}

}  // namespace acm2
}  // namespace webrtc
<commit_msg>CodecOwner: Don't look at definitions for classes we don't link with<commit_after>/*
 *  Copyright (c) 2015 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.
 */

#include "webrtc/modules/audio_coding/main/acm2/codec_owner.h"

#include "webrtc/base/checks.h"
#include "webrtc/engine_configurations.h"
#include "webrtc/modules/audio_coding/codecs/cng/include/audio_encoder_cng.h"
#include "webrtc/modules/audio_coding/codecs/g711/include/audio_encoder_pcm.h"
#ifdef WEBRTC_CODEC_G722
#include "webrtc/modules/audio_coding/codecs/g722/include/audio_encoder_g722.h"
#endif
#ifdef WEBRTC_CODEC_ILBC
#include "webrtc/modules/audio_coding/codecs/ilbc/interface/audio_encoder_ilbc.h"
#endif
#ifdef WEBRTC_CODEC_ISACFX
#include "webrtc/modules/audio_coding/codecs/isac/fix/interface/audio_decoder_isacfix.h"
#include "webrtc/modules/audio_coding/codecs/isac/fix/interface/audio_encoder_isacfix.h"
#endif
#ifdef WEBRTC_CODEC_ISAC
#include "webrtc/modules/audio_coding/codecs/isac/main/interface/audio_decoder_isac.h"
#include "webrtc/modules/audio_coding/codecs/isac/main/interface/audio_encoder_isac.h"
#endif
#ifdef WEBRTC_CODEC_OPUS
#include "webrtc/modules/audio_coding/codecs/opus/interface/audio_encoder_opus.h"
#endif
#include "webrtc/modules/audio_coding/codecs/pcm16b/include/audio_encoder_pcm16b.h"
#ifdef WEBRTC_CODEC_RED
#include "webrtc/modules/audio_coding/codecs/red/audio_encoder_copy_red.h"
#endif

namespace webrtc {
namespace acm2 {

namespace {
bool IsIsac(const CodecInst& codec) {
  return
#if (defined(WEBRTC_CODEC_ISAC) || defined(WEBRTC_CODEC_ISACFX))
      !STR_CASE_CMP(codec.plname, "isac") ||
#endif
      false;
}

bool IsOpus(const CodecInst& codec) {
  return
#ifdef WEBRTC_CODEC_OPUS
      !STR_CASE_CMP(codec.plname, "opus") ||
#endif
      false;
}

bool IsPcmU(const CodecInst& codec) {
  return !STR_CASE_CMP(codec.plname, "pcmu");
}

bool IsPcmA(const CodecInst& codec) {
  return !STR_CASE_CMP(codec.plname, "pcma");
}

bool IsPcm16B(const CodecInst& codec) {
  return !STR_CASE_CMP(codec.plname, "l16");
}

bool IsIlbc(const CodecInst& codec) {
  return
#ifdef WEBRTC_CODEC_ILBC
      !STR_CASE_CMP(codec.plname, "ilbc") ||
#endif
      false;
}

bool IsG722(const CodecInst& codec) {
  return
#ifdef WEBRTC_CODEC_G722
      !STR_CASE_CMP(codec.plname, "g722") ||
#endif
      false;
}
}  // namespace

CodecOwner::CodecOwner() : external_speech_encoder_(nullptr) {
}

CodecOwner::~CodecOwner() = default;

namespace {

rtc::scoped_ptr<AudioDecoder> CreateIsacDecoder(
    LockedIsacBandwidthInfo* bwinfo) {
#if defined(WEBRTC_CODEC_ISACFX)
  return rtc_make_scoped_ptr(new AudioDecoderIsacFix(bwinfo));
#elif defined(WEBRTC_CODEC_ISAC)
  return rtc_make_scoped_ptr(new AudioDecoderIsac(bwinfo));
#else
  FATAL() << "iSAC is not supported.";
  return rtc::scoped_ptr<AudioDecoder>();
#endif
}

rtc::scoped_ptr<AudioEncoder> CreateIsacEncoder(
    const CodecInst& speech_inst,
    LockedIsacBandwidthInfo* bwinfo) {
#if defined(WEBRTC_CODEC_ISACFX)
  return rtc_make_scoped_ptr(new AudioEncoderIsacFix(speech_inst, bwinfo));
#elif defined(WEBRTC_CODEC_ISAC)
  return rtc_make_scoped_ptr(new AudioEncoderIsac(speech_inst, bwinfo));
#else
  FATAL() << "iSAC is not supported.";
  return rtc::scoped_ptr<AudioEncoderMutable>();
#endif
}

rtc::scoped_ptr<AudioEncoder> CreateSpeechEncoder(
    const CodecInst& speech_inst,
    LockedIsacBandwidthInfo* bwinfo) {
  if (IsIsac(speech_inst)) {
    return CreateIsacEncoder(speech_inst, bwinfo);
  } else if (IsOpus(speech_inst)) {
    return rtc_make_scoped_ptr(new AudioEncoderOpus(speech_inst));
  } else if (IsPcmU(speech_inst)) {
    return rtc_make_scoped_ptr(new AudioEncoderPcmU(speech_inst));
  } else if (IsPcmA(speech_inst)) {
    return rtc_make_scoped_ptr(new AudioEncoderPcmA(speech_inst));
  } else if (IsPcm16B(speech_inst)) {
    return rtc_make_scoped_ptr(new AudioEncoderPcm16B(speech_inst));
  } else if (IsIlbc(speech_inst)) {
    return rtc_make_scoped_ptr(new AudioEncoderIlbc(speech_inst));
  } else if (IsG722(speech_inst)) {
    return rtc_make_scoped_ptr(new AudioEncoderG722(speech_inst));
  } else {
    FATAL() << "Could not create encoder of type " << speech_inst.plname;
    return rtc::scoped_ptr<AudioEncoder>();
  }
}

AudioEncoder* CreateRedEncoder(int red_payload_type,
                               AudioEncoder* encoder,
                               rtc::scoped_ptr<AudioEncoder>* red_encoder) {
#ifdef WEBRTC_CODEC_RED
  if (red_payload_type != -1) {
    AudioEncoderCopyRed::Config config;
    config.payload_type = red_payload_type;
    config.speech_encoder = encoder;
    red_encoder->reset(new AudioEncoderCopyRed(config));
    return red_encoder->get();
  }
#endif

  red_encoder->reset();
  return encoder;
}

void CreateCngEncoder(int cng_payload_type,
                      ACMVADMode vad_mode,
                      AudioEncoder* encoder,
                      rtc::scoped_ptr<AudioEncoder>* cng_encoder) {
  if (cng_payload_type == -1) {
    cng_encoder->reset();
    return;
  }
  AudioEncoderCng::Config config;
  config.num_channels = encoder->NumChannels();
  config.payload_type = cng_payload_type;
  config.speech_encoder = encoder;
  switch (vad_mode) {
    case VADNormal:
      config.vad_mode = Vad::kVadNormal;
      break;
    case VADLowBitrate:
      config.vad_mode = Vad::kVadLowBitrate;
      break;
    case VADAggr:
      config.vad_mode = Vad::kVadAggressive;
      break;
    case VADVeryAggr:
      config.vad_mode = Vad::kVadVeryAggressive;
      break;
    default:
      FATAL();
  }
  cng_encoder->reset(new AudioEncoderCng(config));
}
}  // namespace

void CodecOwner::SetEncoders(const CodecInst& speech_inst,
                             int cng_payload_type,
                             ACMVADMode vad_mode,
                             int red_payload_type) {
  speech_encoder_ = CreateSpeechEncoder(speech_inst, &isac_bandwidth_info_);
  external_speech_encoder_ = nullptr;
  ChangeCngAndRed(cng_payload_type, vad_mode, red_payload_type);
}

void CodecOwner::SetEncoders(AudioEncoder* external_speech_encoder,
                             int cng_payload_type,
                             ACMVADMode vad_mode,
                             int red_payload_type) {
  external_speech_encoder_ = external_speech_encoder;
  speech_encoder_.reset();
  ChangeCngAndRed(cng_payload_type, vad_mode, red_payload_type);
}

void CodecOwner::ChangeCngAndRed(int cng_payload_type,
                                 ACMVADMode vad_mode,
                                 int red_payload_type) {
  AudioEncoder* speech_encoder = SpeechEncoder();
  if (cng_payload_type != -1 || red_payload_type != -1) {
    // The RED and CNG encoders need to be in sync with the speech encoder, so
    // reset the latter to ensure its buffer is empty.
    speech_encoder->Reset();
  }
  AudioEncoder* encoder =
      CreateRedEncoder(red_payload_type, speech_encoder, &red_encoder_);
  CreateCngEncoder(cng_payload_type, vad_mode, encoder, &cng_encoder_);
  RTC_DCHECK_EQ(!!speech_encoder_ + !!external_speech_encoder_, 1);
}

AudioDecoder* CodecOwner::GetIsacDecoder() {
  if (!isac_decoder_)
    isac_decoder_ = CreateIsacDecoder(&isac_bandwidth_info_);
  return isac_decoder_.get();
}

AudioEncoder* CodecOwner::Encoder() {
  const auto& const_this = *this;
  return const_cast<AudioEncoder*>(const_this.Encoder());
}

const AudioEncoder* CodecOwner::Encoder() const {
  if (cng_encoder_)
    return cng_encoder_.get();
  if (red_encoder_)
    return red_encoder_.get();
  return SpeechEncoder();
}

AudioEncoder* CodecOwner::SpeechEncoder() {
  const auto* const_this = this;
  return const_cast<AudioEncoder*>(const_this->SpeechEncoder());
}

const AudioEncoder* CodecOwner::SpeechEncoder() const {
  RTC_DCHECK(!speech_encoder_ || !external_speech_encoder_);
  return external_speech_encoder_ ? external_speech_encoder_
                                  : speech_encoder_.get();
}

}  // namespace acm2
}  // namespace webrtc
<|endoftext|>


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

// Software adjust volume of samples, allows each audio stream its own
// volume without impacting master volume for chrome and other applications.

// Implemented as templates to allow 8, 16 and 32 bit implementations.
// 8 bit is unsigned and biased by 128.

// TODO(vrk): This file has been running pretty wild and free, and it's likely
// that a lot of the functions can be simplified and made more elegant. Revisit
// after other audio cleanup is done. (crbug.com/120319)

#include "media/audio/audio_util.h"

#include <algorithm>
#include <limits>

#include "base/basictypes.h"
#include "base/command_line.h"
#include "base/logging.h"
#include "base/string_number_conversions.h"
#include "base/time.h"
#include "media/audio/audio_parameters.h"
#include "media/base/audio_bus.h"
#include "media/base/media_switches.h"

#if defined(OS_MACOSX)
#include "media/audio/mac/audio_low_latency_input_mac.h"
#include "media/audio/mac/audio_low_latency_output_mac.h"
#elif defined(OS_WIN)
#include "base/win/windows_version.h"
#include "media/audio/audio_manager_base.h"
#include "media/audio/win/audio_low_latency_input_win.h"
#include "media/audio/win/audio_low_latency_output_win.h"
#include "media/audio/win/core_audio_util_win.h"
#include "media/base/limits.h"
#endif

namespace media {

// Returns user buffer size as specified on the command line or 0 if no buffer
// size has been specified.
static int GetUserBufferSize() {
  const CommandLine* cmd_line = CommandLine::ForCurrentProcess();
  int buffer_size = 0;
  std::string buffer_size_str(cmd_line->GetSwitchValueASCII(
      switches::kAudioBufferSize));
  if (base::StringToInt(buffer_size_str, &buffer_size) && buffer_size > 0) {
    return buffer_size;
  }

  return 0;
}

// TODO(fbarchard): Convert to intrinsics for better efficiency.
template<class Fixed>
static int ScaleChannel(int channel, int volume) {
  return static_cast<int>((static_cast<Fixed>(channel) * volume) >> 16);
}

template<class Format, class Fixed, int bias>
static void AdjustVolume(Format* buf_out,
                         int sample_count,
                         int fixed_volume) {
  for (int i = 0; i < sample_count; ++i) {
    buf_out[i] = static_cast<Format>(ScaleChannel<Fixed>(buf_out[i] - bias,
                                                         fixed_volume) + bias);
  }
}

static const int kChannel_L = 0;
static const int kChannel_R = 1;
static const int kChannel_C = 2;

template<class Fixed, int min_value, int max_value>
static int AddSaturated(int val, int adder) {
  Fixed sum = static_cast<Fixed>(val) + static_cast<Fixed>(adder);
  if (sum > max_value)
    return max_value;
  if (sum < min_value)
    return min_value;
  return static_cast<int>(sum);
}

// AdjustVolume() does an in place audio sample change.
bool AdjustVolume(void* buf,
                  size_t buflen,
                  int channels,
                  int bytes_per_sample,
                  float volume) {
  DCHECK(buf);
  if (volume < 0.0f || volume > 1.0f)
    return false;
  if (volume == 1.0f) {
    return true;
  } else if (volume == 0.0f) {
    memset(buf, 0, buflen);
    return true;
  }
  if (channels > 0 && channels <= 8 && bytes_per_sample > 0) {
    int sample_count = buflen / bytes_per_sample;
    const int fixed_volume = static_cast<int>(volume * 65536);
    if (bytes_per_sample == 1) {
      AdjustVolume<uint8, int32, 128>(reinterpret_cast<uint8*>(buf),
                                      sample_count,
                                      fixed_volume);
      return true;
    } else if (bytes_per_sample == 2) {
      AdjustVolume<int16, int32, 0>(reinterpret_cast<int16*>(buf),
                                    sample_count,
                                    fixed_volume);
      return true;
    } else if (bytes_per_sample == 4) {
      AdjustVolume<int32, int64, 0>(reinterpret_cast<int32*>(buf),
                                    sample_count,
                                    fixed_volume);
      return true;
    }
  }
  return false;
}

// TODO(enal): use template specialization and size-specific intrinsics.
//             Call is on the time-critical path, and by using SSE/AVX
//             instructions we can speed things up by ~4-8x, more for the case
//             when we have to adjust volume as well.
template<class Format, class Fixed, int min_value, int max_value, int bias>
static void MixStreams(Format* dst, Format* src, int count, float volume) {
  if (volume == 0.0f)
    return;
  if (volume == 1.0f) {
    // Most common case -- no need to adjust volume.
    for (int i = 0; i < count; ++i) {
      Fixed value = AddSaturated<Fixed, min_value, max_value>(dst[i] - bias,
                                                              src[i] - bias);
      dst[i] = static_cast<Format>(value + bias);
    }
  } else {
    // General case -- have to adjust volume before mixing.
    const int fixed_volume = static_cast<int>(volume * 65536);
    for (int i = 0; i < count; ++i) {
      Fixed adjusted_src = ScaleChannel<Fixed>(src[i] - bias, fixed_volume);
      Fixed value = AddSaturated<Fixed, min_value, max_value>(dst[i] - bias,
                                                              adjusted_src);
      dst[i] = static_cast<Format>(value + bias);
    }
  }
}

void MixStreams(void* dst,
                void* src,
                size_t buflen,
                int bytes_per_sample,
                float volume) {
  DCHECK(dst);
  DCHECK(src);
  DCHECK_GE(volume, 0.0f);
  DCHECK_LE(volume, 1.0f);
  switch (bytes_per_sample) {
    case 1:
      MixStreams<uint8, int32, -128, 127, 128>(static_cast<uint8*>(dst),
                                               static_cast<uint8*>(src),
                                               buflen,
                                               volume);
      break;
    case 2:
      DCHECK_EQ(0u, buflen % 2);
      MixStreams<int16, int32, -32768, 32767, 0>(static_cast<int16*>(dst),
                                                 static_cast<int16*>(src),
                                                 buflen / 2,
                                                 volume);
      break;
    case 4:
      DCHECK_EQ(0u, buflen % 4);
      MixStreams<int32, int64, 0x80000000, 0x7fffffff, 0>(
          static_cast<int32*>(dst),
          static_cast<int32*>(src),
          buflen / 4,
          volume);
      break;
    default:
      NOTREACHED() << "Illegal bytes per sample";
      break;
  }
}

int GetAudioHardwareSampleRate() {
#if defined(OS_MACOSX)
  // Hardware sample-rate on the Mac can be configured, so we must query.
  return AUAudioOutputStream::HardwareSampleRate();
#elif defined(OS_WIN)
  if (!CoreAudioUtil::IsSupported()) {
    // Fall back to Windows Wave implementation on Windows XP or lower
    // and use 48kHz as default input sample rate.
    return 48000;
  }

  // TODO(crogers): tune this rate for best possible WebAudio performance.
  // WebRTC works well at 48kHz and a buffer size of 480 samples will be used
  // for this case. Note that exclusive mode is experimental.
  const CommandLine* cmd_line = CommandLine::ForCurrentProcess();
  if (cmd_line->HasSwitch(switches::kEnableExclusiveAudio)) {
    // This sample rate will be combined with a buffer size of 256 samples
    // (see GetAudioHardwareBufferSize()), which corresponds to an output
    // delay of ~5.33ms.
    return 48000;
  }

  // Hardware sample-rate on Windows can be configured, so we must query.
  // TODO(henrika): improve possibility to specify an audio endpoint.
  // Use the default device (same as for Wave) for now to be compatible
  // or possibly remove the ERole argument completely until it is in use.
  return WASAPIAudioOutputStream::HardwareSampleRate(eConsole);
#elif defined(OS_ANDROID)
  return 16000;
#else
  // Hardware for Linux is nearly always 48KHz.
  // TODO(crogers) : return correct value in rare non-48KHz cases.
  return 48000;
#endif
}

int GetAudioInputHardwareSampleRate(const std::string& device_id) {
  // TODO(henrika): add support for device selection on all platforms.
  // Only exists on Windows today.
#if defined(OS_MACOSX)
  return AUAudioInputStream::HardwareSampleRate();
#elif defined(OS_WIN)
  if (!CoreAudioUtil::IsSupported()) {
    return 48000;
  }
  return WASAPIAudioInputStream::HardwareSampleRate(device_id);
#elif defined(OS_ANDROID)
  return 16000;
#else
  return 48000;
#endif
}

size_t GetAudioHardwareBufferSize() {
  int user_buffer_size = GetUserBufferSize();
  if (user_buffer_size)
    return user_buffer_size;

  // The sizes here were determined by experimentation and are roughly
  // the lowest value (for low latency) that still allowed glitch-free
  // audio under high loads.
  //
  // For Mac OS X and Windows the chromium audio backend uses a low-latency
  // Core Audio API, so a low buffer size is possible. For Linux, further
  // tuning may be needed.
#if defined(OS_MACOSX)
  return 128;
#elif defined(OS_WIN)
  // Buffer size to use when a proper size can't be determined from the system.
  static const int kFallbackBufferSize = 4096;

  if (!CoreAudioUtil::IsSupported()) {
    // Fall back to Windows Wave implementation on Windows XP or lower
    // and assume 48kHz as default sample rate.
    return kFallbackBufferSize;
  }

  // TODO(crogers): tune this size to best possible WebAudio performance.
  // WebRTC always uses 10ms for Windows and does not call this method.
  // Note that exclusive mode is experimental.
  const CommandLine* cmd_line = CommandLine::ForCurrentProcess();
  if (cmd_line->HasSwitch(switches::kEnableExclusiveAudio)) {
    return 256;
  }

  // TODO(henrika): remove when the --enable-webaudio-input flag is no longer
  // utilized.
  if (cmd_line->HasSwitch(switches::kEnableWebAudioInput)) {
    AudioParameters params;
    HRESULT hr = CoreAudioUtil::GetPreferredAudioParameters(eRender, eConsole,
                                                            &params);
    return FAILED(hr) ? kFallbackBufferSize : params.frames_per_buffer();
  }

  // This call must be done on a COM thread configured as MTA.
  // TODO(tommi): http://code.google.com/p/chromium/issues/detail?id=103835.
  int mixing_sample_rate =
      WASAPIAudioOutputStream::HardwareSampleRate(eConsole);

  // Windows will return a sample rate of 0 when no audio output is available
  // (i.e. via RemoteDesktop with remote audio disabled), but we should never
  // return a buffer size of zero.
  if (mixing_sample_rate == 0)
    return kFallbackBufferSize;

  // Use different buffer sizes depening on the sample rate . The existing
  // WASAPI implementation is tuned to provide the most stable callback
  // sequence using these combinations.
  if (mixing_sample_rate % 11025 == 0)
    // Use buffer size of ~10.15873 ms.
    return (112 * (mixing_sample_rate / 11025));

  if (mixing_sample_rate % 8000 == 0)
    // Use buffer size of 10ms.
    return (80 * (mixing_sample_rate / 8000));

  // Ensure we always return a buffer size which is somewhat appropriate.
  LOG(ERROR) << "Unknown sample rate " << mixing_sample_rate << " detected.";
  if (mixing_sample_rate > limits::kMinSampleRate)
    return (mixing_sample_rate / 100);
  return kFallbackBufferSize;
#else
  return 2048;
#endif
}

ChannelLayout GetAudioInputHardwareChannelLayout(const std::string& device_id) {
  // TODO(henrika): add support for device selection on all platforms.
  // Only exists on Windows today.
#if defined(OS_MACOSX)
  return CHANNEL_LAYOUT_MONO;
#elif defined(OS_WIN)
  if (!CoreAudioUtil::IsSupported()) {
    // Fall back to Windows Wave implementation on Windows XP or lower and
    // use stereo by default.
    return CHANNEL_LAYOUT_STEREO;
  }
  return WASAPIAudioInputStream::HardwareChannelCount(device_id) == 1 ?
      CHANNEL_LAYOUT_MONO : CHANNEL_LAYOUT_STEREO;
#else
  return CHANNEL_LAYOUT_STEREO;
#endif
}

// Computes a buffer size based on the given |sample_rate|. Must be used in
// conjunction with AUDIO_PCM_LINEAR.
size_t GetHighLatencyOutputBufferSize(int sample_rate) {
  int user_buffer_size = GetUserBufferSize();
  if (user_buffer_size)
    return user_buffer_size;

  // TODO(vrk/crogers): The buffer sizes that this function computes is probably
  // overly conservative. However, reducing the buffer size to 2048-8192 bytes
  // caused crbug.com/108396. This computation should be revisited while making
  // sure crbug.com/108396 doesn't happen again.

  // The minimum number of samples in a hardware packet.
  // This value is selected so that we can handle down to 5khz sample rate.
  static const size_t kMinSamplesPerHardwarePacket = 1024;

  // The maximum number of samples in a hardware packet.
  // This value is selected so that we can handle up to 192khz sample rate.
  static const size_t kMaxSamplesPerHardwarePacket = 64 * 1024;

  // This constant governs the hardware audio buffer size, this value should be
  // chosen carefully.
  // This value is selected so that we have 8192 samples for 48khz streams.
  static const size_t kMillisecondsPerHardwarePacket = 170;

  // Select the number of samples that can provide at least
  // |kMillisecondsPerHardwarePacket| worth of audio data.
  size_t samples = kMinSamplesPerHardwarePacket;
  while (samples <= kMaxSamplesPerHardwarePacket &&
         samples * base::Time::kMillisecondsPerSecond <
         sample_rate * kMillisecondsPerHardwarePacket) {
    samples *= 2;
  }
  return samples;
}

#if defined(OS_WIN)

int NumberOfWaveOutBuffers() {
  // Use 4 buffers for Vista, 3 for everyone else:
  //  - The entire Windows audio stack was rewritten for Windows Vista and wave
  //    out performance was degraded compared to XP.
  //  - The regression was fixed in Windows 7 and most configurations will work
  //    with 2, but some (e.g., some Sound Blasters) still need 3.
  //  - Some XP configurations (even multi-processor ones) also need 3.
  return (base::win::GetVersion() == base::win::VERSION_VISTA) ? 4 : 3;
}

#endif

}  // namespace media
<commit_msg>media: Use named constants instead of literals.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// Software adjust volume of samples, allows each audio stream its own
// volume without impacting master volume for chrome and other applications.

// Implemented as templates to allow 8, 16 and 32 bit implementations.
// 8 bit is unsigned and biased by 128.

// TODO(vrk): This file has been running pretty wild and free, and it's likely
// that a lot of the functions can be simplified and made more elegant. Revisit
// after other audio cleanup is done. (crbug.com/120319)

#include "media/audio/audio_util.h"

#include <algorithm>
#include <limits>

#include "base/basictypes.h"
#include "base/command_line.h"
#include "base/logging.h"
#include "base/string_number_conversions.h"
#include "base/time.h"
#include "media/audio/audio_parameters.h"
#include "media/base/audio_bus.h"
#include "media/base/media_switches.h"

#if defined(OS_MACOSX)
#include "media/audio/mac/audio_low_latency_input_mac.h"
#include "media/audio/mac/audio_low_latency_output_mac.h"
#elif defined(OS_WIN)
#include "base/win/windows_version.h"
#include "media/audio/audio_manager_base.h"
#include "media/audio/win/audio_low_latency_input_win.h"
#include "media/audio/win/audio_low_latency_output_win.h"
#include "media/audio/win/core_audio_util_win.h"
#include "media/base/limits.h"
#endif

namespace media {

// Returns user buffer size as specified on the command line or 0 if no buffer
// size has been specified.
static int GetUserBufferSize() {
  const CommandLine* cmd_line = CommandLine::ForCurrentProcess();
  int buffer_size = 0;
  std::string buffer_size_str(cmd_line->GetSwitchValueASCII(
      switches::kAudioBufferSize));
  if (base::StringToInt(buffer_size_str, &buffer_size) && buffer_size > 0) {
    return buffer_size;
  }

  return 0;
}

// TODO(fbarchard): Convert to intrinsics for better efficiency.
template<class Fixed>
static int ScaleChannel(int channel, int volume) {
  return static_cast<int>((static_cast<Fixed>(channel) * volume) >> 16);
}

template<class Format, class Fixed, int bias>
static void AdjustVolume(Format* buf_out,
                         int sample_count,
                         int fixed_volume) {
  for (int i = 0; i < sample_count; ++i) {
    buf_out[i] = static_cast<Format>(ScaleChannel<Fixed>(buf_out[i] - bias,
                                                         fixed_volume) + bias);
  }
}

static const int kChannel_L = 0;
static const int kChannel_R = 1;
static const int kChannel_C = 2;

template<class Fixed, int min_value, int max_value>
static int AddSaturated(int val, int adder) {
  Fixed sum = static_cast<Fixed>(val) + static_cast<Fixed>(adder);
  if (sum > max_value)
    return max_value;
  if (sum < min_value)
    return min_value;
  return static_cast<int>(sum);
}

// AdjustVolume() does an in place audio sample change.
bool AdjustVolume(void* buf,
                  size_t buflen,
                  int channels,
                  int bytes_per_sample,
                  float volume) {
  DCHECK(buf);
  if (volume < 0.0f || volume > 1.0f)
    return false;
  if (volume == 1.0f) {
    return true;
  } else if (volume == 0.0f) {
    memset(buf, 0, buflen);
    return true;
  }
  if (channels > 0 && channels <= 8 && bytes_per_sample > 0) {
    int sample_count = buflen / bytes_per_sample;
    const int fixed_volume = static_cast<int>(volume * 65536);
    if (bytes_per_sample == 1) {
      AdjustVolume<uint8, int32, 128>(reinterpret_cast<uint8*>(buf),
                                      sample_count,
                                      fixed_volume);
      return true;
    } else if (bytes_per_sample == 2) {
      AdjustVolume<int16, int32, 0>(reinterpret_cast<int16*>(buf),
                                    sample_count,
                                    fixed_volume);
      return true;
    } else if (bytes_per_sample == 4) {
      AdjustVolume<int32, int64, 0>(reinterpret_cast<int32*>(buf),
                                    sample_count,
                                    fixed_volume);
      return true;
    }
  }
  return false;
}

// TODO(enal): use template specialization and size-specific intrinsics.
//             Call is on the time-critical path, and by using SSE/AVX
//             instructions we can speed things up by ~4-8x, more for the case
//             when we have to adjust volume as well.
template<class Format, class Fixed, int min_value, int max_value, int bias>
static void MixStreams(Format* dst, Format* src, int count, float volume) {
  if (volume == 0.0f)
    return;
  if (volume == 1.0f) {
    // Most common case -- no need to adjust volume.
    for (int i = 0; i < count; ++i) {
      Fixed value = AddSaturated<Fixed, min_value, max_value>(dst[i] - bias,
                                                              src[i] - bias);
      dst[i] = static_cast<Format>(value + bias);
    }
  } else {
    // General case -- have to adjust volume before mixing.
    const int fixed_volume = static_cast<int>(volume * 65536);
    for (int i = 0; i < count; ++i) {
      Fixed adjusted_src = ScaleChannel<Fixed>(src[i] - bias, fixed_volume);
      Fixed value = AddSaturated<Fixed, min_value, max_value>(dst[i] - bias,
                                                              adjusted_src);
      dst[i] = static_cast<Format>(value + bias);
    }
  }
}

void MixStreams(void* dst,
                void* src,
                size_t buflen,
                int bytes_per_sample,
                float volume) {
  DCHECK(dst);
  DCHECK(src);
  DCHECK_GE(volume, 0.0f);
  DCHECK_LE(volume, 1.0f);
  switch (bytes_per_sample) {
    case 1:
      MixStreams<uint8, int32, kint8min, kint8max, 128>(
          static_cast<uint8*>(dst),
          static_cast<uint8*>(src),
          buflen,
          volume);
      break;
    case 2:
      DCHECK_EQ(0u, buflen % 2);
      MixStreams<int16, int32, kint16min, kint16max, 0>(
          static_cast<int16*>(dst),
          static_cast<int16*>(src),
          buflen / 2,
          volume);
      break;
    case 4:
      DCHECK_EQ(0u, buflen % 4);
      MixStreams<int32, int64, kint32min, kint32max, 0>(
          static_cast<int32*>(dst),
          static_cast<int32*>(src),
          buflen / 4,
          volume);
      break;
    default:
      NOTREACHED() << "Illegal bytes per sample";
      break;
  }
}

int GetAudioHardwareSampleRate() {
#if defined(OS_MACOSX)
  // Hardware sample-rate on the Mac can be configured, so we must query.
  return AUAudioOutputStream::HardwareSampleRate();
#elif defined(OS_WIN)
  if (!CoreAudioUtil::IsSupported()) {
    // Fall back to Windows Wave implementation on Windows XP or lower
    // and use 48kHz as default input sample rate.
    return 48000;
  }

  // TODO(crogers): tune this rate for best possible WebAudio performance.
  // WebRTC works well at 48kHz and a buffer size of 480 samples will be used
  // for this case. Note that exclusive mode is experimental.
  const CommandLine* cmd_line = CommandLine::ForCurrentProcess();
  if (cmd_line->HasSwitch(switches::kEnableExclusiveAudio)) {
    // This sample rate will be combined with a buffer size of 256 samples
    // (see GetAudioHardwareBufferSize()), which corresponds to an output
    // delay of ~5.33ms.
    return 48000;
  }

  // Hardware sample-rate on Windows can be configured, so we must query.
  // TODO(henrika): improve possibility to specify an audio endpoint.
  // Use the default device (same as for Wave) for now to be compatible
  // or possibly remove the ERole argument completely until it is in use.
  return WASAPIAudioOutputStream::HardwareSampleRate(eConsole);
#elif defined(OS_ANDROID)
  return 16000;
#else
  // Hardware for Linux is nearly always 48KHz.
  // TODO(crogers) : return correct value in rare non-48KHz cases.
  return 48000;
#endif
}

int GetAudioInputHardwareSampleRate(const std::string& device_id) {
  // TODO(henrika): add support for device selection on all platforms.
  // Only exists on Windows today.
#if defined(OS_MACOSX)
  return AUAudioInputStream::HardwareSampleRate();
#elif defined(OS_WIN)
  if (!CoreAudioUtil::IsSupported()) {
    return 48000;
  }
  return WASAPIAudioInputStream::HardwareSampleRate(device_id);
#elif defined(OS_ANDROID)
  return 16000;
#else
  return 48000;
#endif
}

size_t GetAudioHardwareBufferSize() {
  int user_buffer_size = GetUserBufferSize();
  if (user_buffer_size)
    return user_buffer_size;

  // The sizes here were determined by experimentation and are roughly
  // the lowest value (for low latency) that still allowed glitch-free
  // audio under high loads.
  //
  // For Mac OS X and Windows the chromium audio backend uses a low-latency
  // Core Audio API, so a low buffer size is possible. For Linux, further
  // tuning may be needed.
#if defined(OS_MACOSX)
  return 128;
#elif defined(OS_WIN)
  // Buffer size to use when a proper size can't be determined from the system.
  static const int kFallbackBufferSize = 4096;

  if (!CoreAudioUtil::IsSupported()) {
    // Fall back to Windows Wave implementation on Windows XP or lower
    // and assume 48kHz as default sample rate.
    return kFallbackBufferSize;
  }

  // TODO(crogers): tune this size to best possible WebAudio performance.
  // WebRTC always uses 10ms for Windows and does not call this method.
  // Note that exclusive mode is experimental.
  const CommandLine* cmd_line = CommandLine::ForCurrentProcess();
  if (cmd_line->HasSwitch(switches::kEnableExclusiveAudio)) {
    return 256;
  }

  // TODO(henrika): remove when the --enable-webaudio-input flag is no longer
  // utilized.
  if (cmd_line->HasSwitch(switches::kEnableWebAudioInput)) {
    AudioParameters params;
    HRESULT hr = CoreAudioUtil::GetPreferredAudioParameters(eRender, eConsole,
                                                            &params);
    return FAILED(hr) ? kFallbackBufferSize : params.frames_per_buffer();
  }

  // This call must be done on a COM thread configured as MTA.
  // TODO(tommi): http://code.google.com/p/chromium/issues/detail?id=103835.
  int mixing_sample_rate =
      WASAPIAudioOutputStream::HardwareSampleRate(eConsole);

  // Windows will return a sample rate of 0 when no audio output is available
  // (i.e. via RemoteDesktop with remote audio disabled), but we should never
  // return a buffer size of zero.
  if (mixing_sample_rate == 0)
    return kFallbackBufferSize;

  // Use different buffer sizes depening on the sample rate . The existing
  // WASAPI implementation is tuned to provide the most stable callback
  // sequence using these combinations.
  if (mixing_sample_rate % 11025 == 0)
    // Use buffer size of ~10.15873 ms.
    return (112 * (mixing_sample_rate / 11025));

  if (mixing_sample_rate % 8000 == 0)
    // Use buffer size of 10ms.
    return (80 * (mixing_sample_rate / 8000));

  // Ensure we always return a buffer size which is somewhat appropriate.
  LOG(ERROR) << "Unknown sample rate " << mixing_sample_rate << " detected.";
  if (mixing_sample_rate > limits::kMinSampleRate)
    return (mixing_sample_rate / 100);
  return kFallbackBufferSize;
#else
  return 2048;
#endif
}

ChannelLayout GetAudioInputHardwareChannelLayout(const std::string& device_id) {
  // TODO(henrika): add support for device selection on all platforms.
  // Only exists on Windows today.
#if defined(OS_MACOSX)
  return CHANNEL_LAYOUT_MONO;
#elif defined(OS_WIN)
  if (!CoreAudioUtil::IsSupported()) {
    // Fall back to Windows Wave implementation on Windows XP or lower and
    // use stereo by default.
    return CHANNEL_LAYOUT_STEREO;
  }
  return WASAPIAudioInputStream::HardwareChannelCount(device_id) == 1 ?
      CHANNEL_LAYOUT_MONO : CHANNEL_LAYOUT_STEREO;
#else
  return CHANNEL_LAYOUT_STEREO;
#endif
}

// Computes a buffer size based on the given |sample_rate|. Must be used in
// conjunction with AUDIO_PCM_LINEAR.
size_t GetHighLatencyOutputBufferSize(int sample_rate) {
  int user_buffer_size = GetUserBufferSize();
  if (user_buffer_size)
    return user_buffer_size;

  // TODO(vrk/crogers): The buffer sizes that this function computes is probably
  // overly conservative. However, reducing the buffer size to 2048-8192 bytes
  // caused crbug.com/108396. This computation should be revisited while making
  // sure crbug.com/108396 doesn't happen again.

  // The minimum number of samples in a hardware packet.
  // This value is selected so that we can handle down to 5khz sample rate.
  static const size_t kMinSamplesPerHardwarePacket = 1024;

  // The maximum number of samples in a hardware packet.
  // This value is selected so that we can handle up to 192khz sample rate.
  static const size_t kMaxSamplesPerHardwarePacket = 64 * 1024;

  // This constant governs the hardware audio buffer size, this value should be
  // chosen carefully.
  // This value is selected so that we have 8192 samples for 48khz streams.
  static const size_t kMillisecondsPerHardwarePacket = 170;

  // Select the number of samples that can provide at least
  // |kMillisecondsPerHardwarePacket| worth of audio data.
  size_t samples = kMinSamplesPerHardwarePacket;
  while (samples <= kMaxSamplesPerHardwarePacket &&
         samples * base::Time::kMillisecondsPerSecond <
         sample_rate * kMillisecondsPerHardwarePacket) {
    samples *= 2;
  }
  return samples;
}

#if defined(OS_WIN)

int NumberOfWaveOutBuffers() {
  // Use 4 buffers for Vista, 3 for everyone else:
  //  - The entire Windows audio stack was rewritten for Windows Vista and wave
  //    out performance was degraded compared to XP.
  //  - The regression was fixed in Windows 7 and most configurations will work
  //    with 2, but some (e.g., some Sound Blasters) still need 3.
  //  - Some XP configurations (even multi-processor ones) also need 3.
  return (base::win::GetVersion() == base::win::VERSION_VISTA) ? 4 : 3;
}

#endif

}  // namespace media
<|endoftext|>


<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
    (Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/

Copyright (c) 2000-2013 Torus Knot Software Ltd

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgreStableHeaders.h"
#include "OgreStringConverter.h"

namespace Ogre {

    String StringConverter::msDefaultStringLocale = OGRE_DEFAULT_LOCALE;

    //-----------------------------------------------------------------------
    String StringConverter::toString(Real val, unsigned short precision,
        unsigned short width, char fill, std::ios::fmtflags flags)
    {
        StringStream stream;
        stream.precision(precision);
        stream.width(width);
        stream.fill(fill);
        if (flags)
            stream.setf(flags);
        stream << val;

        return stream.str();
    }
#if OGRE_DOUBLE_PRECISION == 1
    //-----------------------------------------------------------------------
    String StringConverter::toString(float val, unsigned short precision,
                                     unsigned short width, char fill, std::ios::fmtflags flags)
    {
        StringStream stream;
        stream.precision(precision);
        stream.width(width);
        stream.fill(fill);
        if (flags)
            stream.setf(flags);
        stream << val;
        return stream.str();
    }
#else
    //-----------------------------------------------------------------------
    String StringConverter::toString(double val, unsigned short precision,
                                     unsigned short width, char fill, std::ios::fmtflags flags)
    {
        StringStream stream;
        stream.precision(precision);
        stream.width(width);
        stream.fill(fill);
        if (flags)
            stream.setf(flags);
        stream << val;
        return stream.str();
    }
#endif
    //-----------------------------------------------------------------------
    String StringConverter::toString(int val,
        unsigned short width, char fill, std::ios::fmtflags flags)
    {
        StringStream stream;
        stream.width(width);
        stream.fill(fill);
        if (flags)
            stream.setf(flags);
        stream << val;
        return stream.str();
    }
    //-----------------------------------------------------------------------
#if OGRE_PLATFORM != OGRE_PLATFORM_NACL &&  ( OGRE_ARCH_TYPE == OGRE_ARCHITECTURE_64 || OGRE_PLATFORM == OGRE_PLATFORM_APPLE || OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS )
    String StringConverter::toString(unsigned int val,
        unsigned short width, char fill, std::ios::fmtflags flags)
    {
        StringStream stream;
        stream.width(width);
        stream.fill(fill);
        if (flags)
            stream.setf(flags);
        stream << val;
        return stream.str();
    }
    //-----------------------------------------------------------------------
    String StringConverter::toString(size_t val,
        unsigned short width, char fill, std::ios::fmtflags flags)
    {
        StringStream stream;
        stream.width(width);
        stream.fill(fill);
        if (flags)
            stream.setf(flags);
        stream << val;
        return stream.str();
    }
#if OGRE_COMPILER == OGRE_COMPILER_MSVC
    //-----------------------------------------------------------------------
    String StringConverter::toString(unsigned long val,
        unsigned short width, char fill, std::ios::fmtflags flags)
    {
        StringStream stream;
        stream.width(width);
        stream.fill(fill);
        if (flags)
            stream.setf(flags);
        stream << val;
        return stream.str();
    }

#endif
    //-----------------------------------------------------------------------
#else
    String StringConverter::toString(size_t val,
        unsigned short width, char fill, std::ios::fmtflags flags)
    {
        StringStream stream;
        stream.width(width);
        stream.fill(fill);
        if (flags)
            stream.setf(flags);
        stream << val;
        return stream.str();
    }
    //-----------------------------------------------------------------------
    String StringConverter::toString(unsigned long val,
        unsigned short width, char fill, std::ios::fmtflags flags)
    {
        StringStream stream;
        stream.width(width);
        stream.fill(fill);
        if (flags)
            stream.setf(flags);
        stream << val;
        return stream.str();
    }
    //-----------------------------------------------------------------------
#endif
    String StringConverter::toString(long val,
        unsigned short width, char fill, std::ios::fmtflags flags)
    {
        StringStream stream;
        stream.width(width);
        stream.fill(fill);
        if (flags)
            stream.setf(flags);
        stream << val;
        return stream.str();
    }
    //-----------------------------------------------------------------------
    String StringConverter::toString(const Vector2& val)
    {
        StringStream stream;
        stream << val.x << " " << val.y;
        return stream.str();
    }
    //-----------------------------------------------------------------------
    String StringConverter::toString(const Vector3& val)
    {
        StringStream stream;
        stream << val.x << " " << val.y << " " << val.z;
        return stream.str();
    }
    //-----------------------------------------------------------------------
    String StringConverter::toString(const Vector4& val)
    {
        StringStream stream;
        stream << val.x << " " << val.y << " " << val.z << " " << val.w;
        return stream.str();
    }
    //-----------------------------------------------------------------------
    String StringConverter::toString(const Matrix3& val)
    {
        StringStream stream;
        stream << val[0][0] << " "
            << val[0][1] << " "
            << val[0][2] << " "
            << val[1][0] << " "
            << val[1][1] << " "
            << val[1][2] << " "
            << val[2][0] << " "
            << val[2][1] << " "
            << val[2][2];
        return stream.str();
    }
    //-----------------------------------------------------------------------
    String StringConverter::toString(bool val, bool yesNo)
    {
        if (val)
        {
            if (yesNo)
            {
                return "yes";
            }
            else
            {
                return "true";
            }
        }
        else
            if (yesNo)
            {
                return "no";
            }
            else
            {
                return "false";
            }
    }
    //-----------------------------------------------------------------------
    String StringConverter::toString(const Matrix4& val)
    {
        StringStream stream;
        stream << val[0][0] << " "
            << val[0][1] << " "
            << val[0][2] << " "
            << val[0][3] << " "
            << val[1][0] << " "
            << val[1][1] << " "
            << val[1][2] << " "
            << val[1][3] << " "
            << val[2][0] << " "
            << val[2][1] << " "
            << val[2][2] << " "
            << val[2][3] << " "
            << val[3][0] << " "
            << val[3][1] << " "
            << val[3][2] << " "
            << val[3][3];
        return stream.str();
    }
    //-----------------------------------------------------------------------
    String StringConverter::toString(const Quaternion& val)
    {
        StringStream stream;
        stream  << val.w << " " << val.x << " " << val.y << " " << val.z;
        return stream.str();
    }
    //-----------------------------------------------------------------------
    String StringConverter::toString(const ColourValue& val)
    {
        StringStream stream;
        stream << val.r << " " << val.g << " " << val.b << " " << val.a;
        return stream.str();
    }
    //-----------------------------------------------------------------------
    String StringConverter::toString(const StringVector& val)
    {
        StringStream stream;
        StringVector::const_iterator i, iend, ibegin;
        ibegin = val.begin();
        iend = val.end();
        for (i = ibegin; i != iend; ++i)
        {
            if (i != ibegin)
                stream << " ";

            stream << *i;
        }
        return stream.str();
    }
    //-----------------------------------------------------------------------
    Real StringConverter::parseReal(const String& val, Real defaultValue, const std::locale &loc)
    {
        // Use iStringStream for direct correspondence with toString
        StringStream str(val);
        str.imbue(loc);
        Real ret = defaultValue;
        if( !(str >> ret) )
            return defaultValue;

        return ret;
    }
    //-----------------------------------------------------------------------
    int StringConverter::parseInt(const String& val, int defaultValue, const std::locale &loc)
    {
        // Use iStringStream for direct correspondence with toString
        StringStream str(val);
        str.imbue(loc);
        int ret = defaultValue;
        if( !(str >> ret) )
            return defaultValue;

        return ret;
    }
    //-----------------------------------------------------------------------
    unsigned int StringConverter::parseUnsignedInt(const String& val, unsigned int defaultValue, const std::locale &loc)
    {
        // Use iStringStream for direct correspondence with toString
        StringStream str(val);
        str.imbue(loc);
        unsigned int ret = defaultValue;
        if( !(str >> ret) )
            return defaultValue;

        return ret;
    }
    //-----------------------------------------------------------------------
    long StringConverter::parseLong(const String& val, long defaultValue, const std::locale &loc)
    {
        // Use iStringStream for direct correspondence with toString
        StringStream str(val);
        str.imbue(loc);
        long ret = defaultValue;
        if( !(str >> ret) )
            return defaultValue;

        return ret;
    }
    //-----------------------------------------------------------------------
    unsigned long StringConverter::parseUnsignedLong(const String& val, unsigned long defaultValue, const std::locale &loc)
    {
        // Use iStringStream for direct correspondence with toString
        StringStream str(val);
        str.imbue(loc);
        unsigned long ret = defaultValue;
        if( !(str >> ret) )
            return defaultValue;

        return ret;
    }
    //-----------------------------------------------------------------------
    size_t StringConverter::parseSizeT(const String& val, size_t defaultValue, const std::locale &loc)
    {
        // Use iStringStream for direct correspondence with toString
        StringStream str(val);
        str.imbue(loc);
        size_t ret = defaultValue;
        if( !(str >> ret) )
            return defaultValue;

        return ret;
    }
    //-----------------------------------------------------------------------
    bool StringConverter::parseBool(const String& val, bool defaultValue, const std::locale &loc)
    {
        if ((StringUtil::startsWith(val, "true") || StringUtil::startsWith(val, "yes")
            || StringUtil::startsWith(val, "1")))
            return true;
        else if ((StringUtil::startsWith(val, "false") || StringUtil::startsWith(val, "no")
            || StringUtil::startsWith(val, "0")))
            return false;
        else
            return defaultValue;
    }
    //-----------------------------------------------------------------------
    Vector2 StringConverter::parseVector2(const String& val, const Vector2& defaultValue, const std::locale &loc)
    {
        // Split on space
        vector<String>::type vec = StringUtil::split(val);

        if (vec.size() != 2)
        {
            return defaultValue;
        }
        else
        {
            return Vector2(parseReal(vec[0], defaultValue[0], loc), parseReal(vec[1], defaultValue[1], loc));
        }
    }
    //-----------------------------------------------------------------------
    Vector3 StringConverter::parseVector3(const String& val, const Vector3& defaultValue, const std::locale &loc)
    {
        // Split on space
        vector<String>::type vec = StringUtil::split(val);

        if (vec.size() != 3)
        {
            return defaultValue;
        }
        else
        {
            return Vector3(parseReal(vec[0], defaultValue[0], loc),
                           parseReal(vec[1], defaultValue[1], loc),
                           parseReal(vec[2], defaultValue[2], loc));
        }
    }
    //-----------------------------------------------------------------------
    Vector4 StringConverter::parseVector4(const String& val, const Vector4& defaultValue, const std::locale &loc)
    {
        // Split on space
        vector<String>::type vec = StringUtil::split(val);

        if (vec.size() != 4)
        {
            return defaultValue;
        }
        else
        {
            return Vector4(parseReal(vec[0], defaultValue[0], loc),
                           parseReal(vec[1], defaultValue[1], loc),
                           parseReal(vec[2], defaultValue[2], loc),
                           parseReal(vec[3], defaultValue[3], loc));
        }
    }
    //-----------------------------------------------------------------------
    Matrix3 StringConverter::parseMatrix3(const String& val, const Matrix3& defaultValue, const std::locale &loc)
    {
        // Split on space
        vector<String>::type vec = StringUtil::split(val);

        if (vec.size() != 9)
        {
            return defaultValue;
        }
        else
        {
            return Matrix3(parseReal(vec[0], defaultValue[0][0], loc),
                           parseReal(vec[1], defaultValue[0][1], loc),
                           parseReal(vec[2], defaultValue[0][2], loc),

                           parseReal(vec[3], defaultValue[1][0], loc),
                           parseReal(vec[4], defaultValue[1][1], loc),
                           parseReal(vec[5], defaultValue[1][2], loc),

                           parseReal(vec[6], defaultValue[2][0], loc),
                           parseReal(vec[7], defaultValue[2][1], loc),
                           parseReal(vec[8], defaultValue[2][2], loc));
        }
    }
    //-----------------------------------------------------------------------
    Matrix4 StringConverter::parseMatrix4(const String& val, const Matrix4& defaultValue, const std::locale &loc)
    {
        // Split on space
        vector<String>::type vec = StringUtil::split(val);

        if (vec.size() != 16)
        {
            return defaultValue;
        }
        else
        {
            return Matrix4(parseReal(vec[0], defaultValue[0][0], loc),
                           parseReal(vec[1], defaultValue[0][1], loc),
                           parseReal(vec[2], defaultValue[0][2], loc),
                           parseReal(vec[3], defaultValue[0][3], loc),

                           parseReal(vec[4], defaultValue[1][0], loc),
                           parseReal(vec[5], defaultValue[1][1], loc),
                           parseReal(vec[6], defaultValue[1][2], loc),
                           parseReal(vec[7], defaultValue[1][3], loc),

                           parseReal(vec[8], defaultValue[2][0], loc),
                           parseReal(vec[9], defaultValue[2][1], loc),
                           parseReal(vec[10], defaultValue[2][2], loc),
                           parseReal(vec[11], defaultValue[2][3], loc),

                           parseReal(vec[12], defaultValue[3][0], loc),
                           parseReal(vec[13], defaultValue[3][1], loc),
                           parseReal(vec[14], defaultValue[3][2], loc),
                           parseReal(vec[14], defaultValue[3][3], loc));
        }
    }
    //-----------------------------------------------------------------------
    Quaternion StringConverter::parseQuaternion(const String& val, const Quaternion& defaultValue, const std::locale &loc)
    {
        // Split on space
        vector<String>::type vec = StringUtil::split(val);

        if (vec.size() != 4)
        {
            return defaultValue;
        }
        else
        {
            return Quaternion(parseReal(vec[0], defaultValue[0], loc),
                              parseReal(vec[1], defaultValue[1], loc),
                              parseReal(vec[2], defaultValue[2], loc),
                              parseReal(vec[3], defaultValue[3], loc));
        }
    }
    //-----------------------------------------------------------------------
    ColourValue StringConverter::parseColourValue(const String& val, const ColourValue& defaultValue, const std::locale &loc)
    {
        // Split on space
        vector<String>::type vec = StringUtil::split(val);

        if (vec.size() == 4)
        {
            return ColourValue(parseReal(vec[0], defaultValue[0], loc),
                               parseReal(vec[1], defaultValue[1], loc),
                               parseReal(vec[2], defaultValue[2], loc),
                               parseReal(vec[3], defaultValue[3], loc));
        }
        else if (vec.size() == 3)
        {
            return ColourValue(parseReal(vec[0], defaultValue[0], loc),
                               parseReal(vec[1], defaultValue[1], loc),
                               parseReal(vec[2], defaultValue[2], loc),
                               1.0f);
        }
        else
        {
            return defaultValue;
        }
    }
    //-----------------------------------------------------------------------
    StringVector StringConverter::parseStringVector(const String& val, const std::locale &loc)
    {
        return StringUtil::split(val);
    }
    //-----------------------------------------------------------------------
    bool StringConverter::isNumber(const String& val, const std::locale &loc)
    {
        StringStream str(val);
        str.imbue(loc);
        float tst;
        str >> tst;
        return !str.fail() && str.eof();
    }
}

<commit_msg>Fix a copy/paste typo in StringConverter::parseMatrix4<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
    (Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/

Copyright (c) 2000-2013 Torus Knot Software Ltd

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgreStableHeaders.h"
#include "OgreStringConverter.h"

namespace Ogre {

    String StringConverter::msDefaultStringLocale = OGRE_DEFAULT_LOCALE;

    //-----------------------------------------------------------------------
    String StringConverter::toString(Real val, unsigned short precision,
        unsigned short width, char fill, std::ios::fmtflags flags)
    {
        StringStream stream;
        stream.precision(precision);
        stream.width(width);
        stream.fill(fill);
        if (flags)
            stream.setf(flags);
        stream << val;

        return stream.str();
    }
#if OGRE_DOUBLE_PRECISION == 1
    //-----------------------------------------------------------------------
    String StringConverter::toString(float val, unsigned short precision,
                                     unsigned short width, char fill, std::ios::fmtflags flags)
    {
        StringStream stream;
        stream.precision(precision);
        stream.width(width);
        stream.fill(fill);
        if (flags)
            stream.setf(flags);
        stream << val;
        return stream.str();
    }
#else
    //-----------------------------------------------------------------------
    String StringConverter::toString(double val, unsigned short precision,
                                     unsigned short width, char fill, std::ios::fmtflags flags)
    {
        StringStream stream;
        stream.precision(precision);
        stream.width(width);
        stream.fill(fill);
        if (flags)
            stream.setf(flags);
        stream << val;
        return stream.str();
    }
#endif
    //-----------------------------------------------------------------------
    String StringConverter::toString(int val,
        unsigned short width, char fill, std::ios::fmtflags flags)
    {
        StringStream stream;
        stream.width(width);
        stream.fill(fill);
        if (flags)
            stream.setf(flags);
        stream << val;
        return stream.str();
    }
    //-----------------------------------------------------------------------
#if OGRE_PLATFORM != OGRE_PLATFORM_NACL &&  ( OGRE_ARCH_TYPE == OGRE_ARCHITECTURE_64 || OGRE_PLATFORM == OGRE_PLATFORM_APPLE || OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS )
    String StringConverter::toString(unsigned int val,
        unsigned short width, char fill, std::ios::fmtflags flags)
    {
        StringStream stream;
        stream.width(width);
        stream.fill(fill);
        if (flags)
            stream.setf(flags);
        stream << val;
        return stream.str();
    }
    //-----------------------------------------------------------------------
    String StringConverter::toString(size_t val,
        unsigned short width, char fill, std::ios::fmtflags flags)
    {
        StringStream stream;
        stream.width(width);
        stream.fill(fill);
        if (flags)
            stream.setf(flags);
        stream << val;
        return stream.str();
    }
#if OGRE_COMPILER == OGRE_COMPILER_MSVC
    //-----------------------------------------------------------------------
    String StringConverter::toString(unsigned long val,
        unsigned short width, char fill, std::ios::fmtflags flags)
    {
        StringStream stream;
        stream.width(width);
        stream.fill(fill);
        if (flags)
            stream.setf(flags);
        stream << val;
        return stream.str();
    }

#endif
    //-----------------------------------------------------------------------
#else
    String StringConverter::toString(size_t val,
        unsigned short width, char fill, std::ios::fmtflags flags)
    {
        StringStream stream;
        stream.width(width);
        stream.fill(fill);
        if (flags)
            stream.setf(flags);
        stream << val;
        return stream.str();
    }
    //-----------------------------------------------------------------------
    String StringConverter::toString(unsigned long val,
        unsigned short width, char fill, std::ios::fmtflags flags)
    {
        StringStream stream;
        stream.width(width);
        stream.fill(fill);
        if (flags)
            stream.setf(flags);
        stream << val;
        return stream.str();
    }
    //-----------------------------------------------------------------------
#endif
    String StringConverter::toString(long val,
        unsigned short width, char fill, std::ios::fmtflags flags)
    {
        StringStream stream;
        stream.width(width);
        stream.fill(fill);
        if (flags)
            stream.setf(flags);
        stream << val;
        return stream.str();
    }
    //-----------------------------------------------------------------------
    String StringConverter::toString(const Vector2& val)
    {
        StringStream stream;
        stream << val.x << " " << val.y;
        return stream.str();
    }
    //-----------------------------------------------------------------------
    String StringConverter::toString(const Vector3& val)
    {
        StringStream stream;
        stream << val.x << " " << val.y << " " << val.z;
        return stream.str();
    }
    //-----------------------------------------------------------------------
    String StringConverter::toString(const Vector4& val)
    {
        StringStream stream;
        stream << val.x << " " << val.y << " " << val.z << " " << val.w;
        return stream.str();
    }
    //-----------------------------------------------------------------------
    String StringConverter::toString(const Matrix3& val)
    {
        StringStream stream;
        stream << val[0][0] << " "
            << val[0][1] << " "
            << val[0][2] << " "
            << val[1][0] << " "
            << val[1][1] << " "
            << val[1][2] << " "
            << val[2][0] << " "
            << val[2][1] << " "
            << val[2][2];
        return stream.str();
    }
    //-----------------------------------------------------------------------
    String StringConverter::toString(bool val, bool yesNo)
    {
        if (val)
        {
            if (yesNo)
            {
                return "yes";
            }
            else
            {
                return "true";
            }
        }
        else
            if (yesNo)
            {
                return "no";
            }
            else
            {
                return "false";
            }
    }
    //-----------------------------------------------------------------------
    String StringConverter::toString(const Matrix4& val)
    {
        StringStream stream;
        stream << val[0][0] << " "
            << val[0][1] << " "
            << val[0][2] << " "
            << val[0][3] << " "
            << val[1][0] << " "
            << val[1][1] << " "
            << val[1][2] << " "
            << val[1][3] << " "
            << val[2][0] << " "
            << val[2][1] << " "
            << val[2][2] << " "
            << val[2][3] << " "
            << val[3][0] << " "
            << val[3][1] << " "
            << val[3][2] << " "
            << val[3][3];
        return stream.str();
    }
    //-----------------------------------------------------------------------
    String StringConverter::toString(const Quaternion& val)
    {
        StringStream stream;
        stream  << val.w << " " << val.x << " " << val.y << " " << val.z;
        return stream.str();
    }
    //-----------------------------------------------------------------------
    String StringConverter::toString(const ColourValue& val)
    {
        StringStream stream;
        stream << val.r << " " << val.g << " " << val.b << " " << val.a;
        return stream.str();
    }
    //-----------------------------------------------------------------------
    String StringConverter::toString(const StringVector& val)
    {
        StringStream stream;
        StringVector::const_iterator i, iend, ibegin;
        ibegin = val.begin();
        iend = val.end();
        for (i = ibegin; i != iend; ++i)
        {
            if (i != ibegin)
                stream << " ";

            stream << *i;
        }
        return stream.str();
    }
    //-----------------------------------------------------------------------
    Real StringConverter::parseReal(const String& val, Real defaultValue, const std::locale &loc)
    {
        // Use iStringStream for direct correspondence with toString
        StringStream str(val);
        str.imbue(loc);
        Real ret = defaultValue;
        if( !(str >> ret) )
            return defaultValue;

        return ret;
    }
    //-----------------------------------------------------------------------
    int StringConverter::parseInt(const String& val, int defaultValue, const std::locale &loc)
    {
        // Use iStringStream for direct correspondence with toString
        StringStream str(val);
        str.imbue(loc);
        int ret = defaultValue;
        if( !(str >> ret) )
            return defaultValue;

        return ret;
    }
    //-----------------------------------------------------------------------
    unsigned int StringConverter::parseUnsignedInt(const String& val, unsigned int defaultValue, const std::locale &loc)
    {
        // Use iStringStream for direct correspondence with toString
        StringStream str(val);
        str.imbue(loc);
        unsigned int ret = defaultValue;
        if( !(str >> ret) )
            return defaultValue;

        return ret;
    }
    //-----------------------------------------------------------------------
    long StringConverter::parseLong(const String& val, long defaultValue, const std::locale &loc)
    {
        // Use iStringStream for direct correspondence with toString
        StringStream str(val);
        str.imbue(loc);
        long ret = defaultValue;
        if( !(str >> ret) )
            return defaultValue;

        return ret;
    }
    //-----------------------------------------------------------------------
    unsigned long StringConverter::parseUnsignedLong(const String& val, unsigned long defaultValue, const std::locale &loc)
    {
        // Use iStringStream for direct correspondence with toString
        StringStream str(val);
        str.imbue(loc);
        unsigned long ret = defaultValue;
        if( !(str >> ret) )
            return defaultValue;

        return ret;
    }
    //-----------------------------------------------------------------------
    size_t StringConverter::parseSizeT(const String& val, size_t defaultValue, const std::locale &loc)
    {
        // Use iStringStream for direct correspondence with toString
        StringStream str(val);
        str.imbue(loc);
        size_t ret = defaultValue;
        if( !(str >> ret) )
            return defaultValue;

        return ret;
    }
    //-----------------------------------------------------------------------
    bool StringConverter::parseBool(const String& val, bool defaultValue, const std::locale &loc)
    {
        if ((StringUtil::startsWith(val, "true") || StringUtil::startsWith(val, "yes")
            || StringUtil::startsWith(val, "1")))
            return true;
        else if ((StringUtil::startsWith(val, "false") || StringUtil::startsWith(val, "no")
            || StringUtil::startsWith(val, "0")))
            return false;
        else
            return defaultValue;
    }
    //-----------------------------------------------------------------------
    Vector2 StringConverter::parseVector2(const String& val, const Vector2& defaultValue, const std::locale &loc)
    {
        // Split on space
        vector<String>::type vec = StringUtil::split(val);

        if (vec.size() != 2)
        {
            return defaultValue;
        }
        else
        {
            return Vector2(parseReal(vec[0], defaultValue[0], loc), parseReal(vec[1], defaultValue[1], loc));
        }
    }
    //-----------------------------------------------------------------------
    Vector3 StringConverter::parseVector3(const String& val, const Vector3& defaultValue, const std::locale &loc)
    {
        // Split on space
        vector<String>::type vec = StringUtil::split(val);

        if (vec.size() != 3)
        {
            return defaultValue;
        }
        else
        {
            return Vector3(parseReal(vec[0], defaultValue[0], loc),
                           parseReal(vec[1], defaultValue[1], loc),
                           parseReal(vec[2], defaultValue[2], loc));
        }
    }
    //-----------------------------------------------------------------------
    Vector4 StringConverter::parseVector4(const String& val, const Vector4& defaultValue, const std::locale &loc)
    {
        // Split on space
        vector<String>::type vec = StringUtil::split(val);

        if (vec.size() != 4)
        {
            return defaultValue;
        }
        else
        {
            return Vector4(parseReal(vec[0], defaultValue[0], loc),
                           parseReal(vec[1], defaultValue[1], loc),
                           parseReal(vec[2], defaultValue[2], loc),
                           parseReal(vec[3], defaultValue[3], loc));
        }
    }
    //-----------------------------------------------------------------------
    Matrix3 StringConverter::parseMatrix3(const String& val, const Matrix3& defaultValue, const std::locale &loc)
    {
        // Split on space
        vector<String>::type vec = StringUtil::split(val);

        if (vec.size() != 9)
        {
            return defaultValue;
        }
        else
        {
            return Matrix3(parseReal(vec[0], defaultValue[0][0], loc),
                           parseReal(vec[1], defaultValue[0][1], loc),
                           parseReal(vec[2], defaultValue[0][2], loc),

                           parseReal(vec[3], defaultValue[1][0], loc),
                           parseReal(vec[4], defaultValue[1][1], loc),
                           parseReal(vec[5], defaultValue[1][2], loc),

                           parseReal(vec[6], defaultValue[2][0], loc),
                           parseReal(vec[7], defaultValue[2][1], loc),
                           parseReal(vec[8], defaultValue[2][2], loc));
        }
    }
    //-----------------------------------------------------------------------
    Matrix4 StringConverter::parseMatrix4(const String& val, const Matrix4& defaultValue, const std::locale &loc)
    {
        // Split on space
        vector<String>::type vec = StringUtil::split(val);

        if (vec.size() != 16)
        {
            return defaultValue;
        }
        else
        {
            return Matrix4(parseReal(vec[0], defaultValue[0][0], loc),
                           parseReal(vec[1], defaultValue[0][1], loc),
                           parseReal(vec[2], defaultValue[0][2], loc),
                           parseReal(vec[3], defaultValue[0][3], loc),

                           parseReal(vec[4], defaultValue[1][0], loc),
                           parseReal(vec[5], defaultValue[1][1], loc),
                           parseReal(vec[6], defaultValue[1][2], loc),
                           parseReal(vec[7], defaultValue[1][3], loc),

                           parseReal(vec[8], defaultValue[2][0], loc),
                           parseReal(vec[9], defaultValue[2][1], loc),
                           parseReal(vec[10], defaultValue[2][2], loc),
                           parseReal(vec[11], defaultValue[2][3], loc),

                           parseReal(vec[12], defaultValue[3][0], loc),
                           parseReal(vec[13], defaultValue[3][1], loc),
                           parseReal(vec[14], defaultValue[3][2], loc),
                           parseReal(vec[15], defaultValue[3][3], loc));
        }
    }
    //-----------------------------------------------------------------------
    Quaternion StringConverter::parseQuaternion(const String& val, const Quaternion& defaultValue, const std::locale &loc)
    {
        // Split on space
        vector<String>::type vec = StringUtil::split(val);

        if (vec.size() != 4)
        {
            return defaultValue;
        }
        else
        {
            return Quaternion(parseReal(vec[0], defaultValue[0], loc),
                              parseReal(vec[1], defaultValue[1], loc),
                              parseReal(vec[2], defaultValue[2], loc),
                              parseReal(vec[3], defaultValue[3], loc));
        }
    }
    //-----------------------------------------------------------------------
    ColourValue StringConverter::parseColourValue(const String& val, const ColourValue& defaultValue, const std::locale &loc)
    {
        // Split on space
        vector<String>::type vec = StringUtil::split(val);

        if (vec.size() == 4)
        {
            return ColourValue(parseReal(vec[0], defaultValue[0], loc),
                               parseReal(vec[1], defaultValue[1], loc),
                               parseReal(vec[2], defaultValue[2], loc),
                               parseReal(vec[3], defaultValue[3], loc));
        }
        else if (vec.size() == 3)
        {
            return ColourValue(parseReal(vec[0], defaultValue[0], loc),
                               parseReal(vec[1], defaultValue[1], loc),
                               parseReal(vec[2], defaultValue[2], loc),
                               1.0f);
        }
        else
        {
            return defaultValue;
        }
    }
    //-----------------------------------------------------------------------
    StringVector StringConverter::parseStringVector(const String& val, const std::locale &loc)
    {
        return StringUtil::split(val);
    }
    //-----------------------------------------------------------------------
    bool StringConverter::isNumber(const String& val, const std::locale &loc)
    {
        StringStream str(val);
        str.imbue(loc);
        float tst;
        str >> tst;
        return !str.fail() && str.eof();
    }
}

<|endoftext|>