• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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/AudioRecord.h>
26 #include <utils/String16.h>
27 
28 #include "legacy/AudioStreamLegacy.h"
29 #include "legacy/AudioStreamRecord.h"
30 #include "utility/AudioClock.h"
31 #include "utility/FixedBlockWriter.h"
32 
33 using namespace android;
34 using namespace aaudio;
35 
AudioStreamRecord()36 AudioStreamRecord::AudioStreamRecord()
37     : AudioStreamLegacy()
38     , mFixedBlockWriter(*this)
39 {
40 }
41 
~AudioStreamRecord()42 AudioStreamRecord::~AudioStreamRecord()
43 {
44     const aaudio_stream_state_t state = getState();
45     bool bad = !(state == AAUDIO_STREAM_STATE_UNINITIALIZED || state == AAUDIO_STREAM_STATE_CLOSED);
46     ALOGE_IF(bad, "stream not closed, in state %d", state);
47 }
48 
open(const AudioStreamBuilder & builder)49 aaudio_result_t AudioStreamRecord::open(const AudioStreamBuilder& builder)
50 {
51     aaudio_result_t result = AAUDIO_OK;
52 
53     result = AudioStream::open(builder);
54     if (result != AAUDIO_OK) {
55         return result;
56     }
57 
58     // Try to create an AudioRecord
59 
60     const aaudio_session_id_t requestedSessionId = builder.getSessionId();
61     const audio_session_t sessionId = AAudioConvert_aaudioToAndroidSessionId(requestedSessionId);
62 
63     // TODO Support UNSPECIFIED in AudioRecord. For now, use stereo if unspecified.
64     int32_t samplesPerFrame = (getSamplesPerFrame() == AAUDIO_UNSPECIFIED)
65                               ? 2 : getSamplesPerFrame();
66     audio_channel_mask_t channelMask = samplesPerFrame <= 2 ?
67                                audio_channel_in_mask_from_count(samplesPerFrame) :
68                                audio_channel_mask_for_index_assignment_from_count(samplesPerFrame);
69 
70     size_t frameCount = (builder.getBufferCapacity() == AAUDIO_UNSPECIFIED) ? 0
71                         : builder.getBufferCapacity();
72 
73 
74     audio_input_flags_t flags;
75     aaudio_performance_mode_t perfMode = getPerformanceMode();
76     switch (perfMode) {
77         case AAUDIO_PERFORMANCE_MODE_LOW_LATENCY:
78             // If the app asks for a sessionId then it means they want to use effects.
79             // So don't use RAW flag.
80             flags = (audio_input_flags_t) ((requestedSessionId == AAUDIO_SESSION_ID_NONE)
81                     ? (AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW)
82                     : (AUDIO_INPUT_FLAG_FAST));
83             break;
84 
85         case AAUDIO_PERFORMANCE_MODE_POWER_SAVING:
86         case AAUDIO_PERFORMANCE_MODE_NONE:
87         default:
88             flags = AUDIO_INPUT_FLAG_NONE;
89             break;
90     }
91 
92     // Preserve behavior of API 26
93     if (getFormat() == AUDIO_FORMAT_DEFAULT) {
94         setFormat(AUDIO_FORMAT_PCM_FLOAT);
95     }
96 
97     // Maybe change device format to get a FAST path.
98     // AudioRecord does not support FAST mode for FLOAT data.
99     // TODO AudioRecord should allow FLOAT data paths for FAST tracks.
100     // So IF the user asks for low latency FLOAT
101     // AND the sampleRate is likely to be compatible with FAST
102     // THEN request I16 and convert to FLOAT when passing to user.
103     // Note that hard coding 48000 Hz is not ideal because the sampleRate
104     // for a FAST path might not be 48000 Hz.
105     // It normally is but there is a chance that it is not.
106     // And there is no reliable way to know that in advance.
107     // Luckily the consequences of a wrong guess are minor.
108     // We just may not get a FAST track.
109     // But we wouldn't have anyway without this hack.
110     constexpr int32_t kMostLikelySampleRateForFast = 48000;
111     if (getFormat() == AUDIO_FORMAT_PCM_FLOAT
112             && perfMode == AAUDIO_PERFORMANCE_MODE_LOW_LATENCY
113             && (samplesPerFrame <= 2) // FAST only for mono and stereo
114             && (getSampleRate() == kMostLikelySampleRateForFast
115                 || getSampleRate() == AAUDIO_UNSPECIFIED)) {
116         setDeviceFormat(AUDIO_FORMAT_PCM_16_BIT);
117     } else {
118         setDeviceFormat(getFormat());
119     }
120 
121     uint32_t notificationFrames = 0;
122 
123     // Setup the callback if there is one.
124     AudioRecord::callback_t callback = nullptr;
125     void *callbackData = nullptr;
126     AudioRecord::transfer_type streamTransferType = AudioRecord::transfer_type::TRANSFER_SYNC;
127     if (builder.getDataCallbackProc() != nullptr) {
128         streamTransferType = AudioRecord::transfer_type::TRANSFER_CALLBACK;
129         callback = getLegacyCallback();
130         callbackData = this;
131         notificationFrames = builder.getFramesPerDataCallback();
132     }
133     mCallbackBufferSize = builder.getFramesPerDataCallback();
134 
135     // Don't call mAudioRecord->setInputDevice() because it will be overwritten by set()!
136     audio_port_handle_t selectedDeviceId = (getDeviceId() == AAUDIO_UNSPECIFIED)
137                                            ? AUDIO_PORT_HANDLE_NONE
138                                            : getDeviceId();
139 
140     const audio_content_type_t contentType =
141             AAudioConvert_contentTypeToInternal(builder.getContentType());
142     const audio_source_t source =
143             AAudioConvert_inputPresetToAudioSource(builder.getInputPreset());
144 
145     const audio_flags_mask_t attrFlags =
146             AAudioConvert_privacySensitiveToAudioFlagsMask(builder.isPrivacySensitive());
147     const audio_attributes_t attributes = {
148             .content_type = contentType,
149             .usage = AUDIO_USAGE_UNKNOWN, // only used for output
150             .source = source,
151             .flags = attrFlags, // Different than the AUDIO_INPUT_FLAGS
152             .tags = ""
153     };
154 
155     // ----------- open the AudioRecord ---------------------
156     // Might retry, but never more than once.
157     for (int i = 0; i < 2; i ++) {
158         const audio_format_t requestedInternalFormat = getDeviceFormat();
159 
160         mAudioRecord = new AudioRecord(
161                 mOpPackageName // const String16& opPackageName TODO does not compile
162         );
163         mAudioRecord->set(
164                 AUDIO_SOURCE_DEFAULT, // ignored because we pass attributes below
165                 getSampleRate(),
166                 requestedInternalFormat,
167                 channelMask,
168                 frameCount,
169                 callback,
170                 callbackData,
171                 notificationFrames,
172                 false /*threadCanCallJava*/,
173                 sessionId,
174                 streamTransferType,
175                 flags,
176                 AUDIO_UID_INVALID, // DEFAULT uid
177                 -1,                // DEFAULT pid
178                 &attributes,
179                 selectedDeviceId
180         );
181 
182         // Set it here so it can be logged by the destructor if the open failed.
183         mAudioRecord->setCallerName(kCallerName);
184 
185         // Did we get a valid track?
186         status_t status = mAudioRecord->initCheck();
187         if (status != OK) {
188             releaseCloseFinal();
189             ALOGE("open(), initCheck() returned %d", status);
190             return AAudioConvert_androidToAAudioResult(status);
191         }
192 
193         // Check to see if it was worth hacking the deviceFormat.
194         bool gotFastPath = (mAudioRecord->getFlags() & AUDIO_INPUT_FLAG_FAST)
195                            == AUDIO_INPUT_FLAG_FAST;
196         if (getFormat() != getDeviceFormat() && !gotFastPath) {
197             // We tried to get a FAST path by switching the device format.
198             // But it didn't work. So we might as well reopen using the same
199             // format for device and for app.
200             ALOGD("%s() used a different device format but no FAST path, reopen", __func__);
201             mAudioRecord.clear();
202             setDeviceFormat(getFormat());
203         } else {
204             break; // Keep the one we just opened.
205         }
206     }
207 
208     mMetricsId = std::string(AMEDIAMETRICS_KEY_PREFIX_AUDIO_RECORD)
209             + std::to_string(mAudioRecord->getPortId());
210 
211     // Get the actual values from the AudioRecord.
212     setSamplesPerFrame(mAudioRecord->channelCount());
213 
214     int32_t actualSampleRate = mAudioRecord->getSampleRate();
215     ALOGW_IF(actualSampleRate != getSampleRate(),
216              "open() sampleRate changed from %d to %d",
217              getSampleRate(), actualSampleRate);
218     setSampleRate(actualSampleRate);
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     setDeviceId(mAudioRecord->getRoutedDeviceId());
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     mAudioRecord.clear();
305     // Do not close mFixedBlockWriter because a data callback
306     // thread might still be running if someone else has a reference
307     // to mAudioRecord.
308     // It has a unique_ptr to its buffer so it will clean up by itself.
309     AudioStream::close_l();
310 }
311 
maybeConvertDeviceData(const void * audioData,int32_t numFrames)312 const void * AudioStreamRecord::maybeConvertDeviceData(const void *audioData, int32_t numFrames) {
313     if (mFormatConversionBufferFloat.get() != nullptr) {
314         LOG_ALWAYS_FATAL_IF(numFrames > mFormatConversionBufferSizeInFrames,
315                             "%s() conversion size %d too large for buffer %d",
316                             __func__, numFrames, mFormatConversionBufferSizeInFrames);
317 
318         int32_t numSamples = numFrames * getSamplesPerFrame();
319         // Only conversion supported is I16 to FLOAT
320         memcpy_to_float_from_i16(
321                     mFormatConversionBufferFloat.get(),
322                     (const int16_t *) audioData,
323                     numSamples);
324         return mFormatConversionBufferFloat.get();
325     } else {
326         return audioData;
327     }
328 }
329 
processCallback(int event,void * info)330 void AudioStreamRecord::processCallback(int event, void *info) {
331     switch (event) {
332         case AudioRecord::EVENT_MORE_DATA:
333             processCallbackCommon(AAUDIO_CALLBACK_OPERATION_PROCESS_DATA, info);
334             break;
335 
336             // Stream got rerouted so we disconnect.
337         case AudioRecord::EVENT_NEW_IAUDIORECORD:
338             processCallbackCommon(AAUDIO_CALLBACK_OPERATION_DISCONNECTED, info);
339             break;
340 
341         default:
342             break;
343     }
344     return;
345 }
346 
requestStart()347 aaudio_result_t AudioStreamRecord::requestStart()
348 {
349     if (mAudioRecord.get() == nullptr) {
350         return AAUDIO_ERROR_INVALID_STATE;
351     }
352 
353     // Enable callback before starting AudioRecord to avoid shutting
354     // down because of a race condition.
355     mCallbackEnabled.store(true);
356     aaudio_stream_state_t originalState = getState();
357     // Set before starting the callback so that we are in the correct state
358     // before updateStateMachine() can be called by the callback.
359     setState(AAUDIO_STREAM_STATE_STARTING);
360     mFramesWritten.reset32(); // service writes frames
361     mTimestampPosition.reset32();
362     status_t err = mAudioRecord->start(); // resets position to zero
363     if (err != OK) {
364         mCallbackEnabled.store(false);
365         setState(originalState);
366         return AAudioConvert_androidToAAudioResult(err);
367     }
368     return AAUDIO_OK;
369 }
370 
requestStop()371 aaudio_result_t AudioStreamRecord::requestStop() {
372     if (mAudioRecord.get() == nullptr) {
373         return AAUDIO_ERROR_INVALID_STATE;
374     }
375     setState(AAUDIO_STREAM_STATE_STOPPING);
376     mFramesWritten.catchUpTo(getFramesRead());
377     mTimestampPosition.catchUpTo(getFramesRead());
378     mAudioRecord->stop();
379     mCallbackEnabled.store(false);
380     // Pass false to prevent errorCallback from being called after disconnect
381     // when app has already requested a stop().
382     return checkForDisconnectRequest(false);
383 }
384 
updateStateMachine()385 aaudio_result_t AudioStreamRecord::updateStateMachine()
386 {
387     aaudio_result_t result = AAUDIO_OK;
388     aaudio_wrapping_frames_t position;
389     status_t err;
390     switch (getState()) {
391     // TODO add better state visibility to AudioRecord
392     case AAUDIO_STREAM_STATE_STARTING:
393         // When starting, the position will begin at zero and then go positive.
394         // The position can wrap but by that time the state will not be STARTING.
395         err = mAudioRecord->getPosition(&position);
396         if (err != OK) {
397             result = AAudioConvert_androidToAAudioResult(err);
398         } else if (position > 0) {
399             setState(AAUDIO_STREAM_STATE_STARTED);
400         }
401         break;
402     case AAUDIO_STREAM_STATE_STOPPING:
403         if (mAudioRecord->stopped()) {
404             setState(AAUDIO_STREAM_STATE_STOPPED);
405         }
406         break;
407     default:
408         break;
409     }
410     return result;
411 }
412 
read(void * buffer,int32_t numFrames,int64_t timeoutNanoseconds)413 aaudio_result_t AudioStreamRecord::read(void *buffer,
414                                       int32_t numFrames,
415                                       int64_t timeoutNanoseconds)
416 {
417     int32_t bytesPerDeviceFrame = getBytesPerDeviceFrame();
418     int32_t numBytes;
419     // This will detect out of range values for numFrames.
420     aaudio_result_t result = AAudioConvert_framesToBytes(numFrames, bytesPerDeviceFrame, &numBytes);
421     if (result != AAUDIO_OK) {
422         return result;
423     }
424 
425     if (getState() == AAUDIO_STREAM_STATE_DISCONNECTED) {
426         return AAUDIO_ERROR_DISCONNECTED;
427     }
428 
429     // TODO add timeout to AudioRecord
430     bool blocking = (timeoutNanoseconds > 0);
431 
432     ssize_t bytesActuallyRead = 0;
433     ssize_t totalBytesRead = 0;
434     if (mFormatConversionBufferI16.get() != nullptr) {
435         // Convert I16 data to float using an intermediate buffer.
436         float *floatBuffer = (float *) buffer;
437         int32_t framesLeft = numFrames;
438         // Perform conversion using multiple read()s if necessary.
439         while (framesLeft > 0) {
440             // Read into short internal buffer.
441             int32_t framesToRead = std::min(framesLeft, mFormatConversionBufferSizeInFrames);
442             size_t bytesToRead = framesToRead * bytesPerDeviceFrame;
443             bytesActuallyRead = mAudioRecord->read(mFormatConversionBufferI16.get(), bytesToRead, blocking);
444             if (bytesActuallyRead <= 0) {
445                 break;
446             }
447             totalBytesRead += bytesActuallyRead;
448             int32_t framesToConvert = bytesActuallyRead / bytesPerDeviceFrame;
449             // Convert into app float buffer.
450             size_t numSamples = framesToConvert * getSamplesPerFrame();
451             memcpy_to_float_from_i16(
452                     floatBuffer,
453                     mFormatConversionBufferI16.get(),
454                     numSamples);
455             floatBuffer += numSamples;
456             framesLeft -= framesToConvert;
457         }
458     } else {
459         bytesActuallyRead = mAudioRecord->read(buffer, numBytes, blocking);
460         totalBytesRead = bytesActuallyRead;
461     }
462     if (bytesActuallyRead == WOULD_BLOCK) {
463         return 0;
464     } else if (bytesActuallyRead < 0) {
465         // In this context, a DEAD_OBJECT is more likely to be a disconnect notification due to
466         // AudioRecord invalidation.
467         if (bytesActuallyRead == DEAD_OBJECT) {
468             setState(AAUDIO_STREAM_STATE_DISCONNECTED);
469             return AAUDIO_ERROR_DISCONNECTED;
470         }
471         return AAudioConvert_androidToAAudioResult(bytesActuallyRead);
472     }
473     int32_t framesRead = (int32_t)(totalBytesRead / bytesPerDeviceFrame);
474     incrementFramesRead(framesRead);
475 
476     result = updateStateMachine();
477     if (result != AAUDIO_OK) {
478         return result;
479     }
480 
481     return (aaudio_result_t) framesRead;
482 }
483 
setBufferSize(int32_t requestedFrames)484 aaudio_result_t AudioStreamRecord::setBufferSize(int32_t requestedFrames)
485 {
486     return getBufferSize();
487 }
488 
getBufferSize() const489 int32_t AudioStreamRecord::getBufferSize() const
490 {
491     return getBufferCapacity(); // TODO implement in AudioRecord?
492 }
493 
getBufferCapacity() const494 int32_t AudioStreamRecord::getBufferCapacity() const
495 {
496     return static_cast<int32_t>(mAudioRecord->frameCount());
497 }
498 
getXRunCount() const499 int32_t AudioStreamRecord::getXRunCount() const
500 {
501     return 0; // TODO implement when AudioRecord supports it
502 }
503 
getFramesPerBurst() const504 int32_t AudioStreamRecord::getFramesPerBurst() const
505 {
506     return static_cast<int32_t>(mAudioRecord->getNotificationPeriodInFrames());
507 }
508 
getTimestamp(clockid_t clockId,int64_t * framePosition,int64_t * timeNanoseconds)509 aaudio_result_t AudioStreamRecord::getTimestamp(clockid_t clockId,
510                                                int64_t *framePosition,
511                                                int64_t *timeNanoseconds) {
512     ExtendedTimestamp extendedTimestamp;
513     if (getState() != AAUDIO_STREAM_STATE_STARTED) {
514         return AAUDIO_ERROR_INVALID_STATE;
515     }
516     status_t status = mAudioRecord->getTimestamp(&extendedTimestamp);
517     if (status == WOULD_BLOCK) {
518         return AAUDIO_ERROR_INVALID_STATE;
519     } else if (status != NO_ERROR) {
520         return AAudioConvert_androidToAAudioResult(status);
521     }
522     return getBestTimestamp(clockId, framePosition, timeNanoseconds, &extendedTimestamp);
523 }
524 
getFramesWritten()525 int64_t AudioStreamRecord::getFramesWritten() {
526     aaudio_wrapping_frames_t position;
527     status_t result;
528     switch (getState()) {
529         case AAUDIO_STREAM_STATE_STARTING:
530         case AAUDIO_STREAM_STATE_STARTED:
531             result = mAudioRecord->getPosition(&position);
532             if (result == OK) {
533                 mFramesWritten.update32(position);
534             }
535             break;
536         case AAUDIO_STREAM_STATE_STOPPING:
537         default:
538             break;
539     }
540     return AudioStreamLegacy::getFramesWritten();
541 }
542