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