-
Notifications
You must be signed in to change notification settings - Fork 66
/
Copy pathapp_audiofork.c
1442 lines (1213 loc) · 45 KB
/
app_audiofork.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
/*
* Asterisk -- An open source telephony toolkit.
*
* Copyright (C) 2019, Nadir Hamid
* Copyright (C) 2005 - 2006, Digium, Inc.
*
* Mark Spencer <[email protected]>
* Kevin P. Fleming <[email protected]>
*
* Based on app_muxmon.c provided by
* Anthony Minessale II <[email protected]>
*
* See http://www.asterisk.org for more information about
* the Asterisk project. Please do not directly contact
* any of the maintainers of this project for assistance;
* the project provides a web site, mailing lists and IRC
* channels for your use.
*
* This program is free software, distributed under the terms of
* the GNU General Public License Version 2. See the LICENSE file
* at the top of the source tree.
*/
/*! \file
*
* \brief AudioFork() - Offload Asterisk audio processing to a Websocket server.
* \ingroup applications
*
* \author Nadir Hamid <[email protected]>
*
* \note Based on app_mixmonitor.c provided by
* asterisk
*/
/*** MODULEINFO
<use type="module">func_periodic_hook</use>
<support_level>core</support_level>
***/
#ifndef AST_MODULE
#define AST_MODULE "Audiofork"
#endif
#include "asterisk.h"
#include "asterisk/paths.h" /* use ast_config_AST_MONITOR_DIR */
#include "asterisk/stringfields.h"
#include "asterisk/file.h"
#include "asterisk/audiohook.h"
#include "asterisk/pbx.h"
#include "asterisk/module.h"
#include "asterisk/cli.h"
#include "asterisk/app.h"
#include "asterisk/channel.h"
#include "asterisk/autochan.h"
#include "asterisk/manager.h"
#include "asterisk/callerid.h"
#include "asterisk/mod_format.h"
#include "asterisk/linkedlists.h"
#include "asterisk/test.h"
#include "asterisk/format_cache.h"
#include "asterisk/beep.h"
#include "asterisk/module.h"
#include "asterisk/astobj2.h"
#include "asterisk/pbx.h"
#include "asterisk/http_websocket.h"
#include "asterisk/tcptls.h"
/*** DOCUMENTATION
<application name="AudioFork" language="en_US">
<synopsis>
Forks a raw audio stream to a websocket server.
</synopsis>
<syntax>
<parameter name="wsserver" required="true" argsep=".">
<argument name="wsserver" required="true">
<para>the URL to the websocket server you want to send the audio to. </para>
</argument>
<argument name="extension" required="true" />
</parameter>
<parameter name="options">
<optionlist>
<option name="b">
<para>Only save audio to the file while the channel is bridged.</para>
<note><para>If you utilize this option inside a Local channel, you must make sure the Local
channel is not optimized away. To do this, be sure to call your Local channel with the
<literal>/n</literal> option. For example: Dial(Local/start@mycontext/n)</para></note>
</option>
<option name="B">
<para>Play a periodic beep while this call is being recorded.</para>
<argument name="interval"><para>Interval, in seconds. Default is 15.</para></argument>
</option>
<option name="v">
<para>Adjust the <emphasis>heard</emphasis> volume by a factor of <replaceable>x</replaceable>
(range <literal>-4</literal> to <literal>4</literal>)</para>
<argument name="x" required="true" />
</option>
<option name="V">
<para>Adjust the <emphasis>spoken</emphasis> volume by a factor
of <replaceable>x</replaceable> (range <literal>-4</literal> to <literal>4</literal>)</para>
<argument name="x" required="true" />
</option>
<option name="W">
<para>Adjust both, <emphasis>heard and spoken</emphasis> volumes by a factor
of <replaceable>x</replaceable> (range <literal>-4</literal> to <literal>4</literal>)</para>
<argument name="x" required="true" />
</option>
<option name="r">
<argument name="file" required="true" />
<para>Use the specified file to record the <emphasis>receive</emphasis> audio feed.
Like with the basic filename argument, if an absolute path isn't given, it will create
the file in the configured monitoring directory.</para>
</option>
<option name="t">
<argument name="file" required="true" />
<para>Use the specified file to record the <emphasis>transmit</emphasis> audio feed.
Like with the basic filename argument, if an absolute path isn't given, it will create
the file in the configured monitoring directory.</para>
</option>
<option name="S">
<para>When combined with the <replaceable>r</replaceable> or <replaceable>t</replaceable>
option, inserts silence when necessary to maintain synchronization between the receive
and transmit audio streams.</para>
</option>
<option name="i">
<argument name="chanvar" required="true" />
<para>Stores the AudioFork's ID on this channel variable.</para>
</option>
<option name="p">
<para>Play a beep on the channel that starts the recording.</para>
</option>
<option name="P">
<para>Play a beep on the channel that stops the recording.</para>
</option>
<option name="D">
<para>Direction of audiohook to process - supports in, out, and both</para>
</option>
<option name="T">
<para>comma separated TLS config for secure websocket connections</para>
</option>
<option name="R">
<para>Timeout for reconnections</para>
</option>
<option name="r">
<para>Number of times to attempt reconnect before closing connections</para>
</option>
</optionlist>
</parameter>
<parameter name="command">
<para>This is executed when the audio fork's hook finishes</para>
<para>Any strings matching <literal>^{X}</literal> will be unescaped to <variable>X</variable>.</para>
<para>All variables will be evaluated at the time AudioFork is called.</para>
<warning><para>Do not use untrusted strings such as <variable>CALLERID(num)</variable>
or <variable>CALLERID(name)</variable> as part of the command parameters. You
risk a command injection attack executing arbitrary commands if the untrusted
strings aren't filtered to remove dangerous characters. See function
<variable>FILTER()</variable>.</para></warning>
</parameter>
</syntax>
<description>
<para>Forks raw audio to a remote websocket.</para>
<para>This application does not automatically answer and should be preceeded by
an application such as Answer or Progress().</para>
<note><para>AudioFork runs as an audiohook.</para></note>
<variablelist>
<variable name="AUDIOFORK_WSSERVER">
<para>The URL of the websocket server.</para>
</variable>
</variablelist>
<warning><para>Do not use untrusted strings such as <variable>CALLERID(num)</variable>
or <variable>CALLERID(name)</variable> as part of ANY of the application's
parameters. You risk a command injection attack executing arbitrary commands
if the untrusted strings aren't filtered to remove dangerous characters. See
function <variable>FILTER()</variable>.</para></warning>
</description>
<see-also>
<ref type="application">AudioFork</ref>
<ref type="application">StopAudioFork</ref>
<ref type="application">PauseMonitor</ref>
<ref type="application">UnpauseMonitor</ref>
<ref type="function">AUDIOHOOK_INHERIT</ref>
</see-also>
</application>
<application name="StopAudioFork" language="en_US">
<synopsis>
Cancels an ongoing audio fork and closes the websocket connection.
</synopsis>
<syntax>
<parameter name="AudioForkID" required="false">
<para>If a valid ID is provided, then this command will stop only that specific
AudioFork.</para>
</parameter>
</syntax>
<description>
<para>Stop an ongoing AudioFork created previously by <literal>AudioFork()</literal>
on the current channel.</para>
</description>
<see-also>
<ref type="application">AudioFork</ref>
</see-also>
</application>
<manager name="AudioForkMute" language="en_US">
<synopsis>
Mute / unMute a AudioFork session.
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
<parameter name="Channel" required="true">
<para>Used to specify the channel to mute.</para>
</parameter>
<parameter name="Direction">
<para>Which part of the audio fork to mute: read, write or both (from channel, to channel or both channels).</para>
</parameter>
<parameter name="State">
<para>Turn mute on or off : 1 to turn on, 0 to turn off.</para>
</parameter>
</syntax>
<description>
<para>This action may be used to mute a AudioFork session.</para>
</description>
</manager>
<manager name="AudioFork" language="en_US">
<synopsis>
Forks a raw audio stream to a websocket server.
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
<parameter name="Channel" required="true">
<para>Used to specify the channel to record.</para>
</parameter>
<parameter name="WsServer">
<para>The websocket server URL to fork audio to.</para>
</parameter>
<parameter name="options">
<para>Options that apply to the AudioFork in the same way as they
would apply if invoked from the AudioFork application. For a list of
available options, see the documentation for the audiofork application. </para>
</parameter>
<parameter name="Command">
<para>Will be executed when the audio fork has completed.
Any strings matching <literal>^{X}</literal> will be unescaped to <variable>X</variable>.
All variables will be evaluated at the time AudioFork is called.</para>
<warning><para>Do not use untrusted strings such as <variable>CALLERID(num)</variable>
or <variable>CALLERID(name)</variable> as part of the command parameters. You
risk a command injection attack executing arbitrary commands if the untrusted
strings aren't filtered to remove dangerous characters. See function
<variable>FILTER()</variable>.</para></warning>
</parameter>
</syntax>
<description>
<para>This action will fork audio from an ongoing call to the designated websocket serrver.</para>
<variablelist>
<variable name="AUDIOFORK_WSSERVER">
<para>The websocket server URL.</para>
</variable>
</variablelist>
</description>
</manager>
<manager name="StopAudioFork" language="en_US">
<synopsis>
Stops an ongoing AudioFork() session
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
<parameter name="Channel" required="true">
<para>The name of the channel monitored.</para>
</parameter>
<parameter name="AudioForkID" required="false">
<para>If a valid ID is provided, then this command will stop only that specific
AudioFork.</para>
</parameter>
</syntax>
<description>
<para>This command stops the audio fork that was created by the <literal>AudioFork</literal>
action.</para>
</description>
</manager>
<function name="AUDIOFORK" language="en_US">
<synopsis>
Retrieve data pertaining to specific instances of AudioFork on a channel.
</synopsis>
<syntax>
<parameter name="id" required="true">
<para>The unique ID of the AudioFork instance. The unique ID can be retrieved through the channel
variable used as an argument to the <replaceable>i</replaceable> option to AudioFork.</para>
</parameter>
<parameter name="key" required="true">
<para>The piece of data to retrieve from the AudioFork.</para>
<enumlist>
<enum name="filename" />
</enumlist>
</parameter>
</syntax>
</function>
***/
#define SAMPLES_PER_FRAME 160
#define get_volfactor(x) x ? ((x > 0) ? (1 << x) : ((1 << abs(x)) * -1)) : 0
static const char *const app = "AudioFork";
static const char *const stop_app = "StopAudioFork";
static const char *const audiofork_spy_type = "AudioFork";
struct audiofork {
struct ast_audiohook audiohook;
struct ast_websocket *websocket;
char *wsserver;
struct ast_tls_config *tls_cfg;
char *tcert;
enum ast_audiohook_direction direction;
const char *direction_string;
int reconnection_attempts;
int reconnection_timeout;
char *post_process;
char *name;
ast_callid callid;
unsigned int flags;
struct ast_autochan *autochan;
struct audiofork_ds *audiofork_ds;
/* the below string fields describe data used for creating voicemails from the recording */
AST_DECLARE_STRING_FIELDS(
AST_STRING_FIELD(call_context);
AST_STRING_FIELD(call_macrocontext);
AST_STRING_FIELD(call_extension);
AST_STRING_FIELD(call_callerchan);
AST_STRING_FIELD(call_callerid);
);
int call_priority;
int has_tls;
};
enum audiofork_flags {
MUXFLAG_APPEND = (1 << 1),
MUXFLAG_BRIDGED = (1 << 2),
MUXFLAG_VOLUME = (1 << 3),
MUXFLAG_READVOLUME = (1 << 4),
MUXFLAG_WRITEVOLUME = (1 << 5),
MUXFLAG_COMBINED = (1 << 8),
MUXFLAG_UID = (1 << 9),
MUXFLAG_BEEP = (1 << 11),
MUXFLAG_BEEP_START = (1 << 12),
MUXFLAG_BEEP_STOP = (1 << 13),
MUXFLAG_RWSYNC = (1 << 14),
MUXFLAG_DIRECTION = (1 << 15),
MUXFLAG_TLS = (1 << 16),
MUXFLAG_RECONNECTION_TIMEOUT = (1 << 17),
MUXFLAG_RECONNECTION_ATTEMPTS = (1 << 17),
};
enum audiofork_args {
OPT_ARG_READVOLUME = 0,
OPT_ARG_WRITEVOLUME,
OPT_ARG_VOLUME,
OPT_ARG_UID,
OPT_ARG_BEEP_INTERVAL,
OPT_ARG_RWSYNC,
OPT_ARG_DIRECTION,
OPT_ARG_TLS,
OPT_ARG_RECONNECTION_TIMEOUT,
OPT_ARG_RECONNECTION_ATTEMPTS,
OPT_ARG_ARRAY_SIZE, /* Always last element of the enum */
};
AST_APP_OPTIONS(audiofork_opts, {
AST_APP_OPTION('a', MUXFLAG_APPEND),
AST_APP_OPTION('b', MUXFLAG_BRIDGED),
AST_APP_OPTION_ARG('B', MUXFLAG_BEEP, OPT_ARG_BEEP_INTERVAL),
AST_APP_OPTION('p', MUXFLAG_BEEP_START),
AST_APP_OPTION('P', MUXFLAG_BEEP_STOP),
AST_APP_OPTION_ARG('v', MUXFLAG_READVOLUME, OPT_ARG_READVOLUME),
AST_APP_OPTION_ARG('V', MUXFLAG_WRITEVOLUME, OPT_ARG_WRITEVOLUME),
AST_APP_OPTION_ARG('W', MUXFLAG_VOLUME, OPT_ARG_VOLUME),
AST_APP_OPTION_ARG('i', MUXFLAG_UID, OPT_ARG_UID),
AST_APP_OPTION_ARG('S', MUXFLAG_RWSYNC, OPT_ARG_RWSYNC),
AST_APP_OPTION_ARG('D', MUXFLAG_DIRECTION, OPT_ARG_DIRECTION),
AST_APP_OPTION_ARG('T', MUXFLAG_TLS, OPT_ARG_TLS),
AST_APP_OPTION_ARG('R', MUXFLAG_RECONNECTION_TIMEOUT, OPT_ARG_RECONNECTION_TIMEOUT),
AST_APP_OPTION_ARG('r', MUXFLAG_RECONNECTION_ATTEMPTS, OPT_ARG_RECONNECTION_ATTEMPTS),
});
struct audiofork_ds {
unsigned int destruction_ok;
ast_cond_t destruction_condition;
ast_mutex_t lock;
/**
* the audio hook we will use for sending raw audio
*/
struct ast_audiohook *audiohook;
unsigned int samp_rate;
char *wsserver;
char *beep_id;
struct ast_tls_config *tls_cfg;
};
static void audiofork_ds_destroy(void *data)
{
struct audiofork_ds *audiofork_ds = data;
ast_mutex_lock(&audiofork_ds->lock);
audiofork_ds->audiohook = NULL;
audiofork_ds->destruction_ok = 1;
ast_free(audiofork_ds->wsserver);
ast_free(audiofork_ds->beep_id);
ast_cond_signal(&audiofork_ds->destruction_condition);
ast_mutex_unlock(&audiofork_ds->lock);
}
static const struct ast_datastore_info audiofork_ds_info = {
.type = "audiofork",
.destroy = audiofork_ds_destroy,
};
static void destroy_monitor_audiohook(struct audiofork *audiofork)
{
if (audiofork->audiofork_ds) {
ast_mutex_lock(&audiofork->audiofork_ds->lock);
audiofork->audiofork_ds->audiohook = NULL;
ast_mutex_unlock(&audiofork->audiofork_ds->lock);
}
/* kill the audiohook. */
ast_audiohook_lock(&audiofork->audiohook);
ast_audiohook_detach(&audiofork->audiohook);
ast_audiohook_unlock(&audiofork->audiohook);
ast_audiohook_destroy(&audiofork->audiohook);
}
static int start_audiofork(struct ast_channel *chan, struct ast_audiohook *audiohook)
{
if (!chan) {
return -1;
}
return ast_audiohook_attach(chan, audiohook);
}
static int audiofork_ws_close(struct audiofork *audiofork)
{
int ret;
ast_verb(2, "[AudioFork] Closing websocket connection\n");
if (audiofork->websocket) {
ast_verb(2, "[AudioFork] Calling ast_websocket_close\n");
ret = ast_websocket_close(audiofork->websocket, 1011);
return ret;
}
ast_verb(2, "[AudioFork] No reference to websocket, can't close connection\n");
return -1;
}
/*
1 = success
0 = fail
*/
static enum ast_websocket_result audiofork_ws_connect(struct audiofork *audiofork)
{
enum ast_websocket_result result;
if (audiofork->websocket) {
ast_verb(2, "<%s> [AudioFork] (%s) Reconnecting to websocket server at: %s\n",
ast_channel_name(audiofork->autochan->chan),
audiofork->direction_string,
audiofork->audiofork_ds->wsserver);
// close the websocket connection before reconnecting
audiofork_ws_close(audiofork);
ao2_cleanup(audiofork->websocket);
}
else {
ast_verb(2, "<%s> [AudioFork] (%s) Connecting to websocket server at: %s\n",
ast_channel_name(audiofork->autochan->chan),
audiofork->direction_string,
audiofork->audiofork_ds->wsserver);
}
// Check if we're running with TLS
if (audiofork->has_tls == 1) {
ast_verb(2, "<%s> [AudioFork] (%s) Creating to WebSocket server with TLS mode enabled\n", ast_channel_name(audiofork->autochan->chan), audiofork->direction_string);
audiofork->websocket = ast_websocket_client_create(audiofork->audiofork_ds->wsserver, "echo", audiofork->tls_cfg, &result);
} else {
ast_verb(2, "<%s> [AudioFork] (%s) Creating to WebSocket server without TLS\n", ast_channel_name(audiofork->autochan->chan), audiofork->direction_string);
audiofork->websocket = ast_websocket_client_create(audiofork->audiofork_ds->wsserver, "echo", NULL, &result);
}
return result;
}
/*
reconn_status
0 = OK
1 = FAILED
*/
static int audiofork_start_reconnecting(struct audiofork *audiofork)
{
int counter= 0;
int status = 0;
int timeout = audiofork->reconnection_timeout;
int attempts = audiofork->reconnection_attempts;
int last_attempt = 0;
int now;
int delta;
int result;
while (counter < attempts) {
now = (int)time(NULL);
delta = now - last_attempt;
// small check to see if we should keep waiting on the reconnection. This uses the
// reconnection_timeout variable configured in the dialplan
if (last_attempt != 0 && delta <= timeout) {
// keep waiting
continue;
}
// try to reconnect
result = audiofork_ws_connect(audiofork);
if (result == WS_OK) {
status = 0;
last_attempt = 0;
break;
}
// reconnection failed...
// update our counter with the last reconnection attempt
last_attempt=(int)time(NULL);
ast_log(LOG_ERROR, "<%s> [AudioFork] (%s) Reconnection failed... trying again in %d seconds. %d attempts remaining reconn_now %d reconn_last_attempt %d\n", ast_channel_name(audiofork->autochan->chan), audiofork->direction_string, timeout, (attempts-counter), now, last_attempt);
counter ++;
status = 1;
}
return status;
}
static void audiofork_free(struct audiofork *audiofork)
{
if (audiofork) {
if (audiofork->audiofork_ds) {
ast_mutex_destroy(&audiofork->audiofork_ds->lock);
ast_cond_destroy(&audiofork->audiofork_ds->destruction_condition);
ast_free(audiofork->audiofork_ds);
}
ast_free(audiofork->name);
ast_free(audiofork->post_process);
ast_free(audiofork->wsserver);
audiofork_ws_close(audiofork);
/* clean stringfields */
ast_string_field_free_memory(audiofork);
ast_free(audiofork);
}
}
static void *audiofork_thread(void *obj)
{
struct audiofork *audiofork = obj;
struct ast_format *format_slin;
char *channel_name_cleanup;
enum ast_websocket_result result;
int frames_sent = 0;
int reconn_status;
/* Keep callid association before any log messages */
if (audiofork->callid) {
ast_verb(2, "<%s> [AudioFork] (%s) Keeping Call-ID Association\n", ast_channel_name(audiofork->autochan->chan), audiofork->direction_string);
ast_callid_threadassoc_add(audiofork->callid);
}
result = audiofork_ws_connect(audiofork);
if (result != WS_OK) {
ast_log(LOG_ERROR, "<%s> Could not connect to websocket server: %s\n", ast_channel_name(audiofork->autochan->chan), audiofork->audiofork_ds->wsserver);
ast_test_suite_event_notify("AUDIOFORK_END", "Ws server: %s\r\n", audiofork->wsserver);
/* kill the audiohook */
destroy_monitor_audiohook(audiofork);
ast_autochan_destroy(audiofork->autochan);
/* We specifically don't do audiofork_free(audiofork) here because the automatic datastore cleanup will get it */
ast_module_unref(ast_module_info->self);
return 0;
}
ast_verb(2, "<%s> [AudioFork] (%s) Begin AudioFork Recording %s\n", ast_channel_name(audiofork->autochan->chan), audiofork->direction_string, audiofork->name);
//fs = &audiofork->audiofork_ds->fs;
ast_mutex_lock(&audiofork->audiofork_ds->lock);
format_slin = ast_format_cache_get_slin_by_rate(audiofork->audiofork_ds->samp_rate);
ast_mutex_unlock(&audiofork->audiofork_ds->lock);
/* The audiohook must enter and exit the loop locked */
ast_audiohook_lock(&audiofork->audiohook);
while (audiofork->audiohook.status == AST_AUDIOHOOK_STATUS_RUNNING) {
// ast_verb(2, "<%s> [AudioFork] (%s) Reading Audio Hook frame...\n", ast_channel_name(audiofork->autochan->chan), audiofork->direction_string);
struct ast_frame *fr = ast_audiohook_read_frame(&audiofork->audiohook, SAMPLES_PER_FRAME, audiofork->direction, format_slin);
if (!fr) {
ast_audiohook_trigger_wait(&audiofork->audiohook);
if (audiofork->audiohook.status != AST_AUDIOHOOK_STATUS_RUNNING) {
ast_verb(2, "<%s> [AudioFork] (%s) AST_AUDIOHOOK_STATUS_RUNNING = 0\n", ast_channel_name(audiofork->autochan->chan), audiofork->direction_string);
break;
}
continue;
}
/* audiohook lock is not required for the next block.
* Unlock it, but remember to lock it before looping or exiting */
ast_audiohook_unlock(&audiofork->audiohook);
struct ast_frame *cur;
//ast_mutex_lock(&audiofork->audiofork_ds->lock);
for (cur = fr; cur; cur = AST_LIST_NEXT(cur, frame_list)) {
// ast_verb(2, "<%s> sending audio frame to websocket...\n", ast_channel_name(audiofork->autochan->chan));
// ast_mutex_lock(&audiofork->audiofork_ds->lock);
if (ast_websocket_write(audiofork->websocket, AST_WEBSOCKET_OPCODE_BINARY, cur->data.ptr, cur->datalen)) {
ast_log(LOG_ERROR, "<%s> [AudioFork] (%s) Could not write to websocket. Reconnecting...\n", ast_channel_name(audiofork->autochan->chan), audiofork->direction_string);
reconn_status = audiofork_start_reconnecting(audiofork);
if (reconn_status == 1) {
audiofork->websocket = NULL;
audiofork->audiohook.status = AST_AUDIOHOOK_STATUS_SHUTDOWN;
break;
}
/* re-send the last frame */
if (ast_websocket_write(audiofork->websocket, AST_WEBSOCKET_OPCODE_BINARY, cur->data.ptr, cur->datalen)) {
ast_log(LOG_ERROR, "<%s> [AudioFork] (%s) Could not re-write to websocket. Complete Failure.\n", ast_channel_name(audiofork->autochan->chan), audiofork->direction_string);
audiofork->audiohook.status = AST_AUDIOHOOK_STATUS_SHUTDOWN;
break;
}
}
frames_sent++;
}
//ast_mutex_unlock(&audiofork->audiofork_ds->lock);
//
/* All done! free it. */
if (fr) {
ast_frame_free(fr, 0);
}
fr = NULL;
ast_audiohook_lock(&audiofork->audiohook);
}
ast_audiohook_unlock(&audiofork->audiohook);
if (ast_test_flag(audiofork, MUXFLAG_BEEP_STOP)) {
ast_autochan_channel_lock(audiofork->autochan);
ast_stream_and_wait(audiofork->autochan->chan, "beep", "");
ast_autochan_channel_unlock(audiofork->autochan);
}
channel_name_cleanup = ast_strdupa(ast_channel_name(audiofork->autochan->chan));
ast_autochan_destroy(audiofork->autochan);
/* Datastore cleanup. close the filestream and wait for ds destruction */
ast_mutex_lock(&audiofork->audiofork_ds->lock);
if (!audiofork->audiofork_ds->destruction_ok) {
ast_cond_wait(&audiofork->audiofork_ds->destruction_condition, &audiofork->audiofork_ds->lock);
}
ast_mutex_unlock(&audiofork->audiofork_ds->lock);
/* kill the audiohook */
destroy_monitor_audiohook(audiofork);
ast_verb(2, "<%s> [AudioFork] (%s) Finished processing audiohook. Frames sent = %d\n", channel_name_cleanup, audiofork->direction_string, frames_sent);
ast_verb(2, "<%s> [AudioFork] (%s) Post Process\n", channel_name_cleanup, audiofork->direction_string);
if (audiofork->post_process) {
ast_verb(2, "<%s> [AudioFork] (%s) Executing [%s]\n", channel_name_cleanup, audiofork->direction_string, audiofork->post_process);
ast_safe_system(audiofork->post_process);
}
// audiofork->name
ast_verb(2, "<%s> [AudioFork] (%s) End AudioFork Recording to: %s\n", channel_name_cleanup, audiofork->direction_string, audiofork->wsserver);
ast_test_suite_event_notify("AUDIOFORK_END", "Ws server: %s\r\n", audiofork->wsserver);
/* free any audiofork memory */
audiofork_free(audiofork);
ast_module_unref(ast_module_info->self);
return NULL;
}
static int setup_audiofork_ds(struct audiofork *audiofork, struct ast_channel *chan, char **datastore_id, const char *beep_id)
{
struct ast_datastore *datastore = NULL;
struct audiofork_ds *audiofork_ds;
if (!(audiofork_ds = ast_calloc(1, sizeof(*audiofork_ds)))) {
return -1;
}
if (ast_asprintf(datastore_id, "%p", audiofork_ds) == -1) {
ast_log(LOG_ERROR, "Failed to allocate memory for AudioFork ID.\n");
ast_free(audiofork_ds);
return -1;
}
ast_mutex_init(&audiofork_ds->lock);
ast_cond_init(&audiofork_ds->destruction_condition, NULL);
if (!(datastore = ast_datastore_alloc(&audiofork_ds_info, *datastore_id))) {
ast_mutex_destroy(&audiofork_ds->lock);
ast_cond_destroy(&audiofork_ds->destruction_condition);
ast_free(audiofork_ds);
return -1;
}
if (ast_test_flag(audiofork, MUXFLAG_BEEP_START)) {
ast_autochan_channel_lock(audiofork->autochan);
ast_stream_and_wait(audiofork->autochan->chan, "beep", "");
ast_autochan_channel_unlock(audiofork->autochan);
}
audiofork_ds->samp_rate = 8000;
audiofork_ds->audiohook = &audiofork->audiohook;
audiofork_ds->wsserver = ast_strdup(audiofork->wsserver);
if (!ast_strlen_zero(beep_id)) {
audiofork_ds->beep_id = ast_strdup(beep_id);
}
datastore->data = audiofork_ds;
ast_channel_lock(chan);
ast_channel_datastore_add(chan, datastore);
ast_channel_unlock(chan);
audiofork->audiofork_ds = audiofork_ds;
return 0;
}
static int launch_audiofork_thread(
struct ast_channel *chan,
const char *wsserver, unsigned int flags,
enum ast_audiohook_direction direction,
char* tcert,
int reconn_timeout,
int reconn_attempts,
int readvol, int writevol,
const char *post_process,
const char *uid_channel_var,
const char *beep_id
)
{
pthread_t thread;
struct audiofork *audiofork;
char postprocess2[1024] = "";
char *datastore_id = NULL;
postprocess2[0] = 0;
/* If a post process system command is given attach it to the structure */
if (!ast_strlen_zero(post_process)) {
char *p1, *p2;
p1 = ast_strdupa(post_process);
for (p2 = p1; *p2; p2++) {
if (*p2 == '^' && *(p2 + 1) == '{') {
*p2 = '$';
}
}
ast_channel_lock(chan);
pbx_substitute_variables_helper(chan, p1, postprocess2, sizeof(postprocess2) - 1);
ast_channel_unlock(chan);
}
/* Pre-allocate audiofork structure and spy */
if (!(audiofork = ast_calloc(1, sizeof(*audiofork)))) {
return -1;
}
/* Now that the struct has been calloced, go ahead and initialize the string fields. */
if (ast_string_field_init(audiofork, 512)) {
audiofork_free(audiofork);
return -1;
}
/* Setup the actual spy before creating our thread */
if (ast_audiohook_init(&audiofork->audiohook, AST_AUDIOHOOK_TYPE_SPY, audiofork_spy_type, 0)) {
audiofork_free(audiofork);
return -1;
}
/* Copy over flags and channel name */
audiofork->flags = flags;
if (!(audiofork->autochan = ast_autochan_setup(chan))) {
audiofork_free(audiofork);
return -1;
}
/* Direction */
audiofork->direction = direction;
if (direction == AST_AUDIOHOOK_DIRECTION_READ) {
audiofork->direction_string = "in";
}
else if (direction == AST_AUDIOHOOK_DIRECTION_WRITE) {
audiofork->direction_string = "out";
}
else {
audiofork->direction_string = "both";
}
ast_verb(2, "<%s> [AudioFork] (%s) Setting Direction\n", ast_channel_name(chan), audiofork->direction_string);
// TODO: make this configurable
audiofork->reconnection_attempts = reconn_attempts;
// 5 seconds
audiofork->reconnection_timeout = reconn_timeout;
ast_verb(2, "<%s> [AudioFork] Setting reconnection attempts to %d\n", ast_channel_name(chan), audiofork->reconnection_attempts);
ast_verb(2, "<%s> [AudioFork] Setting reconnection timeout to %d\n", ast_channel_name(chan), audiofork->reconnection_timeout);
/* Server */
if (!ast_strlen_zero(wsserver)) {
ast_verb(2, "<%s> [AudioFork] (%s) Setting wsserver: %s\n", ast_channel_name(chan), audiofork->direction_string, wsserver);
audiofork->wsserver = ast_strdup(wsserver);
}
/* TLS */
audiofork->has_tls = 0;
if (!ast_strlen_zero(tcert)) {
ast_verb(2, "<%s> [AudioFork] (%s) Setting TLS Cert: %s\n", ast_channel_name(chan), audiofork->direction_string, tcert);
struct ast_tls_config *ast_tls_config;
audiofork->tls_cfg = ast_calloc(1, sizeof(*ast_tls_config));
audiofork->has_tls = 1;
ast_set_flag(&audiofork->tls_cfg->flags, AST_SSL_DONT_VERIFY_SERVER);
}
if (setup_audiofork_ds(audiofork, chan, &datastore_id, beep_id)) {
ast_autochan_destroy(audiofork->autochan);
audiofork_free(audiofork);
ast_free(datastore_id);
return -1;
}
ast_verb(2, "<%s> [AudioFork] (%s) Completed Setup\n", ast_channel_name(audiofork->autochan->chan), audiofork->direction_string);
if (!ast_strlen_zero(uid_channel_var)) {
if (datastore_id) {
pbx_builtin_setvar_helper(chan, uid_channel_var, datastore_id);
}
}
ast_free(datastore_id);
audiofork->name = ast_strdup(ast_channel_name(chan));
if (!ast_strlen_zero(postprocess2)) {
audiofork->post_process = ast_strdup(postprocess2);
}
ast_set_flag(&audiofork->audiohook, AST_AUDIOHOOK_TRIGGER_SYNC);
if ((ast_test_flag(audiofork, MUXFLAG_RWSYNC))) {
ast_set_flag(&audiofork->audiohook, AST_AUDIOHOOK_SUBSTITUTE_SILENCE);
}
if (readvol)
audiofork->audiohook.options.read_volume = readvol;
if (writevol)
audiofork->audiohook.options.write_volume = writevol;
if (start_audiofork(chan, &audiofork->audiohook)) {
ast_log(LOG_WARNING, "<%s> (%s) [AudioFork] Unable to add spy type '%s'\n", audiofork->direction_string, ast_channel_name(chan), audiofork_spy_type);
ast_audiohook_destroy(&audiofork->audiohook);
audiofork_free(audiofork);
return -1;
}
ast_verb(2, "<%s> [AudioFork] (%s) Added AudioHook Spy\n", ast_channel_name(chan), audiofork->direction_string);
/* reference be released at audiofork destruction */
audiofork->callid = ast_read_threadstorage_callid();
return ast_pthread_create_detached_background(&thread, NULL, audiofork_thread, audiofork);
}
static int audiofork_exec(struct ast_channel *chan, const char *data)
{
int x, readvol = 0, writevol = 0;
char *uid_channel_var = NULL;
char beep_id[64] = "";
unsigned int direction = 2;
struct ast_flags flags = { 0 };
char *parse;
char *tcert = NULL;
int reconn_timeout = 5;
int reconn_attempts = 5;
AST_DECLARE_APP_ARGS(args,
AST_APP_ARG(wsserver);
AST_APP_ARG(options);
AST_APP_ARG(post_process);
);
ast_log(LOG_NOTICE, "AudioFork created with args %s\n", data);
if (ast_strlen_zero(data)) {
ast_log(LOG_WARNING, "AudioFork requires an argument wsserver\n");
return -1;
}
parse = ast_strdupa(data);
AST_STANDARD_APP_ARGS(args, parse);
if (args.options) {
char *opts[OPT_ARG_ARRAY_SIZE] = { NULL, };
ast_app_parse_options(audiofork_opts, &flags, opts, args.options);
if (ast_test_flag(&flags, MUXFLAG_READVOLUME)) {
if (ast_strlen_zero(opts[OPT_ARG_READVOLUME])) {
ast_log(LOG_WARNING, "No volume level was provided for the heard volume ('v') option.\n");
} else if ((sscanf(opts[OPT_ARG_READVOLUME], "%2d", &x) != 1) || (x < -4) || (x > 4)) {
ast_log(LOG_NOTICE, "Heard volume must be a number between -4 and 4, not '%s'\n", opts[OPT_ARG_READVOLUME]);
} else {
readvol = get_volfactor(x);
}
}
if (ast_test_flag(&flags, MUXFLAG_WRITEVOLUME)) {
if (ast_strlen_zero(opts[OPT_ARG_WRITEVOLUME])) {
ast_log(LOG_WARNING, "No volume level was provided for the spoken volume ('V') option.\n");
} else if ((sscanf(opts[OPT_ARG_WRITEVOLUME], "%2d", &x) != 1) || (x < -4) || (x > 4)) {
ast_log(LOG_NOTICE, "Spoken volume must be a number between -4 and 4, not '%s'\n", opts[OPT_ARG_WRITEVOLUME]);
} else {
writevol = get_volfactor(x);
}
}
if (ast_test_flag(&flags, MUXFLAG_VOLUME)) {
if (ast_strlen_zero(opts[OPT_ARG_VOLUME])) {
ast_log(LOG_WARNING, "No volume level was provided for the combined volume ('W') option.\n");
} else if ((sscanf(opts[OPT_ARG_VOLUME], "%2d", &x) != 1) || (x < -4) || (x > 4)) {
ast_log(LOG_NOTICE, "Combined volume must be a number between -4 and 4, not '%s'\n", opts[OPT_ARG_VOLUME]);
} else {
readvol = writevol = get_volfactor(x);
}
}
if (ast_test_flag(&flags, MUXFLAG_UID)) {
uid_channel_var = opts[OPT_ARG_UID];
}
if (ast_test_flag(&flags, MUXFLAG_BEEP)) {
const char *interval_str = S_OR(opts[OPT_ARG_BEEP_INTERVAL], "15");
unsigned int interval = 15;
if (sscanf(interval_str, "%30u", &interval) != 1) {
ast_log(LOG_WARNING, "Invalid interval '%s' for periodic beep. Using default of %u\n", interval_str, interval);
}
if (ast_beep_start(chan, interval, beep_id, sizeof(beep_id))) {
ast_log(LOG_WARNING, "Unable to enable periodic beep, please ensure func_periodic_hook is loaded.\n");
return -1;
}
}
if (ast_test_flag(&flags, MUXFLAG_DIRECTION)) {
const char *direction_str = opts[OPT_ARG_DIRECTION];
if (!strcmp(direction_str, "in")) {
direction = AST_AUDIOHOOK_DIRECTION_READ;
} else if (!strcmp(direction_str, "out")) {
direction = AST_AUDIOHOOK_DIRECTION_WRITE;
} else if (!strcmp(direction_str, "both")) {
direction = AST_AUDIOHOOK_DIRECTION_BOTH;
} else {
direction = AST_AUDIOHOOK_DIRECTION_BOTH;
ast_log(LOG_WARNING, "Invalid direction '%s' given. Using default of 'both'\n", opts[OPT_ARG_DIRECTION]);
}