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"
8 #include "base/stl_util.h"
12 AudioChunk::AudioChunk(int bytes_per_sample
)
13 : bytes_per_sample_(bytes_per_sample
) {
16 AudioChunk::AudioChunk(const uint8
* data
, size_t length
, int bytes_per_sample
)
17 : data_string_(reinterpret_cast<const char*>(data
), length
),
18 bytes_per_sample_(bytes_per_sample
) {
19 DCHECK_EQ(length
% bytes_per_sample
, 0U);
22 bool AudioChunk::IsEmpty() const {
23 return data_string_
.empty();
26 size_t AudioChunk::NumSamples() const {
27 return data_string_
.size() / bytes_per_sample_
;
30 const std::string
& AudioChunk::AsString() const {
34 int16
AudioChunk::GetSample16(size_t index
) const {
35 DCHECK(index
< (data_string_
.size() / sizeof(int16
)));
36 return SamplesData16()[index
];
39 const int16
* AudioChunk::SamplesData16() const {
40 return reinterpret_cast<const int16
*>(data_string_
.data());
44 AudioBuffer::AudioBuffer(int bytes_per_sample
)
45 : bytes_per_sample_(bytes_per_sample
) {
46 DCHECK(bytes_per_sample
== 1 ||
47 bytes_per_sample
== 2 ||
48 bytes_per_sample
== 4);
51 AudioBuffer::~AudioBuffer() {
55 void AudioBuffer::Enqueue(const uint8
* data
, size_t length
) {
56 chunks_
.push_back(new AudioChunk(data
, length
, bytes_per_sample_
));
59 scoped_refptr
<AudioChunk
> AudioBuffer::DequeueSingleChunk() {
60 DCHECK(!chunks_
.empty());
61 scoped_refptr
<AudioChunk
> chunk(chunks_
.front());
66 scoped_refptr
<AudioChunk
> AudioBuffer::DequeueAll() {
67 scoped_refptr
<AudioChunk
> chunk(new AudioChunk(bytes_per_sample_
));
68 size_t resulting_length
= 0;
69 ChunksContainer::const_iterator it
;
70 // In order to improve performance, calulate in advance the total length
71 // and then copy the chunks.
72 for (it
= chunks_
.begin(); it
!= chunks_
.end(); ++it
) {
73 resulting_length
+= (*it
)->data_string_
.length();
75 chunk
->data_string_
.reserve(resulting_length
);
76 for (it
= chunks_
.begin(); it
!= chunks_
.end(); ++it
) {
77 chunk
->data_string_
.append((*it
)->data_string_
);
83 void AudioBuffer::Clear() {
87 bool AudioBuffer::IsEmpty() const {
88 return chunks_
.empty();
91 } // namespace content