-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlooper.cpp
More file actions
437 lines (377 loc) · 13.6 KB
/
Copy pathlooper.cpp
File metadata and controls
437 lines (377 loc) · 13.6 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
#include "looper.h"
#include "ui_looper.h"
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include "portaudio.h"
#include "sndfile.h"
using namespace std;
#define SAMPLE_RATE (44100)
#define FRAMES_PER_BUFFER (512)
#define MAX_NUM_SECONDS (30)
#define NUM_CHANNELS (2)
#define DITHER_FLAG (0)
#define WRITE_TO_FILE (0)
#define SYNCH_TIME 5500
/* Select sample format. */
#if 1
#define PA_SAMPLE_TYPE paFloat32
typedef float SAMPLE;
#define SAMPLE_SILENCE (0.0f)
#define PRINTF_S_FORMAT "%.8f"
#elif 1
#define PA_SAMPLE_TYPE paInt16
typedef short SAMPLE;
#define SAMPLE_SILENCE (0)
#define PRINTF_S_FORMAT "%d"
#elif 0
#define PA_SAMPLE_TYPE paInt8
typedef char SAMPLE;
#define SAMPLE_SILENCE (0)
#define PRINTF_S_FORMAT "%d"
#else
#define PA_SAMPLE_TYPE paUInt8
typedef unsigned char SAMPLE;
#define SAMPLE_SILENCE (128)
#define PRINTF_S_FORMAT "%d"
#endif
int globalFrameIndex = 0; //Global variable: tracks the first recording's current frame
int globalTrack0Length = 0; //Global variable: looks for how much the first recording will last
//Function to calculate the real synch time in case it becomes negative:
int calculateSynchTime(int start, int synchConst){
int result = start - synchConst;
if (result < 0){
result = globalTrack0Length + result; //result is negative, so this is actually a subtraction.
}
return result;
}
static int recordCallback( const void *inputBuffer, void *outputBuffer,
unsigned long framesPerBuffer,
const PaStreamCallbackTimeInfo* timeInfo,
PaStreamCallbackFlags statusFlags,
void *userData )
{
/* Declaration of variables */
paTestData *data = (paTestData*)userData;
const SAMPLE *rptr = (const SAMPLE*)inputBuffer;
SAMPLE *wptr = &data->recordedSamples[data->frameIndex * NUM_CHANNELS];
long framesToCalc;
long i;
int finished;
unsigned long framesLeft;
(data->trackNumber == 0) ? framesLeft = data->maxFrameIndex - data->frameIndex : framesLeft = (globalTrack0Length-10) - data->frameIndex;
(void) outputBuffer; // Prevent unused variable warnings.
(void) timeInfo;
(void) statusFlags;
(void) userData;
/* It ensures that the buffer is terminated properly */
if( framesLeft < framesPerBuffer )
{
framesToCalc = framesLeft;
finished = paComplete;
}
else
{
framesToCalc = framesPerBuffer;
finished = paContinue;
}
if( inputBuffer == NULL ) // exceptional case, don't do anything here!!!
{
for( i=0; i<framesToCalc; i++ )
{
*wptr++ = SAMPLE_SILENCE; // left
if( NUM_CHANNELS == 2 ) *wptr++ = SAMPLE_SILENCE; // right
}
}
else
{
for( i=0; i<framesToCalc; i++ )
{
*wptr++ = *rptr++; /* left */
if( NUM_CHANNELS == 2 ) *wptr++ = *rptr++; // right
data->finalFrame++;
if (data->trackNumber == 0) globalTrack0Length = data->finalFrame; //Updates the maximum playback time if this is the first track
}
}
data->frameIndex += framesToCalc;
data->finalFrame = data->frameIndex;
if (data->trackNumber == 0) globalTrack0Length = data->finalFrame; //Updates the maximum playback time if this is the first track
return finished;
}
static int playCallback( const void *inputBuffer, void *outputBuffer,
unsigned long framesPerBuffer,
const PaStreamCallbackTimeInfo* timeInfo,
PaStreamCallbackFlags statusFlags,
void *userData )
{
/* Declaration of variables */
paTestData *data = (paTestData*)userData;
SAMPLE *rptr = &data->recordedSamples[data->frameIndex * NUM_CHANNELS];
SAMPLE *wptr = (SAMPLE*)outputBuffer;
unsigned int i;
int finished;
unsigned int framesLeft = data->finalFrame - data->frameIndex;
(void) inputBuffer; // Prevent unused variable warnings.
(void) timeInfo;
(void) statusFlags;
(void) userData;
if ((data->isVirgin == true) && (data->trackNumber != 0)){ //First playback: makes sure it only starts playing when it's intended
while (globalFrameIndex != 0){
if (calculateSynchTime(data->startingFrame, SYNCH_TIME) >= globalFrameIndex){
break;
}
continue;
}
data->isVirgin = false;
}
if (data->trackNumber != 0){ //Will not enter this loop if we're working with the first track.
int synchedTime = calculateSynchTime(data->startingFrame, SYNCH_TIME);
while ((synchedTime >= (globalFrameIndex)) && (data->frameIndex == 0)){ //Waits until the main track reaches the synch point for this track.
continue;
}
}
if( framesLeft < framesPerBuffer )
{
/* final buffer... */
for( i=0; i<framesLeft; i++ )
{
*wptr++ = *rptr++; // left
if( NUM_CHANNELS == 2 ) *wptr++ = *rptr++; // right
}
if (data->trackNumber != 0) {
while (globalFrameIndex >= data->startingFrame){ //Waits until the main track has finished playing.
continue;
}
}
data->frameIndex = 0;
finished = paContinue;
}
else
{
if (data->trackNumber == 0) globalFrameIndex = data->frameIndex; //Is this the main track? If so, update the global variable so other tracks can synch
for( i=0; i<framesPerBuffer; i++ )
{
*wptr++ = *rptr++; // left
if( NUM_CHANNELS == 2 ) *wptr++ = *rptr++; // right
}
data->frameIndex += framesPerBuffer;
finished = paContinue;
}
return finished;
}
Looper::Looper(QWidget *parent) : QMainWindow(parent),ui(new Ui::Looper)
{
ui->setupUi(this);
err = Pa_Initialize();
totalTracks = 0;
QString TracksText = QString::number(totalTracks);
ui->textEdit_2->setText(" "+TracksText);
recording = false;
paused = false;
if( err != paNoError ) error(err);
inputParameters.device = Pa_GetDefaultInputDevice(); // default input device
if (inputParameters.device == paNoDevice) {
QMessageBox mbox;
mbox.setText("Error: No default input device.\n");
mbox.exec();
}
inputParameters.channelCount = 2; // stereo input
inputParameters.sampleFormat = paFloat32;
inputParameters.suggestedLatency = Pa_GetDeviceInfo( inputParameters.device )->defaultLowInputLatency;
inputParameters.hostApiSpecificStreamInfo = NULL;
outputParameters.device = Pa_GetDefaultOutputDevice(); // default output device
if (outputParameters.device == paNoDevice) {
QMessageBox mbox;
mbox.setText("Error: No default input device.\n");
mbox.exec();
}
outputParameters.channelCount = 2; // stereo output
outputParameters.sampleFormat = paFloat32;
outputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device )->defaultLowOutputLatency;
outputParameters.hostApiSpecificStreamInfo = NULL;
//Startup button begining
ui->pauseButton->setDisabled(true);
ui->stopButton->setDisabled(true);
//Startup ending
}
void Looper::startRecording(int index)
{
/* Acquire parameters, allocate memory, clear it and start recording */
data[index].maxFrameIndex = totalFrames = MAX_NUM_SECONDS * SAMPLE_RATE; // Determines the size of the data
data[index].frameIndex = 0; // Clean the frame index to start recording
data[index].trackNumber = index; //Saves which track this is
(index == 0) ? data[0].startingFrame = 0 : data[index].startingFrame = data[0].frameIndex;
numSamples = totalFrames * NUM_CHANNELS;
numBytes = numSamples * sizeof(SAMPLE);
data[index].recordedSamples = new SAMPLE[numBytes]; // From now on, recordedSamples is initialised.
if( data[index].recordedSamples == NULL ) {
cout << "Could not allocate record array." << endl << flush;
error(err);
}
for( i=0; i<numSamples; i++ ) {
data[index].recordedSamples[i] = 0;
}
/* The recording stream opens here */
err = Pa_OpenStream(
&stream[index],
&inputParameters,
NULL, // &outputParameters,
SAMPLE_RATE,
FRAMES_PER_BUFFER,
paClipOff, // we won't output out of range samples so don't bother clipping them
recordCallback,
&data[index] );
if( err != paNoError ) error(err);
/* Starts recording */
err = Pa_StartStream(stream[index]);
if( err != paNoError ) error(err);
}
void Looper::stopRecording(int index)
{
/* Closes the recording stream */
err = Pa_CloseStream( stream[index] );
data[index].frameIndex = 0;
if( err != paNoError ) error(err);
}
void Looper::startPlayback(int index)
{
data[index].frameIndex = 0; // Clean the frame index to start playback
data[index].isVirgin = true;
/* The playback stream opens here */
err = Pa_OpenStream(
&stream[index],
NULL, // No input
&outputParameters,
SAMPLE_RATE,
FRAMES_PER_BUFFER,
paClipOff, // We won't output out of range samples so don't bother clipping them
playCallback,
&data[index] );
if( err != paNoError ) error(err);
/* Starts playback */
err = Pa_StartStream(stream[index]);
if( err != paNoError ) error(err);
}
void Looper::pausePlayback()
{
/* Function that pauses all audio tracks */
for(int j=0;j<totalTracks;j++) {
err = Pa_StopStream( stream[j] );
if( err != paNoError ) error(err);
}
}
void Looper::resumePlayback()
{
/* Function that resumes all paused audio tracks */
for(int j=0;j<totalTracks;j++) {
err = Pa_StartStream(stream[j]);
if( err != paNoError ) error(err);
}
}
void Looper::stopPlayback()
{
/* Function that stop the program and close all streams */
for(int j=0;j<totalTracks;j++) {
err = Pa_CloseStream(stream[j]);
if( err != paNoError ) error(err);
if( data[j].recordedSamples ) delete data[j].recordedSamples; //Deleting all track samples to prevent memory leak
}
totalTracks = 0;
}
void Looper::savePlayback()
{
SF_INFO ndsInfo;
ndsInfo.frames = FRAMES_PER_BUFFER;
ndsInfo.samplerate = SAMPLE_RATE;
ndsInfo.channels = NUM_CHANNELS;
ndsInfo.format = SF_FORMAT_WAV;
SNDFILE* myFile = sf_open("/home/cadu/Looper/loop.wav", SFM_WRITE, &ndsInfo);
sf_count_t numCount = sf_write_raw(myFile, (void*) data[0].recordedSamples, (data[0].finalFrame)*64);
cout << numCount << endl;
}
Looper::~Looper()
{
/* Destructor to prevent memory leak */
for (int k = 0; k < totalTracks; k++){
if( data[k].recordedSamples ) delete data[k].recordedSamples;
}
delete ui;
}
PaError Looper::error(PaError err)
{
/* Function to handle errors. It will appear throughout the code */
Pa_Terminate();
if( err != paNoError ) {
QMessageBox mbox;
mbox.setText("An unknown error occurred while using the portaudio stream!\n Definitely not our fault!\n");
mbox.exec();
}
this->~Looper();
return err;
}
void Looper::on_recordButton_clicked()
{
/* Qt Button configuration using aleready defined functions */
if(recording == false) {
startRecording(totalTracks);
recording = true;
ui->textEdit->setText("RECORDING");
ui->MicLabel->setPixmap(QPixmap(":/Resources/MicrophoneNormal.png"));
ui->recordButton->setIcon(QIcon(":/Resources/RecordPressed.png"));
ui->recordButton->setText("Stop Recording");
ui->pauseButton->setDisabled(true);
ui->stopButton->setDisabled(true);
}
else {
stopRecording(totalTracks);
startPlayback(totalTracks);
recording = false;
ui->textEdit->setText("PLAYING BACK");
if(totalTracks >= 3) {
ui->textEdit->setText("PLAYING BACK\n*Max number of tracks reached!");
ui->recordButton->setDisabled(true);
}
ui->MicLabel->setPixmap(QPixmap(":/Resources/MicrophoneDisabled.png"));
ui->recordButton->setIcon(QIcon(":/Resources/RecordNormal.png"));
ui->recordButton->setText("Record");
ui->pauseButton->setEnabled(true);
ui->stopButton->setEnabled(true);
totalTracks++;
QString TracksText = QString::number(totalTracks);
ui->textEdit_2->setText(" "+TracksText);
}
}
void Looper::on_pauseButton_clicked()
{
/* Qt Button configuration using aleready defined functions */
if (paused == false) {
pausePlayback();
paused = true;
ui->textEdit->setText("PAUSED");
ui->recordButton->setEnabled(false);
}
else {
resumePlayback();
paused = false;
ui->textEdit->setText("PLAYING BACK");
ui->recordButton->setEnabled(true);
if(totalTracks>=4) ui->recordButton->setEnabled(false);
}
}
void Looper::on_stopButton_clicked()
{
/* Qt Button configuration using aleready defined functions */
stopPlayback();
ui->textEdit->setText("STOPPED");
QString TracksText = QString::number(totalTracks);
ui->textEdit_2->setText(" "+TracksText);
ui->pauseButton->setEnabled(false);
ui->stopButton->setEnabled(false);
ui->recordButton->setEnabled(true);
}
void Looper::on_saveButton_clicked()
{
/* Qt Button configuration using aleready defined functions */
savePlayback();
ui->textEdit->setText("Playback saved to loop.wav");
}