1 /* 2 * Copyright (C) 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 // This file is used in both client and server processes. 18 // This is needed to make sense of the logs more easily. 19 #define LOG_TAG (mInService ? "AudioStreamInternal_Service" : "AudioStreamInternal_Client") 20 //#define LOG_NDEBUG 0 21 #include <utils/Log.h> 22 23 #define ATRACE_TAG ATRACE_TAG_AUDIO 24 25 #include <stdint.h> 26 27 #include <binder/IServiceManager.h> 28 29 #include <aaudio/AAudio.h> 30 #include <cutils/properties.h> 31 #include <utils/String16.h> 32 #include <utils/Trace.h> 33 34 #include "AudioEndpointParcelable.h" 35 #include "binding/AAudioStreamRequest.h" 36 #include "binding/AAudioStreamConfiguration.h" 37 #include "binding/IAAudioService.h" 38 #include "binding/AAudioServiceMessage.h" 39 #include "core/AudioStreamBuilder.h" 40 #include "fifo/FifoBuffer.h" 41 #include "utility/AudioClock.h" 42 #include "utility/LinearRamp.h" 43 44 #include "AudioStreamInternal.h" 45 46 using android::String16; 47 using android::Mutex; 48 using android::WrappingBuffer; 49 50 using namespace aaudio; 51 52 #define MIN_TIMEOUT_NANOS (1000 * AAUDIO_NANOS_PER_MILLISECOND) 53 54 // Wait at least this many times longer than the operation should take. 55 #define MIN_TIMEOUT_OPERATIONS 4 56 57 #define LOG_TIMESTAMPS 0 58 59 AudioStreamInternal::AudioStreamInternal(AAudioServiceInterface &serviceInterface, bool inService) 60 : AudioStream() 61 , mClockModel() 62 , mAudioEndpoint() 63 , mServiceStreamHandle(AAUDIO_HANDLE_INVALID) 64 , mFramesPerBurst(16) 65 , mInService(inService) 66 , mServiceInterface(serviceInterface) 67 , mAtomicTimestamp() 68 , mWakeupDelayNanos(AAudioProperty_getWakeupDelayMicros() * AAUDIO_NANOS_PER_MICROSECOND) 69 , mMinimumSleepNanos(AAudioProperty_getMinimumSleepMicros() * AAUDIO_NANOS_PER_MICROSECOND) 70 { 71 ALOGD("AudioStreamInternal(): mWakeupDelayNanos = %d, mMinimumSleepNanos = %d", 72 mWakeupDelayNanos, mMinimumSleepNanos); 73 } 74 75 AudioStreamInternal::~AudioStreamInternal() { 76 } 77 78 aaudio_result_t AudioStreamInternal::open(const AudioStreamBuilder &builder) { 79 80 aaudio_result_t result = AAUDIO_OK; 81 int32_t capacity; 82 AAudioStreamRequest request; 83 AAudioStreamConfiguration configurationOutput; 84 85 if (getState() != AAUDIO_STREAM_STATE_UNINITIALIZED) { 86 ALOGE("AudioStreamInternal::open(): already open! state = %d", getState()); 87 return AAUDIO_ERROR_INVALID_STATE; 88 } 89 90 // Copy requested parameters to the stream. 91 result = AudioStream::open(builder); 92 if (result < 0) { 93 return result; 94 } 95 96 // We have to do volume scaling. So we prefer FLOAT format. 97 if (getFormat() == AAUDIO_FORMAT_UNSPECIFIED) { 98 setFormat(AAUDIO_FORMAT_PCM_FLOAT); 99 } 100 // Request FLOAT for the shared mixer. 101 request.getConfiguration().setFormat(AAUDIO_FORMAT_PCM_FLOAT); 102 103 // Build the request to send to the server. 104 request.setUserId(getuid()); 105 request.setProcessId(getpid()); 106 request.setSharingModeMatchRequired(isSharingModeMatchRequired()); 107 request.setInService(mInService); 108 109 request.getConfiguration().setDeviceId(getDeviceId()); 110 request.getConfiguration().setSampleRate(getSampleRate()); 111 request.getConfiguration().setSamplesPerFrame(getSamplesPerFrame()); 112 request.getConfiguration().setDirection(getDirection()); 113 request.getConfiguration().setSharingMode(getSharingMode()); 114 115 request.getConfiguration().setBufferCapacity(builder.getBufferCapacity()); 116 117 mServiceStreamHandle = mServiceInterface.openStream(request, configurationOutput); 118 if (mServiceStreamHandle < 0) { 119 result = mServiceStreamHandle; 120 ALOGE("AudioStreamInternal::open(): openStream() returned %d", result); 121 return result; 122 } 123 124 result = configurationOutput.validate(); 125 if (result != AAUDIO_OK) { 126 goto error; 127 } 128 // Save results of the open. 129 setSampleRate(configurationOutput.getSampleRate()); 130 setSamplesPerFrame(configurationOutput.getSamplesPerFrame()); 131 setDeviceId(configurationOutput.getDeviceId()); 132 setSharingMode(configurationOutput.getSharingMode()); 133 134 // Save device format so we can do format conversion and volume scaling together. 135 mDeviceFormat = configurationOutput.getFormat(); 136 137 result = mServiceInterface.getStreamDescription(mServiceStreamHandle, mEndPointParcelable); 138 if (result != AAUDIO_OK) { 139 goto error; 140 } 141 142 // Resolve parcelable into a descriptor. 143 result = mEndPointParcelable.resolve(&mEndpointDescriptor); 144 if (result != AAUDIO_OK) { 145 goto error; 146 } 147 148 // Configure endpoint based on descriptor. 149 result = mAudioEndpoint.configure(&mEndpointDescriptor, getDirection()); 150 if (result != AAUDIO_OK) { 151 goto error; 152 } 153 154 mFramesPerBurst = mEndpointDescriptor.dataQueueDescriptor.framesPerBurst; 155 capacity = mEndpointDescriptor.dataQueueDescriptor.capacityInFrames; 156 157 // Validate result from server. 158 if (mFramesPerBurst < 16 || mFramesPerBurst > 16 * 1024) { 159 ALOGE("AudioStreamInternal::open(): framesPerBurst out of range = %d", mFramesPerBurst); 160 result = AAUDIO_ERROR_OUT_OF_RANGE; 161 goto error; 162 } 163 if (capacity < mFramesPerBurst || capacity > 32 * 1024) { 164 ALOGE("AudioStreamInternal::open(): bufferCapacity out of range = %d", capacity); 165 result = AAUDIO_ERROR_OUT_OF_RANGE; 166 goto error; 167 } 168 169 mClockModel.setSampleRate(getSampleRate()); 170 mClockModel.setFramesPerBurst(mFramesPerBurst); 171 172 if (getDataCallbackProc()) { 173 mCallbackFrames = builder.getFramesPerDataCallback(); 174 if (mCallbackFrames > getBufferCapacity() / 2) { 175 ALOGE("AudioStreamInternal::open(): framesPerCallback too big = %d, capacity = %d", 176 mCallbackFrames, getBufferCapacity()); 177 result = AAUDIO_ERROR_OUT_OF_RANGE; 178 goto error; 179 180 } else if (mCallbackFrames < 0) { 181 ALOGE("AudioStreamInternal::open(): framesPerCallback negative"); 182 result = AAUDIO_ERROR_OUT_OF_RANGE; 183 goto error; 184 185 } 186 if (mCallbackFrames == AAUDIO_UNSPECIFIED) { 187 mCallbackFrames = mFramesPerBurst; 188 } 189 190 int32_t bytesPerFrame = getSamplesPerFrame() 191 * AAudioConvert_formatToSizeInBytes(getFormat()); 192 int32_t callbackBufferSize = mCallbackFrames * bytesPerFrame; 193 mCallbackBuffer = new uint8_t[callbackBufferSize]; 194 } 195 196 setState(AAUDIO_STREAM_STATE_OPEN); 197 198 return result; 199 200 error: 201 close(); 202 return result; 203 } 204 205 aaudio_result_t AudioStreamInternal::close() { 206 aaudio_result_t result = AAUDIO_OK; 207 ALOGD("close(): mServiceStreamHandle = 0x%08X", 208 mServiceStreamHandle); 209 if (mServiceStreamHandle != AAUDIO_HANDLE_INVALID) { 210 // Don't close a stream while it is running. 211 aaudio_stream_state_t currentState = getState(); 212 if (isActive()) { 213 requestStop(); 214 aaudio_stream_state_t nextState; 215 int64_t timeoutNanoseconds = MIN_TIMEOUT_NANOS; 216 result = waitForStateChange(currentState, &nextState, 217 timeoutNanoseconds); 218 if (result != AAUDIO_OK) { 219 ALOGE("close() waitForStateChange() returned %d %s", 220 result, AAudio_convertResultToText(result)); 221 } 222 } 223 setState(AAUDIO_STREAM_STATE_CLOSING); 224 aaudio_handle_t serviceStreamHandle = mServiceStreamHandle; 225 mServiceStreamHandle = AAUDIO_HANDLE_INVALID; 226 227 mServiceInterface.closeStream(serviceStreamHandle); 228 delete[] mCallbackBuffer; 229 mCallbackBuffer = nullptr; 230 231 setState(AAUDIO_STREAM_STATE_CLOSED); 232 result = mEndPointParcelable.close(); 233 aaudio_result_t result2 = AudioStream::close(); 234 return (result != AAUDIO_OK) ? result : result2; 235 } else { 236 return AAUDIO_ERROR_INVALID_HANDLE; 237 } 238 } 239 240 static void *aaudio_callback_thread_proc(void *context) 241 { 242 AudioStreamInternal *stream = (AudioStreamInternal *)context; 243 //LOGD("AudioStreamInternal(): oboe_callback_thread, stream = %p", stream); 244 if (stream != NULL) { 245 return stream->callbackLoop(); 246 } else { 247 return NULL; 248 } 249 } 250 251 /* 252 * It normally takes about 20-30 msec to start a stream on the server. 253 * But the first time can take as much as 200-300 msec. The HW 254 * starts right away so by the time the client gets a chance to write into 255 * the buffer, it is already in a deep underflow state. That can cause the 256 * XRunCount to be non-zero, which could lead an app to tune its latency higher. 257 * To avoid this problem, we set a request for the processing code to start the 258 * client stream at the same position as the server stream. 259 * The processing code will then save the current offset 260 * between client and server and apply that to any position given to the app. 261 */ 262 aaudio_result_t AudioStreamInternal::requestStart() 263 { 264 int64_t startTime; 265 if (mServiceStreamHandle == AAUDIO_HANDLE_INVALID) { 266 ALOGE("requestStart() mServiceStreamHandle invalid"); 267 return AAUDIO_ERROR_INVALID_STATE; 268 } 269 if (isActive()) { 270 ALOGE("requestStart() already active"); 271 return AAUDIO_ERROR_INVALID_STATE; 272 } 273 274 aaudio_stream_state_t originalState = getState(); 275 if (originalState == AAUDIO_STREAM_STATE_DISCONNECTED) { 276 ALOGE("requestStart() but DISCONNECTED"); 277 return AAUDIO_ERROR_DISCONNECTED; 278 } 279 setState(AAUDIO_STREAM_STATE_STARTING); 280 281 // Clear any stale timestamps from the previous run. 282 drainTimestampsFromService(); 283 284 aaudio_result_t result = mServiceInterface.startStream(mServiceStreamHandle); 285 286 startTime = AudioClock::getNanoseconds(); 287 mClockModel.start(startTime); 288 mNeedCatchUp.request(); // Ask data processing code to catch up when first timestamp received. 289 290 // Start data callback thread. 291 if (result == AAUDIO_OK && getDataCallbackProc() != nullptr) { 292 // Launch the callback loop thread. 293 int64_t periodNanos = mCallbackFrames 294 * AAUDIO_NANOS_PER_SECOND 295 / getSampleRate(); 296 mCallbackEnabled.store(true); 297 result = createThread(periodNanos, aaudio_callback_thread_proc, this); 298 } 299 if (result != AAUDIO_OK) { 300 setState(originalState); 301 } 302 return result; 303 } 304 305 int64_t AudioStreamInternal::calculateReasonableTimeout(int32_t framesPerOperation) { 306 307 // Wait for at least a second or some number of callbacks to join the thread. 308 int64_t timeoutNanoseconds = (MIN_TIMEOUT_OPERATIONS 309 * framesPerOperation 310 * AAUDIO_NANOS_PER_SECOND) 311 / getSampleRate(); 312 if (timeoutNanoseconds < MIN_TIMEOUT_NANOS) { // arbitrary number of seconds 313 timeoutNanoseconds = MIN_TIMEOUT_NANOS; 314 } 315 return timeoutNanoseconds; 316 } 317 318 int64_t AudioStreamInternal::calculateReasonableTimeout() { 319 return calculateReasonableTimeout(getFramesPerBurst()); 320 } 321 322 aaudio_result_t AudioStreamInternal::stopCallback() 323 { 324 if (isDataCallbackActive()) { 325 mCallbackEnabled.store(false); 326 return joinThread(NULL); 327 } else { 328 return AAUDIO_OK; 329 } 330 } 331 332 aaudio_result_t AudioStreamInternal::requestStopInternal() 333 { 334 if (mServiceStreamHandle == AAUDIO_HANDLE_INVALID) { 335 ALOGE("requestStopInternal() mServiceStreamHandle invalid = 0x%08X", 336 mServiceStreamHandle); 337 return AAUDIO_ERROR_INVALID_STATE; 338 } 339 340 mClockModel.stop(AudioClock::getNanoseconds()); 341 setState(AAUDIO_STREAM_STATE_STOPPING); 342 mAtomicTimestamp.clear(); 343 344 return mServiceInterface.stopStream(mServiceStreamHandle); 345 } 346 347 aaudio_result_t AudioStreamInternal::requestStop() 348 { 349 aaudio_result_t result = stopCallback(); 350 if (result != AAUDIO_OK) { 351 return result; 352 } 353 result = requestStopInternal(); 354 return result; 355 } 356 357 aaudio_result_t AudioStreamInternal::registerThread() { 358 if (mServiceStreamHandle == AAUDIO_HANDLE_INVALID) { 359 ALOGE("registerThread() mServiceStreamHandle invalid"); 360 return AAUDIO_ERROR_INVALID_STATE; 361 } 362 return mServiceInterface.registerAudioThread(mServiceStreamHandle, 363 gettid(), 364 getPeriodNanoseconds()); 365 } 366 367 aaudio_result_t AudioStreamInternal::unregisterThread() { 368 if (mServiceStreamHandle == AAUDIO_HANDLE_INVALID) { 369 ALOGE("unregisterThread() mServiceStreamHandle invalid"); 370 return AAUDIO_ERROR_INVALID_STATE; 371 } 372 return mServiceInterface.unregisterAudioThread(mServiceStreamHandle, gettid()); 373 } 374 375 aaudio_result_t AudioStreamInternal::startClient(const android::AudioClient& client, 376 audio_port_handle_t *clientHandle) { 377 if (mServiceStreamHandle == AAUDIO_HANDLE_INVALID) { 378 return AAUDIO_ERROR_INVALID_STATE; 379 } 380 381 return mServiceInterface.startClient(mServiceStreamHandle, client, clientHandle); 382 } 383 384 aaudio_result_t AudioStreamInternal::stopClient(audio_port_handle_t clientHandle) { 385 if (mServiceStreamHandle == AAUDIO_HANDLE_INVALID) { 386 return AAUDIO_ERROR_INVALID_STATE; 387 } 388 return mServiceInterface.stopClient(mServiceStreamHandle, clientHandle); 389 } 390 391 aaudio_result_t AudioStreamInternal::getTimestamp(clockid_t clockId, 392 int64_t *framePosition, 393 int64_t *timeNanoseconds) { 394 // Generated in server and passed to client. Return latest. 395 if (mAtomicTimestamp.isValid()) { 396 Timestamp timestamp = mAtomicTimestamp.read(); 397 int64_t position = timestamp.getPosition() + mFramesOffsetFromService; 398 if (position >= 0) { 399 *framePosition = position; 400 *timeNanoseconds = timestamp.getNanoseconds(); 401 return AAUDIO_OK; 402 } 403 } 404 return AAUDIO_ERROR_INVALID_STATE; 405 } 406 407 aaudio_result_t AudioStreamInternal::updateStateMachine() { 408 if (isDataCallbackActive()) { 409 return AAUDIO_OK; // state is getting updated by the callback thread read/write call 410 } 411 return processCommands(); 412 } 413 414 void AudioStreamInternal::logTimestamp(AAudioServiceMessage &command) { 415 static int64_t oldPosition = 0; 416 static int64_t oldTime = 0; 417 int64_t framePosition = command.timestamp.position; 418 int64_t nanoTime = command.timestamp.timestamp; 419 ALOGD("logTimestamp: timestamp says framePosition = %8lld at nanoTime %lld", 420 (long long) framePosition, 421 (long long) nanoTime); 422 int64_t nanosDelta = nanoTime - oldTime; 423 if (nanosDelta > 0 && oldTime > 0) { 424 int64_t framesDelta = framePosition - oldPosition; 425 int64_t rate = (framesDelta * AAUDIO_NANOS_PER_SECOND) / nanosDelta; 426 ALOGD("logTimestamp: framesDelta = %8lld, nanosDelta = %8lld, rate = %lld", 427 (long long) framesDelta, (long long) nanosDelta, (long long) rate); 428 } 429 oldPosition = framePosition; 430 oldTime = nanoTime; 431 } 432 433 aaudio_result_t AudioStreamInternal::onTimestampService(AAudioServiceMessage *message) { 434 #if LOG_TIMESTAMPS 435 logTimestamp(*message); 436 #endif 437 processTimestamp(message->timestamp.position, message->timestamp.timestamp); 438 return AAUDIO_OK; 439 } 440 441 aaudio_result_t AudioStreamInternal::onTimestampHardware(AAudioServiceMessage *message) { 442 Timestamp timestamp(message->timestamp.position, message->timestamp.timestamp); 443 mAtomicTimestamp.write(timestamp); 444 return AAUDIO_OK; 445 } 446 447 aaudio_result_t AudioStreamInternal::onEventFromServer(AAudioServiceMessage *message) { 448 aaudio_result_t result = AAUDIO_OK; 449 switch (message->event.event) { 450 case AAUDIO_SERVICE_EVENT_STARTED: 451 ALOGD("AudioStreamInternal::onEventFromServer() got AAUDIO_SERVICE_EVENT_STARTED"); 452 if (getState() == AAUDIO_STREAM_STATE_STARTING) { 453 setState(AAUDIO_STREAM_STATE_STARTED); 454 } 455 break; 456 case AAUDIO_SERVICE_EVENT_PAUSED: 457 ALOGD("AudioStreamInternal::onEventFromServer() got AAUDIO_SERVICE_EVENT_PAUSED"); 458 if (getState() == AAUDIO_STREAM_STATE_PAUSING) { 459 setState(AAUDIO_STREAM_STATE_PAUSED); 460 } 461 break; 462 case AAUDIO_SERVICE_EVENT_STOPPED: 463 ALOGD("AudioStreamInternal::onEventFromServer() got AAUDIO_SERVICE_EVENT_STOPPED"); 464 if (getState() == AAUDIO_STREAM_STATE_STOPPING) { 465 setState(AAUDIO_STREAM_STATE_STOPPED); 466 } 467 break; 468 case AAUDIO_SERVICE_EVENT_FLUSHED: 469 ALOGD("AudioStreamInternal::onEventFromServer() got AAUDIO_SERVICE_EVENT_FLUSHED"); 470 if (getState() == AAUDIO_STREAM_STATE_FLUSHING) { 471 setState(AAUDIO_STREAM_STATE_FLUSHED); 472 onFlushFromServer(); 473 } 474 break; 475 case AAUDIO_SERVICE_EVENT_CLOSED: 476 ALOGD("AudioStreamInternal::onEventFromServer() got AAUDIO_SERVICE_EVENT_CLOSED"); 477 setState(AAUDIO_STREAM_STATE_CLOSED); 478 break; 479 case AAUDIO_SERVICE_EVENT_DISCONNECTED: 480 // Prevent hardware from looping on old data and making buzzing sounds. 481 if (getDirection() == AAUDIO_DIRECTION_OUTPUT) { 482 mAudioEndpoint.eraseDataMemory(); 483 } 484 result = AAUDIO_ERROR_DISCONNECTED; 485 setState(AAUDIO_STREAM_STATE_DISCONNECTED); 486 ALOGW("WARNING - AudioStreamInternal::onEventFromServer()" 487 " AAUDIO_SERVICE_EVENT_DISCONNECTED - FIFO cleared"); 488 break; 489 case AAUDIO_SERVICE_EVENT_VOLUME: 490 mStreamVolume = (float)message->event.dataDouble; 491 doSetVolume(); 492 ALOGD("AudioStreamInternal::onEventFromServer() AAUDIO_SERVICE_EVENT_VOLUME %lf", 493 message->event.dataDouble); 494 break; 495 default: 496 ALOGW("WARNING - AudioStreamInternal::onEventFromServer() Unrecognized event = %d", 497 (int) message->event.event); 498 break; 499 } 500 return result; 501 } 502 503 aaudio_result_t AudioStreamInternal::drainTimestampsFromService() { 504 aaudio_result_t result = AAUDIO_OK; 505 506 while (result == AAUDIO_OK) { 507 AAudioServiceMessage message; 508 if (mAudioEndpoint.readUpCommand(&message) != 1) { 509 break; // no command this time, no problem 510 } 511 switch (message.what) { 512 // ignore most messages 513 case AAudioServiceMessage::code::TIMESTAMP_SERVICE: 514 case AAudioServiceMessage::code::TIMESTAMP_HARDWARE: 515 break; 516 517 case AAudioServiceMessage::code::EVENT: 518 result = onEventFromServer(&message); 519 break; 520 521 default: 522 ALOGE("WARNING - drainTimestampsFromService() Unrecognized what = %d", 523 (int) message.what); 524 result = AAUDIO_ERROR_INTERNAL; 525 break; 526 } 527 } 528 return result; 529 } 530 531 // Process all the commands coming from the server. 532 aaudio_result_t AudioStreamInternal::processCommands() { 533 aaudio_result_t result = AAUDIO_OK; 534 535 while (result == AAUDIO_OK) { 536 //ALOGD("AudioStreamInternal::processCommands() - looping, %d", result); 537 AAudioServiceMessage message; 538 if (mAudioEndpoint.readUpCommand(&message) != 1) { 539 break; // no command this time, no problem 540 } 541 switch (message.what) { 542 case AAudioServiceMessage::code::TIMESTAMP_SERVICE: 543 result = onTimestampService(&message); 544 break; 545 546 case AAudioServiceMessage::code::TIMESTAMP_HARDWARE: 547 result = onTimestampHardware(&message); 548 break; 549 550 case AAudioServiceMessage::code::EVENT: 551 result = onEventFromServer(&message); 552 break; 553 554 default: 555 ALOGE("WARNING - processCommands() Unrecognized what = %d", 556 (int) message.what); 557 result = AAUDIO_ERROR_INTERNAL; 558 break; 559 } 560 } 561 return result; 562 } 563 564 // Read or write the data, block if needed and timeoutMillis > 0 565 aaudio_result_t AudioStreamInternal::processData(void *buffer, int32_t numFrames, 566 int64_t timeoutNanoseconds) 567 { 568 const char * traceName = "aaProc"; 569 const char * fifoName = "aaRdy"; 570 ATRACE_BEGIN(traceName); 571 if (ATRACE_ENABLED()) { 572 int32_t fullFrames = mAudioEndpoint.getFullFramesAvailable(); 573 ATRACE_INT(fifoName, fullFrames); 574 } 575 576 aaudio_result_t result = AAUDIO_OK; 577 int32_t loopCount = 0; 578 uint8_t* audioData = (uint8_t*)buffer; 579 int64_t currentTimeNanos = AudioClock::getNanoseconds(); 580 const int64_t entryTimeNanos = currentTimeNanos; 581 const int64_t deadlineNanos = currentTimeNanos + timeoutNanoseconds; 582 int32_t framesLeft = numFrames; 583 584 // Loop until all the data has been processed or until a timeout occurs. 585 while (framesLeft > 0) { 586 // The call to processDataNow() will not block. It will just process as much as it can. 587 int64_t wakeTimeNanos = 0; 588 aaudio_result_t framesProcessed = processDataNow(audioData, framesLeft, 589 currentTimeNanos, &wakeTimeNanos); 590 if (framesProcessed < 0) { 591 result = framesProcessed; 592 break; 593 } 594 framesLeft -= (int32_t) framesProcessed; 595 audioData += framesProcessed * getBytesPerFrame(); 596 597 // Should we block? 598 if (timeoutNanoseconds == 0) { 599 break; // don't block 600 } else if (framesLeft > 0) { 601 if (!mAudioEndpoint.isFreeRunning()) { 602 // If there is software on the other end of the FIFO then it may get delayed. 603 // So wake up just a little after we expect it to be ready. 604 wakeTimeNanos += mWakeupDelayNanos; 605 } 606 607 currentTimeNanos = AudioClock::getNanoseconds(); 608 int64_t earliestWakeTime = currentTimeNanos + mMinimumSleepNanos; 609 // Guarantee a minimum sleep time. 610 if (wakeTimeNanos < earliestWakeTime) { 611 wakeTimeNanos = earliestWakeTime; 612 } 613 614 if (wakeTimeNanos > deadlineNanos) { 615 // If we time out, just return the framesWritten so far. 616 // TODO remove after we fix the deadline bug 617 ALOGW("AudioStreamInternal::processData(): entered at %lld nanos, currently %lld", 618 (long long) entryTimeNanos, (long long) currentTimeNanos); 619 ALOGW("AudioStreamInternal::processData(): TIMEOUT after %lld nanos", 620 (long long) timeoutNanoseconds); 621 ALOGW("AudioStreamInternal::processData(): wakeTime = %lld, deadline = %lld nanos", 622 (long long) wakeTimeNanos, (long long) deadlineNanos); 623 ALOGW("AudioStreamInternal::processData(): past deadline by %d micros", 624 (int)((wakeTimeNanos - deadlineNanos) / AAUDIO_NANOS_PER_MICROSECOND)); 625 mClockModel.dump(); 626 mAudioEndpoint.dump(); 627 break; 628 } 629 630 if (ATRACE_ENABLED()) { 631 int32_t fullFrames = mAudioEndpoint.getFullFramesAvailable(); 632 ATRACE_INT(fifoName, fullFrames); 633 int64_t sleepForNanos = wakeTimeNanos - currentTimeNanos; 634 ATRACE_INT("aaSlpNs", (int32_t)sleepForNanos); 635 } 636 637 AudioClock::sleepUntilNanoTime(wakeTimeNanos); 638 currentTimeNanos = AudioClock::getNanoseconds(); 639 } 640 } 641 642 if (ATRACE_ENABLED()) { 643 int32_t fullFrames = mAudioEndpoint.getFullFramesAvailable(); 644 ATRACE_INT(fifoName, fullFrames); 645 } 646 647 // return error or framesProcessed 648 (void) loopCount; 649 ATRACE_END(); 650 return (result < 0) ? result : numFrames - framesLeft; 651 } 652 653 void AudioStreamInternal::processTimestamp(uint64_t position, int64_t time) { 654 mClockModel.processTimestamp(position, time); 655 } 656 657 aaudio_result_t AudioStreamInternal::setBufferSize(int32_t requestedFrames) { 658 int32_t actualFrames = 0; 659 // Round to the next highest burst size. 660 if (getFramesPerBurst() > 0) { 661 int32_t numBursts = (requestedFrames + getFramesPerBurst() - 1) / getFramesPerBurst(); 662 requestedFrames = numBursts * getFramesPerBurst(); 663 } 664 665 aaudio_result_t result = mAudioEndpoint.setBufferSizeInFrames(requestedFrames, &actualFrames); 666 ALOGD("setBufferSize() req = %d => %d", requestedFrames, actualFrames); 667 if (result < 0) { 668 return result; 669 } else { 670 return (aaudio_result_t) actualFrames; 671 } 672 } 673 674 int32_t AudioStreamInternal::getBufferSize() const { 675 return mAudioEndpoint.getBufferSizeInFrames(); 676 } 677 678 int32_t AudioStreamInternal::getBufferCapacity() const { 679 return mAudioEndpoint.getBufferCapacityInFrames(); 680 } 681 682 int32_t AudioStreamInternal::getFramesPerBurst() const { 683 return mEndpointDescriptor.dataQueueDescriptor.framesPerBurst; 684 } 685 686 aaudio_result_t AudioStreamInternal::joinThread(void** returnArg) { 687 return AudioStream::joinThread(returnArg, calculateReasonableTimeout(getFramesPerBurst())); 688 } 689