-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
mod_avmd.c
2309 lines (2036 loc) · 86.4 KB
/
mod_avmd.c
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
/*
* FreeSWITCH Modular Media Switching Software Library / Soft-Switch Application
* Copyright (C) 2010, Eric des Courtis <eric.des.courtis@benbria.com>
*
* Version: MPL 1.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* Eric des Courtis <eric.des.courtis@benbria.com>
* Copyright (C) Benbria. All Rights Reserved.
*
* Contributor(s):
*
* Eric des Courtis <eric.des.courtis@benbria.com>
* Piotr Gregor <piotrgregor@rsyncme.org>
*
* mod_avmd.c -- Advanced Voicemail Detection Module
*
* This module detects single frequency tones (used in voicemail to denote
* the moment caller's voice is started to be recorded, aka. beep sounds,
* beeps) using modified DESA-2 algorithm.
*/
#include <switch.h>
#include <g711.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <float.h>
#ifdef WIN32
#include <float.h>
#define ISNAN(x) (!!(_isnan(x)))
#define ISINF(x) (isinf(x))
#else
int __isnan(double);
int __isinf(double);
#define ISNAN(x) (__isnan(x))
#define ISINF(x) (__isinf(x))
#endif
#include "avmd_buffer.h"
#include "avmd_desa2_tweaked.h"
#include "avmd_sma_buf.h"
#include "avmd_options.h"
#include "avmd_fir.h"
#include "avmd_fast_acosf.h"
/*! Calculate how many audio samples per ms based on the rate */
#define AVMD_SAMPLES_PER_MS(r, m) ((r) / (1000/(m)))
/*! Minimum beep length */
#define AVMD_BEEP_TIME (2)
/*! How often to evaluate the output of DESA-2 in ms */
#define AVMD_SINE_TIME (1*0.125)
/*! How long in samples does DESA-2 results get evaluated */
#define AVMD_SINE_LEN(r) AVMD_SAMPLES_PER_MS((r), AVMD_SINE_TIME)
/*! How long in samples is the minimum beep length */
#define AVMD_BEEP_LEN(r) AVMD_SAMPLES_PER_MS((r), AVMD_BEEP_TIME)
/*! Number of points in DESA-2 sample */
#define AVMD_P (5)
/*! Guesstimate frame length in ms */
#define AVMD_FRAME_TIME (20)
/*! Length in samples of the frame (guesstimate) */
#define AVMD_FRAME_LEN(r) AVMD_SAMPLES_PER_MS((r), AVMD_FRAME_TIME)
/*! Conversion to Hertz */
#define AVMD_TO_HZ(r, f) (((r) * (f)) / (2.0 * M_PI))
/*! Minimum absolute pressure/amplitude */
#define AVMD_MIN_AMP (17.0)
/*! Minimum beep frequency in Hertz */
#define AVMD_MIN_FREQUENCY (440.0)
/*! Minimum frequency as digital normalized frequency */
#define AVMD_MIN_FREQUENCY_R(r) ((2.0 * M_PI * AVMD_MIN_FREQUENCY) / (r))
/*!
* Maximum beep frequency in Hertz
* Note: The maximum frequency the DESA-2 algorithm can uniquely
* identify is 0.25 of the sampling rate. All the frequencies
* below that level are detected unambiguously. This means 2kHz
* for 8kHz audio. All the frequencies above 0.25 sampling rate
* will be aliased to frequencies below that threshold,
* i.e. OMEGA > PI/2 will be aliased to PI - OMEGA.
* This is not a problem here as we are interested in detection
* of any constant amplitude and frequency sine wave instead
* of detection of particular frequency.
* In case of DESA-1, frequencies up to 0.5 sampling rate are
* identified uniquely.
*/
#define AVMD_MAX_FREQUENCY (2000.0)
/*! Maximum frequency as digital normalized frequency */
#define AVMD_MAX_FREQUENCY_R(r) ((2.0 * M_PI * AVMD_MAX_FREQUENCY) / (r))
#define AVMD_VARIANCE_RSD_THRESHOLD (0.000025)
#define AVMD_AMPLITUDE_RSD_THRESHOLD (0.0148)
/*! Syntax of the API call. */
#define AVMD_SYNTAX "<uuid> < start | stop | set [inbound|outbound|default] | load [inbound|outbound] | reload | show >"
/*! Number of expected parameters in api call. */
#define AVMD_PARAMS_API_MIN 1u
#define AVMD_PARAMS_API_MAX 2u
#define AVMD_PARAMS_APP_MAX 30u
#define AVMD_PARAMS_APP_START_MIN 0u
#define AVMD_PARAMS_APP_START_MAX 20u
#define AVMD_READ_REPLACE 0
#define AVMD_WRITE_REPLACE 1
/* don't forget to update avmd_events_str table if you modify this */
enum avmd_event
{
AVMD_EVENT_BEEP = 0,
AVMD_EVENT_SESSION_START = 1,
AVMD_EVENT_SESSION_STOP = 2
};
/* This array MUST be NULL terminated! */
const char* avmd_events_str[] = {
[AVMD_EVENT_BEEP] = "avmd::beep",
[AVMD_EVENT_SESSION_START] = "avmd::start",
[AVMD_EVENT_SESSION_STOP] = "avmd::stop",
NULL /* MUST be last and always here */
};
#define AVMD_CHAR_BUF_LEN 20u
#define AVMD_BUF_LINEAR_LEN 160u
enum avmd_app
{
AVMD_APP_START_APP = 0,
AVMD_APP_STOP_APP = 1,
AVMD_APP_START_FUNCTION = 2 /* deprecated since version 1.6.8 */
};
enum avmd_detection_mode
{
AVMD_DETECT_AMP = 0,
AVMD_DETECT_FREQ = 1,
AVMD_DETECT_BOTH = 2,
AVMD_DETECT_NONE = 3
};
/* Prototypes */
SWITCH_MODULE_SHUTDOWN_FUNCTION(mod_avmd_shutdown);
SWITCH_MODULE_LOAD_FUNCTION(mod_avmd_load);
SWITCH_MODULE_DEFINITION(mod_avmd, mod_avmd_load, mod_avmd_shutdown, NULL);
SWITCH_STANDARD_API(avmd_api_main);
SWITCH_STANDARD_APP(avmd_start_app);
SWITCH_STANDARD_APP(avmd_stop_app);
SWITCH_STANDARD_APP(avmd_start_function);
struct avmd_settings {
uint8_t debug;
uint8_t report_status;
uint8_t fast_math;
uint8_t require_continuous_streak;
uint16_t sample_n_continuous_streak;
uint16_t sample_n_to_skip;
uint8_t require_continuous_streak_amp;
uint16_t sample_n_continuous_streak_amp;
uint8_t simplified_estimation;
uint8_t inbound_channnel;
uint8_t outbound_channnel;
enum avmd_detection_mode mode;
uint8_t detectors_n;
uint8_t detectors_lagged_n;
};
/*! Status of the beep detection */
typedef enum {
BEEP_DETECTED,
BEEP_NOTDETECTED
} avmd_beep_state_t;
/*! Data related to the current status of the beep */
typedef struct {
avmd_beep_state_t beep_state;
size_t last_beep;
} avmd_state_t;
struct avmd_session;
typedef struct avmd_session avmd_session_t;
struct avmd_buffer {
sma_buffer_t sma_b;
sma_buffer_t sqa_b;
sma_buffer_t sma_b_fir;
sma_buffer_t sqa_b_fir;
sma_buffer_t sma_amp_b;
sma_buffer_t sqa_amp_b;
uint8_t resolution;
uint8_t offset;
double amplitude_max;
size_t samples_streak, samples_streak_amp; /* number of DESA samples in single streak without reset needed to validate SMA estimator */
};
struct avmd_detector {
switch_thread_t *thread;
switch_mutex_t *mutex;
uint8_t flag_processing_done;
uint8_t flag_should_exit;
enum avmd_detection_mode result;
switch_thread_cond_t *cond_start_processing;
struct avmd_buffer buffer;
avmd_session_t *s;
size_t samples;
uint8_t idx;
uint8_t lagged, lag;
};
/*! Type that holds avmd detection session information. */
struct avmd_session {
switch_core_session_t *session;
switch_mutex_t *mutex;
struct avmd_settings settings;
uint32_t rate;
circ_buffer_t b;
size_t pos;
double f;
avmd_state_t state;
switch_time_t start_time, stop_time, detection_start_time, detection_stop_time;
size_t frame_n;
uint8_t frame_n_to_skip;
switch_mutex_t *mutex_detectors_done;
switch_thread_cond_t *cond_detectors_done;
struct avmd_detector *detectors;
};
static struct avmd_globals
{
switch_mutex_t *mutex;
struct avmd_settings settings;
switch_memory_pool_t *pool;
size_t session_n;
} avmd_globals;
static void avmd_process(avmd_session_t *session, switch_frame_t *frame, uint8_t direction);
static switch_bool_t avmd_callback(switch_media_bug_t * bug, void *user_data, switch_abc_type_t type);
static switch_status_t avmd_register_all_events(void);
static void avmd_unregister_all_events(void);
static void avmd_fire_event(enum avmd_event type, switch_core_session_t *fs_s, double freq, double v_freq, double amp, double v_amp, avmd_beep_state_t beep_status, uint8_t info,
switch_time_t detection_start_time, switch_time_t detection_stop_time, switch_time_t start_time, switch_time_t stop_time, uint8_t resolution, uint8_t offset, uint8_t idx);
static enum avmd_detection_mode avmd_process_sample(avmd_session_t *s, circ_buffer_t *b, size_t sample_n, size_t pos, struct avmd_detector *d);
/* API [set default], reset to factory settings */
static void avmd_set_xml_default_configuration(switch_mutex_t *mutex);
/* API [set inbound], set inbound = 1, outbound = 0 */
static void avmd_set_xml_inbound_configuration(switch_mutex_t *mutex);
/* API [set outbound], set inbound = 0, outbound = 1 */
static void avmd_set_xml_outbound_configuration(switch_mutex_t *mutex);
/* API [reload], reload XML configuration data from RAM */
static switch_status_t avmd_load_xml_configuration(switch_mutex_t *mutex);
/* API [load inbound], reload + set inbound */
static switch_status_t avmd_load_xml_inbound_configuration(switch_mutex_t *mutex);
/* API [load outbound], reload + set outbound */
static switch_status_t avmd_load_xml_outbound_configuration(switch_mutex_t *mutex);
/* bind reloadxml callback */
static void avmd_reloadxml_event_handler(switch_event_t *event);
/* API command */
static void avmd_show(switch_stream_handle_t *stream, switch_mutex_t *mutex);
static void* SWITCH_THREAD_FUNC
avmd_detector_func(switch_thread_t *thread, void *arg);
static uint8_t
avmd_detection_in_progress(avmd_session_t *s);
static switch_status_t avmd_launch_threads(avmd_session_t *s) {
uint8_t idx;
struct avmd_detector *d;
switch_threadattr_t *thd_attr = NULL;
idx = 0;
while (idx < s->settings.detectors_n) {
d = &s->detectors[idx];
d->flag_processing_done = 1;
d->flag_should_exit = 0;
d->result = AVMD_DETECT_NONE;
d->lagged = 0;
d->lag = 0;
switch_threadattr_create(&thd_attr, avmd_globals.pool);
switch_threadattr_stacksize_set(thd_attr, SWITCH_THREAD_STACKSIZE);
if (switch_thread_create(&d->thread, thd_attr, avmd_detector_func, d, switch_core_session_get_pool(s->session)) != SWITCH_STATUS_SUCCESS) {
return SWITCH_STATUS_FALSE;
}
if (s->settings.debug) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "AVMD: started thread idx=%u\n", idx);
}
++idx;
}
idx = 0;
while (idx < s->settings.detectors_lagged_n) {
d = &s->detectors[s->settings.detectors_n + idx];
d->flag_processing_done = 1;
d->flag_should_exit = 0;
d->result = AVMD_DETECT_NONE;
d->lagged = 1;
d->lag = idx + 1;
switch_threadattr_create(&thd_attr, avmd_globals.pool);
switch_threadattr_stacksize_set(thd_attr, SWITCH_THREAD_STACKSIZE);
if (switch_thread_create(&d->thread, thd_attr, avmd_detector_func, d, switch_core_session_get_pool(s->session)) != SWITCH_STATUS_SUCCESS) {
return SWITCH_STATUS_FALSE;
}
if (s->settings.debug) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "AVMD: started lagged thread idx=%u\n", s->settings.detectors_n + idx);
}
++idx;
}
return SWITCH_STATUS_SUCCESS;
}
static void avmd_join_threads(avmd_session_t *s) {
uint8_t idx;
struct avmd_detector *d;
switch_status_t status;
idx = 0;
while (idx < s->settings.detectors_n) {
d = &s->detectors[idx];
switch_mutex_lock(d->mutex);
if (d->thread != NULL) {
d->flag_should_exit = 1;
d->samples = 0;
switch_thread_cond_signal(d->cond_start_processing);
switch_mutex_unlock(d->mutex);
switch_thread_join(&status, d->thread);
d->thread = NULL;
switch_mutex_destroy(d->mutex);
switch_thread_cond_destroy(d->cond_start_processing);
} else {
switch_mutex_unlock(d->mutex);
}
++idx;
}
idx = 0;
while (idx < s->settings.detectors_lagged_n) {
d = &s->detectors[s->settings.detectors_n + idx];
switch_mutex_lock(d->mutex);
if (d->thread != NULL) {
d->flag_should_exit = 1;
d->samples = 0;
switch_thread_cond_signal(d->cond_start_processing);
switch_mutex_unlock(d->mutex);
switch_thread_join(&status, d->thread);
d->thread = NULL;
switch_mutex_destroy(d->mutex);
switch_thread_cond_destroy(d->cond_start_processing);
} else {
switch_mutex_unlock(d->mutex);
}
++idx;
}
}
static switch_status_t avmd_init_buffer(struct avmd_buffer *b, size_t buf_sz, uint8_t resolution, uint8_t offset, switch_core_session_t *fs_session) {
INIT_SMA_BUFFER(&b->sma_b, buf_sz, fs_session);
if (b->sma_b.data == NULL) {
return SWITCH_STATUS_FALSE;
}
memset(b->sma_b.data, 0, sizeof(BUFF_TYPE) * buf_sz);
INIT_SMA_BUFFER(&b->sqa_b, buf_sz, fs_session);
if (b->sqa_b.data == NULL) {
return SWITCH_STATUS_FALSE;
}
memset(b->sqa_b.data, 0, sizeof(BUFF_TYPE) * buf_sz);
INIT_SMA_BUFFER(&b->sma_b_fir, buf_sz, fs_session);
if (b->sma_b_fir.data == NULL) {
return SWITCH_STATUS_FALSE;
}
memset(b->sma_b_fir.data, 0, sizeof(BUFF_TYPE) * buf_sz);
INIT_SMA_BUFFER(&b->sqa_b_fir, buf_sz, fs_session);
if (b->sqa_b_fir.data == NULL) {
return SWITCH_STATUS_FALSE;
}
memset(b->sqa_b_fir.data, 0, sizeof(BUFF_TYPE) * buf_sz);
INIT_SMA_BUFFER(&b->sma_amp_b, buf_sz, fs_session);
if (b->sma_amp_b.data == NULL) {
return SWITCH_STATUS_FALSE;
}
memset(b->sma_amp_b.data, 0, sizeof(BUFF_TYPE) * buf_sz);
INIT_SMA_BUFFER(&b->sqa_amp_b, buf_sz, fs_session);
if (b->sqa_amp_b.data == NULL) {
return SWITCH_STATUS_FALSE;
}
memset(b->sqa_amp_b.data, 0, sizeof(BUFF_TYPE) * buf_sz);
b->amplitude_max = 0.0;
b->samples_streak = 0;
b->samples_streak_amp = 0;
b->resolution = resolution;
b->offset = offset;
return SWITCH_STATUS_SUCCESS;
}
/*! \brief The avmd session data initialization function.
* @param avmd_session A reference to a avmd session.
* @param fs_session A reference to a FreeSWITCH session.
* @details Avmd globals mutex must be locked.
*/
static switch_status_t init_avmd_session_data(avmd_session_t *avmd_session, switch_core_session_t *fs_session, switch_mutex_t *mutex)
{
uint8_t idx, resolution, offset;
size_t buf_sz;
struct avmd_detector *d;
switch_status_t status = SWITCH_STATUS_SUCCESS;
if (mutex != NULL)
{
switch_mutex_lock(mutex);
}
/*! This is a worst case sample rate estimate */
avmd_session->rate = 48000;
INIT_CIRC_BUFFER(&avmd_session->b, (size_t) AVMD_BEEP_LEN(avmd_session->rate), (size_t) AVMD_FRAME_LEN(avmd_session->rate), fs_session);
if (avmd_session->b.buf == NULL) {
status = SWITCH_STATUS_MEMERR;
goto end;
}
avmd_session->session = fs_session;
avmd_session->pos = 0;
avmd_session->f = 0.0;
avmd_session->state.last_beep = 0;
avmd_session->state.beep_state = BEEP_NOTDETECTED;
switch_mutex_init(&avmd_session->mutex, SWITCH_MUTEX_DEFAULT, switch_core_session_get_pool(fs_session));
avmd_session->frame_n = 0;
avmd_session->detection_start_time = 0;
avmd_session->detection_stop_time = 0;
avmd_session->frame_n_to_skip = 0;
buf_sz = AVMD_BEEP_LEN((uint32_t)avmd_session->rate) / (uint32_t) AVMD_SINE_LEN(avmd_session->rate);
if (buf_sz < 1) {
status = SWITCH_STATUS_MORE_DATA;
goto end;
}
avmd_session->detectors = (struct avmd_detector*) switch_core_session_alloc(fs_session, (avmd_session->settings.detectors_n + avmd_session->settings.detectors_lagged_n) * sizeof(struct avmd_detector));
if (avmd_session->detectors == NULL) {
switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(fs_session), SWITCH_LOG_ERROR, "Can't allocate memory for avmd detectors!\n");
status = SWITCH_STATUS_NOT_INITALIZED;
goto end;
}
idx = 0;
resolution = 0;
while (idx < avmd_session->settings.detectors_n) {
++resolution;
offset = 0;
while ((offset < resolution) && (idx < avmd_session->settings.detectors_n)) {
d = &avmd_session->detectors[idx];
if (avmd_init_buffer(&d->buffer, buf_sz, resolution, offset, fs_session) != SWITCH_STATUS_SUCCESS) {
status = SWITCH_STATUS_FALSE;
goto end;
}
d->s = avmd_session;
d->flag_processing_done = 1;
d->flag_should_exit = 1;
d->idx = idx;
d->thread = NULL;
switch_mutex_init(&d->mutex, SWITCH_MUTEX_DEFAULT, switch_core_session_get_pool(fs_session));
switch_thread_cond_create(&d->cond_start_processing, switch_core_session_get_pool(fs_session));
++offset;
++idx;
}
}
idx = 0;
resolution = 1;
offset = 0;
while (idx < avmd_session->settings.detectors_lagged_n) {
d = &avmd_session->detectors[avmd_session->settings.detectors_n + idx];
if (avmd_init_buffer(&d->buffer, buf_sz, resolution, offset, fs_session) != SWITCH_STATUS_SUCCESS) {
status = SWITCH_STATUS_FALSE;
goto end;
}
d->s = avmd_session;
d->flag_processing_done = 1;
d->flag_should_exit = 1;
d->idx = avmd_session->settings.detectors_n + idx;
d->thread = NULL;
switch_mutex_init(&d->mutex, SWITCH_MUTEX_DEFAULT, switch_core_session_get_pool(fs_session));
switch_thread_cond_create(&d->cond_start_processing, switch_core_session_get_pool(fs_session));
++idx;
}
switch_mutex_init(&avmd_session->mutex_detectors_done, SWITCH_MUTEX_DEFAULT, switch_core_session_get_pool(fs_session));
switch_thread_cond_create(&avmd_session->cond_detectors_done, switch_core_session_get_pool(fs_session));
end:
if (mutex != NULL)
{
switch_mutex_unlock(mutex);
}
return status;
}
static void avmd_session_close(avmd_session_t *s) {
uint8_t idx;
struct avmd_detector *d;
switch_status_t status;
switch_mutex_lock(s->mutex);
switch_mutex_lock(s->mutex_detectors_done);
while (avmd_detection_in_progress(s) == 1) {
switch_thread_cond_wait(s->cond_detectors_done, s->mutex_detectors_done);
}
switch_mutex_unlock(s->mutex_detectors_done);
idx = 0;
while (idx < (s->settings.detectors_n + s->settings.detectors_lagged_n)) {
d = &s->detectors[idx];
switch_mutex_lock(d->mutex);
d = &s->detectors[idx];
d->flag_processing_done = 0;
d->flag_should_exit = 1;
d->samples = 0;
switch_thread_cond_signal(d->cond_start_processing);
switch_mutex_unlock(d->mutex);
switch_thread_join(&status, d->thread);
d->thread = NULL;
switch_mutex_destroy(d->mutex);
switch_thread_cond_destroy(d->cond_start_processing);
++idx;
}
switch_mutex_unlock(s->mutex);
switch_mutex_destroy(s->mutex_detectors_done);
switch_thread_cond_destroy(s->cond_detectors_done);
switch_mutex_destroy(s->mutex);
}
/*! \brief The callback function that is called when new audio data becomes available.
* @param bug A reference to the media bug.
* @param user_data The session information for this call.
* @param type The switch callback type.
* @return The success or failure of the function.
*/
static switch_bool_t avmd_callback(switch_media_bug_t * bug, void *user_data, switch_abc_type_t type) {
avmd_session_t *avmd_session;
switch_codec_t *read_codec;
switch_codec_t *write_codec;
switch_frame_t *frame;
switch_core_session_t *fs_session;
switch_channel_t *channel = NULL;
avmd_session = (avmd_session_t *) user_data;
if (avmd_session == NULL) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "No avmd session assigned!\n");
return SWITCH_FALSE;
}
if ((type != SWITCH_ABC_TYPE_INIT) && (type != SWITCH_ABC_TYPE_CLOSE)) {
switch_mutex_lock(avmd_session->mutex);
}
fs_session = avmd_session->session;
if (fs_session == NULL) {
if (type != SWITCH_ABC_TYPE_INIT) {
switch_mutex_unlock(avmd_session->mutex);
}
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "No FreeSWITCH session assigned!\n");
return SWITCH_FALSE;
}
channel = switch_core_session_get_channel(fs_session);
if (channel == NULL) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "No channel for FreeSWITCH session!\n");
return SWITCH_FALSE;
}
switch (type) {
case SWITCH_ABC_TYPE_INIT:
if ((SWITCH_CALL_DIRECTION_OUTBOUND == switch_channel_direction(channel)) && (avmd_session->settings.outbound_channnel == 1)) {
read_codec = switch_core_session_get_read_codec(fs_session);
if (read_codec == NULL) {
switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(fs_session), SWITCH_LOG_WARNING, "No read codec assigned, default session rate to 8000 samples/s\n");
avmd_session->rate = 8000;
} else {
if (read_codec->implementation == NULL) {
switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(fs_session), SWITCH_LOG_WARNING, "No read codec implementation assigned, default session rate to 8000 samples/s\n");
avmd_session->rate = 8000;
} else {
avmd_session->rate = read_codec->implementation->samples_per_second;
}
}
}
if ((SWITCH_CALL_DIRECTION_INBOUND == switch_channel_direction(channel)) && (avmd_session->settings.inbound_channnel == 1)) {
write_codec = switch_core_session_get_write_codec(fs_session);
if (write_codec == NULL) {
switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(fs_session), SWITCH_LOG_WARNING, "No write codec assigned, default session rate to 8000 samples/s\n");
avmd_session->rate = 8000;
} else {
if (write_codec->implementation == NULL) {
switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(fs_session), SWITCH_LOG_WARNING, "No write codec implementation assigned, default session rate to 8000 samples/s\n");
avmd_session->rate = 8000;
} else {
avmd_session->rate = write_codec->implementation->samples_per_second;
}
}
}
avmd_session->start_time = switch_micro_time_now();
/* avmd_session->vmd_codec.channels = read_codec->implementation->number_of_channels; */
switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(fs_session),SWITCH_LOG_INFO, "Avmd session initialized, [%u] samples/s\n", avmd_session->rate);
break;
case SWITCH_ABC_TYPE_READ_REPLACE:
frame = switch_core_media_bug_get_read_replace_frame(bug);
avmd_process(avmd_session, frame, AVMD_READ_REPLACE);
break;
case SWITCH_ABC_TYPE_WRITE_REPLACE:
frame = switch_core_media_bug_get_write_replace_frame(bug);
avmd_process(avmd_session, frame, AVMD_WRITE_REPLACE);
break;
case SWITCH_ABC_TYPE_CLOSE:
avmd_session_close(avmd_session);
switch_mutex_lock(avmd_globals.mutex);
if (avmd_globals.session_n > 0) {
--avmd_globals.session_n;
}
switch_mutex_unlock(avmd_globals.mutex);
break;
default:
break;
}
if ((type != SWITCH_ABC_TYPE_INIT) && (type != SWITCH_ABC_TYPE_CLOSE)) {
switch_mutex_unlock(avmd_session->mutex);
}
return SWITCH_TRUE;
}
static switch_status_t avmd_register_all_events(void) {
size_t idx = 0;
const char *e = avmd_events_str[0];
while (e != NULL)
{
if (switch_event_reserve_subclass(e) != SWITCH_STATUS_SUCCESS) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Couldn't register subclass [%s]!\n", e);
return SWITCH_STATUS_TERM;
}
++idx;
e = avmd_events_str[idx];
}
return SWITCH_STATUS_SUCCESS;
}
static void avmd_unregister_all_events(void) {
size_t idx = 0;
const char *e = avmd_events_str[0];
while (e != NULL)
{
switch_event_free_subclass(e);
++idx;
e = avmd_events_str[idx];
}
return;
}
static void avmd_fire_event(enum avmd_event type, switch_core_session_t *fs_s, double freq, double v_freq, double amp, double v_amp, avmd_beep_state_t beep_status, uint8_t info,
switch_time_t detection_start_time, switch_time_t detection_stop_time, switch_time_t start_time, switch_time_t stop_time, uint8_t resolution, uint8_t offset, uint8_t idx) {
int res;
switch_event_t *event;
switch_time_t detection_time, total_time;
switch_status_t status;
switch_event_t *event_copy;
char buf[AVMD_CHAR_BUF_LEN];
status = switch_event_create_subclass(&event, SWITCH_EVENT_CUSTOM, avmd_events_str[type]);
if (status != SWITCH_STATUS_SUCCESS) {
return;
}
switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Unique-ID", switch_core_session_get_uuid(fs_s));
switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Call-command", "avmd");
switch (type)
{
case AVMD_EVENT_BEEP:
switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Beep-Status", "DETECTED");
res = snprintf(buf, AVMD_CHAR_BUF_LEN, "%f", freq);
if (res < 0 || res > AVMD_CHAR_BUF_LEN - 1) {
switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(fs_s), SWITCH_LOG_ERROR, "Frequency truncated [%s], [%d] attempted!\n", buf, res);
switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Frequency", "ERROR (TRUNCATED)");
}
switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Frequency", buf);
res = snprintf(buf, AVMD_CHAR_BUF_LEN, "%f", v_freq);
if (res < 0 || res > AVMD_CHAR_BUF_LEN - 1) {
switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(fs_s), SWITCH_LOG_ERROR, "Error, truncated [%s], [%d] attempeted!\n", buf, res);
switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Frequency-variance", "ERROR (TRUNCATED)");
}
switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Frequency-variance", buf);
res = snprintf(buf, AVMD_CHAR_BUF_LEN, "%f", amp);
if (res < 0 || res > AVMD_CHAR_BUF_LEN - 1) {
switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(fs_s), SWITCH_LOG_ERROR, "Amplitude truncated [%s], [%d] attempted!\n", buf, res);
switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Amplitude", "ERROR (TRUNCATED)");
}
switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Amplitude", buf);
res = snprintf(buf, AVMD_CHAR_BUF_LEN, "%f", v_amp);
if (res < 0 || res > AVMD_CHAR_BUF_LEN - 1) {
switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(fs_s), SWITCH_LOG_ERROR, "Error, truncated [%s], [%d] attempeted!\n", buf, res);
switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Amplitude-variance", "ERROR (TRUNCATED)");
}
switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Amplitude-variance", buf);
detection_time = detection_stop_time - detection_start_time;
res = snprintf(buf, AVMD_CHAR_BUF_LEN, "%" PRId64 "", detection_time);
if (res < 0 || res > AVMD_CHAR_BUF_LEN - 1) {
switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(fs_s), SWITCH_LOG_ERROR, "Detection time truncated [%s], [%d] attempted!\n", buf, res);
switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Detection-time", "ERROR (TRUNCATED)");
}
switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Detection-time", buf);
res = snprintf(buf, AVMD_CHAR_BUF_LEN, "%u", resolution);
if (res < 0 || res > AVMD_CHAR_BUF_LEN - 1) {
switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(fs_s), SWITCH_LOG_ERROR, "Error, truncated [%s], [%d] attempeted!\n", buf, res);
switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Detector-resolution", "ERROR (TRUNCATED)");
}
switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Detector-resolution", buf);
res = snprintf(buf, AVMD_CHAR_BUF_LEN, "%u", offset);
if (res < 0 || res > AVMD_CHAR_BUF_LEN - 1) {
switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(fs_s), SWITCH_LOG_ERROR, "Error, truncated [%s], [%d] attempeted!\n", buf, res);
switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Detector-offset", "ERROR (TRUNCATED)");
}
switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Detector-offset", buf);
res = snprintf(buf, AVMD_CHAR_BUF_LEN, "%u", idx);
if (res < 0 || res > AVMD_CHAR_BUF_LEN - 1) {
switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(fs_s), SWITCH_LOG_ERROR, "Error, truncated [%s], [%d] attempeted!\n", buf, res);
switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Detector-index", "ERROR (TRUNCATED)");
}
switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Detector-index", buf);
break;
case AVMD_EVENT_SESSION_START:
res = snprintf(buf, AVMD_CHAR_BUF_LEN, "%" PRId64 "", start_time);
if (res < 0 || res > AVMD_CHAR_BUF_LEN - 1) {
switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(fs_s), SWITCH_LOG_ERROR, "Start time truncated [%s], [%d] attempted!\n", buf, res);
switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Start-time", "ERROR (TRUNCATED)");
}
switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Start-time", buf);
break;
case AVMD_EVENT_SESSION_STOP:
switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Beep-Status", beep_status == BEEP_DETECTED ? "DETECTED" : "NOTDETECTED");
if (info == 0) {
switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Stop-status", "ERROR (AVMD SESSION OBJECT NOT FOUND IN MEDIA BUG)");
}
total_time = stop_time - start_time;
res = snprintf(buf, AVMD_CHAR_BUF_LEN, "%" PRId64 "", total_time);
if (res < 0 || res > AVMD_CHAR_BUF_LEN - 1) {
switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(fs_s), SWITCH_LOG_ERROR, "Total time truncated [%s], [%d] attempted!\n", buf, res);
switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Total-time", "ERROR (TRUNCATED)");
}
switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "Total-time", buf);
break;
default:
switch_event_destroy(&event);
return;
}
if ((switch_event_dup(&event_copy, event)) != SWITCH_STATUS_SUCCESS) {
return;
}
switch_core_session_queue_event(fs_s, &event);
switch_event_fire(&event_copy);
return;
}
int avmd_parse_u8_user_input(const char *input, uint8_t *output, uint8_t min, uint8_t max) {
char *pCh;
unsigned long helper;
helper = strtoul(input, &pCh, 10);
if (helper < min || helper > UINT8_MAX || helper > max || (pCh == input) || (*pCh != '\0')) {
return -1;
}
*output = (uint8_t) helper;
return 0;
}
int avmd_parse_u16_user_input(const char *input, uint16_t *output, uint16_t min, uint16_t max) {
char *pCh;
unsigned long helper;
if (min > max) {
return -1;
}
helper = strtoul(input, &pCh, 10);
if (helper < min || helper > UINT16_MAX || helper > max || (pCh == input) || (*pCh != '\0')) {
return -1;
}
*output = (uint16_t) helper;
return 0;
}
static void avmd_set_xml_default_configuration(switch_mutex_t *mutex) {
if (mutex != NULL) {
switch_mutex_lock(mutex);
}
avmd_globals.settings.debug = 0;
avmd_globals.settings.report_status = 1;
avmd_globals.settings.fast_math = 0;
avmd_globals.settings.require_continuous_streak = 1;
avmd_globals.settings.sample_n_continuous_streak = 3;
avmd_globals.settings.sample_n_to_skip = 0;
avmd_globals.settings.require_continuous_streak_amp = 1;
avmd_globals.settings.sample_n_continuous_streak_amp = 3;
avmd_globals.settings.simplified_estimation = 1;
avmd_globals.settings.inbound_channnel = 0;
avmd_globals.settings.outbound_channnel = 1;
avmd_globals.settings.mode = AVMD_DETECT_BOTH;
avmd_globals.settings.detectors_n = 36;
avmd_globals.settings.detectors_lagged_n = 1;
if (mutex != NULL) {
switch_mutex_unlock(avmd_globals.mutex);
}
return;
}
static void avmd_set_xml_inbound_configuration(switch_mutex_t *mutex)
{
if (mutex != NULL) {
switch_mutex_lock(mutex);
}
avmd_globals.settings.inbound_channnel = 1;
avmd_globals.settings.outbound_channnel = 0;
if (mutex != NULL) {
switch_mutex_unlock(avmd_globals.mutex);
}
return;
}
static void avmd_set_xml_outbound_configuration(switch_mutex_t *mutex) {
if (mutex != NULL) {
switch_mutex_lock(mutex);
}
avmd_globals.settings.inbound_channnel = 0;
avmd_globals.settings.outbound_channnel = 1;
if (mutex != NULL) {
switch_mutex_unlock(avmd_globals.mutex);
}
return;
}
static switch_status_t avmd_load_xml_configuration(switch_mutex_t *mutex) {
switch_xml_t xml = NULL, x_lists = NULL, x_list = NULL, cfg = NULL;
uint8_t bad_debug = 1, bad_report = 1, bad_fast = 1, bad_req_cont = 1, bad_sample_n_cont = 1,
bad_sample_n_to_skip = 1, bad_req_cont_amp = 1, bad_sample_n_cont_amp = 1, bad_simpl = 1,
bad_inbound = 1, bad_outbound = 1, bad_mode = 1, bad_detectors = 1, bad_lagged = 1, bad = 0;
if (mutex != NULL) {
switch_mutex_lock(mutex);
}
if ((xml = switch_xml_open_cfg("avmd.conf", &cfg, NULL)) != NULL) {
if ((x_lists = switch_xml_child(cfg, "settings"))) {
for (x_list = switch_xml_child(x_lists, "param"); x_list; x_list = x_list->next) {
const char *name = switch_xml_attr(x_list, "name");
const char *value = switch_xml_attr(x_list, "value");
if (zstr(name)) {
continue;
}
if (zstr(value)) {
continue;
}
if (!strcmp(name, "debug")) {
avmd_globals.settings.debug = switch_true(value) ? 1 : 0;
bad_debug = 0;
} else if (!strcmp(name, "report_status")) {
avmd_globals.settings.report_status = switch_true(value) ? 1 : 0;
bad_report = 0;
} else if (!strcmp(name, "fast_math")) {
avmd_globals.settings.fast_math = switch_true(value) ? 1 : 0;
bad_fast = 0;
} else if (!strcmp(name, "require_continuous_streak")) {
avmd_globals.settings.require_continuous_streak = switch_true(value) ? 1 : 0;
bad_req_cont = 0;
} else if (!strcmp(name, "sample_n_continuous_streak")) {
if(!avmd_parse_u16_user_input(value, &avmd_globals.settings.sample_n_continuous_streak, 0, UINT16_MAX)) {
bad_sample_n_cont = 0;
}
} else if (!strcmp(name, "sample_n_to_skip")) {
if(!avmd_parse_u16_user_input(value, &avmd_globals.settings.sample_n_to_skip, 0, UINT16_MAX)) {
bad_sample_n_to_skip = 0;
}
} else if (!strcmp(name, "require_continuous_streak_amp")) {
avmd_globals.settings.require_continuous_streak_amp = switch_true(value) ? 1 : 0;
bad_req_cont_amp = 0;
} else if (!strcmp(name, "sample_n_continuous_streak_amp")) {
if(!avmd_parse_u16_user_input(value, &avmd_globals.settings.sample_n_continuous_streak_amp, 0, UINT16_MAX)) {
bad_sample_n_cont_amp = 0;
}
} else if (!strcmp(name, "simplified_estimation")) {
avmd_globals.settings.simplified_estimation = switch_true(value) ? 1 : 0;
bad_simpl = 0;
} else if (!strcmp(name, "inbound_channel")) {
avmd_globals.settings.inbound_channnel = switch_true(value) ? 1 : 0;
bad_inbound = 0;
} else if (!strcmp(name, "outbound_channel")) {
avmd_globals.settings.outbound_channnel = switch_true(value) ? 1 : 0;
bad_outbound = 0;
} else if (!strcmp(name, "detection_mode")) {
if(!avmd_parse_u8_user_input(value, (uint8_t*)&avmd_globals.settings.mode, 0, 2)) {
bad_mode = 0;
}
} else if (!strcmp(name, "detectors_n")) {
if(!avmd_parse_u8_user_input(value, &avmd_globals.settings.detectors_n, 0, UINT8_MAX)) {
bad_detectors = 0;
}
} else if (!strcmp(name, "detectors_lagged_n")) {
if(!avmd_parse_u8_user_input(value, &avmd_globals.settings.detectors_lagged_n, 0, UINT8_MAX)) {
bad_lagged = 0;
}
}
} // for
} // if list
switch_xml_free(xml);
} // if open OK
if (bad_debug) {
bad = 1;
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "AVMD config parameter 'debug' missing or invalid - using default\n");
avmd_globals.settings.debug = 0;
}
if (bad_report) {
bad = 1;
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "AVMD config parameter 'report_status' missing or invalid - using default\n");
avmd_globals.settings.report_status = 1;
}
if (bad_fast) {
bad = 1;
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "AVMD config parameter 'fast_math' missing or invalid - using default\n");
avmd_globals.settings.fast_math = 0;
}
if (bad_req_cont) {
bad = 1;
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "AVMD config parameter 'require_continuous_streak' missing or invalid - using default\n");
avmd_globals.settings.require_continuous_streak = 1;
}
if (bad_sample_n_cont) {
bad = 1;
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "AVMD config parameter 'sample_n_continuous_streak' missing or invalid - using default\n");
avmd_globals.settings.sample_n_continuous_streak = 3;
}
if (bad_sample_n_to_skip) {
bad = 1;
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "AVMD config parameter 'sample_n_to_skip' missing or invalid - using default\n");
avmd_globals.settings.sample_n_to_skip = 0;
}
if (bad_req_cont_amp) {