-
Notifications
You must be signed in to change notification settings - Fork 4.7k
/
EngineSite.cs
535 lines (472 loc) · 16 KB
/
EngineSite.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
// 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;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Speech.Synthesis;
using System.Speech.Synthesis.TtsEngine;
using System.Text;
// Exceptions cannot get through the COM code.
// The engine site saves the last exception before sending it back to the client.
#pragma warning disable 6500
namespace System.Speech.Internal.Synthesis
{
internal class EngineSite : ITtsEngineSite, ITtsEventSink
{
#region Constructors
internal EngineSite(ResourceLoader resourceLoader)
{
_resourceLoader = resourceLoader;
}
#endregion
#region Internal Methods
internal TtsEventMapper EventMapper
{
get
{
return _eventMapper;
}
set
{
_eventMapper = value;
}
}
#region ISpTTSEngineStite implementation
/// <summary>
/// Adds events directly to an event sink.
/// </summary>
public void AddEvents([MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] SpeechEventInfo[] events, int ulCount)
{
try
{
foreach (SpeechEventInfo sapiEvent in events)
{
int evtMask = 1 << sapiEvent.EventId;
if (sapiEvent.EventId == (short)TtsEventId.EndInputStream && _eventMapper != null)
{
_eventMapper.FlushEvent();
}
if ((evtMask & _eventInterest) != 0)
{
TTSEvent ttsEvent = CreateTtsEvent(sapiEvent);
if (_eventMapper == null)
{
AddEvent(ttsEvent);
}
else
{
_eventMapper.AddEvent(ttsEvent);
}
}
}
}
catch (Exception e)
{
_exception = e;
_actions |= SPVESACTIONS.SPVES_ABORT;
}
}
/// <summary>
/// Queries the voice object to determine which real-time action(s) to perform.
/// </summary>
public int Write(IntPtr pBuff, int cb)
{
try
{
_audio.Play(pBuff, cb);
}
catch (Exception e)
{
_exception = e;
_actions |= SPVESACTIONS.SPVES_ABORT;
}
return cb;
}
/// <summary>
/// Retrieves the number and type of items to be skipped in the text stream.
/// </summary>
public SkipInfo GetSkipInfo()
{
return new SkipInfo(1 /*BSPVSKIPTYPE.SPVST_SENTENCE */, 1);
}
/// <summary>
/// Notifies that the last skip request has been completed and to pass it the results.
/// </summary>
public void CompleteSkip(int ulNumSkipped)
{
return;
}
/// <summary>
/// Passes back the event interest for the voice.
/// </summary>
public int EventInterest
{
get
{
return _eventInterest;
}
}
/// <summary>
/// Queries the voice object to determine which real-time action(s) to perform
/// </summary>
public int Actions
{
get
{
return (int)_actions;
}
}
/// <summary>
/// Retrieves the current TTS rendering rate adjustment that should be used by the engine.
/// </summary>
public int Rate
{
get
{
_actions &= ~SPVESACTIONS.SPVES_RATE;
return _defaultRate;
}
}
/// <summary>
/// Retrieves the base output volume level the engine should use during synthesis.
/// </summary>
public int Volume
{
get
{
_actions &= ~SPVESACTIONS.SPVES_VOLUME;
return _volume;
}
}
/// <summary>
/// Load a file either from a local network or from the Internet.
/// </summary>
public Stream LoadResource(Uri uri, string mediaType)
{
try
{
string localPath;
string mediaTypeUnused; // TODO: Should this be passed out of this function?
Uri baseUriUnused;
using (Stream stream = _resourceLoader.LoadFile(uri, out mediaTypeUnused, out baseUriUnused, out localPath))
{
// Read the file in memory for SES and release the original file immediately
// This scheme is really bad if the files being read are big but I would assume
// That it should not be the case.
int cLen = (int)stream.Length;
MemoryStream memStream = new(cLen);
byte[] ab = new byte[cLen];
stream.Read(ab, 0, ab.Length);
_resourceLoader.UnloadFile(localPath);
memStream.Write(ab, 0, cLen);
memStream.Position = 0;
return memStream;
}
}
catch (Exception e)
{
_exception = e;
_actions |= SPVESACTIONS.SPVES_ABORT;
}
return null;
}
#endregion
public void AddEvent(TTSEvent evt)
{
_audio.InjectEvent(evt);
}
public void FlushEvent()
{
}
internal void SetEventsInterest(int eventInterest)
{
_eventInterest = eventInterest;
_eventMapper?.FlushEvent();
}
#endregion
#region Internal Properties
/// <summary>
/// Retrieves the current TTS rendering rate adjustment that should be used by the engine.
/// </summary>
internal int VoiceRate
{
get
{
return _defaultRate;
}
set
{
_defaultRate = value;
_actions |= SPVESACTIONS.SPVES_RATE;
}
}
/// <summary>
/// Retrieves the base output volume level the engine should use during synthesis.
/// </summary>
internal int VoiceVolume
{
get
{
return _volume;
}
set
{
_volume = value;
_actions |= SPVESACTIONS.SPVES_VOLUME;
}
}
/// <summary>
/// Set and reset the last exception
/// </summary>
internal Exception LastException
{
get
{
return _exception;
}
set
{
_exception = value;
}
}
internal void Abort()
{
_actions = SPVESACTIONS.SPVES_ABORT;
}
internal void InitRun(AudioBase audioDevice, int defaultRate, Prompt prompt)
{
_audio = audioDevice;
_prompt = prompt;
_defaultRate = defaultRate;
_actions = SPVESACTIONS.SPVES_RATE | SPVESACTIONS.SPVES_VOLUME;
}
#endregion
#region Private Members
private TTSEvent CreateTtsEvent(SpeechEventInfo sapiEvent)
{
TTSEvent ttsEvent;
switch ((TtsEventId)sapiEvent.EventId)
{
case TtsEventId.Phoneme:
ttsEvent = TTSEvent.CreatePhonemeEvent("" + (char)((uint)sapiEvent.Param2 & 0xFFFF), // current phoneme
"" + (char)(sapiEvent.Param1 & 0xFFFF), // next phoneme
TimeSpan.FromMilliseconds(sapiEvent.Param1 >> 16),
(SynthesizerEmphasis)((uint)sapiEvent.Param2 >> 16),
_prompt, _audio.Duration);
break;
case TtsEventId.Bookmark:
// BookmarkDetected
string bookmark = Marshal.PtrToStringUni(sapiEvent.Param2);
ttsEvent = new TTSEvent((TtsEventId)sapiEvent.EventId, _prompt, null, null, _audio.Duration, _audio.Position, bookmark, (uint)sapiEvent.Param1, sapiEvent.Param2);
break;
default:
ttsEvent = new TTSEvent((TtsEventId)sapiEvent.EventId, _prompt, null, null, _audio.Duration, _audio.Position, null, (uint)sapiEvent.Param1, sapiEvent.Param2);
break;
}
return ttsEvent;
}
#endregion
#region private Fields
private int _eventInterest;
private SPVESACTIONS _actions = SPVESACTIONS.SPVES_RATE | SPVESACTIONS.SPVES_VOLUME;
private AudioBase _audio;
private Prompt _prompt;
// Last Exception
private Exception _exception;
// Rate setup in the control panel
private int _defaultRate;
// Rate setup in the control panel
private int _volume = 100;
// Get a resource load
private ResourceLoader _resourceLoader;
// Map the TTS events to the right format
private TtsEventMapper _eventMapper;
#endregion
}
internal interface ITtsEventSink
{
void AddEvent(TTSEvent evt);
void FlushEvent();
}
internal abstract class TtsEventMapper : ITtsEventSink
{
internal TtsEventMapper(ITtsEventSink sink)
{
_sink = sink;
}
protected virtual void SendToOutput(TTSEvent evt)
{
_sink?.AddEvent(evt);
}
public virtual void AddEvent(TTSEvent evt)
{
SendToOutput(evt);
}
public virtual void FlushEvent()
{
_sink?.FlushEvent();
}
private ITtsEventSink _sink;
}
internal class PhonemeEventMapper : TtsEventMapper
{
public enum PhonemeConversion
{
IpaToSapi,
SapiToIpa,
NoConversion
}
internal PhonemeEventMapper(ITtsEventSink sink, PhonemeConversion conversion, AlphabetConverter alphabetConverter) : base(sink)
{
_queue = new Queue();
_phonemeQueue = new Queue();
_conversion = conversion;
_alphabetConverter = alphabetConverter;
Reset();
}
public override void AddEvent(TTSEvent evt)
{
if (_conversion == PhonemeConversion.NoConversion)
{
SendToOutput(evt);
}
else if (evt.Id == TtsEventId.Phoneme)
{
_phonemeQueue.Enqueue(evt);
int prefixSeek = _phonemes.Length + 1;
_phonemes.Append(evt.Phoneme);
do
{
string prefix = _phonemes.ToString(0, prefixSeek);
if (_alphabetConverter.IsPrefix(prefix, _conversion == PhonemeConversion.SapiToIpa))
{
if (_alphabetConverter.IsConvertibleUnit(prefix, _conversion == PhonemeConversion.SapiToIpa))
{
_lastComplete = prefixSeek;
}
prefixSeek++;
}
else
{
if (_lastComplete == 0)
{
Trace.TraceError("Cannot convert the phonemes correctly. Attempt to start over...");
Reset();
break;
}
ConvertCompleteUnit();
_lastComplete = 0;
prefixSeek = 1;
}
} while (prefixSeek <= _phonemes.Length);
}
else
{
SendToQueue(evt);
}
}
public override void FlushEvent()
{
ConvertCompleteUnit();
while (_queue.Count > 0)
{
SendToOutput((TTSEvent)_queue.Dequeue());
}
_phonemeQueue.Clear();
_lastComplete = 0;
base.FlushEvent();
}
private void ConvertCompleteUnit()
{
if (_lastComplete == 0)
{
return;
}
if (_phonemeQueue.Count == 0)
{
Trace.TraceError("Failed to convert phonemes. Phoneme queue is empty.");
return;
}
char[] source = new char[_lastComplete];
_phonemes.CopyTo(0, source, 0, _lastComplete);
_phonemes.Remove(0, _lastComplete);
char[] target;
if (_conversion == PhonemeConversion.IpaToSapi)
{
target = _alphabetConverter.IpaToSapi(source);
}
else
{
target = _alphabetConverter.SapiToIpa(source);
}
//
// Convert the audio duration
// Update the next phoneme id
// Retain any other information based on the first TTS phoneme event.
//
TTSEvent ttsEvent, targetEvent, basePhonemeEvent = null;
long totalDuration = 0;
basePhonemeEvent = (TTSEvent)_phonemeQueue.Peek();
for (int i = 0; i < _lastComplete;)
{
ttsEvent = (TTSEvent)_phonemeQueue.Dequeue();
totalDuration += ttsEvent.PhonemeDuration.Milliseconds;
i += ttsEvent.Phoneme.Length;
}
targetEvent = TTSEvent.CreatePhonemeEvent(new string(target), "",
TimeSpan.FromMilliseconds(totalDuration),
basePhonemeEvent.PhonemeEmphasis,
basePhonemeEvent.Prompt,
basePhonemeEvent.AudioPosition);
SendToQueue(targetEvent);
}
private void Reset()
{
_phonemeQueue.Clear();
_phonemes = new StringBuilder();
_lastComplete = 0;
}
private void SendToQueue(TTSEvent evt)
{
if (evt.Id == TtsEventId.Phoneme)
{
TTSEvent firstEvent;
if (_queue.Count > 0)
{
firstEvent = _queue.Dequeue() as TTSEvent;
if (firstEvent.Id == TtsEventId.Phoneme)
{
firstEvent.NextPhoneme = evt.Phoneme;
}
else
{
Trace.TraceError("First event in the queue of the phone mapper is not a PHONEME event");
}
SendToOutput(firstEvent);
while (_queue.Count > 0)
{
SendToOutput(_queue.Dequeue() as TTSEvent);
}
}
_queue.Enqueue(evt);
}
else
{
if (_queue.Count > 0)
{
_queue.Enqueue(evt);
}
else
{
SendToOutput(evt);
}
}
}
private PhonemeConversion _conversion;
private StringBuilder _phonemes;
private Queue _queue, _phonemeQueue;
private AlphabetConverter _alphabetConverter;
private int _lastComplete;
}
}