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