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 LOGW("Passing AudioStream pointer deprecated, Use openStream(std::shared_ptr<oboe::AudioStream> &stream) instead.");
93 return openStreamInternal(streamPP);
94 }
95
openStreamInternal(AudioStream ** streamPP)96 Result AudioStreamBuilder::openStreamInternal(AudioStream **streamPP) {
97 auto result = isValidConfig();
98 if (result != Result::OK) {
99 LOGW("%s() invalid config. Error %s", __func__, oboe::convertToText(result));
100 return result;
101 }
102
103 #ifndef OBOE_SUPPRESS_LOG_SPAM
104 LOGI("%s() %s -------- %s --------",
105 __func__, getDirection() == Direction::Input ? "INPUT" : "OUTPUT", getVersionText());
106 #endif
107
108 if (streamPP == nullptr) {
109 return Result::ErrorNull;
110 }
111 *streamPP = nullptr;
112
113 AudioStream *streamP = nullptr;
114
115 // Maybe make a FilterInputStream.
116 AudioStreamBuilder childBuilder(*this);
117 // Check need for conversion and modify childBuilder for optimal stream.
118 bool conversionNeeded = QuirksManager::getInstance().isConversionNeeded(*this, childBuilder);
119 // Do we need to make a child stream and convert.
120 if (conversionNeeded) {
121 AudioStream *tempStream;
122 result = childBuilder.openStreamInternal(&tempStream);
123 if (result != Result::OK) {
124 return result;
125 }
126
127 if (isCompatible(*tempStream)) {
128 // The child stream would work as the requested stream so we can just use it directly.
129 *streamPP = tempStream;
130 return result;
131 } else {
132 AudioStreamBuilder parentBuilder = *this;
133 // Build a stream that is as close as possible to the childStream.
134 if (getFormat() == oboe::AudioFormat::Unspecified) {
135 parentBuilder.setFormat(tempStream->getFormat());
136 }
137 if (getChannelCount() == oboe::Unspecified) {
138 parentBuilder.setChannelCount(tempStream->getChannelCount());
139 }
140 if (getSampleRate() == oboe::Unspecified) {
141 parentBuilder.setSampleRate(tempStream->getSampleRate());
142 }
143 if (getFramesPerDataCallback() == oboe::Unspecified) {
144 parentBuilder.setFramesPerCallback(tempStream->getFramesPerDataCallback());
145 }
146
147 // Use childStream in a FilterAudioStream.
148 LOGI("%s() create a FilterAudioStream for data conversion.", __func__);
149 std::shared_ptr<AudioStream> childStream(tempStream);
150 FilterAudioStream *filterStream = new FilterAudioStream(parentBuilder, childStream);
151 childStream->setWeakThis(childStream);
152 result = filterStream->configureFlowGraph();
153 if (result != Result::OK) {
154 filterStream->close();
155 delete filterStream;
156 // Just open streamP the old way.
157 } else {
158 streamP = static_cast<AudioStream *>(filterStream);
159 }
160 }
161 }
162
163 if (streamP == nullptr) {
164 streamP = build();
165 if (streamP == nullptr) {
166 return Result::ErrorNull;
167 }
168 }
169
170 // If MMAP has a problem in this case then disable it temporarily.
171 bool wasMMapOriginallyEnabled = AAudioExtensions::getInstance().isMMapEnabled();
172 bool wasMMapTemporarilyDisabled = false;
173 if (wasMMapOriginallyEnabled) {
174 bool isMMapSafe = QuirksManager::getInstance().isMMapSafe(childBuilder);
175 if (!isMMapSafe) {
176 AAudioExtensions::getInstance().setMMapEnabled(false);
177 wasMMapTemporarilyDisabled = true;
178 }
179 }
180 result = streamP->open();
181 if (wasMMapTemporarilyDisabled) {
182 AAudioExtensions::getInstance().setMMapEnabled(wasMMapOriginallyEnabled); // restore original
183 }
184 if (result == Result::OK) {
185 // AAudio supports setBufferSizeInFrames() so use it.
186 if (streamP->getAudioApi() == AudioApi::AAudio) {
187 int32_t optimalBufferSize = -1;
188 // Use a reasonable default buffer size.
189 if (streamP->getDirection() == Direction::Input) {
190 // For input, small size does not improve latency because the stream is usually
191 // run close to empty. And a low size can result in XRuns so always use the maximum.
192 optimalBufferSize = streamP->getBufferCapacityInFrames();
193 } else if (streamP->getPerformanceMode() == PerformanceMode::LowLatency
194 && streamP->getDirection() == Direction::Output) { // Output check is redundant.
195 optimalBufferSize = streamP->getFramesPerBurst() *
196 kBufferSizeInBurstsForLowLatencyStreams;
197 }
198 if (optimalBufferSize >= 0) {
199 auto setBufferResult = streamP->setBufferSizeInFrames(optimalBufferSize);
200 if (!setBufferResult) {
201 LOGW("Failed to setBufferSizeInFrames(%d). Error was %s",
202 optimalBufferSize,
203 convertToText(setBufferResult.error()));
204 }
205 }
206 }
207
208 *streamPP = streamP;
209 } else {
210 delete streamP;
211 }
212 return result;
213 }
214
openManagedStream(oboe::ManagedStream & stream)215 Result AudioStreamBuilder::openManagedStream(oboe::ManagedStream &stream) {
216 LOGW("`openManagedStream` is deprecated. Use openStream(std::shared_ptr<oboe::AudioStream> &stream) instead.");
217 stream.reset();
218 AudioStream *streamptr;
219 auto result = openStream(&streamptr);
220 stream.reset(streamptr);
221 return result;
222 }
223
openStream(std::shared_ptr<AudioStream> & sharedStream)224 Result AudioStreamBuilder::openStream(std::shared_ptr<AudioStream> &sharedStream) {
225 sharedStream.reset();
226 AudioStream *streamptr;
227 auto result = openStreamInternal(&streamptr);
228 if (result == Result::OK) {
229 sharedStream.reset(streamptr);
230 // Save a weak_ptr in the stream for use with callbacks.
231 streamptr->setWeakThis(sharedStream);
232 }
233 return result;
234 }
235
236 } // namespace oboe
237