Debian Codegraph @

core/java/android/service/voice/HotwordDetectionService.java

raw symbols SCIP
1 /*
2 * Copyright (C) 2020 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package android.service.voice;
18
19 import static java.util.Objects.requireNonNull;
20
21 import android.annotation.DurationMillisLong;
22 import android.annotation.IntDef;
23 import android.annotation.NonNull;
24 import android.annotation.Nullable;
25 import android.annotation.SdkConstant;
26 import android.annotation.SuppressLint;
27 import android.annotation.SystemApi;
28 import android.app.Service;
29 import android.content.ContentCaptureOptions;
30 import android.content.Context;
31 import android.content.Intent;
32 import android.hardware.soundtrigger.SoundTrigger;
33 import android.media.AudioFormat;
34 import android.media.AudioSystem;
35 import android.os.Bundle;
36 import android.os.IBinder;
37 import android.os.IRemoteCallback;
38 import android.os.ParcelFileDescriptor;
39 import android.os.PersistableBundle;
40 import android.os.RemoteException;
41 import android.os.SharedMemory;
42 import android.util.Log;
43 import android.view.contentcapture.ContentCaptureManager;
44 import android.view.contentcapture.IContentCaptureManager;
45
46 import java.lang.annotation.Documented;
47 import java.lang.annotation.Retention;
48 import java.lang.annotation.RetentionPolicy;
49 import java.util.Locale;
50 import java.util.function.IntConsumer;
51
52 /**
53 * Implemented by an application that wants to offer detection for hotword. The service can be used
54 * for both DSP and non-DSP detectors.
55 *
56 * The system will bind an application's {@link VoiceInteractionService} first. When {@link
57 * VoiceInteractionService#createHotwordDetector(PersistableBundle, SharedMemory,
58 * HotwordDetector.Callback)} or {@link VoiceInteractionService#createAlwaysOnHotwordDetector(
59 * String, Locale, PersistableBundle, SharedMemory, AlwaysOnHotwordDetector.Callback)} is called,
60 * the system will bind application's {@link HotwordDetectionService}. Either on a hardware
61 * trigger or on request from the {@link VoiceInteractionService}, the system calls into the
62 * {@link HotwordDetectionService} to request detection. The {@link HotwordDetectionService} then
63 * uses {@link Callback#onDetected(HotwordDetectedResult)} to inform the system that a relevant
64 * keyphrase was detected, or if applicable uses {@link Callback#onRejected(HotwordRejectedResult)}
65 * to inform the system that a keyphrase was not detected. The system then relays this result to
66 * the {@link VoiceInteractionService} through {@link HotwordDetector.Callback}.
67 *
68 * Note: Methods in this class may be called concurrently
69 *
70 * @hide
71 */
72 @SystemApi
73 public abstract class HotwordDetectionService extends Service {
74 private static final String TAG = "HotwordDetectionService";
75 private static final boolean DBG = false;
76
77 private static final long UPDATE_TIMEOUT_MILLIS = 20000;
78
79 /** @hide */
80 public static final String KEY_INITIALIZATION_STATUS = "initialization_status";
81
82 /**
83 * The maximum number of initialization status for some application specific failed reasons.
84 *
85 * @hide
86 */
87 public static final int MAXIMUM_NUMBER_OF_INITIALIZATION_STATUS_CUSTOM_ERROR = 2;
88
89 /**
90 * Feature flag for Attention Service.
91 *
92 * TODO(b/247920386): Add TestApi annotation
93 * @hide
94 */
95 public static final boolean ENABLE_PROXIMITY_RESULT = true;
96
97 /**
98 * Indicates that the updated status is successful.
99 */
100 public static final int INITIALIZATION_STATUS_SUCCESS = 0;
101
102 /**
103 * Indicates that the callback wasn’t invoked within the timeout.
104 * This is used by system.
105 */
106 public static final int INITIALIZATION_STATUS_UNKNOWN = 100;
107
108 /**
109 * Source for the given audio stream.
110 *
111 * @hide
112 */
113 @Documented
114 @Retention(RetentionPolicy.SOURCE)
115 @IntDef({
116 AUDIO_SOURCE_MICROPHONE,
117 AUDIO_SOURCE_EXTERNAL
118 })
119 @interface AudioSource {}
120
121 /** @hide */
122 public static final int AUDIO_SOURCE_MICROPHONE = 1;
123 /** @hide */
124 public static final int AUDIO_SOURCE_EXTERNAL = 2;
125
126 /**
127 * The {@link Intent} that must be declared as handled by the service.
128 * To be supported, the service must also require the
129 * {@link android.Manifest.permission#BIND_HOTWORD_DETECTION_SERVICE} permission so
130 * that other applications can not abuse it.
131 */
132 @SdkConstant(SdkConstant.SdkConstantType.SERVICE_ACTION)
133 public static final String SERVICE_INTERFACE =
134 "android.service.voice.HotwordDetectionService";
135
136 @Nullable
137 private ContentCaptureManager mContentCaptureManager;
138
139 private final IHotwordDetectionService mInterface = new IHotwordDetectionService.Stub() {
140 @Override
141 public void detectFromDspSource(
142 SoundTrigger.KeyphraseRecognitionEvent event,
143 AudioFormat audioFormat,
144 long timeoutMillis,
145 IDspHotwordDetectionCallback callback)
146 throws RemoteException {
147 if (DBG) {
148 Log.d(TAG, "#detectFromDspSource");
149 }
150 HotwordDetectionService.this.onDetect(
151 new AlwaysOnHotwordDetector.EventPayload.Builder(event).build(),
152 timeoutMillis,
153 new Callback(callback));
154 }
155
156 @Override
157 public void updateState(PersistableBundle options, SharedMemory sharedMemory,
158 IRemoteCallback callback) throws RemoteException {
159 Log.v(TAG, "#updateState" + (callback != null ? " with callback" : ""));
160 HotwordDetectionService.this.onUpdateStateInternal(
161 options,
162 sharedMemory,
163 callback);
164 }
165
166 @Override
167 public void detectFromMicrophoneSource(
168 ParcelFileDescriptor audioStream,
169 @AudioSource int audioSource,
170 AudioFormat audioFormat,
171 PersistableBundle options,
172 IDspHotwordDetectionCallback callback)
173 throws RemoteException {
174 if (DBG) {
175 Log.d(TAG, "#detectFromMicrophoneSource");
176 }
177 switch (audioSource) {
178 case AUDIO_SOURCE_MICROPHONE:
179 HotwordDetectionService.this.onDetect(
180 new Callback(callback));
181 break;
182 case AUDIO_SOURCE_EXTERNAL:
183 HotwordDetectionService.this.onDetect(
184 audioStream,
185 audioFormat,
186 options,
187 new Callback(callback));
188 break;
189 default:
190 Log.i(TAG, "Unsupported audio source " + audioSource);
191 }
192 }
193
194 @Override
195 public void updateAudioFlinger(IBinder audioFlinger) {
196 AudioSystem.setAudioFlingerBinder(audioFlinger);
197 }
198
199 @Override
200 public void updateContentCaptureManager(IContentCaptureManager manager,
201 ContentCaptureOptions options) {
202 mContentCaptureManager = new ContentCaptureManager(
203 HotwordDetectionService.this, manager, options);
204 }
205
206 @Override
207 public void ping(IRemoteCallback callback) throws RemoteException {
208 callback.sendResult(null);
209 }
210
211 @Override
212 public void stopDetection() {
213 HotwordDetectionService.this.onStopDetection();
214 }
215 };
216
217 @Override
218 @Nullable
219 public final IBinder onBind(@NonNull Intent intent) {
220 if (SERVICE_INTERFACE.equals(intent.getAction())) {
221 return mInterface.asBinder();
222 }
223 Log.w(TAG, "Tried to bind to wrong intent (should be " + SERVICE_INTERFACE + ": "
224 + intent);
225 return null;
226 }
227
228 @Override
229 @SuppressLint("OnNameExpected")
230 public @Nullable Object getSystemService(@ServiceName @NonNull String name) {
231 if (Context.CONTENT_CAPTURE_MANAGER_SERVICE.equals(name)) {
232 return mContentCaptureManager;
233 } else {
234 return super.getSystemService(name);
235 }
236 }
237
238 /**
239 * Returns the maximum number of initialization status for some application specific failed
240 * reasons.
241 *
242 * Note: The value 0 is reserved for success.
243 *
244 * @hide
245 */
246 @SystemApi
247 public static int getMaxCustomInitializationStatus() {
248 return MAXIMUM_NUMBER_OF_INITIALIZATION_STATUS_CUSTOM_ERROR;
249 }
250
251 /**
252 * Called when the device hardware (such as a DSP) detected the hotword, to request second stage
253 * validation before handing over the audio to the {@link AlwaysOnHotwordDetector}.
254 * <p>
255 * After {@code callback} is invoked or {@code timeoutMillis} has passed, and invokes the
256 * appropriate {@link AlwaysOnHotwordDetector.Callback callback}.
257 *
258 * @param eventPayload Payload data for the hardware detection event. This may contain the
259 * trigger audio, if requested when calling
260 * {@link AlwaysOnHotwordDetector#startRecognition(int)}.
261 * @param timeoutMillis Timeout in milliseconds for the operation to invoke the callback. If
262 * the application fails to abide by the timeout, system will close the
263 * microphone and cancel the operation.
264 * @param callback The callback to use for responding to the detection request.
265 *
266 * @hide
267 */
268 @SystemApi
269 public void onDetect(
270 @NonNull AlwaysOnHotwordDetector.EventPayload eventPayload,
271 @DurationMillisLong long timeoutMillis,
272 @NonNull Callback callback) {
273 // TODO: Add a helpful error message.
274 throw new UnsupportedOperationException();
275 }
276
277 /**
278 * Called when the {@link VoiceInteractionService#createAlwaysOnHotwordDetector(String, Locale,
279 * PersistableBundle, SharedMemory, AlwaysOnHotwordDetector.Callback)} or
280 * {@link AlwaysOnHotwordDetector#updateState(PersistableBundle, SharedMemory)} requests an
281 * update of the hotword detection parameters.
282 *
283 * @param options Application configuration data to provide to the
284 * {@link HotwordDetectionService}. PersistableBundle does not allow any remotable objects or
285 * other contents that can be used to communicate with other processes.
286 * @param sharedMemory The unrestricted data blob to provide to the
287 * {@link HotwordDetectionService}. Use this to provide the hotword models data or other
288 * such data to the trusted process.
289 * @param callbackTimeoutMillis Timeout in milliseconds for the operation to invoke the
290 * statusCallback.
291 * @param statusCallback Use this to return the updated result; the allowed values are
292 * {@link #INITIALIZATION_STATUS_SUCCESS}, 1<->{@link #getMaxCustomInitializationStatus()}.
293 * This is non-null only when the {@link HotwordDetectionService} is being initialized; and it
294 * is null if the state is updated after that.
295 *
296 * @hide
297 */
298 @SystemApi
299 public void onUpdateState(
300 @Nullable PersistableBundle options,
301 @Nullable SharedMemory sharedMemory,
302 @DurationMillisLong long callbackTimeoutMillis,
303 @Nullable IntConsumer statusCallback) {}
304
305 /**
306 * Called when the {@link VoiceInteractionService} requests that this service
307 * {@link HotwordDetector#startRecognition() start} hotword recognition on audio coming directly
308 * from the device microphone.
309 * <p>
310 * On successful detection of a hotword, call
311 * {@link Callback#onDetected(HotwordDetectedResult)}.
312 *
313 * @param callback The callback to use for responding to the detection request.
314 * {@link Callback#onRejected(HotwordRejectedResult) callback.onRejected} cannot be used here.
315 */
316 public void onDetect(@NonNull Callback callback) {
317 // TODO: Add a helpful error message.
318 throw new UnsupportedOperationException();
319 }
320
321 /**
322 * Called when the {@link VoiceInteractionService} requests that this service
323 * {@link HotwordDetector#startRecognition(ParcelFileDescriptor, AudioFormat,
324 * PersistableBundle)} run} hotword recognition on audio coming from an external connected
325 * microphone.
326 * <p>
327 * Upon invoking the {@code callback}, the system closes {@code audioStream} and sends the
328 * detection result to the {@link HotwordDetector.Callback hotword detector}.
329 *
330 * @param audioStream Stream containing audio bytes returned from a microphone
331 * @param audioFormat Format of the supplied audio
332 * @param options Options supporting detection, such as configuration specific to the source of
333 * the audio, provided through
334 * {@link HotwordDetector#startRecognition(ParcelFileDescriptor, AudioFormat,
335 * PersistableBundle)}.
336 * @param callback The callback to use for responding to the detection request.
337 */
338 public void onDetect(
339 @NonNull ParcelFileDescriptor audioStream,
340 @NonNull AudioFormat audioFormat,
341 @Nullable PersistableBundle options,
342 @NonNull Callback callback) {
343 // TODO: Add a helpful error message.
344 throw new UnsupportedOperationException();
345 }
346
347 private void onUpdateStateInternal(@Nullable PersistableBundle options,
348 @Nullable SharedMemory sharedMemory, IRemoteCallback callback) {
349 IntConsumer intConsumer = null;
350 if (callback != null) {
351 intConsumer =
352 value -> {
353 if (value > getMaxCustomInitializationStatus()) {
354 throw new IllegalArgumentException(
355 "The initialization status is invalid for " + value);
356 }
357 try {
358 Bundle status = new Bundle();
359 status.putInt(KEY_INITIALIZATION_STATUS, value);
360 callback.sendResult(status);
361 } catch (RemoteException e) {
362 throw e.rethrowFromSystemServer();
363 }
364 };
365 }
366 onUpdateState(options, sharedMemory, UPDATE_TIMEOUT_MILLIS, intConsumer);
367 }
368
369 /**
370 * Called when the {@link VoiceInteractionService}
371 * {@link HotwordDetector#stopRecognition() requests} that hotword recognition be stopped.
372 * <p>
373 * Any open {@link android.media.AudioRecord} should be closed here.
374 */
375 public void onStopDetection() {
376 }
377
378 /**
379 * Callback for returning the detection result.
380 *
381 * @hide
382 */
383 @SystemApi
384 public static final class Callback {
385 // TODO: need to make sure we don't store remote references, but not a high priority.
386 private final IDspHotwordDetectionCallback mRemoteCallback;
387
388 private Callback(IDspHotwordDetectionCallback remoteCallback) {
389 mRemoteCallback = remoteCallback;
390 }
391
392 /**
393 * Informs the {@link HotwordDetector} that the keyphrase was detected.
394 *
395 * @param result Info about the detection result. This is provided to the
396 * {@link HotwordDetector}.
397 */
398 public void onDetected(@NonNull HotwordDetectedResult result) {
399 requireNonNull(result);
400 final PersistableBundle persistableBundle = result.getExtras();
401 if (!persistableBundle.isEmpty() && HotwordDetectedResult.getParcelableSize(
402 persistableBundle) > HotwordDetectedResult.getMaxBundleSize()) {
403 throw new IllegalArgumentException(
404 "The bundle size of result is larger than max bundle size ("
405 + HotwordDetectedResult.getMaxBundleSize()
406 + ") of HotwordDetectedResult");
407 }
408 try {
409 mRemoteCallback.onDetected(result);
410 } catch (RemoteException e) {
411 throw e.rethrowFromSystemServer();
412 }
413 }
414
415 /**
416 * Informs the {@link HotwordDetector} that the keyphrase was not detected.
417 * <p>
418 * This cannot not be used when recognition is done through
419 * {@link #onDetect(ParcelFileDescriptor, AudioFormat, Callback)}.
420 *
421 * @param result Info about the second stage detection result. This is provided to
422 * the {@link HotwordDetector}.
423 */
424 public void onRejected(@NonNull HotwordRejectedResult result) {
425 requireNonNull(result);
426 try {
427 mRemoteCallback.onRejected(result);
428 } catch (RemoteException e) {
429 throw e.rethrowFromSystemServer();
430 }
431 }
432 }
433 }