• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #define SAMPLES_PER_FRAME_MAX        FCC_LIMIT
47 #define SAMPLE_RATE_HZ_MIN           8000
48 // HDMI supports up to 32 channels at 1536000 Hz.
49 #define SAMPLE_RATE_HZ_MAX           1600000
50 #define FRAMES_PER_DATA_CALLBACK_MIN 1
51 #define FRAMES_PER_DATA_CALLBACK_MAX (1024 * 1024)
52 
53 /*
54  * AudioStreamBuilder
55  */
AudioStreamBuilder()56 AudioStreamBuilder::AudioStreamBuilder() {
57 }
58 
~AudioStreamBuilder()59 AudioStreamBuilder::~AudioStreamBuilder() {
60 }
61 
builder_createStream(aaudio_direction_t direction,aaudio_sharing_mode_t sharingMode,bool tryMMap,android::sp<AudioStream> & stream)62 static aaudio_result_t builder_createStream(aaudio_direction_t direction,
63                                          aaudio_sharing_mode_t sharingMode,
64                                          bool tryMMap,
65                                          android::sp<AudioStream> &stream) {
66     aaudio_result_t result = AAUDIO_OK;
67 
68     switch (direction) {
69 
70         case AAUDIO_DIRECTION_INPUT:
71             if (tryMMap) {
72                 stream = new AudioStreamInternalCapture(AAudioBinderClient::getInstance(),
73                                                                  false);
74             } else {
75                 stream = new AudioStreamRecord();
76             }
77             break;
78 
79         case AAUDIO_DIRECTION_OUTPUT:
80             if (tryMMap) {
81                 stream = new AudioStreamInternalPlay(AAudioBinderClient::getInstance(),
82                                                               false);
83             } else {
84                 stream = new AudioStreamTrack();
85             }
86             break;
87 
88         default:
89             ALOGE("%s() bad direction = %d", __func__, direction);
90             result = AAUDIO_ERROR_ILLEGAL_ARGUMENT;
91     }
92     return result;
93 }
94 
95 // Try to open using MMAP path if that is allowed.
96 // Fall back to Legacy path if MMAP not available.
97 // Exact behavior is controlled by MMapPolicy.
build(AudioStream ** streamPtr)98 aaudio_result_t AudioStreamBuilder::build(AudioStream** streamPtr) {
99 
100     if (streamPtr == nullptr) {
101         ALOGE("%s() streamPtr is null", __func__);
102         return AAUDIO_ERROR_NULL;
103     }
104     *streamPtr = nullptr;
105 
106     logParameters();
107 
108     aaudio_result_t result = validate();
109     if (result != AAUDIO_OK) {
110         return result;
111     }
112 
113     // The API setting is the highest priority.
114     aaudio_policy_t mmapPolicy = AudioGlobal_getMMapPolicy();
115     // If not specified then get from a system property.
116     if (mmapPolicy == AAUDIO_UNSPECIFIED) {
117         mmapPolicy = AAudioProperty_getMMapPolicy();
118     }
119     // If still not specified then use the default.
120     if (mmapPolicy == AAUDIO_UNSPECIFIED) {
121         mmapPolicy = AAUDIO_MMAP_POLICY_DEFAULT;
122     }
123 
124     int32_t mapExclusivePolicy = AAudioProperty_getMMapExclusivePolicy();
125     if (mapExclusivePolicy == AAUDIO_UNSPECIFIED) {
126         mapExclusivePolicy = AAUDIO_MMAP_EXCLUSIVE_POLICY_DEFAULT;
127     }
128 
129     aaudio_sharing_mode_t sharingMode = getSharingMode();
130     if ((sharingMode == AAUDIO_SHARING_MODE_EXCLUSIVE)
131         && (mapExclusivePolicy == AAUDIO_POLICY_NEVER)) {
132         ALOGD("%s() EXCLUSIVE sharing mode not supported. Use SHARED.", __func__);
133         sharingMode = AAUDIO_SHARING_MODE_SHARED;
134         setSharingMode(sharingMode);
135     }
136 
137     bool allowMMap = mmapPolicy != AAUDIO_POLICY_NEVER;
138     bool allowLegacy = mmapPolicy != AAUDIO_POLICY_ALWAYS;
139 
140     // TODO Support other performance settings in MMAP mode.
141     // Disable MMAP if low latency not requested.
142     if (getPerformanceMode() != AAUDIO_PERFORMANCE_MODE_LOW_LATENCY) {
143         ALOGD("%s() MMAP not used because AAUDIO_PERFORMANCE_MODE_LOW_LATENCY not requested.",
144               __func__);
145         allowMMap = false;
146     }
147 
148     // SessionID and Effects are only supported in Legacy mode.
149     if (getSessionId() != AAUDIO_SESSION_ID_NONE) {
150         ALOGD("%s() MMAP not used because sessionId specified.", __func__);
151         allowMMap = false;
152     }
153 
154     if (!allowMMap && !allowLegacy) {
155         ALOGE("%s() no backend available: neither MMAP nor legacy path are allowed", __func__);
156         return AAUDIO_ERROR_ILLEGAL_ARGUMENT;
157     }
158 
159     setPrivacySensitive(false);
160     if (mPrivacySensitiveReq == PRIVACY_SENSITIVE_DEFAULT) {
161         // When not explicitly requested, set privacy sensitive mode according to input preset:
162         // communication and camcorder captures are considered privacy sensitive by default.
163         aaudio_input_preset_t preset = getInputPreset();
164         if (preset == AAUDIO_INPUT_PRESET_CAMCORDER
165                 || preset == AAUDIO_INPUT_PRESET_VOICE_COMMUNICATION) {
166             setPrivacySensitive(true);
167         }
168     } else if (mPrivacySensitiveReq == PRIVACY_SENSITIVE_ENABLED) {
169         setPrivacySensitive(true);
170     }
171 
172     android::sp<AudioStream> audioStream;
173     result = builder_createStream(getDirection(), sharingMode, allowMMap, audioStream);
174     if (result == AAUDIO_OK) {
175         // Open the stream using the parameters from the builder.
176         result = audioStream->open(*this);
177         if (result != AAUDIO_OK) {
178             bool isMMap = audioStream->isMMap();
179             if (isMMap && allowLegacy) {
180                 ALOGV("%s() MMAP stream did not open so try Legacy path", __func__);
181                 // If MMAP stream failed to open then TRY using a legacy stream.
182                 result = builder_createStream(getDirection(), sharingMode,
183                                               false, audioStream);
184                 if (result == AAUDIO_OK) {
185                     result = audioStream->open(*this);
186                 }
187             }
188         }
189         if (result == AAUDIO_OK) {
190             audioStream->registerPlayerBase();
191             audioStream->logOpenActual();
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     ALOGI("opPackageName = %s", !getOpPackageName().has_value() ?
285         "(null)" : getOpPackageName().value().c_str());
286     ALOGI("attributionTag = %s", !getAttributionTag().has_value() ?
287         "(null)" : getAttributionTag().value().c_str());
288 }
289