1 /*
2 * Copyright 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 #include <sys/types.h>
18
19
20 #include "aaudio/AAudioExtensions.h"
21 #include "aaudio/AudioStreamAAudio.h"
22 #include "FilterAudioStream.h"
23 #include "OboeDebug.h"
24 #include "oboe/Oboe.h"
25 #include "oboe/AudioStreamBuilder.h"
26 #include "opensles/AudioInputStreamOpenSLES.h"
27 #include "opensles/AudioOutputStreamOpenSLES.h"
28 #include "opensles/AudioStreamOpenSLES.h"
29 #include "QuirksManager.h"
30
31 bool oboe::OboeGlobals::mWorkaroundsEnabled = true;
32
33 namespace oboe {
34
35 /**
36 * The following default values are used when oboe does not have any better way of determining the optimal values
37 * for an audio stream. This can happen when:
38 *
39 * - Client is creating a stream on API < 26 (OpenSLES) but has not supplied the optimal sample
40 * rate and/or frames per burst
41 * - Client is creating a stream on API 16 (OpenSLES) where AudioManager.PROPERTY_OUTPUT_* values
42 * are not available
43 */
44 int32_t DefaultStreamValues::SampleRate = 48000; // Common rate for mobile audio and video
45 int32_t DefaultStreamValues::FramesPerBurst = 192; // 4 msec at 48000 Hz
46 int32_t DefaultStreamValues::ChannelCount = 2; // Stereo
47
48 constexpr int kBufferSizeInBurstsForLowLatencyStreams = 2;
49
50 #ifndef OBOE_ENABLE_AAUDIO
51 // Set OBOE_ENABLE_AAUDIO to 0 if you want to disable the AAudio API.
52 // This might be useful if you want to force all the unit tests to use OpenSL ES.
53 #define OBOE_ENABLE_AAUDIO 1
54 #endif
55
isAAudioSupported()56 bool AudioStreamBuilder::isAAudioSupported() {
57 return AudioStreamAAudio::isSupported() && OBOE_ENABLE_AAUDIO;
58 }
59
isAAudioRecommended()60 bool AudioStreamBuilder::isAAudioRecommended() {
61 // See https://github.com/google/oboe/issues/40,
62 // AAudio may not be stable on Android O, depending on how it is used.
63 // To be safe, use AAudio only on O_MR1 and above.
64 return (getSdkVersion() >= __ANDROID_API_O_MR1__) && isAAudioSupported();
65 }
66
build()67 AudioStream *AudioStreamBuilder::build() {
68 AudioStream *stream = nullptr;
69 if (isAAudioRecommended() && mAudioApi != AudioApi::OpenSLES) {
70 stream = new AudioStreamAAudio(*this);
71 } else if (isAAudioSupported() && mAudioApi == AudioApi::AAudio) {
72 stream = new AudioStreamAAudio(*this);
73 LOGE("Creating AAudio stream on 8.0 because it was specified. This is error prone.");
74 } else {
75 if (getDirection() == oboe::Direction::Output) {
76 stream = new AudioOutputStreamOpenSLES(*this);
77 } else if (getDirection() == oboe::Direction::Input) {
78 stream = new AudioInputStreamOpenSLES(*this);
79 }
80 }
81 return stream;
82 }
83
isCompatible(AudioStreamBase & other)84 bool AudioStreamBuilder::isCompatible(AudioStreamBase &other) {
85 return (getSampleRate() == oboe::Unspecified || getSampleRate() == other.getSampleRate())
86 && (getFormat() == (AudioFormat)oboe::Unspecified || getFormat() == other.getFormat())
87 && (getFramesPerDataCallback() == oboe::Unspecified || getFramesPerDataCallback() == other.getFramesPerDataCallback())
88 && (getChannelCount() == oboe::Unspecified || getChannelCount() == other.getChannelCount());
89 }
90
openStream(AudioStream ** streamPP)91 Result AudioStreamBuilder::openStream(AudioStream **streamPP) {
92 auto result = isValidConfig();
93 if (result != Result::OK) {
94 return result;
95 }
96
97 LOGI("%s() %s -------- %s --------",
98 __func__, getDirection() == Direction::Input ? "INPUT" : "OUTPUT", getVersionText());
99
100 if (streamPP == nullptr) {
101 return Result::ErrorNull;
102 }
103 *streamPP = nullptr;
104
105 AudioStream *streamP = nullptr;
106
107 // Maybe make a FilterInputStream.
108 AudioStreamBuilder childBuilder(*this);
109 // Check need for conversion and modify childBuilder for optimal stream.
110 bool conversionNeeded = QuirksManager::getInstance().isConversionNeeded(*this, childBuilder);
111 // Do we need to make a child stream and convert.
112 if (conversionNeeded) {
113 AudioStream *tempStream;
114 result = childBuilder.openStream(&tempStream);
115 if (result != Result::OK) {
116 return result;
117 }
118
119 if (isCompatible(*tempStream)) {
120 // The child stream would work as the requested stream so we can just use it directly.
121 *streamPP = tempStream;
122 return result;
123 } else {
124 AudioStreamBuilder parentBuilder = *this;
125 // Build a stream that is as close as possible to the childStream.
126 if (getFormat() == oboe::AudioFormat::Unspecified) {
127 parentBuilder.setFormat(tempStream->getFormat());
128 }
129 if (getChannelCount() == oboe::Unspecified) {
130 parentBuilder.setChannelCount(tempStream->getChannelCount());
131 }
132 if (getSampleRate() == oboe::Unspecified) {
133 parentBuilder.setSampleRate(tempStream->getSampleRate());
134 }
135 if (getFramesPerDataCallback() == oboe::Unspecified) {
136 parentBuilder.setFramesPerCallback(tempStream->getFramesPerDataCallback());
137 }
138
139 // Use childStream in a FilterAudioStream.
140 LOGI("%s() create a FilterAudioStream for data conversion.", __func__);
141 FilterAudioStream *filterStream = new FilterAudioStream(parentBuilder, tempStream);
142 result = filterStream->configureFlowGraph();
143 if (result != Result::OK) {
144 filterStream->close();
145 delete filterStream;
146 // Just open streamP the old way.
147 } else {
148 streamP = static_cast<AudioStream *>(filterStream);
149 }
150 }
151 }
152
153 if (streamP == nullptr) {
154 streamP = build();
155 if (streamP == nullptr) {
156 return Result::ErrorNull;
157 }
158 }
159
160 // If MMAP has a problem in this case then disable it temporarily.
161 bool wasMMapOriginallyEnabled = AAudioExtensions::getInstance().isMMapEnabled();
162 bool wasMMapTemporarilyDisabled = false;
163 if (wasMMapOriginallyEnabled) {
164 bool isMMapSafe = QuirksManager::getInstance().isMMapSafe(childBuilder);
165 if (!isMMapSafe) {
166 AAudioExtensions::getInstance().setMMapEnabled(false);
167 wasMMapTemporarilyDisabled = true;
168 }
169 }
170 result = streamP->open();
171 if (wasMMapTemporarilyDisabled) {
172 AAudioExtensions::getInstance().setMMapEnabled(wasMMapOriginallyEnabled); // restore original
173 }
174 if (result == Result::OK) {
175
176 int32_t optimalBufferSize = -1;
177 // Use a reasonable default buffer size.
178 if (streamP->getDirection() == Direction::Input) {
179 // For input, small size does not improve latency because the stream is usually
180 // run close to empty. And a low size can result in XRuns so always use the maximum.
181 optimalBufferSize = streamP->getBufferCapacityInFrames();
182 } else if (streamP->getPerformanceMode() == PerformanceMode::LowLatency
183 && streamP->getDirection() == Direction::Output) { // Output check is redundant.
184 optimalBufferSize = streamP->getFramesPerBurst() *
185 kBufferSizeInBurstsForLowLatencyStreams;
186 }
187 if (optimalBufferSize >= 0) {
188 auto setBufferResult = streamP->setBufferSizeInFrames(optimalBufferSize);
189 if (!setBufferResult) {
190 LOGW("Failed to setBufferSizeInFrames(%d). Error was %s",
191 optimalBufferSize,
192 convertToText(setBufferResult.error()));
193 }
194 }
195
196 *streamPP = streamP;
197 } else {
198 delete streamP;
199 }
200 return result;
201 }
202
openManagedStream(oboe::ManagedStream & stream)203 Result AudioStreamBuilder::openManagedStream(oboe::ManagedStream &stream) {
204 stream.reset();
205 auto result = isValidConfig();
206 if (result != Result::OK) {
207 return result;
208 }
209 AudioStream *streamptr;
210 result = openStream(&streamptr);
211 stream.reset(streamptr);
212 return result;
213 }
214
openStream(std::shared_ptr<AudioStream> & sharedStream)215 Result AudioStreamBuilder::openStream(std::shared_ptr<AudioStream> &sharedStream) {
216 sharedStream.reset();
217 auto result = isValidConfig();
218 if (result != Result::OK) {
219 return result;
220 }
221 AudioStream *streamptr;
222 result = openStream(&streamptr);
223 if (result == Result::OK) {
224 sharedStream.reset(streamptr);
225 // Save a weak_ptr in the stream for use with callbacks.
226 streamptr->setWeakThis(sharedStream);
227 }
228 return result;
229 }
230
231 } // namespace oboe
232