-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaudioamplifier.cpp
364 lines (295 loc) · 12 KB
/
audioamplifier.cpp
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
#include "audioamplifier.h"
#include "complexes.h"
#include <QDebug>
#include <QDir>
#include <QTime>
#include <QTimer>
#include <QAudioSink>
#include <QMediaDevices>
#include <cmath> // Amplification logic
AudioAmplifier::AudioAmplifier(const QAudioFormat &format, QObject *parent)
: QObject(parent),
audioFormat(format),
volumeFactor(1.0),
playbackPosition(0)
{
// Initialize audio sinks
playbackSink.reset(new QAudioSink(QMediaDevices::defaultAudioOutput(), format, this));
audioSink.reset(new QAudioSink(QMediaDevices::defaultAudioOutput(), format, this));
connect(audioSink.data(), &QAudioSink::stateChanged, this, &AudioAmplifier::handleStateChanged);
// Initialize QBuffer
audioBuffer.reset(new QBuffer(new QByteArray())); // QBuffer owns QByteArray
playbackBuffer.reset(new QBuffer(new QByteArray()));
playbackFile.setFileName(extractedTmpPlayback);
if (playbackFile.isOpen())
playbackFile.close();
if (!playbackFile.open(QIODevice::ReadOnly)) {
qWarning() << "Failed to open playback file!";
return;
}
playbackData = playbackFile.readAll(); // Read all data
// Initialize timer for probing end of stream
dataPushTimer.reset(new QTimer(this));
connect(dataPushTimer.data(), &QTimer::timeout, this, &AudioAmplifier::checkBufferState);
}
AudioAmplifier::~AudioAmplifier() {
stop();
if (audioBuffer && audioBuffer->isOpen()) {
audioBuffer->close();
}
if (playbackBuffer && playbackBuffer->isOpen()) {
playbackBuffer->close();
}
// Release QByteArrays
if (audioBuffer) {
audioBuffer->setData(QByteArray());
}
if (playbackBuffer) {
playbackBuffer->setData(QByteArray());
}
dataPushTimer->stop();
playbackSink.reset();
audioSink.reset();
audioBuffer.reset();
playbackBuffer.reset();
QObject::disconnect(audioSink.data(), &QAudioSink::stateChanged, this, &AudioAmplifier::handleStateChanged);
QObject::disconnect(dataPushTimer.data(), &QTimer::timeout, this, &AudioAmplifier::checkBufferState);
}
QString AudioAmplifier::checkBufferState() {
if (!audioBuffer->isOpen() || !audioSink || audioSink->isNull()) return ".. .Encoding. ..";
playbackPosition = audioBuffer->pos();
// Total duration based on the original audio size
qint64 totalDuration = originalAudioData.size() * 1000000 / (audioSink->format().sampleRate() *
audioSink->format().channelCount() * audioSink->format().bytesPerSample());
// Convert playbackPosition from bytes to microseconds
qint64 playbackPositionUSecs = playbackPosition * 1000000 / (audioSink->format().sampleRate() *
audioSink->format().channelCount() * audioSink->format().bytesPerSample());
// Correct the processed duration to include the playback position (both in microseconds now)
qint64 processedDuration = playbackPositionUSecs; // + audioSink->processedUSecs();
qint64 threshold = 500000; // stop 500 ms before the end
// Verify buffer size!
if (audioBuffer->bytesAvailable() < 1024) {
qWarning() << "Audio buffer too small during playback. Restarting playback.";
stop();
resetAudioComponents();
rewind();
start();
rewind();
return "NaN";
}
// When close to the end, restart playback
if (processedDuration >= totalDuration - threshold) {
qWarning() << "Buffer near the end. Restarting playback.";
stop();
resetAudioComponents();
rewind();
start();
rewind();
return "NaN";
}
long long totalSeconds = processedDuration / 1000000; // Convert microseconds to seconds
int hours = totalSeconds / 3600;
int minutes = (totalSeconds % 3600) / 60;
int seconds = totalSeconds % 60;
QTime time(hours, minutes, seconds);
return time.toString("hh:mm:ss");
}
void AudioAmplifier::start() {
// Verify if there is original data to amplify
if (!originalAudioData.isEmpty()) {
setAudioOffset(audioFormat.durationForBytes(byteOffset)/1000);
//applyAmplification();
// Validate initial buffer size
if (amplifiedAudioData.size() < 512) {
qWarning() << "Amplified buffer audio size is too small:" << amplifiedAudioData.size();
return;
}
stop();
// Verify if buffer is open, then close before starting
if (audioBuffer->isOpen()) {
audioBuffer->close();
}
audioBuffer->setData(amplifiedAudioData); // Configure QBuffer data
audioBuffer->open(QIODevice::ReadOnly); // and open for reading
audioBuffer->seek(playbackPosition); // Resume prior position
if (playbackBuffer->isOpen()) {
playbackBuffer->close();
}
playbackBuffer->setData(playbackData);
playbackBuffer->open(QIODevice::ReadOnly); // Open the buffer for reading
playbackBuffer->seek(playbackPosition);
playbackSink->start(playbackBuffer.data());
playbackSink->setVolume(playbackVol);
audioSink->start(audioBuffer.data()); // play amplified vocals
dataPushTimer->start(25); // Probe buffer state paranoia style
checkBufferState();
qDebug() << "Start amplified vocals and backing track.";
} else {
qWarning() << "No audio data.";
}
}
void AudioAmplifier::stop() {
if (audioSink->state() != QAudio::State::StoppedState) {
playbackPosition = audioBuffer->pos(); // Store current position before stopping
audioSink->stop(); // Stop the audio sink
qDebug() << "Stopped vocals.";
}
if (playbackSink->state() != QAudio::State::StoppedState) {
playbackSink->stop(); // Stop the playback sink
qDebug() << "Stopped backingtrack.";
}
// Close the buffer if playback is fully stopped
if (audioBuffer->isOpen() && !isPlaying()) {
audioBuffer->close();
qDebug() << "Closed vocals buffer.";
}
if (playbackBuffer->isOpen() && !isPlayingPlayback()) {
playbackBuffer->close();
qDebug() << "Closed backing track buffer.";
}
dataPushTimer->stop(); // Stop the timer when playback stops
}
void AudioAmplifier::seekForward() {
if (audioBuffer->bytesAvailable() > 514000) {
//stop();
//resetAudioComponents();
playbackPosition = audioBuffer->pos() + 514000;
audioBuffer->seek(playbackPosition);
playbackBuffer->seek(playbackPosition);
checkBufferState();
//start();
}
}
void AudioAmplifier::seekBackward() {
if ( audioBuffer->pos() - 514000 > 0 ) {
//stop();
//resetAudioComponents();
playbackPosition = audioBuffer->pos() - 514000;
audioBuffer->seek(playbackPosition);
playbackBuffer->seek(playbackPosition);
checkBufferState();
//start();
}
}
void AudioAmplifier::setVolumeFactor(double factor) {
if (factor != volumeFactor) {
volumeFactor = factor;
// Only restart playback if there is audio data
if (!originalAudioData.isEmpty() && isPlaying()) {
stop();
//resetAudioComponents();
start();
}
}
}
void AudioAmplifier::setAudioData(const QByteArray &data) {
// Release old data
QByteArray().swap(originalAudioData);
originalAudioData = data; // Store the new audio data
}
void AudioAmplifier::setPlaybackVol(bool flag) {
playbackSink->setVolume(flag);
playbackVol = flag;
}
void AudioAmplifier::applyAmplification() {
amplifiedAudioData.clear();
amplifiedAudioData.reserve(originalAudioData.size());
const char *data = originalAudioData.constData();
for (int i = 0; i < originalAudioData.size(); i += 2) {
// Convert two bytes to qint16 (16-bit audio)
qint16 sample = static_cast<qint16>(static_cast<unsigned char>(data[i]) |
(static_cast<unsigned char>(data[i + 1]) << 8));
// Amplify and clip to avoid overflow
int amplifiedSample = static_cast<int>(sample * volumeFactor);
amplifiedSample = std::min(std::max(amplifiedSample, -32768), 32767);
// Rewrite amplified sample as little-endian
amplifiedAudioData.append(static_cast<char>(amplifiedSample & 0xFF));
amplifiedAudioData.append(static_cast<char>((amplifiedSample >> 8) & 0xFF));
}
if (amplifiedAudioData.isEmpty()) {
qWarning() << "Amplified audio data is empty!";
}
}
bool AudioAmplifier::isPlaying() const {
return audioSink->state() == QAudio::ActiveState; // Check if audio is currently playing
}
bool AudioAmplifier::isPlayingPlayback() const {
return playbackSink->state() == QAudio::ActiveState; // Check if audio is currently playing
}
void AudioAmplifier::rewind() {
if (audioBuffer->isOpen()) {
audioBuffer->seek(0); // Seek the buffer to the start
} else {
qDebug() << "Vocals buffer is not open. Cannot rewind.";
}
if (playbackBuffer->isOpen())
playbackBuffer->seek(0);
else
qDebug() << "Playback buffer is not open. Cannot rewind.";
playbackPosition = 0; // Reset playback position
}
void AudioAmplifier::setAudioOffset(qint64 offsetMs) {
// Calculate the byte offset corresponding to the time offset
byteOffset = audioFormat.bytesForDuration(offsetMs * 1000); // Convert ms to µs
qDebug() << "Setting audio offset:" << offsetMs << "ms (" << byteOffset << "bytes)";
// Restore the original audio data
applyAmplification();
if (byteOffset < 0) {
// Negative offset: Prepend silence
qint64 silenceBytes = -byteOffset;
qDebug() << "Negative offset detected. Prepending" << silenceBytes << "bytes of silence.";
// Create a buffer with silence
QByteArray silence(silenceBytes, 0);
// Prepend silence to the audio data
amplifiedAudioData.prepend(silence);
//playbackPosition = 0;
} else {
// Positive offset: Trim the audio data
qint64 trimBytes = byteOffset;
qDebug() << "Positive offset detected. Trimming" << trimBytes << "bytes from the start.";
if (trimBytes < amplifiedAudioData.size()) {
amplifiedAudioData = amplifiedAudioData.mid(trimBytes);
} else {
qWarning() << "Trim exceeds audio size. Clearing buffer.";
amplifiedAudioData.clear();
}
//playbackPosition = 0;
}
if (audioSink->state() != QAudio::State::StoppedState) {
audioSink->stop(); // Stop the audio sink
qDebug() << "Stopped vocals.";
}
// Verify if buffer is open, then close before starting
if (audioBuffer->isOpen()) {
audioBuffer->close();
}
audioBuffer->setData(amplifiedAudioData); // Configure with new QBuffer data
audioBuffer->open(QIODevice::ReadOnly); // and open for reading
audioBuffer->seek(playbackPosition); // Resume prior position
audioSink->start(audioBuffer.data()); // play amplified vocals
}
void AudioAmplifier::handleStateChanged(QAudio::State newState) {
if (newState == QAudio::StoppedState) {
if (audioSink && audioSink->error() != QAudio::NoError) {
qWarning() << "Audio playback error:" << audioSink->error();
return;
}
}
}
void AudioAmplifier::resetAudioComponents() {
// Stop any active sinks
if (audioSink && audioSink->state() == QAudio::ActiveState) {
audioSink->stop();
}
if (playbackSink && playbackSink->state() == QAudio::ActiveState) {
playbackSink->stop();
}
// Properly release old sinks before creating new ones
playbackSink.reset();
audioSink.reset();
// Recreate sinks
playbackSink.reset(new QAudioSink(QMediaDevices::defaultAudioOutput(), audioFormat, this));
audioSink.reset(new QAudioSink(QMediaDevices::defaultAudioOutput(), audioFormat, this));
// Reconnect signals
connect(audioSink.data(), &QAudioSink::stateChanged, this, &AudioAmplifier::handleStateChanged);
}