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

Side by Side Diff: content/browser/speech/speech_recognizer_impl.cc

Issue 549373003: Binding media stream audio track to speech recognition [browser] Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Move thread to recognizer_impl. Use PostDelayedTask. Created 6 years, 2 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
OLDNEW
1 // Copyright (c) 2013 The Chromium Authors. All rights reserved. 1 // Copyright (c) 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "content/browser/speech/speech_recognizer_impl.h" 5 #include "content/browser/speech/speech_recognizer_impl.h"
6 6
7 #include "base/basictypes.h" 7 #include "base/basictypes.h"
8 #include "base/bind.h" 8 #include "base/bind.h"
9 #include "base/memory/shared_memory.h"
10 #include "base/threading/thread.h"
11 #include "base/threading/thread_restrictions.h"
9 #include "base/time/time.h" 12 #include "base/time/time.h"
10 #include "content/browser/browser_main_loop.h" 13 #include "content/browser/browser_main_loop.h"
11 #include "content/browser/media/media_internals.h" 14 #include "content/browser/media/media_internals.h"
12 #include "content/browser/speech/audio_buffer.h" 15 #include "content/browser/speech/audio_buffer.h"
13 #include "content/browser/speech/google_one_shot_remote_engine.h" 16 #include "content/browser/speech/google_one_shot_remote_engine.h"
17 #include "content/browser/speech/speech_recognition_audio_receiver.h"
18 #include "content/public/browser/browser_message_filter.h"
14 #include "content/public/browser/speech_recognition_event_listener.h" 19 #include "content/public/browser/speech_recognition_event_listener.h"
15 #include "media/base/audio_converter.h" 20 #include "media/base/audio_converter.h"
16 #include "net/url_request/url_request_context_getter.h" 21 #include "net/url_request/url_request_context_getter.h"
17 22
18 #if defined(OS_WIN) 23 #if defined(OS_WIN)
19 #include "media/audio/win/core_audio_util_win.h" 24 #include "media/audio/win/core_audio_util_win.h"
20 #endif 25 #endif
21 26
22 using media::AudioBus; 27 using media::AudioBus;
23 using media::AudioConverter; 28 using media::AudioConverter;
(...skipping 10 matching lines...) Expand all
34 class SpeechRecognizerImpl::OnDataConverter 39 class SpeechRecognizerImpl::OnDataConverter
35 : public media::AudioConverter::InputCallback { 40 : public media::AudioConverter::InputCallback {
36 public: 41 public:
37 OnDataConverter(const AudioParameters& input_params, 42 OnDataConverter(const AudioParameters& input_params,
38 const AudioParameters& output_params); 43 const AudioParameters& output_params);
39 virtual ~OnDataConverter(); 44 virtual ~OnDataConverter();
40 45
41 // Converts input audio |data| bus into an AudioChunk where the input format 46 // Converts input audio |data| bus into an AudioChunk where the input format
42 // is given by |input_parameters_| and the output format by 47 // is given by |input_parameters_| and the output format by
43 // |output_parameters_|. 48 // |output_parameters_|.
49 // Skips conversion on |audio_converter_| when input and output formats match.
44 scoped_refptr<AudioChunk> Convert(const AudioBus* data); 50 scoped_refptr<AudioChunk> Convert(const AudioBus* data);
45 51
46 private: 52 private:
47 // media::AudioConverter::InputCallback implementation. 53 // media::AudioConverter::InputCallback implementation.
48 virtual double ProvideInput(AudioBus* dest, 54 virtual double ProvideInput(AudioBus* dest,
49 base::TimeDelta buffer_delay) override; 55 base::TimeDelta buffer_delay) override;
50 56
51 // Handles resampling, buffering, and channel mixing between input and output 57 // Handles resampling, buffering, and channel mixing between input and output
52 // parameters. 58 // parameters.
53 AudioConverter audio_converter_; 59 AudioConverter audio_converter_;
54 60
55 scoped_ptr<AudioBus> input_bus_; 61 scoped_ptr<AudioBus> input_bus_;
56 scoped_ptr<AudioBus> output_bus_; 62 scoped_ptr<AudioBus> output_bus_;
57 const AudioParameters input_parameters_; 63 const AudioParameters input_parameters_;
58 const AudioParameters output_parameters_; 64 const AudioParameters output_parameters_;
59 bool waiting_for_input_; 65 bool waiting_for_input_;
66 bool need_conversion_;
60 scoped_ptr<uint8[]> converted_data_; 67 scoped_ptr<uint8[]> converted_data_;
61 68
62 DISALLOW_COPY_AND_ASSIGN(OnDataConverter); 69 DISALLOW_COPY_AND_ASSIGN(OnDataConverter);
63 }; 70 };
64 71
65 namespace { 72 namespace {
66 73
67 // The following constants are related to the volume level indicator shown in 74 // The following constants are related to the volume level indicator shown in
68 // the UI for recorded audio. 75 // the UI for recorded audio.
69 // Multiplier used when new volume is greater than previous level. 76 // Multiplier used when new volume is greater than previous level.
(...skipping 47 matching lines...) Expand 10 before | Expand all | Expand 10 after
117 SpeechRecognizerImpl::OnDataConverter::OnDataConverter( 124 SpeechRecognizerImpl::OnDataConverter::OnDataConverter(
118 const AudioParameters& input_params, const AudioParameters& output_params) 125 const AudioParameters& input_params, const AudioParameters& output_params)
119 : audio_converter_(input_params, output_params, false), 126 : audio_converter_(input_params, output_params, false),
120 input_bus_(AudioBus::Create(input_params)), 127 input_bus_(AudioBus::Create(input_params)),
121 output_bus_(AudioBus::Create(output_params)), 128 output_bus_(AudioBus::Create(output_params)),
122 input_parameters_(input_params), 129 input_parameters_(input_params),
123 output_parameters_(output_params), 130 output_parameters_(output_params),
124 waiting_for_input_(false), 131 waiting_for_input_(false),
125 converted_data_(new uint8[output_parameters_.GetBytesPerBuffer()]) { 132 converted_data_(new uint8[output_parameters_.GetBytesPerBuffer()]) {
126 audio_converter_.AddInput(this); 133 audio_converter_.AddInput(this);
134 need_conversion_ = !input_parameters_.Equals(output_parameters_);
127 } 135 }
128 136
129 SpeechRecognizerImpl::OnDataConverter::~OnDataConverter() { 137 SpeechRecognizerImpl::OnDataConverter::~OnDataConverter() {
130 // It should now be safe to unregister the converter since no more OnData() 138 // It should now be safe to unregister the converter since no more OnData()
131 // callbacks are outstanding at this point. 139 // callbacks are outstanding at this point.
132 audio_converter_.RemoveInput(this); 140 audio_converter_.RemoveInput(this);
133 } 141 }
134 142
135 scoped_refptr<AudioChunk> SpeechRecognizerImpl::OnDataConverter::Convert( 143 scoped_refptr<AudioChunk> SpeechRecognizerImpl::OnDataConverter::Convert(
136 const AudioBus* data) { 144 const AudioBus* data) {
137 CHECK_EQ(data->frames(), input_parameters_.frames_per_buffer()); 145 CHECK_EQ(data->frames(), input_parameters_.frames_per_buffer());
138 146
139 data->CopyTo(input_bus_.get()); 147 // Do conversion if needed - only when |input_parameters_| differ from
140 148 // |output_parameters_|.
141 waiting_for_input_ = true; 149 if (need_conversion_) {
142 audio_converter_.Convert(output_bus_.get()); 150 data->CopyTo(input_bus_.get());
151 waiting_for_input_ = true;
152 audio_converter_.Convert(output_bus_.get());
153 } else {
154 data->CopyTo(output_bus_.get());
155 }
143 156
144 output_bus_->ToInterleaved( 157 output_bus_->ToInterleaved(
145 output_bus_->frames(), output_parameters_.bits_per_sample() / 8, 158 output_bus_->frames(), output_parameters_.bits_per_sample() / 8,
146 converted_data_.get()); 159 converted_data_.get());
147 160
148 // TODO(primiano): Refactor AudioChunk to avoid the extra-copy here 161 // TODO(primiano): Refactor AudioChunk to avoid the extra-copy here
149 // (see http://crbug.com/249316 for details). 162 // (see http://crbug.com/249316 for details).
150 return scoped_refptr<AudioChunk>(new AudioChunk( 163 return scoped_refptr<AudioChunk>(new AudioChunk(
151 converted_data_.get(), 164 converted_data_.get(),
152 output_parameters_.GetBytesPerBuffer(), 165 output_parameters_.GetBytesPerBuffer(),
(...skipping 15 matching lines...) Expand all
168 return 1; 181 return 1;
169 } 182 }
170 183
171 // SpeechRecognizerImpl implementation 184 // SpeechRecognizerImpl implementation
172 185
173 SpeechRecognizerImpl::SpeechRecognizerImpl( 186 SpeechRecognizerImpl::SpeechRecognizerImpl(
174 SpeechRecognitionEventListener* listener, 187 SpeechRecognitionEventListener* listener,
175 int session_id, 188 int session_id,
176 bool continuous, 189 bool continuous,
177 bool provisional_results, 190 bool provisional_results,
191 bool using_audio_receiver,
192 const base::ProcessHandle peer_process_handle,
178 SpeechRecognitionEngine* engine) 193 SpeechRecognitionEngine* engine)
179 : SpeechRecognizer(listener, session_id), 194 : SpeechRecognizer(listener, session_id),
180 recognition_engine_(engine), 195 recognition_engine_(engine),
181 endpointer_(kAudioSampleRate), 196 endpointer_(kAudioSampleRate),
182 audio_log_(MediaInternals::GetInstance()->CreateAudioLog( 197 audio_log_(MediaInternals::GetInstance()->CreateAudioLog(
183 media::AudioLogFactory::AUDIO_INPUT_CONTROLLER)), 198 media::AudioLogFactory::AUDIO_INPUT_CONTROLLER)),
184 is_dispatching_event_(false), 199 is_dispatching_event_(false),
185 provisional_results_(provisional_results), 200 provisional_results_(provisional_results),
201 using_audio_receiver_(using_audio_receiver),
202 peer_process_handle_(peer_process_handle),
186 state_(STATE_IDLE) { 203 state_(STATE_IDLE) {
187 DCHECK(recognition_engine_ != NULL); 204 DCHECK(recognition_engine_ != NULL);
188 if (!continuous) { 205 if (!continuous) {
189 // In single shot (non-continous) recognition, 206 // In single shot (non-continous) recognition,
190 // the session is automatically ended after: 207 // the session is automatically ended after:
191 // - 0.5 seconds of silence if time < 3 seconds 208 // - 0.5 seconds of silence if time < 3 seconds
192 // - 1 seconds of silence if time >= 3 seconds 209 // - 1 seconds of silence if time >= 3 seconds
193 endpointer_.set_speech_input_complete_silence_length( 210 endpointer_.set_speech_input_complete_silence_length(
194 base::Time::kMicrosecondsPerSecond / 2); 211 base::Time::kMicrosecondsPerSecond / 2);
195 endpointer_.set_long_speech_input_complete_silence_length( 212 endpointer_.set_long_speech_input_complete_silence_length(
(...skipping 11 matching lines...) Expand all
207 } 224 }
208 225
209 // ------- Methods that trigger Finite State Machine (FSM) events ------------ 226 // ------- Methods that trigger Finite State Machine (FSM) events ------------
210 227
211 // NOTE:all the external events and requests should be enqueued (PostTask), even 228 // NOTE:all the external events and requests should be enqueued (PostTask), even
212 // if they come from the same (IO) thread, in order to preserve the relationship 229 // if they come from the same (IO) thread, in order to preserve the relationship
213 // of causality between events and avoid interleaved event processing due to 230 // of causality between events and avoid interleaved event processing due to
214 // synchronous callbacks. 231 // synchronous callbacks.
215 232
216 void SpeechRecognizerImpl::StartRecognition(const std::string& device_id) { 233 void SpeechRecognizerImpl::StartRecognition(const std::string& device_id) {
217 DCHECK(!device_id.empty()); 234 DCHECK(!device_id.empty() ^ using_audio_receiver_);
218 device_id_ = device_id; 235 device_id_ = device_id;
219 236
220 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, 237 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
221 base::Bind(&SpeechRecognizerImpl::DispatchEvent, 238 base::Bind(&SpeechRecognizerImpl::DispatchEvent,
222 this, FSMEventArgs(EVENT_START))); 239 this, FSMEventArgs(EVENT_START)));
223 } 240 }
224 241
225 void SpeechRecognizerImpl::AbortRecognition() { 242 void SpeechRecognizerImpl::AbortRecognition() {
226 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, 243 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
227 base::Bind(&SpeechRecognizerImpl::DispatchEvent, 244 base::Bind(&SpeechRecognizerImpl::DispatchEvent,
(...skipping 10 matching lines...) Expand all
238 // Checking the FSM state from another thread (thus, while the FSM is 255 // Checking the FSM state from another thread (thus, while the FSM is
239 // potentially concurrently evolving) is meaningless. 256 // potentially concurrently evolving) is meaningless.
240 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); 257 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
241 return state_ != STATE_IDLE && state_ != STATE_ENDED; 258 return state_ != STATE_IDLE && state_ != STATE_ENDED;
242 } 259 }
243 260
244 bool SpeechRecognizerImpl::IsCapturingAudio() const { 261 bool SpeechRecognizerImpl::IsCapturingAudio() const {
245 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); // See IsActive(). 262 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); // See IsActive().
246 const bool is_capturing_audio = state_ >= STATE_STARTING && 263 const bool is_capturing_audio = state_ >= STATE_STARTING &&
247 state_ <= STATE_RECOGNIZING; 264 state_ <= STATE_RECOGNIZING;
248 DCHECK((is_capturing_audio && (audio_controller_.get() != NULL)) || 265 DCHECK((is_capturing_audio &&
266 (using_audio_receiver_ || (audio_controller_.get() != NULL))) ||
249 (!is_capturing_audio && audio_controller_.get() == NULL)); 267 (!is_capturing_audio && audio_controller_.get() == NULL));
250 return is_capturing_audio; 268 return is_capturing_audio;
251 } 269 }
252 270
253 const SpeechRecognitionEngine& 271 const SpeechRecognitionEngine&
254 SpeechRecognizerImpl::recognition_engine() const { 272 SpeechRecognizerImpl::recognition_engine() const {
255 return *(recognition_engine_.get()); 273 return *(recognition_engine_.get());
256 } 274 }
257 275
258 SpeechRecognizerImpl::~SpeechRecognizerImpl() { 276 SpeechRecognizerImpl::~SpeechRecognizerImpl() {
259 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); 277 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
260 endpointer_.EndSession(); 278 endpointer_.EndSession();
261 if (audio_controller_.get()) { 279 if (audio_controller_.get()) {
262 audio_controller_->Close( 280 audio_controller_->Close(
263 base::Bind(&KeepAudioControllerRefcountedForDtor, audio_controller_)); 281 base::Bind(&KeepAudioControllerRefcountedForDtor, audio_controller_));
264 audio_log_->OnClosed(0); 282 audio_log_->OnClosed(0);
283 ResetAudioReceiver();
265 } 284 }
266 } 285 }
267 286
268 // Invoked in the audio thread. 287 // Invoked in the audio thread.
269 void SpeechRecognizerImpl::OnError(AudioInputController* controller, 288 void SpeechRecognizerImpl::OnError(AudioInputController* controller,
270 media::AudioInputController::ErrorCode error_code) { 289 media::AudioInputController::ErrorCode error_code) {
271 FSMEventArgs event_args(EVENT_AUDIO_ERROR); 290 FSMEventArgs event_args(EVENT_AUDIO_ERROR);
272 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, 291 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
273 base::Bind(&SpeechRecognizerImpl::DispatchEvent, 292 base::Bind(&SpeechRecognizerImpl::DispatchEvent,
274 this, event_args)); 293 this, event_args));
(...skipping 200 matching lines...) Expand 10 before | Expand all | Expand 10 after
475 state_ <= STATE_RECOGNIZING; 494 state_ <= STATE_RECOGNIZING;
476 const bool clip_detected = DetectClipping(raw_audio); 495 const bool clip_detected = DetectClipping(raw_audio);
477 float rms = 0.0f; 496 float rms = 0.0f;
478 497
479 num_samples_recorded_ += raw_audio.NumSamples(); 498 num_samples_recorded_ += raw_audio.NumSamples();
480 499
481 if (route_to_endpointer) 500 if (route_to_endpointer)
482 endpointer_.ProcessAudio(raw_audio, &rms); 501 endpointer_.ProcessAudio(raw_audio, &rms);
483 502
484 if (route_to_vumeter) { 503 if (route_to_vumeter) {
485 DCHECK(route_to_endpointer); // Depends on endpointer due to |rms|. 504 DCHECK(route_to_endpointer); // Depends on endpointer due to |rms|.
486 UpdateSignalAndNoiseLevels(rms, clip_detected); 505 UpdateSignalAndNoiseLevels(rms, clip_detected);
487 } 506 }
488 if (route_to_sr_engine) { 507 if (route_to_sr_engine) {
489 DCHECK(recognition_engine_.get() != NULL); 508 DCHECK(recognition_engine_.get() != NULL);
490 recognition_engine_->TakeAudioChunk(raw_audio); 509 recognition_engine_->TakeAudioChunk(raw_audio);
491 } 510 }
492 } 511 }
493 512
494 SpeechRecognizerImpl::FSMState 513 SpeechRecognizerImpl::FSMState
495 SpeechRecognizerImpl::StartRecording(const FSMEventArgs&) { 514 SpeechRecognizerImpl::StartRecording(const FSMEventArgs&) {
(...skipping 26 matching lines...) Expand all
522 return Abort(SpeechRecognitionError(SPEECH_RECOGNITION_ERROR_AUDIO)); 541 return Abort(SpeechRecognitionError(SPEECH_RECOGNITION_ERROR_AUDIO));
523 } 542 }
524 543
525 // Audio converter shall provide audio based on these parameters as output. 544 // Audio converter shall provide audio based on these parameters as output.
526 // Hard coded, WebSpeech specific parameters are utilized here. 545 // Hard coded, WebSpeech specific parameters are utilized here.
527 int frames_per_buffer = (kAudioSampleRate * chunk_duration_ms) / 1000; 546 int frames_per_buffer = (kAudioSampleRate * chunk_duration_ms) / 1000;
528 AudioParameters output_parameters = AudioParameters( 547 AudioParameters output_parameters = AudioParameters(
529 AudioParameters::AUDIO_PCM_LOW_LATENCY, kChannelLayout, kAudioSampleRate, 548 AudioParameters::AUDIO_PCM_LOW_LATENCY, kChannelLayout, kAudioSampleRate,
530 kNumBitsPerAudioSample, frames_per_buffer); 549 kNumBitsPerAudioSample, frames_per_buffer);
531 550
551 // Check if using audio receiver as source (audio data processed on renderer).
552 // If |StartRecordingUsingAudioReceiver()| fails, we abort the recognition.
553 if (using_audio_receiver_) {
554 return StartRecordingUsingAudioReceiver(output_parameters)
555 ? STATE_STARTING
556 : Abort(SpeechRecognitionError(SPEECH_RECOGNITION_ERROR_AUDIO));
557 }
558
559 // Get audio data from microphone on the browser.
560
532 // Audio converter will receive audio based on these parameters as input. 561 // Audio converter will receive audio based on these parameters as input.
533 // On Windows we start by verifying that Core Audio is supported. If not, 562 // On Windows we start by verifying that Core Audio is supported. If not,
534 // the WaveIn API is used and we might as well avoid all audio conversations 563 // the WaveIn API is used and we might as well avoid all audio conversations
535 // since WaveIn does the conversion for us. 564 // since WaveIn does the conversion for us.
536 // TODO(henrika): this code should be moved to platform dependent audio 565 // TODO(henrika): this code should be moved to platform dependent audio
537 // managers. 566 // managers.
538 bool use_native_audio_params = true; 567 bool use_native_audio_params = true;
539 #if defined(OS_WIN) 568 #if defined(OS_WIN)
540 use_native_audio_params = media::CoreAudioUtil::IsSupported(); 569 use_native_audio_params = media::CoreAudioUtil::IsSupported();
541 DVLOG_IF(1, !use_native_audio_params) << "Reverting to WaveIn for WebSpeech"; 570 DVLOG_IF(1, !use_native_audio_params) << "Reverting to WaveIn for WebSpeech";
(...skipping 36 matching lines...) Expand 10 before | Expand all | Expand 10 after
578 // The endpointer needs to estimate the environment/background noise before 607 // The endpointer needs to estimate the environment/background noise before
579 // starting to treat the audio as user input. We wait in the state 608 // starting to treat the audio as user input. We wait in the state
580 // ESTIMATING_ENVIRONMENT until such interval has elapsed before switching 609 // ESTIMATING_ENVIRONMENT until such interval has elapsed before switching
581 // to user input mode. 610 // to user input mode.
582 endpointer_.SetEnvironmentEstimationMode(); 611 endpointer_.SetEnvironmentEstimationMode();
583 audio_controller_->Record(); 612 audio_controller_->Record();
584 audio_log_->OnStarted(0); 613 audio_log_->OnStarted(0);
585 return STATE_STARTING; 614 return STATE_STARTING;
586 } 615 }
587 616
617 bool SpeechRecognizerImpl::StartRecordingUsingAudioReceiver(
618 const media::AudioParameters& params) {
619 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
620
621 audio_thread_.reset(new base::Thread("AudioReceiverThread"));
tommi (sloooow) - chröme 2014/10/16 21:20:23 what if this is already set? (should we at least D
burnik 2014/10/17 10:48:02 Done. However: That would indicate the FSM contrac
622 if (!audio_thread_->Start()) {
623 DLOG(ERROR) << "Cannot start new audio thread";
tommi (sloooow) - chröme 2014/10/16 21:20:23 free audio_thread_?
burnik 2014/10/17 10:48:02 Done.
624 return false;
625 }
626
627 // Start receiving audio, incoming data will be posted to |OnAudioTrackData|.
628 base::SharedMemoryHandle foreign_memory_handle;
629 base::SyncSocket::TransitDescriptor foreign_socket_descriptor;
630 audio_receiver_ = SpeechRecognitionAudioReceiver::Create(
631 params,
632 peer_process_handle_,
633 this, // Trigger OnData() and OnError() events here.
634 audio_thread_->task_runner().get(),
635 &foreign_memory_handle,
636 &foreign_socket_descriptor);
637
638 if (!audio_receiver_.get()) {
639 ResetAudioReceiver();
640 return false;
641 }
642
643 // Reusing the audio converter only to create chunks from the bus.
644 // Same input and output format indicate no additional conversion here.
645 audio_converter_.reset(new OnDataConverter(params, params));
646
647 // The endpointer needs to estimate the environment/background noise before
648 // starting to treat the audio as user input. We wait in the state
649 // ESTIMATING_ENVIRONMENT until such interval has elapsed before switching
650 // to user input mode.
651 endpointer_.SetEnvironmentEstimationMode();
652
653 // Start listening on the receiver's audio thread.
654 audio_receiver_->Listen();
655
656 listener()->OnAudioReceiverReady(session_id(),
657 params,
658 foreign_memory_handle,
659 foreign_socket_descriptor);
660
661 return true;
662 }
663
664 void SpeechRecognizerImpl::ResetAudioReceiver() {
665 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
666
667 // We stop listening not to post any new tasks to the audio thread.
668 audio_receiver_->Stop();
669
670 // This synchronous operation is usually instantaneous since the receiver
671 // closes the socket on Stop() and no new tasks will be posted to the
672 // |audio_thread_|.
673 const bool previous_io_allowed = base::ThreadRestrictions::SetIOAllowed(true);
tommi (sloooow) - chröme 2014/10/16 21:20:23 ScopedAllowIO
burnik 2014/10/17 10:48:02 Unfortunately, ScopedAllowIO is deprecated and is
674 audio_thread_->Stop();
675 base::ThreadRestrictions::SetIOAllowed(previous_io_allowed);
676
677 audio_thread_.reset();
678 audio_receiver_.reset();
679 }
680
588 SpeechRecognizerImpl::FSMState 681 SpeechRecognizerImpl::FSMState
589 SpeechRecognizerImpl::StartRecognitionEngine(const FSMEventArgs& event_args) { 682 SpeechRecognizerImpl::StartRecognitionEngine(const FSMEventArgs& event_args) {
590 // This is the first audio packet captured, so the recognition engine is 683 // This is the first audio packet captured, so the recognition engine is
591 // started and the delegate notified about the event. 684 // started and the delegate notified about the event.
592 DCHECK(recognition_engine_.get() != NULL); 685 DCHECK(recognition_engine_.get() != NULL);
593 recognition_engine_->StartRecognition(); 686 recognition_engine_->StartRecognition();
594 listener()->OnAudioStart(session_id()); 687 listener()->OnAudioStart(session_id());
595 688
596 // This is a little hack, since TakeAudioChunk() is already called by 689 // This is a little hack, since TakeAudioChunk() is already called by
597 // ProcessAudioPipeline(). It is the best tradeoff, unless we allow dropping 690 // ProcessAudioPipeline(). It is the best tradeoff, unless we allow dropping
(...skipping 62 matching lines...) Expand 10 before | Expand all | Expand 10 after
660 return Abort(event_args.engine_error); 753 return Abort(event_args.engine_error);
661 } 754 }
662 return Abort(SpeechRecognitionError(SPEECH_RECOGNITION_ERROR_ABORTED)); 755 return Abort(SpeechRecognitionError(SPEECH_RECOGNITION_ERROR_ABORTED));
663 } 756 }
664 757
665 SpeechRecognizerImpl::FSMState SpeechRecognizerImpl::Abort( 758 SpeechRecognizerImpl::FSMState SpeechRecognizerImpl::Abort(
666 const SpeechRecognitionError& error) { 759 const SpeechRecognitionError& error) {
667 if (IsCapturingAudio()) 760 if (IsCapturingAudio())
668 CloseAudioControllerAsynchronously(); 761 CloseAudioControllerAsynchronously();
669 762
763
670 DVLOG(1) << "SpeechRecognizerImpl canceling recognition. "; 764 DVLOG(1) << "SpeechRecognizerImpl canceling recognition. ";
671 765
672 // The recognition engine is initialized only after STATE_STARTING. 766 // The recognition engine is initialized only after STATE_STARTING.
673 if (state_ > STATE_STARTING) { 767 if (state_ > STATE_STARTING) {
674 DCHECK(recognition_engine_.get() != NULL); 768 DCHECK(recognition_engine_.get() != NULL);
675 recognition_engine_->EndRecognition(); 769 recognition_engine_->EndRecognition();
676 } 770 }
677 771
678 if (state_ > STATE_WAITING_FOR_SPEECH && state_ < STATE_WAITING_FINAL_RESULT) 772 if (state_ > STATE_WAITING_FOR_SPEECH && state_ < STATE_WAITING_FINAL_RESULT)
679 listener()->OnSoundEnd(session_id()); 773 listener()->OnSoundEnd(session_id());
(...skipping 83 matching lines...) Expand 10 before | Expand all | Expand 10 after
763 857
764 SpeechRecognizerImpl::FSMState 858 SpeechRecognizerImpl::FSMState
765 SpeechRecognizerImpl::NotFeasible(const FSMEventArgs& event_args) { 859 SpeechRecognizerImpl::NotFeasible(const FSMEventArgs& event_args) {
766 NOTREACHED() << "Unfeasible event " << event_args.event 860 NOTREACHED() << "Unfeasible event " << event_args.event
767 << " in state " << state_; 861 << " in state " << state_;
768 return state_; 862 return state_;
769 } 863 }
770 864
771 void SpeechRecognizerImpl::CloseAudioControllerAsynchronously() { 865 void SpeechRecognizerImpl::CloseAudioControllerAsynchronously() {
772 DCHECK(IsCapturingAudio()); 866 DCHECK(IsCapturingAudio());
867
868 if (using_audio_receiver_) {
869 ResetAudioReceiver();
870 return;
871 }
872
773 DVLOG(1) << "SpeechRecognizerImpl closing audio controller."; 873 DVLOG(1) << "SpeechRecognizerImpl closing audio controller.";
774 // Issues a Close on the audio controller, passing an empty callback. The only 874 // Issues a Close on the audio controller, passing an empty callback. The only
775 // purpose of such callback is to keep the audio controller refcounted until 875 // purpose of such callback is to keep the audio controller refcounted until
776 // Close has completed (in the audio thread) and automatically destroy it 876 // Close has completed (in the audio thread) and automatically destroy it
777 // afterwards (upon return from OnAudioClosed). 877 // afterwards (upon return from OnAudioClosed).
778 audio_controller_->Close(base::Bind(&SpeechRecognizerImpl::OnAudioClosed, 878 audio_controller_->Close(base::Bind(&SpeechRecognizerImpl::OnAudioClosed,
779 this, audio_controller_)); 879 this, audio_controller_));
780 audio_controller_ = NULL; // The controller is still refcounted by Bind. 880 audio_controller_ = NULL; // The controller is still refcounted by Bind.
781 audio_log_->OnClosed(0); 881 audio_log_->OnClosed(0);
782 } 882 }
(...skipping 32 matching lines...) Expand 10 before | Expand all | Expand 10 after
815 SpeechRecognizerImpl::FSMEventArgs::FSMEventArgs(FSMEvent event_value) 915 SpeechRecognizerImpl::FSMEventArgs::FSMEventArgs(FSMEvent event_value)
816 : event(event_value), 916 : event(event_value),
817 audio_data(NULL), 917 audio_data(NULL),
818 engine_error(SPEECH_RECOGNITION_ERROR_NONE) { 918 engine_error(SPEECH_RECOGNITION_ERROR_NONE) {
819 } 919 }
820 920
821 SpeechRecognizerImpl::FSMEventArgs::~FSMEventArgs() { 921 SpeechRecognizerImpl::FSMEventArgs::~FSMEventArgs() {
822 } 922 }
823 923
824 } // namespace content 924 } // namespace content
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698