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/google_one_shot_remote_engine.h"
9 #include "base/json/json_reader.h"
10 #include "base/strings/string_number_conversions.h"
11 #include "base/strings/string_util.h"
12 #include "base/values.h"
13 #include "content/browser/speech/audio_buffer.h"
14 #include "content/public/common/speech_recognition_error.h"
15 #include "content/public/common/speech_recognition_result.h"
16 #include "google_apis/google_api_keys.h"
17 #include "net/base/escape.h"
18 #include "net/base/load_flags.h"
19 #include "net/url_request/http_user_agent_settings.h"
20 #include "net/url_request/url_fetcher.h"
21 #include "net/url_request/url_request_context.h"
22 #include "net/url_request/url_request_context_getter.h"
23 #include "net/url_request/url_request_status.h"
28 const char* const kDefaultSpeechRecognitionUrl
=
29 "https://www.google.com/speech-api/v1/recognize?xjerr=1&client=chromium&";
30 const char* const kStatusString
= "status";
31 const char* const kHypothesesString
= "hypotheses";
32 const char* const kUtteranceString
= "utterance";
33 const char* const kConfidenceString
= "confidence";
34 const int kWebServiceStatusNoError
= 0;
35 const int kWebServiceStatusNoSpeech
= 4;
36 const int kWebServiceStatusNoMatch
= 5;
38 bool ParseServerResponse(const std::string
& response_body
,
39 SpeechRecognitionResult
* result
,
40 SpeechRecognitionError
* error
) {
41 if (response_body
.empty()) {
42 LOG(WARNING
) << "ParseServerResponse: Response was empty.";
45 DVLOG(1) << "ParseServerResponse: Parsing response " << response_body
;
47 // Parse the response, ignoring comments.
48 std::string error_msg
;
49 scoped_ptr
<base::Value
> response_value
= base::JSONReader::ReadAndReturnError(
50 response_body
, base::JSON_PARSE_RFC
, NULL
, &error_msg
);
51 if (response_value
== NULL
) {
52 LOG(WARNING
) << "ParseServerResponse: JSONReader failed : " << error_msg
;
56 if (!response_value
->IsType(base::Value::TYPE_DICTIONARY
)) {
57 DVLOG(1) << "ParseServerResponse: Unexpected response type "
58 << response_value
->GetType();
61 const base::DictionaryValue
* response_object
=
62 static_cast<const base::DictionaryValue
*>(response_value
.get());
66 if (!response_object
->GetInteger(kStatusString
, &status
)) {
67 DVLOG(1) << "ParseServerResponse: " << kStatusString
68 << " is not a valid integer value.";
72 // Process the status.
74 case kWebServiceStatusNoError
:
76 case kWebServiceStatusNoSpeech
:
77 error
->code
= SPEECH_RECOGNITION_ERROR_NO_SPEECH
;
79 case kWebServiceStatusNoMatch
:
80 error
->code
= SPEECH_RECOGNITION_ERROR_NO_MATCH
;
83 error
->code
= SPEECH_RECOGNITION_ERROR_NETWORK
;
84 // Other status codes should not be returned by the server.
85 DVLOG(1) << "ParseServerResponse: unexpected status code " << status
;
89 // Get the hypotheses.
90 const base::Value
* hypotheses_value
= NULL
;
91 if (!response_object
->Get(kHypothesesString
, &hypotheses_value
)) {
92 DVLOG(1) << "ParseServerResponse: Missing hypotheses attribute.";
96 DCHECK(hypotheses_value
);
97 if (!hypotheses_value
->IsType(base::Value::TYPE_LIST
)) {
98 DVLOG(1) << "ParseServerResponse: Unexpected hypotheses type "
99 << hypotheses_value
->GetType();
103 const base::ListValue
* hypotheses_list
=
104 static_cast<const base::ListValue
*>(hypotheses_value
);
106 // For now we support only single shot recognition, so we are giving only a
107 // final result, consisting of one fragment (with one or more hypotheses).
109 for (; index
< hypotheses_list
->GetSize(); ++index
) {
110 const base::Value
* hypothesis
= NULL
;
111 if (!hypotheses_list
->Get(index
, &hypothesis
)) {
112 LOG(WARNING
) << "ParseServerResponse: Unable to read hypothesis value.";
116 if (!hypothesis
->IsType(base::Value::TYPE_DICTIONARY
)) {
117 LOG(WARNING
) << "ParseServerResponse: Unexpected value type "
118 << hypothesis
->GetType();
122 const base::DictionaryValue
* hypothesis_value
=
123 static_cast<const base::DictionaryValue
*>(hypothesis
);
124 base::string16 utterance
;
126 if (!hypothesis_value
->GetString(kUtteranceString
, &utterance
)) {
127 LOG(WARNING
) << "ParseServerResponse: Missing utterance value.";
131 // It is not an error if the 'confidence' field is missing.
132 double confidence
= 0.0;
133 hypothesis_value
->GetDouble(kConfidenceString
, &confidence
);
134 result
->hypotheses
.push_back(SpeechRecognitionHypothesis(utterance
,
138 if (index
< hypotheses_list
->GetSize()) {
139 result
->hypotheses
.clear();
147 const int GoogleOneShotRemoteEngine::kAudioPacketIntervalMs
= 100;
148 int GoogleOneShotRemoteEngine::url_fetcher_id_for_tests
= 0;
150 GoogleOneShotRemoteEngine::GoogleOneShotRemoteEngine(
151 net::URLRequestContextGetter
* context
)
152 : url_context_(context
) {
155 GoogleOneShotRemoteEngine::~GoogleOneShotRemoteEngine() {}
157 void GoogleOneShotRemoteEngine::SetConfig(
158 const SpeechRecognitionEngineConfig
& config
) {
162 void GoogleOneShotRemoteEngine::StartRecognition() {
164 DCHECK(!url_fetcher_
.get());
165 std::string lang_param
= config_
.language
;
167 if (lang_param
.empty() && url_context_
.get()) {
168 // If no language is provided then we use the first from the accepted
169 // language list. If this list is empty then it defaults to "en-US".
170 // Example of the contents of this list: "es,en-GB;q=0.8", ""
171 net::URLRequestContext
* request_context
=
172 url_context_
->GetURLRequestContext();
173 DCHECK(request_context
);
174 // TODO(pauljensen): GoogleOneShotRemoteEngine should be constructed with
175 // a reference to the HttpUserAgentSettings rather than accessing the
176 // accept language through the URLRequestContext.
177 if (request_context
->http_user_agent_settings()) {
178 std::string accepted_language_list
=
179 request_context
->http_user_agent_settings()->GetAcceptLanguage();
180 size_t separator
= accepted_language_list
.find_first_of(",;");
181 lang_param
= accepted_language_list
.substr(0, separator
);
185 if (lang_param
.empty())
186 lang_param
= "en-US";
188 std::vector
<std::string
> parts
;
189 parts
.push_back("lang=" + net::EscapeQueryParamValue(lang_param
, true));
191 if (!config_
.grammars
.empty()) {
192 DCHECK_EQ(config_
.grammars
.size(), 1U);
193 parts
.push_back("lm=" + net::EscapeQueryParamValue(config_
.grammars
[0].url
,
197 if (!config_
.hardware_info
.empty())
198 parts
.push_back("xhw=" + net::EscapeQueryParamValue(config_
.hardware_info
,
200 parts
.push_back("maxresults=" + base::UintToString(config_
.max_hypotheses
));
201 parts
.push_back(config_
.filter_profanities
? "pfilter=2" : "pfilter=0");
203 std::string api_key
= google_apis::GetAPIKey();
204 parts
.push_back("key=" + net::EscapeQueryParamValue(api_key
, true));
206 GURL
url(std::string(kDefaultSpeechRecognitionUrl
) +
207 base::JoinString(parts
, "&"));
209 encoder_
.reset(new AudioEncoder(config_
.audio_sample_rate
,
210 config_
.audio_num_bits_per_sample
));
211 DCHECK(encoder_
.get());
212 url_fetcher_
= net::URLFetcher::Create(url_fetcher_id_for_tests
, url
,
213 net::URLFetcher::POST
, this);
214 url_fetcher_
->SetChunkedUpload(encoder_
->GetMimeType());
215 url_fetcher_
->SetRequestContext(url_context_
.get());
216 url_fetcher_
->SetReferrer(config_
.origin_url
);
218 // The speech recognition API does not require user identification as part
219 // of requests, so we don't send cookies or auth data for these requests to
220 // prevent any accidental connection between users who are logged into the
221 // domain for other services (e.g. bookmark sync) with the speech requests.
222 url_fetcher_
->SetLoadFlags(net::LOAD_DO_NOT_SAVE_COOKIES
|
223 net::LOAD_DO_NOT_SEND_COOKIES
|
224 net::LOAD_DO_NOT_SEND_AUTH_DATA
);
225 url_fetcher_
->Start();
228 void GoogleOneShotRemoteEngine::EndRecognition() {
229 url_fetcher_
.reset();
232 void GoogleOneShotRemoteEngine::TakeAudioChunk(const AudioChunk
& data
) {
233 DCHECK(url_fetcher_
.get());
234 DCHECK(encoder_
.get());
235 DCHECK_EQ(data
.bytes_per_sample(), config_
.audio_num_bits_per_sample
/ 8);
236 encoder_
->Encode(data
);
237 scoped_refptr
<AudioChunk
> encoded_data(encoder_
->GetEncodedDataAndClear());
238 url_fetcher_
->AppendChunkToUpload(encoded_data
->AsString(), false);
241 void GoogleOneShotRemoteEngine::AudioChunksEnded() {
242 DCHECK(url_fetcher_
.get());
243 DCHECK(encoder_
.get());
245 // UploadAudioChunk requires a non-empty final buffer. So we encode a packet
246 // of silence in case encoder had no data already.
247 size_t sample_count
=
248 config_
.audio_sample_rate
* kAudioPacketIntervalMs
/ 1000;
249 scoped_refptr
<AudioChunk
> dummy_chunk(new AudioChunk(
250 sample_count
* sizeof(int16
), encoder_
->GetBitsPerSample() / 8));
251 encoder_
->Encode(*dummy_chunk
.get());
253 scoped_refptr
<AudioChunk
> encoded_dummy_data(
254 encoder_
->GetEncodedDataAndClear());
255 DCHECK(!encoded_dummy_data
->IsEmpty());
258 url_fetcher_
->AppendChunkToUpload(encoded_dummy_data
->AsString(), true);
261 void GoogleOneShotRemoteEngine::OnURLFetchComplete(
262 const net::URLFetcher
* source
) {
263 DCHECK_EQ(url_fetcher_
.get(), source
);
264 SpeechRecognitionResults results
;
265 results
.push_back(SpeechRecognitionResult());
266 SpeechRecognitionResult
& result
= results
.back();
267 SpeechRecognitionError
error(SPEECH_RECOGNITION_ERROR_NETWORK
);
270 // The default error code in case of parse errors is NETWORK_FAILURE, however
271 // ParseServerResponse can change the error to a more appropriate one.
272 bool error_occurred
= (!source
->GetStatus().is_success() ||
273 source
->GetResponseCode() != 200 ||
274 !source
->GetResponseAsString(&data
) ||
275 !ParseServerResponse(data
, &result
, &error
));
276 url_fetcher_
.reset();
277 if (error_occurred
) {
278 DVLOG(1) << "GoogleOneShotRemoteEngine: Network Error " << error
.code
;
279 delegate()->OnSpeechRecognitionEngineError(error
);
281 DVLOG(1) << "GoogleOneShotRemoteEngine: Invoking delegate with result.";
282 delegate()->OnSpeechRecognitionEngineResults(results
);
286 bool GoogleOneShotRemoteEngine::IsRecognitionPending() const {
287 return url_fetcher_
!= NULL
;
290 int GoogleOneShotRemoteEngine::GetDesiredAudioChunkDurationMs() const {
291 return kAudioPacketIntervalMs
;
294 } // namespace content