forked from unispeech/swig-wrapper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
UniMRCP-wrapper.cpp
2006 lines (1696 loc) · 61.3 KB
/
UniMRCP-wrapper.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 2014 SpeechTech, s.r.o. http://www.speechtech.cz/en
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* $Id$
*/
/**
* @file UniMRCP-wrapper.cpp
* @brief UniMRCP Client wrapper implementation.
*/
#ifdef DOXYGEN
/** @brief Define to log data sent to and received from the application */
#define LOG_STREAM_DATA
/** @brief Define to log media frames flowing */
#define LOG_STREAM_FRAMES
#endif // DOXYGEN
/** @brief Tell the header we are including from this source */
#define UNIMRCP_WRAPPER_CPP
#include "UniMRCP-wrapper.h"
#include "UniMRCP-wrapper-version.h"
#include <stdlib.h> // For malloc, realloc and free
#include "apr_general.h"
#include "apr_atomic.h"
#include "apr_mmap.h"
#include "apt_pool.h"
#include "apt_dir_layout.h"
#include "apt_log.h"
#include "apt_pair.h"
#include "unimrcp_client.h"
#include "mrcp_application.h"
#include "mrcp_types.h"
#include "mrcp_message.h"
#include "mrcp_recog_header.h"
#include "mrcp_recorder_header.h"
#include "mrcp_synth_header.h"
#include "mpf_dtmf_generator.h"
#include "mpf_dtmf_detector.h"
#include "apr_version.h"
#include "apu_version.h"
#include "uni_version.h"
/** @brief Sofia include version hack */
#define SU_CONFIGURE_H
#include "sofia-sip/su_config.h"
#include "sofia-sip/sofia_features.h"
#if defined(WIN32) && defined(PTW32_STATIC_LIB)
# include "pthread.h"
#endif
#ifdef _MSC_VER
# define snprintf _snprintf
# define strdup _strdup
#endif
/** @brief Throw UniMRCP exception from here with message */
#define UNIMRCP_THROW(msg) throw UniMRCPException(__FILE__, __LINE__, msg)
/** @brief Log line formatting buffer */
#ifndef MAX_LOG_ENTRY_SIZE
# define MAX_LOG_ENTRY_SIZE 4096
#endif
/** @brief Memory page size (for MMap) */
#ifndef PAGE_SIZE
# define PAGE_SIZE 4096
#endif
/**
* @brief Allocate object's memory from APR memory pool
*/
void* operator new(size_t objSize, apr_pool_t* pool)
{
return apr_palloc(pool, objSize);
}
/**
* @brief Called if construction after allocation from pool failed.
* @see operator new(size_t objSize, apr_pool_t* pool)
*/
void operator delete(void* obj, apr_pool_t* pool)
{
(void) obj;
(void) pool;
}
void* operator new(size_t objSize, mrcp_session_t* sess)
{
return apr_palloc(mrcp_application_session_pool_get(sess), objSize);
}
UniMRCPLogger* UniMRCPLogger::logger = NULL;
unsigned UniMRCPClient::instances = 0;
unsigned UniMRCPClient::staticInitialized = 0;
apr_pool_t* UniMRCPClient::staticPool = NULL;
UniMRCPLogger::~UniMRCPLogger()
{
#ifdef _DEBUG
printf("~UniMRCPLogger logger(%p)\n", logger);
#endif
logger = NULL;
}
int UniMRCPLogger::LogExtHandler(char const* file, int line, char const* id, UniMRCPLogPriority priority, char const* format, va_list arg_ptr)
{
(void) id;
if (!logger) return false;
char buf[MAX_LOG_ENTRY_SIZE];
buf[0] = 0;
apr_vsnprintf(buf, MAX_LOG_ENTRY_SIZE, format, arg_ptr);
return logger->Log(file, line, priority, buf);
}
void UniMRCPClient::UniMRCPVersion(unsigned short& major, unsigned short& minor, unsigned short& patch)
{
major = UNI_MAJOR_VERSION;
minor = UNI_MINOR_VERSION;
patch = UNI_PATCH_VERSION;
}
void UniMRCPClient::WrapperVersion(unsigned short& major, unsigned short& minor, unsigned short& patch)
{
major = UW_MAJOR_VERSION;
minor = UW_MINOR_VERSION;
patch = UW_PATCH_VERSION;
}
void UniMRCPClient::APRVersion(unsigned short& major, unsigned short& minor, unsigned short& patch)
{
major = APR_MAJOR_VERSION;
minor = APR_MINOR_VERSION;
patch = APR_PATCH_VERSION;
}
void UniMRCPClient::APRUtilVersion(unsigned short& major, unsigned short& minor, unsigned short& patch)
{
major = APU_MAJOR_VERSION;
minor = APU_MINOR_VERSION;
patch = APU_PATCH_VERSION;
}
char const* UniMRCPClient::SofiaSIPVersion()
{
return SOFIA_SIP_VERSION;
}
void UniMRCPClient::StaticPreinitialize(int& fd_stdin, int& fd_stdout, int& fd_stderr) THROWS(UniMRCPException)
{
if (staticInitialized) {
staticInitialized++;
#ifdef _DEBUG
printf("staticInitialized(%u)\n", staticInitialized);
#endif
return;
}
// Must be called once per process when linked statically for SofiaSIP to work
#if defined(WIN32) && defined(PTW32_STATIC_LIB)
if (!pthread_win32_process_attach_np())
UNIMRCP_THROW("Cannot initialize pthreads win32");
#endif
// Switch file descriptors in order to be able to write on console
#if defined(WIN32) && defined(DOTNET_CONSOLE_HACK)
fd_stdin = _fileno(stdin);
if (fd_stdin < 0) freopen("CONIN$", "rt", stdin);
fd_stdout = _fileno(stdout);
if (fd_stdout < 0) freopen("CONOUT$", "wt", stdout);
fd_stderr = _fileno(stderr);
if (fd_stderr < 0) freopen("CONERR$", "wt", stderr);
#else
(void) fd_stdin;
(void) fd_stdout;
(void) fd_stderr;
#endif
/* APR global initialization */
if(apr_initialize() != APR_SUCCESS)
{
apr_terminate();
UNIMRCP_THROW("Error initializing APR");
}
/* Create APR pool */
staticPool = apt_pool_create();
if (!staticPool)
UNIMRCP_THROW("Insufficient memory");
staticInitialized++;
#ifdef _DEBUG
printf("staticInitialized(%u)\n", staticInitialized);
#endif
}
void UniMRCPClient::StaticInitialize(char const* root_dir,
UniMRCPLogPriority log_prio,
UniMRCPLogOutput log_out,
char const* log_fname,
unsigned max_log_fsize,
unsigned max_log_fcount) THROWS(UniMRCPException)
{
int fd_stdin, fd_stdout, fd_stderr;
apt_dir_layout_t* dirLayout;
StaticPreinitialize(fd_stdin, fd_stdout, fd_stderr);
/* create the structure of default directories layout */
dirLayout = apt_default_dir_layout_create(root_dir, staticPool);
/* get path to logger configuration file */
const char* logConfPath = apt_confdir_filepath_get(dirLayout, "logger.xml", staticPool);
/* create and load singleton logger */
apt_log_instance_load(logConfPath, staticPool);
/* override the log priority, if specified in command line */
apt_log_priority_set(static_cast<apt_log_priority_e>(log_prio));
apt_log_output_mode_set(static_cast<apt_log_output_e>(log_out));
if (!log_fname) log_fname = unimrcp_client_log_name;
if (apt_log_output_mode_check(APT_LOG_OUTPUT_FILE) == TRUE)
{
/* open the log file */
#if defined(UNI_VERSION_AT_LEAST) && UNI_VERSION_AT_LEAST(1, 3, 0)
apt_log_file_open(apt_dir_layout_path_get(dirLayout, APT_LAYOUT_LOG_DIR),
log_fname, max_log_fsize, max_log_fcount, FALSE, staticPool);
#else
apt_log_file_open(dirLayout->log_dir_path, log_fname,
max_log_fsize, max_log_fcount, FALSE, staticPool);
#endif
}
apt_log(APT_LOG_MARK, APT_PRIO_INFO, "Initialized UniMRCP for %s: log_root_dir(%s) "
"log_prio(%d) log_out(%d) log_fname(%s) max_log_fsize(%u) max_log_fcount(%u)",
swig_target_platform, root_dir, static_cast<int>(log_prio),
static_cast<int>(log_out), log_fname, max_log_fsize, max_log_fcount);
StaticPostinitialize(fd_stdin, fd_stdout, fd_stderr);
}
void UniMRCPClient::StaticInitialize(UniMRCPLogger* logger,
UniMRCPLogPriority log_prio) THROWS(UniMRCPException)
{
int fd_stdin, fd_stdout, fd_stderr;
StaticPreinitialize(fd_stdin, fd_stdout, fd_stderr);
apt_log_instance_create(APT_LOG_OUTPUT_NONE, static_cast<apt_log_priority_e>(log_prio), staticPool);
UniMRCPLogger::logger = logger;
apt_log_ext_handler_set(reinterpret_cast<apt_log_ext_handler_f>(UniMRCPLogger::LogExtHandler));
apt_log(APT_LOG_MARK, APT_PRIO_INFO, "Initialized UniMRCP for %s: "
"logger(%pp) log_prio(%d)", swig_target_platform, logger, static_cast<int>(log_prio));
StaticPostinitialize(fd_stdin, fd_stdout, fd_stderr);
}
void UniMRCPClient::StaticPostinitialize(int fd_stdin, int fd_stdout, int fd_stderr)
{
#if defined(WIN32) && defined(DOTNET_CONSOLE_HACK)
if (fd_stdin < 0) apt_log(APT_LOG_MARK, APT_PRIO_DEBUG,
".NET console hack for stdin: old fd: %d, new fd %d", fd_stdin, _fileno(stdin));
if (fd_stdout < 0) apt_log(APT_LOG_MARK, APT_PRIO_DEBUG,
".NET console hack for stdout: old fd: %d, new fd %d", fd_stdout, _fileno(stdout));
if (fd_stderr < 0) apt_log(APT_LOG_MARK, APT_PRIO_DEBUG,
".NET console hack for stderr: old fd: %d, new fd %d", fd_stderr, _fileno(stderr));
#else
(void) fd_stdin;
(void) fd_stdout;
(void) fd_stderr;
#endif
}
void UniMRCPClient::StaticDeinitialize() THROWS(UniMRCPException)
{
if (!staticInitialized) {
#ifdef _DEBUG
printf("staticInitialized(%u) deinitialize\n", staticInitialized);
#endif
return;
}
if ((staticInitialized == 1) && instances)
UNIMRCP_THROW("Destroy all clients before static deinitialization");
staticInitialized--;
if (staticInitialized) {
#ifdef _DEBUG
printf("staticInitialized(%u) deinitialize\n", staticInitialized);
#endif
return;
}
/* destroy singleton logger */
apt_log_instance_destroy();
/* destroy APR pool */
apr_pool_destroy(staticPool);
staticPool = NULL;
/* APR global termination */
apr_terminate();
# ifdef PTW32_STATIC_LIB
pthread_win32_process_detach_np();
# endif
#ifdef _DEBUG
printf("staticDeinitialized\n");
#endif
}
UniMRCPClient::UniMRCPClient(char const* config, bool dir /* = false */) THROWS(UniMRCPException) :
client(NULL),
app(NULL),
terminated(false),
sess_id(1)
{
if (!staticInitialized)
UNIMRCP_THROW("UniMRCP platform not statically initialized");
if (dir) {
/* create the structure of default directories layout */
apt_dir_layout_t* dirLayout = apt_default_dir_layout_create(config, staticPool);
client = unimrcp_client_create(dirLayout);
} else
client = unimrcp_client_create2(config);
apt_log(APT_LOG_MARK, APT_PRIO_NOTICE, "Creating %s UniMRCPClient (%pp) instance %u",
swig_target_platform, this, instances);
if (!client)
UNIMRCP_THROW("Cannot create UniMRCP client");
app = mrcp_application_create(AppMessageHandler, this, mrcp_client_memory_pool_get(client));
if (!app) {
mrcp_client_destroy(client);
client = NULL;
UNIMRCP_THROW("Cannot create UniMRCP client application");
}
/* register MRCP application to MRCP client */
if (mrcp_client_application_register(client, app, unimrcp_client_app_name) == FALSE) {
mrcp_application_destroy(app);
app = NULL;
mrcp_client_destroy(client);
client = NULL;
UNIMRCP_THROW("Cannot register UniMRCP client application");
}
/* start MRCP client stack processing */
if (mrcp_client_start(client) == FALSE) {
mrcp_application_destroy(app);
app = NULL;
mrcp_client_destroy(client);
client = NULL;
UNIMRCP_THROW("Cannot start UniMRCP client");
}
instances++;
apt_log(APT_LOG_MARK, APT_PRIO_DEBUG, "%s UniMRCPClient created: client(%pp) app(%pp) instances(%u) this(%pp)",
swig_target_platform, client, app, instances, this);
}
UniMRCPClient::~UniMRCPClient()
{
apt_log(APT_LOG_MARK, APT_PRIO_DEBUG, "%s ~UniMRCPClient: client(%pp) app(%pp) this(%pp)",
swig_target_platform, client, app, this);
Destroy();
}
void UniMRCPClient::Destroy()
{
if (client && !terminated) {
terminated = true;
mrcp_client_shutdown(client);
mrcp_client_destroy(client);
app = NULL;
client = NULL;
instances--;
apt_log(APT_LOG_MARK, APT_PRIO_DEBUG, "%s UniMRCPClient (%pp) destroyed, instances(%u)",
swig_target_platform, this, instances);
}
}
apt_bool_t UniMRCPClient::AppMessageHandler(mrcp_app_message_t const* msg)
{
static const mrcp_app_message_dispatcher_t appDisp =
{
reinterpret_cast<int (*)(mrcp_application_t*, mrcp_session_t*, mrcp_sig_status_code_e)>(
UniMRCPClientSession::AppOnSessionUpdate),
reinterpret_cast<int (*)(mrcp_application_t*, mrcp_session_t*, mrcp_sig_status_code_e)>(
UniMRCPClientSession::AppOnSessionTerminate),
reinterpret_cast<int (*)(mrcp_application_t*, mrcp_session_t*, mrcp_channel_t*, mrcp_sig_status_code_e)>(
UniMRCPClientChannel::AppOnChannelAdd),
reinterpret_cast<int (*)(mrcp_application_t*, mrcp_session_t*, mrcp_channel_t*, mrcp_sig_status_code_e)>(
UniMRCPClientChannel::AppOnChannelRemove),
UniMRCPClientChannel::AppOnMessageReceive,
UniMRCPClientSession::AppOnTerminateEvent,
reinterpret_cast<int (*)(mrcp_application_t*, mrcp_session_t*, mrcp_session_descriptor_t*, mrcp_sig_status_code_e)>(
UniMRCPClientSession::AppOnResourceDiscover)
};
return mrcp_application_message_dispatch(&appDisp, msg);
}
UniMRCPClientSession::UniMRCPClientSession(UniMRCPClient* _client, char const* profile) THROWS(UniMRCPException) :
sess(NULL),
client(_client),
terminated(false),
destroyOnTerminate(false)
{
sess = mrcp_application_session_create(client->app, profile, this);
if (!sess)
UNIMRCP_THROW("Cannot create UniMRCP client session");
char name[64];
unsigned int id = apr_atomic_inc32(&client->sess_id);
snprintf(name, sizeof(name) - 1, "%s-%02u", swig_target_platform, static_cast<unsigned>(id));
mrcp_application_session_name_set(sess, name);
}
UniMRCPClientSession::~UniMRCPClientSession()
{
apt_log(APT_LOG_MARK, APT_PRIO_DEBUG, "%s ~UniMRCPClientSession sess(%pp) terminated(%s) this(%pp)",
swig_target_platform, sess, terminated ? "TRUE" : "FALSE", this);
if (sess)
// This object will not exist anymore
mrcp_application_session_object_set(sess, NULL);
Destroy();
}
void UniMRCPClientSession::ResourceDiscover()
{
apt_log(APT_LOG_MARK, APT_PRIO_DEBUG, "%s Session ResourceDiscover sess(%pp) this(%pp)",
swig_target_platform, sess, this);
if (sess)
mrcp_application_resource_discover(sess);
}
void UniMRCPClientSession::Terminate()
{
apt_log(APT_LOG_MARK, APT_PRIO_DEBUG, "%s Session Terminate sess(%pp) terminated(%s) this(%pp)",
swig_target_platform, sess, terminated ? "TRUE" : "FALSE", this);
if (sess && !terminated) {
mrcp_application_session_terminate(sess);
}
}
void UniMRCPClientSession::Destroy()
{
apt_log(APT_LOG_MARK, APT_PRIO_DEBUG, "%s Session Destroy sess(%pp) terminated(%s) this(%pp)",
swig_target_platform, sess, terminated ? "TRUE" : "FALSE", this);
if (client->terminated) return;
if (destroyOnTerminate) return;
if (sess) {
if (!terminated) {
destroyOnTerminate = true;
mrcp_application_session_terminate(sess);
} else {
mrcp_application_session_destroy(sess);
sess = NULL;
}
}
}
char const* UniMRCPClientSession::GetID() const
{
if (!sess) return NULL;
return mrcp_application_session_id_get(sess)->buf;
}
bool UniMRCPClientSession::OnUpdate(UniMRCPSigStatusCode status)
{
(void) status;
return true;
}
bool UniMRCPClientSession::OnTerminate(UniMRCPSigStatusCode status)
{
(void) status;
return true;
}
bool UniMRCPClientSession::OnTerminateEvent()
{
return true;
}
apt_bool_t UniMRCPClientSession::AppOnSessionUpdate(mrcp_application_t* application, mrcp_session_t* session, UniMRCPSigStatusCode status)
{
(void) application;
UniMRCPClientSession* s = reinterpret_cast<UniMRCPClientSession*>(mrcp_application_session_object_get(session));
apt_log(APT_LOG_MARK, APT_PRIO_DEBUG, "%s OnSessionUpdate: sess(%pp) status(%d) sess_obj(%pp)",
swig_target_platform, session, static_cast<int>(status), s);
if (!s) return FALSE;
bool ret = s->OnUpdate(status);
apt_log(APT_LOG_MARK, APT_PRIO_DEBUG, "%s OnSessionUpdate: return %s",
swig_target_platform, ret ? "TRUE" : "FALSE");
return ret;
}
apt_bool_t UniMRCPClientSession::AppOnSessionTerminate(mrcp_application_t* application, mrcp_session_t* session, UniMRCPSigStatusCode status)
{
(void) application;
UniMRCPClientSession* s = reinterpret_cast<UniMRCPClientSession*>(mrcp_application_session_object_get(session));
if (!s) {
// Session object already destroyed so free the C memory as well
apt_log(APT_LOG_MARK, APT_PRIO_DEBUG, "%s OnSessionTerminate: sess(%pp) status(%d) sess_obj(NULL)",
swig_target_platform, session);
mrcp_application_session_destroy(session);
return false;
}
apt_log(APT_LOG_MARK, APT_PRIO_DEBUG, "%s OnSessionTerminate: sess(%pp) status(%d) destroyOnTerminate(%s)",
swig_target_platform, session, static_cast<int>(status), s->destroyOnTerminate ? "TRUE" : "FALSE");
s->terminated = true;
bool ret;
if (!s->destroyOnTerminate)
ret = s->OnTerminate(status);
else
ret = false;
apt_log(APT_LOG_MARK, APT_PRIO_DEBUG, "%s OnSessionTerminate: return %s",
swig_target_platform, ret ? "TRUE" : "FALSE");
if (s->destroyOnTerminate) {
mrcp_application_session_destroy(session);
s->sess = NULL;
}
return ret;
}
apt_bool_t UniMRCPClientSession::AppOnTerminateEvent(mrcp_application_t* application, mrcp_session_t* session, mrcp_channel_t* channel)
{
(void) application;
UniMRCPClientSession* s = reinterpret_cast<UniMRCPClientSession*>(mrcp_application_session_object_get(session));
UniMRCPClientChannel* c = reinterpret_cast<UniMRCPClientChannel*>(mrcp_application_channel_object_get(channel));
if (!s) {
apt_log(APT_LOG_MARK, APT_PRIO_DEBUG, "%s OnTerminateEvent: sess(%pp) status(%d) obj(NULL)",
swig_target_platform, session);
return false;
}
apt_log(APT_LOG_MARK, APT_PRIO_DEBUG, "%s OnTerminateEvent: sess(%pp) chan(%pp) sess_obj(%pp) chan_obj(%pp)",
swig_target_platform, session, channel, s, c);
bool ret = false;
if (!s->destroyOnTerminate) {
if (channel) {
if (c) ret |= c->OnTerminateEvent();
}
if (session) {
ret |= s->OnTerminateEvent();
}
}
apt_log(APT_LOG_MARK, APT_PRIO_DEBUG, "%s OnTerminateEvent: return %s",
swig_target_platform, ret ? "TRUE" : "FALSE");
return ret;
}
apt_bool_t UniMRCPClientSession::AppOnResourceDiscover(mrcp_application_t* application, mrcp_session_t* session, mrcp_session_descriptor_t* descriptor, UniMRCPSigStatusCode status)
{
(void) application;
(void) descriptor;
UniMRCPClientSession* s = reinterpret_cast<UniMRCPClientSession*>(mrcp_application_session_object_get(session));
apt_log(APT_LOG_MARK, APT_PRIO_DEBUG, "%s OnResourceDiscover: sess(%pp) status(%d) sess_obj(%pp)",
swig_target_platform, session, static_cast<int>(status), s);
bool ret = false;
apt_log(APT_LOG_MARK, APT_PRIO_DEBUG, "%s OnResourceDiscover: return %s",
swig_target_platform, ret ? "TRUE" : "FALSE");
return ret;
}
UniMRCPStreamRx::UniMRCPStreamRx() :
frm(NULL),
dtmf_gen(NULL),
term(NULL)
{}
UniMRCPStreamRx::~UniMRCPStreamRx()
{
apt_log(APT_LOG_MARK, APT_PRIO_DEBUG, "%s ~UniMRCPStreamRx term(%pp) dtmf_gen(%pp) this(%pp)",
swig_target_platform, term, dtmf_gen, this);
if (term) {
term->streamRx = NULL;
term = NULL;
}
}
bool UniMRCPStreamRx::SendDTMF(char digit)
{
if (!dtmf_gen) return false;
char digits[2] = {digit, 0};
return mpf_dtmf_generator_enqueue(dtmf_gen, digits) ? true : false;
}
size_t UniMRCPStreamRx::GetDataSize() const
{
if (!frm) return 0;
return frm->codec_frame.size;
}
void UniMRCPStreamRx::SetData(void const* buf, size_t len)
{
if (!frm) return;
if (len > frm->codec_frame.size)
len = frm->codec_frame.size;
if (buf && len)
memcpy(frm->codec_frame.buffer, buf, len);
memset(static_cast<char*>(frm->codec_frame.buffer) + len,
0, frm->codec_frame.size - len);
frm->type |= MEDIA_FRAME_TYPE_AUDIO;
#ifdef LOG_STREAM_DATA
printf("%s UniMRCPStreamRx::SetData %lu bytes:\n", swig_target_platform,
static_cast<unsigned long>(len));
for (size_t i = 0; i < len; i++)
printf("%02x", static_cast<unsigned char const*>(buf)[i]);
putchar('\n');
#endif
}
void UniMRCPStreamRx::OnClose()
{
}
bool UniMRCPStreamRx::ReadFrame()
{
return false;
}
bool UniMRCPStreamRx::OnOpenInternal(UniMRCPAudioTermination const* term, mpf_audio_stream_t const* stm)
{
if (term->dg_band >= 0) {
dtmf_gen = mpf_dtmf_generator_create_ex(stm,
term->dg_band ? static_cast<mpf_dtmf_generator_band_e>(term->dg_band) :
(stm->rx_event_descriptor ? MPF_DTMF_GENERATOR_OUTBAND : MPF_DTMF_GENERATOR_INBAND),
term->dg_tone, term->dg_silence, mrcp_application_session_pool_get(term->sess));
if (!dtmf_gen) {
apt_log(APT_LOG_MARK, APT_PRIO_WARNING, "%s StreamOpenRx: Failed to create DTMF generator",
swig_target_platform);
return false;
}
}
return true;
}
void UniMRCPStreamRx::OnCloseInternal()
{
if (dtmf_gen) {
mpf_dtmf_generator_destroy(dtmf_gen);
dtmf_gen = NULL;
}
}
UniMRCPStreamRxBuffered::UniMRCPStreamRxBuffered() :
UniMRCPStreamRx(),
first(NULL),
last(NULL),
len(0),
pos(0),
flush(false),
mutex(NULL)
#ifdef UW_TRACE_BUFFERS
,rcv(0)
,snt(0)
#endif
{
}
UniMRCPStreamRxBuffered::~UniMRCPStreamRxBuffered()
{
}
/**
* @brief Calculate total buffer chunk size (i.e. metadata/headers plus audio data)
* @param len Length of audio data in bytes
*/
#define CHUNK_SIZE(len) (sizeof(chunk_t) + len)
bool UniMRCPStreamRxBuffered::AddData(void const* buf, size_t len)
{
if (!mutex) return false;
chunk_t* ch = static_cast<chunk_t*>(malloc(CHUNK_SIZE(len)));
if (!ch) return false;
ch->next = NULL;
#ifdef UW_TRACE_BUFFERS
rcv += len;
apt_log(APT_LOG_MARK, APT_PRIO_DEBUG, "Received %8lu bytes, total: %8lu",
static_cast<unsigned long>(len), rcv);
#endif
ch->digit = 0;
ch->len = len;
memcpy(ch->data, buf, len);
apr_thread_mutex_lock(mutex);
if (last)
last->next = ch;
else
first = ch;
last = ch;
this->len += len;
apr_thread_mutex_unlock(mutex);
return true;
}
bool UniMRCPStreamRxBuffered::SendDTMF(char _digit)
{
if (!mutex) return false;
apr_thread_mutex_lock(mutex);
if (last && !last->digit) {
last->digit = _digit;
} else {
chunk_t* ch = static_cast<chunk_t*>(malloc(CHUNK_SIZE(len)));
if (ch) {
ch->next = NULL;
ch->len = 0;
ch->digit = _digit;
if (last)
last->next = ch;
else
first = ch;
last = ch;
}
}
apr_thread_mutex_unlock(mutex);
return true;
}
void UniMRCPStreamRxBuffered::Flush()
{
if (!mutex) return;
apr_thread_mutex_lock(mutex);
flush = true;
apr_thread_mutex_unlock(mutex);
}
bool UniMRCPStreamRxBuffered::ReadFrame()
{
if (!mutex) return false;
size_t copied = 0;
apr_thread_mutex_lock(mutex);
if ((!flush && (len < frm->codec_frame.size)) || (first && !first->len)) {
apr_thread_mutex_unlock(mutex);
return false;
}
while (first && ((copied < frm->codec_frame.size) || !first->len)) {
size_t size = first->len - pos < frm->codec_frame.size - copied ?
first->len - pos : frm->codec_frame.size - copied;
memcpy(static_cast<char*>(frm->codec_frame.buffer) + copied, first->data + pos, size);
pos += size;
len -= size;
copied += size;
if (pos >= first->len) {
if (first->digit) {
apt_bool_t ret = FALSE;
char const digits[2] = {first->digit, 0};
if (dtmf_gen)
ret = mpf_dtmf_generator_enqueue(dtmf_gen, digits);
apt_log(APT_LOG_MARK, ret ? APT_PRIO_INFO : APT_PRIO_WARNING,
"Sending DTMF: %s (%s)", digits, ret ? "OK" : "Failed");
}
pos = 0;
chunk_t *ch = first;
first = first->next;
if (!first) last = NULL;
free(ch);
}
}
if (!first) flush = false;
apr_thread_mutex_unlock(mutex);
if (copied) {
#ifdef UW_TRACE_BUFFERS
snt += copied;
apt_log(APT_LOG_MARK, APT_PRIO_DEBUG, "Sent %8lu bytes, total: %8lu",
static_cast<unsigned long>(copied), snt);
#endif
frm->type |= MEDIA_FRAME_TYPE_AUDIO;
memset(static_cast<char*>(frm->codec_frame.buffer) + copied, 0,
frm->codec_frame.size - copied);
}
return true;
}
bool UniMRCPStreamRxBuffered::OnOpenInternal(UniMRCPAudioTermination const* term, mpf_audio_stream_t const* stm)
{
if (!UniMRCPStreamRx::OnOpenInternal(term, stm))
return false;
apr_status_t status = apr_thread_mutex_create(&mutex, APR_THREAD_MUTEX_DEFAULT,
mrcp_application_session_pool_get(term->sess));
if (status != APR_SUCCESS) {
apt_log(APT_LOG_MARK, APT_PRIO_WARNING, "%s StreamRxBuffered Cannot create mutex: %d %pm",
swig_target_platform, status, &status);
return false;
}
return true;
}
void UniMRCPStreamRxBuffered::OnCloseInternal()
{
chunk_t *ch;
while (first) {
ch = first;
first = first->next;
free(ch);
}
first = NULL;
last = NULL;
if (mutex) {
apr_thread_mutex_destroy(mutex);
mutex = NULL;
}
UniMRCPStreamRx::OnCloseInternal();
}
UniMRCPStreamRxMemory::UniMRCPStreamRxMemory(void const* mem, size_t size, bool copy /*= true*/, StreamRxMemoryEnd onend /*= SRM_NOTHING*/, bool paused /*= false*/) THROWS(UniMRCPException) :
UniMRCPStreamRx(),
mem(NULL)
{
SetMemory(mem, size, copy, onend, paused);
}
UniMRCPStreamRxMemory::~UniMRCPStreamRxMemory()
{
Close();
}
void UniMRCPStreamRxMemory::SetMemory(void const* mem, size_t size, bool copy /*= true*/, StreamRxMemoryEnd onend /*= SRM_NOTHING*/, bool paused /*= false*/) THROWS(UniMRCPException)
{
UniMRCPStreamRxMemory::Close();
if (copy) {
this->mem = static_cast<char*>(malloc(size));
if (!this->mem)
UNIMRCP_THROW("Not enough memory to copy memory block");
memcpy(const_cast<char*>(this->mem), mem, size);
this->copied = true;
} else {
this->mem = static_cast<char const*>(mem);
}
this->size = size;
this->onend = onend;
pos = 0;
this->paused = paused;
}
void UniMRCPStreamRxMemory::Rewind()
{
pos = 0;
}
void UniMRCPStreamRxMemory::Close()
{
if (mem && copied)
free(const_cast<char*>(mem));
mem = NULL;
copied = false;
size = 0;
pos = 0;
}
void UniMRCPStreamRxMemory::SetPaused(bool paused)
{
this->paused = paused;
}
void UniMRCPStreamRxMemory::OnEndOfPlayback()
{
}
bool UniMRCPStreamRxMemory::ReadFrame()
{
if (!mem || !size || paused)
return false;
if ((pos >= size) && (onend == SRM_ZEROS)) {
SetData(NULL, 0); // Send out zeros
return true;
}
size_t sz = GetDataSize();
if (sz > size - pos)
sz = size - pos;
SetData(mem + pos, sz);
pos += sz;
if (pos < size)
return true;
OnEndOfPlayback();
switch (onend) {
case SRM_REWIND:
Rewind();
case SRM_NOTHING:
case SRM_ZEROS:
break;
}
return true;
}
void UniMRCPStreamRxMemory::OnCloseInternal()
{
Close();
UniMRCPStreamRx::OnCloseInternal();
}
UniMRCPStreamRxFile::UniMRCPStreamRxFile(char const* filename, size_t offset /*= 0*/, StreamRxMemoryEnd onend /*= SRM_NOTHING*/, bool paused /*= false*/) :
UniMRCPStreamRxMemory(NULL, 0, false, onend, paused),
filename(strdup(filename)),
offset(offset),
file(NULL),
mmap(NULL)
{
}
UniMRCPStreamRxFile::~UniMRCPStreamRxFile()
{
if (filename) {
free(const_cast<char*>(filename));
filename = NULL;
}
}
bool UniMRCPStreamRxFile::OnOpenInternal(UniMRCPAudioTermination const* term, mpf_audio_stream_t const* stm)
{
if (!UniMRCPStreamRxMemory::OnOpenInternal(term, stm))
return false;
apr_pool_t* pool = mrcp_application_session_pool_get(term->sess);
apr_status_t status;
status = apr_file_open(&file, filename, APR_FOPEN_READ | APR_FOPEN_BINARY, APR_FPROT_OS_DEFAULT, pool);
if (status != APR_SUCCESS) {
apt_log(APT_LOG_MARK, APT_PRIO_WARNING, "Error opening file %s: %d %pm", filename, status, &status);
return false;
}
apr_finfo_t finfo;
status = apr_file_info_get(&finfo, APR_FINFO_SIZE, file);
if (status != APR_SUCCESS) {
apt_log(APT_LOG_MARK, APT_PRIO_WARNING, "Error getting size of file %s: %d %pm", filename, status, &status);
apr_file_close(file);
return false;
}
if ((finfo.size < 0) || (offset >= static_cast<size_t>(finfo.size))) {
apt_log(APT_LOG_MARK, APT_PRIO_WARNING, "Offest %"APR_SIZE_T_FMT" beyond file size %"APR_OFF_T_FMT, offset, finfo.size);
return false;
}
apr_size_t poffset = offset & ~(PAGE_SIZE - 1);
apr_size_t psize = static_cast<apr_size_t>(finfo.size - poffset);
status = apr_mmap_create(&mmap, file, poffset, psize, APR_MMAP_READ, pool);
if (status != APR_SUCCESS) {
apt_log(APT_LOG_MARK, APT_PRIO_WARNING, "Error mmapping file %s: %d %pm", filename, status, &status);
apr_file_close(file);
return false;
}
SetMemory(static_cast<char*>(mmap->mm) + offset - poffset, static_cast<apr_size_t>(finfo.size) - offset, false, onend, paused);