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