Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SAPI: Refactor minitrim functions and also remove silence at the end. #124

Merged
merged 6 commits into from
Nov 6, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
SAPI: Refactor minitrim functions and also remove silence at the end.
  • Loading branch information
m1maker committed Oct 13, 2024
commit aa1650c47c78020b23d58397d5a18bdec10ccbfc
55 changes: 37 additions & 18 deletions src/tts.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -29,26 +29,45 @@
#include <SDL3/SDL.h>
#endif

char* minitrim(char* data, unsigned long* bufsize, int bitrate, int channels) {
char* ptr = data;
if (!ptr || !bufsize || *bufsize % 2 != 0 || *bufsize < 1) return ptr;
short a = 3072;
while (bitrate == 16 && (ptr - data) < *bufsize) {
if (channels == 2) {
short l = (((short) * ptr) << 8) | *(ptr + 1);
short r = (((short) * (ptr + 2)) << 8) | *(ptr + 3);
if (l > -a && l < a && r > -a && r < a)
ptr += 4;
else break;
} else if (channels == 1) {
short s = (((short) * ptr) << 8) | *(ptr + 1);
if (s > -a && s < a)
ptr += 2;
else break;
static char* minitrim(char* data, unsigned long* size, int bytesPerSample, int channels, int threshold = 20) {
int samplesPerFrame = channels * bytesPerSample;
int numSamples = *size / samplesPerFrame;
int startIndex = 0;
int endIndex = numSamples - 1;

for (int i = 0; i < numSamples; i++) {
int maxAbsValue = 0;
for (int j = 0; j < channels; j++) {
int absValue = abs(static_cast<int>(data[i * samplesPerFrame + j]));
if (absValue > maxAbsValue) {
maxAbsValue = absValue;
}
}
if (maxAbsValue >= threshold) {
startIndex = i;
break;
}
}
*bufsize -= (ptr - data);
return ptr;

for (int i = numSamples - 1; i >= 0; i--) {
int maxAbsValue = 0;
for (int j = 0; j < channels; j++) {
int absValue = abs(static_cast<int>(data[i * samplesPerFrame + j]));
if (absValue > maxAbsValue) {
maxAbsValue = absValue;
}
}
if (maxAbsValue >= threshold) {
endIndex = i;
break;
}
}

int trimmedSize = (endIndex - startIndex + 1) * samplesPerFrame;
char* trimmedData = new char[trimmedSize];
memcpy(trimmedData, data + startIndex * samplesPerFrame, trimmedSize);
*size = trimmedSize;
return trimmedData;
}

tts_voice::tts_voice(const std::string& builtin_voice_name) {
Expand Down