-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfrontSoundTouch.cpp
549 lines (486 loc) · 18.5 KB
/
frontSoundTouch.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
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
#include <QObject>
#include <QTimer>
#include "frontSoundTouch.h"
#include <QDebug>
#include <QElapsedTimer>
#include <QSemaphore>
#include <QList>
#include <QThread>
#define CHANNELS 2
#define SAMPLE_RATE (44100)
#define FRAMES_PER_BUFFER SAMPLE_RATE/100 // HOW MANY FRAME TOO QUERY IN CALLBACK. LESS IS, LESS DELAY TO START
#define FRAMES_PER_BUFFER_IN_MEMORY SAMPLE_RATE*2 // FRAME IN BUFFER MEMORY IN SECOND
#define CURRTEMPO (100)
#define CURRSEMITONE (0)
#define TIMERTIMEOUT (400) // CALLBACK ON TIMER FOR INSERT INTO MEMORY BUFFER
#define SIZEMEMBUFFER FRAMES_PER_BUFFER_IN_MEMORY*CHANNELS*10
QElapsedTimer elapsedTimer;
QSemaphore qSem(1);
float data [FRAMES_PER_BUFFER_IN_MEMORY*CHANNELS] ;
float data2 [FRAMES_PER_BUFFER_IN_MEMORY*CHANNELS] ;
struct structTimerBuff {
bool isAvailable=false;
bool endOfFileReached = false;
unsigned long idxNext = 0;
float buffer[SIZEMEMBUFFER]; // Receive in Memory Structure
};
structTimerBuff MainBuffer;
////////////////////////////////////////////////////////////////////////////
/// \brief processFile::paCallback
/// \param inputBuffer
/// \param outputBuffer
/// \param framesPerBuffer
/// \param timeInfo
/// \param statusFlags
/// \param userData
/// \return
////////////////////////////////////////////////////////////////////////////
int frontSoundTouch::paCallback( const void *inputBuffer, void *outputBuffer,
unsigned long framesPerBuffer,
const PaStreamCallbackTimeInfo* timeInfo,
PaStreamCallbackFlags statusFlags,
void *userData
)
{
// Remove Warning unused var in compiler
(void)inputBuffer;
(void)timeInfo;
(void)statusFlags;
frontSoundTouch *localPF;
unsigned long countRead;
float *out = (float*)outputBuffer;
if( MainBuffer.isAvailable ){
localPF = (frontSoundTouch*)userData;
countRead = localPF->getMemBuffer( out,framesPerBuffer );
if( countRead < framesPerBuffer ){
emit(localPF->processed(100));
return paComplete;
}
}
else
memset( out,0,framesPerBuffer*CHANNELS*sizeof(float));
return paContinue;
}
////////////////////////////////////////////////////////////////////////////
/// \brief processFile::processFile
////////////////////////////////////////////////////////////////////////////
frontSoundTouch::frontSoundTouch()
{
PaError err;
currTempo = CURRTEMPO;
currSemiTone = CURRSEMITONE;
bypassStrech = false; // if set to true, prog don't use soundTouch library, no sound streching
fillBufferTimer = new QTimer( this );
// Intitialize Sountouche values
pSoundTouch.setChannels(CHANNELS);
pSoundTouch.setSampleRate(SAMPLE_RATE);
pSoundTouch.setTempo(currTempo/100 );
pSoundTouch.setPitchSemiTones(currSemiTone);
// Intitialize and Start PortAudio
err = Pa_Initialize();
if( err != paNoError ){
qDebug() << "PortAudio error: " << Pa_GetErrorText( err );
goto error;
}
return;
error:
Pa_Terminate();
qDebug() << "An error occured while using the portaudio stream" ;
qDebug() << "Error number: " << err ;
qDebug() << "Error message: " << Pa_GetErrorText( err ) ;
return ;
}
////////////////////////////////////////////////////////////////////////////
/// \brief processFile::~processFile
////////////////////////////////////////////////////////////////////////////
frontSoundTouch::~frontSoundTouch()
{
pause();
sf_close(file);
delete fillBufferTimer;
}
////////////////////////////////////////////////////////////////////////////
/// \brief processFile::setFilename
/// \param fileName
/// \return
////////////////////////////////////////////////////////////////////////////
long long frontSoundTouch::setFilename(QString fileName)
{
PaError err;
PaStreamParameters outputParameters;
PaStreamFlags streamFlags;
PaDeviceIndex outDevNum;
currFileName = fileName;
SF_INFO sfinfo;
sfinfo.channels = CHANNELS;
sfinfo.samplerate = SAMPLE_RATE;
if( isfileOpen )
sf_close( file );
LPCWSTR LfileName = (LPCWSTR)currFileName.utf16();
// file = sf_open( currFileName.toStdString().c_str(),SFM_READ,&sfinfo );
file = sf_wchar_open( LfileName, SFM_READ, &sfinfo);
Q_ASSERT(file != NULL );
isfileOpen = true;
totalFrames = 0;
while (true) {
long long countFrameReadFile = sf_readf_float(file, data, SAMPLE_RATE); // Put One second each time
if( countFrameReadFile == 0)
break;
totalFrames += countFrameReadFile;
}
sf_seek(file,0,SEEK_SET);
// Initialize SoundTouch
pSoundTouch.clear();
// Initialize Buffer
MainBuffer.isAvailable = false;
MainBuffer.idxNext = 0;
MainBuffer.endOfFileReached = false;
currFileFrameRead = 0;
currPlayFrameRead = 0;
currPlayedFrameRead = 0;
listOfBlock.clear();
err = Pa_IsStreamStopped(stream);
if( err == 0){
err = Pa_StopStream( stream );
if( err != paNoError )
goto error;
err = Pa_CloseStream( stream );
if( err != paNoError )
goto error;
}
memset( &outputParameters,0, sizeof( outputParameters ) ); //not necessary if you are filling in all the fields
outDevNum = Pa_GetDefaultOutputDevice();
outputParameters.device = outDevNum; // default output device
if (outputParameters.device == paNoDevice) {
qDebug() << "Error: No default output device.\n";
goto error;
}
outputParameters.channelCount = CHANNELS;
outputParameters.device = outDevNum;
outputParameters.hostApiSpecificStreamInfo = NULL;
outputParameters.sampleFormat = paFloat32;
outputParameters.suggestedLatency = Pa_GetDeviceInfo(outDevNum)->defaultLowOutputLatency ;
outputParameters.hostApiSpecificStreamInfo = NULL; //See you specific host's API docs for info on using this field
streamFlags = paNoFlag;
err = Pa_OpenStream (
&stream,
NULL,
&outputParameters,
SAMPLE_RATE,
FRAMES_PER_BUFFER,
streamFlags,
&frontSoundTouch::paCallback,
this
);
if( err != paNoError )
goto error;
//Fill buffer on Timer to limitate Glitch
isPaused = true;
MainBuffer.idxNext = 0;
fillBufferTimer ->connect(fillBufferTimer, SIGNAL(timeout()),this, SLOT(insertIntoMemBuffer()));
return (long long)0;
error:
Pa_Terminate();
qDebug() << "An error occured while using the portaudio stream" ;
qDebug() << "Error number: " << err ;
qDebug() << "Error message: " << Pa_GetErrorText( err ) ;
return (long long)0;
}
////////////////////////////////////////////////////////////////////////////
/// \brief processFile::play
////////////////////////////////////////////////////////////////////////////
bool frontSoundTouch::play()
{
PaError err;
if( currFileName == "" )
return false;
fillBufferTimer->start( 0 );
QThread::msleep(100);
err = Pa_StartStream(stream);
if( err != paNoError )
goto error;
isPaused = false;
return true;
error:
qDebug() << "An error occured while using the portaudio stream" ;
qDebug() << "Error number: " << err ;
qDebug() << "Error message: " << Pa_GetErrorText( err ) ;
return false;
}
////////////////////////////////////////////////////////////////////////////
/// \brief processFile::pause
////////////////////////////////////////////////////////////////////////////
void frontSoundTouch::pause()
{
isPaused = true;
PaError err;
err = Pa_StopStream(stream);
if( err != paNoError )
goto error;
return;
error:
qDebug() << "An error occured while using the portaudio stream" ;
qDebug() << "Error number: " << err ;
qDebug() << "Error message: " << Pa_GetErrorText( err ) ;
}
////////////////////////////////////////////////////////////////////////////
/// \brief processFile::seek
/// \param frameToStart
////////////////////////////////////////////////////////////////////////////
void frontSoundTouch::seek(long long frameToStart)
{
PaError err;
if( !isfileOpen ){
emit( processed((float)0));
qDebug() << "No file is Opened";
return;
}
err = Pa_IsStreamStopped(stream);
if( err == 0){
// err = Pa_StopStream( stream );
fillBufferTimer->stop();
err = Pa_AbortStream( stream );
if( err != paNoError )
goto error;
}
fillBufferTimer->stop();
sf_seek(file,frameToStart,SEEK_SET);
MainBuffer.isAvailable = false;
MainBuffer.idxNext = 0;
MainBuffer.endOfFileReached = false;
currFileFrameRead = frameToStart;
currPlayFrameRead = frameToStart;
currPlayedFrameRead = frameToStart;
listOfBlock.clear();
if( !isPaused ){
fillBufferTimer->start( 0 );
err = Pa_StartStream(stream);
if( err != paNoError )
goto error;
}
return;
error:
qDebug() << "An error occured while using the portaudio stream" ;
qDebug() << "Error number: " << err ;
qDebug() << "Error message: " << Pa_GetErrorText( err ) ;
}
////////////////////////////////////////////////////////////////////////////
/// \brief processFile::seek
/// \param percentOfFile
////////////////////////////////////////////////////////////////////////////
void frontSoundTouch::seek(double percentOfFile )
{
if( !isfileOpen ){
emit( processed( double(0)));
qDebug() << "No file is Opened";
return;
}
emit( processed(double(percentOfFile)));
seek((long long)((float)totalFrames * percentOfFile/(float)100));
// emit( processed(double(percentOfFile)));
}
////////////////////////////////////////////////////////////////////////////
/// \brief processFile::insertIntoMemBuffer
////////////////////////////////////////////////////////////////////////////
void frontSoundTouch::insertIntoMemBuffer()
{
long countFrameReadFile;
long readST;
posReadFrame pRF;
fillBufferTimer->stop();
qSem.acquire(1);
while ( MainBuffer.idxNext < FRAMES_PER_BUFFER_IN_MEMORY && MainBuffer.endOfFileReached == false ) {
if( bypassStrech ){
if(pSoundTouch.numSamples() != 0 ){ // Case of Switch in middle of file
countFrameReadFile = pSoundTouch.receiveSamples( data, FRAMES_PER_BUFFER_IN_MEMORY);
}
else{
countFrameReadFile = sf_readf_float(file, data, FRAMES_PER_BUFFER_IN_MEMORY);
if(countFrameReadFile == 0){
MainBuffer.endOfFileReached = true;
MainBuffer.isAvailable = true;
qSem.release(1);
// No more interrupt Timer, end of file
return;
}
pRF.fileFrameReadBottom = currFileFrameRead;
pRF.playFrameReadBottom = currPlayFrameRead;
currFileFrameRead += countFrameReadFile;
currPlayFrameRead += countFrameReadFile;
pRF.fileFrameReadTop= currFileFrameRead;
pRF.playFrameReadTop = currPlayFrameRead;
listOfBlock.append(pRF);
garbageListOfBlock();
}
memcpy( &MainBuffer.buffer[MainBuffer.idxNext], data, countFrameReadFile*CHANNELS*sizeof(float));
MainBuffer.idxNext += countFrameReadFile*CHANNELS;
}
else{
if(pSoundTouch.numSamples() == 0){
countFrameReadFile = sf_readf_float(file, data, FRAMES_PER_BUFFER_IN_MEMORY);
if(countFrameReadFile == 0){
MainBuffer.endOfFileReached = true;
MainBuffer.isAvailable = true;
qSem.release(1);
// No more interrupt Timer, end of file
return;
}
pSoundTouch.putSamples(data,countFrameReadFile);
pRF.fileFrameReadBottom = currFileFrameRead;
pRF.playFrameReadBottom = currPlayFrameRead;
currFileFrameRead += countFrameReadFile;
currPlayFrameRead += countFrameReadFile * pSoundTouch.getInputOutputSampleRatio();
pRF.fileFrameReadTop= currFileFrameRead;
pRF.playFrameReadTop = currPlayFrameRead;
listOfBlock.append(pRF);
garbageListOfBlock();
}
readST = pSoundTouch.receiveSamples( data2, FRAMES_PER_BUFFER_IN_MEMORY);
memcpy( &MainBuffer.buffer[MainBuffer.idxNext], data2, readST*CHANNELS*sizeof(float));
MainBuffer.idxNext += readST*CHANNELS;
}
}
MainBuffer.isAvailable = true;
qSem.release(1);
fillBufferTimer->start(TIMERTIMEOUT);
}
////////////////////////////////////////////////////////////////////////////
/// \brief processFile::getMemBuffer
/// \param out
/// \param framesToRead
/// \return
////////////////////////////////////////////////////////////////////////////
long frontSoundTouch::getMemBuffer(float *out,unsigned long framesToRead){
unsigned long read;
qSem.acquire(1);
// elapsedTimer.start();
if( MainBuffer.idxNext >= framesToRead*CHANNELS )
read = framesToRead;
else
read = MainBuffer.idxNext/CHANNELS;
float prc = (float)toFrameOrig(currPlayedFrameRead)/(float)totalFrames * (float)100;
emit( processed(prc));
currPlayedFrameRead += read;
memcpy(out,&MainBuffer.buffer[0],read*CHANNELS*sizeof(float));
memcpy(&MainBuffer.buffer[0],
&MainBuffer.buffer[read * CHANNELS],
MainBuffer.idxNext*sizeof(float) - read * CHANNELS*sizeof(float)
);
if( read < framesToRead) //End of file reached
memset(out+read*CHANNELS,0,framesToRead*CHANNELS*sizeof(float)-MainBuffer.idxNext *sizeof(float));
MainBuffer.idxNext -= read * CHANNELS;
if( read == 0)
MainBuffer.isAvailable = false;
qSem.release(1);
return read;
}
////////////////////////////////////////////////////////////////////////////
/// \brief processFile::setTempo
/// \param tempo
////////////////////////////////////////////////////////////////////////////
void frontSoundTouch::setTempo(int tempo){
// if( currTempo != tempo ){
pSoundTouch.setTempo((float)tempo/100);
currTempo = tempo;
// }
}
////////////////////////////////////////////////////////////////////////////
/// \brief processFile::setPitchSemiTones
/// \param semiTone
////////////////////////////////////////////////////////////////////////////
void frontSoundTouch::setPitchSemiTones(int semiTone){
// if( currSemiTone != semiTone ){
pSoundTouch.setPitchSemiTones(semiTone);
currSemiTone = semiTone;
// }
}
////////////////////////////////////////////////////////////////////////////
/// \brief processFile::setOctava
/// \param octava
////////////////////////////////////////////////////////////////////////////
void frontSoundTouch::setOctava(int octava){
pSoundTouch.setPitchOctaves((float)octava);
currOctava = octava;
}
////////////////////////////////////////////////////////////////////////////
/// \brief processFile::getBPM
/// \return
////////////////////////////////////////////////////////////////////////////
float frontSoundTouch::getBPM(){
long countFrameReadFile;
soundtouch::BPMDetect bpm(CHANNELS, SAMPLE_RATE);
for( int i = 0; i < 30;i++){ // For first n Seconds off file
countFrameReadFile = sf_readf_float(file, data, SAMPLE_RATE); // Put One second each time
if( countFrameReadFile == 0)
break;
bpm.inputSamples(data,countFrameReadFile);
}
sf_seek(file,0,SEEK_SET);
return bpm.getBpm();
}
////////////////////////////////////////////////////////////////////////////
/// \brief processFile::toFrameOrig
/// \param frameToConvert
/// \return
////////////////////////////////////////////////////////////////////////////
long long frontSoundTouch::toFrameOrig(long long frameToConvert){
long long retValue;
for( int i = 0; i < listOfBlock.count();i++){
if(frameToConvert >= listOfBlock.at(i).playFrameReadBottom and frameToConvert < listOfBlock.at(i).playFrameReadTop ){
long long nbOrig = listOfBlock.at(i).fileFrameReadTop - listOfBlock.at(i).fileFrameReadBottom;
long long nbDest = listOfBlock.at(i).playFrameReadTop - listOfBlock.at(i).playFrameReadBottom;
float ratio = (float)nbOrig/(float)nbDest;
retValue = (long long)((float)( frameToConvert - listOfBlock.at(i).playFrameReadBottom ) * ratio + (float)listOfBlock.at(i).fileFrameReadBottom);
frameToTime(retValue,&currTimePlayed);
return retValue;
}
}
return -1;
}
////////////////////////////////////////////////////////////////////////////
/// \brief processFile::garbageListOfBlock
////////////////////////////////////////////////////////////////////////////
void frontSoundTouch::garbageListOfBlock(){
for( int i = 0; i < listOfBlock.count();i++){
if( currPlayedFrameRead > listOfBlock.at(i).playFrameReadTop ){
listOfBlock.removeAt(i);
break;
}
}
}
////////////////////////////////////////////////////////////////////////////
/// \brief processFile::frameToTime
/// \param frameToConvert
/// \param currentTime
////////////////////////////////////////////////////////////////////////////
void frontSoundTouch::frameToTime(long long frameToConvert, QTime *currentTime){
int restOfFrame = frameToConvert%SAMPLE_RATE;
int ms = (int)((float)1000/(float)SAMPLE_RATE * (float)restOfFrame);
int seconde = frameToConvert/SAMPLE_RATE;
int minute = seconde/60;
seconde = seconde%60;
int heure = minute/60;
minute = minute%60;
currentTime->setHMS(heure,minute,seconde,ms);
}
////////////////////////////////////////////////////////////////////////////
/// \brief processFile::getCurrentReadFrame
/// \return
////////////////////////////////////////////////////////////////////////////
long long frontSoundTouch::getCurrentReadFrame(){
return toFrameOrig(currPlayedFrameRead);
}
////////////////////////////////////////////////////////////////////////////
/// \brief processFile::getCurrentReadTime
/// \param currentTime
////////////////////////////////////////////////////////////////////////////
void frontSoundTouch::getCurrentReadTime(QTime *currentTime){
frameToTime(toFrameOrig(currPlayedFrameRead), currentTime );
}
////////////////////////////////////////////////////////////////////////////
////// \brief processFile::framesOfFile
////// \return
////////////////////////////////////////////////////////////////////////////
long long frontSoundTouch::framesOfFile(){
return totalFrames;
}