Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(900)

Side by Side Diff: components/copresence/mediums/audio/audio_recorder.cc

Issue 419073002: Add the copresence DirectiveHandler. (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: Created 6 years, 4 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
(Empty)
1 // Copyright 2014 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.
4
5 #include "components/copresence/mediums/audio/audio_recorder.h"
6
7 #include <algorithm>
8 #include <vector>
9
10 #include "base/bind.h"
11 #include "base/bind_helpers.h"
12 #include "base/logging.h"
13 #include "base/run_loop.h"
14 #include "base/synchronization/waitable_event.h"
15 #include "components/copresence/public/copresence_constants.h"
16 #include "content/public/browser/browser_thread.h"
17 #include "media/audio/audio_manager.h"
18 #include "media/audio/audio_manager_base.h"
19 #include "media/base/audio_bus.h"
20
21 namespace {
22
23 const float kProcessIntervalMs = 500.0f; // milliseconds.
24
25 void AudioBusToString(scoped_ptr<media::AudioBus> source, std::string* buffer) {
26 buffer->resize(source->frames() * source->channels() * sizeof(float));
27 float* buffer_view = reinterpret_cast<float*>(string_as_array(buffer));
28
29 const int channels = source->channels();
30 for (int ch = 0; ch < channels; ++ch) {
31 for (int si = 0, di = ch; si < source->frames(); ++si, di += channels)
32 buffer_view[di] = source->channel(ch)[si];
33 }
34 }
35
36 // Called every kProcessIntervalMs to process the recorded audio. This
37 // converts our samples to the required sample rate, interleaves the samples
38 // and sends them to the whispernet decoder to process.
39 void ProcessSamples(
40 scoped_ptr<media::AudioBus> bus,
41 const copresence::AudioRecorder::DecodeSamplesCallback& callback) {
Daniel Erat 2014/07/31 22:31:16 nit: nest the anon namespace under the copresence
rkc 2014/08/01 21:08:57 Done.
42 std::string samples;
43 AudioBusToString(bus.Pass(), &samples);
44 content::BrowserThread::PostTask(
45 content::BrowserThread::UI, FROM_HERE, base::Bind(callback, samples));
46 }
47
48 } // namespace
49
50 namespace copresence {
51
52 // Public methods.
53
54 AudioRecorder::AudioRecorder(const DecodeSamplesCallback& decode_callback)
55 : stream_(NULL),
56 is_recording_(false),
57 decode_callback_(decode_callback),
58 total_buffer_frames_(0),
59 buffer_frame_index_(0),
60 input_stream_for_testing_(NULL) {
61 }
62
63 void AudioRecorder::Initialize() {
64 media::AudioManager::Get()->GetTaskRunner()->PostTask(
65 FROM_HERE,
66 base::Bind(&AudioRecorder::InitializeOnAudioThread,
67 base::Unretained(this)));
68 }
69
70 AudioRecorder::~AudioRecorder() {
71 }
72
73 void AudioRecorder::Record() {
74 media::AudioManager::Get()->GetTaskRunner()->PostTask(
75 FROM_HERE,
76 base::Bind(&AudioRecorder::RecordOnAudioThread, base::Unretained(this)));
77 }
78
79 void AudioRecorder::Stop() {
80 media::AudioManager::Get()->GetTaskRunner()->PostTask(
81 FROM_HERE,
82 base::Bind(&AudioRecorder::StopOnAudioThread, base::Unretained(this)));
83 }
84
85 void AudioRecorder::Finalize() {
86 media::AudioManager::Get()->GetTaskRunner()->PostTask(
87 FROM_HERE,
88 base::Bind(&AudioRecorder::FinalizeOnAudioThread,
89 base::Unretained(this)));
90 }
91
92 // Private methods.
93
94 void AudioRecorder::InitializeOnAudioThread() {
95 DCHECK(media::AudioManager::Get()->GetTaskRunner()->BelongsToCurrentThread());
96
97 media::AudioParameters params =
98 params_for_testing_
99 ? *params_for_testing_
100 : media::AudioManager::Get()->GetInputStreamParameters(
101 media::AudioManagerBase::kDefaultDeviceId);
102
103 const media::AudioParameters dest_params(params.format(),
104 kDefaultChannelLayout,
105 kDefaultChannels,
106 params.input_channels(),
107 kDefaultSampleRate,
108 kDefaultBitsPerSample,
109 params.frames_per_buffer(),
110 media::AudioParameters::NO_EFFECTS);
111
112 converter_.reset(new media::AudioConverter(
113 params, dest_params, params.sample_rate() == dest_params.sample_rate()));
114 converter_->AddInput(this);
115
116 total_buffer_frames_ = kProcessIntervalMs * dest_params.sample_rate() / 1000;
117 buffer_ =
118 media::AudioBus::Create(dest_params.channels(), total_buffer_frames_);
119 buffer_frame_index_ = 0;
120
121 stream_ = input_stream_for_testing_ ? input_stream_for_testing_ : stream_ =
Daniel Erat 2014/07/31 22:31:16 uh, what's up with the "stream_ =" at the end of t
rkc 2014/08/01 21:08:57 Done.
122 media::AudioManager::Get()->MakeAudioInputStream(
123 params, media::AudioManagerBase::kDefaultDeviceId);
124
125 if (!stream_ || !stream_->Open()) {
126 LOG(ERROR) << "Failed to open an input stream.";
127 if (stream_) {
128 stream_->Close();
Daniel Erat 2014/07/31 22:31:16 do you actually need to call Close() here after Op
rkc 2014/08/01 21:08:57 If the stream open fails, we should close the stre
129 stream_ = NULL;
130 }
131 return;
132 }
133 stream_->SetVolume(stream_->GetMaxVolume());
134 }
135
136 void AudioRecorder::RecordOnAudioThread() {
137 DCHECK(media::AudioManager::Get()->GetTaskRunner()->BelongsToCurrentThread());
138 if (!stream_ || is_recording_)
139 return;
140
141 DVLOG(2) << "Recording Audio.";
142 converter_->Reset();
143 stream_->Start(this);
144 is_recording_ = true;
145 }
146
147 void AudioRecorder::StopOnAudioThread() {
148 DCHECK(media::AudioManager::Get()->GetTaskRunner()->BelongsToCurrentThread());
149 if (!stream_)
150 return;
151
152 stream_->Stop();
153 is_recording_ = false;
154 }
155
156 void AudioRecorder::StopAndCloseOnAudioThread() {
157 DCHECK(media::AudioManager::Get()->GetTaskRunner()->BelongsToCurrentThread());
158 if (!stream_)
159 return;
160
161 if (is_recording_)
Daniel Erat 2014/07/31 22:31:16 why do you check is_recording_ here but not in Sto
rkc 2014/08/01 21:08:57 StopOnAudioThread is called when a user explicitly
162 stream_->Stop();
Daniel Erat 2014/07/31 22:31:16 can this method just call StopOnAudioThread() and
rkc 2014/08/01 21:08:57 Sure. Done.
163 stream_->Close();
164 stream_ = NULL;
165
166 is_recording_ = false;
167 }
168
169 void AudioRecorder::FinalizeOnAudioThread() {
170 DCHECK(media::AudioManager::Get()->GetTaskRunner()->BelongsToCurrentThread());
171 StopAndCloseOnAudioThread();
172 if (input_stream_for_testing_)
173 delete input_stream_for_testing_;
174 delete this;
175 }
176
177 void AudioRecorder::OnData(media::AudioInputStream* stream,
178 const media::AudioBus* source,
179 uint32 /* hardware_delay_bytes */,
180 double /* volume */) {
181 temp_conversion_buffer_ = source;
182 while (temp_conversion_buffer_) {
183 // source->frames() == source_params.frames_per_buffer(), so we only have
184 // one chunk of data in the source; correspondingly set the destination
185 // size to one chunk.
186 // TODO(rkc): Optimize this to directly write into buffer_ so we can avoid
187 // the copy into this buffer and then the copy back into buffer_.
188 scoped_ptr<media::AudioBus> converted_source =
189 media::AudioBus::Create(kDefaultChannels, converter_->ChunkSize());
Daniel Erat 2014/07/31 22:31:16 nit: add blank line after this one so this isn't a
rkc 2014/08/01 21:08:57 Done.
190 // Convert accumulated samples into converted_source. Note: One call may not
191 // be enough to consume the samples from |source|. The converter may have
192 // accumulated samples over time due to a fractional input:output sample
193 // rate ratio. Since |source| is ephemeral, Convert() must be called until
194 // |source| is at least buffered into the converter. Once |source| is
195 // consumed during ProvideInput(), |temp_conversion_buffer_| will be set to
196 // NULL, which will break the conversion loop.
Daniel Erat 2014/07/31 22:31:16 i don't understand this comment. is it saying that
rkc 2014/08/01 21:08:57 No, this is all single threaded. ->Convert is what
197 converter_->Convert(converted_source.get());
198
199 int remaining_buffer_frames = buffer_->frames() - buffer_frame_index_;
200 int frames_to_copy =
201 std::min(remaining_buffer_frames, converted_source->frames());
202 converted_source->CopyPartialFramesTo(
203 0, frames_to_copy, buffer_frame_index_, buffer_.get());
204 buffer_frame_index_ += frames_to_copy;
205
206 // Buffer full, send it for processing.
207 if (buffer_->frames() == buffer_frame_index_) {
208 ProcessSamples(buffer_.Pass(), decode_callback_);
209 buffer_ = media::AudioBus::Create(kDefaultChannels, total_buffer_frames_);
210 buffer_frame_index_ = 0;
211
212 // Copy any remaining frames in the source to our buffer.
213 int remaining_source_frames = converted_source->frames() - frames_to_copy;
Daniel Erat 2014/07/31 22:31:16 is converted_source->frames() guaranteed to be <=
rkc 2014/08/01 21:08:57 total_buffer_frames_ is orders of magnitude higher
214 converted_source->CopyPartialFramesTo(frames_to_copy,
215 remaining_source_frames,
216 buffer_frame_index_,
217 buffer_.get());
Daniel Erat 2014/07/31 22:31:16 it seems like you'll never process the last chunk
rkc 2014/08/01 21:08:57 Whatever samples are leftover after the last Proce
218 buffer_frame_index_ += remaining_source_frames;
219 }
220 }
221 }
222
223 void AudioRecorder::OnError(media::AudioInputStream* /* stream */) {
224 LOG(ERROR) << "Error during sound recording.";
225 media::AudioManager::Get()->GetTaskRunner()->PostTask(
226 FROM_HERE,
227 base::Bind(&AudioRecorder::StopAndCloseOnAudioThread,
228 base::Unretained(this)));
229 }
230
231 double AudioRecorder::ProvideInput(media::AudioBus* dest,
232 base::TimeDelta /* buffer_delay */) {
233 DCHECK(temp_conversion_buffer_);
234 DCHECK_LE(temp_conversion_buffer_->frames(), dest->frames());
235 temp_conversion_buffer_->CopyTo(dest);
236 temp_conversion_buffer_ = NULL;
237 return 1.0;
238 }
239
240 void AudioRecorder::FlushAudioLoopForTesting() {
241 if (media::AudioManager::Get()->GetTaskRunner()->BelongsToCurrentThread())
242 return;
243
244 // Queue task on the audio thread, when it is executed, that means we've
245 // successfully executed all the tasks before us.
246 base::RunLoop rl;
247 media::AudioManager::Get()->GetTaskRunner()->PostTaskAndReply(
248 FROM_HERE,
249 base::Bind(base::IgnoreResult(&AudioRecorder::FlushAudioLoopForTesting),
250 base::Unretained(this)),
251 rl.QuitClosure());
252 rl.Run();
253 }
254
255 } // namespace copresence
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698