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