1 /*
2 **
3 ** Copyright 2007, 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
21
22 #include <math.h>
23 #include <signal.h>
24 #include <sys/time.h>
25 #include <sys/resource.h>
26
27 #include <binder/IPCThreadState.h>
28 #include <binder/IServiceManager.h>
29 #include <utils/Log.h>
30 #include <utils/Trace.h>
31 #include <binder/Parcel.h>
32 #include <binder/IPCThreadState.h>
33 #include <utils/String16.h>
34 #include <utils/threads.h>
35 #include <utils/Atomic.h>
36
37 #include <cutils/bitops.h>
38 #include <cutils/properties.h>
39 #include <cutils/compiler.h>
40
41 #undef ADD_BATTERY_DATA
42
43 #ifdef ADD_BATTERY_DATA
44 #include <media/IMediaPlayerService.h>
45 #include <media/IMediaDeathNotifier.h>
46 #endif
47
48 #include <private/media/AudioTrackShared.h>
49 #include <private/media/AudioEffectShared.h>
50
51 #include <system/audio.h>
52 #include <hardware/audio.h>
53
54 #include "AudioMixer.h"
55 #include "AudioFlinger.h"
56 #include "ServiceUtilities.h"
57
58 #include <media/EffectsFactoryApi.h>
59 #include <audio_effects/effect_visualizer.h>
60 #include <audio_effects/effect_ns.h>
61 #include <audio_effects/effect_aec.h>
62
63 #include <audio_utils/primitives.h>
64
65 #include <powermanager/PowerManager.h>
66
67 // #define DEBUG_CPU_USAGE 10 // log statistics every n wall clock seconds
68 #ifdef DEBUG_CPU_USAGE
69 #include <cpustats/CentralTendencyStatistics.h>
70 #include <cpustats/ThreadCpuUsage.h>
71 #endif
72
73 #include <common_time/cc_helper.h>
74 #include <common_time/local_clock.h>
75
76 #include "FastMixer.h"
77
78 // NBAIO implementations
79 #include "AudioStreamOutSink.h"
80 #include "MonoPipe.h"
81 #include "MonoPipeReader.h"
82 #include "Pipe.h"
83 #include "PipeReader.h"
84 #include "SourceAudioBufferProvider.h"
85
86 #ifdef HAVE_REQUEST_PRIORITY
87 #include "SchedulingPolicyService.h"
88 #endif
89
90 #ifdef SOAKER
91 #include "Soaker.h"
92 #endif
93
94 // ----------------------------------------------------------------------------
95
96 // Note: the following macro is used for extremely verbose logging message. In
97 // order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
98 // 0; but one side effect of this is to turn all LOGV's as well. Some messages
99 // are so verbose that we want to suppress them even when we have ALOG_ASSERT
100 // turned on. Do not uncomment the #def below unless you really know what you
101 // are doing and want to see all of the extremely verbose messages.
102 //#define VERY_VERY_VERBOSE_LOGGING
103 #ifdef VERY_VERY_VERBOSE_LOGGING
104 #define ALOGVV ALOGV
105 #else
106 #define ALOGVV(a...) do { } while(0)
107 #endif
108
109 namespace android {
110
111 static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
112 static const char kHardwareLockedString[] = "Hardware lock is taken\n";
113
114 static const float MAX_GAIN = 4096.0f;
115 static const uint32_t MAX_GAIN_INT = 0x1000;
116
117 // retry counts for buffer fill timeout
118 // 50 * ~20msecs = 1 second
119 static const int8_t kMaxTrackRetries = 50;
120 static const int8_t kMaxTrackStartupRetries = 50;
121 // allow less retry attempts on direct output thread.
122 // direct outputs can be a scarce resource in audio hardware and should
123 // be released as quickly as possible.
124 static const int8_t kMaxTrackRetriesDirect = 2;
125
126 static const int kDumpLockRetries = 50;
127 static const int kDumpLockSleepUs = 20000;
128
129 // don't warn about blocked writes or record buffer overflows more often than this
130 static const nsecs_t kWarningThrottleNs = seconds(5);
131
132 // RecordThread loop sleep time upon application overrun or audio HAL read error
133 static const int kRecordThreadSleepUs = 5000;
134
135 // maximum time to wait for setParameters to complete
136 static const nsecs_t kSetParametersTimeoutNs = seconds(2);
137
138 // minimum sleep time for the mixer thread loop when tracks are active but in underrun
139 static const uint32_t kMinThreadSleepTimeUs = 5000;
140 // maximum divider applied to the active sleep time in the mixer thread loop
141 static const uint32_t kMaxThreadSleepTimeShift = 2;
142
143 // minimum normal mix buffer size, expressed in milliseconds rather than frames
144 static const uint32_t kMinNormalMixBufferSizeMs = 20;
145 // maximum normal mix buffer size
146 static const uint32_t kMaxNormalMixBufferSizeMs = 24;
147
148 nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
149
150 // Whether to use fast mixer
151 static const enum {
152 FastMixer_Never, // never initialize or use: for debugging only
153 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
154 // normal mixer multiplier is 1
155 FastMixer_Static, // initialize if needed, then use all the time if initialized,
156 // multiplier is calculated based on min & max normal mixer buffer size
157 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
158 // multiplier is calculated based on min & max normal mixer buffer size
159 // FIXME for FastMixer_Dynamic:
160 // Supporting this option will require fixing HALs that can't handle large writes.
161 // For example, one HAL implementation returns an error from a large write,
162 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
163 // We could either fix the HAL implementations, or provide a wrapper that breaks
164 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
165 } kUseFastMixer = FastMixer_Static;
166
167 static uint32_t gScreenState; // incremented by 2 when screen state changes, bit 0 == 1 means "off"
168 // AudioFlinger::setParameters() updates, other threads read w/o lock
169
170 // ----------------------------------------------------------------------------
171
172 #ifdef ADD_BATTERY_DATA
173 // To collect the amplifier usage
addBatteryData(uint32_t params)174 static void addBatteryData(uint32_t params) {
175 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
176 if (service == NULL) {
177 // it already logged
178 return;
179 }
180
181 service->addBatteryData(params);
182 }
183 #endif
184
load_audio_interface(const char * if_name,audio_hw_device_t ** dev)185 static int load_audio_interface(const char *if_name, audio_hw_device_t **dev)
186 {
187 const hw_module_t *mod;
188 int rc;
189
190 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, &mod);
191 ALOGE_IF(rc, "%s couldn't load audio hw module %s.%s (%s)", __func__,
192 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
193 if (rc) {
194 goto out;
195 }
196 rc = audio_hw_device_open(mod, dev);
197 ALOGE_IF(rc, "%s couldn't open audio hw device in %s.%s (%s)", __func__,
198 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
199 if (rc) {
200 goto out;
201 }
202 if ((*dev)->common.version != AUDIO_DEVICE_API_VERSION_CURRENT) {
203 ALOGE("%s wrong audio hw device version %04x", __func__, (*dev)->common.version);
204 rc = BAD_VALUE;
205 goto out;
206 }
207 return 0;
208
209 out:
210 *dev = NULL;
211 return rc;
212 }
213
214 // ----------------------------------------------------------------------------
215
AudioFlinger()216 AudioFlinger::AudioFlinger()
217 : BnAudioFlinger(),
218 mPrimaryHardwareDev(NULL),
219 mHardwareStatus(AUDIO_HW_IDLE), // see also onFirstRef()
220 mMasterVolume(1.0f),
221 mMasterVolumeSupportLvl(MVS_NONE),
222 mMasterMute(false),
223 mNextUniqueId(1),
224 mMode(AUDIO_MODE_INVALID),
225 mBtNrecIsOff(false)
226 {
227 }
228
onFirstRef()229 void AudioFlinger::onFirstRef()
230 {
231 int rc = 0;
232
233 Mutex::Autolock _l(mLock);
234
235 /* TODO: move all this work into an Init() function */
236 char val_str[PROPERTY_VALUE_MAX] = { 0 };
237 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
238 uint32_t int_val;
239 if (1 == sscanf(val_str, "%u", &int_val)) {
240 mStandbyTimeInNsecs = milliseconds(int_val);
241 ALOGI("Using %u mSec as standby time.", int_val);
242 } else {
243 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
244 ALOGI("Using default %u mSec as standby time.",
245 (uint32_t)(mStandbyTimeInNsecs / 1000000));
246 }
247 }
248
249 mMode = AUDIO_MODE_NORMAL;
250 mMasterVolumeSW = 1.0;
251 mMasterVolume = 1.0;
252 mHardwareStatus = AUDIO_HW_IDLE;
253 }
254
~AudioFlinger()255 AudioFlinger::~AudioFlinger()
256 {
257
258 while (!mRecordThreads.isEmpty()) {
259 // closeInput() will remove first entry from mRecordThreads
260 closeInput(mRecordThreads.keyAt(0));
261 }
262 while (!mPlaybackThreads.isEmpty()) {
263 // closeOutput() will remove first entry from mPlaybackThreads
264 closeOutput(mPlaybackThreads.keyAt(0));
265 }
266
267 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
268 // no mHardwareLock needed, as there are no other references to this
269 audio_hw_device_close(mAudioHwDevs.valueAt(i)->hwDevice());
270 delete mAudioHwDevs.valueAt(i);
271 }
272 }
273
274 static const char * const audio_interfaces[] = {
275 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
276 AUDIO_HARDWARE_MODULE_ID_A2DP,
277 AUDIO_HARDWARE_MODULE_ID_USB,
278 };
279 #define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
280
findSuitableHwDev_l(audio_module_handle_t module,uint32_t devices)281 audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(audio_module_handle_t module, uint32_t devices)
282 {
283 // if module is 0, the request comes from an old policy manager and we should load
284 // well known modules
285 if (module == 0) {
286 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
287 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
288 loadHwModule_l(audio_interfaces[i]);
289 }
290 } else {
291 // check a match for the requested module handle
292 AudioHwDevice *audioHwdevice = mAudioHwDevs.valueFor(module);
293 if (audioHwdevice != NULL) {
294 return audioHwdevice->hwDevice();
295 }
296 }
297 // then try to find a module supporting the requested device.
298 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
299 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
300 if ((dev->get_supported_devices(dev) & devices) == devices)
301 return dev;
302 }
303
304 return NULL;
305 }
306
dumpClients(int fd,const Vector<String16> & args)307 status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
308 {
309 const size_t SIZE = 256;
310 char buffer[SIZE];
311 String8 result;
312
313 result.append("Clients:\n");
314 for (size_t i = 0; i < mClients.size(); ++i) {
315 sp<Client> client = mClients.valueAt(i).promote();
316 if (client != 0) {
317 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
318 result.append(buffer);
319 }
320 }
321
322 result.append("Global session refs:\n");
323 result.append(" session pid count\n");
324 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
325 AudioSessionRef *r = mAudioSessionRefs[i];
326 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->mSessionid, r->mPid, r->mCnt);
327 result.append(buffer);
328 }
329 write(fd, result.string(), result.size());
330 return NO_ERROR;
331 }
332
333
dumpInternals(int fd,const Vector<String16> & args)334 status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
335 {
336 const size_t SIZE = 256;
337 char buffer[SIZE];
338 String8 result;
339 hardware_call_state hardwareStatus = mHardwareStatus;
340
341 snprintf(buffer, SIZE, "Hardware status: %d\n"
342 "Standby Time mSec: %u\n",
343 hardwareStatus,
344 (uint32_t)(mStandbyTimeInNsecs / 1000000));
345 result.append(buffer);
346 write(fd, result.string(), result.size());
347 return NO_ERROR;
348 }
349
dumpPermissionDenial(int fd,const Vector<String16> & args)350 status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
351 {
352 const size_t SIZE = 256;
353 char buffer[SIZE];
354 String8 result;
355 snprintf(buffer, SIZE, "Permission Denial: "
356 "can't dump AudioFlinger from pid=%d, uid=%d\n",
357 IPCThreadState::self()->getCallingPid(),
358 IPCThreadState::self()->getCallingUid());
359 result.append(buffer);
360 write(fd, result.string(), result.size());
361 return NO_ERROR;
362 }
363
tryLock(Mutex & mutex)364 static bool tryLock(Mutex& mutex)
365 {
366 bool locked = false;
367 for (int i = 0; i < kDumpLockRetries; ++i) {
368 if (mutex.tryLock() == NO_ERROR) {
369 locked = true;
370 break;
371 }
372 usleep(kDumpLockSleepUs);
373 }
374 return locked;
375 }
376
dump(int fd,const Vector<String16> & args)377 status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
378 {
379 if (!dumpAllowed()) {
380 dumpPermissionDenial(fd, args);
381 } else {
382 // get state of hardware lock
383 bool hardwareLocked = tryLock(mHardwareLock);
384 if (!hardwareLocked) {
385 String8 result(kHardwareLockedString);
386 write(fd, result.string(), result.size());
387 } else {
388 mHardwareLock.unlock();
389 }
390
391 bool locked = tryLock(mLock);
392
393 // failed to lock - AudioFlinger is probably deadlocked
394 if (!locked) {
395 String8 result(kDeadlockedString);
396 write(fd, result.string(), result.size());
397 }
398
399 dumpClients(fd, args);
400 dumpInternals(fd, args);
401
402 // dump playback threads
403 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
404 mPlaybackThreads.valueAt(i)->dump(fd, args);
405 }
406
407 // dump record threads
408 for (size_t i = 0; i < mRecordThreads.size(); i++) {
409 mRecordThreads.valueAt(i)->dump(fd, args);
410 }
411
412 // dump all hardware devs
413 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
414 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
415 dev->dump(dev, fd);
416 }
417 if (locked) mLock.unlock();
418 }
419 return NO_ERROR;
420 }
421
registerPid_l(pid_t pid)422 sp<AudioFlinger::Client> AudioFlinger::registerPid_l(pid_t pid)
423 {
424 // If pid is already in the mClients wp<> map, then use that entry
425 // (for which promote() is always != 0), otherwise create a new entry and Client.
426 sp<Client> client = mClients.valueFor(pid).promote();
427 if (client == 0) {
428 client = new Client(this, pid);
429 mClients.add(pid, client);
430 }
431
432 return client;
433 }
434
435 // IAudioFlinger interface
436
437
createTrack(pid_t pid,audio_stream_type_t streamType,uint32_t sampleRate,audio_format_t format,uint32_t channelMask,int frameCount,IAudioFlinger::track_flags_t flags,const sp<IMemory> & sharedBuffer,audio_io_handle_t output,pid_t tid,int * sessionId,status_t * status)438 sp<IAudioTrack> AudioFlinger::createTrack(
439 pid_t pid,
440 audio_stream_type_t streamType,
441 uint32_t sampleRate,
442 audio_format_t format,
443 uint32_t channelMask,
444 int frameCount,
445 IAudioFlinger::track_flags_t flags,
446 const sp<IMemory>& sharedBuffer,
447 audio_io_handle_t output,
448 pid_t tid,
449 int *sessionId,
450 status_t *status)
451 {
452 sp<PlaybackThread::Track> track;
453 sp<TrackHandle> trackHandle;
454 sp<Client> client;
455 status_t lStatus;
456 int lSessionId;
457
458 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
459 // but if someone uses binder directly they could bypass that and cause us to crash
460 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
461 ALOGE("createTrack() invalid stream type %d", streamType);
462 lStatus = BAD_VALUE;
463 goto Exit;
464 }
465
466 {
467 Mutex::Autolock _l(mLock);
468 PlaybackThread *thread = checkPlaybackThread_l(output);
469 PlaybackThread *effectThread = NULL;
470 if (thread == NULL) {
471 ALOGE("unknown output thread");
472 lStatus = BAD_VALUE;
473 goto Exit;
474 }
475
476 client = registerPid_l(pid);
477
478 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
479 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
480 // check if an effect chain with the same session ID is present on another
481 // output thread and move it here.
482 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
483 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
484 if (mPlaybackThreads.keyAt(i) != output) {
485 uint32_t sessions = t->hasAudioSession(*sessionId);
486 if (sessions & PlaybackThread::EFFECT_SESSION) {
487 effectThread = t.get();
488 break;
489 }
490 }
491 }
492 lSessionId = *sessionId;
493 } else {
494 // if no audio session id is provided, create one here
495 lSessionId = nextUniqueId();
496 if (sessionId != NULL) {
497 *sessionId = lSessionId;
498 }
499 }
500 ALOGV("createTrack() lSessionId: %d", lSessionId);
501
502 track = thread->createTrack_l(client, streamType, sampleRate, format,
503 channelMask, frameCount, sharedBuffer, lSessionId, flags, tid, &lStatus);
504
505 // move effect chain to this output thread if an effect on same session was waiting
506 // for a track to be created
507 if (lStatus == NO_ERROR && effectThread != NULL) {
508 Mutex::Autolock _dl(thread->mLock);
509 Mutex::Autolock _sl(effectThread->mLock);
510 moveEffectChain_l(lSessionId, effectThread, thread, true);
511 }
512
513 // Look for sync events awaiting for a session to be used.
514 for (int i = 0; i < (int)mPendingSyncEvents.size(); i++) {
515 if (mPendingSyncEvents[i]->triggerSession() == lSessionId) {
516 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
517 if (lStatus == NO_ERROR) {
518 track->setSyncEvent(mPendingSyncEvents[i]);
519 } else {
520 mPendingSyncEvents[i]->cancel();
521 }
522 mPendingSyncEvents.removeAt(i);
523 i--;
524 }
525 }
526 }
527 }
528 if (lStatus == NO_ERROR) {
529 trackHandle = new TrackHandle(track);
530 } else {
531 // remove local strong reference to Client before deleting the Track so that the Client
532 // destructor is called by the TrackBase destructor with mLock held
533 client.clear();
534 track.clear();
535 }
536
537 Exit:
538 if (status != NULL) {
539 *status = lStatus;
540 }
541 return trackHandle;
542 }
543
sampleRate(audio_io_handle_t output) const544 uint32_t AudioFlinger::sampleRate(audio_io_handle_t output) const
545 {
546 Mutex::Autolock _l(mLock);
547 PlaybackThread *thread = checkPlaybackThread_l(output);
548 if (thread == NULL) {
549 ALOGW("sampleRate() unknown thread %d", output);
550 return 0;
551 }
552 return thread->sampleRate();
553 }
554
channelCount(audio_io_handle_t output) const555 int AudioFlinger::channelCount(audio_io_handle_t output) const
556 {
557 Mutex::Autolock _l(mLock);
558 PlaybackThread *thread = checkPlaybackThread_l(output);
559 if (thread == NULL) {
560 ALOGW("channelCount() unknown thread %d", output);
561 return 0;
562 }
563 return thread->channelCount();
564 }
565
format(audio_io_handle_t output) const566 audio_format_t AudioFlinger::format(audio_io_handle_t output) const
567 {
568 Mutex::Autolock _l(mLock);
569 PlaybackThread *thread = checkPlaybackThread_l(output);
570 if (thread == NULL) {
571 ALOGW("format() unknown thread %d", output);
572 return AUDIO_FORMAT_INVALID;
573 }
574 return thread->format();
575 }
576
frameCount(audio_io_handle_t output) const577 size_t AudioFlinger::frameCount(audio_io_handle_t output) const
578 {
579 Mutex::Autolock _l(mLock);
580 PlaybackThread *thread = checkPlaybackThread_l(output);
581 if (thread == NULL) {
582 ALOGW("frameCount() unknown thread %d", output);
583 return 0;
584 }
585 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
586 // should examine all callers and fix them to handle smaller counts
587 return thread->frameCount();
588 }
589
latency(audio_io_handle_t output) const590 uint32_t AudioFlinger::latency(audio_io_handle_t output) const
591 {
592 Mutex::Autolock _l(mLock);
593 PlaybackThread *thread = checkPlaybackThread_l(output);
594 if (thread == NULL) {
595 ALOGW("latency() unknown thread %d", output);
596 return 0;
597 }
598 return thread->latency();
599 }
600
setMasterVolume(float value)601 status_t AudioFlinger::setMasterVolume(float value)
602 {
603 status_t ret = initCheck();
604 if (ret != NO_ERROR) {
605 return ret;
606 }
607
608 // check calling permissions
609 if (!settingsAllowed()) {
610 return PERMISSION_DENIED;
611 }
612
613 float swmv = value;
614
615 Mutex::Autolock _l(mLock);
616
617 // when hw supports master volume, don't scale in sw mixer
618 if (MVS_NONE != mMasterVolumeSupportLvl) {
619 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
620 AutoMutex lock(mHardwareLock);
621 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
622
623 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
624 if (NULL != dev->set_master_volume) {
625 dev->set_master_volume(dev, value);
626 }
627 mHardwareStatus = AUDIO_HW_IDLE;
628 }
629
630 swmv = 1.0;
631 }
632
633 mMasterVolume = value;
634 mMasterVolumeSW = swmv;
635 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
636 mPlaybackThreads.valueAt(i)->setMasterVolume(swmv);
637
638 return NO_ERROR;
639 }
640
setMode(audio_mode_t mode)641 status_t AudioFlinger::setMode(audio_mode_t mode)
642 {
643 status_t ret = initCheck();
644 if (ret != NO_ERROR) {
645 return ret;
646 }
647
648 // check calling permissions
649 if (!settingsAllowed()) {
650 return PERMISSION_DENIED;
651 }
652 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
653 ALOGW("Illegal value: setMode(%d)", mode);
654 return BAD_VALUE;
655 }
656
657 { // scope for the lock
658 AutoMutex lock(mHardwareLock);
659 mHardwareStatus = AUDIO_HW_SET_MODE;
660 ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode);
661 mHardwareStatus = AUDIO_HW_IDLE;
662 }
663
664 if (NO_ERROR == ret) {
665 Mutex::Autolock _l(mLock);
666 mMode = mode;
667 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
668 mPlaybackThreads.valueAt(i)->setMode(mode);
669 }
670
671 return ret;
672 }
673
setMicMute(bool state)674 status_t AudioFlinger::setMicMute(bool state)
675 {
676 status_t ret = initCheck();
677 if (ret != NO_ERROR) {
678 return ret;
679 }
680
681 // check calling permissions
682 if (!settingsAllowed()) {
683 return PERMISSION_DENIED;
684 }
685
686 AutoMutex lock(mHardwareLock);
687 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
688 ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state);
689 mHardwareStatus = AUDIO_HW_IDLE;
690 return ret;
691 }
692
getMicMute() const693 bool AudioFlinger::getMicMute() const
694 {
695 status_t ret = initCheck();
696 if (ret != NO_ERROR) {
697 return false;
698 }
699
700 bool state = AUDIO_MODE_INVALID;
701 AutoMutex lock(mHardwareLock);
702 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
703 mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state);
704 mHardwareStatus = AUDIO_HW_IDLE;
705 return state;
706 }
707
setMasterMute(bool muted)708 status_t AudioFlinger::setMasterMute(bool muted)
709 {
710 // check calling permissions
711 if (!settingsAllowed()) {
712 return PERMISSION_DENIED;
713 }
714
715 Mutex::Autolock _l(mLock);
716 // This is an optimization, so PlaybackThread doesn't have to look at the one from AudioFlinger
717 mMasterMute = muted;
718 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
719 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
720
721 return NO_ERROR;
722 }
723
masterVolume() const724 float AudioFlinger::masterVolume() const
725 {
726 Mutex::Autolock _l(mLock);
727 return masterVolume_l();
728 }
729
masterVolumeSW() const730 float AudioFlinger::masterVolumeSW() const
731 {
732 Mutex::Autolock _l(mLock);
733 return masterVolumeSW_l();
734 }
735
masterMute() const736 bool AudioFlinger::masterMute() const
737 {
738 Mutex::Autolock _l(mLock);
739 return masterMute_l();
740 }
741
masterVolume_l() const742 float AudioFlinger::masterVolume_l() const
743 {
744 if (MVS_FULL == mMasterVolumeSupportLvl) {
745 float ret_val;
746 AutoMutex lock(mHardwareLock);
747
748 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
749 ALOG_ASSERT((NULL != mPrimaryHardwareDev) &&
750 (NULL != mPrimaryHardwareDev->get_master_volume),
751 "can't get master volume");
752
753 mPrimaryHardwareDev->get_master_volume(mPrimaryHardwareDev, &ret_val);
754 mHardwareStatus = AUDIO_HW_IDLE;
755 return ret_val;
756 }
757
758 return mMasterVolume;
759 }
760
setStreamVolume(audio_stream_type_t stream,float value,audio_io_handle_t output)761 status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
762 audio_io_handle_t output)
763 {
764 // check calling permissions
765 if (!settingsAllowed()) {
766 return PERMISSION_DENIED;
767 }
768
769 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
770 ALOGE("setStreamVolume() invalid stream %d", stream);
771 return BAD_VALUE;
772 }
773
774 AutoMutex lock(mLock);
775 PlaybackThread *thread = NULL;
776 if (output) {
777 thread = checkPlaybackThread_l(output);
778 if (thread == NULL) {
779 return BAD_VALUE;
780 }
781 }
782
783 mStreamTypes[stream].volume = value;
784
785 if (thread == NULL) {
786 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
787 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
788 }
789 } else {
790 thread->setStreamVolume(stream, value);
791 }
792
793 return NO_ERROR;
794 }
795
setStreamMute(audio_stream_type_t stream,bool muted)796 status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
797 {
798 // check calling permissions
799 if (!settingsAllowed()) {
800 return PERMISSION_DENIED;
801 }
802
803 if (uint32_t(stream) >= AUDIO_STREAM_CNT ||
804 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
805 ALOGE("setStreamMute() invalid stream %d", stream);
806 return BAD_VALUE;
807 }
808
809 AutoMutex lock(mLock);
810 mStreamTypes[stream].mute = muted;
811 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
812 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
813
814 return NO_ERROR;
815 }
816
streamVolume(audio_stream_type_t stream,audio_io_handle_t output) const817 float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
818 {
819 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
820 return 0.0f;
821 }
822
823 AutoMutex lock(mLock);
824 float volume;
825 if (output) {
826 PlaybackThread *thread = checkPlaybackThread_l(output);
827 if (thread == NULL) {
828 return 0.0f;
829 }
830 volume = thread->streamVolume(stream);
831 } else {
832 volume = streamVolume_l(stream);
833 }
834
835 return volume;
836 }
837
streamMute(audio_stream_type_t stream) const838 bool AudioFlinger::streamMute(audio_stream_type_t stream) const
839 {
840 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
841 return true;
842 }
843
844 AutoMutex lock(mLock);
845 return streamMute_l(stream);
846 }
847
setParameters(audio_io_handle_t ioHandle,const String8 & keyValuePairs)848 status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
849 {
850 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling pid %d",
851 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
852 // check calling permissions
853 if (!settingsAllowed()) {
854 return PERMISSION_DENIED;
855 }
856
857 // ioHandle == 0 means the parameters are global to the audio hardware interface
858 if (ioHandle == 0) {
859 Mutex::Autolock _l(mLock);
860 status_t final_result = NO_ERROR;
861 {
862 AutoMutex lock(mHardwareLock);
863 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
864 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
865 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
866 status_t result = dev->set_parameters(dev, keyValuePairs.string());
867 final_result = result ?: final_result;
868 }
869 mHardwareStatus = AUDIO_HW_IDLE;
870 }
871 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
872 AudioParameter param = AudioParameter(keyValuePairs);
873 String8 value;
874 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
875 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
876 if (mBtNrecIsOff != btNrecIsOff) {
877 for (size_t i = 0; i < mRecordThreads.size(); i++) {
878 sp<RecordThread> thread = mRecordThreads.valueAt(i);
879 RecordThread::RecordTrack *track = thread->track();
880 if (track != NULL) {
881 audio_devices_t device = (audio_devices_t)(
882 thread->device() & AUDIO_DEVICE_IN_ALL);
883 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
884 thread->setEffectSuspended(FX_IID_AEC,
885 suspend,
886 track->sessionId());
887 thread->setEffectSuspended(FX_IID_NS,
888 suspend,
889 track->sessionId());
890 }
891 }
892 mBtNrecIsOff = btNrecIsOff;
893 }
894 }
895 String8 screenState;
896 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
897 bool isOff = screenState == "off";
898 if (isOff != (gScreenState & 1)) {
899 gScreenState = ((gScreenState & ~1) + 2) | isOff;
900 }
901 }
902 return final_result;
903 }
904
905 // hold a strong ref on thread in case closeOutput() or closeInput() is called
906 // and the thread is exited once the lock is released
907 sp<ThreadBase> thread;
908 {
909 Mutex::Autolock _l(mLock);
910 thread = checkPlaybackThread_l(ioHandle);
911 if (thread == NULL) {
912 thread = checkRecordThread_l(ioHandle);
913 } else if (thread == primaryPlaybackThread_l()) {
914 // indicate output device change to all input threads for pre processing
915 AudioParameter param = AudioParameter(keyValuePairs);
916 int value;
917 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
918 (value != 0)) {
919 for (size_t i = 0; i < mRecordThreads.size(); i++) {
920 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
921 }
922 }
923 }
924 }
925 if (thread != 0) {
926 return thread->setParameters(keyValuePairs);
927 }
928 return BAD_VALUE;
929 }
930
getParameters(audio_io_handle_t ioHandle,const String8 & keys) const931 String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
932 {
933 // ALOGV("getParameters() io %d, keys %s, tid %d, calling pid %d",
934 // ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
935
936 Mutex::Autolock _l(mLock);
937
938 if (ioHandle == 0) {
939 String8 out_s8;
940
941 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
942 char *s;
943 {
944 AutoMutex lock(mHardwareLock);
945 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
946 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
947 s = dev->get_parameters(dev, keys.string());
948 mHardwareStatus = AUDIO_HW_IDLE;
949 }
950 out_s8 += String8(s ? s : "");
951 free(s);
952 }
953 return out_s8;
954 }
955
956 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
957 if (playbackThread != NULL) {
958 return playbackThread->getParameters(keys);
959 }
960 RecordThread *recordThread = checkRecordThread_l(ioHandle);
961 if (recordThread != NULL) {
962 return recordThread->getParameters(keys);
963 }
964 return String8("");
965 }
966
getInputBufferSize(uint32_t sampleRate,audio_format_t format,int channelCount) const967 size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format, int channelCount) const
968 {
969 status_t ret = initCheck();
970 if (ret != NO_ERROR) {
971 return 0;
972 }
973
974 AutoMutex lock(mHardwareLock);
975 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
976 struct audio_config config = {
977 sample_rate: sampleRate,
978 channel_mask: audio_channel_in_mask_from_count(channelCount),
979 format: format,
980 };
981 size_t size = mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, &config);
982 mHardwareStatus = AUDIO_HW_IDLE;
983 return size;
984 }
985
getInputFramesLost(audio_io_handle_t ioHandle) const986 unsigned int AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
987 {
988 if (ioHandle == 0) {
989 return 0;
990 }
991
992 Mutex::Autolock _l(mLock);
993
994 RecordThread *recordThread = checkRecordThread_l(ioHandle);
995 if (recordThread != NULL) {
996 return recordThread->getInputFramesLost();
997 }
998 return 0;
999 }
1000
setVoiceVolume(float value)1001 status_t AudioFlinger::setVoiceVolume(float value)
1002 {
1003 status_t ret = initCheck();
1004 if (ret != NO_ERROR) {
1005 return ret;
1006 }
1007
1008 // check calling permissions
1009 if (!settingsAllowed()) {
1010 return PERMISSION_DENIED;
1011 }
1012
1013 AutoMutex lock(mHardwareLock);
1014 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
1015 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
1016 mHardwareStatus = AUDIO_HW_IDLE;
1017
1018 return ret;
1019 }
1020
getRenderPosition(uint32_t * halFrames,uint32_t * dspFrames,audio_io_handle_t output) const1021 status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
1022 audio_io_handle_t output) const
1023 {
1024 status_t status;
1025
1026 Mutex::Autolock _l(mLock);
1027
1028 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1029 if (playbackThread != NULL) {
1030 return playbackThread->getRenderPosition(halFrames, dspFrames);
1031 }
1032
1033 return BAD_VALUE;
1034 }
1035
registerClient(const sp<IAudioFlingerClient> & client)1036 void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1037 {
1038
1039 Mutex::Autolock _l(mLock);
1040
1041 pid_t pid = IPCThreadState::self()->getCallingPid();
1042 if (mNotificationClients.indexOfKey(pid) < 0) {
1043 sp<NotificationClient> notificationClient = new NotificationClient(this,
1044 client,
1045 pid);
1046 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
1047
1048 mNotificationClients.add(pid, notificationClient);
1049
1050 sp<IBinder> binder = client->asBinder();
1051 binder->linkToDeath(notificationClient);
1052
1053 // the config change is always sent from playback or record threads to avoid deadlock
1054 // with AudioSystem::gLock
1055 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1056 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
1057 }
1058
1059 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1060 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
1061 }
1062 }
1063 }
1064
removeNotificationClient(pid_t pid)1065 void AudioFlinger::removeNotificationClient(pid_t pid)
1066 {
1067 Mutex::Autolock _l(mLock);
1068
1069 mNotificationClients.removeItem(pid);
1070
1071 ALOGV("%d died, releasing its sessions", pid);
1072 size_t num = mAudioSessionRefs.size();
1073 bool removed = false;
1074 for (size_t i = 0; i< num; ) {
1075 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
1076 ALOGV(" pid %d @ %d", ref->mPid, i);
1077 if (ref->mPid == pid) {
1078 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
1079 mAudioSessionRefs.removeAt(i);
1080 delete ref;
1081 removed = true;
1082 num--;
1083 } else {
1084 i++;
1085 }
1086 }
1087 if (removed) {
1088 purgeStaleEffects_l();
1089 }
1090 }
1091
1092 // audioConfigChanged_l() must be called with AudioFlinger::mLock held
audioConfigChanged_l(int event,audio_io_handle_t ioHandle,const void * param2)1093 void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, const void *param2)
1094 {
1095 size_t size = mNotificationClients.size();
1096 for (size_t i = 0; i < size; i++) {
1097 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
1098 param2);
1099 }
1100 }
1101
1102 // removeClient_l() must be called with AudioFlinger::mLock held
removeClient_l(pid_t pid)1103 void AudioFlinger::removeClient_l(pid_t pid)
1104 {
1105 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
1106 mClients.removeItem(pid);
1107 }
1108
1109 // getEffectThread_l() must be called with AudioFlinger::mLock held
getEffectThread_l(int sessionId,int EffectId)1110 sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(int sessionId, int EffectId)
1111 {
1112 sp<PlaybackThread> thread;
1113
1114 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1115 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1116 ALOG_ASSERT(thread == 0);
1117 thread = mPlaybackThreads.valueAt(i);
1118 }
1119 }
1120
1121 return thread;
1122 }
1123
1124 // ----------------------------------------------------------------------------
1125
ThreadBase(const sp<AudioFlinger> & audioFlinger,audio_io_handle_t id,uint32_t device,type_t type)1126 AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
1127 uint32_t device, type_t type)
1128 : Thread(false),
1129 mType(type),
1130 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mNormalFrameCount(0),
1131 // mChannelMask
1132 mChannelCount(0),
1133 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
1134 mParamStatus(NO_ERROR),
1135 mStandby(false), mId(id),
1136 mDevice(device),
1137 mDeathRecipient(new PMDeathRecipient(this))
1138 {
1139 }
1140
~ThreadBase()1141 AudioFlinger::ThreadBase::~ThreadBase()
1142 {
1143 mParamCond.broadcast();
1144 // do not lock the mutex in destructor
1145 releaseWakeLock_l();
1146 if (mPowerManager != 0) {
1147 sp<IBinder> binder = mPowerManager->asBinder();
1148 binder->unlinkToDeath(mDeathRecipient);
1149 }
1150 }
1151
exit()1152 void AudioFlinger::ThreadBase::exit()
1153 {
1154 ALOGV("ThreadBase::exit");
1155 {
1156 // This lock prevents the following race in thread (uniprocessor for illustration):
1157 // if (!exitPending()) {
1158 // // context switch from here to exit()
1159 // // exit() calls requestExit(), what exitPending() observes
1160 // // exit() calls signal(), which is dropped since no waiters
1161 // // context switch back from exit() to here
1162 // mWaitWorkCV.wait(...);
1163 // // now thread is hung
1164 // }
1165 AutoMutex lock(mLock);
1166 requestExit();
1167 mWaitWorkCV.signal();
1168 }
1169 // When Thread::requestExitAndWait is made virtual and this method is renamed to
1170 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
1171 requestExitAndWait();
1172 }
1173
setParameters(const String8 & keyValuePairs)1174 status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1175 {
1176 status_t status;
1177
1178 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
1179 Mutex::Autolock _l(mLock);
1180
1181 mNewParameters.add(keyValuePairs);
1182 mWaitWorkCV.signal();
1183 // wait condition with timeout in case the thread loop has exited
1184 // before the request could be processed
1185 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
1186 status = mParamStatus;
1187 mWaitWorkCV.signal();
1188 } else {
1189 status = TIMED_OUT;
1190 }
1191 return status;
1192 }
1193
sendConfigEvent(int event,int param)1194 void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1195 {
1196 Mutex::Autolock _l(mLock);
1197 sendConfigEvent_l(event, param);
1198 }
1199
1200 // sendConfigEvent_l() must be called with ThreadBase::mLock held
sendConfigEvent_l(int event,int param)1201 void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1202 {
1203 ConfigEvent configEvent;
1204 configEvent.mEvent = event;
1205 configEvent.mParam = param;
1206 mConfigEvents.add(configEvent);
1207 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
1208 mWaitWorkCV.signal();
1209 }
1210
processConfigEvents()1211 void AudioFlinger::ThreadBase::processConfigEvents()
1212 {
1213 mLock.lock();
1214 while (!mConfigEvents.isEmpty()) {
1215 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
1216 ConfigEvent configEvent = mConfigEvents[0];
1217 mConfigEvents.removeAt(0);
1218 // release mLock before locking AudioFlinger mLock: lock order is always
1219 // AudioFlinger then ThreadBase to avoid cross deadlock
1220 mLock.unlock();
1221 mAudioFlinger->mLock.lock();
1222 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
1223 mAudioFlinger->mLock.unlock();
1224 mLock.lock();
1225 }
1226 mLock.unlock();
1227 }
1228
dumpBase(int fd,const Vector<String16> & args)1229 status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1230 {
1231 const size_t SIZE = 256;
1232 char buffer[SIZE];
1233 String8 result;
1234
1235 bool locked = tryLock(mLock);
1236 if (!locked) {
1237 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1238 write(fd, buffer, strlen(buffer));
1239 }
1240
1241 snprintf(buffer, SIZE, "io handle: %d\n", mId);
1242 result.append(buffer);
1243 snprintf(buffer, SIZE, "TID: %d\n", getTid());
1244 result.append(buffer);
1245 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1246 result.append(buffer);
1247 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1248 result.append(buffer);
1249 snprintf(buffer, SIZE, "HAL frame count: %d\n", mFrameCount);
1250 result.append(buffer);
1251 snprintf(buffer, SIZE, "Normal frame count: %d\n", mNormalFrameCount);
1252 result.append(buffer);
1253 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1254 result.append(buffer);
1255 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1256 result.append(buffer);
1257 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1258 result.append(buffer);
1259 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
1260 result.append(buffer);
1261
1262 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1263 result.append(buffer);
1264 result.append(" Index Command");
1265 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1266 snprintf(buffer, SIZE, "\n %02d ", i);
1267 result.append(buffer);
1268 result.append(mNewParameters[i]);
1269 }
1270
1271 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1272 result.append(buffer);
1273 snprintf(buffer, SIZE, " Index event param\n");
1274 result.append(buffer);
1275 for (size_t i = 0; i < mConfigEvents.size(); i++) {
1276 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
1277 result.append(buffer);
1278 }
1279 result.append("\n");
1280
1281 write(fd, result.string(), result.size());
1282
1283 if (locked) {
1284 mLock.unlock();
1285 }
1286 return NO_ERROR;
1287 }
1288
dumpEffectChains(int fd,const Vector<String16> & args)1289 status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1290 {
1291 const size_t SIZE = 256;
1292 char buffer[SIZE];
1293 String8 result;
1294
1295 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1296 write(fd, buffer, strlen(buffer));
1297
1298 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1299 sp<EffectChain> chain = mEffectChains[i];
1300 if (chain != 0) {
1301 chain->dump(fd, args);
1302 }
1303 }
1304 return NO_ERROR;
1305 }
1306
acquireWakeLock()1307 void AudioFlinger::ThreadBase::acquireWakeLock()
1308 {
1309 Mutex::Autolock _l(mLock);
1310 acquireWakeLock_l();
1311 }
1312
acquireWakeLock_l()1313 void AudioFlinger::ThreadBase::acquireWakeLock_l()
1314 {
1315 if (mPowerManager == 0) {
1316 // use checkService() to avoid blocking if power service is not up yet
1317 sp<IBinder> binder =
1318 defaultServiceManager()->checkService(String16("power"));
1319 if (binder == 0) {
1320 ALOGW("Thread %s cannot connect to the power manager service", mName);
1321 } else {
1322 mPowerManager = interface_cast<IPowerManager>(binder);
1323 binder->linkToDeath(mDeathRecipient);
1324 }
1325 }
1326 if (mPowerManager != 0) {
1327 sp<IBinder> binder = new BBinder();
1328 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1329 binder,
1330 String16(mName));
1331 if (status == NO_ERROR) {
1332 mWakeLockToken = binder;
1333 }
1334 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
1335 }
1336 }
1337
releaseWakeLock()1338 void AudioFlinger::ThreadBase::releaseWakeLock()
1339 {
1340 Mutex::Autolock _l(mLock);
1341 releaseWakeLock_l();
1342 }
1343
releaseWakeLock_l()1344 void AudioFlinger::ThreadBase::releaseWakeLock_l()
1345 {
1346 if (mWakeLockToken != 0) {
1347 ALOGV("releaseWakeLock_l() %s", mName);
1348 if (mPowerManager != 0) {
1349 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1350 }
1351 mWakeLockToken.clear();
1352 }
1353 }
1354
clearPowerManager()1355 void AudioFlinger::ThreadBase::clearPowerManager()
1356 {
1357 Mutex::Autolock _l(mLock);
1358 releaseWakeLock_l();
1359 mPowerManager.clear();
1360 }
1361
binderDied(const wp<IBinder> & who)1362 void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1363 {
1364 sp<ThreadBase> thread = mThread.promote();
1365 if (thread != 0) {
1366 thread->clearPowerManager();
1367 }
1368 ALOGW("power manager service died !!!");
1369 }
1370
setEffectSuspended(const effect_uuid_t * type,bool suspend,int sessionId)1371 void AudioFlinger::ThreadBase::setEffectSuspended(
1372 const effect_uuid_t *type, bool suspend, int sessionId)
1373 {
1374 Mutex::Autolock _l(mLock);
1375 setEffectSuspended_l(type, suspend, sessionId);
1376 }
1377
setEffectSuspended_l(const effect_uuid_t * type,bool suspend,int sessionId)1378 void AudioFlinger::ThreadBase::setEffectSuspended_l(
1379 const effect_uuid_t *type, bool suspend, int sessionId)
1380 {
1381 sp<EffectChain> chain = getEffectChain_l(sessionId);
1382 if (chain != 0) {
1383 if (type != NULL) {
1384 chain->setEffectSuspended_l(type, suspend);
1385 } else {
1386 chain->setEffectSuspendedAll_l(suspend);
1387 }
1388 }
1389
1390 updateSuspendedSessions_l(type, suspend, sessionId);
1391 }
1392
checkSuspendOnAddEffectChain_l(const sp<EffectChain> & chain)1393 void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1394 {
1395 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1396 if (index < 0) {
1397 return;
1398 }
1399
1400 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1401 mSuspendedSessions.editValueAt(index);
1402
1403 for (size_t i = 0; i < sessionEffects.size(); i++) {
1404 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1405 for (int j = 0; j < desc->mRefCount; j++) {
1406 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1407 chain->setEffectSuspendedAll_l(true);
1408 } else {
1409 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1410 desc->mType.timeLow);
1411 chain->setEffectSuspended_l(&desc->mType, true);
1412 }
1413 }
1414 }
1415 }
1416
updateSuspendedSessions_l(const effect_uuid_t * type,bool suspend,int sessionId)1417 void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1418 bool suspend,
1419 int sessionId)
1420 {
1421 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1422
1423 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1424
1425 if (suspend) {
1426 if (index >= 0) {
1427 sessionEffects = mSuspendedSessions.editValueAt(index);
1428 } else {
1429 mSuspendedSessions.add(sessionId, sessionEffects);
1430 }
1431 } else {
1432 if (index < 0) {
1433 return;
1434 }
1435 sessionEffects = mSuspendedSessions.editValueAt(index);
1436 }
1437
1438
1439 int key = EffectChain::kKeyForSuspendAll;
1440 if (type != NULL) {
1441 key = type->timeLow;
1442 }
1443 index = sessionEffects.indexOfKey(key);
1444
1445 sp<SuspendedSessionDesc> desc;
1446 if (suspend) {
1447 if (index >= 0) {
1448 desc = sessionEffects.valueAt(index);
1449 } else {
1450 desc = new SuspendedSessionDesc();
1451 if (type != NULL) {
1452 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1453 }
1454 sessionEffects.add(key, desc);
1455 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1456 }
1457 desc->mRefCount++;
1458 } else {
1459 if (index < 0) {
1460 return;
1461 }
1462 desc = sessionEffects.valueAt(index);
1463 if (--desc->mRefCount == 0) {
1464 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1465 sessionEffects.removeItemsAt(index);
1466 if (sessionEffects.isEmpty()) {
1467 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1468 sessionId);
1469 mSuspendedSessions.removeItem(sessionId);
1470 }
1471 }
1472 }
1473 if (!sessionEffects.isEmpty()) {
1474 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1475 }
1476 }
1477
checkSuspendOnEffectEnabled(const sp<EffectModule> & effect,bool enabled,int sessionId)1478 void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1479 bool enabled,
1480 int sessionId)
1481 {
1482 Mutex::Autolock _l(mLock);
1483 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1484 }
1485
checkSuspendOnEffectEnabled_l(const sp<EffectModule> & effect,bool enabled,int sessionId)1486 void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1487 bool enabled,
1488 int sessionId)
1489 {
1490 if (mType != RECORD) {
1491 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1492 // another session. This gives the priority to well behaved effect control panels
1493 // and applications not using global effects.
1494 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1495 // global effects
1496 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1497 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1498 }
1499 }
1500
1501 sp<EffectChain> chain = getEffectChain_l(sessionId);
1502 if (chain != 0) {
1503 chain->checkSuspendOnEffectEnabled(effect, enabled);
1504 }
1505 }
1506
1507 // ----------------------------------------------------------------------------
1508
PlaybackThread(const sp<AudioFlinger> & audioFlinger,AudioStreamOut * output,audio_io_handle_t id,uint32_t device,type_t type)1509 AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1510 AudioStreamOut* output,
1511 audio_io_handle_t id,
1512 uint32_t device,
1513 type_t type)
1514 : ThreadBase(audioFlinger, id, device, type),
1515 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
1516 // Assumes constructor is called by AudioFlinger with it's mLock held,
1517 // but it would be safer to explicitly pass initial masterMute as parameter
1518 mMasterMute(audioFlinger->masterMute_l()),
1519 // mStreamTypes[] initialized in constructor body
1520 mOutput(output),
1521 // Assumes constructor is called by AudioFlinger with it's mLock held,
1522 // but it would be safer to explicitly pass initial masterVolume as parameter
1523 mMasterVolume(audioFlinger->masterVolumeSW_l()),
1524 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1525 mMixerStatus(MIXER_IDLE),
1526 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
1527 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
1528 mScreenState(gScreenState),
1529 // index 0 is reserved for normal mixer's submix
1530 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1)
1531 {
1532 snprintf(mName, kNameLength, "AudioOut_%X", id);
1533
1534 readOutputParameters();
1535
1536 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
1537 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1538 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1539 stream = (audio_stream_type_t) (stream + 1)) {
1540 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1541 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1542 }
1543 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1544 // because mAudioFlinger doesn't have one to copy from
1545 }
1546
~PlaybackThread()1547 AudioFlinger::PlaybackThread::~PlaybackThread()
1548 {
1549 delete [] mMixBuffer;
1550 }
1551
dump(int fd,const Vector<String16> & args)1552 status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1553 {
1554 dumpInternals(fd, args);
1555 dumpTracks(fd, args);
1556 dumpEffectChains(fd, args);
1557 return NO_ERROR;
1558 }
1559
dumpTracks(int fd,const Vector<String16> & args)1560 status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1561 {
1562 const size_t SIZE = 256;
1563 char buffer[SIZE];
1564 String8 result;
1565
1566 result.appendFormat("Output thread %p stream volumes in dB:\n ", this);
1567 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1568 const stream_type_t *st = &mStreamTypes[i];
1569 if (i > 0) {
1570 result.appendFormat(", ");
1571 }
1572 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1573 if (st->mute) {
1574 result.append("M");
1575 }
1576 }
1577 result.append("\n");
1578 write(fd, result.string(), result.length());
1579 result.clear();
1580
1581 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1582 result.append(buffer);
1583 Track::appendDumpHeader(result);
1584 for (size_t i = 0; i < mTracks.size(); ++i) {
1585 sp<Track> track = mTracks[i];
1586 if (track != 0) {
1587 track->dump(buffer, SIZE);
1588 result.append(buffer);
1589 }
1590 }
1591
1592 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1593 result.append(buffer);
1594 Track::appendDumpHeader(result);
1595 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
1596 sp<Track> track = mActiveTracks[i].promote();
1597 if (track != 0) {
1598 track->dump(buffer, SIZE);
1599 result.append(buffer);
1600 }
1601 }
1602 write(fd, result.string(), result.size());
1603
1604 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1605 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
1606 fdprintf(fd, "Normal mixer raw underrun counters: partial=%u empty=%u\n",
1607 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
1608
1609 return NO_ERROR;
1610 }
1611
dumpInternals(int fd,const Vector<String16> & args)1612 status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1613 {
1614 const size_t SIZE = 256;
1615 char buffer[SIZE];
1616 String8 result;
1617
1618 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1619 result.append(buffer);
1620 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1621 result.append(buffer);
1622 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1623 result.append(buffer);
1624 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1625 result.append(buffer);
1626 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1627 result.append(buffer);
1628 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1629 result.append(buffer);
1630 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1631 result.append(buffer);
1632 write(fd, result.string(), result.size());
1633 fdprintf(fd, "Fast track availMask=%#x\n", mFastTrackAvailMask);
1634
1635 dumpBase(fd, args);
1636
1637 return NO_ERROR;
1638 }
1639
1640 // Thread virtuals
readyToRun()1641 status_t AudioFlinger::PlaybackThread::readyToRun()
1642 {
1643 status_t status = initCheck();
1644 if (status == NO_ERROR) {
1645 ALOGI("AudioFlinger's thread %p ready to run", this);
1646 } else {
1647 ALOGE("No working audio driver found.");
1648 }
1649 return status;
1650 }
1651
onFirstRef()1652 void AudioFlinger::PlaybackThread::onFirstRef()
1653 {
1654 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
1655 }
1656
1657 // PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
createTrack_l(const sp<AudioFlinger::Client> & client,audio_stream_type_t streamType,uint32_t sampleRate,audio_format_t format,uint32_t channelMask,int frameCount,const sp<IMemory> & sharedBuffer,int sessionId,IAudioFlinger::track_flags_t flags,pid_t tid,status_t * status)1658 sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1659 const sp<AudioFlinger::Client>& client,
1660 audio_stream_type_t streamType,
1661 uint32_t sampleRate,
1662 audio_format_t format,
1663 uint32_t channelMask,
1664 int frameCount,
1665 const sp<IMemory>& sharedBuffer,
1666 int sessionId,
1667 IAudioFlinger::track_flags_t flags,
1668 pid_t tid,
1669 status_t *status)
1670 {
1671 sp<Track> track;
1672 status_t lStatus;
1673
1674 bool isTimed = (flags & IAudioFlinger::TRACK_TIMED) != 0;
1675
1676 // client expresses a preference for FAST, but we get the final say
1677 if (flags & IAudioFlinger::TRACK_FAST) {
1678 if (
1679 // not timed
1680 (!isTimed) &&
1681 // either of these use cases:
1682 (
1683 // use case 1: shared buffer with any frame count
1684 (
1685 (sharedBuffer != 0)
1686 ) ||
1687 // use case 2: callback handler and frame count is default or at least as large as HAL
1688 (
1689 (tid != -1) &&
1690 ((frameCount == 0) ||
1691 (frameCount >= (int) (mFrameCount * 2))) // * 2 is due to SRC jitter, see below
1692 )
1693 ) &&
1694 // PCM data
1695 audio_is_linear_pcm(format) &&
1696 // mono or stereo
1697 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1698 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
1699 #ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE
1700 // hardware sample rate
1701 (sampleRate == mSampleRate) &&
1702 #endif
1703 // normal mixer has an associated fast mixer
1704 hasFastMixer() &&
1705 // there are sufficient fast track slots available
1706 (mFastTrackAvailMask != 0)
1707 // FIXME test that MixerThread for this fast track has a capable output HAL
1708 // FIXME add a permission test also?
1709 ) {
1710 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1711 if (frameCount == 0) {
1712 frameCount = mFrameCount * 2; // FIXME * 2 is due to SRC jitter, should be computed
1713 }
1714 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1715 frameCount, mFrameCount);
1716 } else {
1717 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
1718 "mFrameCount=%d format=%d isLinear=%d channelMask=%d sampleRate=%d mSampleRate=%d "
1719 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1720 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1721 audio_is_linear_pcm(format),
1722 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1723 flags &= ~IAudioFlinger::TRACK_FAST;
1724 // For compatibility with AudioTrack calculation, buffer depth is forced
1725 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1726 // This is probably too conservative, but legacy application code may depend on it.
1727 // If you change this calculation, also review the start threshold which is related.
1728 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1729 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1730 if (minBufCount < 2) {
1731 minBufCount = 2;
1732 }
1733 int minFrameCount = mNormalFrameCount * minBufCount;
1734 if (frameCount < minFrameCount) {
1735 frameCount = minFrameCount;
1736 }
1737 }
1738 }
1739
1740 if (mType == DIRECT) {
1741 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1742 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1743 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
1744 "for output %p with format %d",
1745 sampleRate, format, channelMask, mOutput, mFormat);
1746 lStatus = BAD_VALUE;
1747 goto Exit;
1748 }
1749 }
1750 } else {
1751 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1752 if (sampleRate > mSampleRate*2) {
1753 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
1754 lStatus = BAD_VALUE;
1755 goto Exit;
1756 }
1757 }
1758
1759 lStatus = initCheck();
1760 if (lStatus != NO_ERROR) {
1761 ALOGE("Audio driver not initialized.");
1762 goto Exit;
1763 }
1764
1765 { // scope for mLock
1766 Mutex::Autolock _l(mLock);
1767
1768 // all tracks in same audio session must share the same routing strategy otherwise
1769 // conflicts will happen when tracks are moved from one output to another by audio policy
1770 // manager
1771 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1772 for (size_t i = 0; i < mTracks.size(); ++i) {
1773 sp<Track> t = mTracks[i];
1774 if (t != 0 && !t->isOutputTrack()) {
1775 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1776 if (sessionId == t->sessionId() && strategy != actual) {
1777 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1778 strategy, actual);
1779 lStatus = BAD_VALUE;
1780 goto Exit;
1781 }
1782 }
1783 }
1784
1785 if (!isTimed) {
1786 track = new Track(this, client, streamType, sampleRate, format,
1787 channelMask, frameCount, sharedBuffer, sessionId, flags);
1788 } else {
1789 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1790 channelMask, frameCount, sharedBuffer, sessionId);
1791 }
1792 if (track == NULL || track->getCblk() == NULL || track->name() < 0) {
1793 lStatus = NO_MEMORY;
1794 goto Exit;
1795 }
1796 mTracks.add(track);
1797
1798 sp<EffectChain> chain = getEffectChain_l(sessionId);
1799 if (chain != 0) {
1800 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1801 track->setMainBuffer(chain->inBuffer());
1802 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1803 chain->incTrackCnt();
1804 }
1805 }
1806
1807 #ifdef HAVE_REQUEST_PRIORITY
1808 if ((flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1809 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1810 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1811 // so ask activity manager to do this on our behalf
1812 int err = requestPriority(callingPid, tid, 1);
1813 if (err != 0) {
1814 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
1815 1, callingPid, tid, err);
1816 }
1817 }
1818 #endif
1819
1820 lStatus = NO_ERROR;
1821
1822 Exit:
1823 if (status) {
1824 *status = lStatus;
1825 }
1826 return track;
1827 }
1828
correctLatency(uint32_t latency) const1829 uint32_t AudioFlinger::MixerThread::correctLatency(uint32_t latency) const
1830 {
1831 if (mFastMixer != NULL) {
1832 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
1833 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
1834 }
1835 return latency;
1836 }
1837
correctLatency(uint32_t latency) const1838 uint32_t AudioFlinger::PlaybackThread::correctLatency(uint32_t latency) const
1839 {
1840 return latency;
1841 }
1842
latency() const1843 uint32_t AudioFlinger::PlaybackThread::latency() const
1844 {
1845 Mutex::Autolock _l(mLock);
1846 return latency_l();
1847 }
latency_l() const1848 uint32_t AudioFlinger::PlaybackThread::latency_l() const
1849 {
1850 if (initCheck() == NO_ERROR) {
1851 return correctLatency(mOutput->stream->get_latency(mOutput->stream));
1852 } else {
1853 return 0;
1854 }
1855 }
1856
setMasterVolume(float value)1857 void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1858 {
1859 Mutex::Autolock _l(mLock);
1860 mMasterVolume = value;
1861 }
1862
setMasterMute(bool muted)1863 void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1864 {
1865 Mutex::Autolock _l(mLock);
1866 setMasterMute_l(muted);
1867 }
1868
setStreamVolume(audio_stream_type_t stream,float value)1869 void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1870 {
1871 Mutex::Autolock _l(mLock);
1872 mStreamTypes[stream].volume = value;
1873 }
1874
setStreamMute(audio_stream_type_t stream,bool muted)1875 void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1876 {
1877 Mutex::Autolock _l(mLock);
1878 mStreamTypes[stream].mute = muted;
1879 }
1880
streamVolume(audio_stream_type_t stream) const1881 float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1882 {
1883 Mutex::Autolock _l(mLock);
1884 return mStreamTypes[stream].volume;
1885 }
1886
1887 // addTrack_l() must be called with ThreadBase::mLock held
addTrack_l(const sp<Track> & track)1888 status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1889 {
1890 status_t status = ALREADY_EXISTS;
1891
1892 // set retry count for buffer fill
1893 track->mRetryCount = kMaxTrackStartupRetries;
1894 if (mActiveTracks.indexOf(track) < 0) {
1895 // the track is newly added, make sure it fills up all its
1896 // buffers before playing. This is to ensure the client will
1897 // effectively get the latency it requested.
1898 track->mFillingUpStatus = Track::FS_FILLING;
1899 track->mResetDone = false;
1900 track->mPresentationCompleteFrames = 0;
1901 mActiveTracks.add(track);
1902 if (track->mainBuffer() != mMixBuffer) {
1903 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1904 if (chain != 0) {
1905 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
1906 chain->incActiveTrackCnt();
1907 }
1908 }
1909
1910 status = NO_ERROR;
1911 }
1912
1913 ALOGV("mWaitWorkCV.broadcast");
1914 mWaitWorkCV.broadcast();
1915
1916 return status;
1917 }
1918
1919 // destroyTrack_l() must be called with ThreadBase::mLock held
destroyTrack_l(const sp<Track> & track)1920 void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1921 {
1922 track->mState = TrackBase::TERMINATED;
1923 // active tracks are removed by threadLoop()
1924 if (mActiveTracks.indexOf(track) < 0) {
1925 removeTrack_l(track);
1926 }
1927 }
1928
removeTrack_l(const sp<Track> & track)1929 void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1930 {
1931 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1932 mTracks.remove(track);
1933 deleteTrackName_l(track->name());
1934 // redundant as track is about to be destroyed, for dumpsys only
1935 track->mName = -1;
1936 if (track->isFastTrack()) {
1937 int index = track->mFastIndex;
1938 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
1939 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1940 mFastTrackAvailMask |= 1 << index;
1941 // redundant as track is about to be destroyed, for dumpsys only
1942 track->mFastIndex = -1;
1943 }
1944 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1945 if (chain != 0) {
1946 chain->decTrackCnt();
1947 }
1948 }
1949
getParameters(const String8 & keys)1950 String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1951 {
1952 String8 out_s8 = String8("");
1953 char *s;
1954
1955 Mutex::Autolock _l(mLock);
1956 if (initCheck() != NO_ERROR) {
1957 return out_s8;
1958 }
1959
1960 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
1961 out_s8 = String8(s);
1962 free(s);
1963 return out_s8;
1964 }
1965
1966 // audioConfigChanged_l() must be called with AudioFlinger::mLock held
audioConfigChanged_l(int event,int param)1967 void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1968 AudioSystem::OutputDescriptor desc;
1969 void *param2 = NULL;
1970
1971 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
1972
1973 switch (event) {
1974 case AudioSystem::OUTPUT_OPENED:
1975 case AudioSystem::OUTPUT_CONFIG_CHANGED:
1976 desc.channels = mChannelMask;
1977 desc.samplingRate = mSampleRate;
1978 desc.format = mFormat;
1979 desc.frameCount = mNormalFrameCount; // FIXME see AudioFlinger::frameCount(audio_io_handle_t)
1980 desc.latency = latency();
1981 param2 = &desc;
1982 break;
1983
1984 case AudioSystem::STREAM_CONFIG_CHANGED:
1985 param2 = ¶m;
1986 case AudioSystem::OUTPUT_CLOSED:
1987 default:
1988 break;
1989 }
1990 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1991 }
1992
readOutputParameters()1993 void AudioFlinger::PlaybackThread::readOutputParameters()
1994 {
1995 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
1996 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1997 mChannelCount = (uint16_t)popcount(mChannelMask);
1998 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
1999 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
2000 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
2001 if (mFrameCount & 15) {
2002 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
2003 mFrameCount);
2004 }
2005
2006 // Calculate size of normal mix buffer relative to the HAL output buffer size
2007 double multiplier = 1.0;
2008 if (mType == MIXER && (kUseFastMixer == FastMixer_Static || kUseFastMixer == FastMixer_Dynamic)) {
2009 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
2010 size_t maxNormalFrameCount = (kMaxNormalMixBufferSizeMs * mSampleRate) / 1000;
2011 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2012 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2013 maxNormalFrameCount = maxNormalFrameCount & ~15;
2014 if (maxNormalFrameCount < minNormalFrameCount) {
2015 maxNormalFrameCount = minNormalFrameCount;
2016 }
2017 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2018 if (multiplier <= 1.0) {
2019 multiplier = 1.0;
2020 } else if (multiplier <= 2.0) {
2021 if (2 * mFrameCount <= maxNormalFrameCount) {
2022 multiplier = 2.0;
2023 } else {
2024 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2025 }
2026 } else {
2027 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL SRC
2028 // (it would be unusual for the normal mix buffer size to not be a multiple of fast
2029 // track, but we sometimes have to do this to satisfy the maximum frame count constraint)
2030 // FIXME this rounding up should not be done if no HAL SRC
2031 uint32_t truncMult = (uint32_t) multiplier;
2032 if ((truncMult & 1)) {
2033 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2034 ++truncMult;
2035 }
2036 }
2037 multiplier = (double) truncMult;
2038 }
2039 }
2040 mNormalFrameCount = multiplier * mFrameCount;
2041 // round up to nearest 16 frames to satisfy AudioMixer
2042 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2043 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount, mNormalFrameCount);
2044
2045 delete[] mMixBuffer;
2046 mMixBuffer = new int16_t[mNormalFrameCount * mChannelCount];
2047 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
2048
2049 // force reconfiguration of effect chains and engines to take new buffer size and audio
2050 // parameters into account
2051 // Note that mLock is not held when readOutputParameters() is called from the constructor
2052 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2053 // matter.
2054 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2055 Vector< sp<EffectChain> > effectChains = mEffectChains;
2056 for (size_t i = 0; i < effectChains.size(); i ++) {
2057 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2058 }
2059 }
2060
2061
getRenderPosition(uint32_t * halFrames,uint32_t * dspFrames)2062 status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
2063 {
2064 if (halFrames == NULL || dspFrames == NULL) {
2065 return BAD_VALUE;
2066 }
2067 Mutex::Autolock _l(mLock);
2068 if (initCheck() != NO_ERROR) {
2069 return INVALID_OPERATION;
2070 }
2071 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
2072
2073 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
2074 }
2075
hasAudioSession(int sessionId)2076 uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
2077 {
2078 Mutex::Autolock _l(mLock);
2079 uint32_t result = 0;
2080 if (getEffectChain_l(sessionId) != 0) {
2081 result = EFFECT_SESSION;
2082 }
2083
2084 for (size_t i = 0; i < mTracks.size(); ++i) {
2085 sp<Track> track = mTracks[i];
2086 if (sessionId == track->sessionId() &&
2087 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
2088 result |= TRACK_SESSION;
2089 break;
2090 }
2091 }
2092
2093 return result;
2094 }
2095
getStrategyForSession_l(int sessionId)2096 uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2097 {
2098 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2099 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2100 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2101 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2102 }
2103 for (size_t i = 0; i < mTracks.size(); i++) {
2104 sp<Track> track = mTracks[i];
2105 if (sessionId == track->sessionId() &&
2106 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
2107 return AudioSystem::getStrategyForStream(track->streamType());
2108 }
2109 }
2110 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2111 }
2112
2113
getOutput() const2114 AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
2115 {
2116 Mutex::Autolock _l(mLock);
2117 return mOutput;
2118 }
2119
clearOutput()2120 AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
2121 {
2122 Mutex::Autolock _l(mLock);
2123 AudioStreamOut *output = mOutput;
2124 mOutput = NULL;
2125 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2126 // must push a NULL and wait for ack
2127 mOutputSink.clear();
2128 mPipeSink.clear();
2129 mNormalSink.clear();
2130 return output;
2131 }
2132
2133 // this method must always be called either with ThreadBase mLock held or inside the thread loop
stream() const2134 audio_stream_t* AudioFlinger::PlaybackThread::stream() const
2135 {
2136 if (mOutput == NULL) {
2137 return NULL;
2138 }
2139 return &mOutput->stream->common;
2140 }
2141
activeSleepTimeUs() const2142 uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2143 {
2144 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2145 }
2146
setSyncEvent(const sp<SyncEvent> & event)2147 status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2148 {
2149 if (!isValidSyncEvent(event)) {
2150 return BAD_VALUE;
2151 }
2152
2153 Mutex::Autolock _l(mLock);
2154
2155 for (size_t i = 0; i < mTracks.size(); ++i) {
2156 sp<Track> track = mTracks[i];
2157 if (event->triggerSession() == track->sessionId()) {
2158 track->setSyncEvent(event);
2159 return NO_ERROR;
2160 }
2161 }
2162
2163 return NAME_NOT_FOUND;
2164 }
2165
isValidSyncEvent(const sp<SyncEvent> & event)2166 bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event)
2167 {
2168 switch (event->type()) {
2169 case AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE:
2170 return true;
2171 default:
2172 break;
2173 }
2174 return false;
2175 }
2176
threadLoop_removeTracks(const Vector<sp<Track>> & tracksToRemove)2177 void AudioFlinger::PlaybackThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2178 {
2179 size_t count = tracksToRemove.size();
2180 if (CC_UNLIKELY(count)) {
2181 for (size_t i = 0 ; i < count ; i++) {
2182 const sp<Track>& track = tracksToRemove.itemAt(i);
2183 if ((track->sharedBuffer() != 0) &&
2184 (track->mState == TrackBase::ACTIVE || track->mState == TrackBase::RESUMING)) {
2185 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
2186 }
2187 }
2188 }
2189
2190 }
2191
2192 // ----------------------------------------------------------------------------
2193
MixerThread(const sp<AudioFlinger> & audioFlinger,AudioStreamOut * output,audio_io_handle_t id,uint32_t device,type_t type)2194 AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
2195 audio_io_handle_t id, uint32_t device, type_t type)
2196 : PlaybackThread(audioFlinger, output, id, device, type),
2197 // mAudioMixer below
2198 #ifdef SOAKER
2199 mSoaker(NULL),
2200 #endif
2201 // mFastMixer below
2202 mFastMixerFutex(0)
2203 // mOutputSink below
2204 // mPipeSink below
2205 // mNormalSink below
2206 {
2207 ALOGV("MixerThread() id=%d device=%d type=%d", id, device, type);
2208 ALOGV("mSampleRate=%d, mChannelMask=%d, mChannelCount=%d, mFormat=%d, mFrameSize=%d, "
2209 "mFrameCount=%d, mNormalFrameCount=%d",
2210 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2211 mNormalFrameCount);
2212 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2213
2214 // FIXME - Current mixer implementation only supports stereo output
2215 if (mChannelCount == 1) {
2216 ALOGE("Invalid audio hardware channel count");
2217 }
2218
2219 // create an NBAIO sink for the HAL output stream, and negotiate
2220 mOutputSink = new AudioStreamOutSink(output->stream);
2221 size_t numCounterOffers = 0;
2222 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2223 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2224 ALOG_ASSERT(index == 0);
2225
2226 // initialize fast mixer depending on configuration
2227 bool initFastMixer;
2228 switch (kUseFastMixer) {
2229 case FastMixer_Never:
2230 initFastMixer = false;
2231 break;
2232 case FastMixer_Always:
2233 initFastMixer = true;
2234 break;
2235 case FastMixer_Static:
2236 case FastMixer_Dynamic:
2237 initFastMixer = mFrameCount < mNormalFrameCount;
2238 break;
2239 }
2240 if (initFastMixer) {
2241
2242 // create a MonoPipe to connect our submix to FastMixer
2243 NBAIO_Format format = mOutputSink->format();
2244 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2245 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2246 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2247 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
2248 const NBAIO_Format offers[1] = {format};
2249 size_t numCounterOffers = 0;
2250 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2251 ALOG_ASSERT(index == 0);
2252 monoPipe->setAvgFrames((mScreenState & 1) ?
2253 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2254 mPipeSink = monoPipe;
2255
2256 #ifdef TEE_SINK_FRAMES
2257 // create a Pipe to archive a copy of FastMixer's output for dumpsys
2258 Pipe *teeSink = new Pipe(TEE_SINK_FRAMES, format);
2259 numCounterOffers = 0;
2260 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2261 ALOG_ASSERT(index == 0);
2262 mTeeSink = teeSink;
2263 PipeReader *teeSource = new PipeReader(*teeSink);
2264 numCounterOffers = 0;
2265 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2266 ALOG_ASSERT(index == 0);
2267 mTeeSource = teeSource;
2268 #endif
2269
2270 #ifdef SOAKER
2271 // create a soaker as workaround for governor issues
2272 mSoaker = new Soaker();
2273 // FIXME Soaker should only run when needed, i.e. when FastMixer is not in COLD_IDLE
2274 mSoaker->run("Soaker", PRIORITY_LOWEST);
2275 #endif
2276
2277 // create fast mixer and configure it initially with just one fast track for our submix
2278 mFastMixer = new FastMixer();
2279 FastMixerStateQueue *sq = mFastMixer->sq();
2280 #ifdef STATE_QUEUE_DUMP
2281 sq->setObserverDump(&mStateQueueObserverDump);
2282 sq->setMutatorDump(&mStateQueueMutatorDump);
2283 #endif
2284 FastMixerState *state = sq->begin();
2285 FastTrack *fastTrack = &state->mFastTracks[0];
2286 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2287 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2288 fastTrack->mVolumeProvider = NULL;
2289 fastTrack->mGeneration++;
2290 state->mFastTracksGen++;
2291 state->mTrackMask = 1;
2292 // fast mixer will use the HAL output sink
2293 state->mOutputSink = mOutputSink.get();
2294 state->mOutputSinkGen++;
2295 state->mFrameCount = mFrameCount;
2296 state->mCommand = FastMixerState::COLD_IDLE;
2297 // already done in constructor initialization list
2298 //mFastMixerFutex = 0;
2299 state->mColdFutexAddr = &mFastMixerFutex;
2300 state->mColdGen++;
2301 state->mDumpState = &mFastMixerDumpState;
2302 state->mTeeSink = mTeeSink.get();
2303 sq->end();
2304 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2305
2306 // start the fast mixer
2307 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
2308 #ifdef HAVE_REQUEST_PRIORITY
2309 pid_t tid = mFastMixer->getTid();
2310 int err = requestPriority(getpid_cached, tid, 2);
2311 if (err != 0) {
2312 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2313 2, getpid_cached, tid, err);
2314 }
2315 #endif
2316
2317 #ifdef AUDIO_WATCHDOG
2318 // create and start the watchdog
2319 mAudioWatchdog = new AudioWatchdog();
2320 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2321 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2322 tid = mAudioWatchdog->getTid();
2323 err = requestPriority(getpid_cached, tid, 1);
2324 if (err != 0) {
2325 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2326 1, getpid_cached, tid, err);
2327 }
2328 #endif
2329
2330 } else {
2331 mFastMixer = NULL;
2332 }
2333
2334 switch (kUseFastMixer) {
2335 case FastMixer_Never:
2336 case FastMixer_Dynamic:
2337 mNormalSink = mOutputSink;
2338 break;
2339 case FastMixer_Always:
2340 mNormalSink = mPipeSink;
2341 break;
2342 case FastMixer_Static:
2343 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2344 break;
2345 }
2346 }
2347
~MixerThread()2348 AudioFlinger::MixerThread::~MixerThread()
2349 {
2350 if (mFastMixer != NULL) {
2351 FastMixerStateQueue *sq = mFastMixer->sq();
2352 FastMixerState *state = sq->begin();
2353 if (state->mCommand == FastMixerState::COLD_IDLE) {
2354 int32_t old = android_atomic_inc(&mFastMixerFutex);
2355 if (old == -1) {
2356 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2357 }
2358 }
2359 state->mCommand = FastMixerState::EXIT;
2360 sq->end();
2361 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2362 mFastMixer->join();
2363 // Though the fast mixer thread has exited, it's state queue is still valid.
2364 // We'll use that extract the final state which contains one remaining fast track
2365 // corresponding to our sub-mix.
2366 state = sq->begin();
2367 ALOG_ASSERT(state->mTrackMask == 1);
2368 FastTrack *fastTrack = &state->mFastTracks[0];
2369 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2370 delete fastTrack->mBufferProvider;
2371 sq->end(false /*didModify*/);
2372 delete mFastMixer;
2373 #ifdef SOAKER
2374 if (mSoaker != NULL) {
2375 mSoaker->requestExitAndWait();
2376 }
2377 delete mSoaker;
2378 #endif
2379 if (mAudioWatchdog != 0) {
2380 mAudioWatchdog->requestExit();
2381 mAudioWatchdog->requestExitAndWait();
2382 mAudioWatchdog.clear();
2383 }
2384 }
2385 delete mAudioMixer;
2386 }
2387
2388 class CpuStats {
2389 public:
2390 CpuStats();
2391 void sample(const String8 &title);
2392 #ifdef DEBUG_CPU_USAGE
2393 private:
2394 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
2395 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
2396
2397 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
2398
2399 int mCpuNum; // thread's current CPU number
2400 int mCpukHz; // frequency of thread's current CPU in kHz
2401 #endif
2402 };
2403
CpuStats()2404 CpuStats::CpuStats()
2405 #ifdef DEBUG_CPU_USAGE
2406 : mCpuNum(-1), mCpukHz(-1)
2407 #endif
2408 {
2409 }
2410
sample(const String8 & title)2411 void CpuStats::sample(const String8 &title) {
2412 #ifdef DEBUG_CPU_USAGE
2413 // get current thread's delta CPU time in wall clock ns
2414 double wcNs;
2415 bool valid = mCpuUsage.sampleAndEnable(wcNs);
2416
2417 // record sample for wall clock statistics
2418 if (valid) {
2419 mWcStats.sample(wcNs);
2420 }
2421
2422 // get the current CPU number
2423 int cpuNum = sched_getcpu();
2424
2425 // get the current CPU frequency in kHz
2426 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
2427
2428 // check if either CPU number or frequency changed
2429 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
2430 mCpuNum = cpuNum;
2431 mCpukHz = cpukHz;
2432 // ignore sample for purposes of cycles
2433 valid = false;
2434 }
2435
2436 // if no change in CPU number or frequency, then record sample for cycle statistics
2437 if (valid && mCpukHz > 0) {
2438 double cycles = wcNs * cpukHz * 0.000001;
2439 mHzStats.sample(cycles);
2440 }
2441
2442 unsigned n = mWcStats.n();
2443 // mCpuUsage.elapsed() is expensive, so don't call it every loop
2444 if ((n & 127) == 1) {
2445 long long elapsed = mCpuUsage.elapsed();
2446 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
2447 double perLoop = elapsed / (double) n;
2448 double perLoop100 = perLoop * 0.01;
2449 double perLoop1k = perLoop * 0.001;
2450 double mean = mWcStats.mean();
2451 double stddev = mWcStats.stddev();
2452 double minimum = mWcStats.minimum();
2453 double maximum = mWcStats.maximum();
2454 double meanCycles = mHzStats.mean();
2455 double stddevCycles = mHzStats.stddev();
2456 double minCycles = mHzStats.minimum();
2457 double maxCycles = mHzStats.maximum();
2458 mCpuUsage.resetElapsed();
2459 mWcStats.reset();
2460 mHzStats.reset();
2461 ALOGD("CPU usage for %s over past %.1f secs\n"
2462 " (%u mixer loops at %.1f mean ms per loop):\n"
2463 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
2464 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
2465 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
2466 title.string(),
2467 elapsed * .000000001, n, perLoop * .000001,
2468 mean * .001,
2469 stddev * .001,
2470 minimum * .001,
2471 maximum * .001,
2472 mean / perLoop100,
2473 stddev / perLoop100,
2474 minimum / perLoop100,
2475 maximum / perLoop100,
2476 meanCycles / perLoop1k,
2477 stddevCycles / perLoop1k,
2478 minCycles / perLoop1k,
2479 maxCycles / perLoop1k);
2480
2481 }
2482 }
2483 #endif
2484 };
2485
checkSilentMode_l()2486 void AudioFlinger::PlaybackThread::checkSilentMode_l()
2487 {
2488 if (!mMasterMute) {
2489 char value[PROPERTY_VALUE_MAX];
2490 if (property_get("ro.audio.silent", value, "0") > 0) {
2491 char *endptr;
2492 unsigned long ul = strtoul(value, &endptr, 0);
2493 if (*endptr == '\0' && ul != 0) {
2494 ALOGD("Silence is golden");
2495 // The setprop command will not allow a property to be changed after
2496 // the first time it is set, so we don't have to worry about un-muting.
2497 setMasterMute_l(true);
2498 }
2499 }
2500 }
2501 }
2502
threadLoop()2503 bool AudioFlinger::PlaybackThread::threadLoop()
2504 {
2505 Vector< sp<Track> > tracksToRemove;
2506
2507 standbyTime = systemTime();
2508
2509 // MIXER
2510 nsecs_t lastWarning = 0;
2511 if (mType == MIXER) {
2512 longStandbyExit = false;
2513 }
2514
2515 // DUPLICATING
2516 // FIXME could this be made local to while loop?
2517 writeFrames = 0;
2518
2519 cacheParameters_l();
2520 sleepTime = idleSleepTime;
2521
2522 if (mType == MIXER) {
2523 sleepTimeShift = 0;
2524 }
2525
2526 CpuStats cpuStats;
2527 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2528
2529 acquireWakeLock();
2530
2531 while (!exitPending())
2532 {
2533 cpuStats.sample(myName);
2534
2535 Vector< sp<EffectChain> > effectChains;
2536
2537 processConfigEvents();
2538
2539 { // scope for mLock
2540
2541 Mutex::Autolock _l(mLock);
2542
2543 if (checkForNewParameters_l()) {
2544 cacheParameters_l();
2545 }
2546
2547 saveOutputTracks();
2548
2549 // put audio hardware into standby after short delay
2550 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2551 mSuspended > 0)) {
2552 if (!mStandby) {
2553
2554 threadLoop_standby();
2555
2556 mStandby = true;
2557 mBytesWritten = 0;
2558 }
2559
2560 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2561 // we're about to wait, flush the binder command buffer
2562 IPCThreadState::self()->flushCommands();
2563
2564 clearOutputTracks();
2565
2566 if (exitPending()) break;
2567
2568 releaseWakeLock_l();
2569 // wait until we have something to do...
2570 ALOGV("%s going to sleep", myName.string());
2571 mWaitWorkCV.wait(mLock);
2572 ALOGV("%s waking up", myName.string());
2573 acquireWakeLock_l();
2574
2575 mMixerStatus = MIXER_IDLE;
2576 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2577
2578 checkSilentMode_l();
2579
2580 standbyTime = systemTime() + standbyDelay;
2581 sleepTime = idleSleepTime;
2582 if (mType == MIXER) {
2583 sleepTimeShift = 0;
2584 }
2585
2586 continue;
2587 }
2588 }
2589
2590 // mMixerStatusIgnoringFastTracks is also updated internally
2591 mMixerStatus = prepareTracks_l(&tracksToRemove);
2592
2593 // prevent any changes in effect chain list and in each effect chain
2594 // during mixing and effect process as the audio buffers could be deleted
2595 // or modified if an effect is created or deleted
2596 lockEffectChains_l(effectChains);
2597 }
2598
2599 if (CC_LIKELY(mMixerStatus == MIXER_TRACKS_READY)) {
2600 threadLoop_mix();
2601 } else {
2602 threadLoop_sleepTime();
2603 }
2604
2605 if (mSuspended > 0) {
2606 sleepTime = suspendSleepTimeUs();
2607 }
2608
2609 // only process effects if we're going to write
2610 if (sleepTime == 0) {
2611 for (size_t i = 0; i < effectChains.size(); i ++) {
2612 effectChains[i]->process_l();
2613 }
2614 }
2615
2616 // enable changes in effect chain
2617 unlockEffectChains(effectChains);
2618
2619 // sleepTime == 0 means we must write to audio hardware
2620 if (sleepTime == 0) {
2621
2622 threadLoop_write();
2623
2624 if (mType == MIXER) {
2625 // write blocked detection
2626 nsecs_t now = systemTime();
2627 nsecs_t delta = now - mLastWriteTime;
2628 if (!mStandby && delta > maxPeriod) {
2629 mNumDelayedWrites++;
2630 if ((now - lastWarning) > kWarningThrottleNs) {
2631 #if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
2632 ScopedTrace st(ATRACE_TAG, "underrun");
2633 #endif
2634 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2635 ns2ms(delta), mNumDelayedWrites, this);
2636 lastWarning = now;
2637 }
2638 // FIXME this is broken: longStandbyExit should be handled out of the if() and with
2639 // a different threshold. Or completely removed for what it is worth anyway...
2640 if (mStandby) {
2641 longStandbyExit = true;
2642 }
2643 }
2644 }
2645
2646 mStandby = false;
2647 } else {
2648 usleep(sleepTime);
2649 }
2650
2651 // Finally let go of removed track(s), without the lock held
2652 // since we can't guarantee the destructors won't acquire that
2653 // same lock. This will also mutate and push a new fast mixer state.
2654 threadLoop_removeTracks(tracksToRemove);
2655 tracksToRemove.clear();
2656
2657 // FIXME I don't understand the need for this here;
2658 // it was in the original code but maybe the
2659 // assignment in saveOutputTracks() makes this unnecessary?
2660 clearOutputTracks();
2661
2662 // Effect chains will be actually deleted here if they were removed from
2663 // mEffectChains list during mixing or effects processing
2664 effectChains.clear();
2665
2666 // FIXME Note that the above .clear() is no longer necessary since effectChains
2667 // is now local to this block, but will keep it for now (at least until merge done).
2668 }
2669
2670 if (mType == MIXER || mType == DIRECT) {
2671 // put output stream into standby mode
2672 if (!mStandby) {
2673 mOutput->stream->common.standby(&mOutput->stream->common);
2674 }
2675 }
2676 if (mType == DUPLICATING) {
2677 // for DuplicatingThread, standby mode is handled by the outputTracks
2678 }
2679
2680 releaseWakeLock();
2681
2682 ALOGV("Thread %p type %d exiting", this, mType);
2683 return false;
2684 }
2685
threadLoop_removeTracks(const Vector<sp<Track>> & tracksToRemove)2686 void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2687 {
2688 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2689 }
2690
threadLoop_write()2691 void AudioFlinger::MixerThread::threadLoop_write()
2692 {
2693 // FIXME we should only do one push per cycle; confirm this is true
2694 // Start the fast mixer if it's not already running
2695 if (mFastMixer != NULL) {
2696 FastMixerStateQueue *sq = mFastMixer->sq();
2697 FastMixerState *state = sq->begin();
2698 if (state->mCommand != FastMixerState::MIX_WRITE &&
2699 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
2700 if (state->mCommand == FastMixerState::COLD_IDLE) {
2701 int32_t old = android_atomic_inc(&mFastMixerFutex);
2702 if (old == -1) {
2703 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2704 }
2705 if (mAudioWatchdog != 0) {
2706 mAudioWatchdog->resume();
2707 }
2708 }
2709 state->mCommand = FastMixerState::MIX_WRITE;
2710 sq->end();
2711 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2712 if (kUseFastMixer == FastMixer_Dynamic) {
2713 mNormalSink = mPipeSink;
2714 }
2715 } else {
2716 sq->end(false /*didModify*/);
2717 }
2718 }
2719 PlaybackThread::threadLoop_write();
2720 }
2721
2722 // shared by MIXER and DIRECT, overridden by DUPLICATING
threadLoop_write()2723 void AudioFlinger::PlaybackThread::threadLoop_write()
2724 {
2725 // FIXME rewrite to reduce number of system calls
2726 mLastWriteTime = systemTime();
2727 mInWrite = true;
2728 int bytesWritten;
2729
2730 // If an NBAIO sink is present, use it to write the normal mixer's submix
2731 if (mNormalSink != 0) {
2732 #define mBitShift 2 // FIXME
2733 size_t count = mixBufferSize >> mBitShift;
2734 #if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
2735 Tracer::traceBegin(ATRACE_TAG, "write");
2736 #endif
2737 // update the setpoint when gScreenState changes
2738 uint32_t screenState = gScreenState;
2739 if (screenState != mScreenState) {
2740 mScreenState = screenState;
2741 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2742 if (pipe != NULL) {
2743 pipe->setAvgFrames((mScreenState & 1) ?
2744 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2745 }
2746 }
2747 ssize_t framesWritten = mNormalSink->write(mMixBuffer, count);
2748 #if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
2749 Tracer::traceEnd(ATRACE_TAG);
2750 #endif
2751 if (framesWritten > 0) {
2752 bytesWritten = framesWritten << mBitShift;
2753 } else {
2754 bytesWritten = framesWritten;
2755 }
2756 // otherwise use the HAL / AudioStreamOut directly
2757 } else {
2758 // Direct output thread.
2759 bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
2760 }
2761
2762 if (bytesWritten > 0) mBytesWritten += mixBufferSize;
2763 mNumWrites++;
2764 mInWrite = false;
2765 }
2766
threadLoop_standby()2767 void AudioFlinger::MixerThread::threadLoop_standby()
2768 {
2769 // Idle the fast mixer if it's currently running
2770 if (mFastMixer != NULL) {
2771 FastMixerStateQueue *sq = mFastMixer->sq();
2772 FastMixerState *state = sq->begin();
2773 if (!(state->mCommand & FastMixerState::IDLE)) {
2774 state->mCommand = FastMixerState::COLD_IDLE;
2775 state->mColdFutexAddr = &mFastMixerFutex;
2776 state->mColdGen++;
2777 mFastMixerFutex = 0;
2778 sq->end();
2779 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2780 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
2781 if (kUseFastMixer == FastMixer_Dynamic) {
2782 mNormalSink = mOutputSink;
2783 }
2784 if (mAudioWatchdog != 0) {
2785 mAudioWatchdog->pause();
2786 }
2787 } else {
2788 sq->end(false /*didModify*/);
2789 }
2790 }
2791 PlaybackThread::threadLoop_standby();
2792 }
2793
2794 // shared by MIXER and DIRECT, overridden by DUPLICATING
threadLoop_standby()2795 void AudioFlinger::PlaybackThread::threadLoop_standby()
2796 {
2797 ALOGV("Audio hardware entering standby, mixer %p, suspend count %u", this, mSuspended);
2798 mOutput->stream->common.standby(&mOutput->stream->common);
2799 }
2800
threadLoop_mix()2801 void AudioFlinger::MixerThread::threadLoop_mix()
2802 {
2803 // obtain the presentation timestamp of the next output buffer
2804 int64_t pts;
2805 status_t status = INVALID_OPERATION;
2806
2807 if (NULL != mOutput->stream->get_next_write_timestamp) {
2808 status = mOutput->stream->get_next_write_timestamp(
2809 mOutput->stream, &pts);
2810 }
2811
2812 if (status != NO_ERROR) {
2813 pts = AudioBufferProvider::kInvalidPTS;
2814 }
2815
2816 // mix buffers...
2817 mAudioMixer->process(pts);
2818 // increase sleep time progressively when application underrun condition clears.
2819 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2820 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2821 // such that we would underrun the audio HAL.
2822 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2823 sleepTimeShift--;
2824 }
2825 sleepTime = 0;
2826 standbyTime = systemTime() + standbyDelay;
2827 //TODO: delay standby when effects have a tail
2828 }
2829
threadLoop_sleepTime()2830 void AudioFlinger::MixerThread::threadLoop_sleepTime()
2831 {
2832 // If no tracks are ready, sleep once for the duration of an output
2833 // buffer size, then write 0s to the output
2834 if (sleepTime == 0) {
2835 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
2836 sleepTime = activeSleepTime >> sleepTimeShift;
2837 if (sleepTime < kMinThreadSleepTimeUs) {
2838 sleepTime = kMinThreadSleepTimeUs;
2839 }
2840 // reduce sleep time in case of consecutive application underruns to avoid
2841 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2842 // duration we would end up writing less data than needed by the audio HAL if
2843 // the condition persists.
2844 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2845 sleepTimeShift++;
2846 }
2847 } else {
2848 sleepTime = idleSleepTime;
2849 }
2850 } else if (mBytesWritten != 0 ||
2851 (mMixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
2852 memset (mMixBuffer, 0, mixBufferSize);
2853 sleepTime = 0;
2854 ALOGV_IF((mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
2855 }
2856 // TODO add standby time extension fct of effect tail
2857 }
2858
2859 // prepareTracks_l() must be called with ThreadBase::mLock held
prepareTracks_l(Vector<sp<Track>> * tracksToRemove)2860 AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
2861 Vector< sp<Track> > *tracksToRemove)
2862 {
2863
2864 mixer_state mixerStatus = MIXER_IDLE;
2865 // find out which tracks need to be processed
2866 size_t count = mActiveTracks.size();
2867 size_t mixedTracks = 0;
2868 size_t tracksWithEffect = 0;
2869 // counts only _active_ fast tracks
2870 size_t fastTracks = 0;
2871 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
2872
2873 float masterVolume = mMasterVolume;
2874 bool masterMute = mMasterMute;
2875
2876 if (masterMute) {
2877 masterVolume = 0;
2878 }
2879 // Delegate master volume control to effect in output mix effect chain if needed
2880 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
2881 if (chain != 0) {
2882 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
2883 chain->setVolume_l(&v, &v);
2884 masterVolume = (float)((v + (1 << 23)) >> 24);
2885 chain.clear();
2886 }
2887
2888 // prepare a new state to push
2889 FastMixerStateQueue *sq = NULL;
2890 FastMixerState *state = NULL;
2891 bool didModify = false;
2892 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
2893 if (mFastMixer != NULL) {
2894 sq = mFastMixer->sq();
2895 state = sq->begin();
2896 }
2897
2898 for (size_t i=0 ; i<count ; i++) {
2899 sp<Track> t = mActiveTracks[i].promote();
2900 if (t == 0) continue;
2901
2902 // this const just means the local variable doesn't change
2903 Track* const track = t.get();
2904
2905 // process fast tracks
2906 if (track->isFastTrack()) {
2907
2908 // It's theoretically possible (though unlikely) for a fast track to be created
2909 // and then removed within the same normal mix cycle. This is not a problem, as
2910 // the track never becomes active so it's fast mixer slot is never touched.
2911 // The converse, of removing an (active) track and then creating a new track
2912 // at the identical fast mixer slot within the same normal mix cycle,
2913 // is impossible because the slot isn't marked available until the end of each cycle.
2914 int j = track->mFastIndex;
2915 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
2916 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
2917 FastTrack *fastTrack = &state->mFastTracks[j];
2918
2919 // Determine whether the track is currently in underrun condition,
2920 // and whether it had a recent underrun.
2921 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
2922 FastTrackUnderruns underruns = ftDump->mUnderruns;
2923 uint32_t recentFull = (underruns.mBitFields.mFull -
2924 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
2925 uint32_t recentPartial = (underruns.mBitFields.mPartial -
2926 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
2927 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
2928 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
2929 uint32_t recentUnderruns = recentPartial + recentEmpty;
2930 track->mObservedUnderruns = underruns;
2931 // don't count underruns that occur while stopping or pausing
2932 // or stopped which can occur when flush() is called while active
2933 if (!(track->isStopping() || track->isPausing() || track->isStopped())) {
2934 track->mUnderrunCount += recentUnderruns;
2935 }
2936
2937 // This is similar to the state machine for normal tracks,
2938 // with a few modifications for fast tracks.
2939 bool isActive = true;
2940 switch (track->mState) {
2941 case TrackBase::STOPPING_1:
2942 // track stays active in STOPPING_1 state until first underrun
2943 if (recentUnderruns > 0) {
2944 track->mState = TrackBase::STOPPING_2;
2945 }
2946 break;
2947 case TrackBase::PAUSING:
2948 // ramp down is not yet implemented
2949 track->setPaused();
2950 break;
2951 case TrackBase::RESUMING:
2952 // ramp up is not yet implemented
2953 track->mState = TrackBase::ACTIVE;
2954 break;
2955 case TrackBase::ACTIVE:
2956 if (recentFull > 0 || recentPartial > 0) {
2957 // track has provided at least some frames recently: reset retry count
2958 track->mRetryCount = kMaxTrackRetries;
2959 }
2960 if (recentUnderruns == 0) {
2961 // no recent underruns: stay active
2962 break;
2963 }
2964 // there has recently been an underrun of some kind
2965 if (track->sharedBuffer() == 0) {
2966 // were any of the recent underruns "empty" (no frames available)?
2967 if (recentEmpty == 0) {
2968 // no, then ignore the partial underruns as they are allowed indefinitely
2969 break;
2970 }
2971 // there has recently been an "empty" underrun: decrement the retry counter
2972 if (--(track->mRetryCount) > 0) {
2973 break;
2974 }
2975 // indicate to client process that the track was disabled because of underrun;
2976 // it will then automatically call start() when data is available
2977 android_atomic_or(CBLK_DISABLED_ON, &track->mCblk->flags);
2978 // remove from active list, but state remains ACTIVE [confusing but true]
2979 isActive = false;
2980 break;
2981 }
2982 // fall through
2983 case TrackBase::STOPPING_2:
2984 case TrackBase::PAUSED:
2985 case TrackBase::TERMINATED:
2986 case TrackBase::STOPPED:
2987 case TrackBase::FLUSHED: // flush() while active
2988 // Check for presentation complete if track is inactive
2989 // We have consumed all the buffers of this track.
2990 // This would be incomplete if we auto-paused on underrun
2991 {
2992 size_t audioHALFrames =
2993 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
2994 size_t framesWritten =
2995 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
2996 if (!track->presentationComplete(framesWritten, audioHALFrames)) {
2997 // track stays in active list until presentation is complete
2998 break;
2999 }
3000 }
3001 if (track->isStopping_2()) {
3002 track->mState = TrackBase::STOPPED;
3003 }
3004 if (track->isStopped()) {
3005 // Can't reset directly, as fast mixer is still polling this track
3006 // track->reset();
3007 // So instead mark this track as needing to be reset after push with ack
3008 resetMask |= 1 << i;
3009 }
3010 isActive = false;
3011 break;
3012 case TrackBase::IDLE:
3013 default:
3014 LOG_FATAL("unexpected track state %d", track->mState);
3015 }
3016
3017 if (isActive) {
3018 // was it previously inactive?
3019 if (!(state->mTrackMask & (1 << j))) {
3020 ExtendedAudioBufferProvider *eabp = track;
3021 VolumeProvider *vp = track;
3022 fastTrack->mBufferProvider = eabp;
3023 fastTrack->mVolumeProvider = vp;
3024 fastTrack->mSampleRate = track->mSampleRate;
3025 fastTrack->mChannelMask = track->mChannelMask;
3026 fastTrack->mGeneration++;
3027 state->mTrackMask |= 1 << j;
3028 didModify = true;
3029 // no acknowledgement required for newly active tracks
3030 }
3031 // cache the combined master volume and stream type volume for fast mixer; this
3032 // lacks any synchronization or barrier so VolumeProvider may read a stale value
3033 track->mCachedVolume = track->isMuted() ?
3034 0 : masterVolume * mStreamTypes[track->streamType()].volume;
3035 ++fastTracks;
3036 } else {
3037 // was it previously active?
3038 if (state->mTrackMask & (1 << j)) {
3039 fastTrack->mBufferProvider = NULL;
3040 fastTrack->mGeneration++;
3041 state->mTrackMask &= ~(1 << j);
3042 didModify = true;
3043 // If any fast tracks were removed, we must wait for acknowledgement
3044 // because we're about to decrement the last sp<> on those tracks.
3045 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3046 } else {
3047 LOG_FATAL("fast track %d should have been active", j);
3048 }
3049 tracksToRemove->add(track);
3050 // Avoids a misleading display in dumpsys
3051 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3052 }
3053 continue;
3054 }
3055
3056 { // local variable scope to avoid goto warning
3057
3058 audio_track_cblk_t* cblk = track->cblk();
3059
3060 // The first time a track is added we wait
3061 // for all its buffers to be filled before processing it
3062 int name = track->name();
3063 // make sure that we have enough frames to mix one full buffer.
3064 // enforce this condition only once to enable draining the buffer in case the client
3065 // app does not call stop() and relies on underrun to stop:
3066 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3067 // during last round
3068 uint32_t minFrames = 1;
3069 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3070 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
3071 if (t->sampleRate() == (int)mSampleRate) {
3072 minFrames = mNormalFrameCount;
3073 } else {
3074 // +1 for rounding and +1 for additional sample needed for interpolation
3075 minFrames = (mNormalFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
3076 // add frames already consumed but not yet released by the resampler
3077 // because cblk->framesReady() will include these frames
3078 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
3079 // the minimum track buffer size is normally twice the number of frames necessary
3080 // to fill one buffer and the resampler should not leave more than one buffer worth
3081 // of unreleased frames after each pass, but just in case...
3082 ALOG_ASSERT(minFrames <= cblk->frameCount);
3083 }
3084 }
3085 if ((track->framesReady() >= minFrames) && track->isReady() &&
3086 !track->isPaused() && !track->isTerminated())
3087 {
3088 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
3089
3090 mixedTracks++;
3091
3092 // track->mainBuffer() != mMixBuffer means there is an effect chain
3093 // connected to the track
3094 chain.clear();
3095 if (track->mainBuffer() != mMixBuffer) {
3096 chain = getEffectChain_l(track->sessionId());
3097 // Delegate volume control to effect in track effect chain if needed
3098 if (chain != 0) {
3099 tracksWithEffect++;
3100 } else {
3101 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
3102 name, track->sessionId());
3103 }
3104 }
3105
3106
3107 int param = AudioMixer::VOLUME;
3108 if (track->mFillingUpStatus == Track::FS_FILLED) {
3109 // no ramp for the first volume setting
3110 track->mFillingUpStatus = Track::FS_ACTIVE;
3111 if (track->mState == TrackBase::RESUMING) {
3112 track->mState = TrackBase::ACTIVE;
3113 param = AudioMixer::RAMP_VOLUME;
3114 }
3115 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
3116 } else if (cblk->server != 0) {
3117 // If the track is stopped before the first frame was mixed,
3118 // do not apply ramp
3119 param = AudioMixer::RAMP_VOLUME;
3120 }
3121
3122 // compute volume for this track
3123 uint32_t vl, vr, va;
3124 if (track->isMuted() || track->isPausing() ||
3125 mStreamTypes[track->streamType()].mute) {
3126 vl = vr = va = 0;
3127 if (track->isPausing()) {
3128 track->setPaused();
3129 }
3130 } else {
3131
3132 // read original volumes with volume control
3133 float typeVolume = mStreamTypes[track->streamType()].volume;
3134 float v = masterVolume * typeVolume;
3135 uint32_t vlr = cblk->getVolumeLR();
3136 vl = vlr & 0xFFFF;
3137 vr = vlr >> 16;
3138 // track volumes come from shared memory, so can't be trusted and must be clamped
3139 if (vl > MAX_GAIN_INT) {
3140 ALOGV("Track left volume out of range: %04X", vl);
3141 vl = MAX_GAIN_INT;
3142 }
3143 if (vr > MAX_GAIN_INT) {
3144 ALOGV("Track right volume out of range: %04X", vr);
3145 vr = MAX_GAIN_INT;
3146 }
3147 // now apply the master volume and stream type volume
3148 vl = (uint32_t)(v * vl) << 12;
3149 vr = (uint32_t)(v * vr) << 12;
3150 // assuming master volume and stream type volume each go up to 1.0,
3151 // vl and vr are now in 8.24 format
3152
3153 uint16_t sendLevel = cblk->getSendLevel_U4_12();
3154 // send level comes from shared memory and so may be corrupt
3155 if (sendLevel > MAX_GAIN_INT) {
3156 ALOGV("Track send level out of range: %04X", sendLevel);
3157 sendLevel = MAX_GAIN_INT;
3158 }
3159 va = (uint32_t)(v * sendLevel);
3160 }
3161 // Delegate volume control to effect in track effect chain if needed
3162 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3163 // Do not ramp volume if volume is controlled by effect
3164 param = AudioMixer::VOLUME;
3165 track->mHasVolumeController = true;
3166 } else {
3167 // force no volume ramp when volume controller was just disabled or removed
3168 // from effect chain to avoid volume spike
3169 if (track->mHasVolumeController) {
3170 param = AudioMixer::VOLUME;
3171 }
3172 track->mHasVolumeController = false;
3173 }
3174
3175 // Convert volumes from 8.24 to 4.12 format
3176 // This additional clamping is needed in case chain->setVolume_l() overshot
3177 vl = (vl + (1 << 11)) >> 12;
3178 if (vl > MAX_GAIN_INT) vl = MAX_GAIN_INT;
3179 vr = (vr + (1 << 11)) >> 12;
3180 if (vr > MAX_GAIN_INT) vr = MAX_GAIN_INT;
3181
3182 if (va > MAX_GAIN_INT) va = MAX_GAIN_INT; // va is uint32_t, so no need to check for -
3183
3184 // XXX: these things DON'T need to be done each time
3185 mAudioMixer->setBufferProvider(name, track);
3186 mAudioMixer->enable(name);
3187
3188 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
3189 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
3190 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
3191 mAudioMixer->setParameter(
3192 name,
3193 AudioMixer::TRACK,
3194 AudioMixer::FORMAT, (void *)track->format());
3195 mAudioMixer->setParameter(
3196 name,
3197 AudioMixer::TRACK,
3198 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
3199 mAudioMixer->setParameter(
3200 name,
3201 AudioMixer::RESAMPLE,
3202 AudioMixer::SAMPLE_RATE,
3203 (void *)(cblk->sampleRate));
3204 mAudioMixer->setParameter(
3205 name,
3206 AudioMixer::TRACK,
3207 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3208 mAudioMixer->setParameter(
3209 name,
3210 AudioMixer::TRACK,
3211 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3212
3213 // reset retry count
3214 track->mRetryCount = kMaxTrackRetries;
3215
3216 // If one track is ready, set the mixer ready if:
3217 // - the mixer was not ready during previous round OR
3218 // - no other track is not ready
3219 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
3220 mixerStatus != MIXER_TRACKS_ENABLED) {
3221 mixerStatus = MIXER_TRACKS_READY;
3222 }
3223 } else {
3224 // clear effect chain input buffer if an active track underruns to avoid sending
3225 // previous audio buffer again to effects
3226 chain = getEffectChain_l(track->sessionId());
3227 if (chain != 0) {
3228 chain->clearInputBuffer();
3229 }
3230
3231 //ALOGV("track %d u=%08x, s=%08x [NOT READY] on thread %p", name, cblk->user, cblk->server, this);
3232 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3233 track->isStopped() || track->isPaused()) {
3234 // We have consumed all the buffers of this track.
3235 // Remove it from the list of active tracks.
3236 // TODO: use actual buffer filling status instead of latency when available from
3237 // audio HAL
3238 size_t audioHALFrames =
3239 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3240 size_t framesWritten =
3241 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3242 if (track->presentationComplete(framesWritten, audioHALFrames)) {
3243 if (track->isStopped()) {
3244 track->reset();
3245 }
3246 tracksToRemove->add(track);
3247 }
3248 } else {
3249 track->mUnderrunCount++;
3250 // No buffers for this track. Give it a few chances to
3251 // fill a buffer, then remove it from active list.
3252 if (--(track->mRetryCount) <= 0) {
3253 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
3254 tracksToRemove->add(track);
3255 // indicate to client process that the track was disabled because of underrun;
3256 // it will then automatically call start() when data is available
3257 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
3258 // If one track is not ready, mark the mixer also not ready if:
3259 // - the mixer was ready during previous round OR
3260 // - no other track is ready
3261 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
3262 mixerStatus != MIXER_TRACKS_READY) {
3263 mixerStatus = MIXER_TRACKS_ENABLED;
3264 }
3265 }
3266 mAudioMixer->disable(name);
3267 }
3268
3269 } // local variable scope to avoid goto warning
3270 track_is_ready: ;
3271
3272 }
3273
3274 // Push the new FastMixer state if necessary
3275 bool pauseAudioWatchdog = false;
3276 if (didModify) {
3277 state->mFastTracksGen++;
3278 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3279 if (kUseFastMixer == FastMixer_Dynamic &&
3280 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3281 state->mCommand = FastMixerState::COLD_IDLE;
3282 state->mColdFutexAddr = &mFastMixerFutex;
3283 state->mColdGen++;
3284 mFastMixerFutex = 0;
3285 if (kUseFastMixer == FastMixer_Dynamic) {
3286 mNormalSink = mOutputSink;
3287 }
3288 // If we go into cold idle, need to wait for acknowledgement
3289 // so that fast mixer stops doing I/O.
3290 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3291 pauseAudioWatchdog = true;
3292 }
3293 sq->end();
3294 }
3295 if (sq != NULL) {
3296 sq->end(didModify);
3297 sq->push(block);
3298 }
3299 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3300 mAudioWatchdog->pause();
3301 }
3302
3303 // Now perform the deferred reset on fast tracks that have stopped
3304 while (resetMask != 0) {
3305 size_t i = __builtin_ctz(resetMask);
3306 ALOG_ASSERT(i < count);
3307 resetMask &= ~(1 << i);
3308 sp<Track> t = mActiveTracks[i].promote();
3309 if (t == 0) continue;
3310 Track* track = t.get();
3311 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3312 track->reset();
3313 }
3314
3315 // remove all the tracks that need to be...
3316 count = tracksToRemove->size();
3317 if (CC_UNLIKELY(count)) {
3318 for (size_t i=0 ; i<count ; i++) {
3319 const sp<Track>& track = tracksToRemove->itemAt(i);
3320 mActiveTracks.remove(track);
3321 if (track->mainBuffer() != mMixBuffer) {
3322 chain = getEffectChain_l(track->sessionId());
3323 if (chain != 0) {
3324 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
3325 chain->decActiveTrackCnt();
3326 }
3327 }
3328 if (track->isTerminated()) {
3329 removeTrack_l(track);
3330 }
3331 }
3332 }
3333
3334 // mix buffer must be cleared if all tracks are connected to an
3335 // effect chain as in this case the mixer will not write to
3336 // mix buffer and track effects will accumulate into it
3337 if ((mixedTracks != 0 && mixedTracks == tracksWithEffect) || (mixedTracks == 0 && fastTracks > 0)) {
3338 // FIXME as a performance optimization, should remember previous zero status
3339 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
3340 }
3341
3342 // if any fast tracks, then status is ready
3343 mMixerStatusIgnoringFastTracks = mixerStatus;
3344 if (fastTracks > 0) {
3345 mixerStatus = MIXER_TRACKS_READY;
3346 }
3347 return mixerStatus;
3348 }
3349
3350 /*
3351 The derived values that are cached:
3352 - mixBufferSize from frame count * frame size
3353 - activeSleepTime from activeSleepTimeUs()
3354 - idleSleepTime from idleSleepTimeUs()
3355 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
3356 - maxPeriod from frame count and sample rate (MIXER only)
3357
3358 The parameters that affect these derived values are:
3359 - frame count
3360 - frame size
3361 - sample rate
3362 - device type: A2DP or not
3363 - device latency
3364 - format: PCM or not
3365 - active sleep time
3366 - idle sleep time
3367 */
3368
cacheParameters_l()3369 void AudioFlinger::PlaybackThread::cacheParameters_l()
3370 {
3371 mixBufferSize = mNormalFrameCount * mFrameSize;
3372 activeSleepTime = activeSleepTimeUs();
3373 idleSleepTime = idleSleepTimeUs();
3374 }
3375
invalidateTracks(audio_stream_type_t streamType)3376 void AudioFlinger::MixerThread::invalidateTracks(audio_stream_type_t streamType)
3377 {
3378 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
3379 this, streamType, mTracks.size());
3380 Mutex::Autolock _l(mLock);
3381
3382 size_t size = mTracks.size();
3383 for (size_t i = 0; i < size; i++) {
3384 sp<Track> t = mTracks[i];
3385 if (t->streamType() == streamType) {
3386 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
3387 t->mCblk->cv.signal();
3388 }
3389 }
3390 }
3391
3392 // getTrackName_l() must be called with ThreadBase::mLock held
getTrackName_l(audio_channel_mask_t channelMask)3393 int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask)
3394 {
3395 return mAudioMixer->getTrackName(channelMask);
3396 }
3397
3398 // deleteTrackName_l() must be called with ThreadBase::mLock held
deleteTrackName_l(int name)3399 void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3400 {
3401 ALOGV("remove track (%d) and delete from mixer", name);
3402 mAudioMixer->deleteTrackName(name);
3403 }
3404
3405 // checkForNewParameters_l() must be called with ThreadBase::mLock held
checkForNewParameters_l()3406 bool AudioFlinger::MixerThread::checkForNewParameters_l()
3407 {
3408 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3409 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3410 bool reconfig = false;
3411
3412 while (!mNewParameters.isEmpty()) {
3413
3414 if (mFastMixer != NULL) {
3415 FastMixerStateQueue *sq = mFastMixer->sq();
3416 FastMixerState *state = sq->begin();
3417 if (!(state->mCommand & FastMixerState::IDLE)) {
3418 previousCommand = state->mCommand;
3419 state->mCommand = FastMixerState::HOT_IDLE;
3420 sq->end();
3421 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3422 } else {
3423 sq->end(false /*didModify*/);
3424 }
3425 }
3426
3427 status_t status = NO_ERROR;
3428 String8 keyValuePair = mNewParameters[0];
3429 AudioParameter param = AudioParameter(keyValuePair);
3430 int value;
3431
3432 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3433 reconfig = true;
3434 }
3435 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
3436 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
3437 status = BAD_VALUE;
3438 } else {
3439 reconfig = true;
3440 }
3441 }
3442 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
3443 if (value != AUDIO_CHANNEL_OUT_STEREO) {
3444 status = BAD_VALUE;
3445 } else {
3446 reconfig = true;
3447 }
3448 }
3449 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3450 // do not accept frame count changes if tracks are open as the track buffer
3451 // size depends on frame count and correct behavior would not be guaranteed
3452 // if frame count is changed after track creation
3453 if (!mTracks.isEmpty()) {
3454 status = INVALID_OPERATION;
3455 } else {
3456 reconfig = true;
3457 }
3458 }
3459 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
3460 #ifdef ADD_BATTERY_DATA
3461 // when changing the audio output device, call addBatteryData to notify
3462 // the change
3463 if ((int)mDevice != value) {
3464 uint32_t params = 0;
3465 // check whether speaker is on
3466 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
3467 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3468 }
3469
3470 int deviceWithoutSpeaker
3471 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3472 // check if any other device (except speaker) is on
3473 if (value & deviceWithoutSpeaker ) {
3474 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3475 }
3476
3477 if (params != 0) {
3478 addBatteryData(params);
3479 }
3480 }
3481 #endif
3482
3483 // forward device change to effects that have requested to be
3484 // aware of attached audio device.
3485 mDevice = (uint32_t)value;
3486 for (size_t i = 0; i < mEffectChains.size(); i++) {
3487 mEffectChains[i]->setDevice_l(mDevice);
3488 }
3489 }
3490
3491 if (status == NO_ERROR) {
3492 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3493 keyValuePair.string());
3494 if (!mStandby && status == INVALID_OPERATION) {
3495 mOutput->stream->common.standby(&mOutput->stream->common);
3496 mStandby = true;
3497 mBytesWritten = 0;
3498 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3499 keyValuePair.string());
3500 }
3501 if (status == NO_ERROR && reconfig) {
3502 delete mAudioMixer;
3503 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
3504 mAudioMixer = NULL;
3505 readOutputParameters();
3506 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3507 for (size_t i = 0; i < mTracks.size() ; i++) {
3508 int name = getTrackName_l((audio_channel_mask_t)mTracks[i]->mChannelMask);
3509 if (name < 0) break;
3510 mTracks[i]->mName = name;
3511 // limit track sample rate to 2 x new output sample rate
3512 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
3513 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
3514 }
3515 }
3516 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3517 }
3518 }
3519
3520 mNewParameters.removeAt(0);
3521
3522 mParamStatus = status;
3523 mParamCond.signal();
3524 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3525 // already timed out waiting for the status and will never signal the condition.
3526 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
3527 }
3528
3529 if (!(previousCommand & FastMixerState::IDLE)) {
3530 ALOG_ASSERT(mFastMixer != NULL);
3531 FastMixerStateQueue *sq = mFastMixer->sq();
3532 FastMixerState *state = sq->begin();
3533 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3534 state->mCommand = previousCommand;
3535 sq->end();
3536 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3537 }
3538
3539 return reconfig;
3540 }
3541
dumpInternals(int fd,const Vector<String16> & args)3542 status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3543 {
3544 const size_t SIZE = 256;
3545 char buffer[SIZE];
3546 String8 result;
3547
3548 PlaybackThread::dumpInternals(fd, args);
3549
3550 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3551 result.append(buffer);
3552 write(fd, result.string(), result.size());
3553
3554 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
3555 FastMixerDumpState copy = mFastMixerDumpState;
3556 copy.dump(fd);
3557
3558 #ifdef STATE_QUEUE_DUMP
3559 // Similar for state queue
3560 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3561 observerCopy.dump(fd);
3562 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3563 mutatorCopy.dump(fd);
3564 #endif
3565
3566 // Write the tee output to a .wav file
3567 NBAIO_Source *teeSource = mTeeSource.get();
3568 if (teeSource != NULL) {
3569 char teePath[64];
3570 struct timeval tv;
3571 gettimeofday(&tv, NULL);
3572 struct tm tm;
3573 localtime_r(&tv.tv_sec, &tm);
3574 strftime(teePath, sizeof(teePath), "/data/misc/media/%T.wav", &tm);
3575 int teeFd = open(teePath, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
3576 if (teeFd >= 0) {
3577 char wavHeader[44];
3578 memcpy(wavHeader,
3579 "RIFF\0\0\0\0WAVEfmt \20\0\0\0\1\0\2\0\104\254\0\0\0\0\0\0\4\0\20\0data\0\0\0\0",
3580 sizeof(wavHeader));
3581 NBAIO_Format format = teeSource->format();
3582 unsigned channelCount = Format_channelCount(format);
3583 ALOG_ASSERT(channelCount <= FCC_2);
3584 unsigned sampleRate = Format_sampleRate(format);
3585 wavHeader[22] = channelCount; // number of channels
3586 wavHeader[24] = sampleRate; // sample rate
3587 wavHeader[25] = sampleRate >> 8;
3588 wavHeader[32] = channelCount * 2; // block alignment
3589 write(teeFd, wavHeader, sizeof(wavHeader));
3590 size_t total = 0;
3591 bool firstRead = true;
3592 for (;;) {
3593 #define TEE_SINK_READ 1024
3594 short buffer[TEE_SINK_READ * FCC_2];
3595 size_t count = TEE_SINK_READ;
3596 ssize_t actual = teeSource->read(buffer, count);
3597 bool wasFirstRead = firstRead;
3598 firstRead = false;
3599 if (actual <= 0) {
3600 if (actual == (ssize_t) OVERRUN && wasFirstRead) {
3601 continue;
3602 }
3603 break;
3604 }
3605 ALOG_ASSERT(actual <= count);
3606 write(teeFd, buffer, actual * channelCount * sizeof(short));
3607 total += actual;
3608 }
3609 lseek(teeFd, (off_t) 4, SEEK_SET);
3610 uint32_t temp = 44 + total * channelCount * sizeof(short) - 8;
3611 write(teeFd, &temp, sizeof(temp));
3612 lseek(teeFd, (off_t) 40, SEEK_SET);
3613 temp = total * channelCount * sizeof(short);
3614 write(teeFd, &temp, sizeof(temp));
3615 close(teeFd);
3616 fdprintf(fd, "FastMixer tee copied to %s\n", teePath);
3617 } else {
3618 fdprintf(fd, "FastMixer unable to create tee %s: \n", strerror(errno));
3619 }
3620 }
3621
3622 if (mAudioWatchdog != 0) {
3623 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3624 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3625 wdCopy.dump(fd);
3626 }
3627
3628 return NO_ERROR;
3629 }
3630
idleSleepTimeUs() const3631 uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
3632 {
3633 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
3634 }
3635
suspendSleepTimeUs() const3636 uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
3637 {
3638 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3639 }
3640
cacheParameters_l()3641 void AudioFlinger::MixerThread::cacheParameters_l()
3642 {
3643 PlaybackThread::cacheParameters_l();
3644
3645 // FIXME: Relaxed timing because of a certain device that can't meet latency
3646 // Should be reduced to 2x after the vendor fixes the driver issue
3647 // increase threshold again due to low power audio mode. The way this warning
3648 // threshold is calculated and its usefulness should be reconsidered anyway.
3649 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
3650 }
3651
3652 // ----------------------------------------------------------------------------
DirectOutputThread(const sp<AudioFlinger> & audioFlinger,AudioStreamOut * output,audio_io_handle_t id,uint32_t device)3653 AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3654 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
3655 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
3656 // mLeftVolFloat, mRightVolFloat
3657 {
3658 }
3659
~DirectOutputThread()3660 AudioFlinger::DirectOutputThread::~DirectOutputThread()
3661 {
3662 }
3663
prepareTracks_l(Vector<sp<Track>> * tracksToRemove)3664 AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3665 Vector< sp<Track> > *tracksToRemove
3666 )
3667 {
3668 sp<Track> trackToRemove;
3669
3670 mixer_state mixerStatus = MIXER_IDLE;
3671
3672 // find out which tracks need to be processed
3673 if (mActiveTracks.size() != 0) {
3674 sp<Track> t = mActiveTracks[0].promote();
3675 // The track died recently
3676 if (t == 0) return MIXER_IDLE;
3677
3678 Track* const track = t.get();
3679 audio_track_cblk_t* cblk = track->cblk();
3680
3681 // The first time a track is added we wait
3682 // for all its buffers to be filled before processing it
3683 uint32_t minFrames;
3684 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) {
3685 minFrames = mNormalFrameCount;
3686 } else {
3687 minFrames = 1;
3688 }
3689 if ((track->framesReady() >= minFrames) && track->isReady() &&
3690 !track->isPaused() && !track->isTerminated())
3691 {
3692 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
3693
3694 if (track->mFillingUpStatus == Track::FS_FILLED) {
3695 track->mFillingUpStatus = Track::FS_ACTIVE;
3696 mLeftVolFloat = mRightVolFloat = 0;
3697 if (track->mState == TrackBase::RESUMING) {
3698 track->mState = TrackBase::ACTIVE;
3699 }
3700 }
3701
3702 // compute volume for this track
3703 float left, right;
3704 if (track->isMuted() || mMasterMute || track->isPausing() ||
3705 mStreamTypes[track->streamType()].mute) {
3706 left = right = 0;
3707 if (track->isPausing()) {
3708 track->setPaused();
3709 }
3710 } else {
3711 float typeVolume = mStreamTypes[track->streamType()].volume;
3712 float v = mMasterVolume * typeVolume;
3713 uint32_t vlr = cblk->getVolumeLR();
3714 float v_clamped = v * (vlr & 0xFFFF);
3715 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3716 left = v_clamped/MAX_GAIN;
3717 v_clamped = v * (vlr >> 16);
3718 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3719 right = v_clamped/MAX_GAIN;
3720 }
3721
3722 if (left != mLeftVolFloat || right != mRightVolFloat) {
3723 mLeftVolFloat = left;
3724 mRightVolFloat = right;
3725
3726 // Convert volumes from float to 8.24
3727 uint32_t vl = (uint32_t)(left * (1 << 24));
3728 uint32_t vr = (uint32_t)(right * (1 << 24));
3729
3730 // Delegate volume control to effect in track effect chain if needed
3731 // only one effect chain can be present on DirectOutputThread, so if
3732 // there is one, the track is connected to it
3733 if (!mEffectChains.isEmpty()) {
3734 // Do not ramp volume if volume is controlled by effect
3735 mEffectChains[0]->setVolume_l(&vl, &vr);
3736 left = (float)vl / (1 << 24);
3737 right = (float)vr / (1 << 24);
3738 }
3739 mOutput->stream->set_volume(mOutput->stream, left, right);
3740 }
3741
3742 // reset retry count
3743 track->mRetryCount = kMaxTrackRetriesDirect;
3744 mActiveTrack = t;
3745 mixerStatus = MIXER_TRACKS_READY;
3746 } else {
3747 // clear effect chain input buffer if an active track underruns to avoid sending
3748 // previous audio buffer again to effects
3749 if (!mEffectChains.isEmpty()) {
3750 mEffectChains[0]->clearInputBuffer();
3751 }
3752
3753 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
3754 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3755 track->isStopped() || track->isPaused()) {
3756 // We have consumed all the buffers of this track.
3757 // Remove it from the list of active tracks.
3758 // TODO: implement behavior for compressed audio
3759 size_t audioHALFrames =
3760 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3761 size_t framesWritten =
3762 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3763 if (track->presentationComplete(framesWritten, audioHALFrames)) {
3764 if (track->isStopped()) {
3765 track->reset();
3766 }
3767 trackToRemove = track;
3768 }
3769 } else {
3770 // No buffers for this track. Give it a few chances to
3771 // fill a buffer, then remove it from active list.
3772 if (--(track->mRetryCount) <= 0) {
3773 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
3774 trackToRemove = track;
3775 } else {
3776 mixerStatus = MIXER_TRACKS_ENABLED;
3777 }
3778 }
3779 }
3780 }
3781
3782 // FIXME merge this with similar code for removing multiple tracks
3783 // remove all the tracks that need to be...
3784 if (CC_UNLIKELY(trackToRemove != 0)) {
3785 tracksToRemove->add(trackToRemove);
3786 mActiveTracks.remove(trackToRemove);
3787 if (!mEffectChains.isEmpty()) {
3788 ALOGV("stopping track on chain %p for session Id: %d", mEffectChains[0].get(),
3789 trackToRemove->sessionId());
3790 mEffectChains[0]->decActiveTrackCnt();
3791 }
3792 if (trackToRemove->isTerminated()) {
3793 removeTrack_l(trackToRemove);
3794 }
3795 }
3796
3797 return mixerStatus;
3798 }
3799
threadLoop_mix()3800 void AudioFlinger::DirectOutputThread::threadLoop_mix()
3801 {
3802 AudioBufferProvider::Buffer buffer;
3803 size_t frameCount = mFrameCount;
3804 int8_t *curBuf = (int8_t *)mMixBuffer;
3805 // output audio to hardware
3806 while (frameCount) {
3807 buffer.frameCount = frameCount;
3808 mActiveTrack->getNextBuffer(&buffer);
3809 if (CC_UNLIKELY(buffer.raw == NULL)) {
3810 memset(curBuf, 0, frameCount * mFrameSize);
3811 break;
3812 }
3813 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3814 frameCount -= buffer.frameCount;
3815 curBuf += buffer.frameCount * mFrameSize;
3816 mActiveTrack->releaseBuffer(&buffer);
3817 }
3818 sleepTime = 0;
3819 standbyTime = systemTime() + standbyDelay;
3820 mActiveTrack.clear();
3821
3822 }
3823
threadLoop_sleepTime()3824 void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3825 {
3826 if (sleepTime == 0) {
3827 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3828 sleepTime = activeSleepTime;
3829 } else {
3830 sleepTime = idleSleepTime;
3831 }
3832 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
3833 memset(mMixBuffer, 0, mFrameCount * mFrameSize);
3834 sleepTime = 0;
3835 }
3836 }
3837
3838 // getTrackName_l() must be called with ThreadBase::mLock held
getTrackName_l(audio_channel_mask_t channelMask)3839 int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask)
3840 {
3841 return 0;
3842 }
3843
3844 // deleteTrackName_l() must be called with ThreadBase::mLock held
deleteTrackName_l(int name)3845 void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3846 {
3847 }
3848
3849 // checkForNewParameters_l() must be called with ThreadBase::mLock held
checkForNewParameters_l()3850 bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3851 {
3852 bool reconfig = false;
3853
3854 while (!mNewParameters.isEmpty()) {
3855 status_t status = NO_ERROR;
3856 String8 keyValuePair = mNewParameters[0];
3857 AudioParameter param = AudioParameter(keyValuePair);
3858 int value;
3859
3860 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3861 // do not accept frame count changes if tracks are open as the track buffer
3862 // size depends on frame count and correct behavior would not be garantied
3863 // if frame count is changed after track creation
3864 if (!mTracks.isEmpty()) {
3865 status = INVALID_OPERATION;
3866 } else {
3867 reconfig = true;
3868 }
3869 }
3870 if (status == NO_ERROR) {
3871 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3872 keyValuePair.string());
3873 if (!mStandby && status == INVALID_OPERATION) {
3874 mOutput->stream->common.standby(&mOutput->stream->common);
3875 mStandby = true;
3876 mBytesWritten = 0;
3877 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3878 keyValuePair.string());
3879 }
3880 if (status == NO_ERROR && reconfig) {
3881 readOutputParameters();
3882 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3883 }
3884 }
3885
3886 mNewParameters.removeAt(0);
3887
3888 mParamStatus = status;
3889 mParamCond.signal();
3890 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3891 // already timed out waiting for the status and will never signal the condition.
3892 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
3893 }
3894 return reconfig;
3895 }
3896
activeSleepTimeUs() const3897 uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
3898 {
3899 uint32_t time;
3900 if (audio_is_linear_pcm(mFormat)) {
3901 time = PlaybackThread::activeSleepTimeUs();
3902 } else {
3903 time = 10000;
3904 }
3905 return time;
3906 }
3907
idleSleepTimeUs() const3908 uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
3909 {
3910 uint32_t time;
3911 if (audio_is_linear_pcm(mFormat)) {
3912 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
3913 } else {
3914 time = 10000;
3915 }
3916 return time;
3917 }
3918
suspendSleepTimeUs() const3919 uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
3920 {
3921 uint32_t time;
3922 if (audio_is_linear_pcm(mFormat)) {
3923 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3924 } else {
3925 time = 10000;
3926 }
3927 return time;
3928 }
3929
cacheParameters_l()3930 void AudioFlinger::DirectOutputThread::cacheParameters_l()
3931 {
3932 PlaybackThread::cacheParameters_l();
3933
3934 // use shorter standby delay as on normal output to release
3935 // hardware resources as soon as possible
3936 standbyDelay = microseconds(activeSleepTime*2);
3937 }
3938
3939 // ----------------------------------------------------------------------------
3940
DuplicatingThread(const sp<AudioFlinger> & audioFlinger,AudioFlinger::MixerThread * mainThread,audio_io_handle_t id)3941 AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
3942 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
3943 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
3944 mWaitTimeMs(UINT_MAX)
3945 {
3946 addOutputTrack(mainThread);
3947 }
3948
~DuplicatingThread()3949 AudioFlinger::DuplicatingThread::~DuplicatingThread()
3950 {
3951 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3952 mOutputTracks[i]->destroy();
3953 }
3954 }
3955
threadLoop_mix()3956 void AudioFlinger::DuplicatingThread::threadLoop_mix()
3957 {
3958 // mix buffers...
3959 if (outputsReady(outputTracks)) {
3960 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
3961 } else {
3962 memset(mMixBuffer, 0, mixBufferSize);
3963 }
3964 sleepTime = 0;
3965 writeFrames = mNormalFrameCount;
3966 standbyTime = systemTime() + standbyDelay;
3967 }
3968
threadLoop_sleepTime()3969 void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
3970 {
3971 if (sleepTime == 0) {
3972 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3973 sleepTime = activeSleepTime;
3974 } else {
3975 sleepTime = idleSleepTime;
3976 }
3977 } else if (mBytesWritten != 0) {
3978 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3979 writeFrames = mNormalFrameCount;
3980 memset(mMixBuffer, 0, mixBufferSize);
3981 } else {
3982 // flush remaining overflow buffers in output tracks
3983 writeFrames = 0;
3984 }
3985 sleepTime = 0;
3986 }
3987 }
3988
threadLoop_write()3989 void AudioFlinger::DuplicatingThread::threadLoop_write()
3990 {
3991 for (size_t i = 0; i < outputTracks.size(); i++) {
3992 outputTracks[i]->write(mMixBuffer, writeFrames);
3993 }
3994 mBytesWritten += mixBufferSize;
3995 }
3996
threadLoop_standby()3997 void AudioFlinger::DuplicatingThread::threadLoop_standby()
3998 {
3999 // DuplicatingThread implements standby by stopping all tracks
4000 for (size_t i = 0; i < outputTracks.size(); i++) {
4001 outputTracks[i]->stop();
4002 }
4003 }
4004
saveOutputTracks()4005 void AudioFlinger::DuplicatingThread::saveOutputTracks()
4006 {
4007 outputTracks = mOutputTracks;
4008 }
4009
clearOutputTracks()4010 void AudioFlinger::DuplicatingThread::clearOutputTracks()
4011 {
4012 outputTracks.clear();
4013 }
4014
addOutputTrack(MixerThread * thread)4015 void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4016 {
4017 Mutex::Autolock _l(mLock);
4018 // FIXME explain this formula
4019 int frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
4020 OutputTrack *outputTrack = new OutputTrack(thread,
4021 this,
4022 mSampleRate,
4023 mFormat,
4024 mChannelMask,
4025 frameCount);
4026 if (outputTrack->cblk() != NULL) {
4027 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
4028 mOutputTracks.add(outputTrack);
4029 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
4030 updateWaitTime_l();
4031 }
4032 }
4033
removeOutputTrack(MixerThread * thread)4034 void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4035 {
4036 Mutex::Autolock _l(mLock);
4037 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4038 if (mOutputTracks[i]->thread() == thread) {
4039 mOutputTracks[i]->destroy();
4040 mOutputTracks.removeAt(i);
4041 updateWaitTime_l();
4042 return;
4043 }
4044 }
4045 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
4046 }
4047
4048 // caller must hold mLock
updateWaitTime_l()4049 void AudioFlinger::DuplicatingThread::updateWaitTime_l()
4050 {
4051 mWaitTimeMs = UINT_MAX;
4052 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4053 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
4054 if (strong != 0) {
4055 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4056 if (waitTimeMs < mWaitTimeMs) {
4057 mWaitTimeMs = waitTimeMs;
4058 }
4059 }
4060 }
4061 }
4062
4063
outputsReady(const SortedVector<sp<OutputTrack>> & outputTracks)4064 bool AudioFlinger::DuplicatingThread::outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks)
4065 {
4066 for (size_t i = 0; i < outputTracks.size(); i++) {
4067 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
4068 if (thread == 0) {
4069 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
4070 return false;
4071 }
4072 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4073 if (playbackThread->standby() && !playbackThread->isSuspended()) {
4074 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
4075 return false;
4076 }
4077 }
4078 return true;
4079 }
4080
activeSleepTimeUs() const4081 uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
4082 {
4083 return (mWaitTimeMs * 1000) / 2;
4084 }
4085
cacheParameters_l()4086 void AudioFlinger::DuplicatingThread::cacheParameters_l()
4087 {
4088 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4089 updateWaitTime_l();
4090
4091 MixerThread::cacheParameters_l();
4092 }
4093
4094 // ----------------------------------------------------------------------------
4095
4096 // TrackBase constructor must be called with AudioFlinger::mLock held
TrackBase(ThreadBase * thread,const sp<Client> & client,uint32_t sampleRate,audio_format_t format,uint32_t channelMask,int frameCount,const sp<IMemory> & sharedBuffer,int sessionId)4097 AudioFlinger::ThreadBase::TrackBase::TrackBase(
4098 ThreadBase *thread,
4099 const sp<Client>& client,
4100 uint32_t sampleRate,
4101 audio_format_t format,
4102 uint32_t channelMask,
4103 int frameCount,
4104 const sp<IMemory>& sharedBuffer,
4105 int sessionId)
4106 : RefBase(),
4107 mThread(thread),
4108 mClient(client),
4109 mCblk(NULL),
4110 // mBuffer
4111 // mBufferEnd
4112 mFrameCount(0),
4113 mState(IDLE),
4114 mSampleRate(sampleRate),
4115 mFormat(format),
4116 mStepServerFailed(false),
4117 mSessionId(sessionId)
4118 // mChannelCount
4119 // mChannelMask
4120 {
4121 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
4122
4123 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
4124 size_t size = sizeof(audio_track_cblk_t);
4125 uint8_t channelCount = popcount(channelMask);
4126 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
4127 if (sharedBuffer == 0) {
4128 size += bufferSize;
4129 }
4130
4131 if (client != NULL) {
4132 mCblkMemory = client->heap()->allocate(size);
4133 if (mCblkMemory != 0) {
4134 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
4135 if (mCblk != NULL) { // construct the shared structure in-place.
4136 new(mCblk) audio_track_cblk_t();
4137 // clear all buffers
4138 mCblk->frameCount = frameCount;
4139 mCblk->sampleRate = sampleRate;
4140 // uncomment the following lines to quickly test 32-bit wraparound
4141 // mCblk->user = 0xffff0000;
4142 // mCblk->server = 0xffff0000;
4143 // mCblk->userBase = 0xffff0000;
4144 // mCblk->serverBase = 0xffff0000;
4145 mChannelCount = channelCount;
4146 mChannelMask = channelMask;
4147 if (sharedBuffer == 0) {
4148 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4149 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4150 // Force underrun condition to avoid false underrun callback until first data is
4151 // written to buffer (other flags are cleared)
4152 mCblk->flags = CBLK_UNDERRUN_ON;
4153 } else {
4154 mBuffer = sharedBuffer->pointer();
4155 }
4156 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
4157 }
4158 } else {
4159 ALOGE("not enough memory for AudioTrack size=%u", size);
4160 client->heap()->dump("AudioTrack");
4161 return;
4162 }
4163 } else {
4164 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
4165 // construct the shared structure in-place.
4166 new(mCblk) audio_track_cblk_t();
4167 // clear all buffers
4168 mCblk->frameCount = frameCount;
4169 mCblk->sampleRate = sampleRate;
4170 // uncomment the following lines to quickly test 32-bit wraparound
4171 // mCblk->user = 0xffff0000;
4172 // mCblk->server = 0xffff0000;
4173 // mCblk->userBase = 0xffff0000;
4174 // mCblk->serverBase = 0xffff0000;
4175 mChannelCount = channelCount;
4176 mChannelMask = channelMask;
4177 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4178 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4179 // Force underrun condition to avoid false underrun callback until first data is
4180 // written to buffer (other flags are cleared)
4181 mCblk->flags = CBLK_UNDERRUN_ON;
4182 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
4183 }
4184 }
4185
~TrackBase()4186 AudioFlinger::ThreadBase::TrackBase::~TrackBase()
4187 {
4188 if (mCblk != NULL) {
4189 if (mClient == 0) {
4190 delete mCblk;
4191 } else {
4192 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
4193 }
4194 }
4195 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
4196 if (mClient != 0) {
4197 // Client destructor must run with AudioFlinger mutex locked
4198 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
4199 // If the client's reference count drops to zero, the associated destructor
4200 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
4201 // relying on the automatic clear() at end of scope.
4202 mClient.clear();
4203 }
4204 }
4205
4206 // AudioBufferProvider interface
4207 // getNextBuffer() = 0;
4208 // This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
releaseBuffer(AudioBufferProvider::Buffer * buffer)4209 void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4210 {
4211 buffer->raw = NULL;
4212 mFrameCount = buffer->frameCount;
4213 // FIXME See note at getNextBuffer()
4214 (void) step(); // ignore return value of step()
4215 buffer->frameCount = 0;
4216 }
4217
step()4218 bool AudioFlinger::ThreadBase::TrackBase::step() {
4219 bool result;
4220 audio_track_cblk_t* cblk = this->cblk();
4221
4222 result = cblk->stepServer(mFrameCount);
4223 if (!result) {
4224 ALOGV("stepServer failed acquiring cblk mutex");
4225 mStepServerFailed = true;
4226 }
4227 return result;
4228 }
4229
reset()4230 void AudioFlinger::ThreadBase::TrackBase::reset() {
4231 audio_track_cblk_t* cblk = this->cblk();
4232
4233 cblk->user = 0;
4234 cblk->server = 0;
4235 cblk->userBase = 0;
4236 cblk->serverBase = 0;
4237 mStepServerFailed = false;
4238 ALOGV("TrackBase::reset");
4239 }
4240
sampleRate() const4241 int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
4242 return (int)mCblk->sampleRate;
4243 }
4244
getBuffer(uint32_t offset,uint32_t frames) const4245 void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
4246 audio_track_cblk_t* cblk = this->cblk();
4247 size_t frameSize = cblk->frameSize;
4248 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
4249 int8_t *bufferEnd = bufferStart + frames * frameSize;
4250
4251 // Check validity of returned pointer in case the track control block would have been corrupted.
4252 ALOG_ASSERT(!(bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd),
4253 "TrackBase::getBuffer buffer out of range:\n"
4254 " start: %p, end %p , mBuffer %p mBufferEnd %p\n"
4255 " server %u, serverBase %u, user %u, userBase %u, frameSize %d",
4256 bufferStart, bufferEnd, mBuffer, mBufferEnd,
4257 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, frameSize);
4258
4259 return bufferStart;
4260 }
4261
setSyncEvent(const sp<SyncEvent> & event)4262 status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
4263 {
4264 mSyncEvents.add(event);
4265 return NO_ERROR;
4266 }
4267
4268 // ----------------------------------------------------------------------------
4269
4270 // Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
Track(PlaybackThread * thread,const sp<Client> & client,audio_stream_type_t streamType,uint32_t sampleRate,audio_format_t format,uint32_t channelMask,int frameCount,const sp<IMemory> & sharedBuffer,int sessionId,IAudioFlinger::track_flags_t flags)4271 AudioFlinger::PlaybackThread::Track::Track(
4272 PlaybackThread *thread,
4273 const sp<Client>& client,
4274 audio_stream_type_t streamType,
4275 uint32_t sampleRate,
4276 audio_format_t format,
4277 uint32_t channelMask,
4278 int frameCount,
4279 const sp<IMemory>& sharedBuffer,
4280 int sessionId,
4281 IAudioFlinger::track_flags_t flags)
4282 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer, sessionId),
4283 mMute(false),
4284 mFillingUpStatus(FS_INVALID),
4285 // mRetryCount initialized later when needed
4286 mSharedBuffer(sharedBuffer),
4287 mStreamType(streamType),
4288 mName(-1), // see note below
4289 mMainBuffer(thread->mixBuffer()),
4290 mAuxBuffer(NULL),
4291 mAuxEffectId(0), mHasVolumeController(false),
4292 mPresentationCompleteFrames(0),
4293 mFlags(flags),
4294 mFastIndex(-1),
4295 mUnderrunCount(0),
4296 mCachedVolume(1.0)
4297 {
4298 if (mCblk != NULL) {
4299 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
4300 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
4301 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
4302 // to avoid leaking a track name, do not allocate one unless there is an mCblk
4303 mName = thread->getTrackName_l((audio_channel_mask_t)channelMask);
4304 mCblk->mName = mName;
4305 if (mName < 0) {
4306 ALOGE("no more track names available");
4307 return;
4308 }
4309 // only allocate a fast track index if we were able to allocate a normal track name
4310 if (flags & IAudioFlinger::TRACK_FAST) {
4311 mCblk->flags |= CBLK_FAST; // atomic op not needed yet
4312 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
4313 int i = __builtin_ctz(thread->mFastTrackAvailMask);
4314 ALOG_ASSERT(0 < i && i < (int)FastMixerState::kMaxFastTracks);
4315 // FIXME This is too eager. We allocate a fast track index before the
4316 // fast track becomes active. Since fast tracks are a scarce resource,
4317 // this means we are potentially denying other more important fast tracks from
4318 // being created. It would be better to allocate the index dynamically.
4319 mFastIndex = i;
4320 mCblk->mName = i;
4321 // Read the initial underruns because this field is never cleared by the fast mixer
4322 mObservedUnderruns = thread->getFastTrackUnderruns(i);
4323 thread->mFastTrackAvailMask &= ~(1 << i);
4324 }
4325 }
4326 ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
4327 }
4328
~Track()4329 AudioFlinger::PlaybackThread::Track::~Track()
4330 {
4331 ALOGV("PlaybackThread::Track destructor");
4332 sp<ThreadBase> thread = mThread.promote();
4333 if (thread != 0) {
4334 Mutex::Autolock _l(thread->mLock);
4335 mState = TERMINATED;
4336 }
4337 }
4338
destroy()4339 void AudioFlinger::PlaybackThread::Track::destroy()
4340 {
4341 // NOTE: destroyTrack_l() can remove a strong reference to this Track
4342 // by removing it from mTracks vector, so there is a risk that this Tracks's
4343 // destructor is called. As the destructor needs to lock mLock,
4344 // we must acquire a strong reference on this Track before locking mLock
4345 // here so that the destructor is called only when exiting this function.
4346 // On the other hand, as long as Track::destroy() is only called by
4347 // TrackHandle destructor, the TrackHandle still holds a strong ref on
4348 // this Track with its member mTrack.
4349 sp<Track> keep(this);
4350 { // scope for mLock
4351 sp<ThreadBase> thread = mThread.promote();
4352 if (thread != 0) {
4353 if (!isOutputTrack()) {
4354 if (mState == ACTIVE || mState == RESUMING) {
4355 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
4356
4357 #ifdef ADD_BATTERY_DATA
4358 // to track the speaker usage
4359 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
4360 #endif
4361 }
4362 AudioSystem::releaseOutput(thread->id());
4363 }
4364 Mutex::Autolock _l(thread->mLock);
4365 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4366 playbackThread->destroyTrack_l(this);
4367 }
4368 }
4369 }
4370
appendDumpHeader(String8 & result)4371 /*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
4372 {
4373 result.append(" Name Client Type Fmt Chn mask Session mFrCnt fCount S M F SRate L dB R dB "
4374 " Server User Main buf Aux Buf Flags Underruns\n");
4375 }
4376
dump(char * buffer,size_t size)4377 void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
4378 {
4379 uint32_t vlr = mCblk->getVolumeLR();
4380 if (isFastTrack()) {
4381 sprintf(buffer, " F %2d", mFastIndex);
4382 } else {
4383 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
4384 }
4385 track_state state = mState;
4386 char stateChar;
4387 switch (state) {
4388 case IDLE:
4389 stateChar = 'I';
4390 break;
4391 case TERMINATED:
4392 stateChar = 'T';
4393 break;
4394 case STOPPING_1:
4395 stateChar = 's';
4396 break;
4397 case STOPPING_2:
4398 stateChar = '5';
4399 break;
4400 case STOPPED:
4401 stateChar = 'S';
4402 break;
4403 case RESUMING:
4404 stateChar = 'R';
4405 break;
4406 case ACTIVE:
4407 stateChar = 'A';
4408 break;
4409 case PAUSING:
4410 stateChar = 'p';
4411 break;
4412 case PAUSED:
4413 stateChar = 'P';
4414 break;
4415 case FLUSHED:
4416 stateChar = 'F';
4417 break;
4418 default:
4419 stateChar = '?';
4420 break;
4421 }
4422 char nowInUnderrun;
4423 switch (mObservedUnderruns.mBitFields.mMostRecent) {
4424 case UNDERRUN_FULL:
4425 nowInUnderrun = ' ';
4426 break;
4427 case UNDERRUN_PARTIAL:
4428 nowInUnderrun = '<';
4429 break;
4430 case UNDERRUN_EMPTY:
4431 nowInUnderrun = '*';
4432 break;
4433 default:
4434 nowInUnderrun = '?';
4435 break;
4436 }
4437 snprintf(&buffer[7], size-7, " %6d %4u %3u 0x%08x %7u %6u %6u %1c %1d %1d %5u %5.2g %5.2g "
4438 "0x%08x 0x%08x 0x%08x 0x%08x %#5x %9u%c\n",
4439 (mClient == 0) ? getpid_cached : mClient->pid(),
4440 mStreamType,
4441 mFormat,
4442 mChannelMask,
4443 mSessionId,
4444 mFrameCount,
4445 mCblk->frameCount,
4446 stateChar,
4447 mMute,
4448 mFillingUpStatus,
4449 mCblk->sampleRate,
4450 20.0 * log10((vlr & 0xFFFF) / 4096.0),
4451 20.0 * log10((vlr >> 16) / 4096.0),
4452 mCblk->server,
4453 mCblk->user,
4454 (int)mMainBuffer,
4455 (int)mAuxBuffer,
4456 mCblk->flags,
4457 mUnderrunCount,
4458 nowInUnderrun);
4459 }
4460
4461 // AudioBufferProvider interface
getNextBuffer(AudioBufferProvider::Buffer * buffer,int64_t pts)4462 status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
4463 AudioBufferProvider::Buffer* buffer, int64_t pts)
4464 {
4465 audio_track_cblk_t* cblk = this->cblk();
4466 uint32_t framesReady;
4467 uint32_t framesReq = buffer->frameCount;
4468
4469 // Check if last stepServer failed, try to step now
4470 if (mStepServerFailed) {
4471 // FIXME When called by fast mixer, this takes a mutex with tryLock().
4472 // Since the fast mixer is higher priority than client callback thread,
4473 // it does not result in priority inversion for client.
4474 // But a non-blocking solution would be preferable to avoid
4475 // fast mixer being unable to tryLock(), and
4476 // to avoid the extra context switches if the client wakes up,
4477 // discovers the mutex is locked, then has to wait for fast mixer to unlock.
4478 if (!step()) goto getNextBuffer_exit;
4479 ALOGV("stepServer recovered");
4480 mStepServerFailed = false;
4481 }
4482
4483 // FIXME Same as above
4484 framesReady = cblk->framesReady();
4485
4486 if (CC_LIKELY(framesReady)) {
4487 uint32_t s = cblk->server;
4488 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4489
4490 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
4491 if (framesReq > framesReady) {
4492 framesReq = framesReady;
4493 }
4494 if (framesReq > bufferEnd - s) {
4495 framesReq = bufferEnd - s;
4496 }
4497
4498 buffer->raw = getBuffer(s, framesReq);
4499 if (buffer->raw == NULL) goto getNextBuffer_exit;
4500
4501 buffer->frameCount = framesReq;
4502 return NO_ERROR;
4503 }
4504
4505 getNextBuffer_exit:
4506 buffer->raw = NULL;
4507 buffer->frameCount = 0;
4508 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
4509 return NOT_ENOUGH_DATA;
4510 }
4511
4512 // Note that framesReady() takes a mutex on the control block using tryLock().
4513 // This could result in priority inversion if framesReady() is called by the normal mixer,
4514 // as the normal mixer thread runs at lower
4515 // priority than the client's callback thread: there is a short window within framesReady()
4516 // during which the normal mixer could be preempted, and the client callback would block.
4517 // Another problem can occur if framesReady() is called by the fast mixer:
4518 // the tryLock() could block for up to 1 ms, and a sequence of these could delay fast mixer.
4519 // FIXME Replace AudioTrackShared control block implementation by a non-blocking FIFO queue.
framesReady() const4520 size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
4521 return mCblk->framesReady();
4522 }
4523
4524 // Don't call for fast tracks; the framesReady() could result in priority inversion
isReady() const4525 bool AudioFlinger::PlaybackThread::Track::isReady() const {
4526 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
4527
4528 if (framesReady() >= mCblk->frameCount ||
4529 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
4530 mFillingUpStatus = FS_FILLED;
4531 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
4532 return true;
4533 }
4534 return false;
4535 }
4536
start(AudioSystem::sync_event_t event,int triggerSession)4537 status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event,
4538 int triggerSession)
4539 {
4540 status_t status = NO_ERROR;
4541 ALOGV("start(%d), calling pid %d session %d",
4542 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
4543
4544 sp<ThreadBase> thread = mThread.promote();
4545 if (thread != 0) {
4546 Mutex::Autolock _l(thread->mLock);
4547 track_state state = mState;
4548 // here the track could be either new, or restarted
4549 // in both cases "unstop" the track
4550 if (mState == PAUSED) {
4551 mState = TrackBase::RESUMING;
4552 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
4553 } else {
4554 mState = TrackBase::ACTIVE;
4555 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
4556 }
4557
4558 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
4559 thread->mLock.unlock();
4560 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
4561 thread->mLock.lock();
4562
4563 #ifdef ADD_BATTERY_DATA
4564 // to track the speaker usage
4565 if (status == NO_ERROR) {
4566 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
4567 }
4568 #endif
4569 }
4570 if (status == NO_ERROR) {
4571 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4572 playbackThread->addTrack_l(this);
4573 } else {
4574 mState = state;
4575 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
4576 }
4577 } else {
4578 status = BAD_VALUE;
4579 }
4580 return status;
4581 }
4582
stop()4583 void AudioFlinger::PlaybackThread::Track::stop()
4584 {
4585 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
4586 sp<ThreadBase> thread = mThread.promote();
4587 if (thread != 0) {
4588 Mutex::Autolock _l(thread->mLock);
4589 track_state state = mState;
4590 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
4591 // If the track is not active (PAUSED and buffers full), flush buffers
4592 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4593 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4594 reset();
4595 mState = STOPPED;
4596 } else if (!isFastTrack()) {
4597 mState = STOPPED;
4598 } else {
4599 // prepareTracks_l() will set state to STOPPING_2 after next underrun,
4600 // and then to STOPPED and reset() when presentation is complete
4601 mState = STOPPING_1;
4602 }
4603 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName, playbackThread);
4604 }
4605 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
4606 thread->mLock.unlock();
4607 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
4608 thread->mLock.lock();
4609
4610 #ifdef ADD_BATTERY_DATA
4611 // to track the speaker usage
4612 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
4613 #endif
4614 }
4615 }
4616 }
4617
pause()4618 void AudioFlinger::PlaybackThread::Track::pause()
4619 {
4620 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
4621 sp<ThreadBase> thread = mThread.promote();
4622 if (thread != 0) {
4623 Mutex::Autolock _l(thread->mLock);
4624 if (mState == ACTIVE || mState == RESUMING) {
4625 mState = PAUSING;
4626 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
4627 if (!isOutputTrack()) {
4628 thread->mLock.unlock();
4629 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
4630 thread->mLock.lock();
4631
4632 #ifdef ADD_BATTERY_DATA
4633 // to track the speaker usage
4634 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
4635 #endif
4636 }
4637 }
4638 }
4639 }
4640
flush()4641 void AudioFlinger::PlaybackThread::Track::flush()
4642 {
4643 ALOGV("flush(%d)", mName);
4644 sp<ThreadBase> thread = mThread.promote();
4645 if (thread != 0) {
4646 Mutex::Autolock _l(thread->mLock);
4647 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED && mState != PAUSED &&
4648 mState != PAUSING) {
4649 return;
4650 }
4651 // No point remaining in PAUSED state after a flush => go to
4652 // FLUSHED state
4653 mState = FLUSHED;
4654 // do not reset the track if it is still in the process of being stopped or paused.
4655 // this will be done by prepareTracks_l() when the track is stopped.
4656 // prepareTracks_l() will see mState == FLUSHED, then
4657 // remove from active track list, reset(), and trigger presentation complete
4658 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4659 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4660 reset();
4661 }
4662 }
4663 }
4664
reset()4665 void AudioFlinger::PlaybackThread::Track::reset()
4666 {
4667 // Do not reset twice to avoid discarding data written just after a flush and before
4668 // the audioflinger thread detects the track is stopped.
4669 if (!mResetDone) {
4670 TrackBase::reset();
4671 // Force underrun condition to avoid false underrun callback until first data is
4672 // written to buffer
4673 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
4674 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
4675 mFillingUpStatus = FS_FILLING;
4676 mResetDone = true;
4677 if (mState == FLUSHED) {
4678 mState = IDLE;
4679 }
4680 }
4681 }
4682
mute(bool muted)4683 void AudioFlinger::PlaybackThread::Track::mute(bool muted)
4684 {
4685 mMute = muted;
4686 }
4687
attachAuxEffect(int EffectId)4688 status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
4689 {
4690 status_t status = DEAD_OBJECT;
4691 sp<ThreadBase> thread = mThread.promote();
4692 if (thread != 0) {
4693 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4694 sp<AudioFlinger> af = mClient->audioFlinger();
4695
4696 Mutex::Autolock _l(af->mLock);
4697
4698 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
4699
4700 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
4701 Mutex::Autolock _dl(playbackThread->mLock);
4702 Mutex::Autolock _sl(srcThread->mLock);
4703 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4704 if (chain == 0) {
4705 return INVALID_OPERATION;
4706 }
4707
4708 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
4709 if (effect == 0) {
4710 return INVALID_OPERATION;
4711 }
4712 srcThread->removeEffect_l(effect);
4713 playbackThread->addEffect_l(effect);
4714 // removeEffect_l() has stopped the effect if it was active so it must be restarted
4715 if (effect->state() == EffectModule::ACTIVE ||
4716 effect->state() == EffectModule::STOPPING) {
4717 effect->start();
4718 }
4719
4720 sp<EffectChain> dstChain = effect->chain().promote();
4721 if (dstChain == 0) {
4722 srcThread->addEffect_l(effect);
4723 return INVALID_OPERATION;
4724 }
4725 AudioSystem::unregisterEffect(effect->id());
4726 AudioSystem::registerEffect(&effect->desc(),
4727 srcThread->id(),
4728 dstChain->strategy(),
4729 AUDIO_SESSION_OUTPUT_MIX,
4730 effect->id());
4731 }
4732 status = playbackThread->attachAuxEffect(this, EffectId);
4733 }
4734 return status;
4735 }
4736
setAuxBuffer(int EffectId,int32_t * buffer)4737 void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
4738 {
4739 mAuxEffectId = EffectId;
4740 mAuxBuffer = buffer;
4741 }
4742
presentationComplete(size_t framesWritten,size_t audioHalFrames)4743 bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
4744 size_t audioHalFrames)
4745 {
4746 // a track is considered presented when the total number of frames written to audio HAL
4747 // corresponds to the number of frames written when presentationComplete() is called for the
4748 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
4749 if (mPresentationCompleteFrames == 0) {
4750 mPresentationCompleteFrames = framesWritten + audioHalFrames;
4751 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
4752 mPresentationCompleteFrames, audioHalFrames);
4753 }
4754 if (framesWritten >= mPresentationCompleteFrames) {
4755 ALOGV("presentationComplete() session %d complete: framesWritten %d",
4756 mSessionId, framesWritten);
4757 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
4758 return true;
4759 }
4760 return false;
4761 }
4762
triggerEvents(AudioSystem::sync_event_t type)4763 void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
4764 {
4765 for (int i = 0; i < (int)mSyncEvents.size(); i++) {
4766 if (mSyncEvents[i]->type() == type) {
4767 mSyncEvents[i]->trigger();
4768 mSyncEvents.removeAt(i);
4769 i--;
4770 }
4771 }
4772 }
4773
4774 // implement VolumeBufferProvider interface
4775
getVolumeLR()4776 uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
4777 {
4778 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
4779 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
4780 uint32_t vlr = mCblk->getVolumeLR();
4781 uint32_t vl = vlr & 0xFFFF;
4782 uint32_t vr = vlr >> 16;
4783 // track volumes come from shared memory, so can't be trusted and must be clamped
4784 if (vl > MAX_GAIN_INT) {
4785 vl = MAX_GAIN_INT;
4786 }
4787 if (vr > MAX_GAIN_INT) {
4788 vr = MAX_GAIN_INT;
4789 }
4790 // now apply the cached master volume and stream type volume;
4791 // this is trusted but lacks any synchronization or barrier so may be stale
4792 float v = mCachedVolume;
4793 vl *= v;
4794 vr *= v;
4795 // re-combine into U4.16
4796 vlr = (vr << 16) | (vl & 0xFFFF);
4797 // FIXME look at mute, pause, and stop flags
4798 return vlr;
4799 }
4800
setSyncEvent(const sp<SyncEvent> & event)4801 status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
4802 {
4803 if (mState == TERMINATED || mState == PAUSED ||
4804 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
4805 (mState == STOPPED)))) {
4806 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
4807 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
4808 event->cancel();
4809 return INVALID_OPERATION;
4810 }
4811 TrackBase::setSyncEvent(event);
4812 return NO_ERROR;
4813 }
4814
4815 // timed audio tracks
4816
4817 sp<AudioFlinger::PlaybackThread::TimedTrack>
create(PlaybackThread * thread,const sp<Client> & client,audio_stream_type_t streamType,uint32_t sampleRate,audio_format_t format,uint32_t channelMask,int frameCount,const sp<IMemory> & sharedBuffer,int sessionId)4818 AudioFlinger::PlaybackThread::TimedTrack::create(
4819 PlaybackThread *thread,
4820 const sp<Client>& client,
4821 audio_stream_type_t streamType,
4822 uint32_t sampleRate,
4823 audio_format_t format,
4824 uint32_t channelMask,
4825 int frameCount,
4826 const sp<IMemory>& sharedBuffer,
4827 int sessionId) {
4828 if (!client->reserveTimedTrack())
4829 return NULL;
4830
4831 return new TimedTrack(
4832 thread, client, streamType, sampleRate, format, channelMask, frameCount,
4833 sharedBuffer, sessionId);
4834 }
4835
TimedTrack(PlaybackThread * thread,const sp<Client> & client,audio_stream_type_t streamType,uint32_t sampleRate,audio_format_t format,uint32_t channelMask,int frameCount,const sp<IMemory> & sharedBuffer,int sessionId)4836 AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
4837 PlaybackThread *thread,
4838 const sp<Client>& client,
4839 audio_stream_type_t streamType,
4840 uint32_t sampleRate,
4841 audio_format_t format,
4842 uint32_t channelMask,
4843 int frameCount,
4844 const sp<IMemory>& sharedBuffer,
4845 int sessionId)
4846 : Track(thread, client, streamType, sampleRate, format, channelMask,
4847 frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED),
4848 mQueueHeadInFlight(false),
4849 mTrimQueueHeadOnRelease(false),
4850 mFramesPendingInQueue(0),
4851 mTimedSilenceBuffer(NULL),
4852 mTimedSilenceBufferSize(0),
4853 mTimedAudioOutputOnTime(false),
4854 mMediaTimeTransformValid(false)
4855 {
4856 LocalClock lc;
4857 mLocalTimeFreq = lc.getLocalFreq();
4858
4859 mLocalTimeToSampleTransform.a_zero = 0;
4860 mLocalTimeToSampleTransform.b_zero = 0;
4861 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
4862 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
4863 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
4864 &mLocalTimeToSampleTransform.a_to_b_denom);
4865
4866 mMediaTimeToSampleTransform.a_zero = 0;
4867 mMediaTimeToSampleTransform.b_zero = 0;
4868 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
4869 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
4870 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
4871 &mMediaTimeToSampleTransform.a_to_b_denom);
4872 }
4873
~TimedTrack()4874 AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
4875 mClient->releaseTimedTrack();
4876 delete [] mTimedSilenceBuffer;
4877 }
4878
allocateTimedBuffer(size_t size,sp<IMemory> * buffer)4879 status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
4880 size_t size, sp<IMemory>* buffer) {
4881
4882 Mutex::Autolock _l(mTimedBufferQueueLock);
4883
4884 trimTimedBufferQueue_l();
4885
4886 // lazily initialize the shared memory heap for timed buffers
4887 if (mTimedMemoryDealer == NULL) {
4888 const int kTimedBufferHeapSize = 512 << 10;
4889
4890 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
4891 "AudioFlingerTimed");
4892 if (mTimedMemoryDealer == NULL)
4893 return NO_MEMORY;
4894 }
4895
4896 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
4897 if (newBuffer == NULL) {
4898 newBuffer = mTimedMemoryDealer->allocate(size);
4899 if (newBuffer == NULL)
4900 return NO_MEMORY;
4901 }
4902
4903 *buffer = newBuffer;
4904 return NO_ERROR;
4905 }
4906
4907 // caller must hold mTimedBufferQueueLock
trimTimedBufferQueue_l()4908 void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
4909 int64_t mediaTimeNow;
4910 {
4911 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4912 if (!mMediaTimeTransformValid)
4913 return;
4914
4915 int64_t targetTimeNow;
4916 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
4917 ? mCCHelper.getCommonTime(&targetTimeNow)
4918 : mCCHelper.getLocalTime(&targetTimeNow);
4919
4920 if (OK != res)
4921 return;
4922
4923 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
4924 &mediaTimeNow)) {
4925 return;
4926 }
4927 }
4928
4929 size_t trimEnd;
4930 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
4931 int64_t bufEnd;
4932
4933 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
4934 // We have a next buffer. Just use its PTS as the PTS of the frame
4935 // following the last frame in this buffer. If the stream is sparse
4936 // (ie, there are deliberate gaps left in the stream which should be
4937 // filled with silence by the TimedAudioTrack), then this can result
4938 // in one extra buffer being left un-trimmed when it could have
4939 // been. In general, this is not typical, and we would rather
4940 // optimized away the TS calculation below for the more common case
4941 // where PTSes are contiguous.
4942 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
4943 } else {
4944 // We have no next buffer. Compute the PTS of the frame following
4945 // the last frame in this buffer by computing the duration of of
4946 // this frame in media time units and adding it to the PTS of the
4947 // buffer.
4948 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
4949 / mCblk->frameSize;
4950
4951 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
4952 &bufEnd)) {
4953 ALOGE("Failed to convert frame count of %lld to media time"
4954 " duration" " (scale factor %d/%u) in %s",
4955 frameCount,
4956 mMediaTimeToSampleTransform.a_to_b_numer,
4957 mMediaTimeToSampleTransform.a_to_b_denom,
4958 __PRETTY_FUNCTION__);
4959 break;
4960 }
4961 bufEnd += mTimedBufferQueue[trimEnd].pts();
4962 }
4963
4964 if (bufEnd > mediaTimeNow)
4965 break;
4966
4967 // Is the buffer we want to use in the middle of a mix operation right
4968 // now? If so, don't actually trim it. Just wait for the releaseBuffer
4969 // from the mixer which should be coming back shortly.
4970 if (!trimEnd && mQueueHeadInFlight) {
4971 mTrimQueueHeadOnRelease = true;
4972 }
4973 }
4974
4975 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
4976 if (trimStart < trimEnd) {
4977 // Update the bookkeeping for framesReady()
4978 for (size_t i = trimStart; i < trimEnd; ++i) {
4979 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
4980 }
4981
4982 // Now actually remove the buffers from the queue.
4983 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
4984 }
4985 }
4986
trimTimedBufferQueueHead_l(const char * logTag)4987 void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
4988 const char* logTag) {
4989 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
4990 "%s called (reason \"%s\"), but timed buffer queue has no"
4991 " elements to trim.", __FUNCTION__, logTag);
4992
4993 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
4994 mTimedBufferQueue.removeAt(0);
4995 }
4996
updateFramesPendingAfterTrim_l(const TimedBuffer & buf,const char * logTag)4997 void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
4998 const TimedBuffer& buf,
4999 const char* logTag) {
5000 uint32_t bufBytes = buf.buffer()->size();
5001 uint32_t consumedAlready = buf.position();
5002
5003 ALOG_ASSERT(consumedAlready <= bufBytes,
5004 "Bad bookkeeping while updating frames pending. Timed buffer is"
5005 " only %u bytes long, but claims to have consumed %u"
5006 " bytes. (update reason: \"%s\")",
5007 bufBytes, consumedAlready, logTag);
5008
5009 uint32_t bufFrames = (bufBytes - consumedAlready) / mCblk->frameSize;
5010 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
5011 "Bad bookkeeping while updating frames pending. Should have at"
5012 " least %u queued frames, but we think we have only %u. (update"
5013 " reason: \"%s\")",
5014 bufFrames, mFramesPendingInQueue, logTag);
5015
5016 mFramesPendingInQueue -= bufFrames;
5017 }
5018
queueTimedBuffer(const sp<IMemory> & buffer,int64_t pts)5019 status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
5020 const sp<IMemory>& buffer, int64_t pts) {
5021
5022 {
5023 Mutex::Autolock mttLock(mMediaTimeTransformLock);
5024 if (!mMediaTimeTransformValid)
5025 return INVALID_OPERATION;
5026 }
5027
5028 Mutex::Autolock _l(mTimedBufferQueueLock);
5029
5030 uint32_t bufFrames = buffer->size() / mCblk->frameSize;
5031 mFramesPendingInQueue += bufFrames;
5032 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
5033
5034 return NO_ERROR;
5035 }
5036
setMediaTimeTransform(const LinearTransform & xform,TimedAudioTrack::TargetTimeline target)5037 status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
5038 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
5039
5040 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
5041 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
5042 target);
5043
5044 if (!(target == TimedAudioTrack::LOCAL_TIME ||
5045 target == TimedAudioTrack::COMMON_TIME)) {
5046 return BAD_VALUE;
5047 }
5048
5049 Mutex::Autolock lock(mMediaTimeTransformLock);
5050 mMediaTimeTransform = xform;
5051 mMediaTimeTransformTarget = target;
5052 mMediaTimeTransformValid = true;
5053
5054 return NO_ERROR;
5055 }
5056
5057 #define min(a, b) ((a) < (b) ? (a) : (b))
5058
5059 // implementation of getNextBuffer for tracks whose buffers have timestamps
getNextBuffer(AudioBufferProvider::Buffer * buffer,int64_t pts)5060 status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
5061 AudioBufferProvider::Buffer* buffer, int64_t pts)
5062 {
5063 if (pts == AudioBufferProvider::kInvalidPTS) {
5064 buffer->raw = 0;
5065 buffer->frameCount = 0;
5066 mTimedAudioOutputOnTime = false;
5067 return INVALID_OPERATION;
5068 }
5069
5070 Mutex::Autolock _l(mTimedBufferQueueLock);
5071
5072 ALOG_ASSERT(!mQueueHeadInFlight,
5073 "getNextBuffer called without releaseBuffer!");
5074
5075 while (true) {
5076
5077 // if we have no timed buffers, then fail
5078 if (mTimedBufferQueue.isEmpty()) {
5079 buffer->raw = 0;
5080 buffer->frameCount = 0;
5081 return NOT_ENOUGH_DATA;
5082 }
5083
5084 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
5085
5086 // calculate the PTS of the head of the timed buffer queue expressed in
5087 // local time
5088 int64_t headLocalPTS;
5089 {
5090 Mutex::Autolock mttLock(mMediaTimeTransformLock);
5091
5092 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
5093
5094 if (mMediaTimeTransform.a_to_b_denom == 0) {
5095 // the transform represents a pause, so yield silence
5096 timedYieldSilence_l(buffer->frameCount, buffer);
5097 return NO_ERROR;
5098 }
5099
5100 int64_t transformedPTS;
5101 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
5102 &transformedPTS)) {
5103 // the transform failed. this shouldn't happen, but if it does
5104 // then just drop this buffer
5105 ALOGW("timedGetNextBuffer transform failed");
5106 buffer->raw = 0;
5107 buffer->frameCount = 0;
5108 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
5109 return NO_ERROR;
5110 }
5111
5112 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
5113 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
5114 &headLocalPTS)) {
5115 buffer->raw = 0;
5116 buffer->frameCount = 0;
5117 return INVALID_OPERATION;
5118 }
5119 } else {
5120 headLocalPTS = transformedPTS;
5121 }
5122 }
5123
5124 // adjust the head buffer's PTS to reflect the portion of the head buffer
5125 // that has already been consumed
5126 int64_t effectivePTS = headLocalPTS +
5127 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
5128
5129 // Calculate the delta in samples between the head of the input buffer
5130 // queue and the start of the next output buffer that will be written.
5131 // If the transformation fails because of over or underflow, it means
5132 // that the sample's position in the output stream is so far out of
5133 // whack that it should just be dropped.
5134 int64_t sampleDelta;
5135 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
5136 ALOGV("*** head buffer is too far from PTS: dropped buffer");
5137 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
5138 " mix");
5139 continue;
5140 }
5141 if (!mLocalTimeToSampleTransform.doForwardTransform(
5142 (effectivePTS - pts) << 32, &sampleDelta)) {
5143 ALOGV("*** too late during sample rate transform: dropped buffer");
5144 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
5145 continue;
5146 }
5147
5148 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
5149 " sampleDelta=[%d.%08x]",
5150 head.pts(), head.position(), pts,
5151 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
5152 + (sampleDelta >> 32)),
5153 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
5154
5155 // if the delta between the ideal placement for the next input sample and
5156 // the current output position is within this threshold, then we will
5157 // concatenate the next input samples to the previous output
5158 const int64_t kSampleContinuityThreshold =
5159 (static_cast<int64_t>(sampleRate()) << 32) / 250;
5160
5161 // if this is the first buffer of audio that we're emitting from this track
5162 // then it should be almost exactly on time.
5163 const int64_t kSampleStartupThreshold = 1LL << 32;
5164
5165 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
5166 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
5167 // the next input is close enough to being on time, so concatenate it
5168 // with the last output
5169 timedYieldSamples_l(buffer);
5170
5171 ALOGVV("*** on time: head.pos=%d frameCount=%u",
5172 head.position(), buffer->frameCount);
5173 return NO_ERROR;
5174 }
5175
5176 // Looks like our output is not on time. Reset our on timed status.
5177 // Next time we mix samples from our input queue, then should be within
5178 // the StartupThreshold.
5179 mTimedAudioOutputOnTime = false;
5180 if (sampleDelta > 0) {
5181 // the gap between the current output position and the proper start of
5182 // the next input sample is too big, so fill it with silence
5183 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
5184
5185 timedYieldSilence_l(framesUntilNextInput, buffer);
5186 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
5187 return NO_ERROR;
5188 } else {
5189 // the next input sample is late
5190 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
5191 size_t onTimeSamplePosition =
5192 head.position() + lateFrames * mCblk->frameSize;
5193
5194 if (onTimeSamplePosition > head.buffer()->size()) {
5195 // all the remaining samples in the head are too late, so
5196 // drop it and move on
5197 ALOGV("*** too late: dropped buffer");
5198 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
5199 continue;
5200 } else {
5201 // skip over the late samples
5202 head.setPosition(onTimeSamplePosition);
5203
5204 // yield the available samples
5205 timedYieldSamples_l(buffer);
5206
5207 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
5208 return NO_ERROR;
5209 }
5210 }
5211 }
5212 }
5213
5214 // Yield samples from the timed buffer queue head up to the given output
5215 // buffer's capacity.
5216 //
5217 // Caller must hold mTimedBufferQueueLock
timedYieldSamples_l(AudioBufferProvider::Buffer * buffer)5218 void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
5219 AudioBufferProvider::Buffer* buffer) {
5220
5221 const TimedBuffer& head = mTimedBufferQueue[0];
5222
5223 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
5224 head.position());
5225
5226 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
5227 mCblk->frameSize);
5228 size_t framesRequested = buffer->frameCount;
5229 buffer->frameCount = min(framesLeftInHead, framesRequested);
5230
5231 mQueueHeadInFlight = true;
5232 mTimedAudioOutputOnTime = true;
5233 }
5234
5235 // Yield samples of silence up to the given output buffer's capacity
5236 //
5237 // Caller must hold mTimedBufferQueueLock
timedYieldSilence_l(uint32_t numFrames,AudioBufferProvider::Buffer * buffer)5238 void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
5239 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
5240
5241 // lazily allocate a buffer filled with silence
5242 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
5243 delete [] mTimedSilenceBuffer;
5244 mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
5245 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
5246 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
5247 }
5248
5249 buffer->raw = mTimedSilenceBuffer;
5250 size_t framesRequested = buffer->frameCount;
5251 buffer->frameCount = min(numFrames, framesRequested);
5252
5253 mTimedAudioOutputOnTime = false;
5254 }
5255
5256 // AudioBufferProvider interface
releaseBuffer(AudioBufferProvider::Buffer * buffer)5257 void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
5258 AudioBufferProvider::Buffer* buffer) {
5259
5260 Mutex::Autolock _l(mTimedBufferQueueLock);
5261
5262 // If the buffer which was just released is part of the buffer at the head
5263 // of the queue, be sure to update the amt of the buffer which has been
5264 // consumed. If the buffer being returned is not part of the head of the
5265 // queue, its either because the buffer is part of the silence buffer, or
5266 // because the head of the timed queue was trimmed after the mixer called
5267 // getNextBuffer but before the mixer called releaseBuffer.
5268 if (buffer->raw == mTimedSilenceBuffer) {
5269 ALOG_ASSERT(!mQueueHeadInFlight,
5270 "Queue head in flight during release of silence buffer!");
5271 goto done;
5272 }
5273
5274 ALOG_ASSERT(mQueueHeadInFlight,
5275 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
5276 " head in flight.");
5277
5278 if (mTimedBufferQueue.size()) {
5279 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
5280
5281 void* start = head.buffer()->pointer();
5282 void* end = reinterpret_cast<void*>(
5283 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
5284 + head.buffer()->size());
5285
5286 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
5287 "released buffer not within the head of the timed buffer"
5288 " queue; qHead = [%p, %p], released buffer = %p",
5289 start, end, buffer->raw);
5290
5291 head.setPosition(head.position() +
5292 (buffer->frameCount * mCblk->frameSize));
5293 mQueueHeadInFlight = false;
5294
5295 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
5296 "Bad bookkeeping during releaseBuffer! Should have at"
5297 " least %u queued frames, but we think we have only %u",
5298 buffer->frameCount, mFramesPendingInQueue);
5299
5300 mFramesPendingInQueue -= buffer->frameCount;
5301
5302 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
5303 || mTrimQueueHeadOnRelease) {
5304 trimTimedBufferQueueHead_l("releaseBuffer");
5305 mTrimQueueHeadOnRelease = false;
5306 }
5307 } else {
5308 LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
5309 " buffers in the timed buffer queue");
5310 }
5311
5312 done:
5313 buffer->raw = 0;
5314 buffer->frameCount = 0;
5315 }
5316
framesReady() const5317 size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
5318 Mutex::Autolock _l(mTimedBufferQueueLock);
5319 return mFramesPendingInQueue;
5320 }
5321
TimedBuffer()5322 AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
5323 : mPTS(0), mPosition(0) {}
5324
TimedBuffer(const sp<IMemory> & buffer,int64_t pts)5325 AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
5326 const sp<IMemory>& buffer, int64_t pts)
5327 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
5328
5329 // ----------------------------------------------------------------------------
5330
5331 // RecordTrack constructor must be called with AudioFlinger::mLock held
RecordTrack(RecordThread * thread,const sp<Client> & client,uint32_t sampleRate,audio_format_t format,uint32_t channelMask,int frameCount,int sessionId)5332 AudioFlinger::RecordThread::RecordTrack::RecordTrack(
5333 RecordThread *thread,
5334 const sp<Client>& client,
5335 uint32_t sampleRate,
5336 audio_format_t format,
5337 uint32_t channelMask,
5338 int frameCount,
5339 int sessionId)
5340 : TrackBase(thread, client, sampleRate, format,
5341 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
5342 mOverflow(false)
5343 {
5344 if (mCblk != NULL) {
5345 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
5346 if (format == AUDIO_FORMAT_PCM_16_BIT) {
5347 mCblk->frameSize = mChannelCount * sizeof(int16_t);
5348 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
5349 mCblk->frameSize = mChannelCount * sizeof(int8_t);
5350 } else {
5351 mCblk->frameSize = sizeof(int8_t);
5352 }
5353 }
5354 }
5355
~RecordTrack()5356 AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
5357 {
5358 sp<ThreadBase> thread = mThread.promote();
5359 if (thread != 0) {
5360 AudioSystem::releaseInput(thread->id());
5361 }
5362 }
5363
5364 // AudioBufferProvider interface
getNextBuffer(AudioBufferProvider::Buffer * buffer,int64_t pts)5365 status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
5366 {
5367 audio_track_cblk_t* cblk = this->cblk();
5368 uint32_t framesAvail;
5369 uint32_t framesReq = buffer->frameCount;
5370
5371 // Check if last stepServer failed, try to step now
5372 if (mStepServerFailed) {
5373 if (!step()) goto getNextBuffer_exit;
5374 ALOGV("stepServer recovered");
5375 mStepServerFailed = false;
5376 }
5377
5378 framesAvail = cblk->framesAvailable_l();
5379
5380 if (CC_LIKELY(framesAvail)) {
5381 uint32_t s = cblk->server;
5382 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
5383
5384 if (framesReq > framesAvail) {
5385 framesReq = framesAvail;
5386 }
5387 if (framesReq > bufferEnd - s) {
5388 framesReq = bufferEnd - s;
5389 }
5390
5391 buffer->raw = getBuffer(s, framesReq);
5392 if (buffer->raw == NULL) goto getNextBuffer_exit;
5393
5394 buffer->frameCount = framesReq;
5395 return NO_ERROR;
5396 }
5397
5398 getNextBuffer_exit:
5399 buffer->raw = NULL;
5400 buffer->frameCount = 0;
5401 return NOT_ENOUGH_DATA;
5402 }
5403
start(AudioSystem::sync_event_t event,int triggerSession)5404 status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
5405 int triggerSession)
5406 {
5407 sp<ThreadBase> thread = mThread.promote();
5408 if (thread != 0) {
5409 RecordThread *recordThread = (RecordThread *)thread.get();
5410 return recordThread->start(this, event, triggerSession);
5411 } else {
5412 return BAD_VALUE;
5413 }
5414 }
5415
stop()5416 void AudioFlinger::RecordThread::RecordTrack::stop()
5417 {
5418 sp<ThreadBase> thread = mThread.promote();
5419 if (thread != 0) {
5420 RecordThread *recordThread = (RecordThread *)thread.get();
5421 recordThread->stop(this);
5422 TrackBase::reset();
5423 // Force overrun condition to avoid false overrun callback until first data is
5424 // read from buffer
5425 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
5426 }
5427 }
5428
dump(char * buffer,size_t size)5429 void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
5430 {
5431 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
5432 (mClient == 0) ? getpid_cached : mClient->pid(),
5433 mFormat,
5434 mChannelMask,
5435 mSessionId,
5436 mFrameCount,
5437 mState,
5438 mCblk->sampleRate,
5439 mCblk->server,
5440 mCblk->user);
5441 }
5442
5443
5444 // ----------------------------------------------------------------------------
5445
OutputTrack(PlaybackThread * playbackThread,DuplicatingThread * sourceThread,uint32_t sampleRate,audio_format_t format,uint32_t channelMask,int frameCount)5446 AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
5447 PlaybackThread *playbackThread,
5448 DuplicatingThread *sourceThread,
5449 uint32_t sampleRate,
5450 audio_format_t format,
5451 uint32_t channelMask,
5452 int frameCount)
5453 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
5454 NULL, 0, IAudioFlinger::TRACK_DEFAULT),
5455 mActive(false), mSourceThread(sourceThread)
5456 {
5457
5458 if (mCblk != NULL) {
5459 mCblk->flags |= CBLK_DIRECTION_OUT;
5460 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
5461 mOutBuffer.frameCount = 0;
5462 playbackThread->mTracks.add(this);
5463 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
5464 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
5465 mCblk, mBuffer, mCblk->buffers,
5466 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
5467 } else {
5468 ALOGW("Error creating output track on thread %p", playbackThread);
5469 }
5470 }
5471
~OutputTrack()5472 AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
5473 {
5474 clearBufferQueue();
5475 }
5476
start(AudioSystem::sync_event_t event,int triggerSession)5477 status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
5478 int triggerSession)
5479 {
5480 status_t status = Track::start(event, triggerSession);
5481 if (status != NO_ERROR) {
5482 return status;
5483 }
5484
5485 mActive = true;
5486 mRetryCount = 127;
5487 return status;
5488 }
5489
stop()5490 void AudioFlinger::PlaybackThread::OutputTrack::stop()
5491 {
5492 Track::stop();
5493 clearBufferQueue();
5494 mOutBuffer.frameCount = 0;
5495 mActive = false;
5496 }
5497
write(int16_t * data,uint32_t frames)5498 bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
5499 {
5500 Buffer *pInBuffer;
5501 Buffer inBuffer;
5502 uint32_t channelCount = mChannelCount;
5503 bool outputBufferFull = false;
5504 inBuffer.frameCount = frames;
5505 inBuffer.i16 = data;
5506
5507 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
5508
5509 if (!mActive && frames != 0) {
5510 start();
5511 sp<ThreadBase> thread = mThread.promote();
5512 if (thread != 0) {
5513 MixerThread *mixerThread = (MixerThread *)thread.get();
5514 if (mCblk->frameCount > frames){
5515 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5516 uint32_t startFrames = (mCblk->frameCount - frames);
5517 pInBuffer = new Buffer;
5518 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
5519 pInBuffer->frameCount = startFrames;
5520 pInBuffer->i16 = pInBuffer->mBuffer;
5521 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
5522 mBufferQueue.add(pInBuffer);
5523 } else {
5524 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
5525 }
5526 }
5527 }
5528 }
5529
5530 while (waitTimeLeftMs) {
5531 // First write pending buffers, then new data
5532 if (mBufferQueue.size()) {
5533 pInBuffer = mBufferQueue.itemAt(0);
5534 } else {
5535 pInBuffer = &inBuffer;
5536 }
5537
5538 if (pInBuffer->frameCount == 0) {
5539 break;
5540 }
5541
5542 if (mOutBuffer.frameCount == 0) {
5543 mOutBuffer.frameCount = pInBuffer->frameCount;
5544 nsecs_t startTime = systemTime();
5545 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
5546 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
5547 outputBufferFull = true;
5548 break;
5549 }
5550 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
5551 if (waitTimeLeftMs >= waitTimeMs) {
5552 waitTimeLeftMs -= waitTimeMs;
5553 } else {
5554 waitTimeLeftMs = 0;
5555 }
5556 }
5557
5558 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
5559 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
5560 mCblk->stepUser(outFrames);
5561 pInBuffer->frameCount -= outFrames;
5562 pInBuffer->i16 += outFrames * channelCount;
5563 mOutBuffer.frameCount -= outFrames;
5564 mOutBuffer.i16 += outFrames * channelCount;
5565
5566 if (pInBuffer->frameCount == 0) {
5567 if (mBufferQueue.size()) {
5568 mBufferQueue.removeAt(0);
5569 delete [] pInBuffer->mBuffer;
5570 delete pInBuffer;
5571 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
5572 } else {
5573 break;
5574 }
5575 }
5576 }
5577
5578 // If we could not write all frames, allocate a buffer and queue it for next time.
5579 if (inBuffer.frameCount) {
5580 sp<ThreadBase> thread = mThread.promote();
5581 if (thread != 0 && !thread->standby()) {
5582 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5583 pInBuffer = new Buffer;
5584 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
5585 pInBuffer->frameCount = inBuffer.frameCount;
5586 pInBuffer->i16 = pInBuffer->mBuffer;
5587 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
5588 mBufferQueue.add(pInBuffer);
5589 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
5590 } else {
5591 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
5592 }
5593 }
5594 }
5595
5596 // Calling write() with a 0 length buffer, means that no more data will be written:
5597 // If no more buffers are pending, fill output track buffer to make sure it is started
5598 // by output mixer.
5599 if (frames == 0 && mBufferQueue.size() == 0) {
5600 if (mCblk->user < mCblk->frameCount) {
5601 frames = mCblk->frameCount - mCblk->user;
5602 pInBuffer = new Buffer;
5603 pInBuffer->mBuffer = new int16_t[frames * channelCount];
5604 pInBuffer->frameCount = frames;
5605 pInBuffer->i16 = pInBuffer->mBuffer;
5606 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
5607 mBufferQueue.add(pInBuffer);
5608 } else if (mActive) {
5609 stop();
5610 }
5611 }
5612
5613 return outputBufferFull;
5614 }
5615
obtainBuffer(AudioBufferProvider::Buffer * buffer,uint32_t waitTimeMs)5616 status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
5617 {
5618 int active;
5619 status_t result;
5620 audio_track_cblk_t* cblk = mCblk;
5621 uint32_t framesReq = buffer->frameCount;
5622
5623 // ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
5624 buffer->frameCount = 0;
5625
5626 uint32_t framesAvail = cblk->framesAvailable();
5627
5628
5629 if (framesAvail == 0) {
5630 Mutex::Autolock _l(cblk->lock);
5631 goto start_loop_here;
5632 while (framesAvail == 0) {
5633 active = mActive;
5634 if (CC_UNLIKELY(!active)) {
5635 ALOGV("Not active and NO_MORE_BUFFERS");
5636 return NO_MORE_BUFFERS;
5637 }
5638 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
5639 if (result != NO_ERROR) {
5640 return NO_MORE_BUFFERS;
5641 }
5642 // read the server count again
5643 start_loop_here:
5644 framesAvail = cblk->framesAvailable_l();
5645 }
5646 }
5647
5648 // if (framesAvail < framesReq) {
5649 // return NO_MORE_BUFFERS;
5650 // }
5651
5652 if (framesReq > framesAvail) {
5653 framesReq = framesAvail;
5654 }
5655
5656 uint32_t u = cblk->user;
5657 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
5658
5659 if (framesReq > bufferEnd - u) {
5660 framesReq = bufferEnd - u;
5661 }
5662
5663 buffer->frameCount = framesReq;
5664 buffer->raw = (void *)cblk->buffer(u);
5665 return NO_ERROR;
5666 }
5667
5668
clearBufferQueue()5669 void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
5670 {
5671 size_t size = mBufferQueue.size();
5672
5673 for (size_t i = 0; i < size; i++) {
5674 Buffer *pBuffer = mBufferQueue.itemAt(i);
5675 delete [] pBuffer->mBuffer;
5676 delete pBuffer;
5677 }
5678 mBufferQueue.clear();
5679 }
5680
5681 // ----------------------------------------------------------------------------
5682
Client(const sp<AudioFlinger> & audioFlinger,pid_t pid)5683 AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
5684 : RefBase(),
5685 mAudioFlinger(audioFlinger),
5686 // FIXME should be a "k" constant not hard-coded, in .h or ro. property, see 4 lines below
5687 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
5688 mPid(pid),
5689 mTimedTrackCount(0)
5690 {
5691 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
5692 }
5693
5694 // Client destructor must be called with AudioFlinger::mLock held
~Client()5695 AudioFlinger::Client::~Client()
5696 {
5697 mAudioFlinger->removeClient_l(mPid);
5698 }
5699
heap() const5700 sp<MemoryDealer> AudioFlinger::Client::heap() const
5701 {
5702 return mMemoryDealer;
5703 }
5704
5705 // Reserve one of the limited slots for a timed audio track associated
5706 // with this client
reserveTimedTrack()5707 bool AudioFlinger::Client::reserveTimedTrack()
5708 {
5709 const int kMaxTimedTracksPerClient = 4;
5710
5711 Mutex::Autolock _l(mTimedTrackLock);
5712
5713 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
5714 ALOGW("can not create timed track - pid %d has exceeded the limit",
5715 mPid);
5716 return false;
5717 }
5718
5719 mTimedTrackCount++;
5720 return true;
5721 }
5722
5723 // Release a slot for a timed audio track
releaseTimedTrack()5724 void AudioFlinger::Client::releaseTimedTrack()
5725 {
5726 Mutex::Autolock _l(mTimedTrackLock);
5727 mTimedTrackCount--;
5728 }
5729
5730 // ----------------------------------------------------------------------------
5731
NotificationClient(const sp<AudioFlinger> & audioFlinger,const sp<IAudioFlingerClient> & client,pid_t pid)5732 AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
5733 const sp<IAudioFlingerClient>& client,
5734 pid_t pid)
5735 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
5736 {
5737 }
5738
~NotificationClient()5739 AudioFlinger::NotificationClient::~NotificationClient()
5740 {
5741 }
5742
binderDied(const wp<IBinder> & who)5743 void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
5744 {
5745 sp<NotificationClient> keep(this);
5746 mAudioFlinger->removeNotificationClient(mPid);
5747 }
5748
5749 // ----------------------------------------------------------------------------
5750
TrackHandle(const sp<AudioFlinger::PlaybackThread::Track> & track)5751 AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
5752 : BnAudioTrack(),
5753 mTrack(track)
5754 {
5755 }
5756
~TrackHandle()5757 AudioFlinger::TrackHandle::~TrackHandle() {
5758 // just stop the track on deletion, associated resources
5759 // will be freed from the main thread once all pending buffers have
5760 // been played. Unless it's not in the active track list, in which
5761 // case we free everything now...
5762 mTrack->destroy();
5763 }
5764
getCblk() const5765 sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
5766 return mTrack->getCblk();
5767 }
5768
start()5769 status_t AudioFlinger::TrackHandle::start() {
5770 return mTrack->start();
5771 }
5772
stop()5773 void AudioFlinger::TrackHandle::stop() {
5774 mTrack->stop();
5775 }
5776
flush()5777 void AudioFlinger::TrackHandle::flush() {
5778 mTrack->flush();
5779 }
5780
mute(bool e)5781 void AudioFlinger::TrackHandle::mute(bool e) {
5782 mTrack->mute(e);
5783 }
5784
pause()5785 void AudioFlinger::TrackHandle::pause() {
5786 mTrack->pause();
5787 }
5788
attachAuxEffect(int EffectId)5789 status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
5790 {
5791 return mTrack->attachAuxEffect(EffectId);
5792 }
5793
allocateTimedBuffer(size_t size,sp<IMemory> * buffer)5794 status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
5795 sp<IMemory>* buffer) {
5796 if (!mTrack->isTimedTrack())
5797 return INVALID_OPERATION;
5798
5799 PlaybackThread::TimedTrack* tt =
5800 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5801 return tt->allocateTimedBuffer(size, buffer);
5802 }
5803
queueTimedBuffer(const sp<IMemory> & buffer,int64_t pts)5804 status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
5805 int64_t pts) {
5806 if (!mTrack->isTimedTrack())
5807 return INVALID_OPERATION;
5808
5809 PlaybackThread::TimedTrack* tt =
5810 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5811 return tt->queueTimedBuffer(buffer, pts);
5812 }
5813
setMediaTimeTransform(const LinearTransform & xform,int target)5814 status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
5815 const LinearTransform& xform, int target) {
5816
5817 if (!mTrack->isTimedTrack())
5818 return INVALID_OPERATION;
5819
5820 PlaybackThread::TimedTrack* tt =
5821 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5822 return tt->setMediaTimeTransform(
5823 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
5824 }
5825
onTransact(uint32_t code,const Parcel & data,Parcel * reply,uint32_t flags)5826 status_t AudioFlinger::TrackHandle::onTransact(
5827 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5828 {
5829 return BnAudioTrack::onTransact(code, data, reply, flags);
5830 }
5831
5832 // ----------------------------------------------------------------------------
5833
openRecord(pid_t pid,audio_io_handle_t input,uint32_t sampleRate,audio_format_t format,uint32_t channelMask,int frameCount,IAudioFlinger::track_flags_t flags,int * sessionId,status_t * status)5834 sp<IAudioRecord> AudioFlinger::openRecord(
5835 pid_t pid,
5836 audio_io_handle_t input,
5837 uint32_t sampleRate,
5838 audio_format_t format,
5839 uint32_t channelMask,
5840 int frameCount,
5841 IAudioFlinger::track_flags_t flags,
5842 int *sessionId,
5843 status_t *status)
5844 {
5845 sp<RecordThread::RecordTrack> recordTrack;
5846 sp<RecordHandle> recordHandle;
5847 sp<Client> client;
5848 status_t lStatus;
5849 RecordThread *thread;
5850 size_t inFrameCount;
5851 int lSessionId;
5852
5853 // check calling permissions
5854 if (!recordingAllowed()) {
5855 lStatus = PERMISSION_DENIED;
5856 goto Exit;
5857 }
5858
5859 // add client to list
5860 { // scope for mLock
5861 Mutex::Autolock _l(mLock);
5862 thread = checkRecordThread_l(input);
5863 if (thread == NULL) {
5864 lStatus = BAD_VALUE;
5865 goto Exit;
5866 }
5867
5868 client = registerPid_l(pid);
5869
5870 // If no audio session id is provided, create one here
5871 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
5872 lSessionId = *sessionId;
5873 } else {
5874 lSessionId = nextUniqueId();
5875 if (sessionId != NULL) {
5876 *sessionId = lSessionId;
5877 }
5878 }
5879 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
5880 recordTrack = thread->createRecordTrack_l(client,
5881 sampleRate,
5882 format,
5883 channelMask,
5884 frameCount,
5885 lSessionId,
5886 &lStatus);
5887 }
5888 if (lStatus != NO_ERROR) {
5889 // remove local strong reference to Client before deleting the RecordTrack so that the Client
5890 // destructor is called by the TrackBase destructor with mLock held
5891 client.clear();
5892 recordTrack.clear();
5893 goto Exit;
5894 }
5895
5896 // return to handle to client
5897 recordHandle = new RecordHandle(recordTrack);
5898 lStatus = NO_ERROR;
5899
5900 Exit:
5901 if (status) {
5902 *status = lStatus;
5903 }
5904 return recordHandle;
5905 }
5906
5907 // ----------------------------------------------------------------------------
5908
RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack> & recordTrack)5909 AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
5910 : BnAudioRecord(),
5911 mRecordTrack(recordTrack)
5912 {
5913 }
5914
~RecordHandle()5915 AudioFlinger::RecordHandle::~RecordHandle() {
5916 stop();
5917 }
5918
getCblk() const5919 sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
5920 return mRecordTrack->getCblk();
5921 }
5922
start(int event,int triggerSession)5923 status_t AudioFlinger::RecordHandle::start(int event, int triggerSession) {
5924 ALOGV("RecordHandle::start()");
5925 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
5926 }
5927
stop()5928 void AudioFlinger::RecordHandle::stop() {
5929 ALOGV("RecordHandle::stop()");
5930 mRecordTrack->stop();
5931 }
5932
onTransact(uint32_t code,const Parcel & data,Parcel * reply,uint32_t flags)5933 status_t AudioFlinger::RecordHandle::onTransact(
5934 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5935 {
5936 return BnAudioRecord::onTransact(code, data, reply, flags);
5937 }
5938
5939 // ----------------------------------------------------------------------------
5940
RecordThread(const sp<AudioFlinger> & audioFlinger,AudioStreamIn * input,uint32_t sampleRate,uint32_t channels,audio_io_handle_t id,uint32_t device)5941 AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5942 AudioStreamIn *input,
5943 uint32_t sampleRate,
5944 uint32_t channels,
5945 audio_io_handle_t id,
5946 uint32_t device) :
5947 ThreadBase(audioFlinger, id, device, RECORD),
5948 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
5949 // mRsmpInIndex and mInputBytes set by readInputParameters()
5950 mReqChannelCount(popcount(channels)),
5951 mReqSampleRate(sampleRate)
5952 // mBytesRead is only meaningful while active, and so is cleared in start()
5953 // (but might be better to also clear here for dump?)
5954 {
5955 snprintf(mName, kNameLength, "AudioIn_%X", id);
5956
5957 readInputParameters();
5958 }
5959
5960
~RecordThread()5961 AudioFlinger::RecordThread::~RecordThread()
5962 {
5963 delete[] mRsmpInBuffer;
5964 delete mResampler;
5965 delete[] mRsmpOutBuffer;
5966 }
5967
onFirstRef()5968 void AudioFlinger::RecordThread::onFirstRef()
5969 {
5970 run(mName, PRIORITY_URGENT_AUDIO);
5971 }
5972
readyToRun()5973 status_t AudioFlinger::RecordThread::readyToRun()
5974 {
5975 status_t status = initCheck();
5976 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
5977 return status;
5978 }
5979
threadLoop()5980 bool AudioFlinger::RecordThread::threadLoop()
5981 {
5982 AudioBufferProvider::Buffer buffer;
5983 sp<RecordTrack> activeTrack;
5984 Vector< sp<EffectChain> > effectChains;
5985
5986 nsecs_t lastWarning = 0;
5987
5988 acquireWakeLock();
5989
5990 // start recording
5991 while (!exitPending()) {
5992
5993 processConfigEvents();
5994
5995 { // scope for mLock
5996 Mutex::Autolock _l(mLock);
5997 checkForNewParameters_l();
5998 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
5999 if (!mStandby) {
6000 mInput->stream->common.standby(&mInput->stream->common);
6001 mStandby = true;
6002 }
6003
6004 if (exitPending()) break;
6005
6006 releaseWakeLock_l();
6007 ALOGV("RecordThread: loop stopping");
6008 // go to sleep
6009 mWaitWorkCV.wait(mLock);
6010 ALOGV("RecordThread: loop starting");
6011 acquireWakeLock_l();
6012 continue;
6013 }
6014 if (mActiveTrack != 0) {
6015 if (mActiveTrack->mState == TrackBase::PAUSING) {
6016 if (!mStandby) {
6017 mInput->stream->common.standby(&mInput->stream->common);
6018 mStandby = true;
6019 }
6020 mActiveTrack.clear();
6021 mStartStopCond.broadcast();
6022 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
6023 if (mReqChannelCount != mActiveTrack->channelCount()) {
6024 mActiveTrack.clear();
6025 mStartStopCond.broadcast();
6026 } else if (mBytesRead != 0) {
6027 // record start succeeds only if first read from audio input
6028 // succeeds
6029 if (mBytesRead > 0) {
6030 mActiveTrack->mState = TrackBase::ACTIVE;
6031 } else {
6032 mActiveTrack.clear();
6033 }
6034 mStartStopCond.broadcast();
6035 }
6036 mStandby = false;
6037 }
6038 }
6039 lockEffectChains_l(effectChains);
6040 }
6041
6042 if (mActiveTrack != 0) {
6043 if (mActiveTrack->mState != TrackBase::ACTIVE &&
6044 mActiveTrack->mState != TrackBase::RESUMING) {
6045 unlockEffectChains(effectChains);
6046 usleep(kRecordThreadSleepUs);
6047 continue;
6048 }
6049 for (size_t i = 0; i < effectChains.size(); i ++) {
6050 effectChains[i]->process_l();
6051 }
6052
6053 buffer.frameCount = mFrameCount;
6054 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
6055 size_t framesOut = buffer.frameCount;
6056 if (mResampler == NULL) {
6057 // no resampling
6058 while (framesOut) {
6059 size_t framesIn = mFrameCount - mRsmpInIndex;
6060 if (framesIn) {
6061 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
6062 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
6063 if (framesIn > framesOut)
6064 framesIn = framesOut;
6065 mRsmpInIndex += framesIn;
6066 framesOut -= framesIn;
6067 if ((int)mChannelCount == mReqChannelCount ||
6068 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
6069 memcpy(dst, src, framesIn * mFrameSize);
6070 } else {
6071 int16_t *src16 = (int16_t *)src;
6072 int16_t *dst16 = (int16_t *)dst;
6073 if (mChannelCount == 1) {
6074 while (framesIn--) {
6075 *dst16++ = *src16;
6076 *dst16++ = *src16++;
6077 }
6078 } else {
6079 while (framesIn--) {
6080 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
6081 src16 += 2;
6082 }
6083 }
6084 }
6085 }
6086 if (framesOut && mFrameCount == mRsmpInIndex) {
6087 if (framesOut == mFrameCount &&
6088 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
6089 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
6090 framesOut = 0;
6091 } else {
6092 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
6093 mRsmpInIndex = 0;
6094 }
6095 if (mBytesRead < 0) {
6096 ALOGE("Error reading audio input");
6097 if (mActiveTrack->mState == TrackBase::ACTIVE) {
6098 // Force input into standby so that it tries to
6099 // recover at next read attempt
6100 mInput->stream->common.standby(&mInput->stream->common);
6101 usleep(kRecordThreadSleepUs);
6102 }
6103 mRsmpInIndex = mFrameCount;
6104 framesOut = 0;
6105 buffer.frameCount = 0;
6106 }
6107 }
6108 }
6109 } else {
6110 // resampling
6111
6112 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
6113 // alter output frame count as if we were expecting stereo samples
6114 if (mChannelCount == 1 && mReqChannelCount == 1) {
6115 framesOut >>= 1;
6116 }
6117 mResampler->resample(mRsmpOutBuffer, framesOut, this);
6118 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
6119 // are 32 bit aligned which should be always true.
6120 if (mChannelCount == 2 && mReqChannelCount == 1) {
6121 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
6122 // the resampler always outputs stereo samples: do post stereo to mono conversion
6123 int16_t *src = (int16_t *)mRsmpOutBuffer;
6124 int16_t *dst = buffer.i16;
6125 while (framesOut--) {
6126 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
6127 src += 2;
6128 }
6129 } else {
6130 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
6131 }
6132
6133 }
6134 if (mFramestoDrop == 0) {
6135 mActiveTrack->releaseBuffer(&buffer);
6136 } else {
6137 if (mFramestoDrop > 0) {
6138 mFramestoDrop -= buffer.frameCount;
6139 if (mFramestoDrop <= 0) {
6140 clearSyncStartEvent();
6141 }
6142 } else {
6143 mFramestoDrop += buffer.frameCount;
6144 if (mFramestoDrop >= 0 || mSyncStartEvent == 0 ||
6145 mSyncStartEvent->isCancelled()) {
6146 ALOGW("Synced record %s, session %d, trigger session %d",
6147 (mFramestoDrop >= 0) ? "timed out" : "cancelled",
6148 mActiveTrack->sessionId(),
6149 (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0);
6150 clearSyncStartEvent();
6151 }
6152 }
6153 }
6154 mActiveTrack->overflow();
6155 }
6156 // client isn't retrieving buffers fast enough
6157 else {
6158 if (!mActiveTrack->setOverflow()) {
6159 nsecs_t now = systemTime();
6160 if ((now - lastWarning) > kWarningThrottleNs) {
6161 ALOGW("RecordThread: buffer overflow");
6162 lastWarning = now;
6163 }
6164 }
6165 // Release the processor for a while before asking for a new buffer.
6166 // This will give the application more chance to read from the buffer and
6167 // clear the overflow.
6168 usleep(kRecordThreadSleepUs);
6169 }
6170 }
6171 // enable changes in effect chain
6172 unlockEffectChains(effectChains);
6173 effectChains.clear();
6174 }
6175
6176 if (!mStandby) {
6177 mInput->stream->common.standby(&mInput->stream->common);
6178 }
6179 mActiveTrack.clear();
6180
6181 mStartStopCond.broadcast();
6182
6183 releaseWakeLock();
6184
6185 ALOGV("RecordThread %p exiting", this);
6186 return false;
6187 }
6188
6189
createRecordTrack_l(const sp<AudioFlinger::Client> & client,uint32_t sampleRate,audio_format_t format,int channelMask,int frameCount,int sessionId,status_t * status)6190 sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
6191 const sp<AudioFlinger::Client>& client,
6192 uint32_t sampleRate,
6193 audio_format_t format,
6194 int channelMask,
6195 int frameCount,
6196 int sessionId,
6197 status_t *status)
6198 {
6199 sp<RecordTrack> track;
6200 status_t lStatus;
6201
6202 lStatus = initCheck();
6203 if (lStatus != NO_ERROR) {
6204 ALOGE("Audio driver not initialized.");
6205 goto Exit;
6206 }
6207
6208 { // scope for mLock
6209 Mutex::Autolock _l(mLock);
6210
6211 track = new RecordTrack(this, client, sampleRate,
6212 format, channelMask, frameCount, sessionId);
6213
6214 if (track->getCblk() == 0) {
6215 lStatus = NO_MEMORY;
6216 goto Exit;
6217 }
6218
6219 mTrack = track.get();
6220 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6221 bool suspend = audio_is_bluetooth_sco_device(
6222 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
6223 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6224 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
6225 }
6226 lStatus = NO_ERROR;
6227
6228 Exit:
6229 if (status) {
6230 *status = lStatus;
6231 }
6232 return track;
6233 }
6234
start(RecordThread::RecordTrack * recordTrack,AudioSystem::sync_event_t event,int triggerSession)6235 status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6236 AudioSystem::sync_event_t event,
6237 int triggerSession)
6238 {
6239 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6240 sp<ThreadBase> strongMe = this;
6241 status_t status = NO_ERROR;
6242
6243 if (event == AudioSystem::SYNC_EVENT_NONE) {
6244 clearSyncStartEvent();
6245 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
6246 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
6247 triggerSession,
6248 recordTrack->sessionId(),
6249 syncStartEventCallback,
6250 this);
6251 // Sync event can be cancelled by the trigger session if the track is not in a
6252 // compatible state in which case we start record immediately
6253 if (mSyncStartEvent->isCancelled()) {
6254 clearSyncStartEvent();
6255 } else {
6256 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
6257 mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000);
6258 }
6259 }
6260
6261 {
6262 AutoMutex lock(mLock);
6263 if (mActiveTrack != 0) {
6264 if (recordTrack != mActiveTrack.get()) {
6265 status = -EBUSY;
6266 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
6267 mActiveTrack->mState = TrackBase::ACTIVE;
6268 }
6269 return status;
6270 }
6271
6272 recordTrack->mState = TrackBase::IDLE;
6273 mActiveTrack = recordTrack;
6274 mLock.unlock();
6275 status_t status = AudioSystem::startInput(mId);
6276 mLock.lock();
6277 if (status != NO_ERROR) {
6278 mActiveTrack.clear();
6279 clearSyncStartEvent();
6280 return status;
6281 }
6282 mRsmpInIndex = mFrameCount;
6283 mBytesRead = 0;
6284 if (mResampler != NULL) {
6285 mResampler->reset();
6286 }
6287 mActiveTrack->mState = TrackBase::RESUMING;
6288 // signal thread to start
6289 ALOGV("Signal record thread");
6290 mWaitWorkCV.signal();
6291 // do not wait for mStartStopCond if exiting
6292 if (exitPending()) {
6293 mActiveTrack.clear();
6294 status = INVALID_OPERATION;
6295 goto startError;
6296 }
6297 mStartStopCond.wait(mLock);
6298 if (mActiveTrack == 0) {
6299 ALOGV("Record failed to start");
6300 status = BAD_VALUE;
6301 goto startError;
6302 }
6303 ALOGV("Record started OK");
6304 return status;
6305 }
6306 startError:
6307 AudioSystem::stopInput(mId);
6308 clearSyncStartEvent();
6309 return status;
6310 }
6311
clearSyncStartEvent()6312 void AudioFlinger::RecordThread::clearSyncStartEvent()
6313 {
6314 if (mSyncStartEvent != 0) {
6315 mSyncStartEvent->cancel();
6316 }
6317 mSyncStartEvent.clear();
6318 mFramestoDrop = 0;
6319 }
6320
syncStartEventCallback(const wp<SyncEvent> & event)6321 void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6322 {
6323 sp<SyncEvent> strongEvent = event.promote();
6324
6325 if (strongEvent != 0) {
6326 RecordThread *me = (RecordThread *)strongEvent->cookie();
6327 me->handleSyncStartEvent(strongEvent);
6328 }
6329 }
6330
handleSyncStartEvent(const sp<SyncEvent> & event)6331 void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
6332 {
6333 if (event == mSyncStartEvent) {
6334 // TODO: use actual buffer filling status instead of 2 buffers when info is available
6335 // from audio HAL
6336 mFramestoDrop = mFrameCount * 2;
6337 }
6338 }
6339
stop(RecordThread::RecordTrack * recordTrack)6340 void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
6341 ALOGV("RecordThread::stop");
6342 sp<ThreadBase> strongMe = this;
6343 {
6344 AutoMutex lock(mLock);
6345 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
6346 mActiveTrack->mState = TrackBase::PAUSING;
6347 // do not wait for mStartStopCond if exiting
6348 if (exitPending()) {
6349 return;
6350 }
6351 mStartStopCond.wait(mLock);
6352 // if we have been restarted, recordTrack == mActiveTrack.get() here
6353 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
6354 mLock.unlock();
6355 AudioSystem::stopInput(mId);
6356 mLock.lock();
6357 ALOGV("Record stopped OK");
6358 }
6359 }
6360 }
6361 }
6362
isValidSyncEvent(const sp<SyncEvent> & event)6363 bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event)
6364 {
6365 return false;
6366 }
6367
setSyncEvent(const sp<SyncEvent> & event)6368 status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
6369 {
6370 if (!isValidSyncEvent(event)) {
6371 return BAD_VALUE;
6372 }
6373
6374 Mutex::Autolock _l(mLock);
6375
6376 if (mTrack != NULL && event->triggerSession() == mTrack->sessionId()) {
6377 mTrack->setSyncEvent(event);
6378 return NO_ERROR;
6379 }
6380 return NAME_NOT_FOUND;
6381 }
6382
dump(int fd,const Vector<String16> & args)6383 status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6384 {
6385 const size_t SIZE = 256;
6386 char buffer[SIZE];
6387 String8 result;
6388
6389 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
6390 result.append(buffer);
6391
6392 if (mActiveTrack != 0) {
6393 result.append("Active Track:\n");
6394 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
6395 mActiveTrack->dump(buffer, SIZE);
6396 result.append(buffer);
6397
6398 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
6399 result.append(buffer);
6400 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
6401 result.append(buffer);
6402 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
6403 result.append(buffer);
6404 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
6405 result.append(buffer);
6406 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
6407 result.append(buffer);
6408
6409
6410 } else {
6411 result.append("No record client\n");
6412 }
6413 write(fd, result.string(), result.size());
6414
6415 dumpBase(fd, args);
6416 dumpEffectChains(fd, args);
6417
6418 return NO_ERROR;
6419 }
6420
6421 // AudioBufferProvider interface
getNextBuffer(AudioBufferProvider::Buffer * buffer,int64_t pts)6422 status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
6423 {
6424 size_t framesReq = buffer->frameCount;
6425 size_t framesReady = mFrameCount - mRsmpInIndex;
6426 int channelCount;
6427
6428 if (framesReady == 0) {
6429 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
6430 if (mBytesRead < 0) {
6431 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
6432 if (mActiveTrack->mState == TrackBase::ACTIVE) {
6433 // Force input into standby so that it tries to
6434 // recover at next read attempt
6435 mInput->stream->common.standby(&mInput->stream->common);
6436 usleep(kRecordThreadSleepUs);
6437 }
6438 buffer->raw = NULL;
6439 buffer->frameCount = 0;
6440 return NOT_ENOUGH_DATA;
6441 }
6442 mRsmpInIndex = 0;
6443 framesReady = mFrameCount;
6444 }
6445
6446 if (framesReq > framesReady) {
6447 framesReq = framesReady;
6448 }
6449
6450 if (mChannelCount == 1 && mReqChannelCount == 2) {
6451 channelCount = 1;
6452 } else {
6453 channelCount = 2;
6454 }
6455 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
6456 buffer->frameCount = framesReq;
6457 return NO_ERROR;
6458 }
6459
6460 // AudioBufferProvider interface
releaseBuffer(AudioBufferProvider::Buffer * buffer)6461 void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
6462 {
6463 mRsmpInIndex += buffer->frameCount;
6464 buffer->frameCount = 0;
6465 }
6466
checkForNewParameters_l()6467 bool AudioFlinger::RecordThread::checkForNewParameters_l()
6468 {
6469 bool reconfig = false;
6470
6471 while (!mNewParameters.isEmpty()) {
6472 status_t status = NO_ERROR;
6473 String8 keyValuePair = mNewParameters[0];
6474 AudioParameter param = AudioParameter(keyValuePair);
6475 int value;
6476 audio_format_t reqFormat = mFormat;
6477 int reqSamplingRate = mReqSampleRate;
6478 int reqChannelCount = mReqChannelCount;
6479
6480 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6481 reqSamplingRate = value;
6482 reconfig = true;
6483 }
6484 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
6485 reqFormat = (audio_format_t) value;
6486 reconfig = true;
6487 }
6488 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
6489 reqChannelCount = popcount(value);
6490 reconfig = true;
6491 }
6492 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6493 // do not accept frame count changes if tracks are open as the track buffer
6494 // size depends on frame count and correct behavior would not be guaranteed
6495 // if frame count is changed after track creation
6496 if (mActiveTrack != 0) {
6497 status = INVALID_OPERATION;
6498 } else {
6499 reconfig = true;
6500 }
6501 }
6502 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6503 // forward device change to effects that have requested to be
6504 // aware of attached audio device.
6505 for (size_t i = 0; i < mEffectChains.size(); i++) {
6506 mEffectChains[i]->setDevice_l(value);
6507 }
6508 // store input device and output device but do not forward output device to audio HAL.
6509 // Note that status is ignored by the caller for output device
6510 // (see AudioFlinger::setParameters()
6511 if (value & AUDIO_DEVICE_OUT_ALL) {
6512 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
6513 status = BAD_VALUE;
6514 } else {
6515 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
6516 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6517 if (mTrack != NULL) {
6518 bool suspend = audio_is_bluetooth_sco_device(
6519 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
6520 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
6521 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
6522 }
6523 }
6524 mDevice |= (uint32_t)value;
6525 }
6526 if (status == NO_ERROR) {
6527 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
6528 if (status == INVALID_OPERATION) {
6529 mInput->stream->common.standby(&mInput->stream->common);
6530 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6531 keyValuePair.string());
6532 }
6533 if (reconfig) {
6534 if (status == BAD_VALUE &&
6535 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
6536 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
6537 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
6538 popcount(mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
6539 (reqChannelCount <= FCC_2)) {
6540 status = NO_ERROR;
6541 }
6542 if (status == NO_ERROR) {
6543 readInputParameters();
6544 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
6545 }
6546 }
6547 }
6548
6549 mNewParameters.removeAt(0);
6550
6551 mParamStatus = status;
6552 mParamCond.signal();
6553 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
6554 // already timed out waiting for the status and will never signal the condition.
6555 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
6556 }
6557 return reconfig;
6558 }
6559
getParameters(const String8 & keys)6560 String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6561 {
6562 char *s;
6563 String8 out_s8 = String8();
6564
6565 Mutex::Autolock _l(mLock);
6566 if (initCheck() != NO_ERROR) {
6567 return out_s8;
6568 }
6569
6570 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
6571 out_s8 = String8(s);
6572 free(s);
6573 return out_s8;
6574 }
6575
audioConfigChanged_l(int event,int param)6576 void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
6577 AudioSystem::OutputDescriptor desc;
6578 void *param2 = NULL;
6579
6580 switch (event) {
6581 case AudioSystem::INPUT_OPENED:
6582 case AudioSystem::INPUT_CONFIG_CHANGED:
6583 desc.channels = mChannelMask;
6584 desc.samplingRate = mSampleRate;
6585 desc.format = mFormat;
6586 desc.frameCount = mFrameCount;
6587 desc.latency = 0;
6588 param2 = &desc;
6589 break;
6590
6591 case AudioSystem::INPUT_CLOSED:
6592 default:
6593 break;
6594 }
6595 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
6596 }
6597
readInputParameters()6598 void AudioFlinger::RecordThread::readInputParameters()
6599 {
6600 delete mRsmpInBuffer;
6601 // mRsmpInBuffer is always assigned a new[] below
6602 delete mRsmpOutBuffer;
6603 mRsmpOutBuffer = NULL;
6604 delete mResampler;
6605 mResampler = NULL;
6606
6607 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
6608 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
6609 mChannelCount = (uint16_t)popcount(mChannelMask);
6610 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
6611 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
6612 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
6613 mFrameCount = mInputBytes / mFrameSize;
6614 mNormalFrameCount = mFrameCount; // not used by record, but used by input effects
6615 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
6616
6617 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
6618 {
6619 int channelCount;
6620 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
6621 // stereo to mono post process as the resampler always outputs stereo.
6622 if (mChannelCount == 1 && mReqChannelCount == 2) {
6623 channelCount = 1;
6624 } else {
6625 channelCount = 2;
6626 }
6627 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
6628 mResampler->setSampleRate(mSampleRate);
6629 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
6630 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
6631
6632 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
6633 if (mChannelCount == 1 && mReqChannelCount == 1) {
6634 mFrameCount >>= 1;
6635 }
6636
6637 }
6638 mRsmpInIndex = mFrameCount;
6639 }
6640
getInputFramesLost()6641 unsigned int AudioFlinger::RecordThread::getInputFramesLost()
6642 {
6643 Mutex::Autolock _l(mLock);
6644 if (initCheck() != NO_ERROR) {
6645 return 0;
6646 }
6647
6648 return mInput->stream->get_input_frames_lost(mInput->stream);
6649 }
6650
hasAudioSession(int sessionId)6651 uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
6652 {
6653 Mutex::Autolock _l(mLock);
6654 uint32_t result = 0;
6655 if (getEffectChain_l(sessionId) != 0) {
6656 result = EFFECT_SESSION;
6657 }
6658
6659 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
6660 result |= TRACK_SESSION;
6661 }
6662
6663 return result;
6664 }
6665
track()6666 AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
6667 {
6668 Mutex::Autolock _l(mLock);
6669 return mTrack;
6670 }
6671
getInput() const6672 AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const
6673 {
6674 Mutex::Autolock _l(mLock);
6675 return mInput;
6676 }
6677
clearInput()6678 AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6679 {
6680 Mutex::Autolock _l(mLock);
6681 AudioStreamIn *input = mInput;
6682 mInput = NULL;
6683 return input;
6684 }
6685
6686 // this method must always be called either with ThreadBase mLock held or inside the thread loop
stream() const6687 audio_stream_t* AudioFlinger::RecordThread::stream() const
6688 {
6689 if (mInput == NULL) {
6690 return NULL;
6691 }
6692 return &mInput->stream->common;
6693 }
6694
6695
6696 // ----------------------------------------------------------------------------
6697
loadHwModule(const char * name)6698 audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
6699 {
6700 if (!settingsAllowed()) {
6701 return 0;
6702 }
6703 Mutex::Autolock _l(mLock);
6704 return loadHwModule_l(name);
6705 }
6706
6707 // loadHwModule_l() must be called with AudioFlinger::mLock held
loadHwModule_l(const char * name)6708 audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
6709 {
6710 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6711 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
6712 ALOGW("loadHwModule() module %s already loaded", name);
6713 return mAudioHwDevs.keyAt(i);
6714 }
6715 }
6716
6717 audio_hw_device_t *dev;
6718
6719 int rc = load_audio_interface(name, &dev);
6720 if (rc) {
6721 ALOGI("loadHwModule() error %d loading module %s ", rc, name);
6722 return 0;
6723 }
6724
6725 mHardwareStatus = AUDIO_HW_INIT;
6726 rc = dev->init_check(dev);
6727 mHardwareStatus = AUDIO_HW_IDLE;
6728 if (rc) {
6729 ALOGI("loadHwModule() init check error %d for module %s ", rc, name);
6730 return 0;
6731 }
6732
6733 if ((mMasterVolumeSupportLvl != MVS_NONE) &&
6734 (NULL != dev->set_master_volume)) {
6735 AutoMutex lock(mHardwareLock);
6736 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
6737 dev->set_master_volume(dev, mMasterVolume);
6738 mHardwareStatus = AUDIO_HW_IDLE;
6739 }
6740
6741 audio_module_handle_t handle = nextUniqueId();
6742 mAudioHwDevs.add(handle, new AudioHwDevice(name, dev));
6743
6744 ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
6745 name, dev->common.module->name, dev->common.module->id, handle);
6746
6747 return handle;
6748
6749 }
6750
openOutput(audio_module_handle_t module,audio_devices_t * pDevices,uint32_t * pSamplingRate,audio_format_t * pFormat,audio_channel_mask_t * pChannelMask,uint32_t * pLatencyMs,audio_output_flags_t flags)6751 audio_io_handle_t AudioFlinger::openOutput(audio_module_handle_t module,
6752 audio_devices_t *pDevices,
6753 uint32_t *pSamplingRate,
6754 audio_format_t *pFormat,
6755 audio_channel_mask_t *pChannelMask,
6756 uint32_t *pLatencyMs,
6757 audio_output_flags_t flags)
6758 {
6759 status_t status;
6760 PlaybackThread *thread = NULL;
6761 struct audio_config config = {
6762 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6763 channel_mask: pChannelMask ? *pChannelMask : 0,
6764 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6765 };
6766 audio_stream_out_t *outStream = NULL;
6767 audio_hw_device_t *outHwDev;
6768
6769 ALOGV("openOutput(), module %d Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
6770 module,
6771 (pDevices != NULL) ? (int)*pDevices : 0,
6772 config.sample_rate,
6773 config.format,
6774 config.channel_mask,
6775 flags);
6776
6777 if (pDevices == NULL || *pDevices == 0) {
6778 return 0;
6779 }
6780
6781 Mutex::Autolock _l(mLock);
6782
6783 outHwDev = findSuitableHwDev_l(module, *pDevices);
6784 if (outHwDev == NULL)
6785 return 0;
6786
6787 audio_io_handle_t id = nextUniqueId();
6788
6789 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
6790
6791 status = outHwDev->open_output_stream(outHwDev,
6792 id,
6793 *pDevices,
6794 (audio_output_flags_t)flags,
6795 &config,
6796 &outStream);
6797
6798 mHardwareStatus = AUDIO_HW_IDLE;
6799 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
6800 outStream,
6801 config.sample_rate,
6802 config.format,
6803 config.channel_mask,
6804 status);
6805
6806 if (status == NO_ERROR && outStream != NULL) {
6807 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
6808
6809 if ((flags & AUDIO_OUTPUT_FLAG_DIRECT) ||
6810 (config.format != AUDIO_FORMAT_PCM_16_BIT) ||
6811 (config.channel_mask != AUDIO_CHANNEL_OUT_STEREO)) {
6812 thread = new DirectOutputThread(this, output, id, *pDevices);
6813 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
6814 } else {
6815 thread = new MixerThread(this, output, id, *pDevices);
6816 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
6817 }
6818 mPlaybackThreads.add(id, thread);
6819
6820 if (pSamplingRate != NULL) *pSamplingRate = config.sample_rate;
6821 if (pFormat != NULL) *pFormat = config.format;
6822 if (pChannelMask != NULL) *pChannelMask = config.channel_mask;
6823 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
6824
6825 // notify client processes of the new output creation
6826 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
6827
6828 // the first primary output opened designates the primary hw device
6829 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
6830 ALOGI("Using module %d has the primary audio interface", module);
6831 mPrimaryHardwareDev = outHwDev;
6832
6833 AutoMutex lock(mHardwareLock);
6834 mHardwareStatus = AUDIO_HW_SET_MODE;
6835 outHwDev->set_mode(outHwDev, mMode);
6836
6837 // Determine the level of master volume support the primary audio HAL has,
6838 // and set the initial master volume at the same time.
6839 float initialVolume = 1.0;
6840 mMasterVolumeSupportLvl = MVS_NONE;
6841
6842 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
6843 if ((NULL != outHwDev->get_master_volume) &&
6844 (NO_ERROR == outHwDev->get_master_volume(outHwDev, &initialVolume))) {
6845 mMasterVolumeSupportLvl = MVS_FULL;
6846 } else {
6847 mMasterVolumeSupportLvl = MVS_SETONLY;
6848 initialVolume = 1.0;
6849 }
6850
6851 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
6852 if ((NULL == outHwDev->set_master_volume) ||
6853 (NO_ERROR != outHwDev->set_master_volume(outHwDev, initialVolume))) {
6854 mMasterVolumeSupportLvl = MVS_NONE;
6855 }
6856 // now that we have a primary device, initialize master volume on other devices
6857 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6858 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
6859
6860 if ((dev != mPrimaryHardwareDev) &&
6861 (NULL != dev->set_master_volume)) {
6862 dev->set_master_volume(dev, initialVolume);
6863 }
6864 }
6865 mHardwareStatus = AUDIO_HW_IDLE;
6866 mMasterVolumeSW = (MVS_NONE == mMasterVolumeSupportLvl)
6867 ? initialVolume
6868 : 1.0;
6869 mMasterVolume = initialVolume;
6870 }
6871 return id;
6872 }
6873
6874 return 0;
6875 }
6876
openDuplicateOutput(audio_io_handle_t output1,audio_io_handle_t output2)6877 audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
6878 audio_io_handle_t output2)
6879 {
6880 Mutex::Autolock _l(mLock);
6881 MixerThread *thread1 = checkMixerThread_l(output1);
6882 MixerThread *thread2 = checkMixerThread_l(output2);
6883
6884 if (thread1 == NULL || thread2 == NULL) {
6885 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
6886 return 0;
6887 }
6888
6889 audio_io_handle_t id = nextUniqueId();
6890 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
6891 thread->addOutputTrack(thread2);
6892 mPlaybackThreads.add(id, thread);
6893 // notify client processes of the new output creation
6894 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
6895 return id;
6896 }
6897
closeOutput(audio_io_handle_t output)6898 status_t AudioFlinger::closeOutput(audio_io_handle_t output)
6899 {
6900 // keep strong reference on the playback thread so that
6901 // it is not destroyed while exit() is executed
6902 sp<PlaybackThread> thread;
6903 {
6904 Mutex::Autolock _l(mLock);
6905 thread = checkPlaybackThread_l(output);
6906 if (thread == NULL) {
6907 return BAD_VALUE;
6908 }
6909
6910 ALOGV("closeOutput() %d", output);
6911
6912 if (thread->type() == ThreadBase::MIXER) {
6913 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6914 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
6915 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
6916 dupThread->removeOutputTrack((MixerThread *)thread.get());
6917 }
6918 }
6919 }
6920 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
6921 mPlaybackThreads.removeItem(output);
6922 }
6923 thread->exit();
6924 // The thread entity (active unit of execution) is no longer running here,
6925 // but the ThreadBase container still exists.
6926
6927 if (thread->type() != ThreadBase::DUPLICATING) {
6928 AudioStreamOut *out = thread->clearOutput();
6929 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
6930 // from now on thread->mOutput is NULL
6931 out->hwDev->close_output_stream(out->hwDev, out->stream);
6932 delete out;
6933 }
6934 return NO_ERROR;
6935 }
6936
suspendOutput(audio_io_handle_t output)6937 status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
6938 {
6939 Mutex::Autolock _l(mLock);
6940 PlaybackThread *thread = checkPlaybackThread_l(output);
6941
6942 if (thread == NULL) {
6943 return BAD_VALUE;
6944 }
6945
6946 ALOGV("suspendOutput() %d", output);
6947 thread->suspend();
6948
6949 return NO_ERROR;
6950 }
6951
restoreOutput(audio_io_handle_t output)6952 status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
6953 {
6954 Mutex::Autolock _l(mLock);
6955 PlaybackThread *thread = checkPlaybackThread_l(output);
6956
6957 if (thread == NULL) {
6958 return BAD_VALUE;
6959 }
6960
6961 ALOGV("restoreOutput() %d", output);
6962
6963 thread->restore();
6964
6965 return NO_ERROR;
6966 }
6967
openInput(audio_module_handle_t module,audio_devices_t * pDevices,uint32_t * pSamplingRate,audio_format_t * pFormat,uint32_t * pChannelMask)6968 audio_io_handle_t AudioFlinger::openInput(audio_module_handle_t module,
6969 audio_devices_t *pDevices,
6970 uint32_t *pSamplingRate,
6971 audio_format_t *pFormat,
6972 uint32_t *pChannelMask)
6973 {
6974 status_t status;
6975 RecordThread *thread = NULL;
6976 struct audio_config config = {
6977 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6978 channel_mask: pChannelMask ? *pChannelMask : 0,
6979 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6980 };
6981 uint32_t reqSamplingRate = config.sample_rate;
6982 audio_format_t reqFormat = config.format;
6983 audio_channel_mask_t reqChannels = config.channel_mask;
6984 audio_stream_in_t *inStream = NULL;
6985 audio_hw_device_t *inHwDev;
6986
6987 if (pDevices == NULL || *pDevices == 0) {
6988 return 0;
6989 }
6990
6991 Mutex::Autolock _l(mLock);
6992
6993 inHwDev = findSuitableHwDev_l(module, *pDevices);
6994 if (inHwDev == NULL)
6995 return 0;
6996
6997 audio_io_handle_t id = nextUniqueId();
6998
6999 status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config,
7000 &inStream);
7001 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, status %d",
7002 inStream,
7003 config.sample_rate,
7004 config.format,
7005 config.channel_mask,
7006 status);
7007
7008 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
7009 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
7010 // or stereo to mono conversions on 16 bit PCM inputs.
7011 if (status == BAD_VALUE &&
7012 reqFormat == config.format && config.format == AUDIO_FORMAT_PCM_16_BIT &&
7013 (config.sample_rate <= 2 * reqSamplingRate) &&
7014 (popcount(config.channel_mask) <= FCC_2) && (popcount(reqChannels) <= FCC_2)) {
7015 ALOGV("openInput() reopening with proposed sampling rate and channels");
7016 inStream = NULL;
7017 status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config, &inStream);
7018 }
7019
7020 if (status == NO_ERROR && inStream != NULL) {
7021 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
7022
7023 // Start record thread
7024 // RecorThread require both input and output device indication to forward to audio
7025 // pre processing modules
7026 uint32_t device = (*pDevices) | primaryOutputDevice_l();
7027 thread = new RecordThread(this,
7028 input,
7029 reqSamplingRate,
7030 reqChannels,
7031 id,
7032 device);
7033 mRecordThreads.add(id, thread);
7034 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
7035 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
7036 if (pFormat != NULL) *pFormat = config.format;
7037 if (pChannelMask != NULL) *pChannelMask = reqChannels;
7038
7039 input->stream->common.standby(&input->stream->common);
7040
7041 // notify client processes of the new input creation
7042 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
7043 return id;
7044 }
7045
7046 return 0;
7047 }
7048
closeInput(audio_io_handle_t input)7049 status_t AudioFlinger::closeInput(audio_io_handle_t input)
7050 {
7051 // keep strong reference on the record thread so that
7052 // it is not destroyed while exit() is executed
7053 sp<RecordThread> thread;
7054 {
7055 Mutex::Autolock _l(mLock);
7056 thread = checkRecordThread_l(input);
7057 if (thread == NULL) {
7058 return BAD_VALUE;
7059 }
7060
7061 ALOGV("closeInput() %d", input);
7062 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
7063 mRecordThreads.removeItem(input);
7064 }
7065 thread->exit();
7066 // The thread entity (active unit of execution) is no longer running here,
7067 // but the ThreadBase container still exists.
7068
7069 AudioStreamIn *in = thread->clearInput();
7070 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
7071 // from now on thread->mInput is NULL
7072 in->hwDev->close_input_stream(in->hwDev, in->stream);
7073 delete in;
7074
7075 return NO_ERROR;
7076 }
7077
setStreamOutput(audio_stream_type_t stream,audio_io_handle_t output)7078 status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
7079 {
7080 Mutex::Autolock _l(mLock);
7081 MixerThread *dstThread = checkMixerThread_l(output);
7082 if (dstThread == NULL) {
7083 ALOGW("setStreamOutput() bad output id %d", output);
7084 return BAD_VALUE;
7085 }
7086
7087 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
7088 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
7089
7090 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7091 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
7092 if (thread != dstThread && thread->type() != ThreadBase::DIRECT) {
7093 MixerThread *srcThread = (MixerThread *)thread;
7094 srcThread->invalidateTracks(stream);
7095 }
7096 }
7097
7098 return NO_ERROR;
7099 }
7100
7101
newAudioSessionId()7102 int AudioFlinger::newAudioSessionId()
7103 {
7104 return nextUniqueId();
7105 }
7106
acquireAudioSessionId(int audioSession)7107 void AudioFlinger::acquireAudioSessionId(int audioSession)
7108 {
7109 Mutex::Autolock _l(mLock);
7110 pid_t caller = IPCThreadState::self()->getCallingPid();
7111 ALOGV("acquiring %d from %d", audioSession, caller);
7112 size_t num = mAudioSessionRefs.size();
7113 for (size_t i = 0; i< num; i++) {
7114 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
7115 if (ref->mSessionid == audioSession && ref->mPid == caller) {
7116 ref->mCnt++;
7117 ALOGV(" incremented refcount to %d", ref->mCnt);
7118 return;
7119 }
7120 }
7121 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
7122 ALOGV(" added new entry for %d", audioSession);
7123 }
7124
releaseAudioSessionId(int audioSession)7125 void AudioFlinger::releaseAudioSessionId(int audioSession)
7126 {
7127 Mutex::Autolock _l(mLock);
7128 pid_t caller = IPCThreadState::self()->getCallingPid();
7129 ALOGV("releasing %d from %d", audioSession, caller);
7130 size_t num = mAudioSessionRefs.size();
7131 for (size_t i = 0; i< num; i++) {
7132 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
7133 if (ref->mSessionid == audioSession && ref->mPid == caller) {
7134 ref->mCnt--;
7135 ALOGV(" decremented refcount to %d", ref->mCnt);
7136 if (ref->mCnt == 0) {
7137 mAudioSessionRefs.removeAt(i);
7138 delete ref;
7139 purgeStaleEffects_l();
7140 }
7141 return;
7142 }
7143 }
7144 ALOGW("session id %d not found for pid %d", audioSession, caller);
7145 }
7146
purgeStaleEffects_l()7147 void AudioFlinger::purgeStaleEffects_l() {
7148
7149 ALOGV("purging stale effects");
7150
7151 Vector< sp<EffectChain> > chains;
7152
7153 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7154 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
7155 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
7156 sp<EffectChain> ec = t->mEffectChains[j];
7157 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
7158 chains.push(ec);
7159 }
7160 }
7161 }
7162 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7163 sp<RecordThread> t = mRecordThreads.valueAt(i);
7164 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
7165 sp<EffectChain> ec = t->mEffectChains[j];
7166 chains.push(ec);
7167 }
7168 }
7169
7170 for (size_t i = 0; i < chains.size(); i++) {
7171 sp<EffectChain> ec = chains[i];
7172 int sessionid = ec->sessionId();
7173 sp<ThreadBase> t = ec->mThread.promote();
7174 if (t == 0) {
7175 continue;
7176 }
7177 size_t numsessionrefs = mAudioSessionRefs.size();
7178 bool found = false;
7179 for (size_t k = 0; k < numsessionrefs; k++) {
7180 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
7181 if (ref->mSessionid == sessionid) {
7182 ALOGV(" session %d still exists for %d with %d refs",
7183 sessionid, ref->mPid, ref->mCnt);
7184 found = true;
7185 break;
7186 }
7187 }
7188 if (!found) {
7189 // remove all effects from the chain
7190 while (ec->mEffects.size()) {
7191 sp<EffectModule> effect = ec->mEffects[0];
7192 effect->unPin();
7193 Mutex::Autolock _l (t->mLock);
7194 t->removeEffect_l(effect);
7195 for (size_t j = 0; j < effect->mHandles.size(); j++) {
7196 sp<EffectHandle> handle = effect->mHandles[j].promote();
7197 if (handle != 0) {
7198 handle->mEffect.clear();
7199 if (handle->mHasControl && handle->mEnabled) {
7200 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
7201 }
7202 }
7203 }
7204 AudioSystem::unregisterEffect(effect->id());
7205 }
7206 }
7207 }
7208 return;
7209 }
7210
7211 // checkPlaybackThread_l() must be called with AudioFlinger::mLock held
checkPlaybackThread_l(audio_io_handle_t output) const7212 AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
7213 {
7214 return mPlaybackThreads.valueFor(output).get();
7215 }
7216
7217 // checkMixerThread_l() must be called with AudioFlinger::mLock held
checkMixerThread_l(audio_io_handle_t output) const7218 AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
7219 {
7220 PlaybackThread *thread = checkPlaybackThread_l(output);
7221 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
7222 }
7223
7224 // checkRecordThread_l() must be called with AudioFlinger::mLock held
checkRecordThread_l(audio_io_handle_t input) const7225 AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
7226 {
7227 return mRecordThreads.valueFor(input).get();
7228 }
7229
nextUniqueId()7230 uint32_t AudioFlinger::nextUniqueId()
7231 {
7232 return android_atomic_inc(&mNextUniqueId);
7233 }
7234
primaryPlaybackThread_l() const7235 AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
7236 {
7237 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7238 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
7239 AudioStreamOut *output = thread->getOutput();
7240 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
7241 return thread;
7242 }
7243 }
7244 return NULL;
7245 }
7246
primaryOutputDevice_l() const7247 uint32_t AudioFlinger::primaryOutputDevice_l() const
7248 {
7249 PlaybackThread *thread = primaryPlaybackThread_l();
7250
7251 if (thread == NULL) {
7252 return 0;
7253 }
7254
7255 return thread->device();
7256 }
7257
createSyncEvent(AudioSystem::sync_event_t type,int triggerSession,int listenerSession,sync_event_callback_t callBack,void * cookie)7258 sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
7259 int triggerSession,
7260 int listenerSession,
7261 sync_event_callback_t callBack,
7262 void *cookie)
7263 {
7264 Mutex::Autolock _l(mLock);
7265
7266 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
7267 status_t playStatus = NAME_NOT_FOUND;
7268 status_t recStatus = NAME_NOT_FOUND;
7269 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7270 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
7271 if (playStatus == NO_ERROR) {
7272 return event;
7273 }
7274 }
7275 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7276 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
7277 if (recStatus == NO_ERROR) {
7278 return event;
7279 }
7280 }
7281 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
7282 mPendingSyncEvents.add(event);
7283 } else {
7284 ALOGV("createSyncEvent() invalid event %d", event->type());
7285 event.clear();
7286 }
7287 return event;
7288 }
7289
7290 // ----------------------------------------------------------------------------
7291 // Effect management
7292 // ----------------------------------------------------------------------------
7293
7294
queryNumberEffects(uint32_t * numEffects) const7295 status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
7296 {
7297 Mutex::Autolock _l(mLock);
7298 return EffectQueryNumberEffects(numEffects);
7299 }
7300
queryEffect(uint32_t index,effect_descriptor_t * descriptor) const7301 status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
7302 {
7303 Mutex::Autolock _l(mLock);
7304 return EffectQueryEffect(index, descriptor);
7305 }
7306
getEffectDescriptor(const effect_uuid_t * pUuid,effect_descriptor_t * descriptor) const7307 status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
7308 effect_descriptor_t *descriptor) const
7309 {
7310 Mutex::Autolock _l(mLock);
7311 return EffectGetDescriptor(pUuid, descriptor);
7312 }
7313
7314
createEffect(pid_t pid,effect_descriptor_t * pDesc,const sp<IEffectClient> & effectClient,int32_t priority,audio_io_handle_t io,int sessionId,status_t * status,int * id,int * enabled)7315 sp<IEffect> AudioFlinger::createEffect(pid_t pid,
7316 effect_descriptor_t *pDesc,
7317 const sp<IEffectClient>& effectClient,
7318 int32_t priority,
7319 audio_io_handle_t io,
7320 int sessionId,
7321 status_t *status,
7322 int *id,
7323 int *enabled)
7324 {
7325 status_t lStatus = NO_ERROR;
7326 sp<EffectHandle> handle;
7327 effect_descriptor_t desc;
7328
7329 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
7330 pid, effectClient.get(), priority, sessionId, io);
7331
7332 if (pDesc == NULL) {
7333 lStatus = BAD_VALUE;
7334 goto Exit;
7335 }
7336
7337 // check audio settings permission for global effects
7338 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
7339 lStatus = PERMISSION_DENIED;
7340 goto Exit;
7341 }
7342
7343 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
7344 // that can only be created by audio policy manager (running in same process)
7345 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
7346 lStatus = PERMISSION_DENIED;
7347 goto Exit;
7348 }
7349
7350 if (io == 0) {
7351 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
7352 // output must be specified by AudioPolicyManager when using session
7353 // AUDIO_SESSION_OUTPUT_STAGE
7354 lStatus = BAD_VALUE;
7355 goto Exit;
7356 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
7357 // if the output returned by getOutputForEffect() is removed before we lock the
7358 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
7359 // and we will exit safely
7360 io = AudioSystem::getOutputForEffect(&desc);
7361 }
7362 }
7363
7364 {
7365 Mutex::Autolock _l(mLock);
7366
7367
7368 if (!EffectIsNullUuid(&pDesc->uuid)) {
7369 // if uuid is specified, request effect descriptor
7370 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
7371 if (lStatus < 0) {
7372 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
7373 goto Exit;
7374 }
7375 } else {
7376 // if uuid is not specified, look for an available implementation
7377 // of the required type in effect factory
7378 if (EffectIsNullUuid(&pDesc->type)) {
7379 ALOGW("createEffect() no effect type");
7380 lStatus = BAD_VALUE;
7381 goto Exit;
7382 }
7383 uint32_t numEffects = 0;
7384 effect_descriptor_t d;
7385 d.flags = 0; // prevent compiler warning
7386 bool found = false;
7387
7388 lStatus = EffectQueryNumberEffects(&numEffects);
7389 if (lStatus < 0) {
7390 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
7391 goto Exit;
7392 }
7393 for (uint32_t i = 0; i < numEffects; i++) {
7394 lStatus = EffectQueryEffect(i, &desc);
7395 if (lStatus < 0) {
7396 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
7397 continue;
7398 }
7399 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
7400 // If matching type found save effect descriptor. If the session is
7401 // 0 and the effect is not auxiliary, continue enumeration in case
7402 // an auxiliary version of this effect type is available
7403 found = true;
7404 memcpy(&d, &desc, sizeof(effect_descriptor_t));
7405 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
7406 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7407 break;
7408 }
7409 }
7410 }
7411 if (!found) {
7412 lStatus = BAD_VALUE;
7413 ALOGW("createEffect() effect not found");
7414 goto Exit;
7415 }
7416 // For same effect type, chose auxiliary version over insert version if
7417 // connect to output mix (Compliance to OpenSL ES)
7418 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
7419 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
7420 memcpy(&desc, &d, sizeof(effect_descriptor_t));
7421 }
7422 }
7423
7424 // Do not allow auxiliary effects on a session different from 0 (output mix)
7425 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
7426 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7427 lStatus = INVALID_OPERATION;
7428 goto Exit;
7429 }
7430
7431 // check recording permission for visualizer
7432 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
7433 !recordingAllowed()) {
7434 lStatus = PERMISSION_DENIED;
7435 goto Exit;
7436 }
7437
7438 // return effect descriptor
7439 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
7440
7441 // If output is not specified try to find a matching audio session ID in one of the
7442 // output threads.
7443 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
7444 // because of code checking output when entering the function.
7445 // Note: io is never 0 when creating an effect on an input
7446 if (io == 0) {
7447 // look for the thread where the specified audio session is present
7448 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7449 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
7450 io = mPlaybackThreads.keyAt(i);
7451 break;
7452 }
7453 }
7454 if (io == 0) {
7455 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7456 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
7457 io = mRecordThreads.keyAt(i);
7458 break;
7459 }
7460 }
7461 }
7462 // If no output thread contains the requested session ID, default to
7463 // first output. The effect chain will be moved to the correct output
7464 // thread when a track with the same session ID is created
7465 if (io == 0 && mPlaybackThreads.size()) {
7466 io = mPlaybackThreads.keyAt(0);
7467 }
7468 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
7469 }
7470 ThreadBase *thread = checkRecordThread_l(io);
7471 if (thread == NULL) {
7472 thread = checkPlaybackThread_l(io);
7473 if (thread == NULL) {
7474 ALOGE("createEffect() unknown output thread");
7475 lStatus = BAD_VALUE;
7476 goto Exit;
7477 }
7478 }
7479
7480 sp<Client> client = registerPid_l(pid);
7481
7482 // create effect on selected output thread
7483 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
7484 &desc, enabled, &lStatus);
7485 if (handle != 0 && id != NULL) {
7486 *id = handle->id();
7487 }
7488 }
7489
7490 Exit:
7491 if (status != NULL) {
7492 *status = lStatus;
7493 }
7494 return handle;
7495 }
7496
moveEffects(int sessionId,audio_io_handle_t srcOutput,audio_io_handle_t dstOutput)7497 status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
7498 audio_io_handle_t dstOutput)
7499 {
7500 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
7501 sessionId, srcOutput, dstOutput);
7502 Mutex::Autolock _l(mLock);
7503 if (srcOutput == dstOutput) {
7504 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
7505 return NO_ERROR;
7506 }
7507 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
7508 if (srcThread == NULL) {
7509 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
7510 return BAD_VALUE;
7511 }
7512 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
7513 if (dstThread == NULL) {
7514 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
7515 return BAD_VALUE;
7516 }
7517
7518 Mutex::Autolock _dl(dstThread->mLock);
7519 Mutex::Autolock _sl(srcThread->mLock);
7520 moveEffectChain_l(sessionId, srcThread, dstThread, false);
7521
7522 return NO_ERROR;
7523 }
7524
7525 // moveEffectChain_l must be called with both srcThread and dstThread mLocks held
moveEffectChain_l(int sessionId,AudioFlinger::PlaybackThread * srcThread,AudioFlinger::PlaybackThread * dstThread,bool reRegister)7526 status_t AudioFlinger::moveEffectChain_l(int sessionId,
7527 AudioFlinger::PlaybackThread *srcThread,
7528 AudioFlinger::PlaybackThread *dstThread,
7529 bool reRegister)
7530 {
7531 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
7532 sessionId, srcThread, dstThread);
7533
7534 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
7535 if (chain == 0) {
7536 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
7537 sessionId, srcThread);
7538 return INVALID_OPERATION;
7539 }
7540
7541 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
7542 // so that a new chain is created with correct parameters when first effect is added. This is
7543 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
7544 // removed.
7545 srcThread->removeEffectChain_l(chain);
7546
7547 // transfer all effects one by one so that new effect chain is created on new thread with
7548 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
7549 audio_io_handle_t dstOutput = dstThread->id();
7550 sp<EffectChain> dstChain;
7551 uint32_t strategy = 0; // prevent compiler warning
7552 sp<EffectModule> effect = chain->getEffectFromId_l(0);
7553 while (effect != 0) {
7554 srcThread->removeEffect_l(effect);
7555 dstThread->addEffect_l(effect);
7556 // removeEffect_l() has stopped the effect if it was active so it must be restarted
7557 if (effect->state() == EffectModule::ACTIVE ||
7558 effect->state() == EffectModule::STOPPING) {
7559 effect->start();
7560 }
7561 // if the move request is not received from audio policy manager, the effect must be
7562 // re-registered with the new strategy and output
7563 if (dstChain == 0) {
7564 dstChain = effect->chain().promote();
7565 if (dstChain == 0) {
7566 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
7567 srcThread->addEffect_l(effect);
7568 return NO_INIT;
7569 }
7570 strategy = dstChain->strategy();
7571 }
7572 if (reRegister) {
7573 AudioSystem::unregisterEffect(effect->id());
7574 AudioSystem::registerEffect(&effect->desc(),
7575 dstOutput,
7576 strategy,
7577 sessionId,
7578 effect->id());
7579 }
7580 effect = chain->getEffectFromId_l(0);
7581 }
7582
7583 return NO_ERROR;
7584 }
7585
7586
7587 // PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
createEffect_l(const sp<AudioFlinger::Client> & client,const sp<IEffectClient> & effectClient,int32_t priority,int sessionId,effect_descriptor_t * desc,int * enabled,status_t * status)7588 sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
7589 const sp<AudioFlinger::Client>& client,
7590 const sp<IEffectClient>& effectClient,
7591 int32_t priority,
7592 int sessionId,
7593 effect_descriptor_t *desc,
7594 int *enabled,
7595 status_t *status
7596 )
7597 {
7598 sp<EffectModule> effect;
7599 sp<EffectHandle> handle;
7600 status_t lStatus;
7601 sp<EffectChain> chain;
7602 bool chainCreated = false;
7603 bool effectCreated = false;
7604 bool effectRegistered = false;
7605
7606 lStatus = initCheck();
7607 if (lStatus != NO_ERROR) {
7608 ALOGW("createEffect_l() Audio driver not initialized.");
7609 goto Exit;
7610 }
7611
7612 // Do not allow effects with session ID 0 on direct output or duplicating threads
7613 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
7614 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
7615 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
7616 desc->name, sessionId);
7617 lStatus = BAD_VALUE;
7618 goto Exit;
7619 }
7620 // Only Pre processor effects are allowed on input threads and only on input threads
7621 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
7622 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
7623 desc->name, desc->flags, mType);
7624 lStatus = BAD_VALUE;
7625 goto Exit;
7626 }
7627
7628 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
7629
7630 { // scope for mLock
7631 Mutex::Autolock _l(mLock);
7632
7633 // check for existing effect chain with the requested audio session
7634 chain = getEffectChain_l(sessionId);
7635 if (chain == 0) {
7636 // create a new chain for this session
7637 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
7638 chain = new EffectChain(this, sessionId);
7639 addEffectChain_l(chain);
7640 chain->setStrategy(getStrategyForSession_l(sessionId));
7641 chainCreated = true;
7642 } else {
7643 effect = chain->getEffectFromDesc_l(desc);
7644 }
7645
7646 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
7647
7648 if (effect == 0) {
7649 int id = mAudioFlinger->nextUniqueId();
7650 // Check CPU and memory usage
7651 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
7652 if (lStatus != NO_ERROR) {
7653 goto Exit;
7654 }
7655 effectRegistered = true;
7656 // create a new effect module if none present in the chain
7657 effect = new EffectModule(this, chain, desc, id, sessionId);
7658 lStatus = effect->status();
7659 if (lStatus != NO_ERROR) {
7660 goto Exit;
7661 }
7662 lStatus = chain->addEffect_l(effect);
7663 if (lStatus != NO_ERROR) {
7664 goto Exit;
7665 }
7666 effectCreated = true;
7667
7668 effect->setDevice(mDevice);
7669 effect->setMode(mAudioFlinger->getMode());
7670 }
7671 // create effect handle and connect it to effect module
7672 handle = new EffectHandle(effect, client, effectClient, priority);
7673 lStatus = effect->addHandle(handle);
7674 if (enabled != NULL) {
7675 *enabled = (int)effect->isEnabled();
7676 }
7677 }
7678
7679 Exit:
7680 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
7681 Mutex::Autolock _l(mLock);
7682 if (effectCreated) {
7683 chain->removeEffect_l(effect);
7684 }
7685 if (effectRegistered) {
7686 AudioSystem::unregisterEffect(effect->id());
7687 }
7688 if (chainCreated) {
7689 removeEffectChain_l(chain);
7690 }
7691 handle.clear();
7692 }
7693
7694 if (status != NULL) {
7695 *status = lStatus;
7696 }
7697 return handle;
7698 }
7699
getEffect(int sessionId,int effectId)7700 sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
7701 {
7702 Mutex::Autolock _l(mLock);
7703 return getEffect_l(sessionId, effectId);
7704 }
7705
getEffect_l(int sessionId,int effectId)7706 sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
7707 {
7708 sp<EffectChain> chain = getEffectChain_l(sessionId);
7709 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
7710 }
7711
7712 // PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
7713 // PlaybackThread::mLock held
addEffect_l(const sp<EffectModule> & effect)7714 status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
7715 {
7716 // check for existing effect chain with the requested audio session
7717 int sessionId = effect->sessionId();
7718 sp<EffectChain> chain = getEffectChain_l(sessionId);
7719 bool chainCreated = false;
7720
7721 if (chain == 0) {
7722 // create a new chain for this session
7723 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
7724 chain = new EffectChain(this, sessionId);
7725 addEffectChain_l(chain);
7726 chain->setStrategy(getStrategyForSession_l(sessionId));
7727 chainCreated = true;
7728 }
7729 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
7730
7731 if (chain->getEffectFromId_l(effect->id()) != 0) {
7732 ALOGW("addEffect_l() %p effect %s already present in chain %p",
7733 this, effect->desc().name, chain.get());
7734 return BAD_VALUE;
7735 }
7736
7737 status_t status = chain->addEffect_l(effect);
7738 if (status != NO_ERROR) {
7739 if (chainCreated) {
7740 removeEffectChain_l(chain);
7741 }
7742 return status;
7743 }
7744
7745 effect->setDevice(mDevice);
7746 effect->setMode(mAudioFlinger->getMode());
7747 return NO_ERROR;
7748 }
7749
removeEffect_l(const sp<EffectModule> & effect)7750 void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
7751
7752 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
7753 effect_descriptor_t desc = effect->desc();
7754 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7755 detachAuxEffect_l(effect->id());
7756 }
7757
7758 sp<EffectChain> chain = effect->chain().promote();
7759 if (chain != 0) {
7760 // remove effect chain if removing last effect
7761 if (chain->removeEffect_l(effect) == 0) {
7762 removeEffectChain_l(chain);
7763 }
7764 } else {
7765 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
7766 }
7767 }
7768
lockEffectChains_l(Vector<sp<AudioFlinger::EffectChain>> & effectChains)7769 void AudioFlinger::ThreadBase::lockEffectChains_l(
7770 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
7771 {
7772 effectChains = mEffectChains;
7773 for (size_t i = 0; i < mEffectChains.size(); i++) {
7774 mEffectChains[i]->lock();
7775 }
7776 }
7777
unlockEffectChains(const Vector<sp<AudioFlinger::EffectChain>> & effectChains)7778 void AudioFlinger::ThreadBase::unlockEffectChains(
7779 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
7780 {
7781 for (size_t i = 0; i < effectChains.size(); i++) {
7782 effectChains[i]->unlock();
7783 }
7784 }
7785
getEffectChain(int sessionId)7786 sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
7787 {
7788 Mutex::Autolock _l(mLock);
7789 return getEffectChain_l(sessionId);
7790 }
7791
getEffectChain_l(int sessionId)7792 sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
7793 {
7794 size_t size = mEffectChains.size();
7795 for (size_t i = 0; i < size; i++) {
7796 if (mEffectChains[i]->sessionId() == sessionId) {
7797 return mEffectChains[i];
7798 }
7799 }
7800 return 0;
7801 }
7802
setMode(audio_mode_t mode)7803 void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
7804 {
7805 Mutex::Autolock _l(mLock);
7806 size_t size = mEffectChains.size();
7807 for (size_t i = 0; i < size; i++) {
7808 mEffectChains[i]->setMode_l(mode);
7809 }
7810 }
7811
disconnectEffect(const sp<EffectModule> & effect,const wp<EffectHandle> & handle,bool unpinIfLast)7812 void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
7813 const wp<EffectHandle>& handle,
7814 bool unpinIfLast) {
7815
7816 Mutex::Autolock _l(mLock);
7817 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
7818 // delete the effect module if removing last handle on it
7819 if (effect->removeHandle(handle) == 0) {
7820 if (!effect->isPinned() || unpinIfLast) {
7821 removeEffect_l(effect);
7822 AudioSystem::unregisterEffect(effect->id());
7823 }
7824 }
7825 }
7826
addEffectChain_l(const sp<EffectChain> & chain)7827 status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
7828 {
7829 int session = chain->sessionId();
7830 int16_t *buffer = mMixBuffer;
7831 bool ownsBuffer = false;
7832
7833 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
7834 if (session > 0) {
7835 // Only one effect chain can be present in direct output thread and it uses
7836 // the mix buffer as input
7837 if (mType != DIRECT) {
7838 size_t numSamples = mNormalFrameCount * mChannelCount;
7839 buffer = new int16_t[numSamples];
7840 memset(buffer, 0, numSamples * sizeof(int16_t));
7841 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
7842 ownsBuffer = true;
7843 }
7844
7845 // Attach all tracks with same session ID to this chain.
7846 for (size_t i = 0; i < mTracks.size(); ++i) {
7847 sp<Track> track = mTracks[i];
7848 if (session == track->sessionId()) {
7849 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
7850 track->setMainBuffer(buffer);
7851 chain->incTrackCnt();
7852 }
7853 }
7854
7855 // indicate all active tracks in the chain
7856 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7857 sp<Track> track = mActiveTracks[i].promote();
7858 if (track == 0) continue;
7859 if (session == track->sessionId()) {
7860 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
7861 chain->incActiveTrackCnt();
7862 }
7863 }
7864 }
7865
7866 chain->setInBuffer(buffer, ownsBuffer);
7867 chain->setOutBuffer(mMixBuffer);
7868 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
7869 // chains list in order to be processed last as it contains output stage effects
7870 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
7871 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
7872 // after track specific effects and before output stage
7873 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
7874 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
7875 // Effect chain for other sessions are inserted at beginning of effect
7876 // chains list to be processed before output mix effects. Relative order between other
7877 // sessions is not important
7878 size_t size = mEffectChains.size();
7879 size_t i = 0;
7880 for (i = 0; i < size; i++) {
7881 if (mEffectChains[i]->sessionId() < session) break;
7882 }
7883 mEffectChains.insertAt(chain, i);
7884 checkSuspendOnAddEffectChain_l(chain);
7885
7886 return NO_ERROR;
7887 }
7888
removeEffectChain_l(const sp<EffectChain> & chain)7889 size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
7890 {
7891 int session = chain->sessionId();
7892
7893 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
7894
7895 for (size_t i = 0; i < mEffectChains.size(); i++) {
7896 if (chain == mEffectChains[i]) {
7897 mEffectChains.removeAt(i);
7898 // detach all active tracks from the chain
7899 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7900 sp<Track> track = mActiveTracks[i].promote();
7901 if (track == 0) continue;
7902 if (session == track->sessionId()) {
7903 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
7904 chain.get(), session);
7905 chain->decActiveTrackCnt();
7906 }
7907 }
7908
7909 // detach all tracks with same session ID from this chain
7910 for (size_t i = 0; i < mTracks.size(); ++i) {
7911 sp<Track> track = mTracks[i];
7912 if (session == track->sessionId()) {
7913 track->setMainBuffer(mMixBuffer);
7914 chain->decTrackCnt();
7915 }
7916 }
7917 break;
7918 }
7919 }
7920 return mEffectChains.size();
7921 }
7922
attachAuxEffect(const sp<AudioFlinger::PlaybackThread::Track> track,int EffectId)7923 status_t AudioFlinger::PlaybackThread::attachAuxEffect(
7924 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
7925 {
7926 Mutex::Autolock _l(mLock);
7927 return attachAuxEffect_l(track, EffectId);
7928 }
7929
attachAuxEffect_l(const sp<AudioFlinger::PlaybackThread::Track> track,int EffectId)7930 status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
7931 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
7932 {
7933 status_t status = NO_ERROR;
7934
7935 if (EffectId == 0) {
7936 track->setAuxBuffer(0, NULL);
7937 } else {
7938 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
7939 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
7940 if (effect != 0) {
7941 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7942 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
7943 } else {
7944 status = INVALID_OPERATION;
7945 }
7946 } else {
7947 status = BAD_VALUE;
7948 }
7949 }
7950 return status;
7951 }
7952
detachAuxEffect_l(int effectId)7953 void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
7954 {
7955 for (size_t i = 0; i < mTracks.size(); ++i) {
7956 sp<Track> track = mTracks[i];
7957 if (track->auxEffectId() == effectId) {
7958 attachAuxEffect_l(track, 0);
7959 }
7960 }
7961 }
7962
addEffectChain_l(const sp<EffectChain> & chain)7963 status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7964 {
7965 // only one chain per input thread
7966 if (mEffectChains.size() != 0) {
7967 return INVALID_OPERATION;
7968 }
7969 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
7970
7971 chain->setInBuffer(NULL);
7972 chain->setOutBuffer(NULL);
7973
7974 checkSuspendOnAddEffectChain_l(chain);
7975
7976 mEffectChains.add(chain);
7977
7978 return NO_ERROR;
7979 }
7980
removeEffectChain_l(const sp<EffectChain> & chain)7981 size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7982 {
7983 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7984 ALOGW_IF(mEffectChains.size() != 1,
7985 "removeEffectChain_l() %p invalid chain size %d on thread %p",
7986 chain.get(), mEffectChains.size(), this);
7987 if (mEffectChains.size() == 1) {
7988 mEffectChains.removeAt(0);
7989 }
7990 return 0;
7991 }
7992
7993 // ----------------------------------------------------------------------------
7994 // EffectModule implementation
7995 // ----------------------------------------------------------------------------
7996
7997 #undef LOG_TAG
7998 #define LOG_TAG "AudioFlinger::EffectModule"
7999
EffectModule(ThreadBase * thread,const wp<AudioFlinger::EffectChain> & chain,effect_descriptor_t * desc,int id,int sessionId)8000 AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
8001 const wp<AudioFlinger::EffectChain>& chain,
8002 effect_descriptor_t *desc,
8003 int id,
8004 int sessionId)
8005 : mThread(thread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
8006 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
8007 {
8008 ALOGV("Constructor %p", this);
8009 int lStatus;
8010 if (thread == NULL) {
8011 return;
8012 }
8013
8014 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
8015
8016 // create effect engine from effect factory
8017 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
8018
8019 if (mStatus != NO_ERROR) {
8020 return;
8021 }
8022 lStatus = init();
8023 if (lStatus < 0) {
8024 mStatus = lStatus;
8025 goto Error;
8026 }
8027
8028 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
8029 mPinned = true;
8030 }
8031 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
8032 return;
8033 Error:
8034 EffectRelease(mEffectInterface);
8035 mEffectInterface = NULL;
8036 ALOGV("Constructor Error %d", mStatus);
8037 }
8038
~EffectModule()8039 AudioFlinger::EffectModule::~EffectModule()
8040 {
8041 ALOGV("Destructor %p", this);
8042 if (mEffectInterface != NULL) {
8043 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8044 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
8045 sp<ThreadBase> thread = mThread.promote();
8046 if (thread != 0) {
8047 audio_stream_t *stream = thread->stream();
8048 if (stream != NULL) {
8049 stream->remove_audio_effect(stream, mEffectInterface);
8050 }
8051 }
8052 }
8053 // release effect engine
8054 EffectRelease(mEffectInterface);
8055 }
8056 }
8057
addHandle(const sp<EffectHandle> & handle)8058 status_t AudioFlinger::EffectModule::addHandle(const sp<EffectHandle>& handle)
8059 {
8060 status_t status;
8061
8062 Mutex::Autolock _l(mLock);
8063 int priority = handle->priority();
8064 size_t size = mHandles.size();
8065 sp<EffectHandle> h;
8066 size_t i;
8067 for (i = 0; i < size; i++) {
8068 h = mHandles[i].promote();
8069 if (h == 0) continue;
8070 if (h->priority() <= priority) break;
8071 }
8072 // if inserted in first place, move effect control from previous owner to this handle
8073 if (i == 0) {
8074 bool enabled = false;
8075 if (h != 0) {
8076 enabled = h->enabled();
8077 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
8078 }
8079 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
8080 status = NO_ERROR;
8081 } else {
8082 status = ALREADY_EXISTS;
8083 }
8084 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
8085 mHandles.insertAt(handle, i);
8086 return status;
8087 }
8088
removeHandle(const wp<EffectHandle> & handle)8089 size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
8090 {
8091 Mutex::Autolock _l(mLock);
8092 size_t size = mHandles.size();
8093 size_t i;
8094 for (i = 0; i < size; i++) {
8095 if (mHandles[i] == handle) break;
8096 }
8097 if (i == size) {
8098 return size;
8099 }
8100 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
8101
8102 bool enabled = false;
8103 EffectHandle *hdl = handle.unsafe_get();
8104 if (hdl != NULL) {
8105 ALOGV("removeHandle() unsafe_get OK");
8106 enabled = hdl->enabled();
8107 }
8108 mHandles.removeAt(i);
8109 size = mHandles.size();
8110 // if removed from first place, move effect control from this handle to next in line
8111 if (i == 0 && size != 0) {
8112 sp<EffectHandle> h = mHandles[0].promote();
8113 if (h != 0) {
8114 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
8115 }
8116 }
8117
8118 // Prevent calls to process() and other functions on effect interface from now on.
8119 // The effect engine will be released by the destructor when the last strong reference on
8120 // this object is released which can happen after next process is called.
8121 if (size == 0 && !mPinned) {
8122 mState = DESTROYED;
8123 }
8124
8125 return size;
8126 }
8127
controlHandle()8128 sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
8129 {
8130 Mutex::Autolock _l(mLock);
8131 return mHandles.size() != 0 ? mHandles[0].promote() : 0;
8132 }
8133
disconnect(const wp<EffectHandle> & handle,bool unpinIfLast)8134 void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpinIfLast)
8135 {
8136 ALOGV("disconnect() %p handle %p", this, handle.unsafe_get());
8137 // keep a strong reference on this EffectModule to avoid calling the
8138 // destructor before we exit
8139 sp<EffectModule> keep(this);
8140 {
8141 sp<ThreadBase> thread = mThread.promote();
8142 if (thread != 0) {
8143 thread->disconnectEffect(keep, handle, unpinIfLast);
8144 }
8145 }
8146 }
8147
updateState()8148 void AudioFlinger::EffectModule::updateState() {
8149 Mutex::Autolock _l(mLock);
8150
8151 switch (mState) {
8152 case RESTART:
8153 reset_l();
8154 // FALL THROUGH
8155
8156 case STARTING:
8157 // clear auxiliary effect input buffer for next accumulation
8158 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8159 memset(mConfig.inputCfg.buffer.raw,
8160 0,
8161 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
8162 }
8163 start_l();
8164 mState = ACTIVE;
8165 break;
8166 case STOPPING:
8167 stop_l();
8168 mDisableWaitCnt = mMaxDisableWaitCnt;
8169 mState = STOPPED;
8170 break;
8171 case STOPPED:
8172 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
8173 // turn off sequence.
8174 if (--mDisableWaitCnt == 0) {
8175 reset_l();
8176 mState = IDLE;
8177 }
8178 break;
8179 default: //IDLE , ACTIVE, DESTROYED
8180 break;
8181 }
8182 }
8183
process()8184 void AudioFlinger::EffectModule::process()
8185 {
8186 Mutex::Autolock _l(mLock);
8187
8188 if (mState == DESTROYED || mEffectInterface == NULL ||
8189 mConfig.inputCfg.buffer.raw == NULL ||
8190 mConfig.outputCfg.buffer.raw == NULL) {
8191 return;
8192 }
8193
8194 if (isProcessEnabled()) {
8195 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
8196 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8197 ditherAndClamp(mConfig.inputCfg.buffer.s32,
8198 mConfig.inputCfg.buffer.s32,
8199 mConfig.inputCfg.buffer.frameCount/2);
8200 }
8201
8202 // do the actual processing in the effect engine
8203 int ret = (*mEffectInterface)->process(mEffectInterface,
8204 &mConfig.inputCfg.buffer,
8205 &mConfig.outputCfg.buffer);
8206
8207 // force transition to IDLE state when engine is ready
8208 if (mState == STOPPED && ret == -ENODATA) {
8209 mDisableWaitCnt = 1;
8210 }
8211
8212 // clear auxiliary effect input buffer for next accumulation
8213 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8214 memset(mConfig.inputCfg.buffer.raw, 0,
8215 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
8216 }
8217 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
8218 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
8219 // If an insert effect is idle and input buffer is different from output buffer,
8220 // accumulate input onto output
8221 sp<EffectChain> chain = mChain.promote();
8222 if (chain != 0 && chain->activeTrackCnt() != 0) {
8223 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
8224 int16_t *in = mConfig.inputCfg.buffer.s16;
8225 int16_t *out = mConfig.outputCfg.buffer.s16;
8226 for (size_t i = 0; i < frameCnt; i++) {
8227 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
8228 }
8229 }
8230 }
8231 }
8232
reset_l()8233 void AudioFlinger::EffectModule::reset_l()
8234 {
8235 if (mEffectInterface == NULL) {
8236 return;
8237 }
8238 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
8239 }
8240
configure()8241 status_t AudioFlinger::EffectModule::configure()
8242 {
8243 uint32_t channels;
8244 if (mEffectInterface == NULL) {
8245 return NO_INIT;
8246 }
8247
8248 sp<ThreadBase> thread = mThread.promote();
8249 if (thread == 0) {
8250 return DEAD_OBJECT;
8251 }
8252
8253 // TODO: handle configuration of effects replacing track process
8254 if (thread->channelCount() == 1) {
8255 channels = AUDIO_CHANNEL_OUT_MONO;
8256 } else {
8257 channels = AUDIO_CHANNEL_OUT_STEREO;
8258 }
8259
8260 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8261 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
8262 } else {
8263 mConfig.inputCfg.channels = channels;
8264 }
8265 mConfig.outputCfg.channels = channels;
8266 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
8267 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
8268 mConfig.inputCfg.samplingRate = thread->sampleRate();
8269 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
8270 mConfig.inputCfg.bufferProvider.cookie = NULL;
8271 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
8272 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
8273 mConfig.outputCfg.bufferProvider.cookie = NULL;
8274 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
8275 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
8276 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
8277 // Insert effect:
8278 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
8279 // always overwrites output buffer: input buffer == output buffer
8280 // - in other sessions:
8281 // last effect in the chain accumulates in output buffer: input buffer != output buffer
8282 // other effect: overwrites output buffer: input buffer == output buffer
8283 // Auxiliary effect:
8284 // accumulates in output buffer: input buffer != output buffer
8285 // Therefore: accumulate <=> input buffer != output buffer
8286 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
8287 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
8288 } else {
8289 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
8290 }
8291 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
8292 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
8293 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
8294 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
8295
8296 ALOGV("configure() %p thread %p buffer %p framecount %d",
8297 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
8298
8299 status_t cmdStatus;
8300 uint32_t size = sizeof(int);
8301 status_t status = (*mEffectInterface)->command(mEffectInterface,
8302 EFFECT_CMD_SET_CONFIG,
8303 sizeof(effect_config_t),
8304 &mConfig,
8305 &size,
8306 &cmdStatus);
8307 if (status == 0) {
8308 status = cmdStatus;
8309 }
8310
8311 if (status == 0 &&
8312 (memcmp(&mDescriptor.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0)) {
8313 uint32_t buf32[sizeof(effect_param_t) / sizeof(uint32_t) + 2];
8314 effect_param_t *p = (effect_param_t *)buf32;
8315
8316 p->psize = sizeof(uint32_t);
8317 p->vsize = sizeof(uint32_t);
8318 size = sizeof(int);
8319 *(int32_t *)p->data = VISUALIZER_PARAM_LATENCY;
8320
8321 uint32_t latency = 0;
8322 PlaybackThread *pbt = thread->mAudioFlinger->checkPlaybackThread_l(thread->mId);
8323 if (pbt != NULL) {
8324 latency = pbt->latency_l();
8325 }
8326
8327 *((int32_t *)p->data + 1)= latency;
8328 (*mEffectInterface)->command(mEffectInterface,
8329 EFFECT_CMD_SET_PARAM,
8330 sizeof(effect_param_t) + 8,
8331 &buf32,
8332 &size,
8333 &cmdStatus);
8334 }
8335
8336 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
8337 (1000 * mConfig.outputCfg.buffer.frameCount);
8338
8339 return status;
8340 }
8341
init()8342 status_t AudioFlinger::EffectModule::init()
8343 {
8344 Mutex::Autolock _l(mLock);
8345 if (mEffectInterface == NULL) {
8346 return NO_INIT;
8347 }
8348 status_t cmdStatus;
8349 uint32_t size = sizeof(status_t);
8350 status_t status = (*mEffectInterface)->command(mEffectInterface,
8351 EFFECT_CMD_INIT,
8352 0,
8353 NULL,
8354 &size,
8355 &cmdStatus);
8356 if (status == 0) {
8357 status = cmdStatus;
8358 }
8359 return status;
8360 }
8361
start()8362 status_t AudioFlinger::EffectModule::start()
8363 {
8364 Mutex::Autolock _l(mLock);
8365 return start_l();
8366 }
8367
start_l()8368 status_t AudioFlinger::EffectModule::start_l()
8369 {
8370 if (mEffectInterface == NULL) {
8371 return NO_INIT;
8372 }
8373 status_t cmdStatus;
8374 uint32_t size = sizeof(status_t);
8375 status_t status = (*mEffectInterface)->command(mEffectInterface,
8376 EFFECT_CMD_ENABLE,
8377 0,
8378 NULL,
8379 &size,
8380 &cmdStatus);
8381 if (status == 0) {
8382 status = cmdStatus;
8383 }
8384 if (status == 0 &&
8385 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8386 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8387 sp<ThreadBase> thread = mThread.promote();
8388 if (thread != 0) {
8389 audio_stream_t *stream = thread->stream();
8390 if (stream != NULL) {
8391 stream->add_audio_effect(stream, mEffectInterface);
8392 }
8393 }
8394 }
8395 return status;
8396 }
8397
stop()8398 status_t AudioFlinger::EffectModule::stop()
8399 {
8400 Mutex::Autolock _l(mLock);
8401 return stop_l();
8402 }
8403
stop_l()8404 status_t AudioFlinger::EffectModule::stop_l()
8405 {
8406 if (mEffectInterface == NULL) {
8407 return NO_INIT;
8408 }
8409 status_t cmdStatus;
8410 uint32_t size = sizeof(status_t);
8411 status_t status = (*mEffectInterface)->command(mEffectInterface,
8412 EFFECT_CMD_DISABLE,
8413 0,
8414 NULL,
8415 &size,
8416 &cmdStatus);
8417 if (status == 0) {
8418 status = cmdStatus;
8419 }
8420 if (status == 0 &&
8421 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8422 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8423 sp<ThreadBase> thread = mThread.promote();
8424 if (thread != 0) {
8425 audio_stream_t *stream = thread->stream();
8426 if (stream != NULL) {
8427 stream->remove_audio_effect(stream, mEffectInterface);
8428 }
8429 }
8430 }
8431 return status;
8432 }
8433
command(uint32_t cmdCode,uint32_t cmdSize,void * pCmdData,uint32_t * replySize,void * pReplyData)8434 status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
8435 uint32_t cmdSize,
8436 void *pCmdData,
8437 uint32_t *replySize,
8438 void *pReplyData)
8439 {
8440 Mutex::Autolock _l(mLock);
8441 // ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
8442
8443 if (mState == DESTROYED || mEffectInterface == NULL) {
8444 return NO_INIT;
8445 }
8446 status_t status = (*mEffectInterface)->command(mEffectInterface,
8447 cmdCode,
8448 cmdSize,
8449 pCmdData,
8450 replySize,
8451 pReplyData);
8452 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
8453 uint32_t size = (replySize == NULL) ? 0 : *replySize;
8454 for (size_t i = 1; i < mHandles.size(); i++) {
8455 sp<EffectHandle> h = mHandles[i].promote();
8456 if (h != 0) {
8457 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
8458 }
8459 }
8460 }
8461 return status;
8462 }
8463
setEnabled(bool enabled)8464 status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
8465 {
8466
8467 Mutex::Autolock _l(mLock);
8468 ALOGV("setEnabled %p enabled %d", this, enabled);
8469
8470 if (enabled != isEnabled()) {
8471 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
8472 if (enabled && status != NO_ERROR) {
8473 return status;
8474 }
8475
8476 switch (mState) {
8477 // going from disabled to enabled
8478 case IDLE:
8479 mState = STARTING;
8480 break;
8481 case STOPPED:
8482 mState = RESTART;
8483 break;
8484 case STOPPING:
8485 mState = ACTIVE;
8486 break;
8487
8488 // going from enabled to disabled
8489 case RESTART:
8490 mState = STOPPED;
8491 break;
8492 case STARTING:
8493 mState = IDLE;
8494 break;
8495 case ACTIVE:
8496 mState = STOPPING;
8497 break;
8498 case DESTROYED:
8499 return NO_ERROR; // simply ignore as we are being destroyed
8500 }
8501 for (size_t i = 1; i < mHandles.size(); i++) {
8502 sp<EffectHandle> h = mHandles[i].promote();
8503 if (h != 0) {
8504 h->setEnabled(enabled);
8505 }
8506 }
8507 }
8508 return NO_ERROR;
8509 }
8510
isEnabled() const8511 bool AudioFlinger::EffectModule::isEnabled() const
8512 {
8513 switch (mState) {
8514 case RESTART:
8515 case STARTING:
8516 case ACTIVE:
8517 return true;
8518 case IDLE:
8519 case STOPPING:
8520 case STOPPED:
8521 case DESTROYED:
8522 default:
8523 return false;
8524 }
8525 }
8526
isProcessEnabled() const8527 bool AudioFlinger::EffectModule::isProcessEnabled() const
8528 {
8529 switch (mState) {
8530 case RESTART:
8531 case ACTIVE:
8532 case STOPPING:
8533 case STOPPED:
8534 return true;
8535 case IDLE:
8536 case STARTING:
8537 case DESTROYED:
8538 default:
8539 return false;
8540 }
8541 }
8542
setVolume(uint32_t * left,uint32_t * right,bool controller)8543 status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
8544 {
8545 Mutex::Autolock _l(mLock);
8546 status_t status = NO_ERROR;
8547
8548 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
8549 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
8550 if (isProcessEnabled() &&
8551 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
8552 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
8553 status_t cmdStatus;
8554 uint32_t volume[2];
8555 uint32_t *pVolume = NULL;
8556 uint32_t size = sizeof(volume);
8557 volume[0] = *left;
8558 volume[1] = *right;
8559 if (controller) {
8560 pVolume = volume;
8561 }
8562 status = (*mEffectInterface)->command(mEffectInterface,
8563 EFFECT_CMD_SET_VOLUME,
8564 size,
8565 volume,
8566 &size,
8567 pVolume);
8568 if (controller && status == NO_ERROR && size == sizeof(volume)) {
8569 *left = volume[0];
8570 *right = volume[1];
8571 }
8572 }
8573 return status;
8574 }
8575
setDevice(uint32_t device)8576 status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
8577 {
8578 Mutex::Autolock _l(mLock);
8579 status_t status = NO_ERROR;
8580 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
8581 // audio pre processing modules on RecordThread can receive both output and
8582 // input device indication in the same call
8583 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
8584 if (dev) {
8585 status_t cmdStatus;
8586 uint32_t size = sizeof(status_t);
8587
8588 status = (*mEffectInterface)->command(mEffectInterface,
8589 EFFECT_CMD_SET_DEVICE,
8590 sizeof(uint32_t),
8591 &dev,
8592 &size,
8593 &cmdStatus);
8594 if (status == NO_ERROR) {
8595 status = cmdStatus;
8596 }
8597 }
8598 dev = device & AUDIO_DEVICE_IN_ALL;
8599 if (dev) {
8600 status_t cmdStatus;
8601 uint32_t size = sizeof(status_t);
8602
8603 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
8604 EFFECT_CMD_SET_INPUT_DEVICE,
8605 sizeof(uint32_t),
8606 &dev,
8607 &size,
8608 &cmdStatus);
8609 if (status2 == NO_ERROR) {
8610 status2 = cmdStatus;
8611 }
8612 if (status == NO_ERROR) {
8613 status = status2;
8614 }
8615 }
8616 }
8617 return status;
8618 }
8619
setMode(audio_mode_t mode)8620 status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
8621 {
8622 Mutex::Autolock _l(mLock);
8623 status_t status = NO_ERROR;
8624 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
8625 status_t cmdStatus;
8626 uint32_t size = sizeof(status_t);
8627 status = (*mEffectInterface)->command(mEffectInterface,
8628 EFFECT_CMD_SET_AUDIO_MODE,
8629 sizeof(audio_mode_t),
8630 &mode,
8631 &size,
8632 &cmdStatus);
8633 if (status == NO_ERROR) {
8634 status = cmdStatus;
8635 }
8636 }
8637 return status;
8638 }
8639
setSuspended(bool suspended)8640 void AudioFlinger::EffectModule::setSuspended(bool suspended)
8641 {
8642 Mutex::Autolock _l(mLock);
8643 mSuspended = suspended;
8644 }
8645
suspended() const8646 bool AudioFlinger::EffectModule::suspended() const
8647 {
8648 Mutex::Autolock _l(mLock);
8649 return mSuspended;
8650 }
8651
dump(int fd,const Vector<String16> & args)8652 status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
8653 {
8654 const size_t SIZE = 256;
8655 char buffer[SIZE];
8656 String8 result;
8657
8658 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
8659 result.append(buffer);
8660
8661 bool locked = tryLock(mLock);
8662 // failed to lock - AudioFlinger is probably deadlocked
8663 if (!locked) {
8664 result.append("\t\tCould not lock Fx mutex:\n");
8665 }
8666
8667 result.append("\t\tSession Status State Engine:\n");
8668 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
8669 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
8670 result.append(buffer);
8671
8672 result.append("\t\tDescriptor:\n");
8673 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8674 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
8675 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
8676 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
8677 result.append(buffer);
8678 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8679 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
8680 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
8681 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
8682 result.append(buffer);
8683 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
8684 mDescriptor.apiVersion,
8685 mDescriptor.flags);
8686 result.append(buffer);
8687 snprintf(buffer, SIZE, "\t\t- name: %s\n",
8688 mDescriptor.name);
8689 result.append(buffer);
8690 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
8691 mDescriptor.implementor);
8692 result.append(buffer);
8693
8694 result.append("\t\t- Input configuration:\n");
8695 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8696 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8697 (uint32_t)mConfig.inputCfg.buffer.raw,
8698 mConfig.inputCfg.buffer.frameCount,
8699 mConfig.inputCfg.samplingRate,
8700 mConfig.inputCfg.channels,
8701 mConfig.inputCfg.format);
8702 result.append(buffer);
8703
8704 result.append("\t\t- Output configuration:\n");
8705 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8706 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8707 (uint32_t)mConfig.outputCfg.buffer.raw,
8708 mConfig.outputCfg.buffer.frameCount,
8709 mConfig.outputCfg.samplingRate,
8710 mConfig.outputCfg.channels,
8711 mConfig.outputCfg.format);
8712 result.append(buffer);
8713
8714 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
8715 result.append(buffer);
8716 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
8717 for (size_t i = 0; i < mHandles.size(); ++i) {
8718 sp<EffectHandle> handle = mHandles[i].promote();
8719 if (handle != 0) {
8720 handle->dump(buffer, SIZE);
8721 result.append(buffer);
8722 }
8723 }
8724
8725 result.append("\n");
8726
8727 write(fd, result.string(), result.length());
8728
8729 if (locked) {
8730 mLock.unlock();
8731 }
8732
8733 return NO_ERROR;
8734 }
8735
8736 // ----------------------------------------------------------------------------
8737 // EffectHandle implementation
8738 // ----------------------------------------------------------------------------
8739
8740 #undef LOG_TAG
8741 #define LOG_TAG "AudioFlinger::EffectHandle"
8742
EffectHandle(const sp<EffectModule> & effect,const sp<AudioFlinger::Client> & client,const sp<IEffectClient> & effectClient,int32_t priority)8743 AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
8744 const sp<AudioFlinger::Client>& client,
8745 const sp<IEffectClient>& effectClient,
8746 int32_t priority)
8747 : BnEffect(),
8748 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
8749 mPriority(priority), mHasControl(false), mEnabled(false)
8750 {
8751 ALOGV("constructor %p", this);
8752
8753 if (client == 0) {
8754 return;
8755 }
8756 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
8757 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
8758 if (mCblkMemory != 0) {
8759 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
8760
8761 if (mCblk != NULL) {
8762 new(mCblk) effect_param_cblk_t();
8763 mBuffer = (uint8_t *)mCblk + bufOffset;
8764 }
8765 } else {
8766 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
8767 return;
8768 }
8769 }
8770
~EffectHandle()8771 AudioFlinger::EffectHandle::~EffectHandle()
8772 {
8773 ALOGV("Destructor %p", this);
8774 disconnect(false);
8775 ALOGV("Destructor DONE %p", this);
8776 }
8777
enable()8778 status_t AudioFlinger::EffectHandle::enable()
8779 {
8780 ALOGV("enable %p", this);
8781 if (!mHasControl) return INVALID_OPERATION;
8782 if (mEffect == 0) return DEAD_OBJECT;
8783
8784 if (mEnabled) {
8785 return NO_ERROR;
8786 }
8787
8788 mEnabled = true;
8789
8790 sp<ThreadBase> thread = mEffect->thread().promote();
8791 if (thread != 0) {
8792 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
8793 }
8794
8795 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
8796 if (mEffect->suspended()) {
8797 return NO_ERROR;
8798 }
8799
8800 status_t status = mEffect->setEnabled(true);
8801 if (status != NO_ERROR) {
8802 if (thread != 0) {
8803 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8804 }
8805 mEnabled = false;
8806 }
8807 return status;
8808 }
8809
disable()8810 status_t AudioFlinger::EffectHandle::disable()
8811 {
8812 ALOGV("disable %p", this);
8813 if (!mHasControl) return INVALID_OPERATION;
8814 if (mEffect == 0) return DEAD_OBJECT;
8815
8816 if (!mEnabled) {
8817 return NO_ERROR;
8818 }
8819 mEnabled = false;
8820
8821 if (mEffect->suspended()) {
8822 return NO_ERROR;
8823 }
8824
8825 status_t status = mEffect->setEnabled(false);
8826
8827 sp<ThreadBase> thread = mEffect->thread().promote();
8828 if (thread != 0) {
8829 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8830 }
8831
8832 return status;
8833 }
8834
disconnect()8835 void AudioFlinger::EffectHandle::disconnect()
8836 {
8837 disconnect(true);
8838 }
8839
disconnect(bool unpinIfLast)8840 void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
8841 {
8842 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
8843 if (mEffect == 0) {
8844 return;
8845 }
8846 mEffect->disconnect(this, unpinIfLast);
8847
8848 if (mHasControl && mEnabled) {
8849 sp<ThreadBase> thread = mEffect->thread().promote();
8850 if (thread != 0) {
8851 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8852 }
8853 }
8854
8855 // release sp on module => module destructor can be called now
8856 mEffect.clear();
8857 if (mClient != 0) {
8858 if (mCblk != NULL) {
8859 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
8860 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
8861 }
8862 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
8863 // Client destructor must run with AudioFlinger mutex locked
8864 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
8865 mClient.clear();
8866 }
8867 }
8868
command(uint32_t cmdCode,uint32_t cmdSize,void * pCmdData,uint32_t * replySize,void * pReplyData)8869 status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
8870 uint32_t cmdSize,
8871 void *pCmdData,
8872 uint32_t *replySize,
8873 void *pReplyData)
8874 {
8875 // ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
8876 // cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
8877
8878 // only get parameter command is permitted for applications not controlling the effect
8879 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
8880 return INVALID_OPERATION;
8881 }
8882 if (mEffect == 0) return DEAD_OBJECT;
8883 if (mClient == 0) return INVALID_OPERATION;
8884
8885 // handle commands that are not forwarded transparently to effect engine
8886 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
8887 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
8888 // no risk to block the whole media server process or mixer threads is we are stuck here
8889 Mutex::Autolock _l(mCblk->lock);
8890 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
8891 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
8892 mCblk->serverIndex = 0;
8893 mCblk->clientIndex = 0;
8894 return BAD_VALUE;
8895 }
8896 status_t status = NO_ERROR;
8897 while (mCblk->serverIndex < mCblk->clientIndex) {
8898 int reply;
8899 uint32_t rsize = sizeof(int);
8900 int *p = (int *)(mBuffer + mCblk->serverIndex);
8901 int size = *p++;
8902 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
8903 ALOGW("command(): invalid parameter block size");
8904 break;
8905 }
8906 effect_param_t *param = (effect_param_t *)p;
8907 if (param->psize == 0 || param->vsize == 0) {
8908 ALOGW("command(): null parameter or value size");
8909 mCblk->serverIndex += size;
8910 continue;
8911 }
8912 uint32_t psize = sizeof(effect_param_t) +
8913 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
8914 param->vsize;
8915 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
8916 psize,
8917 p,
8918 &rsize,
8919 &reply);
8920 // stop at first error encountered
8921 if (ret != NO_ERROR) {
8922 status = ret;
8923 *(int *)pReplyData = reply;
8924 break;
8925 } else if (reply != NO_ERROR) {
8926 *(int *)pReplyData = reply;
8927 break;
8928 }
8929 mCblk->serverIndex += size;
8930 }
8931 mCblk->serverIndex = 0;
8932 mCblk->clientIndex = 0;
8933 return status;
8934 } else if (cmdCode == EFFECT_CMD_ENABLE) {
8935 *(int *)pReplyData = NO_ERROR;
8936 return enable();
8937 } else if (cmdCode == EFFECT_CMD_DISABLE) {
8938 *(int *)pReplyData = NO_ERROR;
8939 return disable();
8940 }
8941
8942 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
8943 }
8944
setControl(bool hasControl,bool signal,bool enabled)8945 void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
8946 {
8947 ALOGV("setControl %p control %d", this, hasControl);
8948
8949 mHasControl = hasControl;
8950 mEnabled = enabled;
8951
8952 if (signal && mEffectClient != 0) {
8953 mEffectClient->controlStatusChanged(hasControl);
8954 }
8955 }
8956
commandExecuted(uint32_t cmdCode,uint32_t cmdSize,void * pCmdData,uint32_t replySize,void * pReplyData)8957 void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
8958 uint32_t cmdSize,
8959 void *pCmdData,
8960 uint32_t replySize,
8961 void *pReplyData)
8962 {
8963 if (mEffectClient != 0) {
8964 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
8965 }
8966 }
8967
8968
8969
setEnabled(bool enabled)8970 void AudioFlinger::EffectHandle::setEnabled(bool enabled)
8971 {
8972 if (mEffectClient != 0) {
8973 mEffectClient->enableStatusChanged(enabled);
8974 }
8975 }
8976
onTransact(uint32_t code,const Parcel & data,Parcel * reply,uint32_t flags)8977 status_t AudioFlinger::EffectHandle::onTransact(
8978 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
8979 {
8980 return BnEffect::onTransact(code, data, reply, flags);
8981 }
8982
8983
dump(char * buffer,size_t size)8984 void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
8985 {
8986 bool locked = mCblk != NULL && tryLock(mCblk->lock);
8987
8988 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
8989 (mClient == 0) ? getpid_cached : mClient->pid(),
8990 mPriority,
8991 mHasControl,
8992 !locked,
8993 mCblk ? mCblk->clientIndex : 0,
8994 mCblk ? mCblk->serverIndex : 0
8995 );
8996
8997 if (locked) {
8998 mCblk->lock.unlock();
8999 }
9000 }
9001
9002 #undef LOG_TAG
9003 #define LOG_TAG "AudioFlinger::EffectChain"
9004
EffectChain(ThreadBase * thread,int sessionId)9005 AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
9006 int sessionId)
9007 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
9008 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
9009 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
9010 {
9011 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
9012 if (thread == NULL) {
9013 return;
9014 }
9015 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
9016 thread->frameCount();
9017 }
9018
~EffectChain()9019 AudioFlinger::EffectChain::~EffectChain()
9020 {
9021 if (mOwnInBuffer) {
9022 delete mInBuffer;
9023 }
9024
9025 }
9026
9027 // getEffectFromDesc_l() must be called with ThreadBase::mLock held
getEffectFromDesc_l(effect_descriptor_t * descriptor)9028 sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
9029 {
9030 size_t size = mEffects.size();
9031
9032 for (size_t i = 0; i < size; i++) {
9033 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
9034 return mEffects[i];
9035 }
9036 }
9037 return 0;
9038 }
9039
9040 // getEffectFromId_l() must be called with ThreadBase::mLock held
getEffectFromId_l(int id)9041 sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
9042 {
9043 size_t size = mEffects.size();
9044
9045 for (size_t i = 0; i < size; i++) {
9046 // by convention, return first effect if id provided is 0 (0 is never a valid id)
9047 if (id == 0 || mEffects[i]->id() == id) {
9048 return mEffects[i];
9049 }
9050 }
9051 return 0;
9052 }
9053
9054 // getEffectFromType_l() must be called with ThreadBase::mLock held
getEffectFromType_l(const effect_uuid_t * type)9055 sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
9056 const effect_uuid_t *type)
9057 {
9058 size_t size = mEffects.size();
9059
9060 for (size_t i = 0; i < size; i++) {
9061 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
9062 return mEffects[i];
9063 }
9064 }
9065 return 0;
9066 }
9067
clearInputBuffer()9068 void AudioFlinger::EffectChain::clearInputBuffer()
9069 {
9070 Mutex::Autolock _l(mLock);
9071 sp<ThreadBase> thread = mThread.promote();
9072 if (thread == 0) {
9073 ALOGW("clearInputBuffer(): cannot promote mixer thread");
9074 return;
9075 }
9076 clearInputBuffer_l(thread);
9077 }
9078
9079 // Must be called with EffectChain::mLock locked
clearInputBuffer_l(sp<ThreadBase> thread)9080 void AudioFlinger::EffectChain::clearInputBuffer_l(sp<ThreadBase> thread)
9081 {
9082 size_t numSamples = thread->frameCount() * thread->channelCount();
9083 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
9084
9085 }
9086
9087 // Must be called with EffectChain::mLock locked
process_l()9088 void AudioFlinger::EffectChain::process_l()
9089 {
9090 sp<ThreadBase> thread = mThread.promote();
9091 if (thread == 0) {
9092 ALOGW("process_l(): cannot promote mixer thread");
9093 return;
9094 }
9095 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
9096 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
9097 // always process effects unless no more tracks are on the session and the effect tail
9098 // has been rendered
9099 bool doProcess = true;
9100 if (!isGlobalSession) {
9101 bool tracksOnSession = (trackCnt() != 0);
9102
9103 if (!tracksOnSession && mTailBufferCount == 0) {
9104 doProcess = false;
9105 }
9106
9107 if (activeTrackCnt() == 0) {
9108 // if no track is active and the effect tail has not been rendered,
9109 // the input buffer must be cleared here as the mixer process will not do it
9110 if (tracksOnSession || mTailBufferCount > 0) {
9111 clearInputBuffer_l(thread);
9112 if (mTailBufferCount > 0) {
9113 mTailBufferCount--;
9114 }
9115 }
9116 }
9117 }
9118
9119 size_t size = mEffects.size();
9120 if (doProcess) {
9121 for (size_t i = 0; i < size; i++) {
9122 mEffects[i]->process();
9123 }
9124 }
9125 for (size_t i = 0; i < size; i++) {
9126 mEffects[i]->updateState();
9127 }
9128 }
9129
9130 // addEffect_l() must be called with PlaybackThread::mLock held
addEffect_l(const sp<EffectModule> & effect)9131 status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
9132 {
9133 effect_descriptor_t desc = effect->desc();
9134 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
9135
9136 Mutex::Autolock _l(mLock);
9137 effect->setChain(this);
9138 sp<ThreadBase> thread = mThread.promote();
9139 if (thread == 0) {
9140 return NO_INIT;
9141 }
9142 effect->setThread(thread);
9143
9144 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
9145 // Auxiliary effects are inserted at the beginning of mEffects vector as
9146 // they are processed first and accumulated in chain input buffer
9147 mEffects.insertAt(effect, 0);
9148
9149 // the input buffer for auxiliary effect contains mono samples in
9150 // 32 bit format. This is to avoid saturation in AudoMixer
9151 // accumulation stage. Saturation is done in EffectModule::process() before
9152 // calling the process in effect engine
9153 size_t numSamples = thread->frameCount();
9154 int32_t *buffer = new int32_t[numSamples];
9155 memset(buffer, 0, numSamples * sizeof(int32_t));
9156 effect->setInBuffer((int16_t *)buffer);
9157 // auxiliary effects output samples to chain input buffer for further processing
9158 // by insert effects
9159 effect->setOutBuffer(mInBuffer);
9160 } else {
9161 // Insert effects are inserted at the end of mEffects vector as they are processed
9162 // after track and auxiliary effects.
9163 // Insert effect order as a function of indicated preference:
9164 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
9165 // another effect is present
9166 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
9167 // last effect claiming first position
9168 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
9169 // first effect claiming last position
9170 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
9171 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
9172 // already present
9173
9174 size_t size = mEffects.size();
9175 size_t idx_insert = size;
9176 ssize_t idx_insert_first = -1;
9177 ssize_t idx_insert_last = -1;
9178
9179 for (size_t i = 0; i < size; i++) {
9180 effect_descriptor_t d = mEffects[i]->desc();
9181 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
9182 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
9183 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
9184 // check invalid effect chaining combinations
9185 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
9186 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
9187 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
9188 return INVALID_OPERATION;
9189 }
9190 // remember position of first insert effect and by default
9191 // select this as insert position for new effect
9192 if (idx_insert == size) {
9193 idx_insert = i;
9194 }
9195 // remember position of last insert effect claiming
9196 // first position
9197 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
9198 idx_insert_first = i;
9199 }
9200 // remember position of first insert effect claiming
9201 // last position
9202 if (iPref == EFFECT_FLAG_INSERT_LAST &&
9203 idx_insert_last == -1) {
9204 idx_insert_last = i;
9205 }
9206 }
9207 }
9208
9209 // modify idx_insert from first position if needed
9210 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
9211 if (idx_insert_last != -1) {
9212 idx_insert = idx_insert_last;
9213 } else {
9214 idx_insert = size;
9215 }
9216 } else {
9217 if (idx_insert_first != -1) {
9218 idx_insert = idx_insert_first + 1;
9219 }
9220 }
9221
9222 // always read samples from chain input buffer
9223 effect->setInBuffer(mInBuffer);
9224
9225 // if last effect in the chain, output samples to chain
9226 // output buffer, otherwise to chain input buffer
9227 if (idx_insert == size) {
9228 if (idx_insert != 0) {
9229 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
9230 mEffects[idx_insert-1]->configure();
9231 }
9232 effect->setOutBuffer(mOutBuffer);
9233 } else {
9234 effect->setOutBuffer(mInBuffer);
9235 }
9236 mEffects.insertAt(effect, idx_insert);
9237
9238 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
9239 }
9240 effect->configure();
9241 return NO_ERROR;
9242 }
9243
9244 // removeEffect_l() must be called with PlaybackThread::mLock held
removeEffect_l(const sp<EffectModule> & effect)9245 size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
9246 {
9247 Mutex::Autolock _l(mLock);
9248 size_t size = mEffects.size();
9249 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
9250
9251 for (size_t i = 0; i < size; i++) {
9252 if (effect == mEffects[i]) {
9253 // calling stop here will remove pre-processing effect from the audio HAL.
9254 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
9255 // the middle of a read from audio HAL
9256 if (mEffects[i]->state() == EffectModule::ACTIVE ||
9257 mEffects[i]->state() == EffectModule::STOPPING) {
9258 mEffects[i]->stop();
9259 }
9260 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
9261 delete[] effect->inBuffer();
9262 } else {
9263 if (i == size - 1 && i != 0) {
9264 mEffects[i - 1]->setOutBuffer(mOutBuffer);
9265 mEffects[i - 1]->configure();
9266 }
9267 }
9268 mEffects.removeAt(i);
9269 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
9270 break;
9271 }
9272 }
9273
9274 return mEffects.size();
9275 }
9276
9277 // setDevice_l() must be called with PlaybackThread::mLock held
setDevice_l(uint32_t device)9278 void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
9279 {
9280 size_t size = mEffects.size();
9281 for (size_t i = 0; i < size; i++) {
9282 mEffects[i]->setDevice(device);
9283 }
9284 }
9285
9286 // setMode_l() must be called with PlaybackThread::mLock held
setMode_l(audio_mode_t mode)9287 void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
9288 {
9289 size_t size = mEffects.size();
9290 for (size_t i = 0; i < size; i++) {
9291 mEffects[i]->setMode(mode);
9292 }
9293 }
9294
9295 // setVolume_l() must be called with PlaybackThread::mLock held
setVolume_l(uint32_t * left,uint32_t * right)9296 bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
9297 {
9298 uint32_t newLeft = *left;
9299 uint32_t newRight = *right;
9300 bool hasControl = false;
9301 int ctrlIdx = -1;
9302 size_t size = mEffects.size();
9303
9304 // first update volume controller
9305 for (size_t i = size; i > 0; i--) {
9306 if (mEffects[i - 1]->isProcessEnabled() &&
9307 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
9308 ctrlIdx = i - 1;
9309 hasControl = true;
9310 break;
9311 }
9312 }
9313
9314 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
9315 if (hasControl) {
9316 *left = mNewLeftVolume;
9317 *right = mNewRightVolume;
9318 }
9319 return hasControl;
9320 }
9321
9322 mVolumeCtrlIdx = ctrlIdx;
9323 mLeftVolume = newLeft;
9324 mRightVolume = newRight;
9325
9326 // second get volume update from volume controller
9327 if (ctrlIdx >= 0) {
9328 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
9329 mNewLeftVolume = newLeft;
9330 mNewRightVolume = newRight;
9331 }
9332 // then indicate volume to all other effects in chain.
9333 // Pass altered volume to effects before volume controller
9334 // and requested volume to effects after controller
9335 uint32_t lVol = newLeft;
9336 uint32_t rVol = newRight;
9337
9338 for (size_t i = 0; i < size; i++) {
9339 if ((int)i == ctrlIdx) continue;
9340 // this also works for ctrlIdx == -1 when there is no volume controller
9341 if ((int)i > ctrlIdx) {
9342 lVol = *left;
9343 rVol = *right;
9344 }
9345 mEffects[i]->setVolume(&lVol, &rVol, false);
9346 }
9347 *left = newLeft;
9348 *right = newRight;
9349
9350 return hasControl;
9351 }
9352
dump(int fd,const Vector<String16> & args)9353 status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
9354 {
9355 const size_t SIZE = 256;
9356 char buffer[SIZE];
9357 String8 result;
9358
9359 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
9360 result.append(buffer);
9361
9362 bool locked = tryLock(mLock);
9363 // failed to lock - AudioFlinger is probably deadlocked
9364 if (!locked) {
9365 result.append("\tCould not lock mutex:\n");
9366 }
9367
9368 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
9369 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
9370 mEffects.size(),
9371 (uint32_t)mInBuffer,
9372 (uint32_t)mOutBuffer,
9373 mActiveTrackCnt);
9374 result.append(buffer);
9375 write(fd, result.string(), result.size());
9376
9377 for (size_t i = 0; i < mEffects.size(); ++i) {
9378 sp<EffectModule> effect = mEffects[i];
9379 if (effect != 0) {
9380 effect->dump(fd, args);
9381 }
9382 }
9383
9384 if (locked) {
9385 mLock.unlock();
9386 }
9387
9388 return NO_ERROR;
9389 }
9390
9391 // must be called with ThreadBase::mLock held
setEffectSuspended_l(const effect_uuid_t * type,bool suspend)9392 void AudioFlinger::EffectChain::setEffectSuspended_l(
9393 const effect_uuid_t *type, bool suspend)
9394 {
9395 sp<SuspendedEffectDesc> desc;
9396 // use effect type UUID timelow as key as there is no real risk of identical
9397 // timeLow fields among effect type UUIDs.
9398 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
9399 if (suspend) {
9400 if (index >= 0) {
9401 desc = mSuspendedEffects.valueAt(index);
9402 } else {
9403 desc = new SuspendedEffectDesc();
9404 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
9405 mSuspendedEffects.add(type->timeLow, desc);
9406 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
9407 }
9408 if (desc->mRefCount++ == 0) {
9409 sp<EffectModule> effect = getEffectIfEnabled(type);
9410 if (effect != 0) {
9411 desc->mEffect = effect;
9412 effect->setSuspended(true);
9413 effect->setEnabled(false);
9414 }
9415 }
9416 } else {
9417 if (index < 0) {
9418 return;
9419 }
9420 desc = mSuspendedEffects.valueAt(index);
9421 if (desc->mRefCount <= 0) {
9422 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
9423 desc->mRefCount = 1;
9424 }
9425 if (--desc->mRefCount == 0) {
9426 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
9427 if (desc->mEffect != 0) {
9428 sp<EffectModule> effect = desc->mEffect.promote();
9429 if (effect != 0) {
9430 effect->setSuspended(false);
9431 sp<EffectHandle> handle = effect->controlHandle();
9432 if (handle != 0) {
9433 effect->setEnabled(handle->enabled());
9434 }
9435 }
9436 desc->mEffect.clear();
9437 }
9438 mSuspendedEffects.removeItemsAt(index);
9439 }
9440 }
9441 }
9442
9443 // must be called with ThreadBase::mLock held
setEffectSuspendedAll_l(bool suspend)9444 void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
9445 {
9446 sp<SuspendedEffectDesc> desc;
9447
9448 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
9449 if (suspend) {
9450 if (index >= 0) {
9451 desc = mSuspendedEffects.valueAt(index);
9452 } else {
9453 desc = new SuspendedEffectDesc();
9454 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
9455 ALOGV("setEffectSuspendedAll_l() add entry for 0");
9456 }
9457 if (desc->mRefCount++ == 0) {
9458 Vector< sp<EffectModule> > effects;
9459 getSuspendEligibleEffects(effects);
9460 for (size_t i = 0; i < effects.size(); i++) {
9461 setEffectSuspended_l(&effects[i]->desc().type, true);
9462 }
9463 }
9464 } else {
9465 if (index < 0) {
9466 return;
9467 }
9468 desc = mSuspendedEffects.valueAt(index);
9469 if (desc->mRefCount <= 0) {
9470 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
9471 desc->mRefCount = 1;
9472 }
9473 if (--desc->mRefCount == 0) {
9474 Vector<const effect_uuid_t *> types;
9475 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
9476 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
9477 continue;
9478 }
9479 types.add(&mSuspendedEffects.valueAt(i)->mType);
9480 }
9481 for (size_t i = 0; i < types.size(); i++) {
9482 setEffectSuspended_l(types[i], false);
9483 }
9484 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
9485 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
9486 }
9487 }
9488 }
9489
9490
9491 // The volume effect is used for automated tests only
9492 #ifndef OPENSL_ES_H_
9493 static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
9494 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
9495 const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
9496 #endif //OPENSL_ES_H_
9497
isEffectEligibleForSuspend(const effect_descriptor_t & desc)9498 bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
9499 {
9500 // auxiliary effects and visualizer are never suspended on output mix
9501 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
9502 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
9503 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
9504 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
9505 return false;
9506 }
9507 return true;
9508 }
9509
getSuspendEligibleEffects(Vector<sp<AudioFlinger::EffectModule>> & effects)9510 void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
9511 {
9512 effects.clear();
9513 for (size_t i = 0; i < mEffects.size(); i++) {
9514 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
9515 effects.add(mEffects[i]);
9516 }
9517 }
9518 }
9519
getEffectIfEnabled(const effect_uuid_t * type)9520 sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
9521 const effect_uuid_t *type)
9522 {
9523 sp<EffectModule> effect = getEffectFromType_l(type);
9524 return effect != 0 && effect->isEnabled() ? effect : 0;
9525 }
9526
checkSuspendOnEffectEnabled(const sp<EffectModule> & effect,bool enabled)9527 void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
9528 bool enabled)
9529 {
9530 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
9531 if (enabled) {
9532 if (index < 0) {
9533 // if the effect is not suspend check if all effects are suspended
9534 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
9535 if (index < 0) {
9536 return;
9537 }
9538 if (!isEffectEligibleForSuspend(effect->desc())) {
9539 return;
9540 }
9541 setEffectSuspended_l(&effect->desc().type, enabled);
9542 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
9543 if (index < 0) {
9544 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
9545 return;
9546 }
9547 }
9548 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
9549 effect->desc().type.timeLow);
9550 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9551 // if effect is requested to suspended but was not yet enabled, supend it now.
9552 if (desc->mEffect == 0) {
9553 desc->mEffect = effect;
9554 effect->setEnabled(false);
9555 effect->setSuspended(true);
9556 }
9557 } else {
9558 if (index < 0) {
9559 return;
9560 }
9561 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
9562 effect->desc().type.timeLow);
9563 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9564 desc->mEffect.clear();
9565 effect->setSuspended(false);
9566 }
9567 }
9568
9569 #undef LOG_TAG
9570 #define LOG_TAG "AudioFlinger"
9571
9572 // ----------------------------------------------------------------------------
9573
onTransact(uint32_t code,const Parcel & data,Parcel * reply,uint32_t flags)9574 status_t AudioFlinger::onTransact(
9575 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
9576 {
9577 return BnAudioFlinger::onTransact(code, data, reply, flags);
9578 }
9579
9580 }; // namespace android
9581