Skip to content

Commit

Permalink
[switch_ivr_play_say] Make better use of memory during speed change
Browse files Browse the repository at this point in the history
Relating to signalwire#244, this commit makes better use of stack and heap
memory allocations
  • Loading branch information
yois615 committed Aug 3, 2022
1 parent aa1dce5 commit 7bfe33b
Showing 1 changed file with 22 additions and 16 deletions.
38 changes: 22 additions & 16 deletions src/switch_ivr_play_say.c
Original file line number Diff line number Diff line change
Expand Up @@ -1285,7 +1285,8 @@ SWITCH_DECLARE(switch_status_t) switch_ivr_play_file(switch_core_session_t *sess
short sp_ovrlap[32];
short sp_has_overlap = 0;
int sp_prev_idx = 0;
short sp_prev[SWITCH_RECOMMENDED_BUFFER_SIZE];
int sp_prev_cap = 0;
short *sp_prev = NULL;

file = argv[cur];
eof = 0;
Expand Down Expand Up @@ -1794,9 +1795,16 @@ SWITCH_DECLARE(switch_status_t) switch_ivr_play_file(switch_core_session_t *sess
int src_rng = (fh->speed > 0 ? supplement : sp_cut_src_rng)* sp_has_overlap;
int datalen = newlen + src_rng + sp_fadeLen;
int extra = datalen - olen;
short* data = NULL;
short data[datalen * 2];
short* currp = NULL;
switch_zmalloc(data, datalen * 2);

memset(data, 0, sizeof(data));

if (!sp_prev) {
sp_prev_cap = olen * 3 + sp_prev_idx;
switch_zmalloc(sp_prev, sp_prev_cap);
}

if (!fh->sp_audio_buffer) {
switch_buffer_create_dynamic(&fh->sp_audio_buffer, 1024, 1024, 0);
}
Expand All @@ -1809,29 +1817,25 @@ SWITCH_DECLARE(switch_status_t) switch_ivr_play_file(switch_core_session_t *sess
// not enough data
switch_buffer_write(fh->sp_audio_buffer, bp, newlen * 2);
cont = 1;
} else if (SWITCH_RECOMMENDED_BUFFER_SIZE < extra + sp_prev_idx) {
// data does not fit
switch_buffer_write(fh->sp_audio_buffer, bp, newlen * 2);
cont = 1;
} else {
memcpy(currp, sp_prev + sp_prev_idx - extra, extra * 2);
memcpy(currp + extra, bp, olen * 2);
}

if (olen * 3 + sp_prev_idx > sp_prev_cap) {
sp_prev_cap = olen * 3 + sp_prev_idx;
sp_prev = realloc(sp_prev, sp_prev_cap);
sp_prev_idx = 0;
}

if (sp_prev_idx > olen) {
memmove(sp_prev, sp_prev + sp_prev_idx - olen, olen * 2);
sp_prev_idx = olen;
}
if (sp_prev_idx + olen <= SWITCH_RECOMMENDED_BUFFER_SIZE) {
memcpy(sp_prev + sp_prev_idx, bp, olen * 2);
sp_prev_idx += olen;
} else {
cont = 1;
}

memcpy(sp_prev + sp_prev_idx, bp, olen * 2);
sp_prev_idx += olen;

if (cont) {
switch_safe_free(data);
continue;
}
} else {
Expand Down Expand Up @@ -1871,7 +1875,6 @@ SWITCH_DECLARE(switch_status_t) switch_ivr_play_file(switch_core_session_t *sess
}

last_speed = fh->speed;
switch_safe_free(data);
continue;
}

Expand Down Expand Up @@ -2028,6 +2031,9 @@ SWITCH_DECLARE(switch_status_t) switch_ivr_play_file(switch_core_session_t *sess
if (fh->sp_audio_buffer) {
switch_buffer_destroy(&fh->sp_audio_buffer);
}

switch_safe_free(sp_prev);

}

if (switch_core_codec_ready((&codec))) {
Expand Down

0 comments on commit 7bfe33b

Please sign in to comment.