1 /*
2 * Copyright (C) 2025 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 // Compress offload
18
19 #include <atomic>
20 #include <condition_variable>
21 #include <fstream>
22 #include <memory>
23 #include <mutex>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string>
27 #include <thread>
28 #include <vector>
29 #include <utility>
30
31 #include <aaudio/AAudio.h>
32 #include <android-base/thread_annotations.h>
33
34 #include "AAudioArgsParser.h"
35 #include "AAudioSimplePlayer.h"
36 #include "SineGenerator.h"
37
38 const static int DEFAULT_TIME_TO_RUN_IN_SECOND = 60;
39
40 aaudio_data_callback_result_t MyDatacallback(AAudioStream* stream,
41 void* userData,
42 void* audioData,
43 int32_t numFrames);
44
45 void MyErrorCallback(AAudioStream* /*stream*/, void* /*userData*/, aaudio_result_t error);
46
47 void MyPresentationEndCallback(AAudioStream* /*stream*/, void* userData);
48
49 class FileDataProvider {
50 public:
loadData(const std::string & filePath)51 bool loadData(const std::string& filePath) {
52 mPosition = 0;
53 std::ifstream is(filePath, std::ios::in | std::ios::binary);
54 if (!is.good()) {
55 printf("Failed to open file %s\n", filePath.c_str());
56 return false;
57 }
58 is.seekg(0, is.end);
59 mData.reserve(mData.size() + is.tellg());
60 is.seekg(0, is.beg);
61 mData.insert(mData.end(), std::istreambuf_iterator<char>(is),
62 std::istreambuf_iterator<char>());
63 if (is.fail()) {
64 printf("Failed to read from file %s\n", filePath.c_str());
65 return false;
66 }
67 return true;
68 }
69
copyData(void * audioData,int32_t numFrames)70 std::pair<bool, int> copyData(void* audioData, int32_t numFrames) {
71 bool endOfFile = false;
72 int dataToCopy = std::min((int)mData.size() - mPosition, numFrames);
73 std::copy(mData.begin() + mPosition, mData.begin() + mPosition + dataToCopy,
74 static_cast<uint8_t*>(audioData));
75 mPosition += dataToCopy;
76 if (mPosition >= mData.size()) {
77 endOfFile = true;
78 mPosition = 0;
79 }
80 return {endOfFile, dataToCopy};
81 }
82
83 private:
84 std::vector<uint8_t> mData;
85 int mPosition;
86 };
87
88 class CompressOffloadPlayer : public AAudioSimplePlayer {
89 public:
CompressOffloadPlayer(AAudioArgsParser & argParser,int delay,int padding,bool useDataCallback,const std::string & filePath)90 CompressOffloadPlayer(AAudioArgsParser& argParser, int delay, int padding,
91 bool useDataCallback, const std::string& filePath)
92 : mArgParser(argParser), mDelay(delay), mPadding(padding),
93 mUseDataCallback(useDataCallback), mFilePath(filePath) {
94 }
95
open()96 aaudio_result_t open() {
97 if (!mDataProvider.loadData(mFilePath)) {
98 return AAUDIO_ERROR_ILLEGAL_ARGUMENT;
99 }
100 return AAudioSimplePlayer::open(
101 mArgParser,
102 mUseDataCallback ? &MyDatacallback : nullptr,
103 &MyErrorCallback,
104 this,
105 &MyPresentationEndCallback);
106 }
107
renderAudio(AAudioStream *,void * audioData,int32_t numFrames)108 aaudio_data_callback_result_t renderAudio(AAudioStream* /*stream*/,
109 void* audioData,
110 int32_t numFrames) {
111 {
112 std::lock_guard lk(mWaitForExitingLock);
113 mReadyToExit = false;
114 }
115 auto [endOfFile, dataCopied] = mDataProvider.copyData(audioData, numFrames);
116 if (endOfFile) {
117 printf("%s(%d): endOfFile=%d, dataCopied=%d\n", __func__, numFrames, endOfFile,
118 dataCopied);
119 setOffloadEndOfStream();
120 return AAUDIO_CALLBACK_RESULT_STOP;
121 }
122 return AAUDIO_CALLBACK_RESULT_CONTINUE;
123 }
124
presentationEnd()125 void presentationEnd() {
126 printf("Presentation end\n");
127 {
128 std::lock_guard lk(mWaitForExitingLock);
129 mReadyToExit = true;
130 }
131 mCV.notify_one();
132 setOffloadDelayPadding(mDelay, mPadding);
133 if (!mUseDataCallback) {
134 std::thread(&CompressOffloadPlayer::writeAllStreamData, this).detach();
135 }
136 }
137
writeData()138 void writeData() {
139 writeAllStreamData();
140 }
141
waitForExiting()142 void waitForExiting() {
143 printf("%s\n", __func__);
144 std::unique_lock lk(mWaitForExitingLock);
145 mCV.wait(lk, [this]{ return mReadyToExit; });
146 }
147
148 private:
writeAllStreamData()149 void writeAllStreamData() {
150 int dataSize = mArgParser.getSampleRate();
151 uint8_t data[dataSize];
152 static constexpr int64_t kTimeOutNanos = 1e9;
153 while (true) {
154 auto [endOfFile, dataCopied] = mDataProvider.copyData(data, dataSize);
155 auto result = AAudioStream_write(getStream(), data, dataCopied, kTimeOutNanos);
156 if (result < AAUDIO_OK) {
157 printf("Failed to write data, error=%d\n", result);
158 break;
159 }
160 if (endOfFile) {
161 printf("All data from the file is written, set offload end of stream\n");
162 setOffloadEndOfStream();
163 break;
164 }
165 }
166 }
167
168 const AAudioArgsParser mArgParser;
169 const int mDelay;
170 const int mPadding;
171 const bool mUseDataCallback;
172 const std::string mFilePath;
173
174 FileDataProvider mDataProvider;
175 std::mutex mWaitForExitingLock;
176 std::condition_variable mCV;
177 bool mReadyToExit GUARDED_BY(mWaitForExitingLock);
178 };
179
MyDatacallback(AAudioStream * stream,void * userData,void * audioData,int32_t numFrames)180 aaudio_data_callback_result_t MyDatacallback(AAudioStream* stream,
181 void* userData,
182 void* audioData,
183 int32_t numFrames) {
184 CompressOffloadPlayer* player = static_cast<CompressOffloadPlayer*>(userData);
185 return player->renderAudio(stream, audioData, numFrames);
186 }
187
MyErrorCallback(AAudioStream *,void *,aaudio_result_t error)188 void MyErrorCallback(AAudioStream* /*stream*/, void* /*userData*/, aaudio_result_t error) {
189 printf("Error callback, error=%d\n", error);
190 }
191
MyPresentationEndCallback(AAudioStream *,void * userData)192 void MyPresentationEndCallback(AAudioStream* /*stream*/, void* userData) {
193 CompressOffloadPlayer* player = static_cast<CompressOffloadPlayer*>(userData);
194 return player->presentationEnd();
195 }
196
usage()197 static void usage() {
198 AAudioArgsParser::usage();
199 printf(" -D{delay} offload delay in frames\n");
200 printf(" -P{padding} offload padding in frames\n");
201 printf(" -T{seconds} time to run the test\n");
202 printf(" -F{filePath} file path for the compressed data\n");
203 printf(" -B use blocking write instead of data callback\n");
204 }
205
main(int argc,char ** argv)206 int main(int argc, char **argv) {
207 AAudioArgsParser argParser;
208 int delay = 0;
209 int padding = 0;
210 int timeToRun = DEFAULT_TIME_TO_RUN_IN_SECOND;
211 bool useDataCallback = true;
212 std::string filePath;
213 for (int i = 1; i < argc; ++i) {
214 const char *arg = argv[i];
215 if (argParser.parseArg(arg)) {
216 if (arg[0] == '-') {
217 char option = arg[1];
218 switch (option) {
219 case 'D':
220 delay = atoi(&arg[2]);
221 break;
222 case 'P':
223 padding = atoi(&arg[2]);
224 break;
225 case 'T':
226 timeToRun = atoi(&arg[2]);
227 break;
228 case 'B':
229 useDataCallback = false;
230 break;
231 case 'F':
232 filePath = &arg[2];
233 break;
234 default:
235 usage();
236 exit(EXIT_FAILURE);
237 }
238 } else {
239 usage();
240 exit(EXIT_FAILURE);
241 }
242 }
243 }
244
245 if (filePath.empty()) {
246 printf("A file path must be specified\n");
247 usage();
248 exit(EXIT_FAILURE);
249 }
250
251 // Force to use offload mode
252 argParser.setPerformanceMode(AAUDIO_PERFORMANCE_MODE_POWER_SAVING_OFFLOADED);
253
254 CompressOffloadPlayer player(
255 argParser, delay, padding, useDataCallback, filePath);
256 if (auto result = player.open(); result != AAUDIO_OK) {
257 printf("Failed to open stream, error=%d\n", result);
258 exit(EXIT_FAILURE);
259 }
260
261 // Failed to set offload delay and padding will affect the gapless transition between tracks
262 // but doesn't affect playback.
263 (void) player.setOffloadDelayPadding(delay, padding);
264
265 if (auto result = player.start(); result != AAUDIO_OK) {
266 printf("Failed to start stream, error=%d", result);
267 exit(EXIT_FAILURE);
268 } else if (!useDataCallback) {
269 player.writeData();
270 }
271
272 sleep(timeToRun);
273
274 player.stop();
275
276 player.waitForExiting();
277
278 return EXIT_SUCCESS;
279 }
280