Eric Laurent | 81784c3 | 2012-11-19 14:55:58 -0800 | [diff] [blame] | 1 | /* |
| 2 | ** |
| 3 | ** Copyright 2012, The Android Open Source Project |
| 4 | ** |
| 5 | ** Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | ** you may not use this file except in compliance with the License. |
| 7 | ** You may obtain a copy of the License at |
| 8 | ** |
| 9 | ** http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | ** |
| 11 | ** Unless required by applicable law or agreed to in writing, software |
| 12 | ** distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | ** See the License for the specific language governing permissions and |
| 15 | ** limitations under the License. |
| 16 | */ |
| 17 | |
| 18 | |
| 19 | #define LOG_TAG "AudioFlinger" |
| 20 | //#define LOG_NDEBUG 0 |
Alex Ray | 371eb97 | 2012-11-30 11:11:54 -0800 | [diff] [blame] | 21 | #define ATRACE_TAG ATRACE_TAG_AUDIO |
Eric Laurent | 81784c3 | 2012-11-19 14:55:58 -0800 | [diff] [blame] | 22 | |
Glenn Kasten | 153b9fe | 2013-07-15 11:23:36 -0700 | [diff] [blame] | 23 | #include "Configuration.h" |
Eric Laurent | 81784c3 | 2012-11-19 14:55:58 -0800 | [diff] [blame] | 24 | #include <math.h> |
| 25 | #include <fcntl.h> |
| 26 | #include <sys/stat.h> |
| 27 | #include <cutils/properties.h> |
| 28 | #include <cutils/compiler.h> |
Glenn Kasten | 1ab85ec | 2013-05-31 09:18:43 -0700 | [diff] [blame] | 29 | #include <media/AudioParameter.h> |
Eric Laurent | 81784c3 | 2012-11-19 14:55:58 -0800 | [diff] [blame] | 30 | #include <utils/Log.h> |
Alex Ray | 371eb97 | 2012-11-30 11:11:54 -0800 | [diff] [blame] | 31 | #include <utils/Trace.h> |
Eric Laurent | 81784c3 | 2012-11-19 14:55:58 -0800 | [diff] [blame] | 32 | |
| 33 | #include <private/media/AudioTrackShared.h> |
| 34 | #include <hardware/audio.h> |
| 35 | #include <audio_effects/effect_ns.h> |
| 36 | #include <audio_effects/effect_aec.h> |
| 37 | #include <audio_utils/primitives.h> |
| 38 | |
| 39 | // NBAIO implementations |
| 40 | #include <media/nbaio/AudioStreamOutSink.h> |
| 41 | #include <media/nbaio/MonoPipe.h> |
| 42 | #include <media/nbaio/MonoPipeReader.h> |
| 43 | #include <media/nbaio/Pipe.h> |
| 44 | #include <media/nbaio/PipeReader.h> |
| 45 | #include <media/nbaio/SourceAudioBufferProvider.h> |
| 46 | |
| 47 | #include <powermanager/PowerManager.h> |
| 48 | |
| 49 | #include <common_time/cc_helper.h> |
| 50 | #include <common_time/local_clock.h> |
| 51 | |
| 52 | #include "AudioFlinger.h" |
| 53 | #include "AudioMixer.h" |
| 54 | #include "FastMixer.h" |
| 55 | #include "ServiceUtilities.h" |
| 56 | #include "SchedulingPolicyService.h" |
| 57 | |
Eric Laurent | 81784c3 | 2012-11-19 14:55:58 -0800 | [diff] [blame] | 58 | #ifdef ADD_BATTERY_DATA |
| 59 | #include <media/IMediaPlayerService.h> |
| 60 | #include <media/IMediaDeathNotifier.h> |
| 61 | #endif |
| 62 | |
Eric Laurent | 81784c3 | 2012-11-19 14:55:58 -0800 | [diff] [blame] | 63 | #ifdef DEBUG_CPU_USAGE |
| 64 | #include <cpustats/CentralTendencyStatistics.h> |
| 65 | #include <cpustats/ThreadCpuUsage.h> |
| 66 | #endif |
| 67 | |
| 68 | // ---------------------------------------------------------------------------- |
| 69 | |
| 70 | // Note: the following macro is used for extremely verbose logging message. In |
| 71 | // order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to |
| 72 | // 0; but one side effect of this is to turn all LOGV's as well. Some messages |
| 73 | // are so verbose that we want to suppress them even when we have ALOG_ASSERT |
| 74 | // turned on. Do not uncomment the #def below unless you really know what you |
| 75 | // are doing and want to see all of the extremely verbose messages. |
| 76 | //#define VERY_VERY_VERBOSE_LOGGING |
| 77 | #ifdef VERY_VERY_VERBOSE_LOGGING |
| 78 | #define ALOGVV ALOGV |
| 79 | #else |
| 80 | #define ALOGVV(a...) do { } while(0) |
| 81 | #endif |
| 82 | |
| 83 | namespace android { |
| 84 | |
| 85 | // retry counts for buffer fill timeout |
| 86 | // 50 * ~20msecs = 1 second |
| 87 | static const int8_t kMaxTrackRetries = 50; |
| 88 | static const int8_t kMaxTrackStartupRetries = 50; |
| 89 | // allow less retry attempts on direct output thread. |
| 90 | // direct outputs can be a scarce resource in audio hardware and should |
| 91 | // be released as quickly as possible. |
| 92 | static const int8_t kMaxTrackRetriesDirect = 2; |
| 93 | |
| 94 | // don't warn about blocked writes or record buffer overflows more often than this |
| 95 | static const nsecs_t kWarningThrottleNs = seconds(5); |
| 96 | |
| 97 | // RecordThread loop sleep time upon application overrun or audio HAL read error |
| 98 | static const int kRecordThreadSleepUs = 5000; |
| 99 | |
| 100 | // maximum time to wait for setParameters to complete |
| 101 | static const nsecs_t kSetParametersTimeoutNs = seconds(2); |
| 102 | |
| 103 | // minimum sleep time for the mixer thread loop when tracks are active but in underrun |
| 104 | static const uint32_t kMinThreadSleepTimeUs = 5000; |
| 105 | // maximum divider applied to the active sleep time in the mixer thread loop |
| 106 | static const uint32_t kMaxThreadSleepTimeShift = 2; |
| 107 | |
| 108 | // minimum normal mix buffer size, expressed in milliseconds rather than frames |
| 109 | static const uint32_t kMinNormalMixBufferSizeMs = 20; |
| 110 | // maximum normal mix buffer size |
| 111 | static const uint32_t kMaxNormalMixBufferSizeMs = 24; |
| 112 | |
| 113 | // Whether to use fast mixer |
| 114 | static const enum { |
| 115 | FastMixer_Never, // never initialize or use: for debugging only |
| 116 | FastMixer_Always, // always initialize and use, even if not needed: for debugging only |
| 117 | // normal mixer multiplier is 1 |
| 118 | FastMixer_Static, // initialize if needed, then use all the time if initialized, |
| 119 | // multiplier is calculated based on min & max normal mixer buffer size |
| 120 | FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load, |
| 121 | // multiplier is calculated based on min & max normal mixer buffer size |
| 122 | // FIXME for FastMixer_Dynamic: |
| 123 | // Supporting this option will require fixing HALs that can't handle large writes. |
| 124 | // For example, one HAL implementation returns an error from a large write, |
| 125 | // and another HAL implementation corrupts memory, possibly in the sample rate converter. |
| 126 | // We could either fix the HAL implementations, or provide a wrapper that breaks |
| 127 | // up large writes into smaller ones, and the wrapper would need to deal with scheduler. |
| 128 | } kUseFastMixer = FastMixer_Static; |
| 129 | |
| 130 | // Priorities for requestPriority |
| 131 | static const int kPriorityAudioApp = 2; |
| 132 | static const int kPriorityFastMixer = 3; |
| 133 | |
| 134 | // IAudioFlinger::createTrack() reports back to client the total size of shared memory area |
| 135 | // for the track. The client then sub-divides this into smaller buffers for its use. |
| 136 | // Currently the client uses double-buffering by default, but doesn't tell us about that. |
| 137 | // So for now we just assume that client is double-buffered. |
| 138 | // FIXME It would be better for client to tell AudioFlinger whether it wants double-buffering or |
| 139 | // N-buffering, so AudioFlinger could allocate the right amount of memory. |
| 140 | // See the client's minBufCount and mNotificationFramesAct calculations for details. |
Glenn Kasten | 9f80dd2 | 2012-12-18 15:57:32 -0800 | [diff] [blame] | 141 | static const int kFastTrackMultiplier = 1; |
Eric Laurent | 81784c3 | 2012-11-19 14:55:58 -0800 | [diff] [blame] | 142 | |
| 143 | // ---------------------------------------------------------------------------- |
| 144 | |
| 145 | #ifdef ADD_BATTERY_DATA |
| 146 | // To collect the amplifier usage |
| 147 | static void addBatteryData(uint32_t params) { |
| 148 | sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService(); |
| 149 | if (service == NULL) { |
| 150 | // it already logged |
| 151 | return; |
| 152 | } |
| 153 | |
| 154 | service->addBatteryData(params); |
| 155 | } |
| 156 | #endif |
| 157 | |
| 158 | |
| 159 | // ---------------------------------------------------------------------------- |
| 160 | // CPU Stats |
| 161 | // ---------------------------------------------------------------------------- |
| 162 | |
| 163 | class CpuStats { |
| 164 | public: |
| 165 | CpuStats(); |
| 166 | void sample(const String8 &title); |
| 167 | #ifdef DEBUG_CPU_USAGE |
| 168 | private: |
| 169 | ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns |
| 170 | CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns |
| 171 | |
| 172 | CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles |
| 173 | |
| 174 | int mCpuNum; // thread's current CPU number |
| 175 | int mCpukHz; // frequency of thread's current CPU in kHz |
| 176 | #endif |
| 177 | }; |
| 178 | |
| 179 | CpuStats::CpuStats() |
| 180 | #ifdef DEBUG_CPU_USAGE |
| 181 | : mCpuNum(-1), mCpukHz(-1) |
| 182 | #endif |
| 183 | { |
| 184 | } |
| 185 | |
| 186 | void CpuStats::sample(const String8 &title) { |
| 187 | #ifdef DEBUG_CPU_USAGE |
| 188 | // get current thread's delta CPU time in wall clock ns |
| 189 | double wcNs; |
| 190 | bool valid = mCpuUsage.sampleAndEnable(wcNs); |
| 191 | |
| 192 | // record sample for wall clock statistics |
| 193 | if (valid) { |
| 194 | mWcStats.sample(wcNs); |
| 195 | } |
| 196 | |
| 197 | // get the current CPU number |
| 198 | int cpuNum = sched_getcpu(); |
| 199 | |
| 200 | // get the current CPU frequency in kHz |
| 201 | int cpukHz = mCpuUsage.getCpukHz(cpuNum); |
| 202 | |
| 203 | // check if either CPU number or frequency changed |
| 204 | if (cpuNum != mCpuNum || cpukHz != mCpukHz) { |
| 205 | mCpuNum = cpuNum; |
| 206 | mCpukHz = cpukHz; |
| 207 | // ignore sample for purposes of cycles |
| 208 | valid = false; |
| 209 | } |
| 210 | |
| 211 | // if no change in CPU number or frequency, then record sample for cycle statistics |
| 212 | if (valid && mCpukHz > 0) { |
| 213 | double cycles = wcNs * cpukHz * 0.000001; |
| 214 | mHzStats.sample(cycles); |
| 215 | } |
| 216 | |
| 217 | unsigned n = mWcStats.n(); |
| 218 | // mCpuUsage.elapsed() is expensive, so don't call it every loop |
| 219 | if ((n & 127) == 1) { |
| 220 | long long elapsed = mCpuUsage.elapsed(); |
| 221 | if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) { |
| 222 | double perLoop = elapsed / (double) n; |
| 223 | double perLoop100 = perLoop * 0.01; |
| 224 | double perLoop1k = perLoop * 0.001; |
| 225 | double mean = mWcStats.mean(); |
| 226 | double stddev = mWcStats.stddev(); |
| 227 | double minimum = mWcStats.minimum(); |
| 228 | double maximum = mWcStats.maximum(); |
| 229 | double meanCycles = mHzStats.mean(); |
| 230 | double stddevCycles = mHzStats.stddev(); |
| 231 | double minCycles = mHzStats.minimum(); |
| 232 | double maxCycles = mHzStats.maximum(); |
| 233 | mCpuUsage.resetElapsed(); |
| 234 | mWcStats.reset(); |
| 235 | mHzStats.reset(); |
| 236 | ALOGD("CPU usage for %s over past %.1f secs\n" |
| 237 | " (%u mixer loops at %.1f mean ms per loop):\n" |
| 238 | " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n" |
| 239 | " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n" |
| 240 | " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f", |
| 241 | title.string(), |
| 242 | elapsed * .000000001, n, perLoop * .000001, |
| 243 | mean * .001, |
| 244 | stddev * .001, |
| 245 | minimum * .001, |
| 246 | maximum * .001, |
| 247 | mean / perLoop100, |
| 248 | stddev / perLoop100, |
| 249 | minimum / perLoop100, |
| 250 | maximum / perLoop100, |
| 251 | meanCycles / perLoop1k, |
| 252 | stddevCycles / perLoop1k, |
| 253 | minCycles / perLoop1k, |
| 254 | maxCycles / perLoop1k); |
| 255 | |
| 256 | } |
| 257 | } |
| 258 | #endif |
| 259 | }; |
| 260 | |
| 261 | // ---------------------------------------------------------------------------- |
| 262 | // ThreadBase |
| 263 | // ---------------------------------------------------------------------------- |
| 264 | |
| 265 | AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id, |
| 266 | audio_devices_t outDevice, audio_devices_t inDevice, type_t type) |
| 267 | : Thread(false /*canCallJava*/), |
| 268 | mType(type), |
| 269 | mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mNormalFrameCount(0), |
| 270 | // mChannelMask |
| 271 | mChannelCount(0), |
| 272 | mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID), |
| 273 | mParamStatus(NO_ERROR), |
| 274 | mStandby(false), mOutDevice(outDevice), mInDevice(inDevice), |
| 275 | mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id), |
| 276 | // mName will be set by concrete (non-virtual) subclass |
| 277 | mDeathRecipient(new PMDeathRecipient(this)) |
| 278 | { |
| 279 | } |
| 280 | |
| 281 | AudioFlinger::ThreadBase::~ThreadBase() |
| 282 | { |
Glenn Kasten | c6ae3c8 | 2013-07-17 09:08:51 -0700 | [diff] [blame] | 283 | // mConfigEvents should be empty, but just in case it isn't, free the memory it owns |
| 284 | for (size_t i = 0; i < mConfigEvents.size(); i++) { |
| 285 | delete mConfigEvents[i]; |
| 286 | } |
| 287 | mConfigEvents.clear(); |
| 288 | |
Eric Laurent | 81784c3 | 2012-11-19 14:55:58 -0800 | [diff] [blame] | 289 | mParamCond.broadcast(); |
| 290 | // do not lock the mutex in destructor |
| 291 | releaseWakeLock_l(); |
| 292 | if (mPowerManager != 0) { |
| 293 | sp<IBinder> binder = mPowerManager->asBinder(); |
| 294 | binder->unlinkToDeath(mDeathRecipient); |
| 295 | } |
| 296 | } |
| 297 | |
| 298 | void AudioFlinger::ThreadBase::exit() |
| 299 | { |
| 300 | ALOGV("ThreadBase::exit"); |
| 301 | // do any cleanup required for exit to succeed |
| 302 | preExit(); |
| 303 | { |
| 304 | // This lock prevents the following race in thread (uniprocessor for illustration): |
| 305 | // if (!exitPending()) { |
| 306 | // // context switch from here to exit() |
| 307 | // // exit() calls requestExit(), what exitPending() observes |
| 308 | // // exit() calls signal(), which is dropped since no waiters |
| 309 | // // context switch back from exit() to here |
| 310 | // mWaitWorkCV.wait(...); |
| 311 | // // now thread is hung |
| 312 | // } |
| 313 | AutoMutex lock(mLock); |
| 314 | requestExit(); |
| 315 | mWaitWorkCV.broadcast(); |
| 316 | } |
| 317 | // When Thread::requestExitAndWait is made virtual and this method is renamed to |
| 318 | // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();" |
| 319 | requestExitAndWait(); |
| 320 | } |
| 321 | |
| 322 | status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs) |
| 323 | { |
| 324 | status_t status; |
| 325 | |
| 326 | ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string()); |
| 327 | Mutex::Autolock _l(mLock); |
| 328 | |
| 329 | mNewParameters.add(keyValuePairs); |
| 330 | mWaitWorkCV.signal(); |
| 331 | // wait condition with timeout in case the thread loop has exited |
| 332 | // before the request could be processed |
| 333 | if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) { |
| 334 | status = mParamStatus; |
| 335 | mWaitWorkCV.signal(); |
| 336 | } else { |
| 337 | status = TIMED_OUT; |
| 338 | } |
| 339 | return status; |
| 340 | } |
| 341 | |
| 342 | void AudioFlinger::ThreadBase::sendIoConfigEvent(int event, int param) |
| 343 | { |
| 344 | Mutex::Autolock _l(mLock); |
| 345 | sendIoConfigEvent_l(event, param); |
| 346 | } |
| 347 | |
| 348 | // sendIoConfigEvent_l() must be called with ThreadBase::mLock held |
| 349 | void AudioFlinger::ThreadBase::sendIoConfigEvent_l(int event, int param) |
| 350 | { |
| 351 | IoConfigEvent *ioEvent = new IoConfigEvent(event, param); |
| 352 | mConfigEvents.add(static_cast<ConfigEvent *>(ioEvent)); |
| 353 | ALOGV("sendIoConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, |
| 354 | param); |
| 355 | mWaitWorkCV.signal(); |
| 356 | } |
| 357 | |
| 358 | // sendPrioConfigEvent_l() must be called with ThreadBase::mLock held |
| 359 | void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio) |
| 360 | { |
| 361 | PrioConfigEvent *prioEvent = new PrioConfigEvent(pid, tid, prio); |
| 362 | mConfigEvents.add(static_cast<ConfigEvent *>(prioEvent)); |
| 363 | ALOGV("sendPrioConfigEvent_l() num events %d pid %d, tid %d prio %d", |
| 364 | mConfigEvents.size(), pid, tid, prio); |
| 365 | mWaitWorkCV.signal(); |
| 366 | } |
| 367 | |
| 368 | void AudioFlinger::ThreadBase::processConfigEvents() |
| 369 | { |
| 370 | mLock.lock(); |
| 371 | while (!mConfigEvents.isEmpty()) { |
| 372 | ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size()); |
| 373 | ConfigEvent *event = mConfigEvents[0]; |
| 374 | mConfigEvents.removeAt(0); |
| 375 | // release mLock before locking AudioFlinger mLock: lock order is always |
| 376 | // AudioFlinger then ThreadBase to avoid cross deadlock |
| 377 | mLock.unlock(); |
| 378 | switch(event->type()) { |
| 379 | case CFG_EVENT_PRIO: { |
| 380 | PrioConfigEvent *prioEvent = static_cast<PrioConfigEvent *>(event); |
Glenn Kasten | a07f17c | 2013-04-23 12:39:37 -0700 | [diff] [blame] | 381 | // FIXME Need to understand why this has be done asynchronously |
| 382 | int err = requestPriority(prioEvent->pid(), prioEvent->tid(), prioEvent->prio(), |
| 383 | true /*asynchronous*/); |
Eric Laurent | 81784c3 | 2012-11-19 14:55:58 -0800 | [diff] [blame] | 384 | if (err != 0) { |
| 385 | ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; " |
| 386 | "error %d", |
| 387 | prioEvent->prio(), prioEvent->pid(), prioEvent->tid(), err); |
| 388 | } |
| 389 | } break; |
| 390 | case CFG_EVENT_IO: { |
| 391 | IoConfigEvent *ioEvent = static_cast<IoConfigEvent *>(event); |
| 392 | mAudioFlinger->mLock.lock(); |
| 393 | audioConfigChanged_l(ioEvent->event(), ioEvent->param()); |
| 394 | mAudioFlinger->mLock.unlock(); |
| 395 | } break; |
| 396 | default: |
| 397 | ALOGE("processConfigEvents() unknown event type %d", event->type()); |
| 398 | break; |
| 399 | } |
| 400 | delete event; |
| 401 | mLock.lock(); |
| 402 | } |
| 403 | mLock.unlock(); |
| 404 | } |
| 405 | |
| 406 | void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args) |
| 407 | { |
| 408 | const size_t SIZE = 256; |
| 409 | char buffer[SIZE]; |
| 410 | String8 result; |
| 411 | |
| 412 | bool locked = AudioFlinger::dumpTryLock(mLock); |
| 413 | if (!locked) { |
| 414 | snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this); |
| 415 | write(fd, buffer, strlen(buffer)); |
| 416 | } |
| 417 | |
| 418 | snprintf(buffer, SIZE, "io handle: %d\n", mId); |
| 419 | result.append(buffer); |
| 420 | snprintf(buffer, SIZE, "TID: %d\n", getTid()); |
| 421 | result.append(buffer); |
| 422 | snprintf(buffer, SIZE, "standby: %d\n", mStandby); |
| 423 | result.append(buffer); |
| 424 | snprintf(buffer, SIZE, "Sample rate: %u\n", mSampleRate); |
| 425 | result.append(buffer); |
| 426 | snprintf(buffer, SIZE, "HAL frame count: %d\n", mFrameCount); |
| 427 | result.append(buffer); |
| 428 | snprintf(buffer, SIZE, "Normal frame count: %d\n", mNormalFrameCount); |
| 429 | result.append(buffer); |
| 430 | snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount); |
| 431 | result.append(buffer); |
| 432 | snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask); |
| 433 | result.append(buffer); |
| 434 | snprintf(buffer, SIZE, "Format: %d\n", mFormat); |
| 435 | result.append(buffer); |
| 436 | snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize); |
| 437 | result.append(buffer); |
| 438 | |
| 439 | snprintf(buffer, SIZE, "\nPending setParameters commands: \n"); |
| 440 | result.append(buffer); |
| 441 | result.append(" Index Command"); |
| 442 | for (size_t i = 0; i < mNewParameters.size(); ++i) { |
| 443 | snprintf(buffer, SIZE, "\n %02d ", i); |
| 444 | result.append(buffer); |
| 445 | result.append(mNewParameters[i]); |
| 446 | } |
| 447 | |
| 448 | snprintf(buffer, SIZE, "\n\nPending config events: \n"); |
| 449 | result.append(buffer); |
| 450 | for (size_t i = 0; i < mConfigEvents.size(); i++) { |
| 451 | mConfigEvents[i]->dump(buffer, SIZE); |
| 452 | result.append(buffer); |
| 453 | } |
| 454 | result.append("\n"); |
| 455 | |
| 456 | write(fd, result.string(), result.size()); |
| 457 | |
| 458 | if (locked) { |
| 459 | mLock.unlock(); |
| 460 | } |
| 461 | } |
| 462 | |
| 463 | void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args) |
| 464 | { |
| 465 | const size_t SIZE = 256; |
| 466 | char buffer[SIZE]; |
| 467 | String8 result; |
| 468 | |
| 469 | snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size()); |
| 470 | write(fd, buffer, strlen(buffer)); |
| 471 | |
| 472 | for (size_t i = 0; i < mEffectChains.size(); ++i) { |
| 473 | sp<EffectChain> chain = mEffectChains[i]; |
| 474 | if (chain != 0) { |
| 475 | chain->dump(fd, args); |
| 476 | } |
| 477 | } |
| 478 | } |
| 479 | |
| 480 | void AudioFlinger::ThreadBase::acquireWakeLock() |
| 481 | { |
| 482 | Mutex::Autolock _l(mLock); |
| 483 | acquireWakeLock_l(); |
| 484 | } |
| 485 | |
| 486 | void AudioFlinger::ThreadBase::acquireWakeLock_l() |
| 487 | { |
| 488 | if (mPowerManager == 0) { |
| 489 | // use checkService() to avoid blocking if power service is not up yet |
| 490 | sp<IBinder> binder = |
| 491 | defaultServiceManager()->checkService(String16("power")); |
| 492 | if (binder == 0) { |
| 493 | ALOGW("Thread %s cannot connect to the power manager service", mName); |
| 494 | } else { |
| 495 | mPowerManager = interface_cast<IPowerManager>(binder); |
| 496 | binder->linkToDeath(mDeathRecipient); |
| 497 | } |
| 498 | } |
| 499 | if (mPowerManager != 0) { |
| 500 | sp<IBinder> binder = new BBinder(); |
| 501 | status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK, |
| 502 | binder, |
Dianne Hackborn | 61d404e | 2013-05-20 11:22:20 -0700 | [diff] [blame] | 503 | String16(mName), |
| 504 | String16("media")); |
Eric Laurent | 81784c3 | 2012-11-19 14:55:58 -0800 | [diff] [blame] | 505 | if (status == NO_ERROR) { |
| 506 | mWakeLockToken = binder; |
| 507 | } |
| 508 | ALOGV("acquireWakeLock_l() %s status %d", mName, status); |
| 509 | } |
| 510 | } |
| 511 | |
| 512 | void AudioFlinger::ThreadBase::releaseWakeLock() |
| 513 | { |
| 514 | Mutex::Autolock _l(mLock); |
| 515 | releaseWakeLock_l(); |
| 516 | } |
| 517 | |
| 518 | void AudioFlinger::ThreadBase::releaseWakeLock_l() |
| 519 | { |
| 520 | if (mWakeLockToken != 0) { |
| 521 | ALOGV("releaseWakeLock_l() %s", mName); |
| 522 | if (mPowerManager != 0) { |
| 523 | mPowerManager->releaseWakeLock(mWakeLockToken, 0); |
| 524 | } |
| 525 | mWakeLockToken.clear(); |
| 526 | } |
| 527 | } |
| 528 | |
| 529 | void AudioFlinger::ThreadBase::clearPowerManager() |
| 530 | { |
| 531 | Mutex::Autolock _l(mLock); |
| 532 | releaseWakeLock_l(); |
| 533 | mPowerManager.clear(); |
| 534 | } |
| 535 | |
| 536 | void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who) |
| 537 | { |
| 538 | sp<ThreadBase> thread = mThread.promote(); |
| 539 | if (thread != 0) { |
| 540 | thread->clearPowerManager(); |
| 541 | } |
| 542 | ALOGW("power manager service died !!!"); |
| 543 | } |
| 544 | |
| 545 | void AudioFlinger::ThreadBase::setEffectSuspended( |
| 546 | const effect_uuid_t *type, bool suspend, int sessionId) |
| 547 | { |
| 548 | Mutex::Autolock _l(mLock); |
| 549 | setEffectSuspended_l(type, suspend, sessionId); |
| 550 | } |
| 551 | |
| 552 | void AudioFlinger::ThreadBase::setEffectSuspended_l( |
| 553 | const effect_uuid_t *type, bool suspend, int sessionId) |
| 554 | { |
| 555 | sp<EffectChain> chain = getEffectChain_l(sessionId); |
| 556 | if (chain != 0) { |
| 557 | if (type != NULL) { |
| 558 | chain->setEffectSuspended_l(type, suspend); |
| 559 | } else { |
| 560 | chain->setEffectSuspendedAll_l(suspend); |
| 561 | } |
| 562 | } |
| 563 | |
| 564 | updateSuspendedSessions_l(type, suspend, sessionId); |
| 565 | } |
| 566 | |
| 567 | void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain) |
| 568 | { |
| 569 | ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId()); |
| 570 | if (index < 0) { |
| 571 | return; |
| 572 | } |
| 573 | |
| 574 | const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects = |
| 575 | mSuspendedSessions.valueAt(index); |
| 576 | |
| 577 | for (size_t i = 0; i < sessionEffects.size(); i++) { |
| 578 | sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i); |
| 579 | for (int j = 0; j < desc->mRefCount; j++) { |
| 580 | if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) { |
| 581 | chain->setEffectSuspendedAll_l(true); |
| 582 | } else { |
| 583 | ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x", |
| 584 | desc->mType.timeLow); |
| 585 | chain->setEffectSuspended_l(&desc->mType, true); |
| 586 | } |
| 587 | } |
| 588 | } |
| 589 | } |
| 590 | |
| 591 | void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type, |
| 592 | bool suspend, |
| 593 | int sessionId) |
| 594 | { |
| 595 | ssize_t index = mSuspendedSessions.indexOfKey(sessionId); |
| 596 | |
| 597 | KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects; |
| 598 | |
| 599 | if (suspend) { |
| 600 | if (index >= 0) { |
| 601 | sessionEffects = mSuspendedSessions.valueAt(index); |
| 602 | } else { |
| 603 | mSuspendedSessions.add(sessionId, sessionEffects); |
| 604 | } |
| 605 | } else { |
| 606 | if (index < 0) { |
| 607 | return; |
| 608 | } |
| 609 | sessionEffects = mSuspendedSessions.valueAt(index); |
| 610 | } |
| 611 | |
| 612 | |
| 613 | int key = EffectChain::kKeyForSuspendAll; |
| 614 | if (type != NULL) { |
| 615 | key = type->timeLow; |
| 616 | } |
| 617 | index = sessionEffects.indexOfKey(key); |
| 618 | |
| 619 | sp<SuspendedSessionDesc> desc; |
| 620 | if (suspend) { |
| 621 | if (index >= 0) { |
| 622 | desc = sessionEffects.valueAt(index); |
| 623 | } else { |
| 624 | desc = new SuspendedSessionDesc(); |
| 625 | if (type != NULL) { |
| 626 | desc->mType = *type; |
| 627 | } |
| 628 | sessionEffects.add(key, desc); |
| 629 | ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key); |
| 630 | } |
| 631 | desc->mRefCount++; |
| 632 | } else { |
| 633 | if (index < 0) { |
| 634 | return; |
| 635 | } |
| 636 | desc = sessionEffects.valueAt(index); |
| 637 | if (--desc->mRefCount == 0) { |
| 638 | ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key); |
| 639 | sessionEffects.removeItemsAt(index); |
| 640 | if (sessionEffects.isEmpty()) { |
| 641 | ALOGV("updateSuspendedSessions_l() restore removing session %d", |
| 642 | sessionId); |
| 643 | mSuspendedSessions.removeItem(sessionId); |
| 644 | } |
| 645 | } |
| 646 | } |
| 647 | if (!sessionEffects.isEmpty()) { |
| 648 | mSuspendedSessions.replaceValueFor(sessionId, sessionEffects); |
| 649 | } |
| 650 | } |
| 651 | |
| 652 | void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect, |
| 653 | bool enabled, |
| 654 | int sessionId) |
| 655 | { |
| 656 | Mutex::Autolock _l(mLock); |
| 657 | checkSuspendOnEffectEnabled_l(effect, enabled, sessionId); |
| 658 | } |
| 659 | |
| 660 | void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect, |
| 661 | bool enabled, |
| 662 | int sessionId) |
| 663 | { |
| 664 | if (mType != RECORD) { |
| 665 | // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on |
| 666 | // another session. This gives the priority to well behaved effect control panels |
| 667 | // and applications not using global effects. |
| 668 | // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect |
| 669 | // global effects |
| 670 | if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) { |
| 671 | setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX); |
| 672 | } |
| 673 | } |
| 674 | |
| 675 | sp<EffectChain> chain = getEffectChain_l(sessionId); |
| 676 | if (chain != 0) { |
| 677 | chain->checkSuspendOnEffectEnabled(effect, enabled); |
| 678 | } |
| 679 | } |
| 680 | |
| 681 | // ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held |
| 682 | sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l( |
| 683 | const sp<AudioFlinger::Client>& client, |
| 684 | const sp<IEffectClient>& effectClient, |
| 685 | int32_t priority, |
| 686 | int sessionId, |
| 687 | effect_descriptor_t *desc, |
| 688 | int *enabled, |
| 689 | status_t *status |
| 690 | ) |
| 691 | { |
| 692 | sp<EffectModule> effect; |
| 693 | sp<EffectHandle> handle; |
| 694 | status_t lStatus; |
| 695 | sp<EffectChain> chain; |
| 696 | bool chainCreated = false; |
| 697 | bool effectCreated = false; |
| 698 | bool effectRegistered = false; |
| 699 | |
| 700 | lStatus = initCheck(); |
| 701 | if (lStatus != NO_ERROR) { |
| 702 | ALOGW("createEffect_l() Audio driver not initialized."); |
| 703 | goto Exit; |
| 704 | } |
| 705 | |
| 706 | // Do not allow effects with session ID 0 on direct output or duplicating threads |
| 707 | // TODO: add rule for hw accelerated effects on direct outputs with non PCM format |
| 708 | if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) { |
| 709 | ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d", |
| 710 | desc->name, sessionId); |
| 711 | lStatus = BAD_VALUE; |
| 712 | goto Exit; |
| 713 | } |
| 714 | // Only Pre processor effects are allowed on input threads and only on input threads |
| 715 | if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) { |
| 716 | ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d", |
| 717 | desc->name, desc->flags, mType); |
| 718 | lStatus = BAD_VALUE; |
| 719 | goto Exit; |
| 720 | } |
| 721 | |
| 722 | ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId); |
| 723 | |
| 724 | { // scope for mLock |
| 725 | Mutex::Autolock _l(mLock); |
| 726 | |
| 727 | // check for existing effect chain with the requested audio session |
| 728 | chain = getEffectChain_l(sessionId); |
| 729 | if (chain == 0) { |
| 730 | // create a new chain for this session |
| 731 | ALOGV("createEffect_l() new effect chain for session %d", sessionId); |
| 732 | chain = new EffectChain(this, sessionId); |
| 733 | addEffectChain_l(chain); |
| 734 | chain->setStrategy(getStrategyForSession_l(sessionId)); |
| 735 | chainCreated = true; |
| 736 | } else { |
| 737 | effect = chain->getEffectFromDesc_l(desc); |
| 738 | } |
| 739 | |
| 740 | ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get()); |
| 741 | |
| 742 | if (effect == 0) { |
| 743 | int id = mAudioFlinger->nextUniqueId(); |
| 744 | // Check CPU and memory usage |
| 745 | lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id); |
| 746 | if (lStatus != NO_ERROR) { |
| 747 | goto Exit; |
| 748 | } |
| 749 | effectRegistered = true; |
| 750 | // create a new effect module if none present in the chain |
| 751 | effect = new EffectModule(this, chain, desc, id, sessionId); |
| 752 | lStatus = effect->status(); |
| 753 | if (lStatus != NO_ERROR) { |
| 754 | goto Exit; |
| 755 | } |
| 756 | lStatus = chain->addEffect_l(effect); |
| 757 | if (lStatus != NO_ERROR) { |
| 758 | goto Exit; |
| 759 | } |
| 760 | effectCreated = true; |
| 761 | |
| 762 | effect->setDevice(mOutDevice); |
| 763 | effect->setDevice(mInDevice); |
| 764 | effect->setMode(mAudioFlinger->getMode()); |
| 765 | effect->setAudioSource(mAudioSource); |
| 766 | } |
| 767 | // create effect handle and connect it to effect module |
| 768 | handle = new EffectHandle(effect, client, effectClient, priority); |
| 769 | lStatus = effect->addHandle(handle.get()); |
| 770 | if (enabled != NULL) { |
| 771 | *enabled = (int)effect->isEnabled(); |
| 772 | } |
| 773 | } |
| 774 | |
| 775 | Exit: |
| 776 | if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) { |
| 777 | Mutex::Autolock _l(mLock); |
| 778 | if (effectCreated) { |
| 779 | chain->removeEffect_l(effect); |
| 780 | } |
| 781 | if (effectRegistered) { |
| 782 | AudioSystem::unregisterEffect(effect->id()); |
| 783 | } |
| 784 | if (chainCreated) { |
| 785 | removeEffectChain_l(chain); |
| 786 | } |
| 787 | handle.clear(); |
| 788 | } |
| 789 | |
| 790 | if (status != NULL) { |
| 791 | *status = lStatus; |
| 792 | } |
| 793 | return handle; |
| 794 | } |
| 795 | |
| 796 | sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId) |
| 797 | { |
| 798 | Mutex::Autolock _l(mLock); |
| 799 | return getEffect_l(sessionId, effectId); |
| 800 | } |
| 801 | |
| 802 | sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId) |
| 803 | { |
| 804 | sp<EffectChain> chain = getEffectChain_l(sessionId); |
| 805 | return chain != 0 ? chain->getEffectFromId_l(effectId) : 0; |
| 806 | } |
| 807 | |
| 808 | // PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and |
| 809 | // PlaybackThread::mLock held |
| 810 | status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect) |
| 811 | { |
| 812 | // check for existing effect chain with the requested audio session |
| 813 | int sessionId = effect->sessionId(); |
| 814 | sp<EffectChain> chain = getEffectChain_l(sessionId); |
| 815 | bool chainCreated = false; |
| 816 | |
| 817 | if (chain == 0) { |
| 818 | // create a new chain for this session |
| 819 | ALOGV("addEffect_l() new effect chain for session %d", sessionId); |
| 820 | chain = new EffectChain(this, sessionId); |
| 821 | addEffectChain_l(chain); |
| 822 | chain->setStrategy(getStrategyForSession_l(sessionId)); |
| 823 | chainCreated = true; |
| 824 | } |
| 825 | ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get()); |
| 826 | |
| 827 | if (chain->getEffectFromId_l(effect->id()) != 0) { |
| 828 | ALOGW("addEffect_l() %p effect %s already present in chain %p", |
| 829 | this, effect->desc().name, chain.get()); |
| 830 | return BAD_VALUE; |
| 831 | } |
| 832 | |
| 833 | status_t status = chain->addEffect_l(effect); |
| 834 | if (status != NO_ERROR) { |
| 835 | if (chainCreated) { |
| 836 | removeEffectChain_l(chain); |
| 837 | } |
| 838 | return status; |
| 839 | } |
| 840 | |
| 841 | effect->setDevice(mOutDevice); |
| 842 | effect->setDevice(mInDevice); |
| 843 | effect->setMode(mAudioFlinger->getMode()); |
| 844 | effect->setAudioSource(mAudioSource); |
| 845 | return NO_ERROR; |
| 846 | } |
| 847 | |
| 848 | void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) { |
| 849 | |
| 850 | ALOGV("removeEffect_l() %p effect %p", this, effect.get()); |
| 851 | effect_descriptor_t desc = effect->desc(); |
| 852 | if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { |
| 853 | detachAuxEffect_l(effect->id()); |
| 854 | } |
| 855 | |
| 856 | sp<EffectChain> chain = effect->chain().promote(); |
| 857 | if (chain != 0) { |
| 858 | // remove effect chain if removing last effect |
| 859 | if (chain->removeEffect_l(effect) == 0) { |
| 860 | removeEffectChain_l(chain); |
| 861 | } |
| 862 | } else { |
| 863 | ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get()); |
| 864 | } |
| 865 | } |
| 866 | |
| 867 | void AudioFlinger::ThreadBase::lockEffectChains_l( |
| 868 | Vector< sp<AudioFlinger::EffectChain> >& effectChains) |
| 869 | { |
| 870 | effectChains = mEffectChains; |
| 871 | for (size_t i = 0; i < mEffectChains.size(); i++) { |
| 872 | mEffectChains[i]->lock(); |
| 873 | } |
| 874 | } |
| 875 | |
| 876 | void AudioFlinger::ThreadBase::unlockEffectChains( |
| 877 | const Vector< sp<AudioFlinger::EffectChain> >& effectChains) |
| 878 | { |
| 879 | for (size_t i = 0; i < effectChains.size(); i++) { |
| 880 | effectChains[i]->unlock(); |
| 881 | } |
| 882 | } |
| 883 | |
| 884 | sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId) |
| 885 | { |
| 886 | Mutex::Autolock _l(mLock); |
| 887 | return getEffectChain_l(sessionId); |
| 888 | } |
| 889 | |
| 890 | sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const |
| 891 | { |
| 892 | size_t size = mEffectChains.size(); |
| 893 | for (size_t i = 0; i < size; i++) { |
| 894 | if (mEffectChains[i]->sessionId() == sessionId) { |
| 895 | return mEffectChains[i]; |
| 896 | } |
| 897 | } |
| 898 | return 0; |
| 899 | } |
| 900 | |
| 901 | void AudioFlinger::ThreadBase::setMode(audio_mode_t mode) |
| 902 | { |
| 903 | Mutex::Autolock _l(mLock); |
| 904 | size_t size = mEffectChains.size(); |
| 905 | for (size_t i = 0; i < size; i++) { |
| 906 | mEffectChains[i]->setMode_l(mode); |
| 907 | } |
| 908 | } |
| 909 | |
| 910 | void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect, |
| 911 | EffectHandle *handle, |
| 912 | bool unpinIfLast) { |
| 913 | |
| 914 | Mutex::Autolock _l(mLock); |
| 915 | ALOGV("disconnectEffect() %p effect %p", this, effect.get()); |
| 916 | // delete the effect module if removing last handle on it |
| 917 | if (effect->removeHandle(handle) == 0) { |
| 918 | if (!effect->isPinned() || unpinIfLast) { |
| 919 | removeEffect_l(effect); |
| 920 | AudioSystem::unregisterEffect(effect->id()); |
| 921 | } |
| 922 | } |
| 923 | } |
| 924 | |
| 925 | // ---------------------------------------------------------------------------- |
| 926 | // Playback |
| 927 | // ---------------------------------------------------------------------------- |
| 928 | |
| 929 | AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger, |
| 930 | AudioStreamOut* output, |
| 931 | audio_io_handle_t id, |
| 932 | audio_devices_t device, |
| 933 | type_t type) |
| 934 | : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type), |
| 935 | mMixBuffer(NULL), mSuspended(0), mBytesWritten(0), |
| 936 | // mStreamTypes[] initialized in constructor body |
| 937 | mOutput(output), |
| 938 | mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false), |
| 939 | mMixerStatus(MIXER_IDLE), |
| 940 | mMixerStatusIgnoringFastTracks(MIXER_IDLE), |
| 941 | standbyDelay(AudioFlinger::mStandbyTimeInNsecs), |
| 942 | mScreenState(AudioFlinger::mScreenState), |
| 943 | // index 0 is reserved for normal mixer's submix |
| 944 | mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1) |
| 945 | { |
| 946 | snprintf(mName, kNameLength, "AudioOut_%X", id); |
Glenn Kasten | 9e58b55 | 2013-01-18 15:09:48 -0800 | [diff] [blame] | 947 | mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName); |
Eric Laurent | 81784c3 | 2012-11-19 14:55:58 -0800 | [diff] [blame] | 948 | |
| 949 | // Assumes constructor is called by AudioFlinger with it's mLock held, but |
| 950 | // it would be safer to explicitly pass initial masterVolume/masterMute as |
| 951 | // parameter. |
| 952 | // |
| 953 | // If the HAL we are using has support for master volume or master mute, |
| 954 | // then do not attenuate or mute during mixing (just leave the volume at 1.0 |
| 955 | // and the mute set to false). |
| 956 | mMasterVolume = audioFlinger->masterVolume_l(); |
| 957 | mMasterMute = audioFlinger->masterMute_l(); |
| 958 | if (mOutput && mOutput->audioHwDev) { |
| 959 | if (mOutput->audioHwDev->canSetMasterVolume()) { |
| 960 | mMasterVolume = 1.0; |
| 961 | } |
| 962 | |
| 963 | if (mOutput->audioHwDev->canSetMasterMute()) { |
| 964 | mMasterMute = false; |
| 965 | } |
| 966 | } |
| 967 | |
| 968 | readOutputParameters(); |
| 969 | |
| 970 | // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor |
| 971 | // There is no AUDIO_STREAM_MIN, and ++ operator does not compile |
| 972 | for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT; |
| 973 | stream = (audio_stream_type_t) (stream + 1)) { |
| 974 | mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream); |
| 975 | mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream); |
| 976 | } |
| 977 | // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here, |
| 978 | // because mAudioFlinger doesn't have one to copy from |
| 979 | } |
| 980 | |
| 981 | AudioFlinger::PlaybackThread::~PlaybackThread() |
| 982 | { |
Glenn Kasten | 9e58b55 | 2013-01-18 15:09:48 -0800 | [diff] [blame] | 983 | mAudioFlinger->unregisterWriter(mNBLogWriter); |
Eric Laurent | 81784c3 | 2012-11-19 14:55:58 -0800 | [diff] [blame] | 984 | delete [] mMixBuffer; |
| 985 | } |
| 986 | |
| 987 | void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args) |
| 988 | { |
| 989 | dumpInternals(fd, args); |
| 990 | dumpTracks(fd, args); |
| 991 | dumpEffectChains(fd, args); |
| 992 | } |
| 993 | |
| 994 | void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args) |
| 995 | { |
| 996 | const size_t SIZE = 256; |
| 997 | char buffer[SIZE]; |
| 998 | String8 result; |
| 999 | |
| 1000 | result.appendFormat("Output thread %p stream volumes in dB:\n ", this); |
| 1001 | for (int i = 0; i < AUDIO_STREAM_CNT; ++i) { |
| 1002 | const stream_type_t *st = &mStreamTypes[i]; |
| 1003 | if (i > 0) { |
| 1004 | result.appendFormat(", "); |
| 1005 | } |
| 1006 | result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume)); |
| 1007 | if (st->mute) { |
| 1008 | result.append("M"); |
| 1009 | } |
| 1010 | } |
| 1011 | result.append("\n"); |
| 1012 | write(fd, result.string(), result.length()); |
| 1013 | result.clear(); |
| 1014 | |
| 1015 | snprintf(buffer, SIZE, "Output thread %p tracks\n", this); |
| 1016 | result.append(buffer); |
| 1017 | Track::appendDumpHeader(result); |
| 1018 | for (size_t i = 0; i < mTracks.size(); ++i) { |
| 1019 | sp<Track> track = mTracks[i]; |
| 1020 | if (track != 0) { |
| 1021 | track->dump(buffer, SIZE); |
| 1022 | result.append(buffer); |
| 1023 | } |
| 1024 | } |
| 1025 | |
| 1026 | snprintf(buffer, SIZE, "Output thread %p active tracks\n", this); |
| 1027 | result.append(buffer); |
| 1028 | Track::appendDumpHeader(result); |
| 1029 | for (size_t i = 0; i < mActiveTracks.size(); ++i) { |
| 1030 | sp<Track> track = mActiveTracks[i].promote(); |
| 1031 | if (track != 0) { |
| 1032 | track->dump(buffer, SIZE); |
| 1033 | result.append(buffer); |
| 1034 | } |
| 1035 | } |
| 1036 | write(fd, result.string(), result.size()); |
| 1037 | |
| 1038 | // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way. |
| 1039 | FastTrackUnderruns underruns = getFastTrackUnderruns(0); |
| 1040 | fdprintf(fd, "Normal mixer raw underrun counters: partial=%u empty=%u\n", |
| 1041 | underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty); |
| 1042 | } |
| 1043 | |
| 1044 | void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args) |
| 1045 | { |
| 1046 | const size_t SIZE = 256; |
| 1047 | char buffer[SIZE]; |
| 1048 | String8 result; |
| 1049 | |
| 1050 | snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this); |
| 1051 | result.append(buffer); |
| 1052 | snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", |
| 1053 | ns2ms(systemTime() - mLastWriteTime)); |
| 1054 | result.append(buffer); |
| 1055 | snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites); |
| 1056 | result.append(buffer); |
| 1057 | snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites); |
| 1058 | result.append(buffer); |
| 1059 | snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite); |
| 1060 | result.append(buffer); |
| 1061 | snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended); |
| 1062 | result.append(buffer); |
| 1063 | snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer); |
| 1064 | result.append(buffer); |
| 1065 | write(fd, result.string(), result.size()); |
| 1066 | fdprintf(fd, "Fast track availMask=%#x\n", mFastTrackAvailMask); |
| 1067 | |
| 1068 | dumpBase(fd, args); |
| 1069 | } |
| 1070 | |
| 1071 | // Thread virtuals |
| 1072 | status_t AudioFlinger::PlaybackThread::readyToRun() |
| 1073 | { |
| 1074 | status_t status = initCheck(); |
| 1075 | if (status == NO_ERROR) { |
| 1076 | ALOGI("AudioFlinger's thread %p ready to run", this); |
| 1077 | } else { |
| 1078 | ALOGE("No working audio driver found."); |
| 1079 | } |
| 1080 | return status; |
| 1081 | } |
| 1082 | |
| 1083 | void AudioFlinger::PlaybackThread::onFirstRef() |
| 1084 | { |
| 1085 | run(mName, ANDROID_PRIORITY_URGENT_AUDIO); |
| 1086 | } |
| 1087 | |
| 1088 | // ThreadBase virtuals |
| 1089 | void AudioFlinger::PlaybackThread::preExit() |
| 1090 | { |
| 1091 | ALOGV(" preExit()"); |
| 1092 | // FIXME this is using hard-coded strings but in the future, this functionality will be |
| 1093 | // converted to use audio HAL extensions required to support tunneling |
| 1094 | mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1"); |
| 1095 | } |
| 1096 | |
| 1097 | // PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held |
| 1098 | sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l( |
| 1099 | const sp<AudioFlinger::Client>& client, |
| 1100 | audio_stream_type_t streamType, |
| 1101 | uint32_t sampleRate, |
| 1102 | audio_format_t format, |
| 1103 | audio_channel_mask_t channelMask, |
| 1104 | size_t frameCount, |
| 1105 | const sp<IMemory>& sharedBuffer, |
| 1106 | int sessionId, |
| 1107 | IAudioFlinger::track_flags_t *flags, |
| 1108 | pid_t tid, |
| 1109 | status_t *status) |
| 1110 | { |
| 1111 | sp<Track> track; |
| 1112 | status_t lStatus; |
| 1113 | |
| 1114 | bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0; |
| 1115 | |
| 1116 | // client expresses a preference for FAST, but we get the final say |
| 1117 | if (*flags & IAudioFlinger::TRACK_FAST) { |
| 1118 | if ( |
| 1119 | // not timed |
| 1120 | (!isTimed) && |
| 1121 | // either of these use cases: |
| 1122 | ( |
| 1123 | // use case 1: shared buffer with any frame count |
| 1124 | ( |
| 1125 | (sharedBuffer != 0) |
| 1126 | ) || |
| 1127 | // use case 2: callback handler and frame count is default or at least as large as HAL |
| 1128 | ( |
| 1129 | (tid != -1) && |
| 1130 | ((frameCount == 0) || |
| 1131 | (frameCount >= (mFrameCount * kFastTrackMultiplier))) |
| 1132 | ) |
| 1133 | ) && |
| 1134 | // PCM data |
| 1135 | audio_is_linear_pcm(format) && |
| 1136 | // mono or stereo |
| 1137 | ( (channelMask == AUDIO_CHANNEL_OUT_MONO) || |
| 1138 | (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) && |
| 1139 | #ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE |
| 1140 | // hardware sample rate |
| 1141 | (sampleRate == mSampleRate) && |
| 1142 | #endif |
| 1143 | // normal mixer has an associated fast mixer |
| 1144 | hasFastMixer() && |
| 1145 | // there are sufficient fast track slots available |
| 1146 | (mFastTrackAvailMask != 0) |
| 1147 | // FIXME test that MixerThread for this fast track has a capable output HAL |
| 1148 | // FIXME add a permission test also? |
| 1149 | ) { |
| 1150 | // if frameCount not specified, then it defaults to fast mixer (HAL) frame count |
| 1151 | if (frameCount == 0) { |
| 1152 | frameCount = mFrameCount * kFastTrackMultiplier; |
| 1153 | } |
| 1154 | ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d", |
| 1155 | frameCount, mFrameCount); |
| 1156 | } else { |
| 1157 | ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d " |
| 1158 | "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u " |
| 1159 | "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x", |
| 1160 | isTimed, sharedBuffer.get(), frameCount, mFrameCount, format, |
| 1161 | audio_is_linear_pcm(format), |
| 1162 | channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask); |
| 1163 | *flags &= ~IAudioFlinger::TRACK_FAST; |
| 1164 | // For compatibility with AudioTrack calculation, buffer depth is forced |
| 1165 | // to be at least 2 x the normal mixer frame count and cover audio hardware latency. |
| 1166 | // This is probably too conservative, but legacy application code may depend on it. |
| 1167 | // If you change this calculation, also review the start threshold which is related. |
| 1168 | uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream); |
| 1169 | uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate); |
| 1170 | if (minBufCount < 2) { |
| 1171 | minBufCount = 2; |
| 1172 | } |
| 1173 | size_t minFrameCount = mNormalFrameCount * minBufCount; |
| 1174 | if (frameCount < minFrameCount) { |
| 1175 | frameCount = minFrameCount; |
| 1176 | } |
| 1177 | } |
| 1178 | } |
| 1179 | |
| 1180 | if (mType == DIRECT) { |
| 1181 | if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) { |
| 1182 | if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) { |
| 1183 | ALOGE("createTrack_l() Bad parameter: sampleRate %u format %d, channelMask 0x%08x " |
| 1184 | "for output %p with format %d", |
| 1185 | sampleRate, format, channelMask, mOutput, mFormat); |
| 1186 | lStatus = BAD_VALUE; |
| 1187 | goto Exit; |
| 1188 | } |
| 1189 | } |
| 1190 | } else { |
| 1191 | // Resampler implementation limits input sampling rate to 2 x output sampling rate. |
| 1192 | if (sampleRate > mSampleRate*2) { |
| 1193 | ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate); |
| 1194 | lStatus = BAD_VALUE; |
| 1195 | goto Exit; |
| 1196 | } |
| 1197 | } |
| 1198 | |
| 1199 | lStatus = initCheck(); |
| 1200 | if (lStatus != NO_ERROR) { |
| 1201 | ALOGE("Audio driver not initialized."); |
| 1202 | goto Exit; |
| 1203 | } |
| 1204 | |
| 1205 | { // scope for mLock |
| 1206 | Mutex::Autolock _l(mLock); |
| 1207 | |
| 1208 | // all tracks in same audio session must share the same routing strategy otherwise |
| 1209 | // conflicts will happen when tracks are moved from one output to another by audio policy |
| 1210 | // manager |
| 1211 | uint32_t strategy = AudioSystem::getStrategyForStream(streamType); |
| 1212 | for (size_t i = 0; i < mTracks.size(); ++i) { |
| 1213 | sp<Track> t = mTracks[i]; |
| 1214 | if (t != 0 && !t->isOutputTrack()) { |
| 1215 | uint32_t actual = AudioSystem::getStrategyForStream(t->streamType()); |
| 1216 | if (sessionId == t->sessionId() && strategy != actual) { |
| 1217 | ALOGE("createTrack_l() mismatched strategy; expected %u but found %u", |
| 1218 | strategy, actual); |
| 1219 | lStatus = BAD_VALUE; |
| 1220 | goto Exit; |
| 1221 | } |
| 1222 | } |
| 1223 | } |
| 1224 | |
| 1225 | if (!isTimed) { |
| 1226 | track = new Track(this, client, streamType, sampleRate, format, |
| 1227 | channelMask, frameCount, sharedBuffer, sessionId, *flags); |
| 1228 | } else { |
| 1229 | track = TimedTrack::create(this, client, streamType, sampleRate, format, |
| 1230 | channelMask, frameCount, sharedBuffer, sessionId); |
| 1231 | } |
| 1232 | if (track == 0 || track->getCblk() == NULL || track->name() < 0) { |
| 1233 | lStatus = NO_MEMORY; |
| 1234 | goto Exit; |
| 1235 | } |
| 1236 | mTracks.add(track); |
| 1237 | |
| 1238 | sp<EffectChain> chain = getEffectChain_l(sessionId); |
| 1239 | if (chain != 0) { |
| 1240 | ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer()); |
| 1241 | track->setMainBuffer(chain->inBuffer()); |
| 1242 | chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType())); |
| 1243 | chain->incTrackCnt(); |
| 1244 | } |
| 1245 | |
| 1246 | if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) { |
| 1247 | pid_t callingPid = IPCThreadState::self()->getCallingPid(); |
| 1248 | // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful, |
| 1249 | // so ask activity manager to do this on our behalf |
| 1250 | sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp); |
| 1251 | } |
| 1252 | } |
| 1253 | |
| 1254 | lStatus = NO_ERROR; |
| 1255 | |
| 1256 | Exit: |
| 1257 | if (status) { |
| 1258 | *status = lStatus; |
| 1259 | } |
| 1260 | return track; |
| 1261 | } |
| 1262 | |
| 1263 | uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const |
| 1264 | { |
| 1265 | return latency; |
| 1266 | } |
| 1267 | |
| 1268 | uint32_t AudioFlinger::PlaybackThread::latency() const |
| 1269 | { |
| 1270 | Mutex::Autolock _l(mLock); |
| 1271 | return latency_l(); |
| 1272 | } |
| 1273 | uint32_t AudioFlinger::PlaybackThread::latency_l() const |
| 1274 | { |
| 1275 | if (initCheck() == NO_ERROR) { |
| 1276 | return correctLatency_l(mOutput->stream->get_latency(mOutput->stream)); |
| 1277 | } else { |
| 1278 | return 0; |
| 1279 | } |
| 1280 | } |
| 1281 | |
| 1282 | void AudioFlinger::PlaybackThread::setMasterVolume(float value) |
| 1283 | { |
| 1284 | Mutex::Autolock _l(mLock); |
| 1285 | // Don't apply master volume in SW if our HAL can do it for us. |
| 1286 | if (mOutput && mOutput->audioHwDev && |
| 1287 | mOutput->audioHwDev->canSetMasterVolume()) { |
| 1288 | mMasterVolume = 1.0; |
| 1289 | } else { |
| 1290 | mMasterVolume = value; |
| 1291 | } |
| 1292 | } |
| 1293 | |
| 1294 | void AudioFlinger::PlaybackThread::setMasterMute(bool muted) |
| 1295 | { |
| 1296 | Mutex::Autolock _l(mLock); |
| 1297 | // Don't apply master mute in SW if our HAL can do it for us. |
| 1298 | if (mOutput && mOutput->audioHwDev && |
| 1299 | mOutput->audioHwDev->canSetMasterMute()) { |
| 1300 | mMasterMute = false; |
| 1301 | } else { |
| 1302 | mMasterMute = muted; |
| 1303 | } |
| 1304 | } |
| 1305 | |
| 1306 | void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value) |
| 1307 | { |
| 1308 | Mutex::Autolock _l(mLock); |
| 1309 | mStreamTypes[stream].volume = value; |
| 1310 | } |
| 1311 | |
| 1312 | void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted) |
| 1313 | { |
| 1314 | Mutex::Autolock _l(mLock); |
| 1315 | mStreamTypes[stream].mute = muted; |
| 1316 | } |
| 1317 | |
| 1318 | float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const |
| 1319 | { |
| 1320 | Mutex::Autolock _l(mLock); |
| 1321 | return mStreamTypes[stream].volume; |
| 1322 | } |
| 1323 | |
| 1324 | // addTrack_l() must be called with ThreadBase::mLock held |
| 1325 | status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track) |
| 1326 | { |
| 1327 | status_t status = ALREADY_EXISTS; |
| 1328 | |
| 1329 | // set retry count for buffer fill |
| 1330 | track->mRetryCount = kMaxTrackStartupRetries; |
| 1331 | if (mActiveTracks.indexOf(track) < 0) { |
| 1332 | // the track is newly added, make sure it fills up all its |
| 1333 | // buffers before playing. This is to ensure the client will |
| 1334 | // effectively get the latency it requested. |
Glenn Kasten | 9f80dd2 | 2012-12-18 15:57:32 -0800 | [diff] [blame] | 1335 | track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING; |
Eric Laurent | 81784c3 | 2012-11-19 14:55:58 -0800 | [diff] [blame] | 1336 | track->mResetDone = false; |
| 1337 | track->mPresentationCompleteFrames = 0; |
| 1338 | mActiveTracks.add(track); |
Eric Laurent | d0107bc | 2013-06-11 14:38:48 -0700 | [diff] [blame] | 1339 | sp<EffectChain> chain = getEffectChain_l(track->sessionId()); |
| 1340 | if (chain != 0) { |
| 1341 | ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), |
| 1342 | track->sessionId()); |
| 1343 | chain->incActiveTrackCnt(); |
Eric Laurent | 81784c3 | 2012-11-19 14:55:58 -0800 | [diff] [blame] | 1344 | } |
| 1345 | |
| 1346 | status = NO_ERROR; |
| 1347 | } |
| 1348 | |
| 1349 | ALOGV("mWaitWorkCV.broadcast"); |
| 1350 | mWaitWorkCV.broadcast(); |
| 1351 | |
| 1352 | return status; |
| 1353 | } |
| 1354 | |
| 1355 | // destroyTrack_l() must be called with ThreadBase::mLock held |
| 1356 | void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track) |
| 1357 | { |
| 1358 | track->mState = TrackBase::TERMINATED; |
| 1359 | // active tracks are removed by threadLoop() |
| 1360 | if (mActiveTracks.indexOf(track) < 0) { |
| 1361 | removeTrack_l(track); |
| 1362 | } |
| 1363 | } |
| 1364 | |
| 1365 | void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track) |
| 1366 | { |
| 1367 | track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE); |
| 1368 | mTracks.remove(track); |
| 1369 | deleteTrackName_l(track->name()); |
| 1370 | // redundant as track is about to be destroyed, for dumpsys only |
| 1371 | track->mName = -1; |
| 1372 | if (track->isFastTrack()) { |
| 1373 | int index = track->mFastIndex; |
| 1374 | ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks); |
| 1375 | ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index))); |
| 1376 | mFastTrackAvailMask |= 1 << index; |
| 1377 | // redundant as track is about to be destroyed, for dumpsys only |
| 1378 | track->mFastIndex = -1; |
| 1379 | } |
| 1380 | sp<EffectChain> chain = getEffectChain_l(track->sessionId()); |
| 1381 | if (chain != 0) { |
| 1382 | chain->decTrackCnt(); |
| 1383 | } |
| 1384 | } |
| 1385 | |
| 1386 | String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys) |
| 1387 | { |
| 1388 | String8 out_s8 = String8(""); |
| 1389 | char *s; |
| 1390 | |
| 1391 | Mutex::Autolock _l(mLock); |
| 1392 | if (initCheck() != NO_ERROR) { |
| 1393 | return out_s8; |
| 1394 | } |
| 1395 | |
| 1396 | s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string()); |
| 1397 | out_s8 = String8(s); |
| 1398 | free(s); |
| 1399 | return out_s8; |
| 1400 | } |
| 1401 | |
| 1402 | // audioConfigChanged_l() must be called with AudioFlinger::mLock held |
| 1403 | void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) { |
| 1404 | AudioSystem::OutputDescriptor desc; |
| 1405 | void *param2 = NULL; |
| 1406 | |
| 1407 | ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, |
| 1408 | param); |
| 1409 | |
| 1410 | switch (event) { |
| 1411 | case AudioSystem::OUTPUT_OPENED: |
| 1412 | case AudioSystem::OUTPUT_CONFIG_CHANGED: |
Glenn Kasten | fad226a | 2013-07-16 17:19:58 -0700 | [diff] [blame^] | 1413 | desc.channelMask = mChannelMask; |
Eric Laurent | 81784c3 | 2012-11-19 14:55:58 -0800 | [diff] [blame] | 1414 | desc.samplingRate = mSampleRate; |
| 1415 | desc.format = mFormat; |
| 1416 | desc.frameCount = mNormalFrameCount; // FIXME see |
| 1417 | // AudioFlinger::frameCount(audio_io_handle_t) |
| 1418 | desc.latency = latency(); |
| 1419 | param2 = &desc; |
| 1420 | break; |
| 1421 | |
| 1422 | case AudioSystem::STREAM_CONFIG_CHANGED: |
| 1423 | param2 = ¶m; |
| 1424 | case AudioSystem::OUTPUT_CLOSED: |
| 1425 | default: |
| 1426 | break; |
| 1427 | } |
| 1428 | mAudioFlinger->audioConfigChanged_l(event, mId, param2); |
| 1429 | } |
| 1430 | |
| 1431 | void AudioFlinger::PlaybackThread::readOutputParameters() |
| 1432 | { |
| 1433 | mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common); |
| 1434 | mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common); |
| 1435 | mChannelCount = (uint16_t)popcount(mChannelMask); |
| 1436 | mFormat = mOutput->stream->common.get_format(&mOutput->stream->common); |
| 1437 | mFrameSize = audio_stream_frame_size(&mOutput->stream->common); |
| 1438 | mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize; |
| 1439 | if (mFrameCount & 15) { |
| 1440 | ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames", |
| 1441 | mFrameCount); |
| 1442 | } |
| 1443 | |
| 1444 | // Calculate size of normal mix buffer relative to the HAL output buffer size |
| 1445 | double multiplier = 1.0; |
| 1446 | if (mType == MIXER && (kUseFastMixer == FastMixer_Static || |
| 1447 | kUseFastMixer == FastMixer_Dynamic)) { |
| 1448 | size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000; |
| 1449 | size_t maxNormalFrameCount = (kMaxNormalMixBufferSizeMs * mSampleRate) / 1000; |
| 1450 | // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer |
| 1451 | minNormalFrameCount = (minNormalFrameCount + 15) & ~15; |
| 1452 | maxNormalFrameCount = maxNormalFrameCount & ~15; |
| 1453 | if (maxNormalFrameCount < minNormalFrameCount) { |
| 1454 | maxNormalFrameCount = minNormalFrameCount; |
| 1455 | } |
| 1456 | multiplier = (double) minNormalFrameCount / (double) mFrameCount; |
| 1457 | if (multiplier <= 1.0) { |
| 1458 | multiplier = 1.0; |
| 1459 | } else if (multiplier <= 2.0) { |
| 1460 | if (2 * mFrameCount <= maxNormalFrameCount) { |
| 1461 | multiplier = 2.0; |
| 1462 | } else { |
| 1463 | multiplier = (double) maxNormalFrameCount / (double) mFrameCount; |
| 1464 | } |
| 1465 | } else { |
| 1466 | // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL |
| 1467 | // SRC (it would be unusual for the normal mix buffer size to not be a multiple of fast |
| 1468 | // track, but we sometimes have to do this to satisfy the maximum frame count |
| 1469 | // constraint) |
| 1470 | // FIXME this rounding up should not be done if no HAL SRC |
| 1471 | uint32_t truncMult = (uint32_t) multiplier; |
| 1472 | if ((truncMult & 1)) { |
| 1473 | if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) { |
| 1474 | ++truncMult; |
| 1475 | } |
| 1476 | } |
| 1477 | multiplier = (double) truncMult; |
| 1478 | } |
| 1479 | } |
| 1480 | mNormalFrameCount = multiplier * mFrameCount; |
| 1481 | // round up to nearest 16 frames to satisfy AudioMixer |
| 1482 | mNormalFrameCount = (mNormalFrameCount + 15) & ~15; |
| 1483 | ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount, |
| 1484 | mNormalFrameCount); |
| 1485 | |
| 1486 | delete[] mMixBuffer; |
| 1487 | mMixBuffer = new int16_t[mNormalFrameCount * mChannelCount]; |
| 1488 | memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t)); |
| 1489 | |
| 1490 | // force reconfiguration of effect chains and engines to take new buffer size and audio |
| 1491 | // parameters into account |
| 1492 | // Note that mLock is not held when readOutputParameters() is called from the constructor |
| 1493 | // but in this case nothing is done below as no audio sessions have effect yet so it doesn't |
| 1494 | // matter. |
| 1495 | // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains |
| 1496 | Vector< sp<EffectChain> > effectChains = mEffectChains; |
| 1497 | for (size_t i = 0; i < effectChains.size(); i ++) { |
| 1498 | mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false); |
| 1499 | } |
| 1500 | } |
| 1501 | |
| 1502 | |
| 1503 | status_t AudioFlinger::PlaybackThread::getRenderPosition(size_t *halFrames, size_t *dspFrames) |
| 1504 | { |
| 1505 | if (halFrames == NULL || dspFrames == NULL) { |
| 1506 | return BAD_VALUE; |
| 1507 | } |
| 1508 | Mutex::Autolock _l(mLock); |
| 1509 | if (initCheck() != NO_ERROR) { |
| 1510 | return INVALID_OPERATION; |
| 1511 | } |
| 1512 | size_t framesWritten = mBytesWritten / mFrameSize; |
| 1513 | *halFrames = framesWritten; |
| 1514 | |
| 1515 | if (isSuspended()) { |
| 1516 | // return an estimation of rendered frames when the output is suspended |
| 1517 | size_t latencyFrames = (latency_l() * mSampleRate) / 1000; |
| 1518 | *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0; |
| 1519 | return NO_ERROR; |
| 1520 | } else { |
| 1521 | return mOutput->stream->get_render_position(mOutput->stream, dspFrames); |
| 1522 | } |
| 1523 | } |
| 1524 | |
| 1525 | uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const |
| 1526 | { |
| 1527 | Mutex::Autolock _l(mLock); |
| 1528 | uint32_t result = 0; |
| 1529 | if (getEffectChain_l(sessionId) != 0) { |
| 1530 | result = EFFECT_SESSION; |
| 1531 | } |
| 1532 | |
| 1533 | for (size_t i = 0; i < mTracks.size(); ++i) { |
| 1534 | sp<Track> track = mTracks[i]; |
Glenn Kasten | 5736c35 | 2012-12-04 12:12:34 -0800 | [diff] [blame] | 1535 | if (sessionId == track->sessionId() && !track->isInvalid()) { |
Eric Laurent | 81784c3 | 2012-11-19 14:55:58 -0800 | [diff] [blame] | 1536 | result |= TRACK_SESSION; |
| 1537 | break; |
| 1538 | } |
| 1539 | } |
| 1540 | |
| 1541 | return result; |
| 1542 | } |
| 1543 | |
| 1544 | uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId) |
| 1545 | { |
| 1546 | // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that |
| 1547 | // it is moved to correct output by audio policy manager when A2DP is connected or disconnected |
| 1548 | if (sessionId == AUDIO_SESSION_OUTPUT_MIX) { |
| 1549 | return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC); |
| 1550 | } |
| 1551 | for (size_t i = 0; i < mTracks.size(); i++) { |
| 1552 | sp<Track> track = mTracks[i]; |
Glenn Kasten | 5736c35 | 2012-12-04 12:12:34 -0800 | [diff] [blame] | 1553 | if (sessionId == track->sessionId() && !track->isInvalid()) { |
Eric Laurent | 81784c3 | 2012-11-19 14:55:58 -0800 | [diff] [blame] | 1554 | return AudioSystem::getStrategyForStream(track->streamType()); |
| 1555 | } |
| 1556 | } |
| 1557 | return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC); |
| 1558 | } |
| 1559 | |
| 1560 | |
| 1561 | AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const |
| 1562 | { |
| 1563 | Mutex::Autolock _l(mLock); |
| 1564 | return mOutput; |
| 1565 | } |
| 1566 | |
| 1567 | AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput() |
| 1568 | { |
| 1569 | Mutex::Autolock _l(mLock); |
| 1570 | AudioStreamOut *output = mOutput; |
| 1571 | mOutput = NULL; |
| 1572 | // FIXME FastMixer might also have a raw ptr to mOutputSink; |
| 1573 | // must push a NULL and wait for ack |
| 1574 | mOutputSink.clear(); |
| 1575 | mPipeSink.clear(); |
| 1576 | mNormalSink.clear(); |
| 1577 | return output; |
| 1578 | } |
| 1579 | |
| 1580 | // this method must always be called either with ThreadBase mLock held or inside the thread loop |
| 1581 | audio_stream_t* AudioFlinger::PlaybackThread::stream() const |
| 1582 | { |
| 1583 | if (mOutput == NULL) { |
| 1584 | return NULL; |
| 1585 | } |
| 1586 | return &mOutput->stream->common; |
| 1587 | } |
| 1588 | |
| 1589 | uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const |
| 1590 | { |
| 1591 | return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000); |
| 1592 | } |
| 1593 | |
| 1594 | status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event) |
| 1595 | { |
| 1596 | if (!isValidSyncEvent(event)) { |
| 1597 | return BAD_VALUE; |
| 1598 | } |
| 1599 | |
| 1600 | Mutex::Autolock _l(mLock); |
| 1601 | |
| 1602 | for (size_t i = 0; i < mTracks.size(); ++i) { |
| 1603 | sp<Track> track = mTracks[i]; |
| 1604 | if (event->triggerSession() == track->sessionId()) { |
| 1605 | (void) track->setSyncEvent(event); |
| 1606 | return NO_ERROR; |
| 1607 | } |
| 1608 | } |
| 1609 | |
| 1610 | return NAME_NOT_FOUND; |
| 1611 | } |
| 1612 | |
| 1613 | bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const |
| 1614 | { |
| 1615 | return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE; |
| 1616 | } |
| 1617 | |
| 1618 | void AudioFlinger::PlaybackThread::threadLoop_removeTracks( |
| 1619 | const Vector< sp<Track> >& tracksToRemove) |
| 1620 | { |
| 1621 | size_t count = tracksToRemove.size(); |
| 1622 | if (CC_UNLIKELY(count)) { |
| 1623 | for (size_t i = 0 ; i < count ; i++) { |
| 1624 | const sp<Track>& track = tracksToRemove.itemAt(i); |
| 1625 | if ((track->sharedBuffer() != 0) && |
| 1626 | (track->mState == TrackBase::ACTIVE || track->mState == TrackBase::RESUMING)) { |
| 1627 | AudioSystem::stopOutput(mId, track->streamType(), track->sessionId()); |
| 1628 | } |
| 1629 | } |
| 1630 | } |
| 1631 | |
| 1632 | } |
| 1633 | |
| 1634 | void AudioFlinger::PlaybackThread::checkSilentMode_l() |
| 1635 | { |
| 1636 | if (!mMasterMute) { |
| 1637 | char value[PROPERTY_VALUE_MAX]; |
| 1638 | if (property_get("ro.audio.silent", value, "0") > 0) { |
| 1639 | char *endptr; |
| 1640 | unsigned long ul = strtoul(value, &endptr, 0); |
| 1641 | if (*endptr == '\0' && ul != 0) { |
| 1642 | ALOGD("Silence is golden"); |
| 1643 | // The setprop command will not allow a property to be changed after |
| 1644 | // the first time it is set, so we don't have to worry about un-muting. |
| 1645 | setMasterMute_l(true); |
| 1646 | } |
| 1647 | } |
| 1648 | } |
| 1649 | } |
| 1650 | |
| 1651 | // shared by MIXER and DIRECT, overridden by DUPLICATING |
| 1652 | void AudioFlinger::PlaybackThread::threadLoop_write() |
| 1653 | { |
| 1654 | // FIXME rewrite to reduce number of system calls |
| 1655 | mLastWriteTime = systemTime(); |
| 1656 | mInWrite = true; |
| 1657 | int bytesWritten; |
| 1658 | |
| 1659 | // If an NBAIO sink is present, use it to write the normal mixer's submix |
| 1660 | if (mNormalSink != 0) { |
| 1661 | #define mBitShift 2 // FIXME |
| 1662 | size_t count = mixBufferSize >> mBitShift; |
Simon Wilson | 2d59096 | 2012-11-29 15:18:50 -0800 | [diff] [blame] | 1663 | ATRACE_BEGIN("write"); |
Eric Laurent | 81784c3 | 2012-11-19 14:55:58 -0800 | [diff] [blame] | 1664 | // update the setpoint when AudioFlinger::mScreenState changes |
| 1665 | uint32_t screenState = AudioFlinger::mScreenState; |
| 1666 | if (screenState != mScreenState) { |
| 1667 | mScreenState = screenState; |
| 1668 | MonoPipe *pipe = (MonoPipe *)mPipeSink.get(); |
| 1669 | if (pipe != NULL) { |
| 1670 | pipe->setAvgFrames((mScreenState & 1) ? |
| 1671 | (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2); |
| 1672 | } |
| 1673 | } |
| 1674 | ssize_t framesWritten = mNormalSink->write(mMixBuffer, count); |
Simon Wilson | 2d59096 | 2012-11-29 15:18:50 -0800 | [diff] [blame] | 1675 | ATRACE_END(); |
Eric Laurent | 81784c3 | 2012-11-19 14:55:58 -0800 | [diff] [blame] | 1676 | if (framesWritten > 0) { |
| 1677 | bytesWritten = framesWritten << mBitShift; |
| 1678 | } else { |
| 1679 | bytesWritten = framesWritten; |
| 1680 | } |
| 1681 | // otherwise use the HAL / AudioStreamOut directly |
| 1682 | } else { |
| 1683 | // Direct output thread. |
| 1684 | bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize); |
| 1685 | } |
| 1686 | |
| 1687 | if (bytesWritten > 0) { |
| 1688 | mBytesWritten += mixBufferSize; |
| 1689 | } |
| 1690 | mNumWrites++; |
| 1691 | mInWrite = false; |
| 1692 | } |
| 1693 | |
| 1694 | /* |
| 1695 | The derived values that are cached: |
| 1696 | - mixBufferSize from frame count * frame size |
| 1697 | - activeSleepTime from activeSleepTimeUs() |
| 1698 | - idleSleepTime from idleSleepTimeUs() |
| 1699 | - standbyDelay from mActiveSleepTimeUs (DIRECT only) |
| 1700 | - maxPeriod from frame count and sample rate (MIXER only) |
| 1701 | |
| 1702 | The parameters that affect these derived values are: |
| 1703 | - frame count |
| 1704 | - frame size |
| 1705 | - sample rate |
| 1706 | - device type: A2DP or not |
| 1707 | - device latency |
| 1708 | - format: PCM or not |
| 1709 | - active sleep time |
| 1710 | - idle sleep time |
| 1711 | */ |
| 1712 | |
| 1713 | void AudioFlinger::PlaybackThread::cacheParameters_l() |
| 1714 | { |
| 1715 | mixBufferSize = mNormalFrameCount * mFrameSize; |
| 1716 | activeSleepTime = activeSleepTimeUs(); |
| 1717 | idleSleepTime = idleSleepTimeUs(); |
| 1718 | } |
| 1719 | |
| 1720 | void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType) |
| 1721 | { |
Glenn Kasten | 7c02724 | 2012-12-26 14:43:16 -0800 | [diff] [blame] | 1722 | ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d", |
Eric Laurent | 81784c3 | 2012-11-19 14:55:58 -0800 | [diff] [blame] | 1723 | this, streamType, mTracks.size()); |
| 1724 | Mutex::Autolock _l(mLock); |
| 1725 | |
| 1726 | size_t size = mTracks.size(); |
| 1727 | for (size_t i = 0; i < size; i++) { |
| 1728 | sp<Track> t = mTracks[i]; |
| 1729 | if (t->streamType() == streamType) { |
Glenn Kasten | 5736c35 | 2012-12-04 12:12:34 -0800 | [diff] [blame] | 1730 | t->invalidate(); |
Eric Laurent | 81784c3 | 2012-11-19 14:55:58 -0800 | [diff] [blame] | 1731 | } |
| 1732 | } |
| 1733 | } |
| 1734 | |
| 1735 | status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain) |
| 1736 | { |
| 1737 | int session = chain->sessionId(); |
| 1738 | int16_t *buffer = mMixBuffer; |
| 1739 | bool ownsBuffer = false; |
| 1740 | |
| 1741 | ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session); |
| 1742 | if (session > 0) { |
| 1743 | // Only one effect chain can be present in direct output thread and it uses |
| 1744 | // the mix buffer as input |
| 1745 | if (mType != DIRECT) { |
| 1746 | size_t numSamples = mNormalFrameCount * mChannelCount; |
| 1747 | buffer = new int16_t[numSamples]; |
| 1748 | memset(buffer, 0, numSamples * sizeof(int16_t)); |
| 1749 | ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session); |
| 1750 | ownsBuffer = true; |
| 1751 | } |
| 1752 | |
| 1753 | // Attach all tracks with same session ID to this chain. |
| 1754 | for (size_t i = 0; i < mTracks.size(); ++i) { |
| 1755 | sp<Track> track = mTracks[i]; |
| 1756 | if (session == track->sessionId()) { |
| 1757 | ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), |
| 1758 | buffer); |
| 1759 | track->setMainBuffer(buffer); |
| 1760 | chain->incTrackCnt(); |
| 1761 | } |
| 1762 | } |
| 1763 | |
| 1764 | // indicate all active tracks in the chain |
| 1765 | for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) { |
| 1766 | sp<Track> track = mActiveTracks[i].promote(); |
| 1767 | if (track == 0) { |
| 1768 | continue; |
| 1769 | } |
| 1770 | if (session == track->sessionId()) { |
| 1771 | ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session); |
| 1772 | chain->incActiveTrackCnt(); |
| 1773 | } |
| 1774 | } |
| 1775 | } |
| 1776 | |
| 1777 | chain->setInBuffer(buffer, ownsBuffer); |
| 1778 | chain->setOutBuffer(mMixBuffer); |
| 1779 | // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect |
| 1780 | // chains list in order to be processed last as it contains output stage effects |
| 1781 | // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before |
| 1782 | // session AUDIO_SESSION_OUTPUT_STAGE to be processed |
| 1783 | // after track specific effects and before output stage |
| 1784 | // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and |
| 1785 | // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX |
| 1786 | // Effect chain for other sessions are inserted at beginning of effect |
| 1787 | // chains list to be processed before output mix effects. Relative order between other |
| 1788 | // sessions is not important |
| 1789 | size_t size = mEffectChains.size(); |
| 1790 | size_t i = 0; |
| 1791 | for (i = 0; i < size; i++) { |
| 1792 | if (mEffectChains[i]->sessionId() < session) { |
| 1793 | break; |
| 1794 | } |
| 1795 | } |
| 1796 | mEffectChains.insertAt(chain, i); |
| 1797 | checkSuspendOnAddEffectChain_l(chain); |
| 1798 | |
| 1799 | return NO_ERROR; |
| 1800 | } |
| 1801 | |
| 1802 | size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain) |
| 1803 | { |
| 1804 | int session = chain->sessionId(); |
| 1805 | |
| 1806 | ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session); |
| 1807 | |
| 1808 | for (size_t i = 0; i < mEffectChains.size(); i++) { |
| 1809 | if (chain == mEffectChains[i]) { |
| 1810 | mEffectChains.removeAt(i); |
| 1811 | // detach all active tracks from the chain |
| 1812 | for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) { |
| 1813 | sp<Track> track = mActiveTracks[i].promote(); |
| 1814 | if (track == 0) { |
| 1815 | continue; |
| 1816 | } |
| 1817 | if (session == track->sessionId()) { |
| 1818 | ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d", |
| 1819 | chain.get(), session); |
| 1820 | chain->decActiveTrackCnt(); |
| 1821 | } |
| 1822 | } |
| 1823 | |
| 1824 | // detach all tracks with same session ID from this chain |
| 1825 | for (size_t i = 0; i < mTracks.size(); ++i) { |
| 1826 | sp<Track> track = mTracks[i]; |
| 1827 | if (session == track->sessionId()) { |
| 1828 | track->setMainBuffer(mMixBuffer); |
| 1829 | chain->decTrackCnt(); |
| 1830 | } |
| 1831 | } |
| 1832 | break; |
| 1833 | } |
| 1834 | } |
| 1835 | return mEffectChains.size(); |
| 1836 | } |
| 1837 | |
| 1838 | status_t AudioFlinger::PlaybackThread::attachAuxEffect( |
| 1839 | const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId) |
| 1840 | { |
| 1841 | Mutex::Autolock _l(mLock); |
| 1842 | return attachAuxEffect_l(track, EffectId); |
| 1843 | } |
| 1844 | |
| 1845 | status_t AudioFlinger::PlaybackThread::attachAuxEffect_l( |
| 1846 | const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId) |
| 1847 | { |
| 1848 | status_t status = NO_ERROR; |
| 1849 | |
| 1850 | if (EffectId == 0) { |
| 1851 | track->setAuxBuffer(0, NULL); |
| 1852 | } else { |
| 1853 | // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX |
| 1854 | sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId); |
| 1855 | if (effect != 0) { |
| 1856 | if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { |
| 1857 | track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer()); |
| 1858 | } else { |
| 1859 | status = INVALID_OPERATION; |
| 1860 | } |
| 1861 | } else { |
| 1862 | status = BAD_VALUE; |
| 1863 | } |
| 1864 | } |
| 1865 | return status; |
| 1866 | } |
| 1867 | |
| 1868 | void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId) |
| 1869 | { |
| 1870 | for (size_t i = 0; i < mTracks.size(); ++i) { |
| 1871 | sp<Track> track = mTracks[i]; |
| 1872 | if (track->auxEffectId() == effectId) { |
| 1873 | attachAuxEffect_l(track, 0); |
| 1874 | } |
| 1875 | } |
| 1876 | } |
| 1877 | |
| 1878 | bool AudioFlinger::PlaybackThread::threadLoop() |
| 1879 | { |
| 1880 | Vector< sp<Track> > tracksToRemove; |
| 1881 | |
| 1882 | standbyTime = systemTime(); |
| 1883 | |
| 1884 | // MIXER |
| 1885 | nsecs_t lastWarning = 0; |
| 1886 | |
| 1887 | // DUPLICATING |
| 1888 | // FIXME could this be made local to while loop? |
| 1889 | writeFrames = 0; |
| 1890 | |
| 1891 | cacheParameters_l(); |
| 1892 | sleepTime = idleSleepTime; |
| 1893 | |
| 1894 | if (mType == MIXER) { |
| 1895 | sleepTimeShift = 0; |
| 1896 | } |
| 1897 | |
| 1898 | CpuStats cpuStats; |
| 1899 | const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid())); |
| 1900 | |
| 1901 | acquireWakeLock(); |
| 1902 | |
Glenn Kasten | 9e58b55 | 2013-01-18 15:09:48 -0800 | [diff] [blame] | 1903 | // mNBLogWriter->log can only be called while thread mutex mLock is held. |
| 1904 | // So if you need to log when mutex is unlocked, set logString to a non-NULL string, |
| 1905 | // and then that string will be logged at the next convenient opportunity. |
| 1906 | const char *logString = NULL; |
| 1907 | |
Eric Laurent | 81784c3 | 2012-11-19 14:55:58 -0800 | [diff] [blame] | 1908 | while (!exitPending()) |
| 1909 | { |
| 1910 | cpuStats.sample(myName); |
| 1911 | |
| 1912 | Vector< sp<EffectChain> > effectChains; |
| 1913 | |
| 1914 | processConfigEvents(); |
| 1915 | |
| 1916 | { // scope for mLock |
| 1917 | |
| 1918 | Mutex::Autolock _l(mLock); |
| 1919 | |
Glenn Kasten | 9e58b55 | 2013-01-18 15:09:48 -0800 | [diff] [blame] | 1920 | if (logString != NULL) { |
| 1921 | mNBLogWriter->logTimestamp(); |
| 1922 | mNBLogWriter->log(logString); |
| 1923 | logString = NULL; |
| 1924 | } |
| 1925 | |
Eric Laurent | 81784c3 | 2012-11-19 14:55:58 -0800 | [diff] [blame] | 1926 | if (checkForNewParameters_l()) { |
| 1927 | cacheParameters_l(); |
| 1928 | } |
| 1929 | |
| 1930 | saveOutputTracks(); |
| 1931 | |
| 1932 | // put audio hardware into standby after short delay |
| 1933 | if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) || |
| 1934 | isSuspended())) { |
| 1935 | if (!mStandby) { |
| 1936 | |
| 1937 | threadLoop_standby(); |
| 1938 | |
| 1939 | mStandby = true; |
| 1940 | } |
| 1941 | |
| 1942 | if (!mActiveTracks.size() && mConfigEvents.isEmpty()) { |
| 1943 | // we're about to wait, flush the binder command buffer |
| 1944 | IPCThreadState::self()->flushCommands(); |
| 1945 | |
| 1946 | clearOutputTracks(); |
| 1947 | |
| 1948 | if (exitPending()) { |
| 1949 | break; |
| 1950 | } |
| 1951 | |
| 1952 | releaseWakeLock_l(); |
| 1953 | // wait until we have something to do... |
| 1954 | ALOGV("%s going to sleep", myName.string()); |
| 1955 | mWaitWorkCV.wait(mLock); |
| 1956 | ALOGV("%s waking up", myName.string()); |
| 1957 | acquireWakeLock_l(); |
| 1958 | |
| 1959 | mMixerStatus = MIXER_IDLE; |
| 1960 | mMixerStatusIgnoringFastTracks = MIXER_IDLE; |
| 1961 | mBytesWritten = 0; |
| 1962 | |
| 1963 | checkSilentMode_l(); |
| 1964 | |
| 1965 | standbyTime = systemTime() + standbyDelay; |
| 1966 | sleepTime = idleSleepTime; |
| 1967 | if (mType == MIXER) { |
| 1968 | sleepTimeShift = 0; |
| 1969 | } |
| 1970 | |
| 1971 | continue; |
| 1972 | } |
| 1973 | } |
| 1974 | |
| 1975 | // mMixerStatusIgnoringFastTracks is also updated internally |
| 1976 | mMixerStatus = prepareTracks_l(&tracksToRemove); |
| 1977 | |
| 1978 | // prevent any changes in effect chain list and in each effect chain |
| 1979 | // during mixing and effect process as the audio buffers could be deleted |
| 1980 | // or modified if an effect is created or deleted |
| 1981 | lockEffectChains_l(effectChains); |
| 1982 | } |
| 1983 | |
| 1984 | if (CC_LIKELY(mMixerStatus == MIXER_TRACKS_READY)) { |
| 1985 | threadLoop_mix(); |
| 1986 | } else { |
| 1987 | threadLoop_sleepTime(); |
| 1988 | } |
| 1989 | |
| 1990 | if (isSuspended()) { |
| 1991 | sleepTime = suspendSleepTimeUs(); |
| 1992 | mBytesWritten += mixBufferSize; |
| 1993 | } |
| 1994 | |
| 1995 | // only process effects if we're going to write |
| 1996 | if (sleepTime == 0) { |
| 1997 | for (size_t i = 0; i < effectChains.size(); i ++) { |
| 1998 | effectChains[i]->process_l(); |
| 1999 | } |
| 2000 | } |
| 2001 | |
| 2002 | // enable changes in effect chain |
| 2003 | unlockEffectChains(effectChains); |
| 2004 | |
| 2005 | // sleepTime == 0 means we must write to audio hardware |
| 2006 | if (sleepTime == 0) { |
| 2007 | |
| 2008 | threadLoop_write(); |
| 2009 | |
| 2010 | if (mType == MIXER) { |
| 2011 | // write blocked detection |
| 2012 | nsecs_t now = systemTime(); |
| 2013 | nsecs_t delta = now - mLastWriteTime; |
| 2014 | if (!mStandby && delta > maxPeriod) { |
| 2015 | mNumDelayedWrites++; |
| 2016 | if ((now - lastWarning) > kWarningThrottleNs) { |
Alex Ray | 371eb97 | 2012-11-30 11:11:54 -0800 | [diff] [blame] | 2017 | ATRACE_NAME("underrun"); |
Eric Laurent | 81784c3 | 2012-11-19 14:55:58 -0800 | [diff] [blame] | 2018 | ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p", |
| 2019 | ns2ms(delta), mNumDelayedWrites, this); |
| 2020 | lastWarning = now; |
| 2021 | } |
| 2022 | } |
| 2023 | } |
| 2024 | |
| 2025 | mStandby = false; |
| 2026 | } else { |
| 2027 | usleep(sleepTime); |
| 2028 | } |
| 2029 | |
| 2030 | // Finally let go of removed track(s), without the lock held |
| 2031 | // since we can't guarantee the destructors won't acquire that |
| 2032 | // same lock. This will also mutate and push a new fast mixer state. |
| 2033 | threadLoop_removeTracks(tracksToRemove); |
| 2034 | tracksToRemove.clear(); |
| 2035 | |
| 2036 | // FIXME I don't understand the need for this here; |
| 2037 | // it was in the original code but maybe the |
| 2038 | // assignment in saveOutputTracks() makes this unnecessary? |
| 2039 | clearOutputTracks(); |
| 2040 | |
| 2041 | // Effect chains will be actually deleted here if they were removed from |
| 2042 | // mEffectChains list during mixing or effects processing |
| 2043 | effectChains.clear(); |
| 2044 | |
| 2045 | // FIXME Note that the above .clear() is no longer necessary since effectChains |
| 2046 | // is now local to this block, but will keep it for now (at least until merge done). |
| 2047 | } |
| 2048 | |
| 2049 | // for DuplicatingThread, standby mode is handled by the outputTracks, otherwise ... |
| 2050 | if (mType == MIXER || mType == DIRECT) { |
| 2051 | // put output stream into standby mode |
| 2052 | if (!mStandby) { |
| 2053 | mOutput->stream->common.standby(&mOutput->stream->common); |
| 2054 | } |
| 2055 | } |
| 2056 | |
| 2057 | releaseWakeLock(); |
| 2058 | |
| 2059 | ALOGV("Thread %p type %d exiting", this, mType); |
| 2060 | return false; |
| 2061 | } |
| 2062 | |
| 2063 | |
| 2064 | // ---------------------------------------------------------------------------- |
| 2065 | |
| 2066 | AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, |
| 2067 | audio_io_handle_t id, audio_devices_t device, type_t type) |
| 2068 | : PlaybackThread(audioFlinger, output, id, device, type), |
| 2069 | // mAudioMixer below |
| 2070 | // mFastMixer below |
| 2071 | mFastMixerFutex(0) |
| 2072 | // mOutputSink below |
| 2073 | // mPipeSink below |
| 2074 | // mNormalSink below |
| 2075 | { |
| 2076 | ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type); |
| 2077 | ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%d, mFormat=%d, mFrameSize=%u, " |
| 2078 | "mFrameCount=%d, mNormalFrameCount=%d", |
| 2079 | mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount, |
| 2080 | mNormalFrameCount); |
| 2081 | mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate); |
| 2082 | |
| 2083 | // FIXME - Current mixer implementation only supports stereo output |
| 2084 | if (mChannelCount != FCC_2) { |
| 2085 | ALOGE("Invalid audio hardware channel count %d", mChannelCount); |
| 2086 | } |
| 2087 | |
| 2088 | // create an NBAIO sink for the HAL output stream, and negotiate |
| 2089 | mOutputSink = new AudioStreamOutSink(output->stream); |
| 2090 | size_t numCounterOffers = 0; |
| 2091 | const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)}; |
| 2092 | ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers); |
| 2093 | ALOG_ASSERT(index == 0); |
| 2094 | |
| 2095 | // initialize fast mixer depending on configuration |
| 2096 | bool initFastMixer; |
| 2097 | switch (kUseFastMixer) { |
| 2098 | case FastMixer_Never: |
| 2099 | initFastMixer = false; |
| 2100 | break; |
| 2101 | case FastMixer_Always: |
| 2102 | initFastMixer = true; |
| 2103 | break; |
| 2104 | case FastMixer_Static: |
| 2105 | case FastMixer_Dynamic: |
| 2106 | initFastMixer = mFrameCount < mNormalFrameCount; |
| 2107 | break; |
| 2108 | } |
| 2109 | if (initFastMixer) { |
| 2110 | |
| 2111 | // create a MonoPipe to connect our submix to FastMixer |
| 2112 | NBAIO_Format format = mOutputSink->format(); |
| 2113 | // This pipe depth compensates for scheduling latency of the normal mixer thread. |
| 2114 | // When it wakes up after a maximum latency, it runs a few cycles quickly before |
| 2115 | // finally blocking. Note the pipe implementation rounds up the request to a power of 2. |
| 2116 | MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/); |
| 2117 | const NBAIO_Format offers[1] = {format}; |
| 2118 | size_t numCounterOffers = 0; |
| 2119 | ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers); |
| 2120 | ALOG_ASSERT(index == 0); |
| 2121 | monoPipe->setAvgFrames((mScreenState & 1) ? |
| 2122 | (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2); |
| 2123 | mPipeSink = monoPipe; |
| 2124 | |
Glenn Kasten | 46909e7 | 2013-02-26 09:20:22 -0800 | [diff] [blame] | 2125 | #ifdef TEE_SINK |
Glenn Kasten | da6ef13 | 2013-01-10 12:31:01 -0800 | [diff] [blame] | 2126 | if (mTeeSinkOutputEnabled) { |
| 2127 | // create a Pipe to archive a copy of FastMixer's output for dumpsys |
| 2128 | Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, format); |
| 2129 | numCounterOffers = 0; |
| 2130 | index = teeSink->negotiate(offers, 1, NULL, numCounterOffers); |
| 2131 | ALOG_ASSERT(index == 0); |
| 2132 | mTeeSink = teeSink; |
| 2133 | PipeReader *teeSource = new PipeReader(*teeSink); |
| 2134 | numCounterOffers = 0; |
| 2135 | index = teeSource->negotiate(offers, 1, NULL, numCounterOffers); |
| 2136 | ALOG_ASSERT(index == 0); |
| 2137 | mTeeSource = teeSource; |
| 2138 | } |
Glenn Kasten | 46909e7 | 2013-02-26 09:20:22 -0800 | [diff] [blame] | 2139 | #endif |
Eric Laurent | 81784c3 | 2012-11-19 14:55:58 -0800 | [diff] [blame] | 2140 | |
| 2141 | // create fast mixer and configure it initially with just one fast track for our submix |
| 2142 | mFastMixer = new FastMixer(); |
| 2143 | FastMixerStateQueue *sq = mFastMixer->sq(); |
| 2144 | #ifdef STATE_QUEUE_DUMP |
| 2145 | sq->setObserverDump(&mStateQueueObserverDump); |
| 2146 | sq->setMutatorDump(&mStateQueueMutatorDump); |
| 2147 | #endif |
| 2148 | FastMixerState *state = sq->begin(); |
| 2149 | FastTrack *fastTrack = &state->mFastTracks[0]; |
| 2150 | // wrap the source side of the MonoPipe to make it an AudioBufferProvider |
| 2151 | fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe)); |
| 2152 | fastTrack->mVolumeProvider = NULL; |
| 2153 | fastTrack->mGeneration++; |
| 2154 | state->mFastTracksGen++; |
| 2155 | state->mTrackMask = 1; |
| 2156 | // fast mixer will use the HAL output sink |
| 2157 | state->mOutputSink = mOutputSink.get(); |
| 2158 | state->mOutputSinkGen++; |
| 2159 | state->mFrameCount = mFrameCount; |
| 2160 | state->mCommand = FastMixerState::COLD_IDLE; |
| 2161 | // already done in constructor initialization list |
| 2162 | //mFastMixerFutex = 0; |
| 2163 | state->mColdFutexAddr = &mFastMixerFutex; |
| 2164 | state->mColdGen++; |
| 2165 | state->mDumpState = &mFastMixerDumpState; |
Glenn Kasten | 46909e7 | 2013-02-26 09:20:22 -0800 | [diff] [blame] | 2166 | #ifdef TEE_SINK |
Eric Laurent | 81784c3 | 2012-11-19 14:55:58 -0800 | [diff] [blame] | 2167 | state->mTeeSink = mTeeSink.get(); |
Glenn Kasten | 46909e7 | 2013-02-26 09:20:22 -0800 | [diff] [blame] | 2168 | #endif |
Glenn Kasten | 9e58b55 | 2013-01-18 15:09:48 -0800 | [diff] [blame] | 2169 | mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer"); |
| 2170 | state->mNBLogWriter = mFastMixerNBLogWriter.get(); |
Eric Laurent | 81784c3 | 2012-11-19 14:55:58 -0800 | [diff] [blame] | 2171 | sq->end(); |
| 2172 | sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED); |
| 2173 | |
| 2174 | // start the fast mixer |
| 2175 | mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO); |
| 2176 | pid_t tid = mFastMixer->getTid(); |
| 2177 | int err = requestPriority(getpid_cached, tid, kPriorityFastMixer); |
| 2178 | if (err != 0) { |
| 2179 | ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d", |
| 2180 | kPriorityFastMixer, getpid_cached, tid, err); |
| 2181 | } |
| 2182 | |
| 2183 | #ifdef AUDIO_WATCHDOG |
| 2184 | // create and start the watchdog |
| 2185 | mAudioWatchdog = new AudioWatchdog(); |
| 2186 | mAudioWatchdog->setDump(&mAudioWatchdogDump); |
| 2187 | mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO); |
| 2188 | tid = mAudioWatchdog->getTid(); |
| 2189 | err = requestPriority(getpid_cached, tid, kPriorityFastMixer); |
| 2190 | if (err != 0) { |
| 2191 | ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d", |
| 2192 | kPriorityFastMixer, getpid_cached, tid, err); |
| 2193 | } |
| 2194 | #endif |
| 2195 | |
| 2196 | } else { |
| 2197 | mFastMixer = NULL; |
| 2198 | } |
| 2199 | |
| 2200 | switch (kUseFastMixer) { |
| 2201 | case FastMixer_Never: |
| 2202 | case FastMixer_Dynamic: |
| 2203 | mNormalSink = mOutputSink; |
| 2204 | break; |
| 2205 | case FastMixer_Always: |
| 2206 | mNormalSink = mPipeSink; |
| 2207 | break; |
| 2208 | case FastMixer_Static: |
| 2209 | mNormalSink = initFastMixer ? mPipeSink : mOutputSink; |
| 2210 | break; |
| 2211 | } |
| 2212 | } |
| 2213 | |
| 2214 | AudioFlinger::MixerThread::~MixerThread() |
| 2215 | { |
| 2216 | if (mFastMixer != NULL) { |
| 2217 | FastMixerStateQueue *sq = mFastMixer->sq(); |
| 2218 | FastMixerState *state = sq->begin(); |
| 2219 | if (state->mCommand == FastMixerState::COLD_IDLE) { |
| 2220 | int32_t old = android_atomic_inc(&mFastMixerFutex); |
| 2221 | if (old == -1) { |
| 2222 | __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1); |
| 2223 | } |
| 2224 | } |
| 2225 | state->mCommand = FastMixerState::EXIT; |
| 2226 | sq->end(); |
| 2227 | sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED); |
| 2228 | mFastMixer->join(); |
| 2229 | // Though the fast mixer thread has exited, it's state queue is still valid. |
| 2230 | // We'll use that extract the final state which contains one remaining fast track |
| 2231 | // corresponding to our sub-mix. |
| 2232 | state = sq->begin(); |
| 2233 | ALOG_ASSERT(state->mTrackMask == 1); |
| 2234 | FastTrack *fastTrack = &state->mFastTracks[0]; |
| 2235 | ALOG_ASSERT(fastTrack->mBufferProvider != NULL); |
| 2236 | delete fastTrack->mBufferProvider; |
| 2237 | sq->end(false /*didModify*/); |
| 2238 | delete mFastMixer; |
| 2239 | #ifdef AUDIO_WATCHDOG |
| 2240 | if (mAudioWatchdog != 0) { |
| 2241 | mAudioWatchdog->requestExit(); |
| 2242 | mAudioWatchdog->requestExitAndWait(); |
| 2243 | mAudioWatchdog.clear(); |
| 2244 | } |
| 2245 | #endif |
| 2246 | } |
Glenn Kasten | 9e58b55 | 2013-01-18 15:09:48 -0800 | [diff] [blame] | 2247 | mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter); |
Eric Laurent | 81784c3 | 2012-11-19 14:55:58 -0800 | [diff] [blame] | 2248 | delete mAudioMixer; |
| 2249 | } |
| 2250 | |
| 2251 | |
| 2252 | uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const |
| 2253 | { |
| 2254 | if (mFastMixer != NULL) { |
| 2255 | MonoPipe *pipe = (MonoPipe *)mPipeSink.get(); |
| 2256 | latency += (pipe->getAvgFrames() * 1000) / mSampleRate; |
| 2257 | } |
| 2258 | return latency; |
| 2259 | } |
| 2260 | |
| 2261 | |
| 2262 | void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove) |
| 2263 | { |
| 2264 | PlaybackThread::threadLoop_removeTracks(tracksToRemove); |
| 2265 | } |
| 2266 | |
| 2267 | void AudioFlinger::MixerThread::threadLoop_write() |
| 2268 | { |
| 2269 | // FIXME we should only do one push per cycle; confirm this is true |
| 2270 | // Start the fast mixer if it's not already running |
| 2271 | if (mFastMixer != NULL) { |
| 2272 | FastMixerStateQueue *sq = mFastMixer->sq(); |
| 2273 | FastMixerState *state = sq->begin(); |
| 2274 | if (state->mCommand != FastMixerState::MIX_WRITE && |
| 2275 | (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) { |
| 2276 | if (state->mCommand == FastMixerState::COLD_IDLE) { |
| 2277 | int32_t old = android_atomic_inc(&mFastMixerFutex); |
| 2278 | if (old == -1) { |
| 2279 | __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1); |
| 2280 | } |
| 2281 | #ifdef AUDIO_WATCHDOG |
| 2282 | if (mAudioWatchdog != 0) { |
| 2283 | mAudioWatchdog->resume(); |
| 2284 | } |
| 2285 | #endif |
| 2286 | } |
| 2287 | state->mCommand = FastMixerState::MIX_WRITE; |
Glenn Kasten | 4182c4e | 2013-07-15 14:45:07 -0700 | [diff] [blame] | 2288 | mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ? |
| 2289 | FastMixerDumpState::kSamplingNforLowRamDevice : FastMixerDumpState::kSamplingN); |
Eric Laurent | 81784c3 | 2012-11-19 14:55:58 -0800 | [diff] [blame] | 2290 | sq->end(); |
| 2291 | sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED); |
| 2292 | if (kUseFastMixer == FastMixer_Dynamic) { |
| 2293 | mNormalSink = mPipeSink; |
| 2294 | } |
| 2295 | } else { |
| 2296 | sq->end(false /*didModify*/); |
| 2297 | } |
| 2298 | } |
| 2299 | PlaybackThread::threadLoop_write(); |
| 2300 | } |
| 2301 | |
| 2302 | void AudioFlinger::MixerThread::threadLoop_standby() |
| 2303 | { |
| 2304 | // Idle the fast mixer if it's currently running |
| 2305 | if (mFastMixer != NULL) { |
| 2306 | FastMixerStateQueue *sq = mFastMixer->sq(); |
| 2307 | FastMixerState *state = sq->begin(); |
| 2308 | if (!(state->mCommand & FastMixerState::IDLE)) { |
| 2309 | state->mCommand = FastMixerState::COLD_IDLE; |
| 2310 | state->mColdFutexAddr = &mFastMixerFutex; |
| 2311 | state->mColdGen++; |
| 2312 | mFastMixerFutex = 0; |
| 2313 | sq->end(); |
| 2314 | // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now |
| 2315 | sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED); |
| 2316 | if (kUseFastMixer == FastMixer_Dynamic) { |
| 2317 | mNormalSink = mOutputSink; |
| 2318 | } |
| 2319 | #ifdef AUDIO_WATCHDOG |
| 2320 | if (mAudioWatchdog != 0) { |
| 2321 | mAudioWatchdog->pause(); |
| 2322 | } |
| 2323 | #endif |
| 2324 | } else { |
| 2325 | sq->end(false /*didModify*/); |
| 2326 | } |
| 2327 | } |
| 2328 | PlaybackThread::threadLoop_standby(); |
| 2329 | } |
| 2330 | |
| 2331 | // shared by MIXER and DIRECT, overridden by DUPLICATING |
| 2332 | void AudioFlinger::PlaybackThread::threadLoop_standby() |
| 2333 | { |
| 2334 | ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended); |
| 2335 | mOutput->stream->common.standby(&mOutput->stream->common); |
| 2336 | } |
| 2337 | |
| 2338 | void AudioFlinger::MixerThread::threadLoop_mix() |
| 2339 | { |
| 2340 | // obtain the presentation timestamp of the next output buffer |
| 2341 | int64_t pts; |
| 2342 | status_t status = INVALID_OPERATION; |
| 2343 | |
| 2344 | if (mNormalSink != 0) { |
| 2345 | status = mNormalSink->getNextWriteTimestamp(&pts); |
| 2346 | } else { |
| 2347 | status = mOutputSink->getNextWriteTimestamp(&pts); |
| 2348 | } |
| 2349 | |
| 2350 | if (status != NO_ERROR) { |
| 2351 | pts = AudioBufferProvider::kInvalidPTS; |
| 2352 | } |
| 2353 | |
| 2354 | // mix buffers... |
| 2355 | mAudioMixer->process(pts); |
| 2356 | // increase sleep time progressively when application underrun condition clears. |
| 2357 | // Only increase sleep time if the mixer is ready for two consecutive times to avoid |
| 2358 | // that a steady state of alternating ready/not ready conditions keeps the sleep time |
| 2359 | // such that we would underrun the audio HAL. |
| 2360 | if ((sleepTime == 0) && (sleepTimeShift > 0)) { |
| 2361 | sleepTimeShift--; |
| 2362 | } |
| 2363 | sleepTime = 0; |
| 2364 | standbyTime = systemTime() + standbyDelay; |
| 2365 | //TODO: delay standby when effects have a tail |
| 2366 | } |
| 2367 | |
| 2368 | void AudioFlinger::MixerThread::threadLoop_sleepTime() |
| 2369 | { |
| 2370 | // If no tracks are ready, sleep once for the duration of an output |
| 2371 | // buffer size, then write 0s to the output |
| 2372 | if (sleepTime == 0) { |
| 2373 | if (mMixerStatus == MIXER_TRACKS_ENABLED) { |
| 2374 | sleepTime = activeSleepTime >> sleepTimeShift; |
| 2375 | if (sleepTime < kMinThreadSleepTimeUs) { |
| 2376 | sleepTime = kMinThreadSleepTimeUs; |
| 2377 | } |
| 2378 | // reduce sleep time in case of consecutive application underruns to avoid |
| 2379 | // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer |
| 2380 | // duration we would end up writing less data than needed by the audio HAL if |
| 2381 | // the condition persists. |
| 2382 | if (sleepTimeShift < kMaxThreadSleepTimeShift) { |
| 2383 | sleepTimeShift++; |
| 2384 | } |
| 2385 | } else { |
| 2386 | sleepTime = idleSleepTime; |
| 2387 | } |
| 2388 | } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) { |
| 2389 | memset (mMixBuffer, 0, mixBufferSize); |
| 2390 | sleepTime = 0; |
| 2391 | ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED), |
| 2392 | "anticipated start"); |
| 2393 | } |
| 2394 | // TODO add standby time extension fct of effect tail |
| 2395 | } |
| 2396 | |
| 2397 | // prepareTracks_l() must be called with ThreadBase::mLock held |
| 2398 | AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l( |
| 2399 | Vector< sp<Track> > *tracksToRemove) |
| 2400 | { |
| 2401 | |
| 2402 | mixer_state mixerStatus = MIXER_IDLE; |
| 2403 | // find out which tracks need to be processed |
| 2404 | size_t count = mActiveTracks.size(); |
| 2405 | size_t mixedTracks = 0; |
| 2406 | size_t tracksWithEffect = 0; |
| 2407 | // counts only _active_ fast tracks |
| 2408 | size_t fastTracks = 0; |
| 2409 | uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset |
| 2410 | |
| 2411 | float masterVolume = mMasterVolume; |
| 2412 | bool masterMute = mMasterMute; |
| 2413 | |
| 2414 | if (masterMute) { |
| 2415 | masterVolume = 0; |
| 2416 | } |
| 2417 | // Delegate master volume control to effect in output mix effect chain if needed |
| 2418 | sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX); |
| 2419 | if (chain != 0) { |
| 2420 | uint32_t v = (uint32_t)(masterVolume * (1 << 24)); |
| 2421 | chain->setVolume_l(&v, &v); |
| 2422 | masterVolume = (float)((v + (1 << 23)) >> 24); |
| 2423 | chain.clear(); |
| 2424 | } |
| 2425 | |
| 2426 | // prepare a new state to push |
| 2427 | FastMixerStateQueue *sq = NULL; |
| 2428 | FastMixerState *state = NULL; |
| 2429 | bool didModify = false; |
| 2430 | FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED; |
| 2431 | if (mFastMixer != NULL) { |
| 2432 | sq = mFastMixer->sq(); |
| 2433 | state = sq->begin(); |
| 2434 | } |
| 2435 | |
| 2436 | for (size_t i=0 ; i<count ; i++) { |
| 2437 | sp<Track> t = mActiveTracks[i].promote(); |
| 2438 | if (t == 0) { |
| 2439 | continue; |
| 2440 | } |
| 2441 | |
| 2442 | // this const just means the local variable doesn't change |
| 2443 | Track* const track = t.get(); |
| 2444 | |
| 2445 | // process fast tracks |
| 2446 | if (track->isFastTrack()) { |
| 2447 | |
| 2448 | // It's theoretically possible (though unlikely) for a fast track to be created |
| 2449 | // and then removed within the same normal mix cycle. This is not a problem, as |
| 2450 | // the track never becomes active so it's fast mixer slot is never touched. |
| 2451 | // The converse, of removing an (active) track and then creating a new track |
| 2452 | // at the identical fast mixer slot within the same normal mix cycle, |
| 2453 | // is impossible because the slot isn't marked available until the end of each cycle. |
| 2454 | int j = track->mFastIndex; |
| 2455 | ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks); |
| 2456 | ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j))); |
| 2457 | FastTrack *fastTrack = &state->mFastTracks[j]; |
| 2458 | |
| 2459 | // Determine whether the track is currently in underrun condition, |
| 2460 | // and whether it had a recent underrun. |
| 2461 | FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j]; |
| 2462 | FastTrackUnderruns underruns = ftDump->mUnderruns; |
| 2463 | uint32_t recentFull = (underruns.mBitFields.mFull - |
| 2464 | track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK; |
| 2465 | uint32_t recentPartial = (underruns.mBitFields.mPartial - |
| 2466 | track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK; |
| 2467 | uint32_t recentEmpty = (underruns.mBitFields.mEmpty - |
| 2468 | track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK; |
| 2469 | uint32_t recentUnderruns = recentPartial + recentEmpty; |
| 2470 | track->mObservedUnderruns = underruns; |
| 2471 | // don't count underruns that occur while stopping or pausing |
| 2472 | // or stopped which can occur when flush() is called while active |
| 2473 | if (!(track->isStopping() || track->isPausing() || track->isStopped())) { |
| 2474 | track->mUnderrunCount += recentUnderruns; |
| 2475 | } |
| 2476 | |
| 2477 | // This is similar to the state machine for normal tracks, |
| 2478 | // with a few modifications for fast tracks. |
| 2479 | bool isActive = true; |
| 2480 | switch (track->mState) { |
| 2481 | case TrackBase::STOPPING_1: |
| 2482 | // track stays active in STOPPING_1 state until first underrun |
| 2483 | if (recentUnderruns > 0) { |
| 2484 | track->mState = TrackBase::STOPPING_2; |
| 2485 | } |
| 2486 | break; |
| 2487 | case TrackBase::PAUSING: |
| 2488 | // ramp down is not yet implemented |
| 2489 | track->setPaused(); |
| 2490 | break; |
| 2491 | case TrackBase::RESUMING: |
| 2492 | // ramp up is not yet implemented |
| 2493 | track->mState = TrackBase::ACTIVE; |
| 2494 | break; |
| 2495 | case TrackBase::ACTIVE: |
| 2496 | if (recentFull > 0 || recentPartial > 0) { |
| 2497 | // track has provided at least some frames recently: reset retry count |
| 2498 | track->mRetryCount = kMaxTrackRetries; |
| 2499 | } |
| 2500 | if (recentUnderruns == 0) { |
| 2501 | // no recent underruns: stay active |
| 2502 | break; |
| 2503 | } |
| 2504 | // there has recently been an underrun of some kind |
| 2505 | if (track->sharedBuffer() == 0) { |
| 2506 | // were any of the recent underruns "empty" (no frames available)? |
| 2507 | if (recentEmpty == 0) { |
| 2508 | // no, then ignore the partial underruns as they are allowed indefinitely |
| 2509 | break; |
| 2510 | } |
| 2511 | // there has recently been an "empty" underrun: decrement the retry counter |
| 2512 | if (--(track->mRetryCount) > 0) { |
| 2513 | break; |
| 2514 | } |
| 2515 | // indicate to client process that the track was disabled because of underrun; |
| 2516 | // it will then automatically call start() when data is available |
| 2517 | android_atomic_or(CBLK_DISABLED, &track->mCblk->flags); |
| 2518 | // remove from active list, but state remains ACTIVE [confusing but true] |
| 2519 | isActive = false; |
| 2520 | break; |
| 2521 | } |
| 2522 | // fall through |
| 2523 | case TrackBase::STOPPING_2: |
| 2524 | case TrackBase::PAUSED: |
| 2525 | case TrackBase::TERMINATED: |
| 2526 | case TrackBase::STOPPED: |
| 2527 | case TrackBase::FLUSHED: // flush() while active |
| 2528 | // Check for presentation complete if track is inactive |
| 2529 | // We have consumed all the buffers of this track. |
| 2530 | // This would be incomplete if we auto-paused on underrun |
| 2531 | { |
| 2532 | size_t audioHALFrames = |
| 2533 | (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000; |
| 2534 | size_t framesWritten = mBytesWritten / mFrameSize; |
| 2535 | if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) { |
| 2536 | // track stays in active list until presentation is complete |
| 2537 | break; |
| 2538 | } |
| 2539 | } |
| 2540 | if (track->isStopping_2()) { |
| 2541 | track->mState = TrackBase::STOPPED; |
| 2542 | } |
| 2543 | if (track->isStopped()) { |
| 2544 | // Can't reset directly, as fast mixer is still polling this track |
| 2545 | // track->reset(); |
| 2546 | // So instead mark this track as needing to be reset after push with ack |
| 2547 | resetMask |= 1 << i; |
| 2548 | } |
| 2549 | isActive = false; |
| 2550 | break; |
| 2551 | case TrackBase::IDLE: |
| 2552 | default: |
| 2553 | LOG_FATAL("unexpected track state %d", track->mState); |
| 2554 | } |
| 2555 | |
| 2556 | if (isActive) { |
| 2557 | // was it previously inactive? |
| 2558 | if (!(state->mTrackMask & (1 << j))) { |
| 2559 | ExtendedAudioBufferProvider *eabp = track; |
| 2560 | VolumeProvider *vp = track; |
| 2561 | fastTrack->mBufferProvider = eabp; |
| 2562 | fastTrack->mVolumeProvider = vp; |
| 2563 | fastTrack->mSampleRate = track->mSampleRate; |
| 2564 | fastTrack->mChannelMask = track->mChannelMask; |
| 2565 | fastTrack->mGeneration++; |
| 2566 | state->mTrackMask |= 1 << j; |
| 2567 | didModify = true; |
| 2568 | // no acknowledgement required for newly active tracks |
| 2569 | } |
| 2570 | // cache the combined master volume and stream type volume for fast mixer; this |
| 2571 | // lacks any synchronization or barrier so VolumeProvider may read a stale value |
Glenn Kasten | e4756fe | 2012-11-29 13:38:14 -0800 | [diff] [blame] | 2572 | track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume; |
Eric Laurent | 81784c3 | 2012-11-19 14:55:58 -0800 | [diff] [blame] | 2573 | ++fastTracks; |
| 2574 | } else { |
| 2575 | // was it previously active? |
| 2576 | if (state->mTrackMask & (1 << j)) { |
| 2577 | fastTrack->mBufferProvider = NULL; |
| 2578 | fastTrack->mGeneration++; |
| 2579 | state->mTrackMask &= ~(1 << j); |
| 2580 | didModify = true; |
| 2581 | // If any fast tracks were removed, we must wait for acknowledgement |
| 2582 | // because we're about to decrement the last sp<> on those tracks. |
| 2583 | block = FastMixerStateQueue::BLOCK_UNTIL_ACKED; |
| 2584 | } else { |
| 2585 | LOG_FATAL("fast track %d should have been active", j); |
| 2586 | } |
| 2587 | tracksToRemove->add(track); |
| 2588 | // Avoids a misleading display in dumpsys |
| 2589 | track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL; |
| 2590 | } |
| 2591 | continue; |
| 2592 | } |
| 2593 | |
| 2594 | { // local variable scope to avoid goto warning |
| 2595 | |
| 2596 | audio_track_cblk_t* cblk = track->cblk(); |
| 2597 | |
| 2598 | // The first time a track is added we wait |
| 2599 | // for all its buffers to be filled before processing it |
| 2600 | int name = track->name(); |
| 2601 | // make sure that we have enough frames to mix one full buffer. |
| 2602 | // enforce this condition only once to enable draining the buffer in case the client |
| 2603 | // app does not call stop() and relies on underrun to stop: |
| 2604 | // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed |
| 2605 | // during last round |
Glenn Kasten | 9f80dd2 | 2012-12-18 15:57:32 -0800 | [diff] [blame] | 2606 | size_t desiredFrames; |
| 2607 | if (t->sampleRate() == mSampleRate) { |
| 2608 | desiredFrames = mNormalFrameCount; |
| 2609 | } else { |
| 2610 | // +1 for rounding and +1 for additional sample needed for interpolation |
| 2611 | desiredFrames = (mNormalFrameCount * t->sampleRate()) / mSampleRate + 1 + 1; |
| 2612 | // add frames already consumed but not yet released by the resampler |
| 2613 | // because cblk->framesReady() will include these frames |
| 2614 | desiredFrames += mAudioMixer->getUnreleasedFrames(track->name()); |
| 2615 | // the minimum track buffer size is normally twice the number of frames necessary |
| 2616 | // to fill one buffer and the resampler should not leave more than one buffer worth |
| 2617 | // of unreleased frames after each pass, but just in case... |
| 2618 | ALOG_ASSERT(desiredFrames <= cblk->frameCount_); |
| 2619 | } |
Eric Laurent | 81784c3 | 2012-11-19 14:55:58 -0800 | [diff] [blame] | 2620 | uint32_t minFrames = 1; |
| 2621 | if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() && |
| 2622 | (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) { |
Glenn Kasten | 9f80dd2 | 2012-12-18 15:57:32 -0800 | [diff] [blame] | 2623 | minFrames = desiredFrames; |
Eric Laurent | 81784c3 | 2012-11-19 14:55:58 -0800 | [diff] [blame] | 2624 | } |
Glenn Kasten | 9f80dd2 | 2012-12-18 15:57:32 -0800 | [diff] [blame] | 2625 | // It's not safe to call framesReady() for a static buffer track, so assume it's ready |
| 2626 | size_t framesReady; |
| 2627 | if (track->sharedBuffer() == 0) { |
| 2628 | framesReady = track->framesReady(); |
| 2629 | } else if (track->isStopped()) { |
| 2630 | framesReady = 0; |
| 2631 | } else { |
| 2632 | framesReady = 1; |
| 2633 | } |
| 2634 | if ((framesReady >= minFrames) && track->isReady() && |
Eric Laurent | 81784c3 | 2012-11-19 14:55:58 -0800 | [diff] [blame] | 2635 | !track->isPaused() && !track->isTerminated()) |
| 2636 | { |
| 2637 | ALOGVV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, |
| 2638 | this); |
| 2639 | |
| 2640 | mixedTracks++; |
| 2641 | |
| 2642 | // track->mainBuffer() != mMixBuffer means there is an effect chain |
| 2643 | // connected to the track |
| 2644 | chain.clear(); |
| 2645 | if (track->mainBuffer() != mMixBuffer) { |
| 2646 | chain = getEffectChain_l(track->sessionId()); |
| 2647 | // Delegate volume control to effect in track effect chain if needed |
| 2648 | if (chain != 0) { |
| 2649 | tracksWithEffect++; |
| 2650 | } else { |
| 2651 | ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on " |
| 2652 | "session %d", |
| 2653 | name, track->sessionId()); |
| 2654 | } |
| 2655 | } |
| 2656 | |
| 2657 | |
| 2658 | int param = AudioMixer::VOLUME; |
| 2659 | if (track->mFillingUpStatus == Track::FS_FILLED) { |
| 2660 | // no ramp for the first volume setting |
| 2661 | track->mFillingUpStatus = Track::FS_ACTIVE; |
| 2662 | if (track->mState == TrackBase::RESUMING) { |
| 2663 | track->mState = TrackBase::ACTIVE; |
| 2664 | param = AudioMixer::RAMP_VOLUME; |
| 2665 | } |
| 2666 | mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL); |
| 2667 | } else if (cblk->server != 0) { |
| 2668 | // If the track is stopped before the first frame was mixed, |
| 2669 | // do not apply ramp |
| 2670 | param = AudioMixer::RAMP_VOLUME; |
| 2671 | } |
| 2672 | |
| 2673 | // compute volume for this track |
| 2674 | uint32_t vl, vr, va; |
Glenn Kasten | e4756fe | 2012-11-29 13:38:14 -0800 | [diff] [blame] | 2675 | if (track->isPausing() || mStreamTypes[track->streamType()].mute) { |
Eric Laurent | 81784c3 | 2012-11-19 14:55:58 -0800 | [diff] [blame] | 2676 | vl = vr = va = 0; |
| 2677 | if (track->isPausing()) { |
| 2678 | track->setPaused(); |
| 2679 | } |
| 2680 | } else { |
| 2681 | |
| 2682 | // read original volumes with volume control |
| 2683 | float typeVolume = mStreamTypes[track->streamType()].volume; |
| 2684 | float v = masterVolume * typeVolume; |
Glenn Kasten | 9f80dd2 | 2012-12-18 15:57:32 -0800 | [diff] [blame] | 2685 | AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy; |
Glenn Kasten | e3aa659 | 2012-12-04 12:22:46 -0800 | [diff] [blame] | 2686 | uint32_t vlr = proxy->getVolumeLR(); |
Eric Laurent | 81784c3 | 2012-11-19 14:55:58 -0800 | [diff] [blame] | 2687 | vl = vlr & 0xFFFF; |
| 2688 | vr = vlr >> 16; |
| 2689 | // track volumes come from shared memory, so can't be trusted and must be clamped |
| 2690 | if (vl > MAX_GAIN_INT) { |
| 2691 | ALOGV("Track left volume out of range: %04X", vl); |
| 2692 | vl = MAX_GAIN_INT; |
| 2693 | } |
| 2694 | if (vr > MAX_GAIN_INT) { |
| 2695 | ALOGV("Track right volume out of range: %04X", vr); |
| 2696 | vr = MAX_GAIN_INT; |
| 2697 | } |
| 2698 | // now apply the master volume and stream type volume |
| 2699 | vl = (uint32_t)(v * vl) << 12; |
| 2700 | vr = (uint32_t)(v * vr) << 12; |
| 2701 | // assuming master volume and stream type volume each go up to 1.0, |
| 2702 | // vl and vr are now in 8.24 format |
| 2703 | |
Glenn Kasten | e3aa659 | 2012-12-04 12:22:46 -0800 | [diff] [blame] | 2704 | uint16_t sendLevel = proxy->getSendLevel_U4_12(); |
Eric Laurent | 81784c3 | 2012-11-19 14:55:58 -0800 | [diff] [blame] | 2705 | // send level comes from shared memory and so may be corrupt |
| 2706 | if (sendLevel > MAX_GAIN_INT) { |
| 2707 | ALOGV("Track send level out of range: %04X", sendLevel); |
| 2708 | sendLevel = MAX_GAIN_INT; |
| 2709 | } |
| 2710 | va = (uint32_t)(v * sendLevel); |
| 2711 | } |
| 2712 | // Delegate volume control to effect in track effect chain if needed |
| 2713 | if (chain != 0 && chain->setVolume_l(&vl, &vr)) { |
| 2714 | // Do not ramp volume if volume is controlled by effect |
| 2715 | param = AudioMixer::VOLUME; |
| 2716 | track->mHasVolumeController = true; |
| 2717 | } else { |
| 2718 | // force no volume ramp when volume controller was just disabled or removed |
| 2719 | // from effect chain to avoid volume spike |
| 2720 | if (track->mHasVolumeController) { |
| 2721 | param = AudioMixer::VOLUME; |
| 2722 | } |
| 2723 | track->mHasVolumeController = false; |
| 2724 | } |
| 2725 | |
| 2726 | // Convert volumes from 8.24 to 4.12 format |
| 2727 | // This additional clamping is needed in case chain->setVolume_l() overshot |
| 2728 | vl = (vl + (1 << 11)) >> 12; |
| 2729 | if (vl > MAX_GAIN_INT) { |
| 2730 | vl = MAX_GAIN_INT; |
| 2731 | } |
| 2732 | vr = (vr + (1 << 11)) >> 12; |
| 2733 | if (vr > MAX_GAIN_INT) { |
| 2734 | vr = MAX_GAIN_INT; |
| 2735 | } |
| 2736 | |
| 2737 | if (va > MAX_GAIN_INT) { |
| 2738 | va = MAX_GAIN_INT; // va is uint32_t, so no need to check for - |
| 2739 | } |
| 2740 | |
| 2741 | // XXX: these things DON'T need to be done each time |
| 2742 | mAudioMixer->setBufferProvider(name, track); |
| 2743 | mAudioMixer->enable(name); |
| 2744 | |
| 2745 | mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl); |
| 2746 | mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr); |
| 2747 | mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va); |
| 2748 | mAudioMixer->setParameter( |
| 2749 | name, |
| 2750 | AudioMixer::TRACK, |
| 2751 | AudioMixer::FORMAT, (void *)track->format()); |
| 2752 | mAudioMixer->setParameter( |
| 2753 | name, |
| 2754 | AudioMixer::TRACK, |
| 2755 | AudioMixer::CHANNEL_MASK, (void *)track->channelMask()); |
Glenn Kasten | e3aa659 | 2012-12-04 12:22:46 -0800 | [diff] [blame] | 2756 | // limit track sample rate to 2 x output sample rate, which changes at re-configuration |
| 2757 | uint32_t maxSampleRate = mSampleRate * 2; |
Glenn Kasten | 9f80dd2 | 2012-12-18 15:57:32 -0800 | [diff] [blame] | 2758 | uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate(); |
Glenn Kasten | e3aa659 | 2012-12-04 12:22:46 -0800 | [diff] [blame] | 2759 | if (reqSampleRate == 0) { |
| 2760 | reqSampleRate = mSampleRate; |
| 2761 | } else if (reqSampleRate > maxSampleRate) { |
| 2762 | reqSampleRate = maxSampleRate; |
| 2763 | } |
Eric Laurent | 81784c3 | 2012-11-19 14:55:58 -0800 | [diff] [blame] | 2764 | mAudioMixer->setParameter( |
| 2765 | name, |
| 2766 | AudioMixer::RESAMPLE, |
| 2767 | AudioMixer::SAMPLE_RATE, |
Glenn Kasten | e3aa659 | 2012-12-04 12:22:46 -0800 | [diff] [blame] | 2768 | (void *)reqSampleRate); |
Eric Laurent | 81784c3 | 2012-11-19 14:55:58 -0800 | [diff] [blame] | 2769 | mAudioMixer->setParameter( |
| 2770 | name, |
| 2771 | AudioMixer::TRACK, |
| 2772 | AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer()); |
| 2773 | mAudioMixer->setParameter( |
| 2774 | name, |
| 2775 | AudioMixer::TRACK, |
| 2776 | AudioMixer::AUX_BUFFER, (void *)track->auxBuffer()); |
| 2777 | |
| 2778 | // reset retry count |
| 2779 | track->mRetryCount = kMaxTrackRetries; |
| 2780 | |
| 2781 | // If one track is ready, set the mixer ready if: |
| 2782 | // - the mixer was not ready during previous round OR |
| 2783 | // - no other track is not ready |
| 2784 | if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY || |
| 2785 | mixerStatus != MIXER_TRACKS_ENABLED) { |
| 2786 | mixerStatus = MIXER_TRACKS_READY; |
| 2787 | } |
| 2788 | } else { |
Glenn Kasten | 9f80dd2 | 2012-12-18 15:57:32 -0800 | [diff] [blame] | 2789 | // only implemented for normal tracks, not fast tracks |
| 2790 | if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) { |
| 2791 | // we missed desiredFrames whatever the actual number of frames missing was |
| 2792 | cblk->u.mStreaming.mUnderrunFrames += desiredFrames; |
| 2793 | // FIXME also wake futex so that underrun is noticed more quickly |
| 2794 | (void) android_atomic_or(CBLK_UNDERRUN, &cblk->flags); |
| 2795 | } |
Eric Laurent | 81784c3 | 2012-11-19 14:55:58 -0800 | [diff] [blame] | 2796 | // clear effect chain input buffer if an active track underruns to avoid sending |
| 2797 | // previous audio buffer again to effects |
| 2798 | chain = getEffectChain_l(track->sessionId()); |
| 2799 | if (chain != 0) { |
| 2800 | chain->clearInputBuffer(); |
| 2801 | } |
| 2802 | |
| 2803 | ALOGVV("track %d u=%08x, s=%08x [NOT READY] on thread %p", name, cblk->user, |
| 2804 | cblk->server, this); |
| 2805 | if ((track->sharedBuffer() != 0) || track->isTerminated() || |
| 2806 | track->isStopped() || track->isPaused()) { |
| 2807 | // We have consumed all the buffers of this track. |
| 2808 | // Remove it from the list of active tracks. |
| 2809 | // TODO: use actual buffer filling status instead of latency when available from |
| 2810 | // audio HAL |
| 2811 | size_t audioHALFrames = (latency_l() * mSampleRate) / 1000; |
| 2812 | size_t framesWritten = mBytesWritten / mFrameSize; |
| 2813 | if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) { |
| 2814 | if (track->isStopped()) { |
| 2815 | track->reset(); |
| 2816 | } |
| 2817 | tracksToRemove->add(track); |
| 2818 | } |
| 2819 | } else { |
| 2820 | track->mUnderrunCount++; |
| 2821 | // No buffers for this track. Give it a few chances to |
| 2822 | // fill a buffer, then remove it from active list. |
| 2823 | if (--(track->mRetryCount) <= 0) { |
Glenn Kasten | c9b2e20 | 2013-02-26 11:32:32 -0800 | [diff] [blame] | 2824 | ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this); |
Eric Laurent | 81784c3 | 2012-11-19 14:55:58 -0800 | [diff] [blame] | 2825 | tracksToRemove->add(track); |
| 2826 | // indicate to client process that the track was disabled because of underrun; |
| 2827 | // it will then automatically call start() when data is available |
| 2828 | android_atomic_or(CBLK_DISABLED, &cblk->flags); |
| 2829 | // If one track is not ready, mark the mixer also not ready if: |
| 2830 | // - the mixer was ready during previous round OR |
| 2831 | // - no other track is ready |
| 2832 | } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY || |
| 2833 | mixerStatus != MIXER_TRACKS_READY) { |
| 2834 | mixerStatus = MIXER_TRACKS_ENABLED; |
| 2835 | } |
| 2836 | } |
| 2837 | mAudioMixer->disable(name); |
| 2838 | } |
| 2839 | |
| 2840 | } // local variable scope to avoid goto warning |
| 2841 | track_is_ready: ; |
| 2842 | |
| 2843 | } |
| 2844 | |
| 2845 | // Push the new FastMixer state if necessary |
| 2846 | bool pauseAudioWatchdog = false; |
| 2847 | if (didModify) { |
| 2848 | state->mFastTracksGen++; |
| 2849 | // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle |
| 2850 | if (kUseFastMixer == FastMixer_Dynamic && |
| 2851 | state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) { |
| 2852 | state->mCommand = FastMixerState::COLD_IDLE; |
| 2853 | state->mColdFutexAddr = &mFastMixerFutex; |
| 2854 | state->mColdGen++; |
| 2855 | mFastMixerFutex = 0; |
| 2856 | if (kUseFastMixer == FastMixer_Dynamic) { |
| 2857 | mNormalSink = mOutputSink; |
| 2858 | } |
| 2859 | // If we go into cold idle, need to wait for acknowledgement |
| 2860 | // so that fast mixer stops doing I/O. |
| 2861 | block = FastMixerStateQueue::BLOCK_UNTIL_ACKED; |
| 2862 | pauseAudioWatchdog = true; |
| 2863 | } |
Eric Laurent | 81784c3 | 2012-11-19 14:55:58 -0800 | [diff] [blame] | 2864 | } |
| 2865 | if (sq != NULL) { |
| 2866 | sq->end(didModify); |
| 2867 | sq->push(block); |
| 2868 | } |
| 2869 | #ifdef AUDIO_WATCHDOG |
| 2870 | if (pauseAudioWatchdog && mAudioWatchdog != 0) { |
| 2871 | mAudioWatchdog->pause(); |
| 2872 | } |
| 2873 | #endif |
| 2874 | |
| 2875 | // Now perform the deferred reset on fast tracks that have stopped |
| 2876 | while (resetMask != 0) { |
| 2877 | size_t i = __builtin_ctz(resetMask); |
| 2878 | ALOG_ASSERT(i < count); |
| 2879 | resetMask &= ~(1 << i); |
| 2880 | sp<Track> t = mActiveTracks[i].promote(); |
| 2881 | if (t == 0) { |
| 2882 | continue; |
| 2883 | } |
| 2884 | Track* track = t.get(); |
| 2885 | ALOG_ASSERT(track->isFastTrack() && track->isStopped()); |
| 2886 | track->reset(); |
| 2887 | } |
| 2888 | |
| 2889 | // remove all the tracks that need to be... |
| 2890 | count = tracksToRemove->size(); |
| 2891 | if (CC_UNLIKELY(count)) { |
| 2892 | for (size_t i=0 ; i<count ; i++) { |
| 2893 | const sp<Track>& track = tracksToRemove->itemAt(i); |
| 2894 | mActiveTracks.remove(track); |
| 2895 | if (track->mainBuffer() != mMixBuffer) { |
| 2896 | chain = getEffectChain_l(track->sessionId()); |
| 2897 | if (chain != 0) { |
| 2898 | ALOGV("stopping track on chain %p for session Id: %d", chain.get(), |
| 2899 | track->sessionId()); |
| 2900 | chain->decActiveTrackCnt(); |
| 2901 | } |
| 2902 | } |
| 2903 | if (track->isTerminated()) { |
| 2904 | removeTrack_l(track); |
| 2905 | } |
| 2906 | } |
| 2907 | } |
| 2908 | |
| 2909 | // mix buffer must be cleared if all tracks are connected to an |
| 2910 | // effect chain as in this case the mixer will not write to |
| 2911 | // mix buffer and track effects will accumulate into it |
| 2912 | if ((mixedTracks != 0 && mixedTracks == tracksWithEffect) || |
| 2913 | (mixedTracks == 0 && fastTracks > 0)) { |
| 2914 | // FIXME as a performance optimization, should remember previous zero status |
| 2915 | memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t)); |
| 2916 | } |
| 2917 | |
| 2918 | // if any fast tracks, then status is ready |
| 2919 | mMixerStatusIgnoringFastTracks = mixerStatus; |
| 2920 | if (fastTracks > 0) { |
| 2921 | mixerStatus = MIXER_TRACKS_READY; |
| 2922 | } |
| 2923 | return mixerStatus; |
| 2924 | } |
| 2925 | |
| 2926 | // getTrackName_l() must be called with ThreadBase::mLock held |
| 2927 | int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask, int sessionId) |
| 2928 | { |
| 2929 | return mAudioMixer->getTrackName(channelMask, sessionId); |
| 2930 | } |
| 2931 | |
| 2932 | // deleteTrackName_l() must be called with ThreadBase::mLock held |
| 2933 | void AudioFlinger::MixerThread::deleteTrackName_l(int name) |
| 2934 | { |
| 2935 | ALOGV("remove track (%d) and delete from mixer", name); |
| 2936 | mAudioMixer->deleteTrackName(name); |
| 2937 | } |
| 2938 | |
| 2939 | // checkForNewParameters_l() must be called with ThreadBase::mLock held |
| 2940 | bool AudioFlinger::MixerThread::checkForNewParameters_l() |
| 2941 | { |
| 2942 | // if !&IDLE, holds the FastMixer state to restore after new parameters processed |
| 2943 | FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE; |
| 2944 | bool reconfig = false; |
| 2945 | |
| 2946 | while (!mNewParameters.isEmpty()) { |
| 2947 | |
| 2948 | if (mFastMixer != NULL) { |
| 2949 | FastMixerStateQueue *sq = mFastMixer->sq(); |
| 2950 | FastMixerState *state = sq->begin(); |
| 2951 | if (!(state->mCommand & FastMixerState::IDLE)) { |
| 2952 | previousCommand = state->mCommand; |
| 2953 | state->mCommand = FastMixerState::HOT_IDLE; |
| 2954 | sq->end(); |
| 2955 | sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED); |
| 2956 | } else { |
| 2957 | sq->end(false /*didModify*/); |
| 2958 | } |
| 2959 | } |
| 2960 | |
| 2961 | status_t status = NO_ERROR; |
| 2962 | String8 keyValuePair = mNewParameters[0]; |
| 2963 | AudioParameter param = AudioParameter(keyValuePair); |
| 2964 | int value; |
| 2965 | |
| 2966 | if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) { |
| 2967 | reconfig = true; |
| 2968 | } |
| 2969 | if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) { |
| 2970 | if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) { |
| 2971 | status = BAD_VALUE; |
| 2972 | } else { |
| 2973 | reconfig = true; |
| 2974 | } |
| 2975 | } |
| 2976 | if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) { |
Glenn Kasten | fad226a | 2013-07-16 17:19:58 -0700 | [diff] [blame^] | 2977 | if ((audio_channel_mask_t) value != AUDIO_CHANNEL_OUT_STEREO) { |
Eric Laurent | 81784c3 | 2012-11-19 14:55:58 -0800 | [diff] [blame] | 2978 | status = BAD_VALUE; |
| 2979 | } else { |
| 2980 | reconfig = true; |
| 2981 | } |
| 2982 | } |
| 2983 | if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) { |
| 2984 | // do not accept frame count changes if tracks are open as the track buffer |
| 2985 | // size depends on frame count and correct behavior would not be guaranteed |
| 2986 | // if frame count is changed after track creation |
| 2987 | if (!mTracks.isEmpty()) { |
| 2988 | status = INVALID_OPERATION; |
| 2989 | } else { |
| 2990 | reconfig = true; |
| 2991 | } |
| 2992 | } |
| 2993 | if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) { |
| 2994 | #ifdef ADD_BATTERY_DATA |
| 2995 | // when changing the audio output device, call addBatteryData to notify |
| 2996 | // the change |
| 2997 | if (mOutDevice != value) { |
| 2998 | uint32_t params = 0; |
| 2999 | // check whether speaker is on |
| 3000 | if (value & AUDIO_DEVICE_OUT_SPEAKER) { |
| 3001 | params |= IMediaPlayerService::kBatteryDataSpeakerOn; |
| 3002 | } |
| 3003 | |
| 3004 | audio_devices_t deviceWithoutSpeaker |
| 3005 | = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER; |
| 3006 | // check if any other device (except speaker) is on |
| 3007 | if (value & deviceWithoutSpeaker ) { |
| 3008 | params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn; |
| 3009 | } |
| 3010 | |
| 3011 | if (params != 0) { |
| 3012 | addBatteryData(params); |
| 3013 | } |
| 3014 | } |
| 3015 | #endif |
| 3016 | |
| 3017 | // forward device change to effects that have requested to be |
| 3018 | // aware of attached audio device. |
Eric Laurent | 7e1139c | 2013-06-06 18:29:01 -0700 | [diff] [blame] | 3019 | if (value != AUDIO_DEVICE_NONE) { |
| 3020 | mOutDevice = value; |
| 3021 | for (size_t i = 0; i < mEffectChains.size(); i++) { |
| 3022 | mEffectChains[i]->setDevice_l(mOutDevice); |
| 3023 | } |
Eric Laurent | 81784c3 | 2012-11-19 14:55:58 -0800 | [diff] [blame] | 3024 | } |
| 3025 | } |
| 3026 | |
| 3027 | if (status == NO_ERROR) { |
| 3028 | status = mOutput->stream->common.set_parameters(&mOutput->stream->common, |
| 3029 | keyValuePair.string()); |
| 3030 | if (!mStandby && status == INVALID_OPERATION) { |
| 3031 | mOutput->stream->common.standby(&mOutput->stream->common); |
| 3032 | mStandby = true; |
| 3033 | mBytesWritten = 0; |
| 3034 | status = mOutput->stream->common.set_parameters(&mOutput->stream->common, |
| 3035 | keyValuePair.string()); |
| 3036 | } |
| 3037 | if (status == NO_ERROR && reconfig) { |
| 3038 | delete mAudioMixer; |
| 3039 | // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't) |
| 3040 | mAudioMixer = NULL; |
| 3041 | readOutputParameters(); |
| 3042 | mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate); |
| 3043 | for (size_t i = 0; i < mTracks.size() ; i++) { |
| 3044 | int name = getTrackName_l(mTracks[i]->mChannelMask, mTracks[i]->mSessionId); |
| 3045 | if (name < 0) { |
| 3046 | break; |
| 3047 | } |
| 3048 | mTracks[i]->mName = name; |
Eric Laurent | 81784c3 | 2012-11-19 14:55:58 -0800 | [diff] [blame] | 3049 | } |
| 3050 | sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED); |
| 3051 | } |
| 3052 | } |
| 3053 | |
| 3054 | mNewParameters.removeAt(0); |
| 3055 | |
| 3056 | mParamStatus = status; |
| 3057 | mParamCond.signal(); |
| 3058 | // wait for condition with time out in case the thread calling ThreadBase::setParameters() |
| 3059 | // already timed out waiting for the status and will never signal the condition. |
| 3060 | mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs); |
| 3061 | } |
| 3062 | |
| 3063 | if (!(previousCommand & FastMixerState::IDLE)) { |
| 3064 | ALOG_ASSERT(mFastMixer != NULL); |
| 3065 | FastMixerStateQueue *sq = mFastMixer->sq(); |
| 3066 | FastMixerState *state = sq->begin(); |
| 3067 | ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE); |
| 3068 | state->mCommand = previousCommand; |
| 3069 | sq->end(); |
| 3070 | sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED); |
| 3071 | } |
| 3072 | |
| 3073 | return reconfig; |
| 3074 | } |
| 3075 | |
| 3076 | |
| 3077 | void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args) |
| 3078 | { |
| 3079 | const size_t SIZE = 256; |
| 3080 | char buffer[SIZE]; |
| 3081 | String8 result; |
| 3082 | |
| 3083 | PlaybackThread::dumpInternals(fd, args); |
| 3084 | |
| 3085 | snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames()); |
| 3086 | result.append(buffer); |
| 3087 | write(fd, result.string(), result.size()); |
| 3088 | |
| 3089 | // Make a non-atomic copy of fast mixer dump state so it won't change underneath us |
Glenn Kasten | 4182c4e | 2013-07-15 14:45:07 -0700 | [diff] [blame] | 3090 | const FastMixerDumpState copy(mFastMixerDumpState); |
Eric Laurent | 81784c3 | 2012-11-19 14:55:58 -0800 | [diff] [blame] | 3091 | copy.dump(fd); |
| 3092 | |
| 3093 | #ifdef STATE_QUEUE_DUMP |
| 3094 | // Similar for state queue |
| 3095 | StateQueueObserverDump observerCopy = mStateQueueObserverDump; |
| 3096 | observerCopy.dump(fd); |
| 3097 | StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump; |
| 3098 | mutatorCopy.dump(fd); |
| 3099 | #endif |
| 3100 | |
Glenn Kasten | 46909e7 | 2013-02-26 09:20:22 -0800 | [diff] [blame] | 3101 | #ifdef TEE_SINK |
Eric Laurent | 81784c3 | 2012-11-19 14:55:58 -0800 | [diff] [blame] | 3102 | // Write the tee output to a .wav file |
| 3103 | dumpTee(fd, mTeeSource, mId); |
Glenn Kasten | 46909e7 | 2013-02-26 09:20:22 -0800 | [diff] [blame] | 3104 | #endif |
Eric Laurent | 81784c3 | 2012-11-19 14:55:58 -0800 | [diff] [blame] | 3105 | |
| 3106 | #ifdef AUDIO_WATCHDOG |
| 3107 | if (mAudioWatchdog != 0) { |
| 3108 | // Make a non-atomic copy of audio watchdog dump so it won't change underneath us |
| 3109 | AudioWatchdogDump wdCopy = mAudioWatchdogDump; |
| 3110 | wdCopy.dump(fd); |
| 3111 | } |
| 3112 | #endif |
| 3113 | } |
| 3114 | |
| 3115 | uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const |
| 3116 | { |
| 3117 | return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2; |
| 3118 | } |
| 3119 | |
| 3120 | uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const |
| 3121 | { |
| 3122 | return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000); |
| 3123 | } |
| 3124 | |
| 3125 | void AudioFlinger::MixerThread::cacheParameters_l() |
| 3126 | { |
| 3127 | PlaybackThread::cacheParameters_l(); |
| 3128 | |
| 3129 | // FIXME: Relaxed timing because of a certain device that can't meet latency |
| 3130 | // Should be reduced to 2x after the vendor fixes the driver issue |
| 3131 | // increase threshold again due to low power audio mode. The way this warning |
| 3132 | // threshold is calculated and its usefulness should be reconsidered anyway. |
| 3133 | maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15; |
| 3134 | } |
| 3135 | |
| 3136 | // ---------------------------------------------------------------------------- |
| 3137 | |
| 3138 | AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, |
| 3139 | AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device) |
| 3140 | : PlaybackThread(audioFlinger, output, id, device, DIRECT) |
| 3141 | // mLeftVolFloat, mRightVolFloat |
| 3142 | { |
| 3143 | } |
| 3144 | |
| 3145 | AudioFlinger::DirectOutputThread::~DirectOutputThread() |
| 3146 | { |
| 3147 | } |
| 3148 | |
| 3149 | AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l( |
| 3150 | Vector< sp<Track> > *tracksToRemove |
| 3151 | ) |
| 3152 | { |
Eric Laurent | d595b7c | 2013-04-03 17:27:56 -0700 | [diff] [blame] | 3153 | size_t count = mActiveTracks.size(); |
Eric Laurent | 81784c3 | 2012-11-19 14:55:58 -0800 | [diff] [blame] | 3154 | mixer_state mixerStatus = MIXER_IDLE; |
| 3155 | |
| 3156 | // find out which tracks need to be processed |
Eric Laurent | d595b7c | 2013-04-03 17:27:56 -0700 | [diff] [blame] | 3157 | for (size_t i = 0; i < count; i++) { |
| 3158 | sp<Track> t = mActiveTracks[i].promote(); |
Eric Laurent | 81784c3 | 2012-11-19 14:55:58 -0800 | [diff] [blame] | 3159 | // The track died recently |
| 3160 | if (t == 0) { |
Eric Laurent | d595b7c | 2013-04-03 17:27:56 -0700 | [diff] [blame] | 3161 | continue; |
Eric Laurent | 81784c3 | 2012-11-19 14:55:58 -0800 | [diff] [blame] | 3162 | } |
| 3163 | |
| 3164 | Track* const track = t.get(); |
| 3165 | audio_track_cblk_t* cblk = track->cblk(); |
| 3166 | |
| 3167 | // The first time a track is added we wait |
| 3168 | // for all its buffers to be filled before processing it |
| 3169 | uint32_t minFrames; |
| 3170 | if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) { |
| 3171 | minFrames = mNormalFrameCount; |
| 3172 | } else { |
| 3173 | minFrames = 1; |
| 3174 | } |
| 3175 | if ((track->framesReady() >= minFrames) && track->isReady() && |
| 3176 | !track->isPaused() && !track->isTerminated()) |
| 3177 | { |
| 3178 | ALOGVV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server); |
| 3179 | |
| 3180 | if (track->mFillingUpStatus == Track::FS_FILLED) { |
| 3181 | track->mFillingUpStatus = Track::FS_ACTIVE; |
| 3182 | mLeftVolFloat = mRightVolFloat = 0; |
| 3183 | if (track->mState == TrackBase::RESUMING) { |
| 3184 | track->mState = TrackBase::ACTIVE; |
| 3185 | } |
| 3186 | } |
| 3187 | |
| 3188 | // compute volume for this track |
| 3189 | float left, right; |
Glenn Kasten | e4756fe | 2012-11-29 13:38:14 -0800 | [diff] [blame] | 3190 | if (mMasterMute || track->isPausing() || mStreamTypes[track->streamType()].mute) { |
Eric Laurent | 81784c3 | 2012-11-19 14:55:58 -0800 | [diff] [blame] | 3191 | left = right = 0; |
| 3192 | if (track->isPausing()) { |
| 3193 | track->setPaused(); |
| 3194 | } |
| 3195 | } else { |
| 3196 | float typeVolume = mStreamTypes[track->streamType()].volume; |
| 3197 | float v = mMasterVolume * typeVolume; |
Glenn Kasten | 9f80dd2 | 2012-12-18 15:57:32 -0800 | [diff] [blame] | 3198 | uint32_t vlr = track->mAudioTrackServerProxy->getVolumeLR(); |
Eric Laurent | 81784c3 | 2012-11-19 14:55:58 -0800 | [diff] [blame] | 3199 | float v_clamped = v * (vlr & 0xFFFF); |
| 3200 | if (v_clamped > MAX_GAIN) { |
| 3201 | v_clamped = MAX_GAIN; |
| 3202 | } |
| 3203 | left = v_clamped/MAX_GAIN; |
| 3204 | v_clamped = v * (vlr >> 16); |
| 3205 | if (v_clamped > MAX_GAIN) { |
| 3206 | v_clamped = MAX_GAIN; |
| 3207 | } |
| 3208 | right = v_clamped/MAX_GAIN; |
| 3209 | } |
Eric Laurent | d595b7c | 2013-04-03 17:27:56 -0700 | [diff] [blame] | 3210 | // Only consider last track started for volume and mixer state control. |
| 3211 | // This is the last entry in mActiveTracks unless a track underruns. |
| 3212 | // As we only care about the transition phase between two tracks on a |
| 3213 | // direct output, it is not a problem to ignore the underrun case. |
| 3214 | if (i == (count - 1)) { |
| 3215 | if (left != mLeftVolFloat || right != mRightVolFloat) { |
| 3216 | mLeftVolFloat = left; |
| 3217 | mRightVolFloat = right; |
Eric Laurent | 81784c3 | 2012-11-19 14:55:58 -0800 | [diff] [blame] | 3218 | |
Eric Laurent | d595b7c | 2013-04-03 17:27:56 -0700 | [diff] [blame] | 3219 | // Convert volumes from float to 8.24 |
| 3220 | uint32_t vl = (uint32_t)(left * (1 << 24)); |
| 3221 | uint32_t vr = (uint32_t)(right * (1 << 24)); |
Eric Laurent | 81784c3 | 2012-11-19 14:55:58 -0800 | [diff] [blame] | 3222 | |
Eric Laurent | d595b7c | 2013-04-03 17:27:56 -0700 | [diff] [blame] | 3223 | // Delegate volume control to effect in track effect chain if needed |
| 3224 | // only one effect chain can be present on DirectOutputThread, so if |
| 3225 | // there is one, the track is connected to it |
| 3226 | if (!mEffectChains.isEmpty()) { |
| 3227 | // Do not ramp volume if volume is controlled by effect |
| 3228 | mEffectChains[0]->setVolume_l(&vl, &vr); |
| 3229 | left = (float)vl / (1 << 24); |
| 3230 | right = (float)vr / (1 << 24); |
| 3231 | } |
| 3232 | mOutput->stream->set_volume(mOutput->stream, left, right); |
Eric Laurent | 81784c3 | 2012-11-19 14:55:58 -0800 | [diff] [blame] | 3233 | } |
Eric Laurent | 81784c3 | 2012-11-19 14:55:58 -0800 | [diff] [blame] | 3234 | |
Eric Laurent | d595b7c | 2013-04-03 17:27:56 -0700 | [diff] [blame] | 3235 | // reset retry count |
| 3236 | track->mRetryCount = kMaxTrackRetriesDirect; |
| 3237 | mActiveTrack = t; |
| 3238 | mixerStatus = MIXER_TRACKS_READY; |
| 3239 | } |
Eric Laurent | 81784c3 | 2012-11-19 14:55:58 -0800 | [diff] [blame] | 3240 | } else { |
Eric Laurent | d595b7c | 2013-04-03 17:27:56 -0700 | [diff] [blame] | 3241 | // clear effect chain input buffer if the last active track started underruns |
| 3242 | // to avoid sending previous audio buffer again to effects |
| 3243 | if (!mEffectChains.isEmpty() && (i == (count -1))) { |
Eric Laurent | 81784c3 | 2012-11-19 14:55:58 -0800 | [diff] [blame] | 3244 | mEffectChains[0]->clearInputBuffer(); |
| 3245 | } |
| 3246 | |
| 3247 | ALOGVV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server); |
| 3248 | if ((track->sharedBuffer() != 0) || track->isTerminated() || |
| 3249 | track->isStopped() || track->isPaused()) { |
| 3250 | // We have consumed all the buffers of this track. |
| 3251 | // Remove it from the list of active tracks. |
| 3252 | // TODO: implement behavior for compressed audio |
| 3253 | size_t audioHALFrames = (latency_l() * mSampleRate) / 1000; |
| 3254 | size_t framesWritten = mBytesWritten / mFrameSize; |
| 3255 | if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) { |
| 3256 | if (track->isStopped()) { |
| 3257 | track->reset(); |
| 3258 | } |
Eric Laurent | d595b7c | 2013-04-03 17:27:56 -0700 | [diff] [blame] | 3259 | tracksToRemove->add(track); |
Eric Laurent | 81784c3 | 2012-11-19 14:55:58 -0800 | [diff] [blame] | 3260 | } |
| 3261 | } else { |
| 3262 | // No buffers for this track. Give it a few chances to |
| 3263 | // fill a buffer, then remove it from active list. |
Eric Laurent | d595b7c | 2013-04-03 17:27:56 -0700 | [diff] [blame] | 3264 | // Only consider last track started for mixer state control |
Eric Laurent | 81784c3 | 2012-11-19 14:55:58 -0800 | [diff] [blame] | 3265 | if (--(track->mRetryCount) <= 0) { |
| 3266 | ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name()); |
Eric Laurent | d595b7c | 2013-04-03 17:27:56 -0700 | [diff] [blame] | 3267 | tracksToRemove->add(track); |
| 3268 | } else if (i == (count -1)){ |
Eric Laurent | 81784c3 | 2012-11-19 14:55:58 -0800 | [diff] [blame] | 3269 | mixerStatus = MIXER_TRACKS_ENABLED; |
| 3270 | } |
| 3271 | } |
| 3272 | } |
| 3273 | } |
| 3274 | |
Eric Laurent | 81784c3 | 2012-11-19 14:55:58 -0800 | [diff] [blame] | 3275 | // remove all the tracks that need to be... |
Eric Laurent | d595b7c | 2013-04-03 17:27:56 -0700 | [diff] [blame] | 3276 | count = tracksToRemove->size(); |
| 3277 | if (CC_UNLIKELY(count)) { |
| 3278 | for (size_t i = 0 ; i < count ; i++) { |
| 3279 | const sp<Track>& track = tracksToRemove->itemAt(i); |
| 3280 | mActiveTracks.remove(track); |
| 3281 | if (!mEffectChains.isEmpty()) { |
| 3282 | ALOGV("stopping track on chain %p for session Id: %d", mEffectChains[0].get(), |
| 3283 | track->sessionId()); |
| 3284 | mEffectChains[0]->decActiveTrackCnt(); |
| 3285 | } |
| 3286 | if (track->isTerminated()) { |
| 3287 | removeTrack_l(track); |
| 3288 | } |
Eric Laurent | 81784c3 | 2012-11-19 14:55:58 -0800 | [diff] [blame] | 3289 | } |
| 3290 | } |
| 3291 | |
| 3292 | return mixerStatus; |
| 3293 | } |
| 3294 | |
| 3295 | void AudioFlinger::DirectOutputThread::threadLoop_mix() |
| 3296 | { |
| 3297 | AudioBufferProvider::Buffer buffer; |
| 3298 | size_t frameCount = mFrameCount; |
| 3299 | int8_t *curBuf = (int8_t *)mMixBuffer; |
| 3300 | // output audio to hardware |
| 3301 | while (frameCount) { |
| 3302 | buffer.frameCount = frameCount; |
| 3303 | mActiveTrack->getNextBuffer(&buffer); |
| 3304 | if (CC_UNLIKELY(buffer.raw == NULL)) { |
| 3305 | memset(curBuf, 0, frameCount * mFrameSize); |
| 3306 | break; |
| 3307 | } |
| 3308 | memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize); |
| 3309 | frameCount -= buffer.frameCount; |
| 3310 | curBuf += buffer.frameCount * mFrameSize; |
| 3311 | mActiveTrack->releaseBuffer(&buffer); |
| 3312 | } |
| 3313 | sleepTime = 0; |
| 3314 | standbyTime = systemTime() + standbyDelay; |
| 3315 | mActiveTrack.clear(); |
| 3316 | |
| 3317 | } |
| 3318 | |
| 3319 | void AudioFlinger::DirectOutputThread::threadLoop_sleepTime() |
| 3320 | { |
| 3321 | if (sleepTime == 0) { |
| 3322 | if (mMixerStatus == MIXER_TRACKS_ENABLED) { |
| 3323 | sleepTime = activeSleepTime; |
| 3324 | } else { |
| 3325 | sleepTime = idleSleepTime; |
| 3326 | } |
| 3327 | } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) { |
| 3328 | memset(mMixBuffer, 0, mFrameCount * mFrameSize); |
| 3329 | sleepTime = 0; |
| 3330 | } |
| 3331 | } |
| 3332 | |
| 3333 | // getTrackName_l() must be called with ThreadBase::mLock held |
| 3334 | int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask, |
| 3335 | int sessionId) |
| 3336 | { |
| 3337 | return 0; |
| 3338 | } |
| 3339 | |
| 3340 | // deleteTrackName_l() must be called with ThreadBase::mLock held |
| 3341 | void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name) |
| 3342 | { |
| 3343 | } |
| 3344 | |
| 3345 | // checkForNewParameters_l() must be called with ThreadBase::mLock held |
| 3346 | bool AudioFlinger::DirectOutputThread::checkForNewParameters_l() |
| 3347 | { |
| 3348 | bool reconfig = false; |
| 3349 | |
| 3350 | while (!mNewParameters.isEmpty()) { |
| 3351 | status_t status = NO_ERROR; |
| 3352 | String8 keyValuePair = mNewParameters[0]; |
| 3353 | AudioParameter param = AudioParameter(keyValuePair); |
| 3354 | int value; |
| 3355 | |
| 3356 | if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) { |
| 3357 | // do not accept frame count changes if tracks are open as the track buffer |
| 3358 | // size depends on frame count and correct behavior would not be garantied |
| 3359 | // if frame count is changed after track creation |
| 3360 | if (!mTracks.isEmpty()) { |
| 3361 | status = INVALID_OPERATION; |
| 3362 | } else { |
| 3363 | reconfig = true; |
| 3364 | } |
| 3365 | } |
| 3366 | if (status == NO_ERROR) { |
| 3367 | status = mOutput->stream->common.set_parameters(&mOutput->stream->common, |
| 3368 | keyValuePair.string()); |
| 3369 | if (!mStandby && status == INVALID_OPERATION) { |
| 3370 | mOutput->stream->common.standby(&mOutput->stream->common); |
| 3371 | mStandby = true; |
| 3372 | mBytesWritten = 0; |
| 3373 | status = mOutput->stream->common.set_parameters(&mOutput->stream->common, |
| 3374 | keyValuePair.string()); |
| 3375 | } |
| 3376 | if (status == NO_ERROR && reconfig) { |
| 3377 | readOutputParameters(); |
| 3378 | sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED); |
| 3379 | } |
| 3380 | } |
| 3381 | |
| 3382 | mNewParameters.removeAt(0); |
| 3383 | |
| 3384 | mParamStatus = status; |
| 3385 | mParamCond.signal(); |
| 3386 | // wait for condition with time out in case the thread calling ThreadBase::setParameters() |
| 3387 | // already timed out waiting for the status and will never signal the condition. |
| 3388 | mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs); |
| 3389 | } |
| 3390 | return reconfig; |
| 3391 | } |
| 3392 | |
| 3393 | uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const |
| 3394 | { |
| 3395 | uint32_t time; |
| 3396 | if (audio_is_linear_pcm(mFormat)) { |
| 3397 | time = PlaybackThread::activeSleepTimeUs(); |
| 3398 | } else { |
| 3399 | time = 10000; |
| 3400 | } |
| 3401 | return time; |
| 3402 | } |
| 3403 | |
| 3404 | uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const |
| 3405 | { |
| 3406 | uint32_t time; |
| 3407 | if (audio_is_linear_pcm(mFormat)) { |
| 3408 | time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2; |
| 3409 | } else { |
| 3410 | time = 10000; |
| 3411 | } |
| 3412 | return time; |
| 3413 | } |
| 3414 | |
| 3415 | uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const |
| 3416 | { |
| 3417 | uint32_t time; |
| 3418 | if (audio_is_linear_pcm(mFormat)) { |
| 3419 | time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000); |
| 3420 | } else { |
| 3421 | time = 10000; |
| 3422 | } |
| 3423 | return time; |
| 3424 | } |
| 3425 | |
| 3426 | void AudioFlinger::DirectOutputThread::cacheParameters_l() |
| 3427 | { |
| 3428 | PlaybackThread::cacheParameters_l(); |
| 3429 | |
| 3430 | // use shorter standby delay as on normal output to release |
| 3431 | // hardware resources as soon as possible |
| 3432 | standbyDelay = microseconds(activeSleepTime*2); |
| 3433 | } |
| 3434 | |
| 3435 | // ---------------------------------------------------------------------------- |
| 3436 | |
| 3437 | AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, |
| 3438 | AudioFlinger::MixerThread* mainThread, audio_io_handle_t id) |
| 3439 | : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(), |
| 3440 | DUPLICATING), |
| 3441 | mWaitTimeMs(UINT_MAX) |
| 3442 | { |
| 3443 | addOutputTrack(mainThread); |
| 3444 | } |
| 3445 | |
| 3446 | AudioFlinger::DuplicatingThread::~DuplicatingThread() |
| 3447 | { |
| 3448 | for (size_t i = 0; i < mOutputTracks.size(); i++) { |
| 3449 | mOutputTracks[i]->destroy(); |
| 3450 | } |
| 3451 | } |
| 3452 | |
| 3453 | void AudioFlinger::DuplicatingThread::threadLoop_mix() |
| 3454 | { |
| 3455 | // mix buffers... |
| 3456 | if (outputsReady(outputTracks)) { |
| 3457 | mAudioMixer->process(AudioBufferProvider::kInvalidPTS); |
| 3458 | } else { |
| 3459 | memset(mMixBuffer, 0, mixBufferSize); |
| 3460 | } |
| 3461 | sleepTime = 0; |
| 3462 | writeFrames = mNormalFrameCount; |
| 3463 | standbyTime = systemTime() + standbyDelay; |
| 3464 | } |
| 3465 | |
| 3466 | void AudioFlinger::DuplicatingThread::threadLoop_sleepTime() |
| 3467 | { |
| 3468 | if (sleepTime == 0) { |
| 3469 | if (mMixerStatus == MIXER_TRACKS_ENABLED) { |
| 3470 | sleepTime = activeSleepTime; |
| 3471 | } else { |
| 3472 | sleepTime = idleSleepTime; |
| 3473 | } |
| 3474 | } else if (mBytesWritten != 0) { |
| 3475 | if (mMixerStatus == MIXER_TRACKS_ENABLED) { |
| 3476 | writeFrames = mNormalFrameCount; |
| 3477 | memset(mMixBuffer, 0, mixBufferSize); |
| 3478 | } else { |
| 3479 | // flush remaining overflow buffers in output tracks |
| 3480 | writeFrames = 0; |
| 3481 | } |
| 3482 | sleepTime = 0; |
| 3483 | } |
| 3484 | } |
| 3485 | |
| 3486 | void AudioFlinger::DuplicatingThread::threadLoop_write() |
| 3487 | { |
| 3488 | for (size_t i = 0; i < outputTracks.size(); i++) { |
| 3489 | outputTracks[i]->write(mMixBuffer, writeFrames); |
| 3490 | } |
| 3491 | mBytesWritten += mixBufferSize; |
| 3492 | } |
| 3493 | |
| 3494 | void AudioFlinger::DuplicatingThread::threadLoop_standby() |
| 3495 | { |
| 3496 | // DuplicatingThread implements standby by stopping all tracks |
| 3497 | for (size_t i = 0; i < outputTracks.size(); i++) { |
| 3498 | outputTracks[i]->stop(); |
| 3499 | } |
| 3500 | } |
| 3501 | |
| 3502 | void AudioFlinger::DuplicatingThread::saveOutputTracks() |
| 3503 | { |
| 3504 | outputTracks = mOutputTracks; |
| 3505 | } |
| 3506 | |
| 3507 | void AudioFlinger::DuplicatingThread::clearOutputTracks() |
| 3508 | { |
| 3509 | outputTracks.clear(); |
| 3510 | } |
| 3511 | |
| 3512 | void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread) |
| 3513 | { |
| 3514 | Mutex::Autolock _l(mLock); |
| 3515 | // FIXME explain this formula |
| 3516 | size_t frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate(); |
| 3517 | OutputTrack *outputTrack = new OutputTrack(thread, |
| 3518 | this, |
| 3519 | mSampleRate, |
| 3520 | mFormat, |
| 3521 | mChannelMask, |
| 3522 | frameCount); |
| 3523 | if (outputTrack->cblk() != NULL) { |
| 3524 | thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f); |
| 3525 | mOutputTracks.add(outputTrack); |
| 3526 | ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread); |
| 3527 | updateWaitTime_l(); |
| 3528 | } |
| 3529 | } |
| 3530 | |
| 3531 | void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread) |
| 3532 | { |
| 3533 | Mutex::Autolock _l(mLock); |
| 3534 | for (size_t i = 0; i < mOutputTracks.size(); i++) { |
| 3535 | if (mOutputTracks[i]->thread() == thread) { |
| 3536 | mOutputTracks[i]->destroy(); |
| 3537 | mOutputTracks.removeAt(i); |
| 3538 | updateWaitTime_l(); |
| 3539 | return; |
| 3540 | } |
| 3541 | } |
| 3542 | ALOGV("removeOutputTrack(): unkonwn thread: %p", thread); |
| 3543 | } |
| 3544 | |
| 3545 | // caller must hold mLock |
| 3546 | void AudioFlinger::DuplicatingThread::updateWaitTime_l() |
| 3547 | { |
| 3548 | mWaitTimeMs = UINT_MAX; |
| 3549 | for (size_t i = 0; i < mOutputTracks.size(); i++) { |
| 3550 | sp<ThreadBase> strong = mOutputTracks[i]->thread().promote(); |
| 3551 | if (strong != 0) { |
| 3552 | uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate(); |
| 3553 | if (waitTimeMs < mWaitTimeMs) { |
| 3554 | mWaitTimeMs = waitTimeMs; |
| 3555 | } |
| 3556 | } |
| 3557 | } |
| 3558 | } |
| 3559 | |
| 3560 | |
| 3561 | bool AudioFlinger::DuplicatingThread::outputsReady( |
| 3562 | const SortedVector< sp<OutputTrack> > &outputTracks) |
| 3563 | { |
| 3564 | for (size_t i = 0; i < outputTracks.size(); i++) { |
| 3565 | sp<ThreadBase> thread = outputTracks[i]->thread().promote(); |
| 3566 | if (thread == 0) { |
| 3567 | ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", |
| 3568 | outputTracks[i].get()); |
| 3569 | return false; |
| 3570 | } |
| 3571 | PlaybackThread *playbackThread = (PlaybackThread *)thread.get(); |
| 3572 | // see note at standby() declaration |
| 3573 | if (playbackThread->standby() && !playbackThread->isSuspended()) { |
| 3574 | ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), |
| 3575 | thread.get()); |
| 3576 | return false; |
| 3577 | } |
| 3578 | } |
| 3579 | return true; |
| 3580 | } |
| 3581 | |
| 3582 | uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const |
| 3583 | { |
| 3584 | return (mWaitTimeMs * 1000) / 2; |
| 3585 | } |
| 3586 | |
| 3587 | void AudioFlinger::DuplicatingThread::cacheParameters_l() |
| 3588 | { |
| 3589 | // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first |
| 3590 | updateWaitTime_l(); |
| 3591 | |
| 3592 | MixerThread::cacheParameters_l(); |
| 3593 | } |
| 3594 | |
| 3595 | // ---------------------------------------------------------------------------- |
| 3596 | // Record |
| 3597 | // ---------------------------------------------------------------------------- |
| 3598 | |
| 3599 | AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger, |
| 3600 | AudioStreamIn *input, |
| 3601 | uint32_t sampleRate, |
| 3602 | audio_channel_mask_t channelMask, |
| 3603 | audio_io_handle_t id, |
Eric Laurent | d3922f7 | 2013-02-01 17:57:04 -0800 | [diff] [blame] | 3604 | audio_devices_t outDevice, |
Glenn Kasten | 46909e7 | 2013-02-26 09:20:22 -0800 | [diff] [blame] | 3605 | audio_devices_t inDevice |
| 3606 | #ifdef TEE_SINK |
| 3607 | , const sp<NBAIO_Sink>& teeSink |
| 3608 | #endif |
| 3609 | ) : |
Eric Laurent | d3922f7 | 2013-02-01 17:57:04 -0800 | [diff] [blame] | 3610 | ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD), |
Eric Laurent | 81784c3 | 2012-11-19 14:55:58 -0800 | [diff] [blame] | 3611 | mInput(input), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL), |
| 3612 | // mRsmpInIndex and mInputBytes set by readInputParameters() |
| 3613 | mReqChannelCount(popcount(channelMask)), |
Glenn Kasten | 46909e7 | 2013-02-26 09:20:22 -0800 | [diff] [blame] | 3614 | mReqSampleRate(sampleRate) |
Eric Laurent | 81784c3 | 2012-11-19 14:55:58 -0800 | [diff] [blame] | 3615 | // mBytesRead is only meaningful while active, and so is cleared in start() |
| 3616 | // (but might be better to also clear here for dump?) |
Glenn Kasten | 46909e7 | 2013-02-26 09:20:22 -0800 | [diff] [blame] | 3617 | #ifdef TEE_SINK |
| 3618 | , mTeeSink(teeSink) |
| 3619 | #endif |
Eric Laurent | 81784c3 | 2012-11-19 14:55:58 -0800 | [diff] [blame] | 3620 | { |
| 3621 | snprintf(mName, kNameLength, "AudioIn_%X", id); |
| 3622 | |
| 3623 | readInputParameters(); |
| 3624 | |
| 3625 | } |
| 3626 | |
| 3627 | |
| 3628 | AudioFlinger::RecordThread::~RecordThread() |
| 3629 | { |
| 3630 | delete[] mRsmpInBuffer; |
| 3631 | delete mResampler; |
| 3632 | delete[] mRsmpOutBuffer; |
| 3633 | } |
| 3634 | |
| 3635 | void AudioFlinger::RecordThread::onFirstRef() |
| 3636 | { |
| 3637 | run(mName, PRIORITY_URGENT_AUDIO); |
| 3638 | } |
| 3639 | |
| 3640 | status_t AudioFlinger::RecordThread::readyToRun() |
| 3641 | { |
| 3642 | status_t status = initCheck(); |
| 3643 | ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this); |
| 3644 | return status; |
| 3645 | } |
| 3646 | |
| 3647 | bool AudioFlinger::RecordThread::threadLoop() |
| 3648 | { |
| 3649 | AudioBufferProvider::Buffer buffer; |
| 3650 | sp<RecordTrack> activeTrack; |
| 3651 | Vector< sp<EffectChain> > effectChains; |
| 3652 | |
| 3653 | nsecs_t lastWarning = 0; |
| 3654 | |
| 3655 | inputStandBy(); |
| 3656 | acquireWakeLock(); |
| 3657 | |
| 3658 | // used to verify we've read at least once before evaluating how many bytes were read |
| 3659 | bool readOnce = false; |
| 3660 | |
| 3661 | // start recording |
| 3662 | while (!exitPending()) { |
| 3663 | |
| 3664 | processConfigEvents(); |
| 3665 | |
| 3666 | { // scope for mLock |
| 3667 | Mutex::Autolock _l(mLock); |
| 3668 | checkForNewParameters_l(); |
| 3669 | if (mActiveTrack == 0 && mConfigEvents.isEmpty()) { |
| 3670 | standby(); |
| 3671 | |
| 3672 | if (exitPending()) { |
| 3673 | break; |
| 3674 | } |
| 3675 | |
| 3676 | releaseWakeLock_l(); |
| 3677 | ALOGV("RecordThread: loop stopping"); |
| 3678 | // go to sleep |
| 3679 | mWaitWorkCV.wait(mLock); |
| 3680 | ALOGV("RecordThread: loop starting"); |
| 3681 | acquireWakeLock_l(); |
| 3682 | continue; |
| 3683 | } |
| 3684 | if (mActiveTrack != 0) { |
| 3685 | if (mActiveTrack->mState == TrackBase::PAUSING) { |
| 3686 | standby(); |
| 3687 | mActiveTrack.clear(); |
| 3688 | mStartStopCond.broadcast(); |
| 3689 | } else if (mActiveTrack->mState == TrackBase::RESUMING) { |
| 3690 | if (mReqChannelCount != mActiveTrack->channelCount()) { |
| 3691 | mActiveTrack.clear(); |
| 3692 | mStartStopCond.broadcast(); |
| 3693 | } else if (readOnce) { |
| 3694 | // record start succeeds only if first read from audio input |
| 3695 | // succeeds |
| 3696 | if (mBytesRead >= 0) { |
| 3697 | mActiveTrack->mState = TrackBase::ACTIVE; |
| 3698 | } else { |
| 3699 | mActiveTrack.clear(); |
| 3700 | } |
| 3701 | mStartStopCond.broadcast(); |
| 3702 | } |
| 3703 | mStandby = false; |
| 3704 | } else if (mActiveTrack->mState == TrackBase::TERMINATED) { |
| 3705 | removeTrack_l(mActiveTrack); |
| 3706 | mActiveTrack.clear(); |
| 3707 | } |
| 3708 | } |
| 3709 | lockEffectChains_l(effectChains); |
| 3710 | } |
| 3711 | |
| 3712 | if (mActiveTrack != 0) { |
| 3713 | if (mActiveTrack->mState != TrackBase::ACTIVE && |
| 3714 | mActiveTrack->mState != TrackBase::RESUMING) { |
| 3715 | unlockEffectChains(effectChains); |
| 3716 | usleep(kRecordThreadSleepUs); |
| 3717 | continue; |
| 3718 | } |
| 3719 | for (size_t i = 0; i < effectChains.size(); i ++) { |
| 3720 | effectChains[i]->process_l(); |
| 3721 | } |
| 3722 | |
| 3723 | buffer.frameCount = mFrameCount; |
Glenn Kasten | 9f80dd2 | 2012-12-18 15:57:32 -0800 | [diff] [blame] | 3724 | status_t status = mActiveTrack->getNextBuffer(&buffer); |
| 3725 | if (CC_LIKELY(status == NO_ERROR)) { |
Eric Laurent | 81784c3 | 2012-11-19 14:55:58 -0800 | [diff] [blame] | 3726 | readOnce = true; |
| 3727 | size_t framesOut = buffer.frameCount; |
| 3728 | if (mResampler == NULL) { |
| 3729 | // no resampling |
| 3730 | while (framesOut) { |
| 3731 | size_t framesIn = mFrameCount - mRsmpInIndex; |
| 3732 | if (framesIn) { |
| 3733 | int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize; |
| 3734 | int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * |
| 3735 | mActiveTrack->mFrameSize; |
| 3736 | if (framesIn > framesOut) |
| 3737 | framesIn = framesOut; |
| 3738 | mRsmpInIndex += framesIn; |
| 3739 | framesOut -= framesIn; |
| 3740 | if (mChannelCount == mReqChannelCount || |
| 3741 | mFormat != AUDIO_FORMAT_PCM_16_BIT) { |
| 3742 | memcpy(dst, src, framesIn * mFrameSize); |
| 3743 | } else { |
| 3744 | if (mChannelCount == 1) { |
| 3745 | upmix_to_stereo_i16_from_mono_i16((int16_t *)dst, |
| 3746 | (int16_t *)src, framesIn); |
| 3747 | } else { |
| 3748 | downmix_to_mono_i16_from_stereo_i16((int16_t *)dst, |
| 3749 | (int16_t *)src, framesIn); |
| 3750 | } |
| 3751 | } |
| 3752 | } |
| 3753 | if (framesOut && mFrameCount == mRsmpInIndex) { |
| 3754 | void *readInto; |
| 3755 | if (framesOut == mFrameCount && |
| 3756 | (mChannelCount == mReqChannelCount || |
| 3757 | mFormat != AUDIO_FORMAT_PCM_16_BIT)) { |
| 3758 | readInto = buffer.raw; |
| 3759 | framesOut = 0; |
| 3760 | } else { |
| 3761 | readInto = mRsmpInBuffer; |
| 3762 | mRsmpInIndex = 0; |
| 3763 | } |
Glenn Kasten | c9b2e20 | 2013-02-26 11:32:32 -0800 | [diff] [blame] | 3764 | mBytesRead = mInput->stream->read(mInput->stream, readInto, |
| 3765 | mInputBytes); |
Eric Laurent | 81784c3 | 2012-11-19 14:55:58 -0800 | [diff] [blame] | 3766 | if (mBytesRead <= 0) { |
| 3767 | if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE)) |
| 3768 | { |
| 3769 | ALOGE("Error reading audio input"); |
| 3770 | // Force input into standby so that it tries to |
| 3771 | // recover at next read attempt |
| 3772 | inputStandBy(); |
| 3773 | usleep(kRecordThreadSleepUs); |
| 3774 | } |
| 3775 | mRsmpInIndex = mFrameCount; |
| 3776 | framesOut = 0; |
| 3777 | buffer.frameCount = 0; |
Glenn Kasten | 46909e7 | 2013-02-26 09:20:22 -0800 | [diff] [blame] | 3778 | } |
| 3779 | #ifdef TEE_SINK |
| 3780 | else if (mTeeSink != 0) { |
Eric Laurent | 81784c3 | 2012-11-19 14:55:58 -0800 | [diff] [blame] | 3781 | (void) mTeeSink->write(readInto, |
| 3782 | mBytesRead >> Format_frameBitShift(mTeeSink->format())); |
| 3783 | } |
Glenn Kasten | 46909e7 | 2013-02-26 09:20:22 -0800 | [diff] [blame] | 3784 | #endif |
Eric Laurent | 81784c3 | 2012-11-19 14:55:58 -0800 | [diff] [blame] | 3785 | } |
| 3786 | } |
| 3787 | } else { |
| 3788 | // resampling |
| 3789 | |
| 3790 | memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t)); |
| 3791 | // alter output frame count as if we were expecting stereo samples |
| 3792 | if (mChannelCount == 1 && mReqChannelCount == 1) { |
| 3793 | framesOut >>= 1; |
| 3794 | } |
| 3795 | mResampler->resample(mRsmpOutBuffer, framesOut, |
| 3796 | this /* AudioBufferProvider* */); |
| 3797 | // ditherAndClamp() works as long as all buffers returned by |
| 3798 | // mActiveTrack->getNextBuffer() are 32 bit aligned which should be always true. |
| 3799 | if (mChannelCount == 2 && mReqChannelCount == 1) { |
| 3800 | ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut); |
| 3801 | // the resampler always outputs stereo samples: |
| 3802 | // do post stereo to mono conversion |
| 3803 | downmix_to_mono_i16_from_stereo_i16(buffer.i16, (int16_t *)mRsmpOutBuffer, |
| 3804 | framesOut); |
| 3805 | } else { |
| 3806 | ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut); |
| 3807 | } |
| 3808 | |
| 3809 | } |
| 3810 | if (mFramestoDrop == 0) { |
| 3811 | mActiveTrack->releaseBuffer(&buffer); |
| 3812 | } else { |
| 3813 | if (mFramestoDrop > 0) { |
| 3814 | mFramestoDrop -= buffer.frameCount; |
| 3815 | if (mFramestoDrop <= 0) { |
| 3816 | clearSyncStartEvent(); |
| 3817 | } |
| 3818 | } else { |
| 3819 | mFramestoDrop += buffer.frameCount; |
| 3820 | if (mFramestoDrop >= 0 || mSyncStartEvent == 0 || |
| 3821 | mSyncStartEvent->isCancelled()) { |
| 3822 | ALOGW("Synced record %s, session %d, trigger session %d", |
| 3823 | (mFramestoDrop >= 0) ? "timed out" : "cancelled", |
| 3824 | mActiveTrack->sessionId(), |
| 3825 | (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0); |
| 3826 | clearSyncStartEvent(); |
| 3827 | } |
| 3828 | } |
| 3829 | } |
| 3830 | mActiveTrack->clearOverflow(); |
| 3831 | } |
| 3832 | // client isn't retrieving buffers fast enough |
| 3833 | else { |
| 3834 | if (!mActiveTrack->setOverflow()) { |
| 3835 | nsecs_t now = systemTime(); |
| 3836 | if ((now - lastWarning) > kWarningThrottleNs) { |
| 3837 | ALOGW("RecordThread: buffer overflow"); |
| 3838 | lastWarning = now; |
| 3839 | } |
| 3840 | } |
| 3841 | // Release the processor for a while before asking for a new buffer. |
| 3842 | // This will give the application more chance to read from the buffer and |
| 3843 | // clear the overflow. |
| 3844 | usleep(kRecordThreadSleepUs); |
| 3845 | } |
| 3846 | } |
| 3847 | // enable changes in effect chain |
| 3848 | unlockEffectChains(effectChains); |
| 3849 | effectChains.clear(); |
| 3850 | } |
| 3851 | |
| 3852 | standby(); |
| 3853 | |
| 3854 | { |
| 3855 | Mutex::Autolock _l(mLock); |
| 3856 | mActiveTrack.clear(); |
| 3857 | mStartStopCond.broadcast(); |
| 3858 | } |
| 3859 | |
| 3860 | releaseWakeLock(); |
| 3861 | |
| 3862 | ALOGV("RecordThread %p exiting", this); |
| 3863 | return false; |
| 3864 | } |
| 3865 | |
| 3866 | void AudioFlinger::RecordThread::standby() |
| 3867 | { |
| 3868 | if (!mStandby) { |
| 3869 | inputStandBy(); |
| 3870 | mStandby = true; |
| 3871 | } |
| 3872 | } |
| 3873 | |
| 3874 | void AudioFlinger::RecordThread::inputStandBy() |
| 3875 | { |
| 3876 | mInput->stream->common.standby(&mInput->stream->common); |
| 3877 | } |
| 3878 | |
| 3879 | sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l( |
| 3880 | const sp<AudioFlinger::Client>& client, |
| 3881 | uint32_t sampleRate, |
| 3882 | audio_format_t format, |
| 3883 | audio_channel_mask_t channelMask, |
| 3884 | size_t frameCount, |
| 3885 | int sessionId, |
| 3886 | IAudioFlinger::track_flags_t flags, |
| 3887 | pid_t tid, |
| 3888 | status_t *status) |
| 3889 | { |
| 3890 | sp<RecordTrack> track; |
| 3891 | status_t lStatus; |
| 3892 | |
| 3893 | lStatus = initCheck(); |
| 3894 | if (lStatus != NO_ERROR) { |
| 3895 | ALOGE("Audio driver not initialized."); |
| 3896 | goto Exit; |
| 3897 | } |
| 3898 | |
| 3899 | // FIXME use flags and tid similar to createTrack_l() |
| 3900 | |
| 3901 | { // scope for mLock |
| 3902 | Mutex::Autolock _l(mLock); |
| 3903 | |
| 3904 | track = new RecordTrack(this, client, sampleRate, |
| 3905 | format, channelMask, frameCount, sessionId); |
| 3906 | |
| 3907 | if (track->getCblk() == 0) { |
| 3908 | lStatus = NO_MEMORY; |
| 3909 | goto Exit; |
| 3910 | } |
| 3911 | mTracks.add(track); |
| 3912 | |
| 3913 | // disable AEC and NS if the device is a BT SCO headset supporting those pre processings |
| 3914 | bool suspend = audio_is_bluetooth_sco_device(mInDevice) && |
| 3915 | mAudioFlinger->btNrecIsOff(); |
| 3916 | setEffectSuspended_l(FX_IID_AEC, suspend, sessionId); |
| 3917 | setEffectSuspended_l(FX_IID_NS, suspend, sessionId); |
| 3918 | } |
| 3919 | lStatus = NO_ERROR; |
| 3920 | |
| 3921 | Exit: |
| 3922 | if (status) { |
| 3923 | *status = lStatus; |
| 3924 | } |
| 3925 | return track; |
| 3926 | } |
| 3927 | |
| 3928 | status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack, |
| 3929 | AudioSystem::sync_event_t event, |
| 3930 | int triggerSession) |
| 3931 | { |
| 3932 | ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession); |
| 3933 | sp<ThreadBase> strongMe = this; |
| 3934 | status_t status = NO_ERROR; |
| 3935 | |
| 3936 | if (event == AudioSystem::SYNC_EVENT_NONE) { |
| 3937 | clearSyncStartEvent(); |
| 3938 | } else if (event != AudioSystem::SYNC_EVENT_SAME) { |
| 3939 | mSyncStartEvent = mAudioFlinger->createSyncEvent(event, |
| 3940 | triggerSession, |
| 3941 | recordTrack->sessionId(), |
| 3942 | syncStartEventCallback, |
| 3943 | this); |
| 3944 | // Sync event can be cancelled by the trigger session if the track is not in a |
| 3945 | // compatible state in which case we start record immediately |
| 3946 | if (mSyncStartEvent->isCancelled()) { |
| 3947 | clearSyncStartEvent(); |
| 3948 | } else { |
| 3949 | // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs |
| 3950 | mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000); |
| 3951 | } |
| 3952 | } |
| 3953 | |
| 3954 | { |
| 3955 | AutoMutex lock(mLock); |
| 3956 | if (mActiveTrack != 0) { |
| 3957 | if (recordTrack != mActiveTrack.get()) { |
| 3958 | status = -EBUSY; |
| 3959 | } else if (mActiveTrack->mState == TrackBase::PAUSING) { |
| 3960 | mActiveTrack->mState = TrackBase::ACTIVE; |
| 3961 | } |
| 3962 | return status; |
| 3963 | } |
| 3964 | |
| 3965 | recordTrack->mState = TrackBase::IDLE; |
| 3966 | mActiveTrack = recordTrack; |
| 3967 | mLock.unlock(); |
| 3968 | status_t status = AudioSystem::startInput(mId); |
| 3969 | mLock.lock(); |
| 3970 | if (status != NO_ERROR) { |
| 3971 | mActiveTrack.clear(); |
| 3972 | clearSyncStartEvent(); |
| 3973 | return status; |
| 3974 | } |
| 3975 | mRsmpInIndex = mFrameCount; |
| 3976 | mBytesRead = 0; |
| 3977 | if (mResampler != NULL) { |
| 3978 | mResampler->reset(); |
| 3979 | } |
| 3980 | mActiveTrack->mState = TrackBase::RESUMING; |
| 3981 | // signal thread to start |
| 3982 | ALOGV("Signal record thread"); |
| 3983 | mWaitWorkCV.broadcast(); |
| 3984 | // do not wait for mStartStopCond if exiting |
| 3985 | if (exitPending()) { |
| 3986 | mActiveTrack.clear(); |
| 3987 | status = INVALID_OPERATION; |
| 3988 | goto startError; |
| 3989 | } |
| 3990 | mStartStopCond.wait(mLock); |
| 3991 | if (mActiveTrack == 0) { |
| 3992 | ALOGV("Record failed to start"); |
| 3993 | status = BAD_VALUE; |
| 3994 | goto startError; |
| 3995 | } |
| 3996 | ALOGV("Record started OK"); |
| 3997 | return status; |
| 3998 | } |
Glenn Kasten | 7c02724 | 2012-12-26 14:43:16 -0800 | [diff] [blame] | 3999 | |
Eric Laurent | 81784c3 | 2012-11-19 14:55:58 -0800 | [diff] [blame] | 4000 | startError: |
| 4001 | AudioSystem::stopInput(mId); |
| 4002 | clearSyncStartEvent(); |
| 4003 | return status; |
| 4004 | } |
| 4005 | |
| 4006 | void AudioFlinger::RecordThread::clearSyncStartEvent() |
| 4007 | { |
| 4008 | if (mSyncStartEvent != 0) { |
| 4009 | mSyncStartEvent->cancel(); |
| 4010 | } |
| 4011 | mSyncStartEvent.clear(); |
| 4012 | mFramestoDrop = 0; |
| 4013 | } |
| 4014 | |
| 4015 | void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event) |
| 4016 | { |
| 4017 | sp<SyncEvent> strongEvent = event.promote(); |
| 4018 | |
| 4019 | if (strongEvent != 0) { |
| 4020 | RecordThread *me = (RecordThread *)strongEvent->cookie(); |
| 4021 | me->handleSyncStartEvent(strongEvent); |
| 4022 | } |
| 4023 | } |
| 4024 | |
| 4025 | void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event) |
| 4026 | { |
| 4027 | if (event == mSyncStartEvent) { |
| 4028 | // TODO: use actual buffer filling status instead of 2 buffers when info is available |
| 4029 | // from audio HAL |
| 4030 | mFramestoDrop = mFrameCount * 2; |
| 4031 | } |
| 4032 | } |
| 4033 | |
| 4034 | bool AudioFlinger::RecordThread::stop_l(RecordThread::RecordTrack* recordTrack) { |
| 4035 | ALOGV("RecordThread::stop"); |
| 4036 | if (recordTrack != mActiveTrack.get() || recordTrack->mState == TrackBase::PAUSING) { |
| 4037 | return false; |
| 4038 | } |
| 4039 | recordTrack->mState = TrackBase::PAUSING; |
| 4040 | // do not wait for mStartStopCond if exiting |
| 4041 | if (exitPending()) { |
| 4042 | return true; |
| 4043 | } |
| 4044 | mStartStopCond.wait(mLock); |
| 4045 | // if we have been restarted, recordTrack == mActiveTrack.get() here |
| 4046 | if (exitPending() || recordTrack != mActiveTrack.get()) { |
| 4047 | ALOGV("Record stopped OK"); |
| 4048 | return true; |
| 4049 | } |
| 4050 | return false; |
| 4051 | } |
| 4052 | |
| 4053 | bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event) const |
| 4054 | { |
| 4055 | return false; |
| 4056 | } |
| 4057 | |
| 4058 | status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event) |
| 4059 | { |
| 4060 | #if 0 // This branch is currently dead code, but is preserved in case it will be needed in future |
| 4061 | if (!isValidSyncEvent(event)) { |
| 4062 | return BAD_VALUE; |
| 4063 | } |
| 4064 | |
| 4065 | int eventSession = event->triggerSession(); |
| 4066 | status_t ret = NAME_NOT_FOUND; |
| 4067 | |
| 4068 | Mutex::Autolock _l(mLock); |
| 4069 | |
| 4070 | for (size_t i = 0; i < mTracks.size(); i++) { |
| 4071 | sp<RecordTrack> track = mTracks[i]; |
| 4072 | if (eventSession == track->sessionId()) { |
| 4073 | (void) track->setSyncEvent(event); |
| 4074 | ret = NO_ERROR; |
| 4075 | } |
| 4076 | } |
| 4077 | return ret; |
| 4078 | #else |
| 4079 | return BAD_VALUE; |
| 4080 | #endif |
| 4081 | } |
| 4082 | |
| 4083 | // destroyTrack_l() must be called with ThreadBase::mLock held |
| 4084 | void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track) |
| 4085 | { |
| 4086 | track->mState = TrackBase::TERMINATED; |
| 4087 | // active tracks are removed by threadLoop() |
| 4088 | if (mActiveTrack != track) { |
| 4089 | removeTrack_l(track); |
| 4090 | } |
| 4091 | } |
| 4092 | |
| 4093 | void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track) |
| 4094 | { |
| 4095 | mTracks.remove(track); |
| 4096 | // need anything related to effects here? |
| 4097 | } |
| 4098 | |
| 4099 | void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args) |
| 4100 | { |
| 4101 | dumpInternals(fd, args); |
| 4102 | dumpTracks(fd, args); |
| 4103 | dumpEffectChains(fd, args); |
| 4104 | } |
| 4105 | |
| 4106 | void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args) |
| 4107 | { |
| 4108 | const size_t SIZE = 256; |
| 4109 | char buffer[SIZE]; |
| 4110 | String8 result; |
| 4111 | |
| 4112 | snprintf(buffer, SIZE, "\nInput thread %p internals\n", this); |
| 4113 | result.append(buffer); |
| 4114 | |
| 4115 | if (mActiveTrack != 0) { |
| 4116 | snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex); |
| 4117 | result.append(buffer); |
| 4118 | snprintf(buffer, SIZE, "In size: %d\n", mInputBytes); |
| 4119 | result.append(buffer); |
| 4120 | snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL)); |
| 4121 | result.append(buffer); |
| 4122 | snprintf(buffer, SIZE, "Out channel count: %u\n", mReqChannelCount); |
| 4123 | result.append(buffer); |
| 4124 | snprintf(buffer, SIZE, "Out sample rate: %u\n", mReqSampleRate); |
| 4125 | result.append(buffer); |
| 4126 | } else { |
| 4127 | result.append("No active record client\n"); |
| 4128 | } |
| 4129 | |
| 4130 | write(fd, result.string(), result.size()); |
| 4131 | |
| 4132 | dumpBase(fd, args); |
| 4133 | } |
| 4134 | |
| 4135 | void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args) |
| 4136 | { |
| 4137 | const size_t SIZE = 256; |
| 4138 | char buffer[SIZE]; |
| 4139 | String8 result; |
| 4140 | |
| 4141 | snprintf(buffer, SIZE, "Input thread %p tracks\n", this); |
| 4142 | result.append(buffer); |
| 4143 | RecordTrack::appendDumpHeader(result); |
| 4144 | for (size_t i = 0; i < mTracks.size(); ++i) { |
| 4145 | sp<RecordTrack> track = mTracks[i]; |
| 4146 | if (track != 0) { |
| 4147 | track->dump(buffer, SIZE); |
| 4148 | result.append(buffer); |
| 4149 | } |
| 4150 | } |
| 4151 | |
| 4152 | if (mActiveTrack != 0) { |
| 4153 | snprintf(buffer, SIZE, "\nInput thread %p active tracks\n", this); |
| 4154 | result.append(buffer); |
| 4155 | RecordTrack::appendDumpHeader(result); |
| 4156 | mActiveTrack->dump(buffer, SIZE); |
| 4157 | result.append(buffer); |
| 4158 | |
| 4159 | } |
| 4160 | write(fd, result.string(), result.size()); |
| 4161 | } |
| 4162 | |
| 4163 | // AudioBufferProvider interface |
| 4164 | status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts) |
| 4165 | { |
| 4166 | size_t framesReq = buffer->frameCount; |
| 4167 | size_t framesReady = mFrameCount - mRsmpInIndex; |
| 4168 | int channelCount; |
| 4169 | |
| 4170 | if (framesReady == 0) { |
| 4171 | mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes); |
| 4172 | if (mBytesRead <= 0) { |
| 4173 | if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE)) { |
| 4174 | ALOGE("RecordThread::getNextBuffer() Error reading audio input"); |
| 4175 | // Force input into standby so that it tries to |
| 4176 | // recover at next read attempt |
| 4177 | inputStandBy(); |
| 4178 | usleep(kRecordThreadSleepUs); |
| 4179 | } |
| 4180 | buffer->raw = NULL; |
| 4181 | buffer->frameCount = 0; |
| 4182 | return NOT_ENOUGH_DATA; |
| 4183 | } |
| 4184 | mRsmpInIndex = 0; |
| 4185 | framesReady = mFrameCount; |
| 4186 | } |
| 4187 | |
| 4188 | if (framesReq > framesReady) { |
| 4189 | framesReq = framesReady; |
| 4190 | } |
| 4191 | |
| 4192 | if (mChannelCount == 1 && mReqChannelCount == 2) { |
| 4193 | channelCount = 1; |
| 4194 | } else { |
| 4195 | channelCount = 2; |
| 4196 | } |
| 4197 | buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount; |
| 4198 | buffer->frameCount = framesReq; |
| 4199 | return NO_ERROR; |
| 4200 | } |
| 4201 | |
| 4202 | // AudioBufferProvider interface |
| 4203 | void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer) |
| 4204 | { |
| 4205 | mRsmpInIndex += buffer->frameCount; |
| 4206 | buffer->frameCount = 0; |
| 4207 | } |
| 4208 | |
| 4209 | bool AudioFlinger::RecordThread::checkForNewParameters_l() |
| 4210 | { |
| 4211 | bool reconfig = false; |
| 4212 | |
| 4213 | while (!mNewParameters.isEmpty()) { |
| 4214 | status_t status = NO_ERROR; |
| 4215 | String8 keyValuePair = mNewParameters[0]; |
| 4216 | AudioParameter param = AudioParameter(keyValuePair); |
| 4217 | int value; |
| 4218 | audio_format_t reqFormat = mFormat; |
| 4219 | uint32_t reqSamplingRate = mReqSampleRate; |
| 4220 | uint32_t reqChannelCount = mReqChannelCount; |
| 4221 | |
| 4222 | if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) { |
| 4223 | reqSamplingRate = value; |
| 4224 | reconfig = true; |
| 4225 | } |
| 4226 | if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) { |
| 4227 | reqFormat = (audio_format_t) value; |
| 4228 | reconfig = true; |
| 4229 | } |
| 4230 | if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) { |
| 4231 | reqChannelCount = popcount(value); |
| 4232 | reconfig = true; |
| 4233 | } |
| 4234 | if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) { |
| 4235 | // do not accept frame count changes if tracks are open as the track buffer |
| 4236 | // size depends on frame count and correct behavior would not be guaranteed |
| 4237 | // if frame count is changed after track creation |
| 4238 | if (mActiveTrack != 0) { |
| 4239 | status = INVALID_OPERATION; |
| 4240 | } else { |
| 4241 | reconfig = true; |
| 4242 | } |
| 4243 | } |
| 4244 | if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) { |
| 4245 | // forward device change to effects that have requested to be |
| 4246 | // aware of attached audio device. |
| 4247 | for (size_t i = 0; i < mEffectChains.size(); i++) { |
| 4248 | mEffectChains[i]->setDevice_l(value); |
| 4249 | } |
| 4250 | |
| 4251 | // store input device and output device but do not forward output device to audio HAL. |
| 4252 | // Note that status is ignored by the caller for output device |
| 4253 | // (see AudioFlinger::setParameters() |
| 4254 | if (audio_is_output_devices(value)) { |
| 4255 | mOutDevice = value; |
| 4256 | status = BAD_VALUE; |
| 4257 | } else { |
| 4258 | mInDevice = value; |
| 4259 | // disable AEC and NS if the device is a BT SCO headset supporting those |
| 4260 | // pre processings |
| 4261 | if (mTracks.size() > 0) { |
| 4262 | bool suspend = audio_is_bluetooth_sco_device(mInDevice) && |
| 4263 | mAudioFlinger->btNrecIsOff(); |
| 4264 | for (size_t i = 0; i < mTracks.size(); i++) { |
| 4265 | sp<RecordTrack> track = mTracks[i]; |
| 4266 | setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId()); |
| 4267 | setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId()); |
| 4268 | } |
| 4269 | } |
| 4270 | } |
| 4271 | } |
| 4272 | if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR && |
| 4273 | mAudioSource != (audio_source_t)value) { |
| 4274 | // forward device change to effects that have requested to be |
| 4275 | // aware of attached audio device. |
| 4276 | for (size_t i = 0; i < mEffectChains.size(); i++) { |
| 4277 | mEffectChains[i]->setAudioSource_l((audio_source_t)value); |
| 4278 | } |
| 4279 | mAudioSource = (audio_source_t)value; |
| 4280 | } |
| 4281 | if (status == NO_ERROR) { |
| 4282 | status = mInput->stream->common.set_parameters(&mInput->stream->common, |
| 4283 | keyValuePair.string()); |
| 4284 | if (status == INVALID_OPERATION) { |
| 4285 | inputStandBy(); |
| 4286 | status = mInput->stream->common.set_parameters(&mInput->stream->common, |
| 4287 | keyValuePair.string()); |
| 4288 | } |
| 4289 | if (reconfig) { |
| 4290 | if (status == BAD_VALUE && |
| 4291 | reqFormat == mInput->stream->common.get_format(&mInput->stream->common) && |
| 4292 | reqFormat == AUDIO_FORMAT_PCM_16_BIT && |
Glenn Kasten | c497431 | 2012-12-14 07:13:28 -0800 | [diff] [blame] | 4293 | (mInput->stream->common.get_sample_rate(&mInput->stream->common) |
Eric Laurent | 81784c3 | 2012-11-19 14:55:58 -0800 | [diff] [blame] | 4294 | <= (2 * reqSamplingRate)) && |
| 4295 | popcount(mInput->stream->common.get_channels(&mInput->stream->common)) |
| 4296 | <= FCC_2 && |
| 4297 | (reqChannelCount <= FCC_2)) { |
| 4298 | status = NO_ERROR; |
| 4299 | } |
| 4300 | if (status == NO_ERROR) { |
| 4301 | readInputParameters(); |
| 4302 | sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED); |
| 4303 | } |
| 4304 | } |
| 4305 | } |
| 4306 | |
| 4307 | mNewParameters.removeAt(0); |
| 4308 | |
| 4309 | mParamStatus = status; |
| 4310 | mParamCond.signal(); |
| 4311 | // wait for condition with time out in case the thread calling ThreadBase::setParameters() |
| 4312 | // already timed out waiting for the status and will never signal the condition. |
| 4313 | mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs); |
| 4314 | } |
| 4315 | return reconfig; |
| 4316 | } |
| 4317 | |
| 4318 | String8 AudioFlinger::RecordThread::getParameters(const String8& keys) |
| 4319 | { |
| 4320 | char *s; |
| 4321 | String8 out_s8 = String8(); |
| 4322 | |
| 4323 | Mutex::Autolock _l(mLock); |
| 4324 | if (initCheck() != NO_ERROR) { |
| 4325 | return out_s8; |
| 4326 | } |
| 4327 | |
| 4328 | s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string()); |
| 4329 | out_s8 = String8(s); |
| 4330 | free(s); |
| 4331 | return out_s8; |
| 4332 | } |
| 4333 | |
| 4334 | void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) { |
| 4335 | AudioSystem::OutputDescriptor desc; |
| 4336 | void *param2 = NULL; |
| 4337 | |
| 4338 | switch (event) { |
| 4339 | case AudioSystem::INPUT_OPENED: |
| 4340 | case AudioSystem::INPUT_CONFIG_CHANGED: |
Glenn Kasten | fad226a | 2013-07-16 17:19:58 -0700 | [diff] [blame^] | 4341 | desc.channelMask = mChannelMask; |
Eric Laurent | 81784c3 | 2012-11-19 14:55:58 -0800 | [diff] [blame] | 4342 | desc.samplingRate = mSampleRate; |
| 4343 | desc.format = mFormat; |
| 4344 | desc.frameCount = mFrameCount; |
| 4345 | desc.latency = 0; |
| 4346 | param2 = &desc; |
| 4347 | break; |
| 4348 | |
| 4349 | case AudioSystem::INPUT_CLOSED: |
| 4350 | default: |
| 4351 | break; |
| 4352 | } |
| 4353 | mAudioFlinger->audioConfigChanged_l(event, mId, param2); |
| 4354 | } |
| 4355 | |
| 4356 | void AudioFlinger::RecordThread::readInputParameters() |
| 4357 | { |
| 4358 | delete mRsmpInBuffer; |
| 4359 | // mRsmpInBuffer is always assigned a new[] below |
| 4360 | delete mRsmpOutBuffer; |
| 4361 | mRsmpOutBuffer = NULL; |
| 4362 | delete mResampler; |
| 4363 | mResampler = NULL; |
| 4364 | |
| 4365 | mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common); |
| 4366 | mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common); |
| 4367 | mChannelCount = (uint16_t)popcount(mChannelMask); |
| 4368 | mFormat = mInput->stream->common.get_format(&mInput->stream->common); |
| 4369 | mFrameSize = audio_stream_frame_size(&mInput->stream->common); |
| 4370 | mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common); |
| 4371 | mFrameCount = mInputBytes / mFrameSize; |
| 4372 | mNormalFrameCount = mFrameCount; // not used by record, but used by input effects |
| 4373 | mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount]; |
| 4374 | |
| 4375 | if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2) |
| 4376 | { |
| 4377 | int channelCount; |
| 4378 | // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid |
| 4379 | // stereo to mono post process as the resampler always outputs stereo. |
| 4380 | if (mChannelCount == 1 && mReqChannelCount == 2) { |
| 4381 | channelCount = 1; |
| 4382 | } else { |
| 4383 | channelCount = 2; |
| 4384 | } |
| 4385 | mResampler = AudioResampler::create(16, channelCount, mReqSampleRate); |
| 4386 | mResampler->setSampleRate(mSampleRate); |
| 4387 | mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN); |
| 4388 | mRsmpOutBuffer = new int32_t[mFrameCount * 2]; |
| 4389 | |
| 4390 | // optmization: if mono to mono, alter input frame count as if we were inputing |
| 4391 | // stereo samples |
| 4392 | if (mChannelCount == 1 && mReqChannelCount == 1) { |
| 4393 | mFrameCount >>= 1; |
| 4394 | } |
| 4395 | |
| 4396 | } |
| 4397 | mRsmpInIndex = mFrameCount; |
| 4398 | } |
| 4399 | |
| 4400 | unsigned int AudioFlinger::RecordThread::getInputFramesLost() |
| 4401 | { |
| 4402 | Mutex::Autolock _l(mLock); |
| 4403 | if (initCheck() != NO_ERROR) { |
| 4404 | return 0; |
| 4405 | } |
| 4406 | |
| 4407 | return mInput->stream->get_input_frames_lost(mInput->stream); |
| 4408 | } |
| 4409 | |
| 4410 | uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const |
| 4411 | { |
| 4412 | Mutex::Autolock _l(mLock); |
| 4413 | uint32_t result = 0; |
| 4414 | if (getEffectChain_l(sessionId) != 0) { |
| 4415 | result = EFFECT_SESSION; |
| 4416 | } |
| 4417 | |
| 4418 | for (size_t i = 0; i < mTracks.size(); ++i) { |
| 4419 | if (sessionId == mTracks[i]->sessionId()) { |
| 4420 | result |= TRACK_SESSION; |
| 4421 | break; |
| 4422 | } |
| 4423 | } |
| 4424 | |
| 4425 | return result; |
| 4426 | } |
| 4427 | |
| 4428 | KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const |
| 4429 | { |
| 4430 | KeyedVector<int, bool> ids; |
| 4431 | Mutex::Autolock _l(mLock); |
| 4432 | for (size_t j = 0; j < mTracks.size(); ++j) { |
| 4433 | sp<RecordThread::RecordTrack> track = mTracks[j]; |
| 4434 | int sessionId = track->sessionId(); |
| 4435 | if (ids.indexOfKey(sessionId) < 0) { |
| 4436 | ids.add(sessionId, true); |
| 4437 | } |
| 4438 | } |
| 4439 | return ids; |
| 4440 | } |
| 4441 | |
| 4442 | AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput() |
| 4443 | { |
| 4444 | Mutex::Autolock _l(mLock); |
| 4445 | AudioStreamIn *input = mInput; |
| 4446 | mInput = NULL; |
| 4447 | return input; |
| 4448 | } |
| 4449 | |
| 4450 | // this method must always be called either with ThreadBase mLock held or inside the thread loop |
| 4451 | audio_stream_t* AudioFlinger::RecordThread::stream() const |
| 4452 | { |
| 4453 | if (mInput == NULL) { |
| 4454 | return NULL; |
| 4455 | } |
| 4456 | return &mInput->stream->common; |
| 4457 | } |
| 4458 | |
| 4459 | status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain) |
| 4460 | { |
| 4461 | // only one chain per input thread |
| 4462 | if (mEffectChains.size() != 0) { |
| 4463 | return INVALID_OPERATION; |
| 4464 | } |
| 4465 | ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this); |
| 4466 | |
| 4467 | chain->setInBuffer(NULL); |
| 4468 | chain->setOutBuffer(NULL); |
| 4469 | |
| 4470 | checkSuspendOnAddEffectChain_l(chain); |
| 4471 | |
| 4472 | mEffectChains.add(chain); |
| 4473 | |
| 4474 | return NO_ERROR; |
| 4475 | } |
| 4476 | |
| 4477 | size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain) |
| 4478 | { |
| 4479 | ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this); |
| 4480 | ALOGW_IF(mEffectChains.size() != 1, |
| 4481 | "removeEffectChain_l() %p invalid chain size %d on thread %p", |
| 4482 | chain.get(), mEffectChains.size(), this); |
| 4483 | if (mEffectChains.size() == 1) { |
| 4484 | mEffectChains.removeAt(0); |
| 4485 | } |
| 4486 | return 0; |
| 4487 | } |
| 4488 | |
| 4489 | }; // namespace android |