1 /*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 // Audio loopback tests to measure the round trip latency and glitches.
18
19 #include <algorithm>
20 #include <assert.h>
21 #include <cctype>
22 #include <errno.h>
23 #include <iomanip>
24 #include <iostream>
25 #include <math.h>
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <unistd.h>
31
32 #include <aaudio/AAudio.h>
33 #include <aaudio/AAudioTesting.h>
34
35 #include "AAudioSimplePlayer.h"
36 #include "AAudioSimpleRecorder.h"
37 #include "AAudioExampleUtils.h"
38
39 // Get logging macros from OboeTester
40 #include "android_debug.h"
41 // Get signal analyzers from OboeTester
42 #include "analyzer/GlitchAnalyzer.h"
43 #include "analyzer/LatencyAnalyzer.h"
44
45 #include "../../utils/AAudioExampleUtils.h"
46
47 // V0.4.00 = rectify and low-pass filter the echos, auto-correlate entire echo
48 // V0.4.01 = add -h hang option
49 // fix -n option to set output buffer for -tm
50 // plot first glitch
51 // V0.4.02 = allow -n0 for minimal buffer size
52 // V0.5.00 = use latency analyzer copied from OboeTester, uses random noise for latency
53 // V0.5.01 = use latency analyzer directly from OboeTester in external/oboe
54 #define APP_VERSION "0.5.01"
55
56 // Tag for machine readable results as property = value pairs
57 #define RESULT_TAG "RESULT: "
58 #define FILENAME_ALL "/data/loopback_all.wav"
59 #define FILENAME_ECHOS "/data/loopback_echos.wav"
60 #define FILENAME_PROCESSED "/data/loopback_processed.wav"
61
62 constexpr int kLogPeriodMillis = 1000;
63 constexpr int kNumInputChannels = 1;
64 constexpr int kNumCallbacksToDrain = 20;
65 constexpr int kNumCallbacksToNotRead = 0; // let input fill back up
66 constexpr int kNumCallbacksToDiscard = 20;
67 constexpr int kDefaultHangTimeMillis = 50;
68 constexpr int kMaxGlitchEventsToSave = 32;
69
printAudioScope(float sample)70 static void printAudioScope(float sample) {
71 const int maxStars = 80; // arbitrary, fits on one line
72 char c = '*';
73 if (sample < -1.0) {
74 sample = -1.0;
75 c = '$';
76 } else if (sample > 1.0) {
77 sample = 1.0;
78 c = '$';
79 }
80 int numSpaces = (int) (((sample + 1.0) * 0.5) * maxStars);
81 printf("%*c%c\n", numSpaces, ' ', c);
82 }
83
84 struct LoopbackData {
85 AAudioStream *inputStream = nullptr;
86 AAudioStream *outputStream = nullptr;
87 int32_t inputFramesMaximum = 0;
88 int16_t *inputShortData = nullptr;
89 float *inputFloatData = nullptr;
90 aaudio_format_t actualInputFormat = AAUDIO_FORMAT_INVALID;
91 int32_t actualInputChannelCount = 0;
92 int32_t actualOutputChannelCount = 0;
93 int32_t numCallbacksToDrain = kNumCallbacksToDrain;
94 int32_t numCallbacksToNotRead = kNumCallbacksToNotRead;
95 int32_t numCallbacksToDiscard = kNumCallbacksToDiscard;
96 int32_t minNumFrames = INT32_MAX;
97 int32_t maxNumFrames = 0;
98 int32_t insufficientReadCount = 0;
99 int32_t insufficientReadFrames = 0;
100 int32_t framesReadTotal = 0;
101 int32_t framesWrittenTotal = 0;
102 int32_t hangPeriodMillis = 5 * 1000; // time between hangs
103 int32_t hangCountdownFrames = 5 * 48000; // frames til next hang
104 int32_t hangTimeMillis = 0; // 0 for no hang
105 bool isDone = false;
106
107 aaudio_result_t inputError = AAUDIO_OK;
108 aaudio_result_t outputError = AAUDIO_OK;
109
110 GlitchAnalyzer sineAnalyzer;
111 WhiteNoiseLatencyAnalyzer echoAnalyzer;
112 AudioRecording audioRecording;
113 LoopbackProcessor *loopbackProcessor;
114
115 int32_t glitchFrames[kMaxGlitchEventsToSave];
116 int32_t numGlitchEvents = 0;
117
hangIfRequestedLoopbackData118 void hangIfRequested(int32_t numFrames) {
119 if (hangTimeMillis > 0) {
120 hangCountdownFrames -= numFrames;
121 if (hangCountdownFrames <= 0) {
122 const int64_t startNanos = getNanoseconds();
123 usleep(hangTimeMillis * 1000);
124 const int64_t endNanos = getNanoseconds();
125 const int32_t elapsedMicros = (int32_t)
126 ((endNanos - startNanos) / 1000);
127 printf("callback hanging for %d millis, actual = %d micros\n",
128 hangTimeMillis, elapsedMicros);
129 hangCountdownFrames = (int64_t) hangPeriodMillis
130 * AAudioStream_getSampleRate(outputStream)
131 / 1000;
132 }
133 }
134
135
136 }
137 };
138
convertPcm16ToFloat(const int16_t * source,float * destination,int32_t numSamples)139 static void convertPcm16ToFloat(const int16_t *source,
140 float *destination,
141 int32_t numSamples) {
142 constexpr float scaler = 1.0f / 32768.0f;
143 for (int i = 0; i < numSamples; i++) {
144 destination[i] = source[i] * scaler;
145 }
146 }
147
148 // ====================================================================================
149 // ========================= CALLBACK =================================================
150 // ====================================================================================
151 // Callback function that fills the audio output buffer.
152
readFormattedData(LoopbackData * myData,int32_t numFrames)153 static int32_t readFormattedData(LoopbackData *myData, int32_t numFrames) {
154 int32_t framesRead = AAUDIO_ERROR_INVALID_FORMAT;
155 if (myData->actualInputFormat == AAUDIO_FORMAT_PCM_I16) {
156 framesRead = AAudioStream_read(myData->inputStream, myData->inputShortData,
157 numFrames,
158 0 /* timeoutNanoseconds */);
159 } else if (myData->actualInputFormat == AAUDIO_FORMAT_PCM_FLOAT) {
160 framesRead = AAudioStream_read(myData->inputStream, myData->inputFloatData,
161 numFrames,
162 0 /* timeoutNanoseconds */);
163 } else {
164 printf("ERROR actualInputFormat = %d\n", myData->actualInputFormat);
165 assert(false);
166 }
167 if (framesRead < 0) {
168 // Expect INVALID_STATE if STATE_STARTING
169 if (myData->framesReadTotal > 0) {
170 myData->inputError = framesRead;
171 printf("ERROR in read = %d = %s\n", framesRead,
172 AAudio_convertResultToText(framesRead));
173 } else {
174 framesRead = 0;
175 }
176 } else {
177 myData->framesReadTotal += framesRead;
178 }
179 return framesRead;
180 }
181
MyDataCallbackProc(AAudioStream * outputStream,void * userData,void * audioData,int32_t numFrames)182 static aaudio_data_callback_result_t MyDataCallbackProc(
183 AAudioStream *outputStream,
184 void *userData,
185 void *audioData,
186 int32_t numFrames
187 ) {
188 (void) outputStream;
189 aaudio_data_callback_result_t result = AAUDIO_CALLBACK_RESULT_CONTINUE;
190 LoopbackData *myData = (LoopbackData *) userData;
191 float *outputData = (float *) audioData;
192
193 // Read audio data from the input stream.
194 int32_t actualFramesRead;
195
196 if (numFrames > myData->inputFramesMaximum) {
197 myData->inputError = AAUDIO_ERROR_OUT_OF_RANGE;
198 return AAUDIO_CALLBACK_RESULT_STOP;
199 }
200
201 if (numFrames > myData->maxNumFrames) {
202 myData->maxNumFrames = numFrames;
203 }
204 if (numFrames < myData->minNumFrames) {
205 myData->minNumFrames = numFrames;
206 }
207
208 // Silence the output.
209 int32_t numBytes = numFrames * myData->actualOutputChannelCount * sizeof(float);
210 memset(audioData, 0 /* value */, numBytes);
211
212 if (myData->numCallbacksToDrain > 0) {
213 // Drain the input.
214 int32_t totalFramesRead = 0;
215 do {
216 actualFramesRead = readFormattedData(myData, numFrames);
217 if (actualFramesRead > 0) {
218 totalFramesRead += actualFramesRead;
219 } else if (actualFramesRead < 0) {
220 result = AAUDIO_CALLBACK_RESULT_STOP;
221 }
222 // Ignore errors because input stream may not be started yet.
223 } while (actualFramesRead > 0);
224 // Only counts if we actually got some data.
225 if (totalFramesRead > 0) {
226 myData->numCallbacksToDrain--;
227 }
228
229 } else if (myData->numCallbacksToNotRead > 0) {
230 // Let the input fill up a bit so we are not so close to the write pointer.
231 myData->numCallbacksToNotRead--;
232 } else if (myData->numCallbacksToDiscard > 0) {
233 // Ignore. Allow the input to fill back up to equilibrium with the output.
234 actualFramesRead = readFormattedData(myData, numFrames);
235 if (actualFramesRead < 0) {
236 result = AAUDIO_CALLBACK_RESULT_STOP;
237 }
238 myData->numCallbacksToDiscard--;
239
240 } else {
241 myData->hangIfRequested(numFrames);
242
243 int32_t numInputBytes = numFrames * myData->actualInputChannelCount * sizeof(float);
244 memset(myData->inputFloatData, 0 /* value */, numInputBytes);
245
246 // Process data after equilibrium.
247 int64_t inputFramesWritten = AAudioStream_getFramesWritten(myData->inputStream);
248 int64_t inputFramesRead = AAudioStream_getFramesRead(myData->inputStream);
249 int64_t framesAvailable = inputFramesWritten - inputFramesRead;
250
251 actualFramesRead = readFormattedData(myData, numFrames); // READ
252 if (actualFramesRead < 0) {
253 result = AAUDIO_CALLBACK_RESULT_STOP;
254 } else {
255
256 if (actualFramesRead < numFrames) {
257 if(actualFramesRead < (int32_t) framesAvailable) {
258 printf("insufficient for no reason, numFrames = %d"
259 ", actualFramesRead = %d"
260 ", inputFramesWritten = %d"
261 ", inputFramesRead = %d"
262 ", available = %d\n",
263 numFrames,
264 actualFramesRead,
265 (int) inputFramesWritten,
266 (int) inputFramesRead,
267 (int) framesAvailable);
268 }
269 myData->insufficientReadCount++;
270 myData->insufficientReadFrames += numFrames - actualFramesRead; // deficit
271 // printf("Error insufficientReadCount = %d\n",(int)myData->insufficientReadCount);
272 }
273
274 int32_t numSamples = actualFramesRead * myData->actualInputChannelCount;
275
276 if (myData->actualInputFormat == AAUDIO_FORMAT_PCM_I16) {
277 convertPcm16ToFloat(myData->inputShortData, myData->inputFloatData, numSamples);
278 }
279
280 // Analyze the data.
281 myData->loopbackProcessor->process(myData->inputFloatData,
282 myData->actualInputChannelCount,
283 numFrames,
284 outputData,
285 myData->actualOutputChannelCount,
286 numFrames);
287 //
288 // if (procResult == LoopbackProcessor::PROCESS_RESULT_GLITCH) {
289 // if (myData->numGlitchEvents < kMaxGlitchEventsToSave) {
290 // myData->glitchFrames[myData->numGlitchEvents++] = myData->audioRecording.size();
291 // }
292 // }
293
294 // Save for later.
295 myData->audioRecording.write(myData->inputFloatData,
296 myData->actualInputChannelCount,
297 actualFramesRead);
298
299 myData->isDone = myData->loopbackProcessor->isDone();
300 if (myData->isDone) {
301 result = AAUDIO_CALLBACK_RESULT_STOP;
302 }
303 }
304 }
305 myData->framesWrittenTotal += numFrames;
306
307 return result;
308 }
309
MyErrorCallbackProc(AAudioStream *,void * userData,aaudio_result_t error)310 static void MyErrorCallbackProc(
311 AAudioStream * /* stream */,
312 void * userData,
313 aaudio_result_t error) {
314 printf("Error Callback, error: %d\n",(int)error);
315 LoopbackData *myData = (LoopbackData *) userData;
316 myData->outputError = error;
317 }
318
usage()319 static void usage() {
320 printf("Usage: aaudio_loopback [OPTION]...\n\n");
321 AAudioArgsParser::usage();
322 printf(" -B{frames} input capacity in frames\n");
323 printf(" -C{channels} number of input channels\n");
324 printf(" -D{deviceId} input device ID\n");
325 printf(" -F{0,1,2} input format, 1=I16, 2=FLOAT\n");
326 printf(" -h{hangMillis} occasionally hang in the callback\n");
327 printf(" -P{inPerf} set input AAUDIO_PERFORMANCE_MODE*\n");
328 printf(" n for _NONE\n");
329 printf(" l for _LATENCY\n");
330 printf(" p for _POWER_SAVING\n");
331 printf(" -t{test} select test mode\n");
332 printf(" g for Glitch detection\n");
333 printf(" l for round trip Latency (default)\n");
334 printf(" f for file latency, analyzes %s\n\n", FILENAME_ECHOS);
335 printf(" -X use EXCLUSIVE mode for input\n");
336 printf("Example: aaudio_loopback -n2 -pl -Pl -x\n");
337 }
338
parsePerformanceMode(char c)339 static aaudio_performance_mode_t parsePerformanceMode(char c) {
340 aaudio_performance_mode_t mode = AAUDIO_ERROR_ILLEGAL_ARGUMENT;
341 c = tolower(c);
342 switch (c) {
343 case 'n':
344 mode = AAUDIO_PERFORMANCE_MODE_NONE;
345 break;
346 case 'l':
347 mode = AAUDIO_PERFORMANCE_MODE_LOW_LATENCY;
348 break;
349 case 'p':
350 mode = AAUDIO_PERFORMANCE_MODE_POWER_SAVING;
351 break;
352 default:
353 printf("ERROR in value performance mode %c\n", c);
354 break;
355 }
356 return mode;
357 }
358
359 enum {
360 TEST_GLITCHES = 0,
361 TEST_LATENCY,
362 TEST_FILE_LATENCY,
363 };
364
parseTestMode(char c)365 static int parseTestMode(char c) {
366 int testMode = TEST_LATENCY;
367 c = tolower(c);
368 switch (c) {
369 case 'm': // deprecated
370 case 'g':
371 testMode = TEST_GLITCHES;
372 break;
373 case 'e': // deprecated
374 case 'l':
375 testMode = TEST_LATENCY;
376 break;
377 case 'f':
378 testMode = TEST_FILE_LATENCY;
379 break;
380 default:
381 printf("ERROR in value test mode %c\n", c);
382 break;
383 }
384 return testMode;
385 }
386
printAudioGraphRegion(AudioRecording & recording,int32_t start,int32_t end)387 void printAudioGraphRegion(AudioRecording &recording, int32_t start, int32_t end) {
388 if (end >= recording.size()) {
389 end = recording.size() - 1;
390 }
391 float *data = recording.getData();
392 // Normalize data so we can see it better.
393 float maxSample = 0.01;
394 for (int32_t i = start; i < end; i++) {
395 float samplePos = fabs(data[i]);
396 if (samplePos > maxSample) {
397 maxSample = samplePos;
398 }
399 }
400 float gain = 0.98f / maxSample;
401
402 for (int32_t i = start; i < end; i++) {
403 float sample = data[i];
404 printf("%6d: %7.4f ", i, sample); // actual value
405 sample *= gain;
406 printAudioScope(sample);
407 }
408 }
409
410
411 // ====================================================================================
412 // TODO break up this large main() function into smaller functions
main(int argc,const char ** argv)413 int main(int argc, const char **argv)
414 {
415
416 AAudioArgsParser argParser;
417 AAudioSimplePlayer player;
418 AAudioSimpleRecorder recorder;
419 LoopbackData loopbackData;
420 AAudioStream *inputStream = nullptr;
421 AAudioStream *outputStream = nullptr;
422
423 aaudio_result_t result = AAUDIO_OK;
424 int32_t requestedInputDeviceId = AAUDIO_UNSPECIFIED;
425 aaudio_sharing_mode_t requestedInputSharingMode = AAUDIO_SHARING_MODE_SHARED;
426 int requestedInputChannelCount = kNumInputChannels;
427 aaudio_format_t requestedInputFormat = AAUDIO_FORMAT_UNSPECIFIED;
428 int32_t requestedInputCapacity = AAUDIO_UNSPECIFIED;
429 aaudio_performance_mode_t inputPerformanceLevel = AAUDIO_PERFORMANCE_MODE_LOW_LATENCY;
430
431 int32_t outputFramesPerBurst = 0;
432
433 aaudio_format_t actualOutputFormat = AAUDIO_FORMAT_INVALID;
434 int32_t actualSampleRate = 0;
435 int written = 0;
436
437 int testMode = TEST_LATENCY;
438 int hangTimeMillis = 0;
439 std::string report;
440
441 // Make printf print immediately so that debug info is not stuck
442 // in a buffer if we hang or crash.
443 setvbuf(stdout, NULL, _IONBF, (size_t) 0);
444
445 printf("%s - Audio loopback using AAudio V" APP_VERSION "\n", argv[0]);
446
447 // Use LOW_LATENCY as the default to match input default.
448 argParser.setPerformanceMode(AAUDIO_PERFORMANCE_MODE_LOW_LATENCY);
449
450 for (int i = 1; i < argc; i++) {
451 const char *arg = argv[i];
452 if (argParser.parseArg(arg)) {
453 // Handle options that are not handled by the ArgParser
454 if (arg[0] == '-') {
455 char option = arg[1];
456 switch (option) {
457 case 'B':
458 requestedInputCapacity = atoi(&arg[2]);
459 break;
460 case 'C':
461 requestedInputChannelCount = atoi(&arg[2]);
462 break;
463 case 'D':
464 requestedInputDeviceId = atoi(&arg[2]);
465 break;
466 case 'F':
467 requestedInputFormat = atoi(&arg[2]);
468 break;
469 case 'h':
470 // Was there a number after the "-h"?
471 if (arg[2]) {
472 hangTimeMillis = atoi(&arg[2]);
473 } else {
474 // If no number then use the default.
475 hangTimeMillis = kDefaultHangTimeMillis;
476 }
477 break;
478 case 'P':
479 inputPerformanceLevel = parsePerformanceMode(arg[2]);
480 break;
481 case 'X':
482 requestedInputSharingMode = AAUDIO_SHARING_MODE_EXCLUSIVE;
483 break;
484 case 't':
485 testMode = parseTestMode(arg[2]);
486 break;
487 default:
488 usage();
489 exit(EXIT_FAILURE);
490 break;
491 }
492 } else {
493 usage();
494 exit(EXIT_FAILURE);
495 break;
496 }
497 }
498
499 }
500
501 if (inputPerformanceLevel < 0) {
502 printf("illegal inputPerformanceLevel = %d\n", inputPerformanceLevel);
503 exit(EXIT_FAILURE);
504 }
505
506 int32_t requestedDuration = argParser.getDurationSeconds();
507 int32_t requestedDurationMillis = requestedDuration * kMillisPerSecond;
508 int32_t timeMillis = 0;
509 int32_t recordingDuration = std::min(60 * 5, requestedDuration);
510
511 int32_t requestedOutputBursts = argParser.getNumberOfBursts();
512
513 switch(testMode) {
514 case TEST_GLITCHES:
515 loopbackData.loopbackProcessor = &loopbackData.sineAnalyzer;
516 break;
517 case TEST_LATENCY:
518 // TODO loopbackData.echoAnalyzer.setGain(gain);
519 loopbackData.loopbackProcessor = &loopbackData.echoAnalyzer;
520 break;
521 case TEST_FILE_LATENCY: {
522 // TODO loopbackData.echoAnalyzer.setGain(gain);
523 loopbackData.loopbackProcessor = &loopbackData.echoAnalyzer;
524 int read = loopbackData.loopbackProcessor->load(FILENAME_ECHOS);
525 printf("main() read %d mono samples from %s on Android device, rate = %d\n",
526 read, FILENAME_ECHOS,
527 loopbackData.loopbackProcessor->getSampleRate());
528 std::cout << loopbackData.loopbackProcessor->analyze();
529 goto report_result;
530 }
531 break;
532 default:
533 exit(1);
534 break;
535 }
536
537 printf("OUTPUT stream ----------------------------------------\n");
538 result = player.open(argParser, MyDataCallbackProc, MyErrorCallbackProc, &loopbackData);
539 if (result != AAUDIO_OK) {
540 fprintf(stderr, "ERROR - player.open() returned %d\n", result);
541 exit(1);
542 }
543 outputStream = loopbackData.outputStream = player.getStream();
544
545 actualOutputFormat = AAudioStream_getFormat(outputStream);
546 if (actualOutputFormat != AAUDIO_FORMAT_PCM_FLOAT) {
547 fprintf(stderr, "ERROR - only AAUDIO_FORMAT_PCM_FLOAT supported\n");
548 exit(1);
549 }
550
551 actualSampleRate = AAudioStream_getSampleRate(outputStream);
552 loopbackData.audioRecording.allocate(recordingDuration * actualSampleRate);
553 loopbackData.audioRecording.setSampleRate(actualSampleRate);
554 outputFramesPerBurst = AAudioStream_getFramesPerBurst(outputStream);
555
556 argParser.compareWithStream(outputStream);
557
558 printf("INPUT stream ----------------------------------------\n");
559 // Use different parameters for the input.
560 argParser.setDeviceId(requestedInputDeviceId);
561 argParser.setNumberOfBursts(AAudioParameters::kDefaultNumberOfBursts);
562 argParser.setFormat(requestedInputFormat);
563 argParser.setPerformanceMode(inputPerformanceLevel);
564 argParser.setChannelCount(requestedInputChannelCount);
565 argParser.setSharingMode(requestedInputSharingMode);
566 if (requestedInputCapacity != AAUDIO_UNSPECIFIED) {
567 printf("Warning! If you set input capacity then maybe no FAST track on Legacy path!\n");
568 }
569 argParser.setBufferCapacity(requestedInputCapacity);
570
571 result = recorder.open(argParser);
572 if (result != AAUDIO_OK) {
573 fprintf(stderr, "ERROR - recorder.open() returned %d\n", result);
574 goto finish;
575 }
576 inputStream = loopbackData.inputStream = recorder.getStream();
577
578 {
579 int32_t actualCapacity = AAudioStream_getBufferCapacityInFrames(inputStream);
580 (void) AAudioStream_setBufferSizeInFrames(inputStream, actualCapacity);
581
582 if (testMode == TEST_GLITCHES
583 && requestedOutputBursts == AAUDIO_UNSPECIFIED) {
584 result = AAudioStream_setBufferSizeInFrames(outputStream, actualCapacity);
585 if (result < 0) {
586 fprintf(stderr, "ERROR - AAudioStream_setBufferSizeInFrames(output) returned %d\n",
587 result);
588 goto finish;
589 } else {
590 printf("Output buffer size set to match input capacity = %d frames!\n", result);
591 }
592 }
593
594 // If the input stream is too small then we cannot satisfy the output callback.
595 if (actualCapacity < 2 * outputFramesPerBurst) {
596 fprintf(stderr, "ERROR - input capacity < 2 * outputFramesPerBurst\n");
597 goto finish;
598 }
599 }
600
601 argParser.compareWithStream(inputStream);
602
603 // ------- Setup loopbackData -----------------------------
604 loopbackData.actualInputFormat = AAudioStream_getFormat(inputStream);
605
606 loopbackData.actualInputChannelCount = recorder.getChannelCount();
607 loopbackData.actualOutputChannelCount = player.getChannelCount();
608
609 // Allocate a buffer for the audio data.
610 loopbackData.inputFramesMaximum = 32 * AAudioStream_getFramesPerBurst(inputStream);
611
612 if (loopbackData.actualInputFormat == AAUDIO_FORMAT_PCM_I16) {
613 loopbackData.inputShortData = new int16_t[loopbackData.inputFramesMaximum
614 * loopbackData.actualInputChannelCount]{};
615 }
616 loopbackData.inputFloatData = new float[loopbackData.inputFramesMaximum *
617 loopbackData.actualInputChannelCount]{};
618
619 loopbackData.hangTimeMillis = hangTimeMillis;
620
621 loopbackData.loopbackProcessor->prepareToTest();
622
623 // Start OUTPUT first so INPUT does not overflow.
624 result = player.start();
625 if (result != AAUDIO_OK) {
626 goto finish;
627 }
628
629 result = recorder.start();
630 if (result != AAUDIO_OK) {
631 goto finish;
632 }
633
634 printf("------- sleep and log while the callback runs --------------\n");
635 while (timeMillis <= requestedDurationMillis) {
636 if (loopbackData.inputError != AAUDIO_OK) {
637 printf(" ERROR on input stream\n");
638 break;
639 } else if (loopbackData.outputError != AAUDIO_OK) {
640 printf(" ERROR on output stream\n");
641 break;
642 } else if (loopbackData.isDone) {
643 printf(" Test says it is DONE!\n");
644 break;
645 } else {
646 // Log a line of stream data.
647 printf("%7.3f: ", 0.001 * timeMillis); // display in seconds
648 loopbackData.loopbackProcessor->printStatus();
649 printf(" insf %3d,", (int) loopbackData.insufficientReadCount);
650
651 int64_t inputFramesWritten = AAudioStream_getFramesWritten(inputStream);
652 int64_t inputFramesRead = AAudioStream_getFramesRead(inputStream);
653 int64_t outputFramesWritten = AAudioStream_getFramesWritten(outputStream);
654 int64_t outputFramesRead = AAudioStream_getFramesRead(outputStream);
655 static const int textOffset = strlen("AAUDIO_STREAM_STATE_"); // strip this off
656 printf(" | INPUT: wr %7lld - rd %7lld = %5lld, st %8s, oruns %3d",
657 (long long) inputFramesWritten,
658 (long long) inputFramesRead,
659 (long long) (inputFramesWritten - inputFramesRead),
660 &AAudio_convertStreamStateToText(
661 AAudioStream_getState(inputStream))[textOffset],
662 AAudioStream_getXRunCount(inputStream));
663
664 printf(" | OUTPUT: wr %7lld - rd %7lld = %5lld, st %8s, uruns %3d\n",
665 (long long) outputFramesWritten,
666 (long long) outputFramesRead,
667 (long long) (outputFramesWritten - outputFramesRead),
668 &AAudio_convertStreamStateToText(
669 AAudioStream_getState(outputStream))[textOffset],
670 AAudioStream_getXRunCount(outputStream)
671 );
672 }
673 int32_t periodMillis = (timeMillis < 2000) ? kLogPeriodMillis / 4 : kLogPeriodMillis;
674 usleep(periodMillis * 1000);
675 timeMillis += periodMillis;
676 }
677
678 result = player.stop();
679 if (result != AAUDIO_OK) {
680 printf("ERROR - player.stop() returned %d = %s\n",
681 result, AAudio_convertResultToText(result));
682 goto finish;
683 }
684
685 result = recorder.stop();
686 if (result != AAUDIO_OK) {
687 printf("ERROR - recorder.stop() returned %d = %s\n",
688 result, AAudio_convertResultToText(result));
689 goto finish;
690 }
691
692 printf("input error = %d = %s\n",
693 loopbackData.inputError, AAudio_convertResultToText(loopbackData.inputError));
694 /*
695 // TODO Restore this code some day if we want to save files.
696 written = loopbackData.loopbackProcessor->save(FILENAME_ECHOS);
697 if (written > 0) {
698 printf("main() wrote %8d mono samples to \"%s\" on Android device\n",
699 written, FILENAME_ECHOS);
700 }
701
702 written = loopbackData.audioRecording.save(FILENAME_ALL);
703 if (written > 0) {
704 printf("main() wrote %8d mono samples to \"%s\" on Android device\n",
705 written, FILENAME_ALL);
706 }
707 */
708 if (loopbackData.inputError == AAUDIO_OK) {
709 if (testMode == TEST_GLITCHES) {
710 if (loopbackData.numGlitchEvents > 0) {
711 // Graph around the first glitch if there is one.
712 const int32_t start = loopbackData.glitchFrames[0] - 8;
713 const int32_t end = start + outputFramesPerBurst + 8 + 8;
714 printAudioGraphRegion(loopbackData.audioRecording, start, end);
715 } else {
716 // Or graph the middle of the signal.
717 const int32_t start = loopbackData.audioRecording.size() / 2;
718 const int32_t end = start + 200;
719 printAudioGraphRegion(loopbackData.audioRecording, start, end);
720 }
721 }
722
723 std::cout << "Please wait several seconds for analysis to complete.\n";
724 std::cout << loopbackData.loopbackProcessor->analyze();
725 }
726
727 {
728 int32_t framesRead = AAudioStream_getFramesRead(inputStream);
729 int32_t framesWritten = AAudioStream_getFramesWritten(inputStream);
730 const int64_t framesAvailable = framesWritten - framesRead;
731 printf("Callback Results ---------------------------------------- INPUT\n");
732 printf(" input overruns = %8d\n", AAudioStream_getXRunCount(inputStream));
733 printf(" framesWritten = %8d\n", framesWritten);
734 printf(" framesRead = %8d\n", framesRead);
735 printf(" myFramesRead = %8d\n", (int) loopbackData.framesReadTotal);
736 printf(" written - read = %8d\n", (int) framesAvailable);
737 printf(" insufficient # = %8d\n", (int) loopbackData.insufficientReadCount);
738 if (loopbackData.insufficientReadCount > 0) {
739 printf(" insuffic. frames = %8d\n", (int) loopbackData.insufficientReadFrames);
740 }
741 int32_t actualInputCapacity = AAudioStream_getBufferCapacityInFrames(inputStream);
742 if (framesAvailable > 2 * actualInputCapacity) {
743 printf(" WARNING: written - read > 2*capacity !\n");
744 }
745 }
746
747 {
748 int32_t framesRead = AAudioStream_getFramesRead(outputStream);
749 int32_t framesWritten = AAudioStream_getFramesWritten(outputStream);
750 printf("Callback Results ---------------------------------------- OUTPUT\n");
751 printf(" output underruns = %8d\n", AAudioStream_getXRunCount(outputStream));
752 printf(" myFramesWritten = %8d\n", (int) loopbackData.framesWrittenTotal);
753 printf(" framesWritten = %8d\n", framesWritten);
754 printf(" framesRead = %8d\n", framesRead);
755 printf(" min numFrames = %8d\n", (int) loopbackData.minNumFrames);
756 printf(" max numFrames = %8d\n", (int) loopbackData.maxNumFrames);
757 }
758
759 if (loopbackData.insufficientReadCount > 3) {
760 printf("ERROR: LOOPBACK PROCESSING FAILED. insufficientReadCount too high\n");
761 result = AAUDIO_ERROR_UNAVAILABLE;
762 }
763
764 finish:
765 player.close();
766 recorder.close();
767 delete[] loopbackData.inputFloatData;
768 delete[] loopbackData.inputShortData;
769
770 report_result:
771
772 for (int i = 0; i < loopbackData.numGlitchEvents; i++) {
773 printf(" glitch at frame %d\n", loopbackData.glitchFrames[i]);
774 }
775
776 written = loopbackData.loopbackProcessor->save(FILENAME_PROCESSED);
777 if (written > 0) {
778 printf("main() wrote %8d processed samples to \"%s\" on Android device\n",
779 written, FILENAME_PROCESSED);
780 }
781
782 if (loopbackData.loopbackProcessor->getResult() < 0) {
783 result = loopbackData.loopbackProcessor->getResult();
784 }
785 printf(RESULT_TAG "result = %d \n", result); // machine readable
786 printf("result is %s\n", AAudio_convertResultToText(result)); // human readable
787 if (result != AAUDIO_OK) {
788 printf("TEST FAILED\n");
789 return EXIT_FAILURE;
790 } else {
791 printf("TEST PASSED\n");
792 return EXIT_SUCCESS;
793 }
794 }
795