Make USB permissions work in the new permission message system
[chromium-blink-merge.git] / content / browser / speech / audio_buffer.cc
blob823fff5291f4774a55370088a56d8e690df140a5
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "content/browser/speech/audio_buffer.h"
7 #include "base/logging.h"
9 namespace content {
11 AudioChunk::AudioChunk(int bytes_per_sample)
12 : bytes_per_sample_(bytes_per_sample) {
15 AudioChunk::AudioChunk(size_t length, int bytes_per_sample)
16 : data_string_(length, '\0'), bytes_per_sample_(bytes_per_sample) {
17 DCHECK_EQ(length % bytes_per_sample, 0U);
20 AudioChunk::AudioChunk(const uint8* data, size_t length, int bytes_per_sample)
21 : data_string_(reinterpret_cast<const char*>(data), length),
22 bytes_per_sample_(bytes_per_sample) {
23 DCHECK_EQ(length % bytes_per_sample, 0U);
26 bool AudioChunk::IsEmpty() const {
27 return data_string_.empty();
30 size_t AudioChunk::NumSamples() const {
31 return data_string_.size() / bytes_per_sample_;
34 const std::string& AudioChunk::AsString() const {
35 return data_string_;
38 int16 AudioChunk::GetSample16(size_t index) const {
39 DCHECK(index < (data_string_.size() / sizeof(int16)));
40 return SamplesData16()[index];
43 const int16* AudioChunk::SamplesData16() const {
44 return reinterpret_cast<const int16*>(data_string_.data());
47 AudioBuffer::AudioBuffer(int bytes_per_sample)
48 : bytes_per_sample_(bytes_per_sample) {
49 DCHECK(bytes_per_sample == 1 ||
50 bytes_per_sample == 2 ||
51 bytes_per_sample == 4);
54 AudioBuffer::~AudioBuffer() {
55 Clear();
58 void AudioBuffer::Enqueue(const uint8* data, size_t length) {
59 chunks_.push_back(new AudioChunk(data, length, bytes_per_sample_));
62 scoped_refptr<AudioChunk> AudioBuffer::DequeueSingleChunk() {
63 DCHECK(!chunks_.empty());
64 scoped_refptr<AudioChunk> chunk(chunks_.front());
65 chunks_.pop_front();
66 return chunk;
69 scoped_refptr<AudioChunk> AudioBuffer::DequeueAll() {
70 size_t resulting_length = 0;
71 ChunksContainer::const_iterator it;
72 // In order to improve performance, calulate in advance the total length
73 // and then copy the chunks.
74 for (it = chunks_.begin(); it != chunks_.end(); ++it) {
75 resulting_length += (*it)->AsString().length();
77 scoped_refptr<AudioChunk> chunk(
78 new AudioChunk(resulting_length, bytes_per_sample_));
79 uint8* dest = chunk->writable_data();
80 for (it = chunks_.begin(); it != chunks_.end(); ++it) {
81 memcpy(dest, (*it)->AsString().data(), (*it)->AsString().length());
82 dest += (*it)->AsString().length();
84 Clear();
85 return chunk;
88 void AudioBuffer::Clear() {
89 chunks_.clear();
92 bool AudioBuffer::IsEmpty() const {
93 return chunks_.empty();
96 } // namespace content