summaryrefslogtreecommitdiff
path: root/chromium/chrome/browser/resources/hotword/nacl_manager.js
blob: db23ece082e6e1586ac3d44f56661b41e31e7967 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

cr.define('hotword', function() {
'use strict';

/**
 * Class used to manage the state of the NaCl recognizer plugin. Handles all
 * control of the NaCl plugin, including creation, start, stop, trigger, and
 * shutdown.
 *
 * @constructor
 * @extends {cr.EventTarget}
 */
function NaClManager() {
  /**
   * Current state of this manager.
   * @private {hotword.NaClManager.ManagerState_}
   */
  this.recognizerState_ = ManagerState_.UNINITIALIZED;

  /**
   * The window.timeout ID associated with a pending message.
   * @private {?number}
   */
  this.naclTimeoutId_ = null;

  /**
   * The expected message that will cancel the current timeout.
   * @private {?string}
   */
  this.expectingMessage_ = null;

  /**
   * Whether the plugin will be started as soon as it stops.
   * @private {boolean}
   */
  this.restartOnStop_ = false;

  /**
   * NaCl plugin element on extension background page.
   * @private {?HTMLEmbedElement}
   */
  this.plugin_ = null;

  /**
   * URL containing hotword-model data file.
   * @private {string}
   */
  this.modelUrl_ = '';

  /**
   * Media stream containing an audio input track.
   * @private {?MediaStream}
   */
  this.stream_ = null;
};

/**
 * States this manager can be in. Since messages to/from the plugin are
 * asynchronous (and potentially queued), it's not possible to know what state
 * the plugin is in. However, track a state machine for NaClManager based on
 * what messages are sent/received.
 * @enum {number}
 * @private
 */
NaClManager.ManagerState_ = {
  UNINITIALIZED: 0,
  LOADING: 1,
  STOPPING: 2,
  STOPPED: 3,
  STARTING: 4,
  RUNNING: 5,
  ERROR: 6,
  SHUTDOWN: 7,
};
var ManagerState_ = NaClManager.ManagerState_;
var Error_ = hotword.constants.Error;
var UmaNaClMessageTimeout_ = hotword.constants.UmaNaClMessageTimeout;
var UmaNaClPluginLoadResult_ = hotword.constants.UmaNaClPluginLoadResult;

NaClManager.prototype.__proto__ = cr.EventTarget.prototype;

/**
 * Called when an error occurs. Dispatches an event.
 * @param {!hotword.constants.Error} error
 * @private
 */
NaClManager.prototype.handleError_ = function(error) {
  var event = new Event(hotword.constants.Event.ERROR);
  event.data = error;
  this.dispatchEvent(event);
};

/**
 * Record the result of loading the NaCl plugin to UMA.
 * @param {!hotword.constants.UmaNaClPluginLoadResult} error
 * @private
 */
NaClManager.prototype.logPluginLoadResult_ = function(error) {
  hotword.metrics.recordEnum(
      hotword.constants.UmaMetrics.NACL_PLUGIN_LOAD_RESULT,
      error,
      UmaNaClPluginLoadResult_.MAX);
};

/**
 * @return {boolean} True if the recognizer is in a running state.
 */
NaClManager.prototype.isRunning = function() {
  return this.recognizerState_ == ManagerState_.RUNNING;
};

/**
 * Set a timeout. Only allow one timeout to exist at any given time.
 * @param {!function()} func
 * @param {number} timeout
 * @private
 */
NaClManager.prototype.setTimeout_ = function(func, timeout) {
  assert(!this.naclTimeoutId_, 'Timeout already exists');
  this.naclTimeoutId_ = window.setTimeout(
      function() {
        this.naclTimeoutId_ = null;
        func();
      }.bind(this), timeout);
};

/**
 * Clears the current timeout.
 * @private
 */
NaClManager.prototype.clearTimeout_ = function() {
  window.clearTimeout(this.naclTimeoutId_);
  this.naclTimeoutId_ = null;
};

/**
 * Starts a stopped or stopping hotword recognizer (NaCl plugin).
 */
NaClManager.prototype.startRecognizer = function() {
  if (this.recognizerState_ == ManagerState_.STOPPED) {
    this.recognizerState_ = ManagerState_.STARTING;
    this.sendDataToPlugin_(hotword.constants.NaClPlugin.RESTART);
    this.waitForMessage_(hotword.constants.TimeoutMs.LONG,
                         hotword.constants.NaClPlugin.READY_FOR_AUDIO);
  } else if (this.recognizerState_ == ManagerState_.STOPPING) {
    // Wait until the plugin is stopped before trying to start it.
    this.restartOnStop_ = true;
  } else {
    throw 'Attempting to start NaCl recogniser not in STOPPED or STOPPING ' +
        'state';
  }
};

/**
 * Stops the hotword recognizer.
 */
NaClManager.prototype.stopRecognizer = function() {
  this.sendDataToPlugin_(hotword.constants.NaClPlugin.STOP);
  this.recognizerState_ = ManagerState_.STOPPING;
  this.waitForMessage_(hotword.constants.TimeoutMs.NORMAL,
                       hotword.constants.NaClPlugin.STOPPED);
};

/**
 * Checks whether the file at the given path exists.
 * @param {!string} path Path to a file. Can be any valid URL.
 * @return {boolean} True if the patch exists.
 * @private
 */
NaClManager.prototype.fileExists_ = function(path) {
  var xhr = new XMLHttpRequest();
  xhr.open('HEAD', path, false);
  try {
    xhr.send();
  } catch (err) {
    return false;
  }
  if (xhr.readyState != xhr.DONE || xhr.status != 200) {
    return false;
  }
  return true;
};

/**
 * Creates and returns a list of possible languages to check for hotword
 * support.
 * @return {!Array.<string>} Array of languages.
 * @private
 */
NaClManager.prototype.getPossibleLanguages_ = function() {
  // Create array used to search first for language-country, if not found then
  // search for language, if not found then no language (empty string).
  // For example, search for 'en-us', then 'en', then ''.
  var langs = new Array();
  if (hotword.constants.UI_LANGUAGE) {
    // Chrome webstore doesn't support uppercase path: crbug.com/353407
    var language = hotword.constants.UI_LANGUAGE.toLowerCase();
    langs.push(language);  // Example: 'en-us'.
    // Remove country to add just the language to array.
    var hyphen = language.lastIndexOf('-');
    if (hyphen >= 0) {
      langs.push(language.substr(0, hyphen));  // Example: 'en'.
    }
  }
  langs.push('');
  return langs;
};

/**
 * Creates a NaCl plugin object and attaches it to the page.
 * @param {!string} src Location of the plugin.
 * @return {!HTMLEmbedElement} NaCl plugin DOM object.
 * @private
 */
NaClManager.prototype.createPlugin_ = function(src) {
  var plugin = /** @type {HTMLEmbedElement} */(document.createElement('embed'));
  plugin.src = src;
  plugin.type = 'application/x-nacl';
  document.body.appendChild(plugin);
  return plugin;
};

/**
 * Initializes the NaCl manager.
 * @param {!string} naclArch Either 'arm', 'x86-32' or 'x86-64'.
 * @param {!MediaStream} stream A stream containing an audio source track.
 * @return {boolean} True if the successful.
 */
NaClManager.prototype.initialize = function(naclArch, stream) {
  assert(this.recognizerState_ == ManagerState_.UNINITIALIZED,
         'Recognizer not in uninitialized state. State: ' +
         this.recognizerState_);
  var langs = this.getPossibleLanguages_();
  var i, j;
  // For country-lang variations. For example, when combined with path it will
  // attempt to find: '/x86-32_en-gb/', else '/x86-32_en/', else '/x86-32_/'.
  for (i = 0; i < langs.length; i++) {
    var folder = hotword.constants.SHARED_MODULE_ROOT + '/_platform_specific/' +
        naclArch + '_' + langs[i] + '/';
    var dataSrc = folder + hotword.constants.File.RECOGNIZER_CONFIG;
    var pluginSrc = hotword.constants.SHARED_MODULE_ROOT + '/hotword_' +
        langs[i] + '.nmf';
    var dataExists = this.fileExists_(dataSrc) && this.fileExists_(pluginSrc);
    if (!dataExists) {
      continue;
    }

    var plugin = this.createPlugin_(pluginSrc);
    this.plugin_ = plugin;
    if (!this.plugin_ || !this.plugin_.postMessage) {
      document.body.removeChild(this.plugin_);
      this.recognizerState_ = ManagerState_.ERROR;
      return false;
    }
    this.modelUrl_ = chrome.extension.getURL(dataSrc);
    this.stream_ = stream;
    this.recognizerState_ = ManagerState_.LOADING;

    plugin.addEventListener('message',
                            this.handlePluginMessage_.bind(this),
                            false);

    plugin.addEventListener('crash',
                            function() {
                              this.handleError_(Error_.NACL_CRASH);
                              this.logPluginLoadResult_(
                                  UmaNaClPluginLoadResult_.CRASH);
                            }.bind(this),
                            false);
    return true;
  }
  this.recognizerState_ = ManagerState_.ERROR;
  this.logPluginLoadResult_(UmaNaClPluginLoadResult_.NO_MODULE_FOUND);
  return false;
};

/**
 * Shuts down the NaCl plugin and frees all resources.
 */
NaClManager.prototype.shutdown = function() {
  if (this.plugin_ != null) {
    document.body.removeChild(this.plugin_);
    this.plugin_ = null;
  }
  this.clearTimeout_();
  this.recognizerState_ = ManagerState_.SHUTDOWN;
  this.stream_ = null;
};

/**
 * Sends data to the NaCl plugin.
 * @param {!string|!MediaStreamTrack} data Command to be sent to NaCl plugin.
 * @private
 */
NaClManager.prototype.sendDataToPlugin_ = function(data) {
  assert(this.recognizerState_ != ManagerState_.UNINITIALIZED,
         'Recognizer in uninitialized state');
  this.plugin_.postMessage(data);
};

/**
 * Waits, with a timeout, for a message to be received from the plugin. If the
 * message is not seen within the timeout, dispatch an 'error' event and go into
 * the ERROR state.
 * @param {number} timeout Timeout, in milliseconds, to wait for the message.
 * @param {!string} message Message to wait for.
 * @private
 */
NaClManager.prototype.waitForMessage_ = function(timeout, message) {
  assert(this.expectingMessage_ == null,
         'Already waiting for message ' + this.expectingMessage_);
  this.setTimeout_(
      function() {
        this.recognizerState_ = ManagerState_.ERROR;
        this.handleError_(Error_.TIMEOUT);
        switch (this.expectingMessage_) {
          case hotword.constants.NaClPlugin.REQUEST_MODEL:
            var metricValue = UmaNaClMessageTimeout_.REQUEST_MODEL;
            break;
          case hotword.constants.NaClPlugin.MODEL_LOADED:
            var metricValue = UmaNaClMessageTimeout_.MODEL_LOADED;
            break;
          case hotword.constants.NaClPlugin.READY_FOR_AUDIO:
            var metricValue = UmaNaClMessageTimeout_.READY_FOR_AUDIO;
            break;
          case hotword.constants.NaClPlugin.STOPPED:
            var metricValue = UmaNaClMessageTimeout_.STOPPED;
            break;
          case hotword.constants.NaClPlugin.HOTWORD_DETECTED:
            var metricValue = UmaNaClMessageTimeout_.HOTWORD_DETECTED;
            break;
          case hotword.constants.NaClPlugin.MS_CONFIGURED:
            var metricValue = UmaNaClMessageTimeout_.MS_CONFIGURED;
            break;
        }
        hotword.metrics.recordEnum(
            hotword.constants.UmaMetrics.NACL_MESSAGE_TIMEOUT,
            metricValue,
            UmaNaClMessageTimeout_.MAX);
      }.bind(this), timeout);
  this.expectingMessage_ = message;
};

/**
 * Called when a message is received from the plugin. If we're waiting for that
 * message, cancel the pending timeout.
 * @param {string} message Message received.
 * @private
 */
NaClManager.prototype.receivedMessage_ = function(message) {
  if (message == this.expectingMessage_) {
    this.clearTimeout_();
    this.expectingMessage_ = null;
  }
};

/**
 * Handle a REQUEST_MODEL message from the plugin.
 * The plugin sends this message immediately after starting.
 * @private
 */
NaClManager.prototype.handleRequestModel_ = function() {
  if (this.recognizerState_ != ManagerState_.LOADING) {
    return;
  }
  this.logPluginLoadResult_(UmaNaClPluginLoadResult_.SUCCESS);
  this.sendDataToPlugin_(
      hotword.constants.NaClPlugin.MODEL_PREFIX + this.modelUrl_);
  this.waitForMessage_(hotword.constants.TimeoutMs.LONG,
                       hotword.constants.NaClPlugin.MODEL_LOADED);
};

/**
 * Handle a MODEL_LOADED message from the plugin.
 * The plugin sends this message after successfully loading the language model.
 * @private
 */
NaClManager.prototype.handleModelLoaded_ = function() {
  if (this.recognizerState_ != ManagerState_.LOADING) {
    return;
  }
  this.sendDataToPlugin_(this.stream_.getAudioTracks()[0]);
  this.waitForMessage_(hotword.constants.TimeoutMs.LONG,
                       hotword.constants.NaClPlugin.MS_CONFIGURED);
};

/**
 * Handle a MS_CONFIGURED message from the plugin.
 * The plugin sends this message after successfully configuring the audio input
 * stream.
 * @private
 */
NaClManager.prototype.handleMsConfigured_ = function() {
  if (this.recognizerState_ != ManagerState_.LOADING) {
    return;
  }
  this.recognizerState_ = ManagerState_.STOPPED;
  this.dispatchEvent(new Event(hotword.constants.Event.READY));
};

/**
 * Handle a READY_FOR_AUDIO message from the plugin.
 * The plugin sends this message after the recognizer is started and
 * successfully receives and processes audio data.
 * @private
 */
NaClManager.prototype.handleReadyForAudio_ = function() {
  if (this.recognizerState_ != ManagerState_.STARTING) {
    return;
  }
  this.recognizerState_ = ManagerState_.RUNNING;
};

/**
 * Handle a HOTWORD_DETECTED message from the plugin.
 * The plugin sends this message after detecting the hotword.
 * @private
 */
NaClManager.prototype.handleHotwordDetected_ = function() {
  if (this.recognizerState_ != ManagerState_.RUNNING) {
    return;
  }
  // We'll receive a STOPPED message very soon.
  this.recognizerState_ = ManagerState_.STOPPING;
  this.waitForMessage_(hotword.constants.TimeoutMs.NORMAL,
                       hotword.constants.NaClPlugin.STOPPED);
  this.dispatchEvent(new Event(hotword.constants.Event.TRIGGER));
};

/**
 * Handle a STOPPED message from the plugin.
 * This plugin sends this message after stopping the recognizer. This can happen
 * either in response to a stop request, or after the hotword is detected.
 * @private
 */
NaClManager.prototype.handleStopped_ = function() {
  this.recognizerState_ = ManagerState_.STOPPED;
  if (this.restartOnStop_) {
    this.restartOnStop_ = false;
    this.startRecognizer();
  }
};

/**
 * Handles a message from the NaCl plugin.
 * @param {!Event} msg Message from NaCl plugin.
 * @private
 */
NaClManager.prototype.handlePluginMessage_ = function(msg) {
  if (msg['data']) {
    this.receivedMessage_(msg['data']);
    switch (msg['data']) {
      case hotword.constants.NaClPlugin.REQUEST_MODEL:
        this.handleRequestModel_();
        break;
      case hotword.constants.NaClPlugin.MODEL_LOADED:
        this.handleModelLoaded_();
        break;
      case hotword.constants.NaClPlugin.MS_CONFIGURED:
        this.handleMsConfigured_();
        break;
      case hotword.constants.NaClPlugin.READY_FOR_AUDIO:
        this.handleReadyForAudio_();
        break;
      case hotword.constants.NaClPlugin.HOTWORD_DETECTED:
        this.handleHotwordDetected_();
        break;
      case hotword.constants.NaClPlugin.STOPPED:
        this.handleStopped_();
        break;
    }
  }
};

return {
  NaClManager: NaClManager
};

});