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
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
|
/**
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.server.soundtrigger;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.soundtrigger.IRecognitionStatusCallback;
import android.hardware.soundtrigger.ModelParams;
import android.hardware.soundtrigger.SoundTrigger;
import android.hardware.soundtrigger.SoundTrigger.GenericRecognitionEvent;
import android.hardware.soundtrigger.SoundTrigger.GenericSoundModel;
import android.hardware.soundtrigger.SoundTrigger.Keyphrase;
import android.hardware.soundtrigger.SoundTrigger.KeyphraseRecognitionEvent;
import android.hardware.soundtrigger.SoundTrigger.KeyphraseRecognitionExtra;
import android.hardware.soundtrigger.SoundTrigger.KeyphraseSoundModel;
import android.hardware.soundtrigger.SoundTrigger.ModelParamRange;
import android.hardware.soundtrigger.SoundTrigger.ModuleProperties;
import android.hardware.soundtrigger.SoundTrigger.RecognitionConfig;
import android.hardware.soundtrigger.SoundTrigger.RecognitionEvent;
import android.hardware.soundtrigger.SoundTrigger.SoundModel;
import android.hardware.soundtrigger.SoundTriggerModule;
import android.os.Binder;
import android.os.DeadObjectException;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.PowerManager;
import android.os.PowerManager.SoundTriggerPowerSaveMode;
import android.os.RemoteException;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Slog;
import com.android.internal.logging.MetricsLogger;
import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
/**
* Helper for {@link SoundTrigger} APIs. Supports two types of models:
* (i) A voice model which is exported via the {@link VoiceInteractionService}. There can only be
* a single voice model running on the DSP at any given time.
*
* (ii) Generic sound-trigger models: Supports multiple of these.
*
* Currently this just acts as an abstraction over all SoundTrigger API calls.
* @hide
*/
public class SoundTriggerHelper implements SoundTrigger.StatusListener {
static final String TAG = "SoundTriggerHelper";
static final boolean DBG = false;
/**
* Return codes for {@link #startRecognition(int, KeyphraseSoundModel,
* IRecognitionStatusCallback, RecognitionConfig)},
* {@link #stopRecognition(int, IRecognitionStatusCallback)}
*/
public static final int STATUS_ERROR = SoundTrigger.STATUS_ERROR;
public static final int STATUS_OK = SoundTrigger.STATUS_OK;
private static final int INVALID_VALUE = Integer.MIN_VALUE;
/** The {@link ModuleProperties} for the system, or null if none exists. */
final ModuleProperties mModuleProperties;
/** The properties for the DSP module */
private SoundTriggerModule mModule;
private final Object mLock = new Object();
private final Context mContext;
private final TelephonyManager mTelephonyManager;
private final PhoneStateListener mPhoneStateListener;
private final PowerManager mPowerManager;
// The SoundTriggerManager layer handles multiple recognition models of type generic and
// keyphrase. We store the ModelData here in a hashmap.
private final HashMap<UUID, ModelData> mModelDataMap;
// An index of keyphrase sound models so that we can reach them easily. We support indexing
// keyphrase sound models with a keyphrase ID. Sound model with the same keyphrase ID will
// replace an existing model, thus there is a 1:1 mapping from keyphrase ID to a voice
// sound model.
private HashMap<Integer, UUID> mKeyphraseUuidMap;
private boolean mCallActive = false;
private @SoundTriggerPowerSaveMode int mSoundTriggerPowerSaveMode =
PowerManager.SOUND_TRIGGER_MODE_ALL_ENABLED;
// Whether ANY recognition (keyphrase or generic) has been requested.
private boolean mRecognitionRequested = false;
private PowerSaveModeListener mPowerSaveModeListener;
private final SoundTriggerModuleProvider mModuleProvider;
// Handler to process call state changes will delay to allow time for the audio
// and sound trigger HALs to process the end of call notifications
// before we re enable pending recognition requests.
private final Handler mHandler;
private static final int MSG_CALL_STATE_CHANGED = 0;
private static final int CALL_INACTIVE_MSG_DELAY_MS = 1000;
/**
* Provider interface for retrieving SoundTriggerModule instances
*/
public interface SoundTriggerModuleProvider {
/**
* Populate module properties for all available modules
*
* @param modules List of ModuleProperties to be populated
* @return Status int 0 on success.
*/
int listModuleProperties(@NonNull ArrayList<SoundTrigger.ModuleProperties> modules);
/**
* Get SoundTriggerModule based on {@link SoundTrigger.ModuleProperties#getId()}
*
* @param moduleId Module ID
* @param statusListener Client listener to be associated with the returned module
* @return Module associated with moduleId
*/
SoundTriggerModule getModule(int moduleId, SoundTrigger.StatusListener statusListener);
}
SoundTriggerHelper(Context context, SoundTriggerModuleProvider moduleProvider) {
ArrayList <ModuleProperties> modules = new ArrayList<>();
mModuleProvider = moduleProvider;
int status = mModuleProvider.listModuleProperties(modules);
mContext = context;
mTelephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
mModelDataMap = new HashMap<UUID, ModelData>();
mKeyphraseUuidMap = new HashMap<Integer, UUID>();
if (status != SoundTrigger.STATUS_OK || modules.size() == 0) {
Slog.w(TAG, "listModules status=" + status + ", # of modules=" + modules.size());
mModuleProperties = null;
mModule = null;
} else {
// TODO: Figure out how to determine which module corresponds to the DSP hardware.
mModuleProperties = modules.get(0);
}
Looper looper = Looper.myLooper();
if (looper == null) {
looper = Looper.getMainLooper();
}
mPhoneStateListener = new MyCallStateListener(looper);
if (looper != null) {
mHandler = new Handler(looper) {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_CALL_STATE_CHANGED:
synchronized (mLock) {
onCallStateChangedLocked(
TelephonyManager.CALL_STATE_OFFHOOK == msg.arg1);
}
break;
default:
Slog.e(TAG, "unknown message in handler:" + msg.what);
break;
}
}
};
} else {
mHandler = null;
}
}
/**
* Starts recognition for the given generic sound model ID. This is a wrapper around {@link
* startRecognition()}.
*
* @param modelId UUID of the sound model.
* @param soundModel The generic sound model to use for recognition.
* @param callback Callack for the recognition events related to the given keyphrase.
* @param recognitionConfig Instance of RecognitionConfig containing the parameters for the
* recognition.
* @return One of {@link #STATUS_ERROR} or {@link #STATUS_OK}.
*/
int startGenericRecognition(UUID modelId, GenericSoundModel soundModel,
IRecognitionStatusCallback callback, RecognitionConfig recognitionConfig,
boolean runInBatterySaverMode) {
MetricsLogger.count(mContext, "sth_start_recognition", 1);
if (modelId == null || soundModel == null || callback == null ||
recognitionConfig == null) {
Slog.w(TAG, "Passed in bad data to startGenericRecognition().");
return STATUS_ERROR;
}
synchronized (mLock) {
ModelData modelData = getOrCreateGenericModelDataLocked(modelId);
if (modelData == null) {
Slog.w(TAG, "Irrecoverable error occurred, check UUID / sound model data.");
return STATUS_ERROR;
}
return startRecognition(soundModel, modelData, callback, recognitionConfig,
INVALID_VALUE /* keyphraseId */, runInBatterySaverMode);
}
}
/**
* Starts recognition for the given keyphraseId.
*
* @param keyphraseId The identifier of the keyphrase for which
* the recognition is to be started.
* @param soundModel The sound model to use for recognition.
* @param callback The callback for the recognition events related to the given keyphrase.
* @return One of {@link #STATUS_ERROR} or {@link #STATUS_OK}.
*/
int startKeyphraseRecognition(int keyphraseId, KeyphraseSoundModel soundModel,
IRecognitionStatusCallback callback, RecognitionConfig recognitionConfig,
boolean runInBatterySaverMode) {
synchronized (mLock) {
MetricsLogger.count(mContext, "sth_start_recognition", 1);
if (soundModel == null || callback == null || recognitionConfig == null) {
return STATUS_ERROR;
}
if (DBG) {
Slog.d(TAG, "startKeyphraseRecognition for keyphraseId=" + keyphraseId
+ " soundModel=" + soundModel + ", callback=" + callback.asBinder()
+ ", recognitionConfig=" + recognitionConfig
+ ", runInBatterySaverMode=" + runInBatterySaverMode);
Slog.d(TAG, "moduleProperties=" + mModuleProperties);
dumpModelStateLocked();
}
ModelData model = getKeyphraseModelDataLocked(keyphraseId);
if (model != null && !model.isKeyphraseModel()) {
Slog.e(TAG, "Generic model with same UUID exists.");
return STATUS_ERROR;
}
// Process existing model first.
if (model != null && !model.getModelId().equals(soundModel.getUuid())) {
// The existing model has a different UUID, should be replaced.
int status = cleanUpExistingKeyphraseModelLocked(model);
if (status != STATUS_OK) {
return status;
}
removeKeyphraseModelLocked(keyphraseId);
model = null;
}
// We need to create a new one: either no previous models existed for given keyphrase id
// or the existing model had a different UUID and was cleaned up.
if (model == null) {
model = createKeyphraseModelDataLocked(soundModel.getUuid(), keyphraseId);
}
return startRecognition(soundModel, model, callback, recognitionConfig,
keyphraseId, runInBatterySaverMode);
}
}
private int cleanUpExistingKeyphraseModelLocked(ModelData modelData) {
// Stop and clean up a previous ModelData if one exists. This usually is used when the
// previous model has a different UUID for the same keyphrase ID.
int status = tryStopAndUnloadLocked(modelData, true /* stop */, true /* unload */);
if (status != STATUS_OK) {
Slog.w(TAG, "Unable to stop or unload previous model: " +
modelData.toString());
}
return status;
}
private int prepareForRecognition(ModelData modelData) {
if (mModule == null) {
mModule = mModuleProvider.getModule(mModuleProperties.getId(), this);
if (mModule == null) {
Slog.w(TAG, "prepareForRecognition: cannot attach to sound trigger module");
return STATUS_ERROR;
}
}
// Load the model if it is not loaded.
if (!modelData.isModelLoaded()) {
// Before we try and load this model, we should first make sure that any other
// models that don't have an active recognition/dead callback are unloaded. Since
// there is a finite limit on the number of models that the hardware may be able to
// have loaded, we want to make sure there's room for our model.
stopAndUnloadDeadModelsLocked();
int[] handle = new int[] { 0 };
int status = mModule.loadSoundModel(modelData.getSoundModel(), handle);
if (status != SoundTrigger.STATUS_OK) {
Slog.w(TAG, "prepareForRecognition: loadSoundModel failed with status: " + status);
return status;
}
modelData.setHandle(handle[0]);
modelData.setLoaded();
if (DBG) {
Slog.d(TAG, "prepareForRecognition: Sound model loaded with handle:" + handle[0]);
}
}
return STATUS_OK;
}
/**
* Starts recognition for the given sound model. A single routine for both keyphrase and
* generic sound models.
*
* @param soundModel The sound model to use for recognition.
* @param modelData Instance of {@link #ModelData} for the given model.
* @param callback Callback for the recognition events related to the given keyphrase.
* @param recognitionConfig Instance of {@link RecognitionConfig} containing the parameters
* @param keyphraseId Keyphrase ID for keyphrase models only. Pass in INVALID_VALUE for other
* models.
* for the recognition.
* @return One of {@link #STATUS_ERROR} or {@link #STATUS_OK}.
*/
int startRecognition(SoundModel soundModel, ModelData modelData,
IRecognitionStatusCallback callback, RecognitionConfig recognitionConfig,
int keyphraseId, boolean runInBatterySaverMode) {
synchronized (mLock) {
if (mModuleProperties == null) {
Slog.w(TAG, "Attempting startRecognition without the capability");
return STATUS_ERROR;
}
IRecognitionStatusCallback oldCallback = modelData.getCallback();
if (oldCallback != null && oldCallback.asBinder() != callback.asBinder()) {
Slog.w(TAG, "Canceling previous recognition for model id: "
+ modelData.getModelId());
try {
oldCallback.onError(STATUS_ERROR);
} catch (RemoteException e) {
Slog.w(TAG, "RemoteException in onDetectionStopped", e);
}
modelData.clearCallback();
}
// If the existing SoundModel is different (for the same UUID for Generic and same
// keyphrase ID for voice), ensure that it is unloaded and stopped before proceeding.
// This works for both keyphrase and generic models. This logic also ensures that a
// previously loaded (or started) model is appropriately stopped. Since this is a
// generalization of the previous logic with a single keyphrase model, we should have
// no regression with the previous version of this code as was given in the
// startKeyphrase() routine.
if (modelData.getSoundModel() != null) {
boolean stopModel = false; // Stop the model after checking that it is started.
boolean unloadModel = false;
if (modelData.getSoundModel().equals(soundModel) && modelData.isModelStarted()) {
// The model has not changed, but the previous model is "started".
// Stop the previously running model.
stopModel = true;
unloadModel = false; // No need to unload if the model hasn't changed.
} else if (!modelData.getSoundModel().equals(soundModel)) {
// We have a different model for this UUID. Stop and unload if needed. This
// helps maintain the singleton restriction for keyphrase sound models.
stopModel = modelData.isModelStarted();
unloadModel = modelData.isModelLoaded();
}
if (stopModel || unloadModel) {
int status = tryStopAndUnloadLocked(modelData, stopModel, unloadModel);
if (status != STATUS_OK) {
Slog.w(TAG, "Unable to stop or unload previous model: " +
modelData.toString());
return status;
}
}
}
modelData.setCallback(callback);
modelData.setRequested(true);
modelData.setRecognitionConfig(recognitionConfig);
modelData.setRunInBatterySaverMode(runInBatterySaverMode);
modelData.setSoundModel(soundModel);
if (!isRecognitionAllowedByDeviceState(modelData)) {
initializeDeviceStateListeners();
return STATUS_OK;
}
return updateRecognitionLocked(modelData,
false /* Don't notify for synchronous calls */);
}
}
/**
* Stops recognition for the given generic sound model. This is a wrapper for {@link
* #stopRecognition}.
*
* @param modelId The identifier of the generic sound model for which
* the recognition is to be stopped.
* @param callback The callback for the recognition events related to the given sound model.
*
* @return One of {@link #STATUS_ERROR} or {@link #STATUS_OK}.
*/
int stopGenericRecognition(UUID modelId, IRecognitionStatusCallback callback) {
synchronized (mLock) {
MetricsLogger.count(mContext, "sth_stop_recognition", 1);
if (callback == null || modelId == null) {
Slog.e(TAG, "Null callbackreceived for stopGenericRecognition() for modelid:" +
modelId);
return STATUS_ERROR;
}
ModelData modelData = mModelDataMap.get(modelId);
if (modelData == null || !modelData.isGenericModel()) {
Slog.w(TAG, "Attempting stopRecognition on invalid model with id:" + modelId);
return STATUS_ERROR;
}
int status = stopRecognition(modelData, callback);
if (status != SoundTrigger.STATUS_OK) {
Slog.w(TAG, "stopGenericRecognition failed: " + status);
}
return status;
}
}
/**
* Stops recognition for the given {@link Keyphrase} if a recognition is
* currently active. This is a wrapper for {@link #stopRecognition()}.
*
* @param keyphraseId The identifier of the keyphrase for which
* the recognition is to be stopped.
* @param callback The callback for the recognition events related to the given keyphrase.
*
* @return One of {@link #STATUS_ERROR} or {@link #STATUS_OK}.
*/
int stopKeyphraseRecognition(int keyphraseId, IRecognitionStatusCallback callback) {
synchronized (mLock) {
MetricsLogger.count(mContext, "sth_stop_recognition", 1);
if (callback == null) {
Slog.e(TAG, "Null callback received for stopKeyphraseRecognition() for keyphraseId:" +
keyphraseId);
return STATUS_ERROR;
}
ModelData modelData = getKeyphraseModelDataLocked(keyphraseId);
if (modelData == null || !modelData.isKeyphraseModel()) {
Slog.w(TAG, "No model exists for given keyphrase Id " + keyphraseId);
return STATUS_ERROR;
}
if (DBG) {
Slog.d(TAG, "stopRecognition for keyphraseId=" + keyphraseId + ", callback =" +
callback.asBinder());
Slog.d(TAG, "current callback="
+ ((modelData == null || modelData.getCallback() == null) ? "null" :
modelData.getCallback().asBinder()));
}
int status = stopRecognition(modelData, callback);
if (status != SoundTrigger.STATUS_OK) {
return status;
}
return status;
}
}
/**
* Stops recognition for the given ModelData instance.
*
* @param modelData Instance of {@link #ModelData} sound model.
* @param callback The callback for the recognition events related to the given keyphrase.
* @return One of {@link #STATUS_ERROR} or {@link #STATUS_OK}.
*/
private int stopRecognition(ModelData modelData, IRecognitionStatusCallback callback) {
synchronized (mLock) {
if (callback == null) {
return STATUS_ERROR;
}
if (mModuleProperties == null || mModule == null) {
Slog.w(TAG, "Attempting stopRecognition without the capability");
return STATUS_ERROR;
}
IRecognitionStatusCallback currentCallback = modelData.getCallback();
if (modelData == null || currentCallback == null ||
(!modelData.isRequested() && !modelData.isModelStarted())) {
// startGenericRecognition hasn't been called or it failed.
Slog.w(TAG, "Attempting stopRecognition without a successful startRecognition");
return STATUS_ERROR;
}
if (currentCallback.asBinder() != callback.asBinder()) {
// We don't allow a different listener to stop the recognition than the one
// that started it.
Slog.w(TAG, "Attempting stopRecognition for another recognition");
return STATUS_ERROR;
}
// Request stop recognition via the update() method.
modelData.setRequested(false);
int status = updateRecognitionLocked(modelData, false);
if (status != SoundTrigger.STATUS_OK) {
return status;
}
// We leave the sound model loaded but not started, this helps us when we start back.
// Also clear the internal state once the recognition has been stopped.
modelData.setLoaded();
modelData.clearCallback();
modelData.setRecognitionConfig(null);
if (!computeRecognitionRequestedLocked()) {
internalClearGlobalStateLocked();
}
return status;
}
}
// Stop a previously started model if it was started. Optionally, unload if the previous model
// is stale and is about to be replaced.
// Needs to be called with the mLock held.
private int tryStopAndUnloadLocked(ModelData modelData, boolean stopModel,
boolean unloadModel) {
int status = STATUS_OK;
if (modelData.isModelNotLoaded()) {
return status;
}
if (stopModel && modelData.isModelStarted()) {
status = stopRecognitionLocked(modelData,
false /* don't notify for synchronous calls */);
if (status != SoundTrigger.STATUS_OK) {
Slog.w(TAG, "stopRecognition failed: " + status);
return status;
}
}
if (unloadModel && (modelData.isModelLoaded() || modelData.isStopPending())) {
Slog.d(TAG, "Unloading previously loaded stale model.");
if (mModule == null) {
return STATUS_ERROR;
}
status = mModule.unloadSoundModel(modelData.getHandle());
MetricsLogger.count(mContext, "sth_unloading_stale_model", 1);
if (status != SoundTrigger.STATUS_OK) {
Slog.w(TAG, "unloadSoundModel call failed with " + status);
} else {
// Clear the ModelData state if successful.
modelData.clearState();
}
}
return status;
}
public ModuleProperties getModuleProperties() {
return mModuleProperties;
}
int unloadKeyphraseSoundModel(int keyphraseId) {
synchronized (mLock) {
MetricsLogger.count(mContext, "sth_unload_keyphrase_sound_model", 1);
ModelData modelData = getKeyphraseModelDataLocked(keyphraseId);
if (mModule == null || modelData == null || !modelData.isModelLoaded()
|| !modelData.isKeyphraseModel()) {
return STATUS_ERROR;
}
// Stop recognition if it's the current one.
modelData.setRequested(false);
int status = updateRecognitionLocked(modelData, false);
if (status != SoundTrigger.STATUS_OK) {
Slog.w(TAG, "Stop recognition failed for keyphrase ID:" + status);
}
status = mModule.unloadSoundModel(modelData.getHandle());
if (status != SoundTrigger.STATUS_OK) {
Slog.w(TAG, "unloadKeyphraseSoundModel call failed with " + status);
}
// Remove it from existence.
removeKeyphraseModelLocked(keyphraseId);
return status;
}
}
int unloadGenericSoundModel(UUID modelId) {
synchronized (mLock) {
MetricsLogger.count(mContext, "sth_unload_generic_sound_model", 1);
if (modelId == null || mModule == null) {
return STATUS_ERROR;
}
ModelData modelData = mModelDataMap.get(modelId);
if (modelData == null || !modelData.isGenericModel()) {
Slog.w(TAG, "Unload error: Attempting unload invalid generic model with id:" +
modelId);
return STATUS_ERROR;
}
if (!modelData.isModelLoaded()) {
// Nothing to do here.
Slog.i(TAG, "Unload: Given generic model is not loaded:" + modelId);
return STATUS_OK;
}
if (modelData.isModelStarted()) {
int status = stopRecognitionLocked(modelData,
false /* don't notify for synchronous calls */);
if (status != SoundTrigger.STATUS_OK) {
Slog.w(TAG, "stopGenericRecognition failed: " + status);
}
}
if (mModule == null) {
return STATUS_ERROR;
}
int status = mModule.unloadSoundModel(modelData.getHandle());
if (status != SoundTrigger.STATUS_OK) {
Slog.w(TAG, "unloadGenericSoundModel() call failed with " + status);
Slog.w(TAG, "unloadGenericSoundModel() force-marking model as unloaded.");
}
// Remove it from existence.
mModelDataMap.remove(modelId);
if (DBG) dumpModelStateLocked();
return status;
}
}
boolean isRecognitionRequested(UUID modelId) {
synchronized (mLock) {
ModelData modelData = mModelDataMap.get(modelId);
return modelData != null && modelData.isRequested();
}
}
int getGenericModelState(UUID modelId) {
synchronized (mLock) {
MetricsLogger.count(mContext, "sth_get_generic_model_state", 1);
if (modelId == null || mModule == null) {
return STATUS_ERROR;
}
ModelData modelData = mModelDataMap.get(modelId);
if (modelData == null || !modelData.isGenericModel()) {
Slog.w(TAG, "GetGenericModelState error: Invalid generic model id:" +
modelId);
return STATUS_ERROR;
}
if (!modelData.isModelLoaded()) {
Slog.i(TAG, "GetGenericModelState: Given generic model is not loaded:" + modelId);
return STATUS_ERROR;
}
if (!modelData.isModelStarted()) {
Slog.i(TAG, "GetGenericModelState: Given generic model is not started:" + modelId);
return STATUS_ERROR;
}
return mModule.getModelState(modelData.getHandle());
}
}
int getKeyphraseModelState(UUID modelId) {
Slog.w(TAG, "GetKeyphraseModelState error: Not implemented");
return STATUS_ERROR;
}
int setParameter(UUID modelId, @ModelParams int modelParam, int value) {
synchronized (mLock) {
return setParameterLocked(mModelDataMap.get(modelId), modelParam, value);
}
}
int setKeyphraseParameter(int keyphraseId, @ModelParams int modelParam, int value) {
synchronized (mLock) {
return setParameterLocked(getKeyphraseModelDataLocked(keyphraseId), modelParam, value);
}
}
private int setParameterLocked(@Nullable ModelData modelData, @ModelParams int modelParam,
int value) {
MetricsLogger.count(mContext, "sth_set_parameter", 1);
if (mModule == null) {
return SoundTrigger.STATUS_NO_INIT;
}
if (modelData == null || !modelData.isModelLoaded()) {
Slog.i(TAG, "SetParameter: Given model is not loaded:" + modelData);
return SoundTrigger.STATUS_BAD_VALUE;
}
return mModule.setParameter(modelData.getHandle(), modelParam, value);
}
int getParameter(@NonNull UUID modelId, @ModelParams int modelParam) {
synchronized (mLock) {
return getParameterLocked(mModelDataMap.get(modelId), modelParam);
}
}
int getKeyphraseParameter(int keyphraseId, @ModelParams int modelParam) {
synchronized (mLock) {
return getParameterLocked(getKeyphraseModelDataLocked(keyphraseId), modelParam);
}
}
private int getParameterLocked(@Nullable ModelData modelData, @ModelParams int modelParam) {
MetricsLogger.count(mContext, "sth_get_parameter", 1);
if (mModule == null) {
throw new UnsupportedOperationException("SoundTriggerModule not initialized");
}
if (modelData == null) {
throw new IllegalArgumentException("Invalid model id");
}
if (!modelData.isModelLoaded()) {
throw new UnsupportedOperationException("Given model is not loaded:" + modelData);
}
return mModule.getParameter(modelData.getHandle(), modelParam);
}
@Nullable
ModelParamRange queryParameter(@NonNull UUID modelId, @ModelParams int modelParam) {
synchronized (mLock) {
return queryParameterLocked(mModelDataMap.get(modelId), modelParam);
}
}
@Nullable
ModelParamRange queryKeyphraseParameter(int keyphraseId, @ModelParams int modelParam) {
synchronized (mLock) {
return queryParameterLocked(getKeyphraseModelDataLocked(keyphraseId), modelParam);
}
}
@Nullable
private ModelParamRange queryParameterLocked(@Nullable ModelData modelData,
@ModelParams int modelParam) {
MetricsLogger.count(mContext, "sth_query_parameter", 1);
if (mModule == null) {
return null;
}
if (modelData == null) {
Slog.w(TAG, "queryParameter: Invalid model id");
return null;
}
if (!modelData.isModelLoaded()) {
Slog.i(TAG, "queryParameter: Given model is not loaded:" + modelData);
return null;
}
return mModule.queryParameter(modelData.getHandle(), modelParam);
}
//---- SoundTrigger.StatusListener methods
@Override
public void onRecognition(RecognitionEvent event) {
if (event == null) {
Slog.w(TAG, "Null recognition event!");
return;
}
if (!(event instanceof KeyphraseRecognitionEvent) &&
!(event instanceof GenericRecognitionEvent)) {
Slog.w(TAG, "Invalid recognition event type (not one of generic or keyphrase)!");
return;
}
if (DBG) Slog.d(TAG, "onRecognition: " + event);
synchronized (mLock) {
switch (event.status) {
case SoundTrigger.RECOGNITION_STATUS_ABORT:
onRecognitionAbortLocked(event);
break;
case SoundTrigger.RECOGNITION_STATUS_FAILURE:
// Fire failures to all listeners since it's not tied to a keyphrase.
onRecognitionFailureLocked();
break;
case SoundTrigger.RECOGNITION_STATUS_SUCCESS:
case SoundTrigger.RECOGNITION_STATUS_GET_STATE_RESPONSE:
if (isKeyphraseRecognitionEvent(event)) {
onKeyphraseRecognitionSuccessLocked((KeyphraseRecognitionEvent) event);
} else {
onGenericRecognitionSuccessLocked((GenericRecognitionEvent) event);
}
break;
}
}
}
private boolean isKeyphraseRecognitionEvent(RecognitionEvent event) {
return event instanceof KeyphraseRecognitionEvent;
}
private void onGenericRecognitionSuccessLocked(GenericRecognitionEvent event) {
MetricsLogger.count(mContext, "sth_generic_recognition_event", 1);
if (event.status != SoundTrigger.RECOGNITION_STATUS_SUCCESS
&& event.status != SoundTrigger.RECOGNITION_STATUS_GET_STATE_RESPONSE) {
return;
}
ModelData model = getModelDataForLocked(event.soundModelHandle);
if (model == null || !model.isGenericModel()) {
Slog.w(TAG, "Generic recognition event: Model does not exist for handle: "
+ event.soundModelHandle);
return;
}
IRecognitionStatusCallback callback = model.getCallback();
if (callback == null) {
Slog.w(TAG, "Generic recognition event: Null callback for model handle: "
+ event.soundModelHandle);
return;
}
if (!event.recognitionStillActive) {
model.setStopped();
}
try {
callback.onGenericSoundTriggerDetected((GenericRecognitionEvent) event);
} catch (DeadObjectException e) {
forceStopAndUnloadModelLocked(model, e);
return;
} catch (RemoteException e) {
Slog.w(TAG, "RemoteException in onGenericSoundTriggerDetected", e);
}
RecognitionConfig config = model.getRecognitionConfig();
if (config == null) {
Slog.w(TAG, "Generic recognition event: Null RecognitionConfig for model handle: "
+ event.soundModelHandle);
return;
}
model.setRequested(config.allowMultipleTriggers);
// TODO: Remove this block if the lower layer supports multiple triggers.
if (model.isRequested()) {
updateRecognitionLocked(model, true);
}
}
@Override
public void onModelUnloaded(int modelHandle) {
if (DBG) Slog.d(TAG, "onModelUnloaded: " + modelHandle);
synchronized (mLock) {
MetricsLogger.count(mContext, "sth_sound_model_updated", 1);
onModelUnloadedLocked(modelHandle);
}
}
@Override
public void onResourcesAvailable() {
if (DBG) Slog.d(TAG, "onResourcesAvailable");
synchronized (mLock) {
onResourcesAvailableLocked();
}
}
@Override
public void onServiceDied() {
Slog.e(TAG, "onServiceDied!!");
MetricsLogger.count(mContext, "sth_service_died", 1);
synchronized (mLock) {
onServiceDiedLocked();
}
}
private void onCallStateChangedLocked(boolean callActive) {
if (mCallActive == callActive) {
// We consider multiple call states as being active
// so we check if something really changed or not here.
return;
}
mCallActive = callActive;
updateAllRecognitionsLocked();
}
private void onPowerSaveModeChangedLocked(
@SoundTriggerPowerSaveMode int soundTriggerPowerSaveMode) {
if (mSoundTriggerPowerSaveMode == soundTriggerPowerSaveMode) {
return;
}
mSoundTriggerPowerSaveMode = soundTriggerPowerSaveMode;
updateAllRecognitionsLocked();
}
private void onModelUnloadedLocked(int modelHandle) {
ModelData modelData = getModelDataForLocked(modelHandle);
if (modelData != null) {
modelData.setNotLoaded();
}
}
private void onResourcesAvailableLocked() {
updateAllRecognitionsLocked();
}
private void onRecognitionAbortLocked(RecognitionEvent event) {
Slog.w(TAG, "Recognition aborted");
MetricsLogger.count(mContext, "sth_recognition_aborted", 1);
ModelData modelData = getModelDataForLocked(event.soundModelHandle);
if (modelData != null && (modelData.isModelStarted() || modelData.isStopPending())) {
modelData.setStopped();
try {
IRecognitionStatusCallback callback = modelData.getCallback();
if (callback != null) {
callback.onRecognitionPaused();
}
} catch (DeadObjectException e) {
forceStopAndUnloadModelLocked(modelData, e);
} catch (RemoteException e) {
Slog.w(TAG, "RemoteException in onRecognitionPaused", e);
}
updateRecognitionLocked(modelData, true);
}
}
private void onRecognitionFailureLocked() {
Slog.w(TAG, "Recognition failure");
MetricsLogger.count(mContext, "sth_recognition_failure_event", 1);
try {
sendErrorCallbacksToAllLocked(STATUS_ERROR);
} finally {
internalClearModelStateLocked();
internalClearGlobalStateLocked();
}
}
private int getKeyphraseIdFromEvent(KeyphraseRecognitionEvent event) {
if (event == null) {
Slog.w(TAG, "Null RecognitionEvent received.");
return INVALID_VALUE;
}
KeyphraseRecognitionExtra[] keyphraseExtras =
((KeyphraseRecognitionEvent) event).keyphraseExtras;
if (keyphraseExtras == null || keyphraseExtras.length == 0) {
Slog.w(TAG, "Invalid keyphrase recognition event!");
return INVALID_VALUE;
}
// TODO: Handle more than one keyphrase extras.
return keyphraseExtras[0].id;
}
private void onKeyphraseRecognitionSuccessLocked(KeyphraseRecognitionEvent event) {
Slog.i(TAG, "Recognition success");
MetricsLogger.count(mContext, "sth_keyphrase_recognition_event", 1);
int keyphraseId = getKeyphraseIdFromEvent(event);
ModelData modelData = getKeyphraseModelDataLocked(keyphraseId);
if (modelData == null || !modelData.isKeyphraseModel()) {
Slog.e(TAG, "Keyphase model data does not exist for ID:" + keyphraseId);
return;
}
if (modelData.getCallback() == null) {
Slog.w(TAG, "Received onRecognition event without callback for keyphrase model.");
return;
}
if (!event.recognitionStillActive) {
modelData.setStopped();
}
try {
modelData.getCallback().onKeyphraseDetected((KeyphraseRecognitionEvent) event);
} catch (DeadObjectException e) {
forceStopAndUnloadModelLocked(modelData, e);
return;
} catch (RemoteException e) {
Slog.w(TAG, "RemoteException in onKeyphraseDetected", e);
}
RecognitionConfig config = modelData.getRecognitionConfig();
if (config != null) {
// Whether we should continue by starting this again.
modelData.setRequested(config.allowMultipleTriggers);
}
// TODO: Remove this block if the lower layer supports multiple triggers.
if (modelData.isRequested()) {
updateRecognitionLocked(modelData, true);
}
}
private void updateAllRecognitionsLocked() {
// updateRecognitionLocked can possibly update the list of models
ArrayList<ModelData> modelDatas = new ArrayList<ModelData>(mModelDataMap.values());
for (ModelData modelData : modelDatas) {
updateRecognitionLocked(modelData, true);
}
}
private int updateRecognitionLocked(ModelData model, boolean notifyClientOnError) {
boolean shouldStartModel = model.isRequested() && isRecognitionAllowedByDeviceState(model);
if (shouldStartModel == model.isModelStarted() || model.isStopPending()) {
// No-op.
return STATUS_OK;
}
if (shouldStartModel) {
int status = prepareForRecognition(model);
if (status != STATUS_OK) {
Slog.w(TAG, "startRecognition failed to prepare model for recognition");
return status;
}
status = startRecognitionLocked(model, notifyClientOnError);
// Initialize power save, call active state monitoring logic.
if (status == STATUS_OK) {
initializeDeviceStateListeners();
}
return status;
} else {
return stopRecognitionLocked(model, notifyClientOnError);
}
}
private void onServiceDiedLocked() {
try {
MetricsLogger.count(mContext, "sth_service_died", 1);
sendErrorCallbacksToAllLocked(SoundTrigger.STATUS_DEAD_OBJECT);
} finally {
internalClearModelStateLocked();
internalClearGlobalStateLocked();
if (mModule != null) {
mModule.detach();
mModule = null;
}
}
}
// internalClearGlobalStateLocked() cleans up the telephony and power save listeners.
private void internalClearGlobalStateLocked() {
// Unregister from call state changes.
final long token = Binder.clearCallingIdentity();
try {
mTelephonyManager.listen(mPhoneStateListener, PhoneStateListener.LISTEN_NONE);
} finally {
Binder.restoreCallingIdentity(token);
}
// Unregister from power save mode changes.
if (mPowerSaveModeListener != null) {
mContext.unregisterReceiver(mPowerSaveModeListener);
mPowerSaveModeListener = null;
}
mRecognitionRequested = false;
}
// Clears state for all models (generic and keyphrase).
private void internalClearModelStateLocked() {
for (ModelData modelData : mModelDataMap.values()) {
modelData.clearState();
}
}
class MyCallStateListener extends PhoneStateListener {
MyCallStateListener(@NonNull Looper looper) {
super(Objects.requireNonNull(looper));
}
@Override
public void onCallStateChanged(int state, String arg1) {
if (DBG) Slog.d(TAG, "onCallStateChanged: " + state);
if (mHandler != null) {
synchronized (mLock) {
mHandler.removeMessages(MSG_CALL_STATE_CHANGED);
Message msg = mHandler.obtainMessage(MSG_CALL_STATE_CHANGED, state, 0);
mHandler.sendMessageDelayed(
msg, (TelephonyManager.CALL_STATE_OFFHOOK == state) ? 0
: CALL_INACTIVE_MSG_DELAY_MS);
}
}
}
}
class PowerSaveModeListener extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (!PowerManager.ACTION_POWER_SAVE_MODE_CHANGED.equals(intent.getAction())) {
return;
}
@SoundTriggerPowerSaveMode int soundTriggerPowerSaveMode =
mPowerManager.getSoundTriggerPowerSaveMode();
if (DBG) {
Slog.d(TAG, "onPowerSaveModeChanged: " + soundTriggerPowerSaveMode);
}
synchronized (mLock) {
onPowerSaveModeChangedLocked(soundTriggerPowerSaveMode);
}
}
}
void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
synchronized (mLock) {
pw.print(" module properties=");
pw.println(mModuleProperties == null ? "null" : mModuleProperties);
pw.print(" call active=");
pw.println(mCallActive);
pw.println(" SoundTrigger Power State=" + mSoundTriggerPowerSaveMode);
}
}
private void initializeDeviceStateListeners() {
if (mRecognitionRequested) {
return;
}
final long token = Binder.clearCallingIdentity();
try {
// Get the current call state synchronously for the first recognition.
mCallActive = mTelephonyManager.getCallState() == TelephonyManager.CALL_STATE_OFFHOOK;
// Register for call state changes when the first call to start recognition occurs.
mTelephonyManager.listen(mPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
// Register for power saver mode changes when the first call to start recognition
// occurs.
if (mPowerSaveModeListener == null) {
mPowerSaveModeListener = new PowerSaveModeListener();
mContext.registerReceiver(mPowerSaveModeListener,
new IntentFilter(PowerManager.ACTION_POWER_SAVE_MODE_CHANGED));
}
mSoundTriggerPowerSaveMode = mPowerManager.getSoundTriggerPowerSaveMode();
mRecognitionRequested = true;
} finally {
Binder.restoreCallingIdentity(token);
}
}
// Sends an error callback to all models with a valid registered callback.
private void sendErrorCallbacksToAllLocked(int errorCode) {
for (ModelData modelData : mModelDataMap.values()) {
IRecognitionStatusCallback callback = modelData.getCallback();
if (callback != null) {
try {
callback.onError(errorCode);
} catch (RemoteException e) {
Slog.w(TAG, "RemoteException sendErrorCallbacksToAllLocked for model handle " +
modelData.getHandle(), e);
}
}
}
}
/**
* Stops and unloads all models. This is intended as a clean-up call with the expectation that
* this instance is not used after.
* @hide
*/
public void detach() {
synchronized (mLock) {
for (ModelData model : mModelDataMap.values()) {
forceStopAndUnloadModelLocked(model, null);
}
mModelDataMap.clear();
internalClearGlobalStateLocked();
if (mModule != null) {
mModule.detach();
mModule = null;
}
}
}
/**
* Stops and unloads a sound model, and removes any reference to the model if successful.
*
* @param modelData The model data to remove.
* @param exception Optional exception to print in logcat. May be null.
*/
private void forceStopAndUnloadModelLocked(ModelData modelData, Exception exception) {
forceStopAndUnloadModelLocked(modelData, exception, null /* modelDataIterator */);
}
/**
* Stops and unloads a sound model, and removes any reference to the model if successful.
*
* @param modelData The model data to remove.
* @param exception Optional exception to print in logcat. May be null.
* @param modelDataIterator If this function is to be used while iterating over the
* mModelDataMap, you can provide the iterator for the current model data to be used to
* remove the modelData from the map. This avoids generating a
* ConcurrentModificationException, since this function will try and remove the model
* data from the mModelDataMap when it can successfully unload the model.
*/
private void forceStopAndUnloadModelLocked(ModelData modelData, Exception exception,
Iterator modelDataIterator) {
if (exception != null) {
Slog.e(TAG, "forceStopAndUnloadModel", exception);
}
if (mModule == null) {
return;
}
if (modelData.isStopPending()) {
// No need to wait for the stop to be confirmed.
modelData.setStopped();
} else if (modelData.isModelStarted()) {
Slog.d(TAG, "Stopping previously started dangling model " + modelData.getHandle());
if (mModule.stopRecognition(modelData.getHandle()) == STATUS_OK) {
modelData.setStopped();
modelData.setRequested(false);
} else {
Slog.e(TAG, "Failed to stop model " + modelData.getHandle());
}
}
if (modelData.isModelLoaded()) {
Slog.d(TAG, "Unloading previously loaded dangling model " + modelData.getHandle());
if (mModule.unloadSoundModel(modelData.getHandle()) == STATUS_OK) {
// Remove the model data from existence.
if (modelDataIterator != null) {
modelDataIterator.remove();
} else {
mModelDataMap.remove(modelData.getModelId());
}
Iterator it = mKeyphraseUuidMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
if (pair.getValue().equals(modelData.getModelId())) {
it.remove();
}
}
modelData.clearState();
} else {
Slog.e(TAG, "Failed to unload model " + modelData.getHandle());
}
}
}
private void stopAndUnloadDeadModelsLocked() {
Iterator it = mModelDataMap.entrySet().iterator();
while (it.hasNext()) {
ModelData modelData = (ModelData) ((Map.Entry) it.next()).getValue();
if (!modelData.isModelLoaded()) {
continue;
}
if (modelData.getCallback() == null
|| (modelData.getCallback().asBinder() != null
&& !modelData.getCallback().asBinder().pingBinder())) {
// No one is listening on this model, so we might as well evict it.
Slog.w(TAG, "Removing model " + modelData.getHandle() + " that has no clients");
forceStopAndUnloadModelLocked(modelData, null /* exception */, it);
}
}
}
private ModelData getOrCreateGenericModelDataLocked(UUID modelId) {
ModelData modelData = mModelDataMap.get(modelId);
if (modelData == null) {
modelData = ModelData.createGenericModelData(modelId);
mModelDataMap.put(modelId, modelData);
} else if (!modelData.isGenericModel()) {
Slog.e(TAG, "UUID already used for non-generic model.");
return null;
}
return modelData;
}
private void removeKeyphraseModelLocked(int keyphraseId) {
UUID uuid = mKeyphraseUuidMap.get(keyphraseId);
if (uuid == null) {
return;
}
mModelDataMap.remove(uuid);
mKeyphraseUuidMap.remove(keyphraseId);
}
private ModelData getKeyphraseModelDataLocked(int keyphraseId) {
UUID uuid = mKeyphraseUuidMap.get(keyphraseId);
if (uuid == null) {
return null;
}
return mModelDataMap.get(uuid);
}
// Use this to create a new ModelData entry for a keyphrase Id. It will overwrite existing
// mapping if one exists.
private ModelData createKeyphraseModelDataLocked(UUID modelId, int keyphraseId) {
mKeyphraseUuidMap.remove(keyphraseId);
mModelDataMap.remove(modelId);
mKeyphraseUuidMap.put(keyphraseId, modelId);
ModelData modelData = ModelData.createKeyphraseModelData(modelId);
mModelDataMap.put(modelId, modelData);
return modelData;
}
// Instead of maintaining a second hashmap of modelHandle -> ModelData, we just
// iterate through to find the right object (since we don't expect 100s of models
// to be stored).
private ModelData getModelDataForLocked(int modelHandle) {
// Fetch ModelData object corresponding to the model handle.
for (ModelData model : mModelDataMap.values()) {
if (model.getHandle() == modelHandle) {
return model;
}
}
return null;
}
/**
* Determines if recognition is allowed at all based on device state
*
* <p>Depending on the state of the SoundTrigger service, whether a call is active, or if
* battery saver mode is enabled, a specific model may or may not be able to run. The result
* of this check is not permanent, and the state of the device can change at any time.
*
* @param modelData Model data to be used for recognition
* @return True if recognition is allowed to run at this time. False if not.
*/
private boolean isRecognitionAllowedByDeviceState(ModelData modelData) {
// if mRecognitionRequested is false, call and power state listeners are not registered so
// we read current state directly from services
if (!mRecognitionRequested) {
mCallActive = mTelephonyManager.getCallState() == TelephonyManager.CALL_STATE_OFFHOOK;
mSoundTriggerPowerSaveMode = mPowerManager.getSoundTriggerPowerSaveMode();
}
return !mCallActive && isRecognitionAllowedByPowerState(
modelData);
}
/**
* Helper function to validate if a recognition should run based on the current power state
*
* @param modelData Model data to be used for recognition
* @return True if device state allows recognition to run, false if not.
*/
boolean isRecognitionAllowedByPowerState(ModelData modelData) {
return mSoundTriggerPowerSaveMode == PowerManager.SOUND_TRIGGER_MODE_ALL_ENABLED
|| (mSoundTriggerPowerSaveMode == PowerManager.SOUND_TRIGGER_MODE_CRITICAL_ONLY
&& modelData.shouldRunInBatterySaverMode());
}
// A single routine that implements the start recognition logic for both generic and keyphrase
// models.
private int startRecognitionLocked(ModelData modelData, boolean notifyClientOnError) {
IRecognitionStatusCallback callback = modelData.getCallback();
RecognitionConfig config = modelData.getRecognitionConfig();
if (callback == null || !modelData.isModelLoaded() || config == null) {
// Nothing to do here.
Slog.w(TAG, "startRecognition: Bad data passed in.");
MetricsLogger.count(mContext, "sth_start_recognition_error", 1);
return STATUS_ERROR;
}
if (!isRecognitionAllowedByDeviceState(modelData)) {
// Nothing to do here.
Slog.w(TAG, "startRecognition requested but not allowed.");
MetricsLogger.count(mContext, "sth_start_recognition_not_allowed", 1);
return STATUS_OK;
}
if (mModule == null) {
return STATUS_ERROR;
}
int status = mModule.startRecognition(modelData.getHandle(), config);
if (status != SoundTrigger.STATUS_OK) {
Slog.w(TAG, "startRecognition failed with " + status);
MetricsLogger.count(mContext, "sth_start_recognition_error", 1);
// Notify of error if needed.
if (notifyClientOnError) {
try {
callback.onError(status);
} catch (DeadObjectException e) {
forceStopAndUnloadModelLocked(modelData, e);
} catch (RemoteException e) {
Slog.w(TAG, "RemoteException in onError", e);
}
}
} else {
Slog.i(TAG, "startRecognition successful.");
MetricsLogger.count(mContext, "sth_start_recognition_success", 1);
modelData.setStarted();
// Notify of resume if needed.
if (notifyClientOnError) {
try {
callback.onRecognitionResumed();
} catch (DeadObjectException e) {
forceStopAndUnloadModelLocked(modelData, e);
} catch (RemoteException e) {
Slog.w(TAG, "RemoteException in onRecognitionResumed", e);
}
}
}
if (DBG) {
Slog.d(TAG, "Model being started :" + modelData.toString());
}
return status;
}
private int stopRecognitionLocked(ModelData modelData, boolean notify) {
if (mModule == null) {
return STATUS_ERROR;
}
IRecognitionStatusCallback callback = modelData.getCallback();
// Stop recognition.
int status = STATUS_OK;
status = mModule.stopRecognition(modelData.getHandle());
if (status != SoundTrigger.STATUS_OK) {
Slog.w(TAG, "stopRecognition call failed with " + status);
MetricsLogger.count(mContext, "sth_stop_recognition_error", 1);
if (notify) {
try {
callback.onError(status);
} catch (DeadObjectException e) {
forceStopAndUnloadModelLocked(modelData, e);
} catch (RemoteException e) {
Slog.w(TAG, "RemoteException in onError", e);
}
}
} else {
modelData.setStopPending();
MetricsLogger.count(mContext, "sth_stop_recognition_success", 1);
// Notify of pause if needed.
if (notify) {
try {
callback.onRecognitionPaused();
} catch (DeadObjectException e) {
forceStopAndUnloadModelLocked(modelData, e);
} catch (RemoteException e) {
Slog.w(TAG, "RemoteException in onRecognitionPaused", e);
}
}
}
if (DBG) {
Slog.d(TAG, "Model being stopped :" + modelData.toString());
}
return status;
}
private void dumpModelStateLocked() {
for (UUID modelId : mModelDataMap.keySet()) {
ModelData modelData = mModelDataMap.get(modelId);
Slog.i(TAG, "Model :" + modelData.toString());
}
}
// Computes whether we have any recognition running at all (voice or generic). Sets
// the mRecognitionRequested variable with the result.
private boolean computeRecognitionRequestedLocked() {
if (mModuleProperties == null || mModule == null) {
mRecognitionRequested = false;
return mRecognitionRequested;
}
for (ModelData modelData : mModelDataMap.values()) {
if (modelData.isRequested()) {
mRecognitionRequested = true;
return mRecognitionRequested;
}
}
mRecognitionRequested = false;
return mRecognitionRequested;
}
// This class encapsulates the callbacks, state, handles and any other information that
// represents a model.
private static class ModelData {
// Model not loaded (and hence not started).
static final int MODEL_NOTLOADED = 0;
// Loaded implies model was successfully loaded. Model not started yet.
static final int MODEL_LOADED = 1;
// Started implies model was successfully loaded and start was called.
static final int MODEL_STARTED = 2;
// Model stop request has been sent. Waiting for an event to signal model being stopped.
static final int MODEL_STOP_PENDING = 3;
// One of MODEL_NOTLOADED, MODEL_LOADED, MODEL_STARTED (which implies loaded).
private int mModelState;
private UUID mModelId;
// mRequested captures the explicit intent that a start was requested for this model. We
// continue to capture and retain this state even after the model gets started, so that we
// know when a model gets stopped due to "other" reasons, that we should start it again.
// This was the intended behavior of the "mRequested" variable in the previous version of
// this code that we are replicating here.
//
// The "other" reasons include power save, abort being called from the lower layer (due
// to concurrent capture not being supported) and phone call state. Once we recover from
// these transient disruptions, we would start such models again where mRequested == true.
// Thus, mRequested gets reset only when there is an explicit intent to stop the model
// coming from the SoundTriggerService layer that uses this class (and thus eventually
// from the app that manages this model).
private boolean mRequested = false;
// One of SoundModel.TYPE_GENERIC or SoundModel.TYPE_KEYPHRASE. Initially set
// to SoundModel.TYPE_UNKNOWN;
private int mModelType = SoundModel.TYPE_UNKNOWN;
private IRecognitionStatusCallback mCallback = null;
private RecognitionConfig mRecognitionConfig = null;
// Model handle is an integer used by the HAL as an identifier for sound
// models.
private int mModelHandle;
/**
* True if the service should continue listening when battery saver mode is enabled.
* Having this flag set requires the client calling
* {@link SoundTriggerModule#startRecognition(int, RecognitionConfig)} to be granted
* {@link android.Manifest.permission#SOUND_TRIGGER_RUN_IN_BATTERY_SAVER}.
*/
public boolean mRunInBatterySaverMode = false;
// The SoundModel instance, one of KeyphraseSoundModel or GenericSoundModel.
private SoundModel mSoundModel = null;
private ModelData(UUID modelId, int modelType) {
mModelId = modelId;
// Private constructor, since we require modelType to be one of TYPE_GENERIC,
// TYPE_KEYPHRASE or TYPE_UNKNOWN.
mModelType = modelType;
}
static ModelData createKeyphraseModelData(UUID modelId) {
return new ModelData(modelId, SoundModel.TYPE_KEYPHRASE);
}
static ModelData createGenericModelData(UUID modelId) {
return new ModelData(modelId, SoundModel.TYPE_GENERIC_SOUND);
}
// Note that most of the functionality in this Java class will not work for
// SoundModel.TYPE_UNKNOWN nevertheless we have it since lower layers support it.
static ModelData createModelDataOfUnknownType(UUID modelId) {
return new ModelData(modelId, SoundModel.TYPE_UNKNOWN);
}
synchronized void setCallback(IRecognitionStatusCallback callback) {
mCallback = callback;
}
synchronized IRecognitionStatusCallback getCallback() {
return mCallback;
}
synchronized boolean isModelLoaded() {
return (mModelState == MODEL_LOADED || mModelState == MODEL_STARTED);
}
synchronized boolean isModelNotLoaded() {
return mModelState == MODEL_NOTLOADED;
}
synchronized boolean isStopPending() {
return mModelState == MODEL_STOP_PENDING;
}
synchronized void setStarted() {
mModelState = MODEL_STARTED;
}
synchronized void setStopped() {
mModelState = MODEL_LOADED;
}
synchronized void setStopPending() {
mModelState = MODEL_STOP_PENDING;
}
synchronized void setLoaded() {
mModelState = MODEL_LOADED;
}
synchronized void setNotLoaded() {
mModelState = MODEL_NOTLOADED;
}
synchronized boolean isModelStarted() {
return mModelState == MODEL_STARTED;
}
synchronized void clearState() {
mModelState = MODEL_NOTLOADED;
mRecognitionConfig = null;
mRequested = false;
mCallback = null;
}
synchronized void clearCallback() {
mCallback = null;
}
synchronized void setHandle(int handle) {
mModelHandle = handle;
}
synchronized void setRecognitionConfig(RecognitionConfig config) {
mRecognitionConfig = config;
}
synchronized void setRunInBatterySaverMode(boolean runInBatterySaverMode) {
mRunInBatterySaverMode = runInBatterySaverMode;
}
synchronized boolean shouldRunInBatterySaverMode() {
return mRunInBatterySaverMode;
}
synchronized int getHandle() {
return mModelHandle;
}
synchronized UUID getModelId() {
return mModelId;
}
synchronized RecognitionConfig getRecognitionConfig() {
return mRecognitionConfig;
}
// Whether a start recognition was requested.
synchronized boolean isRequested() {
return mRequested;
}
synchronized void setRequested(boolean requested) {
mRequested = requested;
}
synchronized void setSoundModel(SoundModel soundModel) {
mSoundModel = soundModel;
}
synchronized SoundModel getSoundModel() {
return mSoundModel;
}
synchronized int getModelType() {
return mModelType;
}
synchronized boolean isKeyphraseModel() {
return mModelType == SoundModel.TYPE_KEYPHRASE;
}
synchronized boolean isGenericModel() {
return mModelType == SoundModel.TYPE_GENERIC_SOUND;
}
synchronized String stateToString() {
switch(mModelState) {
case MODEL_NOTLOADED: return "NOT_LOADED";
case MODEL_LOADED: return "LOADED";
case MODEL_STARTED: return "STARTED";
}
return "Unknown state";
}
synchronized String requestedToString() {
return "Requested: " + (mRequested ? "Yes" : "No");
}
synchronized String callbackToString() {
return "Callback: " + (mCallback != null ? mCallback.asBinder() : "null");
}
synchronized String uuidToString() {
return "UUID: " + mModelId;
}
synchronized public String toString() {
return "Handle: " + mModelHandle + "\n" +
"ModelState: " + stateToString() + "\n" +
requestedToString() + "\n" +
callbackToString() + "\n" +
uuidToString() + "\n" +
modelTypeToString() +
"RunInBatterySaverMode=" + mRunInBatterySaverMode;
}
synchronized String modelTypeToString() {
String type = null;
switch (mModelType) {
case SoundModel.TYPE_GENERIC_SOUND: type = "Generic"; break;
case SoundModel.TYPE_UNKNOWN: type = "Unknown"; break;
case SoundModel.TYPE_KEYPHRASE: type = "Keyphrase"; break;
}
return "Model type: " + type + "\n";
}
}
}
|