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