This repository has been archived by the owner on Jan 16, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 602
/
AudioInputProcessor.cpp
2060 lines (1793 loc) · 89 KB
/
AudioInputProcessor.cpp
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
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.
*/
#include <algorithm>
#include <cctype>
#include <functional>
#include <list>
#include <sstream>
#include <AVSCommon/AVS/CapabilityConfiguration.h>
#include <AVSCommon/AVS/FocusState.h>
#include <AVSCommon/AVS/MessageRequest.h>
#include <AVSCommon/Utils/JSON/JSONGenerator.h>
#include <AVSCommon/Utils/JSON/JSONUtils.h>
#include <AVSCommon/Utils/Logger/Logger.h>
#include <AVSCommon/Utils/Memory/Memory.h>
#include <AVSCommon/Utils/Metrics.h>
#include <AVSCommon/Utils/Metrics/DataPointDurationBuilder.h>
#include <AVSCommon/Utils/Metrics/DataPointCounterBuilder.h>
#include <AVSCommon/Utils/Metrics/DataPointStringBuilder.h>
#include <AVSCommon/Utils/Metrics/MetricEventBuilder.h>
#include <AVSCommon/Utils/String/StringUtils.h>
#include <AVSCommon/Utils/UUIDGeneration/UUIDGeneration.h>
#include <AVSCommon/AVS/Attachment/AttachmentUtils.h>
#include <Settings/SettingEventMetadata.h>
#include <Settings/SharedAVSSettingProtocol.h>
#include <AVSCommon/AVS/Attachment/DefaultAttachmentReader.h>
#include "AIP/AudioInputProcessor.h"
namespace alexaClientSDK {
namespace capabilityAgents {
namespace aip {
using namespace avsCommon::avs;
using namespace avsCommon::utils;
using namespace avsCommon::utils::logger;
using namespace avsCommon::utils::metrics;
using namespace avsCommon::utils::json;
using namespace avsCommon::sdkInterfaces;
using namespace std::chrono;
/// SpeechRecognizer capability constants
/// SpeechRecognizer interface type
static const std::string SPEECHRECOGNIZER_CAPABILITY_INTERFACE_TYPE = "AlexaInterface";
/// SpeechRecognizer interface name
static const std::string SPEECHRECOGNIZER_CAPABILITY_INTERFACE_NAME = "SpeechRecognizer";
/// SpeechRecognizer interface version
#ifdef OVERRIDE_SPEECHRECOGNIZER_VERSION
static const std::string SPEECHRECOGNIZER_CAPABILITY_INTERFACE_VERSION = OVERRIDE_SPEECHRECOGNIZER_VERSION;
#else
static const std::string SPEECHRECOGNIZER_CAPABILITY_INTERFACE_VERSION = "2.3";
#endif
/// Configuration key used to give more details about the device configuration.
static const std::string CAPABILITY_INTERFACE_CONFIGURATIONS_KEY = "configurations";
/// Supported wake words key.
static const std::string CAPABILITY_INTERFACE_WAKE_WORDS_KEY = "wakeWords";
/// Supported maximum number of concurrent wakewords key.
static const std::string CAPABILITY_MAXIMUM_CONCURRENT_WAKEWORDS_KEY = "maximumConcurrentWakeWords";
/// The scope key for each wake words set.
static const std::string CAPABILITY_INTERFACE_SCOPES_KEY = "scopes";
/// The wake word values for a given scope.
static const std::string CAPABILITY_INTERFACE_VALUES_KEY = "values";
/// The scope configuration used as default locale wake words support.
static const std::string CAPABILITY_INTERFACE_DEFAULT_LOCALE = "DEFAULT";
/// String to identify log entries originating from this file.
#define TAG "AudioInputProcessor"
/**
* Create a LogEntry using this file's TAG and the specified event string.
*
* @param The event string for this @c LogEntry.
*/
#define LX(event) alexaClientSDK::avsCommon::utils::logger::LogEntry(TAG, event)
/// The name of the @c FocusManager channel used by @c AudioInputProvider.
static const std::string CHANNEL_NAME = FocusManagerInterface::DIALOG_CHANNEL_NAME;
/// The namespace for this capability agent.
static const std::string NAMESPACE = "SpeechRecognizer";
/// The StopCapture directive signature.
static const avsCommon::avs::NamespaceAndName STOP_CAPTURE{NAMESPACE, "StopCapture"};
/// The ExpectSpeech directive signature.
static const avsCommon::avs::NamespaceAndName EXPECT_SPEECH{NAMESPACE, "ExpectSpeech"};
/// The SetEndOfSpeechOffset directive signature.
static const avsCommon::avs::NamespaceAndName SET_END_OF_SPEECH_OFFSET{NAMESPACE, "SetEndOfSpeechOffset"};
/// The SetWakeWordConfirmation directive signature.
static const avsCommon::avs::NamespaceAndName SET_WAKE_WORD_CONFIRMATION{NAMESPACE, "SetWakeWordConfirmation"};
/// The SetSpeechConfirmation directive signature.
static const avsCommon::avs::NamespaceAndName SET_SPEECH_CONFIRMATION{NAMESPACE, "SetSpeechConfirmation"};
/// The SetWakeWords directive signature.
static const avsCommon::avs::NamespaceAndName SET_WAKE_WORDS{NAMESPACE, "SetWakeWords"};
/// The field identifying the initiator.
static const std::string INITIATOR_KEY = "initiator";
/// The field identifying the initiator's profile.
static const std::string PROFILE_KEY = "profile";
/// The field identifying the initiator's format.
static const std::string FORMAT_KEY = "format";
/// The field identifying the initiator's type.
static const std::string TYPE_KEY = "type";
/// The field identifying the initiator's token.
static const std::string TOKEN_KEY = "token";
/// The field identifying the initiator's payload.
static const std::string PAYLOAD_KEY = "payload";
/// The field identifying the initiator's wakeword indices.
static const std::string WAKEWORD_INDICES_KEY = "wakeWordIndices";
/// The field identifying the initiator's wakeword start index.
static const std::string START_INDEX_KEY = "startIndexInSamples";
/// The field identifying the initiator's wakeword end index.
static const std::string END_INDEX_KEY = "endIndexInSamples";
/// The field identifying the initiator's wake word.
static const std::string WAKE_WORD_KEY = "wakeWord";
/// The field name for the user voice attachment.
static const std::string AUDIO_ATTACHMENT_FIELD_NAME = "audio";
/// The field name for the wake word engine metadata.
static const std::string KWD_METADATA_FIELD_NAME = "wakewordEngineMetadata";
/// The field name for the start of speech timestamp, reported in milliseconds since epoch. This field is provided to
/// the Recognize event and it's sent back as part of SetEndOfSpeechOffset payload.
static const std::string START_OF_SPEECH_TIMESTAMP_FIELD_NAME = "startOfSpeechTimestamp";
/// The field name for the end of speech offset, reported in milliseconds, as part of SetEndOfSpeechOffset payload.
static const std::string END_OF_SPEECH_OFFSET_FIELD_NAME = "endOfSpeechOffsetInMilliseconds";
/// The value of the WakeWordConfirmationChanged Event name.
static const std::string WAKE_WORD_CONFIRMATION_CHANGED_EVENT_NAME = "WakeWordConfirmationChanged";
/// The value of the WakeWordConfirmationReport Event name.
static const std::string WAKE_WORD_CONFIRMATION_REPORT_EVENT_NAME = "WakeWordConfirmationReport";
/// The value of the payload key for wakeWordConfirmation.
static const std::string WAKE_WORD_CONFIRMATION_PAYLOAD_KEY = "wakeWordConfirmation";
/// The value of the SpeechConfirmationChanged Event name.
static const std::string SPEECH_CONFIRMATION_CHANGED_EVENT_NAME = "SpeechConfirmationChanged";
/// The value of the SpeechConfirmationReport Event name.
static const std::string SPEECH_CONFIRMATION_REPORT_EVENT_NAME = "SpeechConfirmationReport";
/// The value of the payload key for speechConfirmation.
static const std::string SPEECH_CONFIRMATION_PAYLOAD_KEY = "speechConfirmation";
/// The value of the WakeWordsChanged Event name.
static const std::string WAKE_WORDS_CHANGED_EVENT_NAME = "WakeWordsChanged";
/// The value of the WakeWordsReport Event name.
static const std::string WAKE_WORDS_REPORT_EVENT_NAME = "WakeWordsReport";
/// The value of the payload key for wake words.
static const std::string WAKE_WORDS_PAYLOAD_KEY = "wakeWords";
/// The component name of power management
static const std::string POWER_RESOURCE_COMPONENT_NAME = "AudioInputProcessor";
/// Metric Activity Name Prefix for AIP metric source
static const std::string METRIC_ACTIVITY_NAME_PREFIX_AIP = "AIP-";
/// Start of Utterance Activity Name for AIP metric source
static const std::string START_OF_UTTERANCE = "START_OF_UTTERANCE";
static const std::string START_OF_UTTERANCE_ACTIVITY_NAME = METRIC_ACTIVITY_NAME_PREFIX_AIP + START_OF_UTTERANCE;
/// Name of audio bytes stream metric Opus
static const std::string WAKEWORD_DETECTION_SEGMENT_UPLOADED_OPUS = "AIP_WAKEWORD_DETECTION_SEGMENT_UPLOADED_OPUS";
/// Name of audio bytes stream metric PCM
static const std::string WAKEWORD_DETECTION_SEGMENT_UPLOADED_PCM = "AIP_WAKEWORD_DETECTION_SEGMENT_UPLOADED_PCM";
/// Recognize EVENT is built for AIP metric source
static const std::string RECOGNIZE_START_SEND_MESSAGE = "RECOGNIZE_EVENT_IS_BUILT";
static const std::string RECOGNIZE_START_SEND_MESSAGE_ACTIVITY_NAME =
METRIC_ACTIVITY_NAME_PREFIX_AIP + RECOGNIZE_START_SEND_MESSAGE;
/// Wakeword Activity Name for AIP metric source
static const std::string START_OF_STREAM_TIMESTAMP = "START_OF_STREAM_TIMESTAMP";
static const std::string WW_DURATION = "WW_DURATION";
static const std::string WW_DURATION_ACTIVITY_NAME = METRIC_ACTIVITY_NAME_PREFIX_AIP + WW_DURATION;
/// Stop Capture Received Activity Name for AIP metric source
static const std::string STOP_CAPTURE_RECEIVED = "STOP_CAPTURE";
static const std::string STOP_CAPTURE_RECEIVED_ACTIVITY_NAME = METRIC_ACTIVITY_NAME_PREFIX_AIP + STOP_CAPTURE_RECEIVED;
/// The duration metric for acquire power resource
static const std::string ACQUIRE_POWER_RESOURCE = "ACQUIRE_POWER_RESOURCE";
static const std::string ACQUIRE_POWER_RESOURCE_ACTIVITY = METRIC_ACTIVITY_NAME_PREFIX_AIP + ACQUIRE_POWER_RESOURCE;
/// The duration metric for release power resource
static const std::string RELEASE_POWER_RESOURCE = "RELEASE_POWER_RESOURCE";
static const std::string RELEASE_POWER_RESOURCE_ACTIVITY = METRIC_ACTIVITY_NAME_PREFIX_AIP + RELEASE_POWER_RESOURCE;
/// The timestamp for the start of execute on context available
static const std::string FETCH_CONTEXT_DURATION = "FETCH_CONTEXT_DURATION";
static const std::string FETCH_CONTEXT_DURATION_ACTIVITY_NAME =
METRIC_ACTIVITY_NAME_PREFIX_AIP + FETCH_CONTEXT_DURATION;
/// End of Speech Offset Received Activity Name for AIP metric source
static const std::string END_OF_SPEECH_OFFSET_RECEIVED = "END_OF_SPEECH_OFFSET";
static const std::string END_OF_SPEECH_OFFSET_RECEIVED_ACTIVITY_NAME =
METRIC_ACTIVITY_NAME_PREFIX_AIP + END_OF_SPEECH_OFFSET_RECEIVED;
/// The duration metric for short time out
static const std::string STOP_CAPTURE_TO_END_OF_SPEECH_METRIC_NAME = "STOP_CAPTURE_TO_END_OF_SPEECH";
static const std::string STOP_CAPTURE_TO_END_OF_SPEECH_ACTIVITY_NAME =
METRIC_ACTIVITY_NAME_PREFIX_AIP + STOP_CAPTURE_TO_END_OF_SPEECH_METRIC_NAME;
/// The recognize request initiator metric.
static const std::string INITIATOR_PREFIX = "INITIATOR_";
static const std::string INITIATOR_ACTIVITY_NAME_PREFIX = METRIC_ACTIVITY_NAME_PREFIX_AIP + INITIATOR_PREFIX;
/// AudioEncodingFormat Activity Name for AIP metric source
static const std::string AUDIO_ENCODING_FORMAT_METRIC_NAME = "AUDIO_ENCODING_FORMAT";
static const std::string AUDIO_ENCODING_FORMAT_ACTIVITY_NAME =
METRIC_ACTIVITY_NAME_PREFIX_AIP + AUDIO_ENCODING_FORMAT_METRIC_NAME;
static const std::string AUDIO_ENCODING_FORMAT_OPUS = "OPUSAudioEncoding";
static const std::string AUDIO_ENCODING_FORMAT_LPCM = "LPCMAudioEncoding";
/// The default resolveKey used as a placeholder when only one encoding format is configured for @c AudioInputProcessor
static const std::string DEFAULT_RESOLVE_KEY = "DEFAULT_RESOLVE_KEY";
/// Keys for instance entry metric specific fields
static const std::string ENTRY_METRIC_ACTOR_NAME = "AudioInputProcessor";
static const std::string ENTRY_METRIC_ACTIVITY_NAME = METRIC_ACTIVITY_NAME_PREFIX_AIP + ENTRY_METRIC_ACTOR_NAME;
static const std::string ENTRY_METRIC_KEY_SEGMENT_ID = "segment_id";
static const std::string ENTRY_METRIC_KEY_ACTOR = "actor";
static const std::string ENTRY_METRIC_KEY_ENTRY_TYPE = "entry_type";
static const std::string ENTRY_METRIC_KEY_ENTRY_NAME = "entry_name";
static const std::string ENTRY_METRIC_NAME_STATE_CHANGE = "StateChange";
/// Preroll duration is a fixed 500ms.
static const std::chrono::milliseconds PREROLL_DURATION = std::chrono::milliseconds(500);
static const int MILLISECONDS_PER_SECOND = 1000;
/// Threshold number of bytes for OPUS Encoded Wakeword detection
static const int WAKEWORD_DETECTION_SEGMENT_SIZE_BYTES_OPUS = 5209;
/// Threshold number of bytes for PCM Encoded Wakeword detection
static const int WAKEWORD_DETECTION_SEGMENT_SIZE_BYTES_PCM = 40480;
/// Cloud resolve key constant. Used to determine the encoding sent to the cloud.
static const std::string CLOUD_RESOLVE_KEY = "CLOUD";
/**
* Helper function to get string values of encoding audio format, which are used in Recognize event.
* @param encoding Target encoding format
* @return String name of the encoding format
*/
static std::string encodingFormatToString(avsCommon::utils::AudioFormat::Encoding encoding) {
switch (encoding) {
case avsCommon::utils::AudioFormat::Encoding::OPUS:
return "OPUS";
case avsCommon::utils::AudioFormat::Encoding::LPCM:
return "AUDIO_L16_RATE_16000_CHANNELS_1";
}
return "UNKNOWN";
}
/**
* Handles a Metric event by creating and recording it. Failure to create or record the event results
* in an early return.
*
* @param metricRecorder The @c MetricRecorderInterface which records Metric events.
* @param metricEventBuilder The @c MetricEventBuilder.
* @param dialogRequestId The dialogRequestId associated with this Metric event; default is empty string.
*/
static void submitMetric(
const std::shared_ptr<MetricRecorderInterface>& metricRecorder,
MetricEventBuilder& metricEventBuilder,
const std::string& dialogRequestId = "") {
metricEventBuilder.addDataPoint(
DataPointStringBuilder{}.setName("DIALOG_REQUEST_ID").setValue(dialogRequestId).build());
auto metricEvent = metricEventBuilder.build();
if (metricEvent == nullptr) {
ACSDK_ERROR(LX("Error creating metric with explicit dialogRequestId"));
return;
}
recordMetric(metricRecorder, metricEvent);
}
/**
* Handles a Metric event by creating and recording it. Failure to create or record the event results
* in an early return.
*
* @param metricRecorder The @c MetricRecorderInterface which records Metric events.
* @param activityName The activityName of the Metric event.
* @param dataPoint The @c DataPoint of this Metric event (e.g. duration).
* @param directive The @c AVSDirective associated with this Metric event; default is nullptr.
*/
static void submitMetric(
const std::shared_ptr<MetricRecorderInterface> metricRecorder,
const std::string& activityName,
const DataPoint& dataPoint,
const std::shared_ptr<AVSDirective>& directive = nullptr) {
auto metricEventBuilder = MetricEventBuilder{}.setActivityName(activityName).addDataPoint(dataPoint);
if (directive != nullptr) {
metricEventBuilder.addDataPoint(
DataPointStringBuilder{}.setName("HTTP2_STREAM").setValue(directive->getAttachmentContextId()).build());
metricEventBuilder.addDataPoint(
DataPointStringBuilder{}.setName("DIRECTIVE_MESSAGE_ID").setValue(directive->getMessageId()).build());
metricEventBuilder.addDataPoint(
DataPointStringBuilder{}.setName("DIALOG_REQUEST_ID").setValue(directive->getDialogRequestId()).build());
}
auto metricEvent = metricEventBuilder.build();
if (metricEvent == nullptr) {
ACSDK_ERROR(LX("Error creating metric from directive"));
return;
}
recordMetric(metricRecorder, metricEvent);
}
/**
* Creates and records an instance entry metric with the given identifiers and metadata.
* @param metricRecorder The @c MetricRecorderInterface which records Metric events.
* @param segmentId The segmentId corresponding to this metric event.
* @param name The name of this metric
* @param metadata Any metadata to be associated with this metric; default is empty
*/
static void submitInstanceEntryMetric(
const std::shared_ptr<MetricRecorderInterface>& metricRecorder,
const std::string& segmentId,
const std::string& name,
const std::map<std::string, std::string>& metadata = {}) {
if (segmentId.empty() || name.empty()) {
ACSDK_ERROR(LX(__FUNCTION__).m("Unable to create instance metric").d("segmentId", segmentId).d("name", name));
return;
}
auto metricBuilder = MetricEventBuilder{}.setActivityName(ENTRY_METRIC_ACTIVITY_NAME);
metricBuilder.addDataPoint(
DataPointStringBuilder{}.setName(ENTRY_METRIC_KEY_SEGMENT_ID).setValue(segmentId).build());
metricBuilder.addDataPoint(
DataPointStringBuilder{}.setName(ENTRY_METRIC_KEY_ACTOR).setValue(ENTRY_METRIC_ACTOR_NAME).build());
metricBuilder.addDataPoint(DataPointStringBuilder{}.setName(ENTRY_METRIC_KEY_ENTRY_NAME).setValue(name).build());
metricBuilder.addDataPoint(
DataPointStringBuilder{}.setName(ENTRY_METRIC_KEY_ENTRY_TYPE).setValue("INSTANCE").build());
for (auto const& pair : metadata) {
metricBuilder.addDataPoint(DataPointStringBuilder{}.setName(pair.first).setValue(pair.second).build());
}
auto metric = metricBuilder.build();
if (metric == nullptr) {
ACSDK_ERROR(LX(__FUNCTION__).m("Error creating instance entry metric."));
return;
}
recordMetric(metricRecorder, metric);
}
/**
* Creates the SpeechRecognizer capability configuration.
*
* @param assetsManager Responsible for retrieving and changing the wake words and locale.
* @return The SpeechRecognizer capability configuration.
*/
static std::shared_ptr<avsCommon::avs::CapabilityConfiguration> getSpeechRecognizerCapabilityConfiguration(
const LocaleAssetsManagerInterface& assetsManager);
/**
* Resolving method to be called in lambda function that will be passed to @c MessageRequest as @c
* MessageRequestResolveFunction
* @param[in,out] request @c EditableMessageRequest to resolve
* @param resolveKey Provided resolve key
* @param encodingFormats Mappings from resolveKey to encoding format
* @param attachmentReaders Mappings from resolveKey to attachment readers
* @param metricRecorder @c MetricRecorderInterface object to emit metrics
* @return @c true if the message is resolved successfully, else @c false
*/
static bool resolveMessageRequest(
const std::shared_ptr<avsCommon::avs::EditableMessageRequest>& request,
const std::string& resolveKey,
AudioInputProcessor::EncodingFormatResponse encodingFormats,
const std::unordered_map<std::string, std::vector<std::shared_ptr<avsCommon::avs::MessageRequest::NamedReader>>>&
attachmentReaders,
const std::shared_ptr<avsCommon::utils::metrics::MetricRecorderInterface>& metricRecorder);
std::shared_ptr<AudioInputProcessor> AudioInputProcessor::create(
std::shared_ptr<DirectiveSequencerInterface> directiveSequencer,
std::shared_ptr<MessageSenderInterface> messageSender,
std::shared_ptr<ContextManagerInterface> contextManager,
std::shared_ptr<FocusManagerInterface> focusManager,
std::shared_ptr<avsCommon::avs::DialogUXStateAggregator> dialogUXStateAggregator,
std::shared_ptr<ExceptionEncounteredSenderInterface> exceptionEncounteredSender,
std::shared_ptr<UserInactivityMonitorInterface> userInactivityMonitor,
std::shared_ptr<SystemSoundPlayerInterface> systemSoundPlayer,
const std::shared_ptr<LocaleAssetsManagerInterface>& assetsManager,
std::shared_ptr<settings::WakeWordConfirmationSetting> wakeWordConfirmation,
std::shared_ptr<settings::SpeechConfirmationSetting> speechConfirmation,
const std::shared_ptr<avsCommon::avs::CapabilityChangeNotifierInterface>& capabilityChangeNotifier,
std::shared_ptr<settings::WakeWordsSetting> wakeWordsSetting,
std::shared_ptr<audioEncoderInterfaces::AudioEncoderInterface> audioEncoder,
AudioProvider defaultAudioProvider,
std::shared_ptr<PowerResourceManagerInterface> powerResourceManager,
std::shared_ptr<avsCommon::utils::metrics::MetricRecorderInterface> metricRecorder,
const std::shared_ptr<ExpectSpeechTimeoutHandler>& expectSpeechTimeoutHandler) {
if (!directiveSequencer) {
ACSDK_ERROR(LX("createFailed").d("reason", "nullDirectiveSequencer"));
return nullptr;
} else if (!messageSender) {
ACSDK_ERROR(LX("createFailed").d("reason", "nullMessageSender"));
return nullptr;
} else if (!contextManager) {
ACSDK_ERROR(LX("createFailed").d("reason", "nullContextManager"));
return nullptr;
} else if (!focusManager) {
ACSDK_ERROR(LX("createFailed").d("reason", "nullFocusManager"));
return nullptr;
} else if (!dialogUXStateAggregator) {
ACSDK_ERROR(LX("createFailed").d("reason", "nullDialogUXStateAggregator"));
return nullptr;
} else if (!exceptionEncounteredSender) {
ACSDK_ERROR(LX("createFailed").d("reason", "nullExceptionEncounteredSender"));
return nullptr;
} else if (!userInactivityMonitor) {
ACSDK_ERROR(LX("createFailed").d("reason", "nullUserInactivityMonitor"));
return nullptr;
} else if (!systemSoundPlayer) {
ACSDK_ERROR(LX("createFailed").d("reason", "nullSystemSoundPlayer"));
return nullptr;
} else if (!wakeWordConfirmation) {
ACSDK_ERROR(LX("createFailed").d("reason", "nullWakeWordsConfirmation"));
return nullptr;
} else if (!speechConfirmation) {
ACSDK_ERROR(LX("createFailed").d("reason", "nullSpeechConfirmation"));
return nullptr;
} else if (!assetsManager) {
ACSDK_ERROR(LX("createFailed").d("reason", "nullAssetsManager"));
return nullptr;
} else if (!assetsManager->getDefaultSupportedWakeWords().empty() && !wakeWordsSetting) {
ACSDK_ERROR(LX("createFailed").d("reason", "nullWakeWordsSetting"));
return nullptr;
} else if (!capabilityChangeNotifier) {
ACSDK_ERROR(LX("createFailed").d("reason", "nullCapabilityChangeNotifier"));
return nullptr;
}
auto capabilitiesConfiguration = getSpeechRecognizerCapabilityConfiguration(*assetsManager);
if (!capabilitiesConfiguration) {
ACSDK_ERROR(LX("createFailed").d("reason", "unableToCreateCapabilitiesConfiguration"));
return nullptr;
}
auto aip = std::shared_ptr<AudioInputProcessor>(new AudioInputProcessor(
directiveSequencer,
messageSender,
contextManager,
focusManager,
exceptionEncounteredSender,
userInactivityMonitor,
systemSoundPlayer,
assetsManager,
audioEncoder,
defaultAudioProvider,
wakeWordConfirmation,
speechConfirmation,
capabilityChangeNotifier,
wakeWordsSetting,
capabilitiesConfiguration,
powerResourceManager,
std::move(metricRecorder),
expectSpeechTimeoutHandler));
if (!aip->initialize()) {
ACSDK_ERROR(LX("createFailed").d("reason", "unableToInitialize"));
return nullptr;
}
if (aip) {
dialogUXStateAggregator->addObserver(aip);
}
return aip;
}
avsCommon::avs::DirectiveHandlerConfiguration AudioInputProcessor::getConfiguration() const {
avsCommon::avs::DirectiveHandlerConfiguration configuration;
configuration[STOP_CAPTURE] = BlockingPolicy(BlockingPolicy::MEDIUMS_NONE, false);
configuration[EXPECT_SPEECH] = BlockingPolicy(BlockingPolicy::MEDIUM_AUDIO, true);
configuration[SET_END_OF_SPEECH_OFFSET] = BlockingPolicy(BlockingPolicy::MEDIUMS_NONE, false);
configuration[SET_WAKE_WORD_CONFIRMATION] = BlockingPolicy(BlockingPolicy::MEDIUMS_NONE, false);
configuration[SET_SPEECH_CONFIRMATION] = BlockingPolicy(BlockingPolicy::MEDIUMS_NONE, false);
configuration[SET_WAKE_WORDS] = BlockingPolicy(BlockingPolicy::MEDIUMS_NONE, false);
return configuration;
}
void AudioInputProcessor::addObserver(std::shared_ptr<ObserverInterface> observer) {
if (!observer) {
ACSDK_ERROR(LX("addObserverFailed").d("reason", "nullObserver"));
return;
}
m_executor.execute([this, observer]() { m_observers.insert(observer); });
}
void AudioInputProcessor::removeObserver(std::shared_ptr<ObserverInterface> observer) {
if (!observer) {
ACSDK_ERROR(LX("removeObserverFailed").d("reason", "nullObserver"));
return;
}
m_executor.submit([this, observer]() { m_observers.erase(observer); }).wait();
}
std::future<bool> AudioInputProcessor::recognize(
AudioProvider audioProvider,
Initiator initiator,
steady_clock::time_point startOfSpeechTimestamp,
avsCommon::avs::AudioInputStream::Index begin,
avsCommon::avs::AudioInputStream::Index keywordEnd,
std::string keyword,
std::shared_ptr<const std::vector<char>> KWDMetadata,
const std::string& initiatorToken) {
ACSDK_METRIC_IDS(TAG, "Recognize", "", "", Metrics::Location::AIP_RECEIVE);
ACSDK_DEBUG5(LX(__func__));
std::string upperCaseKeyword = keyword;
std::transform(upperCaseKeyword.begin(), upperCaseKeyword.end(), upperCaseKeyword.begin(), ::toupper);
if (KEYWORD_TEXT_STOP == upperCaseKeyword) {
ACSDK_DEBUG(LX("skippingRecognizeEvent").d("reason", "invalidKeyword").d("keyword", keyword));
std::promise<bool> ret;
ret.set_value(false);
return ret.get_future();
}
// If no begin index was provided, grab the current index ASAP so that we can start streaming from the time this
// call was made.
if (audioProvider.stream && INVALID_INDEX == begin) {
static const bool startWithNewData = true;
auto reader = audioProvider.stream->createReader(
avsCommon::avs::AudioInputStream::Reader::Policy::NONBLOCKING, startWithNewData);
if (!reader) {
ACSDK_ERROR(LX("recognizeFailed").d("reason", "createReaderFailed"));
std::promise<bool> ret;
ret.set_value(false);
return ret.get_future();
}
begin = reader->tell();
}
return m_executor.submit([this,
audioProvider,
initiator,
startOfSpeechTimestamp,
begin,
keywordEnd,
keyword,
KWDMetadata,
initiatorToken]() {
return executeRecognize(
audioProvider, initiator, startOfSpeechTimestamp, begin, keywordEnd, keyword, KWDMetadata, initiatorToken);
});
}
std::future<bool> AudioInputProcessor::stopCapture() {
return m_executor.submit([this]() { return executeStopCapture(); });
}
std::future<void> AudioInputProcessor::resetState() {
ACSDK_DEBUG0(LX(__func__));
return m_executor.submit([this]() { executeResetState(); });
}
void AudioInputProcessor::onContextAvailable(const std::string& jsonContext) {
ACSDK_DEBUG0(LX(__func__));
m_executor.execute([this, jsonContext]() { executeOnContextAvailable(jsonContext); });
}
void AudioInputProcessor::onContextFailure(const ContextRequestError error) {
ACSDK_DEBUG0(LX(__func__));
m_executor.execute([this, error]() { executeOnContextFailure(error); });
}
void AudioInputProcessor::handleDirectiveImmediately(std::shared_ptr<avsCommon::avs::AVSDirective> directive) {
handleDirective(std::make_shared<DirectiveInfo>(directive, nullptr));
}
void AudioInputProcessor::preHandleDirective(std::shared_ptr<DirectiveInfo> info) {
}
void AudioInputProcessor::handleDirective(std::shared_ptr<DirectiveInfo> info) {
if (!info) {
ACSDK_ERROR(LX("handleDirectiveFailed").d("reason", "nullDirectiveInfo"));
return;
}
if (!info->directive) {
ACSDK_ERROR(LX("handleDirectiveFailed").d("reason", "nullDirective"));
return;
}
if (info->directive->getName() == STOP_CAPTURE.name) {
ACSDK_METRIC_MSG(TAG, info->directive, Metrics::Location::AIP_RECEIVE);
submitMetric(
m_metricRecorder,
STOP_CAPTURE_RECEIVED_ACTIVITY_NAME,
DataPointCounterBuilder{}.setName(STOP_CAPTURE_RECEIVED).increment(1).build(),
info->directive);
handleStopCaptureDirective(info);
} else if (info->directive->getName() == EXPECT_SPEECH.name) {
handleExpectSpeechDirective(info);
} else if (info->directive->getName() == SET_END_OF_SPEECH_OFFSET.name) {
handleSetEndOfSpeechOffsetDirective(info);
} else if (info->directive->getName() == SET_WAKE_WORD_CONFIRMATION.name) {
handleSetWakeWordConfirmation(info);
} else if (info->directive->getName() == SET_SPEECH_CONFIRMATION.name) {
handleSetSpeechConfirmation(info);
} else if (info->directive->getName() == SET_WAKE_WORDS.name) {
handleSetWakeWords(info);
} else {
std::string errorMessage =
"unexpected directive " + info->directive->getNamespace() + ":" + info->directive->getName();
m_exceptionEncounteredSender->sendExceptionEncountered(
info->directive->getUnparsedDirective(),
avsCommon::avs::ExceptionErrorType::UNEXPECTED_INFORMATION_RECEIVED,
errorMessage);
if (info->result) {
info->result->setFailed(errorMessage);
}
ACSDK_ERROR(LX("handleDirectiveFailed")
.d("reason", "unknownDirective")
.d("namespace", info->directive->getNamespace())
.d("name", info->directive->getName()));
removeDirective(info);
}
}
void AudioInputProcessor::cancelDirective(std::shared_ptr<DirectiveInfo> info) {
removeDirective(info);
}
void AudioInputProcessor::onDeregistered() {
resetState();
}
void AudioInputProcessor::onFocusChanged(avsCommon::avs::FocusState newFocus, avsCommon::avs::MixingBehavior behavior) {
ACSDK_DEBUG9(LX("onFocusChanged").d("newFocus", newFocus).d("MixingBehavior", behavior));
m_executor.execute([this, newFocus]() { executeOnFocusChanged(newFocus); });
}
void AudioInputProcessor::onDialogUXStateChanged(DialogUXStateObserverInterface::DialogUXState newState) {
m_executor.execute([this, newState]() { executeOnDialogUXStateChanged(newState); });
}
AudioInputProcessor::AudioInputProcessor(
std::shared_ptr<DirectiveSequencerInterface> directiveSequencer,
std::shared_ptr<MessageSenderInterface> messageSender,
std::shared_ptr<ContextManagerInterface> contextManager,
std::shared_ptr<FocusManagerInterface> focusManager,
std::shared_ptr<ExceptionEncounteredSenderInterface> exceptionEncounteredSender,
std::shared_ptr<UserInactivityMonitorInterface> userInactivityMonitor,
std::shared_ptr<SystemSoundPlayerInterface> systemSoundPlayer,
const std::shared_ptr<LocaleAssetsManagerInterface>& assetsManager,
std::shared_ptr<audioEncoderInterfaces::AudioEncoderInterface> audioEncoder,
AudioProvider defaultAudioProvider,
std::shared_ptr<settings::WakeWordConfirmationSetting> wakeWordConfirmation,
std::shared_ptr<settings::SpeechConfirmationSetting> speechConfirmation,
const std::shared_ptr<avsCommon::avs::CapabilityChangeNotifierInterface>& capabilityChangeNotifier,
std::shared_ptr<settings::WakeWordsSetting> wakeWordsSetting,
std::shared_ptr<avsCommon::avs::CapabilityConfiguration> capabilitiesConfiguration,
std::shared_ptr<PowerResourceManagerInterface> powerResourceManager,
std::shared_ptr<avsCommon::utils::metrics::MetricRecorderInterface> metricRecorder,
const std::shared_ptr<ExpectSpeechTimeoutHandler>& expectSpeechTimeoutHandler) :
CapabilityAgent{NAMESPACE, exceptionEncounteredSender},
RequiresShutdown{"AudioInputProcessor"},
m_metricRecorder{metricRecorder},
m_directiveSequencer{directiveSequencer},
m_messageSender{messageSender},
m_contextManager{contextManager},
m_focusManager{focusManager},
m_userInactivityMonitor{userInactivityMonitor},
m_encoder{audioEncoder},
m_defaultAudioProvider{defaultAudioProvider},
m_lastAudioProvider{AudioProvider::null()},
m_state{ObserverInterface::State::IDLE},
m_focusState{avsCommon::avs::FocusState::NONE},
m_preparingToSend{false},
m_initialDialogUXStateReceived{false},
m_localStopCapturePerformed{false},
m_streamIsClosedInRecognizingState{false},
m_systemSoundPlayer{systemSoundPlayer},
m_assetsManager{assetsManager},
m_precedingExpectSpeechInitiator{nullptr},
m_wakeWordConfirmation{wakeWordConfirmation},
m_speechConfirmation{speechConfirmation},
m_capabilityChangeNotifier{capabilityChangeNotifier},
m_wakeWordsSetting{wakeWordsSetting},
m_powerResourceManager{powerResourceManager},
m_expectSpeechTimeoutHandler{expectSpeechTimeoutHandler},
m_timeSinceLastResumeMS{std::chrono::milliseconds(0)},
m_timeSinceLastPartialMS{std::chrono::milliseconds(0)},
m_resourceFlags{0},
m_usingEncoder{false},
m_messageRequestResolver{nullptr},
m_encodingAudioFormats{{DEFAULT_RESOLVE_KEY, AudioFormat::Encoding::LPCM}} {
m_capabilityConfigurations.insert(capabilitiesConfiguration);
m_fetchContextTimeMetricData.setName(FETCH_CONTEXT_DURATION);
if (m_powerResourceManager) {
m_powerResourceId = m_powerResourceManager->create(
POWER_RESOURCE_COMPONENT_NAME, false, PowerResourceManagerInterface::PowerResourceLevel::ACTIVE_HIGH);
if (!m_powerResourceId) {
ACSDK_ERROR(
LX(__func__).d("reason", "createRawPowerResourceFailed").d("name", POWER_RESOURCE_COMPONENT_NAME));
}
}
}
/**
* Generate supported wake words json capability configuration for a given scope (default, language or locale).
*
* @param scope The scope being reported.
* @param wakeWordsCombination The set of a combination of wake words supported in the given scope.
* @return A json representation of the scope configuration.
*/
std::string generateSupportedWakeWordsJson(
const std::string& scope,
const LocaleAssetsManagerInterface::WakeWordsSets& wakeWordsCombination) {
json::JsonGenerator generator;
generator.addStringArray(CAPABILITY_INTERFACE_SCOPES_KEY, std::list<std::string>({scope}));
generator.addCollectionOfStringArray(CAPABILITY_INTERFACE_VALUES_KEY, wakeWordsCombination);
return generator.toString();
}
std::shared_ptr<avsCommon::avs::CapabilityConfiguration> getSpeechRecognizerCapabilityConfiguration(
const LocaleAssetsManagerInterface& assetsManager) {
std::unordered_map<std::string, std::string> configMap;
configMap.insert({CAPABILITY_INTERFACE_TYPE_KEY, SPEECHRECOGNIZER_CAPABILITY_INTERFACE_TYPE});
configMap.insert({CAPABILITY_INTERFACE_NAME_KEY, SPEECHRECOGNIZER_CAPABILITY_INTERFACE_NAME});
configMap.insert({CAPABILITY_INTERFACE_VERSION_KEY, SPEECHRECOGNIZER_CAPABILITY_INTERFACE_VERSION});
// Generate wake words capability configuration if supportedWakeWords is not empty.
auto defaultWakeWords = assetsManager.getDefaultSupportedWakeWords();
if (!defaultWakeWords.empty()) {
std::set<std::string> wakeWords;
wakeWords.insert(generateSupportedWakeWordsJson(CAPABILITY_INTERFACE_DEFAULT_LOCALE, defaultWakeWords));
for (const auto& entry : assetsManager.getLanguageSpecificWakeWords()) {
wakeWords.insert(generateSupportedWakeWordsJson(entry.first, entry.second));
}
for (const auto& entry : assetsManager.getLocaleSpecificWakeWords()) {
wakeWords.insert(generateSupportedWakeWordsJson(entry.first, entry.second));
}
json::JsonGenerator generator;
generator.addMembersArray(CAPABILITY_INTERFACE_WAKE_WORDS_KEY, wakeWords);
configMap.insert({CAPABILITY_INTERFACE_CONFIGURATIONS_KEY, generator.toString()});
ACSDK_DEBUG5(LX(__func__).d("wakeWords", generator.toString()));
}
return std::make_shared<avsCommon::avs::CapabilityConfiguration>(configMap);
}
settings::SettingEventMetadata AudioInputProcessor::getWakeWordsEventsMetadata() {
return settings::SettingEventMetadata{
NAMESPACE, WAKE_WORDS_CHANGED_EVENT_NAME, WAKE_WORDS_REPORT_EVENT_NAME, WAKE_WORDS_PAYLOAD_KEY};
}
void AudioInputProcessor::doShutdown() {
m_executor.shutdown();
executeResetState();
m_directiveSequencer.reset();
m_messageSender.reset();
m_contextManager.reset();
m_focusManager.reset();
m_userInactivityMonitor.reset();
m_observers.clear();
m_expectSpeechTimeoutHandler.reset();
if (m_powerResourceManager && m_powerResourceId) {
m_powerResourceManager->close(m_powerResourceId);
}
}
bool resolveMessageRequest(
const std::shared_ptr<EditableMessageRequest>& request,
const std::string& resolveKey,
AudioInputProcessor::EncodingFormatResponse encodingFormats,
const std::unordered_map<std::string, std::vector<std::shared_ptr<MessageRequest::NamedReader>>>& attachmentReaders,
const std::shared_ptr<avsCommon::utils::metrics::MetricRecorderInterface>& metricRecorder) {
if (!request) {
ACSDK_ERROR(LX("Failed to resolve MessageRequest")
.d("reason", "Null pointer to MessageRequest")
.d("value", resolveKey));
return false;
}
if (encodingFormats.find(resolveKey) == encodingFormats.end()) {
ACSDK_ERROR(LX("Failed to resolve MessageRequest").d("reason", "Invalid resolveKey").d("value", resolveKey));
return false;
}
rapidjson::Document eventWithContext;
jsonUtils::parseJSON(request->getJsonContent(), &eventWithContext);
auto event = eventWithContext.FindMember("event");
if (event == eventWithContext.MemberEnd()) {
ACSDK_ERROR(LX("Failed to resolve MessageRequest").d("reason", "No event found in json"));
return false;
}
auto payload = event->value.FindMember("payload");
if (payload == event->value.MemberEnd()) {
ACSDK_ERROR(LX("Failed to resolve MessageRequest").d("reason", "No payload in json"));
return false;
}
rapidjson::Value formatValue;
auto encodingFormat = encodingFormats.at(resolveKey);
auto formatString = encodingFormatToString(encodingFormat);
formatValue.SetString(formatString.c_str(), static_cast<rapidjson::SizeType>(formatString.length()));
if (payload->value.FindMember(FORMAT_KEY) != payload->value.MemberEnd()) {
ACSDK_WARN(LX("Format already exists in Json payload. Replace it with").d("format", formatString));
payload->value.FindMember(FORMAT_KEY)->value.SetString(formatString.c_str(), eventWithContext.GetAllocator());
} else {
payload->value.AddMember(
rapidjson::StringRef(FORMAT_KEY.c_str()), formatValue, eventWithContext.GetAllocator());
}
// emit metric
auto metricEvent = MetricEventBuilder{}
.setActivityName(AUDIO_ENCODING_FORMAT_ACTIVITY_NAME)
.addDataPoint(DataPointStringBuilder{}.setName("resolveKey").setValue(resolveKey).build());
switch (encodingFormat) {
case AudioFormat::Encoding::LPCM:
submitMetric(
metricRecorder,
metricEvent.addDataPoint(
DataPointCounterBuilder{}.setName(AUDIO_ENCODING_FORMAT_LPCM).increment(1).build()));
break;
case AudioFormat::Encoding::OPUS:
submitMetric(
metricRecorder,
metricEvent.addDataPoint(
DataPointCounterBuilder{}.setName(AUDIO_ENCODING_FORMAT_OPUS).increment(1).build()));
break;
default:
break;
}
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
eventWithContext.Accept(writer);
std::string jsonContent(buffer.GetString());
request->setJsonContent(jsonContent);
if (attachmentReaders.find(resolveKey) != attachmentReaders.end()) {
request->setAttachmentReaders(attachmentReaders.at(resolveKey));
}
return true;
}
std::future<bool> AudioInputProcessor::expectSpeechTimedOut() {
return m_executor.submit([this]() { return executeExpectSpeechTimedOut(); });
}
void AudioInputProcessor::handleStopCaptureDirective(std::shared_ptr<DirectiveInfo> info) {
m_stopCaptureReceivedTime = steady_clock::now();
m_executor.execute([this, info]() {
bool stopImmediately = true;
executeStopCapture(stopImmediately, info);
});
}
void AudioInputProcessor::handleExpectSpeechDirective(std::shared_ptr<DirectiveInfo> info) {
int64_t timeout;
bool found = avsCommon::utils::json::jsonUtils::retrieveValue(
info->directive->getPayload(), "timeoutInMilliseconds", &timeout);
if (!found) {
static const char* errorMessage = "missing/invalid timeoutInMilliseconds";
m_exceptionEncounteredSender->sendExceptionEncountered(
info->directive->getUnparsedDirective(),
avsCommon::avs::ExceptionErrorType::UNSUPPORTED_OPERATION,
errorMessage);
if (info->result) {
info->result->setFailed(errorMessage);
}
ACSDK_ERROR(LX("handleExpectSpeechDirectiveFailed")
.d("reason", "missingJsonField")
.d("field", "timeoutInMilliseconds"));
removeDirective(info);
return;
}
m_executor.execute([this, timeout, info]() { executeExpectSpeech(milliseconds{timeout}, info); });
}
void AudioInputProcessor::handleSetEndOfSpeechOffsetDirective(std::shared_ptr<DirectiveInfo> info) {
// The duration from StopCapture to SetEndOfSpeechOffset. END_OF_SPEECH_OFFSET_RECEIVED starts from Recognize,
// it is not helpful for figuring out the best SHORT timeout.
submitMetric(
m_metricRecorder,
STOP_CAPTURE_TO_END_OF_SPEECH_ACTIVITY_NAME,
DataPointDurationBuilder{duration_cast<milliseconds>(steady_clock::now() - m_stopCaptureReceivedTime)}
.setName(STOP_CAPTURE_TO_END_OF_SPEECH_METRIC_NAME)
.build(),
info->directive);
auto payload = info->directive->getPayload();
int64_t endOfSpeechOffset = 0;
std::string startOfSpeechTimeStampInString;
bool foundEnd = json::jsonUtils::retrieveValue(payload, END_OF_SPEECH_OFFSET_FIELD_NAME, &endOfSpeechOffset);
bool foundStart =
json::jsonUtils::retrieveValue(payload, START_OF_SPEECH_TIMESTAMP_FIELD_NAME, &startOfSpeechTimeStampInString);
if (foundEnd && foundStart) {
int64_t startOfSpeechTimestamp = 0;
auto offset = milliseconds(endOfSpeechOffset);
submitMetric(
m_metricRecorder,
END_OF_SPEECH_OFFSET_RECEIVED_ACTIVITY_NAME,
DataPointDurationBuilder{offset}.setName(END_OF_SPEECH_OFFSET_RECEIVED).build(),
info->directive);
std::istringstream iss{startOfSpeechTimeStampInString};
iss >> startOfSpeechTimestamp;
ACSDK_DEBUG0(LX("handleSetEndOfSpeechOffsetDirective")
.d("startTimeSpeech(ms)", startOfSpeechTimestamp)
.d("endTimeSpeech(ms)", startOfSpeechTimestamp + endOfSpeechOffset));
info->result->setCompleted();
} else {
std::string missing;
if (!foundEnd && !foundStart) {
missing = END_OF_SPEECH_OFFSET_FIELD_NAME + " and " + START_OF_SPEECH_TIMESTAMP_FIELD_NAME;
} else if (!foundEnd) {
missing = END_OF_SPEECH_OFFSET_FIELD_NAME;
} else {
missing = START_OF_SPEECH_TIMESTAMP_FIELD_NAME;
}
ACSDK_ERROR(LX("handleSetEndOfSpeechOffsetDirective").d("missing", missing));
info->result->setFailed("Missing parameter(s): " + missing);
}
removeDirective(info);
}
bool AudioInputProcessor::executeRecognize(
AudioProvider provider,
Initiator initiator,
steady_clock::time_point startOfSpeechTimestamp,
avsCommon::avs::AudioInputStream::Index begin,
avsCommon::avs::AudioInputStream::Index end,
const std::string& keyword,
std::shared_ptr<const std::vector<char>> KWDMetadata,
const std::string& initiatorToken) {
// Make sure we have a keyword if this is a wakeword initiator.
if (Initiator::WAKEWORD == initiator && keyword.empty()) {
ACSDK_ERROR(LX("executeRecognizeFailed").d("reason", "emptyKeywordWithWakewordInitiator"));
return false;
}
// 500ms preroll.
avsCommon::avs::AudioInputStream::Index preroll = provider.format.sampleRateHz / 2;
// Check if we have everything we need to enable false wakeword detection.
// TODO: Consider relaxing the hard requirement for a full 500ms preroll - ACSDK-276.
bool falseWakewordDetection =
Initiator::WAKEWORD == initiator && begin != INVALID_INDEX && begin >= preroll && end != INVALID_INDEX;
// If we will be enabling false wakeword detection, add preroll and build the initiator payload.
json::JsonGenerator generator;
std::string initiatorString = initiatorToString(initiator);
generator.addMember(TYPE_KEY, initiatorString);
generator.startObject(PAYLOAD_KEY);
// If we will be enabling false wakeword detection, add preroll and build the initiator payload.
if (falseWakewordDetection) {
generator.startObject(WAKEWORD_INDICES_KEY);
generator.addMember(START_INDEX_KEY, preroll);
generator.addMember(END_INDEX_KEY, preroll + (end - begin));
generator.finishObject();
begin -= preroll;
}