[Stt/Tts][Fix description about exception]
[platform/core/csapi/tizenfx.git] / src / Tizen.Uix.SttEngine / Tizen.Uix.SttEngine / SttEngine.cs
1 /*
2 * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
3 *
4 * Licensed under the Apache License, Version 2.0 (the License);
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an AS IS BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 using System;
18 using System.Runtime.InteropServices;
19 using static Interop.SttEngine;
20
21 namespace Tizen.Uix.SttEngine
22 {
23     /// <summary>
24     /// Enumeration for audio type.
25     /// </summary>
26     public enum AudioType
27     {
28         /// <summary>
29         /// Signed 16bit audio type, Little endian
30         /// </summary>
31         PcmS16Le = 0,
32         /// <summary>
33         /// Unsigned 8bit audio type
34         /// </summary>
35         PcmU8
36     };
37
38     /// <summary>
39     /// Enumeration for result.
40     /// </summary>
41     public enum ResultEvent
42     {
43         /// <summary>
44         /// Event when either the full matched or the final result is delivered
45         /// </summary>
46         FinalResult = 0,
47         /// <summary>
48         /// Event when the partial matched result is delivered
49         /// </summary>
50         PartialResult,
51         /// <summary>
52         /// Event when the recognition has failed
53         /// </summary>
54         Error
55     };
56
57     /// <summary>
58     /// Enumeration for result time.
59     /// </summary>
60     public enum TimeEvent
61     {
62         /// <summary>
63         /// Event when the token is beginning type
64         /// </summary>
65         Beginning = 0,
66         /// <summary>
67         /// Event when the token is middle type
68         /// </summary>
69         Middle = 1,
70         /// <summary>
71         /// Event when the token is end type
72         /// </summary>
73         End = 2
74     };
75
76     /// <summary>
77     /// Enumeration for speech status.
78     /// </summary>
79     public enum SpeechStatus
80     {
81         /// <summary>
82         /// Beginning point of speech is detected
83         /// </summary>
84         BeginningPointDetected = 0,
85         /// <summary>
86         /// End point of speech is detected
87         /// </summary>
88         EndPointDetected
89     };
90
91     /// <summary>
92     /// Enumeration representing the result message
93     /// </summary>
94     public enum ResultMessage
95     {
96         /// <summary>
97         /// No Error
98         /// </summary>
99         None,
100         /// <summary>
101         /// Recognition failed  because the speech started too soon.
102         /// </summary>
103         TooSoon,
104         /// <summary>
105         /// Recognition failed  because the speech is too short.
106         /// </summary>
107         TooShort,
108         /// <summary>
109         /// Recognition failed  because the speech is too long.
110         /// </summary>
111         TooLong,
112         /// <summary>
113         /// Recognition failed  because the speech is too quiet to listen.
114         /// </summary>
115         TooQuiet,
116         /// <summary>
117         /// Recognition failed  because the speech is too loud to listen.
118         /// </summary>
119         TooLoud,
120         /// <summary>
121         /// Recognition failed  because the speech is too fast to listen.
122         /// </summary>
123         TooFast
124     };
125
126
127     /// <summary>
128     /// Enum for Error values that can occur
129     /// </summary>
130     public enum Error
131     {
132         /// <summary>
133         /// Successful, No error
134         /// </summary>
135         None = ErrorCode.None,
136         /// <summary>
137         /// Out of Memory
138         /// </summary>
139         OutOfMemory = ErrorCode.OutOfMemory,
140         /// <summary>
141         /// I/O error
142         /// </summary>
143         IoError = ErrorCode.IoError,
144         /// <summary>
145         /// Invalid parameter
146         /// </summary>
147         InvalidParameter = ErrorCode.InvalidParameter,
148         /// <summary>
149         /// Network down(Out of network)
150         /// </summary>
151         NetworkDown = ErrorCode.NetworkDown,
152         /// <summary>
153         /// Invalid state
154         /// </summary>
155         InvalidState = ErrorCode.InvalidState,
156         /// <summary>
157         /// Invalid language
158         /// </summary>
159         InvalidLanguage = ErrorCode.InvalidLanguage,
160         /// <summary>
161         /// Operation failed
162         /// </summary>
163         OperationFailed = ErrorCode.OperationFailed,
164         /// <summary>
165         /// Not supported feature of current engine
166         /// </summary>
167         NotSupportedFeature = ErrorCode.NotSupportedFeature,
168         /// <summary>
169         /// NOT supported
170         /// </summary>
171         NotSupported = ErrorCode.NotSupported,
172         /// <summary>
173         /// Permission denied
174         /// </summary>
175         PermissionDenied = ErrorCode.PermissionDenied,
176         /// <summary>
177         /// Recording timed out
178         /// </summary>
179         RecordingTimedOut = ErrorCode.RecordingTimedOut
180     };
181
182     /// <summary>
183     /// This Class represents the Stt Engine which has to be inherited to make the engine.
184     /// </summary>
185     public abstract class Engine
186     {
187         private CallbackStructGCHandle _callbackStructGCHandle = new CallbackStructGCHandle();
188         private PrivateDataSetCb _privateDataSetCb;
189         private Action<string> _privateDatacallback;
190         private PrivateDataRequestedCb _privateDataRequestedCb;
191         private OutAction<string> _privateDataRequestedCallback;
192         private static Engine _engine;
193         private IntPtr _structIntPtrHandle;
194
195         /// <summary>
196         /// An Action with 2 Input Parameter returning a Error
197         /// </summary>
198         /// <typeparam name="T">Generic Type for Parameter 1</typeparam>
199         /// <param name="a">The Input Parameter 1</param>
200         /// <param name="b">The Input Parameter 2</param>
201         /// <returns>Error Value</returns>
202         public delegate Error Action<T>(T a, T b);
203
204         /// <summary>
205         /// An Action with 2 Out Parameter returning a Error
206         /// </summary>
207         /// <typeparam name="T">Generic Type for Parameter 1</typeparam>
208         /// <param name="a">The Input Parameter 1</param>
209         /// <param name="b">The Input Parameter 2</param>
210         /// <returns>Error Value</returns>
211         public delegate Error OutAction<T>(T a, out T b);
212
213         /// <summary>
214         /// Called when Stt engine provides the time stamp of result to the engine service user.
215         /// This callback function is implemented by the engine service user. Therefore, the engine developer does NOT have to implement this callback function.
216         /// </summary>
217         /// <param name="index">The result index</param>
218         /// <param name="resultEvent">The token event</param>
219         /// <param name="text">The result text</param>
220         /// <param name="startTime">The time started speaking the result text</param>
221         /// <param name="endTime">The time finished speaking the result text</param>
222         /// <param name="userData">The User data</param>
223         /// <returns>true to continue with the next iteration of the loop, false to break out of the loop</returns>
224         /// <precondition>SendResult() should be called.</precondition>
225         public delegate bool ResultTime(int index, TimeEvent resultEvent, string text, long startTime, long endTime, IntPtr userData);
226
227         /// <summary>
228         /// Called when Stt engine informs the engine service user about whole supported language list.
229         /// This callback function is implemented by the engine service user. Therefore, the engine developer does NOT have to implement this callback function.
230         /// </summary>
231         /// <param name="language">The language is specified as an ISO 3166 alpha-2 two letter country-code
232         /// followed by ISO 639-1 for the two-letter language code
233         /// for example, "ko_KR" for Korean, "en_US" for American English</param>
234         /// <param name="userData">The User data</param>
235         /// <returns>true to continue with the next iteration of the loop, false to break out of the loop</returns>
236         /// <precondition>ForEachSupportedLanguages() should be called</precondition>
237         public delegate bool SupportedLanguages(string language, IntPtr userData);
238
239         /// <summary>
240         /// Called when the engine service user requests the basic information of Stt engine.
241         /// </summary>
242         /// <remarks>
243         /// In order to upload the engine at Tizen Appstore, both a service app and a ui app are necessary. Therefore, engineSetting must be transferred to the engine service user.
244         /// </remarks>
245         /// <param name="engineUuid">UUID of engine</param>
246         /// <param name="engineName">Name of engine</param>
247         /// <param name="engineSetting">The engine setting application(ui app)'s app ID</param>
248         /// <param name="useNetwork">A variable for checking whether the network is used or not</param>
249         /// <returns>
250         /// Following Error Codes can be returned
251         /// 1. None
252         /// 2. OperationFailed
253         /// 3. InvalidParameter
254         /// </returns>
255         public abstract Error GetInformation(out string engineUuid, out string engineName, out string engineSetting, out bool useNetwork);
256
257         /// <summary>
258         /// Called when the engine service user initializes Stt engine.
259         /// This callback function is called by the engine service user to request for Stt engine to be started.
260         /// </summary>
261         /// <returns>
262         /// Following Error Codes can be returned
263         /// 1. None
264         /// 2. InvalidParameter
265         /// 3. InvalidState
266         /// 4. OperationFailed
267         /// </returns>
268         public abstract Error Initialize();
269
270         /// <summary>
271         /// Called when the engine service user deinitializes Stt engine.
272         /// This callback function is called by the engine service user to request for Stt engine to be deinitialized.
273         /// </summary>
274         /// <returns>
275         /// Following Error Codes can be returned
276         /// 1. None
277         /// 2. InvalidState
278         /// </returns>
279         public abstract Error Deinitialize();
280
281         /// <summary>
282         /// Called when the engine service user gets the whole supported language list.
283         /// </summary>
284         /// <remarks>
285         /// In this function, the engine service user's callback function 'SupportedLanguages' is invoked repeatedly for getting all supported languages
286         /// and user_data must be transferred to 'SupportedLanguages'. If 'SupportedLanguages' returns false, it should be stopped to call 'SupportedLanguages'.
287         /// </remarks>
288         /// <param name="callback">The callback function</param>
289         /// <param name="userData">The user data which must be passed to the callback delegate 'SupportedLanguages'</param>
290         /// <returns>
291         /// Following Error Codes can be returned
292         /// 1. None
293         /// 2. InvalidState
294         /// 3. InvalidParameter
295         /// </returns>
296         /// <postcondition>
297         /// This callback function invokes SupportedLanguages repeatedly for getting supported languages.
298         /// </postcondition>
299         public abstract Error ForEachSupportedLanguages(SupportedLanguages callback, IntPtr userData);
300
301         /// <summary>
302         /// Called when the engine service user checks whether the corresponding language is valid or not in Stt engine.
303         /// </summary>
304         /// <param name="language">The language is specified as an ISO 3166 alpha-2 two letter country-code followed by ISO 639-1 for the two-letter language code
305         /// For example, "ko_KR" for Korean, "en_US" for American English</param>
306         /// <param name="isValid">A variable for checking whether the corresponding language is valid or not. true to be valid, false to be invalid</param>
307         /// <returns>
308         /// Following Error Codes can be returned
309         /// 1. None
310         /// 2. InvalidParameter
311         /// </returns>
312         public abstract Error IsValidLanguage(string language, out bool isValid);
313
314         /// <summary>
315         /// Called when the engine service user checks whether Stt engine supports silence detection.
316         /// </summary>
317         /// <returns>true to support silence detection, false not to support silence detection</returns>
318         public abstract bool SupportSilenceDetection();
319
320         /// <summary>
321         /// Called when the engine service user checks whether Stt engine supports the corresponding recognition type.
322         /// </summary>
323         /// <param name="type">The type for recognition, "stt.recognition.type.FREE" or "stt.recognition.type.FREE.PARTIAL"</param>
324         /// <param name="isSupported">A variable for checking whether Stt engine supports the corresponding recognition type.
325         /// true to support recognition type, false not to support recognition type</param>
326         /// <returns>
327         /// Following Error Codes can be returned
328         /// 1. None
329         /// 2. InvalidParameter
330         /// </returns>
331         public abstract Error SupportRecognitionType(string type, out bool isSupported);
332
333         /// <summary>
334         /// Called when the engine service user gets the proper recording format of Stt engine.
335         /// The recording format is used for creating the recorder.
336         /// </summary>
337         /// <param name="types">The format used by the recorder</param>
338         /// <param name="rate">The sample rate used by the recorder</param>
339         /// <param name="channels">The number of channels used by the recorder</param>
340         /// <returns>
341         /// Following Error Codes can be returned
342         /// 1. None
343         /// 2. InvalidState
344         /// </returns>
345         public abstract Error GetRecordingFormat(out AudioType types, out int rate, out int channels);
346
347         /// <summary>
348         /// Called when the engine service user sets the silence detection.
349         /// If the engine service user sets this option as 'TRUE', Stt engine will detect the silence (EPD) and send the callback event about it.
350         /// </summary>
351         /// <param name="isSet">A variable for setting the silence detection. true to detect the silence, false not to detect the silence</param>
352         /// <returns>
353         /// Following Error Codes can be returned
354         /// 1. None
355         /// 2. InvalidState
356         /// 3. NotSupportedFeature
357         /// </returns>
358         public abstract Error SetSilenceDetection(bool isSet);
359
360         /// <summary>
361         /// Called when the engine service user requests for Stt engine to check whether the application agreed the usage of Stt engine.
362         /// This callback function is called when the engine service user requests for Stt engine to check the application's agreement about using the engine.
363         /// According to the need, the engine developer can provide some user interfaces to check the agreement.
364         /// </summary>
365         /// <param name="appid">The Application ID</param>
366         /// <param name="isAgreed">A variable for checking whether the application agreed to use Stt engine or not. true to agree, false to disagree</param>
367         /// <returns>
368         /// Following Error Codes can be returned
369         /// 1. None
370         /// 2. InvalidState
371         /// 3. NotSupportedFeature
372         /// </returns>
373         public abstract Error CheckAppAgreed(string appid, out bool isAgreed);
374
375         /// <summary>
376         /// Called when the engine service user checks whether Stt engine needs the application's credential.
377         /// </summary>
378         /// <returns>true if Stt engine needs the application's credential, otherwise false </returns>
379         public abstract bool NeedAppCredential();
380
381         /// <summary>
382         /// Called when the engine service user gets the result time information(stamp).
383         /// </summary>
384         /// <remarks>
385         /// In this function, the engine service user's callback delegate 'ResultTime' is invoked repeatedly for sending the time information to the engine service user
386         /// and user_data must be transferred to 'ResultTime'. If 'ResultTime' returns false, it should be stopped to call 'ResultTime'.
387         /// timeInfo is transferred from SendResult. The type of timeInfo is up to the Stt engine developer.
388         /// </remarks>
389         /// <param name="timeInfo">The time information</param>
390         /// <param name="callback">The callback function</param>
391         /// <param name="userData">The user data which must be passed to the callback function ResultTime</param>
392         /// <returns>
393         /// Following Error Codes can be returned
394         /// 1. None
395         /// 2. InvalidState
396         /// 3. InvalidParameter
397         /// </returns>
398         /// <precondition>
399         /// SendResult will invoke this function
400         /// </precondition>
401         /// <postcondition>
402         /// This function invokes ResultTime repeatedly for getting result time information.
403         /// </postcondition>
404         public abstract Error ForEachResultTime(IntPtr timeInfo, ResultTime callback, IntPtr userData);
405
406         /// <summary>
407         /// Called when the engine service user starts to recognize the recording data.
408         /// In this callback function, Stt engine must transfer the recognition result and userData to the engine service user using SendResult().
409         /// Also, if Stt engine needs the application's credential, it sets the credential granted to the application.
410         /// </summary>
411         /// <param name="language">The language is specified as an ISO 3166 alpha-2 two letter country-code followed by ISO 639-1 for the two-letter language code
412         /// For example, "ko_KR" for Korean, "en_US" for American English</param>
413         /// <param name="type">The recognition type, "stt.recognition.type.FREE" or "stt.recognition.type.FREE.PARTIAL"</param>
414         /// <param name="appid">The Application ID</param>
415         /// <param name="credential">The credential granted to the application</param>
416         /// <param name="userData">The user data to be passed to the callback function</param>
417         /// <returns>
418         /// Following Error Codes can be returned
419         /// 1. None
420         /// 2. InvalidState
421         /// 3. InvalidParameter
422         /// 4. InvalidLanguage
423         /// 5. OperationFailed
424         /// 6. NetworkDown
425         /// </returns>
426         /// <precondition>
427         /// The engine is not in recognition processing.
428         /// </precondition>
429         public abstract Error Start(string language, string type, string appid, string credential, IntPtr userData);
430
431         /// <summary>
432         /// Called when the engine service user sets and sends the recording data for speech recognition.
433         /// This callback function is called by the engine service user to send the recording data to Stt engine.The engine receives the recording data and uses for speech recognition. 
434         /// this function should be returned immediately after recording data copy.
435         /// </summary>
436         /// <param name="data">The recording data</param>
437         /// <param name="length">The length of recording data</param>
438         /// <returns>
439         /// Following Error Codes can be returned
440         /// 1. None
441         /// 2. InvalidState
442         /// 3. InvalidParameter
443         /// 4. OperationFailed
444         /// </returns>
445         /// <precondition>
446         /// Start should succeed</precondition>
447         /// <postcondition>
448         /// If the engine supports partial result, SendResult() should be invoked.</postcondition>
449         public abstract Error SetRecordingData(string data, uint length);
450
451         /// <summary>
452         /// Called when the engine service user stops to recognize the recording data.
453         /// This callback function is called by the engine service user to stop recording and to get the recognition result.
454         /// </summary>
455         /// <returns>Following Error Codes can be returned
456         /// 1. None
457         /// 2. InvalidState
458         /// 3. OperationFailed
459         /// 4. NetworkDown
460         /// </returns>
461         /// <precondition>
462         /// Start should succeed</precondition>
463         /// <postcondition>
464         /// After processing of the engine, , SendResult() should be invoked.</postcondition>
465         public abstract Error Stop();
466
467         /// <summary>
468         /// Called when the engine service user cancels to recognize the recording data.
469         /// This callback function is called by the engine service user to cancel to recognize the recording data.Also, when starting the recorder is failed, this function is called.
470         /// </summary>
471         /// <returns>
472         /// Following Error Codes can be returned
473         /// 1. None
474         /// 2. InvalidState
475         /// </returns>
476         /// <precondition>Stt engine is in recognition processing or recording.</precondition>
477         public abstract Error Cancel();
478
479         /// <summary>
480         /// Public Constructor
481         /// </summary>
482         /// <feature>
483         /// http://tizen.org/feature/speech.recognition
484         /// http://tizen.org/feature/microphone
485         /// </feature>
486         public Engine()
487         {
488             _engine = this;
489         }
490
491         /// <summary>
492         /// Main function for Speech-To-Text (STT) engine.
493         /// This function is the main function for operating Stt engine.
494         /// </summary>
495         /// <privilege>
496         /// http://tizen.org/privilege/recorder
497         /// </privilege>
498         /// <feature>
499         /// http://tizen.org/feature/speech.recognition
500         /// http://tizen.org/feature/microphone
501         /// </feature>
502         /// <remarks>
503         /// ServiceAppMain should be used for working the engine after this function.
504         /// </remarks>
505         /// <param name="argc">The Number of Arguments</param>
506         /// <param name="argv">The Arguments Array</param>
507         /// <exception cref="UnauthorizedAccessException">Thrown in case of Permission denied</exception>
508         /// <exception cref="NotSupportedException">Thrown in case of Not supported</exception>
509         /// <exception cref="InvalidOperationException">thrown in case of Operation failure</exception>
510         public void EngineMain(int argc, string[] argv)
511         {
512             _callbackStructGCHandle.CallbackStruct.version = 1;
513             _callbackStructGCHandle.CallbackStruct.getInfo = _getInfoCb;
514             _callbackStructGCHandle.CallbackStruct.initialize = Initialize;
515             _callbackStructGCHandle.CallbackStruct.deinitialize = _deinitializeCb;
516             _callbackStructGCHandle.CallbackStruct.supportedLanaguge = ForEachSupportedLanguages;
517             _callbackStructGCHandle.CallbackStruct.validLanaguage = _isValidLanguageCb;
518             _callbackStructGCHandle.CallbackStruct.silence = SupportSilenceDetection;
519             _callbackStructGCHandle.CallbackStruct.recognitionType = SupportRecognitionType;
520             _callbackStructGCHandle.CallbackStruct.recordingFormat = GetRecordingFormat;
521             _callbackStructGCHandle.CallbackStruct.resultTime = ForEachResultTime;
522             _callbackStructGCHandle.CallbackStruct.silenceDetection = SetSilenceDetection;
523             _callbackStructGCHandle.CallbackStruct.start = _startCb;
524             _callbackStructGCHandle.CallbackStruct.recordingData = SetRecordingData;
525             _callbackStructGCHandle.CallbackStruct.stop = Stop;
526             _callbackStructGCHandle.CallbackStruct.cancel = Cancel;
527             _callbackStructGCHandle.CallbackStruct.checkAppAgreed = CheckAppAgreed;
528             _callbackStructGCHandle.CallbackStruct.needAppCredential = NeedAppCredential;
529             _structIntPtrHandle = Marshal.AllocHGlobal(Marshal.SizeOf(_callbackStructGCHandle.CallbackStruct));
530             Marshal.StructureToPtr<RequestCallbackStruct>(_callbackStructGCHandle.CallbackStruct, _structIntPtrHandle, false);
531             Error error = STTEMain(argc, argv, _structIntPtrHandle);
532             if (error != Error.None)
533             {
534                 Log.Error(LogTag, "STTEMain Failed with error " + error);
535                 throw ExceptionFactory.CreateException((ErrorCode)error);
536             }
537
538             Log.Info(LogTag, "After STTEMain");
539         }
540
541         /// <summary>
542         /// Sends the recognition result to the engine service user.
543         /// </summary>
544         /// <feature>
545         /// http://tizen.org/feature/speech.recognition
546         /// http://tizen.org/feature/microphone
547         /// </feature>
548         /// <remarks>
549         /// This API is used in SetRecordingData() and Stop(), when Stt engine sends the recognition result to the engine service user.
550         /// This function is called in the following situations; 1) after Stop() is called, 2) the end point of speech is detected from recording, or 3) partial result is occurred.
551         /// The recognition result must be transferred to the engine service user through this function. Also, timeInfo must be transferred to ForEachResultTime().
552         /// The type of timeInfo is up to the Stt engine developer.
553         /// </remarks>
554         /// <param name="resultEvent">The result event</param>
555         /// <param name="type">The recognition type, "stt.recognition.type.FREE" or "stt.recognition.type.FREE.PARTIAL"</param>
556         /// <param name="result">Result texts</param>
557         /// <param name="resultCount">Result text count</param>
558         /// <param name="msg">Engine message</param>
559         /// <param name="timeInfo">The time information</param>
560         /// <exception cref="UnauthorizedAccessException">Thrown in case of Permission denied</exception>
561         /// <exception cref="NotSupportedException">Thrown in case of Not supported</exception>
562         /// <exception cref="InvalidOperationException">thrown in case of Operation failure</exception>
563         /// <precondition>
564         /// EngineMain function should be invoked before this function is called. Stop will invoke this function.
565         /// </precondition>
566         /// <postcondition>
567         /// This function invokes ForEachResultTime
568         /// </postcondition>
569         public void SendResult(ResultEvent resultEvent, string type, string[] result, int resultCount, ResultMessage msg, IntPtr timeInfo)
570         {
571             if ((result != null) && (result.Length != 0))
572             {
573
574                 string message = "stt.result.message.none";
575                 switch (msg)
576                 {
577                     case ResultMessage.None:
578                     message = "stt.result.message.none";
579                     break;
580
581                     case ResultMessage.TooFast:
582                     message = "stt.result.message.error.too.fast";
583                     break;
584
585                     case ResultMessage.TooLong:
586                     message = "stt.result.message.error.too.long";
587                     break;
588
589                     case ResultMessage.TooLoud:
590                     message = "stt.result.message.error.too.loud";
591                     break;
592
593                     case ResultMessage.TooQuiet:
594                     message = "stt.result.message.error.too.quiet";
595                     break;
596
597                     case ResultMessage.TooShort:
598                     message = "stt.result.message.error.too.short";
599                     break;
600
601                     case ResultMessage.TooSoon:
602                     message = "stt.result.message.error.too.soon";
603                     break;
604                 }
605
606                 Error error = STTESendResult(resultEvent, type, result, resultCount, message, timeInfo, IntPtr.Zero);
607                 if (error != Error.None)
608                 {
609                     Log.Error(LogTag, "STTESendResult Failed with error " + error);
610                     throw ExceptionFactory.CreateException((ErrorCode)error);
611                 }
612
613             }
614             else
615             {
616                 throw new ArgumentNullException("result", "is null or empty");
617             }
618         }
619
620         /// <summary>
621         /// Sends the error to the engine service user.
622         /// </summary>
623         /// <feature>
624         /// http://tizen.org/feature/speech.recognition
625         /// http://tizen.org/feature/microphone
626         /// </feature>
627         /// <param name="error">The Error Reason</param>
628         /// <param name="msg">The error message</param>
629         /// <exception cref="UnauthorizedAccessException">Thrown in case of Permission denied</exception>
630         /// <exception cref="NotSupportedException">Thrown in case of Not supported</exception>
631         /// <exception cref="InvalidOperationException">Thrown in case of Operation failure</exception>
632         /// <precondition>
633         /// Main function should be invoked before this function is called.
634         /// </precondition>
635         public void SendError(Error error, string msg)
636         {
637             Error err = STTESendError(error, msg);
638             if (err != Error.None)
639             {
640                 Log.Error(LogTag, "SendError Failed with error " + err);
641                 throw ExceptionFactory.CreateException((ErrorCode)error);
642             }
643         }
644
645         /// <summary>
646         /// Sends the speech status to the engine service user when Stt engine notifies the change of the speech status.
647         /// </summary>
648         /// <feature>
649         /// http://tizen.org/feature/speech.recognition
650         /// http://tizen.org/feature/microphone
651         /// </feature>
652         /// <remarks>
653         /// This API is invoked when Stt engine wants to notify the change of the speech status anytime. NOTE that this API can be invoked for recognizing the speech.
654         /// </remarks>
655         /// <param name="status">SpeechStatus</param>
656         /// <exception cref="UnauthorizedAccessException">Thrown in case of Permission denied</exception>
657         /// <exception cref="NotSupportedException">Thrown in case of Not supported</exception>
658         /// <exception cref="InvalidOperationException">thrown in case of Operation failure</exception>
659         /// <precondition>
660         /// Main function should be invoked before this function is called. Start() and SetRecordingData() will invoke this function.
661         /// </precondition>
662         public void SendSpeechStatus(SpeechStatus status)
663         {
664             Error error = STTESendSpeechStatus(status, IntPtr.Zero);
665             if (error != Error.None)
666             {
667                 Log.Error(LogTag, "SendSpeechStatus Failed with error " + error);
668                 throw ExceptionFactory.CreateException((ErrorCode)error);
669             }
670
671         }
672
673         /// <summary>
674         /// Sets a callback function for setting the private data.
675         /// </summary>
676         /// <privilege>
677         /// http://tizen.org/privilege/recorder
678         /// </privilege>
679         /// <feature>
680         /// http://tizen.org/feature/speech.recognition
681         /// http://tizen.org/feature/microphone
682         /// </feature>
683         /// <param name="callback">
684         /// Called when Stt engine receives the private data from the engine service user.
685         /// This callback function is called when the engine service user sends the private data to Stt engine.
686         /// In Parameters:
687         /// a = Key -- The key field of private data
688         /// b = data -- The data field of private data
689         /// Following Error Codes can be returned
690         /// 1. None
691         /// 2. InvalidParameter
692         /// 3. OperationFailed
693         /// </param>
694         /// <exception cref="ArgumentException">Thrown in case of Invalid Parameter</exception>
695         /// <exception cref="UnauthorizedAccessException">Thrown in case of Permission denied</exception>
696         /// <exception cref="NotSupportedException">Thrown in case of Not supported</exception>
697         /// <exception cref="InvalidOperationException">thrown in case of Operation failure</exception>
698         /// <precondition>
699         /// Main function should be invoked before this function is called.
700         /// </precondition>
701         public void SetPrivateDataSetDelegate(Action<string> callback)
702         {
703             if (null == callback)
704             {
705                 Log.Error(LogTag, "callback is null");
706                 throw ExceptionFactory.CreateException(ErrorCode.InvalidParameter);
707             }
708
709             _privateDatacallback = callback;
710             _privateDataSetCb = (string key, string data) =>
711             {
712                 return _privateDatacallback.Invoke(key, data);
713             };
714             Error error = STTESetPrivateDataSetCb(_privateDataSetCb);
715             if (error != Error.None)
716             {
717                 Log.Error(LogTag, "SetPrivateDataSetDelegate Failed with error " + error);
718                 throw ExceptionFactory.CreateException((ErrorCode)error);
719             }
720
721         }
722
723         /// <summary>
724         /// Sets a callback delegate for requesting the private data.
725         /// </summary>
726         /// <privilege>
727         /// http://tizen.org/privilege/recorder
728         /// </privilege>
729         /// <feature>
730         /// http://tizen.org/feature/speech.recognition
731         /// http://tizen.org/feature/microphone
732         /// </feature>
733         /// <param name="callback">callback function
734         /// Called when Stt engine provides the engine service user with the private data.
735         /// This callback function is called when the engine service user gets the private data from Stt engine.
736         /// Out Parameters:
737         /// a = Key -- The key field of private data
738         /// b = data -- The data field of private data
739         /// Following Error Codes can be returned
740         /// 1. None
741         /// 2. InvalidParameter
742         /// 3. OperationFailed
743         /// </param>
744         /// <exception cref="ArgumentException">Thrown in case of Invalid Parameter</exception>
745         /// <exception cref="UnauthorizedAccessException">Thrown in case of Permission denied</exception>
746         /// <exception cref="NotSupportedException">Thrown in case of Not supported</exception>
747         /// <exception cref="InvalidOperationException">thrown in case of Operation failure</exception>
748         /// <precondition>
749         /// Main function should be invoked before this function is called.
750         /// </precondition>
751         public void SetPrivateDataRequestedDelegate(OutAction<string> callback)
752         {
753             if (null == callback)
754             {
755                 Log.Error(LogTag, "callback is null");
756                 throw ExceptionFactory.CreateException(ErrorCode.InvalidParameter);
757             }
758
759             _privateDataRequestedCallback = callback;
760             _privateDataRequestedCb = (string key, out string data) =>
761             {
762                 return _privateDataRequestedCallback.Invoke(key, out data);
763             };
764             Error error = STTESetPrivateDataRequestedCb(_privateDataRequestedCb);
765             if (error != Error.None)
766             {
767                 Log.Error(LogTag, "SetPrivateDataRequestedDelegate Failed with error " + error);
768                 throw ExceptionFactory.CreateException((ErrorCode)error);
769             }
770
771         }
772
773         private StartCb _startCb = (IntPtr language, IntPtr type, IntPtr appid, IntPtr credential, IntPtr userData) =>
774         {
775             string lan = null;
776             string typ = null;
777             string apid = null;
778             string cre = null;
779             if (language != null)
780                 lan = Marshal.PtrToStringAnsi(language);
781             if (type != null)
782                 typ = Marshal.PtrToStringAnsi(type);
783             if (appid != null)
784                 apid = Marshal.PtrToStringAnsi(appid);
785             if (credential != null)
786                 cre = Marshal.PtrToStringAnsi(credential);
787             return _engine.Start(lan, typ, apid, cre, IntPtr.Zero);
788         };
789
790         private IsValidLanguageCb _isValidLanguageCb = (IntPtr langauge, IntPtr isValid) =>
791         {
792             string langaugeStr = Marshal.PtrToStringAnsi(langauge);
793             bool valid;
794             Error err = _engine.IsValidLanguage(langaugeStr, out valid);
795             if (valid == true)
796             {
797                 Marshal.WriteByte(isValid, 0, 1);
798             }
799             else
800             {
801                 Marshal.WriteByte(isValid, 0, 0);
802             }
803             return err;
804         };
805
806         private GetInfoCb _getInfoCb = (out IntPtr engineUuid, out IntPtr engineName, out IntPtr engineSetting, out IntPtr useNetwork) =>
807         {
808             string uuid;
809             string name;
810             string setting;
811             bool network;
812             Error err = _engine.GetInformation(out uuid, out name, out setting, out network);
813             int size = Marshal.SizeOf<int>();
814             IntPtr pBool = Marshal.AllocHGlobal(size);
815             if (network == true)
816             {
817                 Marshal.WriteInt32(pBool, 0, 1);
818             }
819             else
820             {
821                 Marshal.WriteInt32(pBool, 0, 0);
822             }
823             engineUuid = Marshal.StringToHGlobalAnsi(uuid);
824             engineName = Marshal.StringToHGlobalAnsi(name);
825             engineSetting = Marshal.StringToHGlobalAnsi(setting);
826             useNetwork = pBool;
827             return err;
828         };
829
830         private DeinitializeCb _deinitializeCb = () =>
831         {
832             Marshal.FreeHGlobal(_engine._structIntPtrHandle);
833             return _engine.Deinitialize();
834         };
835     }
836 }