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,AudioStream ** audioStreamPtr)63 static aaudio_result_t builder_createStream(aaudio_direction_t direction,
64                                          aaudio_sharing_mode_t sharingMode,
65                                          bool tryMMap,
66                                          AudioStream **audioStreamPtr) {
67     *audioStreamPtr = nullptr;
68     aaudio_result_t result = AAUDIO_OK;
69 
70     switch (direction) {
71 
72         case AAUDIO_DIRECTION_INPUT:
73             if (tryMMap) {
74                 *audioStreamPtr = new AudioStreamInternalCapture(AAudioBinderClient::getInstance(),
75                                                                  false);
76             } else {
77                 *audioStreamPtr = new AudioStreamRecord();
78             }
79             break;
80 
81         case AAUDIO_DIRECTION_OUTPUT:
82             if (tryMMap) {
83                 *audioStreamPtr = new AudioStreamInternalPlay(AAudioBinderClient::getInstance(),
84                                                               false);
85             } else {
86                 *audioStreamPtr = 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     AudioStream *audioStream = nullptr;
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     // The API setting is the highest priority.
116     aaudio_policy_t mmapPolicy = AudioGlobal_getMMapPolicy();
117     // If not specified then get from a system property.
118     if (mmapPolicy == AAUDIO_UNSPECIFIED) {
119         mmapPolicy = AAudioProperty_getMMapPolicy();
120     }
121     // If still not specified then use the default.
122     if (mmapPolicy == AAUDIO_UNSPECIFIED) {
123         mmapPolicy = AAUDIO_MMAP_POLICY_DEFAULT;
124     }
125 
126     int32_t mapExclusivePolicy = AAudioProperty_getMMapExclusivePolicy();
127     if (mapExclusivePolicy == AAUDIO_UNSPECIFIED) {
128         mapExclusivePolicy = AAUDIO_MMAP_EXCLUSIVE_POLICY_DEFAULT;
129     }
130 
131     aaudio_sharing_mode_t sharingMode = getSharingMode();
132     if ((sharingMode == AAUDIO_SHARING_MODE_EXCLUSIVE)
133         && (mapExclusivePolicy == AAUDIO_POLICY_NEVER)) {
134         ALOGD("%s() EXCLUSIVE sharing mode not supported. Use SHARED.", __func__);
135         sharingMode = AAUDIO_SHARING_MODE_SHARED;
136         setSharingMode(sharingMode);
137     }
138 
139     bool allowMMap = mmapPolicy != AAUDIO_POLICY_NEVER;
140     bool allowLegacy = mmapPolicy != AAUDIO_POLICY_ALWAYS;
141 
142     // TODO Support other performance settings in MMAP mode.
143     // Disable MMAP if low latency not requested.
144     if (getPerformanceMode() != AAUDIO_PERFORMANCE_MODE_LOW_LATENCY) {
145         ALOGD("%s() MMAP not used because AAUDIO_PERFORMANCE_MODE_LOW_LATENCY not requested.",
146               __func__);
147         allowMMap = false;
148     }
149 
150     // SessionID and Effects are only supported in Legacy mode.
151     if (getSessionId() != AAUDIO_SESSION_ID_NONE) {
152         ALOGD("%s() MMAP not used because sessionId specified.", __func__);
153         allowMMap = false;
154     }
155 
156     if (!allowMMap && !allowLegacy) {
157         ALOGE("%s() no backend available: neither MMAP nor legacy path are allowed", __func__);
158         return AAUDIO_ERROR_ILLEGAL_ARGUMENT;
159     }
160 
161     setPrivacySensitive(false);
162     if (mPrivacySensitiveReq == PRIVACY_SENSITIVE_DEFAULT) {
163         // When not explicitly requested, set privacy sensitive mode according to input preset:
164         // communication and camcorder captures are considered privacy sensitive by default.
165         aaudio_input_preset_t preset = getInputPreset();
166         if (preset == AAUDIO_INPUT_PRESET_CAMCORDER
167                 || preset == AAUDIO_INPUT_PRESET_VOICE_COMMUNICATION) {
168             setPrivacySensitive(true);
169         }
170     } else if (mPrivacySensitiveReq == PRIVACY_SENSITIVE_ENABLED) {
171         setPrivacySensitive(true);
172     }
173 
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             *streamPtr = audioStream;
180         } else {
181             bool isMMap = audioStream->isMMap();
182             delete audioStream;
183             audioStream = nullptr;
184 
185             if (isMMap && allowLegacy) {
186                 ALOGV("%s() MMAP stream did not open so try Legacy path", __func__);
187                 // If MMAP stream failed to open then TRY using a legacy stream.
188                 result = builder_createStream(getDirection(), sharingMode,
189                                               false, &audioStream);
190                 if (result == AAUDIO_OK) {
191                     result = audioStream->open(*this);
192                     if (result == AAUDIO_OK) {
193                         *streamPtr = audioStream;
194                     } else {
195                         delete audioStream;
196                         audioStream = nullptr;
197                     }
198                 }
199             }
200         }
201         if (audioStream != nullptr) {
202             audioStream->logOpen();
203         }
204     }
205 
206     return result;
207 }
208 
validate() const209 aaudio_result_t AudioStreamBuilder::validate() const {
210 
211     // Check for values that are ridiculously out of range to prevent math overflow exploits.
212     // The service will do a better check.
213     aaudio_result_t result = AAudioStreamParameters::validate();
214     if (result != AAUDIO_OK) {
215         return result;
216     }
217 
218     switch (mPerformanceMode) {
219         case AAUDIO_PERFORMANCE_MODE_NONE:
220         case AAUDIO_PERFORMANCE_MODE_POWER_SAVING:
221         case AAUDIO_PERFORMANCE_MODE_LOW_LATENCY:
222             break;
223         default:
224             ALOGE("illegal performanceMode = %d", mPerformanceMode);
225             return AAUDIO_ERROR_ILLEGAL_ARGUMENT;
226             // break;
227     }
228 
229     // Prevent ridiculous values from causing problems.
230     if (mFramesPerDataCallback != AAUDIO_UNSPECIFIED
231         && (mFramesPerDataCallback < FRAMES_PER_DATA_CALLBACK_MIN
232             || mFramesPerDataCallback > FRAMES_PER_DATA_CALLBACK_MAX)) {
233         ALOGE("framesPerDataCallback out of range = %d",
234               mFramesPerDataCallback);
235         return AAUDIO_ERROR_OUT_OF_RANGE;
236     }
237 
238     return AAUDIO_OK;
239 }
240 
AAudio_convertSharingModeToShortText(aaudio_sharing_mode_t sharingMode)241 static const char *AAudio_convertSharingModeToShortText(aaudio_sharing_mode_t sharingMode) {
242     switch (sharingMode) {
243         case AAUDIO_SHARING_MODE_EXCLUSIVE:
244             return "EX";
245         case AAUDIO_SHARING_MODE_SHARED:
246             return "SH";
247         default:
248             return "?!";
249     }
250 }
251 
AAudio_convertDirectionToText(aaudio_direction_t direction)252 static const char *AAudio_convertDirectionToText(aaudio_direction_t direction) {
253     switch (direction) {
254         case AAUDIO_DIRECTION_OUTPUT:
255             return "OUTPUT";
256         case AAUDIO_DIRECTION_INPUT:
257             return "INPUT";
258         default:
259             return "?!";
260     }
261 }
262 
logParameters() const263 void AudioStreamBuilder::logParameters() const {
264     // This is very helpful for debugging in the future. Please leave it in.
265     ALOGI("rate   = %6d, channels  = %d, format   = %d, sharing = %s, dir = %s",
266           getSampleRate(), getSamplesPerFrame(), getFormat(),
267           AAudio_convertSharingModeToShortText(getSharingMode()),
268           AAudio_convertDirectionToText(getDirection()));
269     ALOGI("device = %6d, sessionId = %d, perfMode = %d, callback: %s with frames = %d",
270           getDeviceId(),
271           getSessionId(),
272           getPerformanceMode(),
273           ((getDataCallbackProc() != nullptr) ? "ON" : "OFF"),
274           mFramesPerDataCallback);
275     ALOGI("usage  = %6d, contentType = %d, inputPreset = %d, allowedCapturePolicy = %d",
276           getUsage(), getContentType(), getInputPreset(), getAllowedCapturePolicy());
277     ALOGI("privacy sensitive = %s", isPrivacySensitive() ? "true" : "false");
278 }
279