blob: 4373fa9b9a67cd97b8c3231fb00c5246b664871b [file] [log] [blame]
Eric Laurent629afae2017-05-25 18:25:51 -07001/*
2 * Copyright (C) 2017 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// Play sine waves using an AAudio callback.
18
19#ifndef AAUDIO_SIMPLE_PLAYER_H
20#define AAUDIO_SIMPLE_PLAYER_H
21
Eric Laurent629afae2017-05-25 18:25:51 -070022#include <sched.h>
Phil Burk67ed9da2017-09-06 16:26:52 -070023#include <unistd.h>
Eric Laurent629afae2017-05-25 18:25:51 -070024
25#include <aaudio/AAudio.h>
Phil Burk44795232017-06-30 16:27:38 -070026#include "AAudioArgsParser.h"
Eric Laurent629afae2017-05-25 18:25:51 -070027#include "SineGenerator.h"
28
29//#define SHARING_MODE AAUDIO_SHARING_MODE_EXCLUSIVE
30#define SHARING_MODE AAUDIO_SHARING_MODE_SHARED
31#define PERFORMANCE_MODE AAUDIO_PERFORMANCE_MODE_NONE
32
Phil Burk967abf82017-11-21 10:02:34 -080033// Arbitrary period for glitches
34#define FORCED_UNDERRUN_PERIOD_FRAMES (2 * 48000)
Phil Burkfaeb8b22017-07-25 15:15:07 -070035
Phil Burk67ed9da2017-09-06 16:26:52 -070036#define MAX_TIMESTAMPS 16
Phil Burk187dcd42017-08-29 09:04:35 -070037
38typedef struct Timestamp {
39 int64_t position;
40 int64_t nanoseconds;
41} Timestamp;
42
Eric Laurent629afae2017-05-25 18:25:51 -070043/**
44 * Simple wrapper for AAudio that opens an output stream either in callback or blocking write mode.
45 */
46class AAudioSimplePlayer {
47public:
48 AAudioSimplePlayer() {}
49 ~AAudioSimplePlayer() {
50 close();
51 };
52
53 /**
54 * Call this before calling open().
55 * @param requestedSharingMode
56 */
57 void setSharingMode(aaudio_sharing_mode_t requestedSharingMode) {
58 mRequestedSharingMode = requestedSharingMode;
59 }
60
61 /**
62 * Call this before calling open().
63 * @param requestedPerformanceMode
64 */
65 void setPerformanceMode(aaudio_performance_mode_t requestedPerformanceMode) {
66 mRequestedPerformanceMode = requestedPerformanceMode;
67 }
68
Phil Burk44795232017-06-30 16:27:38 -070069 // TODO Extract a common base class for record and playback.
Phil Burk44795232017-06-30 16:27:38 -070070
71 /**
72 * Only call this after open() has been called.
73 */
74 int32_t getSampleRate() const {
Eric Laurent629afae2017-05-25 18:25:51 -070075 if (mStream == nullptr) {
76 return AAUDIO_ERROR_INVALID_STATE;
77 }
Phil Burk44795232017-06-30 16:27:38 -070078 return AAudioStream_getSampleRate(mStream);
Eric Laurent629afae2017-05-25 18:25:51 -070079 }
80
81 /**
82 * Only call this after open() has been called.
83 */
84 int32_t getChannelCount() {
85 if (mStream == nullptr) {
86 return AAUDIO_ERROR_INVALID_STATE;
87 }
Phil Burk44795232017-06-30 16:27:38 -070088 return AAudioStream_getChannelCount(mStream);
Eric Laurent629afae2017-05-25 18:25:51 -070089 }
90
91 /**
92 * Open a stream
93 */
Phil Burk44795232017-06-30 16:27:38 -070094 aaudio_result_t open(const AAudioParameters &parameters,
95 AAudioStream_dataCallback dataCallback = nullptr,
96 AAudioStream_errorCallback errorCallback = nullptr,
97 void *userContext = nullptr) {
98 aaudio_result_t result = AAUDIO_OK;
99
100 // Use an AAudioStreamBuilder to contain requested parameters.
101 AAudioStreamBuilder *builder = nullptr;
102 result = AAudio_createStreamBuilder(&builder);
103 if (result != AAUDIO_OK) return result;
104
105 parameters.applyParameters(builder); // apply args
106
107 AAudioStreamBuilder_setDirection(builder, AAUDIO_DIRECTION_OUTPUT);
108
109 if (dataCallback != nullptr) {
110 AAudioStreamBuilder_setDataCallback(builder, dataCallback, userContext);
111 }
112 if (errorCallback != nullptr) {
113 AAudioStreamBuilder_setErrorCallback(builder, errorCallback, userContext);
114 }
115 //AAudioStreamBuilder_setFramesPerDataCallback(builder, CALLBACK_SIZE_FRAMES);
116 //AAudioStreamBuilder_setBufferCapacityInFrames(builder, 48 * 8);
117
118 // Open an AAudioStream using the Builder.
119 result = AAudioStreamBuilder_openStream(builder, &mStream);
120
121 if (result == AAUDIO_OK) {
122 int32_t sizeInBursts = parameters.getNumberOfBursts();
123 if (sizeInBursts > 0) {
124 int32_t framesPerBurst = AAudioStream_getFramesPerBurst(mStream);
125 AAudioStream_setBufferSizeInFrames(mStream, sizeInBursts * framesPerBurst);
126 }
127 }
128
129 AAudioStreamBuilder_delete(builder);
130 return result;
131 }
132
Eric Laurent629afae2017-05-25 18:25:51 -0700133 aaudio_result_t open(int channelCount, int sampSampleRate, aaudio_format_t format,
Phil Burk44795232017-06-30 16:27:38 -0700134 AAudioStream_dataCallback dataProc,
135 AAudioStream_errorCallback errorProc,
Eric Laurent629afae2017-05-25 18:25:51 -0700136 void *userContext) {
137 aaudio_result_t result = AAUDIO_OK;
138
139 // Use an AAudioStreamBuilder to contain requested parameters.
Phil Burk44795232017-06-30 16:27:38 -0700140 AAudioStreamBuilder *builder = nullptr;
141 result = AAudio_createStreamBuilder(&builder);
Eric Laurent629afae2017-05-25 18:25:51 -0700142 if (result != AAUDIO_OK) return result;
143
Phil Burk44795232017-06-30 16:27:38 -0700144 AAudioStreamBuilder_setDirection(builder, AAUDIO_DIRECTION_OUTPUT);
145 AAudioStreamBuilder_setPerformanceMode(builder, mRequestedPerformanceMode);
146 AAudioStreamBuilder_setSharingMode(builder, mRequestedSharingMode);
147
148 AAudioStreamBuilder_setChannelCount(builder, channelCount);
149 AAudioStreamBuilder_setSampleRate(builder, sampSampleRate);
150 AAudioStreamBuilder_setFormat(builder, format);
151
Eric Laurent629afae2017-05-25 18:25:51 -0700152 if (dataProc != nullptr) {
Phil Burk44795232017-06-30 16:27:38 -0700153 AAudioStreamBuilder_setDataCallback(builder, dataProc, userContext);
Eric Laurent629afae2017-05-25 18:25:51 -0700154 }
155 if (errorProc != nullptr) {
Phil Burk44795232017-06-30 16:27:38 -0700156 AAudioStreamBuilder_setErrorCallback(builder, errorProc, userContext);
Eric Laurent629afae2017-05-25 18:25:51 -0700157 }
Phil Burk44795232017-06-30 16:27:38 -0700158 //AAudioStreamBuilder_setFramesPerDataCallback(builder, CALLBACK_SIZE_FRAMES);
159 //AAudioStreamBuilder_setBufferCapacityInFrames(builder, 48 * 8);
Eric Laurent629afae2017-05-25 18:25:51 -0700160
161 // Open an AAudioStream using the Builder.
Phil Burk44795232017-06-30 16:27:38 -0700162 result = AAudioStreamBuilder_openStream(builder, &mStream);
Eric Laurent629afae2017-05-25 18:25:51 -0700163
Phil Burk44795232017-06-30 16:27:38 -0700164 AAudioStreamBuilder_delete(builder);
Phil Burk67ed9da2017-09-06 16:26:52 -0700165
Eric Laurent629afae2017-05-25 18:25:51 -0700166 return result;
167 }
168
169 aaudio_result_t close() {
170 if (mStream != nullptr) {
Eric Laurent629afae2017-05-25 18:25:51 -0700171 AAudioStream_close(mStream);
172 mStream = nullptr;
Eric Laurent629afae2017-05-25 18:25:51 -0700173 }
174 return AAUDIO_OK;
175 }
176
177 // Write zero data to fill up the buffer and prevent underruns.
178 aaudio_result_t prime() {
179 int32_t samplesPerFrame = AAudioStream_getChannelCount(mStream);
180 const int numFrames = 32;
181 float zeros[numFrames * samplesPerFrame];
182 memset(zeros, 0, sizeof(zeros));
183 aaudio_result_t result = numFrames;
184 while (result == numFrames) {
185 result = AAudioStream_write(mStream, zeros, numFrames, 0);
186 }
187 return result;
188 }
189
190 // Start the stream. AAudio will start calling your callback function.
191 aaudio_result_t start() {
192 aaudio_result_t result = AAudioStream_requestStart(mStream);
193 if (result != AAUDIO_OK) {
Phil Burk5bce4c92018-10-18 09:29:14 -0700194 printf("ERROR - AAudioStream_requestStart(output) returned %d %s\n",
Eric Laurent629afae2017-05-25 18:25:51 -0700195 result, AAudio_convertResultToText(result));
196 }
197 return result;
198 }
199
200 // Stop the stream. AAudio will stop calling your callback function.
201 aaudio_result_t stop() {
202 aaudio_result_t result = AAudioStream_requestStop(mStream);
203 if (result != AAUDIO_OK) {
Phil Burk5bce4c92018-10-18 09:29:14 -0700204 printf("ERROR - AAudioStream_requestStop(output) returned %d %s\n",
Phil Burk67ed9da2017-09-06 16:26:52 -0700205 result, AAudio_convertResultToText(result));
Eric Laurent629afae2017-05-25 18:25:51 -0700206 }
207 int32_t xRunCount = AAudioStream_getXRunCount(mStream);
208 printf("AAudioStream_getXRunCount %d\n", xRunCount);
209 return result;
210 }
211
Phil Burk67ed9da2017-09-06 16:26:52 -0700212 // Pause the stream. AAudio will stop calling your callback function.
213 aaudio_result_t pause() {
214 aaudio_result_t result = AAudioStream_requestPause(mStream);
215 if (result != AAUDIO_OK) {
Phil Burk5bce4c92018-10-18 09:29:14 -0700216 printf("ERROR - AAudioStream_requestPause(output) returned %d %s\n",
Phil Burk67ed9da2017-09-06 16:26:52 -0700217 result, AAudio_convertResultToText(result));
218 }
219 int32_t xRunCount = AAudioStream_getXRunCount(mStream);
220 printf("AAudioStream_getXRunCount %d\n", xRunCount);
221 return result;
222 }
223
Phil Burk45ebf852018-10-11 12:28:54 -0700224 aaudio_result_t waitUntilPaused() {
225 aaudio_result_t result = AAUDIO_OK;
226 aaudio_stream_state_t currentState = AAudioStream_getState(mStream);
227 aaudio_stream_state_t inputState = AAUDIO_STREAM_STATE_PAUSING;
228 while (result == AAUDIO_OK && currentState == AAUDIO_STREAM_STATE_PAUSING) {
229 result = AAudioStream_waitForStateChange(mStream, inputState,
230 &currentState, NANOS_PER_SECOND);
231 inputState = currentState;
232 }
233 if (result != AAUDIO_OK) {
234 return result;
235 }
236 return (currentState == AAUDIO_STREAM_STATE_PAUSED)
237 ? AAUDIO_OK : AAUDIO_ERROR_INVALID_STATE;
238 }
239
Phil Burk67ed9da2017-09-06 16:26:52 -0700240 // Flush the stream. AAudio will stop calling your callback function.
241 aaudio_result_t flush() {
242 aaudio_result_t result = AAudioStream_requestFlush(mStream);
243 if (result != AAUDIO_OK) {
Phil Burk5bce4c92018-10-18 09:29:14 -0700244 printf("ERROR - AAudioStream_requestFlush(output) returned %d %s\n",
Phil Burk67ed9da2017-09-06 16:26:52 -0700245 result, AAudio_convertResultToText(result));
246 }
247 return result;
248 }
249
Eric Laurent629afae2017-05-25 18:25:51 -0700250 AAudioStream *getStream() const {
251 return mStream;
252 }
253
254private:
Eric Laurent629afae2017-05-25 18:25:51 -0700255 AAudioStream *mStream = nullptr;
256 aaudio_sharing_mode_t mRequestedSharingMode = SHARING_MODE;
257 aaudio_performance_mode_t mRequestedPerformanceMode = PERFORMANCE_MODE;
Phil Burk7a61a3a2017-07-10 11:53:09 -0700258
Eric Laurent629afae2017-05-25 18:25:51 -0700259};
260
261typedef struct SineThreadedData_s {
Phil Burk7a61a3a2017-07-10 11:53:09 -0700262
Phil Burk67ed9da2017-09-06 16:26:52 -0700263 SineGenerator sineOscillators[MAX_CHANNELS];
264 Timestamp timestamps[MAX_TIMESTAMPS];
265 int64_t framesTotal = 0;
266 int64_t nextFrameToGlitch = FORCED_UNDERRUN_PERIOD_FRAMES;
267 int32_t minNumFrames = INT32_MAX;
268 int32_t maxNumFrames = 0;
269 int32_t timestampCount = 0; // in timestamps
270 int32_t sampleRate = 48000;
271 int32_t prefixToneFrames = 0;
272 bool sweepSetup = false;
Phil Burk7a61a3a2017-07-10 11:53:09 -0700273
Phil Burk67ed9da2017-09-06 16:26:52 -0700274 int scheduler = 0;
275 bool schedulerChecked = false;
Phil Burkf1533002019-02-07 13:04:28 -0800276 int32_t hangTimeMSec = 0;
Phil Burk7a61a3a2017-07-10 11:53:09 -0700277
278 AAudioSimplePlayer simplePlayer;
279 int32_t callbackCount = 0;
280 WakeUp waker{AAUDIO_OK};
281
Phil Burk67ed9da2017-09-06 16:26:52 -0700282 /**
283 * Set sampleRate first.
284 */
285 void setupSineBlip() {
286 for (int i = 0; i < MAX_CHANNELS; ++i) {
287 double centerFrequency = 880.0 * (i + 2);
288 sineOscillators[i].setup(centerFrequency, sampleRate);
289 sineOscillators[i].setSweep(centerFrequency, centerFrequency, 0.0);
290 }
291 }
292
293 void setupSineSweeps() {
294 for (int i = 0; i < MAX_CHANNELS; ++i) {
295 double centerFrequency = 220.0 * (i + 2);
296 sineOscillators[i].setup(centerFrequency, sampleRate);
297 double minFrequency = centerFrequency * 2.0 / 3.0;
298 // Change range slightly so they will go out of phase.
299 double maxFrequency = centerFrequency * 3.0 / 2.0;
300 double sweepSeconds = 5.0 + i;
301 sineOscillators[i].setSweep(minFrequency, maxFrequency, sweepSeconds);
302 }
303 sweepSetup = true;
304 }
305
Eric Laurent629afae2017-05-25 18:25:51 -0700306} SineThreadedData_t;
307
308// Callback function that fills the audio output buffer.
309aaudio_data_callback_result_t SimplePlayerDataCallbackProc(
310 AAudioStream *stream,
311 void *userData,
312 void *audioData,
313 int32_t numFrames
314 ) {
315
316 // should not happen but just in case...
317 if (userData == nullptr) {
Phil Burkfaeb8b22017-07-25 15:15:07 -0700318 printf("ERROR - SimplePlayerDataCallbackProc needs userData\n");
Eric Laurent629afae2017-05-25 18:25:51 -0700319 return AAUDIO_CALLBACK_RESULT_STOP;
320 }
321 SineThreadedData_t *sineData = (SineThreadedData_t *) userData;
322
Phil Burk67ed9da2017-09-06 16:26:52 -0700323 // Play an initial high tone so we can tell whether the beginning was truncated.
324 if (!sineData->sweepSetup && sineData->framesTotal >= sineData->prefixToneFrames) {
325 sineData->setupSineSweeps();
326 }
Phil Burkfaeb8b22017-07-25 15:15:07 -0700327
Phil Burkf1533002019-02-07 13:04:28 -0800328 if (sineData->hangTimeMSec > 0) {
Phil Burkfaeb8b22017-07-25 15:15:07 -0700329 if (sineData->framesTotal > sineData->nextFrameToGlitch) {
Phil Burkf1533002019-02-07 13:04:28 -0800330 usleep(sineData->hangTimeMSec * 1000);
331 printf("Hang callback at %lld frames for %d msec\n",
332 (long long) sineData->framesTotal,
333 sineData->hangTimeMSec);
Phil Burkfaeb8b22017-07-25 15:15:07 -0700334 sineData->nextFrameToGlitch += FORCED_UNDERRUN_PERIOD_FRAMES;
335 }
336 }
337
Eric Laurent629afae2017-05-25 18:25:51 -0700338 if (!sineData->schedulerChecked) {
339 sineData->scheduler = sched_getscheduler(gettid());
340 sineData->schedulerChecked = true;
341 }
342
Phil Burk187dcd42017-08-29 09:04:35 -0700343 if (sineData->timestampCount < MAX_TIMESTAMPS) {
344 Timestamp *timestamp = &sineData->timestamps[sineData->timestampCount];
345 aaudio_result_t result = AAudioStream_getTimestamp(stream,
346 CLOCK_MONOTONIC, &timestamp->position, &timestamp->nanoseconds);
347 if (result == AAUDIO_OK && // valid?
348 (sineData->timestampCount == 0 || // first one?
349 (timestamp->position != (timestamp - 1)->position))) { // advanced position?
350 sineData->timestampCount++; // keep this one
351 }
352 }
353
Phil Burkfcf9efd2017-07-14 08:25:08 -0700354 if (numFrames > sineData->maxNumFrames) {
355 sineData->maxNumFrames = numFrames;
356 }
357 if (numFrames < sineData->minNumFrames) {
358 sineData->minNumFrames = numFrames;
359 }
360
Eric Laurent629afae2017-05-25 18:25:51 -0700361 int32_t samplesPerFrame = AAudioStream_getChannelCount(stream);
Phil Burk67ed9da2017-09-06 16:26:52 -0700362
363
364 int numActiveOscilators = (samplesPerFrame > MAX_CHANNELS) ? MAX_CHANNELS : samplesPerFrame;
Eric Laurent629afae2017-05-25 18:25:51 -0700365 switch (AAudioStream_getFormat(stream)) {
366 case AAUDIO_FORMAT_PCM_I16: {
367 int16_t *audioBuffer = (int16_t *) audioData;
Phil Burk67ed9da2017-09-06 16:26:52 -0700368 for (int i = 0; i < numActiveOscilators; ++i) {
369 sineData->sineOscillators[i].render(&audioBuffer[i], samplesPerFrame,
370 numFrames);
Eric Laurent629afae2017-05-25 18:25:51 -0700371 }
372 }
Phil Burk67ed9da2017-09-06 16:26:52 -0700373 break;
Eric Laurent629afae2017-05-25 18:25:51 -0700374 case AAUDIO_FORMAT_PCM_FLOAT: {
375 float *audioBuffer = (float *) audioData;
Phil Burk67ed9da2017-09-06 16:26:52 -0700376 for (int i = 0; i < numActiveOscilators; ++i) {
377 sineData->sineOscillators[i].render(&audioBuffer[i], samplesPerFrame,
378 numFrames);
Eric Laurent629afae2017-05-25 18:25:51 -0700379 }
380 }
Phil Burk67ed9da2017-09-06 16:26:52 -0700381 break;
Eric Laurent629afae2017-05-25 18:25:51 -0700382 default:
383 return AAUDIO_CALLBACK_RESULT_STOP;
384 }
385
Phil Burk67ed9da2017-09-06 16:26:52 -0700386 sineData->callbackCount++;
387 sineData->framesTotal += numFrames;
Eric Laurent629afae2017-05-25 18:25:51 -0700388 return AAUDIO_CALLBACK_RESULT_CONTINUE;
389}
390
391void SimplePlayerErrorCallbackProc(
392 AAudioStream *stream __unused,
393 void *userData __unused,
Phil Burk7a61a3a2017-07-10 11:53:09 -0700394 aaudio_result_t error) {
395 // should not happen but just in case...
396 if (userData == nullptr) {
397 printf("ERROR - MyPlayerErrorCallbackProc needs userData\n");
398 return;
399 }
400 SineThreadedData_t *sineData = (SineThreadedData_t *) userData;
401 android::status_t ret = sineData->waker.wake(error);
402 printf("Error Callback, error: %d, futex wake returns %d\n", error, ret);
Eric Laurent629afae2017-05-25 18:25:51 -0700403}
404
Phil Burk7a61a3a2017-07-10 11:53:09 -0700405
Eric Laurent629afae2017-05-25 18:25:51 -0700406#endif //AAUDIO_SIMPLE_PLAYER_H