1 /*
2 * Copyright 2016 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 "AudioStreamRecord"
18 //#define LOG_NDEBUG 0
19 #include <utils/Log.h>
20
21 #include <stdint.h>
22
23 #include <aaudio/AAudio.h>
24 #include <audio_utils/primitives.h>
25 #include <media/AidlConversion.h>
26 #include <media/AudioRecord.h>
27 #include <utils/String16.h>
28
29 #include "core/AudioGlobal.h"
30 #include "legacy/AudioStreamLegacy.h"
31 #include "legacy/AudioStreamRecord.h"
32 #include "utility/AudioClock.h"
33 #include "utility/FixedBlockWriter.h"
34
35 using android::content::AttributionSourceState;
36
37 using namespace android;
38 using namespace aaudio;
39
AudioStreamRecord()40 AudioStreamRecord::AudioStreamRecord()
41 : AudioStreamLegacy()
42 , mFixedBlockWriter(*this)
43 {
44 }
45
~AudioStreamRecord()46 AudioStreamRecord::~AudioStreamRecord()
47 {
48 const aaudio_stream_state_t state = getState();
49 bool bad = !(state == AAUDIO_STREAM_STATE_UNINITIALIZED || state == AAUDIO_STREAM_STATE_CLOSED);
50 ALOGE_IF(bad, "stream not closed, in state %d", state);
51 }
52
open(const AudioStreamBuilder & builder)53 aaudio_result_t AudioStreamRecord::open(const AudioStreamBuilder& builder)
54 {
55 aaudio_result_t result = AAUDIO_OK;
56
57 result = AudioStream::open(builder);
58 if (result != AAUDIO_OK) {
59 return result;
60 }
61
62 // Try to create an AudioRecord
63
64 const aaudio_session_id_t requestedSessionId = builder.getSessionId();
65 const audio_session_t sessionId = AAudioConvert_aaudioToAndroidSessionId(requestedSessionId);
66
67 // TODO Support UNSPECIFIED in AudioRecord. For now, use stereo if unspecified.
68 audio_channel_mask_t channelMask =
69 AAudio_getChannelMaskForOpen(getChannelMask(), getSamplesPerFrame(), true /*isInput*/);
70
71 size_t frameCount = (builder.getBufferCapacity() == AAUDIO_UNSPECIFIED) ? 0
72 : builder.getBufferCapacity();
73
74
75 audio_input_flags_t flags;
76 aaudio_performance_mode_t perfMode = getPerformanceMode();
77 switch (perfMode) {
78 case AAUDIO_PERFORMANCE_MODE_LOW_LATENCY:
79 // If the app asks for a sessionId then it means they want to use effects.
80 // So don't use RAW flag.
81 flags = (audio_input_flags_t) ((requestedSessionId == AAUDIO_SESSION_ID_NONE)
82 ? (AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW)
83 : (AUDIO_INPUT_FLAG_FAST));
84 break;
85
86 case AAUDIO_PERFORMANCE_MODE_POWER_SAVING:
87 case AAUDIO_PERFORMANCE_MODE_NONE:
88 default:
89 flags = AUDIO_INPUT_FLAG_NONE;
90 break;
91 }
92
93 const audio_format_t requestedFormat = getFormat();
94 // Preserve behavior of API 26
95 if (requestedFormat == AUDIO_FORMAT_DEFAULT) {
96 setFormat(AUDIO_FORMAT_PCM_FLOAT);
97 }
98
99
100 setDeviceFormat(getFormat());
101
102 // To avoid glitching, let AudioFlinger pick the optimal burst size.
103 uint32_t notificationFrames = 0;
104
105 // Setup the callback if there is one.
106 sp<AudioRecord::IAudioRecordCallback> callback;
107 AudioRecord::transfer_type streamTransferType = AudioRecord::transfer_type::TRANSFER_SYNC;
108 if (builder.getDataCallbackProc() != nullptr) {
109 streamTransferType = AudioRecord::transfer_type::TRANSFER_CALLBACK;
110 callback = sp<AudioRecord::IAudioRecordCallback>::fromExisting(this);
111 }
112 mCallbackBufferSize = builder.getFramesPerDataCallback();
113
114 // Don't call mAudioRecord->setInputDevice() because it will be overwritten by set()!
115 audio_port_handle_t selectedDeviceId = (getDeviceId() == AAUDIO_UNSPECIFIED)
116 ? AUDIO_PORT_HANDLE_NONE
117 : getDeviceId();
118
119 const audio_content_type_t contentType =
120 AAudioConvert_contentTypeToInternal(builder.getContentType());
121 const audio_source_t source =
122 AAudioConvert_inputPresetToAudioSource(builder.getInputPreset());
123
124 const audio_flags_mask_t attrFlags =
125 AAudioConvert_privacySensitiveToAudioFlagsMask(builder.isPrivacySensitive());
126 const audio_attributes_t attributes = {
127 .content_type = contentType,
128 .usage = AUDIO_USAGE_UNKNOWN, // only used for output
129 .source = source,
130 .flags = attrFlags, // Different than the AUDIO_INPUT_FLAGS
131 .tags = ""
132 };
133
134 // TODO b/182392769: use attribution source util
135 AttributionSourceState attributionSource;
136 attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(getuid()));
137 attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(getpid()));
138 attributionSource.packageName = builder.getOpPackageName();
139 attributionSource.attributionTag = builder.getAttributionTag();
140 attributionSource.token = sp<BBinder>::make();
141
142 // ----------- open the AudioRecord ---------------------
143 // Might retry, but never more than once.
144 for (int i = 0; i < 2; i ++) {
145 const audio_format_t requestedInternalFormat = getDeviceFormat();
146
147 mAudioRecord = new AudioRecord(
148 attributionSource
149 );
150 mAudioRecord->set(
151 AUDIO_SOURCE_DEFAULT, // ignored because we pass attributes below
152 getSampleRate(),
153 requestedInternalFormat,
154 channelMask,
155 frameCount,
156 callback,
157 notificationFrames,
158 false /*threadCanCallJava*/,
159 sessionId,
160 streamTransferType,
161 flags,
162 AUDIO_UID_INVALID, // DEFAULT uid
163 -1, // DEFAULT pid
164 &attributes,
165 selectedDeviceId
166 );
167
168 // Set it here so it can be logged by the destructor if the open failed.
169 mAudioRecord->setCallerName(kCallerName);
170
171 // Did we get a valid track?
172 status_t status = mAudioRecord->initCheck();
173 if (status != OK) {
174 safeReleaseClose();
175 ALOGE("open(), initCheck() returned %d", status);
176 return AAudioConvert_androidToAAudioResult(status);
177 }
178
179 // Check to see if it was worth hacking the deviceFormat.
180 bool gotFastPath = (mAudioRecord->getFlags() & AUDIO_INPUT_FLAG_FAST)
181 == AUDIO_INPUT_FLAG_FAST;
182 if (getFormat() != getDeviceFormat() && !gotFastPath) {
183 // We tried to get a FAST path by switching the device format.
184 // But it didn't work. So we might as well reopen using the same
185 // format for device and for app.
186 ALOGD("%s() used a different device format but no FAST path, reopen", __func__);
187 mAudioRecord.clear();
188 setDeviceFormat(getFormat());
189 } else {
190 break; // Keep the one we just opened.
191 }
192 }
193
194 mMetricsId = std::string(AMEDIAMETRICS_KEY_PREFIX_AUDIO_RECORD)
195 + std::to_string(mAudioRecord->getPortId());
196 android::mediametrics::LogItem(mMetricsId)
197 .set(AMEDIAMETRICS_PROP_PERFORMANCEMODE,
198 AudioGlobal_convertPerformanceModeToText(builder.getPerformanceMode()))
199 .set(AMEDIAMETRICS_PROP_SHARINGMODE,
200 AudioGlobal_convertSharingModeToText(builder.getSharingMode()))
201 .set(AMEDIAMETRICS_PROP_ENCODINGCLIENT, toString(requestedFormat).c_str()).record();
202
203 // Get the actual values from the AudioRecord.
204 setChannelMask(AAudioConvert_androidToAAudioChannelMask(
205 mAudioRecord->channelMask(), true /*isInput*/,
206 AAudio_isChannelIndexMask(getChannelMask())));
207 setSampleRate(mAudioRecord->getSampleRate());
208 setBufferCapacity(getBufferCapacityFromDevice());
209 setFramesPerBurst(getFramesPerBurstFromDevice());
210
211 // Use the same values for device values.
212 setDeviceSamplesPerFrame(getSamplesPerFrame());
213 setDeviceSampleRate(mAudioRecord->getSampleRate());
214 setDeviceBufferCapacity(getBufferCapacityFromDevice());
215 setDeviceFramesPerBurst(getFramesPerBurstFromDevice());
216
217 setHardwareSamplesPerFrame(mAudioRecord->getHalChannelCount());
218 setHardwareSampleRate(mAudioRecord->getHalSampleRate());
219 setHardwareFormat(mAudioRecord->getHalFormat());
220
221 // We may need to pass the data through a block size adapter to guarantee constant size.
222 if (mCallbackBufferSize != AAUDIO_UNSPECIFIED) {
223 // The block adapter runs before the format conversion.
224 // So we need to use the device frame size.
225 mBlockAdapterBytesPerFrame = getBytesPerDeviceFrame();
226 int callbackSizeBytes = mBlockAdapterBytesPerFrame * mCallbackBufferSize;
227 mFixedBlockWriter.open(callbackSizeBytes);
228 mBlockAdapter = &mFixedBlockWriter;
229 } else {
230 mBlockAdapter = nullptr;
231 }
232
233 // Allocate format conversion buffer if needed.
234 if (getDeviceFormat() == AUDIO_FORMAT_PCM_16_BIT
235 && getFormat() == AUDIO_FORMAT_PCM_FLOAT) {
236
237 if (builder.getDataCallbackProc() != nullptr) {
238 // If we have a callback then we need to convert the data into an internal float
239 // array and then pass that entire array to the app.
240 mFormatConversionBufferSizeInFrames =
241 (mCallbackBufferSize != AAUDIO_UNSPECIFIED)
242 ? mCallbackBufferSize : getFramesPerBurst();
243 int32_t numSamples = mFormatConversionBufferSizeInFrames * getSamplesPerFrame();
244 mFormatConversionBufferFloat = std::make_unique<float[]>(numSamples);
245 } else {
246 // If we don't have a callback then we will read into an internal short array
247 // and then convert into the app float array in read().
248 mFormatConversionBufferSizeInFrames = getFramesPerBurst();
249 int32_t numSamples = mFormatConversionBufferSizeInFrames * getSamplesPerFrame();
250 mFormatConversionBufferI16 = std::make_unique<int16_t[]>(numSamples);
251 }
252 ALOGD("%s() setup I16>FLOAT conversion buffer with %d frames",
253 __func__, mFormatConversionBufferSizeInFrames);
254 }
255
256 // Update performance mode based on the actual stream.
257 // For example, if the sample rate does not match native then you won't get a FAST track.
258 audio_input_flags_t actualFlags = mAudioRecord->getFlags();
259 aaudio_performance_mode_t actualPerformanceMode = AAUDIO_PERFORMANCE_MODE_NONE;
260 // FIXME Some platforms do not advertise RAW mode for low latency inputs.
261 if ((actualFlags & (AUDIO_INPUT_FLAG_FAST))
262 == (AUDIO_INPUT_FLAG_FAST)) {
263 actualPerformanceMode = AAUDIO_PERFORMANCE_MODE_LOW_LATENCY;
264 }
265 setPerformanceMode(actualPerformanceMode);
266
267 setSharingMode(AAUDIO_SHARING_MODE_SHARED); // EXCLUSIVE mode not supported in legacy
268
269 // Log warning if we did not get what we asked for.
270 ALOGW_IF(actualFlags != flags,
271 "open() flags changed from 0x%08X to 0x%08X",
272 flags, actualFlags);
273 ALOGW_IF(actualPerformanceMode != perfMode,
274 "open() perfMode changed from %d to %d",
275 perfMode, actualPerformanceMode);
276
277 setState(AAUDIO_STREAM_STATE_OPEN);
278 setDeviceId(mAudioRecord->getRoutedDeviceId());
279
280 aaudio_session_id_t actualSessionId =
281 (requestedSessionId == AAUDIO_SESSION_ID_NONE)
282 ? AAUDIO_SESSION_ID_NONE
283 : (aaudio_session_id_t) mAudioRecord->getSessionId();
284 setSessionId(actualSessionId);
285
286 mAudioRecord->addAudioDeviceCallback(this);
287
288 return AAUDIO_OK;
289 }
290
release_l()291 aaudio_result_t AudioStreamRecord::release_l() {
292 // TODO add close() or release() to AudioFlinger's AudioRecord API.
293 // Then call it from here
294 if (getState() != AAUDIO_STREAM_STATE_CLOSING) {
295 mAudioRecord->removeAudioDeviceCallback(this);
296 logReleaseBufferState();
297 // Data callbacks may still be running!
298 return AudioStream::release_l();
299 } else {
300 return AAUDIO_OK; // already released
301 }
302 }
303
close_l()304 void AudioStreamRecord::close_l() {
305 // The callbacks are normally joined in the AudioRecord destructor.
306 // But if another object has a reference to the AudioRecord then
307 // it will not get deleted here.
308 // So we should join callbacks explicitly before returning.
309 // Unlock around the join to avoid deadlocks if the callback tries to lock.
310 // This can happen if the callback returns AAUDIO_CALLBACK_RESULT_STOP
311 mStreamLock.unlock();
312 mAudioRecord->stopAndJoinCallbacks();
313 mStreamLock.lock();
314
315 mAudioRecord.clear();
316 // Do not close mFixedBlockReader. It has a unique_ptr to its buffer
317 // so it will clean up by itself.
318 AudioStream::close_l();
319 }
320
maybeConvertDeviceData(const void * audioData,int32_t numFrames)321 const void * AudioStreamRecord::maybeConvertDeviceData(const void *audioData, int32_t numFrames) {
322 if (mFormatConversionBufferFloat.get() != nullptr) {
323 LOG_ALWAYS_FATAL_IF(numFrames > mFormatConversionBufferSizeInFrames,
324 "%s() conversion size %d too large for buffer %d",
325 __func__, numFrames, mFormatConversionBufferSizeInFrames);
326
327 int32_t numSamples = numFrames * getSamplesPerFrame();
328 // Only conversion supported is I16 to FLOAT
329 memcpy_to_float_from_i16(
330 mFormatConversionBufferFloat.get(),
331 (const int16_t *) audioData,
332 numSamples);
333 return mFormatConversionBufferFloat.get();
334 } else {
335 return audioData;
336 }
337 }
338
requestStart_l()339 aaudio_result_t AudioStreamRecord::requestStart_l()
340 {
341 if (mAudioRecord.get() == nullptr) {
342 return AAUDIO_ERROR_INVALID_STATE;
343 }
344
345 // Enable callback before starting AudioRecord to avoid shutting
346 // down because of a race condition.
347 mCallbackEnabled.store(true);
348 aaudio_stream_state_t originalState = getState();
349 // Set before starting the callback so that we are in the correct state
350 // before updateStateMachine() can be called by the callback.
351 setState(AAUDIO_STREAM_STATE_STARTING);
352 mFramesWritten.reset32(); // service writes frames
353 mTimestampPosition.reset32();
354 status_t err = mAudioRecord->start(); // resets position to zero
355 if (err != OK) {
356 mCallbackEnabled.store(false);
357 setState(originalState);
358 return AAudioConvert_androidToAAudioResult(err);
359 }
360 return AAUDIO_OK;
361 }
362
requestStop_l()363 aaudio_result_t AudioStreamRecord::requestStop_l() {
364 if (mAudioRecord.get() == nullptr) {
365 return AAUDIO_ERROR_INVALID_STATE;
366 }
367 setState(AAUDIO_STREAM_STATE_STOPPING);
368 mFramesWritten.catchUpTo(getFramesRead());
369 mTimestampPosition.catchUpTo(getFramesRead());
370 mAudioRecord->stop();
371 mCallbackEnabled.store(false);
372 // Pass false to prevent errorCallback from being called after disconnect
373 // when app has already requested a stop().
374 return checkForDisconnectRequest(false);
375 }
376
processCommands()377 aaudio_result_t AudioStreamRecord::processCommands() {
378 aaudio_result_t result = AAUDIO_OK;
379 aaudio_wrapping_frames_t position;
380 status_t err;
381 switch (getState()) {
382 // TODO add better state visibility to AudioRecord
383 case AAUDIO_STREAM_STATE_STARTING:
384 // When starting, the position will begin at zero and then go positive.
385 // The position can wrap but by that time the state will not be STARTING.
386 err = mAudioRecord->getPosition(&position);
387 if (err != OK) {
388 result = AAudioConvert_androidToAAudioResult(err);
389 } else if (position > 0) {
390 setState(AAUDIO_STREAM_STATE_STARTED);
391 }
392 break;
393 case AAUDIO_STREAM_STATE_STOPPING:
394 if (mAudioRecord->stopped()) {
395 setState(AAUDIO_STREAM_STATE_STOPPED);
396 }
397 break;
398 default:
399 break;
400 }
401 return result;
402 }
403
read(void * buffer,int32_t numFrames,int64_t timeoutNanoseconds)404 aaudio_result_t AudioStreamRecord::read(void *buffer,
405 int32_t numFrames,
406 int64_t timeoutNanoseconds)
407 {
408 int32_t bytesPerDeviceFrame = getBytesPerDeviceFrame();
409 int32_t numBytes;
410 // This will detect out of range values for numFrames.
411 aaudio_result_t result = AAudioConvert_framesToBytes(numFrames, bytesPerDeviceFrame, &numBytes);
412 if (result != AAUDIO_OK) {
413 return result;
414 }
415
416 if (isDisconnected()) {
417 return AAUDIO_ERROR_DISCONNECTED;
418 }
419
420 // TODO add timeout to AudioRecord
421 bool blocking = (timeoutNanoseconds > 0);
422
423 ssize_t bytesActuallyRead = 0;
424 ssize_t totalBytesRead = 0;
425 if (mFormatConversionBufferI16.get() != nullptr) {
426 // Convert I16 data to float using an intermediate buffer.
427 float *floatBuffer = (float *) buffer;
428 int32_t framesLeft = numFrames;
429 // Perform conversion using multiple read()s if necessary.
430 while (framesLeft > 0) {
431 // Read into short internal buffer.
432 int32_t framesToRead = std::min(framesLeft, mFormatConversionBufferSizeInFrames);
433 size_t bytesToRead = framesToRead * bytesPerDeviceFrame;
434 bytesActuallyRead = mAudioRecord->read(mFormatConversionBufferI16.get(), bytesToRead, blocking);
435 if (bytesActuallyRead <= 0) {
436 break;
437 }
438 totalBytesRead += bytesActuallyRead;
439 int32_t framesToConvert = bytesActuallyRead / bytesPerDeviceFrame;
440 // Convert into app float buffer.
441 size_t numSamples = framesToConvert * getSamplesPerFrame();
442 memcpy_to_float_from_i16(
443 floatBuffer,
444 mFormatConversionBufferI16.get(),
445 numSamples);
446 floatBuffer += numSamples;
447 framesLeft -= framesToConvert;
448 }
449 } else {
450 bytesActuallyRead = mAudioRecord->read(buffer, numBytes, blocking);
451 totalBytesRead = bytesActuallyRead;
452 }
453 if (bytesActuallyRead == WOULD_BLOCK) {
454 return 0;
455 } else if (bytesActuallyRead < 0) {
456 // In this context, a DEAD_OBJECT is more likely to be a disconnect notification due to
457 // AudioRecord invalidation.
458 if (bytesActuallyRead == DEAD_OBJECT) {
459 setDisconnected();
460 return AAUDIO_ERROR_DISCONNECTED;
461 }
462 return AAudioConvert_androidToAAudioResult(bytesActuallyRead);
463 }
464 int32_t framesRead = (int32_t)(totalBytesRead / bytesPerDeviceFrame);
465 incrementFramesRead(framesRead);
466
467 result = updateStateMachine();
468 if (result != AAUDIO_OK) {
469 return result;
470 }
471
472 return (aaudio_result_t) framesRead;
473 }
474
setBufferSize(int32_t)475 aaudio_result_t AudioStreamRecord::setBufferSize(int32_t /*requestedFrames*/)
476 {
477 return getBufferSize();
478 }
479
getBufferSize() const480 int32_t AudioStreamRecord::getBufferSize() const
481 {
482 return getBufferCapacity(); // TODO implement in AudioRecord?
483 }
484
getBufferCapacityFromDevice() const485 int32_t AudioStreamRecord::getBufferCapacityFromDevice() const
486 {
487 return static_cast<int32_t>(mAudioRecord->frameCount());
488 }
489
getXRunCount() const490 int32_t AudioStreamRecord::getXRunCount() const
491 {
492 return 0; // TODO implement when AudioRecord supports it
493 }
494
getFramesPerBurstFromDevice() const495 int32_t AudioStreamRecord::getFramesPerBurstFromDevice() const {
496 return static_cast<int32_t>(mAudioRecord->getNotificationPeriodInFrames());
497 }
498
getTimestamp(clockid_t clockId,int64_t * framePosition,int64_t * timeNanoseconds)499 aaudio_result_t AudioStreamRecord::getTimestamp(clockid_t clockId,
500 int64_t *framePosition,
501 int64_t *timeNanoseconds) {
502 ExtendedTimestamp extendedTimestamp;
503 if (getState() != AAUDIO_STREAM_STATE_STARTED) {
504 return AAUDIO_ERROR_INVALID_STATE;
505 }
506 status_t status = mAudioRecord->getTimestamp(&extendedTimestamp);
507 if (status == WOULD_BLOCK) {
508 return AAUDIO_ERROR_INVALID_STATE;
509 } else if (status != NO_ERROR) {
510 return AAudioConvert_androidToAAudioResult(status);
511 }
512 return getBestTimestamp(clockId, framePosition, timeNanoseconds, &extendedTimestamp);
513 }
514
getFramesWritten()515 int64_t AudioStreamRecord::getFramesWritten() {
516 aaudio_wrapping_frames_t position;
517 status_t result;
518 switch (getState()) {
519 case AAUDIO_STREAM_STATE_STARTING:
520 case AAUDIO_STREAM_STATE_STARTED:
521 result = mAudioRecord->getPosition(&position);
522 if (result == OK) {
523 mFramesWritten.update32((int32_t)position);
524 }
525 break;
526 case AAUDIO_STREAM_STATE_STOPPING:
527 default:
528 break;
529 }
530 return AudioStreamLegacy::getFramesWritten();
531 }
532