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