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