1 /*
2 * Copyright 2015 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 #define LOG_TAG "AudioStreamBuilder"
18 //#define LOG_NDEBUG 0
19 #include <utils/Log.h>
20
21 #include <new>
22 #include <stdint.h>
23
24 #include <aaudio/AAudio.h>
25 #include <aaudio/AAudioTesting.h>
26
27 #include "binding/AAudioBinderClient.h"
28 #include "client/AudioStreamInternalCapture.h"
29 #include "client/AudioStreamInternalPlay.h"
30 #include "core/AudioGlobal.h"
31 #include "core/AudioStream.h"
32 #include "core/AudioStreamBuilder.h"
33 #include "legacy/AudioStreamRecord.h"
34 #include "legacy/AudioStreamTrack.h"
35
36 using namespace aaudio;
37
38 #define AAUDIO_MMAP_POLICY_DEFAULT AAUDIO_POLICY_NEVER
39 #define AAUDIO_MMAP_EXCLUSIVE_POLICY_DEFAULT AAUDIO_POLICY_NEVER
40
41 // These values are for a pre-check before we ask the lower level service to open a stream.
42 // So they are just outside the maximum conceivable range of value,
43 // on the edge of being ridiculous.
44 // TODO These defines should be moved to a central place in audio.
45 #define SAMPLES_PER_FRAME_MIN 1
46 // TODO Remove 8 channel limitation.
47 #define SAMPLES_PER_FRAME_MAX FCC_8
48 #define SAMPLE_RATE_HZ_MIN 8000
49 // HDMI supports up to 32 channels at 1536000 Hz.
50 #define SAMPLE_RATE_HZ_MAX 1600000
51 #define FRAMES_PER_DATA_CALLBACK_MIN 1
52 #define FRAMES_PER_DATA_CALLBACK_MAX (1024 * 1024)
53
54 /*
55 * AudioStreamBuilder
56 */
AudioStreamBuilder()57 AudioStreamBuilder::AudioStreamBuilder() {
58 }
59
~AudioStreamBuilder()60 AudioStreamBuilder::~AudioStreamBuilder() {
61 }
62
builder_createStream(aaudio_direction_t direction,aaudio_sharing_mode_t sharingMode,bool tryMMap,android::sp<AudioStream> & stream)63 static aaudio_result_t builder_createStream(aaudio_direction_t direction,
64 aaudio_sharing_mode_t sharingMode,
65 bool tryMMap,
66 android::sp<AudioStream> &stream) {
67 aaudio_result_t result = AAUDIO_OK;
68
69 switch (direction) {
70
71 case AAUDIO_DIRECTION_INPUT:
72 if (tryMMap) {
73 stream = new AudioStreamInternalCapture(AAudioBinderClient::getInstance(),
74 false);
75 } else {
76 stream = new AudioStreamRecord();
77 }
78 break;
79
80 case AAUDIO_DIRECTION_OUTPUT:
81 if (tryMMap) {
82 stream = new AudioStreamInternalPlay(AAudioBinderClient::getInstance(),
83 false);
84 } else {
85 stream = new AudioStreamTrack();
86 }
87 break;
88
89 default:
90 ALOGE("%s() bad direction = %d", __func__, direction);
91 result = AAUDIO_ERROR_ILLEGAL_ARGUMENT;
92 }
93 return result;
94 }
95
96 // Try to open using MMAP path if that is allowed.
97 // Fall back to Legacy path if MMAP not available.
98 // Exact behavior is controlled by MMapPolicy.
build(AudioStream ** streamPtr)99 aaudio_result_t AudioStreamBuilder::build(AudioStream** streamPtr) {
100
101 if (streamPtr == nullptr) {
102 ALOGE("%s() streamPtr is null", __func__);
103 return AAUDIO_ERROR_NULL;
104 }
105 *streamPtr = nullptr;
106
107 logParameters();
108
109 aaudio_result_t result = validate();
110 if (result != AAUDIO_OK) {
111 return result;
112 }
113
114 // The API setting is the highest priority.
115 aaudio_policy_t mmapPolicy = AudioGlobal_getMMapPolicy();
116 // If not specified then get from a system property.
117 if (mmapPolicy == AAUDIO_UNSPECIFIED) {
118 mmapPolicy = AAudioProperty_getMMapPolicy();
119 }
120 // If still not specified then use the default.
121 if (mmapPolicy == AAUDIO_UNSPECIFIED) {
122 mmapPolicy = AAUDIO_MMAP_POLICY_DEFAULT;
123 }
124
125 int32_t mapExclusivePolicy = AAudioProperty_getMMapExclusivePolicy();
126 if (mapExclusivePolicy == AAUDIO_UNSPECIFIED) {
127 mapExclusivePolicy = AAUDIO_MMAP_EXCLUSIVE_POLICY_DEFAULT;
128 }
129
130 aaudio_sharing_mode_t sharingMode = getSharingMode();
131 if ((sharingMode == AAUDIO_SHARING_MODE_EXCLUSIVE)
132 && (mapExclusivePolicy == AAUDIO_POLICY_NEVER)) {
133 ALOGD("%s() EXCLUSIVE sharing mode not supported. Use SHARED.", __func__);
134 sharingMode = AAUDIO_SHARING_MODE_SHARED;
135 setSharingMode(sharingMode);
136 }
137
138 bool allowMMap = mmapPolicy != AAUDIO_POLICY_NEVER;
139 bool allowLegacy = mmapPolicy != AAUDIO_POLICY_ALWAYS;
140
141 // TODO Support other performance settings in MMAP mode.
142 // Disable MMAP if low latency not requested.
143 if (getPerformanceMode() != AAUDIO_PERFORMANCE_MODE_LOW_LATENCY) {
144 ALOGD("%s() MMAP not used because AAUDIO_PERFORMANCE_MODE_LOW_LATENCY not requested.",
145 __func__);
146 allowMMap = false;
147 }
148
149 // SessionID and Effects are only supported in Legacy mode.
150 if (getSessionId() != AAUDIO_SESSION_ID_NONE) {
151 ALOGD("%s() MMAP not used because sessionId specified.", __func__);
152 allowMMap = false;
153 }
154
155 if (!allowMMap && !allowLegacy) {
156 ALOGE("%s() no backend available: neither MMAP nor legacy path are allowed", __func__);
157 return AAUDIO_ERROR_ILLEGAL_ARGUMENT;
158 }
159
160 setPrivacySensitive(false);
161 if (mPrivacySensitiveReq == PRIVACY_SENSITIVE_DEFAULT) {
162 // When not explicitly requested, set privacy sensitive mode according to input preset:
163 // communication and camcorder captures are considered privacy sensitive by default.
164 aaudio_input_preset_t preset = getInputPreset();
165 if (preset == AAUDIO_INPUT_PRESET_CAMCORDER
166 || preset == AAUDIO_INPUT_PRESET_VOICE_COMMUNICATION) {
167 setPrivacySensitive(true);
168 }
169 } else if (mPrivacySensitiveReq == PRIVACY_SENSITIVE_ENABLED) {
170 setPrivacySensitive(true);
171 }
172
173 android::sp<AudioStream> audioStream;
174 result = builder_createStream(getDirection(), sharingMode, allowMMap, audioStream);
175 if (result == AAUDIO_OK) {
176 // Open the stream using the parameters from the builder.
177 result = audioStream->open(*this);
178 if (result != AAUDIO_OK) {
179 bool isMMap = audioStream->isMMap();
180 if (isMMap && allowLegacy) {
181 ALOGV("%s() MMAP stream did not open so try Legacy path", __func__);
182 // If MMAP stream failed to open then TRY using a legacy stream.
183 result = builder_createStream(getDirection(), sharingMode,
184 false, audioStream);
185 if (result == AAUDIO_OK) {
186 result = audioStream->open(*this);
187 }
188 }
189 }
190 if (result == AAUDIO_OK) {
191 audioStream->logOpen();
192 *streamPtr = startUsingStream(audioStream);
193 } // else audioStream will go out of scope and be deleted
194 }
195
196 return result;
197 }
198
startUsingStream(android::sp<AudioStream> & audioStream)199 AudioStream *AudioStreamBuilder::startUsingStream(android::sp<AudioStream> &audioStream) {
200 // Increment the smart pointer so it will not get deleted when
201 // we pass it to the C caller and it goes out of scope.
202 // The C code cannot hold a smart pointer so we increment the reference
203 // count to indicate that the C app owns a reference.
204 audioStream->incStrong(nullptr);
205 return audioStream.get();
206 }
207
stopUsingStream(AudioStream * stream)208 void AudioStreamBuilder::stopUsingStream(AudioStream *stream) {
209 // Undo the effect of startUsingStream()
210 android::sp<AudioStream> spAudioStream(stream);
211 ALOGV("%s() strongCount = %d", __func__, spAudioStream->getStrongCount());
212 spAudioStream->decStrong(nullptr);
213 }
214
validate() const215 aaudio_result_t AudioStreamBuilder::validate() const {
216
217 // Check for values that are ridiculously out of range to prevent math overflow exploits.
218 // The service will do a better check.
219 aaudio_result_t result = AAudioStreamParameters::validate();
220 if (result != AAUDIO_OK) {
221 return result;
222 }
223
224 switch (mPerformanceMode) {
225 case AAUDIO_PERFORMANCE_MODE_NONE:
226 case AAUDIO_PERFORMANCE_MODE_POWER_SAVING:
227 case AAUDIO_PERFORMANCE_MODE_LOW_LATENCY:
228 break;
229 default:
230 ALOGE("illegal performanceMode = %d", mPerformanceMode);
231 return AAUDIO_ERROR_ILLEGAL_ARGUMENT;
232 // break;
233 }
234
235 // Prevent ridiculous values from causing problems.
236 if (mFramesPerDataCallback != AAUDIO_UNSPECIFIED
237 && (mFramesPerDataCallback < FRAMES_PER_DATA_CALLBACK_MIN
238 || mFramesPerDataCallback > FRAMES_PER_DATA_CALLBACK_MAX)) {
239 ALOGE("framesPerDataCallback out of range = %d",
240 mFramesPerDataCallback);
241 return AAUDIO_ERROR_OUT_OF_RANGE;
242 }
243
244 return AAUDIO_OK;
245 }
246
AAudio_convertSharingModeToShortText(aaudio_sharing_mode_t sharingMode)247 static const char *AAudio_convertSharingModeToShortText(aaudio_sharing_mode_t sharingMode) {
248 switch (sharingMode) {
249 case AAUDIO_SHARING_MODE_EXCLUSIVE:
250 return "EX";
251 case AAUDIO_SHARING_MODE_SHARED:
252 return "SH";
253 default:
254 return "?!";
255 }
256 }
257
AAudio_convertDirectionToText(aaudio_direction_t direction)258 static const char *AAudio_convertDirectionToText(aaudio_direction_t direction) {
259 switch (direction) {
260 case AAUDIO_DIRECTION_OUTPUT:
261 return "OUTPUT";
262 case AAUDIO_DIRECTION_INPUT:
263 return "INPUT";
264 default:
265 return "?!";
266 }
267 }
268
logParameters() const269 void AudioStreamBuilder::logParameters() const {
270 // This is very helpful for debugging in the future. Please leave it in.
271 ALOGI("rate = %6d, channels = %d, format = %d, sharing = %s, dir = %s",
272 getSampleRate(), getSamplesPerFrame(), getFormat(),
273 AAudio_convertSharingModeToShortText(getSharingMode()),
274 AAudio_convertDirectionToText(getDirection()));
275 ALOGI("device = %6d, sessionId = %d, perfMode = %d, callback: %s with frames = %d",
276 getDeviceId(),
277 getSessionId(),
278 getPerformanceMode(),
279 ((getDataCallbackProc() != nullptr) ? "ON" : "OFF"),
280 mFramesPerDataCallback);
281 ALOGI("usage = %6d, contentType = %d, inputPreset = %d, allowedCapturePolicy = %d",
282 getUsage(), getContentType(), getInputPreset(), getAllowedCapturePolicy());
283 ALOGI("privacy sensitive = %s", isPrivacySensitive() ? "true" : "false");
284 }
285