/
RecognizedPhrase.cs
1223 lines (1081 loc) · 50.2 KB
/
RecognizedPhrase.cs
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Speech.Internal.SapiInterop;
using System.Speech.Internal.SrgsCompiler;
using System.Speech.Internal.SrgsParser;
using System.Text;
using System.Xml;
using System.Xml.XPath;
#pragma warning disable 56500 // Remove all the catch all statements warnings used by the interop layer
namespace System.Speech.Recognition
{
[Serializable]
[DebuggerDisplay("{Text}")]
public class RecognizedPhrase
{
#region Constructors
internal RecognizedPhrase()
{
}
#endregion
#region Public Methods
public IXPathNavigable ConstructSmlFromSemantics()
{
if (!string.IsNullOrEmpty(_smlContent))
{
XmlDocument smlDocument = new();
smlDocument.LoadXml(_smlContent);
return smlDocument;
}
if (_serializedPhrase.SemanticErrorInfoOffset != 0)
{
ThrowInvalidSemanticInterpretationError();
}
XmlDocument document = new();
XmlElement root = document.CreateElement("SML");
NumberFormatInfo nfo = new();
nfo.NumberDecimalDigits = 3;
document.AppendChild(root);
root.SetAttribute("text", Text);
root.SetAttribute("utteranceConfidence", Confidence.ToString("f", nfo));
root.SetAttribute("confidence", Confidence.ToString("f", nfo));
if (Semantics.Count > 0)
{
AppendPropertiesSML(document, root, Semantics, nfo);
}
else if (Semantics.Value != null)
{
XmlText valueText = document.CreateTextNode(Semantics.Value.ToString());
root.AppendChild(valueText);
}
// now append the alternates
for (int i = 0; i < _recoResult.Alternates.Count; i++)
{
RecognizedPhrase alternate = _recoResult.Alternates[i];
alternate.AppendSml(document, i + 1, nfo);
}
_smlContent = document.OuterXml;
return document;
}
#endregion
#region Public Properties
public string Text
{
get
{
if (_text == null)
{
Collection<ReplacementText> replacements = ReplacementWordUnits;
ReplacementText replacement;
int iCurReplacementIndex = 0;
int iWordReplacement = NextReplacementWord(replacements, out replacement, ref iCurReplacementIndex);
StringBuilder sb = new();
for (int i = 0; i < Words.Count; i++)
{
DisplayAttributes displayAttribute;
string text;
if (i == iWordReplacement)
{
displayAttribute = replacement.DisplayAttributes;
text = replacement.Text;
i += replacement.CountOfWords - 1;
iWordReplacement = NextReplacementWord(replacements, out replacement, ref iCurReplacementIndex);
}
else
{
displayAttribute = Words[i].DisplayAttributes;
text = Words[i].Text;
}
// Remove leading spaces
if ((displayAttribute & DisplayAttributes.ConsumeLeadingSpaces) != 0)
{
while (sb.Length > 0 && sb[sb.Length - 1] == ' ')
{
sb.Remove(sb.Length - 1, 1);
}
}
// Append text
sb.Append(text);
// Add trailing spaces
if ((displayAttribute & DisplayAttributes.ZeroTrailingSpaces) != 0)
{
// no action
}
else if ((displayAttribute & DisplayAttributes.OneTrailingSpace) != 0)
{
sb.Append(' ');
}
else if ((displayAttribute & DisplayAttributes.TwoTrailingSpaces) != 0)
{
sb.Append(" ");
}
}
_text = sb.ToString().Trim(' ');
}
return _text;
}
}
public float Confidence
{
get
{
return _confidence;
}
}
public ReadOnlyCollection<RecognizedWordUnit> Words
{
get
{
if (_words == null)
{
int countOfElements = (int)_serializedPhrase.Rule.ulCountOfElements;
int elementsOffset = (int)_serializedPhrase.ElementsOffset;
List<RecognizedWordUnit> wordList = new(countOfElements);
int sizeofPhraseElement = Marshal.SizeOf<SPSERIALIZEDPHRASEELEMENT>();
GCHandle gc = GCHandle.Alloc(_phraseBuffer, GCHandleType.Pinned);
try
{
IntPtr buffer = gc.AddrOfPinnedObject();
for (int i = 0; i < countOfElements; i++)
{
IntPtr elementBuffer = new((long)buffer + elementsOffset + i * sizeofPhraseElement);
SPSERIALIZEDPHRASEELEMENT element = Marshal.PtrToStructure<SPSERIALIZEDPHRASEELEMENT>(elementBuffer);
string displayForm = null, lexicalForm = null, pronunciation = null;
if (element.pszDisplayTextOffset != 0)
{
IntPtr displayFormBuffer = new((long)buffer + (int)element.pszDisplayTextOffset);
displayForm = Marshal.PtrToStringUni(displayFormBuffer);
}
if (element.pszLexicalFormOffset != 0)
{
IntPtr lexicalFormBuffer = new((long)buffer + (int)element.pszLexicalFormOffset);
lexicalForm = Marshal.PtrToStringUni(lexicalFormBuffer);
}
if (element.pszPronunciationOffset != 0)
{
IntPtr pronunciationBuffer = new((long)buffer + (int)element.pszPronunciationOffset);
pronunciation = Marshal.PtrToStringUni(pronunciationBuffer);
if (!_hasIPAPronunciation)
{
pronunciation = _recoResult.ConvertPronunciation(pronunciation, _serializedPhrase.LangID);
}
}
DisplayAttributes displayAttributes = RecognizedWordUnit.SapiAttributesToDisplayAttributes(element.bDisplayAttributes);
// On SAPI 5.1, the engine confidence is not set. Force a value in this case
if (!_isSapi53Header)
{
element.SREngineConfidence = 1.0f;
}
wordList.Add(new RecognizedWordUnit(displayForm, element.SREngineConfidence, pronunciation, lexicalForm, displayAttributes, new TimeSpan(element.ulAudioTimeOffset * TimeSpan.TicksPerMillisecond / 10000), new TimeSpan(element.ulAudioSizeTime * TimeSpan.TicksPerMillisecond / 10000)));
}
_words = new ReadOnlyCollection<RecognizedWordUnit>(wordList);
}
finally
{
gc.Free();
}
}
return _words;
}
}
// Semantic data about result:
public SemanticValue Semantics
{
get
{
if (_serializedPhrase.SemanticErrorInfoOffset != 0)
{
ThrowInvalidSemanticInterpretationError();
}
if (_phraseBuffer == null)
{
throw new NotSupportedException();
}
if (_semantics == null)
{
CalcSemantics(Grammar);
}
return _semantics;
}
}
// Homophonic alternates for this phrase
public ReadOnlyCollection<RecognizedPhrase> Homophones
{
get
{
if (_phraseBuffer == null)
{
throw new NotSupportedException();
}
if (_homophones == null)
{
// Walks the list of alternates and collects all phrases that have the same
// homophoneGroupId at the phrase
List<RecognizedPhrase> homophones = new(_recoResult.Alternates.Count);
for (int i = 0; i < _recoResult.Alternates.Count; i++)
{
if ((_recoResult.Alternates[i]._homophoneGroupId == _homophoneGroupId) && (_recoResult.Alternates[i].Text != this.Text))
{
homophones.Add(_recoResult.Alternates[i]);
}
}
_homophones = new ReadOnlyCollection<RecognizedPhrase>(homophones);
}
return _homophones;
}
}
public Grammar Grammar
{
get
{
// If this phrase comes from a deserialize, then throw
if (_grammarId == unchecked((ulong)(-1)))
{
throw new NotSupportedException(SR.Get(SRID.CantGetPropertyFromSerializedInfo, "Grammar"));
}
if (_grammar == null && _recoResult.Recognizer != null)
{
_grammar = _recoResult.Recognizer.GetGrammarFromId(_grammarId);
}
return _grammar;
}
}
public Collection<ReplacementText> ReplacementWordUnits
{
get
{
if (_replacementText == null)
{
_replacementText = new Collection<ReplacementText>();
GCHandle gc = GCHandle.Alloc(_phraseBuffer, GCHandleType.Pinned);
try
{
IntPtr buffer = gc.AddrOfPinnedObject();
// Get the ITN and Look for replacement phrase/
IntPtr itnBuffer = new((long)buffer + _serializedPhrase.ReplacementsOffset);
for (int i = 0; i < _serializedPhrase.cReplacements; i++, itnBuffer = (nint)itnBuffer + Marshal.SizeOf<SPPHRASEREPLACEMENT>())
{
SPPHRASEREPLACEMENT replacement = (SPPHRASEREPLACEMENT)Marshal.PtrToStructure<SPPHRASEREPLACEMENT>(itnBuffer);
string text = Marshal.PtrToStringUni(new IntPtr((long)buffer + replacement.pszReplacementText));
DisplayAttributes displayAttributes = RecognizedWordUnit.SapiAttributesToDisplayAttributes(replacement.bDisplayAttributes);
_replacementText.Add(new ReplacementText(displayAttributes, text, (int)replacement.ulFirstElement, (int)replacement.ulCountOfElements));
}
}
finally
{
gc.Free();
}
}
return _replacementText;
}
}
public int HomophoneGroupId
{
get
{
return _homophoneGroupId;
}
}
#endregion
#region Internal Methods
internal static SPSERIALIZEDPHRASE GetPhraseHeader(IntPtr phraseBuffer, uint expectedPhraseSize, bool isSapi53Header)
{
SPSERIALIZEDPHRASE serializedPhrase;
if (isSapi53Header)
{
serializedPhrase = Marshal.PtrToStructure<SPSERIALIZEDPHRASE>(phraseBuffer);
}
else
{
SPSERIALIZEDPHRASE_Sapi51 legacyPhrase = Marshal.PtrToStructure<SPSERIALIZEDPHRASE_Sapi51>(phraseBuffer);
serializedPhrase = new SPSERIALIZEDPHRASE(legacyPhrase);
}
if (serializedPhrase.ulSerializedSize > expectedPhraseSize)
{
throw new FormatException(SR.Get(SRID.ResultInvalidFormat));
}
return serializedPhrase;
}
internal void InitializeFromSerializedBuffer(RecognitionResult recoResult, SPSERIALIZEDPHRASE serializedPhrase, IntPtr phraseBuffer, int phraseLength, bool isSapi53Header, bool hasIPAPronunciation)
{
_recoResult = recoResult;
_isSapi53Header = isSapi53Header;
_serializedPhrase = serializedPhrase;
_confidence = _serializedPhrase.Rule.SREngineConfidence;
_grammarId = _serializedPhrase.ullGrammarID;
_homophoneGroupId = _serializedPhrase.wHomophoneGroupId;
_hasIPAPronunciation = hasIPAPronunciation;
// Save the phrase blob
_phraseBuffer = new byte[phraseLength];
Marshal.Copy(phraseBuffer, _phraseBuffer, 0, phraseLength);
// Get the grammar options
_grammarOptions = recoResult.Grammar != null ? recoResult.Grammar._semanticTag : GrammarOptions.KeyValuePairSrgs;
// This triggers the semantic processing if any
CalcSemantics(recoResult.Grammar);
}
#endregion
#region Internal Properties
internal ulong GrammarId
{
get
{
return _grammarId;
}
}
internal string SmlContent
{
get
{
if (_smlContent == null)
{
// this method already sets _smlContent
ConstructSmlFromSemantics();
}
return _smlContent;
}
}
#endregion
#region Internal fields
internal SPSERIALIZEDPHRASE _serializedPhrase;
internal byte[] _phraseBuffer;
internal bool _isSapi53Header;
internal bool _hasIPAPronunciation;
#endregion
#region Private Methods
// Semantic data about result:
private void CalcSemantics(Grammar grammar)
{
if (_semantics == null && _serializedPhrase.SemanticErrorInfoOffset == 0)
{
GCHandle gc = GCHandle.Alloc(_phraseBuffer, GCHandleType.Pinned);
try
{
IntPtr buffer = gc.AddrOfPinnedObject();
if (!CalcILSemantics(buffer))
{
// List of recognized words
IList<RecognizedWordUnit> words = Words;
// Build the list of rules and property values
RuleNode ruleTree = ExtractRules(grammar, _serializedPhrase.Rule, buffer);
List<ResultPropertiesRef> propertyList = BuildRecoPropertyTree(_serializedPhrase, buffer, ruleTree, words, _isSapi53Header);
// Recursively build the dictionary of properties
_semantics = RecursiveBuildSemanticProperties(words, propertyList, ruleTree, _grammarOptions & GrammarOptions.TagFormat, ref _dupItems);
// Delay the call to TryExecuteOnRecognition until the _semantics has been set
_semantics.Value = TryExecuteOnRecognition(grammar, _recoResult, ruleTree._rule);
}
}
finally
{
gc.Free();
}
}
}
private bool CalcILSemantics(IntPtr phraseBuffer)
{
if ((_grammarOptions & (GrammarOptions.MssV1 | GrammarOptions.W3cV1)) != 0 || _grammarOptions == GrammarOptions.KeyValuePairs)
{
IList<RecognizedWordUnit> words = Words;
_semantics = new SemanticValue("<ROOT>", null, _confidence);
if (_serializedPhrase.PropertiesOffset != 0)
{
RecursivelyExtractSemanticValue(phraseBuffer, (int)_serializedPhrase.PropertiesOffset, _semantics, words, _isSapi53Header, _grammarOptions & GrammarOptions.TagFormat);
}
return true;
}
return false;
}
private static List<ResultPropertiesRef> BuildRecoPropertyTree(SPSERIALIZEDPHRASE serializedPhrase, IntPtr phraseBuffer, RuleNode ruleTree, IList<RecognizedWordUnit> words, bool isSapi53Header)
{
List<ResultPropertiesRef> propertyList = new();
// Array of string containing the rule names.
if ((int)serializedPhrase.PropertiesOffset > 0)
{
RecursivelyExtractSemanticProperties(propertyList, (int)serializedPhrase.PropertiesOffset, phraseBuffer, ruleTree, words, isSapi53Header);
}
return propertyList;
}
private static SemanticValue RecursiveBuildSemanticProperties(IList<RecognizedWordUnit> words, List<ResultPropertiesRef> properties, RuleNode ruleTree, GrammarOptions semanticTag, ref Collection<SemanticValue> dupItems)
{
SemanticValue semanticValue = new(ruleTree._name, null, ruleTree._confidence);
// Add the semantic values from the child rules
for (RuleNode children = ruleTree._child; children != null; children = children._next)
{
// Propagate up the semantic values calculated at the children level
SemanticValue childrenSemantics = RecursiveBuildSemanticProperties(words, properties, children, semanticTag, ref dupItems);
if (!children._hasName)
{
foreach (KeyValuePair<string, SemanticValue> kv in childrenSemantics._dictionary)
{
InsertSemanticValueToDictionary(semanticValue, kv.Key, kv.Value, semanticTag, ref dupItems);
}
if (childrenSemantics.Value != null)
{
if ((semanticTag & (GrammarOptions.MssV1 | GrammarOptions.W3cV1)) == 0 && semanticValue._valueFieldSet && !semanticValue.Value.Equals(childrenSemantics.Value))
{
throw new InvalidOperationException(SR.Get(SRID.DupSemanticValue, ruleTree._name));
}
semanticValue.Value = childrenSemantics.Value;
semanticValue._valueFieldSet = true;
}
}
else
{
// If no value has been set then the recognized text is returned as the value
if (!childrenSemantics._valueFieldSet && childrenSemantics.Count == 0)
{
StringBuilder sb = new();
for (int i = 0; i < children._count; i++)
{
if (sb.Length > 0)
{
sb.Append(' ');
}
sb.Append(words[(int)children._firstElement + i].Text);
}
childrenSemantics._valueFieldSet = true;
childrenSemantics.Value = sb.ToString();
}
semanticValue._dictionary.Add(children._name, childrenSemantics);
}
}
// Add the semantic value from the properties
foreach (ResultPropertiesRef property in properties)
{
if (property._ruleNode == ruleTree)
{
InsertSemanticValueToDictionary(semanticValue, property._name, property._value, semanticTag, ref dupItems);
}
}
Exception exceptionThrown = null;
// Try to execute the semantic value if OnParse is defined
object newValue;
bool doneOnParse = TryExecuteOnParse(ruleTree, semanticValue, words, out newValue, ref exceptionThrown);
if (exceptionThrown != null)
{
ExceptionDispatchInfo.Throw(exceptionThrown);
}
//
if (doneOnParse)
{
semanticValue._dictionary.Clear();
semanticValue.Value = newValue;
semanticValue._valueFieldSet = true;
}
return semanticValue;
}
private static void RecursivelyExtractSemanticProperties(List<ResultPropertiesRef> propertyList, int semanticsOffset, IntPtr phraseBuffer, RuleNode ruleTree, IList<RecognizedWordUnit> words, bool isSapi53Header)
{
IntPtr propertyBuffer = new((long)phraseBuffer + semanticsOffset);
SPSERIALIZEDPHRASEPROPERTY property = Marshal.PtrToStructure<SPSERIALIZEDPHRASEPROPERTY>(propertyBuffer);
string propertyName;
SemanticValue thisSemanticValue = ExtractSemanticValueInformation(semanticsOffset, property, phraseBuffer, isSapi53Header, out propertyName);
RuleNode node = ruleTree.Find(property.ulFirstElement, property.ulCountOfElements);
if (propertyName == "SemanticKey")
{
node._name = (string)thisSemanticValue.Value;
node._hasName = true;
}
else
{
propertyList.Add(new ResultPropertiesRef(propertyName, thisSemanticValue, node));
}
if (property.pFirstChildOffset > 0)
{
// add children to the new node
RecursivelyExtractSemanticProperties(propertyList, (int)property.pFirstChildOffset, phraseBuffer, ruleTree, words, isSapi53Header);
}
if (property.pNextSiblingOffset > 0)
{
// add siblings to parent node
RecursivelyExtractSemanticProperties(propertyList, (int)property.pNextSiblingOffset, phraseBuffer, ruleTree, words, isSapi53Header);
}
}
private void RecursivelyExtractSemanticValue(IntPtr phraseBuffer, int semanticsOffset, SemanticValue semanticValue, IList<RecognizedWordUnit> words, bool isSapi53Header, GrammarOptions semanticTag)
{
IntPtr propertyBuffer = new((long)phraseBuffer + semanticsOffset);
SPSERIALIZEDPHRASEPROPERTY property =
Marshal.PtrToStructure<SPSERIALIZEDPHRASEPROPERTY>(propertyBuffer);
string propertyName;
SemanticValue thisSemanticValue = ExtractSemanticValueInformation(semanticsOffset, property, phraseBuffer, isSapi53Header, out propertyName);
if (propertyName == "_value" && semanticValue != null)
{
// 'remove' the _value node from the tree by setting its value to the parent's value
// and use the parent as the node to add children (if present)
semanticValue.Value = thisSemanticValue.Value;
if (property.pFirstChildOffset > 0)
{
thisSemanticValue = semanticValue;
}
}
else
{
InsertSemanticValueToDictionary(semanticValue, propertyName, thisSemanticValue, semanticTag, ref _dupItems);
}
if (property.pFirstChildOffset > 0)
{
// add children to the new node
RecursivelyExtractSemanticValue(phraseBuffer, (int)property.pFirstChildOffset, thisSemanticValue, words, isSapi53Header, semanticTag);
}
if (property.pNextSiblingOffset > 0)
{
// add siblings to parent node
RecursivelyExtractSemanticValue(phraseBuffer, (int)property.pNextSiblingOffset, semanticValue, words, isSapi53Header, semanticTag);
}
}
private static void InsertSemanticValueToDictionary(SemanticValue semanticValue, string propertyName, SemanticValue thisSemanticValue, GrammarOptions semanticTag, ref Collection<SemanticValue> dupItems)
{
string key = propertyName;
if ((key == "$" && semanticTag == GrammarOptions.MssV1)
|| (key == "=" && (semanticTag == GrammarOptions.KeyValuePairSrgs || semanticTag == GrammarOptions.KeyValuePairs))
|| (thisSemanticValue.Count == -1 && semanticTag == GrammarOptions.W3cV1))
{
if ((semanticTag & (GrammarOptions.MssV1 | GrammarOptions.W3cV1)) == 0 && semanticValue._valueFieldSet && !semanticValue.Value.Equals(thisSemanticValue.Value))
{
throw new InvalidOperationException(SR.Get(SRID.DupSemanticValue, semanticValue.KeyName));
}
semanticValue.Value = thisSemanticValue.Value;
semanticValue._valueFieldSet = true;
}
else
{
bool containsKey = semanticValue._dictionary.ContainsKey(key);
if (!containsKey)
{
semanticValue._dictionary.Add(key, thisSemanticValue);
}
else
{
if (!semanticValue._dictionary[key].Equals(thisSemanticValue))
{
// Error out for Srgs grammars
if (semanticTag == GrammarOptions.KeyValuePairSrgs)
{
throw new InvalidOperationException(SR.Get(SRID.DupSemanticKey, propertyName, semanticValue.KeyName));
}
// Append a _* on the key name for none SAPI grammars
int count = 0;
do
{
key = propertyName + string.Format(CultureInfo.InvariantCulture, "_{0}", count++);
}
while (semanticValue._dictionary.ContainsKey(key));
semanticValue._dictionary.Add(key, thisSemanticValue);
dupItems ??= new Collection<SemanticValue>();
SemanticValue s = semanticValue._dictionary[key];
dupItems.Add(s);
}
}
}
}
private static SemanticValue ExtractSemanticValueInformation(int semanticsOffset, SPSERIALIZEDPHRASEPROPERTY property, IntPtr phraseBuffer, bool isSapi53Header, out string propertyName)
{
object propertyValue;
bool isIdName = false;
if (property.pszNameOffset > 0)
{
IntPtr nameBuffer = new((long)phraseBuffer + (int)property.pszNameOffset);
propertyName = Marshal.PtrToStringUni(nameBuffer);
}
else
{
propertyName = property.ulId.ToString(CultureInfo.InvariantCulture);
isIdName = true;
}
if (property.pszValueOffset > 0)
{
IntPtr valueStringBuffer = new((long)phraseBuffer + (int)property.pszValueOffset);
propertyValue = Marshal.PtrToStringUni(valueStringBuffer);
if (!isSapi53Header && isIdName && ((string)propertyValue).Contains("$"))
{
// SAPI 5.1 result that contains script fragments rather than output of executing script.
// Strip this information as script-based grammars aren't supported on 5.1.
throw new NotSupportedException(SR.Get(SRID.NotSupportedWithThisVersionOfSAPI));
}
}
else
{
if (property.SpVariantSubset >= 0)
{
IntPtr valueBuffer = new((long)phraseBuffer + +semanticsOffset + SpVariantSubsetOffset);
#pragma warning disable 0618 // VarEnum is obsolete
switch ((VarEnum)property.vValue)
{
case VarEnum.VT_I4:
propertyValue = Marshal.ReadInt32(valueBuffer);
break;
case VarEnum.VT_UI4:
propertyValue = Marshal.PtrToStructure<uint>(valueBuffer);
break;
case VarEnum.VT_I8:
propertyValue = Marshal.ReadInt64(valueBuffer);
break;
case VarEnum.VT_UI8:
propertyValue = Marshal.PtrToStructure<ulong>(valueBuffer);
break;
case VarEnum.VT_R4:
propertyValue = Marshal.PtrToStructure<float>(valueBuffer);
break;
case VarEnum.VT_R8:
propertyValue = Marshal.PtrToStructure<double>(valueBuffer);
break;
case VarEnum.VT_BOOL:
propertyValue = (Marshal.ReadByte(valueBuffer) != 0);
break;
case VarEnum.VT_EMPTY:
propertyValue = null;
break;
default:
throw new NotSupportedException(SR.Get(SRID.UnhandledVariant));
}
#pragma warning restore 0618
}
else
{
propertyValue = string.Empty;
}
}
return new SemanticValue(propertyName, propertyValue, property.SREngineConfidence);
}
private static RuleNode ExtractRules(Grammar grammar, SPSERIALIZEDPHRASERULE rule, IntPtr phraseBuffer)
{
// Get the rule name
IntPtr nameBuffer = new((long)phraseBuffer + (int)rule.pszNameOffset);
// Add the rule name to the proper element index
string name = Marshal.PtrToStringUni(nameBuffer);
// find the grammar for this rule. If the grammar does not belong to any existing ruleref then
// it must be local.
Grammar ruleRef = grammar?.Find(name);
if (ruleRef != null)
{
grammar = ruleRef;
}
RuleNode node = new(grammar, name, rule.SREngineConfidence, rule.ulFirstElement, rule.ulCountOfElements);
if (rule.NextSiblingOffset > 0)
{
IntPtr elementBuffer = new((long)phraseBuffer + rule.NextSiblingOffset);
SPSERIALIZEDPHRASERULE ruleNext = Marshal.PtrToStructure<SPSERIALIZEDPHRASERULE>(elementBuffer);
node._next = ExtractRules(grammar, ruleNext, phraseBuffer);
}
if (rule.FirstChildOffset > 0)
{
IntPtr elementBuffer = new((long)phraseBuffer + rule.FirstChildOffset);
SPSERIALIZEDPHRASERULE ruleFirst = Marshal.PtrToStructure<SPSERIALIZEDPHRASERULE>(elementBuffer);
node._child = ExtractRules(grammar, ruleFirst, phraseBuffer);
}
return node;
}
private void ThrowInvalidSemanticInterpretationError()
{
//string error;
if (!_isSapi53Header)
{
throw new NotSupportedException(SR.Get(SRID.NotSupportedWithThisVersionOfSAPI));
}
GCHandle gc = GCHandle.Alloc(_phraseBuffer, GCHandleType.Pinned);
try
{
IntPtr smlBuffer = gc.AddrOfPinnedObject();
SPSEMANTICERRORINFO semanticError = Marshal.PtrToStructure<SPSEMANTICERRORINFO>((nint)smlBuffer + (nint)_serializedPhrase.SemanticErrorInfoOffset);
string source = Marshal.PtrToStringUni((nint)smlBuffer + (nint)semanticError.pszSourceOffset);
string description = Marshal.PtrToStringUni((nint)smlBuffer + (nint)semanticError.pszDescriptionOffset);
string script = Marshal.PtrToStringUni((nint)smlBuffer + (nint)semanticError.pszScriptLineOffset);
string error = string.Format(CultureInfo.InvariantCulture, "Error while evaluating semantic interpretation:\n" +
" HRESULT: {0:x}\n" +
" Line: {1}\n" +
" Source: {2}\n" +
" Description: {3}\n" +
" Script: {4}\n", semanticError.hrResultCode, semanticError.ulLineNumber, source, description, script);
throw new InvalidOperationException(error);
}
finally
{
gc.Free();
}
}
private static bool TryExecuteOnParse(RuleNode ruleRef, SemanticValue value, IList<RecognizedWordUnit> words, out object newValue, ref Exception exceptionThrown)
{
newValue = null;
bool doneOnParse = false;
Grammar grammar = ruleRef._grammar;
if (grammar != null && grammar._scripts != null)
{
// Check if the Inner
try
{
if (exceptionThrown == null)
{
doneOnParse = ExecuteOnParse(grammar, ruleRef, value, words, out newValue);
}
else
{
if (ExecuteOnError(grammar, ruleRef, exceptionThrown))
{
exceptionThrown = null;
}
}
}
catch (Exception e)
{
if (exceptionThrown == null)
{
exceptionThrown = e;
// Try to execute on Error on this thread
try
{
if (ExecuteOnError(grammar, ruleRef, exceptionThrown))
{
exceptionThrown = null;
}
}
catch (Exception e2)
{
exceptionThrown = e2;
}
}
}
}
return doneOnParse;
}
private static bool ExecuteOnParse(Grammar grammar, RuleNode ruleRef, SemanticValue value, IList<RecognizedWordUnit> words, out object newValue)
{
// Get the rule list
ScriptRef[] scripts = grammar._scripts;
bool doneOnParse = false;
newValue = null;
// Look if an OnParse exist for this method
for (int iScript = 0; iScript < scripts.Length; iScript++)
{
ScriptRef script = scripts[iScript];
if (ruleRef._rule == script._rule)
{
if (script._method == RuleMethodScript.onParse)
{
// Get the method to invoke
RecognizedWordUnit[] recoUnits = new RecognizedWordUnit[ruleRef._count];
for (int i = 0; i < ruleRef._count; i++)
{
recoUnits[i] = words[i];
}
object[] parameters = new object[2] { value, recoUnits };
if (grammar._proxy != null)
{
Exception appDomainException;
newValue = grammar._proxy.OnParse(script._rule, script._sMethod, parameters, out appDomainException);
if (appDomainException != null)
{
ExceptionDispatchInfo.Throw(appDomainException);
}
}
else
{
MethodInfo onParse;
System.Speech.Recognition.Grammar rule;
GetRuleInstance(grammar, script._rule, script._sMethod, out onParse, out rule);
// Execute the parse routine
newValue = onParse.Invoke(rule, parameters);
}
doneOnParse = true;
}
}
}
return doneOnParse;
}
private static bool ExecuteOnError(Grammar grammar, RuleNode ruleRef, Exception e)
{
// Get the rule list
ScriptRef[] scripts = grammar._scripts;
bool invoked = false;
// Look if an OnParse exist for this method
for (int iScript = 0; iScript < scripts.Length; iScript++)
{
ScriptRef script = scripts[iScript];
if (ruleRef._rule == script._rule)
{
if (script._method == RuleMethodScript.onError)
{
// Get the method to invoke
object[] parameters = new object[] { e };
if (grammar._proxy != null)
{
Exception appDomainException;
grammar._proxy.OnError(script._rule, script._sMethod, parameters, out appDomainException);
if (appDomainException != null)
{
ExceptionDispatchInfo.Throw(appDomainException);
}
}
else
{
MethodInfo onError;
System.Speech.Recognition.Grammar rule;
GetRuleInstance(grammar, script._rule, script._sMethod, out onError, out rule);
// Execute the parse routine
onError.Invoke(rule, parameters);
}
invoked = true;
}
}
}
return invoked;
}
private static object TryExecuteOnRecognition(Grammar grammar, RecognitionResult result, string rootRule)
{
object resultValue = result.Semantics.Value;
if (grammar != null && grammar._scripts != null)
{
// Get the rule list
ScriptRef[] scripts = grammar._scripts;
// Look if an OnRecognition exist for this method
for (int iScript = 0; iScript < scripts.Length; iScript++)
{
ScriptRef script = scripts[iScript];
if (rootRule == script._rule)
{
if (script._method == RuleMethodScript.onRecognition)
{
// Get the method to invoke
object[] parameters = new object[1] { result };
if (grammar._proxy != null)
{
Exception appDomainException;
resultValue = grammar._proxy.OnRecognition(script._sMethod, parameters, out appDomainException);
if (appDomainException != null)
{
ExceptionDispatchInfo.Throw(appDomainException);
}
}
else
{
Type grammarType = grammar.GetType();
MethodInfo onRecognition = grammarType.GetMethod(script._sMethod, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
// Execute the parse routine
resultValue = onRecognition.Invoke(grammar, parameters);
}
}
}
}
}
return resultValue;
}
private static void GetRuleInstance(Grammar grammar, string rule, string method, out MethodInfo onParse, out Grammar ruleInstance)
{
Type grammarType = grammar.GetType();
Assembly assembly = grammarType.Assembly;
Type ruleClass = rule == grammarType.Name ? grammarType : GetTypeForRule(assembly, rule);
if (ruleClass == null || !ruleClass.IsSubclassOf(typeof(System.Speech.Recognition.Grammar)))
{
throw new FormatException(SR.Get(SRID.RecognizerInvalidBinaryGrammar));
}
ruleInstance = ruleClass == grammarType ? grammar : (System.Speech.Recognition.Grammar)assembly.CreateInstance(ruleClass.FullName);
onParse = ruleInstance.MethodInfo(method);
}
private static Type GetTypeForRule(Assembly assembly, string rule)
{
Type[] types = assembly.GetTypes();
for (int iType = 0; iType < types.Length; iType++)
{