xref: /aosp_15_r20/frameworks/av/media/libaaudio/src/core/AudioStreamBuilder.cpp (revision ec779b8e0859a360c3d303172224686826e6e0e1)
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 <numeric>
23 #include <stdint.h>
24 #include <vector>
25 
26 #include <aaudio/AAudio.h>
27 #include <aaudio/AAudioTesting.h>
28 #include <android/media/audio/common/AudioMMapPolicy.h>
29 #include <android/media/audio/common/AudioMMapPolicyInfo.h>
30 #include <android/media/audio/common/AudioMMapPolicyType.h>
31 #include <media/AudioSystem.h>
32 #include <system/aaudio/AAudio.h>
33 
34 #include "binding/AAudioBinderClient.h"
35 #include "client/AudioStreamInternalCapture.h"
36 #include "client/AudioStreamInternalPlay.h"
37 #include "core/AudioGlobal.h"
38 #include "core/AudioStream.h"
39 #include "core/AudioStreamBuilder.h"
40 #include "legacy/AudioStreamRecord.h"
41 #include "legacy/AudioStreamTrack.h"
42 #include "utility/AAudioUtilities.h"
43 
44 using namespace aaudio;
45 
46 using android::media::audio::common::AudioMMapPolicy;
47 using android::media::audio::common::AudioMMapPolicyInfo;
48 using android::media::audio::common::AudioMMapPolicyType;
49 
50 #define AAUDIO_MMAP_POLICY_DEFAULT             AAUDIO_POLICY_NEVER
51 #define AAUDIO_MMAP_EXCLUSIVE_POLICY_DEFAULT   AAUDIO_POLICY_NEVER
52 #define AAUDIO_MMAP_POLICY_DEFAULT_AIDL        AudioMMapPolicy::NEVER
53 #define AAUDIO_MMAP_EXCLUSIVE_POLICY_DEFAULT_AIDL AudioMMapPolicy::NEVER
54 
55 #define FRAMES_PER_DATA_CALLBACK_MIN 1
56 #define FRAMES_PER_DATA_CALLBACK_MAX (1024 * 1024)
57 
58 /*
59  * AudioStreamBuilder
60  */
builder_createStream(aaudio_direction_t direction,aaudio_sharing_mode_t,bool tryMMap,android::sp<AudioStream> & stream)61 static aaudio_result_t builder_createStream(aaudio_direction_t direction,
62                                             aaudio_sharing_mode_t /*sharingMode*/,
63                                             bool tryMMap,
64                                             android::sp<AudioStream> &stream) {
65     aaudio_result_t result = AAUDIO_OK;
66 
67     switch (direction) {
68 
69         case AAUDIO_DIRECTION_INPUT:
70             if (tryMMap) {
71                 stream = new AudioStreamInternalCapture(AAudioBinderClient::getInstance(),
72                                                                  false);
73             } else {
74                 stream = new AudioStreamRecord();
75             }
76             break;
77 
78         case AAUDIO_DIRECTION_OUTPUT:
79             if (tryMMap) {
80                 stream = new AudioStreamInternalPlay(AAudioBinderClient::getInstance(),
81                                                               false);
82             } else {
83                 stream = new AudioStreamTrack();
84             }
85             break;
86 
87         default:
88             ALOGE("%s() bad direction = %d", __func__, direction);
89             result = AAUDIO_ERROR_ILLEGAL_ARGUMENT;
90     }
91     return result;
92 }
93 
94 // Try to open using MMAP path if that is allowed.
95 // Fall back to Legacy path if MMAP not available.
96 // Exact behavior is controlled by MMapPolicy.
build(AudioStream ** streamPtr)97 aaudio_result_t AudioStreamBuilder::build(AudioStream** streamPtr) {
98 
99     if (streamPtr == nullptr) {
100         ALOGE("%s() streamPtr is null", __func__);
101         return AAUDIO_ERROR_NULL;
102     }
103     *streamPtr = nullptr;
104 
105     logParameters();
106 
107     aaudio_result_t result = validate();
108     if (result != AAUDIO_OK) {
109         return result;
110     }
111 
112     std::vector<AudioMMapPolicyInfo> policyInfos;
113     aaudio_policy_t mmapPolicy = AudioGlobal_getMMapPolicy();
114     ALOGD("%s, global mmap policy is %d", __func__, mmapPolicy);
115     if (status_t status = android::AudioSystem::getMmapPolicyInfos(
116             AudioMMapPolicyType::DEFAULT, &policyInfos); status == NO_ERROR) {
117         aaudio_policy_t systemMmapPolicy = AAudio_getAAudioPolicy(
118                 policyInfos, AAUDIO_MMAP_POLICY_DEFAULT_AIDL);
119         ALOGD("%s, system mmap policy is %d", __func__, systemMmapPolicy);
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         ALOGD("%s, failed to query system mmap policy, error=%d", __func__, status);
133         // If it fails querying mmap policy info, it is highly possible that the AAudioService is
134         // not created. In this case, we don't try mmap path.
135         if (mmapPolicy == AAUDIO_POLICY_ALWAYS) {
136             return AAUDIO_ERROR_NO_SERVICE;
137         }
138         mmapPolicy = AAUDIO_POLICY_NEVER;
139     }
140     // If still not specified then use the default.
141     if (mmapPolicy == AAUDIO_UNSPECIFIED) {
142         mmapPolicy = AAUDIO_MMAP_POLICY_DEFAULT;
143     }
144     ALOGD("%s, final mmap policy is %d", __func__, mmapPolicy);
145 
146     policyInfos.clear();
147     aaudio_policy_t mmapExclusivePolicy = AAUDIO_UNSPECIFIED;
148     if (status_t status = android::AudioSystem::getMmapPolicyInfos(
149             AudioMMapPolicyType::EXCLUSIVE, &policyInfos); status == NO_ERROR) {
150         mmapExclusivePolicy = AAudio_getAAudioPolicy(
151                 policyInfos, AAUDIO_MMAP_EXCLUSIVE_POLICY_DEFAULT_AIDL);
152         ALOGD("%s, system mmap exclusive policy is %d", __func__, mmapExclusivePolicy);
153     } else {
154         ALOGD("%s, failed to query mmap exclusive policy, error=%d", __func__, status);
155     }
156     if (mmapExclusivePolicy == AAUDIO_UNSPECIFIED) {
157         mmapExclusivePolicy = AAUDIO_MMAP_EXCLUSIVE_POLICY_DEFAULT;
158     }
159     ALOGD("%s, final mmap exclusive policy is %d", __func__, mmapExclusivePolicy);
160 
161     aaudio_sharing_mode_t sharingMode = getSharingMode();
162     if ((sharingMode == AAUDIO_SHARING_MODE_EXCLUSIVE)
163         && (mmapExclusivePolicy == AAUDIO_POLICY_NEVER)) {
164         ALOGD("%s() EXCLUSIVE sharing mode not supported. Use SHARED.", __func__);
165         sharingMode = AAUDIO_SHARING_MODE_SHARED;
166         setSharingMode(sharingMode);
167     }
168 
169     bool allowMMap = mmapPolicy != AAUDIO_POLICY_NEVER;
170     bool allowLegacy = mmapPolicy != AAUDIO_POLICY_ALWAYS;
171 
172     // TODO Support other performance settings in MMAP mode.
173     // Disable MMAP if low latency not requested.
174     if (getPerformanceMode() != AAUDIO_PERFORMANCE_MODE_LOW_LATENCY) {
175         ALOGD("%s() MMAP not used because AAUDIO_PERFORMANCE_MODE_LOW_LATENCY not requested.",
176               __func__);
177         allowMMap = false;
178     }
179     if (!audio_is_linear_pcm(getFormat())) {
180         ALOGD("%s() MMAP not used because the requested format(%#x) is not pcm",
181               __func__, getFormat());
182         allowMMap = false;
183     }
184 
185     // SessionID and Effects are only supported in Legacy mode.
186     if (getSessionId() != AAUDIO_SESSION_ID_NONE) {
187         ALOGD("%s() MMAP not used because sessionId specified.", __func__);
188         allowMMap = false;
189     }
190 
191     if (getFormat() == AUDIO_FORMAT_IEC61937) {
192         ALOGD("%s IEC61937 format is selected, do not allow MMAP in this case.", __func__);
193         allowMMap = false;
194     }
195 
196     if (!allowMMap && !allowLegacy) {
197         ALOGE("%s() no backend available: neither MMAP nor legacy path are allowed", __func__);
198         return AAUDIO_ERROR_ILLEGAL_ARGUMENT;
199     }
200 
201     setPrivacySensitive(false);
202     if (mPrivacySensitiveReq == PRIVACY_SENSITIVE_DEFAULT) {
203         // When not explicitly requested, set privacy sensitive mode according to input preset:
204         // communication and camcorder captures are considered privacy sensitive by default.
205         aaudio_input_preset_t preset = getInputPreset();
206         if (preset == AAUDIO_INPUT_PRESET_CAMCORDER
207                 || preset == AAUDIO_INPUT_PRESET_VOICE_COMMUNICATION) {
208             setPrivacySensitive(true);
209         }
210     } else if (mPrivacySensitiveReq == PRIVACY_SENSITIVE_ENABLED) {
211         setPrivacySensitive(true);
212     }
213 
214     android::sp<AudioStream> audioStream;
215     result = builder_createStream(getDirection(), sharingMode, allowMMap, audioStream);
216     if (result == AAUDIO_OK) {
217         // Open the stream using the parameters from the builder.
218         result = audioStream->open(*this);
219         if (result != AAUDIO_OK) {
220             bool isMMap = audioStream->isMMap();
221             if (isMMap && allowLegacy) {
222                 ALOGV("%s() MMAP stream did not open so try Legacy path", __func__);
223                 // If MMAP stream failed to open then TRY using a legacy stream.
224                 result = builder_createStream(getDirection(), sharingMode,
225                                               false, audioStream);
226                 if (result == AAUDIO_OK) {
227                     result = audioStream->open(*this);
228                 }
229             }
230         }
231         if (result == AAUDIO_OK) {
232             audioStream->registerPlayerBase();
233             audioStream->logOpenActual();
234             *streamPtr = startUsingStream(audioStream);
235         } // else audioStream will go out of scope and be deleted
236     }
237 
238     return result;
239 }
240 
startUsingStream(android::sp<AudioStream> & audioStream)241 AudioStream *AudioStreamBuilder::startUsingStream(android::sp<AudioStream> &audioStream) {
242     // Increment the smart pointer so it will not get deleted when
243     // we pass it to the C caller and it goes out of scope.
244     // The C code cannot hold a smart pointer so we increment the reference
245     // count to indicate that the C app owns a reference.
246     audioStream->incStrong(nullptr);
247     return audioStream.get();
248 }
249 
stopUsingStream(AudioStream * stream)250 void AudioStreamBuilder::stopUsingStream(AudioStream *stream) {
251     // Undo the effect of startUsingStream()
252     android::sp<AudioStream> spAudioStream(stream);
253     ALOGV("%s() strongCount = %d", __func__, spAudioStream->getStrongCount());
254     spAudioStream->decStrong(nullptr);
255 }
256 
validate() const257 aaudio_result_t AudioStreamBuilder::validate() const {
258 
259     // Check for values that are ridiculously out of range to prevent math overflow exploits.
260     // The service will do a better check.
261     aaudio_result_t result = AAudioStreamParameters::validate();
262     if (result != AAUDIO_OK) {
263         return result;
264     }
265 
266     switch (mPerformanceMode) {
267         case AAUDIO_PERFORMANCE_MODE_NONE:
268         case AAUDIO_PERFORMANCE_MODE_POWER_SAVING:
269         case AAUDIO_PERFORMANCE_MODE_LOW_LATENCY:
270             break;
271         case AAUDIO_PERFORMANCE_MODE_POWER_SAVING_OFFLOADED:
272             if (getDirection() != AAUDIO_DIRECTION_OUTPUT ||
273                 getFormat() == AUDIO_FORMAT_DEFAULT ||
274                 getSampleRate() == 0 ||
275                 getChannelMask() == AAUDIO_UNSPECIFIED) {
276                 return AAUDIO_ERROR_ILLEGAL_ARGUMENT;
277             }
278             break;
279         default:
280             ALOGE("illegal performanceMode = %d", mPerformanceMode);
281             return AAUDIO_ERROR_ILLEGAL_ARGUMENT;
282             // break;
283     }
284 
285     // Prevent ridiculous values from causing problems.
286     if (mFramesPerDataCallback != AAUDIO_UNSPECIFIED
287         && (mFramesPerDataCallback < FRAMES_PER_DATA_CALLBACK_MIN
288             || mFramesPerDataCallback > FRAMES_PER_DATA_CALLBACK_MAX)) {
289         ALOGE("framesPerDataCallback out of range = %d",
290               mFramesPerDataCallback);
291         return AAUDIO_ERROR_OUT_OF_RANGE;
292     }
293 
294     return AAUDIO_OK;
295 }
296 
addTag(const char * tag)297 aaudio_result_t AudioStreamBuilder::addTag(const char* tag) {
298     const std::string tagStr(tag);
299     mTags.insert(tagStr);
300     // The tags will be joined with `;` and ended with null terminator when sending to the HAL.
301     const int tagsLength = std::accumulate(
302             mTags.begin(), mTags.end(), 0, [](int v, const std::string& s) { return v + s.size(); })
303             + mTags.size();
304     if (tagsLength <= AUDIO_ATTRIBUTES_TAGS_MAX_SIZE) {
305         return AAUDIO_OK;
306     }
307     mTags.erase(tagStr);
308     return AAUDIO_ERROR_OUT_OF_RANGE;
309 }
310 
clearTags()311 void AudioStreamBuilder::clearTags() {
312     mTags.clear();
313 }
314 
AAudio_convertSharingModeToShortText(aaudio_sharing_mode_t sharingMode)315 static const char *AAudio_convertSharingModeToShortText(aaudio_sharing_mode_t sharingMode) {
316     switch (sharingMode) {
317         case AAUDIO_SHARING_MODE_EXCLUSIVE:
318             return "EX";
319         case AAUDIO_SHARING_MODE_SHARED:
320             return "SH";
321         default:
322             return "?!";
323     }
324 }
325 
AAudio_convertDirectionToText(aaudio_direction_t direction)326 static const char *AAudio_convertDirectionToText(aaudio_direction_t direction) {
327     switch (direction) {
328         case AAUDIO_DIRECTION_OUTPUT:
329             return "OUTPUT";
330         case AAUDIO_DIRECTION_INPUT:
331             return "INPUT";
332         default:
333             return "?!";
334     }
335 }
336 
logParameters() const337 void AudioStreamBuilder::logParameters() const {
338     // This is very helpful for debugging in the future. Please leave it in.
339     ALOGI("rate   = %6d, channels  = %d, channelMask = %#x, format   = %d, sharing = %s, dir = %s",
340           getSampleRate(), getSamplesPerFrame(), getChannelMask(), getFormat(),
341           AAudio_convertSharingModeToShortText(getSharingMode()),
342           AAudio_convertDirectionToText(getDirection()));
343     ALOGI("devices = %s, sessionId = %d, perfMode = %d, callback: %s with frames = %d",
344           android::toString(getDeviceIds()).c_str(),
345           getSessionId(),
346           getPerformanceMode(),
347           ((getDataCallbackProc() != nullptr) ? "ON" : "OFF"),
348           mFramesPerDataCallback);
349     ALOGI("usage  = %6d, contentType = %d, inputPreset = %d, allowedCapturePolicy = %d",
350           getUsage(), getContentType(), getInputPreset(), getAllowedCapturePolicy());
351     ALOGI("privacy sensitive = %s, opPackageName = %s, attributionTag = %s",
352           isPrivacySensitive() ? "true" : "false",
353           !getOpPackageName().has_value() ? "(null)" : getOpPackageName().value().c_str(),
354           !getAttributionTag().has_value() ? "(null)" : getAttributionTag().value().c_str());
355 }
356