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