-
Notifications
You must be signed in to change notification settings - Fork 146
Expand file tree
/
Copy pathaudio_streamer_glue.cpp
More file actions
928 lines (757 loc) · 33.9 KB
/
audio_streamer_glue.cpp
File metadata and controls
928 lines (757 loc) · 33.9 KB
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
#include <string>
#include <cstring>
#include "mod_audio_stream.h"
#include "WebSocketClient.h"
#include <switch_json.h>
#include <fstream>
#include <switch_buffer.h>
#include <unordered_set>
#include <atomic>
#include <vector>
#include <memory>
#include <mutex>
#include "base64.h"
#define FRAME_SIZE_8000 320 /* 1000x0.02 (20ms)= 160 x(16bit= 2 bytes) 320 frame size*/
class AudioStreamer {
public:
// Factory
static std::shared_ptr<AudioStreamer> create(
const char* uuid, const char* wsUri, responseHandler_t callback, int deflate, int heart_beat,
bool suppressLog, const char* extra_headers, const char* tls_cafile, const char* tls_keyfile,
const char* tls_certfile, bool tls_disable_hostname_validation) {
std::shared_ptr<AudioStreamer> sp(new AudioStreamer(
uuid, wsUri, callback, deflate, heart_beat,
suppressLog, extra_headers, tls_cafile, tls_keyfile,
tls_certfile, tls_disable_hostname_validation
));
sp->bindCallbacks(std::weak_ptr<AudioStreamer>(sp));
sp->client.connect();
return sp;
}
~AudioStreamer()= default;
void disconnect() {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "disconnecting...\n");
client.disconnect();
}
bool isConnected() {
return client.isConnected();
}
void writeBinary(uint8_t* buffer, size_t len) {
if(!this->isConnected()) return;
client.sendBinary(buffer, len);
}
void writeText(const char* text) {
if(!this->isConnected()) return;
client.sendMessage(text, strlen(text));
}
void deleteFiles() {
std::vector<std::string> files;
{
std::lock_guard<std::mutex> lk(m_stateMutex);
if (m_Files.empty())
return;
files.assign(m_Files.begin(), m_Files.end());
m_Files.clear();
m_playFile = 0;
}
for (const auto& fn : files) {
::remove(fn.c_str());
}
}
void markCleanedUp() {
m_cleanedUp.store(true, std::memory_order_release);
client.setMessageCallback({});
client.setOpenCallback({});
client.setErrorCallback({});
client.setCloseCallback({});
}
bool isCleanedUp() const {
return m_cleanedUp.load(std::memory_order_acquire);
}
private:
// Ctor
AudioStreamer(
const char* uuid, const char* wsUri, responseHandler_t callback, int deflate, int heart_beat,
bool suppressLog, const char* extra_headers, const char* tls_cafile, const char* tls_keyfile,
const char* tls_certfile, bool tls_disable_hostname_validation
) : m_sessionId(uuid), m_notify(callback), m_suppress_log(suppressLog),
m_extra_headers(extra_headers), m_playFile(0) {
WebSocketHeaders hdrs;
WebSocketTLSOptions tls;
if (m_extra_headers) {
cJSON *headers_json = cJSON_Parse(m_extra_headers);
if (headers_json) {
cJSON *iterator = headers_json->child;
while (iterator) {
if (iterator->type == cJSON_String && iterator->valuestring != nullptr) {
hdrs.set(iterator->string, iterator->valuestring);
}
iterator = iterator->next;
}
cJSON_Delete(headers_json);
}
}
client.setUrl(wsUri);
// Setup TLS options
// NONE - disables validation
// SYSTEM - uses the system CAs bundle
if (tls_cafile) {
tls.caFile = tls_cafile;
}
if (tls_keyfile) {
tls.keyFile = tls_keyfile;
}
if (tls_certfile) {
tls.certFile = tls_certfile;
}
tls.disableHostnameValidation = tls_disable_hostname_validation;
client.setTLSOptions(tls);
// Optional heart beat, sent every xx seconds when there is not any traffic
// to make sure that load balancers do not kill an idle connection.
if(heart_beat)
client.setPingInterval(heart_beat);
// Per message deflate connection is enabled by default. You can tweak its parameters or disable it
if(deflate)
client.enableCompression(false);
// Set extra headers if any
if(!hdrs.empty())
client.setHeaders(hdrs);
}
struct ProcessResult {
switch_bool_t ok = SWITCH_FALSE;
std::string rewrittenJsonData;
std::vector<std::string> errors;
};
static inline void push_err(ProcessResult& out, const std::string& sid, const std::string& s) {
out.errors.push_back("(" + sid + ") " + s);
}
void bindCallbacks(std::weak_ptr<AudioStreamer> wp) {
client.setMessageCallback([wp](const std::string& message) {
auto self = wp.lock();
if (!self) return;
if (self->isCleanedUp()) return;
self->eventCallback(MESSAGE, message.c_str());
});
client.setOpenCallback([wp]() {
auto self = wp.lock();
if (!self) return;
if (self->isCleanedUp()) return;
cJSON* root = cJSON_CreateObject();
cJSON_AddStringToObject(root, "status", "connected");
char* json_str = cJSON_PrintUnformatted(root);
self->eventCallback(CONNECT_SUCCESS, json_str);
cJSON_Delete(root);
switch_safe_free(json_str);
});
client.setErrorCallback([wp](int code, const std::string& msg) {
auto self = wp.lock();
if (!self) return;
if (self->isCleanedUp()) return;
cJSON* root = cJSON_CreateObject();
cJSON_AddStringToObject(root, "status", "error");
cJSON* message = cJSON_CreateObject();
cJSON_AddNumberToObject(message, "code", code);
cJSON_AddStringToObject(message, "error", msg.c_str());
cJSON_AddItemToObject(root, "message", message);
char* json_str = cJSON_PrintUnformatted(root);
self->eventCallback(CONNECT_ERROR, json_str);
cJSON_Delete(root);
switch_safe_free(json_str);
});
client.setCloseCallback([wp](int code, const std::string& reason) {
auto self = wp.lock();
if (!self) return;
if (self->isCleanedUp()) return;
cJSON* root = cJSON_CreateObject();
cJSON_AddStringToObject(root, "status", "disconnected");
cJSON* message = cJSON_CreateObject();
cJSON_AddNumberToObject(message, "code", code);
cJSON_AddStringToObject(message, "reason", reason.c_str());
cJSON_AddItemToObject(root, "message", message);
char* json_str = cJSON_PrintUnformatted(root);
self->eventCallback(CONNECTION_DROPPED, json_str);
cJSON_Delete(root);
switch_safe_free(json_str);
});
}
switch_media_bug_t *get_media_bug(switch_core_session_t *session) {
switch_channel_t *channel = switch_core_session_get_channel(session);
if(!channel) {
return nullptr;
}
auto *bug = (switch_media_bug_t *) switch_channel_get_private(channel, MY_BUG_NAME);
return bug;
}
inline void media_bug_close(switch_core_session_t *session) {
auto *bug = get_media_bug(session);
if(bug) {
auto* tech_pvt = (private_t*) switch_core_media_bug_get_user_data(bug);
tech_pvt->close_requested = 1;
switch_core_media_bug_close(&bug, SWITCH_FALSE);
}
}
inline void send_initial_metadata(switch_core_session_t *session) {
auto *bug = get_media_bug(session);
if(bug) {
auto* tech_pvt = (private_t*) switch_core_media_bug_get_user_data(bug);
if(tech_pvt && strlen(tech_pvt->initialMetadata) > 0) {
switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG,
"sending initial metadata %s\n", tech_pvt->initialMetadata);
writeText(tech_pvt->initialMetadata);
}
}
}
void eventCallback(notifyEvent_t event, const char* message) {
std::string msg = message ? message : "";
// processing without holding a session
ProcessResult pr;
if (event == MESSAGE) {
pr = processMessage(msg);
if (pr.ok == SWITCH_TRUE) {
msg = pr.rewrittenJsonData; // overwrite only on success
}
}
switch_core_session_t* psession = switch_core_session_locate(m_sessionId.c_str());
if (!psession) {
return;
}
for (const auto& e : pr.errors) {
switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(psession), SWITCH_LOG_ERROR, "%s\n", e.c_str());
}
switch (event) {
case CONNECT_SUCCESS:
send_initial_metadata(psession);
m_notify(psession, EVENT_CONNECT, msg.c_str());
break;
case CONNECTION_DROPPED:
switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(psession), SWITCH_LOG_INFO, "connection closed\n");
m_notify(psession, EVENT_DISCONNECT, msg.c_str());
break;
case CONNECT_ERROR:
switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(psession), SWITCH_LOG_INFO, "connection error\n");
m_notify(psession, EVENT_ERROR, msg.c_str());
media_bug_close(psession);
break;
case MESSAGE:
if (pr.ok == SWITCH_TRUE) {
m_notify(psession, EVENT_PLAY, msg.c_str());
} else {
// fall back to EVENT_JSON
m_notify(psession, EVENT_JSON, msg.c_str());
}
if (!m_suppress_log) {
switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(psession), SWITCH_LOG_DEBUG,
"response: %s\n", msg.c_str());
}
break;
}
switch_core_session_rwunlock(psession);
}
ProcessResult processMessage(const std::string& message) {
ProcessResult out;
// RAII
using jsonPtr = std::unique_ptr<cJSON, decltype(&cJSON_Delete)>;
jsonPtr root(cJSON_Parse(message.c_str()), &cJSON_Delete);
if (!root) return out;
const char* jsonType = cJSON_GetObjectCstr(root.get(), "type");
if (!jsonType || std::strcmp(jsonType, "streamAudio") != 0) {
return out; // not ours
}
cJSON* jsonData = cJSON_GetObjectItem(root.get(), "data");
if (!jsonData) {
push_err(out, m_sessionId, "processMessage - no data in streamAudio");
return out;
}
const char* jsAudioDataType = cJSON_GetObjectCstr(jsonData, "audioDataType");
if (!jsAudioDataType) jsAudioDataType = "";
jsonPtr jsonAudio(cJSON_DetachItemFromObject(jsonData, "audioData"), &cJSON_Delete);
if (!jsonAudio) {
push_err(out, m_sessionId, "processMessage - streamAudio missing 'audioData' field");
return out;
}
if (!cJSON_IsString(jsonAudio.get()) || !jsonAudio->valuestring) {
push_err(out, m_sessionId, "processMessage - 'audioData' is not a string (expected base64 string)");
return out;
}
// sampleRate (only meaningful for raw)
int sampleRate = 0;
if (cJSON* jsonSampleRate = cJSON_GetObjectItem(jsonData, "sampleRate")) {
sampleRate = jsonSampleRate->valueint;
}
// map file type
std::string fileType;
if (std::strcmp(jsAudioDataType, "raw") == 0) {
switch (sampleRate) {
case 8000: fileType = ".r8"; break;
case 16000: fileType = ".r16"; break;
case 24000: fileType = ".r24"; break;
case 32000: fileType = ".r32"; break;
case 48000: fileType = ".r48"; break;
case 64000: fileType = ".r64"; break;
default:
push_err(out, m_sessionId, "processMessage - unsupported sample rate: " + std::to_string(sampleRate));
return out;
}
} else if (std::strcmp(jsAudioDataType, "wav") == 0) fileType = ".wav";
else if (std::strcmp(jsAudioDataType, "mp3") == 0) fileType = ".mp3";
else if (std::strcmp(jsAudioDataType, "ogg") == 0) fileType = ".ogg";
else if (std::strcmp(jsAudioDataType, "pcmu") == 0) fileType = ".pcmu";
else if (std::strcmp(jsAudioDataType, "pcma") == 0) fileType = ".pcma";
else {
push_err(out, m_sessionId, "processMessage - unsupported audio type: " + std::string(jsAudioDataType));
return out;
}
// base64 decode
std::string decoded;
try {
decoded = base64_decode(jsonAudio->valuestring);
} catch (const std::exception& e) {
push_err(out, m_sessionId, "processMessage - base64 decode error: " + std::string(e.what()));
return out;
}
// reserve file index
int idx = 0;
{
std::lock_guard<std::mutex> lk(m_stateMutex);
idx = m_playFile++;
}
char filePath[256];
switch_snprintf(filePath, sizeof(filePath), "%s%s%s_%d.tmp%s",
SWITCH_GLOBAL_dirs.temp_dir, SWITCH_PATH_SEPARATOR,
m_sessionId.c_str(), idx, fileType.c_str());
// write file
{
std::ofstream f(filePath, std::ios::binary);
if (!f.is_open()) {
push_err(out, m_sessionId, std::string("processMessage - failed to open file for write: ") + filePath);
return out;
}
f.write(decoded.data(), static_cast<std::streamsize>(decoded.size()));
if (!f.good()) {
push_err(out, m_sessionId, std::string("processMessage - failed writing file: ") + filePath);
return out;
}
}
// track file for cleanup
{
std::lock_guard<std::mutex> lk(m_stateMutex);
m_Files.insert(filePath);
}
cJSON_AddItemToObject(jsonData, "file", cJSON_CreateString(filePath));
// return rewritten jsonData as string
char* jsonString = cJSON_PrintUnformatted(jsonData);
if (!jsonString) {
push_err(out, m_sessionId, "processMessage - cJSON_PrintUnformatted failed");
return out;
}
out.rewrittenJsonData.assign(jsonString);
std::free(jsonString);
out.ok = SWITCH_TRUE;
return out;
}
private:
std::string m_sessionId;
responseHandler_t m_notify;
WebSocketClient client;
bool m_suppress_log;
const char* m_extra_headers;
int m_playFile;
std::unordered_set<std::string> m_Files;
std::atomic<bool> m_cleanedUp{false};
std::mutex m_stateMutex;
};
namespace {
switch_status_t stream_data_init(private_t *tech_pvt, switch_core_session_t *session, char *wsUri,
uint32_t sampling, int desiredSampling, int channels, char *metadata, responseHandler_t responseHandler,
int deflate, int heart_beat, bool suppressLog, int rtp_packets, const char* extra_headers,
const char *tls_cafile, const char *tls_keyfile, const char *tls_certfile,
bool tls_disable_hostname_validation)
{
int err; //speex
switch_memory_pool_t *pool = switch_core_session_get_pool(session);
memset(tech_pvt, 0, sizeof(private_t));
strncpy(tech_pvt->sessionId, switch_core_session_get_uuid(session), MAX_SESSION_ID);
strncpy(tech_pvt->ws_uri, wsUri, MAX_WS_URI);
tech_pvt->sampling = desiredSampling;
tech_pvt->responseHandler = responseHandler;
tech_pvt->rtp_packets = rtp_packets;
tech_pvt->channels = channels;
tech_pvt->audio_paused = 0;
if (metadata) strncpy(tech_pvt->initialMetadata, metadata, MAX_METADATA_LEN);
//size_t buflen = (FRAME_SIZE_8000 * desiredSampling / 8000 * channels * 1000 / RTP_PERIOD * BUFFERED_SEC);
const size_t buflen = (FRAME_SIZE_8000 * desiredSampling / 8000 * channels * rtp_packets);
auto sp = AudioStreamer::create(tech_pvt->sessionId, wsUri, responseHandler, deflate, heart_beat,
suppressLog, extra_headers, tls_cafile, tls_keyfile,
tls_certfile, tls_disable_hostname_validation);
tech_pvt->pAudioStreamer = new std::shared_ptr<AudioStreamer>(sp);
switch_mutex_init(&tech_pvt->mutex, SWITCH_MUTEX_NESTED, pool);
if (switch_buffer_create(pool, &tech_pvt->sbuffer, buflen) != SWITCH_STATUS_SUCCESS) {
switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_ERROR,
"%s: Error creating switch buffer.\n", tech_pvt->sessionId);
return SWITCH_STATUS_FALSE;
}
if (desiredSampling != sampling) {
switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "(%s) resampling from %u to %u\n", tech_pvt->sessionId, sampling, desiredSampling);
tech_pvt->resampler = speex_resampler_init(channels, sampling, desiredSampling, SWITCH_RESAMPLE_QUALITY, &err);
if (0 != err) {
switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_ERROR, "Error initializing resampler: %s.\n", speex_resampler_strerror(err));
return SWITCH_STATUS_FALSE;
}
}
else {
switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "(%s) no resampling needed for this call\n", tech_pvt->sessionId);
}
switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "(%s) stream_data_init\n", tech_pvt->sessionId);
return SWITCH_STATUS_SUCCESS;
}
void destroy_tech_pvt(private_t* tech_pvt) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "%s destroy_tech_pvt\n", tech_pvt->sessionId);
if (tech_pvt->resampler) {
speex_resampler_destroy(tech_pvt->resampler);
tech_pvt->resampler = nullptr;
}
if (tech_pvt->mutex) {
switch_mutex_destroy(tech_pvt->mutex);
tech_pvt->mutex = nullptr;
}
}
}
extern "C" {
int validate_ws_uri(const char* url, char* wsUri) {
const char* scheme = nullptr;
const char* hostStart = nullptr;
const char* hostEnd = nullptr;
const char* portStart = nullptr;
// Check scheme
if (strncmp(url, "ws://", 5) == 0) {
scheme = "ws";
hostStart = url + 5;
} else if (strncmp(url, "wss://", 6) == 0) {
scheme = "wss";
hostStart = url + 6;
} else {
return 0;
}
// Find host end or port start
hostEnd = hostStart;
while (*hostEnd && *hostEnd != ':' && *hostEnd != '/') {
if (!std::isalnum(*hostEnd) && *hostEnd != '-' && *hostEnd != '.') {
return 0;
}
++hostEnd;
}
// Check if host is empty
if (hostStart == hostEnd) {
return 0;
}
// Check for port
if (*hostEnd == ':') {
portStart = hostEnd + 1;
while (*portStart && *portStart != '/') {
if (!std::isdigit(*portStart)) {
return 0;
}
++portStart;
}
}
// Copy valid URI to wsUri
std::strncpy(wsUri, url, MAX_WS_URI);
return 1;
}
switch_status_t is_valid_utf8(const char *str) {
switch_status_t status = SWITCH_STATUS_FALSE;
while (*str) {
if ((*str & 0x80) == 0x00) {
// 1-byte character
str++;
} else if ((*str & 0xE0) == 0xC0) {
// 2-byte character
if ((str[1] & 0xC0) != 0x80) {
return status;
}
str += 2;
} else if ((*str & 0xF0) == 0xE0) {
// 3-byte character
if ((str[1] & 0xC0) != 0x80 || (str[2] & 0xC0) != 0x80) {
return status;
}
str += 3;
} else if ((*str & 0xF8) == 0xF0) {
// 4-byte character
if ((str[1] & 0xC0) != 0x80 || (str[2] & 0xC0) != 0x80 || (str[3] & 0xC0) != 0x80) {
return status;
}
str += 4;
} else {
// invalid character
return status;
}
}
return SWITCH_STATUS_SUCCESS;
}
switch_status_t stream_session_send_text(switch_core_session_t *session, char* text) {
switch_channel_t *channel = switch_core_session_get_channel(session);
auto *bug = (switch_media_bug_t*) switch_channel_get_private(channel, MY_BUG_NAME);
if (!bug) {
switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_ERROR, "stream_session_send_text failed because no bug\n");
return SWITCH_STATUS_FALSE;
}
auto *tech_pvt = (private_t*) switch_core_media_bug_get_user_data(bug);
if (!tech_pvt) return SWITCH_STATUS_FALSE;
std::shared_ptr<AudioStreamer> streamer;
switch_mutex_lock(tech_pvt->mutex);
if (tech_pvt->pAudioStreamer) {
auto sp_wrap = static_cast<std::shared_ptr<AudioStreamer>*>(tech_pvt->pAudioStreamer);
if (sp_wrap && *sp_wrap) {
streamer = *sp_wrap; // copy shared_ptr
}
}
switch_mutex_unlock(tech_pvt->mutex);
if (streamer) {
streamer->writeText(text);
return SWITCH_STATUS_SUCCESS;
}
return SWITCH_STATUS_FALSE;
}
switch_status_t stream_session_pauseresume(switch_core_session_t *session, int pause) {
switch_channel_t *channel = switch_core_session_get_channel(session);
auto *bug = (switch_media_bug_t*) switch_channel_get_private(channel, MY_BUG_NAME);
if (!bug) {
switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_ERROR, "stream_session_pauseresume failed because no bug\n");
return SWITCH_STATUS_FALSE;
}
auto *tech_pvt = (private_t*) switch_core_media_bug_get_user_data(bug);
if (!tech_pvt) return SWITCH_STATUS_FALSE;
switch_core_media_bug_flush(bug);
tech_pvt->audio_paused = pause;
return SWITCH_STATUS_SUCCESS;
}
switch_status_t stream_session_init(switch_core_session_t *session,
responseHandler_t responseHandler,
uint32_t samples_per_second,
char *wsUri,
int sampling,
int channels,
char* metadata,
void **ppUserData)
{
int deflate, heart_beat;
bool suppressLog = false;
const char* buffer_size;
const char* extra_headers;
int rtp_packets = 1; //20ms burst
const char* tls_cafile = NULL;;
const char* tls_keyfile = NULL;;
const char* tls_certfile = NULL;;
bool tls_disable_hostname_validation = false;
switch_channel_t *channel = switch_core_session_get_channel(session);
if (switch_channel_var_true(channel, "STREAM_MESSAGE_DEFLATE")) {
deflate = 1;
}
if (switch_channel_var_true(channel, "STREAM_SUPPRESS_LOG")) {
suppressLog = true;
}
tls_cafile = switch_channel_get_variable(channel, "STREAM_TLS_CA_FILE");
tls_keyfile = switch_channel_get_variable(channel, "STREAM_TLS_KEY_FILE");
tls_certfile = switch_channel_get_variable(channel, "STREAM_TLS_CERT_FILE");
if (switch_channel_var_true(channel, "STREAM_TLS_DISABLE_HOSTNAME_VALIDATION")) {
tls_disable_hostname_validation = true;
}
const char* heartBeat = switch_channel_get_variable(channel, "STREAM_HEART_BEAT");
if (heartBeat) {
char *endptr;
long value = strtol(heartBeat, &endptr, 10);
if (*endptr == '\0' && value <= INT_MAX && value >= INT_MIN) {
heart_beat = (int) value;
}
}
if ((buffer_size = switch_channel_get_variable(channel, "STREAM_BUFFER_SIZE"))) {
int bSize = atoi(buffer_size);
if(bSize % 20 != 0) {
switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_WARNING, "%s: Buffer size of %s is not a multiple of 20ms. Using default 20ms.\n",
switch_channel_get_name(channel), buffer_size);
} else if(bSize >= 20){
rtp_packets = bSize/20;
}
}
extra_headers = switch_channel_get_variable(channel, "STREAM_EXTRA_HEADERS");
// allocate per-session tech_pvt
auto* tech_pvt = (private_t *) switch_core_session_alloc(session, sizeof(private_t));
if (!tech_pvt) {
switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_ERROR, "error allocating memory!\n");
return SWITCH_STATUS_FALSE;
}
if (SWITCH_STATUS_SUCCESS != stream_data_init(tech_pvt, session, wsUri, samples_per_second, sampling, channels,
metadata, responseHandler, deflate, heart_beat, suppressLog, rtp_packets,
extra_headers, tls_cafile, tls_keyfile, tls_certfile, tls_disable_hostname_validation)) {
destroy_tech_pvt(tech_pvt);
return SWITCH_STATUS_FALSE;
}
*ppUserData = tech_pvt;
return SWITCH_STATUS_SUCCESS;
}
switch_bool_t stream_frame(switch_media_bug_t *bug) {
auto *tech_pvt = (private_t *)switch_core_media_bug_get_user_data(bug);
if (!tech_pvt) return SWITCH_TRUE;
if (tech_pvt->audio_paused || tech_pvt->cleanup_started) return SWITCH_TRUE;
std::shared_ptr<AudioStreamer> streamer;
std::vector<std::vector<uint8_t>> pending_send;
if (switch_mutex_trylock(tech_pvt->mutex) != SWITCH_STATUS_SUCCESS) {
return SWITCH_TRUE;
}
if (!tech_pvt->pAudioStreamer) {
switch_mutex_unlock(tech_pvt->mutex);
return SWITCH_TRUE;
}
auto sp_ptr = static_cast<std::shared_ptr<AudioStreamer>*>(tech_pvt->pAudioStreamer);
if (!sp_ptr || !(*sp_ptr)) {
switch_mutex_unlock(tech_pvt->mutex);
return SWITCH_TRUE;
}
streamer = *sp_ptr;
auto *resampler = tech_pvt->resampler;
const int channels = tech_pvt->channels;
const int rtp_packets = tech_pvt->rtp_packets;
if (nullptr == resampler) {
uint8_t data_buf[SWITCH_RECOMMENDED_BUFFER_SIZE];
switch_frame_t frame = {};
frame.data = data_buf;
frame.buflen = SWITCH_RECOMMENDED_BUFFER_SIZE;
while (switch_core_media_bug_read(bug, &frame, SWITCH_TRUE) == SWITCH_STATUS_SUCCESS) {
if (!frame.datalen) {
continue;
}
if (rtp_packets == 1) {
pending_send.emplace_back((uint8_t*)frame.data, (uint8_t*)frame.data + frame.datalen);
continue;
}
size_t freespace = switch_buffer_freespace(tech_pvt->sbuffer);
if (freespace >= frame.datalen) {
switch_buffer_write(tech_pvt->sbuffer, static_cast<uint8_t *>(frame.data), frame.datalen);
}
if (switch_buffer_freespace(tech_pvt->sbuffer) == 0) {
switch_size_t inuse = switch_buffer_inuse(tech_pvt->sbuffer);
if (inuse > 0) {
std::vector<uint8_t> tmp(inuse);
switch_buffer_read(tech_pvt->sbuffer, tmp.data(), inuse);
switch_buffer_zero(tech_pvt->sbuffer);
pending_send.emplace_back(std::move(tmp));
}
}
}
} else {
uint8_t data[SWITCH_RECOMMENDED_BUFFER_SIZE];
switch_frame_t frame = {};
frame.data = data;
frame.buflen = SWITCH_RECOMMENDED_BUFFER_SIZE;
while (switch_core_media_bug_read(bug, &frame, SWITCH_TRUE) == SWITCH_STATUS_SUCCESS) {
if(!frame.datalen) {
continue;
}
const size_t freespace = switch_buffer_freespace(tech_pvt->sbuffer);
spx_uint32_t in_len = frame.samples;
spx_uint32_t out_len = (freespace / (tech_pvt->channels * sizeof(spx_int16_t)));
if(out_len == 0) {
if(freespace == 0) {
switch_size_t inuse = switch_buffer_inuse(tech_pvt->sbuffer);
if (inuse > 0) {
std::vector<uint8_t> tmp(inuse);
switch_buffer_read(tech_pvt->sbuffer, tmp.data(), inuse);
switch_buffer_zero(tech_pvt->sbuffer);
pending_send.emplace_back(std::move(tmp));
}
}
continue;
}
std::vector<spx_int16_t> out;
out.resize((size_t)out_len * (size_t)channels);
if(channels == 1) {
speex_resampler_process_int(resampler,
0,
(const spx_int16_t *)frame.data,
&in_len,
out.data(),
&out_len);
} else {
speex_resampler_process_interleaved_int(resampler,
(const spx_int16_t *)frame.data,
&in_len,
out.data(),
&out_len);
}
if(out_len > 0) {
const size_t bytes_written = (size_t)out_len * (size_t)channels * sizeof(spx_int16_t);
if (rtp_packets == 1) { //20ms packet
const uint8_t* p = (const uint8_t*)out.data();
pending_send.emplace_back(p, p + bytes_written);
continue;
}
if (bytes_written <= switch_buffer_freespace(tech_pvt->sbuffer)) {
switch_buffer_write(tech_pvt->sbuffer, (const uint8_t *)out.data(), bytes_written);
}
}
if (switch_buffer_freespace(tech_pvt->sbuffer) == 0) {
switch_size_t inuse = switch_buffer_inuse(tech_pvt->sbuffer);
if (inuse > 0) {
std::vector<uint8_t> tmp(inuse);
switch_buffer_read(tech_pvt->sbuffer, tmp.data(), inuse);
switch_buffer_zero(tech_pvt->sbuffer);
pending_send.emplace_back(std::move(tmp));
}
}
}
}
switch_mutex_unlock(tech_pvt->mutex);
if (!streamer || !streamer->isConnected()) return SWITCH_TRUE;
for (auto &chunk : pending_send) {
if (!chunk.empty()) {
streamer->writeBinary(chunk.data(), chunk.size());
}
}
return SWITCH_TRUE;
}
switch_status_t stream_session_cleanup(switch_core_session_t *session, char* text, int channelIsClosing) {
switch_channel_t *channel = switch_core_session_get_channel(session);
auto *bug = (switch_media_bug_t*) switch_channel_get_private(channel, MY_BUG_NAME);
if(bug)
{
auto* tech_pvt = (private_t*) switch_core_media_bug_get_user_data(bug);
char sessionId[MAX_SESSION_ID];
strcpy(sessionId, tech_pvt->sessionId);
std::shared_ptr<AudioStreamer>* sp_wrap = nullptr;
std::shared_ptr<AudioStreamer> streamer;
switch_mutex_lock(tech_pvt->mutex);
if (tech_pvt->cleanup_started) {
switch_mutex_unlock(tech_pvt->mutex);
return SWITCH_STATUS_SUCCESS;
}
tech_pvt->cleanup_started = 1;
switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "(%s) stream_session_cleanup\n", sessionId);
switch_channel_set_private(channel, MY_BUG_NAME, nullptr);
sp_wrap = static_cast<std::shared_ptr<AudioStreamer>*>(tech_pvt->pAudioStreamer);
tech_pvt->pAudioStreamer = nullptr;
if (sp_wrap && *sp_wrap) {
streamer = *sp_wrap;
}
switch_mutex_unlock(tech_pvt->mutex);
if (!channelIsClosing) {
switch_core_media_bug_remove(session, &bug);
}
if (sp_wrap) {
delete sp_wrap;
sp_wrap = nullptr;
}
if(streamer) {
streamer->deleteFiles();
if (text) streamer->writeText(text);
streamer->markCleanedUp();
streamer->disconnect();
}
destroy_tech_pvt(tech_pvt);
switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_INFO, "(%s) stream_session_cleanup: connection closed\n", sessionId);
return SWITCH_STATUS_SUCCESS;
}
switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "stream_session_cleanup: no bug - websocket connection already closed\n");
return SWITCH_STATUS_FALSE;
}
}