Repository navigation
Expand file tree
/
Copy pathaudio_streamer_glue.cpp
More file actions
743 lines (626 loc) · 29.4 KB
/
Copy pathaudio_streamer_glue.cpp
File metadata and controls
743 lines (626 loc) · 29.4 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
#include <string>
#include <cstring>
#include "mod_audio_stream.h"
//#include <ixwebsocket/IXWebSocket.h>
#include "WebSocketClient.h"
#include <switch_json.h>
#include <fstream>
#include <switch_buffer.h>
#include <unordered_map>
#include <unordered_set>
#include "base64.h"
#define FRAME_SIZE_8000 320 /* 1000x0.02 (20ms)= 160 x(16bit= 2 bytes) 320 frame size*/
class AudioStreamer {
public:
AudioStreamer(const char* uuid, const char* wsUri, responseHandler_t callback, int deflate, int heart_beat,
bool suppressLog, const char* extra_headers, bool no_reconnect,
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 eventual TLS options.
// tls_cafile may hold the special values
// NONE, which disables validation and SYSTEM which 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);
// Setup a callback to be fired when a message or an event (open, close, error) is received
client.setMessageCallback([this](const std::string& message) {
eventCallback(MESSAGE, message.c_str());
});
client.setOpenCallback([this]() {
cJSON *root;
root = cJSON_CreateObject();
cJSON_AddStringToObject(root, "status", "connected");
char *json_str = cJSON_PrintUnformatted(root);
eventCallback(CONNECT_SUCCESS, json_str);
cJSON_Delete(root);
switch_safe_free(json_str);
});
client.setErrorCallback([this](int code, const std::string &msg) {
cJSON *root, *message;
root = cJSON_CreateObject();
cJSON_AddStringToObject(root, "status", "error");
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);
eventCallback(CONNECT_ERROR, json_str);
cJSON_Delete(root);
switch_safe_free(json_str);
});
client.setCloseCallback([this](int code, const std::string &reason) {
cJSON *root, *message;
root = cJSON_CreateObject();
cJSON_AddStringToObject(root, "status", "disconnected");
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);
eventCallback(CONNECTION_DROPPED, json_str);
cJSON_Delete(root);
switch_safe_free(json_str);
});
// Now that our callback is setup, we can start our background thread and receive messages
client.connect();
}
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 = true;
// Clear the channel's private data first
switch_channel_t *channel = switch_core_session_get_channel(session);
switch_channel_set_private(channel, MY_BUG_NAME, nullptr);
// Then close the media bug
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) {
switch_core_session_t* psession = switch_core_session_locate(m_sessionId.c_str());
if(psession) {
switch (event) {
case CONNECT_SUCCESS:
send_initial_metadata(psession);
m_notify(psession, EVENT_CONNECT, message);
break;
case CONNECTION_DROPPED:
switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(psession), SWITCH_LOG_INFO, "connection closed\n");
m_notify(psession, EVENT_DISCONNECT, message);
break;
case CONNECT_ERROR:
switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(psession), SWITCH_LOG_INFO, "connection error\n");
m_notify(psession, EVENT_ERROR, message);
media_bug_close(psession);
break;
case MESSAGE:
std::string msg(message);
if(processMessage(psession, msg) != SWITCH_TRUE) {
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);
}
}
switch_bool_t processMessage(switch_core_session_t* session, std::string& message) {
cJSON* json = cJSON_Parse(message.c_str());
switch_bool_t status = SWITCH_FALSE;
if (!json) {
return status;
}
const char* jsType = cJSON_GetObjectCstr(json, "type");
if(jsType && strcmp(jsType, "streamAudio") == 0) {
cJSON* jsonData = cJSON_GetObjectItem(json, "data");
if(jsonData) {
cJSON* jsonFile = nullptr;
cJSON* jsonAudio = cJSON_DetachItemFromObject(jsonData, "audioData");
const char* jsAudioDataType = cJSON_GetObjectCstr(jsonData, "audioDataType");
std::string fileType;
int sampleRate;
if (0 == strcmp(jsAudioDataType, "raw")) {
cJSON* jsonSampleRate = cJSON_GetObjectItem(jsonData, "sampleRate");
sampleRate = jsonSampleRate && jsonSampleRate->valueint ? jsonSampleRate->valueint : 0;
std::unordered_map<int, const char*> sampleRateMap = {
{8000, ".r8"},
{16000, ".r16"},
{24000, ".r24"},
{32000, ".r32"},
{48000, ".r48"},
{64000, ".r64"}
};
auto it = sampleRateMap.find(sampleRate);
fileType = (it != sampleRateMap.end()) ? it->second : "";
} else if (0 == strcmp(jsAudioDataType, "wav")) {
fileType = ".wav";
} else if (0 == strcmp(jsAudioDataType, "mp3")) {
fileType = ".mp3";
} else if (0 == strcmp(jsAudioDataType, "ogg")) {
fileType = ".ogg";
} else {
switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_ERROR, "(%s) processMessage - unsupported audio type: %s\n",
m_sessionId.c_str(), jsAudioDataType);
}
if(jsonAudio && jsonAudio->valuestring != nullptr && !fileType.empty()) {
char filePath[256];
std::string rawAudio;
try {
rawAudio = base64_decode(jsonAudio->valuestring);
} catch (const std::exception& e) {
switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_ERROR, "(%s) processMessage - base64 decode error: %s\n",
m_sessionId.c_str(), e.what());
cJSON_Delete(jsonAudio); cJSON_Delete(json);
return status;
}
switch_snprintf(filePath, 256, "%s%s%s_%d.tmp%s", SWITCH_GLOBAL_dirs.temp_dir,
SWITCH_PATH_SEPARATOR, m_sessionId.c_str(), m_playFile++, fileType.c_str());
std::ofstream fstream(filePath, std::ofstream::binary);
fstream << rawAudio;
fstream.close();
m_Files.insert(filePath);
jsonFile = cJSON_CreateString(filePath);
cJSON_AddItemToObject(jsonData, "file", jsonFile);
}
if(jsonFile) {
char *jsonString = cJSON_PrintUnformatted(jsonData);
m_notify(session, EVENT_PLAY, jsonString);
message.assign(jsonString);
free(jsonString);
status = SWITCH_TRUE;
}
if (jsonAudio)
cJSON_Delete(jsonAudio);
} else {
switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_ERROR, "(%s) processMessage - no data in streamAudio\n", m_sessionId.c_str());
}
}
cJSON_Delete(json);
return status;
}
~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() {
if(m_playFile >0) {
for (const auto &fileName: m_Files) {
remove(fileName.c_str());
}
}
}
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;
};
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,
bool no_reconnect, 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));
snprintf(tech_pvt->sessionId, MAX_SESSION_ID, "%s", switch_core_session_get_uuid(session));
snprintf(tech_pvt->ws_uri, MAX_WS_URI, "%s", wsUri);
tech_pvt->sampling = desiredSampling;
tech_pvt->responseHandler = responseHandler;
tech_pvt->rtp_packets = rtp_packets;
tech_pvt->channels = channels;
tech_pvt->audio_paused = false;
if (metadata) snprintf(tech_pvt->initialMetadata, MAX_METADATA_LEN, "%s", metadata);
//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* as = new AudioStreamer(tech_pvt->sessionId, wsUri, responseHandler, deflate, heart_beat,
suppressLog, extra_headers, no_reconnect,
tls_cafile, tls_keyfile, tls_certfile, tls_disable_hostname_validation);
tech_pvt->pAudioStreamer = static_cast<void *>(as);
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;
}
if (tech_pvt->pAudioStreamer) {
auto* as = (AudioStreamer *) tech_pvt->pAudioStreamer;
delete as;
tech_pvt->pAudioStreamer = nullptr;
}
}
void finish(private_t* tech_pvt) {
std::shared_ptr<AudioStreamer> aStreamer;
aStreamer.reset((AudioStreamer *)tech_pvt->pAudioStreamer);
tech_pvt->pAudioStreamer = nullptr;
std::thread t([aStreamer]{
aStreamer->disconnect();
});
t.detach();
}
}
extern "C" {
int validate_ws_uri(const char* url_in, char* url_out) {
const char* host_start = NULL;
// Validate scheme
if (strncmp(url_in, "ws://", 5) == 0) {
host_start = url_in + 5;
} else if (strncmp(url_in, "wss://", 6) == 0) {
host_start = url_in + 6;
} else {
return 0; // Invalid scheme
}
if (*host_start == '\0') {
return 0; // URI cannot end after the scheme
}
// Locate host and port boundaries
const char* path_start = strchr(host_start, '/');
const char* port_delim = strchr(host_start, ':');
// If a colon exists, it must be for a port, not part of the path
if (port_delim && path_start && port_delim > path_start) {
port_delim = NULL;
}
const char* host_end = port_delim ? port_delim : (path_start ? path_start : (host_start + strlen(host_start)));
// Host must not be empty
if (host_start == host_end) {
return 0;
}
// Validate host characters
for (const char* p = host_start; p < host_end; ++p) {
if (!isalnum((unsigned char)*p) && *p != '-' && *p != '.') {
return 0;
}
}
// Validate port (if it exists)
if (port_delim) {
const char* port_start = port_delim + 1;
const char* port_end = path_start ? path_start : port_start + strlen(port_start);
if (port_start == port_end) {
return 0; // Port must not be empty
}
char* end_ptr;
long port = strtol(port_start, &end_ptr, 10);
if (end_ptr != port_end || port < 0 || port > 65535) {
return 0; // Invalid port number or out of range
}
}
// Copy the URL
snprintf(url_out, MAX_WS_URI, "%s", url_in);
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;
auto *pAudioStreamer = static_cast<AudioStreamer *>(tech_pvt->pAudioStreamer);
if (pAudioStreamer && text) pAudioStreamer->writeText(text);
return SWITCH_STATUS_SUCCESS;
}
switch_status_t stream_session_pauseresume(switch_core_session_t *session, bool 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
bool no_reconnect = false;
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;
}
if (switch_channel_var_true(channel, "STREAM_NO_RECONNECT")) {
no_reconnect = 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, no_reconnect, 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 || tech_pvt->audio_paused) return SWITCH_TRUE;
if (switch_mutex_trylock(tech_pvt->mutex) != SWITCH_STATUS_SUCCESS) {
return SWITCH_TRUE;
}
auto *pAudioStreamer = static_cast<AudioStreamer *>(tech_pvt->pAudioStreamer);
if (!pAudioStreamer || !pAudioStreamer->isConnected()) {
switch_mutex_unlock(tech_pvt->mutex);
return SWITCH_TRUE;
}
auto flush_sbuffer = [&]() {
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);
pAudioStreamer->writeBinary(tmp.data(), inuse);
}
};
uint8_t data_buf[SWITCH_RECOMMENDED_BUFFER_SIZE];
switch_frame_t frame = {0};
frame.data = data_buf;
frame.buflen = SWITCH_RECOMMENDED_BUFFER_SIZE;
while (switch_core_media_bug_read(bug, &frame, SWITCH_TRUE) == SWITCH_STATUS_SUCCESS) {
if (!tech_pvt->resampler) {
if (tech_pvt->rtp_packets == 1) {
pAudioStreamer->writeBinary((uint8_t *)frame.data, frame.datalen);
} else {
size_t write_len = frame.datalen;
const uint8_t *write_data = (const uint8_t *)frame.data;
switch_size_t free_space = switch_buffer_freespace(tech_pvt->sbuffer);
if (write_len > free_space) {
flush_sbuffer();
}
switch_buffer_write(tech_pvt->sbuffer, write_data, write_len);
if (switch_buffer_freespace(tech_pvt->sbuffer) == 0) {
flush_sbuffer();
}
}
continue;
}
size_t available = switch_buffer_freespace(tech_pvt->sbuffer);
spx_uint32_t in_len = frame.samples;
spx_uint32_t out_len = available / (tech_pvt->channels * sizeof(spx_int16_t));
if (out_len == 0) {
flush_sbuffer();
available = switch_buffer_freespace(tech_pvt->sbuffer);
out_len = available / (tech_pvt->channels * sizeof(spx_int16_t));
}
// Use dynamic allocation
std::vector<spx_int16_t> outbuf(out_len * tech_pvt->channels);
if (tech_pvt->channels == 1) {
speex_resampler_process_int(
tech_pvt->resampler,
0,
(const spx_int16_t *)frame.data,
&in_len,
outbuf.data(),
&out_len
);
} else {
speex_resampler_process_interleaved_int(
tech_pvt->resampler,
(const spx_int16_t *)frame.data,
&in_len,
outbuf.data(),
&out_len
);
}
size_t bytes_written = out_len * tech_pvt->channels * sizeof(spx_int16_t);
if (bytes_written > 0) {
switch_buffer_write(
tech_pvt->sbuffer,
reinterpret_cast<const uint8_t *>(outbuf.data()),
bytes_written
);
if (switch_buffer_freespace(tech_pvt->sbuffer) == 0) {
flush_sbuffer();
}
}
}
flush_sbuffer();
switch_mutex_unlock(tech_pvt->mutex);
return SWITCH_TRUE;
}
switch_status_t stream_session_cleanup(switch_core_session_t *session, char* text, bool 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];
snprintf(sessionId, MAX_SESSION_ID, "%s", tech_pvt->sessionId);
switch_mutex_lock(tech_pvt->mutex);
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);
if (!channelIsClosing) {
switch_core_media_bug_remove(session, &bug);
}
auto* audioStreamer = (AudioStreamer *) tech_pvt->pAudioStreamer;
if(audioStreamer) {
audioStreamer->deleteFiles();
if (text) audioStreamer->writeText(text);
finish(tech_pvt);
}
switch_mutex_unlock(tech_pvt->mutex);
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;
}
}