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